/*=================================================================================
	There is logic in place in the js.gsp file to only include this file on the
	product pages.
/*=================================================================================*/
var timeStamp = (new Date()).getTime(); //unique timestamp to stop IE from caching ajax requests
var query = location.search.substr(1, location.search.length-1); //get the query string from appended to the URL
var isProdDetailPage = false; //default set to false... true value set in "refineSearchProducts.gsp"

$(document).ready(function() { //DOM is loaded
	currHost = window.location.pathname; //grab the path of the URL for later evaluation
	targExp = /\/products\//; //regular expression searching for the term "/products/"
	targString = String(currHost.match(targExp)); //boolean to determine if reg exp was found in URL path
	if(targString == "/products/"){ //if found, we can safely assume we need to repopulate the filter
		repopProdFilter(); 
	}
	else { //if not found, we can safely assume that we are on the products landing page
		initProdFilter();
	}
	
	/*
	// We are currently using the default behavior to sumbit the form. 
	// The method below should be used for asynchronous requests.
	$("#btn_submit_prodFilter").click(function(){ //bind click event to submit button
		$("#productFilter_form").ajaxSubmit(); //submit form
		return false;
	});
	*/
	
	if(jQuery.browser.safari){ //Safari and Google Chrome
		//We will not be creating custom select boxes in Safari or Chrome
		//The default behavior of select boxes is sufficient in these browsers
		$('.origSelectBox').css('display','block'); //display original select menus in safari/chrome browsers
	}
}); //end: document.ready();

/////////////////////////////////////////////////////////////////////////////////////////
//===== START: PRODUCT FILTER FUNCTIONS ==============================================//
/////////////////////////////////////////////////////////////////////////////////////// 
/*
 BECAUSE WE ARE USING CUSTOM IMAGES in place of regular <input> tags for our radio buttons and checkboxes, we must simulate a click event.
 the following code captures a mouse-click anywhere on the page and determines if it originated from a custom form element.
 if it did, we then get the ID attribute of the very next sibling element from the DOM (which will be the original <input> radio button).
 once we have this object, we can simulate a click event to trigger the necessary updates to other elements which may have dependencies on this selection.
*/
$(document).bind('click', function(e) { //bind click event to entire document
	var clicked = $(e.target); //reference to the clicked object
	var getClass = clicked.attr('class'); //get object's class attribute
	var targObjID = ""; //var to hold the target object's ID attribute
	if(getClass == "radio"){ //if the click happened on a radio button
		targObjID = ($(clicked).next().attr("id")); //get the ID of the next sibling element
		if(targObjID == "radio-PD" || targObjID == "radio-SD") {
			if(targObjID == "radio-PD") {
				$("#lifestage_wrapper").hide();
			}
			else if(targObjID == "radio-SD") {
				$("#lifestage_wrapper").show();
			}
			$("#"+targObjID).trigger("click"); //simulate an onclick event
		}
		else if(targObjID == "radio-feline" || targObjID == "radio-canine") {
			$("#"+targObjID).trigger("click"); //simulate an onclick event
		}
	}
});

function initProdFilter(){ //initialize filter to default status (no query params passed)
	/*
	 Default status is as such...
	 - PD will be selected on page load
	 - Feline will be selected on page load
	 - Lifestage's will be hidden on page load (due to PD being selected)
	 	*note - anytime PD is selected, lifestage should not be displayed and should be cleared of any selected values
	 - Nothing will be selected for "food form" (wet,dry,treats) on page load
	 - Disease/Condition will be enabled and will load feline conditions on page load
	 - Sub Disease/Condition will be disabled on page load
	*/
	var currSpecies = $('input:checkbox[name=species]:checked').val(); //get the current selected species
	Custom.init(); //initialize the Custom Radio/Checkbox code
	
	$("#lifestage_wrapper").hide(); //hide both lifestage's by hiding the lifestage wrapper
	$("#lifestage_feline").show(); //feline will be the selected default species so will initiate the feline lifestage
	getConditions("cat"); //populate the conditions dropdown menu
	
	$("#radio-PD").click(function() {
		$("#lifestage_feline input").each(function(){ //reset feline lifestage checkBoxes
			$(this).attr('checked', false);
		});
		$("#lifestage_canine input").each(function(){ //reset canine lifestage checkBoxes
			$(this).attr('checked', false);
		});
	});
	
	$("#radio-feline").click(function(){
		$("#lifestage_feline").show();
		$("#lifestage_canine").hide();
		$("#lifestage_canine input").each(function(){ //reset canine lifestage checkBoxes
			$(this).attr('checked', false);
		});
		currSpecies = $(this).val();
		removeAllMenus();
		getConditions(currSpecies);
	});
	$("#radio-canine").click(function(){
		$("#lifestage_feline").hide();
		$("#lifestage_canine").show();
		$("#lifestage_feline input").each(function(){ //reset feline lifestage checkBoxes
			$(this).attr('checked', false);
		});
		currSpecies = $(this).val();
		removeAllMenus();
		getConditions(currSpecies);
	});
	$("#selectDisease").change(function(){
		var species = currSpecies;
		var condition = $(this).val();
		$("#target_selectSubDisease").remove();
		getSubConditions(species, condition);
	});  
} //end initProdFilter()

