

google.load("maps", "2.x");
google.load("jquery","1");

//if (typeof document.onselectstart!="undefined")-->
//{-->
//<!--	document.onselectstart = function() {return false;};-->
//<//!--}-->
//<!--		else-->
//<!--		{-->
//<!--			document.onmousedown = function(){return false;};-->
//<!--			document.onmouseup = function(){return true;};-->
//<!--		}-->
	
var MARKER_OFFSET_X = 20;
var MARKER_OFFSET_Y = -20;
var MIN_ZOOM = 2;
var MAX_ZOOM = 17;
var MOUSE_CLICK_TIME = 300;
var FIRST_YEAR = -3000;
var LAST_YEAR = 1000;
var YEAR_STEP = 100;
var YEAR_STEP_WIDTH = 80;
var TIMELINE_HEIGHT = 2;
var INITIAL_CURRENT_YEAR = -580;

var TIMELINE_FIRST_LINE_Y = 1;
var TIMELINE_LINE_HEIGHT = 5;
var TIMELINE_LINE_SPACE = 1;
var TIMELINE_LINE_DELTA = TIMELINE_LINE_HEIGHT + TIMELINE_LINE_SPACE;

var timeline;
var markers = [];
var cities;
var empires;
var regions = [];
var map;

var downAtPos = 0;
var downAtTime = 0;
var total_width = (LAST_YEAR-FIRST_YEAR);
var pixels_per_year = YEAR_STEP_WIDTH/YEAR_STEP;
var timelineMouseIsOver = 0;
var currentYear = null;
var cityMarkersVisible = true;
var regionsVisible = true;
var empiresLoaded = false;
var citiesLoaded = false;
var icon;
var currentMarker = null;
var currentTimeout = null;
var editRegionMenuItem;

var KEY = "ABQIAAAAE_4wAf_38kSijMOj1ebagxRra3JrZE2MVvgJYCt2HumSp15vaBSy18kGUvjPXly4FHNlIi4KevR-Og";		

function setCurrentYear( year )
{
	if ( currentYear==null ) return;
	if ( year!=currentYear )
	{
		currentYear = year;
		$("#current_year")
			.html( "<small>Loading ... </small>" + (currentYear<0 ? ((-currentYear)+'<small>BC</small>') : currentYear ));

		$.ajax({
			url: 'data.php5',
			data: { "action":"get_regions","year":currentYear },
			dataType: 'json',
			error: function(request,text,error){
				alert('get regions error ' + text);
				$("#current_year")
					.html( (currentYear<0 ? ((-currentYear)+'<small>BC</small>') : currentYear ));},
			success: function(data,text,request){
				for ( var i=0 ; i<regions.length ; i++ )
				{
					map.removeOverlay(regions[i].polygon);
				}

				regions = [];

				for ( var i=0 ; i<data.count ; i++ )
				{
					var points = [];
					var ps = data.regions[i].points.split(' ');
					for ( var j=0 ; j<ps.length ; j++ )
					{
						var ll = ps[j].split(',');
						var lat = parseFloat(ll[0]);
						var lng = parseFloat(ll[1]);
						if ( isNaN(lat) || isNaN(lng) ) continue;
						points.push( new GLatLng(lat,lng));
					}
					var color = '#000000';
					$(empires).children().each( function()
						{
							if ( $(this).data('gb_marker').data.id == data.regions[i].empire )
							{
								color = $(this).data('gb_marker').data.color;
								return false;
							}
						});
					data.regions[i].polygon = new GPolygon(points, color, 1, 1,color,0.5);
					regions.push(data.regions[i]);
					if ( !regionsVisible ) data.regions[i].polygon.hide();
					map.addOverlay(data.regions[i].polygon);						
				}
				$("#current_year")
					.html( (currentYear<0 ? ((-currentYear)+'<small>BC</small>') : currentYear ));}});
	}
	else
	{
		$("#current_year")
			.html( (currentYear<0 ? ((-currentYear)+'<small>BC</small>') : currentYear ));
	}

	$("#timeline > div.current")
		.css( { 'left' : yearToX(year) });

	$(cities).children().each( function(){
		if ( $(this).data('gb_marker') )
		{
			var marker = $(this).data('gb_marker');
			if ( cityMarkersVisible
					&& currentYear >= marker.data.from_year 
					&& currentYear <= marker.data.to_year )
			{
				marker.show();
			}
			else
			{
				marker.hide();
			}
		}});
}

