﻿var map;
var restIcon;
var motelIcon;
var niteIcon;
var hosIcon;
var autoIcon;
var blackIcon;
var shopIcon;
var historicalIcon;
var tourIcon;
var currentCenter;
var theTimeout = null;
var nearbyResults = new NearbyResults();

function loadHomePageMap(lat, lng, zoom, inlat, inlng, inBusinessName, inAddress, inCity, inStateCode, inZip, inPhone, inWebAddress, inImageMarker, inMoreInfo) {	
	var map = new GMap2(document.getElementById("HomePageMap"));        
        map.setCenter(new GLatLng(lat,lng), zoom); 
        map.addControl(new GLargeMapControl());  
        map.addControl(new GMapTypeControl());       
	if (GBrowserIsCompatible()) {
	    var point; 
        var bn = inBusinessName.split(',');
        var a = inAddress.split(',');
        var c = inCity.split(',');
        var sc = inStateCode.split(',');        
        var p = inPhone.split(',');
        var z = inZip.split(',');
        var wa = inWebAddress.split(',');        
        var myl = inlat.split(',');
        var mylo = inlng.split(',');         
        var icon = inImageMarker.split(','); 
         var info = inMoreInfo.split(','); 
        var x;      
        
        for (x in bn)
        {  
            point = new GLatLng(myl[x], mylo[x]);
            map.addOverlay(createMarker2(point, bn[x], a[x], c[x], sc[x], z[x], p[x], wa[x], icon[x], info[x]));  
        }  
		
          
      }
}

function populateData() {
	nearbyResults.SetTitle('Nearby Results');
	nearbyResults.SetLatitude(currentCenter.lat());
	nearbyResults.SetLongitude(currentCenter.lng());
	nearbyResults.Execute();
}

function updateView(doReget) {
	nearbyResults.ClearMain(true);
	if(doReget) {
		nearbyResults.ClearMain(false);
		populateData();
	} else {
		nearbyResults.RenderMain();
	}
}



