/*
* 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
* @return
*/
/*
function geocode(addr){
	console.debug('geocode called');
	var locationcollection = new MQA.LocationCollection();
	var geoExec = new MQA.Exec(geocodeServer, serverPath, serverPort, proxyServer, proxyPath, proxyPort);
	//Geocode address
	geoExec.geocode(addr, locationcollection, null);

	if(locationcollection.getSize()==0){
		//If results are 0 then the address can not be geocoded.
		alert("Please enter the 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);
		
		if(validateResultCode(location.getResultCode())){
			return location;
		}
		else {
			alert("Address you specified seems to be incorrect, please enter valid address.");
			return false;
		}
	}
	else {
		  alert("Address you specified seems to match multiple address, enter specific address");
	}

}
*/

/*
* Function which handles the form submissions
* 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 displayMap(){
	console.debug('display map');
	var addr, geoAddress, name, city, state, country, zipcode, miles;
	addr = new MQA.Address();
	addr.setStreet(document.getElementById("a0").value);
	addr.setCity(document.getElementById("c0").value);
	var state=document.getElementById("s0");
	addr.setState(state.options[state.selectedIndex].value);
	addr.setPostalCode(document.getElementById("z0").value);
	addr.setCountry(document.getElementById("u0").value);
	/*
	 *if((StringFunctions.isBlank(addr.getCity()) ||  StringFunctions.isBlank(addr.getState())) && StringFunctions.isBlank(addr.getPostalCode())){
	 * 			alert("City & State or Zip required!")
     * 				return false;
	 *}
	 */
	/*
	ga = geocode(addr);
	//If this function has geocoded an address either by location
	//category then assign the latitude and longitude to the hidden form fields for those values.
	if(ga){
		showMap(ga);
		return true;
	}
	else {
		return false;
	}
}
	*/

/*
* 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(ga){
	console.debug('process map');
	frm.hdnlatitude.value = ga.getMQLatLng().getLatitude();
	frm.hdnlongitude.value = ga.getMQLatLng().getLongitude();
	showMap(frm,ga)
  }

/*
function showMap(ga){
	console.debug('show map');
		//read the address values to do the search
		var address = document.getElementById("a0").value
		var	city = document.getElementById("c0").value
		var state = document.getElementById("s0").value
		var zipCode = document.getElementById("z0").value
		var latitude = ga.getMQLatLng().getLatitude();
		var longitude = ga.getMQLatLng().getLongitude();
		var radius;
		var r0=document.getElementsByName("r0")

		for (var i=0; i < r0.length; i++)
   		{
   			if (r0[i].checked)
      			{
      				radius = r0[i].value;
     			}
   		}

		//Build Data Manager Record based on origin address
		var originAddress = new DataManagerRecord();
		originAddress.setId("origin");
		originAddress.setStreet(address);
		originAddress.setCity(city);
		originAddress.setState(state);
		originAddress.setPostalCode(zipCode);

		//Build Map Div
		document.getElementById('mapDiv').innerHTML="";
		var mapwindow = document.getElementById('mapDiv');
		map = new MQA.TileMap(mapwindow);

		//Add zoom controls to Map
		var zoomControl =  new MQA.LargeZoomControl;
		map.addControl(zoomControl, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(0, 0)))

		//Add view controls to map
		var viewControl = new MQA.ViewControl();
		map.addControl(viewControl, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_RIGHT, new MQA.Size(-6, 0)))

		//Place MapQuest and Copyright logos
		map.setLogoPlacement(MQMapLogo.MAPQUEST, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(44, 0)));
		map.setLogoPlacement(MQMapLogo.SCALES, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_RIGHT, new MQA.Size(0, 23)));
		map.setLogoPlacement(MQMapLogo.NAVTEQ_COPYRIGHT, new MQA.MapCornerPlacement(MQA.MapCorner.BOTTOM_RIGHT, new MQA.Size(2, 12)));
		map.setLogoPlacement(MQMapLogo.MAPQUEST_COPYRIGHT, new MQA.MapCornerPlacement(MQA.MapCorner.BOTTOM_RIGHT, new MQA.Size(0, 0)));
		map.setLogoPlacement(MQMapLogo.ICUBED_COPYRIGHT, new MQA.MapCornerPlacement(MQA.MapCorner.BOTTOM_RIGHT, new MQA.Size(103, 1)));

		//Build Origin Poi and Add it to the Map
		var poi = new MQA.Poi(new MQA.LatLng(latitude, longitude),  new MQA.MapIcon());
		poi.setKey("origin");
		poi.setInfoTitleHTML(originAddress.getInfoTitleHTML());
		poi.setInfoContentHTML(originAddress.getInfoContentHTML());
		map.addPoi(poi);

		document.getElementById("mapDiv").style.visibility="visible";
		//Search origin and display results
		var resArray = search(latitude, longitude, radius);
		
		var message = document.getElementById("msgId");
		removeAllChildren(message);
		var totalStores = resArray.length;
		var text = document.createTextNode(totalStores+" Locations within "+radius+" miles");
		message.appendChild(text);
		
		showResults(resArray, new MQA.LatLng(latitude, longitude));
	
 }
*/

