var helico= {
 	  lat:0,
      lng:0,
	  alti:0,
	  alti_cons:0,
	  alti_sol:0,
	  alti_model0:0,
	  alt_min:0,
	  alt_max:6000,
	  alti_avion_old:0,
	  loc:null,
	  scal:1,
	  scal_obj:null,
	  orient:null,
	  tilt:0,
	  roll:0,
	  heading:0,	  
	  d_cap:0,
	  placemark:null,
	  auto:true,
	  timer_auto:-1,
	  nom:"Helicopter",
      model:"helo_aiguilles.kmz/models/helo_aiguilles.dae",
	  cap0:180,
	  cruise_speed:25,
	  speed:0,
	  k_speed:0,
	  type:0  
};
var v_cons={ vr:0, vz:0, vx:0, vy:0,rc:0.2};
var v_reel={ vr:0, vz:0, vx:0, vy:0,rc:0.2};
	
var scene={	update_on:false,init_3d_ok:true,idx_lat:0,dist_min_arrive:0.001,t_last_modif:0,approche:true};

google.load("earth", "1");
var ge = null;
var href=window.location.href.substr(0,(window.location.href.lastIndexOf("/")))+"/";
var screenOverlay="";


/* Initialisation */
/******************/
function init() {
		position_boutons();
		init_site(); // Liste des sites
		google.earth.createInstance("map3d", initCallback, failureCallback);
		setTimeout('document.getElementById("keyboard").style.display="none";',5000);
		document.getElementById("voyant_r").style.visibility="hidden";
		cam_view(1);// BG colour
}
function dit(x){
	document.getElementById("disp_").innerHTML+=x;
}
// Init GE
function initCallback(object) {
	
	  ge = object;
	  ge.getWindow().setVisibility(true);
	  ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, true);
	  ge.getOptions().setFlyToSpeed(3.5);
	  camera.type_of_view=1;		
		helico.lat=lati[0] ;
		helico.lng=lngi[0];
		init_platforme();	
 		map_type=G_PHYSICAL_MAP;	
		init_carte_2d();
		init_instruments();
		place();  // Icone lieux
		setTimeout("update_instruments();",1000);  // on donne tempas arrivé info fonds
		
		
		window.google.earth.addEventListener(ge, 'frameend', function() { 		
					
					mise_jour_position ();
				});
		
	Camera(camera.lat,camera.lng,camera.alti,camera.range,camera.head,camera.tilt);	
		setTimeout("approche_camera();",1500); 
	
		
}