function repopProdFilter() { //repopulate the filter based of found query params or meta-data
	if(isProdDetailPage == true) { //assume we are populating the filter on a product detail page
		//alert('isDetail=true');
		targExp = /product-search-results/;
		targString = String(pageRefer.match(targExp)); //boolean to determine if reg exp was found
		if(targString == "product-search-results"){ //if found, display "back to list" link
			$('#productOverviewBack').css('display','block');
		}
		metaBrand = metaBrand.toLowerCase().replace(/\b\w/g, function(match){return match.toUpperCase();}); //capatilize the first letter of each word
		metaLifeStage = metaLifeStage.toLowerCase(); //convert entire string to lowercase
		//create dynamic form to utilize jquery's serialize() method (temporarily add to the DOM)
		$('body').append('<form id="dynaForm">' 
			//the following variables are being set inside of "refineSearchProducts.gsp"
			+'<input type="hiddden" name="brand" value="'+metaBrand+'" />'
			+'<input type="hiddden" name="species" value="'+metaSpecies+'" />'
			+'<input type="hiddden" name="lifestage" value="'+metaLifeStage+'" />'
			+'<input type="hiddden" name="form" value="'+metaProdForm+'" />'
			+'</form>'
		); 
		query = $('#dynaForm').serialize(); //this generates the querystring in the format needed to repopulate the form later
		$('#dynaForm').remove(); //remove dynamic form from the DOM (send to trash collection)
		populate("productFilter_form", query);
		$("#productFilter_form").attr("action","product-search-results.html");
	}
	else { //assume we are on the product search results page
		populate("productFilter_form", query);
		$("#productFilter_form").attr("action","product-search-results.html");
	}
} //end repopProdFilter()

function reInitProdFilter(){ //initialize filter using query params found
	var currSpecies = $('input:radio[name=species]:checked').val(); //get the current selected species from repopulated form
	var currBrand = $('input:radio[name=brand]:checked').val(); //get the current selected brand
	var currCondition = $.getUrlVar('condition'); //get "condition" from URL querystring
	var currSubCondition = $.getUrlVar('subcondition'); //get "subcondition" from URL querystring
	Custom.init(); //initialize the Custom Radio/Checkbox code
	
	$("#radio-PD").click(function() {
		$("#lifestage_feline input").each(function(){ //reset feline lifestage checkBoxes
			$(this).attr('checked', false);
		});
		$("#lifestage_canine input").each(function(){ //reset canine lifestage checkBoxes
			$(this).attr('checked', false);
		});
	});
	
	if(currBrand){
		if(currBrand == "Prescription Diet") {
			$("#lifestage_wrapper").hide(); //hide both lifestage's by hiding the lifestage wrapper
		}
		else if (currBrand == "Science Diet") {
			$("#lifestage_wrapper").show(); //show both lifestage's
		}
	}
	
	if(currSpecies == "dog") { //current species is canine
		$("#lifestage_canine").show(); //show canine lifestage
		getConditions("dog"); //fetch canine conditions
		$("#lifestage_feline input").each(function(){ //reset feline lifestage checkBoxes
			$(this).attr('checked', false);
		});
	}
	else { //current species is feline
		$("#lifestage_feline").show(); //show feline lifestage
		getConditions("cat"); //fetch feline conditions
		$("#lifestage_canine input").each(function(){ //reset canine lifestage checkBoxes
			$(this).attr('checked', false);
		});
	}
	
	$("#radio-feline").click(function(){
		currSpecies = $(this).val();
		$("#lifestage_feline").fadeIn("slow");
		$("#lifestage_canine").hide();
		$("#lifestage_canine input").each(function(){ //reset canine lifestage checkBoxes
			$(this).attr('checked', false);
		});
		resetSubConditions();
		removeAllMenus();
		getConditions($(this).val());
	});
	$("#radio-canine").click(function(){
		currSpecies = $(this).val();
		$("#lifestage_feline").hide();
		$("#lifestage_canine").fadeIn("slow");
		$("#lifestage_feline input").each(function(){ //reset feline lifestage checkBoxes
			$(this).attr('checked', false);
		});
		resetSubConditions();
		removeAllMenus();
		getConditions($(this).val());
	});
	$("#selectDisease").change(function(){
		var species = currSpecies;
		var condition = $(this).val();
		$("#target_selectSubDisease").remove();
		getSubConditions(species, condition);
	}); 
	
	if(currCondition && currSubCondition){
		currCondition = fixQString(currCondition);
		currSubCondition = fixQString(currSubCondition);
		setTimeout('repopBothConditions("'+currCondition+'","'+currSubCondition+'")', 500);
	}
	else if(currCondition){ 
		currCondition = fixQString(currCondition);
		setTimeout('repopOnlyConditions("'+currCondition+'")', 500);
	}
	
} //reInitProdFilter()

