/**
	Changes to 2.1:
		- addition of monitoring maximize window
	Changes to 2.1:
		- addition of clean power estimator 
	Changes to 2.3 orig:
		- added math.round to roof sqft value

*/


var map;
var centerLatitude = 37.871802;
var centerLongitude = -122.268403; 
var startZoom = 13;
var iconSun; 
var iconYellowPnt;
var tooltip;
var existingMarkers= {};
var existingMuniMarkers= {};
var existingObsMarkers= {};
var showSmallMarkers = true;
var geocoder;


var iconOrangeBig;
var iconAquaBig;
var iconBlueBig;
var iconGreenBig;
var iconOrangeBig;
var iconPinkBig;
var iconRedBig;
var iconYellowBig;

function addMarker(longitude, latitude, description, iconName) {
	var marker = new GMarker(new GLatLng(latitude, longitude));
	GEvent.addListener(marker, 'click',
		function() {
			marker.openInfoWindowHtml(description);
		}
	);
	map.addOverlay(marker);
}

function getSafeValues(response){
	if (!response || response.Status.code != 200) {
		alert("Sorry, we were unable to find the address you entered.  Please try again.");
	} else {
		place = response.Placemark[0];
		latitude=place.Point.coordinates[1];
		longitude=place.Point.coordinates[0];
		accuracy = place.AddressDetails.Accuracy;
		
		berkeleyLatMin=37.83979;
		berkeleyLatMax=37.909945;
		berkeleyLngMin=-122.32554;
		berkeleyLngMax=-122.227272;
		
		
		

		if(accuracy <= 5){
			alert("A exact address was not found.  Please try again entering your address in the format street, city, zipcode.  ");
		}else if(latitude<berkeleyLatMin || latitude>berkeleyLatMax || longitude<berkeleyLngMin || longitude>berkeleyLngMax){
			alert("Data for this site is only available for the city of Berkeley.  Please try again entering your address again in the format street, zipcode.  ");
		}else{
			if(typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) !== 'undefined'){ 
				streetName = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
			}else if(typeof(place.AddressDetails.Country.AdministrativeArea) !== 'undefined'){ 
				streetName = place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
			}
			
			
			jQuery.ajax({
				type: "POST",
				url: "getSafeValues.php",
				data: "lat="+latitude+"&lng="+longitude+"&address="+streetName,
				error: function(msg){alert("ajax error: "+msg);},
				success: function(msg){
					//if(curMarker!== null){
					//	map.DeleteShape(curMarker);
					//}
					if(jQuery('em', msg).text() == "1"){				
						setMarker(jQuery('lat', msg).text(), jQuery('lng', msg).text(), streetName,  jQuery('area', msg).text(),  jQuery('pct', msg).text());
					}else{
						alert("An exact match to the berkeley database was not found. Please try again.");
						//map.SetCenterAndZoom(new VELatLong(latitude,longitude), 17);
					}
				}});
		}

	}

}

function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case.
	return 0;
}

function handleResize() {
	if(document.getElementById('page-header')){
		var height = windowHeight() - document.getElementById('page-header').offsetHeight  - document.getElementById('page-bar').offsetHeight - document.getElementById('footer').offsetHeight;
		document.getElementById('map').style.height = height + 'px';
		
		sideHeight = height - document.getElementById('tablist').offsetHeight;
		document.getElementById('box_dash_detail').style.height = sideHeight + 'px';
		document.getElementById('box_dash_message').style.height = sideHeight + 'px';
		linkHeight = height - 150;

		document.getElementById('welcome-text').style.height = linkHeight + 'px';
	}
}



function changeBodyClass(from, to) {
	document.body.className = document.body.className.replace(from, to);
	return false;
}

