/*
* 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
* @author       Seisan Consulting   2-16-2006
*/
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
* @author       Seisan Consulting   2-16-2006
*/
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.
* @author       Seisan Consulting   2-16-2006
*/
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.
* @author       Seisan Consulting   2-16-2006
*/
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.
* @author       Seisan Consulting   2-16-2006
*/
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.
* @author       Seisan Consulting   2-16-2006
*/
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.
* @author       Seisan Consulting   2-16-2006
*/
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.
* @author       Seisan Consulting   2-16-2006
*/
function getResultForm(recordset, i){
	var frm, input;
	frm = document.createElement("form");
	frm.method="get";
	frm.action = "";
	frm.id = "frm" + i;
    //alert("demo_common: entering getResultForm");
	input = createInputElement("hidden", "txtName", recordset.getField("N"));
	frm.appendChild(input);
    //alert (recordset.getField("Address"));
	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", "ddwnDistance", 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
* @author       Seisan Consulting   2-16-2006
*/
function submitForm(id, action){    
	var frm = document.getElementById(id);
	frm.action = action;	
	//alert("id=" + id + "; action=" + action + "; method=" + frm.method);
	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
* @author       Seisan Consulting   2-16-2006
*/
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()){
				//Removed as business request.  InfoWindow will remain visible until the next click of a poi/result
				//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();
		//alert(poiid);
		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()){
			//Removed as business request.  InfoWindow will remain visible until the next click of a poi/result
			//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()){
					if (featureCollection.getAt(i).getDistance() == '')
				        dmRecord.setDistance(0);
				    else
					    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 CheckSrcItemForOnclick(e){

    //alert ("entering CheckSrcItemForOnclick");
    var winEvent;
    onPoiClick(e);
    
    if (e)
        winEvent = e.target.tagName;
    else
        winEvent = window.event.srcElement.tagName;
    //alert (winEvent);
    if ( winEvent == "A")
    {
        var pDoc = parent.document;
        var mqfrm, searchType;
        var qs = new Querystring();
    
        if(null != qs.get("ddwnSearchType"))
	    {
            searchType = qs.get("ddwnSearchType"); 
            if ( searchType == 'FA' )
            {
                mqfrm = pDoc.getElementById('mapquestfa');
                mqfrm.contentWindow.ShowMsgDiv("<p class=\"error\"><img src=\"/publish/tm/images/progress.gif\" width=\"20px\" height=\"20px\" alt=\"Progress\">Loading page in progress...</p>");
            }
            else
            {
                mqfrm = pDoc.getElementById('mapquestbranch');
                // Change for Showing result only when the link doesnt contains fabrcriteria which is for MapQuestBranch
                if(parent.location.search.indexOf('fabrcriteria') == -1)
                {
                    mqfrm.contentWindow.ShowMsgDiv("<p class=\"error\"><img src=\"/publish/tm/images/progress.gif\" width=\"20px\" height=\"20px\" alt=\"Progress\">Loading Branch page in progress...</p>");
                }
                // Code ends here
             }
	    }
    }
}
/*
* 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 Branch Information.
* @return
* @author       Seisan Consulting   2-16-2006
*/
function showResults(results, origLatLng, isPoiSearch){
	var icon, poi, latlng;
    var qs = new Querystring();		
	var origGeoAddress  = new MQGeoAddress();
	var orgTxtCity, orgTxtState, orgTxtZip, hndInput;
	var showErrMsg = false;
	
	
	//Digvijoy
	//Remove this in the next build
	var getsearchType = qs.get("ddwnSearchType");
	/*Code for Dart BOA JS*/
	//var script = '';
	var objIframe = document.createElement('iframe');
	var frameSrc = 'http://fls.doubleclick.net/activityi;src=1359940;type=sdlpb511;cat=';
	var axel = Math.random()+"";
	var a = axel * 10000000000000;
	objIframe.width = "1";
	objIframe.height="1"
	objIframe.frameBorder="0";
	
    if (null != getsearchType)
    {
        if ( getsearchType == 'BRANCH' )
        {
            objIframe.src = frameSrc + 'mlfin137;ord=1;num='+ a + '?';
            //objIframe.src = fls.doubleclick.net/activityi;src=1359940;type=sdlpb511;cat=mlfin137;ord=1;num=\'+ a + \'?" WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>\');';
        }
        else if ( getsearchType == 'FA' )
        {
            objIframe.src = frameSrc + 'mlfin407;ord=1;num='+ a + '?';  
            //script = 'var axel = Math.random()+"";a = axel * 10000000000000;document.write(\'<IFRAME SRC="http://fls.doubleclick.net/activityi;src=1359940;type=sdlpb511;cat=mlfin407;ord=1;num=\'+ a + \'?" WIDTH=1 HEIGHT=1 FRAMEBORDER=0></IFRAME>\');';
        }
    }
   

	//objScript.createTextNode(script);
	document.body.appendChild(objIframe);
	 /*Code ends here Dart BOA JS*/
	var dvResult = document.getElementById("divResults");
	dvResult.style.display = "block";
	
	//Get the topmost parent DOM document
	var pDoc = parent.document;
    var mqfrm;
	
	orgTxtCity = qs.get("txtCity");
	orgTxtState = qs.get("selStateProvince");
	orgTxtZip = qs.get("txtPostalCode");
	orgLatitude = qs.get("hdnLatitude");
	orgLongitude = qs.get("hdnLongitude");
    
    if (orgTxtCity)
	    origGeoAddress.setCity(orgTxtCity);
	if (orgTxtState)
	    origGeoAddress.setState(orgTxtState);
	if (orgTxtZip)
	    origGeoAddress.setPostalCode(orgTxtZip);
	if (orgLatitude && orgLongitude)
	    origGeoAddress.setMQLatLng(new MQLatLng(orgLatitude,orgLongitude));
        
    //alert("entering showResults: " + results.length);
    
	//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.width = 465;
	tbl.className = "resultstable";

	var tr, td, th, img, a, b, distance, time, imgSrc, inPutHidden;
	var spacer;

	var rowItt = 0;
	var cellItt = 0;
	var rowNum = 2;
	//alert("Results= " + results.length);
	//alert ("BranchFinderResults= " + BranchFinderNameSearchResults.length);
    var searchType = qs.get("ddwnSearchType");
    if (null != searchType)
    {
        if ( searchType == 'FA' )
            mqfrm = pDoc.getElementById('mapquestfa');
        else
            mqfrm = pDoc.getElementById('mapquestbranch');
    }
                    
    if ( searchType == 'FA' )
    {
        if(BranchFinderNameSearchResults.length == 0)
        {
		    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 Results Found.  Please refine your search criteria and try again."));
		    td.appendChild(b);
            mqfrm.contentWindow.ShowMsgDiv("<p class=\"error\">No Results Found.  Please refine your search criteria and try again.</p>")
            showErrMsg = true;
            
	        //Append the results to the page
	        var _parent = document.getElementById("divResults");
	        removeAllChildren(_parent);
	        _parent.appendChild(tbl);
    		
    		//This will remove the map when no results are returned.  Only for this specific case
    		var _parentContent = document.getElementById("divContent");
	        removeAllChildren(_parentContent);
	        
	        //var qs = new Querystring();		
	        //var searchType = '';
    		
	        if(!showErrMsg)
	        {                    
	            mqfrm.contentWindow.ShowMsgDiv('');
	        }        
            return;
        }
    }

    if(results.length >= MAX_MATCHES)
    {
        	tr = tbl.insertRow(rowItt++);
		    cellItt = 0;

		    td = tr.insertCell(cellItt++);
		    td.className = "noresult";
		    td.colSpan = 5;

		    b = document.createElement("b");
		    //b.appendChild(document.createTextNode("Your search has returned the maximum allowed results.  Please refine your search and try again."));
		    td.appendChild(b);
		    mqfrm.contentWindow.ShowMsgDiv("<p class=\"error\">Your search has returned the maximum allowed results.  Please refine your search and try again.</p>");
		    showErrMsg = true;
	}
    var resultCount = 0;
	if(results.length > 0){	    
		for(var i=currentPage * PAGE_SIZE; i < results.length && i <= MAX_MATCHES && i < (currentPage * PAGE_SIZE + PAGE_SIZE); i++){	            
			    var NameList = new Array();
                var finderResult = new Array();
                finderResult = BranchFinderNameSearchResults.split('%');
                
                if(finderResult.length > 1)
                {
                    for(x=0; x<finderResult.length; x++)
                    {
                        NameList = finderResult[x].split('|');
                        //if there is no page url for an fa - disregard it and move to next record
                        //alert (NameList[0]);    
                        if(results[i].getBranchId() == NameList[0])
                        {
		                    if(NameList[2].length == 0)
		                        continue;
		                    else
		                        resultCount++;
			                //Populate the Map with the Results
                            //alert ("PostalCode=" + orgTxtZip + " for frm" + i);
			                icon = new MQMapIcon();
			                //alert("POISearch=" + isPoiSearch + "DisplayType: " + results[1].getField("T") + " " + results[2].getField("T"));
			                //If isPoiSearch is true, then use the corresponding poi icon based on the DT Style - displaying Points of Interest
			                if(isPoiSearch){
				                imgSrc = MLGlobalVar_GlobalImagePath + results[i].getField("T") + ".gif";
				                icon.setImage(imgSrc, 20, 20, true, false);
			                }
			                else {
			                //Otherwise, use the numbered icons to display results - displaying Branch Information
				                imgSrc = MLGlobalVar_GlobalImagePath + (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 = "resultstablerow" + rowNum;
			                tr.id = "tr1_" + results[i].getId();
			                //alert(results[i].getId());

			                frm = results[i].getResultForm(i);
                			
			                //Build hidden fields for original address
			                //hndInput = createInputElement("hidden", "hdnAddress", origGeoAddress.getStreet());
	                        //frm.appendChild(hndInput);
	                        hndInput = createInputElement("hidden", "branchCode", results[i].getBranchId());
	                        frm.appendChild(hndInput);	  
	                        hndInput = createInputElement("hidden", "branchName", results[i].getName());
	                        frm.appendChild(hndInput);	    	                                              
	                        hndInput = createInputElement("hidden", "hdnCity", origGeoAddress.getCity());
	                        frm.appendChild(hndInput);
	                        hndInput = createInputElement("hidden", "hdnStateProvince", origGeoAddress.getState());
	                        frm.appendChild(hndInput);
	                        hndInput = createInputElement("hidden", "hdnPostalCode", origGeoAddress.getPostalCode());
	                        frm.appendChild(hndInput);
	                        if(origGeoAddress.getMQLatLng()){
		                        hndInput = createInputElement("hidden", "orgLatitude", origGeoAddress.getMQLatLng().getLatitude());
		                        frm.appendChild(hndInput);

		                        hndInput = createInputElement("hidden", "orgLongitude", origGeoAddress.getMQLatLng().getLongitude());
		                        frm.appendChild(hndInput);
	                        }	        
			                tr.appendChild(frm);
                			
			                //alert(results[i].getBranchId());

                            td = tr.insertCell(cellItt++);
                            td.rowSpan = 2;
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            //td.onclick = onPoiClick;
                            td.onclick = CheckSrcItemForOnclick;
                            td.id = "td1_" + results[i].getId();

                            img = document.createElement("img");
                            img.src = imgSrc
                            img.id = "img_"+ results[i].getId();
                            td.appendChild(img);
                            //tr.appendChild(td);
                			

                            td = tr.insertCell(cellItt++);
                            td.id = "td2_" + results[i].getId();
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            td.onclick = CheckSrcItemForOnclick;
                            //td.onclick = onPoiClick;
                            

                            a = document.createElement("a");
//                            a.onmouseover = onPoiMouseover;
//                            a.onmouseout = onPoiMouseout;
                            a.id = "a9_"+ results[i].getId();
                            
                            
                            
                            b = document.createElement("b");
                            b.id = "b9_"+ results[i].getId();
//                            b.onmouseover = onPoiMouseover;
//                            b.onmouseout = onPoiMouseout;
                            
                            if(NameList[3] == 'FA')
                            {
                                //alert ("FA");
                                if(NameList[2].length > 0)
                                {
                                    //alert (NameList[2].length);
                                    a.href = MLGlobalVar_FAPageUrl + NameList[2] + "&locator=2C8C74AC-04AB-4D14-95D4-50E05906016C";
                                    a.target = "_top";                                    
                                    a.appendChild(document.createTextNode(NameList[1]));
                                }
                                else
                                {
                                    //alert ("NameList is empty");
                                    a.href = MLGlobalVar_BranchPageUrl + results[i].getBranchId() + "&locator=2C8C74AC-04AB-4D14-95D4-50E05906016C";
                                    a.target = "_top";
                                    a.appendChild(document.createTextNode(NameList[1]));					                            
                                }
                            }
                            else if(NameList[3] == 'BRANCH')
                            {
                                //alert ("BRANCH");
                                a.href = MLGlobalVar_BranchPageUrl + results[i].getBranchId() + "&locator=2C8C74AC-04AB-4D14-95D4-50E05906016C";
                                a.target = "_top";
                                a.appendChild(document.createTextNode(NameList[1]));					                            
                            }                        
                            
                            
                            b.appendChild(a);
                                                                            
                            td.appendChild(b);
                            //tr.appendChild(td);

                            //Build an empty placeholder
                            td = tr.insertCell(cellItt++);
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            td.id = "td3_" + results[i].getId();

                            //Build an empty placeholder
                            td = tr.insertCell(cellItt++);
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            td.id = "tdx_" + results[i].getId();
        			                        
        			                        
                            //Build an empty placeholder
                            td = tr.insertCell(cellItt++);
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            td.id = "tdy_" + results[i].getId();
        			                        
                            //a = document.createElement("a");
                            //a.id = "a1_"+ results[i].getId();
                			
                            td.appendChild(document.createTextNode(" "));
                            //td.appendChild(a);
                                			

                            //tbl.appendChild(tr);

                            //Build an empty placeholder
                            tr = tbl.insertRow(rowItt++);
                            cellItt = 0;
                            tr.id = "tr2_" + results[i].getId();
                            tr.className = "resultstablerow" + rowNum;

                            td = tr.insertCell(cellItt++);
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            //td.onclick = onPoiClick;
                            td.onclick = CheckSrcItemForOnclick;
                            td.id = "td6_" + results[i].getId();		

                            td.appendChild(document.createTextNode(results[i].getStreet()));
                            
                            td.appendChild(document.createElement("br"));                        
                            	
                            td.appendChild(document.createTextNode(results[i].getCityStatePostalCodeString()));
                            
                            td.appendChild(document.createElement("br"));
                            
                            if(document.location.search.indexOf('FA')!=-1)
                            {
                                var phoneNo = document.createTextNode(results[i].getPhone());
                                phoneNo.data = "Office Number: " + phoneNo.data;
                                td.appendChild(phoneNo);                                
                            }
                            else
                            {                            
                                td.appendChild(document.createTextNode(results[i].getPhone()));
                            }
 
                            //Build links to display detail information
                            td = tr.insertCell(cellItt++);
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            td.id = "td4_" + results[i].getId();
                            			
                            if(isPoiSearch){
                                //isPoiSearch is true - hide the details link
                                //td.onclick = onPoiClick;
                                td.onclick = CheckSrcItemForOnclick;
                                td.appendChild(document.createTextNode(" "));
                            }
                            else {
                                //isPoiSearch is false - displaying Branch Information - link displays Hotel Details
//                                a = document.createElement("a");
//                                a.onmouseover = onPoiMouseover;
//                                a.onmouseout = onPoiMouseout;
//                                a.id = "a2_"+ results[i].getId();
//                                //a.href = "details.htm?pid=" + results[i].getId();
//                                
//                                if(NameList[3] == 'FA')
//                                {
//                                    if(NameList[2].length > 0)
//                                    {
//                                        a.href = MLGlobalVar_FAPageUrl + NameList[2];
//                                        a.target = "_top";
//                                        a.appendChild(document.createTextNode("View Web Site"));
//                                    }
//                                    else
//                                    {
//                                        a.href = MLGlobalVar_BranchPageUrl + results[i].getBranchId();
//                                        a.target = "_top";
//                                        a.appendChild(document.createTextNode("View Web Site"));					                            
//                                    }
//                                }
//                                else if(NameList[3] == 'BRANCH')
//                                {
//                                    a.href = MLGlobalVar_BranchPageUrl + results[i].getBranchId();
//                                    a.target = "_top";
//                                    a.appendChild(document.createTextNode("View Web Site"));				                        
//                                }
//                                
//                                b = document.createElement("b");
//                                b.id = "b8_"+ results[i].getId();
//                                b.onmouseover = onPoiMouseover;
//                                b.onmouseout = onPoiMouseout;
//                                
//                                b.appendChild(a);
//                                                            
//                                td.appendChild(b);
                            }
                            //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.target = "_top";
//                            a.appendChild(document.createTextNode("Map/Directions"));
//                            b = document.createElement("b");
//                            b.id = "b7_"+ results[i].getId();
//                            b.onmouseover = onPoiMouseover;
//                            b.onmouseout = onPoiMouseout;
//                            
//                            b.appendChild(a);
//                                                        
//                            td.appendChild(b);
                            //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.onclick = CheckSrcItemForOnclick;
                                td.rowSpan = 1;
                                td.id = "td5_" + results[i].getId();
                                spacer = false;
                                //if using center of US as radius do not display distance
                                if (orgLatitude != CENTER_OF_THE_US_LATITUDE && orgLongitude != CENTER_OF_THE_US_LONGITUDE){
                                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);
                                }
                            }          
                                //tbl.appendChild(tr);					                        
                        }
                        
                        if(rowNum == '1')
                            rowNum = '2';
                        else
                            rowNum = '1';
                    }	
 
				}
					
			}
			
                   else
                    {
                        //we're doing just the branches.
                        //alert('in');
			                //Populate the Map with the Results
                            //alert ("PostalCode=" + orgTxtZip + " for frm" + i);
			                icon = new MQMapIcon();
			                //alert("POISearch=" + isPoiSearch + "DisplayType: " + results[1].getField("T") + " " + results[2].getField("T"));
			                //If isPoiSearch is true, then use the corresponding poi icon based on the DT Style - displaying Points of Interest
			                if(isPoiSearch){
				                imgSrc = MLGlobalVar_GlobalImagePath + results[i].getField("T") + ".gif";
				                icon.setImage(imgSrc, 20, 20, true, false);
			                }
			                else {
			                //Otherwise, use the numbered icons to display results - displaying Branch Information
				                imgSrc = MLGlobalVar_GlobalImagePath + (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(false);
			                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 = "resultstablerow" + rowNum;
			                tr.id = "tr1_" + results[i].getId();
			                //alert(results[i].getId());

			                frm = results[i].getResultForm(i);
                			
			                //Build hidden fields for original address
			                //hndInput = createInputElement("hidden", "hdnAddress", origGeoAddress.getStreet());
	                        //frm.appendChild(hndInput);
	                        hndInput = createInputElement("hidden", "branchCode", results[i].getBranchId());
	                        frm.appendChild(hndInput);	  
	                        hndInput = createInputElement("hidden", "branchName", results[i].getName());
	                        frm.appendChild(hndInput);	                        
	                        hndInput = createInputElement("hidden", "hdnCity", origGeoAddress.getCity());
	                        frm.appendChild(hndInput);
	                        hndInput = createInputElement("hidden", "hdnStateProvince", origGeoAddress.getState());
	                        frm.appendChild(hndInput);
	                        hndInput = createInputElement("hidden", "hdnPostalCode", origGeoAddress.getPostalCode());
	                        frm.appendChild(hndInput);
	                        if(origGeoAddress.getMQLatLng()){
		                        hndInput = createInputElement("hidden", "orgLatitude", origGeoAddress.getMQLatLng().getLatitude());
		                        frm.appendChild(hndInput);

		                        hndInput = createInputElement("hidden", "orgLongitude", origGeoAddress.getMQLatLng().getLongitude());
		                        frm.appendChild(hndInput);
	                        }	        
			                tr.appendChild(frm);
                			
			                //alert(results[i].getBranchId());

                            td = tr.insertCell(cellItt++);
                            td.rowSpan = 2;
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            //td.onclick = onPoiClick;
                            td.onclick = CheckSrcItemForOnclick;                            
                            td.id = "td1_" + results[i].getId();

                            img = document.createElement("img");
                            img.src = imgSrc
                            img.id = "img_"+ results[i].getId();
                            td.appendChild(img);
                            //tr.appendChild(td);
                			

                            td = tr.insertCell(cellItt++);
                            td.id = "td2_" + results[i].getId();
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            //td.onclick = onPoiClick;
                            td.onclick = CheckSrcItemForOnclick; //CheckSrcItemForOnclick();";
                            

                            a = document.createElement("a");
//                            a.onmouseover = onPoiMouseover;
//                            a.onmouseout = onPoiMouseout;
                            a.id = "a9_"+ results[i].getId();
                            
                            b = document.createElement("b");
                            b.id = "b9_"+ results[i].getId();
//                            b.onmouseover = onPoiMouseover;
//                            b.onmouseout = onPoiMouseout;

    
                            
                            a.href = MLGlobalVar_BranchPageUrl + results[i].getBranchId() + "&locator=2C8C74AC-04AB-4D14-95D4-50E05906016C";
                            //a.onclick = "javascript:handleHrefClick('Navigating to the Branch page: " + results[i].getName() + "');";
                            a.target = "_top";
                            a.appendChild(document.createTextNode(results[i].getName()));					                            
                      
                            // Added for opening the results in new window for MapQuest Branch FA Only Page
                            if(parent.location.search.indexOf('fabrcriteria') > 0)
                            {
                               a.target = "_blank";                               
                            }
                            // Code Ends here
                            
                            b.appendChild(a);
                                                                            
                            td.appendChild(b);
                            //tr.appendChild(td);

                            //Build an empty placeholder
                            td = tr.insertCell(cellItt++);
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            td.id = "td3_" + results[i].getId();

                            //Build an empty placeholder
                            td = tr.insertCell(cellItt++);
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            td.id = "tdx_" + results[i].getId();
        			                        
        			                        
                            //Build an empty placeholder
                            td = tr.insertCell(cellItt++);
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            td.id = "tdy_" + results[i].getId();
        			                        
                            //a = document.createElement("a");
                            //a.id = "a1_"+ results[i].getId();
                			
                            td.appendChild(document.createTextNode(" "));
                            //td.appendChild(a);
                                			

                            //tbl.appendChild(tr);

                            //Build an empty placeholder
                            tr = tbl.insertRow(rowItt++);
                            cellItt = 0;
                            tr.id = "tr2_" + results[i].getId();
                            tr.className = "resultstablerow" + rowNum;

                            td = tr.insertCell(cellItt++);
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            //td.onclick = onPoiClick;
                            td.onclick = CheckSrcItemForOnclick;
                            td.id = "td6_" + results[i].getId();		

                            td.appendChild(document.createTextNode(results[i].getStreet()));
                            
                            td.appendChild(document.createElement("br"));                        
                            	
                            td.appendChild(document.createTextNode(results[i].getCityStatePostalCodeString()));
                            
                            td.appendChild(document.createElement("br"));
                            
                            td.appendChild(document.createTextNode(results[i].getPhone()));
 
                            //Build links to display detail information
                            td = tr.insertCell(cellItt++);
//                            td.onmouseover = onPoiMouseover;
//                            td.onmouseout = onPoiMouseout;
                            td.id = "td4_" + results[i].getId();
                            			
                            if(isPoiSearch){
                                //isPoiSearch is true - hide the details link
                                //td.onclick = onPoiClick;                                
                                td.onclick = CheckSrcItemForOnclick;
                                td.appendChild(document.createTextNode(" "));
                            }
                            else {
                                //isPoiSearch is false - displaying Branch Information - link displays Hotel Details
//                                a = document.createElement("a");
//                                a.onmouseover = onPoiMouseover;
//                                a.onmouseout = onPoiMouseout;
//                                a.id = "a2_"+ results[i].getId();
//                                //a.href = "details.htm?pid=" + results[i].getId();
//                                

//                                a.href = MLGlobalVar_BranchPageUrl + results[i].getBranchId();
//                                a.target = "_top";
//                                a.appendChild(document.createTextNode("View Web Site"));				                        

//                                
//                                b = document.createElement("b");
//                                b.id = "b8_"+ results[i].getId();
//                                b.onmouseover = onPoiMouseover;
//                                b.onmouseout = onPoiMouseout;
//                                
//                                b.appendChild(a);
//                                                            
//                                td.appendChild(b);
                            }
                            //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("Map/Directions"));
//                            b = document.createElement("b");
//                            b.id = "b7_"+ results[i].getId();
//                            b.onmouseover = onPoiMouseover;
//                            b.onmouseout = onPoiMouseout;
//                            
//                            b.appendChild(a);
//                                                        
//                            td.appendChild(b);
                            //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.onclick = CheckSrcItemForOnclick;
                                td.rowSpan = 1;
                                td.id = "td5_" + results[i].getId();
                                spacer = false;
                                //if using center of US as radius do not display distance
                                if (orgLatitude != CENTER_OF_THE_US_LATITUDE && orgLongitude != CENTER_OF_THE_US_LONGITUDE){
                                    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);
                                    }
                                }
                                //tbl.appendChild(tr);					                        
                        }
                        
                        if(rowNum == '1')
                            rowNum = '2';
                        else
                            rowNum = '1';                        
                        //end doing just the branches.
                    }         					
		}

		//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.className = "paged";
			td.colSpan = 5;

			if(currentPage > 0 ){
				a = document.createElement("a");
				a.href = "javascript:changePage(0);"
				a.appendChild(document.createTextNode("<<<"));
				td.appendChild(a);

                sp_blank = document.createTextNode(' ');
			    td.appendChild(sp_blank);
			    
				a = document.createElement("a");
				a.href = "javascript:changePage(" + (currentPage -1) + ");"
				a.appendChild(document.createTextNode("<"));
				td.appendChild(a);
			}

            sp_blank = document.createTextNode(' ');
			td.appendChild(sp_blank);
			
			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);
				}
				sp_blank = document.createTextNode(' ');
			    td.appendChild(sp_blank);
			}

            sp_blank = document.createTextNode(' ');
			td.appendChild(sp_blank);
			
			if(currentPage < pages - 1 ){
				a = document.createElement("a");
				a.href = "javascript:changePage(" + (currentPage + 1) + ");"
				a.appendChild(document.createTextNode(">"));
				td.appendChild(a);
            
                sp_blank = document.createTextNode(' ');
			    td.appendChild(sp_blank);
			    
				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 Results Found..  Please refine your search criteria and try again."));
		td.appendChild(b);
		mqfrm.contentWindow.ShowMsgDiv("<p class=\"error\">No Results Found.  Please refine your search criteria and try again.</p>")
		showErrMsg = true;	
	}
	
	if(resultCount == 0 && searchType == 'FA')
	{
	    if(results.length > 0)
	    {
		    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 Results Found..  Please refine your search criteria and try again."));
		    td.appendChild(b);
		    mqfrm.contentWindow.ShowMsgDiv("<p class=\"error\">No Results Found.  Please refine your search criteria and try again.</p>")
		    showErrMsg = true;		    
        }
	}

	//Append the results to the page
	var _parent = document.getElementById("divResults");
	//if(!browserCheck.ie){
		removeAllChildren(_parent);
		_parent.appendChild(tbl);
		
		//var qs = new Querystring();		
		//var searchType = '';
		
		if(!showErrMsg)
		{       
		    mqfrm.contentWindow.ShowMsgDiv('');
		}
		
	/*}
	else {
		//alert(tbl.outerHTML);
		parent.innerHTML = tbl.outerHTML;
	}*/

	//Best fit the results on the map
	//alert ("results size= " + results.length + "results count=" + resultCount);
	if(results.length > 0)
	{	    
	    if(resultCount == 0 && searchType == 'FA')
	    {
	        var _parent = document.getElementById("divContent");
	        removeAllChildren(_parent);
	  }
	    else
	    {
	        map.bestFit(false,1,11);    
	    }
	}
	else
	{
	   var _parent = document.getElementById("divContent");
	   removeAllChildren(_parent);	   
	}
