//"gExplorer to explore "Places"
//written by: Paul van Dinther
//            Dinther Product Design
//            Software development and specialists in simulation
//            email: vandinther@gmail.com
  
    //multiply with this to get angle in radians
    var degreesToRad = 0.017453292519943;
	
	//multiply a meter with this to get a delta latitude
    var metersToLocalLat = 0.000032964014284406189909348960717883
    var halfmetersToLocalLat = metersToLocalLat/2; 

    //multiply a delta latitude with this to get meters (1/60 of a degree is 1852 meters)
    var deltaLatitudeToMeters = 30336.1;
    
    //multiply with this to get angle in radians
    var degreesToRad = 0.017453292519943;

    //this is a full circle equivalent of 360 degrees expressed in radians
    var radianCircle = 57.295779513082320876798154814105;

    var ge = null;
    var map = null;
	var landerModel = null;
	var landerParent = null;
	var crashedModel = null;
	var crashedParent = null;
	var landerShadow = null;
	var landerFlame = null;
	var flameParent = null;
	var lander = null;
	var target = null; 
	var rocketPlaying = false;
	var engineflash = null;
	var score = 0;
    var lastMill;
	var targetLat = 0;
	var targetLon = 0;
	var run = false;
	var landed = false;
	var camDistance = 0;
	var landingDistance = 0;
	var camDistance = new smooth(180,180,100,0.0,6,6);
	var instrumentAltitude = new smooth(180,180,100,0.0,10,6);
	var oldSoundID = '';
	var lowFuelReport = false;
	var placemark = null;
	var unlimitedFuel = false;
    
    var leftKey = false;
    var rightKey = false;
    var upKey = false;
    var downKey = false;
    var spaceKey = false;

    var mouseIsDown = false;
    var currentCam = null;
    var distanceCutOff = 4000;
    var now = 0;
    
    var bannerTimeOut = 0;
    var showBanner = true;

    var fullScreenState = false;
    var placesStart = null;
    
    var normalLeft = 0;
    var normalTop = 0;
    var normalWidth = 0;
    var normalHeight = 0;
    
    var applicationTitle = ''
    var mouseY = 0;
    var mouseX = 0;
    var windowFocusDone = false;
    var aspect = 0;
    var shift = 0;
	var dustblast = null;
	var dustcover = null;

    var noMoveTimeOut = 60;
	//var fuelDisplay = null;
	//var scoreDisplay = null;


function resizeWindow(){
    aspect = document.getElementById('map3d').offsetWidth / document.getElementById('map3d').offsetHeight;
	altitudeTape.getSize().setY(altitudeRateTape.getSize().getX()* aspect * 40.625);
	altitudeRateTape.getSize().setY(altitudeRateTape.getSize().getX()* aspect * 62.5);
	instrumentPanel.getSize().setY(instrumentPanel.getSize().getX()* aspect * 14.285714285714285714285714285714);
	altitudeTape.getOverlayXY().setY(-((lander.altitude+1925)/100));
	altitudeRateTape.getOverlayXY().setY(0.5 - (aspect*(lander.vSpeed/30)));
	//altitudeTape.getScreenXY().setY(0 * aspect);
	altitudeTape.getOverlayXY().setY(0.5 - (aspect * 0.255));
	percentGauge.getSize().setY(percentGauge.getSize().getX()* aspect);
	percentGauge.getOverlayXY().setY(0.5 +(0.185*aspect));
	percentNeedle.getSize().setY(percentNeedle.getSize().getX()* aspect);
	percentNeedle.getOverlayXY().setY(0.5 +(0.185*aspect));
}

    
function init(){
    //masterHost = 'http://dinther.dnsalias.com/planetinaction/moonlander/';
    masterHost = 'http://www.planetinaction.com/moonlander/';
   	applicationTitle = 'Moonlander v1.0 by PlanetInAction.com';        
    //google.load("earth", "1", {'other_params': 'sensor=false' });
    lastMill = (new Date()).getTime();
    //google.loader.ApiKey = 'ABQIAAAAO9Sgc3F39TEw1oJFd3DA1RSsx7swxwOcboxZPrvi4OPe-BdlWxQKBurh_guMIiVqxQXsnVPcFb0uag'; //dinther.dnsalias.com
    google.loader.ApiKey = 'ABQIAAAAO9Sgc3F39TEw1oJFd3DA1RSQPGU1IGcalbIO44ys7kPBwJdFlBRHbESMO1sQkjVQUlhN6fBj296jZA'; //www.planetinaction.com
  	//var sphereNode = document.getElementById('sphere');
	var options = {};
  	options = { database: 'http://khmdb.google.com/?db=moon' };    
	google.earth.createInstance("map3d", initCB, failureCB, options);
	
    soundManager.url = masterHost; // directory where SM2 .SWFs live
    soundManager.debugMode = false;
    soundManager.useConsole = false;
    soundManager.useHighPerformance = true;
    //soundManager.waitForWindowLoad = true; 
    
    if(navigator.appName.indexOf("Microsoft") != -1){soundManager.onload = function(){ createSounds();}}
    else createSounds();	
		
}