function hideMarkerText(marker,time)
{
	if ( !time ) time = 300;
	currentTimeout = setTimeout("hideMarkerText2('"+marker.data.type+"',"+marker.data.id+")",time);
}

function hideMarkerText2( type,id )
{
	if ( currentMarker!=null && currentMarker.data.type==type && currentMarker.data.id==id )
	{
		$("#message").hide();
		if ( type=='empire' )
		{
			// highlight all the regions
			for ( var i=0 ; i<regions.length ; i++ )
			{
				if ( regions[i].empire==id )
				{
					regions[i].polygon.setStrokeStyle({ weight: 1 });
				}
			}
		}
	}
}

function showMarkerText(marker)
{
	currentMarker = marker;
	var markerOffset = map.fromLatLngToDivPixel(marker.getLatLng());
	var text = "<b>"+marker.data.name+"</b><br />";
	if ( marker.data.type=='city' )
	{
		text += marker.getLatLng().lat()+","+marker.getLatLng().lng()+"<br />";
	}
	else if ( marker.data.type=='empire' )
	{
		// highlight all the regions
		for ( var i=0 ; i<regions.length ; i++ )
		{
			if ( regions[i].empire==marker.data.id )
			{
				regions[i].polygon.setStrokeStyle({ weight: 2 });
			}
		}
	}
	if ( marker.data.from_year==-99999 ) text += "unknown";
	else if ( marker.data.from_year<0 ) text += (-marker.data.from_year)+"<small>BC</small>";
	else text += marker.data.from_year;
	text+= "&nbsp;-&nbsp;"
	if ( marker.data.to_year==99999 ) text += "unknown";
	else if ( marker.data.to_year<0 ) text += (-marker.data.to_year)+"<small>BC</small>";
	else text += marker.data.to_year;
	text += "<br />";
	text += "<a target='_new' href='http://en.wikipedia.org/wiki/Special:Search?search="+marker.data.name+"'>More&nbsp;Information</a>";

	$("#message_content")
		.html(text);
	$("#message")
	 	.css({ top:markerOffset.y+MARKER_OFFSET_Y, left:markerOffset.x+MARKER_OFFSET_X })
		.show();
}

function gotoMarker(marker)
{
	if ( marker.getLatLng().lat()!= map.getCenter().lat() && marker.getLatLng().lng()!= map.getCenter().lng() )
	{
		var moveEnd = GEvent.addListener(map, "moveend", function(){
			GEvent.removeListener(moveEnd); 
			map.setCenter(marker.getLatLng());
			showMarkerText(marker);});
		map.panTo(marker.getLatLng());
	}
	else
	{
		showMarkerText(marker);
	}
}

function init()
{
	var d = document.createElement("div"); 
	$(d).attr('id','header').appendTo(document.body);
	$(document.createElement("div")).html("map<i>.</i>belteshazzar<i>.</i>com").appendTo(d);

	$(document.createElement("div")).attr('id','window_mask').appendTo(document.body);
	$(document.createElement("div")).attr('id','popup').appendTo(document.body);
	
	initMap();
	initTimeline();
	initMenu();

	$('#window_mask').click( function() {
		$('#popup').hide();
		$('#window_mask').hide();});

	$(window).resize(function() {
		var height = $(window).height();
		var width = $(window).width();
		$('#map')
			.height(height-200)
			.width(width-200);
		$('#timeline')
			.css({ top: height-100 })
			.width(width-200);
		$('#timeline_mask')
			.css({ top: height-100 })
			.width(width-200);
		$('#menu')
			.height(height-100)
			.css({ left: width-200 });});
	window.onunload=GUnload;
}

