 /*
 /           _|
 / _|_|_|        _|_|_|
 / _|    _|  _|  _|    _|
 / _|    _|  _|  _|    _|
 / _|    _|  _|  _|    _|
 /
 / nin: access
*/

/**
 * earth.js
 *
 * Contains javascript for rendering google
 * earth.
 *
 */

// set namespace
//
var earth    = {};

earth.scripts  = document.getElementsByTagName('script');
earth.index    = earth.scripts.length - 1;
earth.myScript = earth.scripts[earth.index];
earth.elm      = utils.getQueryValue('elm',earth.myScript.src);
earth.mURL     = utils.getQueryValue('m',earth.myScript.src);
earth.uURL     = utils.getQueryValue('u',earth.myScript.src);
earth.initlat  = utils.getQueryValue('lat',earth.myScript.src) - 0;
earth.initlon  = utils.getQueryValue('lon',earth.myScript.src) - 0;
earth.initr    = utils.getQueryValue('r',earth.myScript.src) - 0;
earth.inith    = utils.getQueryValue('h',earth.myScript.src) - 0;
earth.initt    = utils.getQueryValue('t',earth.myScript.src) - 0;
earth.initalt  = utils.getQueryValue('alt',earth.myScript.src) - 0;
earth.initaltm = utils.getQueryValue('altm',earth.myScript.src) - 0;
earth.initbdr  = utils.getQueryValue('bdr',earth.myScript.src) - 0;
earth.initrds  = utils.getQueryValue('rds',earth.myScript.src) - 0;
earth.initbld  = utils.getQueryValue('bld',earth.myScript.src) - 0;
earth.authStatus = utils.getQueryValue('authStatus',earth.myScript.src);
earth.ge       = null;
earth.geocoder = null;
earth.maxId    = 0;
 
// auto move? (non-interactive mode);
//
earth.defaultAutoMode   = true;
earth.firstLook         = true;
earth.currentMsg        = false;
earth.disableBrowseTip  = false;
earth.browsePopulated   = false;

// init
//
earth.init = function() {
  $(document).ready(function(){
    google.earth.createInstance(earth.elm, earth.initCB, earth.failureCB);
  });
};

// load earth api
//
google.load("earth", "1", {"callback" : earth.init});


// init geocoder
//
earth.initGeoCoder = function() {
  earth.geocoder = new google.maps.ClientGeocoder();  
};

// init callback
//
earth.initCB = function(instance) {
  earth.ge = instance;
  earth.ge.getWindow().setVisibility(true);
  google.load("maps", "2.150", {"callback" : earth.initGeoCoder});

  google.earth.addEventListener(earth.ge.getGlobe(), "mouseup", earth.globeWindowEventListener);

  earth.autoMode(earth.defaultAutoMode);
  earth.addKmlFromUrl(earth.mURL + '?authStatus=' + earth.authStatus);

  if(earth.initbld > 0) {
    $("#buildings").attr('checked', true);
    earth.ge.getLayerRoot().enableLayerById(earth.ge.LAYER_BUILDINGS, true);
  }

  if(earth.initrds > 0) {
    $("#streets").attr('checked', true);
    earth.ge.getLayerRoot().enableLayerById(earth.ge.LAYER_ROADS, true);
  }

  if(earth.initbdr > 0) {
    $("#borders").attr('checked', true);
    earth.ge.getLayerRoot().enableLayerById(earth.ge.LAYER_BORDERS, true);
  }

  earth.checkScroll();
};

// roads layer
//
earth.roadsLayer = function(visible) {
  if(earth.ge) {    
    earth.ge.getLayerRoot().enableLayerById(earth.ge.LAYER_ROADS, visible);
  }
};

// borders layer
//
earth.bordersLayer = function(visible) {
  if(earth.ge) {    
    earth.ge.getLayerRoot().enableLayerById(earth.ge.LAYER_BORDERS, visible); 
  }
};

// buildings layer
//
earth.buildingsLayer = function(visible) {
  if(earth.ge) {
    earth.ge.getLayerRoot().enableLayerById(earth.ge.LAYER_BUILDINGS, visible);
  }
};

// set Auto Mode
//
earth.autoMode = function(auto) {
  earth.auto = auto;

  if(earth.auto && earth.ge) {
    earth.ge.getOptions().setMouseNavigationEnabled(false);
    earth.ge.getNavigationControl().setVisibility(earth.ge.VISIBILITY_HIDE);
  } else {
    earth.ge.getNavigationControl().setVisibility(earth.ge.VISIBILITY_AUTO);    
    earth.ge.getOptions().setMouseNavigationEnabled(true);
  }

};

