/*
* Function to format a floating point distance value to 2 decimals
* Pre-Condtion: The dist value must be > 0
* Post-Condition: The distance is returned as a floating point number formatted to 2 decimal places.
*
* @param        dist - floating point number containing a distance value
* @return		Formated distance value to 2 decimals
*/
function formatDistance(dist){
	dist = parseFloat(dist);
	if(dist < .01 && dist > 0)
		return .01;
	else {
		var d = parseInt(parseFloat(dist) * 100);
		return parseFloat(d)/ 100;
	}
}


/*
* Function to change a value of time to the provided format.
* Pre-Condtion: The time must exist.
* Post-Condition: The time is returned in the requested format.
*
* @param        time - a strign containing a value of time.
* @param		format - a string containing the requested format.
* @return		format - the time string in the request format
*/
function formatTime(time, format){
	//If a format is not provided, the default is used
	if(!format){
		format = "%h:%m:%s";
	}
	time = parseFloat(time);
	var h = parseInt(time / (60 * 60));
	time = parseFloat(time % (60 * 60));
	var m = parseInt(time / 60);
	var s = parseFloat(time % 60);

	if(format.indexOf("%h") >= 0){
		format = format.replace("%h", h);
	}
	if(format.indexOf("%m") >= 0){
		format = format.replace("%m", m);
	}
	if(format.indexOf("%s") >= 0){
		format = format.replace("%s", s);
	}
	return format;
}

/*
* Function to build a route directions table based on the results and options provided.
* Pre-Condtion: The routeresults must != null
* Post-Condition: A html table element is returned containing route directions as per options specified.
*
* @param        routeresult - an MQRouteResult object.
* @param        showCount - a boolean flag whether to display the direction count.
* @param        showText - a boolean flag whether to display the direction text.
* @param        showDistance - a boolean flag whether to display the route distances.
* @param        showTime - a boolean flag whether to display the route times.
* @param		headers - a boolean flag whether to display the Total Route time, distance and maneuvers count.
* @return		tbl - an html table element containing the route directions as per options specified.
*/
function getRouteDirections(routeResult, showCount, showText, showDistance, showTime, headers){
	var tbl, tr, td;

	tbl = document.createElement("table");
	tbl.className = "routeresults"
	tbl.cellSpacing = 0;
	tbl.cellPadding = 4;
	tbl.border = 0;
	// If headers is true, append total route time, total route distance and maneuver count
	if(headers){
		tr = document.createElement("tr");

		var cnt = 0;
		if(showCount|| showText){
			td = document.createElement("td");
			td.className = "hdrrouteresults"
			td.appendChild(document.createTextNode(headers[cnt++]));
			tr.appendChild(td);
		}

		if(showDistance){
			td = document.createElement("td");
			td.className = "hdrrouteresults"
			if(headers.length > cnt){
				td.appendChild(document.createTextNode(headers[cnt++]));
			}
			else {
				td.appendChild(document.createTextNode(" "));
			}
			tr.appendChild(td);
		}

		if(showTime){
			td = document.createElement("td");
			td.className = "hdrrouteresults"
			if(headers.length > cnt){
				td.appendChild(document.createTextNode(headers[cnt++]));
			}
			else {
				td.appendChild(document.createTextNode(" "));
			}
			tr.appendChild(td);
		}

		tbl.appendChild(tr);
	}

	//Iterate through all maneuvers and display text, time and distance for each maneuver based on options
	var trek, treks, maneuvers, maneuver, text;
	treks = routeResult. getTrekRoutes();
	for(var i=0; i < treks.getSize(); i++){
		trek = treks.getAt(i);
		maneuvers = trek.getManeuvers();
		for(var j=0; j < maneuvers.getSize(); j++){
			maneuver = maneuvers.getAt(j);

			tr = document.createElement("tr");
			tr.className = "trrouteresults" + (j % 2);

			if(showCount || showText){
				td = document.createElement("td");
				text = "";
				if(showCount){
					text += (j+1) + ".";
				}
				if(showCount && showText){
					text += " ";
				}
				if(showText){
					text += maneuver.getNarrative();
				}
				td.appendChild(document.createTextNode(text));
				tr.appendChild(td);
			}

			if(showDistance){
				td = document.createElement("td");
				td.appendChild(document.createTextNode(formatDistance(maneuver.getDistance()) + " mi"));
				tr.appendChild(td);
			}

			if(showTime){
				td = document.createElement("td");
				td.appendChild(document.createTextNode(formatTime(maneuver.getTime())));
				tr.appendChild(td);
			}

			tbl.appendChild(tr);
		}
	}

	return tbl;
}

