/**
	Changes to 2.1:
		- addition of monitoring maximize window
	Changes to 2.1:
		- addition of clean power estimator 

*/


var map;
var centerLatitude = 45.5165100098; 
var centerLongitude = -122.678878784;
var startZoom = 13;
var iconSun; 
var iconYellowPnt;
var tooltip;
var existingMarkers= {};
var existingMarkersType= {};
var showSmallMarkers = true;

var iconOrangeBig;
var iconAquaBig;
var iconBlueBig;
var iconGreenBig;
var iconOrangeBig;
var iconPinkBig;
var iconRedBig;
var iconYellowBig;
var _enteredAddress, _marker, tileOverlay1, tileOverlay2, tileOverlay3, tileOverlay4, tileOverlay5, tileOverlay6, tileOverlay7, _rooftop = null;

// Added by rcm
jQuery(document).ready(
	function()	{
			if (jQuery.browser.mozilla) {
				//$(document).keypress (checkKey);
				jQuery('#autocompleteMe').bind('keypress', function(e) {
					switch (e.keyCode) {
						case(13):
							parcelSearch();
							return false;
							break;
					}
				});

			} else {
				//$(document).keydown (checkKey);
				jQuery('#autocompleteMe').bind('keydown', function(e) {
					switch (e.keyCode) {
						case(13):
							parcelSearch();
							return false;
							break;
					}
				});
			}
	}
);

