/**
 * fsairlines.flightmonitor.utils.js
 *
 * Everything concerning the Google Earth API.
 *
 * @author Claudio Gusmini
 * @version 0.1
 */
var href="http://www.fsairlines.net/";
var ge=null;
google.load("earth", "1");
google.load("maps", "2");

/**
 * Flight Monitor class.
 * @param id  The ID of the div where the Flight Monitor will be in.
 * @param callback  The functions which will be called right after the initialization.
 * @return
 */
function FlightMonitor(id_monitor, id_controls, id_all, callback, fullscreen) {
	
	that=this;
	
	this.id_monitor = id_monitor;
	this.id_all = id_all;
	this.id_controls = id_controls;
	this.links = new Array();
	this.links['all'] = new Array();
	
	this.callback = callback;
	
	this.fullscreen = fullscreen;
	
	this.filterArea = 'all';
	
	this.autorefreshtimeout = 0;
	this.autorefresh = null;
	
	this.currentModelScale = 10000;
	
	this.modelzoom = 1;
	
	this.pendingRequests = 0;
	

	/**
	 * Initlialize the Google Earth API.
	 */
	var fmInit = function () {
		google.earth.createInstance(id_monitor, fmInitCallback, fmFailureCallback);
	};
	
	/**
	 * Initialization callback.
	 * @param object  The object containing some data.
	 */
	var fmInitCallback = function(object) {
		  ge = object;
		  ge.getWindow().setVisibility(true);
		  that.resize();
		  that.callback();
	};
	
	/**
	 * Called if initialization fails.
	 * @param object  The object containing some data.
	 * @return
	 */
	var fmFailureCallback = function(object) {
		alert("A problem with the flight monitor occured!");
	};
	
	// Initialize the Google Earth API
	fmInit();
};

/**
 * Checks if data is already loaded.
 * @param  name  The name of the KML-Reference.
 */
FlightMonitor.prototype.isLoaded = function(name) {
	if (this.links[this.filterArea][name] == undefined) return false;
	else return true;
}

/**
 * Checks if data is already loaded and displays it.
 * @param  name  The name of the KML-Reference.
 * @return
 */
FlightMonitor.prototype.show = function(name) {
	if (!this.isLoaded(name)) {
		this.loadKML(name, true);
		loading();
	} else {
		this.links[this.filterArea][name].setVisibility(true);
		if (this.isInfoVisible()) this.showInfo(name);
	}
};


/**
 * Update a KML file.
 * @param name  The name of the KML-Reference.
 * @return
 */
FlightMonitor.prototype.update = function(name) {
	if (!this.isLoaded(name)) this.show(name);
	else {
		this.loadKML(name, true);
	}
}

/**
 * Hides the data.
 * @param  name  The name of the KML-Reference.
 * @return
 */
FlightMonitor.prototype.hide = function(area, name) {
	if (this.links[area] != undefined) {
		if (this.links[area][name] != undefined)
			this.links[area][name].setVisibility(false);
	}
};

/**
 * Hides all the data.
 * @param  name  The name of the KML-Reference.
 * @return
 */
FlightMonitor.prototype.hideAll = function() {
	for (area in this.links) {
		for (name in this.links[area]) {
			this.hide(area, name);
		}
	}
};

/**
 * Loads data to the Flight Monitor.
 * @param name  The name used to identify the data, if multiple data is loaded.
 * @param href  The link to the KML file.
 * @param show  The visibility of the data.
 * @return
 */
FlightMonitor.prototype.loadKML = function(name, show) {

	var alt = parseInt(that.getViewAltitude());
	var url = href+"kml/interface.php5?name="+name+"&area="+this.filterArea+"&n="+Math.random()+"&alt="+alt+"&modelzoom="+this.modelzoom;
	//alert(url);
	google.earth.fetchKml(ge, url, this.fmKMLFinished);
	
	this.pendingRequests++;
};

/**
 * Called when a KML file is loaded.
 * @param object  The network link which has been loaded.
 * @return
 */
FlightMonitor.prototype.fmKMLFinished = function(object) {
	this.pendingRequests--;
	aaaObject = object;
    if (!object) {
      // wrap alerts in API callbacks and event handlers
      // in a setTimeout to prevent deadlock in some browsers
    	loaded();
    	$('#warning').html('A problem occured! Please use the old flight monitor!');
    	return;
    }
    
    $('#warning').html('');

    var name = object.getId();
    if (that.links[that.filterArea][name] != undefined) that.hide(that.filterArea, name);
	that.links[that.filterArea][name] = object;
    
    ge.getFeatures().appendChild(object);
    
	loaded();
	
    if (that.isInfoVisible()) that.showInfo(name);
};


FlightMonitor.prototype.toggle = function (name) {
    if (this.links[this.filterArea][name] == undefined) {
    	this.loadKML(name, true);
    } else {
		if (this.links[this.filterArea][name].getVisibility())
	    	this.links[this.filterArea][name].setVisibility(false);
	    else this.links[this.filterArea][name].setVisibility(true);
    }
};

FlightMonitor.prototype.progressBar = function(id, interval) {
	$("#"+id).progressbar({value: 0});
	
	var update = function() { $("#"+id).progressbar( 'value' , ge.getStreamingPercent() ); };
	
	setInterval(update, interval);
};

