/**************************************************************/
/* MdS2008 Javascript function file for Google Earth access   */
/* Includes KML file load and control functions               */
/*                                                            */
/* Author - Richard Pomeroy                                   */
/* Copyright - p4media ltd. 2008                              */
/*                                                            */
/* V1.0 27/10/08 First version, without collapsable Menu      */
/* V1.1 31/10/08 Included collapsable menu                    */
/* V1.2 01/11/08 Fixed for Firefox Browser / IE compatibility */
/* V1.3 05/11/08 Added highlight and menu opening control     */
/* V1.4 07/11/08 Removed geneic functions to utility.js       */
/* V1.5 09/11/08 Minor tweaks - commented out getfeatures in  */
/*               loadNetworkLink function and refactoring     */
/* V1.6 17/11/08 Adjusted for dual file use and changed       */
/*               nodeTraverse to ignore '-' and blank in menu */
/* V1.7 27/11/08 Added replaceKml update for generic load     */
/* V1.8 07/12/08 Changed to ignore '*' in both menu and tour  */
/*                                                            */
/**************************************************************/
/* <![CDATA[ */
                        
/* Global variables */
                        
// Initialize environment parameters
var strInitDomain = "http://www.p4media.com/"; // "http://localhost/ge/";
var strKmlDomain = strInitDomain;
var strInitFile = "RaceMenu.kml";
var strKmlFile = strInitFile;
var strKmlUrl = strKmlDomain + strKmlFile;
// Initialize GE parameters
var ge = null;
var kmlObject = null;
var arrPlaceMarks = [];
var kmlImages = null;
var currentPlaceMark = null;
// Initialize Menu parameters
var strMenuHtml = '';
var arrPlacemarkMenu = [];
var currentPlacemarkIndex = 0;
var intPlaceMarks = 0;
var boolFullScreen = false;
var kmlTour = false;
var tourTimer = null;
var maxFolders = 0;
var linesPerFolder = []; 

// var buildMenu = false;
// var mainmenu = true;

google.load("earth", "1");

/* Functions */	


//init()
//Main entry point

function init() {
    setKMLFile(strInitFile); // set initial file or passed parameter
    setWindowStatus ('Attempting to load Google Earth', 2000)
    google.earth.createInstance("map3d", initCallback, function(object){/*die gracefully*/});
    dhtmlHistory.initialize();
    dhtmlHistory.addListener(yourListener);

}

                        

// setKMLFile (string kmlFile)
// Sets the initial (first kml file to the passed parameter content or the top 
// level race menu if nothing is passed after ?
function setKMLFile(kmlFile){
    
    origURL = parent.document.URL;
    strKmlFile = origURL.substring(origURL.indexOf('#')+1, origURL.length);
    if (strKmlFile.length==origURL.length || strKmlFile=='') { // if blank
        strKmlFile = kmlFile
        location.replace(strInitDomain + "racemenu.html#" + strKmlFile);
    // dhtmlHistory.add(strKmlFile, true);
    }
    // alert ("URL: " + parent.document.URL + "\n" +
    //       "KML: " + strKmlFile);
    strKmlUrl = strKmlDomain + strKmlFile;
}
//initCallback(object ge)
//configure ge and load the KML
function initCallback(object) {
    ge = object;
    ge.getWindow().setVisibility(true);
    setWindowStatus ('Loading KML tour file', 1000)

    google.earth.fetchKml(ge, strKmlUrl, fetchKmlCallback);		
    kmlImages = loadNetworkLink(strKmlUrl, true);
    toggleOptions();
    ge.getOptions().setFlyToSpeed(0.25);

}

//fetchKmlCallback(KmlObject kml)	
//Adds the KML data to ge and make call to build the menu
function fetchKmlCallback(object) {		
    if (!object) { 
        alert('Bad or NULL kml'); resetKml('-1'); return;
    }
    kmlObject = object;	
    setWindowStatus ('Creating Menu', 1000)
    traverseNodes(kmlObject);
    //                    alert(strMenuHtml);
    gebid("collapseMenuContainer").innerHTML = strMenuHtml;
    ge.getGlobe().getFeatures().appendChild(kmlObject);
    setWindowStatus ('Going to first Placemark', 1000);
    runCollapseMenu('0');
    getPlacemark('0');
}

