function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string') {
			if (document.getElementById) {
				element = document.getElementById(element);
			} else if (document.all) {
				element = document.all[element];
			}
		}
		elements.push(element);
	}

	if (arguments.length == 1 && elements.length > 0) {
		return elements[0];
	} else {
		return elements;
	}
}

function initMap() {

	var omniRefresh = window.setInterval(refreshpage,30000);

	var a = window.location.href.split("#",2);
	if (a[1] != undefined) {
		var b = a[1].split("&",3);
		var theme = b[0].split("=",2);
		var center = b[1].split("=",2);
		var zoom = b[2].split("=",2);
		if (theme != undefined && center != undefined && zoom != undefined ) {
			latlon = center[1].split("|",2);
			var s = "r";
			if (theme[1] == "Topographic") {
				s = "a";
			} else if (theme[1] == "Satellite") {
				s = "h";
			}
			var c = String(latlon[1] + "," + latlon[0]);
			var z = 1;
			if (zoom[1] <= 73874399.6427141) z = 2;
			if (zoom[1] <= 36937199.8213571) z = 3;
			if (zoom[1] <= 18468599.9106785) z = 4;
			if (zoom[1] <= 9234299.95533926) z = 5;
			if (zoom[1] <= 4617149.97766963) z = 6;
			if (zoom[1] <= 2308574.98883482) z = 7;
			if (zoom[1] <= 1154287.49441741) z = 8;
			if (zoom[1] <= 577143.747208704) z = 9;
			if (zoom[1] <= 288571.873604352) z = 10;
			if (zoom[1] <= 144285.936802176) z = 11;
			if (zoom[1] <= 72142.968401088) z = 12;
			if (zoom[1] <= 36071.484200544) z = 13;
			if (zoom[1] <= 18035.742100272) z = 14;
			if (zoom[1] <= 9017.871050136) z = 15;
			if (zoom[1] <= 4508.935525068) z = 17;
			if (zoom[1] <= 2254.467762534) z = 19;
			if (zoom[0] == "z") {
				s = theme[1];
				c = String(center[1]);
				z = zoom[1];
			}
			if (c.match(/%20/)) {
				latlon = c.split("%20",2);
				c = String(latlon[0] + latlon[1]);
			}
			var customMap = 1;
		}
	}

//			document.getElementById('resultDiv').innerHTML = ;

	map = new VEMap('myMap');
	//map.SetDashboardSize(VEDashboardSize.Small);
	map.SetDashboardSize(VEDashboardSize.Normal);
	map.LoadMap();
	if (customMap) {
		map.SetMapStyle(s);
		latlon = c.split(",",2);
		var x = new VELatLong(latlon[0], latlon[1]);
//		alert(s+":"+x+":"+z);
		map.SetCenterAndZoom(x,z);
//		map.SetZoomLevel(z);
	}
	// Set up overview Map
	map.ShowMiniMap(490, 20);

	map.AttachEvent("onclick",MouseHandler);
	map.AttachEvent("ondoubleclick",MouseHandler);
	map.AttachEvent("onmousedown",MouseHandler);
	map.AttachEvent("onmouseup",MouseHandler);
	map.AttachEvent("onmousewheel",MouseHandler);
	map.AttachEvent("onendzoom",EndZoomHandler);

	
	document.getElementById('MSVE_minimap_content').onmouseup = function() {
		EndZoomHandler();
	}

	document.getElementById('Compass').onmouseup = function() {
		EndZoomHandler();
	}

	updatePath();
	
	var threedButton = document.getElementById("threed-button");
	
	if(threedButton != undefined){
		if (navigator.appVersion.indexOf("Win")!=-1){
			threedButton.className = "threed-button-off";
			use3D = true;
		}
		else {
			threedButton.className = "threed-button-hidden";
		}
	}
}

function DoCenterZoom(lat,lon,zoom) {
	map.SetCenterAndZoom(new VELatLong(lat, lon), zoom);
}

function MouseHandler(e) {
	var msg;
	if (e.eventName == "onclick") {
		if (e.leftMouseButton)
			msg = "onclick (left mouse button)  event";
		else if (e.rightMouseButton)
			msg = "onclick (right mouse button)  event";
		else if (e.leftMouseButton)
			msg = "onclick (middle mouse button)  event";
	} else {
		msg = e.eventName + " event.";
	}
	updatePath(msg);
}

function minimapHandler(e) {
	alert("hello");
}

