/*
 * SimpleModal Contact Form
 * http://www.ericmmartin.com/projects/simplemodal/
 * http://code.google.com/p/simplemodal/
 *
 * Copyright (c) 2010 Eric Martin - http://ericmmartin.com
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Revision: $Id: contact.js 254 2010-07-23 05:14:44Z emartin24 $
 */

var ice_edit_elem;  // current element object
var iceEdit_ID;     // current element db id
var _fade = 100;

/* TODO: undo changes in DOM if preview, not save
 */

jQuery(function ($) {
  var contact = {
    message: null,
    init: function () {
      $('.btn_ice').live('click', function (e) {
        e.preventDefault();
        ice_mode = true;
        ice_edit_elem = $(this).next();
        ice_edit_elem.removeClass("ice_hilite");
        var lang = $(this).attr("lang");
        ice_work = lang.split("#");
        $.log("btn_ice clicked lang: " + lang, ice_work, {type: "info"});

        iceEdit_ID = ice_work[0];
        sMainDiv = ice_work[1];
        sTitle = ice_work[2];
        iWantTxt = (ice_work[3] == "txt") ? true : false;

        cmsIDfield = "id";
        img_clean = 0; //don't clean up image paths

        $.log("simplemodal iceEdit_ID:" + iceEdit_ID);

        // load the contact form using ajax
        $.get("site/iceEdit.php?id=" + iceEdit_ID, function(data) {

          $.log("post.get data=", data);

          // create a modal dialog with the data
          $(data).modal({
            closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
            position: ["15%"],
            overlayId: 'eic-overlay',
            containerId: 'eic-container',
            onOpen: contact.open,
            onShow: contact.show,
            onClose: contact.close
          });
          $.log("postpost.get");
        });
      });
    },
    open: function (dialog) {
      // add padding to the buttons in firefox/mozilla
      if ($.browser.mozilla) {
        $('#eic-container .eic-button').css({
          'padding-bottom': '2px'
        });
      }
      // input field font size
      if ($.browser.safari) {
        $('#eic-container .eic-input').css({
          'font-size': '.9em'
        });
      }

      // dynamically determine height
      var h = 280;
      if ($('#eic-subject').length) {
        h += 26;
      }
      if ($('#eic-cc').length) {
        h += 22;
      }

      var title = $('#eic-container .eic-title').html();
      $('#eic-container .eic-title').html('Loading...');
      dialog.overlay.fadeIn(_fade, function () {
        dialog.container.fadeIn(_fade, function () {
          dialog.data.fadeIn(_fade, function () {
            $('#eic-container .eic-content').animate({
              height: h
            }, function () {
              $('#eic-container .eic-title').html(title);
              $('#eic-container form').fadeIn(_fade, function () {
                $('#eic-container #eic-name').focus();

                $('#eic-container .eic-cc').click(function () {
                  var cc = $('#eic-container #eic-cc');
                  cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
                });

                // fix png's for IE 6
                if ($.browser.msie && $.browser.version < 7) {
                  $('#eic-container .eic-button').each(function () {
                    if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
                      var src = RegExp.$1;
                      $(this).css({
                        backgroundImage: 'none',
                        filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + src + '", sizingMethod="crop")'
                      });
                    }
                  });
                }
              });
            });
          });
        });
      });
    },
    show: function (dialog) {
      $('#eic-container .eic-prior').click(function (e) {
        e.preventDefault();
        bSave = false;
        $("#eic-text").html($("#eic-text_prior").html());
        $("#eic-hdr").val($("#eic-hdr_prior").val());
      });

      $('#eic-container .eic-add').click(function (e) {
        e.preventDefault();
        bSave = false;
        $("#eic-hdr").val("chuck");
        $("#eic-sub").val("e.");
        $("#eic-text").html("newby");
        addNewItem();
      });

      $('#eic-container .eic-delete').click(function (e) {
        e.preventDefault();
        bSave = false;
        $("#eic-hdr").val("zippy");
        $("#eic-sub").val("and");
        $("#eic-text").html("zappy");
      });

      $('#eic-container .eic-preview').click(function (e) {
        e.preventDefault();
        bFalse = true;
        // validate form
        if (contact.validate()) {
          var msg = $('#eic-container .eic-text');
          msg.fadeOut(function () {
            msg.removeClass('eic-error').empty();
          });

          rez_title = $("#eic-hdr").val();
          rez_subtitle = $("#eic-sub").val();
          rez_cont = $("#eic-text").val();

          if (rez_subtitle) {
            $.log("** set rez subtitle: " + rez_subtitle, ice_edit_elem); //
            ice_edit_elem.children(".iceSubtitle").html(rez_subtitle);
          }

          if (rez_title) {
            $.log("** set rez title: " + rez_title, ice_edit_elem); //
            ice_edit_elem.children(".iceTitle").html(rez_title);
          }

          if (rez_cont) {
            $.log("** set rez content: " + rez_cont, ice_edit_elem); //
            ice_edit_elem.children(".iceContent").html(rez_cont); // update DOM
          }

        } else {
          alert ("validation failed");
        }
      });


      $('#eic-container .eic-save').click(function (e) {
        e.preventDefault();
        bSave = true;
        // validate form
        if (contact.validate()) {
          var msg = $('#eic-container .eic-text');
          msg.fadeOut(function () {
            msg.removeClass('eic-error').empty();
          });

          $('#eic-container .eic-title').html('Saving...');
          $('#eic-container form').fadeOut(_fade);
          $('#eic-container .eic-content').animate({
            height: '80px'
          }, function () {
            $('#eic-container .eic-loading').fadeIn(_fade, function () {
//			the_parms="xxxxxxr5parms=u:icc_item:id:"+iceEdit_ID+"&title="+encodeURIComponent(rez_title)+"&text="+encodeURIComponent(rez_cont)

              the_parms = "r5parms=u:icc_item:type:" + iceEdit_ID + '&action=save&' + $('#frmEic').serialize();
              $.log(the_parms);
              $.ajax({
                url: 'admin/inc/ice_db.php',
                data: the_parms,
                type: 'POST',
                cache: false,
                dataType: 'html'
              })
                  .success(function (data) {
                      $.log("success data", data);
                    rez_title = $("#eic-hdr").val();
                    rez_subtitle = $("#eic-sub").val();
                    rez_cont = $("#eic-text").val();

                    if (rez_subtitle) {
                      $.log("** set rez subtitle: " + rez_subtitle, ice_edit_elem); //
                      ice_edit_elem.children(".iceSubtitle").html(rez_subtitle);
                    }

                    if (rez_title) {
                      $.log("** set rez title: " + rez_title, ice_edit_elem); //
                      ice_edit_elem.children(".iceTitle").html(rez_title);
                    }
                    
                    if (rez_cont) {
                      $.log("** set rez content: " + rez_cont, ice_edit_elem); //
                      ice_edit_elem.children(".iceContent").html(rez_cont); // update DOM
                    }

                    $('#eic-container .eic-loading').fadeOut(_fade, function () {
                      $('#eic-container .eic-title').html('Thank you!');
                      msg.html(data).fadeIn(_fade);
                      $.modal.close();
                    });

                  })

                  .error(function (data) {
                      $.log("error data", data);
                    contact.error
                  });

            });
          });

          /*
           $.log("pre-ajax:"+the_parms);

           $.ajax({
           type: "POST",
           url: "admin/inc/ice_db.php",
           data: the_parms,

           error: function(fld) {
           $.log("ice.js ajax err",fld);
           alert ("ajax error in cms.js\n"+fld);
           },

           success: function(sJson){
           $.log("ice.js ajax returns >"+sJson); //////////////////
           if (sJson.indexOf("OKAY:")>0) {
           sJsonResult=sJson.substr(6);
           if (sSuccess) {
           alert (sSuccess);
           }

           }
           }
           });
           */
        }
        else {
          if ($('#eic-container .eic-text:visible').length > 0) {
            var msg = $('#eic-container .eic-text div');
            msg.fadeOut(_fade, function () {
              msg.empty();
              contact.showError();
              msg.fadeIn(_fade);
            });
          }
          else {
            $('#eic-container .eic-text').animate({
              height: '30px'
            }, contact.showError);
          }

        }
      });
    },
    error: function (xhr) {
      alert(xhr.statusText);
    },

    validate: function () {
      contact.message = '';
      if (!$('#eic-container #eic-title').val()) {
        //			contact.message += 'Name is required. ';
      }

      return true;

    },

    showError: function () {
      $('#eic-container .eic-text')
          .html($('<div class="eic-error"></div>').append(contact.message))
          .fadeIn(_fade);
    },

    close: function (dialog) {
//$.log("ice.js close: dialog", {type:"err"}); //dialog.data[0].innerHTML,

      $('#eic-container .eic-text').fadeOut();
      $('#eic-container .eic-title').html('Goodbye...');
      $('#eic-container form').fadeOut(_fade);
      $('#eic-container .eic-content').animate({
        height: 40
      }, function () {
        dialog.data.fadeOut(_fade, function () {
          dialog.container.fadeOut(_fade, function () {
            dialog.overlay.fadeOut(_fade, function () {
              $.modal.close();
            });
          });
        });
      });
    }

  };
  contact.init();
});