function createSounds(){
    soundManager.createSound({id: 'v220feet', url: '220feet.mp3', autoLoad: true});
	soundManager.createSound({id: 'v200feet', url: '200feet.mp3', autoLoad: true});
	soundManager.createSound({id: 'v100feet', url: '100feet.mp3', autoLoad: true});
	soundManager.createSound({id: 'v75feet', url: '75feet.mp3', autoLoad: true});
	soundManager.createSound({id: 'v40feet', url: '40feet.mp3', autoLoad: true});
	soundManager.createSound({id: 'v30feet', url: '30feet.mp3', autoLoad: true});
	soundManager.createSound({id: 'v10feet', url: '10feet.mp3, autoLoad: true'});
	soundManager.createSound({id: 'landed', url: 'landed.mp3', autoLoad: true});
	soundManager.createSound({id: 'problem', url: 'problem.mp3', autoLoad: true});
	soundManager.createSound({id: 'staticend', url: 'staticend.mp3', autoLoad: true});		
	soundManager.stopAll();
}

function initCB(object) {
    ge = object;
    ge.getWindow().setVisibility(true);
    ge.getOptions().setStatusBarVisibility(true);
    ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE);
    ge.getOptions().setFlyToSpeed(ge.SPEED_TELEPORT);
    //ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, 0);
	//ge.getOptions().setAtmosphereVisibility(false);

	createSToStart();
	createAltitudeTape();
	createAltitudeRateTape();
	createInstrumentPanel();
	createVSpeedSign();
	createLatSpeedSign();
	createLevelSign();
	createLandedSign();
	createPercentGauge();
	createPercentNeedle();
	createLogo();

	//fuelDisplay = new textDisplay();
	//fuelDisplay.setDisplayLength(4);
	//fuelDisplay.digitSize = 0.02;
	//fuelDisplay.loadCharacterIcon('0',masterHost + 'd0.png');	
	//fuelDisplay.loadCharacterIcon('1',masterHost + 'd1.png');
	//fuelDisplay.loadCharacterIcon('2',masterHost + 'd2.png');
	//fuelDisplay.loadCharacterIcon('3',masterHost + 'd3.png');
	//fuelDisplay.loadCharacterIcon('4',masterHost + 'd4.png');
	//fuelDisplay.loadCharacterIcon('5',masterHost + 'd5.png');
	//fuelDisplay.loadCharacterIcon('6',masterHost + 'd6.png');	
	//fuelDisplay.loadCharacterIcon('7',masterHost + 'd7.png');	
	//fuelDisplay.loadCharacterIcon('8',masterHost + 'd8.png');	
	//fuelDisplay.loadCharacterIcon('9',masterHost + 'd9.png');

	//scoreDisplay = new textDisplay();
	//scoreDisplay.setDisplayLength(4);
	//scoreDisplay.drawOrder = 200;
	//scoreDisplay.digitSize = 0.02;
	//scoreDisplay.loadCharacterIcon('0',masterHost + 'd0.png');	
	//scoreDisplay.loadCharacterIcon('1',masterHost + 'd1.png');
	//scoreDisplay.loadCharacterIcon('2',masterHost + 'd2.png');
	//scoreDisplay.loadCharacterIcon('3',masterHost + 'd3.png');
	//scoreDisplay.loadCharacterIcon('4',masterHost + 'd4.png');
	//scoreDisplay.loadCharacterIcon('5',masterHost + 'd5.png');
	//scoreDisplay.loadCharacterIcon('6',masterHost + 'd6.png');	
	//scoreDisplay.loadCharacterIcon('7',masterHost + 'd7.png');	
	//scoreDisplay.loadCharacterIcon('8',masterHost + 'd8.png');	
	//scoreDisplay.loadCharacterIcon('9',masterHost + 'd9.png');
	//scoreDisplay.loadCharacterIcon('-',masterHost + 'ddash.png');

    leftKey = false;
    rightKey = false;
    upKey = false;
    downKey = false;

    google.earth.addEventListener(ge, "frameend", moveexplorer);
    google.earth.addEventListener(ge.getWindow(), 'mouseup', setMouseUp);
    google.earth.addEventListener(ge.getWindow(), 'mousedown', setMouseDown);
    google.earth.addEventListener(ge.getWindow(), 'mousemove', setMouseMove);

	//setup view to moon landscape
	google.earth.fetchKml(ge, masterHost + 'lander2.kmz', initLander);
	google.earth.fetchKml(ge, masterHost + 'lunar_crashed.kmz', initCrashed);
	google.earth.fetchKml(ge, masterHost + 'flame4.kmz', initFlame);
	targetLat = 0.6814861;
	targetLon = 23.459758;
	target = createOverlay(0.6814861,23.459758,9,9,0,masterHost + 'target.png');
	target.getColor().setA(100);
	landerShadow = createOverlay(0.6814861,23.459758,5,5,0,masterHost + 'lander_shadow2.png');
	lander = new landerSim(0.6814861,23.47,-1850,0,-50,0,-90);
	lander.maxFuel = 30;
    lander.onGround = function (){ handleOnGround(); }
	
	//create blast array
	//for (var i = 0; i < 1; i++) {
		dustblast = createOverlay(lander.latitude,lander.longitude,15,15,0,masterHost + 'blast.png');
		dustblast.getColor().setA(0);
		dustcover = createOverlay(lander.latitude,lander.longitude,30,30,0,masterHost + 'dust.png');
		dustcover.getColor().setA(0);
	//}	
	
	
	
	engineflash.engineLoad('');
	engineflash.enginePlay();
	engineflash.engineVolume(0);
	//engineflash.engineVolume(40);
        resizeWindow();
	window.focus();
}

