google.load("earth", "1");

var ge = null;

//global homestyle
var homeStyleMap;
var homeStyle;


function init() {
	//load ge instance
	google.earth.createInstance("map3d", initCallback, failureCallback);
	
	//initialize impact widget listeners
	init_iw();
}

function initCallback(pluginInstance) {
	$("#loader").remove();
	//initialization callback, set up general ge params
	ge = pluginInstance;

	
	//hide the loader and show the app
	$("#map3d").attr("style","width:100%; height:100%; display:block;");
	
	ge.getWindow().setVisibility(true); // required!
	ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW);
	
	// add some layers
	ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
	//ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);
	//fly to US
    var la = ge.createLookAt('');
    la.set(parseFloat(39), parseFloat(-98),
      0, // altitude
      ge.ALTITUDE_RELATIVE_TO_GROUND,
      0, // heading
      0, // straight-down tilt
      5000000 // range (inverse of zoom)
      );
    ge.getView().setAbstractView(la);
    
	 //create the main home stylemap
	 //homeStyleMap = ge.createStyleMap("homeStyleMap");
	 //homeStyle = ge.createStyle("homeStyle");
	 //homeStyleMap.setNormalStyleUrl("#homeStyle");
	 //homeStyleMap.setHighlightStyleUrl("#homeStyle");
    
   
    setTimeout(function() {
	
		 //request the user information
		var aOpts = {
				'url':'index.php?key=' + key + '&a=users/userjson',
				'dataType':'json',
				'success':function(data){buildIntroWindow(data);},
				'complete':function(){initPurchaseListeners();}
		 };
		 jQuery.ajax(aOpts);
		},100);

}


function failureCallback(errorCode) {
  //alert("Failure loading the Google Earth Plugin: " + errorCode);
	//alert("Google Earth error, please refresh the page");
	$("#loader").remove();
	$("#map3d").attr("style","width:100%; height:100%; display:block;");
}

