var curLat = null;
var curLon = null;
var curAddress = null;
var curSqft = null;
var curPoly = null;
var curStation = null;
var curZip = null;
var curPctUsable = null;
var curUsedSafe = null;
var curBldgCount = null;
var lastRec = null;
var curMarker = null;
var slideInProgress = false;
var polygon = null;


var cityCode = function(data) {
	//jQuery('#address').html(data.value);
	jQuery('#lat').html(data.lat);
	jQuery('#lon').html(data.lon);
	jQuery('#sqft').html(data.sqft);
	jQuery('#sqft').html(data.poly);
	curLat = data.lat;
	curLon = data.lon;	
	curAddress = data.value;
	curSqft = data.sqft;
	//curPoly = data.poly;
	curStation = data.sta;
	curZip = data.zip;
	curPctUsable = data.pct;
	curUsedSafe = data.safe;
	curBldgCount = data.count;
	curBldgCount = data.mapblklot;
};

var fadeInSuggestion = function(suggestionBox, suggestionIframe){
	jQuery(suggestionBox).fadeTo(300,0.95);
};
var fadeOutSuggestion = function(suggestionBox, suggestionIframe){
	jQuery(suggestionBox).fadeTo(300,0);
};

function setMaxZoomCenter(map, latlng) {
  map.getCurrentMapType().getMaxZoomAtLatLng(latlng, function(response) {
    if (response && response['status'] == G_GEO_SUCCESS) {
      map.setCenter(latlng, response['zoom']);
    }
  });
}