function addCommas(nStr){
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function addressHelp() {
	tb_show('What Can Solar Do For You?', 'addresshelp.html?TB_iframe=true&amp;height=300&amp;width=400', null);
}

function clearContents() {
	document.getElementById('autocompleteMe').value = '';
}

function parcelSearch() {

	document.getElementById('autocompleteMe').style.backgroundPosition = "100% -18px";
	document.getElementById('autocompleteMe').onFocus = '#';
	_enteredAddress = document.getElementById('autocompleteMe').value.toUpperCase();
	var aAddress = _enteredAddress.split(' ');
	var geocoder = new GClientGeocoder();
	  geocoder.getLatLng(
	    _enteredAddress + ' oregon',
	    function(point) {
	      if (!point) {
	        document.getElementById('autocompleteMe').style.backgroundPosition = "100% 0px";
	        alert('Sorry, ' + _enteredAddress + " could not be found. Please try your search again.");
	      } else {
	       jQuery.ajax({
	         type: "GET",
	         url: "portland_search.php?lat="+point.y+"&long="+point.x,
	         success: function(msg) {
	         
	          try {
	           var msg = eval('(' + msg + ')');
	           var match = 0;
	           var oldmatch = 0;
	           var mostmatch = 0;
	           for (var i=0;i<15;i++) {
	              if (msg[i].add != null) {
	           	var add = msg[i].add.split(' ');
	           	for (var j=0;j<add.length;j++) {
	           		for (var k=0;k<aAddress.length;k++) {
	           			if (aAddress[k] == add[j]) {
	           				match++;
	           			}
	           		}
	           	}
	           	if (match > oldmatch) {
	           		mostmatch = i;
	           		oldmatch = match;
	           	}
	           	match = 0;
	              }
	           }
	           _rooftop = msg[mostmatch].bldsqft;
	           addMarker(parseFloat(msg[mostmatch].lon), parseFloat(msg[mostmatch].lat), msg[mostmatch].add, msg[mostmatch].bldsqft, null);
 		  } catch (e) {
 		  	document.getElementById('autocompleteMe').style.backgroundPosition = "100% 0px";
 		  	alert('Sorry, no parcel could be found matching your search. Please check your address and try again.');
 		  }
	         }
	       });
	      }
	    }
	  );
}

function addMarker(longitude, latitude, address, rooftop, iconName) {
	try {
		map.removeOverlay(_marker);
	} catch(e) {
	}
	document.getElementById('autocompleteMe').style.backgroundPosition = "100% 0px";
	var description = buildDesc(address, rooftop);
	var point = new GLatLng(latitude, longitude);
	var blueIcon = new GIcon(G_DEFAULT_ICON);
	blueIcon.iconSize = new GSize(24, 34);
	blueIcon.image = "images/current_24.png";
	markerOptions = { icon:blueIcon };
	_marker = new GMarker(point,markerOptions);
	map.setCenter(point, 17);
	GEvent.addListener(_marker, 'click',
		function() {
			_marker.openInfoWindowHtml(description);
			createSlider();
		}
	);

	map.addOverlay(_marker);
	_marker.openInfoWindowHtml(description);
	createSlider();
	
}

function createSlider() {
	jQuery("#slider").slider({ step: 5, value: 25, slide: function(event, ui) { 
			document.getElementById('usable').innerHTML = addCommas(Math.round(ui.value / 100 * _rooftop)) +  ' sqft'; 
			document.getElementById('estsolarpot').innerHTML = addCommas(Math.round(ui.value / 10 * _rooftop)) +  ' Watts';
			document.getElementById('annual').innerHTML = addCommas(Math.round(ui.value / 10 * _rooftop)) +  ' kWh';
			document.getElementById('perc').innerHTML =  ui.value + '%';
		} 
	});
}

function buildDesc(address, rooftop) {

	var desc = '<table width="350px"><tr><td colspan="2" style="background-color:#DCC725;font-weight:bold;padding:3px 0; text-align:center">' + address + '</td></tr>';
	desc += '<tr><td colspan="2" style="font-weight:bold;">My Solar Electric Potential<hr/><br/></td></tr>';
	if (rooftop > 0 ) {
		desc += '<tr><td>Building Footprint:</td><td>' + addCommas(Math.round(rooftop*100)/100) + ' sqft</td></tr>';
		desc += '<tr><td colspan="2" style="font-size:10px;"><br/>Select what percentage of your roof has clear access to the south:<br/></td></tr>';
		desc += '<tr><td colspan="2" align="center"><div style="width:300px;"><div id="perc" style="width:60px;float:left;">25%</div><div id="slider" style="width:220px;float:left;"></div></div><br/><br/></td></tr>';
		desc += '<tr><td>Usable Roof Area:</td>';
		desc += '<td><div id="usable">' + addCommas(Math.round(rooftop * 0.25)) + ' sqft</div></td>';
		desc += '<tr><td>Estimated solar potential:</td><td id="estsolarpot">' + addCommas(Math.round(rooftop * 2.5)) + ' Watts</td></tr>';
		desc += '<tr><td>Estimated Annual Energy Output:</td><td id="annual">' +  addCommas(Math.round(rooftop * 2.5)) + ' kWh</td></tr>';
	} else {
		desc += '<tr><td colspan="2">Sorry, we were unable to calculate the square footage of your roof.</td></tr>';
	}
	desc += '<tr><td colspan="2"><br/><a style="color:#009999;" href="http://energytrust.org/shared-resources/solar-calculator/" target="_blank">Calculate your solar costs and incentives</a></td></tr>';
	desc += '<tr><td colspan="2"><p style="font-size:10px;text-align:justify;">* The above estimates are for solar photovoltaic electric systems, but there are other great solar options as well.  A solar water heating system is one of the most affordable ways to go solar and can offset one of the biggest energy uses in your home. Residential solar water heating systems typically save 1,500 - 3,000 kilowatt hours (kWh) of electricity or 80 - 150 therms of gas per year. That is 60% of the energy used to heat water in an average Oregon home. In the summer, your system may meet 100% of your hot water needs.</p></td></tr>';
	desc += '<tr><td colspan="2"><a style="color:#009999;font-size:10px;" href="javascript:openDisclaimer();">Disclaimers</a></td></tr>';
	desc += '</table>';
	
	return desc;
}

function openDisclaimer() {
	tb_show('Disclaimers', 'disclaimers.html?TB_iframe=true&amp;height=400&amp;width=600', null);
}

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() {
	handleResize();
	
	// tb_show('Welcome to the Oregon Clean Energy Map', 'welcome.html?TB_iframe=true&amp;height=100&amp;width=400', null);
	
	map = new GMap2(document.getElementById("map"), {draggableCursor: "default", draggingCursor: "move"});
	map.addControl(new GLargeMapControl());

// ============= Add the residential pv =================

        tileOverlay1 = new GTileLayerOverlay(
  			new GTileLayer(null, null, null, {
    			tileUrlTemplate: 'http://204.227.9.151:8080/geowebcache/service/gmaps?layers=portland:residential_pv&zoom={Z}&x={X}&y={Y}', 
    			isPng:true,
    			opacity:1.0 }
    			)
		);
	tileOverlay1.isPng = function(){return true;};
	tileOverlay1.type = 'ResidentialPV';

// ============= Add the residential swh =================
        tileOverlay2 = new GTileLayerOverlay(
  			new GTileLayer(null, null, null, {
    			tileUrlTemplate: 'http://204.227.9.151:8080/geowebcache/service/gmaps?layers=portland:residential_swh&zoom={Z}&x={X}&y={Y}', 
    			isPng:true,
    			opacity:1.0 }
    			)
		);
	tileOverlay2.isPng = function(){return true;};
	tileOverlay2.type = 'ResidentialSWH';
	
// ============= Add the commercial PV =================
        tileOverlay3 = new GTileLayerOverlay(
  			new GTileLayer(null, null, null, {
    			tileUrlTemplate: 'http://204.227.9.151:8080/geowebcache/service/gmaps?layers=portland:commercial_pv&zoom={Z}&x={X}&y={Y}', 
    			isPng:true,
    			opacity:1.0 }
    			)
		);
	tileOverlay3.isPng = function(){return true;};
	tileOverlay3.type = 'CommercialPV';
// ============= Add the commercial SWH =================
        tileOverlay4 = new GTileLayerOverlay(
  			new GTileLayer(null, null, null, {
    			tileUrlTemplate: 'http://204.227.9.151:8080/geowebcache/service/gmaps?layers=portland:commercial_swh&zoom={Z}&x={X}&y={Y}', 
    			isPng:true,
    			opacity:1.0 }
    			)
		);
	tileOverlay4.isPng = function(){return true;};
	tileOverlay4.type = 'Commercial_swh';
	
// ============= Add the schools PV =================
        tileOverlay5 = new GTileLayerOverlay(
  			new GTileLayer(null, null, null, {
    			tileUrlTemplate: 'http://204.227.9.151:8080/geowebcache/service/gmaps?layers=portland:school&zoom={Z}&x={X}&y={Y}', 
    			isPng:true,
    			opacity:1.0 }
    			)
		);
	tileOverlay5.isPng = function(){return true;};
	tileOverlay5.type = 'schools_pv';
	
// ============= Add the gov pv =================
        tileOverlay6 = new GTileLayerOverlay(
  			new GTileLayer(null, null, null, {
    			tileUrlTemplate: 'http://204.227.9.151:8080/geowebcache/service/gmaps?layers=portland:government&zoom={Z}&x={X}&y={Y}', 
    			isPng:true,
    			opacity:1.0 }
    			)
		);
	tileOverlay6.isPng = function(){return true;};
	tileOverlay6.type = 'govt_pv';
	
// ============= Add the commercial PV =================
        tileOverlay7 = new GTileLayerOverlay(
  			new GTileLayer(null, null, null, {
    			tileUrlTemplate: 'http://204.227.9.151:8080/geowebcache/service/gmaps?layers=portland:govt_swh&zoom={Z}&x={X}&y={Y}', 
    			isPng:true,
    			opacity:1.0 }
    			)
		);
	tileOverlay7.isPng = function(){return true;};
	tileOverlay7.type = 'govt_swh';
	
// ============= Add the urban renewals area =================
	var tilelayer8 = new GTileLayer(new GCopyrightCollection(), 0, 14);
	tilelayer8.getTileUrl = function(tile,zoom){
		if(zoom >= 15){
			return "tiles_v22/blank.png"; 
		}else{
			return "mapTiles/urbanRenewalAreas/" + zoom + "/" + tile.x + "/" + tile.y + ".png"; 
		}
	};
	tilelayer8.isPng = function(){return true;};
	tilelayer8.getOpacity = function(){return 0.6};
	tileOverlay8 = new GTileLayerOverlay(tilelayer8);
	tileOverlay8.type = 'govt_swh';
	
// ============= Add the urban renewals area =================
	var tilelayer9 = new GTileLayer(new GCopyrightCollection(), 0, 14);
	tilelayer9.getTileUrl = function(tile,zoom){
		if(zoom >= 15){
			return "tiles_v22/blank.png"; 
		}else{
			return "mapTiles/historicDistricts/" + zoom + "/" + tile.x + "/" + tile.y + ".png"; 
		}
	};
	tilelayer9.isPng = function(){return true;};
	tilelayer9.getOpacity = function(){return 0.6};
	tileOverlay9 = new GTileLayerOverlay(tilelayer9);
	tileOverlay9.type = 'govt_swh';
	
// ============= Add the urban renewals area =================
	var tilelayer10 = new GTileLayer(new GCopyrightCollection(), 0, 14);
	tilelayer10.getTileUrl = function(tile,zoom){
		if(zoom >= 15){
			return "tiles_v22/blank.png"; 
		}else{
			return "mapTiles/conservationDistricts/" + zoom + "/" + tile.x + "/" + tile.y + ".png"; 
		}
	};
	tilelayer10.isPng = function(){return true;};
	tilelayer10.getOpacity = function(){return 0.6};
	tileOverlay10 = new GTileLayerOverlay(tilelayer10);
	tileOverlay10.type = 'govt_swh';
	
	map.addControl(new PromoControl());
	map.enableScrollWheelZoom();
	map.enableContinuousZoom();
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
	map.setMapType(G_HYBRID_MAP);
	
	map.addOverlay(tileOverlay8);
	map.addOverlay(tileOverlay9);
	map.addOverlay(tileOverlay10);
	tileOverlay8.hide();
	tileOverlay9.hide();
	tileOverlay10.hide();
	
	map.addOverlay(tileOverlay1);
	map.addOverlay(tileOverlay2);
	map.addOverlay(tileOverlay3);
	map.addOverlay(tileOverlay4);
	map.addOverlay(tileOverlay5);
	map.addOverlay(tileOverlay6);
	map.addOverlay(tileOverlay7);
	

	// ====== 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);

	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].lon)< allowableLngOffset)){
					var typeHtml = '';
					if( installMarkers[k].ej == 'Y'){ // ej is environ justice install
						typeHtml = 'Environmental Justice';
					}else if( installMarkers[k].t == '0'){ // typ 0 is normal install
						typeHtml = 'Residential';
					}else if( installMarkers[k].t == '1'){ // typ 1 is commercial funded
						typeHtml = 'Commercial';
					}else if( installMarkers[k].t == '2'){ // typ 1 is commercial funded
						typeHtml = 'Government';
					}else if( installMarkers[k].t == '3'){ // typ 1 is commercial funded
						typeHtml = 'School';
					}


					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].type,	//type swh or pv
						 installMarkers[k].date,
						 installMarkers[k].cn,
						 installMarkers[k].info
					);

					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;
				}
			}

		}

	});

	updateMarkers();

	GEvent.addListener(map, 'zoomend', function(){
		updateMarkers();
		if (jQuery('#checkres')[0].src == "http://oregon.cleanenergymap.com/images/unchecked.png") {
			tileOverlay1.hide();
			tileOverlay2.hide();
		}
		if (jQuery('#checkcom')[0].src == "http://oregon.cleanenergymap.com/images/unchecked.png") {
			tileOverlay3.hide();
			tileOverlay4.hide();
		}
		if (jQuery('#checksch')[0].src == "http://oregon.cleanenergymap.com/images/unchecked.png") {
			tileOverlay5.hide();
		}
		if (jQuery('#checkgov')[0].src == "http://oregon.cleanenergymap.com/images/unchecked.png") {
			tileOverlay6.hide();
			tileOverlay7.hide();
		}
		if (jQuery('#checkpv')[0].src == "http://oregon.cleanenergymap.com/images/unchecked.png") {
			tileOverlay1.hide();
			tileOverlay3.hide();
			tileOverlay5.hide();
			tileOverlay6.hide();
		}
		if (jQuery('#checkswh')[0].src == "http://oregon.cleanenergymap.com/images/unchecked.png") {
			tileOverlay2.hide();
			tileOverlay4.hide();
			tileOverlay7.hide();
		}
		if (jQuery('#urbanrenewal')[0].src == "http://oregon.cleanenergymap.com/images/unchecked.png") {
			tileOverlay8.hide();
		}
		if (jQuery('#historic')[0].src == "http://oregon.cleanenergymap.com/images/unchecked.png") {
			tileOverlay9.hide();
		}
		if (jQuery('#conservation')[0].src == "http://oregon.cleanenergymap.com/images/unchecked.png") {
			tileOverlay10.hide();
		}
	});

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

	GEvent.addListener(map, 'movestart', function(){
		map.savePosition();
	});
	
	_marker = new GMarker(map.getCenter());
	var description = '<div id="slider" style="width:80%;"></div>';
	map.addOverlay(_marker);
	_marker.openInfoWindowHtml(description);
	_marker.closeInfoWindow();
	map.removeOverlay(_marker);

}
function toggleLayer(elemId){

	var state = jQuery('#'+elemId)[0].src;

	typeHtml = 'Residential and Small Commercial';
	typeHtml = 'Large Residential';
	typeHtml = 'Large Commercial';
	typeHtml = 'Government/Non-Profit';

	var curZoom = map.getZoom();
	if (state == "http://oregon.cleanenergymap.com/images/checked.png") {
		jQuery('#'+elemId).attr("src", "images/unchecked.png");
		switch (elemId){
			case 'checkres':
				if(curZoom>=15)	removeMarkers('Residential');
				tileOverlay1.hide();
				tileOverlay2.hide();
				break;
			case 'checkcom':
				if(curZoom>=15)	removeMarkers('Commercial');
				tileOverlay3.hide();
				tileOverlay4.hide();
				break;
			case 'checksch':
				if(curZoom>=15) removeMarkers('Schools');
				tileOverlay5.hide();
				break;
			case 'checkgov':
				if(curZoom>=15) removeMarkers('Government');
				tileOverlay6.hide();
				tileOverlay7.hide();
				break;
			case 'checkpv':
				tileOverlay1.hide();
				tileOverlay3.hide();
				tileOverlay5.hide();
				tileOverlay6.hide();
				break;
			case 'checkswh':
				tileOverlay2.hide();
				tileOverlay4.hide();
				tileOverlay7.hide();
				break;
			case 'urbanrenewal':
				tileOverlay8.hide();
				break;
			case 'historic':
				tileOverlay9.hide();
				break;
			case 'conservation':
				tileOverlay10.hide();
				break;
		}	
	}else{
		jQuery('#'+elemId).attr("src", "images/checked.png");
		switch (elemId){
			case 'checkres':
				if(curZoom>=15) addMarkers('Residential', 0, iconRedBig);
				tileOverlay1.show();
				tileOverlay2.show();
				break;
			case 'checkcom':
				if(curZoom>=15) addMarkers('Commercial', 1, iconPinkBig);
				tileOverlay3.show();
				tileOverlay4.show();
				break;
			case 'checksch':
				if(curZoom>=15) addMarkers('Schools', 2, iconAquaBig);
				tileOverlay5.show();
				break;
			case 'checkgov':
				if(curZoom>=15) addMarkers('Government', 3, iconGreenBig);
				tileOverlay6.show();
				tileOverlay7.show();
				break;
			case 'checkpv':
				tileOverlay1.show();
				jQuery('#checkres').attr("src", "images/checked.png");
				jQuery('#checkcom').attr("src", "images/checked.png");
				jQuery('#checksch').attr("src", "images/checked.png");
				jQuery('#checkgov').attr("src", "images/checked.png");
				tileOverlay3.show();
				tileOverlay5.show();
				tileOverlay6.show();
				break;
			case 'checkswh':
				
				jQuery('#checkres').attr("src", "images/checked.png");
				jQuery('#checkcom').attr("src", "images/checked.png");
				jQuery('#checksch').attr("src", "images/checked.png");
				jQuery('#checkgov').attr("src", "images/checked.png");
				tileOverlay2.show();
				tileOverlay4.show();
				tileOverlay7.show();
				break;
			case 'urbanrenewal':
				tileOverlay8.show();
				break;
			case 'historic':
				tileOverlay9.show();
				break;
			case 'conservation':
				tileOverlay10.show();
				break;
		}		
	}
}