/*
* Function to take an MQAddress object and return an string containing address information in a single line.
* Pre-Condtion: The MqAddress object != null
* Post-Condition: A string is returned containing address information on a single line.
*
* @param        mqaddress - an MQAddress object
* @return		A string containing address information on a single line.
*/
function mqAddressToSingleLineString(mqAddress){
	var element = mqAddressToSingleLineHTMLElement(mqAddress, document.createElement("div"));
	return element.innerHTML;
}

/*
* Function to take an MQAddress object and return an html element containing address information in a single line.
* Pre-Condtion: The MqAddress object != null
* Post-Condition: An html element is returned containing address information on a single line.
*
* @param        mqaddress - an MQAddress object
* @param		element - the html element the address information is being appended to
* @return		A string of html containing address information.
* @author       Seisan Consulting   2-16-2006
*/function mqAddressToSingleLineHTMLElement(mqAddress, element){
	if(!element)
		element = document.createElement("span");

	if(mqAddress.getName){
		if(mqAddress.getName() != ""){
			var b = document.createElement("b");
			b.appendChild(document.createTextNode(mqAddress.getName()));
			element.appendChild(b);
			element.appendChild(document.createTextNode(" "));
		}
	}

	if(mqAddress.getStreet() != ""){
		element.appendChild(document.createTextNode(mqAddress.getStreet()));
		element.appendChild(document.createTextNode(" "));
	}

	var spacer = false;
	if(mqAddress.getCity()){
		element.appendChild(document.createTextNode(mqAddress.getCity()));
		spacer = true;
	}

	if(mqAddress.getState()){
		if(spacer){
			element.appendChild(document.createTextNode(", "));
		}
		element.appendChild(document.createTextNode(mqAddress.getState()));
		spacer = true;
	}

	if(mqAddress.getPostalCode()){
		if(spacer){
			element.appendChild(document.createTextNode(" "));
		}
		element.appendChild(document.createTextNode(mqAddress.getPostalCode()));
		spacer = true;
	}


	return element;
}

/*
* Function to take an MQAddress object and return a string containing all address information.
* Pre-Condtion: MQAddress != null
* Post-Condition: A string containing address information is returned.
*
* @param        mqaddress - an MqAddress object
* @return		A string containing address information.
*/
function mqAddressToString(mqAddress){
	var element = mqAddressToHTMLElement(mqAddress, document.createElement("div"));
	return element.innerHTML;
}

/*
* Function to take an MQAddress object and return an html element containing all address information.
* Pre-Condtion: MQAddress != null
* Post-Condition: An html element containing address information is returned.
*
* @param        mqaddress - an MqAddress object
* @param        element - an html element
* @return		An html element containing the appended address information.
*/
function mqAddressToHTMLElement(mqAddress, element){
	if(!element)
		element = document.createElement("span");

	if(mqAddress.getName){
		if(mqAddress.getName() != ""){
			var b = document.createElement("b");
			b.appendChild(document.createTextNode(mqAddress.getName()));
			element.appendChild(b);
			element.appendChild(document.createElement("br"));
		}
	}

	if(mqAddress.getStreet() != ""){
		element.appendChild(document.createTextNode(mqAddress.getStreet()));
		element.appendChild(document.createElement("br"));
	}

	var spacer = false;
	if(mqAddress.getCity()){
		element.appendChild(document.createTextNode(mqAddress.getCity()));
		spacer = true;
	}

	if(mqAddress.getState()){
		if(spacer){
			element.appendChild(document.createTextNode(", "));
		}
		element.appendChild(document.createTextNode(mqAddress.getState()));
		spacer = true;
	}

	if(mqAddress.getPostalCode()){
		if(spacer){
			element.appendChild(document.createTextNode(" "));
		}
		element.appendChild(document.createTextNode(mqAddress.getPostalCode()));
		spacer = true;
	}


	return element;
}

/*
* Function to take a Record Set and build a string containing address information.
* Pre-Condtion: The Recordset != null
* Post-Condition: A strign is returned containing address information.
*
* @param        recordset - a recordset object
* @return		str - a string containing address information pulled from the record set.
*/
function getContentString(recordset){
	var str = "";
	str += recordset.getField("Address") + "<br/>";
	str += recordset.getField("City") + ", ";
	str += recordset.getField("State") + " ";
	str += recordset.getField("ZIP");

	return str;

}