function initialiseGame(){
	vspeedsign.setVisibility(false);
	latspeedsign.setVisibility(false);
	levelsign.setVisibility(false);
	landedsign.setVisibility(false);
	lowFuelReport = false;
	run = true;
	lander.latitude = 0.6814861;
	lander.longitude = 23.47;
	lander.altitude = -1850;
	instrumentAltitude.set(74);
	lander.lonSpeed = -30;
	lander.latSpeed = 0;
	lander.vSpeed = 0;
	lander.roll.set(-75);
	lander.pitch.set(0);
	lander.fuel = lander.maxFuel;
	lander.thrust = 0;
	landerParent.setVisibility(true);
	crashedParent.setVisibility(false);
	flameParent.setVisibility(false);
	landed = false;
	camDistance.set(180);
	soundManager.stopAll();
	ge.setBalloon(null);
	ge.getFeatures().removeChild(placemark);

}

function handleOnGround(){
	var aboveTarget = false;
	landingDistance = distanceof(lander.latitude, lander.longitude,targetLat,targetLon);
	if (landingDistance < 4.5) {
		aboveTarget = true;
	}

	var maxVSpeed = 1.2;
	var maxSpeed = 1.2;
	spaceKey = false;
	dustblast.getColor().setA(0);
	var roll = Math.abs(lander.roll.current);
	var pitch = Math.abs(lander.pitch.current);
	
	
	vspeedsign.setVisibility(false);
	latspeedsign.setVisibility(false);
	levelsign.setVisibility(false);
	landedsign.setVisibility(false);
	
	lander.horizontalSpeed = Math.sqrt(lander.latSpeed*lander.latSpeed + lander.lonSpeed*lander.lonSpeed);
	landed = true;
	if (lander.vSpeed < -maxVSpeed) {
		vspeedsign.setVisibility(true);
		landed = false;
	}
	else
	{
		if (lander.horizontalSpeed > maxSpeed) {
			latspeedsign.setVisibility(true);
			landed = false;
			lander.latSpeed = 0;
			lander.lonSpeed = 0;
		}
		else
		{
			lander.latSpeed = 0;
			lander.lonSpeed = 0;
			if (roll > 10) {
				levelsign.setVisibility(true);
				landed = false;
				lander.roll.set(0);
			}
			else
			{
				lander.roll.set(0);	
			}
			if (pitch.current > 10) {
				levelsign.setVisibility(true);
				landed = false;
				lander.pitch.set(90);
			}
			else
			{
				lander.pitch.set(0);
			}
		}
	}
	if (landed==true) {
		if (aboveTarget == true) 
			landedaction();
	}
	else 
	{
		crashed();
	}
}
       
