// JavaScript Document
google.load("earth", "1");
var ge = null;

function initGoogleEarth() {
  google.earth.createInstance("map", initCallback, failureCallback);
}

function initCallback(pluginInstance) {
  ge = pluginInstance;
  ge.getWindow().setVisibility(true); // required!
//  addKmlFromUrl('http://thelivingroomofthenation.com/boxapixels.xml?dummy='+(new Date()).getTime());

  tagMovies();
}

function failureCallback(errorCode) {
  alert("Failure loading the Google Earth Plugin: " + errorCode);
}

function refreshMapView() {
  ge = pluginInstance;
  ge.getWindow().setVisibility(true); // required!
}

function addKmlFromUrl(kmlUrl) {
	google.earth.fetchKml(ge, kmlUrl, kmlFinishedLoading);
}

function kmlFinishedLoading(kmlObject) {
  if (kmlObject) {
    ge.getFeatures().appendChild(kmlObject);
	la = ge.createLookAt('init_view');
	
	la.setLongitude(24.0);
	la.setLatitude(62.0);
	la.setAltitude(100000.0);
	la.setRange(1000000.0);
  	ge.getView().setAbstractView(la);
  }
}

function positionMap(geoTagString) {
	if(geoTagString!="NULL") {
		var temp = new Array();
		temp = geoTagString.split(' ');
		var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
		lookAt.setLatitude(parseFloat(temp[0]));
		lookAt.setLongitude(parseFloat(temp[1]));
		ge.getView().setAbstractView(lookAt);
	}
}

function clickHandler(event) {
	event.preventDefault();
	placemark = event.getTarget();
	index = placemark.getAddress();
	selectMovie(index);
	scrollThumbs(index);
}

function tagMovies() {
	  for (var i = 0; i < movies.length; i++) {
		var movie_record = movies[i];
		var placemark = ge.createPlacemark('');
		placemark.setAddress(i+'');
		placemark.setName(movie_record['title']);
		var point = ge.createPoint('');
		var geo = movie_record['geo'].split(' ');
		point.setLatitude(parseFloat(geo[0]));
		point.setLongitude(parseFloat(geo[1]));
		placemark.setGeometry(point);
		var style = ge.createStyle('');
		placemark.setStyleSelector(style);
		var icon = ge.createIcon('');
		icon.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
		style.getIconStyle().setIcon(icon);
		google.earth.addEventListener(placemark, 'click', clickHandler);		
		ge.getFeatures().appendChild(placemark);	  
	}
	la = ge.createLookAt('init_view');
	
	la.setLongitude(26.0);
	la.setLatitude(64.0);
	la.setAltitude(200000.0);
	la.setRange(2000000.0);
  	ge.getView().setAbstractView(la);
}