var loadDelay;		// allows message only to displaye if wait is more than 1 second
var myGlobalHandlers = {
onCreate: function(){
	clearTimeout(loadDelay);	
	loadDelay = setTimeout(function() {$D('showing animation'); Element.show('requesting_data')}, 1000);
},
onComplete: function() {
	clearTimeout(loadDelay);	
	$D('hiding animation')
	Element.hide('requesting_data');
}
};
Ajax.Responders.register(myGlobalHandlers);


window.onbeforeunload = function () {		// clears queue if user leaves page
   renderQueueClear();
}


/// If set to true, will lock results to those catagories
var catArts = true;
var catHotel = true;
var catShopping = true;
var catOutdoors = true;
var catDining = true;
var stepPoints = [];
var activeMarker = null;

function toggleLock(wOn) {
	
	lockresults = wOn;
	clearSearchUnits();
	if (wOn) {
		setCheckboxes();
	}
	else {
		displayUserMessage("You are now including points of interest outside of " + catName );
	}
	triggerRefresh();
}

var curLocation = 0;
var unitSetCheckBoxes = [ {} ];
var outdoorCategoryCheckBoxes = [  ];
var cuisineCategoryCheckBoxes = [  ];
var lastUnits = null;
var SET_ARTS_N_CULTURE = 1;
var SET_HOTEL = 2;
var SET_SHOPPING = 3;
var SET_OUTDOORS = 4;
var SET_DINING = 5;
var SET_TROLLEY = 6;

var ARTS_CHECK  =1;
var HOTEL_CHECK  =2;
var DINING_CHECK = 3;
var OUTDOORS_CHECK = 4;
var SHOPPING_CHECK  =5;
var TROLLEY_CHECK  =6;

var showalert = true;
var isMoving = false;	// set to true when user is moving map
var maxZoom = 5;		// lower number is farther out
var minZoom = 15;
var tooFar = false;

var currentZoom;
var infoWindowOpen = false;

function checkZoomLevel() {
	if (map == null) return;
	var cZoom = map.getZoom();
	//$D("zoom: " + cZoom);
	if (cZoom < maxZoom) {
		tooFar = true;
	}
	else {
		tooFar = false;
	}
	if (tooFar && currentZoom != cZoom) {
		//map.setZoom(maxZoom);
		displayMessage("Results may be limited, please zoom in to recieve more results");
	}
	currentZoom = cZoom;
	
}

var map;
var mgr;
var hasControls = false;
var panoClient;  
var directionsClient;
var geocoderClient;
var directionsPanel;

function setCheckbox(wCheckbox, flip) {

	console.log(wCheckbox);
	if (flip == true) {		
		wCheckbox.click();
	}
	var cIMGOn = wCheckbox.parents(".menuItem").find("IMG.imgOn");
	var cIMGOff = wCheckbox.parents(".menuItem").find("IMG.imgOff");	
	if (wCheckbox.attr("checked")) {
		wCheckbox.parents(".menuItem").addClass("on");
		cIMGOn.show();
		cIMGOff.hide();		
	}
	else {
		wCheckbox.parents(".menuItem").removeClass("on");
		cIMGOff.show();
		cIMGOn.hide();	
		hideDropNow();
	}
	//setCheckboxes();
}

function activateMenu() {
	mItems = $J(".menuItem INPUT");
	mItems.each(		
		function(i){		
			setCheckbox($J(this));
	});		
}

var overlayTimeout, ovControl, overmap;
var ovwidth = 270;
var ovheight = 175;
var ovFixZoom = 5;

