var url = "http://gunroom.shootingsportsman.com/ajax/";  // ajax page - we're using code igniter so it's not a real 'page' per se
var global_focus;  // what element has focus (so we can go back to it after an ajax save)
var ajaxCalls = 0; // count how many ajax calls in progress
var ajax; // the ajax call so we can abort manually if needed
var noupd = false;  // true if we want to not show the blocking/systemworking message


// begin our jquery stuff.
$(document).ready(function() { 
   $.ajaxSetup( { 
      url: url, type: "POST", dataType:'html', timeout:10000,
      error: function (x,s,eo) { display("There was an error in the AJAX request: "+s,true); } 
   });
   //$('#systemWorking').ajaxStart( function() { if (!noupd) $(this).show(); } ).ajaxStop( function() { $(this).hide(); } );
   $('[@title]').not('.thickbox').not('.nohovertitle').Tooltip({delay:0,showURL:false,track:true,showBody:"|"});
   if (jQuery.browser.version == '6.0' && jQuery.browser.msie) {
      $("#nav li").hover(function(){$(this).addClass("sfhover");}, function() { $(this).removeClass("sfhover"); });
      $("#nav ul").bgiframe();
   }
   $("#tooltip").bgiframe();
   addTableSortingDateParser();
   $('img[@src$=.png]').pngfix();
   hideMessages();
   $("#img_gal").slideView({ easeTime:'0' });
});



function initUsersPage() {
   $("#users_form").validate({onblur:false,onkeyup:false});
}
function initSearchPage() {
   $('#search_filters input').each(function(i) {
      $(this).click(function(){$(this).select(); });
      $(this).not('[@name*=min],[@name*=max]').change(function(){if ( $.trim($(this).val()) == '') $(this).val('Any'); }) ;
      $(this).filter('[@name*=min]').change(function(){if ( $.trim($(this).val()) == '') $(this).val('Min'); });
      $(this).filter('[@name*=max]').change(function(){if ( $.trim($(this).val()) == '') $(this).val('Max'); });
   });
}
function initAddField() {
   $("#add_fields_form").validate({wrapper:'p'});
}
function initListingForm() {
   $("#listing_form").validate({
      submitHandler: function(form) { $('#savebutton').attr('disabled',true); form.submit();}, 
      onkeyup: false,
      errorPlacement: function(error, element) {error.appendTo( element.parents("span") );} 
   });
   if (!$("#listing_form").length) return false;
   $("#listing_form :input, #listing_form :select, #listing_form :textarea").change(listingChange).focus(function() {global_focus = this.name});
}
function initFieldsChange() {   // watches on the editing of fields/forms (admins)
   if (!$("#config_fields_form").length) return false;
   $("#config_fields_form :input, #config_fields_form :select, #config_fields_form :textarea").change(fieldsChange).focus(function() {global_focus = this.name});
   $("#config_fields_form :input[@type=checkbox], #config_fields_form :input[@type=radio]").click(function() {this.blur()});
}
function initMetaChange() {   // watches on the editing of fields/forms (admins)
   if (!$("#config_meta_form").length) return false;
   $("#config_meta_form :input, #config_meta_form :select, #config_meta_form :textarea").change(metaChange).focus(function() {global_focus = this.name});
}
function initOptionsChange() {   // watches on the editing of options (admins)
   if (!$("#config_options_form").length) return false;
   $("#config_options_form :input, #config_options_form :select, #config_options_form :textarea").change(optionsChange).focus(function() {global_focus = this.name});
}   
   




