$('document').ready(function() {	
	//Map Goodness for Locations
	// This code will be executed when the DOM is ready
	
	/********* DEFAULTS ********************************************************/
	var def_zoomLevel 		= 4;
	var def_jsonFile 		= '/locations/locations.json.php';
	var def_maxDistance 	= 100; 					// the maximum distance from any of the points
	var def_LatLng			= new GLatLng(38, -97);
	/********* END DEFAULTS ****************************************************/
	
	// Initialize the map
	var map = new GMap2(document.getElementById("map"));
	map.setCenter(def_LatLng, def_zoomLevel);
	
	geocoder = new GClientGeocoder();
	
	// set the map controls
	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/tomato_locations.png";
	baseIcon.shadow = "/images/tomato_locations_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);
	
	function add_marker(latlng,loc,icon_num){
		if(icon_num != null){
			baseIcon.image = "/images/tomato_locations_" + icon_num + ".png";
		}
		var marker = new GMarker(latlng,{icon:baseIcon});
		map.addOverlay(marker);
		GEvent.addListener(marker, 'click', function() {
			//map.setCenter(latlng, 12);
			var address2 = '';
			if(loc.AddressLine2 != ''){ address2 = loc.AddressLine2 + "<br />" }
			var orderLink = '';
			if(loc.OnlineOrderingURL != ''){ orderLink = '<br /><a target="_blank" href="' + loc.OnlineOrderingURL + '"><img alt="Order Online" src="/images/_site/online_order_bttn.png" style="margin-top: 5px;"></a>'; }
			var distance = parseFloat(loc.distance);
			var showDistance = '';
			if(!isNaN(distance)){
				showDistance = " (" + distance.toFixed(1) + " miles)";
			}
			marker.openInfoWindowHtml("<div class=\"mapAddress\"><strong>Fazoli's" + showDistance + "</strong><br />" + loc.AddressLine1 + "<br />" + address2 + loc.City + ", " + loc.State + " " + loc.Zip + "<br />" + loc.Phone + orderLink + "</div>");
		});
		return marker;
	}
	
	function get_points(filter){
		// get the addresses from the json file
		$.getJSON(def_jsonFile,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 != ''){
					add_marker(new GLatLng(loc.geo_lat,loc.geo_lng),loc);
				}
				else {
					// start the geocoder
					var searchAddress = loc.AddressLine1 + ", " + loc.City + ", " + loc.State + " " + loc.Zip;
					geocoder.getLatLng(
						searchAddress, // the location address
						function(point) {
							if (!point) {
								// log that the point wasn't found
							} else {
								add_marker(point,loc,null);
								// cache the point
								$.getJSON('/locations/locations_update.php?StoreId=' + loc.StoreId + '&lat=' + point.lat() + '&lng=' + 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);
	}
	
	$('#searchLocations').submit(function() {
		var address = $('#addressInput').val();
		geocoder.getLatLng(address, function(latlng) {
			if (!latlng) {
				alert(address + ' not found');
			} else {searchLocationsNear(latlng);}
		});
		return false;
	});
	
	function searchLocationsNear(center) {
		var searchUrl = '/locations/locations.search.json.php?lat=' + center.lat() + '&lng=' + center.lng();
		$.getJSON(searchUrl, function(json) {
			map.clearOverlays();
            
            $('#sideBarMapList').html('').html('<ol></ol>');
            
            if (json.locations.length == 0) {
				$('#sidebar').html('Error getting results.');
				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.AddressLine2 != ''){
			address2 = loc.AddressLine2 + "<br />";
		}
		var orderLink = '';
		if(loc.OnlineOrderingURL != ''){
			orderLink = '<br /><a target="_blank" href="' + loc.OnlineOrderingURL + '"><img alt="Order Online" src="/images/_site/online_order_bttn.png" style="margin-top: 5px;"></a>';
		}
		var distance = parseFloat(loc.distance);
		$('#sideBarMapList ol').append('<li id="sidebar_' + loc.StoreId + '" class="sidebarItem"><a name="map_' + loc.StoreId + '"><strong>Fazoli\'s (' + distance.toFixed(1) + ' miles)</strong></a><br />' + loc.AddressLine1 + '<br />' + address2 + loc.City + ', ' + loc.State + ' ' + loc.Zip + '<br />' + loc.Phone + orderLink + '</li>');
		
		GEvent.addDomListener(document.getElementById('sidebar_' + loc.StoreId), 'click', function() {
			GEvent.trigger(marker, 'click');
		});
		
		GEvent.addDomListener(marker, 'click', function() {
			$('.sidebarItem').css('background-color','transparent');
			$('#sidebar_' + loc.StoreId).css('background-color','#eee');
		});
		
		$('.sidebarItem').hover(
			function(){$(this).css('background-color','#eee');}, 
			function(){$(this).css('background-color','transparent');}
		);
	}
	
	var qParam = $(document).getUrlParam("address");
	if(qParam != null){
		qParam = qParam.replace(/\%20/gi, ' ');
		geocoder.getLatLng(qParam, function(latlng) {
			if (!latlng) {
				alert(qParam + ' not found');
				get_points('');
			} else {searchLocationsNear(latlng);}
		});
	}
	else {get_points('');}
});

