//<![CDATA[

//Declare variable and arrays
var imagepath = "images/brands/";

var IE = document.all ? true : false;
var map;
var detailmap;
var dirObj;
var container;
var clckTimeOut = null;
var loading = false;
var saveState = true;
var sliderMoving = false;
var directionsInfoDiv;
var customMapsInfo;
var iw;
var	mapMode;
var pLine;
var startMarker;
var endMarker;
var poiMarkers = new Array();
var pLinePoints;
var searchAreaHighlight;
var poiMarkers = Array();

//set info for base icon
var baseIcon = new GIcon();
baseIcon.iconSize=new GSize(25,25);
baseIcon.iconAnchor=new GPoint(8,8);
baseIcon.infoWindowAnchor=new GPoint(10,0);

//add images for collored icons
var yellowIcon = (new GIcon(baseIcon, "images/yellowSquare.png", null, ""));
var greenIcon = (new GIcon(baseIcon, "images/greenCircle.png", null, ""));
var redIcon = (new GIcon(baseIcon, "images/redCircle.png", null, ""));
var orangeIcon = (new GIcon(baseIcon, "images/orangeCircle.png", null, ""));
var blueIcon = (new GIcon(baseIcon, "images/blueCircle.png", null, ""));
var violetIcon = (new GIcon(baseIcon, "images/violetCircle.png", null, "")); 

//set info for larger icons
var baseIcon2 = new GIcon();
baseIcon2.iconSize=new GSize(25,25);
baseIcon2.iconAnchor=new GPoint(6,14);
baseIcon2.infoWindowAnchor=new GPoint(6,0);

var NormalLayer = G_NORMAL_MAP.getTileLayers()[0];
var SatelliteLayer = G_SATELLITE_MAP.getTileLayers()[0];
var satProj = G_SATELLITE_MAP.getProjection();
var normalProj = G_NORMAL_MAP.getProjection();


// Defaults --------------------------------------------
var zoom = 4;
var centerPoint = new GLatLng(40.000000,-99.316406);
var mType = 0;


var USstates = Array('Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','District of Columbia','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming')
var pattern = '(' + USstates.join('|') + ')';


function load() {
	if (GBrowserIsCompatible()) {
		container = document.getElementById("mapDiv");
		map = new GMap2(container, {draggableCursor:"hand"});

		directionsInfoDiv = document.getElementById("directions_info"); //get directions after start and destination have been submitted
		dirObj = new GDirections(map); //create GDirections object to request and store directions

		//set center and map type
		map.setCenter(centerPoint, zoom);
		map.setMapType(map.getMapTypes()[mType]);

		//add extras to the map display
		map.addControl(new GScaleControl());
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());

		//map navigation options
		//map.enableDoubleClickZoom(); 
		map.enableContinuousZoom();
		//map.enableScrollWheelZoom();


		//add listeners for common events
		GEvent.addListener(map, 'mousemove', mouseMove); //show mouse position in status box and update link
		GEvent.addListener(map, "moveend", moveEnd); //update link
		GEvent.addListener(map, "zoomend", zoomEnd); //update link and markzoomarea
		GEvent.addListener(map, "maptypechanged", mapTypeChenged); // update link
		GEvent.addListener(map, 'click', mapClick); //

		GEvent.addListener(dirObj, "load", onDirectionsLoad);
		GEvent.addListener(dirObj, "error", onDirectionsError);

		//reset center and page
		resizePage();
		//update "link to this page" link
		updateLink();

	}
}


function UnCheckAll(chk)
{
	for (i = 0; i < chk.length; i++)
	chk[i].checked = false ;
}

//show mouse position in mouseTrack box
function mouseMove(mousePt) {
	mouseLatLng = mousePt;
	var zoom = map.getZoom();
	var mousePx = normalProj.fromLatLngToPixel(mousePt, zoom);
}

function mapTypeChenged() {
	//updateLink();
}

function moveEnd() {
	//updateLink();
}