function landedaction(){
	landedsign.setVisibility(true);
	crashedModel.getLocation().setLatLngAlt(0.6814861,23.460078,0);
	crashedParent.setVisibility(false);
	landerParent.setVisibility(true);
	engineflash.engineVolume(0);
	soundManager.stopAll();
	soundManager.play('landed', {volume:100});
	run = false;
	landed = true;
	showStatistics();
}

function crashed(){
	crashedModel.getLocation().setLatLngAlt(lander.latitude,lander.longitude,lander.altitude);
	crashedParent.setVisibility(true);
	landerParent.setVisibility(false);
	engineflash.engineVolume(0);
	soundManager.stopAll();
	soundManager.play('staticend', {volume:100});
	lander.thrust = 0;
	run = false;
	landed = false;
	score = 0;
	showStatistics();
}

function showStatistics(){
	if (placemark != null) {
		ge.getFeatures().removeChild(placemark);
		placemark = null;
	}
	placemark = ge.createPlacemark('');
	var point = ge.createPoint('');
	point.setLatitude(lander.latitude);
	point.setLongitude(lander.longitude);
	point.setAltitude(lander.height);
	
	
	// Apply stylemap to a placemark
	var styleMap = ge.createStyleMap('');
	// Create normal style for style map
	var normalStyle = ge.createStyle('');
	var normalIcon = ge.createIcon('');
	normalIcon.setHref(''); //'http://maps.google.com/mapfiles/kml/shapes/triangle.png'
	normalStyle.getIconStyle().setIcon(normalIcon);

	// Create highlight style for style map
	var highlightStyle = ge.createStyle('');
	var highlightIcon = ge.createIcon('');
	highlightIcon.setHref(''); //'http://maps.google.com/mapfiles/kml/shapes/square.png'
	highlightStyle.getIconStyle().setIcon(highlightIcon);

	styleMap.setNormalStyle(normalStyle);
	styleMap.setHighlightStyle(highlightStyle);

	// Apply stylemap to a placemark
	placemark.setStyleSelector(styleMap);
	
	
	
	placemark.setGeometry(point);
	ge.getFeatures().appendChild(placemark);
	if (landed){ 
		var statText = '<h2>Eagle touchdown</h2>';
	}else
	{
		var statText = '<h2>Eagle has been lost</h2>';
	}
	var landingSpeed = lander.vSpeed*3.28;
	var score = 0;
	if (landed) {
		//score = lander.fuel * (10000 - landingDistance * landingDistance);
		score = ((100 - landingDistance^2 * 5 - lander.vSpeed*5))*lander.fuel*10
		//score = (100-(((landingDistance)^2 * 5)-(lander.vSpeed*5)))*lander.fuel*10;
		if (score<0) score = 0;
		
	}
		statText += '<p style="color: black;">Your statistics...</p>';
		if (unlimitedFuel) statText += '<p style="color: black;">Fuel cheat on.</p>'; 
	    statText += '<table width="100%" style="color: black;"><tbody>'
		statText += '<tr><td>Fuel remaining</td><td>' + lander.fuel.toFixed(1) + ' s</td><td><b>(Spec: max '+ lander.maxFuel.toFixed(0) +' s)</b></td></tr>';
	    statText += '<tr><td>Vertical speed</td><td>' + landingSpeed.toFixed(1) + ' feet/sec</td><td><b>(Spec: max -4 f/s)</b></td></tr>';
		statText += '<tr><td>Horizontal speed</td><td>' + lander.horizontalSpeed.toFixed(1) + ' m/s</td><td><b>(Spec: max 1.2 m/s)</b></td></tr>';
		statText += '<tr><td>Dist to target</td><td>' + landingDistance.toFixed(2) + ' m</td><td><b>(Spec max 4.5 m)</b></td></tr>';
		statText += '<tr><td>Pitch</td><td>' + lander.pitch.current.toFixed(0) + ' deg</td><td><b>(Spec: max 10)</b></td></tr>';
		statText += '<tr><td>Roll</td><td>' + lander.roll.current.toFixed(0) + ' deg</td><td><b>(Spec: max 10)</b></td></tr>';
		statText += '<tr><td>&nbsp;</td><td></td><td></td></tr>';
		statText += '<tr><td>Your score</td><td COLSPAN=2><b>' + score.toFixed(0) + ' points</b></td></tr></tbody></table>';	
    //placemark.setDescription(statText);
	var balloon = ge.createHtmlStringBalloon('');
	balloon.setMinWidth(340);
    balloon.setMaxWidth(340);
    balloon.setFeature(placemark);
	balloon.setContentString(statText);
    ge.setBalloon(balloon);
}