function repopOnlyConditions(currCondition) {
	$("#selectDisease option[value='"+currCondition+"']").attr("selected", true);
	removeAllMenus();
	if(jQuery.browser.safari){ //Safari and Google Chrome
		//do not create custom select boxes
	}
	else { //browser is MSIE or FF
		createDropDown("selectDisease");
	}
	$("#selectDisease").trigger("change");
} //repopOnlyConditions()

function repopBothConditions(currCondition,currSubCondition) {
	removeAllMenus();
	$("#selectDisease option[value='"+currCondition+"']").attr("selected", true);
	if(jQuery.browser.safari){ //Safari and Google Chrome
		//do not create custom select boxes
	}
	else { //browser is MSIE or FF
		createDropDown("selectDisease");
	}
	$("#selectDisease").trigger("change");
	setTimeout('repopSubConditions("'+currSubCondition+'")',500);
} //repopBothConditions()

function repopSubConditions(currSubCondition){
	$("#selectSubDisease option[value='"+currSubCondition+"']").attr("selected", true);
	$("#target_selectSubDisease dt a").html($("#selectSubDisease option:selected").html()); //simulate selected option 
	$("#target_selectSubDisease dt a span").html(currSubCondition);
} //repopSubConditions

function removeAllMenus(){
	$("#target_selectDisease").remove();
	$("#target_selectSubDisease").remove();
} //removeAllMenus()

function resetSubConditions(){
	var options = "<option value=''>Select Sub Disease/Condition</option>";
	$("select#selectSubDisease").html(options);
	$("select#selectSubDisease").attr("disabled", "true");
	$("#target_selectSubDisease").remove();
	createDropDown("selectSubDisease");
} //resetSubConditions()


///////////////////////////////////////////////////////////////////////////////////////////
//==== START: POPULATE FORMS VIA QUERYSTRING PARAMS ====================================//
//preset.js  Copyright 2009 by Richard L. Trethewey - All Rights Reserved
//Permission is granted to use this code as long as this copyright notice
//is left intact.  For more information, see http://www.rainbodesign.com/pub/
/*================================================================================*/
function findForm(theForm) {
	var formCount = document.forms.length;
	if (document.getElementById) {
		formElement = document.getElementById(theForm); 
	} 
	else {
		for (i=0; i<formCount; i++) {
			if (document.forms[i].name == theForm) { formElement = document.forms[i]; }
	    }
	}
	return formElement;
} //findForm()  

function setOption(theOption,choice) {
	max = theOption.length;
	for (i = 0; i < max; i++) {
	   if (theOption.options[i].value == choice) { theOption.options.selectedIndex = i; }
	}
} //setOption()

function setRadio(theOption,optionName) {
  max = theOption.length;
   for (i = 0; i < max; i++) { 
	//alert(theOption[i].name + ' ' + theOption[i].checked);
    if (theOption[i].value == optionName) { theOption[i].checked = true; }
   }
} //setRadio()