function zoomEnd(oldZ,zoom) {
	//updateLink();
	markSearchArea();
}


//Needs some work
function updateLink() {
	//get current map center
	var center = map.getCenter();
	//get current map zoom level
	var zoom = map.getZoom();
	//get current map types
	var mTypes = map.getMapTypes();
	//set maptypes in array
	for (var n = 0 ; n < mTypes.length ; n++ ) {
		if (mTypes[n] == map.getCurrentMapType()) {
			mType = n;
		}
	}

	//get current map bounds
	var bounds = map.getBounds();
	var SW = bounds.getSouthWest();
	var NE = bounds.getNorthEast();
	
}

///////////////////////////////////////////////////////////////////////////////////////////////////////


function mapClick(marker, point) {
	//if timeout is set
	if (clckTimeOut) {
		//clear timeout
		window.clearTimeout(clckTimeOut);
		//unset click timeout
		clckTimeOut = null;
		//call doubleClick (which does nothing)
		doubleClick(marker, point);
	}
	//if timeout is not set
	else {
		//set timeout to call singleClick after half a second
		clckTimeOut = window.setTimeout(function(){singleClick(marker, point)},500);
	}
}

function doubleClick(marker, point) {

}

function singleClick(marker, point) {
	//clear timeout
	window.clearTimeout(clckTimeOut);
	//unset timeout
	clckTimeOut = null;

	//if a point is passed and mapMode is directions
	if (point && (mapMode == 'directions')) {
		//if startMarker isn't set yet
		if (!startMarker) {
			//get driveFrom box object
			var oDriveFrom = document.getElementById('driveFrom');
			//set options for marker at start point
			startMarker = new GMarker(point,{icon:greenIcon,draggable:true,bouncy:false});
			//set endMarker's formField to driveFrom	 element
			startMarker.formField = oDriveFrom;
			//call markerDrag to startMarker is drug
			GEvent.addListener(startMarker,'drag',markerDrag);
			//add the startMarker to the map
			map.addOverlay(startMarker);
			//set oDriveFrom value to 6 digit lat and long of clickset startMarker
			oDriveFrom.value = startMarker.getPoint().lat().toFixed(6) + ',' + startMarker.getPoint().lng().toFixed(6);
			return;
		}
		//if endMarker isn't set yet
		else if (!endMarker) {
			//get driveTo box object
			var oDriveTo = document.getElementById('driveTo');
			//set options for marker at end point
			endMarker = new GMarker(point,{icon:redIcon,draggable:true,bouncy:false});
			//set endMarker's formField to driveTo element
			endMarker.formField = oDriveTo;
			//call markerDrag if endMarker is drug
			GEvent.addListener(endMarker,'drag',markerDrag);
			//add the endMarker to the map
			map.addOverlay(endMarker);
			//set oDriveTo value to 6 digit lat and long of clickset endpoint
			oDriveTo.value = endMarker.getPoint().lat().toFixed(6) + ',' + endMarker.getPoint().lng().toFixed(6);
			return;
		}
	
	}

}

function indicateLoading() {
	loading = true;
	displayLoadingMsg();
}

function displayLoadingMsg() {
	var oLMsg = document.getElementById('loadingMessage');
	oLMsg.style.display = '';
	oLMsg.style.left = container.offsetLeft + (container.clientWidth / 2) - (oLMsg.clientWidth / 2) + 'px';
	oLMsg.style.top = container.offsetTop + (container.clientHeight / 2) - (oLMsg.clientHeight / 2) + 'px';
	oLMsg.style.filter="alpha(opacity=70)";

	if (loading){
		var to = window.setTimeout('displayLoadingMsg()',100);
	}
	else {
		oLMsg.style.display = 'none';
	}
}


function getData(url,qString) {
	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari, ...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}

	//call processXML when request is returned
	http_request.onreadystatechange =  function() { processXML(http_request); };
	if (qString) { // POST
		http_request.open('POST', url, true);
		http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');  //For POST Method
http_request.setRequestHeader("Content-length", qString.length);
//http_request.setRequestHeader("Connection", "close");
		http_request.send(qString);

	}
	else {
		http_request.open('GET', url, true);
		http_request.send(null);
	}
}