function initLander(object){  
    if (!object) {
        // wrap alerts in API callbacks and event handlers
        // in a setTimeout to prevent deadlock in some browsers
        setTimeout(function() { alert('Bad or null KML.'); }, 0);
    return;
    }  
	landerParent = object;
	landerModel = object.getFeatures().getChildNodes().item(1).getGeometry();
	landerModel.setAltitudeMode(ge.ALTITUDE_ABSOLUTE);
	landerModel.getScale().set(2,2,2);
	landerModel.getLocation().setLatLngAlt(0.6814861,23.459758,-1925);
    ge.getFeatures().appendChild(object);
}

function initFlame(object){  
    if (!object) {
        // wrap alerts in API callbacks and event handlers
        // in a setTimeout to prevent deadlock in some browsers
        setTimeout(function() { alert('Bad or null KML.'); }, 0);
    return;
    }
	flameParent = object;  
	landerFlame = object.getFeatures().getChildNodes().item(1).getGeometry();
	landerFlame.setAltitudeMode(ge.ALTITUDE_ABSOLUTE);
	landerFlame.getScale().set(2,2,2);
	landerFlame.getLocation().setLatLngAlt(0.6814861,23.459758,-1925);
	flameParent.setVisibility(false);
    ge.getFeatures().appendChild(object);
}

function initCrashed(object){  
    if (!object) {
        // wrap alerts in API callbacks and event handlers
        // in a setTimeout to prevent deadlock in some browsers
        setTimeout(function() { alert('Bad or null KML.'); }, 0);
    return;
    }	
	crashedParent = object;  
	crashedModel = object.getFeatures().getChildNodes().item(1).getGeometry();
	crashedModel.getScale().set(2,2,2);
	crashedModel.setAltitudeMode(ge.ALTITUDE_ABSOLUTE);
	crashedModel.getLocation().setLatLngAlt(0.6814861,23.459758,-1925);
	crashedParent.setVisibility(false);
    ge.getFeatures().appendChild(object);
}


function failureCB(object) {
    window.location="../installgoogleearth.htm"
}

function toggleFullScreen(){
	if (fullScreenState == true) {makeNormalScreen();}
    else {makeFullScreen();}
}
function makeFullScreen(){
    if (!fullScreenState){
    	//hide adverts specially for Chrome
    	document.getElementById('notge').style.display = 'none';
    	document.getElementById('headermoonlander').style.display = 'none';
        document.getElementById('footeradvert').style.display = 'none';
    	document.getElementById('rightcolumn').style.display = 'none';
    	document.getElementById('footeradvert').style.display = 'none';
    	document.getElementById('footer').style.display = 'none';
    	document.getElementById('signoff').style.display = 'none';
    	var container = document.getElementById('map3d');
		var mybuttonbar = document.getElementById('buttonbar')
		mybuttonbar.style.position = 'absolute';
		mybuttonbar.style.bottom = '4px';
		mybuttonbar.style.left = '10px'; 
		document.getElementById('fullscreenbtn').value='Normal screen';
    	container.className ="container-fullscreen90";
    	fullScreenState = true;
		resizeWindow();
    	window.focus();
   	}
}

