$('document').ready(function() {
	/********* DEFAULTS ********************************************************/
	var def_catId			= 32;					// 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/mapPoint.png";
		baseIcon.shadow = "/images/site/mapPointShadow.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 html = "<div class=\"bubble\">";
			html += "<h1 class=\"bubble\">" + input.name + "<br /><span class=\"locationDistance\">(" + parseFloat(input.distance).toFixed(1) + " miles)</span>" + "</h1>";
			html += "<p>" + input.address1 + "<br/>" + input.city + ", " + input.state + " " + input.zip + "<br />" + input.phone + "</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('/pro_shop_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('/pro_shop_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));
		}

		$('#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 = '/pro_shop_locator/locations_search/' + center.lat() + '/' + center.lng() + '/' + def_catId;
			$.getJSON(searchUrl, function(json) {
				map.clearOverlays();
				$('#searchResults').remove();
				$('#gMap').after('<ol id="searchResults"></ol>');

				if (json.locations.length == 0) {
					$('#locationList').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.address2 != ''){
				address2 = loc.address2 + "<br />";
			}
			var distance = parseFloat(loc.distance);
			$('#searchResults').append('<li id="location_' + loc.id + '" class="locationItem"><p><a name="map_' + loc.id + '"><strong>' + loc.name + '</strong> <span class="distance">(' + distance.toFixed(1) + ' miles)</span></a><br />' + loc.address1 + '<br />' + loc.city + ', ' + loc.state + ' ' + loc.zip + '<br />' + loc.phone + '</p></li>');
		
			GEvent.addDomListener(document.getElementById('location_' + loc.id), 'click', function() {
				GEvent.trigger(marker, 'click');
			});

			GEvent.addDomListener(marker, 'click', function() {
				$('.locationItem').css('background-color','transparent');
				$('#location_' + loc.id).css('background-color','#eee');
			});
		
			$('.locationItem').hover(
				function(){$(this).css('background-image','url(/images/site/LocatorHover.jpg)')},
				function(){ $(this).css('background-image','url(/images/site/locatorBG.jpg)'); }
			); 
		}

		//get_points('');

	} // end browser compatibility test
}); // end ready()