/*
function search(searchLat, searchLng, searchRadius){
		console.debug('search called');
		//Build Radius Search Criteria
		var criteria = new MQA.RadiusSearchCriteria();
		//Set Origin
		criteria.setCenter(new MQA.LatLng(searchLat, searchLng));
		//Set Radius
		criteria.setRadius(searchRadius);
		//Set Maximum number of Matches
		criteria.setMaxMatches(MAX_MATCHES);

		//Build Database Query Object
		var dbLayerQuery = new MQA.DBLayerQuery();
		//Define Data Table
		dbLayerQuery.setDBLayerName(poisTable);

		//Create Database Query Collection and Add Database Query to Collection
		var dbLayerQueryCollection = new MQA.DBLayerQueryCollection();
		dbLayerQueryCollection.add(dbLayerQuery);

		var searchFeatures = new MQFeatureCollection();

		var dtCollection = new MQDTCollection();

		var results = new MQFeatureCollection();

		//Build Spatial Search Object
		var spatialExec = new MQA.Exec(spatialServer, serverPath, serverPort, proxyServer, proxyPath, proxyPort);
		//Perform Search
		spatialExec.search(criteria, results, "", dbLayerQueryCollection,  searchFeatures, dtCollection);

		//Build Array to store results
		var resultsArray = new Array();
		//If get results from search create collection of location ids from result keys
		if(results.getSize() > 0 ){
			var recordset = new MQRecordSet();
			var ids = new MQStringCollection();
			for(var i=0; i < results.getSize(); i++){
				ids.add(results.getAt(i).getKey());
			}

			//Retrieve record set for each id in the results
			var fields = new MQStringCollection();
			spatialExec.getRecordInfo(fields, dbLayerQuery, recordset, ids);
			resultsArray = getResultsAsArray(recordset, results, false);
		}

		return resultsArray;
	}
*/

function displayMap(){
	console.debug('display map refactor');
	var addr, geoAddress, name, city, state, country, zipcode, miles;
	addr = new MQAddress();
	addr.setStreet(dojo.byId("a0").value);
	addr.setCity(dojo.byId("c0").value);
	var state=dojo.byId("s0");
	addr.setState(state.options[state.selectedIndex].value);
	addr.setPostalCode(dojo.byId("z0").value);
	addr.setCountry(dojo.byId("u0").value);
	
	geoAddress = getGeoCode(addr);
	
	//If this function has geocoded an address either by location
	//category then assign the latitude and longitude to the hidden form fields for those values.
	if(geoAddress){
		showMap(geoAddress);
		return true;
	}
	else {
		return false;
	}
}