function init() {
	//document.getElementById('button-sidebar-hide').onclick = function() { return changeBodyClass('sidebar-right', 'nosidebar'); };
	//document.getElementById('button-sidebar-show').onclick = function() { return changeBodyClass('nosidebar', 'sidebar-right'); };
	handleResize();
	
	map = new GMap2(document.getElementById("map"), {draggableCursor: "default", draggingCursor: "move"});
	map.addControl(new GLargeMapControl());

	// ============= Add the tiles =================
	var tilelayer = new GTileLayer(new GCopyrightCollection(), 1, 19);
	tilelayer.getTileUrl = function(tile,zoom){
		//var url = 
		if(zoom > 15){
			return "tiles/blank.png"; 
		}else{
			tileUrl ="tiles/" + zoom + "/" + tile.x + "/" + tile.y + ".png"; 
			return tileUrl; 
		}
	};
	tilelayer.isPng = function(){return true;};
	var tileOverlay = new GTileLayerOverlay(tilelayer);
	tileOverlay.type = 'currentInstalls';
	

	//map.addControl(new GMapTypeControl());
	map.addControl(new PromoControl());
	map.enableScrollWheelZoom();
	map.enableContinuousZoom();
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
	geocoder = new GClientGeocoder();
	map.setMapType(G_HYBRID_MAP);
	map.addOverlay(tileOverlay);

	// ====== set up marker mouseover tooltip div ======
	tooltip = document.createElement("div");
	map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
	tooltip.style.visibility="hidden";
	tooltip.style.width="200px";
	var LegendControl = function(url) {this.url_ = url;};
	LegendControl.prototype = new GControl(true);
	LegendControl.prototype.initialize = function(map) {
		var container = document.createElement("div");
		container.style.width="220px";
		container.style.height=map.getSize().height+"px";
		container.style.zIndex="-500";
		url = this.url_;
		map.getContainer().appendChild(container);
			return container;
	};
	LegendControl.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(20, 0));
	};
	map.addControl(new LegendControl());

	var baseMarker = new GIcon();
	baseMarker.shadow = "images/markers2/shadow50.png";
	baseMarker.iconSize = new GSize(24, 34);
	baseMarker.shadowSize = new GSize(37, 34);
	baseMarker.iconAnchor = new GPoint(10, 17);
	baseMarker.infoWindowAnchor = new GPoint(10, 1);

	// create icons
	iconOrangeBig = new GIcon(baseMarker);
	iconOrangeBig.image = "images/markers2/orange_marker_24.png";
	iconAquaBig = new GIcon(baseMarker);
	iconAquaBig.image = "images/markers2/aqua_marker_24.png";
	iconBlueBig = new GIcon(baseMarker);
	iconBlueBig.image = "images/markers2/blue_marker_24.png";
	iconGreenBig = new GIcon(baseMarker);
	iconGreenBig.image = "images/markers2/green_marker_24.png";
	iconOrangeBig = new GIcon(baseMarker);
	iconOrangeBig.image = "images/markers2/orange_marker_24.png";
	iconPinkBig = new GIcon(baseMarker);
	iconPinkBig.image = "images/markers2/pink_marker_24.png";
	iconRedBig = new GIcon(baseMarker);
	iconRedBig.image = "images/markers2/red_marker_24.png";
	iconYellowBig = new GIcon(baseMarker);
	iconYellowBig.image = "images/markers2/yellow_marker_24.png";

	var basePoint = new GIcon();
	basePoint.iconSize = new GSize(8, 8);
	basePoint.iconAnchor = new GPoint(3, 3);
	basePoint.infoWindowAnchor = new GPoint(6, 5);

	iconAquaPnt = new GIcon(basePoint);
	iconAquaPnt.image = "images/markers2/aqua8.gif";
	iconBluePnt = new GIcon(basePoint);
	iconBluePnt.image = "images/markers2/blue8.gif";
	iconGreenPnt = new GIcon(basePoint);
	iconGreenPnt.image = "images/markers2/green8.gif";
	iconOrangePnt = new GIcon(basePoint);
	iconOrangePnt.image = "images/markers2/orange8.gif";
	iconPinkPnt = new GIcon(basePoint);
	iconPinkPnt.image = "images/markers2/pink8.gif";
	iconRedPnt = new GIcon(basePoint);
	iconRedPnt.image = "images/markers2/red8.gif";
	iconYellowPnt = new GIcon(basePoint);
	iconYellowPnt.image = "images/markers2/yellow8.gif";

	iconSun = new GIcon();
	iconSun.image = "images/markers2/current_24.png";
	iconSun.shadow = "images/markers2/shadow50.png";
	iconSun.iconSize = new GSize(24, 34);
	iconSun.shadowSize = new GSize(37, 34);
	iconSun.iconAnchor = new GPoint(10, 17);
	iconSun.infoWindowAnchor = new GPoint(10, 1);

	iconCS = new GIcon();
	iconCS.image = "images/markers2/cs_marker_24.png";
	iconCS.shadow = "images/markers2/shadow50.png";
	iconCS.iconSize = new GSize(24, 34);
	iconCS.shadowSize = new GSize(37, 34);
	iconCS.iconAnchor = new GPoint(10, 17);
	iconCS.infoWindowAnchor = new GPoint(10, 1);



	// SET UP CASE STUDIES


	// END OF ADD NEW CASE STUDY

	updateMarkers();

	GEvent.addListener(map, 'zoomend', function(){
		updateMarkers();
	});

	GEvent.addListener(map, 'moveend', function(){
		updateMarkers();
	});
	GEvent.addListener(map, 'zoomstart', function(){
		map.savePosition();
	});

	GEvent.addListener(map, 'movestart', function(){
		map.savePosition();
	});

	GEvent.addListener(map, "click", function(overlay,point) {
		if(map.getZoom() > 15){
			return true;
		
		}

		mapWidth = map.getSize().width;
		mapHeight = map.getSize().height;

		nePnt = map.getBounds().getNorthEast();
		swPnt = map.getBounds().getSouthWest();
		
		diffLng = Math.abs(swPnt.lng() - nePnt.lng());
		diffLat = Math.abs(nePnt.lat() - swPnt.lat());
		
		latPixel = diffLng/mapWidth;
		lngPixel = diffLat/mapHeight;

		allowableLatOffset = latPixel*4;
		allowableLngOffset = lngPixel*4;

		if(point){
			// == Hit the database to find the records ==
			var minLat;
			var minLng;
			var curLat = point.lat();
			var curLng = point.lng();
			var foundOne = false;
			for(k = 0; k< installMarkers.length; k++){
				if((Math.abs(curLat - installMarkers[k].lat) < allowableLatOffset) && (Math.abs(curLng - installMarkers[k].lng)< allowableLngOffset)){
					var typeHtml = '';
						//	0 - Berkeley first
						//	1 - Commercial
						//	2 - Government
						//	3 - Nonprofit
						//	4 - Residential
						//	5 - Thermal
					if( installMarkers[k].t == '0'){ // typ 0 is normal install
						typeHtml = 'Berkeley FIRST';
					}else if( installMarkers[k].typ == '1'){ // typ 1 is commercial funded
						typeHtml = 'Commercial';
					}else if( installMarkers[k].typ == '2'){ // typ 1 is commercial funded
						typeHtml = 'Government';
					}else if( installMarkers[k].typ == '3'){ // typ 1 is commercial funded
						typeHtml = 'Nonprofit';
					}else if( installMarkers[k].typ == '4'){ // typ 1 is commercial funded
						typeHtml = 'Residential';
					}else if( installMarkers[k].typ == '5'){ // typ 1 is commercial funded
						typeHtml = 'Solar Thermal';
					}


					var markerHtml = createInstallMarkerHtml(
															 installMarkers[k].d, 		//size
															 installMarkers[k].c, 		//company
															 installMarkers[k].cl, 	//company link
															 installMarkers[k].src,  	//imageTxt
															 installMarkers[k].s,		//savings
															 installMarkers[k].o,		//output
															 installMarkers[k].q,		//quote
															 typeHtml,					//type
															 installMarkers[k].own,		//name of owner - business name
															 installMarkers[k].mon		//monitoring url
														);

					var monUrl = installMarkers[k].mon;
					if(monUrl.length>0){
						var maxContentDiv = document.createElement('div');
						maxContentDiv.innerHTML = '<iframe src ="'+installMarkers[k].mon+'" width="100%" height="700px"></iframe>';
						var maxTitle = "Solar Performance Monitoring";
						map.openInfoWindowHtml(point, markerHtml, {maxWidth:350, maxContent: maxContentDiv, maxTitle: maxTitle});
					}else{
						map.openInfoWindow(point, markerHtml, {maxWidth:350});
					}
					foundOne = true;
					break;
				}
			}
			
		}

	});



}