function initMap()
{
	if (!GBrowserIsCompatible()) return;

	$(document.createElement("div")).attr('id','map').appendTo(document.body);
	$(document.createElement("div")).attr('id','coords').appendTo(document.body);
	var message = document.createElement("div");
	$(message).attr('id','message').appendTo(document.body);
	$(document.createElement("div")).attr('id','message_pointer').appendTo(message);
	$(document.createElement("span")).attr('id','message_content').appendTo(message);
	
	var d = document.createElement("div");
	$(d).attr('id','zoom').appendTo(document.body);
	$(document.createElement("img")).attr('id','zoom_out').attr('src','images/delete.png').attr('width',16).attr('height',16).appendTo(d);
	$(document.createElement("img")).attr('id','zoom_in').attr('src','images/add.png').attr('width',16).attr('height',16).appendTo(d);

	$(document.createElement("div")).attr('id','current_year').html("<small>Loading ...</small>").appendTo(document.body);

	d = document.createElement("div");
	$(d).attr('id','year_controls').appendTo(document.body);
	$(document.createElement("img")).attr('id','prev_year').attr('src','images/delete.png').attr('width',16).attr('height',16).appendTo(d);
	$(document.createElement("img")).attr('id','next_year').attr('src','images/add.png').attr('width',16).attr('height',16).appendTo(d);

	$('#map').height($(window).height()-200);
	$('#map').width($(window).width()-200);

	map = new google.maps.Map2(document.getElementById("map"));
	map.setCenter(new GLatLng(0,0), 2,G_SATELLITE_MAP);

	icon = new GIcon();
	icon.image = "images/red-pushpin.png";
	icon.iconSize=new GSize(16,16); 
	icon.iconAnchor=new GPoint(5,16);

	$("#message")
		.mouseenter( function() { clearTimeout(currentTimeout); } )
		.mouseleave( function() { hideMarkerText2(currentMarker.data.type,currentMarker.data.id); })
		.appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));
	GEvent.addListener(map, "dblclick", function( ){
		hideMarkerText2(currentMarker.data.type,currentMarker.data.id);});

	var d = document.createElement("div"); 
	$(d).attr('id','coords').appendTo('#map');
	
	GEvent.addListener(map,"mousemove",function( latlng ) {
		$("#coords").html("Lat/Lng: "+Math.round(latlng.lat()*100)/100 + "," + Math.round(latlng.lng()*100)/100); });
	
	$("#zoom_in").click(function(){
		if ( map.getZoom()==MAX_ZOOM) return;
		map.zoomIn();});

	$("#zoom_out").click(function(){
		if ( map.getZoom()==MIN_ZOOM) return;
		map.zoomOut();});
	
	$("#next_year").click(function(){
		setCurrentYear(currentYear+1);});

	$("#prev_year").click(function(){
		setCurrentYear(currentYear-1);});

}

function xToYear( x )
{
	return Math.round(x/pixels_per_year+FIRST_YEAR);
}

function yearToX( year )
{
	if ( year<FIRST_YEAR ) year = FIRST_YEAR;
	else if ( year>LAST_YEAR ) year = LAST_YEAR;
	return Math.round( (year - FIRST_YEAR)*pixels_per_year );
}

function layoutTimeline()
{
	$("#timeline div.marker").each( function() {
		$(this).css( { 'left': yearToX( $(this).data('gb_year') ), width:YEAR_STEP_WIDTH });});

	$("#timeline div.line").each( function() {
		var d = $(this).data('gb_marker').data;
		d.left = yearToX(d.from_year);
		d.right = yearToX(d.to_year);
		d.width = d.right-d.left;
		$(this).css({ left: d.left,width:d.width});});

	$("div.current")
		.css( { 'left' : yearToX( currentYear ) })
}

