// Version 2.0.0
//
// The contents of this file are subject to the Mozilla Public License
// Version 1.1 (the "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
//
// Alternatively, you may redistribute this library, use and/or modify it under the terms of the
// GNU Lesser General Public License as published by the Free Software Foundation;
// either version 2.1 of the License, or (at your option) any later version.
// You may obtain a copy of the LGPL at http://www.gnu.org/copyleft/.
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
// specific language governing rights and limitations under the License.
//
// The original code is geapi.js, released DECEMBER 1, 2006.
//
// The initial developer of the original code is Luca Rocchi (Rome, Italy, www.googleearthairlines.com),
// (lr1313@gmail.com).

//-----------------------------------------
//GoogleEarth Api javascript library for Mozilla & IE browser
//-----------------------------------------
var ApplicationGE =  {
      defKML:"",
      menuUrl:'',
      topBar:"1",
      bottomBar:"1",
      GetCamera : function(considerTerrain) {
         if (isNaN(considerTerrain))
            return null;
         return new ICameraInfoGE(considerTerrain);
      },

      SetCamera : function(camera,speed) {
         this.SetCameraParams(camera.FocusPointLatitude,camera.FocusPointLongitude,camera.FocusPointAltitude,camera.FocusPointAltitudeMode,camera.Range,camera.Tilt,camera.Azimuth,speed);
      },

      SetCameraParams : function(lat,lon,alt,altMode,Range,Tilt,Azimuth,speed) {
         if (isNaN(lat) || isNaN(lon)|| isNaN(alt)|| isNaN(altMode)|| isNaN(Range)|| isNaN(Tilt)|| isNaN(Azimuth) || isNaN(speed))
            return;

         var params=lat+' '+lon+' '+alt+' '+altMode+' '+Range+' '+Tilt+' '+Azimuth+' '+speed;
         plug.setViewParams(params);
      },

      Get_StreamingProgressPercentage : function() {
         return plug.streamingProgressPercentage();
      },

      SaveScreenShot : function(fileName,quality) {
         return plug.saveImage(fileName);
      },

      OpenKmlFile : function(filename,suppressMessages) {
         plug.openFile(filename);
      },

      LoadKmlData : function(kmlData) {
         plug.loadKml(kmlData);
      },

      Get_AutoPilotSpeed : function() {
         return plug.getParamValue("speed");
      },

      Set_AutoPilotSpeed : function(speed) {
         if (isNaN(speed))
            return null;
         plug.setValue("speed",speed);
      },

      Get_ViewExtents : function() {
         return new IViewExtentsGE();
      },

      GetFeatureByName : function(Name) {
         var feature=new IFeatureGE(Name);
         return feature.Name==''?null:feature;
      },

      GetFeatureByHref : function(href) {
         return this.GetFeatureByName(href);
      },

      SetFeatureView : function(feature,speed) {
         if (isNaN(speed))
            return null;
         plug.setFeature(feature.toString(),speed);
      },

      GetPointOnTerrainFromScreenCoords : function(screen_x,screen_y) {
         if (isNaN(screen_x) || isNaN(screen_y))
            return null;
         return new IPointOnTerrainGE(screen_x,screen_y);
      },

      Get_VersionMajor : function() {
         return plug.getParamValue('versionMajor');
      },

      Get_VersionMinor : function() {
         return plug.getParamValue('versionMinor');
      },

      Get_VersionBuild : function() {
         return plug.getParamValue('versionBuild');
      },

      Get_VersionAppType : function() {
         return plug.getParamValue('versionAppType');
      },

      IsInitialized : function() {
         return plug.isReady();
      },

      IsOnline : function() {
         return plug.isReady();
      },

      Login : function() {
         plug.setValue("login",0);
      },

      Logout : function() {
         plug.setValue("login",1);
      },

      ShowDescriptionBalloon : function(feature) {
         plug.setValue(feature.toString(),1);
      },

      HideDescriptionBalloons : function() {
          plug.setValue("balloons",0);
      },

      GetHighlightedFeature : function() {
         return this.GetFeatureByName('highlighted');
      },

      GetMyPlaces : function() {
         return this.GetFeatureByName('my places');
      },

      GetTemporaryPlaces : function() {
         return this.GetFeatureByName('temporary places');
      },

      GetLayersDatabases : function() {
         return new IFeatureCollectionGE('layers');
      },

      Get_ElevationExaggeration : function() {
         return plug.getParamValue("elevationexaggeration");
      },

      Set_ElevationExaggeration : function(exag) {
         if (!isNaN(exag) && (exag>=0.5) && (exag<=3.0)){
            plug.setValue("elevationexaggeration",exag);
         }
      },

      GetMainHwnd : function() {
         return plug.getParamValue("mainhwnd");
      },

      Get_TourController : function() {
         return new ITourControllerGE();
      },

      Get_SearchController : function() {
         return new IFeatureCollectionGE();
      },

      Get_AnimationController : function() {
         return new IAnimationControllerGE();
      },

      GetRenderHwnd : function() {
         return plug.getParamValue("renderhwnd");
      },
      Run: function() {
         //ApplicationGE  = new ActiveXObject("GoogleEarth.ApplicationGE");
      },
      Plugin: function(divId) {
         var fields=new Array("kml","bottomBar","topBar","BackColor","MenuUrl");
         var values=new Array(ApplicationGE.defKML,ApplicationGE.bottomBar,ApplicationGE.topBar,"#ffffff",ApplicationGE.menuUrl);
         var elType='embed';
         var classid="classid='clsid:CA538B16-F9BB-44A6-96FB-5C487C12869E'\n";
         var pluginspage="pluginspage='http://www.googleearthairlines.com/setup.exe'\n";
         var type="type='application/kml-plugin'\n" ;
         var oninit="oninit='javascript:__ApplicationGE_OnInit()'\n" ;
         var onclick="onclick='javascript:__ApplicationGE_OnClick()'\n";
         var onspeechend="onspeechend='javascript:__ApplicationGE_OnSpeechEnd()'\n";
         var width ="width='100%'\n";
         var height="height='100%'\n";
         var ax=false;
         try{
            ax=window.ActiveXObject!=undefined;
         }catch(e){}
         if (ax){
            elType='object';
         }
         //alert(navigator.platform );
         var found=false;
         if (!ax){
            for (var i=0;i<navigator.plugins.length;i++){
                if (navigator.plugins[i].name=="GoogleEarthAirlines Plug-in"){
                    //alert(navigator.plugins[i].name);
                    found=true;
                    break;
                }
            }
         }

         var html='\n';
         html+=' <'+elType+' \n';
         html+="id='ApplicationGE.Plugin'\n";
         html+=classid;
         html+=pluginspage;
         html+=type;
         html+=oninit;
         html+=onclick;
         html+=onspeechend ;
         html+=width;
         html+=height;
         if (!ax){
             for (var i=0;i<fields.length;i++){
                html+=fields[i]+"=\""+values[i]+'\"\n';
             }
         }
         html+='>\n';
         if (ax){
            for (var i=0;i<fields.length;i++){
                html+='<param name="'+fields[i]+'" value="'+values[i]+'"/>';
            }
            html+=htmlIExploreInstall;
         }else if (!found){
            html=htmlMozillaInstall;
         }

         html+='</'+elType+'>';
         html+='\n';
         //alert(html);

         parentDiv =document.getElementById(divId);
         if (parentDiv!=null){
             parentDiv.innerHTML=html+ieInitEvent+ieClickEvent;
             plug =document.getElementById('ApplicationGE.Plugin');
         }
      }
};
//-----------------------------------------
function ICameraInfoGE(terrain) {
    this.FocusPointLatitude =0;
    this.FocusPointLongitude=0;
    this.FocusPointAltitude=0;
    this.FocusPointAltitudeMode=0;
    this.Range=0;
    this.Tilt=0;
    this.Azimuth=0;
    try{
        var cp=plug.getParamValue("camera("+terrain+")");
       // alert(cp);
        cp=cp.replace(/,/gi,".");
        var values=cp.split(" ");
        this.FocusPointLatitude    =values[0];
        this.FocusPointLongitude   =values[1];
        this.FocusPointAltitude    =values[2];
        this.FocusPointAltitudeMode=values[3];
        this.Range       =values[4];
        this.Tilt        =values[5];
        this.Azimuth     =values[6];
    }catch(e){
        alert(camera.toSource());
        //alert("GetCamera!");
    }

}
ICameraInfoGE.prototype.toString=function(){
   var s='({';
   s+='FocusPointLatitude:'+this.FocusPointLatitude+',';
   s+='FocusPointLongitude:'+this.FocusPointLongitude+',';
   s+='FocusPointAltitude:'+this.FocusPointAltitude+',';
   s+='FocusPointAltitudeMode:'+this.FocusPointAltitudeMode+',';
   s+='Range:'+this.Range+',';
   s+='Tilt:'+this.Tilt+',';
   s+='Azimuth:'+this.Azimuth+'})';
   return s;
}
//-----------------------------------------
function IFeatureCollectionGE(name) {
    var items=new Array();
    var co=plug.getParamValue(name);
    //alert(co);
    if (co!=''){
       var values=eval(co);
       for (var i=0;i<values.length;i++){
          
       }
    }
}
IFeatureCollectionGE.prototype.Item=function(i){
   return i>=1 && i<=this.Count()?items[i]:null;
}
IFeatureCollectionGE.prototype.Count=function(){
   return items.length;
}
//-----------------------------------------
function IFeatureGE(name) {
    this.Name    ='';
    this.Visibility=0;
    this.HasView    =0;
    this.Highlighted=0;
    this.TimeInterval=new ITimeIntervalGE();
    this._parentName='';
    if (name!=undefined){
       var fe=plug.getParamValue(name);
       if (fe!=''){
          var values=eval(fe);
          this.Name    =values[0];
          this.Visibility=values[1];
          this.HasView    =values[2];
          this.Highlighted=values[3];
          try{
              this._parentName=values[4];
          }catch(e){
          }
       }
    }
}
IFeatureGE.prototype.Highlight=function(){
   plug.setValue(this.toString(),2);
}
IFeatureGE.prototype.GetParent=function(){
   if (this._parentName==''){
      return null;
   }
   return new IFeatureGE(this._parentName);
}
IFeatureGE.prototype.GetChildren=function(){
   alert('IFeatureGE.GetChildren not yet implemented');
   return null;
}