// Code Added for Opera Issue on alignment 
// Date:14/05/2008
// Manish Bhoir
	if(mqBrowserInfo.isOpera)
	{	   
	    document.getElementById('divResults').innerHTML = document.getElementById('divResults').innerHTML;
	    for(i=0;i<document.getElementById('divResults').getElementsByTagName('td').length;i++)
	    {
	     document.getElementById('divResults').getElementsByTagName('td')[i].style.color="#666666";
	     document.getElementById('divResults').getElementsByTagName('td')[i].style.fontSize="8.85pt";
	    }
	    for(i=0;i<document.getElementById('divResults').getElementsByTagName('a').length;i++)
	    {
	       document.getElementById('divResults').getElementsByTagName('a')[i].style.fontSize="8.85pt";	      
	    }
	    for(i=0;i<document.getElementById('divResults').getElementsByTagName('b').length;i++)
	    {
	     document.getElementById('divResults').getElementsByTagName('b')[i].style.color="#666666";
	     document.getElementById('divResults').getElementsByTagName('b')[i].style.fontSize="8.85pt";
	    }
	    
	    document.getElementById('divResults').style.color="#666666";
	    document.getElementById('divResults').style.backgroundColor="#F8F8F8";
	}	    
// Opera Code Ends Here
}

/*
* 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;
	}
}

