// starting on window.load instead of document.ready is supposed to delay until all media is loaded
$( window).load(function(){
	// all the map functionality has been moved inside this function, since we have to defer executing it until the ajax call is complete
	var activate_map = function() {
		// remember the size of the different map sclaes
		var full_map_size = {
			width: $('#map-image').width(),
			height: $('#map-image').height()
		};
		var navigator_size = {
			width: $('#map-navigator').width(),
			height: $('#map-navigator').height()
		};
		var nano_size = {
			width: $('#map-nano').width(),
			height: $('#map-nano').height()
		};

		var now_dragging_map = false;
		var now_dragging_loupe = false;
		var last_drag_position = { x: 0, y: 0};
		var start_drag_position = { x: 0, y: 0};
		var sidebar_hidden = false;

		if (window.for_iframe) {
		    sidebar_hidden = true;
		}

		var navigator_hidden = false;
		var hide_navigator_timeout = null;
		var dragged_map_more_than_a_little = false;
		var ward_highlighted_prior_to_drag = null;
		var massmap_active = false;
		var massmap_pending;

		// show_map_position in full map coordinates; moves map and two loupes
		function center_map_on_position( x, y)
		{
			var map = $('#map');
			var map_image = $('#map-image');
			var left = x - (map.width() / 2);
			var top = y - (map.height() / 2);
			var loupe = $('#loupe');
			var loupe_nano = $('#loupe-nano');
			var loupe_size = { width: loupe.width(), height: loupe.height()};
			var loupe_nano_size = { width: loupe_nano.width(), height: loupe_nano.height()};
			var map_size = { width: map.width(), height: map.height()};
			if ( left < 0) left = 0;
			if ( top < 0) top = 0;
			if ( left >= (full_map_size.width - map_size.width))
				left = full_map_size.width - (map_size.width + 1);
			if ( top >= (full_map_size.height - map_size.height))
				top = full_map_size.height - (map_size.height + 1);
			map_image.css('left', (-left) + 'px');
			map_image.css('top', (-top) + 'px');
			var o_left = left;
			var o_top = top;

			left = o_left * ( navigator_size.width / full_map_size.width);
			top = o_top * ( navigator_size.width / full_map_size.width);
			if ( left < 0) left = 0;
			if ( top < 0) top = 0;
			if ( left >= (navigator_size.width - loupe.width))
				left = navigator_size.width - (loupe.width + 1);
			if ( top >= (navigator_size.height - loupe.height))
				left = navigator_size.height - (loupe.height
					 + 1);

			loupe.css('left', (left) + 'px');
			loupe.css('top', (top) + 'px');
			loupe.css('opacity', .33); // force IE to redraw it
			show_navigator();

			left = o_left * ( nano_size.width / full_map_size.width);
			top = o_top * ( nano_size.width / full_map_size.width);
			if ( left < 0) left = 0;
			if ( top < 0) top = 0;
			if ( left >= (nano_size.width - loupe_nano.width))
				left = nano_size.width - (loupe_nano.width + 1);
			if ( top >= (nano_size.height - loupe_nano.height))
				left = nano_size.height - (loupe_nano.height
					 + 1);

			loupe_nano.css('left', (left) + 'px');
			loupe_nano.css('top', (top) + 'px');
			massmap_schedule_hide();
		}

		// move map relative to its current position
		function move_map( h, v)
		{
			var map = $('#map');
			var map_image = $('#map-image');
			var x = -map_image.position().left;
			var y = -map_image.position().top;

			x = x + map.width() / 2;
			y = y + map.height() / 2;

			center_map_on_position( x + h, y + v);
		}

		// begin click or drag in full (large) map
		$('#map,#massmap area').mousedown( function (e) {
			if ( !massmap_active) ward_highlighted_prior_to_drag = null;
			if ( !$.browser.msie)
			{
				now_dragging_map = true;
				dragged_map_more_than_a_little = false;
				last_drag_position.x = e.pageX;
				last_drag_position.y = e.pageY;
				$('#map-image, #massmap area').css('cursor','move');
			}
			e.preventDefault();
			hide_sidebar();
			massmap_hide_floater();
			return false;
		});

		// begin click or drag in navigator (medium) map
		$('#loupe').mousedown( function (e) { e.preventDefault(); return true; });
		$('#map-navigator').mousedown( function (e) {
			var offset = $('#map-navigator').offset();
			var x = e.pageX - offset.left, y = e.pageY - offset.top;
			center_map_on_position( x * 9.25, y * 9.25);

			now_dragging_loupe = true;
			last_drag_position.x = e.pageX;
			last_drag_position.y = e.pageY;
			start_drag_position.x = e.pageX;
			start_drag_position.y = e.pageY;
			e.preventDefault();
			hide_sidebar();
			return false;
		});

		$('#map-navigator').mouseleave( function (e) {
			reset_navigator_timeout( true);
		});

		$("#massmap area").click( function (e) {
			if (dragged_map_more_than_a_little)
			{
				// a click in an "area" within the full map might have just been a drag
				e.preventDefault();
				dragged_map_more_than_a_little = false;
				return false
			}
			return true;
		});

		// track mouse up anywhere -- could occur outside of window, even
		$().mouseup( function (e) {
			if ( now_dragging_map || now_dragging_loupe)
			{
				// an attempt to work around IE bug
				// if (!$.browser.msie)
				// 	e.preventDefault();
			}
			if ( now_dragging_map)
			{
				reset_navigator_timeout( true);
				towns_floater_position( null);
			}
			if ( now_dragging_loupe)
			{
				// reset_navigator_timeout( false);
				// should we check to see if we are now out of the navigator?
			}
			now_dragging_map = false;
			now_dragging_loupe = false;
			$('#map-image').css('cursor','auto');
			$('#massmap area').css('cursor','pointer');
		});

		$('#map-navigator').mousemove( function( e) {
			if ( now_dragging_loupe) {
				var offset = $(this).offset();
				var x = e.pageX - offset.left, y = e.pageY - offset.top;
				center_map_on_position( x * 9.25, y * 9.25);

				e.preventDefault();
			}
			// reset_navigator_timeout( false);
		});

		$('#map-nano,#map-navigator').mouseenter( function( e) {
			/* IE BUG **********
				trying to fix bug, where IE (or jQuery) will fire this when mouse is entering
				#massmap area, even passing #map-navigator as this.
			*/
			show_navigator();
		});

		// track the mouse movement anywhere -- could be a drag outside of the window
		$().mousemove( function( e) {
			var drag_x = e.pageX - last_drag_position.x;
			var drag_y = e.pageY - last_drag_position.y;
			var result = true;
			if ( now_dragging_map) {
				if ( Math.abs( e.pageX - start_drag_position.x) > 1 || Math.abs( e.pageX - start_drag_position.y) > 1)
				{
					dragged_map_more_than_a_little = true;
				}
				move_map( -drag_x, -drag_y);
				result = false;
				e.preventDefault();
			}
			if ( now_dragging_loupe)
			{
				result = false;
				e.preventDefault();
			}
			last_drag_position.x = e.pageX;
			last_drag_position.y = e.pageY;
			return result;
		});

		if (window.for_iframe) {
		    $().mouseout( function( e) {
			    var result = true;
			    if ( (e.pageX <= 0 ) ||
				 ( e.pageX >= $('#map-container').width()) ||
				 (e.pageY <= 0 ) ||
				 ( e.pageY >= $('#map-container').height()))
				{
				    now_dragging_loupe = false;
				    now_dragging_map = false;
				    result = false;
				    e.preventDefault();
				}
			    return result;
			});
		}

		function hide_sidebar()
		{
			if ( !sidebar_hidden) {
				$('#map').animate({width:'974px'});
				$('#map-sidebar').css({left: '650px', width: '333px'});
				$('#map-sidebar').animate({left: '981px', width: '10px'});
				$('#map-sidebar .contents').animate({opacity: 0});
				$('#map-sidebar .expand').css( {opacity: 0, visibility: 'visible'});
				$('#map-sidebar .expand').animate( {opacity: 1});
				sidebar_hidden = true
			}
		}

		function show_sidebar()
		{
			if ( sidebar_hidden)
			{
				$('#map').animate({width:'641px'});
				$('#map-sidebar').animate({left: '650px', width: '333px'});
				$('#map-sidebar .contents').animate({opacity: 1});
				$('#map-sidebar .expand').animate( {opacity: 0});
				sidebar_hidden = false;
			}
			massmap_schedule_hide();
		}

		function hide_navigator( instant)
		{
			if ( !navigator_hidden)
			{
				if ( !instant)
				{
						$('#map-navigator').animate( {opacity: 0.0}, 250, null, function() { if ( navigator_hidden) $(this).toggle( false); });
						$('#map-nano').toggle(true).animate( {opacity: .5}, 250, null, function() {});
				} else
				{
					$('#map-navigator').toggle( false).css('opacity', 0);
					$('#map-nano').css('opacity', .5).toggle(true);
				}
				navigator_hidden = true;
			}
		}

		function show_navigator( instant)
		{
			reset_navigator_timeout();
			if ( navigator_hidden)
			{
				if ( !instant)
				{
					$('#map-navigator').toggle(true).animate( {opacity: .75}, 250, null, function() {  });
					$('#map-nano').animate( {opacity: 0.0}, 250, null, function() { if ( !navigator_hidden) $(this).toggle( false); });
				} else
				{
					$('#map-nano').toggle( false).css('opacity', 0);
					$('#map-navigator').css('opacity', .75).toggle(true);
				}
				navigator_hidden = false;
			}
			massmap_schedule_hide();
		}

		function reset_navigator_timeout( reset)
		{
			if ( typeof reset == 'undefined') reset = false;
			if ( hide_navigator_timeout != null)
			{
				clearTimeout( hide_navigator_timeout);
				hide_navigator_timeout = null;
			}
			if ( reset == true)
				hide_navigator_timeout = setTimeout( hide_navigator, 1000);
		}


		/* pop up info for each ward (votenoma theme-script.js) */
		function massmap_cancel_hide () {
		  if (massmap_pending) {
		    clearTimeout (massmap_pending);
		    massmap_pending = null;
		  }
		}

		function massmap_hide_floater () {
		  massmap_cancel_hide ();
			if ( $.browser.msie)
				$("#towns_floater").toggle(false);
			else
				$("#towns_floater").fadeOut("fast");
		  massmap_active = false;
		}

		function massmap_schedule_hide () {
		  massmap_cancel_hide ();
		  massmap_pending = setTimeout (massmap_hide_floater, 50);
		}


		function towns_floater_position( area)
		{
		    var floater = $("#towns_floater");
			if (area == null) area = ward_highlighted_prior_to_drag;
			if ( area == null) return;
			reset_navigator_timeout( true);
			ward_highlighted_prior_to_drag = area;
		    massmap_active = true;
		    massmap_cancel_hide ();
		    floater.show();
			// get bounding box of town
			var coords = $(area).attr('coords').split(',');
			var left = null;
			var top = null;
			var right = null;
			var bottom = null;
			var map_image = $('#map-image');
			var map_container_offset = $('#map-container').offset();
			var left_or_right = 'right';
		        var h_center;

		        if (window.for_iframe) {
			    h_center = $('#map').width() / 2 - 10;
			} else {
			    if (sidebar_hidden) {
				h_center = 480;
			    } else {
				h_center = 310;
			    }
			}

			for ( i = 0; i < coords.length; i+= 2)
			{
				coords[i] = parseInt( coords[i]);
				coords[i+1] = parseInt( coords[i+1]);
				if ( left == null)
				{
					left = coords[i];
					right = coords[i];
					top = coords[i+1];
					bottom = coords[i+1];
				} else
				{
					if ( left > coords[i]) left = coords[i];
					if ( right < coords[i]) right = coords[i];
					if ( top > coords[i+1]) top = coords[i+1];
					if ( bottom < coords[i+1]) bottom = coords[i+1];
				}
			}
			if ((((left+right)/2) + map_image.position().left) > h_center) {
				left = left - (floater.width() + 40);
				left_or_right = 'left';
			}
			else {
				left = right + 2;
			}
			if ( (map_image.position().left + left) < 0) left = 0 - map_image.position().left;
			var info_top =  (top + map_image.position().top);
			var ideal_info_top = info_top;

			if ( info_top < 0) info_top = 0;
			if ( (info_top + floater.height()) > $('#map').height()) info_top = $('#map').height() - floater.height();
			var background_top = (bottom - top - 40) / 2;
			background_top = background_top - (info_top - ideal_info_top);

			if ( background_top < 1) background_top = 1;
			if ( background_top > (floater.height() - 39)) background_top = floater.height() - 39;
			var args = {
				position: 'absolute',
				left: (left + map_image.position().left) + 'px',
				top: info_top + 'px',
				backgroundPosition: ((left_or_right == 'left') ? ('right') : ('left')) + ' -' + (381 - background_top) + 'px'
				};
			floater.css( args);
			floater.removeClass('left right');
			floater.addClass(left_or_right);
			$('#towns_floater .towns_floater_content').css('borderStyle',
				left_or_right == 'left' ? 'solid none solid solid' : 'solid solid solid none');
		}

		function massmap_mouseover (ev) {
			if ( now_dragging_map) return;

			var href = "" + ev.target.href;
			var town_code = href.replace (new RegExp ('.*town_code='), '');

			if (town_code >= 1 && town_code <= 351) {
				var floater_content = $('#towns_floater .towns_floater_content');

				floater_content.html($("#map"+town_code).html());
				floater_content.find('span.img-placeholder').each( function() {
					$(this).removeClass('img-placeholder');
					$(this).html('<img src="' + $(this).html() + '" class="' +
						$(this).attr("class") + '" />');
				})

				towns_floater_position( this);
			} else {
		    	massmap_active = false;
		  	}
		}

		function massmap_select_town (ev) {
		  var town_code = $("#town_code_selector").val();
		  if (town_code) {
		    $("#town_text").html($("#map"+town_code).html());

		    $("#town_text .map_more").html("<a target='_blank' href='towns.php?town_code="+town_code+"'>[click for more details]</a>");
		  }
		}

	    $("#massmap area").mouseover (massmap_mouseover);
	    // $("#massmap area").mouseout (massmap_schedule_hide);
		// $("area").mousedown( function(e) { console.log('area mousedown'); e.preventDefault(); return true;})
		// $("map").click( function(e) { console.log('map was clicked'); e.preventDefault(); return false;})
	    $("#town_code_selector").change (massmap_select_town);

		$('#map-sidebar .expand').click( function( e) {
			show_sidebar();
		});

		$('#towns_floater .towns_floater_content').mouseenter( massmap_schedule_hide);
		center_map_on_position( 2000, 677); // boston
		hide_navigator();
		if ( $.browser.msie) $('#map').css('cursor','pointer');
		// $('img[usemap]').maphilight();
		// show_navigator();
	};

	// load_and_activate_map: load & inject HTML for the map area & the popup info
	var load_and_activate_map = function() {
	    if ($('#map-image').size()) {
		$('#map-image').attr('src', 'massmap_color_test2.gif');
		$("#ajax-map-container").load("massmap.php", activate_map);
		// unbind the event (in case we turn on load-on-click, below)
		$("#map").unbind('mousedown', load_and_activate_map);
		return false;
	    }
	};
	
	// this is a hacky way to scroll the map to the correct starting position (since the function is now delayed until the ajax call is complete)
	$('#map-image').css({
		left: '-1679.5px',
		top: '-417px'
	});

	// load map on mouse down; would require some kind of feedback
	// $('#map').mousedown( load_and_activate_map);
	// or, just load the map, 
	if (window.for_iframe) {
	    activate_map();
	} else {
	    load_and_activate_map();
	}

});