
// It is assumed that AJAX is supported in the web browser being used
var httpRequestSupported = true;

///////////////////////////////////////////////////////////
// Returns true if AJAX requests are supported by the 
// clients web browser.  Else false.
// On a true result, the object returned is an 
// Active-X XMLHTTP object.
//
// In Internet Explorer, you create an http object using 
// new ActiveXObject("Msxml2.XMLHTTP") or 
// new ActiveXObject("Microsoft.XMLHTTP") 
// depending on the version of MSXML installed. 
//
// In Mozilla and Safari (Gecko engine) you use 
// new XMLHttpRequest()
//
// IceBrowser is not supported in this code
//
// @return boolean
///////////////////////////////////////////////////////////
function isHttpRequestSupported() {

	if (window.XMLHttpRequest) {   
		// Test if the Gecko engine is running.  Gecko supports AJAX
		httpRequest = new XMLHttpRequest(); 
		if (httpRequest.overrideMimeType) { 
			httpRequest.overrideMimeType('text/xml'); 
		} 
	} else if (window.ActiveXObject) { 
		// Test if an IE engine is running
		try { 
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
		} catch (e) { 
			try { 
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
			} catch (e) {} 
		} 
	} 
	
	if (!httpRequest) { 
		httpRequestSupported = false;
	} 
	
	return httpRequest;
} // end function


///////////////////////////////////////////////////////////
// Makes a HTTP request back to the server given a URL.
//
// callbackFunction is a string value containing the name
// of a method to call when the HTTP request is completed.
// The resulting output of the HTTP request is passed in
// as a variable to the callback function.  The callback
// function formats the response to be displayed in 
// a web browser.
//
// if returnData is specified, the response is retruned
// in xml
//
// @param url
// @param callbackFunction
// @param returnData
///////////////////////////////////////////////////////////
function makeHttpRequest(url, callbackFunction, returnData) 
{ 
	var httpRequest = false; 
	
	// Exit if this function is not supported
	if (!httpRequestSupported) {
		return;  
	}
	
	// check if supported
	httpRequest = isHttpRequestSupported();
	
	if (!httpRequest) { 
		httpRequestSupported = false;
		return false; 
	} 
   
	// Map the response to the callback function
	httpRequest.onreadystatechange = function() { 
		if (httpRequest.readyState == 4) {       
			if (httpRequest.status == 200) { 
				if (returnData) { 
					eval(callbackFunction + '(httpRequest.responseXML)'); 
				} else { 
					eval(callbackFunction + '(httpRequest.responseText)'); 
				} 
			} else { 
				// TODO:  Keep this line commented in production.  The user will have no idea what this means.
				//alert('The AJAX request was made to our backend server and the following error occurred: ' + httpRequest.status); 
				eval(callbackFunction + '("")'); 
			} 
		} 
	} 
	
	httpRequest.open('GET', url, true); 
	httpRequest.send(null); 
} // end function