function resetInnerZoom() {
	console.log("FIXING ZOOM");
	overmap.setZoom(13);
}
function overlayCheck() {
	overmap = ovControl.getOverviewMap();
    if (overmap) {
		//console.log("GOT OVERLAY");
		clearInterval(overlayTimeout);
		//console.log(overmap);
		$J(".overIcon").show();
		$J("#insetHide").show();
		
		//overmap.setZoom(5);
		// FIX ZOOM LEVEL
		GEvent.addListener(overmap, "zoomend", function() {			
        	resetInnerZoom()
      	}); 
		GEvent.addListener(overmap, "zoomstart", function() {			
        	resetInnerZoom()
      	}); 		
		//overmap.setMapType(G_SATELLITE_MAP); 
		
		// ADD OVERLAY TO INSET
	    var pointSW = new GLatLng(39.92858634836331,-75.18925399683718);
	    var pointNE = new GLatLng(39.97432996503595,-75.13816078062587);
   		var groundOverlay = new GGroundOverlay("/assets/images/imap/overlay1.png", new GLatLngBounds(pointSW, pointNE)) ;	
		
		overmap.addOverlay(groundOverlay);
		
		
	}
}

var showInset = true;
function toggleInset() {
	if (!ovControl) return;
	if (showInset) {
		$J("#insetHide").hide();
		$J("#insetShow").show();
		$J(".overIcon").hide();
		ovControl.hide();
	}
	else {
		$J("#insetHide").show();
		$J("#insetShow").hide();	
		$J(".overIcon").show();		
		ovControl.show();
	}
	showInset = !showInset;
}
function Gload() {
	//console.log(G_START_ICON.image);
	//G_START_ICON.image = "/assets/images/maps/map_icons/06_general.png"; 
	//console.log(G_START_ICON.image);
	
	activateMenu();
	
	/* BEGIN MENU INTERACTIONS */
	mItems = $J(".menuItem IMG");	// needed for IE
	mItems.each(		
		function(i){		
			$J(this).click( function() { setCheckbox($J(this).parent().find("INPUT"), true); });
			
			
			$J(this).mouseover( function() { 					    
			    var io = $J(this).parent().find("IMG.menuOver");
			    io.show();  		
			});		
			$J(this).mouseout( function() { 
			   	var io = $J(this).parent().find("IMG.menuOver");
				io.hide();  
		    });
		    
	    });		
	

	$J("#item4").click(function() { if ($J(this).parent().hasClass("on"))  showDrop(true, 'OutdoorSelector');});
	$J("#item4").mouseover(function() { if ($J(this).parent().hasClass("on"))  showDrop(true, 'OutdoorSelector');});
	$J("#item4").mouseout(function() { showDrop(false, 'OutdoorSelector');});

	$J("#item5").click(function() { if ($J(this).parent().hasClass("on")) showDrop(true, 'CuisineSelector2');});
	$J("#item5").mouseover(function() { if ($J(this).parent().hasClass("on")) showDrop(true, 'CuisineSelector2');});
	$J("#item5").mouseout(function() { showDrop(false, 'CuisineSelector2');});	
	
	
	/* END MENU INTERACTIONS */
	
	$D("gload");
	if (GBrowserIsCompatible()) {	  	
		map = new GMap2(document.getElementById("map"));		// throws IE error if var isn't defined globally
				
		if (startLat != 0 && startLong != 0)
			centerPoint = new GLatLng(startLat, startLong) 
		else
			centerPoint = new GLatLng(39.9495, -75.1720) 

		map.setCenter(centerPoint)

		if (startZoom > 0)
			map.setZoom(startZoom);	
		else 
			map.setZoom(18);
	
		//panoClient = new GStreetviewClient();   
		
		map.addControl(new GMapTypeControl());
		map.addControl(new GLargeMapControl());	
		
		
		if (params("showmap") == "1") {
			// MAP INSET
			ovControl = new GOverviewMapControl(new GSize(ovwidth,ovheight)); 
	    	map.addControl(ovControl);
			overlayTimeout = setInterval( function() { overlayCheck(); }, 250);
		}

		var points = [ ];
		var bounds = new GLatLngBounds(centerPoint, centerPoint);
		
		
		directionsPanel = document.getElementById("directionsPanel");

		directionsClient = new GDirections(map, directionsPanel);	
		geocoderClient = new GClientGeocoder();

					
		GEvent.addListener(map, "moveend", function() {
			checkZoomLevel();
		});			
		
		if ($('UnitSetSelector')) {
			hasControls = true;			
		}
		if (hasControls) {		
			runAllInputs($('UnitSetSelector'), 'checkbox', function(obj) { 
				unitSetCheckBoxes.push(obj);
				Event.observe(obj, "click", function() {
					closeHelp();							 
					enableSpecificDropDowns();
					updateSelectedSet();
					setTimeout('setPoints();', 100);
				});
			});
			
			runAllInputs($('OutdoorSelector'), 'checkbox', function(obj) { 
				outdoorCategoryCheckBoxes.push(obj);
				Event.observe(obj, "click", function() {
					updateSelectedOutdoorCategories();
					setTimeout('setPoints();', 100);
				});
			});
			
			runAllInputs($('CuisineSelector2'), 'checkbox', function(obj) { 
				cuisineCategoryCheckBoxes.push(obj);
				Event.observe(obj, "click", function() {
					updateSelectedCuisineCategories();
					setTimeout('setPoints();', 100);
				});
			});
						
			updateSelectedSet();	
			updateSelectedOutdoorCategories();	
			updateSelectedCuisineCategories();
		}
		
		$D("SEARCH POINTS: " + searchPoints.length );		
		

		if (catPoints.length > 0) {
			setupCategoryPage();
			enableSpecificDropDowns();			
		}
		else if (searchPoints.length > 0 ) { 
			$D("STEP POINTS: " + stepPoints.length );
			setSearchPoints();		// set any initial search points
			enableSpecificDropDowns();
		}	
		else if (stepPoints.length > 0 ) { 
			setStepPoints();		// set any initial search points
			//enableSpecificDropDowns();
		}			
		else {
			generateMapItems();
			registerMapMoveHook();
			enableSpecificDropDowns();
		}
		
		var groundOverlay, imageURL;
		if (histOverlay)  {
			imageURL  = "/assets/images/historic/map-overlay2-thick.png";
			// SW, NE
			groundOverlay = new GGroundOverlay(imageURL, new GLatLngBounds(new GLatLng(39.94304166666667,  -75.15438055555556), new GLatLng(39.9574888888889,  -75.13733055555555)));
		   	map.addOverlay(groundOverlay);
			
		}

	}
	
	$D("gload done");
}



