// 
//  locator.js
//  Ebonite International Locator
//  
//  Created by Sean Gates on 2008-08-15.
//  Copyright 2008 Paramore | Redd Online Marketing. All rights reserved.
// 

$('document').ready(function() {
	/********* DEFAULTS ********************************************************/
	var def_catId			= 29;					// important for the categories to work correctly
	var def_zoomLevel 		= 3;
	var def_jsonFile 		= 'locations_json';
	var def_maxDistance 	= 100; 					// the maximum distance from any of the points
	var def_LatLng			= new GLatLng(38, -97);
	/********* END DEFAULTS ****************************************************/

	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		map.setCenter(def_LatLng, def_zoomLevel);

		geocoder = new GClientGeocoder();

		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		
		// Create a base icon for all of our markers that specifies the
		// shadow, icon dimensions, etc.
/*		var baseIcon = new GIcon();
		baseIcon.image = "/images/site/map/track_map_icon.png";
		baseIcon.shadow = "/images/site/map/track_map_icon-shadow.png";
		baseIcon.iconSize = new GSize(38, 36);
		baseIcon.shadowSize = new GSize(60, 38);
		baseIcon.iconAnchor = new GPoint(18, 38);
		baseIcon.infoWindowAnchor = new GPoint(19, 2);
		baseIcon.infoShadowAnchor = new GPoint(0, 2);
*/
/*
		// Adding tabs to the bubbles
		function createMarker(input){
			var marker = new GMarker(input.point);
			var tabs_array = [
				new GInfoWindowTab("Tab1", "Tab 1 Information"),
				new GInfoWindowTab("Tab2", "Tab 2 Information")];
			GEvent.addListener(marker, "click", function(){
				marker.openInfoWindowTabsHtml(tabs_array);
			});
			return marker;
		}
*/

		function formatBubble(input){
			var showUrl = '';
			if(input.url != ''){ 
				if(input.url.match(/http:\/\//i)){
					showUrl = '<br><a target="_blank" href="' + input.url + '">visit online</a>';
				}
				else{
					showUrl = '<br><a target="_blank" href="http://' + input.url + '">visit online</a>';
				}
			}
			var html = "<div class=\"bubble\">";
			html += "<h1>" + input.name + " <span class=\"location_distance\">(" + parseFloat(input.distance).toFixed(1) + " miles)</span>" + "</h1>";
			html += "<p>" + input.address1 + "&nbsp;" + input.address2 + "<br/>" + input.city + ", " + input.state + " " + input.zip + "<br />" + input.phone + showUrl + "</p>";
			/* Some more formatting */
			html += "</div>";
			return html;
		}

		function add_marker(latlng, loc,icon_num){
			if(icon_num != null){
				//baseIcon.image = "/images/site/map/track_map_icon_" + icon_num + ".png";
			}
			/*var marker = new GMarker(latlng,{ icon:baseIcon });*/
			var marker = new GMarker(latlng);
			map.addOverlay(marker);
			GEvent.addListener(marker, 'click', function(){
				//map.setCenter(latlng, 12);
				if(loc.address2 != ''){ address2 = loc.address2 + "<br/>" }
				var distance = parseFloat(loc.distance);
				var showDistance = '';
				if(!isNaN(distance)){
					showDistance = " (" + distance.toFixed(1) + " miles)";
				}
				marker.openInfoWindowHtml(formatBubble(loc));
			//	marker.openInfoWindowHtml("<div class=\"bubble\"><p><strong>" + loc.name + showDistance + "</strong><br />" + loc.address1 + "<br />" + address2 + loc.city + ", " + loc.state + " " + loc.zip + "<br />" + loc.phone + "</p></div>");
			});
			return marker;
		} // end function add_marker

		function get_points(filter){
			// get the addresses from the json file
			var bounds = new GLatLngBounds();
			$.getJSON('/locator/locations_json',function(data){
				// loop through each of the markers in the json file
				$.each(data.locations, function(i,loc){
					// check for the lat and lng in the database -- if present use it to create the marker
					if(loc.geo_lat != '' && loc.geo_lng != ''){
						var point = new GLatLng(parseFloat(loc.geo_lat),parseFloat(loc.geo_lng));
						add_marker(point,loc);
						bounds.extend(point);
					}
					else {
						//alert('geocoding');
						// start the geocoder
						var searchAddress = loc.address1 + ", " + loc.city + ", " + loc.state + " " + loc.zip;
						geocoder.getLatLng(
							searchAddress, // the location address
							function(point) {
								if (!point) {
									//alert('could not find ' + loc.address1 + ', ' + loc.city + ', ' + loc.state + ' ' + loc.zip);
									// log that the point wasn't found
								} else {
									add_marker(point,loc,null);
									bounds.extend(point);
									// cache the point
									$.getJSON('/locator/locations_update/' + loc.id + '/' + point.lat() + '/' + point.lng(),function(json){
											if(json.status == 'error') { alert(json.error) };
									});
								}
							}
						);
					}
				});
			});
		
			// reset the center of the map and zoom out
			map.setCenter(def_LatLng,def_zoomLevel);
			//map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
		}

		$('#search_locations').submit(function() {
			var address = $('#address_input').val();
			geocoder.getLatLng(address, function(latlng) {
				if (!latlng) {
					alert(address + ' not found');
				} else {
					searchLocationsNear(latlng);
				}
			});
			return false;
		});

		function searchLocationsNear(center) {
			var searchUrl = '/locator/locations_search/' + center.lat() + '/' + center.lng() + '/' + def_catId;
			$.getJSON(searchUrl, function(json) {
				map.clearOverlays();
				$('#search_results').remove();
				$('#search_locations').after('<ol id="search_results"></ol>');

				if (json.locations.length == 0) {
					$('#search_locations').after('<p>Error getting results.</p>');
					return;
				}

				var bounds = new GLatLngBounds();

				$.each(json.locations,function(i,loc){
					var point = new GLatLng(parseFloat(loc.geo_lat),parseFloat(loc.geo_lng));
					var marker = add_marker(point,loc,(i+1));
					createSidebarEntry(marker, loc, (i+1));
					bounds.extend(point);
				});
				map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
			});
		}

		function createSidebarEntry(marker, loc, mapNum){
			var address2 ='';
			if(loc.address2 != ''){
				address2 = loc.address2 + "<br />";
			}
			var dealertype ='';
			if(loc.dealertype == 'Gold'){
				dealertype = "<img src='/images/site/ps_gold.png' alt='Gold Member' style='vertical-align: sub;' />";
			}
			var distance = parseFloat(loc.distance);
			// $('#search_results').append('<li id="location_' + loc.id + '" class="location_item"><p><a name="map_' + loc.id + '"><strong>' + loc.name + '</strong></a><br />' + loc.address1 + '<br />' + address2 + loc.city + ', ' + loc.state + ' ' + loc.zip + '<br />' + loc.phone + '</p></li>');
			$('#search_results').append('<li id="location_' + loc.id + '" class="location_item"><p><a name="map_' + loc.id + '" href="#"><strong>' + loc.name + '</strong></a><br />' + loc.address1 + '<br />' + address2 + loc.city + ', ' + loc.state + ' ' + loc.zip + '<br />' + loc.phone + dealertype + '</p></li>');
			
			GEvent.addDomListener(document.getElementById('location_' + loc.id), 'click', function() {
				GEvent.trigger(marker, 'click');
			});

			GEvent.addDomListener(marker, 'click', function() {
				$('.location_item').css('background-color','transparent');
				$('#location_' + loc.id).css('background-color','#EEE');
			});
		
			$('.location_item').hover(
				function(){ $(this).css('background-color','#eee'); }, 
				function(){ $(this).css('background-color','transparent'); }
			);
		}

		//get_points('');

	} // end browser compatibility test
}); // end ready()