function NearbyResults() {
    var ajaxFeed = null;
	var ajaxTitle = 'Unknown';
	var ajaxLatitude = 0;
	var ajaxLongitude = 0;
	var ajaxMainItems = [];
	var ajaxItemData = [];
	function doClean() {
		ajaxFeed = null;
		ajaxTitle = null;
		ajaxLatitude = null;
		ajaxLongitude = null;
		ajaxMethod = null;
		ajaxMainItems = null;
		ajaxItemData = null;
	}
	this.Clean = doClean;
	function createBreaker() {
		return(document.createElement('br'));
	}
	function createBoldAndCentered(inText) {
		var CenterItem = document.createElement('center');
		CenterItem.appendChild(createBold(inText));
		return(CenterItem);
	}
	function createBold(inText) {
		var BoldItem = document.createElement('b');
		BoldItem.innerHTML = inText;
		return(BoldItem);
	}
	function processReqChange() {
		if (ajaxFeed.readyState == 4) {
			if (ajaxFeed.status == 200)
				handleFoundData();
			else {
				//handleError('ajaxError', ajaxTitle + ': Error, ' + ajaxFeed.statusText);
			}
		}
	}
	function createDiv(text, ID) {
		var newDiv = document.createElement('div');
		newDiv.setAttribute('id', ID);
		newDiv.innerHTML = text;
		return(newDiv);
	}
	function createMarker(inLat, inLng, inBN, inFA, inC, inS, inZ, inWA, inP, inR, inFBN, inMarker) {
		var BusinessMarker = new GMarker(new GLatLng(inLat, inLng), inMarker);
		GEvent.addListener(BusinessMarker, "click",
			function() {
				var BusinessName = new String("<div style=\"font-weight: bold;\">" + inBN + "</div>");
				var Address = new String("<div>" + inFA + "<br />" + inC + ", " + inS + " " + inZ + "</div>");
				var Phone = new String("<div>" + inP + "</div>");
				var WebAddress = new String("");
				var GoodWebAddress = true;
				for(var iCnt = 0; iCnt < inWA.length; iCnt++) {
					if(inWA.substr(iCnt, 1) == " ")
						GoodWebAddress = false;
				}
				if(GoodWebAddress)
					WebAddress = WebAddress.concat("<div><a href=\"http://" + inWA + "\">", inWA, "</a></div>");
				BusinessMarker.openInfoWindowHtml(BusinessName.concat(Address, Phone, WebAddress, "<div><a href=\"http://www.thinklocal.com/" + inFBN + "-" + inR + ".html\">more info</a></div>"));
			}
		); 
		return(BusinessMarker);
	}
	function handleFoundData() {
		//handleError('ajaxError', '');
		for(var iCnt = 0; iCnt < ajaxItemData.length; iCnt++) {
			ajaxItemData[iCnt] = null;
		}
		ajaxItemData.length = 0;
		try {
			var incomingXml = ajaxFeed.responseXML;
			ajaxFeed = null;
			for(var iRootNode = 0; iRootNode < incomingXml.childNodes.length; iRootNode++) {
				switch(incomingXml.childNodes[iRootNode].nodeName) {
					case('Error'):
						//handleError('ajaxError', ajaxTitle + ': ' + getTextValue(incomingXml.childNodes[iRootNode]));
						break;
					case('NearbyListings'):
						var NearbyListingsCollection = incomingXml.childNodes[iRootNode];
						for(var iNearbyListingsItem = 0; iNearbyListingsItem < NearbyListingsCollection.childNodes.length; iNearbyListingsItem++) {
							switch(NearbyListingsCollection.childNodes[iNearbyListingsItem].nodeName) {
								case('Table'):
									var TableCollection = NearbyListingsCollection.childNodes[iNearbyListingsItem];
									var Latitude = 0;
									var Longitude = 0;
									var BDC = 0;
									var businessItem = new BusinessItem();
									for(var iTitleItem = 0; iTitleItem < TableCollection.childNodes.length; iTitleItem++) {
										switch(TableCollection.childNodes[iTitleItem].nodeName) {
											case('BDC'):
												BDC = parseInt(getTextValue(TableCollection.childNodes[iTitleItem]));
												break;
											case('businessName'):
												businessItem.SetBusinessName(getTextValue(TableCollection.childNodes[iTitleItem]));
												break;
											case('fullAddress'):
												businessItem.SetFullAddress(getTextValue(TableCollection.childNodes[iTitleItem]));
												break;
											case('cityName'):
												businessItem.SetCity(getTextValue(TableCollection.childNodes[iTitleItem]));
												break;
											case('StateCode'):
												businessItem.SetState(getTextValue(TableCollection.childNodes[iTitleItem]));
												break;
											case('ZIP'):
												businessItem.SetZip(getTextValue(TableCollection.childNodes[iTitleItem]));
												break;
											case('FormattedPhone'):
												businessItem.SetPhone(getTextValue(TableCollection.childNodes[iTitleItem]));
												break;
											case('webAddress'):
												businessItem.SetWebAddress(getTextValue(TableCollection.childNodes[iTitleItem]));
												break;
											case('RecordID'):
												businessItem.SetRecordID(parseInt(getTextValue(TableCollection.childNodes[iTitleItem])));
												break;
											case('URLName'):
												businessItem.SetURLName(getTextValue(TableCollection.childNodes[iTitleItem]));
												break;
											case('latitude'):
												try {
													Latitude = parseFloat(getTextValue(TableCollection.childNodes[iTitleItem]));
												}
												catch(ex) {
													Latitude = 0;
												}
												break;
											case('longitude'):
												try {
													Longitude = parseFloat(getTextValue(TableCollection.childNodes[iTitleItem]));
												}
												catch(ex) {
													Longitude = 0;
												}
												break;
										}
									}
									ajaxItemData.push(businessItem);
									var theIcon = null;
									switch(BDC) {
										case(1602):
											theIcon = greenIcon;
											break;
										case(1603):
											theIcon = blueIcon;
											break;
										case(270104):
											theIcon = redIcon;
											break;
										case(2102):
											theIcon = blackIcon;
											break;
										case(2703):
											theIcon = grayIcon;
											break;
										case(2705):
											theIcon = orangeIcon;
											break;
										default:
											theIcon = purpleIcon;
											break;
									}
									ajaxMainItems.push(createMarker(Latitude, Longitude, businessItem.GetBusinessName(), businessItem.GetFullAddress(), businessItem.GetCity(), businessItem.GetState(), businessItem.GetZip(), businessItem.GetWebAddress(), businessItem.GetPhone(), businessItem.GetRecordID(), businessItem.GetURLName(), theIcon));
									break;
								default:
									break;
							}
						}
						break;
					default:
						break;
				}
			}
		}
		catch(ex) {
			//handleError('ajaxError', ajaxTitle + ': ' + ex);
		}
		//printMain();
		//printData();
		map.clearOverlays();
	}
	this.RenderMain = printMain;
	this.RenderAll = printAll;
	this.RenderData = printData;
	this.ClearMain = eraseMain;
	this.ClearAll = eraseAll;
	this.ClearData = eraseData;
	function eraseAll() {
		eraseMain();
		eraseData();
	}
	function eraseMain(justRemove) {
		for(var iCnt = 0; iCnt < ajaxMainItems.length; iCnt++) {
			map.removeOverlay(ajaxMainItems[iCnt]);
			if(!justRemove)
				ajaxMainItems[iCnt] = null;
		}
		if(!justRemove)
			ajaxMainItems.length = 0;
	}
	function eraseData() {
		var BusinessListings = document.getElementById('businessListings');
		while (BusinessListings.firstChild) {
			BusinessListings.removeChild(BusinessListings.firstChild);
		}
	}
	function printAll() {
		printMain();
		printData();
	}
	function printMain() {
		for(var iCnt = 0; iCnt < ajaxMainItems.length; iCnt++) {
			map.addOverlay(ajaxMainItems[iCnt]);
		}
	}
	function printData() {
		var BLT = document.getElementById('businessListings');
		while (BLT.firstChild) {
			BLT.removeChild(BLT.firstChild);
		}
		var newTbody = document.createElement('tbody');
		var newTr = document.createElement('tr');
		var iMax = 1;
		for(var iCnt = 0; iCnt < ajaxItemData.length; iCnt++) {
			if(iMax <= 5) {
				var theTd = document.createElement('td');
				var businessItem = ajaxItemData[iCnt];
				theTd.appendChild(createDiv(businessItem.GetBusinessName(), 'blbn' + iMax.toString()));
				theTd.appendChild(createDiv(businessItem.GetFullAddress(), 'blfa' + iMax.toString()));
				theTd.appendChild(createDiv(businessItem.GetCity() + ', ' + businessItem.GetState() + ' ' + businessItem.GetZip(), 'blcsz' + iMax.toString()));
				theTd.appendChild(createDiv(businessItem.GetPhone(), 'blp' + iMax.toString()));
				newTr.appendChild(theTd);
				iMax += 1;
			}
		}
		newTbody.appendChild(newTr);
		document.getElementById('businessListings').appendChild(newTbody);
		for(var iCnt = 1; iCnt <= iMax; iCnt++) {
			try {
			document.getElementById('blbn' + iCnt.toString()).style.fontWeight = 'bold';
			}
			catch(ex) { }
		}
	}
	function performExecute() {
		if(!ajaxFeed) {
			ajaxFeed = GetNativeXMLHttpRequest();
			ajaxFeed.onreadystatechange = processReqChange;
		}
		else
			ajaxFeed.abort();
		if(ajaxFeed) {
			var URL = "NearbyResults.html?n=6&lat=" + ajaxLatitude + "&lng=" + ajaxLongitude + "&Random=" + Math.random().toString();
			ajaxFeed.open("GET", URL, doAsync);
			ajaxFeed.send(null);
		}
		else {
			//handleError('ajaxError', ajaxTitle + ': Unable to create Ajax client.');
		}
	}
	function set_Latitude(value) {
		ajaxLatitude = value;
	}
	function set_Longitude(value) {
		ajaxLongitude = value;
	}
	function set_Ajax(value) {
		ajaxFeed = value;
	}
	function set_Title(value) {
		ajaxTitle = value;
	}
	function get_Latitude() {
		return(ajaxLatitude);
	}
	function get_Longitude() {
		return(ajaxLongitude);
	}
	function get_Ajax() {
		return(ajaxFeed);
	}
	function get_Title() {
		return(ajaxTitle);
	}

	this.Execute = performExecute;

	this.SetLatitude = set_Latitude;
	this.SetLongitude = set_Longitude;
	this.SetAjax = set_Ajax;
	this.SetTitle = set_Title;

	this.GetLatitude = get_Latitude;
	this.GetLongitude = get_Longitude;
	this.GetAjax = get_Ajax;
	this.GetTitle = get_Title;

	this.Process = processReqChange;
}
function BusinessItem() {
	var itemBusinessName = '';
	var itemFullAddress = '';
	var itemCity = '';
	var itemState = '';
	var itemZip = '';
	var itemPhone = '';
	var itemWebAddress = '';
	var itemRecordID = 0;
	var itemURLName = '';
	function set_BusinessName(value) {
		itemBusinessName = value;
	}
	function set_FullAddress(value) {
		itemFullAddress = value;
	}
	function set_City(value) {
		itemCity = value;
	}
	function set_State(value) {
		itemState = value;
	}
	function set_Zip(value) {
		itemZip = value;
	}
	function set_Phone(value) {
		itemPhone = value;
	}
	function set_WebAddress(value) {
		itemWebAddress = value;
	}
	function set_RecordID(value) {
		itemRecordID = value;
	}
	function set_URLName(value) {
		itemURLName = value;
	}
	function get_BusinessName() {
		return(itemBusinessName);
	}
	function get_FullAddress() {
		return(itemFullAddress);
	}
	function get_City() {
		return(itemCity);
	}
	function get_State() {
		return(itemState);
	}
	function get_Zip() {
		return(itemZip);
	}
	function get_Phone() {
		return(itemPhone);
	}
	function get_WebAddress() {
		return(itemWebAddress);
	}
	function get_RecordID() {
		return(itemRecordID);
	}
	function get_URLName() {
		return(itemURLName);
	}
	this.SetBusinessName = set_BusinessName;
	this.SetFullAddress = set_FullAddress;
	this.SetCity = set_City;
	this.SetState = set_State;
	this.SetZip = set_Zip;
	this.SetPhone = set_Phone;
	this.SetWebAddress = set_WebAddress;
	this.SetRecordID = set_RecordID;
	this.SetURLName = set_URLName;
	
	this.GetBusinessName = get_BusinessName;
	this.GetFullAddress = get_FullAddress;
	this.GetCity = get_City;
	this.GetState = get_State;
	this.GetZip = get_Zip;
	this.GetPhone = get_Phone;
	this.GetWebAddress = get_WebAddress;
	this.GetRecordID = get_RecordID;
	this.GetURLName = get_URLName;
}






    var map;
    var gdir;
    var geocoder = null;
    var addressMarker;

    function initialize(toAddress, fromAddress, locale) {
      if (GBrowserIsCompatible()) {      
        map = new GMap2(document.getElementById("map_canvas"));
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        setDirections(fromAddress, toAddress, locale);
      }
    }
   
    function setDirections(fromAddress, toAddress, locale) {
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
    }

    function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	      alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	      alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	      alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	      alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");
	    
	   else  alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.");
	   
	}

	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}
    


