/* Developer Notes 
Copyright 2008 Geoplan Consulting

XML files are used  to set up available flightpath and overlay combos for the simulator.
 flightpaths.xml is the xml file of available (published) paths for the simulated fly-over.
In the flightpath.xml file, each flightpath has three nodes (attributes): name, description and model (the Collada or Google sketch-up).
Each flightpath has a series of segments. For example, quest_northkml , quest_south.kml 
 would contain the legs (flight segments) for a fly-over of the Yukon Quest course, with English, French and German descriptions 
 Each  flightpath kml file contains a sequence of segments or legs,
 in race order, with nodes for origin, destination,  and a reference for the coordinates file ( kml) for each leg.
 Each leg is then represented by its own KML file containing one placemark, with a description and list of coordinates.
 i.e. All of the following files are related: flightpaths.kml ->course.kml -> leg.kml
Cross-browser xml import utilities are found in importxml.js  (from Mark Wilton-Jones @ http://www.howtocreate.co.uk)
All flight simulation is controlled by simulator.js (from Google Inc. with thanks to Roman Nurik!!!!)
3d models were obtained from Googles 3d warehouse.
*/

function createNamedElement(type, name) {
   var element = null;
   // Try the IE way; this fails on standards-compliant browsers
   try {
      element = document.createElement('<'+type+' name="'+name+'">');
   } catch (e) { 
     }
   if (!element || element.nodeName != type.toUpperCase()) {
      // Non-IE browser; use canonical method to create named element
      element = document.createElement(type);
      element.name = name;
      element.id = name;
   }
   element.id=name;
   return element;
}

function updateMap() {
	DS_simulator.destroy();
	selector = document.getElementById('legselect');
	var url = selector[selector.selectedIndex].value;
	var count = document.getElementById("descr_text").getElementsByTagName("div").length;
	for (i=0;i<count;i++){
	
	theDiv =document.getElementById('div_' +i);
	theDiv.style.display="none";		
	theFrDiv =document.getElementById('div_' +i+ 'fr');
	theFrDiv.style.display="none";			
	theGerDiv =document.getElementById('div_' +i+ 'ge');
	theGerDiv.style.display="none";		
	
	}
	setDiv =document.getElementById('div_' +selector.selectedIndex)
	setDiv.style.display="block";
	setFrDiv =document.getElementById('div_' +selector.selectedIndex + 'fr')
	setFrDiv.style.display="block";
	setGerDiv =document.getElementById('div_' +selector.selectedIndex + 'ge')
	setGerDiv.style.display="block";
   google.earth.fetchKml(Ds_ge, url, fetchFinished);   
 
}

function createCourses(xmlDoc){
	
	var theForm = createNamedElement('FORM','course');
               var routeSelect = createNamedElement('select','routeSelect');
        		routeSelect.onchange = function(){updateTable();}
        		 var optValue = xmlDoc.getElementsByTagName("name");
         		var optText= xmlDoc.getElementsByTagName("description");
	for (i=0;i<optValue.length;i++)
	{
			if (optValue[i].childNodes[0].nodeType == 1) continue;
			var item = document.createElement('option');
			var z =optValue[i].childNodes[0].nodeValue;
		    var y = document.createTextNode(optText[i].childNodes[0].nodeValue);
			item.appendChild(y);
			item.setAttribute('value', z);
			routeSelect.appendChild(item);
			}		    
			routeSelect.style.width=228;
	theForm.appendChild(routeSelect);
	theForm.style.margin = 0;
		document.getElementById("route_selector").appendChild(theForm);
         routeSelect.selectedIndex = 0; 
	var currentXml = routeSelect.options[0].value + '.xml';
	curUrl = importXML(currentXml,'createTable');   
}

function createTable(xmlDoc){
	var newForm=document.getElementById('segments');
	var xmlFile = xmlDoc.getElementsByTagName('route');
	 var optFrom = xmlDoc.getElementsByTagName('from');
     var optDesc= xmlDoc.getElementsByTagName('desc_en');
     var optDescFr = xmlDoc.getElementsByTagName('desc_fr');
     var optDescGer = xmlDoc.getElementsByTagName('desc_ge');
    var optFile= xmlDoc.getElementsByTagName('kmlfile');
	firstRun = base_url + document.createTextNode(optFile[0].childNodes[0].nodeValue).nodeValue;
  	if (newForm ==null){
var newForm = createNamedElement('FORM','segments');}
var legSelect = createNamedElement('select','legselect');
legSelect.onchange= function(){updateMap();}
	for (i=0;i<optFile.length;i++)
	{
			if (optFile[i].childNodes[0].nodeType == 1) continue;
			var item = document.createElement('option');
			fromText = document.createTextNode(optFrom[i].childNodes[0].nodeValue);
			item.appendChild(fromText);	
			descText = document.createTextNode(optDesc[i].childNodes[0].nodeValue);
			descTextFr = document.createTextNode(optDescFr[i].childNodes[0].nodeValue);
			descTextGer = document.createTextNode(optDescGer[i].childNodes[0].nodeValue);
			var fileText = base_url  + optFile[i].childNodes[0].nodeValue; 
			item.setAttribute('value',fileText);
			legSelect.appendChild(item);
			var newDiv = createNamedElement('DIV','div_' + i);
			newDiv.style.display="none";
		    newDiv.innerHTML = descText.nodeValue;
		     document.getElementById('descr_text').appendChild(newDiv);
		     
		     	     
		     var frDiv = createNamedElement('DIV','div_' + i + 'fr');
			frDiv.style.display="none";
		    frDiv.innerHTML = descTextFr.nodeValue;
		     document.getElementById('descr_text_fr').appendChild(frDiv);
		     
		     var gerDiv = createNamedElement('DIV','div_' + i + 'ge');
			gerDiv.style.display="none";
		    gerDiv.innerHTML = descTextGer.nodeValue;
		     document.getElementById('descr_text_ge').appendChild(gerDiv);

			}
			legSelect.style.width=228;
			newForm.appendChild(legSelect); 
			newForm.style.margin = 0;
	document.getElementById("leg_selector").appendChild(newForm); 
         legSelect.selectedIndex = 0; 
	document.getElementById('div_0').style.display="block";    
	document.getElementById('div_0fr').style.display="block";    
	document.getElementById('div_0ge').style.display="block";   

	}


