var sc_w;
var sc_h;
/** width of the div list */
var lw = 300;
/** list_content width */
var plw = 20;
/** header height */
var oh = 144;
/** panel open/close */
var op = true;
/** Page width */
var pw;
/** Final height */
var fh;
/** Div max height */
var dh;
/** Map width */
var mw;
/** Earth object */
var earth;

/** TEMP stuff */
var roads;

function init(){
	
	page_setup();	
	
	earth = new Earth();
	earth.init("map");
	
	earth.onClickEv(get_maps);
	append = false;
}


function page_setup(){
	
	alertSize();
	
	pw = sc_w - 2;
	fh = sc_h - oh;
	mw = pw - plw - lw;
	/** Full height minus tools tab width */
	dh = fh - 125;
		
	$("#page_content").width(pw);
	$("#page_content").height(dh);

	$("#panel").css("top", oh);
	$("#panel").css("left", mw);

	$("#map_list").css("top", oh);
	$("#map_list").css("left", mw+plw);
	
	$("#map").css("top", oh);
	$("#map").css("left", 0);
	
	/** set height up */ 
	$("#panel").height(fh);	
	$("#map").height(fh);	
	$("#map_list").height(fh);
	
	/** set poi and map list max heihgt*/
	$("#maps_div").height(dh - 24);
	$("#poi_div").height(dh);
	
	
	/** set width of divs */
	$("#map").width(mw);	
	$("#map_list").width(lw);
	$("#panel").width(plw);
	
	if(!op){
		$("#map_list").toggle("slow");
		op = true;
	}
			
} 


function alertSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  
  sc_w = myWidth;
  sc_h = myHeight;
}


$(document).ready(function() {
	
	// allow window resize 
	$("#panel").click(function() {

		if(op){
			try{
			$("#map_list").toggle("fast");
			$("#map").animate({width: (pw) + "px"}, 300);
			op = false;
			
			$("#panel").removeClass("open").addClass("close");
			$("#panel").css("left", pw - plw);
			$("#panel").css("z-index", 1000);
			
			setTimeout("earth.update();", 300);
			}catch(e){
				alert("Error: " + e);
			}
			
		} else {
			$("#map").animate({width: (mw) + "px"}, 300);
		
			$("#map_list").toggle("fast");
			op = true;
			$("#panel").removeClass("close").addClass("open");
			$("#panel").css("left", mw);
			setTimeout("earth.update();", 300);
		}
	});

	makeMenu();
	loadPOI();

});

window.onresize = function() {
       page_setup();
};


function makeMenu(){		
		
	  $('#tools_menu ul').hide();
 	  $('#tools_menu ul:first').show();
 	  $('#tools_menu li a').click(  	
		    function() {
		      
			  var checkElement = $(this).next();
		      if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
		        return false;
		        }
		      if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
		        $('#tools_menu ul:visible').slideUp('fast');
		        checkElement.slideDown('fast');
		        return false;
		        }
		    }
    );
}

function get_maps(lt, lg){
	
	$('#tools_menu ul:visible').slideUp('fast');
   	$('#maps_li a').next().slideDown('fast');
	$("#maps_div").html("<div style='text-align: center;'><br /><img src='/images/loading_small.gif'><br /></div>");
	earth.removeAll();	
	
	$("#maps_div").html("<div style='width: 95%; text-align: center; padding-top: 30px;'><img src='/Earth/loading_small.gif'></div>");
	
	$.ajax({ url: '/Earth/search_maps.php?lat=' + lt + '&long=' + lg + '&l=1', 
				 cache: false,
				 dataType: 'html',
				 async: false,
				 success:  function(data){
				 	$("#maps_div").html(data);	     	
				}		
	});

	$("div.small").appendTo("#small");
	$("div.medium").appendTo("#medium");
	$("div.large").appendTo("#large");	
	

	//$("#small").children().each(function() {
	//	var year = $(this).find("a:first").text();
	//});
	
	
	if ($("#small").html() == '') { $("#small").remove(); $("#smallh3").remove(); }
	if ($("#medium").html() == '') { $("#medium").remove(); $("#mediumh3").remove(); }
	if ($("#large").html() == '') { $("#large").remove(); $("#largeh3").remove(); }
				
	return;
}