function EndZoomHandler() {
	msg = "Zoom event";
	updatePath();
}
function updatePath(msg) {

	document.getElementById('maxRF').innerHTML = "1";

	var s = map.GetMapStyle();
	var c = map.GetCenter();
	var z = map.GetZoomLevel();
	// Use stored location and zoom for Bird's Eye View
	if (c == "") {
		c = cMemory;
		z = zMemory;
	}
	var newURL = getURL() + "#s=" + s + "&c=" + c + "&z=" + z;
	window.location.href = newURL;
	// Store location and zoom level in memory
	cMemory = c;
	zMemory = z;
	setTabs()
}

function getURL() {
	a = window.location.href;
	baseURL = a.split("#",1);
	return baseURL;
}

function FindLoc() {
	try {
		map.Find(null, document.getElementById('txtWhere').value, null, null, null, null, null, null, null, null, AddPushpin);
	}
	catch(e) {
		alert(e.message);
	}
}

function setmap(s) {
	refreshpage();
	if(s == "d"){
		if(map.GetMapMode() == VEMapMode.Mode3D){
			document.getElementById("threed-button").className = "twod-button-off";
			map.SetMapMode(VEMapMode.Mode2D);
		}
		else {
			document.getElementById("threed-button").className = "threed-button-off";
			map.SetMapMode(VEMapMode.Mode3D);
		}
	}
	else {
		map.SetMapStyle(s);
	}
	updatePath();
}

function cleartxt() {
	a = document.getElementById('txtWhere').value;
	if (a == "Search for an Address, Country, State, or U.S. Zip Code") {
		document.getElementById('txtWhere').value = "";
	}
}

function searchkey(e) {
	var keynum;
	if(window.event) { // IE 
		keynum = e.keyCode;
	} else if(e.which) { // Netscape/Firefox/Opera
		keynum = e.which;
	}
	if (keynum == 13) {
		FindLoc();
	}
}

function setTabs() {
	var s = map.GetMapStyle();
	document.getElementById("road-button").className = "road-button-off";
	document.getElementById("satellite-button").className = "satellite-button-off";
	
	var threedButton = document.getElementById("threed-button");

	if(use3D && threedButton != null) {
		if(map.GetMapMode() == VEMapMode.Mode3D){
			threedButton.className = "twod-button-off";
		}
		else {
			threedButton.className = "threed-button-off";
		}
	}
		
	var birdButton = document.getElementById("birdseye-button");
	
	if(birdButton != null){
		if (map.IsBirdseyeAvailable()) {
			birdButton.className = "birdseye-button-off";
			birdButton.onclick = function(){setmap('b');};
		}
		else {
			birdButton.className = "birdseye-button-disabled";
			birdButton.onclick = null;
		}
	}
	
	if (s == "b" && birdButton != null) {
		document.getElementById("birdseye-button").className = "birdseye-button-on";
	} else if (s == "h") {
		document.getElementById("satellite-button").className = "satellite-button-on";
	} else {
		document.getElementById("road-button").className = "road-button-on";
	}
}

function jscss(a,o,c1,c2) {
  switch (a){
    case 'swap':
      o.className=!jscss('check',o,c1)?o.className.replace(c2,c1): o.className.replace(c1,c2);
    break;
    case 'add':
      if(!jscss('check',o,c1)){o.className+=o.className?' '+c1:c1;}
    break;
    case 'remove':
      var rep=o.className.match(' '+c1)?' '+c1:c1;
      o.className=o.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+c1+'\\b').test(o.className)
    break;
  }
}

function printMap(opt) {
	a = window.location.href;
	baseURL = a.split("#",2);
	winURL = opt + "#" + baseURL[1];
	window.open(winURL,"_blank","width=991,height=662");
}

function showEmail() {
	$("VEError").style.display = 'none';
	$("VEEntry").style.display = 'block';
	$("VEConfirm").style.display = 'none';
	$("virtual-earth-email").style.display = 'block';
}

function hideEmail() {
	document.getElementById('virtual-earth-email').style.display = "none";
}

function refreshpage() {
	maxRF = document.getElementById('maxRF').innerHTML;
	if (maxRF == "1") {
		ngsPageView();

		var Dtoday=new Date();
		var Dh=Dtoday.getHours();
		var Dm=Dtoday.getMinutes();
		var Ds=Dtoday.getSeconds();
		mmAdRefresh();
		document.getElementById('resultDiv').innerHTML = "Omniture Call: "+Dh+":"+Dm+":"+Ds+" == "+maxRF;
	}
	document.getElementById('maxRF').innerHTML = "0";
}