function updateMarkers(){
	// start zoom is 13, max zoom is 19
	// show big markers after 15
	var mapBounds = map.getBounds();
	var curZoom = map.getZoom();
	var deleteMarkers = false;
	
	
	
	// show the small point markers in the legend
	if ((curZoom < 16) && (!showSmallMarkers)){
		//need to switch to small markers
		deleteMarkers = true;
		showSmallMarkers = true;
		jQuery('#legend').empty().append(
				'<table border="0" width="178px" cellspacing="0" cellpadding="0" style="margin:0;padding:0;">'+
				'<tr><td  class="marker" style="margin:0;padding:0;font-weight: bold;"><img src="images/spacer5.gif"/>Solar Installations</td></tr>'+
				'<tr><td class="marker"><img src="images/spacer5.gif"/><img id="marker-owner" src="images/markers2/yellow8.gif" align="top" />Residential PV</td></tr>'+
				'<tr><td class="marker"><img src="images/spacer5.gif"/><img id="marker-owner" src="images/markers2/pink8.gif" align="top" /> Municipal PV</td></tr>'+
				'<tr><td class="marker"><img src="images/spacer5.gif"/><img id="marker-owner" src="images/markers2/green8.gif" align="top" /> School/Non-Profit PV</td></tr>'+
				'<tr><td class="marker"><img src="images/spacer5.gif"/><img id="marker-owner" src="images/markers2/aqua8.gif" align="top" /> Commercial PV</td></tr>'+
				'<tr><td class="marker"><img src="images/spacer5.gif"/><img id="marker-owner" src="images/markers2/blue8.gif" align="top" /> <a href="http://www.cityofberkeley.info/sustainable" target="_blank">Berkeley FIRST installations</a></td></tr>'+
				'<tr><td class="marker"><img src="images/spacer5.gif"/><img id="marker-owner" src="images/markers2/red8.gif" align="top" /> Solar Thermal</td></tr>'+
				'</table>'+
				'<div><a onclick="PopUpWindow(\'submitSolar.php\',true, 850, 600, 1, 1);">Add my installation to the map</a></div>');

	}else if((curZoom > 15) && (showSmallMarkers)){
		//need to switch to big markers
		deleteMarkers = true;
		showSmallMarkers = false;
		jQuery('#legend').empty().append('<table border="0" width="178px" cellspacing="0" cellpadding="0" style="margin:0;padding:0;">'+
				'<tr><td class="marker" style="margin:0;padding:0;font-weight: bold;"><img src="images/spacer5.gif"/>Solar Installations</td></tr>'+

				'<tr><td class="marker"><img src="images/spacer5.gif"/><img id="marker-owner" src="images/markers2/yellow_marker_15.png" align="top" /> Residential PV</td></tr>'+
				'<tr><td class="marker"><img src="images/spacer5.gif"/><img id="marker-owner" src="images/markers2/pink_marker_15.png" align="top" /> Municipal PV</td></tr>'+
				'<tr><td class="marker"><img src="images/spacer5.gif"/><img id="marker-city" src="images/markers2/green_marker_15.png" align="top" /> School/Nonprofit PV</td></tr>'+
				'<tr><td class="marker"><img src="images/spacer5.gif"/><img id="marker-owner" src="images/markers2/aqua_marker_15.png" align="top" /> Commercial PV</td></tr>'+
				'<tr><td class="marker"><img src="images/spacer5.gif"/><img id="marker-owner" src="images/markers2/blue_marker_15.png" align="top" /> <a href="http://www.cityofberkeley.info/sustainable" target="_blank">Berkeley FIRST installations</a></td></tr>'+
				'<tr><td class="marker"><img src="images/spacer5.gif"/><img id="marker-owner" src="images/markers2/red_marker_15.png" align="top" /> Solar Thermal</td></tr>'+
				'</table>'+
				'<div><a onclick="PopUpWindow(\'submitSolar.php\',true, 850, 600, 1, 1);">Add my installation to the map</a></div>');
	}

	// clear the current marker class on the map when you zoom to a specific place
	if(deleteMarkers){
		for(k in existingMarkers){
			map.removeOverlay(existingMarkers[k]);
			delete existingMarkers[k];
		}
	}

	// clear the current marker class on the map that are not in the current extent
	for(k in existingMarkers){
		if(!mapBounds.contains(existingMarkers[k].getPoint())){
			map.removeOverlay(existingMarkers[k]);
			delete existingMarkers[k];
		}
	}

	/**
		Type: 
			0 - Berkeley first 
			1 - Commercial 
			2 - Government 
			3 - Nonprofit
			4 - Residential 
			5 - Thermal 
	*/
if(curZoom > 15){
	for(k = 0; k< installMarkers.length; k++){
		var latlng = new GLatLng( installMarkers[k].lat, installMarkers[k].lng);
		if(!existingMarkers[k] && mapBounds.contains(latlng)){
			var newIcon = null;
			var typeHtml = '';
			if( installMarkers[k].typ == '0'){ // typ 0 is normal install
				newIcon =  (showSmallMarkers) ? iconBluePnt : iconBlueBig;
				typeHtml = 'Berkeley FIRST';
			}else if( installMarkers[k].typ == '1'){ // typ 1 is commercial funded
				newIcon =  (showSmallMarkers) ? iconAquaPnt : iconAquaBig;
				typeHtml = 'Commercial';
			}else if( installMarkers[k].typ == '2'){ // typ 1 is commercial funded
				newIcon =  (showSmallMarkers) ? iconPinkPnt : iconPinkBig;
				typeHtml = 'Government';
			}else if( installMarkers[k].typ == '3'){ // typ 1 is commercial funded
				newIcon =  (showSmallMarkers) ? iconGreenPnt : iconGreenBig;
				typeHtml = 'Non-Profit';
			}else if( installMarkers[k].typ == '4'){ // typ 1 is commercial funded
				newIcon =  (showSmallMarkers) ? iconYellowPnt : iconYellowBig;
				typeHtml = 'Residential';
			}else if( installMarkers[k].typ == '5'){ // typ 1 is commercial funded
				newIcon =  (showSmallMarkers) ? iconRedPnt : iconRedBig;
				typeHtml = 'Thermal';
			}else{ // else --> typ 2 would be city facility
				newIcon =  (showSmallMarkers) ? iconGreenPnt : iconGreenBig;
			}

//createMarker(lon, lat, size, installer, coLink, iconName, imageTxt, savings, output, ownerQuote, typeHtml, ownerName, monUrl)
			existingMarkers[k] = createMarker(
										 installMarkers[k].lng, 	//lon
										 installMarkers[k].lat, 	//lat
										 installMarkers[k].d, 		//size
										 installMarkers[k].c, 		//company
										 installMarkers[k].cl, 	//company link
										newIcon, 		//iconName
										installMarkers[k].src, // installMarkers[k].img,  	//imageTxt
										 installMarkers[k].s,		//savings
										 installMarkers[k].o,		//output
										 installMarkers[k].q,		//quote
										 typeHtml,					//type
										 installMarkers[k].own,		//name of owner - business name
										 installMarkers[k].mon		//monitoring url
										);	
			map.addOverlay(existingMarkers[k]);
		}
	}
}
}

						//longitude, lat, size, company, companyLink, iconName, imageTxt, savings, output, quote
