var l_sStateCodes = "AA,AE,AK,AL,AP,AR,AS,AZ,CA,CO,CT,DC,DE,FL,GA,GU,HI,IA,ID,IL,IN,KS,KY,LA,MA,MD,ME,MI,MN,MO,MP,MS,MT,NC,ND,NE,NH,NJ,NM,NV,NY,OH,OK,OR,PA,PR,PW,RI,SC,SD,TN,TX,UT,VA,VI,VT,WA,WI,WV,WY";
var ajaxElem;
var ajaxElemList;
var iAjaxElem;	/* required because there are three freetext location boxes rather than just one */
var objAjaxElem;
var bTopAjaxElemSelected = false;

var ar_bValidLocation = new Array(true,true,true);
var ar_sLocationLockDown = new Array("","","");

var bHasFocusFreetext = false;
var bHasFocusLocationChoices = false;
var bMenu = false;

function bValidStateCode(sValue)	{

	sValue = sValue.toUpperCase();
	if(sValue.length == 2 && l_sStateCodes.indexOf(sValue) != -1)	{
		return true;
	}
	else	{
		return false;
	}
}

function doShowHide(iElem, whatAction)	{

	if(iElem == -1)	{	// there is a single freetext elem on page, eg: on homepage
		thisLocationDv = locationDv;
	}
	else	{
		thisLocationDv = locationDv[iElem];
	}

	if(whatAction == "show")	{
		thisLocationDv.style.display = "inline";	// show Ajax drop-down

		if(iElem != -1)	{	// for advanced search page only - have to hide some elements which go behind drop-down
			if(iElem < 2)	{
				document.getElementsByName('radiusSpan')[iElem + 1].style.visibility = "hidden";
				document.getElementById('topDropDown').style.display = "inline";
				if(iElem < 1)	{
					document.getElementsByName('radiusSpan')[iElem + 2].style.visibility = "hidden";
				}
			}
			else	{
				document.getElementById('positiontype').style.visibility = "hidden";
			}
		}
	}
	else	{
		thisLocationDv.style.display = "none";	// hide Ajax drop-down
		
		if(iElem != -1)	{	// for advanced search page only - have to show some elements again which go behind drop-down
			if(iElem < 2)	{
				document.getElementsByName('radiusSpan')[iElem + 1].style.visibility = "visible";
				document.getElementById('topDropDown').style.display = "none";
				if(iElem < 1)	{
					document.getElementsByName('radiusSpan')[iElem + 2].style.visibility = "visible";
				}
			}
			else	{
				document.getElementById('positiontype').style.visibility = "visible";
			}
		}
	}
}

function doShowHideElement(whichElem, whatAction)	{

	document.getElementById(whichElem).style.display = whatAction;
}

function handleArrowKeys(evt) {
    evt = (evt) ? evt : ((window.event) ? event : null);
    if (evt) {
    
    	// set vars dependent on whether single or multiple freetext location boxes
    	if(iAjaxElem == -1)	{	// there is a single freetext elem on page, eg: on homepage
			var thisLocationElemNumber = 0;
			var thisLocationChoice = eval(formName.locationChoices);
		}
		else	{
			var thisLocationElemNumber = iAjaxElem;
			var thisLocationChoice = eval(formName.locationChoices[iAjaxElem]);
		}
		
    	/* when arrow down (keyCode == 40) is pressed */
        if(evt.keyCode == 40	/* arrow down */
        	&& document.getElementsByName("locationDiv")[thisLocationElemNumber].style.display == "inline"
        		&& thisLocationChoice.options.length > 0)	{

        	if(bHasFocusFreetext)	{	/* when focus is in freetext box */
        		thisLocationChoice.selectedIndex = 0;
        		thisLocationChoice.focus();
        	
        		bHasFocusLocationChoices = true;
        	
	        	bTopAjaxElemSelected = true;	// this flag is to indicate that the next arrow up will take focus into freetext box
        		bHasFocusFreetext = false;
        	}
        	else	{
        		bTopAjaxElemSelected = false;	// this ensures that focus doesn't hop off first selection as soon as you move up to it from the second element in the drop-down list
        	}
        }
        /* when arrow down (keyCode == 38) is pressed and when focus is in location choices Ajax drop-down box */
        else if(bHasFocusLocationChoices && evt.keyCode == 38)	{	/* arrow up */
        	if(thisLocationChoice.selectedIndex == 0)	{	// top option is selected so arrow up takes focus out of drop-down and into freetext box
        		if(bTopAjaxElemSelected)	{	// this condition means that focus doesn't hop off first selection as soon as you move up to it from the second element in the drop-down list
        			thisLocationChoice.selectedIndex = -1;
        			thisLocationChoice.blur();
        			
        			iSuffix = iAjaxElem>0?(iAjaxElem + 1).toString():"";	// only put suffix if 2nd or 3rd element (1 or 2 in array)
					sThisRadLoc = eval("formName.sRadiusLocation" + iSuffix);
	        		sThisRadLoc.focus();
	        		
	        		bHasFocusLocationChoices = false;
	        		bHasFocusFreetext = true;
        		}
        		else	{
        			bHasFocusLocationChoices = true;
	        		bTopAjaxElemSelected = true;
	        		bHasFocusFreetext = false;
        		}
        	}
        	else	{
        		bHasFocusLocationChoices = true;
        		bTopAjaxElemSelected = false;
        		bHasFocusFreetext = false;
        	}
        }
        else if(bHasFocusLocationChoices && evt.keyCode == 13)	{	/* enter */
        	if(thisLocationChoice.options.length > 0)	{
        		doSetValue(objAjaxElem, iAjaxElem, thisLocationChoice.options[thisLocationChoice.selectedIndex].value);
        		objAjaxElem.focus();
        		return false;
        	}
        }
        else if(bHasFocusLocationChoices && evt.keyCode == 27)	{	/* escape */
        	doSetValue(objAjaxElem, iAjaxElem, "");
        }
        else if(bHasFocusFreetext && objAjaxElem.value == "")	{
        	doSetValue(objAjaxElem, iAjaxElem, "");
        	doSearch(iAjaxElem, objAjaxElem.value);
        }
        else if(bHasFocusFreetext)	{
        	if(USTrim(objAjaxElem.value) != USTrim(ar_sLocationLockDown[iAjaxElem]))	{
        		doSearch(iAjaxElem, objAjaxElem.value);
        	}
        }
    }
}