/*
* Function to take a Record Set and build a string containing address information on a single line.
* Pre-Condtion: The Recordset != null
* Post-Condition: A strign is returned containing address information on a single line.
*
* @param        recordset - a recordset object
* @return		str - a string containing address information on a single line pulled from the record set.
* @author       Seisan Consulting   2-16-2006
*/
function getContentStringSingleLine(recordset){
	var str = "";
	str += recordset.getField("Address") + " ";
	str += recordset.getField("City") + ", ";
	str += recordset.getField("State") + " ";
	str += recordset.getField("ZIP");

	return str;

}

/*
* Function to build an html hidden form element containing address information from a record set.
* Pre-Condtion: The Record Set != null
* Post-Condition: An html hidden form element is created containing address information.
*
* @param        recordset - a record set object
* @param		i - index of the record set being passed
* @return		An html hidden form element containing address information aquired from the record set.
*/
function getResultForm(recordset, i){
	var frm, input;
	frm = document.createElement("form");
	frm.method="get";
	frm.action = "";
	frm.id = "frm" + i;

	input = createInputElement("hidden", "txtName", recordset.getField("N"));
	frm.appendChild(input);

	input = createInputElement("hidden", "txtBrand", recordset.getField("brand"));
	frm.appendChild(input);


	input = createInputElement("hidden", "txtAddress", recordset.getField("Address"));
	frm.appendChild(input);

	input = createInputElement("hidden", "txtCity", recordset.getField("City"));
	frm.appendChild(input);

	input = createInputElement("hidden", "selStateProvince", recordset.getField("State"));
	frm.appendChild(input);

	input = createInputElement("hidden", "txtPostalCode", recordset.getField("ZIP"));
	frm.appendChild(input);

	input = createInputElement("hidden", "hdnLatitude", recordset.getField("Lat"));
	frm.appendChild(input);

	input = createInputElement("hidden", "hdnLongitude", recordset.getField("Lng"));
	frm.appendChild(input);

	input = createInputElement("hidden", "hdnType", type);
	frm.appendChild(input);

	input = createInputElement("hidden", "rdoUnit", DEFAULT_UNIT);
	frm.appendChild(input);

	input = createInputElement("hidden", "txtDistance", DEFAULT_RADIUS);
	frm.appendChild(input);

	return frm;
}

/*
* Function to submit a form with the appropriate form action passed
* Pre-Condtion: none
* Post-Condition: The form provided is submitted with the action passed.
*
* @param        id - id of the form being submitted
* @param		action - the action of the form, example POST, GET etc
*/
function submitForm(id, action){
	var frm = document.getElementById(id);
	frm.action = action;
	frm.submit();
}

/*
* Function to handle the click event on a poi and table result
* Pre-Condtion: The event must exist.
* Post-Condition: The appropriate action is taken based on the object that triggered the event.
*
* @param        e - a javascript event
*/
function onPoiClick(e){
	var poiid = false;
	var poi = null;
	//If the key is defined then a Poi has triggered this event
	if(this.getKey){
		//retrieve the correct table rows from the results table based on the key of the poi that triggered the event
		poiid = this.getKey();

		poi = map.getPoiByKey(poiid);

		if(poi != null){
			poi.showInfoWindow();
		}
	}
	else {
		//The result on the result table has triggered the event
		var obj = getEventCurrentTarget(e);
		poiid =  obj.id;
		poiid = poiid.substring(poiid.lastIndexOf("_")+1);
		//Retrieve the poi based on the key read from the table row that triggered the event
		poi = map.getPoiByKey(poiid);

		if(poi != null){
			poi.showInfoWindow();
		}
	}

}

/*
* Function to handle the mouseover event on a poi and table result
* Pre-Condtion: The event must exist.
* Post-Condition: The appropriate action is taken based on the object that triggered the event.
*
* @param        e - a javascript event
* @author       Seisan Consulting   2-16-2006
*/
function onPoiMouseover(e){
	var poiid = false;
	var poi = null;
	//If the key is defined then a Poi has triggered this event
	var infowindow = map.getInfoWindow();

	if(this.getKey){
		if(this != infowindow.getOpener()){
			if(!infowindow.isHidden()){
				infowindow.hide();
			}
		}

		//retrieve the correct table rows from the results table based on the key of the poi that triggered the event
		poiid = this.getKey();
		var tr1 = document.getElementById("tr1_" + poiid);
		var tr2 = document.getElementById("tr2_" + poiid);
		//Switch the class names of the table rows to the class for the highlighted table row
		if(tr1.className.indexOf("_over") == -1){
			tr1.className = tr1.className + "_over";
		}
		if(tr2.className.indexOf("_over") == -1){
			tr2.className = tr2.className + "_over";
		}
		if(!e.supressScroll){
			//scroll to the search result on the table
			scrollToSearchResult(poiid);
		}

	}
	else {
		//The result on the result table has triggered the event

		if(!infowindow.isHidden()){
			infowindow.hide();
		}

		var obj = getEventCurrentTarget(e);
		poiid =  obj.id;
		poiid = poiid.substring(poiid.lastIndexOf("_")+1);
		//Retrieve the poi based on the key read from the table row that triggered the event
		poi = map.getPoiByKey(poiid);



		if(poi != null){

			//Create a mouseover event and send it to the matching poi on the map to have the poi show the infowindow
			var event = new Object();
			event.type ="mouseover";
			event.supressScroll = true;
			poi.onMouseOver(event);
		}
	}

}