function createMapMarker(unit, isStep) {    
	var bubbleWidth = "420";
	var bubbleHeight = "250";

	var point = unit.Pos;
	var pinLabel = unit.pinLabel;
	var html;
	if (isStep == true) {
		html = sprintf("<iframe src='/map/mapWindowNew.aspx?step=%s' width='%s' height='%s' scrolling='no' frameborder='0' class='segFrameimap' id='mapWin'></iframe>", unit.UnitID, bubbleWidth, bubbleHeight);	
	}
	else {	
		if (typeof(unit.LocationID) != "undefined" && unit.LocationID > 0)
		html = sprintf("<iframe src='/map/mapWindowNew.aspx?location=%s' width='%s' height='%s' scrolling='no' frameborder='0' class='segFrameimap' id='mapWin'></iframe>", unit.LocationID, bubbleWidth, bubbleHeight);
		else
		html = sprintf("<iframe src='/map/mapWindowNew.aspx?unit=%s' width='%s' height='%s' scrolling='no' frameborder='0' class='segFrameimap' id='mapWin'></iframe>", unit.UnitID, bubbleWidth, bubbleHeight);
	}
	
	var icon = new GIcon();
	icon.shadow =  "/assets/images/maps/map_icons/shadow.png";
	icon.iconSize = new GSize(23, 30);
	icon.shadowSize = new GSize(46, 31);
	icon.iconAnchor = new GPoint(6, 38);  
//	icon.iconAnchor = new GPoint(11, 28); // adjusted for Itinerary updates

	icon.image = sprintf("/assets/images/maps/map_icons/%s", GetMarkerImage(unit));
	$D("createMapMarker: " +  icon.image);

	icon.infoWindowAnchor = new GPoint(10, 10);
	var marker = new GMarker(point,{ icon: icon, title: pinLabel } );
	if (html == null) return marker;
	
	// SETUP TABS
	var slat = unit.Pos.y;
	var slong = unit.Pos.x;	
	streetHtml =  sprintf("<iframe src='/map/mapWindowStreet.aspx?unit=%s&slat=%d&slong=%d' width='%s' height='%s' scrolling='no' frameborder='0' class='segFrameimap' id='mapWin'></iframe>", unit.UnitID,slat,slong, bubbleWidth, bubbleHeight);
	nearbyHtml = sprintf("<iframe src='/map/mapWindowNearby.aspx?unit=%s' width='%s' height='%s' scrolling='no' frameborder='0' class='segFrameimap' id='mapWin'></iframe>", unit.UnitID, bubbleWidth, bubbleHeight);
	
	console.log(streetHtml);
	
	unit.tabArray = new Array();
	unit.tabOverview =  new GInfoWindowTab("Overview",html);
	unit.tabNearby =  new GInfoWindowTab("Nearby",nearbyHtml);
	unit.tabStreet =  new GInfoWindowTab("Street View",streetHtml);		
	
	/* old method
	unit.addStreetView = function(panoData) {
		//console.log(panoData.code);
		if (panoData.code == 200) {		
			//console.log("Adding StreetView" + unit.UnitID);	

			unit.tabArray.push(unit.tabStreet);			
		}
	}
	*/
	
	
	unit.tabArray.push(unit.tabOverview);
	unit.tabArray.push(unit.tabNearby);
	if (unit.showStreet)  unit.tabArray.push(unit.tabStreet);	
	//panoClient.getNearestPanorama(unit.Pos, unit.addStreetView);
	
	
	GEvent.addListener(marker, "click", function() {		
		addToHistory(unit);		
		marker.openInfoWindowTabsHtml(unit.tabArray);
		setRenderPause(3000);
	});
	GEvent.addListener(marker, "click", function() {		// remove hook when automatic repositioning
		removeMapMoveHook();
	});
	
	GEvent.addListener(marker, "infowindowopen", function() {		// remove hook when automatic repositioning
		console.log("open");
		infoWindowOpen = true;
	});
	
	GEvent.addListener(marker, "infowindowclose", function() {		// remove hook when automatic repositioning
		console.log("closed")
		infoWindowOpen = false;
	});
	
	
	return marker;
}


