/*
* 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
*/
function geocode(addr, frm, multiResultsHTMLElementParentId, multiResultsSubmtPage){

    //alert('in geocode [' + addr.getPostalCode() + ']');

	var locationcollection = new MQLocationCollection();
	var geoExec = new MQExec(geocodeServer, serverPath, serverPort, proxyServer, proxyPath, proxyPort);
	//Geocode address
	geoExec.geocode(addr, locationcollection, null);

    //alert('in geocode locationcollection.getSize() ['+locationcollection.getSize()+']');
    
	if(locationcollection.getSize()==0){
		//If results are 0 then the address can not be geocoded.
		alert("Please enter a valid address.");
		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('in geocode llocation.getResultCode() ['+location.getResultCode()+']');
        //alert('in geocode validateResultCode(location.getResultCode()) ['+validateResultCode(location.getResultCode())+']');

		if(validateResultCode(location.getResultCode())){
			return location;
		}
		else {
			alert("Please enter a valid address.");
			return false;
		}
	}
	else {
		//Otherwise multiple results were found and create a ambiguous results table on the specified page.
		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.
*/
function onFormSubmit(frmid){


	var frm = document.getElementById(frmid);
	var addr, geoAddress, name, city, state, province, postalcode;
	//Hidden field containing search type is read


	switch(frm.hdnType.value){
		//If search by location type - address fields are validated and geocoded and submitted to search by location page
		case "FromCashAdvancePage":
            //alert('onFormSubmit ['+frm.hdnType.value+']');
            
			addr = new MQAddress();
            //alert('onFormSubmit [1]');


			addr.setStreet("");
			addr.setCity("");
            addr.setState("");
			addr.setPostalCode(document.getElementById("ctl00_Content_ctl00_txtPostalCode_text").value);
			addr.setCountry("US");

			ga = geocode(addr, frm, "divFrmInput", "searchlocation.aspx");
			break;
		case "ByZip":
            //alert('onFormSubmit ['+frm.hdnType.value+':'+ document.getElementById("ctl00_PaydayContent_ctl00_txtPostalCode_text").value+']');
            
			addr = new MQAddress();
            //alert('onFormSubmit [1]');


			addr.setStreet("");
			addr.setCity("");
            addr.setState("");
			addr.setPostalCode(document.getElementById("ctl00_PaydayContent_ctl00_txtPostalCode_text").value);
			addr.setCountry("US");

			ga = geocode(addr, frm, "divFrmInput", "searchlocation.aspx");
			break;
		//If search by POI name type - poi name field is validated and submitted to search by poi name page
		case "CouponByZip":
            //alert('onFormSubmit ['+frm.hdnType.value+':'+ document.getElementById("txtPostalCode").value+']');
            
			addr = new MQAddress();
            //alert('onFormSubmit [1]');


			addr.setStreet("");
			addr.setCity("");
            addr.setState("");
			addr.setPostalCode(document.getElementById("txtPostalCode").value);
			addr.setCountry("US");

			ga = geocode(addr, frm, "divFrmInput", "searchlocation.aspx");
			break;
		case "ByLocation":
            //alert('onFormSubmit ['++']');
            
			addr = new MQAddress();


			//addr.setStreet(frm.txtAddress.value);
			addr.setStreet(document.getElementById("txtAddress_text").value);
            //alert('addr.setStreet ['+document.getElementById("txtAddress_text").value+']');
			//addr.setCity(frm.txtCity.value);
			addr.setCity(document.getElementById("txtCity_text").value);
            //alert('addr.setCity ['+document.getElementById("txtCity_text").value+']');
            addr.setState(document.getElementById("selStateProvince_Input").value);
			//addr.setState(frm.selStateProvince.options[frm.selStateProvince.selectedIndex].value);
            //alert('addr.setState ['+document.getElementById("selStateProvince_Input").value+']');
			//addr.setPostalCode(frm.txtPostalCode.value);
			addr.setPostalCode(document.getElementById("txtPostalCode_text").value);
            //alert('addr.getPostalCode ['+document.getElementById("txtPostalCode_text").value+']');
			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", "searchlocation.aspx");
			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", "searchlocation.html");
				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('call processmap');
		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.
*/
function getAdditionalParameters(frm){
	var params = new Array();
	switch(frm.hdnType.value){
		case "ByLocation":
			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("selDisplay", frm.selDisplay.options[frm.selDisplay.selectedIndex].value));
			params.push(new Array("txtDistance", frm.txtDistance.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
*/
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 "FromCashAdvancePage":
		    //alert('byzip processMap');
			frm.ctl00$Content$ctl00$hdnLatitude.value =  ga.getMQLatLng().getLatitude();
			frm.ctl00$Content$ctl00$hdnLongitude.value = ga.getMQLatLng().getLongitude();
			break;
	    case "ByZip":
		    //alert('byzip processMap');
			frm.ctl00$PaydayContent$ctl00$hdnLatitude.value =  ga.getMQLatLng().getLatitude();
			frm.ctl00$PaydayContent$ctl00$hdnLongitude.value = ga.getMQLatLng().getLongitude();
			break;
        case "CouponByZip":
        case "ByLocation":
		case "ByPOICategory":
			frm.hdnLatitude.value =  ga.getMQLatLng().getLatitude();
			frm.hdnLongitude.value = ga.getMQLatLng().getLongitude();
		    //alert('frm.hdnLatitude.value ['+ ga.getMQLatLng().getLatitude()+']');
		    //alert('ga.getMQLatLng().getLongitude() ['+ga.getMQLatLng().getLongitude()+']');
			frm.submit();
			break;
	}
}
