var fActiveMenu = false;
var oOverMenu = false;

var bWaitingForCallback = false;
var bSubmitting = false;
var sSentAddr = "";
var gSelectedLat = null;
var gSelectedLon = null;
var bSuspendFocusHandling = false;

function getQueryVariable(variable) 
{  
	var query = window.location.search.substring(1);  
	var vars = query.split("&");  
	for (var i=0;i<vars.length;i++) {    
		var pair = vars[i].split("=");    
		if (pair[0] == variable) {      
			return pair[1];    }
	  } 
	  
	return "";
}

// {{{ urldecode
function urldecode( str ) {

    var histogram = {};
    if (typeof str == 'undefined')
    {
    	str = "";
    }
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';

    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);

    return ret;
}// }}}


// not used
function mouseSelect(e)
{
	if (fActiveMenu)
	{
		if (oOverMenu == false)
		{
			oOverMenu = false;
			document.getElementById(fActiveMenu).style.display = "none";
			fActiveMenu = false;
			return false;
		}
		return false;
	}
	return true;
}

function setFocusEvents ()
{
    var e, i = 0
    while (e = document.getElementsByTagName ('*')[i++]) 
    {
        e.onfocus = onFocus;
    }        
}

function menuActivate(idEdit, idMenu, idSel)
{
	//if (fActiveMenu) return mouseSelect(0);

	oMenu = document.getElementById(idMenu);
	oEdit = document.getElementById(idEdit);
	oSel = document.getElementById(idSel);
	
	nTop = Position.get (oEdit).top + Position.get (oEdit).height;
	nLeft = Position.get (oEdit).left;

	oMenu.style.left = nLeft + "px";;
	oMenu.style.top = nTop + "px";
	oMenu.style.display = "";
	
	var nMinWidth = 300;
	if (Position.get(oEdit).width > nMinWidth)
	{
		oSel.style.width = Position.get(oEdit).width + "px";
	}
	else
	{
		oSel.style.width = nMinWidth + "px";
	}
	fActiveMenu = idMenu;
	document.getElementById('combosel').style.visibility = "visible";
	//document.getElementById(idSel).focus();
	setFocusEvents ();
	return false;
}

function getObjInnerText(obj){
  if (document.all) { // IE;
    return obj.innerText;
  }
  else{
    if (obj.text)
    {
      return obj.text;
    }
  }
}

function getAddrFromId (id)
{
    var ohOption = document.getElementById (id);
    return getObjInnerText (ohOption);
}

function textSet()
{
	var ohCombo = document.getElementById ('combosel');
	var ohElement = ohCombo.childNodes [ohCombo.selectedIndex];
	if (typeof ohElement == 'undefined')
	    return;
	gSelectedLat = ohElement.getAttribute ("lat");
	gSelectedLon = ohElement.getAttribute ("lon");
	document.getElementById('addr').value = getAddrFromId (ohCombo.value);
}

function comboKey(event)
{
    if (event.keyCode == 27)
    {
        document.getElementById('combosel').style.visibility = "hidden";
        bSuspendFocusHandling = true;
        document.getElementById('addr').focus ();
        return;
    }
    if (event.keyCode == 13)
    {
        onSubmit ();
        return;
    }
	var ohCombo = document.getElementById ('combosel');

	textSet();
	UpdateMap ();
}

function UpdateMap ()
{
	var mapdiv = document.getElementById ("map");
	if (typeof mapdiv != 'undefined')
	{
		if (mapdiv.className == 'mapsearch')
		{
			ShowLocation ();
		}
	}
}

function isRelated (ohA, ohB)
{
    var ohIter = ohA;
    do
    {
        if (ohIter == ohB)
            return true;
        
        ohIter = ohIter.parentNode;
    } while (ohIter != null);
    return false;
}

function onFocus ( )
{    
    if (this == document.getElementById ('addr'))
    {
        if (bSuspendFocusHandling == true)
        {
            bSuspendFocusHandling = false;
            return;
        }
	    if (HasLocations())
	    {	
	        fnActivateComboAndSetSize ();
	    }
	    return;
	}
	if (isRelated (document.getElementById('combosel'), this) == false)
	{	    
	    document.getElementById('combosel').style.visibility = "hidden";
	}
}