var mapHook, mapHookAdd
function removeMapMoveHook() {	// disables the hook for one move, then re-enables;
	$D("removeMapMoveHook");
	if (mapHookAdd) GEvent.removeListener(mapHookAdd);
	if (mapHook) GEvent.removeListener(mapHook);		
	mapHookAdd = GEvent.addListener(map, "moveend", function() {
			registerMapMoveHook();
	});	
}

function registerMapMoveHook() {
	$D("registerMapMoveHook");
	if (mapHookAdd) GEvent.removeListener(mapHookAdd);
	if (mapHook) GEvent.removeListener(mapHook);	
	mapHook = GEvent.addListener(map, "moveend", function() {						
			generateMapItems();
	});
}

var mapRequestPause = null;
var mapRequestTimeout = null;		// used to limit consequtive requests
var requestRateLimit = 3500;
var ajaxUnitRequest;
var ajaxSearchRequest;
var ajaxLinkRequest;
var ajaxDirFrom;
var ajaxDirTo;

var preventMapRequest = false;
function generateMapItems(isDelay) {	
  console.log("generateMapItems");
  if (!GBrowserIsCompatible()) return;
  if (tooFar) return;
  
  if (!preventMapRequest) {
	  	controlledMapRequest()
		preventMapRequest = true;
		
    	if (mapRequestPause) clearTimeout(mapRequestPause);		
		mapRequestPause = setTimeout(function() {preventMapRequest = false;},requestRateLimit);	
  }
  else {
	  $D("request cancelled: too soon, queing request")
	  if (mapRequestTimeout) clearTimeout(mapRequestTimeout);		
	  mapRequestTimeout = setTimeout(function() {preventMapRequest = false; $D("--DELAYED REQUEST"); generateMapItems();},requestRateLimit);	  
  }

 // mapRequestTimeout = setTimeout(function() {controlledMapRequest()},requestRateLimit);
}

