function ConstructLocator() {
	setTimeout(load);
}

var map;
var global_setMarker;
function load() {
//	function setEvent(e, f) {
//		if (window.addEventListener) {
//			e.addEventListener(e, f, false);
//		} else {
//			e.attachEvent("on" + e, f);
//		}
//	}
//	function UnsetEvent(e, f) {
//		if (window.addEventListener) {
//			
//		}
//	}
	var currentDestination = document.getElementById("currentdestination");
	var txtSearch = document.getElementById("where");
	var optHowmany = document.getElementById("howmany");
	var optWhatFor = document.getElementById("whatfor");
	var cmdSearch = document.getElementById("search");
	var divGdf = document.getElementById("getdirectionsfrom");
	var txtGdf = document.getElementById("txtgdf");
	var cmdGdf = document.getElementById("cmdgdf");
	var cmdBackToResults = document.getElementById("cmdBackToResults");
	var directionsList = document.getElementById("directionsList");
	var resultList = document.getElementById("resultList");
	var lnkPrint = document.getElementById("lnkPrint");

	directionsList.style.display = "none";
	resultList.style.display = "";


	//document.getElementById("Adoe
  if (GBrowserIsCompatible()) {
	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(0, 0), 1);
	// Controls
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
//		map.setCenter(new GLatLng(37.4419, -122.1419), 13);
		map.enableScrollWheelZoom();
		
	GEvent.bind(map,"click", null,  
		function(overlay, point) {	
			if (overlay != null && typeof(overlay.onclick) == "function") {
				overlay.onclick();
			}
			if (overlay && overlay.F) {
				overlay.enableDragging();
//				overlay.F.Jg(); // Pick up
//				overlay.F.wh(); // Drop
				overlay.disableDragging();
			}
		}
	)
	// Get Directions From (gdf) 
		var currentMarker;
		var directions;

		var handleErrors = function(){
		   if (directions.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.\nError code: " + directions.getStatus().code);
		   else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
			 alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code);
		   
		   else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
			 alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code);

		   else if (directions.getStatus().code == G_GEO_BAD_KEY)
			 alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code);

		   else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
			 alert("A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);
		    
		   else alert("An unknown error occurred.");
		   
		}
		function onGDirectionsLoad(){ 
			home.hide();
			currentDestination.innerHTML = divs[currentMarker.index].html;
		}

		directions = new GDirections(map, directionsList);
		GEvent.addListener(directions, "load", onGDirectionsLoad);
		GEvent.addListener(directions, "error", handleErrors);

		var tabGdf = new GInfoWindowTab(gt_directions, divGdf);
		divGdf.style.display = "block";
		directionsList.style.display = "none";
		cmdBackToResults.onclick = function() {
			directionsList.style.display = "none";
			resultList.style.display = "";
		}
//		cmdGdf.onclick = function() {
//		cmdGdf.attachEvent("onclick", function() {
		function cmdGdf_onclick() {
			map.closeInfoWindow();
			var point = currentMarker.getPoint();
			directionsList.style.display = "block";
			resultList.style.display = "none";

			var to = addressToString(currentMarker.location.Address);
			lnkPrint.href = "http://maps.google.com/maps?saddr=" + escape(this.txtGdf.value) + "&daddr=" + escape(to);
			setDirections(this.txtGdf.value, to, "en_US")

		}