function loadPOI(){	

	$.ajax({ url: '/Earth/poi.php', 
				 cache: false,
				 dataType: 'html',
				 async: false,
				 success:  function(data){
						$('#poi_div').html(data);		        	
				}		
			});	
	
		return;
}

function put_map(layer_name, layer){

	var exist = earth.Exist(layer_name);
	var visible = earth.isVisible(layer_name);
	
	/************************************************************************************************************/
	//	before adding a map, check if the current zoom level is within the map's range
	var checkzoom = earth.checkZoomLevel(layer_name);
	
	var addedmap = true;
	
	//	if the map already exists, and zoom level is ok, make it visible
	if(exist && checkzoom == false){
		earth.toggleMap(layer_name);
	//	otherwise add a new overlay and return whether it could be added (can fail to add because of zoom level)
	} else {
		addedmap = earth.addOverlay(layer_name, layer);
	}

	//	if the overlay wasnt added because the zoom level is out of the range, display an error message that disappears automatically because there is no listener for this map to remove it later on
	if (addedmap == false) { 
		
		$('#u'+layer_name+'msg').remove();
		$('<div id=u'+layer_name+'msg class=zoommsg>This map is not available at the current zoom level. Please zoom '+checkzoom+'.</div>').insertAfter('#m'+layer_name);		
		$('#u'+layer_name+'msg').width(220);
		$('#u'+layer_name+'msg').css('margin-left','15px');
		$('#u'+layer_name+'msg').animate({opacity: 1.0}, 4000).fadeOut(1000);	
	
		return; 
		
	}
	/************************************************************************************************************/
	
	if(!visible){
		$("#pres_" + layer_name).html("<img src='on.png' style='vertical-align: -4px;' border=0>");
	} else {
		$("#pres_" + layer_name).html("<img src='off.png' style='vertical-align: -4px;' border=0>");	
	}
	
	$('#u'+layer_name+'msg').remove();
	$('#u'+layer_name).toggle();			
	$('#up_'+layer_name).toggle();
	$('#u'+layer_name+'msg').hide();

	if(exist == false && addedmap == true){
		
		var s = new Slider(document.getElementById("s" + layer_name), null);
		s.onchange = function () {
			earth.changeOpac( layer_name, s.getValue() );
		};
		s.setValue(100);
	}	
}

/************************************************************************************************************/
//	called by the listener when the zoom level is outside of the allowable range. 
//	hides the map and displays the error message that wont disappear until zoom level is back within range
function hide_map_zoom(layer_name, msg) {
	
	all_layers[layer_name].setVisibility(false);
	$('#u'+layer_name).toggle();			
	$('#up_'+layer_name).toggle();
	
	$('#u'+layer_name+'msg').remove();
	$('<div id=u'+layer_name+'msg class=zoommsg>This map is not available at the current zoom level. Please zoom '+msg+' and then re-enable the map.</div>').insertAfter('#u'+layer_name);		
	//$('#u'+layer_name+'msg').animate({opacity: 1.0}, 4000).fadeOut(1000);	
		
	$('#pres_'+layer_name).html('<img src="off.png" style="vertical-align: -4px;" border="0">');
	
}

//	called by the listener when the map has been hidden, but zoom level is now back within the acceptable range
function hide_zoom_msg(layer_name) {

	$('#u'+layer_name+'msg').remove();

}
/************************************************************************************************************/

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
	
function raiseLayer(mid){
	earth.raise(mid, 1);
}

function lowerLayer(mid){
	earth.raise(mid, -1);
}

function hide_map(mid, hidden){

	if(hidden == 1){
		$('#vis'+mid).css("display","none");
		$('#nvis'+mid).css("display","inline");
	} else {
		$('#nvis'+mid).css("display","none");
		$('#vis'+mid).css("display","inline");
	}
}

function addPOI(obj, name){

	if(obj.checked){
		return earth.addPoi(name);
	} else {
		earth.removePoi(name);
	}
	
}