function controlledMapRequest() {		// gets all units in bounds
  if (!GBrowserIsCompatible()) return;
  if (lockresults) {
	  $D("results locked : no request");
	  setPoints();
	  return;
  }
  if (true) {
	Element.hide('requesting_data');
	$D('controlledMapRequest: Requesting from server.');
	var bounds = map.getBounds();
	var northeast = bounds.getNorthEast();
	var southwest = bounds.getSouthWest();
	var pars = sprintf('request=unitregion&northeast-lat=%d&northeast-lng=%d&southwest-lat=%d&southwest-lng=%d', 
		northeast.lat(), northeast.lng(), 
		southwest.lat(), southwest.lng());


	//$D('Requesting url: /map/MapsAjaxHandler.aspx?' + pars);
	if (ajaxUnitRequest) ajaxUnitRequest.transport.abort();
	ajaxUnitRequest = new Ajax.Request( "/map/MapsAjaxHandler.aspx", { method: 'get', onlyLatestOfClass: 'units', parameters: pars, onComplete: function(originalRequest) {
		var response = originalRequest.responseText;
		//$D("MAP RESPONSE: " + response)		
		if (response == "") {	// BUG? return's empty string if server is busy?
		//	displayMessage("Server busy");
			return;
		}
		setPoints(eval(response));
		
		ajaxUnitRequest = null;
	  }
	});
  }
  else
  {
	$D('Value from cache');
	setPoints();
  }
}




var displayedMarkers = new Object;
var displayedMarkersQIndex = new Object;
var renderQueue = new Array();
var renderQueueIndex = 0;

var showOnce = true


var markerOverlays = new Array();
var markerOverlaysMarkers = new Array();

function renderQueueExec() {
	if (pauseRendering) return;
	//if (infoWindowOpen) return;
	//if (mgr == null) mgr = new GMarkerManager(map);		// marker manager causes blinking
	//$D("QUEUELENGTH: " + renderQueue[renderQueueIndex]);
	
	if (renderQueueIndex < renderQueue.length) {
		if (renderQueue[renderQueueIndex] != null ) {
			cMarker = renderQueue[renderQueueIndex];	
			map.addOverlay(cMarker);
			
			//markerOverlaysMarkers.push(cMarker);
			//jsonData = "({markerid:" + markerOverlaysMarkers.length + ",unitid: 1})"		// HOW CAN I GET THE UNIT ID OF THE MARKER
			//markerOverlays.push(eval(jsonData));
			
		//	console.log(cMarker.markerunitid); // doesn't work
			
 			//mgr.addMarker(renderQueue[renderQueueIndex], maxZoom);
			//mgr.refresh();			
			//$D(sprintf('RenderQueue %s/%s', renderQueueIndex, renderQueue.length))
			if (activeMarker == renderQueueIndex && showOnce) {
				GEvent.trigger(renderQueue[activeMarker], "click")
				showOnce = false;
			}
			
			renderQueueIndex++;
			renderNum++;
		}
		else {
			renderQueueIndex++;
			renderQueueExec()
		}
		
		if (renderQueue.length == 1 && showOnce) {		// if one item, open window
			
			GEvent.trigger(renderQueue[0], "click")
			showOnce = false;
		}
		renderQueue[renderQueueIndex - 1] = null;	

	}
	
}

function renderQueueAdd(unitID, wMarker) {
	console.log("adding to queue: " + unitID);
	//if (displayedMarkers[unitID] != null) { renderQueueRemove(unitID); }
	displayedMarkers[unitID] = wMarker;	
	var cLength = renderQueue.length
	displayedMarkersQIndex[unitID] = cLength;
	renderQueue.push(wMarker);
	return cLength;
}

function renderQueueRemove(unitID) {
	if (displayedMarkers[unitID] == null) return;
	map.removeOverlay(displayedMarkers[unitID]); 
	displayedMarkers[unitID] = null;
	renderQueue[displayedMarkersQIndex[unitID]] = null;
}

