jQuery(document).ready(function(){
	
	// Globals
	var msgeo_markers = [];
	var msgeo_map;
	var geo;
	var msgeo_orig_lat = Number(msgeoL10n.start_lat);
	var msgeo_orig_lng = Number(msgeoL10n.start_lng);
	var msgeo_orig_zoom = Number(msgeoL10n.zoom);
	var msgeo_api_key = msgeoL10n.api_key;
	var msgeo_post_id = Number(msgeoL10n.post_id);
	var msgeo_container;
	var msgeo_lookup;
	
	
	
	jQuery('#ms-geo-map').fadeTo('fast', .5);
	jQuery('#ms-leader-geo-map').fadeTo('fast', .5);
	
	jQuery("#ms-geo-map").click(function(){
		msgeo_container = jQuery("#ms-geo-map");
		msgeo_lookup = true;
		initMap();
	});
	
	jQuery(".map-message").click(function(){
		msgeo_container = jQuery("#ms-geo-map");
		msgeo_lookup = true;
		initMap();
	});
	
	jQuery("#ms-leader-geo-map").click(function(){
		msgeo_container = jQuery("#ms-leader-geo-map");
		msgeo_lookup = false;
		initMap();
	});
	
	jQuery(".leader-map-message").click(function(){
		msgeo_container = jQuery("#ms-leader-geo-map");
		msgeo_lookup = false;
		initMap();
	});
	
	function initMap(){
		msgeo_container.css('background-image', 'none');
		msgeo_container.fadeTo('slow', 1);
		jQuery('.map-message').remove();
		jQuery('.leader-map-message').remove();
		jQuery('.map-controls').slideDown('slow');
		loadMap();
	}
	
	function loadMap()
	{
		jQuery(msgeo_container).unbind("click");
		setLatLng('', '');
		
		google.load("maps", "2.x", {callback:displayMap});
	}
	
	function setLatLng(lat, lng)
	{
		jQuery('#msgeo_post_lng').val(lng);
		jQuery('#msgeo_post_lat').val(lat);
	}
	
	function displayMap()
	{
		
		geo = new GClientGeocoder(); 
		
		msgeo_map = new GMap2(msgeo_container.get(0));
		msgeo_map.setUIToDefault();
		
		GEvent.addListener(msgeo_container, "load", function() {
			if(msgeo_lookup)
			{	
				jQuery.getJSON(msgeoL10n.msgeo_plugin_url+"/php/ms-geo-points.json.php?id="+msgeo_post_id, function(json) {
					if (json.locations.length > 0) {
						for (i=0; i<json.locations.length; i++) {
							var location = json.locations[i];
							if(location.lat != 0 && location.lng != 0)
							var marker = new GLatLng(location.lat,location.lng);
							createMarker(marker);
						}
					}
				});
			}
		});
		
		var center = new GLatLng(msgeo_orig_lat, msgeo_orig_lng);
		msgeo_map.setCenter(center, msgeo_orig_zoom);
		
		jQuery('.map-reset').show();
		jQuery('.map-reset').click(function(){
			loadMap();
			return false;
		});
		
		jQuery('.map-center').show();
		jQuery('.map-center').click(function(){
			var coords = msgeo_markers[0].getLatLng();
			msgeo_map.panTo(coords, msgeo_map.getZoom());
			return false;
		});
		
		jQuery('.find-address').show();
		jQuery('.find-address').click(function(){
			geoEncode();
			return false;
		});

		GEvent.addListener(msgeo_map, "click", function(overlay, location) {
			if(overlay == null)
			{
				createMarker(location, msgeo_map);
			}
			return false;
		});
	}
	
	function geoEncode() {
		
		var reasons=[];
		reasons[G_GEO_SUCCESS]            = "Success";
		reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address";
		reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address.";
		reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address";
		reasons[G_GEO_BAD_KEY]            = "Bad API Key";
		reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries";
		reasons[G_GEO_SERVER_ERROR]       = "Server error";
		
		var address = jQuery("#address").val();
		
		geo.getLocations(address, function (result){
			if (result.Status.code == G_GEO_SUCCESS) {
				var geocode = result.Placemark[0].Point.coordinates;
				createMarker(new GLatLng(geocode[1], geocode[0], geocode[2]));
			} else {
				var reason="Code "+result.Status.code;
				if (reasons[result.Status.code]) {
					reason = '<span class="error">'+reasons[result.Status.code]+'</span>';
				} 
				jQuery(".error").html(reason).fadeIn();
				geocode = false;
			}
		});
	}
	
	function resetSearch()
	{
		jQuery('#address').val('');
	}

	function createMarker(location) {
		var marker = new GMarker(location, {draggable:true});
		var coords = marker.getLatLng();
		setLatLng(coords.lat(), coords.lng());
		msgeo_markers.push(marker);

		if(msgeo_markers.length > 1)
		{
			console.log('showing markers');
			var temp_marker = msgeo_markers.shift();
			msgeo_map.removeOverlay(temp_marker);	
		}
		
		msgeo_map.addOverlay(marker);
		// Each time this is updated, set a hidden input value to store lat and longitude.
		msgeo_map.panTo(coords, msgeo_map.getZoom());
		GEvent.addListener(marker, "dragend", function(){
			var coords = marker.getLatLng();
			setLatLng(coords.lat(), coords.lng());
			msgeo_map.panTo(new GLatLng(coords.lat(), coords.lng()), msgeo_map.getZoom());
			resetSearch();
			} );
		GEvent.addListener(marker, "dragstart", function(){
			marker.closeInfoWindow();
		});
	}
	
});