function makeNormalScreen(){
    if (fullScreenState){
    	document.getElementById('notge').style.display = '';
    	document.getElementById('headermoonlander').style.display = '';
        document.getElementById('footeradvert').style.display = '';
    	document.getElementById('rightcolumn').style.display = '';
    	document.getElementById('footeradvert').style.display = '';
    	document.getElementById('footer').style.display = '';
    	document.getElementById('signoff').style.display = '';
    	var container = document.getElementById('map3d');
		var mybuttonbar = document.getElementById('buttonbar')
		mybuttonbar.style.position = 'static';
		document.getElementById('fullscreenbtn').value='Full screen';	
    	container.className ="container";
    	fullScreenState = false;
		resizeWindow();
   	}
}

function setMouseUp(event){
    mouseClickAge = 0;
    var handledClick = false;
    var INSET_PIXELS_X = document.getElementById("map3d").offsetWidth - event.getClientX();
    var INSET_PIXELS_Y = event.getClientY();
    var PIXELS_Y = document.getElementById("map3d").offsetHeight - event.getClientY();
       
    //click in fullscreen area
    if (INSET_PIXELS_X < 32 && handledClick == false){
        if (INSET_PIXELS_Y < 32){
            toggleFullScreen();
            handledClick = true;
        }
    }
     
    if (handledClick){
        event.preventDefault();
    } 
    window.focus();
    ge.getWindow().blur();
    mouseIsDown = false;

}

function setMouseDown(event){
    //currentCam = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE);
    mouseIsDown = true;
    windowFocusDone = false;

}

function setMouseMove(event){
    if (mouseClickAge > mousePauseDuration && (exploring || recorder.recording || recordCountDown > -1) && myExplorer.altitude.target < 100000){ 
        mouseX = ((event.getClientX() / document.getElementById("map3d").offsetWidth)-0.5)*2;
        if (mouseX > 0){
            spin = (mouseX * mouseX)*250;
        }
        else {
            spin = (-mouseX * mouseX)*250;
        }
        //spin = ((event.getClientX() / document.getElementById("map3d").offsetWidth) - 0.5)*360;
        mouseY = ((event.getClientY() / document.getElementById("map3d").offsetHeight) - 0.5) * 2;
        if (mouseY > 0){
            myExplorer.targetHeadTilt.target = (-mouseY * mouseY)*70;
        }
        else {
            myExplorer.targetHeadTilt.target = (mouseY * mouseY) * 70;
        }
        mouseMoveAge = 0;
    }
}