function renderQueueClear() {
	// reset all unrendered displayMarkers
	for (i = renderQueueIndex; i < renderQueue.length; i++) {
		clearedMarker = renderQueue[i];
		for(x in displayedMarkers) {	// mark all existing units as false 
			if (displayedMarkers[x] == clearedMarker)	{
				displayedMarkers[x] = null;		
			}
		}			
		// clear displayedMarkersQIndex too??		
	}
	
	renderQueue = null;
	renderQueue = new Array();	
	renderQueueIndex = 0;
	
	
	pauseRendering = false;
}


var pauseRendering = false
var renderNum = 0;
var renderInterval = 200;
var speedCheckInterval = 12;
setInterval(renderQueueExec,renderInterval);		// calls render queue repeatedly to show units
setInterval(renderSpeedCheck,renderInterval * speedCheckInterval);		// sets render speed 

function renderSpeedCheck() {	// if rendering every second, pause 
	if (renderNum/speedCheckInterval >= 1) setRenderPause(2000);
	renderNum = 0;
}

function setRenderPause(rWait) {
	$D("PAUSING RENDER: " + rWait);
	pauseRendering = true;
	setTimeout(function() {pauseRendering = false}, rWait); 
}


var displayedUnits = new Object;		// USED TO ONLY RENDER NEW UNITS // doesntExist = null; removeFromMap = false; keepOnMap = true;
var displayedSearchUnits = new Object;		// USED TO ONLY RENDER NEW UNITS // doesntExist = null; removeFromMap = false; keepOnMap = true;
function setPoints(units) { // parses units and sets them according to category
	$D("lock to cat: " + lockresults);
	$D("setPoints");
	if (!units) units = lastUnits;
	if (!lockresults) {
		if (!units) return generateMapItems();	
	}
	lastUnits = units;
	var dateObj = new Date();
	
	
	var unitDisplayed = 0;

	for(x in displayedUnits) {	// mark all existing units as false 
		if (displayedUnits[x] == true)	{
			displayedUnits[x] = false;		
		}
	}

	for (var i = 0; i < catPoints.length; i++) {		// CATEGORIES
		var unit = catPoints[i];
		if (!unitInSelectedSets(unit)) continue;
		
		if (displayedUnits[unit.UnitID] == false) {		// if already exists, set to true to keep it
			displayedUnits[unit.UnitID] = true;		
		}
		if (displayedUnits[unit.UnitID] != true && unitIsVisible(unit)) {		// if unit doesn't exist, create it
			var marker = createMapMarker(unit);			
			if (marker != null) {
				unitDisplayed++;
				//$D("ADDING: " + unit.UnitID);
				displayedUnits[unit.UnitID] = true;				// set all refound units as true
				renderQueueAdd(unit.UnitID, marker)
			}
		}
	}	
	if (!lockresults && units) {		// if results are locked only show things in the category
	$D("displaying regional units");
	$D(sprintf('Received %d units.', units.length));
		for (var i = 0; i < units.length; i++) {
			var unit = units[i];
			if (!unitInSelectedSets(unit)) continue;
			
			if (displayedUnits[unit.UnitID] == false) {		// if already exists, set to true to keep it
				displayedUnits[unit.UnitID] = true;		
			}
			if (displayedUnits[unit.UnitID] != true && unitIsVisible(unit)) {		// if unit doesn't exist, create it
				var marker = createMapMarker(unit);			
				if (marker != null) {
					unitDisplayed++;
					//$D("ADDING: " + unit.UnitID);
					displayedUnits[unit.UnitID] = true;				// set all refound units as true
					renderQueueAdd(unit.UnitID, marker)
				}
			}
		}
	}	
	
	if (linkPoints) {
	for (var i = 0; i <  linkPoints.length; i++) {		// Link Points
		var unit = linkPoints[i];		
		if (displayedUnits[unit.UnitID] == false) {		// if already exists, set to true to keep it
			displayedUnits[unit.UnitID] = true;		
		}
	}
	}
	for(x in displayedUnits) {								// remove all marker still set to false
		if (displayedUnits[x] == false)	{
		//	$D("REMOVING: " + x);
			displayedUnits[x] = null;
			renderQueueRemove(x);
		}	
	}

  var dateObj2 = new Date();
 $D(sprintf('setPoints took: %s ms, render queue now has %s', dateObj2-dateObj, renderQueue.length ));
}

