
var StatesLayer;var StateLegend;var CountyLayer;var CountyLegend;var ApplicationLayer;var ApplicationLegend;var Map;var hideInfoBoxTimerId=null;function ShowMap()
{try{Map=new VEMap(MapPanel[0].id);Map.AttachEvent("oncredentialserror",function(){ShowModalDialog("Authentication Error","Map credentials are invalid.");});Map.SetCredentials("AmFM5C1QpeR_sBXTXV5VPGty_P-1qDXkXikheUwZHH9MrKJYJnQvN2O_e8IDDOc6");var View=GetSavedMapView();if(View===null){View=new Object();View.LatLong=InitialLatLong;View.ZoomLevel=InitialZoomLevel;View.MapMode=VEMapMode.Mode2D;View.MapStyle=VEMapStyle.Road;}
Map.LoadMap(View.LatLong,View.ZoomLevel,View.MapStyle,false,View.MapMode,false,1);Map.EnableShapeDisplayThreshold(false);StatesLayer=new VEShapeLayer();Map.AddShapeLayer(StatesLayer);CountyLayer=new VEShapeLayer();Map.AddShapeLayer(CountyLayer);ApplicationLayer=new VEShapeLayer();Map.AddShapeLayer(ApplicationLayer);Map.AttachEvent("onchangeview",onMapchangeview);Map.AttachEvent("onmouseover",onMouseOver);Map.AttachEvent("onmouseout",onMouseOut);Map.AttachEvent('onendzoom',onEndZoom);onMapchangeview();$('#itemdetailsdiv').hide();}catch(err){ShowModalDialog("Error",'ShowMap: '+err.message);}}
function onMapchangeview(event)
{if(Map.GetMapStyle()=='b')
{StatesLayer.Hide();CountyLayer.Hide();ApplicationLayer.Hide();}
else
{var zoomLevel=Map.GetZoomLevel();if(zoomLevel>=ApplicationMinZoomLevel&&zoomLevel<=ApplicationMaxZoomLevel)
{ApplicationLayer.Show();ApplicationLegend.show();}else{ApplicationLayer.Hide();ApplicationLegend.hide();}
if(zoomLevel>=CountyMinZoomLevel&&zoomLevel<=CountyMaxZoomLevel)
{CountyLayer.Show();CountyLegend.show();}else{CountyLayer.Hide();CountyLegend.hide();}
if(zoomLevel>=StateMinZoomLevel&&zoomLevel<=StateMaxZoomLevel)
{StatesLayer.Show();StateLegend.show();}else{StatesLayer.Hide();StateLegend.hide();}
if(StatesLayer.IsVisible())ShowStatesInView();if(CountyLayer.IsVisible())ShowCountiesInView();if(ApplicationLayer.IsVisible())ShowApplicationsInView();}
SaveMapView();}
function onEndZoom(e)
{if(e.zoomLevel<MinZoomLevel){Map.SetZoomLevel(MinZoomLevel);return true;}
if(e.zoomLevel>MaxZoomLevel){Map.SetZoomLevel(MaxZoomLevel);return true;}}
var ColorMapZeroColor=new VEColor(128,128,128,0.4);var RainbowColorMap=new Array(new VEColor(0,0,255,0.5),new VEColor(0,255,255,0.5),new VEColor(0,255,0,0.5),new VEColor(255,255,0,0.5),new VEColor(255,0,0,0.5));function MapColor(value,minValue,maxValue,colorMap,useZeroColor)
{if(value<minValue)value=minValue;if(value>maxValue)value=maxValue;var valueFraction=0;if(maxValue>minValue)valueFraction=(value-minValue)/(maxValue-minValue);if(valueFraction===0&&useZeroColor)
return ColorMapZeroColor;var mapIndex=valueFraction*(colorMap.length-1);var floorMapIndex=Math.floor(mapIndex);var ceilMapIndex=Math.ceil(mapIndex);var floorMapColor=colorMap[floorMapIndex];var ceilMapColor=colorMap[ceilMapIndex];var indexFraction=mapIndex-floorMapIndex;return new VEColor(Math.round(floorMapColor.R+(indexFraction*(ceilMapColor.R-floorMapColor.R))),Math.round(floorMapColor.G+(indexFraction*(ceilMapColor.G-floorMapColor.G))),Math.round(floorMapColor.B+(indexFraction*(ceilMapColor.B-floorMapColor.B))),floorMapColor.A+(indexFraction*(ceilMapColor.A-floorMapColor.A)));}
function VEColorToHex(veColor)
{var hexColor=((Math.round(veColor.R)*256+Math.round(veColor.G))*256+Math.round(veColor.B)).toString(16);while(hexColor.length<6)hexColor="0"+hexColor;return hexColor;}
function CreateLegend(legenddiv,title,minValue,maxValue,sections,colorMap)
{var ColorsPerSection=12;if(maxValue<minValue)minValue=maxValue;var colorInterval=(maxValue-minValue)/((sections-1)*ColorsPerSection);var s="";s+="<div class='mapLegendTitle'>"+title+"</div>";s+="<div class='mapLegendScaleContainer'>";s+="<table cellpadding='0' cellspacing='0'>";for(var colorIndex=0;colorIndex<sections*ColorsPerSection;colorIndex++)
{s+="<tr>";s+="<td class='mapLegendColor' ";if(colorIndex>=ColorsPerSection/2&&colorIndex<sections*ColorsPerSection-ColorsPerSection/2){var colorValue=maxValue-(colorIndex-ColorsPerSection/2)*colorInterval;s+="style='background-color:#"+VEColorToHex(MapColor(colorValue,minValue,maxValue,colorMap,false))+"'";}
s+=">";s+="</td>";s+="<td class='mapLegendColSpacer'> ";s+="</td>";if((colorIndex%ColorsPerSection)===0){var value=maxValue-colorIndex*colorInterval;s+="<td class='mapLegendNumber' rowspan="+ColorsPerSection+">";s+=Math.round(value);s+="</td>";}
s+="</tr>";}
s+="</table>";s+="</div>";legenddiv.html(s);}
function SaveMapView()
{var MapView=new Object();MapView.MapMode=Map.GetMapMode();MapView.MapStyle=Map.GetMapStyle();MapView.ZoomLevel=Map.GetZoomLevel();MapView.LatLong=Map.GetCenter();if(MapView.MapStyle=='b'){var birdsEyeScene=Map.GetBirdseyeScene();MapView.BirdsEyeOrientation=birdsEyeScene.GetOrientation();}
if(MapView.MapStyle!='b'){MapViewField.val(JSON.stringify(MapView));}}
function GetSavedMapView()
{var jsonMapView=MapViewField.val();if(jsonMapView.length===0)return null;var mapView=JSON.parse(jsonMapView);var SavedView=new Object();SavedView.LatLong=new VELatLong(mapView.LatLong.Latitude,mapView.LatLong.Longitude);SavedView.ZoomLevel=mapView.ZoomLevel;SavedView.MapMode=mapView.MapMode;SavedView.MapStyle=mapView.MapStyle;return SavedView;}
function ShowStatesInView()
{if(GetAllStates&&StatesLayer.GetShapeCount()>0)
return;var viewRect=Map.GetMapView();$.ajax({type:"POST",url:"ReportMapService.asmx/GetStates",data:JSON.stringify({'reportId':ReportId,'reportGroupId':ReportGroupId,'queryId':StateQueryId,'parameters':QueryParams,'topLeft':(GetAllStates?null:viewRect.TopLeftLatLong),'botRight':(GetAllStates?null:viewRect.BottomRightLatLong)}),contentType:"application/json; charset=utf-8",dataType:"json",success:function(msg){var states=msg.d;StatesLayer.DeleteAllShapes();AddStatesToLayer(StatesLayer,states);},error:function(result){ShowModalDialog("Failed to get state details",result.status+' '+result.statusText);}});}
function ShowCountiesInView()
{if(GetAllCounties&&CountyLayer.GetShapeCount()>0)
return;var viewRect=Map.GetMapView();$.ajax({type:"POST",url:"ReportMapService.asmx/GetCounties",data:JSON.stringify({'reportId':ReportId,'reportGroupId':ReportGroupId,'queryId':CountyQueryId,'parameters':QueryParams,'topLeft':(GetAllCounties?null:viewRect.TopLeftLatLong),'botRight':(GetAllCounties?null:viewRect.BottomRightLatLong)}),contentType:"application/json; charset=utf-8",dataType:"json",success:function(msg){var counties=msg.d;CountyLayer.DeleteAllShapes();AddCountiesToLayer(CountyLayer,counties);},error:function(result){ShowModalDialog("Failed to get county details",result.status+' '+result.statusText);}});}
function ShowApplicationsInView()
{var viewRect=Map.GetMapView();$.ajax({type:"POST",url:"ReportMapService.asmx/GetApplications",data:JSON.stringify({'reportId':ReportId,'reportGroupId':ReportGroupId,'queryId':AppQueryId,'parameters':QueryParams,'topLeft':viewRect.TopLeftLatLong,'botRight':viewRect.BottomRightLatLong}),contentType:"application/json; charset=utf-8",dataType:"json",success:function(msg){var applications=msg.d;ApplicationLayer.DeleteAllShapes();AddApplicationsToLayer(ApplicationLayer,applications);},error:function(result){ShowModalDialog("Failed to get installation details",result.status+' '+result.statusText);}});}
function onMouseOver(event)
{ShowShapeInfo(event.elementID);}
function onMouseOut(event)
{hideInfoBoxTimerId=setTimeout("HideShapeInfo()",500);}
function ShowShapeInfo(elementID)
{if(elementID!==null)
{var shape=Map.GetShapeByID(elementID);if(shape.GetType()!=VEShapeType.Pushpin)
{if(hideInfoBoxTimerId!==null)
{clearTimeout(hideInfoBoxTimerId);hideInfoBoxTimerId=null;}
$('#itemTitle').text(shape.GetTitle());$('#itemDescription').html(shape.GetDescription());$('#itemdetailsdiv').stop(true,true);if(!$('#itemdetailsdiv').is(':visible'))
{$('#itemdetailsdiv').show('slide',{direction:'down'},'fast');}}}}
function HideShapeInfo()
{if($('#itemdetailsdiv').is(':visible'))
{$('#itemdetailsdiv').stop(true,true).hide('slide',{direction:'down'},'slow');}}
function AddStatesToLayer(layer,states)
{for(var stateIndex in states)
{var state=states[stateIndex];var fillColor=MapColor(state.AppCount,0,StateMaxApplications,RainbowColorMap,true);AddObjectToLayer(layer,state.Name+" State",state.AppCount+" PV Systems<br />"+"Avg. size "+state.AvgkW+" kW-DC<br />"+"Avg. price $"+state.AvgCostPerW+"/Watt-DC",state.Boundary,new VEColor(51,102,153,1),1,fillColor);}
CreateLegend(StateLegend,"PV Systems<br>by State",1,StateMaxApplications,6,RainbowColorMap);}
function AddCountiesToLayer(layer,counties)
{for(var countyIndex in counties)
{var county=counties[countyIndex];var fillColor=MapColor(county.AppCount,0,CountyMaxApplications,RainbowColorMap,true);AddObjectToLayer(layer,county.Name+" County, "+county.StateCode,county.AppCount+" PV Systems<br />"+"Avg. size "+county.AvgkW+" kW-DC<br />"+"Avg. price $"+county.AvgCostPerW+"/Watt-DC",county.Boundary,new VEColor(51,102,153,1),1,fillColor);}
CreateLegend(CountyLegend,"PV Systems<br>by County",1,CountyMaxApplications,6,RainbowColorMap);}
function IconImageUrl(sectorId)
{var imageFileName;switch(parseInt(sectorId,10))
{case 1:imageFileName='round_push_4.gif';break;case 2:imageFileName='round_push_8.gif';break;case 3:imageFileName='round_push_5.gif';break;case 4:imageFileName='round_push_1.gif';break;case 5:imageFileName='round_push_2.gif';break;default:ShowModalDialog("Error","Invalid sector <"+sectorId+">");break;}
return ImageFolderPath+imageFileName;}
function SectorName(sectorId)
{switch(parseInt(sectorId,10))
{case 1:return'Commercial';case 2:return'Industrial';case 3:return'Residential';case 4:return'Non-Profit';case 5:return'Government';default:ShowModalDialog("Error","Invalid sector <"+sectorId+">");return null;}}
function AddApplicationsToLayer(layer,applications)
{for(var applicationIndex in applications)
{var app=applications[applicationIndex];AddObjectToLayer(layer,app.City+", "+app.StateCode,app.kW+" kW-DC, $"+app.CostPerW+"/Watt-DC<br />"+"Installed "+app.InstallDate,app.Location,null,null,null,IconImageUrl(app.SectorId));}
CreateApplicationLegend(ApplicationLegend,"PV Systems");}
function CreateApplicationLegend(legenddiv,title)
{var s="";s+="<div class='mapLegendTitle'>"+title+"</div>";s+="<table cellpadding='5' cellspacing='5'>";for(var sectorId=1;sectorId<=5;sectorId++)
{s+="<tr>";s+="<td class='mapLegendPushpin'>";s+="<img src='"+IconImageUrl(sectorId)+"'/>";s+="</td>";s+="<td align='left'>";s+=SectorName(sectorId);s+="</td>";s+="</tr>";}
s+="</table>";legenddiv.html(s);}
function AddObjectToLayer(layer,title,description,boundary,lineColor,lineWidth,fillColor,customIcon)
{var shapes=CreateShapesFromGeography(boundary);for(var shapeIndex in shapes){var shape=shapes[shapeIndex];shape.SetTitle(title);shape.SetDescription(description);if(lineColor)shape.SetLineColor(lineColor);if(lineWidth)shape.SetLineWidth(lineWidth);if(fillColor)shape.SetFillColor(fillColor);if(customIcon)
shape.SetCustomIcon(customIcon);else
shape.HideIcon();layer.AddShape(shapes[shapeIndex]);}}
var DifferentialCoordinateScalingFactor=10000;function CreateShapesFromGeography(geography)
{var shapes=new Array();var geometries=geography.split(GeometrySeparator);for(var geometryIndex in geometries)
{var geometry=geometries[geometryIndex];var points=geometry.split(PointSeparator);var shapePoints=new Array();var lastLatitude=null;var lastLongitude=null;for(var pointIndex in points)
{var point=points[pointIndex];var coords=point.split(CoordinateSeparator);var decodedLatitude=parseFloat(coords[0]);var decodedLongitude=parseFloat(coords[1]);if(lastLatitude!==null)
{decodedLatitude=lastLatitude+(decodedLatitude/DifferentialCoordinateScalingFactor);decodedLongitude=lastLongitude+(decodedLongitude/DifferentialCoordinateScalingFactor);}
lastLatitude=decodedLatitude;lastLongitude=decodedLongitude;shapePoints.push(new VELatLong(decodedLatitude,decodedLongitude,0,VEAltitudeMode.RelativeToGround));}
var shape=new VEShape(shapePoints.length>1?VEShapeType.Polygon:VEShapeType.Pushpin,shapePoints);shapes.push(shape);}
return shapes;}