function moveexplorer() {
	//measure frame time so animation is frame independant
    now = (new Date()).getTime();
    var deltaTime = (now - lastMill) / 1000.0;
	var heightAlpha = 0;
    lastMill = now;
	sToStart.setVisibility(!run);   
	dustcover.getColor().setA(dustcover.getColor().getA() - dustcover.getColor().getA() * deltaTime * 0.1); 
	if (run) {
		lander.update(deltaTime);
		//apply input
		if (spaceKey == true && lander.fuel > 0) {
			lander.thrust = lander.maxMainThrust;
			if (!rocketPlaying) {
				//engineflash.enginePlay();
				engineflash.engineVolume(40);
			}
			rocketPlaying = true;
			heightAlpha = 200 - (lander.height * 20);
			if (heightAlpha < 0) { heightAlpha = 0; }
			dustcover.getColor().setA(dustcover.getColor().getA() + (heightAlpha + 55 - dustcover.getColor().getA()) * deltaTime * 3);  
		}
		else {
			lander.thrust = 0;
			engineflash.engineVolume(0);
			rocketPlaying = false;
		}		
	}
	if (unlimitedFuel) lander.fuel = lander.maxFuel;
	camDistance.update(deltaTime);

	flameParent.setVisibility(lander.thrust != 0);
	landerModel.getLocation().setLatLngAlt(lander.latitude,lander.longitude,lander.altitude);
	landerFlame.getLocation().setLatLngAlt(lander.latitude,lander.longitude,lander.altitude);
	landerModel.getOrientation().set(0, lander.pitch.current, lander.roll.current);
	landerFlame.getOrientation().set(0, lander.pitch.current, lander.roll.current); 
	var shadowoffset = 0.0000025 + lander.height * 0.00005;
	setLatLonBoxAsMeters(landerShadow.getLatLonBox(), lander.latitude + shadowoffset,lander.longitude - shadowoffset, 5, 5, -lander.roll.current/2);
	if (run) {
		updateView(deltaTime);
		//Update instruments
		instrumentAltitude.target = lander.height;
		instrumentAltitude.update(deltaTime);
		
		altitudeTape.getOverlayXY().setY(0.5 - (aspect * 0.255)-(instrumentAltitude.current * aspect * 0.013));
			
		altitudeRateTape.getOverlayXY().setY(0.5 - (aspect*(lander.vSpeed/65.5)));
		landingDistance = distanceof(lander.latitude, lander.longitude,targetLat,targetLon);
		score = lander.fuel * (100-landingDistance);
		if (lander.fuel == 0 && !lowFuelReport){
			soundManager.stopAll();
			soundManager.play('problem', {volume: 100});
			lowFuelReport = true;
		}			
	}
	else {
		animateView(deltaTime);
	}
	
	percentNeedle.setRotation(-(lander.fuel/lander.maxFuel)*270);

	//var fuelValue = '0000' + Math.floor(lander.fuel * 100);
	//fuelValue = fuelValue.substring(fuelValue.length-4,fuelValue.length);
	//document.title = fuelValue;	
	//fuelDisplay.render(fuelValue,0.92,0.5 +(0.16*aspect), aspect);
	var scoreValue = '----';
	if (score > 0) {
		scoreValue += '0000'+Math.floor(score);
		scoreValue = scoreValue.substring(scoreValue.length-4,scoreValue.length);
	}
	//scoreDisplay.render(scoreValue+'',0.92,0.5 -(0.140*aspect), aspect);
	
	//update blast
	//for (var i = 0; i < 1; i++) {
	dustblast.getColor().setA(heightAlpha);
	setLatLonBoxAsMeters(dustblast.getLatLonBox(),lander.latitude,lander.longitude,15,15,0);
	setLatLonBoxAsMeters(dustcover.getLatLonBox(),lander.latitude,lander.longitude,30,30,0);

		
	//}
	
	
	//soundclips      
	if (lander.vSpeed < 0 && run){
		var soundID = '';
		if (lander.height < 67 && lander.height > 60 && oldSoundID !== 'v220feet') {soundID = 'v220feet';}
		if (lander.height < 60 && lander.height > 30 && oldSoundID != 'v200feet') {soundID = 'v200feet';}
		if (lander.height < 30 && lander.height > 23 && oldSoundID != 'v100feet') {soundID = 'v100feet';}
		if (lander.height < 23 && lander.height > 12 && oldSoundID != 'v75feet') {soundID = 'v75feet';}
		if (lander.height < 12 && lander.height >  9 && oldSoundID != 'v40feet') {soundID = 'v40feet';}
		if (lander.height <  9 && lander.height >  3 && oldSoundID != 'v30feet') {soundID = 'v30feet';}
		if (lander.height < 3 && oldSoundID != '10feet') {soundID = 'v10feet';}
	
		if (soundID != '') {
			soundManager.stopAll();
			soundManager.play(soundID, {volume: 100});
			oldSoundID = soundID;
		}
	}
}

function updateView(deltaTime){
    currentCam = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE);
	camDistance.target = 40 + lander.height * 1.5;
	cameraLookAt(currentCam,lander.latitude,lander.longitude,lander.altitude,180,70,camDistance.current);
    ge.getView().setAbstractView(currentCam);
}

function animateView(deltaTime){
    currentCam = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE);
	camDistance.target = 180;
	cameraLookAt(currentCam,lander.latitude,lander.longitude,lander.altitude,currentCam.getHeading()-180+10*deltaTime,60,camDistance.current);
    ge.getView().setAbstractView(currentCam);	
}