function clearSearchUnits() {
	for(x in displayedSearchUnits) {								// remove all marker still set to false
		if (displayedSearchUnits[x] == true)	{
		//	$D("REMOVING: " + x);
			displayedSearchUnits[x] = null;
			renderQueueRemove(x);
		}	
	}
}

function unitIsVisible(unit) {
	return map.getBounds().contains(unit.Pos);
}

var categoryUnits = new Object;
function setupCategoryPage() {	// parses searchPoints and sets them
	lockResults = true;
	
	if (mapHook) GEvent.removeListener(mapHook);	
	
	$D("generate cat points");
	if (!catPoints || catPoints.length == 0) return;
	
	lockResults = true;
	$("togLock").style.visibility = "visible";
	var bounds = new GLatLngBounds(catPoints[0].Pos, catPoints[0].Pos);

	catPoints.each(function(item, index) {
		if (item)  {			
			var marker = createMapMarker(item);
			bounds.extend(item.Pos);
			renderQueueAdd(item.UnitID, marker)		
			displayedUnits[item.UnitID] = true;				// add to display allow them to be removed on unchecking
			categoryUnits[item.UnitID] = true;
		}
	}) 
	
	if (startLat == 0 || startLong == 0 || startZoom == 0) {
		
		map.setZoom(Math.min(map.getBoundsZoomLevel(bounds),minZoom));
		map.setCenter(bounds.getCenter());
	}

	Element.hide('requesting_data');
	$D("generate search results done");
	registerMapMoveHook();
	generateMapItems();

}



function setSearchPoints() {	// parses searchPoints and sets them
	if (mapHook) GEvent.removeListener(mapHook);	
	
	$D("generate search results");
	if (!searchPoints || searchPoints.length == 0) return;
	var bounds = new GLatLngBounds(searchPoints[0].Pos, searchPoints[0].Pos);

	searchPoints.each(function(item, index) {
		if (item)  {			
			var marker = createMapMarker(item);
			bounds.extend(item.Pos);
			renderQueueAdd(item.UnitID, marker);
			displayedSearchUnits[item.UnitID] = true;				// add to display allow them to be removed on unchecking
		}
	}) 
	
//	map.setZoom(Math.min(Math.max(map.getBoundsZoomLevel(bounds), maxZoom),minZoom));
//	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setZoom(Math.min(map.getBoundsZoomLevel(bounds),minZoom));
	map.setCenter(bounds.getCenter());

	Element.hide('requesting_data');
	$D("generate search results done");
	registerMapMoveHook();

}

var itinRoute = new GPolyline([], "#ff0000", 5);
function setStepPoints() {	// parses searchPoints and sets them
	if (mapHook) GEvent.removeListener(mapHook);	
	
	$D("generate search results");
	if (!stepPoints || stepPoints.length == 0) return;
	var bounds = new GLatLngBounds(stepPoints[0].Pos, stepPoints[0].Pos);

	map.addOverlay(itinRoute);
	
	
	stepPoints.each(function(item, index) {
		if (item)  {			
			var marker = createMapMarker(item, true);
			bounds.extend(item.Pos);
			var cMarkerIndex = renderQueueAdd(item.UnitID, marker);
			if (currentStep == item.UnitID) activeMarker = cMarkerIndex;
			displayedSearchUnits[item.UnitID] = true;				// add to display allow them to be removed on unchecking
			itinRoute.insertVertex(0,item.Pos);
		}
	}) 
	
//	map.setZoom(Math.min(Math.max(map.getBoundsZoomLevel(bounds), maxZoom),minZoom));
//	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setZoom(Math.min(map.getBoundsZoomLevel(bounds),minZoom));
	map.setCenter(bounds.getCenter());

	Element.hide('requesting_data');
	$D("generate step results done");
	//registerMapMoveHook();
	
	
	//itinRoute.insertVertex(0,   new GLatLng(39.950161, -75.145686));
	//itinRoute.insertVertex(1,   new GLatLng(39.954578, -75.18126));
}



