//---------------------------------------
// PUBLIC VARIABLES
//---------------------------------------
var is_ajaxing = null;
//---------------------------------------
// CONSTRUCTORS
//---------------------------------------
$(document).ready(function(){
   $(".affiliate_hide").hide();

   //check domain name on keyup for better user interface
   $("#web_address").keyup(function(){
      var domain = $('input#web_address').val();
      var tld_label = $("#tld option:selected").text();
      $(".domain_name_label").text(domain);
      $(".tld_label").text(tld_label);
      
      switch($(".domain_status:checked").val()) {
         case "existing_domain":
         break;
         case "new_domain":
         default://allows for form to be used without domain_status option
            doValidateDomain(true);
            checkDomain();
         break;
      }
   }).focus(function(){
      if ( $(this).val() == 'YourDomainName') {
         hideBoxes();
         $(this).val('');
      }
   }).blur(function(){
       if ($(this).val() == '') {
         hideBoxes();
         $(this).val('YourDomainName');
       }
   });
   
   //add_email_adresses
   $("input#add_email_adresses").click(function(){
      if($(this).attr("checked")) {
         $("#group_email_wrapper").show();
      } else {
         $("#group_email_wrapper").hide();
      }
   });
   
   //admin_email_accessible
   $(".admin_email_accessible").click(function(){
      if ($("#is_accessible").attr("checked")) {
         $("#not_accessible_message").hide();
      } else {
         $("#not_accessible_message").show(); 
      }
   });
   
   //additional_domains
   $(".additional_domains").click(function(){
      if ($("#no_additional_domains").attr("checked")) {
         $("#additional_domain_list").hide();
      } else {
         $("#additional_domain_list").show(); 
      }
   });
      //maintain_domains
      $(".maintain_domains").click(function(){
         if ($("#do_not_maintain").attr("checked")) {
            $("#exchange_server").hide();
         } else {
            $("#exchange_server").show(); 
         }
      });
         //exchange_server
         $(".exchange_server").click(function(){
            if ($("#no_exchange_server").attr("checked")) {
               $("#continue_exchange_server").hide();
            } else {
               $("#continue_exchange_server").show(); 
            }
         });
            //continue_exchange_server
            $(".continue_exchange_server").click(function(){
               if ($("#yes_continue_exchange_server").attr("checked")) {
                  $("#continue_exchange_server_message").hide();
               } else {
                  $("#continue_exchange_server_message").show(); 
               }
            });
});
//---------------------------------------
// PUBLIC METHODS
//---------------------------------------
function _debug ($string) {
   try {
      console.log($string);
   } catch (err) { 
      //$("#footer").append($string + "<div class='hr'><hr /></div>"); 
   }
}
//---------------------------------------
function addTask() {
   Shadowbox.open({
      player:     'iframe',
      title:      'Select Your Theme',
      content:    '/select_theme.php',
      height:     '500',
      width:      '900'
   });
}
//---------------------------------------
function selectOption(id) {
   selectBox = document.forms[0].selectTheme;
   for (var i=0; i<selectBox.options.length; i++){
      if (selectBox.options[i].value==id){
         selectBox.selectedIndex = i;
         break;
      }
   }
}
//---------------------------------------
function checkDomain() {
   domainName = $('input#web_address').val();
   tld = $("#tld option:selected").text();
   if (validateDomain && domainName != 'YourDomainName') {
      if (domainName) {
         hideBoxes();
         $('#domainLoading').css({ "display":"block" });
         ajax_update({ajaxURL:"/spark/_globals/ajax/domain_available.php",data:{ domain: domainName+tld },callback:{fn:checkDomainResponse}});
      } else {
         hideBoxes();
         $('input#web_address').val('YourDomainName');
      }
   }
}
//---------------------------------------
function checkDomainResponse (params) {
   //_debug(params);
   hideBoxes();
   div = (parseInt(params.data)) ? "#domainAvailable" : "#domainNotAvailable";
   $(div).show();
}
//---------------------------------------
function hideBoxes() {
   $('#domainLoading').hide();
   $('#domainAvailable').hide();
   $('#domainNotAvailable').hide();
   $('#existingWarning').hide();
}
//---------------------------------------
function doValidateDomain(myValue) {
  validateDomain = myValue;
  //for existing domain checks? (if checkbox exists)
  if ($('#existingWarning').length > 0) {
     if (myValue) {
       $('#existingWarning').hide();
     } else {
       $('#existingWarning').show();
     }
  }
}
//---------------------------------------
function cloneItem (caller) {
   $("#"+caller).children("div.line:last").clone(true).css("display","none").appendTo("#"+caller);

   if($("#"+caller).children(".line").length > 1) {
      $("#"+caller + " .line .option_remove").removeClass("hidden").show();
   }

   //loop through and update new values for new clone
   $.each($("#"+caller+" div.line:last div.spacer"), function () {
      //create new id and name attributes
      var tmp = $(this).children("label").attr("for");
      //_debug(tmp);
      var old_id = tmp.match(/\d/g).join("");
      var new_id = parseInt(old_id)+1;
      /*_debug($(this));
      _debug(old_id);
      _debug(new_id);*/
      var new_form_id = tmp.replace(old_id,new_id);
      //_debug(new_form_id);
      var old_form_name = ($(this).children("select").length > 0) ? $(this).children("select").attr("name") : $(this).children("input").attr("name");
      var new_form_name = old_form_name.replace(old_id,new_id);
      if($(this).children("select").length > 0 && $(this).children("select").hasClass("clone_multiple")) {
         //TODO CLEAN UP (don't do selections 2x)
         var old_form_multiselect_rel = $(this).children("select").attr("rel");
         var old_form_ul_id = $(this).parent().next().children().children("ul").attr("id");
         var new_form_multiselect_rel = old_form_multiselect_rel.replace(old_id,new_id);
         // new_form_multiselect_rel = new_form_multiselect_rel.replace("ContactsDonationAnalytic","NewContactsDonationAnalytic");
         var new_form_ul_id = old_form_ul_id.replace(old_id,new_id);

         $(this).children("select").attr("rel",new_form_multiselect_rel);
         $(this).parent().next().children().children("ul").attr("id", new_form_ul_id);
         $(this).parent().next().children().children("ul").empty();
      }
      
      //update the new values
      $(this).children("label").attr("for", new_form_id);
      $(this).children("select").attr("id", new_form_id).attr('name',new_form_name).attr('disabled','').removeClass("disabled");
      $(this).children("input").attr("id", new_form_id).attr("name", new_form_name).attr("value", '').attr("readonly","").removeClass("disabled");
   });

   //show new clone
   $("#"+caller+" div.line:last").slideDown("slow");
}
//---------------------------------------
function removeItem (params) {
   $(params.target).parent().parent().parent(".line").remove();
   if($(params.container + " .line").length == 1) {
      $(params.container + " .line .option_remove").addClass("hidden").hide();
   }
}
//---------------------------------------
function ajax_update(_atts) {
   var _data = (_atts.data) ? _atts.data : null;
   var _type = (_atts.type) ? _atts.type : "";
   var _ajax_loader_target = (_atts.load_icon) ? _atts.load_icon : null;
   var _ajax_loader_opts = (_atts.load_icon_opts) ? _atts.load_icon_opts : null;
   var _data_type = (_atts.dataType) ? _atts.dataType : "html";
   var _do_ajax = false;

   switch (_type) {
      case "serialize":
         _data = $('#'+_atts.formId).serialize();
         _do_ajax = true;
      break;
      default:
         if (_data != null) {
            _do_ajax = true;
         } else if ($('#sortOrder').val() != "") {
            //_data = {sortOrder: $('#sortOrder').val()};
            _do_ajax = true;
         } else {}
      break;
   }

   if (_do_ajax) {
      if (typeof toggle_ajax_loader == 'function') {
         toggle_ajax_loader({target:_ajax_loader_target,options:_ajax_loader_opts});
      }
      ajax_in_action = true;

      //abort any open ajax calls
      if(is_ajaxing) {
         is_ajaxing.abort();
      }

      is_ajaxing = $.ajax({
             type: "POST"
            ,url: _atts.ajaxURL
            ,data: _data
            ,cache: false
            ,dataType: _data_type
            ,success: function(data) {
               ajax_in_action = false;

               if(data.error) {
                  //_debug(data.id);
               } else {
                  if(_atts.callback) {
                     (_atts.callback.params) ? _atts.callback.params.data = data : _atts.callback.params = {data: data};
                     (_atts.callback.params && _ajax_loader_target != null) ? _atts.callback.params.load_icon = _ajax_loader_target : "";
                     _atts.callback.fn(_atts.callback.params);
                  } else {
                     ($(".admin").length > 0) ? toggle_submit_btn('saved') : "";
                  }
                  //hide loading icon
                  if (typeof toggle_ajax_loader == 'function') {
                     toggle_ajax_loader({target:_ajax_loader_target,options:_ajax_loader_opts},true);
                  }
               }
            }//end success
      });
   }//end if
}