function removeMarkers(typ){
	for(k in existingMarkers){
		if(existingMarkersType[k] == typ){
			map.removeOverlay(existingMarkers[k]);
			delete existingMarkers[k];
			delete existingMarkersType[k];
		}
	}
	
}
function addMarkers(typ, num, newIcon){
	var mapBounds = map.getBounds();

	for(k = 0; k< installMarkers.length; k++){
		var latlng = new GLatLng( installMarkers[k].lat, installMarkers[k].lon);
		if(!existingMarkers[k] && mapBounds.contains(latlng)){
			var typeHtml = typ;
			if(installMarkers[k].t == num){
				existingMarkersType[k] = typeHtml;
				existingMarkers[k] = createMarker(
					 installMarkers[k].lon, 	//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].type,		//monitoring url
					 installMarkers[k].date
					);	
				map.addOverlay(existingMarkers[k]);
			}
		}
	}
}

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 < 15) && (!showSmallMarkers)){
		//need to switch to small markers
		deleteMarkers = true;
		showSmallMarkers = true;
		jQuery('#marker-res').attr('src','images/marker_red.gif');
		jQuery('#marker-com').attr('src','images/marker_purple.gif');
		jQuery('#marker-sch').attr('src','images/marker_aqua.gif');
		jQuery('#marker-gov').attr('src','images/marker_green.gif');
		jQuery('#otherdata').css('display','block');
	} else if((curZoom >= 15) && (showSmallMarkers)){
		//need to switch to big markers
		deleteMarkers = false;
		showSmallMarkers = false;
		jQuery('#marker-res').attr('src','images/markers2/red_marker_15.png');
		jQuery('#marker-com').attr('src','images/markers2/pink	_marker_15.png');
		jQuery('#marker-sch').attr('src','images/markers2/aqua_marker_15.png');
		jQuery('#marker-gov').attr('src','images/markers2/green_marker_15.png');
		jQuery('#otherdata').css('display','none');
	}

	// 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];
			delete existingMarkersType[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:  Residential Install --> Yellow
		1:  Commercial install 	--> Pink
		2:  NGO facility	--> Blue
		3:  School		--> Aqua
	*/
     if(curZoom >= 15){
	for(k = 0; k< installMarkers.length; k++){
		var latlng = new GLatLng( installMarkers[k].lat, installMarkers[k].lon);
		if(!existingMarkers[k] && mapBounds.contains(latlng)){
			var newIcon = null;
			var typeHtml = '';
			var fndMarker = false;
			if( installMarkers[k].t == '0' && jQuery('#checkres')[0].src == "http://oregon.cleanenergymap.com/images/checked.png"){ // typ 0 is normal install
				newIcon =  (showSmallMarkers) ? iconRedPnt : iconRedBig;
				typeHtml = 'Residential';
				fndMarker = true;
			}else if( installMarkers[k].t == '1' && jQuery('#checkcom')[0].src == "http://oregon.cleanenergymap.com/images/checked.png"){ // typ 1 is commercial funded
				newIcon =  (showSmallMarkers) ? iconPinkPnt : iconPinkBig;
				typeHtml = 'Commercial';
				fndMarker = true;
			}else if( installMarkers[k].t == '3' && jQuery('#checkgov')[0].src == "http://oregon.cleanenergymap.com/images/checked.png"){ // typ 1 is commercial funded
				newIcon =  (showSmallMarkers) ? iconGreenPnt : iconGreenBig;
				typeHtml = 'Government';
				fndMarker = true;
			}else if( installMarkers[k].t == '2' && jQuery('#checksch')[0].src == "http://oregon.cleanenergymap.com/images/checked.png"){ // typ 1 is commercial funded
				newIcon =  (showSmallMarkers) ? iconAquaPnt : iconAquaBig;
				typeHtml = 'Schools';
				fndMarker = true;
			}
			if (fndMarker) {
				existingMarkersType[k] = typeHtml;
				existingMarkers[k] = createMarker(
					 installMarkers[k].lon, 	//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].type,		//monitoring url
					 installMarkers[k].date,
					 installMarkers[k].cn,
					 installMarkers[k].info
					);	
				map.addOverlay(existingMarkers[k]);
			}
		}
	}
     }
}