//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// *******************************************************
// Begin Part number specific JavaScript
// *******************************************************
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
	var lastLetterCode = '';
	var newLetterCode = '';
	var partNumberArray = new Array();  	// Array of all category IDs on the page to store category discounts
	var numInPartNumberArray = 0;
	var MAX_RESULTS_TO_SHOW_AT_A_TIME = 10;
	var skuTextBoxObject = null;
	
	// After this # of characters, a search is done on the SKU.  We do this for performance reasons.
	// We only do a search when this # of characters are typed in.  This becomes part of the cache key
	var NUM_OF_CHARACTERS_TO_DO_SEARCH = 2; 
	
	// Displays and hides the part number drop down menu
	function toggleBox(szDivID, iState) // 1 visible, 0 hidden
	{
		var obj = document.layers ? document.layers[szDivID] :
		document.getElementById ?  document.getElementById(szDivID).style :
		document.all[szDivID].style;
		obj.visibility = document.layers ? (iState ? "show" : "hide") : (iState ? "visible" : "hidden");
	}
	

	// @param sInString	- string to strip whitespace from
	function trimString(sInString) {
		sInString = sInString.replace( /^\s+/g, "" );// strip leading
		return sInString.replace( /\s+$/g, "" );// strip trailing
	}

	// Private method to help in drawing the drop down part number menu
	function drawOutput(textValue, startValue) {
		var outputText = '<table cellpadding="0" cellspacing="0" border="0" id="" width="100%" class="bgColor">';
		outputText+='<tr><td><table cellpadding="0" cellspacing="1" width="100%">';
		outputText+='<tr><td class="partNumber">';
		var numDisplayed = 0;
		var startElement = 0;

		if (startValue !=0) {
			var topValue = (startValue - MAX_RESULTS_TO_SHOW_AT_A_TIME) > 0 ?(startValue - MAX_RESULTS_TO_SHOW_AT_A_TIME) : 0;
			outputText+='<img src="http://img.iconcdn.com/Freemotion/images/bc_arrow.gif" onmouseover="document.getElementById(\'partNumAjax\').innerHTML=drawOutput(\''+skuTextBoxObject.value.toUpperCase()+'\','+topValue+');toggleBox(\'partNumAjax\',1);">...</a><br />';
		}
		
		for (var x = startValue; x < numInPartNumberArray && numDisplayed < MAX_RESULTS_TO_SHOW_AT_A_TIME; x++) {
			var num = partNumberArray[x];

			if (textValue == '' || textValue.length <= num.length 
				&& num.substring(0,textValue.length).toUpperCase() == textValue.toUpperCase()) {

				outputText+=x;
				outputText+=') ';
				outputText+='<a href="#" class="partNumber" onclick="javascript:document.QuickOrderForm.'+skuTextBoxObject.name+'.value=\''+num+'\'">';
				outputText+=num;
				outputText+='</a>';
				outputText+='<br />';
				numDisplayed ++;
			}
		}
		if (numDisplayed == MAX_RESULTS_TO_SHOW_AT_A_TIME) {
			outputText+='<img src="http://img.iconcdn.com/Freemotion/images/bc_arrow.gif" onmouseover="document.getElementById(\'partNumAjax\').innerHTML=drawOutput	(\''+skuTextBoxObject.value.toUpperCase()+'\','+numDisplayed+');toggleBox(\'partNumAjax\',1);">...</a>';
		}
		outputText+='</td></tr></table></td></tr></table>';
		return outputText;
	}
	
	// Draws the result of a part number search. 
	// This method parses a list of part numbers in the text field which are separated by a comma.
	// @param text	- the HTML to be displayed in the 'partNumAjax' div area
	function partNumberCallback(text) { 
		partNumberArray = new Array(); // destroy the old array and build a new one
		numInPartNumberArray = 0;
		
		var lastIndex = 0;
		for (var c = 0; c < text.length; c++) {
			if (text.charAt(c).indexOf(",") != -1) {
				if (lastIndex > 0) {
					partNumberArray[numInPartNumberArray++] = trimString(text.substring(lastIndex,c));
				}
				lastIndex = c+1;
			}
		}
		
		if (numInPartNumberArray == 0) {
			partNumberArray[numInPartNumberArray++] = 'No matching SKU';	
		}

		document.getElementById("partNumAjax").innerHTML=drawOutput(skuTextBoxObject.value.toUpperCase(),0);

		toggleBox('partNumAjax',1);
	}
	
	// Calls the view PartNumberLookup command and registers the 
	// function partNumberCallback() to be called when a result is returned.
	// The request goes back to the server if exactly NUM_OF_CHARACTERS_TO_DO_SEARCH
	// characters are typed into the textbox.
	// @param textBox	- the HTML <input> box for the part number entry form
	// @param storeId	- the Id of the current store
	// @param catalogId	- the current catalog id for the store
	function skuLookup(textBox, storeId, catalogId) {
		skuTextBoxObject = textBox;
		var textBoxValue = skuTextBoxObject.value.toUpperCase();
		
		if (textBox.value != '' && textBox.value.length==NUM_OF_CHARACTERS_TO_DO_SEARCH) {
			// Make a new request
			lastLetterCode = textBoxValue;
			var url = '/webapp/wcs/stores/servlet/PartNumberLookup?storeId='+storeId+'&catalogId='+catalogId+'&URL=PartNumberLookupView&partNumberStart='+ textBoxValue;
			makeHttpRequest(url, 'partNumberCallback');
		} else if (textBox.value != '' && textBox.value.length>NUM_OF_CHARACTERS_TO_DO_SEARCH) {
			// Parse what we have in memory
			document.getElementById("partNumAjax").innerHTML=drawOutput(textBoxValue,0);
			toggleBox('partNumAjax',1);
		}
	}

//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// *******************************************************
// End Part number specific JavaScript
// *******************************************************
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////