//
//
function loadNetworkLink(url, flyto) {
    var networkLink = ge.createNetworkLink("");
    networkLink.setDescription("NetworkLink open to fetched content");
    networkLink.setName("Open NetworkLink");
    if(flyto) {	
        networkLink.setFlyToView(true);
    }
    var link = ge.createLink("");
    link.setHref(url);
    networkLink.setLink(link);
    //    ge.getFeatures().appendChild(networkLink);
    return networkLink;
}

var yourListener = function(newLocation, historyData) {
    //do something;
    //alert(newLocation + " & " + historyData);
    strKmlFile=newLocation;
    if (historyData) strMenuHtml = "";
    else {
        strMenuHtml = '<div class="mainHeading" onclick="resetKml(\'-1\'); "title="Click to return to Main Race Menu">';
        strMenuHtml += 'Race Menu</div>';
    }

    replaceKml();
}


//replaceKml()
//Replaces the current KML file and resets the menu
function replaceKml(){ // id is menu item for networkLink

    gebid("collapseMenuContainer").innerHTML = "";
    ge.setBalloon(null);
    
    //    window.location.href = strInitDomain + "racemenu.html#" + strKmlFile;
    var new_url = strKmlDomain + strKmlFile;

    arrPlaceMarks.length = 0;
    intPlaceMarks = 0;
    maxFolders=0;
    ge.getGlobe().getFeatures().removeChild(kmlObject);
    kmlObject.setVisibility(false); //we just hide the kmlObject to stop duplicates...
    kmlObject = null;
    google.earth.fetchKml(ge, new_url, fetchKmlCallback);
    strKmlUrl = new_url
}

function resetKml(id){ // id is menu item for networkLink

    var tempStr = "";
    var lastSlashPosn ;

    // Reset KML file parameters and initialize menu
    if (id==-1) {
        strMenuHtml = "";
        strKmlDomain = strInitDomain;
        strKmlFile = strInitFile;
        dhtmlHistory.add(strKmlFile, true);
    }
    else {
        strMenuHtml = '<div class="mainHeading" onclick="resetKml(\'-1\'); "title="Click to return to Main Race Menu">';
        strMenuHtml += 'Race Menu</div>';
        tempStr = arrPlaceMarks[id].getLink().getHref();
        lastSlashPosn = tempStr.lastIndexOf('/')+1;
        strKmlDomain = tempStr.substring(0, lastSlashPosn); // e.g. "http://localhost/ge/";
        strKmlFile = tempStr.substring(lastSlashPosn);      // e.g. "RaceMenu.kml";
        dhtmlHistory.add(strKmlFile, false);
    }
    replaceKml();
}

// myLookat(double latitude, double lonitude)
// createLookAt() wrapper
function myLookat(x, y, a) {
    var la = ge.createLookAt('');
    la.set(x, y, a, ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, 0);
    ge.getView().setAbstractView(la);
}

