var debug = false;

var move_duration = 500;
var highlight_duration = 1000;
var map_move_easing = "swing";

var map_id_extension = "_map";
var map_id_marker_extension = "_marker";

var max_modal_height = 300;

var index_char_limit = 3;

jQuery.fn.centerMapOnXY = function(x,y, container) {
	var currentMapCenterX = (container.width()/2) - $(this).position().left;
	var currentMapCenterY = (container.height()/2) - $(this).position().top;
	var left = $(this).position().left + (currentMapCenterX - x);
	var top = $(this).position().top + (currentMapCenterY - y);
	$(this).moveBox(container, top, left, move_duration, map_move_easing);
}

jQuery.fn.moveBox = function(container, top, left, duration, easing) {
	$(this).animate({
		top: top + "px",
		left: left + "px"
	  }, duration, easing);
}

jQuery.fn.bindModalWindow = function(trigger) {
	$(this).jqm({
		overlay: 0,
		trigger: trigger,
		closeClass:"jqmCloser"
	});
}

// outline map areas, css styles don't work on image map areas
jQuery.fn.highlightMap = function(bounding_box, coord_correction) {
	map_area_id = $(this);
	marker_id = "#" + map_area_id.attr("id") + map_id_marker_extension;

	// hide 'em all
	$("div[id$='" + map_id_marker_extension + "']").hide();

	if ($(marker_id + ":hidden").length > 0) {
		// if the div has already been created, just show it
		$(marker_id).show();
	}
	else {
		// get the coords from the appropriate area tag
		coords = map_area_id.attr("coords").split(",");
		// we need to add the margin on the mover div to our outline divs
		// so they align properly with the map areas
		L = (+coords[0]) + (+coord_correction);
		T = (+coords[1]) + (+coord_correction);
		W = coords[2] - coords[0];
		H = coords[3] - coords[1];
		// get rid of the initial '#' for the ID when creating new div
		marker = $('<div id="' + marker_id.substr(1) + '" class="map_marker half_transp"></div>');
		marker.appendTo(bounding_box).css({"left":L+"px", "top":T+"px", "width":W+"px", "height":H+"px" });
	}
}