function processXML(http_request) {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			readPOIs(http_request);
			loading = false;
		}
		else {
			alert('Request Failed: ' + http_request.status);
		}
	}
}

// ---------------- AJAX READ POIs ------------------------------------------ //

function readPOIs(http_request) {
	var xmlDoc = http_request.responseXML;

	var results = xmlDoc.documentElement.getElementsByTagName("p");
	//var bounds = new GLatLngBounds();	
	
	var point = new Array();
	var tablehtml = new Array();

	for (var i = 0 ; i < results.length ; i++) {
		var hv = new Array();
		var attrs = results[i].attributes;

		for ( var n = 0; n < attrs.length ; n++) {
			hv[attrs[n].name] = attrs[n].value;
		}

		html = '<div>';
		html += hv['Names'] + '<br />';
		html += hv['Address'] + '<br />';
		html += hv['City'] + ', ' + hv['State'] + ' ' + hv['ZIP'] + '<br />';
		html += hv['Telephone'] + '<br />';
		if (hv['URL']) {
			html += '<a href="' + hv['URL'] + '">Website</a><br />';		
		}
		html += 'Distance: ' + hv['d'] + ' miles<br/>';
		html += '</div>';

		point[i] = new GLatLng(hv['y'], hv['x']);
		//bounds.extend(point);
		if (hv['LogoID']) {
			image = imagepath;
			image += hv['LogoID'];
		} else {
			image = imagepath;
			image += "generic25.gif";			
		}
		icon = (new GIcon(baseIcon2, image, null, ""));
		var marker = createMarker(point[i],hv['Names'],html,icon);
		if (!poiMarkers['cb_'+hv['c']]) {
			poiMarkers['cb_'+hv['c']] = Array();
		}
		poiMarkers['cb_'+hv['c']].push(marker);
		map.addOverlay(marker);
				
		tablehtml[i] = '<td style="width:35px;text-align:right;"><img src="' + image + '"></td>';
		tablehtml[i] += '<td><b>' + hv['Names'] +'</b><br />';
		tablehtml[i] += hv['City'] + ', ' + hv['State'] + ' ' + hv['ZIP'] + '<br />';
		tablehtml[i] += hv['Telephone'] + '<br />';
		if (hv['PetInfo']) {
			tablehtml[i] += hv['PetInfo'] + '<br />';
		}
		if (hv['URL']) {
			tablehtml[i] += '<a href="http://' + hv['URL'] + '">Website</a><br />';		
		}
		tablehtml[i] += '</td><td>Distance from Route: ' + hv['d'] + ' miles<br/>';
		// tablehtml[i] += 'Amenities: ' + hv['Amenities'] + '<br />';

		tablehtml[i] += '</td>';

	}

	interspersePOIs(tablehtml, point);

	markSearchArea();

	//map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); 
	
}

function interspersePOIs (html, points) {;	
	var tbl = document.getElementById("routeTable_0");
	
	//foreach class=stepRow
    var stepRow = tbl.getElementsByTagName("tr");
	var steps = stepRow.length;
	var counter = 0;
	
	for(var i=0; i<steps; i++){
		var	stepStart = stepRow[i+counter].getElementsByTagName("td")[3];
		stepStart = stepStart.innerHTML;

		stepStartLat = getLatLng(stepStart, "lat");
		stepStartLng = getLatLng(stepStart, "lng");
		stepStart = new GLatLng(stepStartLat, stepStartLng);
		
		var radius = stepRow[i+counter].getElementsByTagName("td")[2];
		radius = convertToMeters(radius);
	
		for(var j=0; j<points.length; j++) { //points.length
			if (!points[j] == "") {
				if (stepStart.distanceFrom(points[j]) < radius) {
					var temp = document.getElementById('temp');
					temp.innerHTML = '<table><tbody><tr>' + html[j];
					var row = document.getElementById('stepRow_'+i);
					row.parentNode.insertBefore(temp.firstChild.firstChild.firstChild, row);
					//var newRow = tb.insertRow(i+counter);
					//newRow.innerHTML = html[j];
					//erase that data so points are only displayed once
					points[j] = "";
					html[j] = "";
					counter++;
				}
			}
		}
	}
}