//traverseNodes(KmlFeature node) 
//Recursively iterates through the KmlDocument
//makes the menu using folder names as headings and placemark names as links
function traverseNodes(node) {
    if(node.getFeatures().hasChildNodes()) {
        var subNodes = node.getFeatures().getChildNodes();
        var length = subNodes.getLength();
        for(var i = 0; i < length; i++) {
            var eachSubNode = subNodes.item(i);
            var nodeType = eachSubNode.getType();
            var nodeName = eachSubNode.getName();

            switch(nodeType) {
                case 'KmlFolder' :
                    //                                if(nodeName != 'Projects Folder') {
                    if(maxFolders!=0) strMenuHtml += '</div>'; 

                    strMenuHtml += '<div onclick="runCollapseMenu(' + maxFolders + ');">';
                    strMenuHtml += '<div class="folderHeading" onselectstart="return false;">' + nodeName + '</div></div>';
                    strMenuHtml += '<div id="CollapseMenu' + maxFolders + 'Content" class="collapseMenuContent">';
                    linesPerFolder[maxFolders]=0;
                    maxFolders++;
                    //                                }
                    traverseNodes(eachSubNode); //recurse..
                    //                                if (nodeName != 'Projects Folder') {
                    //                                    strMenuHtml += '</div>'; 
                    //strMenuHtml += '</div>';//                                }

                    break;
                case 'KmlPlacemark' :
                    if (nodeName.charAt(0)!='-' && nodeName!="" && nodeName.charAt(0)!='*'){   // if first char is not '-' and not blank
                        arrPlaceMarks[intPlaceMarks] = eachSubNode; // set up menu item
                        arrPlacemarkMenu[intPlaceMarks] = maxFolders-1;
                        //                    alert(nodeName);
                        strMenuHtml += '<a id="CollapseMenu' + intPlaceMarks 
                        + 'Item" onMouseOver="javascript:highlight(' + intPlaceMarks +', true)" onMouseOut="javascript:highlight(' + intPlaceMarks +', false)" href="javascript:getPlacemark(\''
                        + intPlaceMarks
                        + '\')">'
                        + nodeName
                        + '</a><br />';

                        linesPerFolder[maxFolders-1]+=Math.round((nodeName.length+20)/40);
                        intPlaceMarks++;
                    }
                    else if (nodeName.charAt(0)=='*'){   // if first char is not '-' and not blank
                    // Ignore
                    }

                    else
                    {                                               // otherwise create collapsemenu item for tour
                        arrPlaceMarks[intPlaceMarks] = eachSubNode; // but do not display
                        arrPlacemarkMenu[intPlaceMarks] = maxFolders-1;
                        tempStrMenuHtml = '<a id="CollapseMenu' + intPlaceMarks + 'Item"></a>'; 
                        strMenuHtml +=tempStrMenuHtml;
                        intPlaceMarks++;
                    }
                    break;
                case 'KmlNetworkLink' : // Use Networklink for URL of new KML
                    eachSubNode.setVisibility(false); // DO NOT display links in Menu
                    arrPlaceMarks[intPlaceMarks] = eachSubNode;
                    arrPlacemarkMenu[intPlaceMarks] = maxFolders-1;
                    strMenuHtml += '<a id="CollapseMenu' + intPlaceMarks
                    + 'Item" onMouseOver="javascript:highlight('
                    + intPlaceMarks + ', true)" onMouseOut="javascript:highlight('
                    + intPlaceMarks + ', false)" href="javascript:resetKml('
                    + intPlaceMarks + ')">'
                    + nodeName
                    + '</a><br />';

                    linesPerFolder[maxFolders-1]+=Math.round((nodeName.length+20)/40);
                    intPlaceMarks++;
                    break;
                case 'KmlScreenOverlay' :
                default :
                    break;
            }
        }
    }
}
                        
//getPlacemark(int id)
//Navigate to a placemark
function getPlacemark(id) {
    var placemark = arrPlaceMarks[id];
    var oldPlacemarkId=0;
    
    if (id!=null) highlight(id, true);
    // highlightPlacemark (id, currentPlacemarkIndex)
    //var point = placemark.getGeometry();
    //myLookat(point.getLatitude(), point.getLongitude(), 200);
    ge.getView().setAbstractView(placemark.getAbstractView());
    currentPlaceMark = placemark;
    
    oldPlacemarkId = currentPlacemarkIndex;
    currentPlacemarkIndex = id;
    if (oldPlacemarkId!=null) highlight(oldPlacemarkId, false);
// openBalloon();
}

//
//
function openBalloon() {
    ge.setBalloon(null);
    //Wait to open the feature ballon...
    //It looks quite messy if its open whilst the earth is moving!
    setTimeout(function() {
        //openVideoBalloon();
        //return;
        var balloon = ge.createFeatureBalloon('');
        balloon.setFeature(currentPlaceMark);
        ge.setBalloon(balloon);
    //openVideoBalloon();
    },4500);
}
                                                                      