function loadSearchPageMap(lat, lng, zoom, inlat, inlng, inBusinessName, inAddress, inCity, inStateCode, inZip, inPhone, inWebAddress, inMoreInfo) {	
	if (GBrowserIsCompatible()) { 
	var map = new GMap2(document.getElementById("SearchPageMap"));
        
        map.addControl(new GSmallMapControl());  
        
        var point; 
        var bn = inBusinessName.split(',');
        var a = inAddress.split(',');
        var c = inCity.split(',');
        var sc = inStateCode.split(',');        
        var p = inPhone.split(',');
        var z = inZip.split(',');
        var wa = inWebAddress.split(',');        
        var myl = inlat.split(',');
        var mylo = inlng.split(',');
        map.setCenter(new GLatLng(myl[0],mylo[0]), zoom);  
        var icon = new Array("/imgs/New/mkr_1.png", "/imgs/New/mkr_2.png", "/imgs/New/mkr_3.png", "/imgs/New/mkr_4.png", "/imgs/New/mkr_5.png", "/imgs/New/mkr_6.png", "/imgs/New/mkr_7.png", "/imgs/New/mkr_8.png", "/imgs/New/mkr_9.png", "/imgs/New/mkr_10.png"); 
        var info = inMoreInfo.split(',');
        var x;
        for (x in bn)
        {  
            point = new GLatLng(myl[x], mylo[x]);
            map.addOverlay(createMarker2(point, bn[x], a[x], c[x], sc[x], z[x], p[x], wa[x], icon[x], info[x]));  
        }        
     }
}

