var _MMF_API_U = "info@mapmyfitness.com";
var _MMF_API_P = "0945fc9611f55fd0e183fb8b044f1afe";
var _MMF_API_KEY = "b513571b80685c74fa95b7755d916c24048889df4";
var _MMF_API_AUTH = "consumer_key="+_MMF_API_KEY+"&u="+_MMF_API_U+"&p="+_MMF_API_P+"&signed_token=09123j1k2kj1923892908091jsaj9e&signed_token_limit=1";

var ge;
var tour = null;
var tour_url = '';
var kml_url = '';

google.load("earth", "1");

function initFlyby(jsonSettings)
{
	var strRouteKey = jsonSettings.route_key;
	var strSite = jsonSettings.site;
	if (strSite == "") { strSite = "mapmyfitness.com"; }
	tour_url = "http://api.mapmyfitness.com/3.1/routes/get_route_kml_tour?" + _MMF_API_AUTH + "&site="+strSite+"&route_key=" + strRouteKey;
	kml_url = "http://api.mapmyfitness.com/4/routes/get_route_kml?" + _MMF_API_AUTH + "&site="+strSite+"&route_key=" + strRouteKey;
	$("#tour_window").html("");
	google.earth.createInstance("tour_window", initCB, failureCB);
}

function failureCB(errorCode) {
	alert("We are unable to render this video at this time.  Do you have the recent Google Earth Plugin for this browser? (" + errorCode + ")");
	}

function initCB(instance)
{
	ge = instance;
	ge.getWindow().setVisibility(true);
	ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
	ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
	ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
	ge.getLayerRoot().enableLayerById(ge.LAYER_TERRAIN, true);
	
	// Add the KML
	google.earth.fetchKml(ge, kml_url, function(kmlObject) {
	      if (kmlObject)
	         ge.getFeatures().appendChild(kmlObject);
	});
	
	// Add the Tour
	google.earth.fetchKml(ge, tour_url, function(kmlObject)
		{
			if (!kmlObject) {
				setTimeout(function(){
			  		alert('Bad or null KML.');
				}, 0);
				return;
			}
		
			// Show the entire KML file in the plugin.
			ge.getFeatures().appendChild(kmlObject);
			
			// Walk the DOM looking for a KmlTour
			walkKmlDom(kmlObject, function(){
				if (this.getType() == 'KmlTour')
				{
			  		tour = this;
			  		ge.getTourPlayer().setTour(tour);
					ge.getTourPlayer().play();
			  		return false; // stop the DOM walk here.
				}
			});
	});
}

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