IFeatureGE.prototype.toString=function(){
   var s='({';
   s+='Name:"'+this.Name+'",';
   s+='Visibility:'+this.Visibility+',';
   s+='HasView:'+this.HasView+',';
   s+='Highlighted:'+this.Highlighted+'})';
   return s;
}
//-----------------------------------------
function IViewExtentsGE() {
    this.North=43.0;
    this.South=42.0;
    this.East=13.0;
    this.West=12.0;
    try{
        var cv=plug.getViewExtents();
        cv=cv.replace(/,/gi,".");
        var values=cv.split(" ");
        this.North=values[0];
        this.South=values[1];
        this.East =values[2];
        this.West =values[3];
    }catch(e){
        //geap.traceException("getViewExtent");
    }
}
//-----------------------------------------
function IPointOnTerrainGE(x,y) {

    this.Latitude=0;
    this.Longitude=0;
    this.Altitude=0;
    this.ProjectedOntoGlobe=0;
    this.ZeroElevationExaggeration=0;

    try{
        var cv=plug.getPointOnTerrain(x,y);
        cv=cv.replace(/,/gi,".");
        var values=cv.split(" ");
        this.Latitude    =values[0];
        this.Longitude   =values[1];
        this.Altitude    =values[2];
        this.ProjectedOntoGlobe=values[3];
        this.ZeroElevationExaggeration=values[4];
    }catch(e){
        //traceException("PointOnTerrain");
    }
}

