/*
* Function to geocode an MQAddress object and return the MQGeoAddress object.
* If Ambiguous results are found, the ambiguous results are submitted to the provided page.
* Pre-Condtion: The address must be a MQGeoAddress object, the html from element must exist.
* Post-Condition: The MQAddress object passed is geocoded and location returned.
* Ambiguous results are passed to the appropriate page specified in multiResultsHTMLElementParentId.
*
* @param        addr - an MQAddress object
* @param        frm - id of the html form element providing the MQAddress object
* @param        multiResultsHTMLElementParentId - frmid for the Ambiguous results to be passed to.
* @param		multiResultsSubmtPage - page for the geocoded results to be submitted to when ambiguous.
* @return
* @author       Seisan Consulting   2-16-2007
*/
function geocode(addr, frm, multiResultsHTMLElementParentId, multiResultsSubmtPage){
    //alert ("Entering geocode function");
	var locationcollection = new MQLocationCollection();
	var geoExec = new MQExec(geocodeServer, serverPath, serverPort, proxyServer, proxyPath, proxyPort);
	//Geocode address
	//alert("GeoCode it. " + addr.getPostalCode());
	geoExec.geocode(addr, locationcollection, null);

    //alert("GeoCoding done " + locationcollection.getSize());
	if(locationcollection.getSize()==0){
	    //If results are 0 then the address can not be geocoded.
		//alert("Address couldn't be geocoded!");
		document.getElementById("Message").innerHTML = "<p class=\"error\">Address couldn't be geocoded!</p>";
		return false;
	}
	else if(locationcollection.getSize()==1){
		//If a single result is returned from the geocoder, validate the result, return the geocoded address		
		var location = locationcollection.getAt(0);
		//alert(location.getResultCode());
		if(validateResultCode(location.getResultCode())){
			return location;
		}
		else {
			//alert("Address couldn't be geocoded!");
			document.getElementById("Message").innerHTML = "<p class=\"error\">Address couldn't be geocoded!</p>";
			return false;
		}
	}
	else {
		//Otherwise multiple results were found and create a ambiguous results table on the specified page.
		//alert("Mulple results");
		if(multiResultsHTMLElementParentId){
			buildGeocodeResultTable(multiResultsHTMLElementParentId, locationcollection, multiResultsSubmtPage, getAdditionalParameters(frm));
		}
		return false;
	}

}

/*
* Function which handles the form submissions depending on the type of search requested.
* Pre-Condtion: the html form element must exist.
* Post-Condition: The approriate action is performed and the form is submitted to the corresponding page based on the search type.
*
* @param        frmid - id of the html form element being submitted.
* @return		a Boolean that evaluates whether the form was submitted or not. True if form submission was successful, false if not.
* @author       Seisan Consulting   2-16-2007
*/
function onFormSubmit(frmid, zipcode){
    
	var frm = document.getElementById(frmid);
	//frm.action='searchlocation.aspx';
    //alert(frmid);
    //alert(frm);
    
	var addr, geoAddress, name, city, state, province, postalcode;
	//alert("Entering onFormSubmit");
	//Hidden field containing search type is read
	//alert (frm.hdnType.value);
	switch(frm.hdnType.value){
		//If search by location type - address fields are validated and geocoded and submitted to search by location page
		case "ByLocation":
		    document.getElementById("Message").innerHTML =  "";
		    //alert("Search by location");		    
			addr = new MQAddress();
			//addr.setStreet(frm.txtAddress.value);
			addr.setCity(frm.txtCity.value);
			addr.setState(frm.selStateProvince.options[frm.selStateProvince.selectedIndex].value);
			if(zipcode)
			    addr.setPostalCode(zipcode);
			else
			    addr.setPostalCode(frm.txtPostalCode.value);
			addr.setCountry("US");
//			if((StringFunctions.isBlank(addr.getCity()) ||  StringFunctions.isBlank(addr.getState())) && StringFunctions.isBlank(addr.getPostalCode())){
//			    alert("State or Zip required!")
//				return false;
//			}
            //alert (addr.getCity() + addr.getState() + addr.getPostalCode());
            if ( !StringFunctions.isBlank(addr.getPostalCode()) )
                ga = geocode(addr, frm, "divFrmInput", "/totalmerrill/system/searchlocation.aspx");
            else if( StringFunctions.isBlank(addr.getState())&& StringFunctions.isBlank(addr.getPostalCode()) )
            {   
                if (frm.txtName.value.length > 0)
                {		        
			        var ga = new MQGeoAddress();
			        ga.setMQLatLng(new MQLatLng(CENTER_OF_THE_US_LATITUDE, CENTER_OF_THE_US_LONGITUDE));
			        frm.ddwnDistance.selectedIndex = 0;      
			    }
			    else
			    {
			        if (document.getElementById("txtFirstName"))                    
			            document.getElementById("Message").innerHTML = "<p class=\"error\">Please enter a last name with at least one character.</p>"
			        else
			            document.getElementById("Message").innerHTML = "<p class=\"error\">State or Zip required.</p>"			            
			            
			        return false;
			    }
			}
			else if(StringFunctions.isBlank(addr.getCity()) && !StringFunctions.isBlank(addr.getState()) && StringFunctions.isBlank(addr.getPostalCode()))
			    {			        
			        var ga = new MQGeoAddress();
			        ga.setMQLatLng(new MQLatLng(CENTER_OF_THE_US_LATITUDE, CENTER_OF_THE_US_LONGITUDE));
			        frm.ddwnDistance.selectedIndex = 0;
			    }
			else			    
			   ga = geocode(addr, frm, "divFrmInput", "/totalmerrill/system/searchlocation.aspx");
			   			                	
        	if(ga)
        	{        	    
        	    document.getElementById("Message").innerHTML = "<p class=\"error\"><img src=\"/publish/tm/images/progress.gif\" width=\"20px\" height=\"20px\" alt=\"Progress\">Search in progress...</p>"
			    DoSearch(ga);			        
			    return false;
			}
			break;
		//If search by POI name type - poi name field is validated and submitted to search by poi name page
		case "ByPOIName":
			name = frm.txtPOIName.value;
			if(StringFunctions.isBlank(name)){
				alert("Please enter a Point of Interest (Name)!");
				return false;
			}
			else {
				frm.submit();
				return true;

			}
		//If search by poi category type - Poi category and address fields are validated and geocoded and submitted to search by location page
		case "ByPOICategory":
			city = frm.txtCity.value;
			state = frm.selStateProvince.options[frm.selStateProvince.selectedIndex].value;
			postalcode = frm.txtPostalCode.value;
			if(frm.selCategory.selectedIndex == 0){
				alert("Please Select a POI Category!");
				return false;
			}
			else {
				addr = new MQAddress();
				addr.setCity(city);
				addr.setState(state);
				addr.setPostalCode(postalcode);
				addr.setCountry("US");
				if((StringFunctions.isBlank(addr.getCity()) ||  StringFunctions.isBlank(addr.getState())) && StringFunctions.isBlank(addr.getPostalCode())){
					alert("City & State or Zip required!")
					return false;
				}

				ga = geocode(addr, frm, "divFrmInput", "/totalmerrill/system/searchlocation.aspx");
				break;
			}
		//If search by location type - address fields for origin and destination are validated and submitted to route page
		case "ByRoute":
			var city = frm.txtOriginCity.value;
			var state = frm.selOriginStateProvince.options[frm.selOriginStateProvince.selectedIndex].value;
			var postalcode = frm.txtOriginPostalCode.value;
			if((StringFunctions.isBlank(city) ||  StringFunctions.isBlank(state)) && StringFunctions.isBlank(postalcode)){
				alert("Origin City & State or Zip required!")
				return false;
			}

			var city = frm.txtDestCity.value;
			var state = frm.selDestStateProvince.options[frm.selDestStateProvince.selectedIndex].value;
			var postalcode = frm.txtDestPostalCode.value;
			if((StringFunctions.isBlank(city) ||  StringFunctions.isBlank(state)) && StringFunctions.isBlank(postalcode)){
				alert("Destination City & State or Zip required!")
				return false;
			}

			frm.submit();
			return true;
		default:
			alert("Undefined Action");
			return false;
	}
	//If this function has geocoded an address either by location or by poi category then assign the latitude and longitude to the hidden form fields for those values.
	if(ga){	    
	    //alert(ga.getPostalCode());
		processMap(frm, ga);
		return true;
	}
	else {
		return false;
	}
}