function keyDown(event) {
    if (!event) {
        event = window.event;
    }
    switch(event.keyCode){
        case 27:           {if (fullScreenState){makeNormalScreen();}else{resetPlace();} event.returnValue = false; break;} //ESCAPE
        case 32: {spaceKey = true; event.returnValue = false; break;} //space
        case 37: {leftKey = true; lander.roll.target += 5; noMoveTimeOut = -1; event.returnValue = false; break;} //left
        case 39: {rightKey = true; lander.roll.target -= 5; noMoveTimeOut = -1; event.returnValue = false; break;} //right
        case 38: {upKey = true; lander.pitch.target += 5; noMoveTimeOut = -1; event.returnValue = false; break;} //up
        case 40: {downKey = true; lander.pitch.target -= 5; noMoveTimeOut = -1; event.returnValue = false; break;} //down     
        default: return true;
    }
    mouseIsDown = false;
    return false;
}

function keyUp(event) {
    if (!event) {
        event = window.event;
    }   
    switch(event.keyCode){
		case 32: {spaceKey = false; event.returnValue = false; break;} //space
        case 37: {leftKey = false; event.returnValue = false; break;} //left
        case 39: {rightKey = false; event.returnValue = false; break;} //right
        case 38: {upKey = false; event.returnValue = false; break;} //up
        case 40: {downKey = false; event.returnValue = false; break;} //down
        default: return true;
    }
    mouseIsDown = false;
    return false;
}

function stopDef(e) {
    if (e &&e.preventDefault) e.preventDefault();
    else if (window.event && window.event.returnValue)
    event.cancelBubble = true;
    event.stopPropagation();    
    window.eventReturnValue = false;
}

//places overlay with size defined in meters corrected for latitude
function createOverlay(latitude, longitude, height, width, angle, href) {
    var icon = ge.createIcon('');
    icon.setHref(href);
    var latLonBox = ge.createLatLonBox('');
    var myGroundOverlay = ge.createGroundOverlay('');
    myGroundOverlay.setIcon(icon);
    myGroundOverlay.setLatLonBox(latLonBox);
    setLatLonBoxAsMeters(myGroundOverlay.getLatLonBox(), latitude, longitude, height, width, angle);
    ge.getFeatures().appendChild(myGroundOverlay);
    return (myGroundOverlay);
} 

//defines latlonbox at a given location expressed in size and width and height in meters and angle
function setLatLonBoxAsMeters(latLonBox, latitude, longitude, height, width, angle){
    var radLatitude = latitude * degreesToRad;
    var cosLatitude = Math.cos(radLatitude);         
    height = height / deltaLatitudeToMeters;  
    width = width / (deltaLatitudeToMeters * cosLatitude );
    latLonBox.setNorth(latitude + height);
    latLonBox.setSouth(latitude - height);
    latLonBox.setEast(longitude + width);
    latLonBox.setWest(longitude - width);
    latLonBox.setRotation(-angle+90);
    return (latLonBox);
}

//sets the kmlcamera to the defined bearing, tilt and distance relative to the given point (lat,lon,alt)
function cameraLookAt(camera, latitude, longitude, altitude, bearing, tilt, distance){
  //calc camera position
  var radbearing = bearing * degreesToRad;
  var radtilt = tilt * degreesToRad; 
  var horDistance = Math.sin(radtilt)* distance;
  var vertDistance = Math.cos(radtilt)* distance;
  var deltalon = Math.sin(radbearing) * horDistance * lander.metersToLocalLon;
  var deltalat = Math.cos(radbearing) * horDistance * metersToLocalLat;
  camera.set(latitude + deltalat, longitude + deltalon, altitude + vertDistance, ge.ALTITUDE_ABSOLUTE, bearing+180, tilt, 0);	
}

//return disance between two points at equal altitude
function distanceof(latitude1,longitude1,latitude2,longitude2){
	var d1 = (longitude1-longitude2) * (1/lander.metersToLocalLon);
	var d2 = (latitude1 - latitude2) * deltaLatitudeToMeters;
	return Math.sqrt(d1*d1+d2*d2);	
}

function test1(){
	myDisplay.render('54321',0.5,0.5, aspect);
}

function test2(){
	myDisplay.render('12345',0.5,0.5, aspect);
}

function toggleUnlimited(){
	if (run==false) unlimitedFuel = !unlimitedFuel;
	document.getElementById('unlimited').checked = unlimitedFuel;
}