function trim12 (str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

function labels(name){
	earth.setLabels(name);
}

function put_point(lat, lng, desc, fromzoomify){	
	earth.placeMarker(lat, lng, desc);
	get_maps(lat, lng);
	if (fromzoomify) {
		earth.zoomToLevel(10);
		addCoverage();
	}
}

function change_base(name){
	try{
		earth.changeBase(name);
	}catch(e){
		alert(e);
	}
}

function disable_poi_controls(value){
	
	var ch;
	value ? ch = true: ch = false;  	
	
	var form = document.forms['poi_form'];
	$(' input:checkbox', form).each( function() {
		this.disabled = ch;
	});
	
}

function get_mapinfo(layer_name){

	col = layer_name.substring(0,2);
	mid = layer_name.substring(2);  

	$.ajax({ url: '/Earth/mapinfo.php?c=' + col + '&m=' + mid, 
				 cache: false,
				 dataType: 'html',
				 //async: false,
				 success:  function(data){
					$("#map_info").html(data);	  
					$('#tools_menu ul:visible').slideUp('fast');
				   	$('#mapinfo_li a').next().slideDown('fast');      	
				}		
			});	
	
	return;
}

function tog(year){
	$("#dr_" + year).toggle('fast', function(){
		
		var img = $("#im_" + year).attr("src");
		if(img  == '/Earth/plus.png'){
			$("#im_" + year).attr("src", "/Earth/minus.png");
		} else {
			$("#im_" + year).attr("src", "/Earth/plus.png");
		}
		
	});	
	
}

function empty_map(){
	earth.center();
	earth.coverage();
}

function enable_ballon(val){
	earth.showBalloon(val);
}

function refresh(){
	var url = "http://www.historicmapworks.com/Earth/location.php?d=";
	var data = earth.lastPointer();
	url += data;
	window.location = url;
}

function addCoverage(){
	return earth.coverage();
}

function coveageDisabled(){
	document.forms['tools_form'].cov_box.checked = false;
}

function search_address(){

	var address = document.forms['tools_form'].address.value;
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(address, function(data){
		if(data.x && data.y){
			put_point(data.y, data.x, address);
		} else {
			alert("Address not found");
		}
	});
}

/************************************************************************************************************/

function bookmark(collection, mapid, currentnotes) {

	//layer_name = collection + mapid;
	layer_name = mapid;
	
	if(!$('#u'+layer_name+'bookmark').length) {
			
		$('<div id=\"u'+layer_name+'bookmark\" class=\"bookmark\"><form onSubmit=\"return add_bookmark(\''+collection+'\',\''+mapid+'\')\"><table cellpadding=\"0\" cellspacing=\"0\"><tr><td colspan=\"2\"><textarea cols=\"26\" name=\"notes'+layer_name+'\" id=\"notes'+layer_name+'\">'+currentnotes+'</textarea></td></tr><td><input type=\"submit\" value=\"Add/Edit Notes\"></td><td align=\"right\"><!--//<input type=\"button\" value=\"Cancel\" onclick=\"hide_bookmark(\''+layer_name+'\');\">//--></td></tr></table></form></div>').insertAfter('#u'+layer_name).hide();
			
	}
		
	$('#u'+layer_name+'bookmark').slideToggle('fast');		
		
}

function hide_bookmark(collection,mapid) {
	
	//layer_name = collection + mapid;
	layer_name = mapid;
	$('#u'+layer_name+'bookmark').slideUp('fast');
	
}

function add_bookmark(collection, mapid) {

	//layer_name = collection + mapid;
	layer_name = mapid;
	//	get the value of the notes textarea
	var notes = $('#u'+layer_name+'bookmark #notes'+layer_name).val();
	notes = encodeURIComponent(notes);

	//	make a request to bookmark.php which will insert the notes into the database and return the new notes value to be put back in the notes textarea
	$.ajax({ url: '/Earth/bookmark.php?c=' + collection + '&m=' + mapid + '&notes=' + notes, 
				 cache: false,
				 dataType: 'html',
				 //async: false,
				 success:  function(data){
					
					if (data) {
						
						//	bookmark.php will echo the notes after it inserts them. set the value of the textarea to that, so when the user adds a note and then re-opens the bookmark div, the note appears in the textarea
						$('#notes'+layer_name).val(data);
						//	hide the bookamark div, set the icon to indicate that it's now bookmarked 
						$('#u'+layer_name+'bookmark').slideUp('fast');
						$('#bimg'+layer_name).attr('src', 'notebook_added.gif');
						$('#bimg'+layer_name).attr('title', 'Bookmarked');
						
						//$('#blink'+mapid).attr('onclick','');
						
					}
					
				}		
			});	
			
	
	return false;

}

/************************************************************************************************************/

