// 
//  locations.js
//  Ochsner Locations
//  
//  Created by Sean Gates on 2008-08-15.
//  Copyright 2008 Paramore | Redd Online Marketing. All rights reserved.
// 

$('document').ready(function() {
	/********* DEFAULTS ********************************************************/
	var def_zoomLevel 		= 9;
	var def_jsonFile 		= '/locations/locations_json';
	var def_LatLng			= new GLatLng(30.075, -90.44);
	/********* END DEFAULTS ****************************************************/

	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("large-map"));
		map.setCenter(def_LatLng, def_zoomLevel);
		
		geocoder = new GClientGeocoder();

		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		
		var map_markers = new Array();
		
		var loc_markers = new Array();
//		loc_markers['showhealth'] = new Array();
//		loc_markers['showmedical'] = new Array();
//		loc_markers['showspecial'] = new Array();
		loc_markers['showhospital'] = new Array();
		loc_markers['showspecialty'] = new Array();
		loc_markers['showoutpatient'] = new Array();
		loc_markers['showfitness'] = new Array();
		loc_markers['showemergency'] = new Array();
		loc_markers['showurgent'] = new Array();
		
		function add_marker(latlng, loc, icon_type){
			
			var baseIcon = new GIcon();
			// switch the type of marker used
			
			var location_type = "";
			var secondary_type = "";
			

			if (loc.type.indexOf("Medical Center") != -1) {
				if (loc.type.indexOf("Medical Center") == 0) {
					location_type = "hospital";
				} else {
					secondary_type = "Medical Center";
				}
			} 
			
			if (loc.type.indexOf("Health Care") != -1) {
				if (loc.type.indexOf("Health Care") == 0) {
					location_type = "outpatient";
				} else {
					secondary_type = "Health Care";
				}
			}
			
			if (loc.type.indexOf("Specialty Center") != -1) {
				if (loc.type.indexOf("Specialty Center") == 0) {
					location_type = "specialty";
				} else {
					secondary_type = "Specialty Center";
				}			
			} 
				
			if (loc.type.indexOf("Emergency Care") != -1) {
				if (loc.type.indexOf("Emergency Care") == 0) {
					location_type = "emergency";
				} else {
					secondary_type = "Emergency Care";
				}
			}
			if (loc.type.indexOf("Urgent Care Center") != -1) {
				if (loc.type.indexOf("Urgent Care Center") == 0) {
					location_type = "urgent";
				} else {
					secondary_type = "Urgent Care Center";
				}
			}		
			
			if (loc.type.indexOf("Elmwood Fitness Center") != -1) {
				if (loc.type.indexOf("Elmwood Fitness Center") == 0) {
					location_type = "fitness";
				} else {
					secondary_type = "Elmwood Fitness Center";
				}
			}

			
			
			if (secondary_type != "") {
				var secondary_loc = loc;
				secondary_loc.type = secondary_type;
				add_marker(latlng, secondary_loc, icon_type);
			}
			

			baseIcon.image = "/images/ico/flag_" + location_type + "_map.png";

			
			baseIcon.shadow = "/images/ico/flag_shadow.png";
			baseIcon.iconSize = new GSize(19, 25);
			baseIcon.shadowSize = new GSize(33, 25);
			baseIcon.iconAnchor = new GPoint(9, 20);
			baseIcon.infoWindowAnchor = new GPoint(9, 2);
			
			var marker = new GMarker(latlng, { icon:baseIcon });
			map.addOverlay(marker);
			
			var tab1 = new GInfoWindowTab('Details','<div class="bubble"><p><strong>' + loc.name + '</strong><br />' + loc.address + '<br />' + loc.city + ', ' + loc.state + ' ' + loc.zip + '<br />' + loc.phone + '<br><a href="/locations/' + loc.url_title + '">View Details</a><br>&nbsp;</p></div>');
			
			var tab2 = new GInfoWindowTab('Directions','<div class="bubble"><form action="http://maps.google.com/maps" method="get" target="_blank"><fieldset><legend>Driving Directions</legend><label for="saddr">Starting Address</label><input type="text" name="saddr" id="saddr"></fieldset><fieldset><legend>Submit</legend><input type="hidden" value="' + loc.address + ', ' + loc.city + ', ' + loc.state + ' ' + loc.zip + '" name="daddr"><input type="submit" value="Get Directions &raquo;" class="map-directions" /></fieldset></form></div>');
			
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowTabsHtml([tab1,tab2]);
			});
			
			// add the markers to a storage array
			loc_markers['show' + location_type].push(marker);
			
			map_markers.push(marker);
			
			return marker;
		} // end function add_marker

		$('#search-locations').submit(function() {
			var address = $('#address-input').val();
			geocoder.getLatLng(address, function(latlng) {
				if (!latlng) {
					alert(address + ' not found');
				} else {
					searchLocationsNear(latlng,address);
				}
			});
			return false;
		});
		
		function sortByKey(arr,key,direction) {
			function sortNumeric(a,b) {
				var c=a[key],d=b[key];
				if (direction=="ASC") {
					return (c==="")-(d==="") || c-d;
				} else {
					return (c==="")-(d==="") || d-c;   
				}
			}       
			return arr.sort(sortNumeric);
	    }
		
		function convertToMiles(meters){
			miles = meters / 1609.344;
			return parseFloat(miles).toFixed(1);
		}
		
		var searchedMarkers = new Array(0);
		
		function searchLocationsNear(center,address) {
			var baseIcon = new GIcon();
			baseIcon.image = "/images/ico/flag_home_map.png";
			baseIcon.shadow = "/images/ico/flag_shadow.png";
			baseIcon.iconSize = new GSize(19, 25);
			baseIcon.shadowSize = new GSize(33, 25);
			baseIcon.iconAnchor = new GPoint(9, 20);
			baseIcon.infoWindowAnchor = new GPoint(9, 2);
			
			var bounds = new GLatLngBounds();
			var marker = new GMarker(center, { icon:baseIcon });
			var marker_sort = new Array();
			
			$.each(searchedMarkers, function(i,m){
				map.removeOverlay(m);
				searchedMarkers.pop();
			});
			
			searchedMarkers.push(marker);
			
			map.addOverlay(marker);
			
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml("<div class=\"bubble\"><p><strong>Your Location:</strong><br />" + address + "</p></div>");
			});
			
			bounds.extend(center);
			
			$.each(map_markers, function(i,m){
				// alert("distance: " + center.distanceFrom(m.getLatLng()));
				marker_sort[i] = {
					"marker" : m,
					"distance": convertToMiles(center.distanceFrom(m.getLatLng()))
					};
			});
			
			marker_sort = sortByKey(marker_sort,"distance","ASC");

			var foundCount = 0;
			$.each(marker_sort, function(i,m){
				if(foundCount < 2 && m.marker.isHidden() === false) {
					ll = m.marker.getLatLng();
					var point = new GLatLng(parseFloat(ll.lat()),parseFloat(ll.lng()));
					bounds.extend(point);
					foundCount++;
				}
			});
			
			map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
			return;
		}

		function get_points(){
			// get the addresses from the json file
			var bounds = new GLatLngBounds();
			$.getJSON(def_jsonFile,function(data){
				// loop through each of the markers in the json file
				$.each(data.locations, function(i,loc){
					if(loc.geo_lat == '' && loc.geo_lng == '')
					{
						// start the geocoder
						var searchAddress = loc.address + ", " + loc.city + ", " + loc.state + " " + loc.zip;
						geocoder.getLatLng(
							searchAddress, // the location address
							function(point) {
								if (!point) {
									alert('could not find ' + loc.address + ', ' + loc.city + ', ' + loc.state + ' ' + loc.zip);
									// log that the point wasn't found
								} else {
									add_marker(point,loc,null);
									bounds.extend(point);
								}
							}
						);
					}
					else {
						var point = new GLatLng(parseFloat(loc.geo_lat),parseFloat(loc.geo_lng));
						add_marker(point,loc,null);
						bounds.extend(point);
					}
				});
				
				map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
			});
			
			
			setTimeout(function(){
				var url_zip = location.href;
				if(url_zip.indexOf('zip') > 0) {
					url_zip = url_zip.replace(/.+[\/]([^\/]+)$/,'$1');
					$("#address-input").val(url_zip);
					geocoder.getLatLng(url_zip, function(latlng) {
						if (!latlng) {
							alert(url_zip + ' not found');
						} else {
							searchLocationsNear(latlng,url_zip);
						}
					});
				}
			},500);
			
			return;
		}
		
		get_points();
		
		function hideMarkers(markers_array){
			$.each(markers_array, function(i,m){
				m.hide();
			});
		}
		function showMarkers(markers_array){
			$.each(markers_array, function(i,m){
				m.show();
			});
		}
		
		$("input[type='checkbox']").click(function(){
			if($(this).attr('checked')){
				showMarkers(loc_markers[$(this).attr('id')]);
			}
			else {
				hideMarkers(loc_markers[$(this).attr('id')]);
			}
		});
		
		$('#large-map').click(function(event) {
			var $target = $(event.target);
			if( $target.is('.map-directions')) {
				$target.parent('form').sumbit();
				return false;
			}
		});

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