function mise_jour_position () {  //Helico en cicuit sommets
				var date_t=new Date();
				var le_temps=date_t.getTime();
				var t0=le_temps-scene.t_last_modif;
				
				if ( t0>50) {
					
					scene.t_last_modif=le_temps;
					calcul_position();
					update_position_helico() ;
					if (scene.approche) {
						
										Camera();
												
					} else {
											if (scene.update_on) {
												
												camera.head=camera.rc*(helico.heading+camera.offset)+(1-camera.rc)*camera.head;
												
												var range_=Math.max(20,2.5*helico.alti_sol); // Pour eviter disparition helico en altitude
												
												//range_=Math.max(range_,(helico.alti-helico.alti_avion_old)*100);
												camera.range=camera.rc*range_+(1-camera.rc)*camera.range;
												if (camera.range<200) {
													helico.scal=1;
												} else {
													helico.scal=camera.range/200; // Illusion pour ne pas faire disparaitre helico
													
												}
												
												var tilt_=Math.min(120,200*get_alti_camera()/range_);
												tilt_=Math.min(tilt_,120+50*Math.min(helico.alti-helico.alti_avion_old,0));
												tilt_=Math.max(tilt_,0);
												camera.tilt=camera.rc*tilt_+(1-camera.rc)*camera.tilt;
												camera.lat=helico.lat;
												camera.lng=helico.lng;
												camera.alti=helico.alti;
												if (camera.type_of_view==2) {
													camera.head=frc(helico.heading,camera.head,0.3);
													camera.tilt=frc(90+helico.tilt,camera.tilt,0.3);
													camera.roll=frc(helico.roll,camera.roll,0.3);
												}
												Camera();
												helico.scal_obj.set(helico.scal,helico.scal,helico.scal);
											}
					}
				
									
					 
					
				}
				
				 
				
	
}
function calcul_position() {

	
	
	if (scene.update_on && scene.init_3d_ok) {
		
					// lissage altitude
					var alti_du_sol= ge.getGlobe().getGroundAltitude(helico.lat,helico.lng); // Altitude du sol <0 en mer
					alti_du_sol=Math.max(alti_du_sol,0) ; //pas de sol <0 
					helico.alti_avion_old=helico.alti; // Alti par rapport à mer
					
					if (helico.auto) { //automatique
							if ( helico.alti_cons<120) { //Decollage
								helico.alti_cons=0.05+1.03*helico.alti_cons;
								helico.alti_cons=Math.min(helico.alti_cons,120)
								v_cons.vx=Math.floor(helico.alti_cons/15);	//On decolle et avance				
							} 
							helico.alti_cons=Math.max(helico.alti_cons,helico.alt_min);
							helico.alti_cons=Math.min(helico.alti_cons,helico.alt_max);
							var alti_avion=helico.alti_cons+alti_du_sol;
							helico.alti=Math.max(alti_avion*0.2+0.8*helico.alti,0.999*helico.alti);
							//Gestion choc au sol
							var delta_sol=helico.alti-alti_du_sol;
							if (delta_sol <0.5*helico.alti_cons ) helico.alti+=0.1*helico.alti_cons;  // Pour remonter si on va toucher le fond
							if (delta_sol < 0.1*helico.alti_cons  ) helico.alti+=0.1*helico.alti_cons;
							var vz=10*(helico.alti-helico.alti_avion_old);  // Vitesse de montée, unité bidon
							if (vz<0) vz=vz/20; //On calme la vitesse de descente
							v_cons.vz=frc(vz,v_cons.vz,v_cons.rc); //On filtre un peu
					} else { //MAnuel
							if (hautButtonDown ) v_cons.vz+=0.1+Math.abs(v_cons.vz)*0.1;
							if (basButtonDown ) v_cons.vz+=-0.1-Math.abs(v_cons.vz)*0.1;
							v_cons.vz=Math.min(v_cons.vz,256);v_cons.vz=Math.max(v_cons.vz,-256);
							helico.alti+=v_reel.vz/10;
							if (helico.alti<=helico.alt_min || helico.alti>helico.alt_max || helico.alti<alti_du_sol ) { // Ca touche
							 	helico.alti=Math.max(helico.alti,helico.alt_min);
							 	helico.alti=Math.min(helico.alti,helico.alt_max);
								helico.alti=Math.max(helico.alti,alti_du_sol);
								v_cons.vz=10*(helico.alti-helico.alti_avion_old); 
							}
						
					}
					
					
					helico.alti=Math.max(helico.alti,alti_du_sol);  // on peut pas rentrer dans le sol 
					helico.alti_sol=helico.alti-alti_du_sol; // altitude par rapport au sol sur terre 
					
							
							// Cap à prendre
							var dlat=lati[scene.idx_lat]-helico.lat;
							var dlng=lngi[scene.idx_lat]-helico.lng;
			
						if (dlat==0) dlat=0.0000000001;
						var heading_c=Math.atan(dlng*Math.cos(3.14159*helico.lat/180)/dlat);  // Cap 
						heading_c=heading_c*180/Math.PI;
						if (dlat<0) {
								heading_c=heading_c+180;
						}
						
						
						//Cap consigne
						heading_c=(heading_c+360)%360;  // 
						
						var dh=heading_c-helico.heading;
						if (dh>180 ) dh=dh-360;
						if (dh<-180 ) dh=dh+360; // Ecart en cap
						
						
						
						if (helico.auto) { // Auto
							
	
								// Pour eviter oscillation en fin de 1/2 tour
								if (dh>0) { 
									if(dh<v_cons.vr ) {
										v_cons.vr=Math.min(dh,v_cons.vr); 
										v_reel.vr=Math.min(dh,v_reel.vr);
									} 
								} 
								if (dh<0) {
									if(dh>v_cons.vr ) {
										v_cons.vr=Math.max(dh,v_cons.vr);
										v_reel.vr=Math.max(dh,v_reel.vr);
									}
								}
		
								v_cons.vr=frc(dh,v_cons.vr,v_cons.rc); //On filtre un peu
						} else {
									
							
									if (leftButtonDown ) v_cons.vr+=-0.1-Math.abs(v_cons.vr)*0.2;  //Eviter rotation trop rapide
									if (rightButtonDown ) v_cons.vr+=0.1+Math.abs(v_cons.vr)*0.2;
									v_cons.vr=Math.max(v_cons.vr,-256);v_cons.vr=Math.min(v_cons.vr,256);
									
									
						}
						
						helico.heading  = helico.heading + v_reel.vr/10; //Pas la consigne
						
						helico.heading=helico.heading%360;
						heading_c=helico.heading*Math.PI/180
						//Deplacement lateral
						if (helico.auto) { // Auto
								v_cons.vy=0;
						} else {
								
						}
						
						helico.lat+=v_reel.vx*helico.speed*Math.cos(heading_c)-v_reel.vy*helico.speed*Math.sin(heading_c);
						helico.lng+=v_reel.vx*helico.speed*Math.sin(heading_c)+v_reel.vy*helico.speed*Math.cos(heading_c);
						
					
									
									
						
						
								//TEST ARRIVE a destination
								var k_arriv=9;
								
							if ((Math.abs(dlat)+Math.abs(dlng)) <Math.max(k_arriv*v_reel.vx*helico.speed,scene.dist_min_arrive) ) { // on est pratiquement arrivé
									WP_suivant();
							}
						
	
			
								
										
					
	
		}
	 
	
 } 