//		);
			function setDirections(fromAddress, toAddress, locale) {
			  directions.load("from: " + fromAddress + " to: " + toAddress,
						{ "locale": locale });
			}			
		
		
	// Results 
		var resultList = document.getElementById("resultList");
		var divs = [];
		for (var i = 0; i < 100; i++) {
			divs[i] = document.createElement("div");
			divs[i].style.marginBottom = "14px";
			resultList.appendChild(divs[i]);
		}
		function clearResultList() {
			for (var i = 0; i < divs.length; i++) {
				divs[i].innerHTML = "";
				divs[i].style.display = "none";
			}
		}
		function addressToString(addr) {
			var ret = "";
			function add(txt) {
				if (typeof(txt) == "string" & txt != "" & txt != null) {
					if (ret != "") ret += ", ";
					ret += txt;
				}
			}
			add(addr.Address1);
			add(addr.Address2);
			add(addr.City);
			add(addr.State);
			add(addr.Postal);
			add(addr.Country);
			return ret;
		}
		function image_click() {
			var index = this.index;
			var marker = markers[index];
			var div = divs[index];
			var location = locations[index];
			var tab1 = new GInfoWindowTab(gt_location, div.html);
			currentMarker = markers[index];
			/*
				marker.location = location;
				marker.openInfoWindowTabs([tab1, tabGdf], {maxWidth: 260});
			*/
			/**/
				var myDivGdf = divGdf.cloneNode(true);
				myDivGdf.txtGdf = myDivGdf.getElementsByTagName("INPUT")[0];
				myDivGdf.cmdGdf = myDivGdf.getElementsByTagName("INPUT")[1];
				myDivGdf.cmdGdf.txtGdf = myDivGdf.txtGdf;
				myDivGdf.cmdGdf.onclick = cmdGdf_onclick;
				var myTabGdf = new GInfoWindowTab(gt_directions, myDivGdf);
				
				marker.openInfoWindowTabs([tab1, myTabGdf], {maxWidth: 260});
			/**/
			//map.panTo(marker.getPoint());
		}
		function image_mouseover() {
			var index = this.index;
			var marker = markers[index];
			var div = divs[index];
		}
		function image_mouseout() {
			var index = this.index;
			var marker = markers[index];
			var div = divs[index];
		}
		
		function setResultList(i,html) {
			var div = divs[i];
			div.innerHTML = html;
			div.html = html;
			div.style.display = "";
			div.image = document.getElementById("result" + i + "_image");
			div.link = document.getElementById("result" + i + "_link");
			div.image.index = i;
			div.link.index = i;
			div.image.onclick = image_click;
			div.image.style.cursor = "hand";
			div.link.onclick = image_click;
			div.link.style.cursor = "hand";
			markers[i].onclick = image_click;
			markers[i].index = i;
			markers[i].location = locations[i];
		}
	// Marker
		var homeOpt = {};
			var homeIcon = new GIcon();
			homeIcon.image = "/images/maps/arrow.png";
			homeIcon.iconSize = new GSize(39,34);
			homeIcon.shadow = "/images/maps/arrowShadow.png";
			homeIcon.shadowSize = new GSize(39,34);
			homeIcon.iconAnchor = new GPoint(11,33);
		homeOpt.icon = homeIcon;
		var home = new GMarker(new GLatLng(0,0), homeOpt);
		map.addOverlay(home);
		home.hide();
		var opt = {};
		// redIcon
			var redIcon = new GIcon();
			redIcon.image = "/images/maps/triangleMarker.png";
			redIcon.iconSize = new GSize(54,35);
			redIcon.shadow = "/images/maps/triangleMarkerShadow.png";
			redIcon.shadowSize = new GSize(54,35);
			redIcon.iconAnchor = new GPoint(17,32);
			redIcon.infoWindowAnchor = new GPoint(17,0);
		// small Red Icon
			var redIconsm = new GIcon();
			redIconsm.image = "/images/maps/triangleMarkersm.png";
			redIconsm.iconSize = new GSize(27,18);
			redIconsm.shadow = "/images/maps/triangleMarkerShadowsm.png";
			redIconsm.shadowSize = new GSize(27,18);
			redIconsm.iconAnchor = new GPoint(8,15);
			redIconsm.dragCrossImage = "/images/blank.gif";
			redIconsm.dragCrossSize = new GSize(1,1);
			redIconsm.dragCrossAnchor = new GPoint(1,1);
			redIconsm.infoWindowAnchor = new GPoint(8,0);
		opt.icon = redIconsm;
		opt.draggable = true;
		opt.bounceGravity = 0.1;
	//Search Form
		
	// Markers
		var markers = [];
		for (var i = 0; i < 100; i++) {
			var marker = new GMarker(new GLatLng(0,0), opt);
			map.addOverlay(marker)
			markers[i] = marker;
			marker.hide();
		}
		var marker_cursor = 0;
		function hideMarkers() {
			for (var i = 0; i < markers.length; i++) {
				markers[i].hide();
			}
			marker_cursor = 0;
			home.hide();
			if (smTimer != null) clearTimeout(smTimer);
		}
		function setMarker(point) {
			var marker = markers[marker_cursor];
			marker_cursor++;
			if (marker_cursor == markers.length) marker_cursor = 0;
			marker.setPoint(point);
			showMarker(marker);
		}
		function showMarker(marker) {
			marker.show();
			//marker.enableDragging();
//			marker.F.Jg(); // Pick up
//			marker.F.wh(); // Drop
			//marker.disableDragging();
		}
		var smc = 0;
		var smTimer = null;
		function showMarkers(start) {
			return;
			if (start) {
				if (smTimer != null) clearTimeout(smTimer);
				smc = 0;
				smTimer = setTimeout(showMarkers,100);
			} else {
				var marker = markers[smc];
				smc++;
				showMarker(marker);
				if (smc < 100) {
					smTimer = setTimeout(showMarkers,10);
				} else {
					smTimer = null;
				}
			}
		}
		global_setMarker = setMarker;
		function setHome(point) {
			home.setPoint(point);
			home.show();
		}
	// Ajax Search
		var locations = null;
		function searchReturn(val) {
			var myLatLng = new GLatLng(val.LatLong.Latitude, val.LatLong.Longitude);
			setHome(myLatLng);
			
			// Track bounds of results
//			var minlat, minlon, maxlat, maxlon
//			minlat = maxlat = val.LatLong.Latitude;
//			minlon = maxlon = val.LatLong.Longitude;

			var bounds = new GLatLngBounds(myLatLng, myLatLng);
			locations = val.Locations;
			for (var i = 0; i < val.Locations.length; i++) {
				var location = val.Locations[i];
				var lat = location.LatLong.Latitude;
				var lon = location.LatLong.Longitude
				var point = new GLatLng(lat, lon);
				bounds.extend(point);
				var marker = setMarker(point);
				setResultList(i,val.HTMLs[i]);
				// Update bounds of results
//				if (lat < minlat) minlat = lat;
//				if (lat > maxlat) maxlat = lat;
//				if (lon < minlon) minlon = lon;
//				if (lon > maxlon) maxlon = lon;
			}
			showMarkers(true);
			map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
			
			// Find center point of results;
//			var lat = (minlat + maxlat) / 2;
//			var lon = (minlon + maxlon) / 2;
//			var center = new GLatLng(lat,lon);
//			map.panTo(center);
//			var zoomLevel = map.getBoundsZoomLevel(
//				new GLatLngBounds(
//					new GLatLng(minlat, maxlon),
//					new GLatLng(maxlat, minlon)
			searching = false;
			cmdSearch.disabled = false;
			
		}
		function searchError(val) {
			alert("An error occured during your search:\n\n" + val.get_message());
			searching = false;
			cmdSearch.disabled = false;
		}
		var searching = false;
		function Search() {
			if (!searching) {
				var within = optHowmany.value;
				var whatfor = optWhatFor.value;
				var unit;
				var distance = 0;
				var qs = new Querystring();
				unit = qs.get("u");
				switch (within.substring(0,1)) {
					case "w":
						distance = parseInt(within.substring(1));
						break;
					case "n":
						distance = parseInt(within.substring(1)) * -1;
						break;
				}
				txtGdf.value = txtSearch.value;
				cmdSearch.disabled = true;
				searching = true;
				hideMarkers();
				clearResultList();
				directions.clear();
				DealerLocatorService.FindDealers(
					CountryID, LanguageID, 
					txtSearch.value, distance, unit, whatfor,
					searchReturn,
					searchError
				);
			}
		}
		//$addHandler(cmdSearch, "click", function() {alert('test');} );
		cmdSearch.onclick = Search;
		document.getElementById("aspnetForm").action = "#";
		document.getElementById("aspnetForm").method = "GET";
		function search_2() {
			Search();
			if (window.event) {
				window.event.returnValue = false;
				window.event.cancelBubble = true;
			}
			return false;
		}
		document.getElementById("aspnetForm").onsubmit = function() { return false; };
		document.getElementById("aspnetForm").attachEvent("onsubmit", search_2);
		//document.getElementById("aspnetForm").removeNode();
		