function createMuniMarker(lon, lat, size, installer, coLink, iconName, locName, caseStudy, hasPhoto, photoSrc){
	var marker = new GMarker(new GLatLng(lat, lon), {icon: iconName});

	//System size: 1.7 kW
	//System output: 330 kWh/year
	//Electric savings: $200/year
	//Installer: ABC installer (hyperlink to url)
	//
	//System owner says: “I love solar!”
	//[photo inserted, if available]
	var markerHtml = createMuniMarkerHtml(size, installer, coLink, locName, caseStudy, hasPhoto, photoSrc);
//GLog.write(existingHtml);
	GEvent.addListener(marker, 'click', function(){
		marker.openInfoWindowHtml(markerHtml, {maxWidth:350});
	});

	return marker;
}

function createMuniMarkerHtml(size, installer, coLink, locName, caseStudy, hasPhoto, imageTxt){
	var sizeOutput = (size != 'unk') ? "System size: " + size +" kW <br/>": "The system size has not been reported<br/>";
	//var outputOutput = (output.length>0) ? "System output: " + output +"<br/>": "";
	//var savingsOutput = (savings.length>0) ? "Electric savings: " + savings +"<br/>": "";
	var coHtml = (coLink.length>0) ? '<a class= "cont-link" href="'+coLink+'" target="_blank">'+installer+'</a>' : installer;
	var installerOutput = (installer) ? "Installer: " + coHtml +"<br/><br/>": "<br/>";
	var caseStudyOutput = (caseStudy) ? "<a class= 'cont-link' href='"+caseStudy+"' target='_blank'>Read about this installation</a>": "";
				 
	var imageOutput = '';
	if(imageTxt.length > 0){
		if(imageTxt.indexOf('http') >=0){
			imageOutput = '<a  class= "cont-link" href="'+imageTxt+'" target="_blank">view photos</a>'		
		
		}else{
			var temp = new Array();
			temp = imageTxt.split('&');
			imageOutput = '<img width="300px" height="'+temp[1]+'" src="photos/'+temp[0]+'.jpg"/>';
		}
	}

	//var quoteOutput = (ownerQuote.length>0) ? 'System owner says: <span class="owner-quote" > '+ownerQuote+'</span><br/>': '';
				 
	//var imageOutput = '';
	//if(imageTxt.length > 0){
	//	var temp = new Array();
	//	temp = imageTxt.split('&');
	//	imageOutput = '<img width="300px" height="'+temp[1]+'" src="photos/'+temp[0]+'.jpg"/>';
	//}
	var existingHtml = "<div id=\"table-address\">"+locName+"</div>"+sizeOutput+installerOutput+caseStudyOutput+imageOutput;

	return existingHtml;
}