FlightMonitor.prototype.flyTo = function(id) {
	var geocodeLocation = document.getElementById(id).value;
	
	var geocoder = new google.maps.ClientGeocoder();
	geocoder.getLatLng(geocodeLocation, function(point) {
	  if (point) {
	    var lookAt = ge.createLookAt('');
	    lookAt.set(point.y, point.x, 200000, ge.ALTITUDE_RELATIVE_TO_GROUND,
	               0, 0, 20000);
	    ge.getView().setAbstractView(lookAt);
	  }
	});
};


FlightMonitor.prototype.toggleFullScreen = function() {
    if (!this.fullscreen) {
    	this.fullscreen=true;
    	FM.toggleInfo($('#flights').val());
    } else {
    	this.fullscreen=false;
    }
    this.resize();
};

FlightMonitor.prototype.resize = function() {
	var width = $(window).width();
	var height = $(window).height();
	var containerWidth = $('#container').width();
	
	if (this.fullscreen) {
    	var left = -width/2 + containerWidth/2 + 10;
    	var heightMonitor = height - $('#'+this.id_controls).height() - 25;
    	if (this.isInfoVisible()) widthMonitor = width-$('#info').width()-10;
    	else widthMonitor = width;
    	
    	$('#all').attr('style', 'position:absolute; left:'+left+'px; top:0px; height:'+height+'px; width:'+width+'px; background: #FFF; display:block; margin:0; padding:0');
    	$('#'+this.id_monitor).attr('style', 'height:'+heightMonitor+'px; width:'+widthMonitor+'px');
    	$('#autoRefreshTab').show();
    	$('#infoTab').show();
    	$('#search').show();
    	if (this.isInfoVisible()) $('#info').attr('style', 'height:'+heightMonitor+'; overflow:auto; width:200px; float:right; margin:0; padding:0');
    	this.navigation(1);
    } else {
    	$('#all').attr('style', 'position:absolute; width:600px; height:600px');
    	$('#'+this.id_monitor).attr('style', 'height:500px');
    	$('#autoRefreshTab').hide();
    	$('#infoTab').hide();
    	$('#search').hide();
    	$('#info').hide();
    	this.navigation(0);
    }
};

FlightMonitor.prototype.navigation = function(show) {
	if (show == 0)
		ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE);
	else if (show == 1)
		ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW);
	else if (show == 2)
		ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
};

FlightMonitor.prototype.gotoCoords = function(lat, lon) {
	var lookAt = ge.createLookAt('');
    lookAt.set(lat, lon, 100000, ge.ALTITUDE_RELATIVE_TO_GROUND,
               0, 0, 10000);
    ge.getView().setAbstractView(lookAt);
}

FlightMonitor.prototype.setFilterArea = function(area) {
	this.filterArea = area;
};

FlightMonitor.prototype.showInfo = function(which) {
	if (this.isLoaded(which)) {
		var html = this.links[this.filterArea][which].getDescription();
		$('#info_content').html(html);
	}
	$('#info').show();
	that.resize();
	setTimeout("that.resize()", 100);
	setTimeout("that.resize()", 1000);
};

FlightMonitor.prototype.hideInfo = function() {
	$('#info').hide();
	this.resize();
};

FlightMonitor.prototype.toggleInfo = function(which) {
	if (this.isInfoVisible()) this.hideInfo();
	else this.showInfo(which);
};

FlightMonitor.prototype.isInfoVisible = function() {
	if ($('#info').css("display") == "none") return false;
	else return true;
};

FlightMonitor.prototype.setAutoRefresh = function (timeout) {
	this.autorefreshtimeout = timeout;
	if (this.autorefresh != null) clearInterval(this.autorefresh);
	if (timeout > 0) this.autorefresh = setInterval('updateFlight()', timeout);
	updateFlight();
};

FlightMonitor.prototype.getViewAltitude = function() {
	// Get the current view
	if (!ge)
		return 2000000;
	var camera=ge.getView().copyAsCamera(ge.ALTITUDE_RELATIVE_TO_GROUND)
	// Zoom out to twice the current distance
	return camera.getAltitude();
};

FlightMonitor.prototype.modelScale = function() {
	var placemarks = ge.getElementsByType('KmlPlacemark');
	var viewAlt = that.getViewAltitude();
	
	if (viewAlt >= 1000000)
		fScale = 100000;
	else if (viewAlt < 1000000 && viewAlt >= 100000)
		fScale = 10000;
	else if (viewAlt < 100000 && viewAlt >= 50000)
		fScale = 5000;
	else if (viewAlt < 50000)
		fScale = 1000;
	
	if (fScale == that.currentModelScale)
		return;
	else
		that.currentModelScale = fScale;
	
	for (var i = 0; i < placemarks.getLength(); ++i) {
		var placemark = placemarks.item(i);
		if (placemark.getName() == '')
			continue;
		var geometry = placemark.getGeometry();
		var scale = geometry.getScale();
		scale.set(fScale, fScale, fScale);
	}
};

FlightMonitor.prototype.toggleModelZoom = function() {
	if (this.modelzoom)
		this.modelzoom = 0;
	else
		this.modelzoom = 1;
};