//-----------------------------------------
//-----------------------------------------
//ITimeIntervalGE
//-----------------------------------------
function ITimeIntervalGE() {
   this.BeginTime=new ITimeGE();
   this.EndTime=new ITimeGE();
}
//-----------------------------------------
//-----------------------------------------
//ITimeGE
function ITimeGE() {
   //todo
   this.type=0;
   this.Year=0;
   this.Month=0;
   this.Day=0;
   this.Hour=0;
   this.Minute=0;
   this.Second=0;
   this.TimeZone=0;
}
ITimeGE.prototype.Clone=function(){
   var timege=new ITimeGE();
   timege.type    =this.type    ;
   timege.Year    =this.Year    ;
   timege.Month   =this.Month   ;
   timege.Day     =this.Day     ;
   timege.Hour    =this.Hour    ;
   timege.Minute  =this.Minute  ;
   timege.Second  =this.Second  ;
   timege.TimeZone=this.TimeZone;
   return timege;
}
ITimeGE.prototype.ConvertToZone=function(TimeZone){
   var timege=new ITimeGE();
   //todo
   /*
   timege.type    =this.type    ;
   timege.Year    =this.Year    ;
   timege.Month   =this.Month   ;
   timege.Day     =this.Day     ;
   timege.Hour    =this.Hour    ;
   timege.Minute  =this.Minute  ;
   timege.Second  =this.Second  ;
   timege.TimeZone=this.TimeZone;*/
   return timege;
}
//-----------------------------------------
//-----------------------------------------
//ITourControllerGE
function ITourControllerGE() {
}
ITourControllerGE.prototype.PlayOrPause=function(){
   plug.setValue("Tour:PlayOrPause",1);
}
ITourControllerGE.prototype.Stop=function(){
   plug.setValue("Tour:Stop",1);
}
ITourControllerGE.prototype.Get_speed=function(){
   return plug.getParamValue("Tour:Get_speed");
}
ITourControllerGE.prototype.Set_speed=function(speed){
   plug.setValue("Tour:Set_speed",speed);
}
ITourControllerGE.prototype.Get_PauseDelay=function(){
   return plug.getParamValue("Tour:Get_PauseDelay");
}
ITourControllerGE.prototype.Set_PauseDelay=function(pauseDelay){
   plug.setValue("Tour:Set_PauseDelay",pauseDelay);
}
ITourControllerGE.prototype.Get_Cycles=function(){
   return plug.getParamValue("Tour:Get_Cycles");
}
ITourControllerGE.prototype.Set_Cycles=function(cycles){
   plug.setValue("Tour:Set_Cycles",cycles);
}
//-----------------------------------------
//-----------------------------------------
//IAnimationControllerGE
function IAnimationControllerGE() {
}
IAnimationControllerGE.prototype.Play=function(){
   //todo
   alert('IAnimationControllerGE.Play not yet implemented');
}
IAnimationControllerGE.prototype.Pause=function(){
}
IAnimationControllerGE.prototype.Get_SliderTimeInterval=function(){
   return 0;
}
IAnimationControllerGE.prototype.Get_CurrentTimeInterval=function(){
   return 0;
}