////////		// POIs
////////		var bounds = map.getBounds();
////////		var southWest = bounds.getSouthWest();
////////		var northEast = bounds.getNorthEast();
////////		var lngSpan = northEast.lng() - southWest.lng();
////////		var latSpan = northEast.lat() - southWest.lat();
////////		for (var i = 0; i < 10; i++) {
////////		  var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
////////			  southWest.lng() + lngSpan * Math.random());
////////		  map.addOverlay(new GMarker(point));
////////		}

//////		// Info Window
////////		map.setCenter(new GLatLng(37.4419, -122.1419), 13);
////////		map.openInfoWindow(map.getCenter(),
////////			document.createTextNode("Hello, world"));
//////		//DealerLocatorService.HelloWorld(function(ret){alert(ret);});
//////      }
//////      function FindDealersReturn(ret) {
//////        var myposition = new GLatLng(ret.LatLong.Latitude, ret.LatLong.Longitude);
//////		map.panTo(myposition);
//////		var dealers = ret.Locations;
//////		for (var i = 0; i < dealers.length; i++) {
//////			var dealer = dealers[i];
//////			dealer.position = new GLatLng(dealer.LatLong.Latitude, dealer.LatLong.Longitude);
//////			dealer.marker = new GMarker(dealer.position);
//////			map.addOverlay(dealer.marker);
//////		}
//////      }
//////      var search = document.getElementById("search");
//////      var address = document.getElementById("address");
//////      search.onclick = function() {
//////		DealerLocatorService.FindDealers(address.value, 5, 'M', FindDealersReturn, function(ret) { alert(ret.message) });

	} else {
		alert("Sorry, your browser is not GoogleMaps compatible.");
	}
}
function handle(delta) {
//	if (delta > 0) {
//		map.zoomIn();
//	} else {
//		map.zoomOut();
//	}
}
function wheel(event){
		var delta = 0;
		if (!event) /* For IE. */
				event = window.event;
		if (event.wheelDelta) { /* IE/Opera. */
				delta = event.wheelDelta/120;
				/** In Opera 9, delta differs in sign as compared to IE.
				 */
				if (window.opera)
						delta = -delta;
		} else if (event.detail) { /** Mozilla case. */
				/** In Mozilla, sign of delta is different than in IE.
				 * Also, delta is multiple of 3.
				 */
				delta = -event.detail/3;
		}
		/** If delta is nonzero, handle it.
		 * Basically, delta is now positive if wheel was scrolled up,
		 * and negative, if wheel was scrolled down.
		 */
		if (delta)
				handle(delta);
		/** Prevent default actions caused by mouse wheel.
		 * That might be ugly, but we handle scrolls somehow
		 * anyway, so don't bother here..
		 */
		if (event.preventDefault)
				event.preventDefault();
	event.returnValue = false;
}

/** Initialization code. 
 * If you use your own event management code, change it as required.
 */
if (window.addEventListener)
		/** DOMMouseScroll is for mozilla. */
		window.addEventListener('DOMMouseScroll', wheel, false);
/** IE/Opera. */
window.onmousewheel = document.onmousewheel = wheel;