/*
* Function to handle the mouseout event on a poi and table result
* Pre-Condtion: The event must exist.
* Post-Condition: The appropriate action is taken based on the object that triggered the event.
*
* @param        e - a javascript event
* @author       Seisan Consulting   2-16-2006
*/
function onPoiMouseout(e){
	//If the key is defined then a Poi has triggered this event
	var poiid = false;
	var poi = null;
	if(this.getKey){
		//retrieve the correct table rows from the results table based on the key of the poi that triggered the event
		poiid = this.getKey();
		var tr1 = document.getElementById("tr1_" + poiid);
		var tr2 = document.getElementById("tr2_" + poiid);
		//Switch the class names of the table rows to the class for the non-highlighted table row
		var cn = tr1.className;
		if(cn.indexOf("_over") > -1){
			cn = cn.substring(0,cn.indexOf("_over"));
			tr1.className = cn;
		}
		var cn = tr2.className;
		if(cn.indexOf("_over") > -1){
			cn = cn.substring(0,cn.indexOf("_over"));
			tr2.className = cn;
		}
	}
	else {
		//The result on the result table has triggered the event

		var obj = getEventCurrentTarget(e);
		poiid =  obj.id;
		poiid = poiid.substring(poiid.lastIndexOf("_")+1);
		//Retrieve the poi based on the key read from the table row that triggered the event
		poi = map.getPoiByKey(poiid);
		if(poi != null){
			//Create a mouseover event and send it to the matching poi on the map to have the poi show the infowindow
			var event = new Object();
			event.type ="mouseout";
			poi.onMouseOut(event);
		}
	}

}

/*
* Function to sort the datamanager results ordered by distance.
* Pre-Condtion: none
* Post-Condition: The results are sorted numerically by distance from smallest to largest.
*
* @param        dm1 - a datamanager result
* @param		dm2 - a datamanager result
* @return		The differenc between the results.
* @author       Seisan Consulting   2-16-2006
*/
function sortDataManagerResults(dm1, dm2){

	var d1 = dm1.getDistance();
	var d2 = dm2.getDistance();
	if(d1 == null && d2 == null)
		return 0;
	else if(d1 == null){
		return 1;
	}
	else if(d2 == null){
		return -1;
	}
	else {
		return parseFloat(d1) - parseFloat(d2);
	}
}


/*
* Function to sort the datamanager results ordered by route time.
* Pre-Condtion: none
* Post-Condition: The results are sorted numerically by time from smallest to largest.
*
* @param        dm1 - a datamanager result
* @param		dm2 - a datamanager result
* @return		The differenc between the results.
* @author       Seisan Consulting   2-16-2006
*/
function sortDataManagerResultsTime(dm1, dm2){

	var t1 = dm1.getRouteTime();
	var t2 = dm2.getRouteTime();
	if(t1 == null && t2 == null)
		return 0;
	else if(t1 == null){
		return 1;
	}
	else if(t2 == null){
		return -1;
	}
	else {
		return parseFloat(t1) - parseFloat(t2);
	}
}

/*
* Function to build an array of Datamanager records from the recordset and feature collection.
* Pre-Condtion: none
* Post-Condition: An array of datamanager records is returned.
*
* @param        recordset - a recordset object.
* @param        recordset - an MQFeatureCollection object.
* @return		results - an array of data manager record objects obtained from the feature collection
* @author       Seisan Consulting   2-16-2006
*/
function getResultsAsArray(recordSet, featureCollection, time){
	// An array of data manager records
	var results = new Array();
	var dmRecord;
	while(!recordSet.isEOF()){
		dmRecord = new DataManagerRecord(recordSet);
		if(featureCollection){
			for(var i=0; i < featureCollection.getSize(); i++){
				if(dmRecord.getId() == featureCollection.getAt(i).getKey()){
					dmRecord.setDistance(featureCollection.getAt(i).getDistance());
					break;
				}
			}
		}

		results.push(dmRecord);

		recordSet.moveNext();
	}
	if(featureCollection){
		results.sort(sortDataManagerResults);
	}
	return results;

}