/**********************/
function resetSearch(form) {
   //$('#'.form).clearForm();
   $('#'+form+' select').selectOptions('');
   $('#'+form+' input[@id$=min], #'+form+' input[@id$=minlb]').val('Min');
   $('#'+form+' input[@id$=max], #'+form+' input[@id$=maxlb]').val('Max');
   $('#'+form+' div[@class=arrowToggle]').each(function(i) { arrowToggle(this.id,'close'); });
   $('#'+form+' input[@type=text]').clearFields();
   //$('#'+form).submit();
}
/**********************/
function resetMoney(id) {
   $('#'+id+'_min').val('Min'); $('#'+id+'_max').val('Max');
   $('#'+id+'_min').parents('form').submit();
}
/**********************/
function resetText(id) {
   $('#'+id).clearFields();
   $('#'+id).parents('form').submit();
}
/**********************/
function resetSelect(id) {
   $('#'+id).clearFields();
   $('#'+id).parents('form').submit();
}
/**********************/
function resetWeight(id) {
   $('#'+id+'_minlb').val('Min'); $('#'+id+'_maxlb').val('Max');
   $('#'+id+'_minlb').parents('form').submit();
}
/**********************/
function resetDate(id) {
   $('#'+id+'_mindate').val(''); $('#'+id+'_maxdate').val('');
   $('#'+id+'_mindate').parents('form').submit();
}
/**********************/
function abortAjax() {
   if (ajax) ajax.abort();  
   return false;
}
/**********************/
image_cnt = 0;  // this will give different fields non-sequential ids (add to image, add to file, add to image...), but it won't matter
function addFileField(sql_field) {
   $("#"+sql_field+"_div").append('<div id="'+sql_field+'_ai'+image_cnt+'"><input type="file" name="'+sql_field+'_ai['+image_cnt+']" size="20">       <input type="text" name="'+sql_field+'_ac['+image_cnt+']" onClick="this.select()" maxlength="50" size="20" title="Caption here" value=""> <a href="#" onClick="removeFileField(\''+sql_field+'_ai'+image_cnt+'\');return false;"><img title="Remove image" src="images/icons/trash.gif"></a></div>');   
   image_cnt++;
   $("#"+sql_field+"_div [@title]").not('.thickbox').not('.nohovertitle').Tooltip({delay:0,showURL:false,track:true,showBody:"|"});
} 
/**********************/
function removeFileField(el) {
   $("#"+el).remove();
}
/**********************/
function optionsChange() {
   var opt = this.name.match(/opt_(.+)(\[([0-9]+)\])/);  if (!opt || !opt[1] || !opt[3]) return false;
   var name = $.trim(opt[1]);  var id = $.trim(opt[3]);
   ajax = $.ajax({
      dataType:'json',
      url:url+'update_one_field_options',
      data:{id:id, name:name, value:this.value},
      success:function (response) { 
         if (ajaxCalls <= 1) {
            // response should be JSON for 'messages', 'errors', and possibly 'html'
            if (response.html) {
               $('#config_options_html').html(response.html); $('[@name="'+global_focus+'"]').focus(); 
               initOptionsChange(); hideMessages();
            }
            if (response.errors) { display(response.errors,true); }
            if (response.messages) { display(response.messages); }
         }
      }
   });
}
/**********************/
function metaChange() {
   var directory_id = parseInt($('#directory_id').val()); if (!directory_id) return false;
   ajax = $('#config_meta_html').load(url+'update_directory',{directory_id:directory_id, name:this.name, value:this.value},
   function () { $('[@name="'+global_focus+'"]').focus(); initMetaChange(); 
      ajax = $('#config_select_directory_html').load(url+'load_edit_field_select_html',{directory_id:directory_id}, 
      function() {hideMessages();});}
   );
}
/**********************/
function fieldsChange() {
   var directory_id = $('#directory_id').val();
   var matches = this.name.match(/(.*)\[([0-9]+)\](\[\])?/);
   if (!matches || !matches[1] || !matches[2]) return false;
   var name = $.trim(matches[1]);  var id = parseInt(matches[2]);
   if (!name || !id || !directory_id) return false;
   var data = '';
   $('#config_fields_form [@name="'+this.name+'"]').each(function(i) {    
      data += $.trim(this.type == 'checkbox' ? (this.checked ? this.value : '') : this.value) + ' ';
   });
   noupd = false; if ($('#noupdate').attr('checked')) noupd = true;
   ajax = $.ajax({
      dataType:'json',
      url:url+'update_one_field',
      beforeSend: function() { ajaxCalls++; }, complete: function() { ajaxCalls--; },
      data:{directory_id:directory_id, id:id, name:name, value:data, noupdate:noupd},
      success:function (response) { 
         if (ajaxCalls <= 1) {
            // response should be JSON for 'messages', 'errors', and possibly 'html'
            if (response.html) {
               $('#config_fields_html').html(response.html); $('#config_fields_form [@name="'+global_focus+'"]').focus(); 
               initFieldsChange(); hideMessages();
            }
            if (response.errors) { display(response.errors,true); }
            if (response.messages) { display(response.messages); }
         }
      }
   });
}
/**********************/
// we had a change to one of our listing values; look up and see if we have to change any options
function listingChange() {
   var data = this.value; if (!data) return false;
   var formdata = $('#listing_form').formSerialize(true); formdata += "&field_id="+encodeURIComponent(this.name);
   // delay so we don't kill the user's input when they click stuff
   setTimeout(function(){
   ajax = $.getJSON(url+'check_listing_options', formdata, 
      function (response) {
         for (var i in response) {
            var options = response[i].options; var index = i.toString(); var field = $('#'+index); 
            
            if (response[i].type.indexOf("select") != -1) {
               var old_value = field.val(); 
               field.removeOption(/./);
               if (response[i].options) field.addOption(response[i].options);
               field.selectOptions(old_value,true);
            // make a radio for each option, and select value previously chosen, if any
            } else if (response[i]['type'] == "radio") {
               $('#'+index+'_c input[@type=radio]').each(function(){
                  if (this.checked) selected = this.value;
               });
               $('#'+index+'_c').html(''); // reset options
               for (var j in options) {
                  $('#'+index+'_c').append("<label><input type='radio' name='"+index+"' value='"+response[i]['options'][j]+"'"+ ( (response[i]['options'][j] == selected) ? " checked=checked" : "" ) +">"+response[i]['options'][j]+"&nbsp;&nbsp; </label>");
               }
               
               initListingForm();
            }
            if (options.length < 1 || (options.length <= 1 && options[0] == '')) {
               $('#'+index+'_tc').hide();
            } else {
               $('#'+index+'_tc').show();
            }
         } // end for
      } // end function
   );
   },250);
}
/**********************/
// request to add an option
function addOption() {
   field_id = parseInt($('#field_id').val()); if (!field_id || field_id == 0) return false;
   ajax = $('#config_options_html').load(url+'add_field_option',{ field_id: field_id, condition:$('#condition').val(),
      priority:$('#priority').val(), values:$('#values').val() },
      function () { $('#values').val(''); $('#priority').val('0'); $('#condition').val(''); initOptionsChange(); hideMessages(); });
}
/**********************/
// request to delete an option
function deleteOption(delete_id) {
   if (!delete_id) return false; delete_id = parseInt(delete_id);
   if (!confirm("Are you sure you wish to delete this option?")) return false;
   field_id = parseInt($('#field_id').val()); if (!field_id) return false;
   ajax = $('#config_options_html').load(url+'delete_field_option',{id:delete_id, field_id: field_id},
   function () { initOptionsChange(); hideMessages(); });
}
/**********************/
// we had a new submitted field; lets save!
function addField(form) {
   if (!form) return false;
   ajax = $('#config_fields_html').load(url+'add_field',$(form).formToArray(), function () {
      initFieldsChange(); $(form).resetForm(); hideMessages(); });
}
/**********************/
// request to delete a field entry
function deleteField(delete_id) {
   if (!delete_id) return false;
   if (!confirm("Are you sure you wish to delete this entry?")) return false;
   var directory_id = parseInt($('#directory_id').val())  // not really needed, php looks it up ... but one less step
   if (!directory_id) return false;
   ajax = $('#config_fields_html').load(url+'delete_field',{id:delete_id, directory_id: directory_id},
   function () { initFieldsChange();hideMessages(); });
}
/**********************/
// start a timer to auto-hide the message div after a short while
timeout = timeout2 = null;
function hideMessages() {
   if (timeout) window.clearTimeout(timeout);
   if (timeout2) window.clearTimeout(timeout2);
   timeout  = window.setTimeout("$('#msg_handler').fadeOut('slow');",3000);  // 3 sec
   timeout2 = window.setTimeout("$('#err_handler').fadeOut('slow');",8000);  // 8 sec
}
/**********************/
function display(msg,isError) {
   if (isError == true) {
      if (timeout2) window.clearTimeout(timeout2);
      var msgbox = $('#err_handler');
      if (msgbox.html()) { msgbox.html(msg).show("fast"); } 
      else { $("body").append('<div id="err_handler">'+msg+'</div>').show(); }
      timeout2 = window.setTimeout(function() { $("#err_handler").fadeOut("medium") }, 8000);
   } else {
      if (timeout) window.clearTimeout(timeout);
      var msgbox = $('#msg_handler');
      if (msgbox.html()) { msgbox.html(msg).show("fast"); } 
      else { $("body").append('<div id="msg_handler">'+msg+'</div>').show(); }
      timeout = window.setTimeout(function() { $("#msg_handler").fadeOut("medium") }, 3000);
   }
}
/**********************/
// when editing field options, we might limit options to a certain condition (or hide if blank)
function addCondition() {
   condition_box = $('#condition'); val_condition_box = $.trim(condition_box.val());
   field = $('#if_field'); val_field = $.trim($('#if_field').val()); 
   cond = $('#cond'); val_cond = $.trim($('#cond').val());
   cond_value = $('#cond_value'); val_cond_value = $.trim($('#cond_value').val());
   
   if (!field || val_field=='' || !cond || val_cond=='' || !cond_value || !condition_box) return false;
   var c = val_field + " " + val_cond + " '" + val_cond_value.replace(/\'/,"\\'") + "'";
   if (val_condition_box != "") { condition_box.val(val_condition_box + " AND\n"); } 
   condition_box.val(condition_box.val() + c); field[0].selectedIndex = 0; cond[0].selectedIndex = 0; cond_value.val('');
}
/**********************/
// we'll have 2 objects for this weight inputObj; one is name_lb, other is name_oz   
function checkWeight(inputObj) {
   if (!inputObj) return false;
   var name_arr = inputObj.id.match(/(.*)_(lb|oz)/);
   if (!name_arr || !name_arr[1]) { return false; } else { var name = name_arr[1]; }
   var weight_lb = parseInt($('#'+name+'_lb').val()); var weight_oz = parseInt($('#'+name+'_oz').val());
   if (isNaN(weight_lb)) weight_lb = 0; if (isNaN(weight_oz)) weight_oz = 0;
   var overflow = weight_oz / 16;
   if (overflow < 1) { $('#'+name+'_lb').val(weight_lb); $('#'+name+'_oz').val(weight_oz); }
   else { var temp = (weight_lb*16) + weight_oz; $('#'+name+'_lb').val(parseInt(temp/16)); $('#'+name+'_oz').val(parseInt(temp%16)); }
}
/**********************/
function insertTime(inputObj) {
   if (!inputObj) return false;
   var t = new Date();
   mon = t.getMonth()+1; if (mon < 10)   mon = "0"+mon;   day = t.getDate();    if (day < 10) day = "0"+day;
   hrs = t.getHours(); if (hrs < 10)   hrs = "0"+hrs;   min = t.getMinutes(); if (min < 10) min = "0"+min;
   sec = t.getSeconds(); if (sec < 10) sec = "0"+sec; 
   $("#"+inputObj).val(t.getFullYear()+'-'+mon+'-'+day+' '+hrs+':'+min+':'+sec);
}
/**********************/
function checkMoney(inputObj) {
   if (!inputObj) return false;
   var num = $(inputObj).val();
   num = num.replace(/\$/,'');
   num = num.replace(/,/,'');
   num = num.replace(/\//,'.');
   var num = parseFloat(num);
   if (!isNaN(num)) $(inputObj).val(num.toFixed(2));
}
/**********************/
function arrowToggle(objName,what) {
   if (!what) {
      $('#'+objName).toggle();
      $('#'+objName+'_a').toggleClass('closed');
   } else {
      if (what == 'open') {
         $('#'+objName).show();
         $('#'+objName+'_a').removeClass('closed');
      } else if (what == 'close') {  
         $('#'+objName).hide();
         $('#'+objName+'_a').removeClass('closed').addClass('closed');
      }
   }
}
/**********************/
function debug(msg) {
   if (typeof(console) != "undefined" && typeof(console.log) != "undefined") { console.log(msg); }
   else { display(msg); } 
}
/**********************/
function confirmDeleteDir(name) {
   return confirm('Are you sure you wish to delete this ENTIRE directory ('+name+
   ') and all its associated data? This is NOT reversable!');
}
function addTableSortingDateParser() {
    $.tablesorter.addParser({
		id: "dateTime",
		is: function(s) {
			return /\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}\s+@\s+(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm|AM|PM)))/.test(s);
		},
		format: function(s,table) {
   		s = s.replace(new RegExp(/(\d{1,2})[\/-](\d{1,2})[\/-](\d{2,4})\s+@\s+(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm|AM|PM)))/), "$3/$1/$2 $4");
			return $.tablesorter.formatFloat(new Date(s).getTime());
		},
		type: "numeric"
	});
}