// loop timer
//
earth.loopTimer = function() {
  earth.getCurrentView();
  setTimeout(earth.mainLoop, 10111);
};

// main loop
//
earth.mainLoop = function() { 
  var d = new Date();
  earth.addKmlFromUrl(earth.uURL + '?authStatus=' + earth.authStatus + '&id=' + earth.maxId + '&time=' + d.getTime().toString());

  earth.loopTimer(); 
};

// scrollbar hack
//
earth.checkScroll = function() {

  if(activetab == 1 &&  $("#browse-content:visible").length == 0) {
    $('#browse-content').jScrollPane();
  }

  if(activetab == 0 &&  $("#auto-content:visible").length == 0) {
    $('#auto-content').jScrollPane();
  }

  setTimeout(earth.checkScroll, 1000);
};

// get current view
//
earth.getCurrentView = function() {
  earth.latitude  = earth.ge.getView().copyAsLookAt(earth.ge.ALTITUDE_RELATIVE_TO_GROUND).getLatitude();
  earth.longitude = earth.ge.getView().copyAsLookAt(earth.ge.ALTITUDE_RELATIVE_TO_GROUND).getLongitude();
  earth.altitude  = earth.ge.getView().copyAsLookAt(earth.ge.ALTITUDE_RELATIVE_TO_GROUND).getAltitude();
  earth.altmode   = earth.ge.getView().copyAsLookAt(earth.ge.ALTITUDE_RELATIVE_TO_GROUND).getAltitudeMode();
  earth.range     = earth.ge.getView().copyAsLookAt(earth.ge.ALTITUDE_RELATIVE_TO_GROUND).getRange();
  earth.heading   = earth.ge.getView().copyAsLookAt(earth.ge.ALTITUDE_RELATIVE_TO_GROUND).getHeading();
  earth.tilt      = earth.ge.getView().copyAsLookAt(earth.ge.ALTITUDE_RELATIVE_TO_GROUND).getTilt();
};

// get view link
//
earth.getViewLink = function() {
  earth.getCurrentView();

  var bld = $("#buildings").attr('checked') ? 1 : 0;
  var bdr = $("#borders").attr('checked') ? 1 : 0;
  var rds = $("#streets").attr('checked') ? 1 : 0;

  var link = '?latitude=' + earth.latitude 
    + '&longitude='  + earth.longitude 
    + '&range='    + earth.range 
    + '&heading='    + earth.heading 
    + '&tilt='    + earth.tilt 
    + '&altitude='  + earth.altitude
    + '&altitude_modem=' + earth.altmode
    + '&models='  + bld
    + '&roads='  + rds
    + '&borders='  + bdr;

  console.log(link);
};

// on failiure
//
earth.failureCB = function(errorCode) {
};

// look at
//
earth.lookAtPlacemark = function(latitude,longitude,range,heading,tilt,alt,altm) {
  earth.removeImage();
  earth.ge.setBalloon(null);

  var la       = earth.ge.createLookAt('');
  var r        = range ? range : Math.floor(Math.random()*1200)+200;
  var t        = tilt ? tilt : Math.floor(Math.random()*50)+1;
  var head     = heading ? heading : Math.floor(Math.random()*10)+1;
  var altitude = alt ? alt : 0;
  var amode    = altm ? altm : earth.ge.ALTITUDE_RELATIVE_TO_GROUND;

  la.set(latitude,longitude,0,earth.ge.ALTITUDE_RELATIVE_TO_GROUND,head,t,r);
  earth.ge.getView().setAbstractView(la);
};

// add kml from URL
//
earth.addKmlFromUrl = function(kmlUrl) {
  google.earth.fetchKml(earth.ge, kmlUrl, earth.kmlFinishedLoading);
};

// kml finished loading
//
earth.kmlFinishedLoading = function(kmlObject) {
  if (kmlObject) {
    earth.ge.getFeatures().appendChild(kmlObject);

    if (kmlObject.getAbstractView() !== null && earth.auto) {
      earth.ge.setBalloon(null);
      earth.ge.getView().setAbstractView(kmlObject.getAbstractView());      
    }

    if(earth.firstLook) {
      earth.loopTimer();
      setTimeout(earth.initView, 500);
    }

    var features = kmlObject.getFeatures();

    earth.updateMessages(features);
    earth.firstLook = false;
  }

};