function fnIsLocationValid (location)
{
    if (typeof location.AddressDetails.Country == "undefined")
    {
        return false;
    }
//	if (location.AddressDetails.Country.CountryNameCode != "US")
//	{
//		return false;
//	}
//	if (typeof location.AddressDetails.Country.AdministrativeArea != "undefined"
//	    && location.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName != "CA")
//	{
//		return false;
//	}
	return true;
}


function fnActivateComboAndSetSize ()
{	
	var ohCombo = document.getElementById ('combosel');
//	var nSize = ohCombo.childNodes.length;
//	if (nSize > 10)
//	{
//		nSize = 10;
//	}
//	nSize++;
	var nSize = 5;
	ohCombo.size = nSize;
	menuActivate('addr', 'combodiv', 'combosel');
	
}

function clearLocations ()
{
	var ohCombo = document.getElementById ('combosel');
	ohCombo.innerHTML = "";
}	

function getPrimaryLocation ()
{
	// check if lat lon is entered directly
	var ohAddr = document.getElementById ('addr')
	if (ohAddr.value [0] == "[")
		return null;
	var ohCombo = document.getElementById ('combosel')
	
	if (ohCombo == null)
	    return null;

    var ohElements = ohCombo.childNodes;    
    if (ohElements.length == 0)
        return null;    
            
    if (ohElements[0].tagName != 'OPTION')
        return null;
        
    return ohElements[0];
}

function getPrimaryLocationName ()
{
    var ohPrim = getPrimaryLocation ();
    if (ohPrim == null)
    {
		var ohAddr = document.getElementById ('addr')
		if (ohAddr.value [0] == "[")
			return ohAddr.value ;
		else		  	
			return "";   			
    }
         
    return getObjInnerText (ohPrim);
}

function getPrimaryLocationLat ()
{
    var ohPrim = getPrimaryLocation ();
    if (ohPrim == null)
    {
		var ohAddr = document.getElementById ('addr')
		
		if (ohAddr.value [0] == "[")
		{
			var sLatLon = ohAddr.value.substring (1, ohAddr.value.length -1 ) 			
			var aLatLon = sLatLon.split (",");			
			return aLatLon [0] ;
		}
		else		  	
			return null;   			
    }
             
    return ohPrim.getAttribute ("lat");
}

function getPrimaryLocationLon ()
{
    var ohPrim = getPrimaryLocation ();
    if (ohPrim == null)
    {
		var ohAddr = document.getElementById ('addr')
		
		if (ohAddr.value [0] == "[")
		{
			var sLatLon = ohAddr.value.substring (1, ohAddr.value.length -1 ) 			
			var aLatLon = sLatLon.split (",");			
			return aLatLon [1] ;
		}
		else		  	
			return null;   			
    }
    
    return ohPrim.getAttribute ("lon");
}

bFirst = true;
function addLocation (location, i)
{
	if (i == 0)
	{
		bFirst = true;
	}
	
	if (fnIsLocationValid (location))
	{
		var ohCombo = document.getElementById ('combosel');
		var ohOptionNew = document.createElement ("OPTION");
        ohOptionNew.setAttribute ("id", "addroption" + i);
        ohOptionNew.setAttribute ("name", "addroption");
        ohOptionNew.setAttribute ("value", "addroption" + i);
        ohOptionNew.setAttribute ("lat", location.Point.coordinates [1]);
        ohOptionNew.setAttribute ("lon", location.Point.coordinates [0]);
		ohOptionNew.innerHTML = location.address;
		
		if (bFirst == true)
		{
			clearLocations ();
			ohOptionNew.setAttribute("selected", "true");
		}
		bFirst = false;

		ohCombo.appendChild (ohOptionNew);
	}
	if (HasLocations())
	{	
	    fnActivateComboAndSetSize ();
	}
}