function createObsMarker(lon, lat, n, num, iconName){
	var marker = new GMarker(new GLatLng(lat, lon), {icon: iconName});

	//System size: 1.7 kW
	//System output: 330 kWh/year
	//Electric savings: $200/year
	//Installer: ABC installer (hyperlink to url)
	//
	//System owner says: “I love solar!”
	//[photo inserted, if available]

	//var sizeOutput = (size != 'unk') ? "System size: " + size +" kW <br/>": "The system size has not been reported<br/>";
	//var outputOutput = (output.length>0) ? "System output: " + output +"<br/>": "";
	//var savingsOutput = (savings.length>0) ? "Electric savings: " + savings +"<br/>": "";
	//var coHtml = (coLink.length>0) ? '<a class= "cont-link" href="'+coLink+'" target="_blank">'+installer+'</a>' : installer;
	//var installerOutput = (installer) ? "Installer: " + coHtml +"<br/><br/>": "<br/>";
	//var caseStudyOutput = (caseStudy) ? "<br/><a class= 'cont-link' href='"+caseStudy+"' target='_blank'>Read about this installation</a>": "";
				 
	//var quoteOutput = (ownerQuote.length>0) ? 'System owner says: <span class="owner-quote" > '+ownerQuote+'</span><br/>': '';
	
	
	var markerHtml = createObsMarkerHtml(n, num);

	GEvent.addListener(marker, 'click', function(){
		marker.openInfoWindowHtml(markerHtml, {maxWidth:600});
	});

	return marker;
}