function swapTable(xmlDoc){

	var newForm=document.getElementById('segments');
	var xmlFile = xmlDoc.getElementsByTagName('route');
	 var optFrom = xmlDoc.getElementsByTagName('from');
     var optDesc= xmlDoc.getElementsByTagName('desc_en');
     var optDescFr =  xmlDoc.getElementsByTagName('desc_fr');
     var optDescGer =  xmlDoc.getElementsByTagName('desc_ge');
    var optFile= xmlDoc.getElementsByTagName('kmlfile');
	firstRun = base_url + document.createTextNode(optFile[0].childNodes[0].nodeValue).nodeValue;
  	if (newForm ==null){
var newForm = createNamedElement('FORM','segments');}
var legSelect = createNamedElement('select','legselect');
legSelect.onchange= function(){updateMap();}
	for (i=0;i<optFile.length;i++)
	{
			if (optFile[i].childNodes[0].nodeType == 1) continue;
			var item = document.createElement('option');
			fromText = document.createTextNode(optFrom[i].childNodes[0].nodeValue);
			descText = document.createTextNode(optDesc[i].childNodes[0].nodeValue);
			descTextFr = document.createTextNode(optDescFr[i].childNodes[0].nodeValue);
			descTextGer = document.createTextNode(optDescGer[i].childNodes[0].nodeValue);
			item.appendChild(fromText);
			var fileText = base_url  + optFile[i].childNodes[0].nodeValue; 
			item.setAttribute('value',fileText);
			legSelect.appendChild(item);
			var newDiv = createNamedElement('DIV','div_' + i);
			newDiv.style.display="none";
		    newDiv.innerHTML = descText.nodeValue;
		     document.getElementById('descr_text').appendChild(newDiv);
		     
		     var frDiv = createNamedElement('DIV','div_' + i + 'fr');
			frDiv.style.display="none";
		    frDiv.innerHTML = descTextFr.nodeValue;
		     document.getElementById('descr_text_fr').appendChild(frDiv);
		     
		     var gerDiv = createNamedElement('DIV','div_' + i + 'ge');
			gerDiv.style.display="none";
		    gerDiv.innerHTML = descTextGer.nodeValue;
		     document.getElementById('descr_text_ge').appendChild(gerDiv);

			}
			newForm.appendChild(legSelect); 
	document.getElementById("leg_selector").appendChild(newForm); 
         legSelect.selectedIndex = 0;
	document.getElementById('div_0').style.display="block";    
	document.getElementById('div_0fr').style.display="block";    
	document.getElementById('div_0ge').style.display="block";    
   	DS_simulator.destroy();
	myurl = firstRun;
	 google.earth.fetchKml(Ds_ge, myurl, fetchFinished);

}
function updateTable(){
	var currentRoute=document.getElementById('routeSelect');
	document.getElementById('leg_selector').innerHTML='';
	var currentXml=currentRoute.options[currentRoute.selectedIndex].value+'.xml';
	document.getElementById('descr_text').innerHTML='';
	document.getElementById('descr_text_fr').innerHTML='';
	document.getElementById('descr_text_ge').innerHTML='';
    importXML(currentXml ,'swapTable');   
    
              }
function createRadioElement(  ) {   
	    try {        
	    	var radioHtml = '<input type="radio" name="legs"' ;       
	          radioHtml += ' onclick="updateMap()" />';    
	          radioInput = document.createElement(radioHtml);    
	          } catch( err ) {
	          	radioInput = document.createElement('input');
	               radioInput.setAttribute('type', 'radio');        
	               radioInput.setAttribute('name','legs');   
	               radioInput.setAttribute('onclick',"updateMap();");
	              }    
	     return radioInput;
}


function fetchFinished(kmlObject) {
	// create the array of GLatLng coordinates
	var coordsKmlObj = kmlObject.getGeometry().getCoordinates();
	var coordsArray = [];
	var n = coordsKmlObj.getLength();
	for (var i = 0; i < n; i++) {
		var coord = coordsKmlObj.get(i);
		coordsArray.push(new google.maps.LatLng(coord.getLatitude(),
		coord.getLongitude()));
	}
	// drive speed (in meters per second)
	var speed = 45; //10 gives initial eye elev of 515 ft.50 is 850 ft.

	// create the path
	var geHelpers = new GEHelpers(Ds_ge);
	var path = [];
	for (var i = 0; i < n; i++) {
		if (i == coordsArray.length - 1) {
			// last coordinate
			path.push({
				loc: coordsArray[i],
				step: 0,
				distance: 0,
				duration: 0
			});
			} else {
			var distance = geHelpers.distance(coordsArray[i], coordsArray[i
			+ 1]);
			path.push({
				loc: coordsArray[i],
				step: 0,
				distance: distance,
				duration: distance / speed
			});
		}

	}
	// now you can use path to create a DDSimulator...
DS_simulator = new DDSimulator(Ds_ge, path);

DS_simulator.initUI();
  DS_simulator.options.speed = 1.0
        DS_updateSpeedIndicator();
DS_simulator.start();

}

