/*****
Dealer Locator Script (Map Mashup)

Description:
This script is used in conjunction with the Google Maps API to instantiate 
a Google Map on the page and to dynamically display map markers after a
request is sent to the JSONP web service script.  The script relies on
the jQuery JavaScript library for the AJAX request to the JSONP web service
as well as for access to several DOM elements.

Last modified:
04/22/2010

Developed By:
Cartosoft, LLC (http://www.cartosoft.com)

Use:
The following input parameters can be used in the GET request:

	lat: [float]	Latitude (required)
	lng: [float]	Longitude (required)
	cc: [string]	Two letter country code (default: US)
	l: [integer]	Total number of records to return (default: 10)
	u: [string]		Distance units (m or k | default: m)
	dt: [integer]	Distance threshold (i.e., maximum search distance)
	
Copyright 2010 Cartosoft, LLC. All rights reserved.
http://www.cartosoft.com
You may use any of the code in this script as long as the above copyright
and URL notice is left in place

*****/

 //<![CDATA[

if (GBrowserIsCompatible())
{
	var map = null;  // Main map object
	var iconImage = null;  // A placeholder for the images used for marker icons
	var bounds = new GLatLngBounds();  // A new Google bounds object (used to determine extent)
	//Declare array objects used to store markers, HTML, and hash values
	var gmarkers = []; //Empty array used to reference marker objects
	var sidehtml = ""; //Empty string that will be populated with store info
	var jsonService = "http://bvt.runco.com/map/php/jsonp.php"; // RO
	
	var geocoder = new GClientGeocoder();  //instantiate the geocoder
	var place;
	
	//This is a helper function used to open marker windows from the sidebar
	function findMarker(mn) {
		GEvent.trigger(gmarkers[mn], "click");
	}
	
	//Function called by the geocoder after an address match
	function getAddress(response) {
		if (!response || response.Status.code != 200) {
			alert("Sorry, that address didn't work.\nTry using a different address.");
		} else {
		place = response.Placemark[0];
			var queryLat = place.Point.coordinates[1];
			var queryLng = place.Point.coordinates[0];
			var place = response.Placemark[0];
			var fullAddress = place.address;
			jQuery("#search_results").html("<h3>Finding results near:<br/>" + fullAddress + "</h3>");
			loadData(queryLat,queryLng);
		}
	}
	
	//Call this function from body onLoad event in html output
	function load(){

		map = new GMap2(document.getElementById("map"));  //Set the map object
		
		//Set the initial center point
		//(this will be adusted at the end to the bounds of the data points selected)
		var centerPoint = new GLatLng(25,-20);
			map.setUIToDefault();
			map.addControl(new GOverviewMapControl());
			map.enableDoubleClickZoom();
			map.setCenter(centerPoint, 2);
			
		//Set the icon class
		baseIcon = new GIcon();
	
	} //end load function
	
	//loadData function...calls the JSON locator web service
	function loadData(lat,lng) {
	
		//The base request parameters
		var baseRequest = '?lat='+lat+'&lng='+lng;
		
		//Additional query parameters
		var distance = jQuery("#distance").attr("value");
		var country = jQuery("#country").attr("value");
		var units = jQuery("#units").attr("value");
		
		var customRequest = "&dt="+distance+"&cc="+country+"&u="+units;
		
		var requestUrl = jsonService + baseRequest + customRequest;
		
		//Add a marker for the geocoded location (i.e., user input address)
		var centerIcon = new GIcon(baseIcon);
		centerIcon.image = "http://maps.google.com/mapfiles/ms/micons/blue-dot.png";
		centerIcon.iconSize = new GSize(32,32);
		centerIcon.iconAnchor = new GPoint(16,32);
		
		var centerPoint = new GLatLng(lat,lng);
		map.addOverlay(new GMarker(centerPoint, {icon:centerIcon}));
		
		//Call the JSON service
		requestData(requestUrl);
	
		//This function creates the map markers.  createMarker(point as GPoint, titleValue as string, html as string, ihtml as String, cId as string)
		function createMarker(point, titleValue, html, cId) {
			
			html = '<div style="overflow:auto; max-height:200px; width:250px">'+html+'</div>'; //div wrapper for info window
			
			var textNum = cId + 1;
					
			//Create the icon for the marker
			var icon = new GIcon(baseIcon);
			icon.image = "http://runco.com/CatalystImages/gmaps/marker" + textNum+".png"
			icon.iconSize = new GSize(20,34);
			icon.iconAnchor = new GPoint(10,34);
			icon.infoWindowAnchor = new GPoint(10,0);

			//Instantiate GMarker class
			var marker = new GMarker(point, {title:titleValue, icon:icon});
			
			//Attach an event listener to the marker.
			//Show information in the info window.
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml('<div class="infowindow"><h3>'+titleValue+'</h3>'+html+'</div>');
				_gaq.push(['_trackEvent', 'Map', 'Dealer', titleValue]);
			});	
			
			gmarkers[cId] = marker;

			sidehtml += '<td style="padding-bottom:10px; padding-top:10px; border-bottom: 1px solid #999999">';
			sidehtml += '<a href="javascript:findMarker(\'' + cId + '\')" class="header">'+textNum+'. '+titleValue+'</a>';
			sidehtml += '<br/>';
			sidehtml += html;
			sidehtml += '</td></tr>';	
			return marker;
		}
					
		//This function gets a JSONP object
		//and adds the markers to the map...
		function requestData(requestUrl) {
			jQuery.ajax({url:requestUrl, dataType: 'jsonp', success: function(data,textStatus) {
				
				if (!data.num_records) {
					jQuery("#search_results").html("No results were found.");
					jQuery("#loading_div").fadeOut();
					return;
				}

					
				jQuery.each(data.items, function(i,item){
						var html = "";
						
						//Get the JSON data items and assign to variables as needed
						var title = item.name;
						var address_1 = item.address_1;
						var address_2 = item.address_2;
						var city = item.city;
						var state = item.state;
						var postal_code = item.postal_code;
						var telephone = item.telephone;
						var url = item.url;
						var email = item.email;
						var demos = item.demos;
						var distance = item.distance;
						var units = item.units;
						var azimuth = item.azimuth;
						var units_text = "Miles";
						
						var lat = item.lat;
						var lng = item.lng;
						
						//Some conditional value checks
						if (address_2 != "") {
							var address = address_1 + "<br/>" + address_2;
						} else {
							var address = address_1;
						}
						
						if (telephone == "") {
							telephone = "N/A";
						}
						
						if (email == "") {
							var email_text = "";
						} else {
							var email_text = 'E-mail: <a href="mailto:' + email + '">' + email + '</a><br/>';
						}
						
						if (url == "") {
							url_text = "";
						}
						else {
							link_url = "http://" + url;
							url_text = 'Web: <a href="'+ link_url + '" target="_blank">' + link_url + '</a><br/>';
						}
						
						if (demos == "") {
							var demos_text = "";
						} else {
							var demos_text = "On display: " + demos + "<br/>";
						}
						
						if (units == "k") {
							units_text = "Kilometers";
						}
						
						//Generate HTML used for info windows and sidebar
						html += "<div>";
						html += address + "<br/>" + city + ", ";
						html += state + " " + postal_code;
						html += "<br/>";
						html += "Telephone: " + telephone + "<br/>";
						html += email_text;
						html += url_text;
						html += demos_text;
						html += "Approximately " + distance + " ";
						html += units_text + " to the " + azimuth;
						
						//Create the GLatLng object
						var point = new GLatLng(lat, lng);
						
						//Create the marker using the createMarker function
						var marker = createMarker(point, title, html, i);
	
						map.addOverlay(marker); //Add the marker to the map
						bounds.extend(marker.getPoint()); //Extend the bounds
				  });
				  
				  //Set the extent to the aggregate extent
				  //for the records that were returned
				  // Make sure we're not too zoomed in. RO 2011-05-05
				  if (map.getBoundsZoomLevel(bounds) < 15) {
					map.setZoom((map.getBoundsZoomLevel(bounds)));
				  } else {
					map.setZoom(15);
				  }
				  var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
				  var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
				  map.setCenter(new GLatLng(clat,clng));
				  
				  //The HTML that will be added to the sidebar
				  var fullHtml = "<h3>We found " + data.num_records + " stores</h3>";
				  fullHtml += "<table>" + sidehtml + "</table>";
				  
				  jQuery("#search_results").html(fullHtml);
				  
				  jQuery("#loading_div").fadeOut();
			 
		}
		});
	}
	
	}

}

//If the browser is not Javascript enabled/capable, then let the user know that the map cannot be displayed....
else {
document.getElementById("map").innerHTML = 'Sorry, your browser does not support the mapping API';
}

//]]>