function update_position_helico() {

												//Positionnement	à chaque fin d'image écran									
												helico.loc.setLatitude(helico.lat);
												helico.loc.setLongitude(helico.lng);												
												helico.loc.setAltitude(helico.alti +helico.alti_model0);  // Altitude par rapport mer + correction modele 
												helico.orient.setHeading((helico.heading+helico.cap0)%360);	// Correction Offset Model
														
														// ROOL rotation + lateral
														var roll=v_reel.vr*Math.min(v_reel.vx,4) +(v_cons.vy-0.8*v_reel.vy)/4;  
														roll=Math.max(roll,-40);roll=Math.min(roll,+40);
														
														helico.roll=roll;
														
														var dh=roll;
														var dhm=(360-dh)%360;
														
														
														
														var tilt=(-v_cons.vx+0.8*v_reel.vx)/2;
														tilt=Math.max(tilt,-40);tilt=Math.min(tilt,+40);
														helico.tilt=tilt;
														
														
														var tiltm=(360-tilt)%360;
														
														switch(helico.cap0) {  // Applique la rotation en virage et tilt. Depend offset cap du model.
																case 90:
																		helico.orient.setTilt(dh);  
																		helico.orient.setRoll(tiltm);
																break;
																case 270:
																		helico.orient.setTilt(dhm);  
																		helico.orient.setRoll(tilt);
																break;
																case 180:
																		helico.orient.setRoll(dh); 
																		helico.orient.setTilt(tilt);  
																break;
																case 0:
																		helico.orient.setRoll(dhm);  
																		helico.orient.setTilt(tiltm);  
																break;
														}
														
														
												
											
												 
										
					
}

function failureCallback(object) {  // Google earth ne 'installe pas
		scene.init_3d_ok=false;
		
		
}