IAnimationControllerGE.prototype.Set_CurrentTimeInterval=function(pInterval){
}
//-----------------------------------------
function ISearchControllerGE() {
}
ISearchControllerGE.prototype.Search=function(searchString){
   //todo
   alert('ISearchControllerGE.Search not yet implemented');
}
ISearchControllerGE.prototype.IsSearchInProgress=function(){
   return false;
}
ISearchControllerGE.prototype.GetResults=function(){
   return new IFeatureCollectionGE();
}
ISearchControllerGE.prototype.ClearResults=function(){
}


//-----------------------------------------
//-----------------------------------------
//special init & click internal event handler.
//To receive event notification implements your own ApplicationGE_OnInit & ApplicationGE_OnClick functions 
//-----------------------------------------
function __ApplicationGE_OnInit() {
   try{
      if (ApplicationGE_OnInit!=undefined){
         ApplicationGE_OnInit();
      }
   }catch(e){
   }
}
//-----------------------------------------
function __ApplicationGE_OnClick() {
   try{
      if (ApplicationGE_OnClick!=undefined){
         ApplicationGE_OnClick();
      }
   }catch(e){
   }
}
//-----------------------------------------
function __ApplicationGE_OnSpeechEnd() {
   try{
      if (ApplicationGE_OnSpeechEnd!=undefined){
         ApplicationGE_OnSpeechEnd();
      }
   }catch(e){
   }
}
//-----------------------------------------
var plug=null;
var ieInitEvent='<SCRIPT LANGUAGE="JavaScript" EVENT="OnInit" FOR="ApplicationGE.Plugin">__ApplicationGE_OnInit();</SCRIPT>';
var ieClickEvent='<SCRIPT LANGUAGE="JavaScript" EVENT="OnClick" FOR="ApplicationGE.Plugin">__ApplicationGE_OnClick();</SCRIPT>';

var htmlIExploreInstall='<div style="left:0px;width:100%;height:100%;text-align:center;background:url(./images/back.jpg) center top no-repeat;"><SPAN STYLE="color:red;vertical-align:middle;"><h5><br><a href="setup.exe" STYLE="color:white">Click to install GoogleEarthAirlines plugin</a><br>then press F5 to reload the page </h5></SPAN></div>';
var htmlMozillaInstall ='<div style="left:0px;width:100%;height:100%;text-align:center;background:url(./images/back.jpg) center top no-repeat;"><SPAN STYLE="color:red;vertical-align:middle;"><h5><br><a href="setup.exe" STYLE="color:white">Click to install GoogleEarthAirlines plugin</a><br>then restart the browser</h5></SPAN></div>';
//-----------------------------------------