function initTimeline()
{
	timeline = document.createElement("div");
	$(timeline).attr('id','timeline').width($(window).width()-200).css({ top: $(window).height()-100 }).appendTo(document.body);

	var timeline_mask = document.createElement("div");
	$(timeline_mask).attr('id','timeline_mask').width($(window).width()-200).css({ top: $(window).height()-100 }).appendTo(document.body);
	
	$(timeline_mask).mousedown(function(e){ // e.pageX,e.pageY
		downAtPos = e;
		downAtTime = new Date().getTime();
		$(timeline).scrollLeft($(timeline).scrollLeft()+5);
		return false;});
	$(timeline_mask).mousemove(function(e){ // e.pageX,e.pageY
		if ( downAtPos === 0 ) 
		{
			var year = xToYear($(timeline).scrollLeft()+e.pageX);
			var timelineY = e.pageY-$(this).offset().top;
			var hidePopup = timelineMouseIsOver!==0;
			timelineMouseIsOver = 0;
			if ( hidePopup && timelineMouseIsOver===0 ) $("#timeline_popup").fadeOut();
		}
		else
		{						
			$(timeline).scrollLeft($(timeline).scrollLeft()+(downAtPos.pageX-e.pageX));
			downAtPos = e;
		}});
	$(timeline_mask).mouseup(function(e){ // e.pageX,e.pageY
		if ( downAtTime !== 0 )
		{
			var timeDiff = ( new Date().getTime() - downAtTime );
			if ( timeDiff<MOUSE_CLICK_TIME )
			{
				var x = $(timeline).scrollLeft()+e.pageX;
				setCurrentYear(xToYear(x));
			}
		}
		downAtPos = 0;
		return false;});
	$(timeline_mask).mouseleave(function(e){ // e.pageX,e.pageY
		downAtPos = 0;
		return false;});

	for ( var year = FIRST_YEAR ; year<LAST_YEAR ; year = year + YEAR_STEP)
	{
		var left = yearToX(year);
		var year_text = year;
		if ( year<0 ) year_text = -year+"BC";
		else if ( year==0 ) year_text = "1";
		var d = document.createElement("div");
		
		$(d).addClass('marker').css({left:left,width:YEAR_STEP_WIDTH}).data('gb_year',year).appendTo(timeline);
		$(document.createElement('div')).text(year_text).appendTo(d);
	}

	var d = document.createElement("div");
	$(d).attr('id','timeline_zoom').appendTo(document.body);
	$(document.createElement("img"))
		.attr('src','images/delete.png')
		.attr('width',16)
		.attr('height',16)
		.click( function() { 
			YEAR_STEP_WIDTH /= 2;
			pixels_per_year = YEAR_STEP_WIDTH/YEAR_STEP;
			layoutTimeline();
			$(timeline).scrollLeft($(timeline).scrollLeft()/2);
			})
		.appendTo(d);
	$(document.createElement("img"))
		.attr('src','images/add.png')
		.attr('width',16)
		.attr('height',16)
		.click( function() {
			YEAR_STEP_WIDTH *= 2;
			pixels_per_year = YEAR_STEP_WIDTH/YEAR_STEP;
			layoutTimeline();
			$(timeline).scrollLeft($(timeline).scrollLeft()*2);
			})
		.appendTo(d);

	$(document.createElement("div"))
		.addClass('current')					
		.css( { 'left' : yearToX( INITIAL_CURRENT_YEAR ) })
		.appendTo(timeline);

	$(timeline).scrollLeft(yearToX(INITIAL_CURRENT_YEAR)-($(window).width()-200)/2);					
}