function handleMouseClicks(evt) {
    evt = (evt) ? evt : ((window.event) ? event : null);

    if (evt) {
        if(bHasFocusFreetext)	{
        	if(objAjaxElem.value == "")	{
	        	doSetValue(objAjaxElem, iAjaxElem, "");
	        	objAjaxElem.focus();
	        }
	        else	{
	        	if(USTrim(objAjaxElem.value) != USTrim(ar_sLocationLockDown[iAjaxElem]))	{
	        		doSearch(iAjaxElem, objAjaxElem.value);
	        	}
	        }
        }
    }
}

function handleMouseMoves(evt) {
    evt = (evt) ? evt : ((window.event) ? event : null);

	if(bMenu)	{
		bMenu = false;
	    if (evt) {
	        if(bHasFocusFreetext)	{
	        	if(objAjaxElem.value == "")	{
		        	doSetValue(objAjaxElem, iAjaxElem, "");
		        	objAjaxElem.focus();
		        }
		        else	{
			    	doSearch(iAjaxElem, objAjaxElem.value);
		        }
	        }
	    }
	}
}

function setBMenu()	{
	bMenu = true;
}

function doSearch(iElem, thisString)	{
	
	if(iElem == -1)	{	// there is a single freetext elem on page, eg: on homepage
		thisRadiusElem = formName.iRadius;
	}
	else	{
		iSuffix = (iElem + 1).toString().replace("1", "");
		thisRadiusElem = eval("formName.iRadius" + (isNaN(iSuffix)?"":iSuffix));
		
		thisRadiusElem.disabled = true;
	}
	
	var thisUrl = "/v2/ajax_cf/us_locations/qFindLocations_US.cfm?locationString=" + escape(thisString);
	iAjaxElem = iElem;
	if((isNaN(thisString) && thisString.length > 3) || thisString.length > 4)	{
		doAjax(thisUrl);
	}
	
	ar_bValidLocation[iElem] = bValidStateCode(thisString) || USTrim(thisString) == "";	/*	typed value is invalid (ie: incomplete) unless it is a statecode or empty - except for valid statecodes and empty string, typed value becomes valid only by clicking on Ajax option	*/
}

function doPopulateSelectBox(iElem, thisList)	{

	if(iElem == -1)	{	// there is a single freetext elem on page, eg: on homepage
		thisLocationChoice = formName.locationChoices;
	}
	else	{
		thisLocationChoice = formName.locationChoices[iElem];
	}
	thisLocationChoice.options.length = 0;
	if(typeof thisList != "undefined" && thisList != "")	{
	
		var thisArray = thisList.split("|");
		
		if(thisArray.length > 0)	{
			/* Ajax has returned some results so display drop-down (and hide other 2 drop-downs if they are open) */
			if(iElem != -1)	{	// for advanced search page only
			
				for(i=0; i <= 2; i++)	{
					if(i != iElem)	{
						if(locationDv[i].style.display != "none")	{
							doShowHide(i, "hide");
						}
						
						iSuffix = (i + 1).toString().replace("1", "");
						thisRadiusLocation = eval("formName.sRadiusLocation" + (isNaN(iSuffix)?"":iSuffix));
						thisRadiusLocation.value = ar_sLocationLockDown[i];	/* put in last valid value as a location has not been selected */
					}
				}
				for(i=0; i <= 2; i++)	{
					if(i == iElem)	{
						doShowHide(i, "show");
					}
				}
			}
			else	{
				doShowHide(-1, "show");
			}
			
			for(i=0; i < thisArray.length; i++)	{
				thisOption = new Option(thisArray[i], thisArray[i]);
				thisLocationChoice.options[i] = thisOption;
			}
		}
		else	{
			doShowHide(iElem, "hide");	/* No results from Ajax so hide drop-down */
		}
	}
	else	{
		doShowHide(iElem, "hide");	/* No results from Ajax so hide drop-down */
	}
}