function init_platforme() { //Initialisation 

		 // Altitude
		
		if (scene.init_3d_ok) {
				helico.placemark = ge.createPlacemark('');
				helico.placemark.setName('model');
				var model = ge.createModel('');
				ge.getFeatures().appendChild(helico.placemark);
				helico.loc = ge.createLocation('');
				model.setLocation(helico.loc);
				helico.scal_obj=ge.createScale  	( '' )   ;
				model.setScale	(helico.scal_obj);
				helico.orient=ge.createOrientation('');
				model.setOrientation(helico.orient);
				link = ge.createLink('');				
				link.setHref(href+"images/models/"+helico.model); // model 3d
				model.setLink(link);
				model.setAltitudeMode(ge.ALTITUDE_ABSOLUTE);
				helico.scal_obj.set(helico.scal,helico.scal,helico.scal);
				helico.loc.setLatitude(helico.lat);
				helico.loc.setLongitude(helico.lng);
				helico.loc.setAltitude(helico.alti);
				helico.orient.setHeading((helico.heading+helico.cap0)%360);
				helico.placemark.setGeometry(model);
		

	}
	helico.speed=helico.cruise_speed/(60*3600*20);
	
	//Init info pilotage
		screenOverlay = ge.createScreenOverlay('');
		
		// Specify a path to the image and set as the icon
		var icon = ge.createIcon('');
		icon.setHref(href+'images/pilotage.png');
		screenOverlay.setIcon(icon);
		
		// Set the ScreenOverlay's position in the window
		screenOverlay.getOverlayXY().setXUnits(ge.UNITS_PIXELS);
		screenOverlay.getOverlayXY().setYUnits(ge.UNITS_PIXELS);
		screenOverlay.getOverlayXY().setX(116);
		screenOverlay.getOverlayXY().setY(57);
		
		// Set the overlay's size in pixels
		screenOverlay.getSize().setXUnits(ge.UNITS_PIXELS);
		screenOverlay.getSize().setYUnits(ge.UNITS_PIXELS);
		screenOverlay.getSize().setX(231);
		screenOverlay.getSize().setY(114);
		
		
		// Add the ScreenOverlay to Earth
		ge.getFeatures().appendChild(screenOverlay);
	window.focus();
}









 function WP_suivant() {
 									var pas_trouve=true;
									while (pas_trouve) {
									 	scene.idx_lat++;  // On va changer de WP
										scene.idx_lat=scene.idx_lat%lati.length;
										if (survol[scene.idx_lat]==1) pas_trouve=false;
									}
									document.getElementById("sel_site").value=scene.idx_lat;
									
									
									
}
 


/* NAVIGATION */
/**************/

function force_site(idx) {  // On veut rejoindre un site
	
	if (helico.auto) {
	 //Goto
			 
			scene.idx_lat=idx;
	} else {
	 //Manual
			scene.idx_lat=idx;
			helico.lat=lati[scene.idx_lat] ;
			helico.lng=lngi[scene.idx_lat];
			place_pres_WP();
	
	}
	document.getElementById("sel_site").value=scene.idx_lat;
	
	
}

function place_pres_WP() { // on place objet en avant du WP pour le voir
	var d=2.5*scene.dist_min_arrive; 
	var teta=(190+helico.heading); //leger desaxe
	helico.lat+=d*Math.cos(Math.PI*teta/180);
	helico.lng+=d*Math.sin(Math.PI*teta/180);
}



function gId(x) { return document.getElementById(x); }
function place(){
	for (i=0;i<nom_lieu.length;i++) {
			place=one_place(nom_lieu[i],lati[i],lngi[i]);
			if (i==0) pub_chalet(place);
	}
}
function one_place(nom,lat,lng) {
	var placemark = ge.createPlacemark('');
			placemark.setName(nom );
			ge.getFeatures().appendChild(placemark);
			
			// Create style map for placemark
			var normal = ge.createIcon('');
			normal.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
			var iconNormal = ge.createStyle('');
			iconNormal.getIconStyle().setIcon(normal);
			var highlight = ge.createIcon('');
			highlight.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
			var iconHighlight = ge.createStyle('');
			iconHighlight.getIconStyle().setIcon(highlight);
			var styleMap = ge.createStyleMap('');
			styleMap.setNormalStyle(iconNormal);
			styleMap.setHighlightStyle(iconHighlight);
			placemark.setStyleSelector(styleMap);
			  
			// Create point
			var la = ge.getView().copyAsLookAt(ge.ALTITUDE_ABSOLUTE);
			var point = ge.createPoint('');
			point.setLatitude(lat);
			point.setLongitude(lng);
			placemark.setGeometry(point);
			return placemark;
}
function pub_chalet(placemark){
 		var balloon = ge.createHtmlStringBalloon('');
         balloon.setFeature(placemark); // optional
		 var txt='<div><strong>Chalet Les Aiguilles</strong></div><div><a href="/index.php">A Louer / For Rent</a></div>';
		
         balloon.setContentString(txt);
         balloon.setBackgroundColor('#FFFFBB');
         ge.setBalloon(balloon);
}