function fnKeyUp ( event )
{
    if (event.keyCode == 27)
    {
        document.getElementById('combosel').style.visibility = "hidden";                
        return;    
    }
	if (event.keyCode == 40)
	{
		var ohCombo = document.getElementById ('combosel');
		if (HasLocations())
		{
		    ohCombo.style.visibility = "visible";
		    ohCombo.focus ();
		}
		return;
	}
	if (event.keyCode == 13)
	{
	    onSubmit ();
	    return;
	}
    getLocation ();	
    // selected location is no longer valid
    gSelectedLat = null;
    gSelectedLon = null;
}


function getLocation ()
{
	var ohInput = document.getElementById ('addr');
	
	if (typeof GClientGeocoder == "undefined")
	    return;
	
	var geocoder = new GClientGeocoder();

	bWaitingForCallback = true;
	sSentAddr = ohInput.value;
	var response = geocoder.getLocations (sSentAddr, callback);	
}

function HasLocations ()
{
    var ohCombo = document.getElementById ('combosel');
    if (ohCombo.value.length > 0)
    {   
        return true;
    }
    else
    {
        return false;
    }
}


function callback (result)
{
    if (result.name != document.getElementById ('addr').value)
    {
        return; // not the request for the current text, so ignore
    }
	bWaitingForCallback = false;
	clearLocations ();
	if (typeof result.Placemark != 'undefined')
	{		
		for (var i = 0; i < result.Placemark.length; i++)
		{
			addLocation (result.Placemark [i], i);
		}		
	}
	if (HasLocations () == false)
	{
	    document.getElementById('combosel').style.visibility = "hidden";
	}
	if (bSubmitting)
	{
	    SubmitForm ();
	}
}

function trimAll(sString)
{
    while (sString.substring(0,1) == ' ')
    {
        sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length-1, sString.length) == ' ')
    {
        sString = sString.substring(0,sString.length-1);
    }
    return sString;
}

function onSubmit ()
{
    if (bWaitingForCallback)
    {
        bSubmitting = true;
    }
    else
    {
        SubmitForm ();
    }
}

function canSubmit ()
{
    if (bWaitingForCallback)
    {
        bSubmitting = true;
        return false;
    }
    else
    {
        SubmitForm ();
    }
}

function SetLatLon ()
{
    if (readCookie ('addrName') == document.getElementById ('addr').value
        && readCookie ('addrName') != '')
    { 
                     
        // use cookie data
        document.getElementById("lat").setAttribute("value", readCookie ('lat'));
        document.getElementById("lon").setAttribute ("value", readCookie ('lon'));

    }
    else
    {        
    	
        var lat = null;
        var lon = null;
        if (gSelectedLat == null)
        {                 
            lat = getPrimaryLocationLat (); 
            if (lat == null)
            {            	
            	// if this is a link where a third party provided the location, then use the location from url
            	if (getQueryVariable ("addrname") != "" && document.getElementById ('addr').value == urldecode (getQueryVariable ("addrname")))
            	{            		
            		// this means the user hasn't touched the address and we can use the lat and lon from the query string if available
				    document.getElementById("lat").setAttribute("value", getQueryVariable ('lat'));
				    document.getElementById("lon").setAttribute ("value", getQueryVariable ('lon'));
            		
            	}
            	else
            	{
	                // location is not valid, clear cookie and submit form                
	                createCookie ('addrName', "");
	                createCookie ('lat', "");
	                createCookie ('lon', "");
            	}
                return;
            }                
                          
            lon = getPrimaryLocationLon ();
            document.getElementById('addr').value = getPrimaryLocationName (); 
        }
        else
        {
            lat = gSelectedLat;
            lon = gSelectedLon;
        }
        
        if (lat != null)
        {                      	
            document.getElementById("lat").setAttribute("value", lat);
            document.getElementById("lon").setAttribute("value", lon);   
            
            // set cookie
            createCookie ('addrName', document.getElementById('addr').value);
            createCookie ('lat', lat);
            createCookie ('lon', lon);
        }
    }     	
	
}

function SubmitForm ()
{    
   	SetLatLon ();
    document.form.submit ();
}