function loadKml(type) {
	if(type.match('VUL')) {
		var stat = type.split('VUL');
		var request = 'impact/index.php?key='+ key + '&a=vulcan&count=30&type=county&sort=up&stat=' + stat[1];
	} else {
		var request = 'impact/index.php?key='+ key + '&a=projects/typekml&name=' + type;
	}
	
		 
	 var kmlUrl = baseUrl + request;
	 
	 //alert(kmlUrl);
	  
	 // fetch the KML
	 google.earth.fetchKml(ge, kmlUrl, function(kmlObject) {
	 // NOTE: we still have access to the 'file' variable (via JS closures)
	 	//alert(kmlObject);
	   if (kmlObject) {
	     // show it on Earth
	     iwKMLobjects[type] = kmlObject;
		  try 
		  {
		 		ge.getFeatures().appendChild(kmlObject);
		 		//set up the zoom listeners
			 		if(!type.match('VUL')) {
			     		var feat = kmlObject.getFeatures().getChildNodes();
				 		for(var i=0; i<feat.getLength(); i++) {
				 			var pm = '';
				 			if(feat.item(i).getType() == 'KmlPlacemark') {
				 				pm = feat.item(i);	 				
				 				google.earth.addEventListener(pm, 'click', clickZoom);
				 			}
				 		}
			 		} else {
			 			//attach all the listeners to the vulcan object bubble
			     		var feat = kmlObject.getFeatures().getChildNodes();
				 		for(var i=0; i<feat.getLength(); i++) {
				 			var pm = '';
				 			if(feat.item(i).getType() == 'KmlPlacemark') {
				 				pm = feat.item(i);	 				
				 				google.earth.addEventListener(pm, 'click', clickNoZoom);
				 			}
				 		}
			 		}
	     } 
	     
	     catch(ex) 
	     {
	     		alert(ex);
	     		alert('error loading kml');
	     		return;
	     }
	
	   } else {
	     // bad KML
	     iwKMLObjects[type] = null;
	  
	     // wrap alerts in API callbacks and event handlers
	     // in a setTimeout to prevent deadlock in some browsers
	     setTimeout(function() {
	       alert('Bad or null KML.');
	     }, 0);
	     

	   }
	 }); 
}
 
 	function clickZoom(e) {
 		e.preventDefault();
 		var pm = e.getTarget();
		var la = pm.getAbstractView();		
		if(la === null) {
				var point = pm.getGeometry();
				var lat = point.getLatitude();
				var lon = point.getLongitude();
			   var la = ge.createLookAt('');
			   var range = 4000;
			    la.set(lat, lon,
			      0, // altitude
			      ge.ALTITUDE_RELATIVE_TO_GROUND,
			      0, // heading
			      0, // straight-down tilt
			      4000 // range (inverse of zoom)
			      );
		}
		
		ge.getView().setAbstractView(la);
		
		//set the balloon
  		var balloon = ge.createHtmlStringBalloon('');
    	balloon.setFeature(pm);
  		balloon.setContentString(pm.getDescription())
  		//balloon.setMaxWidth(400);

  		setTimeout(function() {
  			ge.setBalloon(balloon);
			/* no more purchases through project windows
			$("#startbuyoffset").click(function(){
				initPurchasePop();				
				//initPurchase(key);
			});
			*/
			
			$("#closeme").click(function(){
				ge.setBalloon(null);
				return false;
			});
			
			//set the zoom out listener
			$(".reset_all",".links").each(function(){
				$(this).click(function(){
					resetView();
				});
			});
			
  		},1500);
  		
 

 	}
 	
  	function clickNoZoom(e) {
 		e.preventDefault();
 		var pm = e.getTarget();	
		//set the balloon
  		var balloon = ge.createHtmlStringBalloon('');
    	balloon.setFeature(pm);
  		balloon.setContentString(pm.getDescription())
  		//balloon.setMaxWidth(400);

  		setTimeout(function() {
  			ge.setBalloon(balloon);
  			$("#bubble_startbuyoffset").unbind('click');
			$("#bubble_startbuyoffset").click(function(){
				initPurchasePop();
				//initPurchase(key);
			});

			$("#closeme").click(function(){
				ge.setBalloon(null);
				return false;
			});
			
			//set the zoom out listener
			$(".reset_all",".links").each(function(){
				$(this).click(function(){
					resetView();
				});
			});
			
  		},500);
 	}
  	
  	function run_tour(data) {
  		var tour = data.tour
  		var i = 1
  		var ival = setInterval(function(){
  			tour_step(tour[i]);
  			i++;
  		;},
  		15000)
  	}
  
  

	
  
  function tour_step(step) {
    var la = ge.createLookAt('');
    la.set(Number(step.lat), Number(step.lon),
      0, // altitude
      ge.ALTITUDE_RELATIVE_TO_GROUND,
      0, // heading
      0, // straight-down tilt
      500// range (inverse of zoom)
      );
    ge.getView().setAbstractView(la);
    
	//get the init callback
	
	var makeIntroWindow = function(data){
		 var udata = data['user'];
		 //create the placemark
	    placemark = ge.createPlacemark('');
	    
	    var point = ge.createPoint('');
	    point.setLatitude(Number(udata['lat']));
	    point.setLongitude(Number(udata['lon']));
	    placemark.setGeometry(point);
    
    	// add the placemark to the earth DOM
    	ge.getFeatures().appendChild(placemark);

	 	//create an abstract balloon
	 	var intro_balloon = ge.createHtmlStringBalloon('');
		intro_balloon.setFeature(placemark);
	 	intro_balloon.setMaxWidth(500);
	 	intro_balloon.setMaxHeight(375);
	 	intro_balloon.setContentString(udata['bubble']);
	 	ge.setBalloon(intro_balloon);
	 }
	 
  }  
  
  
  
  
  function load_tour() {
 	 //request the tour information
	 var aOpts = {
			'url':'index.php?key=' + key + '&a=projects/tour',
			'dataType':'json',
			'success':function(data){run_tour(data);},
			'complete':function(){}
	 };
	 jQuery.ajax(aOpts);  
  
  }
    
   
   function load_impact(id) {
	 var aOpts = {
			'url':'index.php?key=' + key + '&a=impacts/get&id=' + id,
			'dataType':'json',
			'success':function(data){
				for(var i in data.impacts) {
					var id = i;
					var impact = data.impacts.i;
				}						
				fly_to(impact);
			},
			'complete':function(){}
	 };
	 jQuery.ajax(aOpts);  
  
  }
   
   
  function fly_to(data) {
	    var la = ge.createLookAt('');
	    la.set(Number(data.lat), Number(data.lon),
	      0, // altitude
	      ge.ALTITUDE_RELATIVE_TO_GROUND,
	      0, // heading
	      0, // straight-down tilt
	      500// range (inverse of zoom)
	      );
	    ge.getView().setAbstractView(la);
	
		//set the balloon if there is one
		if(data.balloon) {
		    placemark = ge.createPlacemark('');
		    
		    var point = ge.createPoint('');
		    point.setLatitude(Number(data['lat']));
		    point.setLongitude(Number(data['lon']));
		    placemark.setGeometry(point);
	    
	    	// add the placemark to the earth DOM
	    	ge.getFeatures().appendChild(placemark);		
		  	var balloon = ge.createHtmlStringBalloon('');
		 	balloon.setFeature(placemark);
		  	balloon.setContentString(data.bubble)
		  		//balloon.setMaxWidth(400);
		
		  	setTimeout(function() {
		  		ge.setBalloon(balloon);
		  	},1500);
		}	

  }
  
 /* Impact Widget Functions*/
 function init_iw() {
  	init_iw_listen();  
 }
 
