// This JavaScript file requires the overlib.js library to be imported on the page
// that uses it.  The overlib.js library contains the code to handle the mouseclick
// event for the state field.

var makingRequest = false;
var debugMode = false; 
var zipField, zip2Field = null;
var citiesField, cities2Field = null;
var stateField, state2Field = null;
var countryField, country2Field = null;
var getMexico = "false";
var cityStateHash = $H();
var cityState2Hash = $H();
var cityCountryHash = $H();
var cityCountry2Hash = $H();
var fieldMadeRequest = "";

String.prototype.trim = function() 
{
  return this.replace(/^\s+|\s+$/g,"");
};

// Fires when the Ajax request is created.  It only does something
// when in debug mode right now.
function handleAjaxCreate() 
{
	if (debugMode) alert('...a request has been initialized...');
};

// Start dual location functions.
// Some pages have two locations to track on their form, generally a
// shipper and receiver location.  The following 6 functions deal with
// determining which location is getting updated at the moment.
function getCitiesFieldRequested()
{
	if (fieldMadeRequest == zipField.name)
	{
		return citiesField;
	}
	else
	{
		return cities2Field;
	}
}

function getStateFieldRequested(fieldName)
{
	if (fieldName == zipField.name || fieldName == citiesField.name)
	{
		return stateField;
	}
	else
	{
		return state2Field;
	}
}

function getCityStateHashRequested(fieldName)
{
	if (fieldName == citiesField.name || fieldName == zipField.name)
	{
		return cityStateHash;
	}
	else
	{
		return cityState2Hash;
	}
}

function getCityCountryHashRequested(fieldName)
{
	if (fieldName == citiesField.name || fieldName == zipField.name)
	{
		return cityCountryHash;
	}
	else
	{
		return cityCountry2Hash;
	}
}

function getCountryFieldRequested(fieldName)
{
	if (fieldName == citiesField.name)
	{
		return countryField;
	}
	else
	{
		return country2Field;
	}
}

function setFieldMadeRequest(value)
{
	fieldMadeRequest = value;
	if (debugMode) alert("fieldMadeRequest - " + fieldMadeRequest);
}
// End dual location functions.

// Handles the response from the Ajax request.  Should receive a "|" delimited
// list of cities, states and countries that correspond to the given zipcode.  
// Whatever values that were in the cities list are removed and the new list appended.   
function handleAjaxComplete(xmlHttpRequest, jsonObj) 
{
	makingRequest = false; // Ajax request complete, so set to false
	try 
	{
		var response = xmlHttpRequest.responseText;
		var thisStateField = getStateFieldRequested(fieldMadeRequest);
		var thisCitiesField = getCitiesFieldRequested();
		var thisCityStateHash = getCityStateHashRequested(fieldMadeRequest);
		var thisCityCountryHash = getCityCountryHashRequested(fieldMadeRequest);

		if (response.length == 2) InvalidPopup(false);
		clearCityList(thisCitiesField);
		thisStateField.value = "";
		
		var x = 0;
		var responseList = response.split("|");
		var temp;
		for(x = 0; x < responseList.length; x++)
		{
			newOption = document.createElement("OPTION");
			temp = responseList[x].split(",");
			newText = document.createTextNode(temp[0]);
			newOption.appendChild(newText);
			thisCitiesField.appendChild(newOption);
			thisCityStateHash.set(temp[0],temp[1]);
			thisCityCountryHash.set(temp[0],temp[2]);
		}
	} 
	catch(error) 
	{
	  	alert("handleAjaxComplete Error: " + error.name + " " + error.description);
	}
};

function clearCityList(thisCitiesField)
{
	thisCitiesField.options.length = 0;
	newOption = document.createElement("OPTION");
	newText = document.createTextNode("Choose City");
	newOption.appendChild(newText);
	thisCitiesField.appendChild(newOption);
}

function isNumeric(n) 
{   
	return !isNaN(parseFloat(n)) && isFinite(n); 
} 

function InvalidPopup(isZipOk)
{
	if (!isZipOk)
	{
		alert("Invalid Zip Code!");
		clearCityList(getCitiesFieldRequested(fieldMadeRequest));
	}
}