function showMap(geoAddress){
	console.debug('show map refactor');
	//read the address values to do the search
	var address = dojo.byId("a0").value
	var city = dojo.byId("c0").value
	var state = dojo.byId("s0").value
	var zipCode = dojo.byId("z0").value
	var latitude = geoAddress.getMQLatLng().getLatitude();
	var longitude = geoAddress.getMQLatLng().getLongitude();
	var radius;
	var r0=document.getElementsByName("r0")

	for (var i=0; i < r0.length; i++)
	{
		if (r0[i].checked)
		{
			radius = r0[i].value;
		}
	}

	//Build Data Manager Record based on origin address
	var originAddress = new DataManagerRecord();
	originAddress.setId("origin");
	originAddress.setStreet(address);
	originAddress.setCity(city);
	originAddress.setState(state);
	originAddress.setPostalCode(zipCode);

	//Build Map Div
	dojo.byId('mapDiv').innerHTML="";
	var mapwindow = dojo.byId('mapDiv');
	map = new MQA.TileMap(mapwindow);

	//Add zoom controls to Map
	var zoomControl =  new MQA.LargeZoomControl;
	map.addControl(zoomControl, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(0, 0)))

	//Add view controls to map
	//var viewControl = new MQNoAerialViewControl(); //MQViewControl();
	//map.addControl(viewControl, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_RIGHT, new MQA.Size(-6, 0)))
	//map.addControl(viewControl, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_RIGHT, new MQA.Size(-6, 0)));
	//map.addControl(new MQNoAerialViewControl(map));
	
	//Place MapQuest and Copyright logos
	map.setLogoPlacement(MQMapLogo.MAPQUEST, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(44, 0)));
	map.setLogoPlacement(MQMapLogo.SCALES, new MQA.MapCornerPlacement(MQA.MapCorner.TOP_RIGHT, new MQA.Size(0, 23)));
	map.setLogoPlacement(MQMapLogo.NAVTEQ_COPYRIGHT, new MQA.MapCornerPlacement(MQA.MapCorner.BOTTOM_RIGHT, new MQA.Size(2, 12)));
	map.setLogoPlacement(MQMapLogo.MAPQUEST_COPYRIGHT, new MQA.MapCornerPlacement(MQA.MapCorner.BOTTOM_RIGHT, new MQA.Size(0, 0)));
	map.setLogoPlacement(MQMapLogo.ICUBED_COPYRIGHT, new MQA.MapCornerPlacement(MQA.MapCorner.BOTTOM_RIGHT, new MQA.Size(103, 1)));

	//Build Origin Poi and Add it to the Map
	var poi = new MQA.Poi(new MQA.LatLng(latitude, longitude),  new MQA.Icon());
	poi.setKey("origin");
	poi.setValue('InfoTitleHTML', originAddress.getInfoTitleHTML());
	poi.setValue('InfoContentHTML', originAddress.getInfoContentHTML());
	map.addPoi(poi);

	dojo.byId("mapDiv").style.visibility="visible";
	//Search origin and display results
	var resArray = searchMapForStoreData(latitude, longitude, radius);
	
	var message = dojo.byId("msgId");
	removeAllChildren(message);
	var totalStores = resArray.length;
	var text = document.createTextNode(totalStores+" Locations within "+radius+" miles");
	message.appendChild(text);
	
	showResults(resArray, new MQA.LatLng(latitude, longitude));
}

function searchMapForStoreData(searchLat, searchLng, searchRadius){
	console.debug('search called refactor');
	//Build Radius Search Criteria
	var criteria = new MQRadiusSearchCriteria();
	//Set Origin
	criteria.setCenter(new MQA.LatLng(searchLat, searchLng));
	//Set Radius
	criteria.setRadius(searchRadius);
	//Set Maximum number of Matches
	criteria.setMaxMatches(MAX_MATCHES);

	//Build Database Query Object
	var dbLayerQuery = new MQDBLayerQuery();
	//Define Data Table
	dbLayerQuery.setDBLayerName(poisTable);

	//Create Database Query Collection and Add Database Query to Collection
	var dbLayerQueryCollection = new MQDBLayerQueryCollection();
	dbLayerQueryCollection.add(dbLayerQuery);

	var searchFeatures = new MQFeatureCollection();

	var dtCollection = new MQDTCollection();

	var results = new MQFeatureCollection();

	//Build Spatial Search Object
	var spatialExec = new MQExec(spatialServer, serverPath, serverPort, proxyServer, proxyPath, proxyPort);
	//Perform Search
	spatialExec.search(criteria, results, "", dbLayerQueryCollection,  searchFeatures, dtCollection);

	//Build Array to store results
	var resultsArray = new Array();
	//If get results from search create collection of location ids from result keys
	if(results.getSize() > 0 ){
		var recordset = new MQRecordSet();
		var ids = new MQStringCollection();
		for(var i=0; i < results.getSize(); i++){
			ids.add(results.getAt(i).getKey());
		}

		//Retrieve record set for each id in the results
		var fields = new MQStringCollection();
		spatialExec.getRecordInfo(fields, dbLayerQuery, recordset, ids);
		resultsArray = getResultsAsArray(recordset, results, false);
	}

	return resultsArray;
}

function getGeoCode(addr){
	console.debug('getGeoCode called refactor');
	var locationcollection = new MQLocationCollection();
	var geoExec = new MQExec(geocodeServer, serverPath, serverPort, proxyServer, proxyPath, proxyPort);
	//Geocode address
	geoExec.geocode(addr, locationcollection, null);

	if(locationcollection.getSize()==0){
		//If results are 0 then the address can not be geocoded.
		alert("Please enter the 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);
		
		if(validateResultCode(location.getResultCode())){
			return location;
		}
		else {
			alert("Address you specified seems to be incorrect, please enter valid address.");
			return false;
		}
	}
	else {
		  alert("Address you specified seems to match multiple address, enter specific address");
	}
}	