/*initialize listeners*/
function init_iw_listen() {
	$("#controls .impact_toggle").each(function() {
		//get project type
		var linkid = $(this).attr('id');
		var type = linkid.split('_')[1];
		$(this).click(function() {
			if(!$('#' + linkid).hasClass('active')) {
				$('#' + linkid).addClass('active');
				loadKml(type)
			} else {
				$('#' + linkid).removeClass('active');
					ge.getFeatures().removeChild(iwKMLobjects[type]);
					iwKMLobjects[type] = null;
			}
			return false;
		});
	});
	
	$("#controls .showall").each(function() {
		var linkid = $(this).attr('id');
		var type = linkid.split('_')[1];
		var vul = (type== 'vulcan') ? true : false;
		var loadMe = Array()
		for(var mtype in iwKMLobjects) {
			if(vul && mtype.match('VUL')) {
				loadMe.push(mtype);
				continue;
			} else if(!vul && !mtype.match('VUL')) {
				loadMe.push(mtype);
				continue;
			}
		}
		if(vul) {
			var buttons = $(".bad_toggle","#controls");
		} else {
			var buttons = $(".good_toggle","#controls");
		}
		$(this).click(function(){
			if($('#' + linkid).hasClass('active')) {
				unloadAll(linkid,loadMe,buttons);
			} else {
				loadAll(linkid,loadMe,buttons);
			}

			return false;
		});
	});
	//init reset listener
	$(".reset_all","#controls").each(function(){
		$(this).click(function(){
			resetView();
		});
	});
	
	//init all the take action buttons
	$("#startbuyoffset").unbind('click');
	$("#startbuyoffset","#controls").click(function(){
		initPurchasePop();
		/*		
		ge.setBalloon(null);
		setTimeout(function(){
	 		var offset_balloon = ge.createHtmlDivBalloon('');
			offset_balloon.setMaxWidth(800);
			offset_balloon.setMinWidth(500);
			offset_balloon.setMaxHeight(400);
			offset_balloon.setMinHeight(350);
			
			// create the <div>
			var div = document.createElement('DIV');
			div.innerHTML = '<div id="buyoffset"></div>';
			offset_balloon.setContentDiv(div);
	 		ge.setBalloon(offset_balloon);
			initPurchase(key);
		},800);
		*/
	});
	
	//init tour listener
	$("#tourlink").click(function(){
		load_tour();
	});
} 

function initPurchaseListeners() {
  	$("#bubble_startbuyoffset").unbind('click');
	$("#bubble_startbuyoffset").click(function(){
		initPurchasePop();		
		//initPurchase(key)
	});
}
	
function loadAll(linkid,all,buttons) {
	$('#' + linkid).addClass('active');
	for(var i=0; i<all.length; i++) {
		if(iwKMLobjects[all[i]] == null) {
			loadKml(all[i]);
		}
	}	
	//'activate' all buttons
	$(buttons).each(function(){
		$(this).addClass('active');
	});
}

