/*
	Code Written By: Delta Systems Group;
	
*/		
		
		//	for tracking number of info windows
		var count = 0;
		//	markers array - array to hold all marker objects
		var markers = [];
		//	htmls_links - array to hold all html info windows that do not have a "starting address" forms
		var htmls_links = [];
		//	htmls_forms - array to hold all html info windows that do have "starting address" forms
		var htmls_forms = [];
		//	markerToIdDictionary - array to map dealerIndex (id) to marker, used in locating dealers from the list of states
		var markerToIdDictionary = [];
		//	zoomLevelArray	-	array to keep distance-to-zoom level values, so when a user requests 15 miles they get a certain zoom, 100 they get a different, more appropriate zoom
		var zoomLevelArray = [];
		zoomLevelArray[15] = 9;
		zoomLevelArray[30] = 8;
		zoomLevelArray[50] = 7;
		zoomLevelArray[75] = 7;
		zoomLevelArray[100] = 6;

		function formHandler(){
			var st = $_('st');
			var c = $_('c');
			var z = $_('z');
			var go = $_('goButton');
			
			if(z.value != ''){
				go.disabled = '';
			}else if(c.value != '' && st.options[st.selectedIndex].value != ''){
				go.disabled = '';
			}else{
				go.disabled = true;				
			}
			
		}
		
		function submitForm(e){
			YAHOO.util.Event.preventDefault(e); 
			var z = $_('z');
			var c = $_('c');
			var st = $_('st');
			var d = $_('d');
			var dealerIndex = false;
			if($_('dealerIndex')) {
				dealerIndex = $_("dealerIndex").value;
			}
			var point;
	
			toggleDirections(false);
			
			//	on search for new zip, clear out markers, empty directions div			
			markers.length = 0;
			htmls_links.length = 0;
			htmls_forms.length = 0;
			markerToIdDictionary.length = 0;
			count = 0;		
    		map.clearOverlays();
			directionsDiv = document.getElementById("locator-directions");
			directionsDiv.innerHTML = "&nbsp;";
			if((z.value != '' || (c.value != '' && st.options[st.selectedIndex].value != '')) && d.value != ''){
				/*
					GET Latitude and Longitude From Google Here
				*/
				var lat;
				var lng;
				if(z.value != '' && (c.value != '' && st.options[st.selectedIndex].value != '')){
					//default to zip code if both params are entered
					getLatLong(z.value, dealerIndex, d.value);
				}else if(z.value != ''){
					//zip code
					getLatLong(z.value, dealerIndex, d.value);
				}else{
					//city and state
					getLatLong(c.value+', '+st.value, dealerIndex, d.value);
				}
			}			
		}
		function getLatLong(location, dealerIndex, distance) {
			geocoder.getLatLng(
				location,
				function(point) {
					if (!point) {
						
					} else {
						var lat = point.lat();
						var lng = point.lng();
						InitRequest.startRequest(
								{	
									'zip'			:	$_('z').value,
									'distance'		:	$_('d').options[$_('d').selectedIndex].value,
									'lat'			:	lat,
									'lon'			:	lng,
									'dealerIndex'	: 	dealerIndex 
								}
						);
						if (GBrowserIsCompatible()) {
							map.setCenter(new GLatLng(lat,lng), zoomLevelArray[distance]);
							//map.setCenter(new GLatLng(lat,lng), 10);
					   }
					   //	update results-message to indicate results are below
					   $_("result-message").innerHTML = "Results are shown below";
					}
					
				}
			);
		}
		
		function createMarker(point, data) {
			var marker = new GMarker(point);
			GEvent.addListener(marker, "click", function() {
			   map.panTo(marker.getLatLng());
		 	   marker.openInfoWindowHtml(data); 
			});
			count++;
			return marker;
		}
		
		function makeDataObject(data, point) {
			var temp ="";
			if(data.WebsiteURL != 'http://'){
				temp+= "<a href='"+data.WebsiteURL+"'><strong>"+data.Name+"</strong></a><br />";
				/*temp+= "<a href='"+data.WebsiteURL+"'>"+data.WebsiteURL+"</a><br />";*/
			} else {
				temp += "<strong>"+data.Name+"</strong><br/>";			   
			} 
			
			temp += data.Address+"<br />";
			if(data.Address2 != ''){
				temp+= data.Address2+"<br />";
			}
			temp += data.City+", "+data.StateName+" "+data.PostalCode+"<br />";
			if(data.Phone != ''){
				temp+= "Phone: "+data.Phone+"<br />";
			}
			
			temp += "Distance: "+data.distance+" miles<br/>&nbsp;";
			
			return temp;
		}   
		
		/**
		 *	getDirectionsForm
		 *	seperate function to keep the panel info seperate from the additional form, 
		 *	since the panel and the div in the results section is the same information
		 *
		 *  @param: point - glat/glng point from google results for this search result
		 *  @param: count - index of the item in markers[] and htmls[]
		 */
		function getDirectionsForm(point, count, address) {
			// The info window version with the "to here" form open      
			var str_address = address.Address + " ";
			if(address.Address2 != ''){
				str_address += address.Address2 + " ";
			}
			str_address += address.City + ", " + address.StateName + " " + address.PostalCode;
			temp = '<div id="directionForm'+count+'" class="directions-form">' +
				'Get Directions from:<form action="javascript:getDirections('+count+')">' +
				'<input type="text" SIZE=40 MAXLENGTH=100 name="saddr" id="saddr" value="" /><br>' +
				'<INPUT value="Get Directions" TYPE="SUBMIT">&nbsp;<a href="javascript:openMarkerInfoWindow('+count+')"">close</a>' +
				'<input type="hidden" name="daddr" id="daddr" value="'+ str_address + '"/>' +
				'</div>';		
			return temp;
		}

		/**
		 *	getDirectionsLink
		 *	generates a link to open the html with the getDirections() form for the matching marker
		 */
		function getDirectionsLink(count) {
			// The info window version with the "to here" form open        
			temp = '<a href="javascript:openMarkerWithForm('+count+')">Get Directions<a/><br />';		
			return temp;
		}
		

		
		var InitRequest = {
			handleSuccess:function(o){
				this.processResult(o);
			},
			handleFailure:function(o){
			},
			processResult:function(o){
				//check that the response is not undefined, and as overkill check that it isnt empty
				$_('result-set').innerHTML = '';
				$_('message').style.display = "none";
				if(o.responseText !== undefined && o.responseText != ''){ 
					var json = eval("(" + o.responseText + ")");
					/*
						USE json.addresses to get the data out of the JSON array passed back from the script
					*/
					for(var i =0; i< json.address.length; i++){
						createMarkerWithAddress(json.address, i);
					}
				} else {
					document.getElementById('message').style.display = "block";
				}
			},
			startRequest:function(data) {
				YAHOO.util.Connect.asyncRequest('GET', '/_content/locator_includes/requestCities.php?z='+data.zip+'&d='+data.distance+'&lat='+data.lat+'&long='+data.lon+'&dealerIndex='+data.dealerIndex+'',InitCallback);
			}
		};

		/**
		 *
		 */
		function createMarkerWithAddress(address, index) {
			/**
			 *	Create Google points here.
			 */
			var point = new GLatLng(parseFloat(address[index].Lat),
			parseFloat(address[index].Lng));
			var result_div = makeDataObject(address[index], point);
			var direction_form = getDirectionsForm(point, count, address[index]);
			var direction_link = getDirectionsLink(count);
			var panel_link = "<div class='panel-address-info'>" + result_div + direction_link +"</div>";	
			var panel_form = "<div class='panel-address-info'>" + result_div + direction_form +"</div>";	
			var result_info = "<div class='locator-address-info'><a href='javascript:openMarkerInfoWindow("+index+")'><img src='/_content/locator_includes/markerImage.png' width='12' height='20' /></a>" + result_div + "</div>";
			var new_marker = createMarker(point, panel_link);
			markers[index] = new_marker;
			htmls_links[index] = panel_link;
			htmls_forms[index] = panel_form;
			markerToIdDictionary[address[index].dealerIndex] = new_marker;
			if(!map) {
                map = new GMap2($_("map"));
                map.setCenter(new_marker.getLatLng(), 8);
                map.addControl(new GLargeMapControl());
                map.addControl(new GMapTypeControl());
			}
			map.addOverlay(new_marker);
			$_('result-set').innerHTML = $_('result-set').innerHTML + result_info;
		}

        /**
         *  openMarkerFromResults: 
         *  this function will open the matching pin on the map when clicked from the results section of the
         *      html
         *  @param: markerIndex - index of the item in question in the markers/htmls array
         */
        function openMarkerInfoWindow(markerIndex) 
        {   
            //  open corresponding HTML
            markers[markerIndex].openInfoWindowHtml(htmls_links[markerIndex]);
            //  pan to marker
            map.panTo(markers[markerIndex].getLatLng()); 
            scroll(0,0);
        }

        function openMarkerWithForm(markerIndex) 
        {   
            //  open corresponding HTML
            markers[markerIndex].openInfoWindowHtml(htmls_forms[markerIndex]);
            //  pan to marker
            map.panTo(markers[markerIndex].getLatLng()); 
        }

		var InitCallback =
		{
			success:InitRequest.handleSuccess,
			failure:InitRequest.handleFailure,
			scope: InitRequest
		};
				
		var linksRequest = {
			handleSuccess:function(o){
				this.processResult(o);
			},
			handleFailure:function(o){
				    box.innerHTML = "Please Try Your Search Again";
			},
			processResult:function(o){
				if(o.responseText !== undefined){ 
					box.innerHTML = o.responseText;
				} 
			},
			startRequest:function(city,srch) {
				YAHOO.util.Connect.asyncRequest('GET', '/_content/locator_includes/linksReq.php?c='+city+'&s='+srch,linksCallback);
			}
		};

		var linksCallback =
		{
			success:linksRequest.handleSuccess,
			failure:linksRequest.handleFailure,
			scope: linksRequest
		};

		/**
		 *	getMakerByDealerIndex
		 *	this function will request dealer address information for a specific dealer index
		 */
		function getMakerByDealerIndex(index)
		{
			
		}
			
		/**
		 *	getDirections()
		 *	called by the infoWindowHtml with the current points lat/lng as the end point
		 *	@param index - index in the marker array to close the infowindow of
		 */
		function getDirections(index) {
			var saddr = document.getElementById("saddr").value
			var daddr = document.getElementById("daddr").value
			gDirections.load("from: "+saddr+" to: "+daddr);
			map.setCenter(new GLatLng(markers[index].getPoint().lat(),markers[index].getPoint().lng()), 8);
			markers[index].closeInfoWindow();
		}
		
		/**
		 *	toggleDirections()
		 *	called when a user requests directions, and the GDirections fires the 'load()' event
		 *	toggles the 'result-set' and 'locator-directions' divs, hiding one or the other
		 *	@param show bool value to tell page to show or hide the 'locator-directions'.  if 'true', show 'locator-directions' and hide 'result-set'.  if false, show 'result-set', hide 'locator-directions'
		 */
		
		 function toggleDirections(showDirections) {
		 	if(showDirections == true) {
		 		document.getElementById('locator-directions').style.display="block";
		 		document.getElementById('toggle-directions').style.display="block";
		 		document.getElementById('result-set').style.display="none";
		 		//document.getElementById('remove-directions').style.display="none";
		 		document.getElementById('locator-directions').innerHTML = document.getElementById('locator-directions').innerHTML;
		 	} else {		 		
		 		document.getElementById('locator-directions').style.display="none";
		 		document.getElementById('toggle-directions').style.display="none";
		 		document.getElementById('result-set').style.display="block";
		 		//document.getElementById('remove-directions').style.display="block";
		 	}
		 }
		 