function clearRequests() {
	if (ajaxUnitRequest) ajaxUnitRequest.transport.abort();
	if (ajaxSearchRequest) ajaxSearchRequest.transport.abort();
	if (ajaxLinkRequest)  ajaxLinkRequest.transport.abort();
	if (ajaxDirFrom)  ajaxDirFrom.abort();
	if (ajaxDirTo) ajaxDirTo.abort();
}

function displayMessage(wMessage) {
	var searchResultsDiv = $('searchResultsMessage');
	searchResultsDiv.innerHTML = wMessage;
	searchResultsDiv.style.display = 'block';
	setTimeout(function() { searchResultsDiv.style.display='none'; }, 3000);	
}

function displayUserMessage(wMessage) {
	var userDiv = $('userMessage');
	userDiv.innerHTML = wMessage;
	userDiv.style.display = 'block';
	setTimeout(function() { userDiv.style.display='none'; }, 3000);	
}
							
	
function goSearch() {
	var searchTerm = $F('mapSearch');
	
	if (searchTerm == "" || searchTerm == null || searchTerm == "Search") {
		displayMessage("Please enter a search term");
		return;
	}	
	
	closeHelp();
	
	renderQueueClear();
	clearCheckboxes();
	clearRequests();
	clearDirections()
	
	showOnce = true;
	

	var pars = sprintf('request=search&term=%s', searchTerm);

	map.clearOverlays();
	Element.show('requesting_data');
	ajaxSearchRequest = new Ajax.Request( "/map/MapsAjaxHandler.aspx", { method: 'get', onlyLatestOfClass: 'search', parameters: pars, onComplete: function(originalRequest) {
		
		var response = originalRequest.responseText;
		//$D("SEARCH RESULTS:"  + response)
		eval(sprintf('searchPoints = %s.compact()', response ));
		displayMessage(sprintf('Your search returned %d result%s.', searchPoints.length, (searchPoints.length == 1 ? '' : 's')));
		setSearchPoints();
		generateMapItems();
		ajaxSearchRequest = null;
	  }
	});
}

var linkPoints;
function unitLink(unitID) {
	renderQueueClear();
	clearRequests();	
	//infoWindowOpen = false;
	
	
	var pars = sprintf('request=link&unitLink=%s', unitID);
	//map.clearOverlays();
	//Element.show('requesting_data');
	ajaxLinkRequest = new Ajax.Request( "/map/MapsAjaxHandler.aspx", { method: 'get', onlyLatestOfClass: 'search', parameters: pars, onComplete: function(originalRequest) {		
		var response = originalRequest.responseText;
		eval(sprintf('linkPoints = %s.compact()', response ));
		setLinkPoints();
		//console.log("GENERATE");
		preventMapRequest = false;
		setTimeout(function() { generateMapItems(); }, 2000);
		//console.log("GENERATE2");		
		ajaxLinkRequest = null;
	  }
	});	
	
}


function setLinkPoints() {	// parses searchPoints and sets them
	if (mapHook) GEvent.removeListener(mapHook);	
	
	$D("generate link points");
	if (!linkPoints || linkPoints.length == 0) return;
	//var bounds = new GLatLngBounds(linkPoints[0].Pos, linkPoints[0].Pos);
	$D("have link points");
	
	var lastItem;
	showOnce = true;
	linkPoints.each(function(item, index) {					 
		var unit = item;				
		//console.log("link" + unit.UnitID);
		//console.log(displayedMarkers[unit.UnitID]);
		
		
		if (displayedMarkers[unit.UnitID] == null) {		// if unit doesn't exist, create it
			//console.log("creating");
			var marker = createMapMarker(unit);	
			
			if (marker != null) {
				//unitDisplayed++;
				//$D("ADDING: " + unit.UnitID);
				displayedUnits[unit.UnitID] = true;				// set all refound units as true				
				renderQueueAdd(unit.UnitID, marker);
			//	displayedSearchUnits[unit.UnitID] = true;		
			}				
		}
		else {
			GEvent.trigger(displayedMarkers[unit.UnitID], "click");
		}
	
	}) 

	
}