function AddPushpin(a,b,c,d,e) {

	// Zoom in if search result zoomed out to globe view
	// otherwise the pushpin will be in the wrong location
	var z = map.GetZoomLevel();

	if (z < 3) {
		map.SetCenterAndZoom(c[0].LatLong,3);
//		map.SetZoomLevel(3);
	}


	document.getElementById('resultDiv').innerHTML = "Shape: "+shape+ " -- "+c[0].LatLong;

	if(shape != "") {
		map.DeleteShape(shape);
		shape = null;
	}

	shape = new VEShape(VEShapeType.Pushpin, c[0].LatLong);

	//Set the icon
	shape.SetCustomIcon(icon);
         
	//Set the info box
//	map.ClearInfoBoxStyles();
//	shape.SetTitle("<h2>Custom Pin</h2>");
//	shape.SetDescription(infobox);
         
	//Add the shape the the map
	map.AddShape(shape);
}

// Email Functions

function isblank(s){
	for(var i = 0; i < s.length; i++){
		var c = s.charAt(i);
		if ((c != ' ') && (c != '\n') && (c != '\t')) {
			return false;
		}
	}
	return true;
}

function isEmailAddr(email){
	var result = false
	var theStr = new String(email)
	var index = theStr.indexOf("@");
	if (index > 0) {
    	var pindex = theStr.indexOf(".",index);
		if ((pindex > index+1) && (theStr.length > pindex+1)){
			var sindex = theStr.indexOf(" ");
			if (sindex == -1){
				result = true;
			}
		}
	}
	return result;
}

function validateEmail(email_addr,email_name){
	var msg1 = "Please enter your friend's email address.\n";
	var msg2 = "Please enter a valid email address.\n";
	var msg3 = "Your name cannot be left blank.<br>\n";
	$("VEError").innerHTML = "";
	if ((email_addr == null) || (email_addr == "") || isblank(email_addr)){
		$("VEError").innerHTML = msg1;
		$("VEError").style.display = 'block';
	}
	if (isEmailAddr(email_addr) == false){
		$("VEError").innerHTML = msg2;
		$("VEError").style.display = 'block';
	}
	if (isblank(email_name)){
		$("VEError").innerHTML = msg3 + $("VEError").innerHTML;
		$("VEError").style.display = 'block';
	}
	if ($("VEError").innerHTML != "") {
		return false;
	}
	return true;
}

function validateEmailFriend() {
	var emailAddr = $("VEEmail").value;
	var emailName = $("VEName").value;
	var emailMssg = $("VEMessage").value;
	if (validateEmail(emailAddr,emailName) && !isblank(emailName)){
		var emailScript = "http://mesa.nationalgeographic.com/mapmachine/cgi-bin/emailmap.cgi?";
		//add params for email
		emailScript += "page_name="+map.GetMapStyle();       
		emailScript += "&your_name="+emailName;
		emailScript += "&friend_email="+emailAddr;
		emailScript += "&map_comments="+VEMessage;
		emailScript += "&lat="+map.GetCenter().Latitude;
		emailScript += "&lon="+map.GetCenter().Longitude;
		emailScript += "&scale="+map.GetZoomLevel();       
		emailScript += "&map_type=ve";
		$("hiddenRR").src = emailScript;
		$("VEError").style.display = 'none';
		$("VEEntry").style.display = 'none';
		$("VEConfirm").style.display = 'block';
		$("VEEmail").value = "";
	}

	return false;
}

// End Email Functions

// Custom Ad Refresh Code

function mmAdRefresh() {	
	var myFrames = document.getElementsByTagName('iframe');	
	var rand = Math.floor(1000000*Math.random());	
	var queryVar = "ngsAdvertisingRefreshRand";
	var frameSrc;	
	for (var i=0;i< myFrames.length; i++){		
		if (myFrames[i].name.indexOf("adFrame_ngm") != -1){
			frameSrc = myFrames[i].src.split("?" + queryVar);				
			myFrames[i].src = frameSrc[0] + "?"+queryVar+"=" + rand;					
		}
	}
}

var map = null;
var customMap = 0;
addLoadEvent(initMap);
var use3D = false;

var omniRefresh = 0;
var maxRF = 0;

var shape = "";
var pinid = 0;
var icon = "<div class=\"ve-pushpin\"></div>";