// =========== Create Install Marker HTML ===================
function createObsMarkerHtml(n, num){
	var imageOutput = (num) ? '<div style="height:350px;overflow: auto;"> <div height="700px"><img width="550px" height="360px" src="http://sfwater.org/files/powerpolicy/SolarMonitoring/WeeklyOutput_1'+num+'.png" />'+
					'<br/><br/><img width="550px" height="360px" src="http://sfwater.org/files/powerpolicy/SolarMonitoring/MonthlyOutput_1'+num+'.png" /></div></div>': '<a class= "cont-link" href="http://sfwater.org/detail.cfm/MC_ID/12/MSC_ID/139/MTO_ID/360/C_ID/1888" target="_blank">Get additional information on monitoring stations</a>';
	//if(imageTxt.length > 0){
	//	var temp = new Array();
	//	temp = imageTxt.split('&');
	//	imageOutput = '<img width="300px" height="'+temp[1]+'" src="photos/'+temp[0]+'.jpg"/>';
	//}
	var existingHtml = "<div id=\"table-address\">"+n+"</div>"+imageOutput;
	return existingHtml;


}
// =========== Create Install Marker HTML ===================
function createInstallMarkerHtml(size, installer, coLink, imageTxt, savings, output, ownerQuote, typeHtml, ownerName, monUrl){
	
	var noInfo = false;
	
	if(size != 'unk' && output.length>0){
		var sizeOutput = "System size: " + size +" kW <br/>";
	}else{
		var sizeOutput = "";
		noInfo=true;
	}
	var outputOutput = (output && output.length>0) ? "System output: " + output +"<br/>": "";
	var savingsOutput = (savings && savings.length>0) ? "Electric savings: " + savings +"<br/>": "";
	var coHtml = (coLink && coLink.length>0) ? '<a class= "cont-link" href="'+coLink+'" target="_blank">'+installer+'</a>' : installer;
	var installerOutput = (installer) ? "Installer: " + coHtml +"<br/><br/>": "<br/>";
	var ownerOutput = (ownerName) ? "Location: " + ownerName +"<br/>": "";
				 
	var quoteOutput = (ownerQuote && ownerQuote.length>0) ? 'System owner says: <span class="owner-quote" > '+ownerQuote+'</span><br/>': '';
	
	var monitoringOutput = (monUrl&&monUrl.length>0)? '<br/><a class= "cont-link"  href=\'javascript:maxThis();\'>View monitoring information</a>':'';
	
	var imageOutput = '';
	if(imageTxt&&imageTxt.length > 0){
		if(imageTxt.indexOf('http') >=0){
			imageOutput = '<a  class= "cont-link" href="'+imageTxt+'" target="_blank">view photos</a>'		
		
		}else{
			var temp = new Array();
			temp = imageTxt.split('&');
			imageOutput = '<img width="300px" height="'+temp[1]+'" src="photos/'+temp[0]+'.jpg"/>';
		}
	}
	var submitInfo = '';
	if(noInfo){
		submitInfo='Is this your solar system?  If so, please <a onclick="PopUpWindow(\'submitSolar.php\',true, 850, 550, 1, 1 );">submit your information</a> and share your experiences with solar.';
	}

	var existingHtml = "<div id=\"table-address\">Current "+typeHtml+" Solar Install</div>"+ownerOutput+sizeOutput+outputOutput+savingsOutput+installerOutput+quoteOutput+imageOutput+monitoringOutput+submitInfo;
	return existingHtml;
}

function maxThis(){
	map.getInfoWindow().maximize();
}


window.onresize = handleResize;
//window.onload = init;

var PromoControl = function(url) {
	this.url_ = url;
};

PromoControl.prototype = new GControl(true);

PromoControl.prototype.initialize = function(map) {
	var container = document.createElement("a");
	addClass(container, 'gmnoprint');
	container.innerHTML = '<img  class="fixpng" style="cursor:pointer" src="images/designedby3.png" style="BORDER-RIGHT: 0px; PADDING-RIGHT: 0px; BORDER-TOP: 0px; PADDING-LEFT: 0px; PADDING-BOTTOM: 0px; MARGIN: 0px; BORDER-LEFT: 0px; WIDTH: 86px; CURSOR: pointer; PADDING-TOP: 0px; BORDER-BOTTOM: 0px; HEIGHT: 30px" border="0" >';
	container.style.width='86px';
	//container.style.height='34.5333px';
	
	url = this.url_;
	
	GEvent.addDomListener(container, "click", function() {
		document.location = "http://www.ch2m.com/ess";
	});
	
	map.getContainer().appendChild(container);
	
	return container;
};

PromoControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(70, 0));
};

function addClass(element, value) {
	if (!element.className) {
		element.className = value;
	} else {
		var newClassName = element.className;
		newClassName += " ";
		newClassName += value;
		element.className = newClassName;
	}
}

function getMarkerHtml(totrfsq, pct){
		// correct units on values in db m2->ft2
		totrfsq = parseInt(totrfsq)*10.76391;
		var solarIns = 5.45;
		rfsq = parseInt(totrfsq)*parseFloat(pct);
		//Solar PV Potential 
		//kW (low estimate) = Math.round((roofSize/100)/4)
		//kW (high estimate) = Math.round((roofSize/50)/4)
		var kwH = Math.round((rfsq/100)*10)/10;

		//Annual Electricity Produced 
		//KWh/year = kW*5*(.60 x 365)
		var kwYearH = kwH*solarIns*365*0.77;
		//var kwYearL = kwL*solarIns*365*0.77;

		//Annual Electricity Savings 
		//$/year = (kW x 1461)*0.11430
		// 06/26/08 - changed from 0.11430 to 0.16474 per Jason's request
		var dolYrH = (kwH * solarIns * 365)*0.13*0.77;
		//var dolYrL = (kwL * solarIns * 365)*0.16474*0.77;

		//Annual Carbon Savings 
		//lbs. CO2/year =1812*kWh
		var lbsCO2YearH =0.746*(kwH*solarIns*365)*0.77;
		//var lbsCO2YearL =0.746*(kwL*solarIns*365)*0.77;

		var shwTherms = rfsq*2.6;
		var lbsCO2swh = shwTherms*12.325;

		output = '<table style="font-size:11px;">'+
				 '  <tr><td colspan=2 > The information below provides an estimate of solar electricity or solar thermal potential of the building\'s roof size.  The  estmimated values may not be sufficient to generate the entire energy needs of the building and conversely, the estimate may exceed the energy required to result in a net zero cost utility bill.   To determine the total energy needed for this building based on current usage history, go to the <a onclick="PopUpWindow(\'calculator3.html\',true, 850, 550, true, true );">solar calculator</a> on this website.</td></tr>'+
				 '  <tr><td colspan=2 style="font-weight:bold;">My Roof Area</td></tr>'+
				 '  <tr><td colspan=2 ><hr/></td></tr>'+
				 '  <tr><td>Estimated Roof Size:</td><td>'+Math.round(totrfsq)+' sq. ft.</td></tr>'+
				 '  <tr><td>Estimated Solar Area:</td><td>'+Math.round(rfsq)+' sq. ft.</td></tr>'+
				 '  <tr><td colspan=2 style="font-weight:bold;"><br/>Solar Electric Potential</td></tr>'+
				 '  <tr><td colspan=2 ><hr/></td></tr>'+
				 '  <tr><td>Estimated solar PV potential: </td><td>Up to '+kwH+' kW</td></tr>'+
				 '  <tr><td>Estimated electricity produced: </td><td>Up to '+kwYearH.toFixed(1)+' kWh/yr</td></tr>'+
				 '  <tr><td>Estimated electricity savings: </td><td>Up to $'+dolYrH.toFixed(0)+' per year</td></tr>'+
				 '  <tr><td>Estimated carbon savings: </td><td>Up to '+Math.round(lbsCO2YearH)+' lbs per year</td></tr>'+
				 '  <tr><td colspan=2 style="font-weight:bold;"><br/>Solar Hot Water Potential</td></tr>'+
				 '  <tr><td colspan=2 ><hr/></td></tr>'+
				 '  <tr><td>Estimated solar thermal potential: </td><td>Up to '+Math.round(shwTherms)+' therms</td></tr>'+
				 '  <tr><td>Estimated carbon savings: </td><td>Up to '+Math.round(lbsCO2swh)+' lbs/yr</td></tr>'+
				 '  <tr><td>&nbsp;</td><td>&nbsp;</td></tr>'+
		// take the next step		 '  <tr><td COLSPAN=2 ALIGN="center" ><a id="nextstep" onclick="nextStep();" href="#" title="nextstep" class="thickbox">Take the next step</a></td></tr>'+
				 '</table>'+
		//		 '<div class="hr"></div><span class="infowin">'+
			//		'<a href=\'javascript:maxThis();\' ><span style="font-weight:bold;font-size:12px;">Get Cost Estimates >></span></a><br/>'+
			//		'<hr/>'+
			//		'<br/><span style="font-weight:bold;font-size:12px;">Links</span>'+
			//		'<hr/>'+
					'<a onclick="showWin(\'calculator\');">Do a Financial Analysis</a><br/>';
			//		'<a href="http://www.ebenergy.org/smartsolar" target="_blank">More information</a> about installing solar <br/>'+
			//		'<br/>'+
			//		'<span style="color:red;">*</span><a onclick="showWin(\'disclaimer\');">Disclaimer</a><span style="color:red;">*</span> <br/>'+
			//		'Map locations are approximate<br/>'+
			//		'<a onclick="showWin(\'estimates\');">Find out how we estimated your solar potential</a></span>';

//nextstep.html?TB_iframe=true&amp;height=400&amp;width=600			 
	return output;
}