/*
* Function to change the value of the page number and reload the results based on that page number.
* Pre-Condtion: pageNum is numeric
* Post-Condition: the page number is changed and the results reloaded.
*
* @param        pagenum - number of the page to be changed to
* @author       Seisan Consulting   2-16-2006
*/
var currentPage = 0;
var currentResults = new Array();

function changePage(pageNum){
	currentPage = pageNum;
	showResults()
}

/*
* Function to scroll the results table to the location of the id passed.
* Pre-Condtion: The key != null
*
* @param        key - a poi id key
* @author       Seisan Consulting   2-16-2006
*/
function scrollToSearchResult(key){
	var div = document.getElementById("divResults");
	if(div){
		var cnt = 0;


		for(var i=currentPage * PAGE_SIZE; i < currentResults.length && i <= MAX_MATCHES && i < (currentPage * PAGE_SIZE + PAGE_SIZE); i++){
			if(currentResults[i].getId() == key){
				break;
			}
			cnt++;
		}

		div.scrollTop = cnt * SCROLL_DISTANCE;

	}
}

/*
* Function to display the search results on the Map and in a table
* Pre-Condtion: results > 0
* Post-Condition: A table is displayed with the results from the search
*
* @param        results - Search Results Collection
* @param		origLatLng - an MqLatLng object containing the Origin Latitude and Longitude
* @param        isPoiSearch - Boolean value contains the evaluation of whether the results are of Pois or Hotel Addresses.
* @return
*/
function showResults(results, origLatLng, isPoiSearch){
	var icon, poi, latlng;

	//If a new set of results have been passed in replace the current results being shown
	if(results){
		currentResults = results;
	}
	//Otherwise results have not changed, working with the same results
	else {
		results = currentResults;
	}

	//Remove all pois from the map except, start, end and origin
	var pois = map.getPois();
	for(var i = pois.getSize()-1; i >= 0; i--){
		poi = pois.getAt(i);
		if(poi.getKey() != "origin" && poi.getKey() != "start" && poi.getKey() != "end"){
			map.removePoi(poi);
		}
	}

	//Build results table
	var tbl = document.createElement("table");
	tbl.cellPadding = 4;
	tbl.cellSpacing = 0;
	tbl.border = 0;
	tbl.className = "resultstable";

	var tr, td, th, img, a, b, distance, time, imgSrc;
	var spacer;

	var rowItt = 0;
	var cellItt = 0;
	if(results.length > 0){
		for(var i=currentPage * PAGE_SIZE; i < results.length && i <= MAX_MATCHES && i < (currentPage * PAGE_SIZE + PAGE_SIZE); i++){

			//Populate the Map with the Results

			icon = new MQMapIcon();
			//If isPoiSearch is true, then use the corresponding poi icon based on the DT Style - displaying Points of Interest
			if(isPoiSearch){
				imgSrc = "locatorImages/mq_icons/" + results[i].getField("T") + ".gif";
				icon.setImage(imgSrc, 20, 20, true, false);
			}
			else {
			//Otherwise, use the numbered icons to display results - displaying Hotel Addresses
				imgSrc = "locatorImages/icons/" + (i+1) + ".gif";
				icon.setImage(imgSrc, 16, 16, true, false);
			}

			latlng = results[i].getMQLatLng();

			//Build the pois content and set the mouseover and mouseout events
			poi = new MQPoi(latlng, icon);
			poi.setInfoTitleHTML(results[i].getInfoTitleHTML());
			poi.setInfoContentElement(results[i].getInfoContentElement(i, isPoiSearch));
			//poi.setInfoContentHTML(results[i].getInfoContentHTML(i, isPoiSearch));
			poi.setRolloverEnabled(true);
			poi.setKey(results[i].getId());
			MQEventManager.addListener(poi,"mouseover", onPoiMouseover);
			MQEventManager.addListener(poi,"mouseout", onPoiMouseout);
			MQEventManager.addListener(poi,"click", onPoiClick);

			//Add each poi to the map
			map.addPoi(poi);

			//Build each Table row and add in events for mouseover and mouseout
			tr = tbl.insertRow(rowItt++);
			cellItt = 0;
			tr.vAlign = "top";
			tr.className = "resultstablerow1";
			tr.id = "tr1_" + results[i].getId();
			//tr.appendChild(results[i].getResultForm(i));

			td = tr.insertCell(cellItt++);
			td.rowSpan = 2;
			td.onmouseover = onPoiMouseover;
			td.onmouseout = onPoiMouseout;
			td.onclick = onPoiClick;
			td.id = "td1_" + results[i].getId();

			img = document.createElement("img");
			img.src = imgSrc
			img.id = "img_"+ results[i].getId();
			td.appendChild(img);
			td.appendChild(results[i].getResultForm(i));
			tr.appendChild(td);

			td = tr.insertCell(cellItt++);
			td.id = "td2_" + results[i].getId();
			td.onmouseover = onPoiMouseover;
			td.onmouseout = onPoiMouseout;
			td.onclick = onPoiClick;
			td.appendChild(document.createTextNode(results[i].getName()));
			tr.appendChild(td);

			td = tr.insertCell(cellItt++);
			td.onmouseover = onPoiMouseover;
			td.onmouseout = onPoiMouseout;
			td.id = "td3_" + results[i].getId();

			//Build links for searching for hotel locations or Poi Location based on isPoiSearch
			a = document.createElement("a");
			a.id = "a1_"+ results[i].getId();
			a.onmouseover = onPoiMouseover;
			a.onmouseout = onPoiMouseout;

			if(isPoiSearch){
				//isPoiSearch is true - displaying Points of Interest - link searches for Hotel Addresses
				a.href = "javascript:submitForm('frm" + i + "', 'searchlocation.html');"
			}
			else {
				//isPoiSearch is false - displaying Location Addresses - link searches for Points of Interest
				a.href = "javascript:submitForm('frm" + i + "', 'surroundingarea.html');"
			}
			if(isPoiSearch)
				a.appendChild(document.createTextNode("Find Locations"));
			else
				a.appendChild(document.createTextNode("Surrounding Area"));
			//td.appendChild(a);
			tr.appendChild(td);

			td = tr.insertCell(cellItt++);
			td.onmouseover = onPoiMouseover;
			td.onmouseout = onPoiMouseout;
			td.id = "td4_" + results[i].getId();


			//Build links to display detail information
			if(isPoiSearch){
				//isPoiSearch is true - hide the details link
				td.onclick = onPoiClick;
				td.appendChild(document.createTextNode(" "));

			}
			else {
				//isPoiSearch is false - displaying Hotel Addresses - link displays Hotel Details
				a = document.createElement("a");
				a.onmouseover = onPoiMouseover;
				a.onmouseout = onPoiMouseout;
				a.id = "a2_"+ results[i].getId();
				a.href = "details.html?pid=" + results[i].getId();
				//a.appendChild(document.createTextNode("Property Overview"));
				//td.appendChild(a);
			}
			tr.appendChild(td);

			//Display the Distance and Time from the Origin
			if(results[i].getDistance() != null || results[i].getRouteTime() != null){
				td = tr.insertCell(cellItt++);
				td.onmouseover = onPoiMouseover;
				td.onmouseout = onPoiMouseout;
				td.onclick = onPoiClick;
				td.rowSpan = 2;
				td.id = "td5_" + results[i].getId();
				spacer = false;
				if(results[i].getRouteTime() != null){
					b = document.createElement("b");
					b.id = "b1_"+ results[i].getId();
					b.onmouseover = onPoiMouseover;
					b.onmouseout = onPoiMouseout;

					distance = formatDistance(results[i].getRouteDistance());
					b.appendChild(document.createTextNode(distance + " Miles"));
					td.appendChild(b);

					td.appendChild(document.createElement("br"));

					b = document.createElement("b");
					b.id = "a2_"+ results[i].getId();
					b.onmouseover = onPoiMouseover;
					b.onmouseout = onPoiMouseout;

					if(results[i].getRouteTime() >= 3600)
						time = formatTime(results[i].getRouteTime(),"%h hr %m min %s sec");
					else
						time = formatTime(results[i].getRouteTime(),"%m min %s sec");
					b.appendChild(document.createTextNode(time));
					td.appendChild(b);
					spacer = true;
				}
				else {
					b = document.createElement("b");
					b.id = "a1_"+ results[i].getId();
					b.onmouseover = onPoiMouseover;
					b.onmouseout = onPoiMouseout;
					distance = formatDistance(results[i].getDistance());
					b.appendChild(document.createTextNode(distance + " Miles"));
					td.appendChild(b);
				}

				tr.appendChild(td);
			}

			//tbl.appendChild(tr);

			tr = tbl.insertRow(rowItt++);
			cellItt = 0;
			tr.id = "tr2_" + results[i].getId();
			tr.className = "resultstablerow2";


			td = tr.insertCell(cellItt++);
			td.onmouseover = onPoiMouseover;
			td.onmouseout = onPoiMouseout;
			td.onclick = onPoiClick;
			td.id = "td6_" + results[i].getId();
			td.appendChild(document.createTextNode(results[i].getSingleLineHTML()));
			br = document.createElement("br");
			td.appendChild(br);
			br1 = document.createElement("br");
			td.appendChild(br1);
			if (results[i].getMonClose() != results[i].getTuesClose())
			{
			    td.appendChild(document.createTextNode("Store Hours: Mon : "));
			    td.appendChild(document.createTextNode(results[i].getMonOpen()));
			    td.appendChild(document.createTextNode(" - "));
			    td.appendChild(document.createTextNode(results[i].getMonClose()));
			    td.appendChild(document.createTextNode(" T - F : "));
			    td.appendChild(document.createTextNode(results[i].getMonOpen()));
			    td.appendChild(document.createTextNode(" - "));
			    td.appendChild(document.createTextNode(results[i].getTuesClose()));
			}
			else
			{
			    td.appendChild(document.createTextNode("Store Hours: M - F : "));
			    td.appendChild(document.createTextNode(results[i].getMonOpen()));
			    td.appendChild(document.createTextNode(" - "));
			    td.appendChild(document.createTextNode(results[i].getMonClose()));
			}
			td.appendChild(document.createTextNode("  Sat: "));
			td.appendChild(document.createTextNode(results[i].getSatOpen()));
			td.appendChild(document.createTextNode(" - "));
			td.appendChild(document.createTextNode(results[i].getSatClose()));
			td.appendChild(document.createTextNode("  Sun: "));
			if (results[i].getSunOpen() != "0:00PM" )
			{
				td.appendChild(document.createTextNode(results[i].getSunOpen()));
			}
				else
			{
			    td.appendChild(document.createTextNode(" Closed "));
			}
					
			if (results[i].getSunClose() != "Closed" && results[i].getSunClose() != "0:00PM" && results[i].getSunClose() != "CLOSED"  )
			{
			td.appendChild(document.createTextNode(" - "));
			td.appendChild(document.createTextNode(results[i].getSunClose()));
			}
			
			tr.appendChild(td);

			//Build link for Driving Directions
			td = tr.insertCell(cellItt++);
			td.onmouseover = onPoiMouseover;
			td.onmouseout = onPoiMouseout;
			td.id = "td7_" + results[i].getId();
			a = document.createElement("a");
			a.id = "a3_"+ results[i].getId();
			a.onmouseover = onPoiMouseover;
			a.onmouseout = onPoiMouseout;
			a.href = "javascript:submitForm('frm" + i + "', 'drivingdirections.aspx');";
			a.appendChild(document.createTextNode("Driving Directions"));
			td.appendChild(a);
			br = document.createElement("br");
			td.appendChild(br);
			br1 = document.createElement("br");
			td.appendChild(br1);
			td.appendChild(document.createTextNode("Phone Number: "));
			td.appendChild(document.createTextNode(results[i].getPhone()));
			
			tr.appendChild(td);

			td = tr.insertCell(cellItt++);
			tr.vAlign = "top";
			td.onmouseover = onPoiMouseover;
			td.onmouseout = onPoiMouseout;
			td.id = "td8_" + results[i].getId();
			a = document.createElement("a");
			a.id = "a4_"+ results[i].getId();
			a.onmouseover = onPoiMouseover;
			a.onmouseout = onPoiMouseout;
			a.href = "StoreLocator.aspx";
			a.appendChild(document.createTextNode("Search Again"));
			td.appendChild(a);
			tr.appendChild(td);

			//tbl.appendChild(tr);

		}

		//Handle the paging if the results > PAGE_SIZE
		//Build Paging Links to display results on other pages
		if(results.length > PAGE_SIZE){
			var pages = Math.ceil(results.length / PAGE_SIZE);
			if(pages * PAGE_SIZE > MAX_MATCHES){
				pages = Math.ceil(MAX_MATCHES / PAGE_SIZE);
			}

		    tr = tbl.insertRow(rowItt++);
		    cellItt = 0;

		    td = tr.insertCell(cellItt++);
		    td.colSpan = 5;

			tr = tbl.insertRow(rowItt++);
			cellItt = 0;

			td = tr.insertCell(cellItt++);
			td.className = "paged";
			td.colSpan = 5;

			if(currentPage > 0 ){
				a = document.createElement("a");
				a.href = "javascript:changePage(0);"
				a.appendChild(document.createTextNode("<<<"));
				td.appendChild(a);

				a = document.createElement("a");
				a.href = "javascript:changePage(" + (currentPage -1) + ");"
				a.appendChild(document.createTextNode("<"));
				td.appendChild(a);
			}

			for (var i=0; i < pages; i ++){
				if(currentPage == i){
					b = document.createElement("b");
					b.appendChild(document.createTextNode(i+1));
					td.appendChild(b);
				}
				else {
					a = document.createElement("a");
					a.href = "javascript:changePage(" + i + ");"
					a.appendChild(document.createTextNode(i+1));
					td.appendChild(a);
				}
			}

			if(currentPage < pages - 1 ){
				a = document.createElement("a");
				a.href = "javascript:changePage(" + (currentPage + 1) + ");"
				a.appendChild(document.createTextNode(">"));
				td.appendChild(a);

				a = document.createElement("a");
				a.href = "javascript:changePage(" + (pages - 1) + ");"
				a.appendChild(document.createTextNode(">>>"));
				td.appendChild(a);
			}

			//tr.appendChild(td);
			//tbl.appendChild(tr);

		}
	}
	else {
		tr = tbl.insertRow(rowItt++);
		cellItt = 0;

		td = tr.insertCell(cellItt++);
		td.className = "noresult";
		td.colSpan = 5;

		b = document.createElement("b");
		b.appendChild(document.createTextNode("No stores were found within the distance you specified.  Please search again and increase the number of miles to search."));
		td.appendChild(b);

		tr = tbl.insertRow(rowItt++);
		cellItt = 0;

		td = tr.insertCell(cellItt++);
		td.className = "noresult";
		td.colSpan = 5;
		
		a = document.createElement("a");
		a.href = "StoreLocator.aspx";
		a.appendChild(document.createTextNode("Search Again"));
		td.appendChild(a);

	}

	//Append the results to the page
	var parent = document.getElementById("divResults");
	//if(!browserCheck.ie){
		removeAllChildren(parent);
		parent.appendChild(tbl);
	/*}
	else {
		//alert(tbl.outerHTML);
		parent.innerHTML = tbl.outerHTML;
	}*/

	//Best fit the results on the map
	if(results.length > 0)
		map.bestFit(false);
}


