//var currentPostalCodeTextbox; // Keeps track of which postal code text box the location popup will populate
var currentCityTextbox; // Keeps track of which city text box the location popup will populate
var currentStateSelect; // Keeps track of which state text box the location popup will populate
var currentLocationTextbox; // Keeps track of which text box the location popup will appear below

// For postal code
var lastSearchTerm = ""; // The last postal code we searched for
var incrementalSearchTimer; // Timer handle for postal code search

// For name (city)
var lastNameSearchTerm = ""; // The last name we searched for
var incrementalNameSearchTimer; // Timer handle for name search

// Call the postal code lookup web service
function PostalCodeIncrementalLookup()
{
	// Get the origin postal code
	var postalCodeTextBox = document.getElementById(currentPostalCodeTextbox);
	var PostalCode = postalCodeTextBox.value;

	// Call the lookup function
	StarRate.SRWebServiceProxy.PostalCodeIncrementalLookupAsString(PostalCode, OnIncrementalPostalCodeSearchSuccess, OnFailure);		
}

// Call the name lookup web service
function NameIncrementalLookup()
{
	// Get the origin postal code
	var CityTextBox = document.getElementById(currentCityTextbox);
	var City = CityTextBox.value.toUpperCase();

	// Call the lookup function
	StarRate.SRWebServiceProxy.NameIncrementalLookupAsString(City, OnIncrementalNameSearchSuccess, OnFailure);	
}

// Callback function for postal search success
function OnIncrementalPostalCodeSearchSuccess(results)
{
	// Create the location array from the results
	var locationArray = results.split("\n");
	
    // If only one result is returned then populate text boxes, else display location popup
    PopulateLocationPopup(results);    
    if (IsNumeric(locationArray[0]) && locationArray[0] == 1)
    {
        LocationSelectionMade();    
	}
	else
	{
	    DisplayLocationPopup(currentPostalCodeTextbox);
	}
}


// Callback function for postal search success
function OnIncrementalNameSearchSuccess(results)
{
	// Create the location array from the results
	var locationArray = results.split("\n");

    // If only one result is returned then populate text boxes, else display location popup
    PopulateLocationPopup(results);    
    if (IsNumeric(locationArray[0]) && locationArray[0] == 1)
    {
        LocationSelectionMade();
	}
	else
	{
	    DisplayLocationPopup(currentCityTextbox);    
	}
}

function PopulateLocationPopup(results)
{
	// Clear the select control
	var locationSelect = document.getElementById("selLocation");
	locationSelect.options.length = 0;

	// Create the location array from the results
	var locationArray = results.split("\n");

	// Check the length of the array
	if (IsNumeric(locationArray[0]))
	{
		// Populate the select control
		var recordArray = null;
		var i = 0;
		for (i = 1; i <= locationArray[0]; i++)
		{
			// postal code, city, state, country
			recordArray = locationArray[i].split(",");
			locationSelect.options[i - 1] = new Option(recordArray[0] + " " + recordArray[1] + ", " + recordArray[2] + " (" + recordArray[3] + ")", locationArray[i]);   
		}

		// Set the new size
		//locationSelect.size = locationArray[0];
		locationSelect.size = locationArray[0] > 10 ? 10 : locationArray[0];

	    // Select the first item in the list
	    locationSelect.selectedIndex = 0;
	}
	else 
	{
		// An error occured
		document.getElementById("lblError").innerHTML = locationArray[0];
	}
}

// Position and display the location popup
function DisplayLocationPopup(displayControl)
{
	var locationSelect = document.getElementById("selLocation");

	// If no results then return before displaying it
	if (locationSelect.options.length == 0)
	{
		return;
	}

	// Select the first item in the list
	locationSelect.selectedIndex = 0;

	// Calculate the position for the location popup control
	var currentTextBox = document.getElementById(displayControl);
	var locationPopup = document.getElementById("locationpopup");     
	var locationPopupTop = currentTextBox.offsetTop + currentTextBox.offsetHeight;
	var locationPopupLeft = currentTextBox.offsetLeft;
	var currentControl = currentTextBox;
	while (currentControl.offsetParent)
	{
		currentControl = currentControl.offsetParent;
		locationPopupTop += currentControl.offsetTop;
		locationPopupLeft += currentControl.offsetLeft;
	}
	
	// Set the position (the "px" is needed for Firefox)
	locationPopup.style.top = locationPopupTop + "px";
	locationPopup.style.left = locationPopupLeft + "px";
	
	// Display the popup
	locationPopup.style.display = "inline";
}