var defaultText = 'Enter your address';
jQuery(document).ready(

	function()
	{

	  /* code for the maptype buttons */
	  jQuery("td.maptype").click(function() { jQuery("td.maptype").removeClass("selected"); jQuery(this).addClass("selected"); });

	  //jQuery("div").contains("Satellite").css({ color: "red", background: "blue" });
	  // show/hide the ajax loading animated gif
	  jQuery('#autocompleteMe').ajaxStart(function()
	  {
	    jQuery(this).addClass("throbbing");
	  }).ajaxStop(function()
	  {
	    jQuery(this).removeClass("throbbing");
	  });
	  jQuery('body').click(function() { hideRecommender(); });
	  jQuery('a').click(function() { hideRecommender(); });

	  jQuery('#help').ToolTip({
	    className: 'tooltip',
	    position: 'left',
	    delay: 200
	  }
		);
	  jQuery('#help').click(function() { tb_show('Help', 'addresshelp.html?TB_iframe=true&amp;height=300&amp;width=350', null); });

	  jQuery("form").bind("submit", function() { jQuery("div.submit").click(); return false; });
	  // show tb_content on load if the user wants to see it
	  var COOKIE_NAME = 'showWelcome';
	  if (jQuery.cookie(COOKIE_NAME) != null)
	  {
	    //The cookie exists. No need to do anything. :)
	  } else
	  {
	    //The cookie doesn't exist. Open the thickbox window.
	    //tb_show('Welcome to SF.SolarMap.org', 'welcome3.html?TB_iframe=true&amp;height=455&amp;width=615', null);
	  }


	  jQuery("input").blur(function()
	  {
	    if (this.value == '')
	      this.value = defaultText;
	  }
		);

	  jQuery("input").focus(function() { if (this.value == defaultText) this.value = ''; });

	  jQuery("a.submit").click(function()
	  {
	    // do a test to see if the current info in the box is the same as the curAddress.  
	    // this will be the case if the user selected from the pulldown
	    //	if(jQuery("input").val() == curAddress){
	    //			//map.clearOverlays();
	    //			setMarker(curLat, curLon, curAddress, curSqft, curPoly, curStation, curZip, curPctUsable, curUsedSafe);
	    //	}else{ 



	    jQuery.ajax({
	      type: "POST",
	      url: "recommend_v24b_pg.php",
	      data: "value=" + jQuery("input").val(),
	      success: function(msg)
	      {
	        //alert(msg);
	        deleteBuildingMarkers()
	        lastRec = jQuery('item', msg);
	        var outText = '';
	        var numRecs = jQuery('item', msg).size();
	        if (numRecs == 0)
	        {
	          jQuery('#recommend-span').html('An address match was not found.  Please reenter an address');
	          jQuery('#recommend-result').html(outText);
	        } else if (numRecs == 1)
	        {
	          //var t = lastRec.get(this.getAttribute('dir'));


	          //setMarker(jQuery('lat', msg).text(), jQuery('lon', msg).text(), jQuery('value', msg).text(), jQuery('sqft', msg).text(), jQuery('poly', msg).text(), jQuery('sta', msg).text(), jQuery('zip', msg).text(), jQuery('pct', t).text(), jQuery('safe', t).text(), jQuery('count', t).text(), jQuery('mapblklot', t).text() );
	          setMarker(jQuery('lat', msg).text(), jQuery('lon', msg).text(), jQuery('value', msg).text(), jQuery('sqft', msg).text(), jQuery('poly', msg).text(), jQuery('sta', msg).text(), jQuery('zip', msg).text(), jQuery('pct', msg).text(), jQuery('safe', msg).text(), jQuery('count', msg).text(), jQuery('mapblklot', msg).text(), jQuery('lu', msg).text());
	        } else
	        {
	          jQuery(msg).find('item').each(function(nr)
	          {
	            outText += '<li class="maplink" rel="' + jQuery('value', this).text() + '" dir="' + nr + '">' + jQuery('value', this).text() + '</li>';
	          });
	          jQuery('#recommend-span').html('An exact match of your address was not found.  Did you mean:');
	          jQuery('#recommend-result').html(outText);
	          jQuery('#recommend-inst').html('If your address is not listed, choose an address near yours, or zoom to your location on the map and then double-click on the roof of your building.  Once selected, your solar potential will be shown.');
	        }
	        if (numRecs != 1)
	        {
	          var subject = jQuery('#autocompleteMe').get(0);
	          var position = jQuery.iUtil.getPositionLite(subject);
	          var size = jQuery.iUtil.getSize(subject);
	          jQuery('#recommendHelper').css('top', position.y + size.hb + 'px').css('left', position.x + 'px').fadeTo(300, 0.95);
	          jQuery('.maplink').hover(function()
	          {
	            jQuery(this).addClass("hover");
	          }, function()
	          {
	            jQuery(this).removeClass("hover");
	          });
	          jQuery(".maplink").click(function()
	          {
	            jQuery("input").val(this.getAttribute('rel'));
	            var t = lastRec.get(this.getAttribute('dir'));
	            setMarker(jQuery('lat', t).text(), jQuery('lon', t).text(), jQuery('value', t).text(), jQuery('sqft', t).text(), jQuery('poly', t).text(), jQuery('sta', t).text(), jQuery('zip', t).text(), jQuery('pct', t).text(), jQuery('safe', t).text(), jQuery('count', t).text(), jQuery('mapblklot', t).text(), jQuery('lu', t).text());
	          });



	        }
	      }
	    });
	    // end of else	}
	  });

	  jQuery("dt.someClass").click(function()
	  {
	    jQuery(this).next().slideToggle("slow");
	  });

	  jQuery('#autocompleteMe').Autocomplete(
			{
			  source: 'autocomplete_v24pg.php',
			  fx: {
			    type: 'slide',
			    duration: 400
			  },
			  autofill: false,
			  helperClass: 'autocompleter',
			  selectClass: 'selectAutocompleter',
			  minchars: 6,
			  onSelect: cityCode,
			  onShow: fadeInSuggestion,
			  onHide: fadeOutSuggestion
			}
		);


	  //				delay: 500,
	  //		jQuery('#myAccordion').Accordion(
	  //			{
	  //				headerSelector	: 'dt',
	  //				panelSelector	: 'dd',
	  //				activeClass		: 'myAccordionActive',
	  //				hoverClass		: 'myAccordionHover',
	  //				panelHeight		: 120,
	  //				speed			: 300
	  //			}
	  //		);

	}
);

		function hideRecommender(){
 			if(jQuery('#recommendHelper').css("display") != 'none'){
				if(!slideInProgress){
	 				slideInProgress = true;
	 				jQuery('#recommendHelper').slideUp("slow",function(){slideInProgress = false;});
				}
			}				
		}

var cpeLoaded = false;

