var Locator = {
	my_location:false,
	init:function(map_id){		
  		//init map
		if (map_id && GBrowserIsCompatible()) {	
			Locator.map = new GMap2(document.getElementById(map_id));
        	Locator.map.setCenter(new GLatLng(44.40, -73.2), 9);
      		var keys = new GKeyboardHandler(Locator.map);
				
				//Locator.manager = new GMarkerManager(Locator.map);
				Locator.markers = new Array();
				Locator.show_locations();
				Locator.geocoder = new GClientGeocoder(Locator.cache); 
				
		}else if(map_id){
			document.getElementById(map_id).innerHTML = "<p>Please upgrade your browser to make use of this map.</p>";
		}

		Locator.map.addControl(new GSmallMapControl());	
	},
	show_locations:function(){
		var bounds = new GLatLngBounds();					
			for(var d = 0; d < Locator.dealers.length; d++){
	
		   	 var mm = new MapMarker(Locator.dealers[d], OpenInfo, d);
				if(mm.geopoint){ 
					//	LocatorMap.manager.addMarker(mm.marker, 0, 8); 
					//Locator.manager.addMarker(mm.marker, 9);
					Locator.markers.push(mm);	
					Locator.map.addOverlay(mm.marker);
					bounds.extend(mm.geopoint);									
				}
			}
			Locator.map.setZoom(Locator.map.getBoundsZoomLevel(bounds, new GSize(600,500)));
			Locator.map.panTo(bounds.getCenter());
	},
	filter_country:function(value){
		Locator.country = value;
		var bounds = new GLatLngBounds();					
			for(var m = 0; m < Locator.markers.length; m++){
				Locator.map.removeOverlay(Locator.markers[m].marker);
				if(Locator.markers[m].object.country == value || value == ""){
					bounds.extend(Locator.markers[m].geopoint);
					Locator.map.addOverlay(Locator.markers[m].marker)
				}
					
			}
			Locator.map.setZoom(Locator.map.getBoundsZoomLevel(bounds, new GSize(600,500)));
			Locator.map.panTo(bounds.getCenter());				
	},
	clear_manual:function(){
		document.getElementById("manual_loc").value = "";
	},
	locations_near_me:function(frm){
		
		
		var address = frm.manual_location.value;
		Locator.within_dist = frm.within_dist.value;
		Locator.my_location = address;
		
		if(address != "Enter an address" && address != ""){
			//reset dropdown if tehrei's a manual value
			document.getElementById("country_enter").selectedIndex = 0;
		}
		
		document.getElementById("status").innerHTML = "<p>Searching...</p>";

		 Locator.geocoder.getLocations( address ,
			function(location) {
				if(location.Placemark){
					var lat 		= location.Placemark[0].Point.coordinates[1];
					var lng 		= location.Placemark[0].Point.coordinates[0];
				
					//construct point and get distance from other points.
					//find 5 closest dealers by keeping track of  
					var point = new GLatLng(lat, lng);
					var bounds = new GLatLngBounds();
					var locations = new Array(); 
					var indexes = new Array();
					for(var m = 0; m < Locator.markers.length; m++){
						Locator.map.removeOverlay(Locator.markers[m].marker);
						//get points within 500 miles (roughly 800km)
						if(Locator.markers[m].geopoint.distanceFrom(point) < Locator.within_dist){
							bounds.extend(Locator.markers[m].geopoint);
							Locator.map.addOverlay(Locator.markers[m].marker);
							//list location in left nav
							locations.push(Locator.markers[m]);
							indexes.push(m);
						}
					}
					
					
					if(locations.length > 0){
						
						Locator.map.setZoom(Locator.map.getBoundsZoomLevel(bounds, new GSize(600,500)));
						Locator.map.panTo(bounds.getCenter());
						
						document.getElementById("status").innerHTML = "<p><strong>" + locations.length + " locations found.</strong></p>";
						//loop over results
						var html = new Array();
						for(var l = 0; l < locations.length; l++){
							html.push("<p><strong><a href='javascript:void(OpenInfo(false,"+indexes[l]+"));'>" + locations[l].object.dealer_name + "</a></strong>");
							html.push("<br />" + locations[l].object.address1);
							if(locations[l].object.address2 != "")
								html.push("<br />" + locations[l].object.address2);
							
							html.push("<br />" + locations[l].object.city + " " + locations[l].object.state );
							
							if(locations[l].object.phone1 != "")										
								html.push("<br />PHONE: " + locations[l].object.phone1);
							if(locations[l].object.fax != "")
								html.push("<br />FAX: " + locations[l].object.fax);
							html.push("<br /><br /></p");	
						}
						document.getElementById("results").innerHTML = html.join("");
						document.getElementById("results").style.display = "block";
					} else {
						
						document.getElementById("status").innerHTML = "<p style='color:red;'>Sorry, we weren't able to locate any dealers within that distance from your address. Try selecting a greater distance from the menu</p>";										
						
					}		
					
					
				}else{
					if(document.getElementById("manual_loc").value != "Enter an address" && document.getElementById("manual_loc").value != ""){
						document.getElementById("status").innerHTML = "<p style='color:red;'>Sorry, we weren't able to locate any dealers within that distance from your address. Try selecting a greater distance from the menu</p>";										
					} else if(document.getElementById("country_enter").value != "") {
						Locator.filter_country(document.getElementById("country_enter").value);
						document.getElementById("status").innerHTML = "";
						document.getElementById("results").innerHTML = "";
					} else {
						document.getElementById("status").innerHTML = "<p style='color:red;'>Please select your country OR enter an address manually</p>";															
					}
				}
			});							
	}
}

