$('document').ready(function(){
	/********* DEFAULTS ********************************************************/
	var def_catId			= '';					// important for the categories to work correctly
	var def_zoomLevel 		= 7;
	var def_jsonFile 		= 'locator/locations_json';
	var def_maxDistance 	= 100; 					// the maximum distance from any of the points
	var def_LatLng			= new GLatLng(37.5, -86);
	/********* END DEFAULTS ****************************************************/
	
	var isMobile = false;
	if( navigator.userAgent.match(/Android/i) ||
	 navigator.userAgent.match(/webOS/i) ||
	 navigator.userAgent.match(/iPhone/i) ||
	 navigator.userAgent.match(/iPod/i) ||
	 navigator.userAgent.match(/BlackBerry/)
	 ){
		isMobile = true;
	}

	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 = "/css/img/map-building.png";
		baseIcon.shadow = "/css/img/map-shadow.png";
		baseIcon.iconSize = new GSize(25, 25);
		baseIcon.shadowSize = new GSize(30, 25);
		baseIcon.iconAnchor = new GPoint(9, 30);
		baseIcon.infoWindowAnchor = new GPoint(9, 9);
		baseIcon.infoShadowAnchor = new GPoint(0, 2);

		// Create an associate icon for all of our markers that specifies the shadow, icon dimensions, etc.
		var associateIcon = new GIcon();
		associateIcon.image = "/css/img/map-dude.png";
		associateIcon.shadow = "/css/img/map-shadow.png";
		associateIcon.iconSize = new GSize(25, 25);
		associateIcon.shadowSize = new GSize(30, 25);
		associateIcon.iconAnchor = new GPoint(9, 30);
		associateIcon.infoWindowAnchor = new GPoint(9, 9);
		associateIcon.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\">";
			var linkBase = "/locator/detail/";
			if (isMobile) {
				linkBase = "/m/locator/detail/";
			}
			html += "<h3 class=\"bubble\"><a href=\"" + linkBase + input.url + "\">" + input.name + "</a></h3>";
			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){
			// Default to the baseIcon marker, then check to see if it is defined as any other category
			var marker = new GMarker(latlng,{ icon:baseIcon });
			if(loc.category == 75)		marker = new GMarker(latlng,{ icon:baseIcon });
			else if(loc.category == 74)	marker = new GMarker(latlng,{ icon:associateIcon });
			//var marker = new GMarker(latlng);
			map.addOverlay(marker);
			GEvent.addListener(marker, 'click', function(){
				//map.setCenter(latlng, 12);
				if(loc.address2 != ''){ address2 = loc.address2 + "<br/>" }
				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){
			// console.log('getting points');
			// get the addresses from the json file
			var bounds = new GLatLngBounds();
			// alert("Updating...");
			
			if(filter == '') { 
				filter = '/locator/locations_json';
			}
			map.clearOverlays();
			$('#searchResults').html('');
			
			$.getJSON(filter, 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){
									// console.log('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) };
									});
								}
							}
						);
					}
				});
			}); /* */
			// console.log("Done!");
			// 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){
					// console.log(address + ' not found');
					// alert(address + ' not found');
				}
				else{
					searchLocationsNear(latlng);
				}
			});
			return false;
		});
		
		var url = $.url();
		if (url.segment(2) && url.segment(2) != '' && url.segment(2) != null) {
			var address = url.segment(2);
			$("#addressInput").val(address);
			geocoder.getLatLng(address, function(latlng){
				if(!latlng){
					// console.log(address + ' not found');
					// alert(address + ' not found');
				}
				else{
					searchLocationsNear(latlng);
				}
			});
		}

		function searchLocationsNear(center){
			var searchUrl = '/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){
			
			if(loc.category == 75)		icon = '/css/img/map-building.png';
			else if(loc.category == 74)	icon = '/css/img/map-dude.png';
			
			var address2 ='';
			if(loc.address2 != ''){
				address2 = loc.address2 + "<br />";
			}
			var distance = parseFloat(loc.distance);
			var linkBase = "/locator/detail/";
			if (isMobile) {
				linkBase = "/m/locator/detail/";
			}
			$('#searchResults').append('<li id="location_' + loc.id + '" class="locationItem"><img src="' + icon + '" alt="icon" /><p><a href="' + linkBase + loc.url + '" name="map_' + loc.id + '"><strong>' + loc.name + '</strong></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','#eeeeee');
			});

		}
		//get_points('');
		
		$("#nav-sidebar a[@rel='history']").click(function(){
			// history info
			var hash = this.href;
			hash = hash.replace(/^.*#/, '');
			// moves to a new page. 
			// pageload is called at once. 
			$.historyLoad(hash);
			
			return false;
		});
		
		/*****************************
		PAGE HISTORY STUFF
		*****************************/
		// PageLoad function
		// This function is called when:
		// 1. after calling $.historyInit();
		// 2. after calling $.historyLoad();
		// 3. after pushing "Go Back" button of a browser
		function pageload(hash) {
			// clear the id from the subnav li's
			$('#subnav li').attr('id','');
			
			// hash doesn't contain the first # character.
			if(hash && hash != 'main' && hash != '') {
				def_catId = (hash == 'store') ? '75' : '74';
				$('#map-'+hash+'-link').parent('li').attr('id', 'current');
				get_points('/locator/locations_json_' + hash);
			} else {
				if(location.hash.slice(1)){
					if(location.hash.slice(1) != 'main'){
						def_catId = (location.hash.slice(1) == 'store') ? '75' : '74';
						$('#map-'+location.hash.slice(1)+'-link').parent('li').attr('id', 'current');
						get_points('/locator/locations_json_' + location.hash.slice(1));
					}
					else {
						def_catId = '';
						get_points('/locator/locations_json');
					}
				}
				else {
					// start page
					def_catId = '';
					get_points('/locator/locations_json');
				}
			}
		}

		// Initialize history plugin.
		// The callback is called at once by present location.hash. 
		// $.historyInit(pageload);

		// set onlick event for buttons
		$("a[@rel='history']").click(function(){
			return false;
		});
		
	} // end browser compatibility test
}); // end ready()