// =========== Create Install Marker HTML ===================
function createInstallMarkerHtml(size, installer, coLink, imageTxt, savings, output, ownerQuote, typeHtml, ownerName, solartype, installdate, comname, exinfo){
	
	var sizeOutput = (size != 0) ? "System size: " + size +" kW <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:'';
	// var ownerOutput = (ownerName) ? "Location: " + ownerName +"<br/>": '';
				 
	var quoteOutput = (ownerQuote.length>0) ? 'System owner says: <span class="owner-quote" > '+ownerQuote+'</span><br/>': '';
	
	var solartypeOutput = (solartype.length>0)? '<br/>Solar Type: ' + solartype + '<br/>':'';
	
	var imageOutput = (imageTxt.length>0) ? "<br/><img src=http://oregon.cleanenergymap.com/" + imageTxt + " />": '';
	
	var iDate = (installdate.length>0) ? 'Date Installed: ' + installdate + '<br/>': '';
	
	var CommercialName = (comname.length>0) ? 'Company: ' + comname + '<br/>': '';
	
	var ExtraInfo = (exinfo.length>0) ? 'Additional Info: <a class="cont-link" href="' + exinfo + '" target="_blank">'+exinfo+'</a><br/>': '';

	var existingHtml = "<div id=\"table-address\">Current "+typeHtml+" Solar Install</div>"+CommercialName+sizeOutput+outputOutput+savingsOutput+installerOutput+solartypeOutput+iDate+ExtraInfo+quoteOutput+imageOutput;
	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(rawsqft, radStationId, myPctUsable, myUsedSafe){
	if((rawsqft.length > 0) && (parseInt(rawsqft)>0)){
	
		if(myUsedSafe == 1){
			rfsq = Math.round(rawsqft * myPctUsable);
			areaHtml = '  <tr><td>Roof Size:</td><td>'+Math.round(rawsqft)+' ft<sup>2</sup> (Usable Roof: '+rfsq+' ft<sup>2</sup>)</td></tr>';
		}else{
			rfsq = Math.round(rawsqft);
			areaHtml = '  <tr><td>Roof Size:</td><td>'+rfsq+' ft<sup>2</sup></td></tr>';
		}
	
		var solarIns = 5;
		switch (radStationId){
		case "Sf01":
			solarIns = 4.2;
			break;
		case "Sf02":
			solarIns = 4.6;
			break;
		case "Sf03":
			solarIns = 4.6;
			break;
		case "Sf04":
			solarIns = 4.1;
			break;
		case "Sf05":
			solarIns = 4.6;
			break;
		case "Sf06":
			solarIns = 4.6;
			break;
		case "Sf07":
			solarIns = 4.2;
			break;
		case "Sf08":
			solarIns = 4.5;
			break;
		case "Sf09":
			solarIns = 4.6;
			break;
		case "Sf10":
			solarIns = 4.5;
			break;
		case "Sf11":
			solarIns = 4.6;
			break;
		}	
	
		//Solar PV Potential 
		//kW (low estimate) = Math.round((roofSize/100)/4)
		//kW (high estimate) = Math.round((roofSize/50)/4)
		var kwL = Math.round((rfsq/200));  // remove form 
		var kwH = Math.round((rfsq/100));

		//Annual Electricity Produced 
		//KWh/year = kW*5*(.60 x 365)
		var kwYearH = kwH*solarIns*365*0.77; // multiply *.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.77)*0.16474;
		var dolYrL = (kwL * solarIns * 365*0.77)*0.16474;

		//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);

		areaHtml =  

		output = '<table>'+
				 '  <tr><td colspan=2 style="font-weight:bold;">My Solar Potential</td></tr>'+
				 '  <tr><td colspan=2 ><hr/></td></tr>'+areaHtml+
				 '  <tr><td>Estimated solar PV potential: </td><td>'+kwL+' - '+kwH+' kW</td></tr>'+
				 '  <tr><td>Estimated electricity produced: </td><td>'+kwYearL.toFixed(0)+' - '+kwYearH.toFixed(0)+' KWh/yr<sup>a</sup></td></tr>'+
				 '  <tr><td>Estimated electricity savings: </td><td>$'+dolYrL.toFixed(0)+'-$'+dolYrH.toFixed(0)+' per year<sup>a</sup></td></tr>'+
				 '  <tr><td>Estimated carbon savings: </td><td>'+lbsCO2YearL.toFixed(0)+' - '+lbsCO2YearH.toFixed(0)+' lbs per year<sup>a</sup></td></tr>'+
				 '  <tr><td COLSPAN=2 ALIGN="center"><font style="color:gray;font-size:10px;"><sup>a</sup> Assumes '+solarIns+' average peak sun-hours per day</font></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 href="http://www.gosolarcalifornia.ca.gov/database/" target="_blank">Find a solar installer</a><br/>'+
					'<a href="http://www.sfenvironment.org/our_programs/interests.html?ssi=6&ti=15&ii=63" 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>';
	}else{
		output = '<div>Unfortunately, information for this address <br/>is currently not available.  Please try a different<br/> address or contact <a class="sf-env" href="http://www.sfenvironment.org/our_programs/interests.html?ssi=6&ti=15&ii=63" target="_blank"> SF Environment </a> for more <br/>information about this location.</div>'+
				 '<div class="hr"></div><span class="infowin"><br/>'+
					'<a href="http://www.gosolarcalifornia.ca.gov/database/" target="_blank">Click here </a>to find a solar installer <br/>'+
					'<a href="http://www.sfenvironment.org/our_programs/interests.html?ssi=6&ti=15&ii=63" target="_blank">Click here </a>for more information on installing solar <br/>'+
					'<br/>'+
					'<a onclick="showWin(\'estimates\');">How the estimates were derived</a> &nbsp;&nbsp;----&nbsp;&nbsp; <a onclick="showWin(\'disclaimer\');">Disclaimer</a> <br/>'+
					'** Map locations are approximate</span>';

//					'<a href=\'javascript:maxThis();\'>Click here </a>for a more detailed estimate <br/>'+


	}
//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 '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;
	}

	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, solartype, installdate, comname, exinfo){

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

	var markerHtml = createInstallMarkerHtml(size, installer, coLink, imageTxt, savings, output, ownerQuote, typeHtml, ownerName, solartype, installdate, comname, exinfo);

	/* if(monUrl.length>0){
		var maxContentDiv = document.createElement('div');
		maxContentDiv.innerHTML = '<iframe src ="'+monUrl+'" width="100%" height="700px"></iframe>';
		var maxTitle = "Solar Performance Monitoring";
	} */
	

	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(){
	 var type = document.getElementById('selectMapType').selectedIndex;
	 var mt = map.getMapTypes();
	 map.setMapType(mt[type]);
}
function resetMap(){
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
}
function closeNavPanel() {
	document.getElementById('closenav').style.display = "none";
	document.getElementById('navPanel').style.display = "none";
	document.getElementById('opennav').style.display = "block";
}
function openNavPanel() {
	document.getElementById('closenav').style.display = "block";
	document.getElementById('navPanel').style.display = "inline";
	document.getElementById('opennav').style.display = "none";
}