$(document).ready(function(){

	// check for js=0 in the QS
	// abort scripts if we find it
	use_js = $.getQueryString({id:"js", defaultvalue:1});

	// the '+' converts the QS str into an int
	if (!+use_js) {
		return false;
	}

	// load dynamic stylesheet
	$.include('style/map_dynamic.css');

	// grab some DOM elements we will use a lot
	var test_div = $("#test");
	var top = $("#top");
	var mainBody = $("#mainBody");
	var mapContainer = $("#mapContainer");
	var map = $("#map");
	var hover_menu = $("#hover_menu");
	var search_results = $("#search_results");

	var current_cursor = "";
	var hover_menu_width = 250;

	var popupCenterOffset = [250,100];
	var popupPadding = [-10,10];
	var popup_z = 3000;

	var temp_inline_ajax_section_height = "100px";

	var ajax_directions_get_sections = "div.plain";
	var map_img_margin = map.css("padding-left").replace(/px/i,"");

	// we hide the mainBody and show the loader bar in index.html <script>
	// bring back the map on full load
	$(window).load(function() {
		$("#loader").fadeOut(500);
		$("#mainBody").fadeIn(1000);
	});

	Array.prototype.unique = function () {
		var r = new Array();
		o:for(var i = 0, n = this.length; i < n; i++)
		{
			for(var x = 0, y = r.length; x < y; x++)
			{
				if(r[x]==this[i])
				{ continue o; }
			}
			r[r.length] = this[i];
		}
		return r;
	}

	Array.prototype.lower = function (map_func) {
		for(var i = 0, n = this.length; i < n; i++)
		{
			this[i]=map_func(this[i]);
		}
		return this;
	}

	String.prototype.capitalize = function () {
		return this.substring(0,1).toUpperCase() + this.substring(1,this.length);
	}

	var bindMapLocationLink = function(bind_to, link_to_id) {
		$(bind_to).click(function() {
			map_area = link_to_id + map_id_extension;
			map_marker = map_area + map_id_marker_extension;
			coords = $(map_area).attr("coords").split(",");
			$(map).centerMapOnXY(parseInt(coords[0],10) + popupCenterOffset[0], parseInt(coords[1],10) + popupCenterOffset[1], mapContainer);
			$(map_area).highlightMap(map, map_img_margin);
			return false;
		})
	}

	var bindInfoPopupLink = function(bind_to) {
		$(bind_to).toggle(function() {
			directions = $(this).parent(".location");
			directions_content = $(this).after('<div class="directions_content"></div>').nextAll(".directions_content");
			ajax_url = $(this).attr("href");
			directions_content.height(temp_inline_ajax_section_height).addClass("spinner");

			the_stuff = $.get(ajax_url, function(data) {
				// get the directions, but NOT the embedded google maps
				directions_content.html($(data).find("div#directions").children(":not(div.graphic-map)"));
				directions_content.height("auto").removeClass("spinner");
			});

			return false;
		},
		function() {
			directions_content = $(this).nextAll(".directions_content").hide();
		});
	}

	var setMapSize = function(top_spacing) {
		h = $(window).height() - (top_spacing);
		w = $(window).width();
		$("#mainBody, #mapContainer").css({height:h,width:w});
	}

	// do some initial set up for the dynamic map
	$("#map_locations").appendTo("#map");

	var top_row_height = top.height();
	// set map size and keep it resized
	setMapSize(top_row_height);
	$(window).bind('resize', function() {
		setMapSize(top_row_height);
	});

	/* prepare our map location data for searching */
	var lower = function(t) {
		if (t.length > 3) {
			return t.toLowerCase()
		}
		else return t;
	}
	var trim = function(t) {
		if (!t || t=="" || t==false) {
			return false;
		}
		else {return t;}
	}
	var limit = function(t) {
		if (t.length <= index_char_limit) {
			return false;
		}
		else {return t;}
	};
	var make_words = function(t) {
		// Break up 'slashed' phrases,
		// then get rid of any other non-word characters
		t = t.toString().replace(/\//g, ' ');
		return t.replace(/\W/g, '');
	}

	// We have to manually add spacing to the some of the text in the map locations.
	// Otherwise, IE smashes everything together and we end up with
	// lots of meaningless compound words
	$("#map_locations *").append(" ");

	txt = $("#map_locations").text().split(/[\s,]/g);

	txt = jQuery.map(txt, trim);
	// we do limit() before make_words() so building IDs stay in the list,
	// even though they are less than the character limit
	// eg. (CA)
	txt = jQuery.map(txt, limit);
	txt = jQuery.map(txt, make_words);
	txt = jQuery.map(txt, lower);
	txt = txt.sort().unique();

	var modalOnShow = function(h) {
		/* callback executed when a trigger click. */
		h.w.addClass("vis");
		map_popup = "#" + h.w.attr("id");
		map_area = map_popup + map_id_extension;
		map_marker = map_area + map_id_marker_extension
		// highlight the map area and add new popup trigger to the highlighter
		$(map_area).highlightMap(map, map_img_margin);
		t = $(map_marker).css("top");
		l = $(map_marker).css("left");
		w = $(map_marker).width();
		h.w.css({'top':parseInt(t,10) + popupPadding[1],'left':parseInt(l,10) + parseInt(w,10) + popupPadding[0],'z-index':popup_z++});
		h.w.fadeIn("fast");
		h.w.dropShadow({left:7,top:7,opacity:.9});
	}

	var modalOnHide = function(h) {
		/* callback executed on window hide. Hide notice, overlay. */
		h.w.removeClass("vis");
		h.w.fadeOut("fast");
		h.w.removeShadow();
		$(".map_marker").hide();
	}

	// get our modal windows ready
	var closer = '<a class="jqmCloser" href="#"><img src="images/closer-icon.gif" /></a>';
	$(".location").addClass("jqmWindow").prepend(closer).each(function() {
		if ($(this).height() > 	max_modal_height) {
			$(this).height(max_modal_height);
		}
	});

	// set up the location window behavior
	$("map[name=SHCParkMap] area[href]").each(function() {
		href = $(this).attr("href").substr(1) + map_id_extension;
		$(this).attr("id", href);
		win = $($(this).attr("href"));
		win.bindModalWindow("#" + href);
		win.jqm({onShow:modalOnShow, onHide:modalOnHide});
	});

	// set up inline loading of driving and travel directions
	// this has to run AFTER the modal windows are set up
	var ajax_directions_links = $("#navigation li a.ajax");
	ajax_directions_links.each(function() {
		name = $(this).attr("name");
		if (name != "") {
			map_popup = "#" + name;
			bindMapLocationLink($(this), map_popup);
			$(map_popup).jqmAddTrigger($(this));
		}
		bindInfoPopupLink($(this));
	})

	// Set up the inline direction loaders
	$(".directions a").each(function() {
		bindInfoPopupLink($(this));
	})

	// Set up autocomplete on the search box
	$("#q").autocomplete({
		data: txt
	});
	$("#q").autocomplete("result", function(event, data, formatted){
		mapSearch(data);
		return false;
	});

	// search in contents of map locations
	var mapSearch = function(search_text) {
		// remove any existing search highlights
		$("#map_locations .highlight").removeClass("highlight");

		// look for both capitalized and lower case version of search term
		search_terms = Array(search_text.toString(), search_text.toString().capitalize());
		found = false;
		// build an array of location items that match our term
		for (i = 0; i < search_terms.length; i++) {
			// highlight appropriate search terms, kind of
			if (found.length > 0) {
				these = $("#map_locations *:contains('" + search_terms[i] + "')").addClass("highlight").parent().removeClass("highlight").parents(".location");
				if (these.length > 0) {
					found.add(these);
				}
			}
			else {
				found = $("#map_locations *:contains('" + search_terms[i] + "')").addClass("highlight").parent().removeClass("highlight").parents(".location");
			}
		}

		search_results.show().html('<h3>Search Results for ' + search_text + '</h3>');
		search_html = $('<ul></ul>');

		found.each(function() {
			parent_id = $(this).attr("id");
			if (parent_id != "") {
				parent_id = "#" + parent_id;
				parent_title = $(parent_id).find(".title").html();
				parent_desc = $(parent_id).find(".description").html() || "";
				search_html.append('<li><a href="' + parent_id + '">' + parent_title + '</a><br/><span class="result_desc">' + parent_desc + '</span></li>');
			}
		});

		search_results.append(search_html);

		$("#search_results li a").each(function() {
			href = $(this).attr("href");
			// only grab the anchor part of the href
			href = href.substr(href.indexOf('#'));
			bindMapLocationLink($(this), href);
			$(href).jqmAddTrigger($(this));
		});
	}

	// add draggable behaviors to map
	map.draggable({
		start: function(ev, ui) {
			current_cursor = $(this).css("cursor");
			$(this).css({cursor:"move"});
		},
		stop: function(ev, ui) {
			$(this).css({cursor:current_cursor});
		},
		// keep from dragging when clicking on a popup window or popup window scrollbar
		cancel: '.jqmWindow'
	});
	hover_menu.draggable({handle:$(".draggable")});

	// center map on mouse double click
	map.dblclick(function(e) {
		var map_x = e.pageX - $(this).offset().left;
		var map_y = e.pageY - $(this).offset().top;
		$(this).centerMapOnXY(map_x, map_y, mapContainer);
	});

});