function convertToMeters(radius) {
	radius = radius.innerHTML;
	unit = radius.match(/[fikmt]./);
	radius = radius.replace(/[^0-9.]/g, "");
	if (unit == 'ft') {
		radius = radius*.3048;
	} else if (unit == 'mi') {
		radius = radius*1609.344;
	} else if (unit == 'km') {
		radius = radius*1000;
	}
	return radius;
}

function getLatLng(latlng, which) {
	latlng = latlng.split("(");
	latlng = latlng[1].split(")");
	latlng = latlng[0].split(", ");
	if (which == "lat") {
		return latlng[0];
	} else {
		return latlng[1];
	}
}

function createMarker(point,markerName,markerHtml,mIcon) {
	var htmlInfo = '<div class="bubble">';
	htmlInfo += '<b>' + markerName + '</b><br>';
	htmlInfo += markerHtml;	
	htmlInfo += '</div>';	
	
	var marker = new GMarker(point,{icon:mIcon, title:markerName});
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(htmlInfo);
	});
	return marker;
}



// ---------------- END AJAX READ ------------------------------------------ //


// Map State Functions ---------------------------------------

function getCookie(cookieName) {
	if (document.cookie.length > 0) {
		var cIndex = document.cookie.indexOf(cookieName+"=");
		if (cIndex != -1) {
			cIndex += cookieName.length + 1;
			var cLength = document.cookie.indexOf(";", cIndex);
			if (cLength == -1) {
				cLength = document.cookie.length;
			}
			return unescape(document.cookie.substring(cIndex, cLength)); 
		}
	}
	return null;
}



function setCookie(cookieName, value, expiredays) {
	var exp = "";
	if (expiredays) {
		var ExpireDate = new Date ();
		ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
		exp = ExpireDate.toGMTString();
	}
	document.cookie = cookieName + "=" + escape(value) + "; expires=" + exp + "; path=/";
}