function showWin(page){
	switch(page){
		case 'nextStep':
			sendTo = 'http://www2.sfenvironment.org/aboutus/energy/solarsf/how_checklist.htm?TB_iframe=true&amp;height=400&amp;width=700';
			pageTitle = 'Take the next step';
			break;
		case 'calculator':
			sendTo = 'calculator3.html?TB_iframe=true&amp;height=600&amp;width=800';
			pageTitle = 'Calculate My Solar Savings';
			break;
		case 'disclaimer':
			sendTo = 'disclaimers.html?TB_iframe=true&amp;height=400&amp;width=600';
			pageTitle = 'Disclaimers';
			break;
		case 'estimates':
			sendTo = 'estimates_v2.html?TB_iframe=true&amp;height=400&amp;width=600';
			pageTitle = 'How estimates were derived';
			break;
		case 'education':
			sendTo = 'education.html?TB_iframe=true&amp;height=400&amp;width=600';
			pageTitle = 'Learn About Energy';
			break;
		case 'submitSolar':
			sendTo = 'submitSolar.php?TB_iframe=true&amp;height=400&amp;width=800';
			pageTitle = 'Submit a Solar System';
			break;
		case 'help':
			sendTo = 'help.htm?TB_iframe=true&amp;height=400&amp;width=800';
			pageTitle = 'Help Using This Map';
			break;



	}

	tb_show(pageTitle, sendTo, null);


}

function nextStep(){
	tb_show('Take the next step', 'http://www2.sfenvironment.org/aboutus/energy/solarsf/how_checklist.htm?TB_iframe=true&amp;height=400&amp;width=700', null);
}


function showCaseStudy(filename){
	 window.open ('files/'+filename,"mywindow");
	//tb_show('caseStudy', 'petcamp.pdf?TB_iframe=true&amp;height=600&amp;width=600', null);
}
						//longitude, lat, size, company, companyLink, iconName, imageTxt, savings, output, quote
function createMarker(lon, lat, size, installer, coLink, iconName, imageTxt, savings, output, ownerQuote, typeHtml, ownerName, monUrl){

	var marker = new GMarker(new GLatLng(lat, lon), {icon: iconName});

	//System size: 1.7 kW
	//System output: 330 kWh/year
	//Electric savings: $200/year
	//Installer: ABC installer (hyperlink to url)
	//
	//System owner says: “I love solar!”
	//[photo inserted, if available]

	//if(size != 'unk'){
	//	//var eleOutput = output;
	//	//var eleSavings = Math.round((size * 1461)*0.11430);
	//	existingHtml = existingHtml + "System size: "+size+" kW <br /> System output: "+output+" kWh/yr <br/> Electric savings: $"+eleSavings+"/yr <br/> Installer: "+ installer +"<br/><br/>"+imageTxt;
	//} else {
	//	existingHtml = existingHtml + "<div>The system size at this location is unknown<br/> Installer: "+ installer +"<br/><br/>"+imageTxt+"</div>";
	//}
	var markerHtml = createInstallMarkerHtml(size, installer, coLink, imageTxt, savings, output, ownerQuote, typeHtml, ownerName, monUrl);

	if(monUrl.length>0){
		var maxContentDiv = document.createElement('div');
		maxContentDiv.innerHTML = '<iframe src ="'+monUrl+'" width="100%" height="700px"></iframe>';
		var maxTitle = "Solar Performance Monitoring";
	}
	
	//var iw = map.getInfoWindow();
	//GEvent.addListener(iw, "maximizeclick", function() {
	//	GDownloadUrl(monUrl, function(data) {
	//		maxContentDiv.innerHTML = data;
	//	});
	//});

	GEvent.addListener(marker, 'click', function(){
		if(monUrl.length>0){
			marker.openInfoWindowHtml(markerHtml, {maxWidth:350, maxContent: maxContentDiv, maxTitle: maxTitle});
		}else{
			marker.openInfoWindowHtml(markerHtml, {maxWidth:350});
		}
	});

	return marker;
}




// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a side_bar mouseover
function showTooltip(marker) {
	tooltip.innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
}

function setMapType(type){
	 var mt = map.getMapTypes();
	 map.setMapType(mt[type]);
}
function resetMap(){
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
}
