/* jQuery plugin for URL parameters */

jQuery.query = function(s) {
    var r = {};
    if (s) {
        var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
				q = q.replace(/#.*/, ''); // remove anchor
				q = q.replace(/\&$/, ''); // remove the trailing &
        jQuery.each(q.split('&'), function() {
            var splitted = this.split('=');
            var key = splitted[0];
            var val = splitted[1];
			// convert %20 and + into spaces
			val = decodeURI(val);
			val = val.replace(/\+/g,' ');
            // convert numbers
            if (/^[0-9.]+$/.test(val)) val = parseFloat(val);
            // convert booleans
            if (val == 'true') val = true;
            if (val == 'false') val = false;
            // ignore empty values
            if (typeof val == 'number' || typeof val == 'boolean' || val.length > 0) r[key] = val;
        });
    }
    return r;
};

/* Map stuff */

var map, map_one, map_two, focus_marker, focus_marker_one, focus_marker_two, target_marker, current_focus_text, current_target_text, geocoder, fillOverlay, lineOverlay;
var default_focus_text = "where are you?";
var default_target_text = "and where are you going?";
var default_texts = [default_focus_text, default_target_text, "address 1", "address 2", "", null];

current_focus_text = default_focus_text;
current_target_text = default_target_text;

function resizeMap() {
	var height = document.body.clientHeight ? document.body.clientHeight : window.innerHeight;
	if($("#map_canvas").size()) {
		$("#map_canvas").height(height * 0.70);		
	} else {
		$("#map_canvas_one").height(height * 0.70);		
		$("#map_canvas_two").height(height * 0.70);
	}
}

function initMap(map_id, cLat, cLng, zoomLevel) {
	if(map_id == "map_canvas") {
		var current_map = new GMap2(document.getElementById(map_id), {	googleBarOptions: { 
																		suppressInitialResultSelection: true,
																		showOnLoad: true, 
																		onIdleCallback: function() { 
																			window.setTimeout(function() {
																				$('.gsc-input').each( function() { 
																					try { this.blur(); } catch(err) { }
																					try { $(this).addClass('untouched'); } catch(err) { }
																					try { $(this).focus(function() { $(this).removeClass('untouched'); }); } catch(err) { }
																					try { this.value = "Find nearby..."; } catch(err) { }
																				} )
																			}, 15); } 
																  } } );
	} else {
		var current_map = new GMap2(document.getElementById(map_id));
	}
	if(cLat == null) cLat = 40.731706;
	if(cLng == null) cLng = -74.003178;
	if(zoomLevel == null) zoomLevel = 13;

	current_map.setCenter(new GLatLng(cLat, cLng), zoomLevel);
	
	var customUI = current_map.getDefaultUI();
	customUI.controls.scalecontrol = false;
	current_map.setUI(customUI);
	
	if(map_id == "map_canvas") current_map.enableGoogleBar();
	
	resizeMap();
	geocoder = new GClientGeocoder();
	return current_map;
}

function refocus(updateMap) { 
	var address = $("#address").val();
	if($(default_texts).index(address) >= 0 || address == current_focus_text) return false;
	current_focus_text = address;
	setAddress(map, address, 'focus', updateMap, 'focus_marker');
	return false;
}

function retarget(updateMap) {
	var address = $("#target").val();
	if(address == current_target_text) return false;
	if($(default_texts).index(address) >= 0) {
		if(target_marker != null) {
			map.removeOverlay(target_marker);
			target_marker = null;
		}
		return false;
	}
	current_target_text = address;
  	setAddress(map, address, 'target', updateMap);
	return false;
}

function reOverlay(current_map, current_focus_marker, id) {
	var pointSW = new GLatLng(40.525867,-74.057895);
	var pointNE = new GLatLng(40.927315,-73.711668);

	var partition = Math.floor(id / 1000);
	
	current_map.clearOverlays();
	
	if(fillOverlay != null) current_map.removeOverlay(fillOverlay);	
	fillOverlay = new GGroundOverlay("http://nyc-heatmap-images.s3.amazonaws.com/" + partition + "/" + id + "_fill.png", new GLatLngBounds(pointSW, pointNE));
	current_map.addOverlay(fillOverlay);
	
	if(lineOverlay != null) current_map.removeOverlay(lineOverlay);	
	lineOverlay = new GGroundOverlay("http://nyc-heatmap-images.s3.amazonaws.com/" + partition + "/" + id + "_lines.png", new GLatLngBounds(pointSW, pointNE));
	current_map.addOverlay(lineOverlay);
	
	if(current_focus_marker != null) {
		current_map.removeOverlay(current_focus_marker);
		current_map.addOverlay(current_focus_marker);
	}
	if(target_marker != null) {
		current_map.removeOverlay(target_marker);
		current_map.addOverlay(target_marker);
	}
}

function showSlowLoadingDialog() {
	try {
		if($.cookie("seen_slow_loading_dialog") != "true") {
			$("#slow_loading_dialog").dialog().dialog("open");
			$.cookie('seen_slow_loading_dialog', "true");
		}
	} catch(err) {}
}

function setAddress(current_map, address, marker_type, updateMap, focus_marker_name) {
  if(updateMap == null) updateMap = true;
  eval("var current_focus_marker = " + focus_marker_name);
	
  geocoder.getLatLng(
    address + ", ny, ny",
    function(point) {
      if (!point) {
        alert(address + " not found");
      } else {
		$.getJSON("/point?latitude=" + point.lat() + "&longitude=" + point.lng() + "&type=" + marker_type, 
			function(json){ 
				if(marker_type == "focus" || marker_type == "compare") reOverlay(current_map, current_focus_marker, json.point.id);
			});
			
		if(marker_type == "focus" || marker_type == "compare") {
			$("#targeter").css("visibility","visible");
			if(current_focus_marker != null) current_map.removeOverlay(current_focus_marker);
			current_focus_marker = new GMarker(point);
			if(marker_type == "focus") showSlowLoadingDialog();
       		current_map.addOverlay(current_focus_marker);
			GEvent.addListener(current_focus_marker, "click", function() {
			    current_focus_marker.openInfoWindowHtml(address);
			});
		} else if(marker_type == 'target') {
			if(target_marker != null) current_map.removeOverlay(target_marker);
			target_marker = new GMarker(point);
       		current_map.addOverlay(target_marker);
			GEvent.addListener(target_marker, "click", function() {
			    target_marker.openInfoWindowHtml(address);
			});
			
		}

		if(updateMap) reZoom(current_map, current_focus_marker);
		eval(focus_marker_name + " = current_focus_marker");
      }
    }
  );
}

function reZoom(map, current_focus_marker) {
	if(focus_marker == null && target_marker == null && current_focus_marker == null) return false;
	
	var bounds = new GLatLngBounds();

	if(current_focus_marker != null) bounds.extend(current_focus_marker.getLatLng());
	if(focus_marker != null) bounds.extend(focus_marker.getLatLng());
	if(target_marker != null) bounds.extend(target_marker.getLatLng());
	
	var zoomLevel = map.getBoundsZoomLevel(bounds);
	if(zoomLevel < map.getZoom()) map.setZoom(zoomLevel);
	map.setCenter(bounds.getCenter());
}

function getFocusText() {
	var focus_text = $("#address").val();
	if(focus_text == default_focus_text) return null;
	return focus_text;
}

function getTargetText() {
	var target_text = $("#target").val();
	if(target_text == default_target_text) return null;
	return target_text;	
}

function showLink() {
	urlString = getLink();
	var page_link = $("#page_link");
	page_link.val(urlString);
	$("#page_link_title").text(getTitle());
	$("#page_link_dialog").dialog().dialog('open');
	page_link.focus();
	page_link.select();
}

function getLink() {
	var domain = "http://www.triptropnyc.com/";
	var urlString;
	if($("#address").size()) {
		var f_value = $("#address").val();
		var t_value = $("#target").val();
	
		if(f_value == default_focus_text) f_value = "";
		if(t_value == default_target_text) t_value = "";
		f_value = f_value.replace(/ /g,'+');
		t_value = t_value.replace(/ /g,'+');
	
		urlString = domain + "?f=" + encodeURI(f_value) + "&t=" + encodeURI(t_value) + "&z=" + map.getZoom() + "&lat=" + map.getCenter().lat() + "&lng=" + map.getCenter().lng();
	} else {
		var a1_value = $("#address_1").val();
		var a2_value = $("#address_2").val();
		urlString = domain + "compare?a1=" + encodeURI(a1_value) + "&a2=" + encodeURI(a2_value);
	}
	return urlString;
}

function shareOnFB() {
	window.open("http://www.facebook.com/sharer.php?u=" + getLink() + "&t=" + getTitle() + ": triptrop nyc" );
}

function getTitle() {
	var titleText;
	
	if($("#address").size()) {
		var focus = getFocusText();
		var target = getTargetText();
	
		if(target == null) {
			titleText = focus;
		} else {
			titleText = focus + " to " + target
		}
	
		titleText = titleText + " | travel time map";
	} else {
		var a1_value = $("#address_1").val();
		var a2_value = $("#address_2").val();
		titleText = a1_value + " versus " + a2_value + " | subway travel time map"
	}
	return titleText;
}

function compare() {
	var address_1 = $("#address_1").val();
	var address_2 = $("#address_2").val();
	if($(default_texts).index(address_1) >= 0 || $(default_texts).index(address_2) >= 0) return false;
	setAddress(map_one, address_1, 'compare', true, 'focus_marker_one');
	setAddress(map_two, address_2, 'compare', true, 'focus_marker_two');
	
	return false;
}

function checkSelectedText() {
	var obj = $(this);
	if($(default_texts).index(obj.val()) >= 0) obj.val("");
	obj.removeClass("untouched");
}

function setText(item, value) {
	item = $(item);
	item.val(value);
	item.removeClass("untouched");
}

$(document).ready(function() {
	resizeMap();
	$(window).resize(resizeMap);

	$("#get_page_link").click(showLink);
	$("#slow_loading_dialog").dialog({ autoOpen: false, minHeight: 30, buttons: { "Okay, okay, I got it!": function() { $(this).dialog("close"); } }  });
	$("#page_link_dialog").dialog({ autoOpen: false, minHeight: 30, modal: true, minWidth : 400, width: 400, buttons: { "Close": function() { $(this).dialog("close"); }, "Share on Facebook": shareOnFB, "Open in new window": function() { window.open(getLink()); } }  });

	var parameters = $.query(location.href);

	$(".map").each( function() {
		eval(this.id.replace('_canvas','') + " = initMap(this.id, parameters['lat'], parameters['lng'], parameters['z']);");
	});
	
	if($("#address").size()) {
		if(parameters['f']) setText("#address", parameters['f']);
		if(parameters['t']) setText("#target", parameters['t']);
		refocus(false);
		retarget(false); 
		$("#address").focus(checkSelectedText);
		$("#target").focus(checkSelectedText)
	} else {
		if(parameters['a1']) setText("#address_1", parameters['a1']);
		if(parameters['a2']) setText("#address_2", parameters['a2']);
		compare();
		$("#address_1").focus(checkSelectedText);
		$("#address_2").focus(checkSelectedText);
	}
	
	$("#link_footnote_g").click(function() { $("#footnote_g").effect("highlight", {}, 4000); })
	$("#link_footnote_method").click(function() { $("#footnote_method").effect("highlight", {}, 4000); })
});