function MapMarker(location_obj, handler, index){
	var This = this;
	this.object = location_obj;
	if(location_obj.lng){
		this.geopoint = new GLatLng(location_obj.lat, location_obj.lng);
		this.handler = handler;
		this.index = index;
		this.marker = new GMarker(this.geopoint);			
		GEvent.addListener(this.marker, "click", function() { This.handler(This) } );

	} else {

		this.geopoint = false;
	}
	return this;							
}

function OpenInfo(marker, index){
	if(index) marker = Locator.markers[index];
	var html = "<div class='markerwin' style='width:375px;height:170px'>";
		html += '<h3>'+marker.object.dealer_name+' </h3>';
		html += '<p>'+marker.object.address1+' '+marker.object.address2;
		html += '<br />'+marker.object.city+', ' + marker.object.state + ' ' + marker.object.zip + '</p>';
		html += '<p>';
		if(marker.object.email != "")
			html += '<br />EMAIL: <a href="mailto:' +marker.object.email +'" target="_self">'+ marker.object.email +'</a>';	//rxb
		if(marker.object.website != "")
			html += '<br />WEBSITE: <a href="' +marker.object.website +'" target="_blank">'+ marker.object.website +'</a>';	//rxb
		if(marker.object.phone1 != "")
			html += '<br />PHONE: ' + marker.object.phone1;
		if(marker.object.fax != "")
			html += '<br />FAX: ' + marker.object.fax;
		html += '<br /><br/></p>';
		if(Locator.my_location){
			dest = marker.object.address1.replace(/\#/,'') +' '+ marker.object.address2.replace(/\#/,'') + ' '+marker.object.city+', ' + marker.object.state + ' ' + marker.object.zip;
			html += '<a href="javascript:void(OpenDirections(\''+dest+'\'))">Get directions here</a>';
		}else{
			dest = marker.object.address1.replace(/\#/,'') +' '+ marker.object.address2.replace(/\#/,'') + ' '+marker.object.city+', ' + marker.object.state + ' ' + marker.object.zip;
			html += '<a href="javascript:void(OpenDirections(\''+dest+'\',true))">Get directions here</a>';
			
		}
		html += "</div>";
		marker.marker.openInfoWindowHtml(html);			
}

function OpenDirections(dest,start){
	var start = start ? Locator.country : Locator.my_location;
	var url = "http://maps.google.com/maps?f=d&hl=en&geocode=&saddr="+start+"&daddr="+dest+"&sll=37.0625,-95.677068&sspn=33.572881,66.621094&ie=UTF8&z=8";
	window.open(url);
}