function delCookie (cookieName) {
	if (getCookie(cookieName)) {
		document.cookie = cookieName + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

// End Map state -------------------------------------------

function resizePage() {
	
	//get outer table
	var oTable = document.getElementById("content");
	//get directions box
	var dDiv = document.getElementById("directions_info");
	
	//get map center
	var center = map.getCenter();
	//get zoom level
	var zoom = map.getZoom();

	if (map) {
		map.checkResize();	
		map.setCenter(center,zoom);
	}
}

function unload(x) {
	doUnload(0);
}

function doUnload(mReset) {
	if (mReset) {
		delCookie('map2');
		saveState = false;
		window.location = window.location.pathname;
	}
	
	UnCheckAll(document.locOptions.chckbox);

	if (saveState) {
		var cookieStr = '';
		var center = map.getCenter();

		cookieStr += 'lat=' + center.lat() + ',';
		cookieStr += 'lon=' + center.lng() + ',';
		cookieStr += 'z=' + map.getZoom() + ',';
		cookieStr += 'mType=' + mType + ',';
		cookieStr += 'mapMode=' + mapMode;

		setCookie('map2', cookieStr, 365);
	}
	GUnload();
}

function rmOverlays() {
	directionsInfoDiv.innerHTML = '';
	map.clearOverlays();
	resizePage();
	startMarker = null;
	endMarker = null;
	pLinePoints = Array();
}


function getDirections() {
	var oDriveFrom = document.getElementById('origin_address').value;
	oDriveFrom += ' ' + document.getElementById('origin_city').value;
	oDriveFrom += ', ' + document.getElementById('origin_state').value;
	oDriveFrom += ' ' + document.getElementById('origin_zip').value;
	oDriveFrom += ' ' + document.getElementById('origin_country').value;
	var oDriveTo = document.getElementById('dest_address').value;
	oDriveTo += ' ' + document.getElementById('dest_city').value;
	oDriveTo += ', ' + document.getElementById('dest_state').value;
	oDriveTo += ' ' + document.getElementById('dest_zip').value;
	oDriveTo += ' ' + document.getElementById('dest_country').value;
	var oLocale = document.getElementById('locale');
	
	map.clearOverlays();

	directionsInfoDiv.style.display = '';
	//Check here to see if anything is checked?
	
	//resetSearchcontrols();
	var loadStr;

	if (oDriveFrom && oDriveTo) {
		loadStr = 'from:' + oDriveFrom;

		loadStr += ' to: ' + oDriveTo;
	}
	if (loadStr) {
		indicateLoading();
		dirObj.load(loadStr,{locale:oLocale.value,getPolyline:true,getSteps:true,preserveViewport:false});
		updateLink();
	}
	
}


function getPolylinePoints(p) {
	var pLinePoints = Array();
	//get number of vertices on polyline and iterate through
	for (var n = 0 ; n < p.getVertexCount() ; n++ ) {
		//add each vertex to pLinePoints array
		pLinePoints.push(p.getVertex(n));
	}
	return pLinePoints;
}


function reducePolylinePoints(p, frequency) {
	var pLinePoints = Array();
	var threshhold = frequency * 1609.344; // * 0.1;
	var lastPoint = p.getVertex(0);
	pLinePoints.push(lastPoint);
	for (var n = 0 ; n < p.getVertexCount() ; n++ ) {		
		var point = p.getVertex(n);
		//check if the distance from the last point is within the user's radius
		if (point.distanceFrom(lastPoint) > threshhold) {
			//if within radius add to the array of points to check against locations
			pLinePoints.push(point);
			lastPoint = point;
		}
	}
	//add last point too even if it isn't outside of threshhold yet
	pLinePoints.push(point);
	return pLinePoints;
}


function onDirectionsLoad() {
	var html = '';
	//get status of direction request object
	var status = dirObj.getStatus();
	//get start and destination coordinates
	var bounds = dirObj.getBounds();
	//get copyright info
	var copyrightHTML = dirObj.getCopyrightsHtml();
	//total distance and travel time summary
	var summaryHTML = dirObj.getSummaryHtml();
	//total travel distance in meters (displayed in miles)
	var distance = dirObj.getDistance();
	//total travel time in seconds (displayed in hours and minutes)
	var duration = dirObj.getDuration();
	//polyline characteristics
	var polyline = dirObj.getPolyline();

	//create array of all vertices on the route polyline
	pLinePoints = getPolylinePoints(polyline);
	//new polyline object
	var pLine = new GPolyline(pLinePoints,'#F7098A');
	//get number of geocoded entries in available in the map
	var numGeoCodes = dirObj.getNumGeocodes();
	//get geocode of first vertex
	var startPoint = dirObj.getGeocode(0);
	//get geocode of last vertex
	var endPoint = dirObj.getGeocode(numGeoCodes-1);

	//if a click created a start marker
	if (startMarker) {
		//get start point
		var clickStartPoint = startMarker.getPoint();
		//get start point from geocodes array
		var resultStartLatLon = new GLatLng(startPoint.Point.coordinates[1],startPoint.Point.coordinates[0]);

		//GLog.write(clickStartPoint.distanceFrom(resultStartLatLon))		
		//warns if clickpoint is not the same as the calculated start point
		if (clickStartPoint.distanceFrom(resultStartLatLon) > 0) {
			html += 'WARNING: The route starts some distance away from the point clicked.<br>';
		}
	}
	//if a click created an end marker
	if (endMarker) {
		//get end point
		var clickEndPoint = endMarker.getPoint();
		//get end point from geocodes array
		var resultEndLatLon = new GLatLng(endPoint.Point.coordinates[1],endPoint.Point.coordinates[0]);
		//warns if clickpoint is not the same as calculated end point
		if (clickEndPoint.distanceFrom(resultEndLatLon) > 0) {
			html += 'WARNING: The route ends some distance away from the point clicked.<br>';
		}
	}

	//iterate through available geocodes
	for (var n = 0 ; n < numGeoCodes ; n++ ) {
		//get geocode
		var geoCode = dirObj.getGeocode(n);
		//get marker associated with the nth geocode
		var marker = dirObj.getMarker(n);
	}

	//write directions box html
	html += '<div class="globalSummaryDiv">';
	html += '<table cellspacing="0" cellpadding="2" width="100%">';
	html += '<tr><td class="route_summary" valign="top"> <b> Directions: ' + startPoint.address + '</b> to <b>' + endPoint.address + '</b></td></tr>';
	html += '<tr><td class="route_stats" valign="top"> '+summaryHTML+'</td></tr>';
	html += '</table></div>';

	//get number of route polylines
	var numRoutes = dirObj.getNumRoutes();
	//for each route
	for (var r = 0 ; r < numRoutes ; r++ ) {
		//get route
		var route = dirObj.getRoute(r);
		//get start point geocode (address)
		var startGeoCode = dirObj.getGeocode(r);//route.getStartGeocode();
		//get end point geocode (address)
		var endGeoCode = dirObj.getGeocode(r+1);//route.getEndGeocode();
		//get endpoint latlong
		var endLanLng = route.getEndLatLng();
		//get route summary html
		var routeSummaryHTML = route.getSummaryHtml();
		//get route distance
		var routeDistance = route.getDistance();
		//get route time
		var routeDuration = route.getDuration();

		//get number of steps in the route
		var numSteps = route.getNumSteps();
		html += '<table cellspacing="0" cellpadding="0" id="routeTable_'+r+'" width="100%"><tbody id="tb">';
		//for each step of the route
		for (var s = 0 ; s < numSteps ; s++ ) {
			//the the sth step
			var step = route.getStep(s);
			//get start coordinates of the step
			var stepLatLng = step.getLatLng();
			//get the index number for the step's polyline
			var stepPolylineIndex = step.getPolylineIndex();
			//get the html for the step
			var stepDescriptionHTML = step.getDescriptionHtml();
			//create new regexp
			var re = new RegExp(pattern,'g');
			//display state names in red
			stepDescriptionHTML = stepDescriptionHTML.replace(re,'<b style="color:#CA0039">$1</b>')
			//get distance
			var stepDistance = step.getDistance();
			//get time
			var stepDuration = step.getDuration();
			//create html for direction box
			html += '<tr class="stepRow" id="stepRow_'+s+'" onclick="showStep('+r+','+s+')"><td>&nbsp;&nbsp;' + (s+1) + '.</td><td> ' + stepDescriptionHTML + '</td><td>' + stepDistance.html + '</td>';
			html += '<td class="stepLatLng" style="display:none">' + stepLatLng + '</td></tr>';
		}
		html += '</tbody></table>';
	}
	
	//insert created html
	directionsInfoDiv.innerHTML = html;
	var drivingDir = document.getElementById('infoContainer');
	drivingDir.style.display = '';	
	
	for (var i=5; i < 9; i++) {
		var checkbox = document.getElementById('cb_'+ i);
		if (checkbox.checked) {
			getPOIs(checkbox);
		}	
	}
	
	//signal end of loading
	loading = false;


}

function onDirectionsError() {
	//signal end of loading
	loading = false;
	//display error message
	directionsInfoDiv.innerHTML = 'Error: ' + dirObj.getStatus().code;
}

function toggleSteps(routeNo) {
	//get directions element
	oRouteTable = document.getElementById('routeTable_' + routeNo);
	//toggle display=none
	oRouteTable.style.display = oRouteTable.style.display == 'none' ? '' : 'none';
}

function showStep(r,s) {
	//close the marker's window
	map.closeInfoWindow();
	//get step
	var step = dirObj.getRoute(r).getStep(s);
	//get latlng for step
	var stepLatLng = step.getLatLng();
	//get step's description
	var stepDescriptionHTML = step.getDescriptionHtml();
	//make state names appear bold and red
	var re = new RegExp(pattern,'g');
	stepDescriptionHTML = stepDescriptionHTML.replace(re,'<b style="color:#CA0039">$1</b>')
	//get step distance
	var stepDistance = step.getDistance();
	//get step time
	var stepDuration = step.getDuration();

	//build html for marker's infoWindow
	var infoHTML = '<div id="tab1" class="bubble">';
	infoHTML += '<table>';
	infoHTML += '<tr class="stepRow"><td>&nbsp;&nbsp;' + (s+1) + '.</td><td> ' + stepDescriptionHTML + '</td><td>' + stepDistance.html + '</td></tr>';
	infoHTML += '<tr class="stepRow"><td>&nbsp;&nbsp;</td colspan="2"><td> ' + stepLatLng + '</td></tr>';
	infoHTML += '</table>';
	infoHTML += '</div>';


	//insert infoHTML to tabs
	var tab1 = new GInfoWindowTab("Location", '<div id="detailmap"></div>');
	var tab2 = new GInfoWindowTab("Info", infoHTML);
	var infoTabs = [tab1,tab2];

	//add info window to map
	map.openInfoWindowTabsHtml(stepLatLng,infoTabs);

//	detailmap = null;
// Minimap for driving directions
	var dMapDiv = document.getElementById("detailmap");
	detailmap = new GMap2(dMapDiv);
	detailmap.setCenter(stepLatLng,15);

	detailmap.addOverlay(pLine);

//	detailmap.addControl(new GSmallMapControl());

}


function getPOIs(caller) {
	//get the id of the element that called the function
	var pclass = caller.id;
	if (caller) {
		//if caller is being checked, add markers
		if (caller.checked) {
			//get user inputted radius
			var radObj = document.getElementById('radius');
			var freqObj = document.getElementById('frequency');
			//use 25 if radObj not set
			var radius = 10;
			if (radObj) {
				radius = radObj.value;
			}
			//use 50 if radObj not set
			var frequency = 50;
			if (freqObj) {
				frequency = freqObj.value;
			}
			//convert to km
			//var radius = radius * 1609.344 * 0.1;
			var freq = frequency * 1609.344;
			
			//UPDATE THIS!!
			var url = 'http://www.petswelcome.com/search-by-route/routeQuery3.php';

			//initialize query string
			var qString = '';
			//add element's id number to query
			qString += 'pClass=' + pclass.replace(/cb_/,"");
			//add 6 digit latitude to query
			qString += '&lat=' + map.getCenter().lat().toFixed(6);
			//add 6 digit longitude to query
			qString += '&lon=' + map.getCenter().lng().toFixed(6);
			//add radius to query
			qString += '&rad=' + radius;

			var lineString = '';
			var lastPoint = new GLatLng(0,0);
			//if there is a route
			if (pLinePoints && pLinePoints.length) {
				//for each point
				for (n = 0 ; n < pLinePoints.length ; n++) {
					var p = pLinePoints[n];
					//check if the distance from the last point is within the user's radius
					if (p.distanceFrom(lastPoint) > freq) {
						//add 6 digit lat and long to lineString (becomes pline for query)
						lineString += p.lat().toFixed(6) + ',' + p.lng().toFixed(6) + 'x';
						lastPoint = p;
					}
				}
				
				lineString += p.lat().toFixed(6) + ',' + p.lng().toFixed(6) + 'x';
				
				//add lineString to query as pLine
				qString += '&pline=' + lineString;
				//show loading window
				indicateLoading();
				//send query
				getData(url,qString);
			}
		}
		//if caller is unchecked, clear markers
		else {
			//if there is a route
			if (poiMarkers[pclass] && poiMarkers[pclass].length) {
				//for each marker on the route
				for ( n = 0 ; n < poiMarkers[pclass].length ; n++ ) {
					//if there is a marker?
					if (poiMarkers[pclass][n]) {
						//remove marker
						map.removeOverlay(poiMarkers[pclass][n]);

					}
				}
				poiMarkers[pclass] = new Array();
				if (searchAreaHighlight) {
					//remove highlighting
					map.removeOverlay(searchAreaHighlight);
				}
			}
		}
	}
}

function markSearchArea() {

	//if an area is already highlighted
	if (searchAreaHighlight) {
		//remove highlighting
		map.removeOverlay(searchAreaHighlight);
	}

	var displaySearch = 0;
	//for each marker
	for (pclass in poiMarkers) {
		if (poiMarkers[pclass] && poiMarkers[pclass].length) {
			//display search is true
			displaySearch = 1;
		}
	}
	//if displaySearch doesn't become true leave function
	if (!displaySearch) {
		return;
	}

	var center = map.getCenter();
	var zoom = map.getZoom();
	
	var radObj = document.getElementById('radius');
	var radius = 25;
	if (radObj) {
		//radius gets the user entered value
		radius = radObj.value;
	}
	//if there is a route
	if (pLinePoints && pLinePoints.length) {
		//for each point on the route p gets a point? I don't think this gets used?
		for (n = 0 ; n < pLinePoints.length ; n++) {
			var p = pLinePoints[n];
		}
		//map center location in pixels
		var centerPx = normalProj.fromLatLngToPixel(center, zoom);
		//lat and long of pixel one over from center
		var nextPxLatLon =  normalProj.fromPixelToLatLng(new GPoint(centerPx.x+1,centerPx.y), zoom);
		//distance of next pixel in meters
		var dPx = nextPxLatLon.distanceFrom(center) / 1609.344;
		//radius divided by distance rounded up times two to set width of polyline
		var pxWidth = Math.ceil(radius / dPx) * 2;

		//GPolyline(points,  color?,  weight?,  opacity?)
		searchAreaHighlight = new GPolyline(pLinePoints,'#FFFF00',pxWidth, 0.30);
		//add searched area polyline overlay
		map.addOverlay(searchAreaHighlight);
	}
	else {
		//get array of points on the circle
		var circlePoints = drawCircle(center,radius,'MI')

		//	GPolygon(points,  strokeColor?,  strokeWeight?,  strokeOpacity?,  fillColor?,  fillOpacity?)
		searchAreaHighlight = new GPolygon(circlePoints, '#00C000', 2 , 0.5 , '#00C000', 0.10);	
		//add route overlay
		map.addOverlay(searchAreaHighlight);
	}
}


function drawCircle(center,circleRadius,circleUnits){
	var circlePoints = Array();
	with (Math) {
		if (circleUnits == 'KM') {
			var rLat = (circleRadius/6378.8) * (180/PI);
		}
		else { //miles
			var rLat = (circleRadius/3963.189) * (180/PI);
		}
		var rLng = rLat/cos(center.lat() * (PI/180));

		for (var a = 0 ; a < 361 ; a+=1 ) {
			var aRad = a*(PI/180);
			var x = center.lng() + (rLng * cos(aRad));
			var y = center.lat() + (rLat * sin(aRad));
			var point = new GLatLng(parseFloat(y),parseFloat(x));
			circlePoints.push(point);
		}
	}
	return circlePoints;
}

function resetSearchcontrols() {
	//remove any highlighted searchAreas
	if (searchAreaHighlight) {
		map.removeOverlay(searchAreaHighlight);
	}

	UnCheckAll(document.locOptions.chckbox);

	for (pclass in poiMarkers) {

		//remove all poi markers
		if (poiMarkers[pclass] && poiMarkers[pclass].length) {
			for ( n = 0 ; n < poiMarkers[pclass].length ; n++ ) {
				if (poiMarkers[pclass][n]) {
					map.removeOverlay(poiMarkers[pclass][n]);
				}
			} //for
		} //if
	} //for
} //resetSearchControls

//]]>