function setMarker(lat, lon, address, sqft, polyTxt, sta, zip, pctUsable, usedSafe, bldgCount, mapblklot, landuse){
	var point = new GLatLng(lat,lon);
	var t = map.getCurrentMapType().getMaximumResolution(point) - 1;

	map.setCenter(point, t);
	
	//var t = map.getCurrentMapType().getMaximumResolution(point) - 2;
	//if(map.getCurrentMapType() == 'G_NORMAL_MAP')
	//	map.setCenter(point, t);
	//else
	//	setMaxZoomCenter(map, point);
	//if(map.getZoom() < 16)
	//	map.setCenter(point, maxZoom);
	//else
	//	map.setCenter(point);
		
	if(!curMarker){
		curMarker = new GMarker(point, iconSun);
		map.addOverlay(curMarker);
	}else{
		curMarker.setPoint(point);
	}

	// estimate the mean roof kW used for the CPE
	// formulas actually reside in function getMarkerHtml
	//		var kwL = Math.round((rfsq/200)/4);
	//		var kwH = Math.round((rfsq/100)/4);
	if(usedSafe == 1){
		//var maxKw = Math.round((safeArea/100)/4);
		var maxKw = Math.round(sqft * pctUsable/100);
	}else{
		var maxKw = Math.round((sqft/100)/4);
	}


	// clean power estimator max
	var maxContentDiv = document.createElement('div');
	//	maxContentDiv.innerHTML = '<iframe src="cpe/cpe.php?address='+address+'&maxKw='+maxKw+'&zip='+zip+'" width="100%" height="800px" id="cpe-frame"></iframe>';
	maxContentDiv.innerHTML = 'Loading';
	var maxTitle = "Clean Power Estimate";
	//map.openInfoWindowHtml(point, markerHtml, {maxWidth:450, maxContent: maxContentDiv, maxTitle: maxTitle});

	//markerText = getMarkerHtml(curSqft);
	markerText = '<div id="table-address">'+address+'<sup>**</sup></div>'+getMarkerHtml(sqft, sta, pctUsable, usedSafe, bldgCount, mapblklot, zip); //+'<div id="table-address"><span id=\'assumptions\'>assumptions</span><span id=\'close\'>close window and zoom out</span></div>';

	// add the polygon to the map
	//GLog.write('polyTxt= '+polyTxt);
	// do not draw polygone
	//if(polyTxt.length >0){
	//	var polyVerts = new Array();
	//	var polyVertsString = new Array();
	//	polyVertsString =  polyTxt.split(';');
	//	for(k = 0; k< polyVertsString.length; k++){
	//		coordString = polyVertsString[k];
	//		// get index of comma
	//		commaLoc = coordString.indexOf(',');
	//		vertX = coordString.substring(0, commaLoc);
	//		vertY = coordString.substring(commaLoc+1);
	//		polyVerts.push(new GLatLng(vertY, vertX));
	//	}
	//	if(polygon) map.removeOverlay(polygon);
	//	polygon = new GPolygon(polyVerts, "#ff0000", 1, .5, "#ff0000", 0.2);
	//	  map.addOverlay(polygon);
	//}


	// use to max window:  curMarker.openInfoWindowHtml(markerText, {maxWidth:450,maxContent: maxContentDiv, maxTitle: maxTitle});
	curMarker.openInfoWindowHtml(markerText, {maxWidth:450});
	var iw = map.getInfoWindow();
	//GEvent.addListener(iw, "maximizeclick", function() {
	//	maxContentDiv.innerHTML = '<iframe src="cpe/cpe24b.php?address='+address+'&maxKw='+maxKw+'&zip='+zip+'&lu='+landuse+'" width="100%" height="800px" id="cpe-frame"></iframe>';
	//});

	GEvent.addListener(curMarker, 'click', function(){
		//us to max window: curMarker.openInfoWindowHtml(markerText, {maxWidth:450, maxContent: maxContentDiv, maxTitle: maxTitle});
		curMarker.openInfoWindowHtml(markerText, {maxWidth:450});
	});
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
   var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
   if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function openVideo(){
	tb_show('Welcome to SF.SolarMap.org', 'welcome.html?TB_iframe=true&amp;height=455&amp;width=615', null);
}