/*
* Function to retrieve the route distance and time for the search results when searching by minutes. Performs route Matrix.
* Pre-Condtion: OrigLatLng != null
* Post-Condition: The dataManagerRecordArray is returned with all route times and route distances for each result populated
*
* @param        originLatLng - MQLatLng object containing origin Latitude and Longitude
* @param		dataManagerRecordArray - array of Datamanager Records
* @return		dataManagerRecordArray - array containing each search result with the route times and route distances calculated and populated
* @author       Seisan Consulting   2-16-2006
*/
function getRouteDistanceTime(originLatLng, dataManagerRecordArray, searchtime){
	if(dataManagerRecordArray.length >= 0 ){
		var routeExec = new MQExec(routeServer, serverPath, serverPort, proxyServer, proxyPath, proxyPort);
		var origAddress = new MQGeoAddress();
		origAddress.setStreet("origin");
		origAddress.setMQLatLng(originLatLng);

		//populate array with all addresses to pass to function to calculate route matrix
		var destAddresses = new MQLocationCollection();
		destAddresses.add(origAddress);
		for(var i=0; i < dataManagerRecordArray.length; i++){
			destAddresses.add(dataManagerRecordArray[i]);
		}

		var rOptions = new MQRouteOptions();
		var rmResults = new MQRouteMatrixResults();

		//Perform Route Matrix
		routeExec.doRouteMatrix(destAddresses, false, rOptions, rmResults);


		var newList = new Array()
		//Populate Time and Distance Results
		var maxtime = parseInt(searchtime) * 60;
		for(var i=0; i < dataManagerRecordArray.length; i++){
			if( maxtime >= parseInt(rmResults.getTime(0, i+1))){
				var obj = dataManagerRecordArray[i]
				obj.setRouteTime(rmResults.getTime(0, i+1));
				obj.setRouteDistance(rmResults.getDistance(0, i+1));
				newList.push(obj);
			}
		}

		newList.sort(sortDataManagerResultsTime);
		return newList;
	}
	else {
		return dataManagerRecordArray;
	}
}