function isValidZip(zip)
{
	var sendRequest = false;
	
		if (zip.length > 5) // Canada
		{
			var canadaRegExp = new RegExp(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)/i);
			sendRequest = canadaRegExp.test(zip);
			InvalidPopup(sendRequest);
		}
		else if (zip.length > 4 && isNumeric(zip))// US Zip
		{
			var usaRegExp = new RegExp(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}$)/i);
			sendRequest = usaRegExp.test(zip);
			InvalidPopup(sendRequest);
		}

	return sendRequest;
}

// Sets the two global fields from the passed field names.
// Assigns the handleChangeZip function to the zipField's onchange event.
function initCitiesFromZip(zipFieldName, citiesFieldName, stateFieldName, countryFieldName
							, zip2FieldName, cities2FieldName, state2FieldName, country2FieldName, includeMexico)
{
	try 
	{
		if (debugMode) alert("initCitiesFromZip");
		
		zipField = $(zipFieldName);
		citiesField = $(citiesFieldName);
		stateField = $(stateFieldName);
		countryField = $(countryFieldName);
		zip2Field = $(zip2FieldName);
		cities2Field = $(cities2FieldName);
		state2Field = $(state2FieldName);
		country2Field = $(country2FieldName);
		if(includeMexico != null){
			getMexico = includeMexico;
		}
		
		setZipFieldEventHandlers();
		setStateFieldEventHandlers();
		setCityFieldEventHandlers();
	} 
	catch(error) 
	{
	  	alert("initCitiesFromZip() Error: " + error.name + " - " + error.description);
	}
};

// Handles the zipField's onkeyup event.  It sends an Ajax request to the Location
// servlet, passing the GetCitiesFromZip function name and the zip code.
function handleKeyUpZip(event) { 
	
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 37 || keyCode == 39 || keyCode == 13) 
	{
		return false;
	}
	
	setFieldMadeRequest(this.name);
	if (isValidZip(this.value))
	{
	    if (!makingRequest) 
	    {
			makingRequest = true;	// Ajax request initiated, so set to true
			var ajax = 
				new Ajax.Request(
					'/servlet/Location',
					{
						method: 	'get', 
						parameters:	{ 
							action: 		'doGet', 
					 		whichFunc: 		'GetCitiesFromZip',
					 		zipCode: 		this.value,
					 		getMexico:		getMexico
					 	}, 
						onCreate:	handleAjaxCreate,
						onComplete: handleAjaxComplete 
					}
				);
			return true;
	    } 
	    else 
	    {
			return false;
	    }
	}
};

//The following functions handle events for the various fields.
function setZipFieldEventHandlers()
{
	Event.observe(zipField, 'keyup', handleKeyUpZip);
	if (zip2Field != null) {
		Event.observe(zip2Field, 'keyup', handleKeyUpZip);
	}
}

function setStateFieldEventHandlers()
{
	if(stateField != null){
		Event.observe(stateField, 'click', handleClickState);
		Event.observe(stateField, 'mouseout', handleMouseoutState);
	}
	if(state2Field != null){
		Event.observe(state2Field, 'click', handleClickState);
		Event.observe(state2Field, 'mouseout', handleMouseoutState);
	}
}

function setCityFieldEventHandlers()
{
	if(citiesField != null){
		Event.observe(citiesField, 'change', handleChangeCity);
	}
	if(cities2Field != null){
		Event.observe(cities2Field, 'change', handleChangeCity);
	}
}

// Creates a popup textbox if the user clicks on the state field.
function handleClickState()
{
	overlib('Please input the zip code and select the city and the appropriate state will be selected.' 
			,CENTER, ABOVE, FGCOLOR,'#A1101B');
}

// Gets rid of the textbox when the user moves the mouse away from the state field.
function handleMouseoutState()
{
	nd();
}

function handleChangeCity()
{
	var stateHash = getCityStateHashRequested(this.name);
	var countryHash = getCityCountryHashRequested(this.name);
	var thisStateField = getStateFieldRequested(this.name);
	var thisCountryField = getCountryFieldRequested(this.name);
	var thisField = $(this);

	if (!thisField.options[thisField.selectedIndex].text.strip() == ""
		&& thisField.options[thisField.selectedIndex].text.strip() != "Choose City")
	{
		if (thisStateField != null)
		{
			thisStateField.value = stateHash.get(thisField.options[thisField.selectedIndex].text);
		}
		
		if (thisCountryField != null)
		{
			thisCountryField.value = countryHash.get(thisField.options[thisField.selectedIndex].text);
		}
	}
}	