/*
* Function to read hidden form elements containing address information and build an array matrix of fieldnames and values.
* Pre-Condtion: The html form element must exist.
* Post-Condition: An array is built containing a matrix of field name-value pairs of address information.
*
* @param        frm - an html form element
* @return		params - an array matrix of address information in the form of field name-value pairs.
* @author       Seisan Consulting   2-16-2007
*/
function getAdditionalParameters(frm){
	var params = new Array();
	switch(frm.hdnType.value){
		case "ByLocation":
		    
		    var qs = new Querystring();		
		    var searchType = '';
		    if(null != qs.get("ddwnSearchType"))
                searchType = qs.get("ddwnSearchType");

			//params.push(new Array("txtAddress", frm.txtAddress.value));
			params.push(new Array("txtCity", frm.txtCity.value));
			params.push(new Array("selStateProvince", frm.selStateProvince.options[frm.selStateProvince.selectedIndex].value));
			params.push(new Array("txtPostalCode", frm.txtPostalCode.value));
			params.push(new Array("ddwnSearchType", searchType));
			params.push(new Array("txtName", frm.txtName.value));
			//params.push(new Array("txtFirstName", frm.txtFirstName.value));
			params.push(new Array("ddwnDistance", frm.ddwnDistance.options[frm.ddwnDistance.selectedIndex].value));
			if(document.getElementById("rdoUnitMi").checked){
				params.push(new Array("rdoUnit", "mi"));
			}
			else {
				params.push(new Array("rdoUnit", "min"));
			}
			params.push(new Array("hdnType", "ByLocation"));
			break;
		case "ByPOICategory":
			params.push(new Array("selCategory", frm.selCategory.options[frm.selCategory.selectedIndex].value));
			params.push(new Array("hdnType", "ByPOICategory"));
			break;
	}
	return params;
}

/*
* Function to assign hidden form fields containing Latitude and Longitude from the geocoded address.
* Pre-Condtion: The html form element must exist.
* Post-Condition: The hidden form fields for Latitude and Longitude will be assigned from the Geocoded Address.
*
* @param        frm - an html form element
* @param        ga - an MQGeoAddress object
* @author       Seisan Consulting   2-16-2007
*/
function processMap(frm, ga){
	//If the form is of type ByLocation or ByPoiCategory the hidden latitude and longitude
	//fields needs filled in once the address is geocoded.
	switch(frm.hdnType.value){
		case "ByLocation":
		case "ByPOICategory":
		    //alert("ProcessMap: ByPOICategory " + "Lng: " + ga.getMQLatLng().getLatitude() + "Lat: " + ga.getMQLatLng().getLongitude());		    
			frm.hdnLatitude.value = ga.getMQLatLng().getLatitude();
			frm.hdnLongitude.value = ga.getMQLatLng().getLongitude();
			frm.submit();
			break;
	}
}