function fixQString(theStr) {
	pattern = '\\+';
	flags = 'g';
	reg_exp = new RegExp(pattern, flags);
	theStr = theStr.replace(reg_exp, ' ');
	theStr = unescape(theStr);
	return theStr;
} //fixQString()

function populate(formName, query) {
	if (query) {
		var params =  query.split("&"); 
		var theForm = findForm(formName); 
		if (theForm != null) {
			for (q=0; q<params.length; q++) {
				xy = params[q].split("="); 
				paramName = xy[0];
				newValue = fixQString(xy[1]);
				if (theForm.elements[paramName]) { 
					//alert(theForm.elements[paramName].type + ' ' + paramName);
					switch(theForm.elements[paramName].type) {
						case 'text':theForm.elements[paramName].value = newValue;
						break;
						
						case 'hidden': theForm.elements[paramName].value = newValue;
						break;
						
						case 'select-one': setOption(theForm.elements[paramName], newValue);
						break;
						
						case undefined: setRadio(theForm.elements[paramName], newValue);
						break;
						
						case 'checkbox': theForm.elements[paramName].checked = true;
						break;
					} 
				} 
			} 
		} 
	} 
	reInitProdFilter();
} //populate()

///////////////////////////////////////////////////////////////////////////////////////////
//==== END: POPULATE FORMS VIA QUERYSTRING PARAMS ======================================//
/////////////////////////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////////////////////////
//==== START: POPULATE DISEASE/CONDITION SELECTBOX(S)  ================================//
////////////////////////////////////////////////////////////////////////////////////////
function getConditions(species){
	$.ajax({
		type: "GET",
		url: "/hillsvet-web/conditions.groovy?species=" + species,
		cache: false,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data){	
			//alert("json[array].length = " + data.length);
			var options = "<option value=''>Select Disease/Condition</option>";      
			for (var i = 0; i < data.length; i++) {
				options += "<option value='" + data[i].key + "'>" + data[i].value + "</option>";
			}      
			$("select#selectDisease").html(options);
			$("select#selectDisease").removeAttr("disabled");
			if(jQuery.browser.safari){ //Safari and Google Chrome
				//do not create custom select boxes
			}
			else { //browser is MSIE or FF
				createDropDown("selectDisease");
				createDropDown("selectSubDisease");
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			alert("product_searchFilterWidget = getConditions()\n XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
		}
	});
} //getConditions()

function getSubConditions(species, condition){
	$.ajax({
		type: "GET",
		url: "/hillsvet-web/conditions.groovy?species=" + species + "&condition=" + condition,
		cache: false,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(data){	
			//alert("json[array].length = " + data.length);
			var options = "<option value=''>Select Sub Disease/Condition</option>";      
			if (data.length < 1){
				options = "<option value=''>Not Applicable</option>";
			}
			for (var i = 0; i < data.length; i++) {
				options += "<option value='" + data[i].key + "'>" + data[i].value + "</option>";
			}      
			$("select#selectSubDisease").html(options);
			if (data.length > 0){
				$("select#selectSubDisease").removeAttr("disabled");
			}
			else {
				$("select#selectSubDisease").attr("disabled", "true");
			}
			if(jQuery.browser.safari){ //Safari and Google Chrome
				//do not create custom select boxes
			}
			else { //browser is MSIE or FF
				createDropDown("selectSubDisease");
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			alert("product_searchFilterWidget = getSubConditions()\n XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
		}
	});
} //getSubConditions()
//////////////////////////////////////////////////////////////////////////////////////////
//==== END: POPULATE DISEASE/CONDITION SELECTBOX(S) ===================================//
////////////////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////////////
//==== CUSTOM JQUERY FUNCTIONS =====================================================//
/////////////////////////////////////////////////////////////////////////////////////
$.extend({ //Add custom jquery function to get URL params
	getUrlVars: function(){
		var vars = [], hash;    
		var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');    
		for(var i = 0; i < hashes.length; i++) {
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
		return vars;  
	}, getUrlVar: function(name){
		return $.getUrlVars()[name];  
	}
});
///////////////////////////////////////////////////////////////////////////////////
//==== END: CUSTOM JQUERY FUNCTIONS =============================================/
/////////////////////////////////////////////////////////////////////////////////