function loadBPPageMap(inlat, inlng, zoom, inBusinessName, inAddress, inCity, inStateCode, inZip, inPhone, inWebAddress) {	
	if (GBrowserIsCompatible()) { 
	var map = new GMap2(document.getElementById("BPPageMap"));
        map.setCenter(new GLatLng(inlat,inlng), zoom);  
        map.addControl(new GLargeMapControl()); 
        map.addControl(new GMapTypeControl()); 
        var point; 
        var bn = new Array(inBusinessName);
        var a = new Array(inAddress);
        var c = new Array(inCity);
        var sc = new Array(inStateCode);        
        var p = new Array(inPhone);
        var z = new Array(inZip);
        var wa = new Array(inWebAddress);
        inlat = inlat+''
        inlng = inlng+''
        var myl = new Array(inlat);
        var mylo = new Array(inlng);
        var icon = new Array("/imgs/New/mkr_1.png", "/imgs/New/mkr_2.png", "/imgs/New/mkr_3.png", "/imgs/New/mkr_4.png", "/imgs/New/mkr_5.png", "/imgs/New/mkr_6.png", "/imgs/New/mkr_7.png", "/imgs/New/mkr_8.png", "/imgs/New/mkr_9.png", "/imgs/New/mkr_10.png"); 
        var x;
        for (x in bn)
        {        
         point = new GLatLng(myl[x], mylo[x]);
         map.addOverlay(createMarker(point, bn[x], a[x], c[x], sc[x], z[x], p[x], wa[x], icon[x]));  
        }
               
     }
}