function doAjax(url)	{

	if (window.XMLHttpRequest) {
		ajaxObj = new XMLHttpRequest();
	} else if (window.ActiveXObject) {

		var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp",	"MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.4.0",	"MSXML2.XmlHttp.5.0"];
		for (var i = avers.length -1; i >= 0; i--)
		{
			try {
				ajaxObj = new ActiveXObject(avers[i]);
			} catch(e) {}
		}
	}

	ajaxObj.onreadystatechange = doProcessRequest;
	ajaxObj.open("GET", url, true);
	ajaxObj.send(null);
}

function doProcessRequest()	{

	if (ajaxObj.readyState == 4) {
		if (ajaxObj.status == 200) {
			ajaxElemList = ajaxObj.responseText;
			doPopulateSelectBox(iAjaxElem, ajaxElemList);
		}
		else	{
			alert ("Unable to retrieve data.");/* Ajax request failed */
		}
	}
}

function doSetValue(sThisLoc, iElem, thisValue)	{

	if(iElem == -1)	{	// there is a single freetext elem on page, eg: on homepage
	
		thisRadiusElem = formName.iRadius;
	}
	else	{
	
		iSuffix = (iElem + 1).toString().replace("1", "");
		thisRadiusElem = eval("formName.iRadius" + (isNaN(iSuffix)?"":iSuffix));
		
		thisRadiusElem.disabled = true;
	}

	if(thisValue && thisValue != "" && thisValue.indexOf("unknown zip") == -1  && thisValue.indexOf("no location found") == -1)	{
		ar_sLocationLockDown[iElem] = thisValue;
		sThisLoc.value = ar_sLocationLockDown[iElem];
		thisRadiusElem.disabled = false;
		ar_bValidLocation[iElem] = true;
	}
	else if(ar_sLocationLockDown[iElem] != "" && sThisLoc.value != "")	{
		sThisLoc.value = ar_sLocationLockDown[iElem];
		thisRadiusElem.disabled = false;
		ar_bValidLocation[iElem] = true;
	}
	else	{
		ar_sLocationLockDown[iElem] = "";
		sThisLoc.value = ar_sLocationLockDown[iElem];	/* invalid data, so clear text box */
		thisRadiusElem.disabled = true;
		ar_bValidLocation[iElem] = true;
		
	}
	if (iElem) doShowHide(iElem, "hide");	/* User has selected location so hide drop-down */
}

function fn_BCheckLocationData()	{

	return (ar_bValidLocation[0] && ar_bValidLocation[1] && ar_bValidLocation[2]);	/*	returns true only if all elems are true	*/
}



function doToggleTabs(whatAction)	{

	if(whatAction != "nothing")	{

		USTb.style.display = (whatAction == "Global")?"none":"block";
		GlobalTb.style.display = (whatAction == "Global")?"block":"none";
		
		document.getElementById('multiLocationUS_arrow_img').style.display = (whatAction == "Global")?"none":"block";
		document.getElementById('multiLocationGlobal_arrow_img').style.display = (whatAction == "Global")?"block":"none";

		formName.sUSLocationWhichTab.value = whatAction;
		clearTabsData(whatAction);
	}
}

function clearTabsData(clearOtherTab)	{
	if(clearOtherTab == "Global")	{
		formName.sRadiusLocation.value="";
		formName.sRadiusLocation2.value="";
		formName.sRadiusLocation3.value="";
	} else {
		formName.iCountry.value = 0;
		updateSelectBoxLocation(formName.iCity,0);
		formName.iCountry2.value=0;
		updateSelectBoxLocation(formName.iCity2,0);
		formName.iCountry2.value=0;
		updateSelectBoxLocation(formName.iCity3,0);
	}
}

function USTrim(sString)	{

	return sString;
}

document.onkeyup = handleArrowKeys;
document.oncontextmenu = setBMenu;
document.onclick = handleMouseClicks;
document.onmousemove = handleMouseMoves;