google.load("earth", "1");
var ge = null;
var CURRENT_KML_URL = "";
var LOAD_SITE_POINTERS = true;
var GE_PLACEMARK = null;
var FLYTO_SPEED = 0.5;
var MIN_RANGE_FOR_CLICK = 5000000;
var GOOGLE_EARTH_STATE = 2; // possible values are 1-found, 0-not found, and 2-checking
var FORCE_MAP=(window.location.href.indexOf("force=map")>0);
function init() {
	ge_init();
}
function ge_init() {
	if (FORCE_MAP){
		failureCallback();
		return;
	}
	google.earth.createInstance("google_earth_plugin", initCallback, failureCallback);
}
function initCallback(object) {
	GOOGLE_EARTH_STATE = 1;
	ge = object;
	ge.getWindow().setVisibility(true);
	ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
	ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
	//ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, true);
	//ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
	//ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, true);
	ge.getOptions().setFlyToSpeed(FLYTO_SPEED);
	ge.getOptions().setStatusBarVisibility(true);
	ge.getOptions().setScaleLegendVisibility(true);
	ge.getOptions().setUnitsFeetMiles(false);
	if (LOAD_SITE_POINTERS && typeof(loadKml_v2)=="function"){
		loadMotherKML();
	}
	if (CURRENT_KML_URL!=""){
		loadKml_v2(CURRENT_KML_URL, true);
	}
	if (typeof(writeFloatingIframe)=="function"){
		writeFloatingIframe();
	}
	loadMultipleKmls();
}
function deleteGEInstance(){
	while(node = document.getElementById("google_earth_plugin").firstChild){
		document.getElementById("google_earth_plugin").removeChild(node);
	}
}
function failureCallback(object) {
	GOOGLE_EARTH_STATE = 0;
	deleteGEInstance();
	startMapUI();
	if (typeof(writeFloatingIframe)=="function"){
		writeFloatingIframe();
	}
}
function toggleGoogleEarthPlugin(show){
	if (!ge){
		return;
	}
	if (show==null){
		ge.getWindow().setVisibility(!ge.getWindow().getVisibility());
		document.getElementById("google_earth_plugin").style.visibility="visible";
	} else if (show===true){
		ge.getWindow().setVisibility(true);
		document.getElementById("google_earth_plugin").style.visibility="visible";
	} else {
		ge.getWindow().setVisibility(false);
		document.getElementById("google_earth_plugin").style.visibility="hidden";
	}
}
function loadKml(url){
	CURRENT_KML_URL = url;
	if (!ge){
		return;
	}
	
	// NetworkLink
	var networkLink = ge.createNetworkLink('');
	networkLink.setDescription('NetworkLink open to fetched content');
	networkLink.setName('Open NetworkLink');
	networkLink.setFlyToView(true);
	
	// NetworkLink/Link
	var link = ge.createLink('');
	link.setHref(url);
	networkLink.setLink(link);
	
	// add the network link to earth
	ge.getFeatures().appendChild(networkLink);
}
function loadKml_v2(url, doFly, balloons){
	if (doFly==null){
		doFly = true;
	}
	if (balloons==null){
		balloons = true;
	}
	CURRENT_KML_URL = url;
	if (GOOGLE_EARTH_STATE==0){ //GE not found
		loadKML2Map(url, doFly, true);
		return;
	} else if (GOOGLE_EARTH_STATE==2){ //GE not ready
		// ignore the call, will be loaded later by the loadMultipleKmls called from the GE ready event
	} else { //GE ready
		// NetworkLink
		var networkLink = ge.createNetworkLink('');
		networkLink.setDescription('NetworkLink open to fetched content');
		networkLink.setName('Open NetworkLink');
		networkLink.setFlyToView(doFly);
		
		// NetworkLink/Link
		var link = ge.createLink('');
		link.setHref(url);
		networkLink.setLink(link);
		
		// add the network link to earth
		ge.getFeatures().appendChild(networkLink);
	}	
}
function unloadKml_v2(url){
	if (GOOGLE_EARTH_STATE==0){ //GE not found
		unloadKML2Map(url);
	} else if (GOOGLE_EARTH_STATE==1){ //GE found
		var kmls = ge.getFeatures().getChildNodes();
		for (i=0; i<kmls.getLength(); i++){
			node = kmls.item(i);
			if (node.getLink().getHref()==url){
				ge.getFeatures().removeChild(node);
			}
		}
	} else { //GE not ready
		return false;
	}
}
function clearKMLs(){
	if (GOOGLE_EARTH_STATE==0){ //GE not found
		clearMapPointers();
	} else if (GOOGLE_EARTH_STATE==2){ //GE not ready
		// ignore the call, will be loaded later by the loadMultipleKmls called from the GE ready event
	} else { //GE ready
		while (ge.getFeatures().hasChildNodes()){
			ge.getFeatures().removeChild(ge.getFeatures().getFirstChild());
		}
	}
}
var MOTHER_KML = null;
function loadMotherKML(){
	if (GOOGLE_EARTH_STATE!=1){
		return;
	}
	
	if (MOTHER_KML == null){
		// NetworkLink
		var networkLink = ge.createNetworkLink('');
		networkLink.setDescription('NetworkLink open to fetched content');
		networkLink.setName('Open NetworkLink');
		networkLink.setFlyToView(false);
		
		// NetworkLink/Link
		var link = ge.createLink('');
		link.setHref("http://ghn.globalheritagefund.org/dynamic_kml.php");
		//link.setHref("http://localhost/dynamic_kml.php");
		networkLink.setLink(link);
		MOTHER_KML = networkLink;
	}
	
	// add the network link to earth
	ge.getFeatures().appendChild(MOTHER_KML);
	
	// add listener for clicks
	google.earth.addEventListener(ge.getWindow(), 'click', function(event) {
		var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
		eyeAlt = lookAt.getRange();
		if (eyeAlt<MIN_RANGE_FOR_CLICK && event.getTarget().getType() == 'KmlPlacemark') {
			var placemark = event.getTarget();
			//alert(placemark.getName() + " (" + placemark.getDescription() + ")");
			loadSiteFromGE(placemark.getDescription());
		}
	});
}
function kmlDump(){
	if (!ge){
		return;
	}
	var kmls = ge.getFeatures().getChildNodes();
	msg="";
	for (i=0; i<kmls.getLength(); i++){
		node = kmls.item(i);
		msg += node.getLink().getHref() + "\n";
	}
	alert(msg);
}
function addPlaceMark(coord){
	if (!ge){
		return;
	}
	$arr_coord = new Array();
	if (coord!=null && coord!=""){
		$arr_coord = coord.split(',');
	}
	if (GE_PLACEMARK==null){
		GE_PLACEMARK = ge.createPlacemark('');
	}
	var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
	GE_PLACEMARK.setName("Drag me");
	var point = ge.createPoint('');
	var latitude  = (coord!=null && coord!="") ? Number($arr_coord[1]) : lookAt.getLatitude();
	var longitude = (coord!=null && coord!="") ? Number($arr_coord[0]) : lookAt.getLongitude();
	point.setLatitude(latitude);
	point.setLongitude(longitude);
	GE_PLACEMARK.setGeometry(point);
	ge.getFeatures().appendChild(GE_PLACEMARK);
	
	// listen for mousedown on the window (look specifically for point placemarks)
	google.earth.addEventListener(ge.getWindow(), 'mousedown', function(event) {
		if (event.getTarget().getType() == 'KmlPlacemark' && event.getTarget().getGeometry().getType() == 'KmlPoint') {
			//event.preventDefault();
			var placemark = event.getTarget();
			dragInfo = { placemark: event.getTarget(), dragged: false };
		}
	});
	
	// listen for mousemove on the globe
	google.earth.addEventListener(ge.getGlobe(), 'mousemove', function(event) {
		if (dragInfo) {
			event.preventDefault();
			var point = dragInfo.placemark.getGeometry();
			point.setLatitude(event.getLatitude());
			point.setLongitude(event.getLongitude());
			dragInfo.dragged = true;
		}
	});
	
	// listen for mouseup on the window
	google.earth.addEventListener(ge.getWindow(), 'mouseup', function(event) {
		if (dragInfo) {
			if (dragInfo.dragged) {
				// if the placemark was dragged, prevent balloons from popping up
				event.preventDefault();
			}
			dragInfo = null;
		}
	});
}
function getPlaceMarkCoordinates(){
	if (GE_PLACEMARK==null){
		return false;
	}
	var arr = new Array();
	arr['longitude'] = GE_PLACEMARK.getGeometry().getLongitude();
	arr['latitude'] = GE_PLACEMARK.getGeometry().getLatitude();
	return arr;
}
function removePlaceMark(){
	if (!ge){
		return;
	}
	var kmls = ge.getFeatures().getChildNodes();
	for (i=0; i<kmls.getLength(); i++){
		ge.getFeatures().removeChild(kmls.item(i));
	}
}