//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// *******************************************************
// Begin State/Province specific JavaScript
// *******************************************************
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
	
	// Draws the result of a province search.  The results are generated in ProvinceLookupDisplay.jsp
	// @param text	- the HTML to be displayed in the 'provinceAjax' div area
	function provinceCallBack(text) { 

		if (text != '') {
			document.getElementById("provinceAjax").innerHTML=text;
		}
		toggleBox('provinceAjax',1);
		busyLookingUpProvince = false;
	}
	
	// Calls the view ProvinceLookupView and registers the 
	// function provinceCallBack() to be called when a result is returned.
	// @param selectBox	- the HTML <select> box for the selected country
	// @param storeId	- the Id of the current store
	// @param catalogId	- the current catalog id for the store
	// @param selectedOption- the current province/state result to select if the address is pre filled
	function provinceLookup(selectBox, storeId, catalogId, selectedOption) {

		toggleBox('provinceAjax',0);  // hide the input box now until it is loaded
		var countryName = selectBox.options[selectBox.selectedIndex].value;			

		if (countryName != '' && countryName.length>0) {
			// Get the list of all provinces that are in the above specified country
			var url = '/webapp/wcs/stores/servlet/ProvinceLookupView?storeId='+storeId+'&catalogId='+catalogId+'&countryName='+ countryName +'&selectedOption='+ selectedOption;
			makeHttpRequest(url, 'provinceCallBack');
		} 		
	}
	
	// Called when a page loads.  This method will get all the provinces/states for the selected country
	// @param theForm	- the HTML <form> element for the form containing a <Select name='country'> element.
	// @param storeId	- the Id of the current store
	// @param catalogId	- the current catalog id for the store
	// @param selectedOption- the current province/state result to select if the address is pre filled
	function bodyOnload(theForm, storeId, catalogId, selectedOption) {
		if (theForm != undefined) {
			provinceLookup(theForm.country, storeId, catalogId, selectedOption);
		}
	}

//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// *******************************************************
// End State/Province specific JavaScript
// *******************************************************
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// *******************************************************
// Begin AJAX Resources for MQ Message waiting specific 
// JavaScript
// *******************************************************
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
	
	// Draws the result of a MQ message.  The results are generated in CustomerCreditAJAXDisplay.jsp
	// @param text	- the HTML to be displayed in the 'mqWaitAjax' div area
	function mqMessageCallBack(text) { 

		if (text != '') {
			document.getElementById("mqWaitAjax").innerHTML=text;
		}
	}
	
	// Calls the view CustomerCreditAJAXView which goes out to MQ to get a message
	// function mqMessageCallBack() to be called when a result is returned.
	// @param storeId	- the Id of the current store
	// @param catalogId	- the current catalog id for the store
	function mqMessageSend(storeId, catalogId) {

		// Call the following view which includes a Data Bean to go out to MQ to get a synchronous message
		var url = '/webapp/wcs/stores/servlet/CustomerCreditAJAXView?storeId='+storeId+'&catalogId='+catalogId;
		makeHttpRequest(url, 'mqMessageCallBack');
	}
	

//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// *******************************************************
// Begin AJAX Resources for MQ Message waiting specific 
// JavaScript
// *******************************************************
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////

	// Draws the result of a MQ message.  The results are generated in CustomerCreditAJAXDisplay.jsp
	// @param text	- the HTML to be displayed in the 'mqWaitAjax' div area
	function customerRepCallBack(text) { 
		if (text != '') {
			document.getElementById("repDetails").innerHTML=text;
		}
	}
	
	function alertFailure(XMLHttpRequest, textStatus, errorThrown) {
		if (XMLHttpRequest.responseText != '') {
			alert(XMLHttpRequest.responseText);
		} else {
			alert("There was a problem processing your request");
		}
	}
	
	function submitAjaxForm(form, callbackSuccess) {
		$.ajax({
		   type: form.method,
		   url: form.action,
		   timeout: 10000,
		   data: $(form).serialize(),
		   dataType: 'text',
		   success: callbackSuccess,
		   error: alertFailure
		});
		return false;
	}
		
	// Calls the view CustomerCreditAJAXView which goes out to MQ to get a message
	// function mqMessageCallBack() to be called when a result is returned.
	// @param storeId	- the Id of the current store
	// @param catalogId	- the current catalog id for the store
	function getRepInfo(formId, divId) {
	
		var form = document.getElementById(formId);
		var selectedState = form.state[form.state.selectedIndex].value;
		
		if (selectedState != '') {
			document.getElementById(divId).innerHTML="<b>loading</b>&nbsp;<img src='http://img.iconcdn.com/Freemotion/images/indicator.gif' alt='loading...' />";

			submitAjaxForm(form, function(data) {
				$("#" + divId).html(data)
			});
		}
	}