//toggleOptions()
//Toggle the various ge options and layers
function toggleOptions() {
    var options = ge.getOptions();
    var root = ge.getLayerRoot();
    var sun = ge.getSun();
    var form = gebid("options");
    //sun.setVisibility(true);
    options.setStatusBarVisibility(form.statusbar.checked);
    options.setGridVisibility(form.grid.checked);
    options.setOverviewMapVisibility(form.overview.checked);
    options.setScaleLegendVisibility(form.scaleLegend.checked);
    options.setAtmosphereVisibility(form.atmosphere.checked);  
    kmlImages.setVisibility(form.photos.checked);
    root.enableLayerById(ge.LAYER_TERRAIN, form.terrain.checked);
    root.enableLayerById(ge.LAYER_ROADS, form.roads.checked);
    root.enableLayerById(ge.LAYER_BORDERS, form.borders.checked);
    root.enableLayerById(ge.LAYER_BUILDINGS, form.buildings.checked);
    (form.nav.checked ? ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW) : 
        ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE)) 
    if (form.nav.checked) {
        ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW);
    } else {
        ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE);
    }
}

//
//
function keyPressCallback(event) {
    if(event.keyCode==27) {
        //toggleFullScreen();
        altitude();
    }
}

//
//
function altitude() {
    var cam = ge.getView().copyAsCamera( ge.ALTITUDE_ABSOLUTE );
//alert("alt " + cam.getAltitude());
}

//
//
function playTour(){                        
    if (!kmlTour) {                 // If not already started
        setWindowStatus('Playing Tour');
        kmlTour=true;
        gebid("tourcontrols").elements['play'].value="Pause";
        //        if (currentPlacemarkIndex!=0) currentPlacemarkIndex=-1;   // Start at -1 as inc in function
        if (currentPlacemarkIndex==0) tour(1);    //tourTimer=setTimeout("tour()",0);
        else tour(0);
    }
    else {                          // If started 
        if(gebid("tourcontrols").elements['play'].value=="Play"){  // and either paused
            setWindowStatus('Resuming Tour');
            gebid("tourcontrols").elements['play'].value="Pause";
            highlight(currentPlacemarkIndex++, false);
            //            currentPlacemarkIndex++;
            tour(currentPlacemarkIndex); // tourTimer=setTimeout("tour()",0);
        }
        else {                          // or playing
            setWindowStatus('Pausing Tour');
            gebid("tourcontrols").elements['play'].value="Play"    
            clearTimeout(tourTimer);    // to pause, clear timer, but keep kmltour flag active
        }
    }
}
            
// The main tour animation function - called by itself after the timeout
// occurs
function tour(newPM){
    //    var newPlacemark = currentPlacemarkIndex;
    //    newPlacemark++;
    //    if (newPlacemark<intPlaceMarks) {
    if (newPM<intPlaceMarks) {
        if (arrPlacemarkMenu[currentPlacemarkIndex]!=arrPlacemarkMenu[newPM])
            runCollapseMenu(arrPlacemarkMenu[newPM]);
        getPlacemark(newPM);
        newPM++;
        tourTimer=setTimeout("tour(" + newPM + ");",6500);
        
    } else cancelTour();            // if at the end then reset
}

function cancelTour(){
    clearTimeout(tourTimer);
    kmlTour=false;                
    gebid("tourcontrols").elements['play'].value="Play"
    setWindowStatus('Stopping Tour');
}


// This will trigger myEventListener() when user clicks on 'placemark',
// and will pass in a KmlEvent object.
//google.earth.addEventListener(placemark, "mousedown", myEventListener);

// This will trigger myEventListener() when user clicks on the globe,
// and will pass in a KmlEvent object.
//google.earth.addEventListener(ge.getGlobe(), "mousedown", myEventListener);

// This will trigger myEventListener() when user clicks anywhere in the window,
// and will pass in a KmlEvent object.
//google.earth.addEventListener(ge.getWindow(), "mousedown", myEventListener);

         
/* ]]> */