function initMenu()
{
	var menu = document.createElement("div");
	$(menu).attr('id','menu').appendTo(document.body);

	$('#menu').height($(window).height()-100).css({ left: $(window).width()-200 });

	function createSection( name )
	{
		$(document.createElement("div")).html(name).appendTo(menu);						
		var r = document.createElement("ul");
		$(r).hide().appendTo(menu);
		return r;
	}
	function addItem(section,name,fn)
	{
		var el = document.createElement("li");
		$(el)
			.html(name)
			.click(fn)
			.appendTo(section);
		return el;
	}
	function addZoomItem(section,name,lat,lng,zoom)
	{
		$(document.createElement("li"))
			.html(name)
			.data('gb_latlng',new GLatLng(lat,lng))
			.data('gb_zoom',zoom)
			.click(function(){
				$('#message').hide();
				map.setCenter($(this).data('gb_latlng'),$(this).data('gb_zoom')); })
			.appendTo(section);			
	}

	var zoomto = createSection("Quick Nav");
	addZoomItem(zoomto,"Default",0.0,0.0,MIN_ZOOM);
	addZoomItem(zoomto,"Europe",46.0,16.0,4);
	addZoomItem(zoomto,"China",43.0,96.0,4);
	addZoomItem(zoomto,"North Africa",23,13,4);
	addZoomItem(zoomto,"Middle East",28,46,4);
	addZoomItem(zoomto,"Central America",19,-83,4);
	addZoomItem(zoomto,"South America",-26,-58,3);

	// CITIES MENU ----------------------------------------------
		
	cities = createSection("Cities");

	$(document.createElement("li"))
		.html("Loading ...")
		.appendTo(cities);	

	$.ajax({
		url: 'data.php5',
		data: { "action":"get_cities" },
		dataType: 'json',
		error: function(request,text,error) {
				$(cities).find(":first").html("Error Loading");
		},
		success: function(data,test,request) {
			for ( var i=0 ; i<data.length ; i++ )
			{
				data[i].name = data[i].name.replace(/ /g,"&nbsp;");
				data[i].type = 'city';
				var point = new GLatLng(data[i].lat,data[i].lng);
				var marker = new GMarker(point,{ 'icon':icon,hide:true });
				marker.data = data[i];
					GEvent.addListener(marker, "click", function(){$(this).data('gb_hide_on_leave',false); gotoMarker(this);});
					GEvent.addListener(marker,"mouseover",function(){ $(this).data('gb_hide_on_leave',true); showMarkerText(this); });
					GEvent.addListener(marker,"mouseout",function(){ if ( $(this).data('gb_hide_on_leave') ) hideMarkerText(this); });
				 	map.addOverlay(marker);

				$(document.createElement("li"))
					.html(data[i].name)
					.data('gb_marker',marker)
					.click(function(){ gotoMarker($(this).data('gb_marker')); })
					.appendTo(cities);
			}

			$(cities).find(":first").remove();
			citiesLoaded = true;
			if ( empiresLoaded ) 
			{
				currentYear = INITIAL_CURRENT_YEAR-1;
				setCurrentYear(INITIAL_CURRENT_YEAR);
			}}});

	// EMPIRES MENU ----------------------------------------------
	
	empires = createSection("Empires");

	$(document.createElement("li"))
		.html("Loading ...")
		.appendTo(empires);	

	$.ajax({
		url: 'data.php5',
		data: { "action":"get_empires" },
		dataType: 'json',
		error: function(request,text,error){
			$(empires).find(":first").html(text+" - "+error);},
		success: function(data,test,request){
			var empireMarkers = [];
			for ( var i=0 ; i<data.length ; i++ )
			{
				data[i].name = data[i].name.replace(/ /g,"&nbsp;");
				data[i].type = 'empire';
				var point = new GLatLng(data[i].lat,data[i].lng);
				var marker = new GMarker(point,{ 'icon':icon,hide:true });
				marker.data = data[i];
				empireMarkers.push(marker);
				map.addOverlay(marker);

				data[i].left = yearToX(data[i].from_year);
				data[i].right = yearToX(data[i].to_year);
				data[i].width = data[i].right-data[i].left;
								
				$(document.createElement("li"))
					.html(data[i].name)
					.data('gb_marker',marker)
					.click(function(){
						gotoMarker($(this).data('gb_marker'));})
					.appendTo(empires);
					
			}

			// now go through empires in order of year_from to add to the timeline
			
			var empireMarkersAdded = [];

			while ( empireMarkers.length > 0 )
			{
				// get the earliest empire
				var earliestAt = 0;
				for ( var i=1 ; i<empireMarkers.length ; i++ )
				{
					if ( empireMarkers[i].data.from_year<empireMarkers[earliestAt].data.from_year )
					{
						earliestAt = i;
					}
				}
				var earliest = empireMarkers.splice(earliestAt,1)[0];

				// find where it can fit
				var i = 0;
				for ( ; i<empireMarkersAdded.length ; i++ )
				{
					if ( empireMarkersAdded[i].data.to_year <= earliest.data.from_year ) 
					{
						// earliest will fit after empireMarkersAdded[i], so add it
						earliest.data.top = empireMarkersAdded[i].data.top;
						empireMarkersAdded[i] = earliest;
						i = -1;
						break;
					}
				}
				if ( i!=-1 )
				{
					// didn't find a spot for it, so add to a new position
					earliest.data.top = TIMELINE_FIRST_LINE_Y + empireMarkersAdded.length*TIMELINE_LINE_DELTA;
					empireMarkersAdded.push(earliest);
				}
			
				$(document.createElement("div"))
					.data('gb_marker',earliest)
					.addClass('line')
					.css({ position: 'absolute',left: earliest.data.left,top:earliest.data.top,height:TIMELINE_LINE_HEIGHT,width:earliest.data.width,background:earliest.data.color})
					.appendTo(timeline)
					.mouseenter( function (ev) {
						$(this).data('gb_hide_on_leave',true);
						showMarkerText($(this).data('gb_marker'));})
					.mouseleave( function() { 
						if ( $(this).data('gb_hide_on_leave') ) hideMarkerText($(this).data('gb_marker')); } )
					.click(function(){
						$(this).data('gb_hide_on_leave',false);
						gotoMarker($(this).data('gb_marker'));});
			}

			$(empires).find(":first").remove();
			empiresLoaded = true;
			if ( citiesLoaded )
			{
				currentYear = INITIAL_CURRENT_YEAR-1;
				setCurrentYear(INITIAL_CURRENT_YEAR);
			}}});

	// EDIT MENU ----------------------------------------------

	var edit = createSection("Edit");						

	addItem(edit,"Add City",function() { showForm("form_add_city.html"); });
	addItem(edit,"Edit City",function() { showForm("form_edit_city.html"); });

	addItem(edit,"Hide City Markers",function(){
		$('#message').hide();
		cityMarkersVisible = !cityMarkersVisible;
		setCurrentYear(currentYear);
		if ( cityMarkersVisible ) $(this).html("Hide City Markers");
		else $(this).html("Show City Markers");});

	addItem(edit,"Add Empire",function() { showForm("form_add_empire.html"); });
	addItem(edit,"Edit Empire",function() { showForm("form_edit_empire.html"); });

	addItem(edit,"Hide Empire Outlines",function(){
		regionsVisible = !regionsVisible;
		for ( var i=0 ; i<regions.length ; i++ )
		{
			if ( regionsVisible ) regions[i].polygon.show();
			else regions[i].polygon.hide();
		}
		if ( regionsVisible ) $(this).html("Hide Empire Outlines");
		else $(this).html("Show Empire Outlines");});

	addItem(edit,"Add Empire Region",function(){
			if ( !$(this).data('gb_polygon') )
			{
				var points = [];
				var lat = map.getCenter().lat();
				var lng = map.getCenter().lng();
				var s = 3;
				points.push( new GLatLng(lat-s,lng-s));
				points.push( new GLatLng(lat+s,lng-s));
				points.push( new GLatLng(lat+s,lng+s));
				points.push( new GLatLng(lat-s,lng+s));
				points.push( new GLatLng(lat-s,lng-s));
				var polygon = new GPolygon(points, '#0000FF', 1, 1);
				map.addOverlay(polygon);
				polygon.enableEditing();
				$(this)
					.data('gb_polygon',polygon)
					.html("Finish New Region");
			}
			else
			{
				var polygon = $(this).data('gb_polygon');
				polygon.disableEditing();
				map.removeOverlay(polygon);
				$(this)
					.html("Add Empire Region")
					.data('gb_polygon',null);

				showForm("form_add_empire_region.html", function(){
					var points = "";
					for ( var i=0 ; i<polygon.getVertexCount() ; i++ )
					{
						points += " " + polygon.getVertex(i).lat() +","+polygon.getVertex(i).lng();
					}
					$("#points").attr('value',points);});
			}});
	editRegionMenuItem = addItem(edit,"Edit Empire Region",function(){
		if ( $(this).html()=="Edit Empire Region" )
		{
			showForm("form_edit_region.html");
		}
		else
		{
			var r = $(this).data('gb_region');
			if ( r!=null )
			{
				r.polygon.disableEditing();
				showForm("form_edit_region2.html",function() {
					var points = "";
					for ( var i=0 ; i<r.polygon.getVertexCount() ; i++ )
					{
						points += " " + r.polygon.getVertex(i).lat() +","+r.polygon.getVertex(i).lng();
					}
					document.forms.edit_region2.id.value = r.id;
					document.forms.edit_region2.points.value = points;
					if ( r.from_year==-99999 ) document.forms.edit_region2.from_year.value = '';
					else if ( r.from_year<0 ) document.forms.edit_region2.from_year.value = (-r.from_year) + 'bc';
					else document.forms.edit_region2.from_year.value = r.from_year;
					if ( r.to_year==99999 ) document.forms.edit_region2.to_year.value = '';
					else if ( r.to_year<0 ) document.forms.edit_region2.to_year.value = (-r.to_year) + 'bc';
					else document.forms.edit_region2.to_year.value = r.to_year;
				});
			}
			else
			{
				for ( var x=0 ; x<regions.length ; x++ )
				{
					regions[x].polygon.disableEditing();
					GEvent.clearListeners(regions[x].polygon);
				}
			}
			$(this).html("Edit Empire Region");
		} });

	// HELP MENU ----------------------------------------------

	var help = createSection("Help");
	addItem(help,"Contact",function(){ showForm("form_contact.html"); });
	addItem(help,"About",function(){ showForm("form_about.html");});

	// ----------------------------------------------

	$('#menu div').click( function (){
		var checkElement = $(this).next();
					
		if ( !checkElement.is(':visible') )
		{
			$('#menu ul:visible').slideUp();
			checkElement.slideDown();
			return false;
		}
		else
		{
			checkElement.slideUp();
		}});

	//$(cities).slideDown();
}

function showForm(filename,fn)
{
	$('#window_mask').show();
	$("#popup").html("Loading ...");
	$('#popup').fadeIn('slow');

	$.ajax({
		url: filename,
		dataType: 'html',
		error: function(request,text,error) {
			$("#popup").html("Sorry, there has been an error loading the form.");},
		success: function(data,test,request) {
			$("#popup").html(data);
			$("#popup input").click( function() { this.focus(); } );
			if (fn) fn.call(data);}});
}

function initialise()
{
	$(document).ready(init);
}

google.setOnLoadCallback(initialise);