// Hide the location popup
function HideLocationPopup(e)
{
	document.getElementById("locationpopup").style.display = "none";
}

// Determine if the popup should appear, position, and display it
function DoLocationSearch(postalCodeTextboxId, cityTextboxId, stateSelectId)
{
	// Set global variables
	currentPostalCodeTextbox = postalCodeTextboxId;
	currentCityTextbox = cityTextboxId;
	currentStateSelect = stateSelectId;
	currentLocationTextbox = currentPostalCodeTextbox;

	var postalCodeTextBox = document.getElementById(postalCodeTextboxId);

	var postalCodeText = postalCodeTextBox.value

	// Make sure the text changed
	if (postalCodeText == lastSearchTerm && lastSearchTerm != "")
	{
		DisplayLocationPopup(currentPostalCodeTextbox);
		return;
	}

	if (postalCodeText.length > 2)
	{
		// Set the last search term
		lastSearchTerm = postalCodeText;

		// Do the search
		PostalCodeIncrementalLookup();
	}
}

// Populate and display the location popup control if needed
function PostalCodeTextBoxKeyDown(e, postalCodeTextboxId, cityTextboxId, stateSelectId, sitesDropDownListId)
{
	var locationPopup = document.getElementById("locationpopup");

	// Get the character number
	var keynum = GetKeyNumFromEvent(e);

	if (keynum == 40 || keynum == 13) // 40 = down arrow, 13 = enter
	{
	
		// If a query has been made previously
		if (currentPostalCodeTextbox)
		{
			// If the search term hasn't changed since the last query
			if (document.getElementById(currentPostalCodeTextbox).value == lastSearchTerm && lastSearchTerm != "")
			{
				DisplayLocationPopup(currentPostalCodeTextbox);
				var locationSelect = document.getElementById("selLocation");
				locationSelect.focus();
				return false; // Suppress down arrow            
			}
		}

		// Move to the location popup if it is visible
		if (locationPopup.style.display != "none")
		{
			var locationSelect = document.getElementById("selLocation");
			locationSelect.focus();
			return true;
		}
	}

	// Hide the location popup control
	HideLocationPopup();
	
	// Clear the city text box and state select
	if (keynum != 9 && keynum != 16 && keynum != 35 && keynum != 36) // 9 = tab, 16 = shift, 35 end, 36 home
	{	
	    document.getElementById(cityTextboxId).value = "";
	    document.getElementById(stateSelectId).options[0].selected = true;
	    if (document.getElementById(sitesDropDownListId) != null)
	    {
	        document.getElementById(sitesDropDownListId).options[0].selected = true;
	    }
	}

	// Clear any existing timer
	window.clearTimeout(incrementalSearchTimer);

	// Set a time to call the DoLocationPopup - for fast typists and so we can get the textbox's value post keydown
	// Only certain keys can cause a popup 
	// 46 = delete, 40 = down arrow, 13 = enter, 8 = backspace
	if (IsAlphaNumericKey(keynum) || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8)	
	{
		incrementalSearchTimer = window.setTimeout("DoLocationSearch('" + postalCodeTextboxId + "','" + cityTextboxId + "','" + stateSelectId + "');", 300);
	}
	
	return true;
}

// Determine if the popup should appear, position, and display it
function DoNameLocationSearch(postalCodeTextboxId, cityTextboxId, stateSelectId)
{
	// Set global variables
	currentPostalCodeTextbox = postalCodeTextboxId;
	currentCityTextbox = cityTextboxId;
	currentStateSelect = stateSelectId;
	currentLocationTextbox = currentCityTextbox;

	var cityTextBox = document.getElementById(cityTextboxId);

	var cityText = cityTextBox.value

	// Make sure the text changed
	if (cityText == lastSearchTerm && lastSearchTerm != "")
	{
		DisplayLocationPopup(currentCityTextbox);
		return;
	}

	if (cityText.length > 3)
	{
		// Set the last search term
		lastSearchTerm = cityText;

		// Do the search
		NameIncrementalLookup();
	}
}