// initial view
//
earth.initView = function() {
  if((earth.initlat != 0) && (earth.initlon != 0)) {
    $("#tabs").tabs('select', 1);
    $('#browse-content').jScrollPane();
    earth.lookAtPlacemark(earth.initlat,earth.initlon,earth.initr,earth.inith,earth.initt,earth.initalt,earth.initaltm);
  }
};

earth.autoMessagesArray = new Array();
earth.places            = new Array();
earth.updateCount       = 0;

// populate places array
//
earth.populatePlaces = function(placemarks) {
    var place = placemarks.getFirstChild();    
    while(place) {
      earth.places.push(place);
      place = place.getNextSibling();
    }
    earth.places.reverse();
};

// update messages
//
earth.updateMessages = function(placemarks) {

  earth.updateCount++;

  var place = null;

  if(earth.firstLook) {
    earth.populatePlaces(placemarks);
    place = placemarks.getLastChild();    
    $('#auto-loading').empty();
  } else {
    place = placemarks.getFirstChild();    
  }

  var loops  = 0;

  while(place) {
    loops++;

    var plid  = (place.getId() - 0);

    if(plid > earth.maxId) {
      earth.maxId = plid;
    }

    var mid     = 'auto-content_' + plid;
    var emid    = '#' + mid;

    earth.autoMessagesArray.push(mid);

    if(earth.autoMessagesArray.length > 50) {
      var elm = '#' + earth.autoMessagesArray.shift();
      $(elm).remove();
    }
  
    if(earth.firstLook) {
      $('#auto-messages').append(earth.getContentDiv(place,mid));
    } else {
      $('#auto-messages').prepend(earth.getContentDiv(place,mid));
    }

    $(emid + " .message .footer .tools").prepend(earth.getTargetLink(place));


    // calculate distance from current view
    //
    if(place && !earth.firstLook && !earth.auto) {
      // get a snapshot of the current view
      //earth.getCurrentView();

      var dist = LatLon.distHaversine(earth.latitude, earth.longitude, place.getGeometry().getLatitude(), place.getGeometry().getLongitude());

      dist = dist + 0;

      if(dist < 8.04672) {
	var bmid = 'browse-content_'+ place.getId();
	var bemid = '#'+ bmid;
	$('#browse-content').prepend(earth.getContentDiv(place,bmid));
	$(bemid).show();
	$(bemid + " .message .footer .tools").html(earth.getTargetLink(place));	
      }

    }

  
    if(!earth.firstLook) {
      $(emid).slideDown("slow");      
    } else {
      $(emid).show();
    }

    if (earth.firstLook) {
      if (loops < 10) {
        place = place.getPreviousSibling();
      } else {
	earth.currentMsg = place;
	earth.places.push(place);
        place = null;
      }
    } else {
      place = place.getNextSibling();
      earth.currentMsg = place;
    }

  }
  
  //setTimeout(earth.autoContentScrollBar, 1000);
  earth.autoContentScrollBar();
};

earth.browseLat  = false;
earth.browseLong = false;

// populate browse
//
earth.populateBrowse = function() {

  // get a snapshot of the current view
  earth.getCurrentView();

  if((earth.latitude != earth.browseLat && earth.longitude != earth.browseLong) || !earth.browsePopulated) {
    earth.browseLat  = earth.latitude;
    earth.browseLong = earth.longitude;

    if(activetab == 1) {
      // sort places by distance (from curent view)

      earth.places.sort(earth.placesComparator);
      earth.browsePopulated = true;

      // get the closest 10
      var i;
      var firstN = (earth.places.length > 20) ? 21 : earth.places.length;

      $('#browse-content').empty();

      for(i = 0; i < firstN; i++) {
	var mid = 'browse-content_'+ earth.places[i].getId();
	var emid = '#'+ mid;
	$('#browse-content').append(earth.getContentDiv(earth.places[i],mid));
	$(emid).show();
	$(emid + " .message .footer .tools").html(earth.getTargetLink(earth.places[i]));

	//var dist = LatLon.distHaversine(earth.latitude, earth.longitude, earth.places[i].getGeometry().getLatitude(), earth.places[i].getGeometry().getLongitude());
	//console.log("distance: "+dist);

      } 

      $('#browse-content').prepend('<div id="browse-tips"><img src="/images/access/browse-closest-title.png" /></div>');
      
      earth.browseContentScrollBar();
    }
  } else {
  }

};

// places comparator
//
earth.placesComparator = function(a, b) {
  return LatLon.distHaversine(earth.latitude, earth.longitude, a.getGeometry().getLatitude(), a.getGeometry().getLongitude()) -  
         LatLon.distHaversine(earth.latitude, earth.longitude, b.getGeometry().getLatitude(), b.getGeometry().getLongitude());
};