function createMarker(point, inBusinessName, inAddress, inCity, inStateCode, inZip, inPhone, inWebAddress, inIcon) {
          // Create a lettered icon for this point using our icon class  
          var baseIcon = new GIcon();        
        baseIcon.iconSize = new GSize(22, 22); 
        baseIcon.shadowSize = new GSize(24, 22);       
        baseIcon.iconAnchor = new GPoint(22, 22);
                
        baseIcon.infoWindowAnchor = new GPoint(5, 1);               
          var letteredIcon = new GIcon(baseIcon);
          letteredIcon.image = inIcon;

          // Set up our GMarkerOptions object   
          markerOptions = { icon:letteredIcon };      
          var marker = new GMarker(point,  markerOptions);

          GEvent.addListener(marker, "click", function() {
				var BusinessName = new String("<div style=\"font-weight: bold;\">" + inBusinessName + "</div>");
				var Address = new String("<div>" + inAddress + "<br />" +inCity + ", " + inStateCode + " " + inZip + "</div>");
				var Phone = new String("<div>" + inPhone + "</div>");
				var WebAddress = new String("");
				var GoodWebAddress = true;
				for(var iCnt = 0; iCnt < inWebAddress.length; iCnt++) {
					if(inWebAddress.substr(iCnt, 1) == " ")
						GoodWebAddress = false;
				}
				if(GoodWebAddress)
				WebAddress = WebAddress.concat("<div><a href=\"http://" + inWebAddress + "\">", inWebAddress, "</a></div>");
				marker.openInfoWindowHtml(BusinessName.concat(Address, Phone, WebAddress));
			});
          return marker;
          }
          
          function createMarker2(point, inBusinessName, inAddress, inCity, inStateCode, inZip, inPhone, inWebAddress, inIcon, inMoreInfo) {
          // Create a lettered icon for this point using our icon class  
          var baseIcon = new GIcon();        
        baseIcon.iconSize = new GSize(22, 22); 
        baseIcon.shadowSize = new GSize(24, 22);       
        baseIcon.iconAnchor = new GPoint(22, 22);
                
        baseIcon.infoWindowAnchor = new GPoint(5, 1);               
          var letteredIcon = new GIcon(baseIcon);
          letteredIcon.image = inIcon;

          // Set up our GMarkerOptions object   
          markerOptions = { icon:letteredIcon };      
          var marker = new GMarker(point,  markerOptions);

          GEvent.addListener(marker, "click", function() {
				var BusinessName = new String("<div style=\"font-weight: bold;\">" + inBusinessName + "</div>");
				var Address = new String("<div>" + inAddress + "<br />" +inCity + ", " + inStateCode + " " + inZip + "</div>");
				var Phone = new String("<div>" + inPhone + "</div>");
				var WebAddress = new String("");
				var GoodWebAddress = true;
				for(var iCnt = 0; iCnt < inWebAddress.length; iCnt++) {
					if(inWebAddress.substr(iCnt, 1) == " ")
						GoodWebAddress = false;
				}
				if(GoodWebAddress)
				WebAddress = WebAddress.concat("<div><a href=\"http://" + inWebAddress + "\">", inWebAddress, "</a></div>");
				var moreInfo = new String("<div>" + inMoreInfo + "</div>");
				marker.openInfoWindowHtml(BusinessName.concat(Address, Phone, WebAddress, moreInfo));
			});
          return marker;
          }