// Populate and display the location popup control if needed
function CityTextBoxKeyDown(e, postalCodeTextboxId, cityTextboxId, stateSelectId, sitesDropDownListId)
{
	var locationPopup = document.getElementById("locationpopup");

	// Get the character number
	var keynum = GetKeyNumFromEvent(e);

	if (keynum == 40 || keynum == 13) // 40 = down arrow, 13 = enter
	{
	
		// If a query has been made previously
		if (currentCityTextbox)
		{
			// If the search term hasn't changed since the last query
			if (document.getElementById(currentCityTextbox).value == lastSearchTerm && lastSearchTerm != "")
			{
				DisplayLocationPopup(currentCityTextbox);
				var locationSelect = document.getElementById("selLocation");
				locationSelect.focus();
				return false; // Suppress down arrow            
			}
		}

		// Move to the location popup if it is visible
		if (locationPopup.style.display != "none")
		{
			var locationSelect = document.getElementById("selLocation");
			locationSelect.focus();
			return true;
		}
	}

	// Hide the location popup control
	HideLocationPopup();

	// Clear the postal code text box and state select
	if (keynum != 9 && keynum != 16 && keynum != 35 && keynum != 36) // 9 = tab, 16 = shift, 35 end, 36 home
	{
        document.getElementById(postalCodeTextboxId).value = "";
        document.getElementById(stateSelectId).options[0].selected = true;
	    if (document.getElementById(sitesDropDownListId) != null)
	    {
	        document.getElementById(sitesDropDownListId).options[0].selected = true;
	    }
    }

	// Clear any existing timer
	window.clearTimeout(incrementalSearchTimer);

	// Set a time to call the DoLocationPopup - for fast typists and so we can get the textbox's value post keydown
	// Only certain keys can cause a popup 
	// 46 = delete, 40 = down arrow, 13 = enter, 8 = backspace
	if (IsAlphaNumericKey(keynum) || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8)	
	{
		incrementalSearchTimer = window.setTimeout("DoNameLocationSearch('" + postalCodeTextboxId + "','" + cityTextboxId + "','" + stateSelectId + "');", 300);
	}
	
	return true;
}

// Make a location selection 
function LocationSelectionMade()
{
	var postalCode;
	var city;
	var state;
	var country;
	var stateAndCountry;

    var locationSelect = document.getElementById("selLocation");

	var record = locationSelect.options[locationSelect.selectedIndex].value.split(",");
	postalCode = record[0];
	city = record[1];
	state = record[2];
	country = record[3];
	stateAndCountry = state + "," + country

	// Populate the postal code, city, and state
	document.getElementById(currentPostalCodeTextbox).value = postalCode;
	document.getElementById(currentCityTextbox).value = city;
	var stateSelect = document.getElementById(currentStateSelect);
	for (i = 0; i < stateSelect.options.length; i++)
	{
		if (stateSelect.options[i].value == stateAndCountry)
		{
			stateSelect.options[i].selected = true;
			break;
		}
	}

	// Change the focus back to the text box 
	document.getElementById(currentLocationTextbox).focus()
	
	// Change the focus to the next set of controls
	//var goToTabIndex = document.getElementById(currentStateSelect).getAttribute('tabindex') + 1;
	//alert("goToTabIndex = " + goToTabIndex);

	// Hide the popup
	HideLocationPopup();
}

// Handle a click (selection) on the location popup
function LocationSelectClick()
{
	LocationSelectionMade();
}

// Handle a keypress on the location select
function LocationSelectKeyPress(e)
{
	var keynum = GetKeyNumFromEvent(e);

	if (keynum == 13) // enter
	{
		LocationSelectionMade();
	}
	if (keynum == 27) // escape
	{
		// Change the focus back to the text box
		document.getElementById(currentLocationTextbox).focus()

		// Hide the popup
		HideLocationPopup();   

		return false;         
	}
}

// Filter postal code input
function PostalCodeTextBoxKeyPress(e)
{
	ForceUppercase(e);
	var keynum = GetKeyNumFromEvent(e);
	//var keychar = GetKeyChar(keynum);
	return (IsAlphaNumericKey(keynum) || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8 || keynum == 9);	
}

// Filter city input
function CityTextBoxKeyPress(e)
{
	ForceUppercase(e);        
	var keynum = GetKeyNumFromEvent(e);
	return (IsAlphaKey(keynum) || keychar == ' ' || keynum == 46 || keynum == 40 || keynum == 13 || keynum == 8 || keynum == 9);            	
}

// Hide location popup if user clicks out of postal textbox control 
function BodyOnClick()
{
	if (document.getElementById("locationpopup").style.display != "none")
	{
		// NOTE: I thought I would have to trap whether or not the user clicked on the popup, 
		// but it doesn't seem to register the click if I do
		HideLocationPopup();
	}
}