// get content div
//
earth.getContentDiv = function(place,mid) {
  return '<div id="'+ mid + '" class="sideMessage" style="display: none;">' + place.getDescription() + "</div>";  
};

// get target link
//
earth.getTargetLink = function(place) {
  var geo           = place.getGeometry();
  var latitude      = geo.getLatitude();
  var longitude     = geo.getLongitude();
  var target        = '<img id="target" height="15" width="16" src="/images/access/target.png" />';
  var target_onclk  = 'earth.lookAtPlacemark('+ latitude +','+ longitude +')';
  var htmlLink      = '<a href="#" onclick="'+ target_onclk +'; return false;">'+ target +'</a>';
  return htmlLink;
};

// init auto scrollbar
//
earth.autoContentScrollBar = function() {
  $('#auto-content').jScrollPane();
};

// init browse scrollbar
//
earth.browseContentScrollBar = function() {
  $('#browse-content').jScrollPane();

  if($('#browse-content')) {
    try {
      $('#browse-content')[0].scrollTo(0);    
    } catch(err) { }
  }

};

earth.browseLastEventTime = 0;

// google earth global event listener
//
earth.globeWindowEventListener = function(event) {
  earth.ge.setBalloon(null);
  earth.browseLastEventTime = (new Date).getTime();
  earth.removeImage();

  if(earth.auto && !earth.disableBrowseTip) {
    earth.showBrowseTip();
  }

  setTimeout(earth.populateBrowseOnEvent, 2500);
};

// populate browse on event
//
earth.populateBrowseOnEvent = function() {
  var delta = (new Date).getTime() - earth.browseLastEventTime;
  if(delta > 2300) {
    earth.populateBrowse();    
  }
};

// show browse tip
//
earth.showBrowseTip = function() {
  if($("#auto-tips").css('display') == 'none') {
    $('#auto-content')[0].scrollTo(0);
    $("#auto-tips").fadeIn("slow");  
  }
};

// hide browse tip
//
earth.hideBrowseTip = function() {
  if($("#auto-tips").css('display') == 'block') {
    earth.disableBrowseTip = true;
    $("#auto-tips").fadeOut("slow");  
  }
};

// search location
//
earth.search = function(location) {
  if(earth.geocoder) {
    earth.geocoder.getLatLng(location, function(point) {
      if (point) {
	if(earth.auto) {
	  $("#tabs").tabs('select', 1);
	} else {
	  setTimeout(earth.populateBrowse, 1500); 
	}
	var lookAt = earth.ge.createLookAt('');

	var range = Math.floor(Math.random()*12000)+40000;
	var tilt  = Math.floor(Math.random()*50)+1;
	var head  = Math.floor(Math.random()*10)+1;

	lookAt.set(point.lat(), point.lng(), 10, earth.ge.ALTITUDE_RELATIVE_TO_GROUND, head, tilt, range);
	earth.ge.getView().setAbstractView(lookAt);
      }
    });
  }
};

earth.currentBgOverlay    = false;
earth.currentImageOverlay = false;

// show image
//
earth.showImage = function(imageUrl) {
  earth.ge.setBalloon(null);

  if(earth.currentImageOverlay) {
    earth.ge.getFeatures().removeChild(earth.currentImageOverlay);
  }

  if(earth.currentBgOverlay) {
    earth.ge.getFeatures().removeChild(earth.currentBgOverlay);
  }

// to do fix for IE v Firefox
/*
  var bg = earth.ge.createIcon('');
  bg.setHref('http://ningeo.cpdev.sudjam.com/images/access/overlay-bg.png');

  var screenOverlayBg = earth.ge.createScreenOverlay('');
  screenOverlayBg.setIcon(bg);
  earth.currentBgOverlay = earth.ge.getFeatures().appendChild(screenOverlayBg);
*/


  var icon = earth.ge.createIcon('');
  icon.setHref(imageUrl);

  var screenOverlay = earth.ge.createScreenOverlay('');
  screenOverlay.setIcon(icon);
  earth.currentImageOverlay = earth.ge.getFeatures().appendChild(screenOverlay);  

  return false;
};

// remove image
//
earth.removeImage = function() {
  if(earth.currentImageOverlay) {
    earth.ge.getFeatures().removeChild(earth.currentImageOverlay);
    earth.currentImageOverlay = false;

    //earth.ge.getFeatures().removeChild(earth.currentBgOverlay);
    //earth.currentBgOverlay = false;
  }

  return false;
};

// initialize earth
//
//google.setOnLoadCallback(earth.init);