function unloadAll(linkid,all,buttons) {
	$('#' + linkid).removeClass('active');
	for(var i=0; i<all.length; i++) {
		var it = all[i]
		if(iwKMLobjects[it] != null) {
			ge.getFeatures().removeChild(iwKMLobjects[it]);
			iwKMLobjects[it] = null;
		}
	}
	
	//'deactivate' all buttons
	$(buttons).each(function(){
		$(this).removeClass('active');
	});
}

function resetView() {
	//close balloons
	ge.setBalloon(null);
	//fly to US
    var la = ge.createLookAt('');
    la.set(39, -98,
      0, // altitude
      ge.ALTITUDE_RELATIVE_TO_GROUND,
      0, // heading
      0, // straight-down tilt
      3500000 // range (inverse of zoom)
      );
    ge.getView().setAbstractView(la);
}




function buildIntroWindow(data) {
	 var udata = data['user'];
	 
	 //create the pm icon
	 //var homeIcon = ge.createIcon('');
	 //homeIcon.setHref(udata['icon']);
	 //homeStyle.getIconStyle().setIcon(homeIcon);
	 
	 //create the placemark
	 placemark = ge.createPlacemark('');
	 

 
 	 // add the placemark to the earth DOM
 	 ge.getFeatures().appendChild(placemark);

	 //set the style
	var icon = ge.createIcon('');
	icon.setHref(udata['icon']);
	var style = ge.createStyle('');
	style.getIconStyle().setIcon(icon);
	placemark.setStyleSelector(style);

	 
	 var point = ge.createPoint('');
	 point.setLatitude(Number(udata['lat']));
	 point.setLongitude(Number(udata['lon']));
    placemark.setGeometry(point); 
 
 	//create an abstract balloon
 	var intro_balloon = ge.createHtmlStringBalloon('');
	intro_balloon.setFeature(placemark);
 	intro_balloon.setMaxWidth(500);
 	intro_balloon.setMaxHeight(375);
 	intro_balloon.setContentString(udata['bubble']);
 	ge.setBalloon(intro_balloon);
 	
 	//add purchase listener
 	
 	
 	//add listener for view our impact
 	$("#viewimpact").click(function(){
 		ge.setBalloon(null);
 		var vaid = 'sa_project';
 		var loadMe = Array()
		for(var mtype in iwKMLobjects) {
			if(!mtype.match('VUL')) {
				loadMe.push(mtype);
				continue;
			}
		}

		var buttons = $(".good_toggle","#controls"); 
		loadAll(vaid,loadMe,buttons);
		return false;		
 	});
 	
 	//add rollover event listener
 	
 	if(udata['isadmin']) {
   	google.earth.addEventListener(placemark,'click',function(){
			   //create an abstract balloon
	 			var hq_balloon = ge.createHtmlDivBalloon('');
				hq_balloon.setFeature(placemark);
				hq_balloon.setMinWidth(200);
				hq_balloon.setMinHeight(300);
				hq_balloon.setMaxWidth(800);

				// create the <div>
				var div = document.createElement('DIV');
				div.id = 'gme_bub';
				div.innerHTML = '<img src="http://www.begreennow.com/includes/images/impact_user_logos/r_150_gme_logo_150.gif" alt="GME" /><h2 id="hq">Green Mountain Energy\'s Headquarters</h2><img src="http://www.begreennow.com/images/ReceptionDesk.jpg" alt="GME" />';
				hq_balloon.setContentDiv(div);
	 			ge.setBalloon(hq_balloon);   	
   	});
   	
   }
   
}

function iw_unload() {
	$(window).trigger('unload');
	if(ge != null) {	
		ge.setBalloon(null);
		ge = null;
	}
}

function initPurchasePop() {
	var height = 700;
	var width = 550;
	var top = 100;
	var left = 75;
	var pop = 'https://www.begreennow.com/impact/index.php?key='+ key + '&p=impacts/purchase';
	wopen(pop,'_blank',width,height,top,left);	
}

function wopen(url, name, w, h, top, left)
{
	// Fudge factors for window decoration space.
	w += 32;
	h += 96;
	 var win = window.open(url,
	  name,
	  'width=' + w + ', height=' + h + ', ' +
	  'menubar=no, ' +
	  'status=no, toolbar=no, scrollbars=yes');
	 win.moveTo(top,left);
	 win.resizeTo(w, h);
	 win.focus();
}





 
 
