var g;var calc;var Calculator=Class.create();function handleNavigation(C,A){var B=$$("a.calculator-nav.active")[0];if(Event.element(C).hasClassName("next-step")){var D=B.up().next().down("a")}else{var D=B.up().previous().down("a")}calc.menu.trigger(D)}Calculator.prototype={map:null,performanceCalc:null,roi:null,analysis:null,savings:null,report:null,menu:null,fs:["quick-calculation","bill-analysis","effect-on-bills","roi-report","performance","select-utility-company"],cookieFields:["zipCode","currentPowerRateField","solarPowerRateField","powerCompanyField","averageBill","customRateCost","customRateUsed","customRateSelector","averageRateSelector","averageStateRate","totalOutput"],initialize:function(opt){Object.extend(this,opt||{});for(var i=0;i<this.cookieFields.length;i++){this[this.cookieFields[i]].cookieName=this.cookieFields[i];if(!this[this.cookieFields[i]].value){this[this.cookieFields[i]].value=Cookie.get(this.cookieFields[i])||""}Event.observe(this[this.cookieFields[i]],"change",function(e){Cookie.set(e.target.cookieName,this.value)}.bind(this[this.cookieFields[i]]))}this.menu=new Menu("menu",{load:{"roof-area":function(){Element.removeClassName("polygons","shrink");window.setTimeout(this.map.map.checkResize.bind(this.map.map),100)}.bind(this),"enter-utility-bills":function(){Element.addClassName("polygons","shrink")}.bind(this),"get-a-quote":function(){Element.addClassName("polygons","shrink")}.bind(this),"financial-analysis":function(){Element.addClassName("polygons","shrink");this.roi.refresh();if(Cookie.get("_roofray_conv")){$("bill-analysis").setStyle({display:"none"});$("effect-on-bills").setStyle({display:"none"});$("roi-report").setStyle({display:"none"})}}.bind(this)}});this.subMenu=new Menu("financial-analysis-nav",{steps:this.fs,parent:"financial-analysis",load:{performance:function(){$("financial-analysis-caption").innerHTML="Performance";Element.addClassName("polygons","shrink");this.performanceCalc.refresh()}.bind(this),"select-utility-company":function(){$("financial-analysis-caption").innerHTML="Confirm Utility Rates";Element.addClassName("polygons","shrink")}.bind(this),"quick-calculation":function(){$("financial-analysis-caption").innerHTML="Quick Calculation";Element.addClassName("polygons","shrink")},"bill-analysis":function(){$("financial-analysis-caption").innerHTML="Bill Breakdown";Element.addClassName("polygons","shrink");this.analysis.refresh()}.bind(this),"effect-on-bills":function(){$("financial-analysis-caption").innerHTML="Effect of Solar on Bills";Element.addClassName("polygons","shrink");this.savings.refresh()}.bind(this),"roi-report":function(){$("financial-analysis-caption").innerHTML="Costs Summary & ROI";Element.addClassName("polygons","shrink");if(!this.report){this.report=new RoofRayReport({avoided_electricity_cost:$("avoided-electricity-cost"),output_depreciation:$("output-depreciation"),energy_inflation_rate:$("energy-inflation-rate"),container:$("roi-report-results"),system_size_slider:$("system-size-slider"),system_size_input:$("system-size-input"),system_price:$("system-price"),net_expense:$("net-expense"),state_rebate:$("state-rebate"),net_after_rebate:$("net-after-rebate"),cost_of_permit:$("cost-of-permit"),net_system_costs:$("net-system-costs"),federal_tax_credit:$("federal-tax-credit"),system_size_header:$("system-size-header"),system_cost_header:$("system-cost-header"),breakeven_point_header:$("breakeven-point-header"),savings:this.savings,map:this.map,calc:this});Event.observe("reset-roi-report","click",this.report.reset.bind(this.report))}else{this.report.updateSystemSize()}}.bind(this)}});$("next-step").observe("click",handleNavigation);$("xxxnext-step").observe("click",handleNavigation);$("prev-step").observe("click",handleNavigation);var centerPointJSON=Cookie.get("center");var calculation=eval("("+Cookie.get("calculation")+")");var mapzoomlevel=19;if(calculation){if(calculation.zoomlevel){mapzoomlevel=calculation.zoomlevel}}this.map=new RoofRayMap("map",(centerPointJSON?eval("("+centerPointJSON+")"):null),{tilt:24,solarToDC:solarToDC,name_field:$("name-field"),tiltField:this.tilt,polygonList:$("polygon-list"),zoomLevel:mapzoomlevel});this.map.dom.observe("r:newpolygon",this.newPolygon.bind(this));this.map.dom.observe("r:dragend",function(e){var cp=this.map.map.getCenter();var coord="["+cp.lat()+","+cp.lng()+"]";Cookie.set("center",coord);if(e.memo>100||!e.memo){this.updateLocalData()}}.bind(this));try{initMap(this.map)}catch(e){if(!(typeof console=="undefined")){console.log(e)}}this.tiltSlider=new Slider($("tilt_slider"),0,60,300,this.tilt,(calculation?calculation.tilt:this.map.tilt),{onChange:function(tilt){this.map.tilt=tilt;this.map.dom.fire("r:change")}.bind(this)});this.performanceCalc=new RoofRayPerformance({container:$("performance-output"),tilt:this.tilt,url:"/calculator/run",map:this.map});$("performance-refresh").observe("click",this.performanceCalc.refresh.bind(this.performanceCalc));$("remove-point").observe("click",this.map.removePoint.bind(this.map));$("expander").observe("click",function(){Effect.toggle("polygon-list","appear",{duration:0.1})});$("orientation-howto").observe("click",this.map.placeOrientationMarker.bind(this.map));this.zipCode.observe("keypress",numericFilter);this.averageBill.observe("keypress",moneyFilter);this.roi=new RoofRayROI({container:$("roi-output"),tilt:this.tilt,url:"/calculator/analyze",map:this.map,calc:this});if(calculation){this.map.loadCalculation(calculation);if(calculation.tilt){this.tiltSlider.set(calculation.tilt)}}this.map.dom.observe("r:change",function(e){Cookie.set("calculation",this.map.json());var tilt=this.tilt.getValue();for(var i=0;i<this.map.polygons.length;i++){var p=this.map.polygons[i];if(!p){break}var watts=p.watts(tilt);var squareFeet=p.area(tilt)/0.0929;var wpsf=watts/squareFeet;p.areaNode.innerHTML=parseInt(squareFeet)+" Sq. Ft";var orientation=p.getOrientation();if(orientation){p.orientation.innerHTML=round(orientation)+"&deg; "+p.compassLetter(orientation)}else{p.orientation.innerHTML="?"}var oPot=(180-Math.abs(orientation-180))/180;if(isNaN(oPot)){oPot=1}var centerPoint=this.map.polygons[i].centerPoint();if(centerPoint){var tPot=(90-Math.abs(parseFloat(tilt)-centerPoint.lat()))/90;var potential=((oPot+tPot)/2);p.wattsNode.innerHTML=round(watts*potential)+" Watts DC";p.potentialNode.innerHTML=parseInt(potential*100)+"%";p.powerPerNode.innerHTML=(isNaN(wpsf)?0:round(wpsf*potential))+" Watts DC"}}if(this.map.activePolygon){}else{}}.bind(this));this.analysis=new RoofRayAnalysis({container:$("bill-analysis-results"),url:"/calculator/bill_analysis",summer_months:summerMonths,winter_months:winterMonths,usage_container:$("usage-data"),map:this.map,calc:this});this.savings=new RoofRaySavings({container:$("effect-on-bills-results"),url:"/calculator/savings",power_company_id:$("power-company"),average_monthly_cost:$("average-electric-bill"),zip_code:$("zip-code"),current_power_rate:$("current-power-rate"),solar_power_rate:$("solar-power-rate"),derateFactor:dcToAcFactor,tilt:$("tilt"),summer_months:summerMonths,winter_months:winterMonths,analysis:this.analysis,map:this.map,calc:this});$("effect-on-bills-refresh").observe("click",this.savings.refresh.bind(this.savings));this.map.dom.fire("r:change");this.updateLocalData();for(var i=1;i<=12;i++){$("usage_"+i+"_kwh").observe("change",this.expireReports.bind(this));$("usage_"+i+"_cost").observe("change",this.expireReports.bind(this))}$("new-calculation-link").observe("click",function(){Cookie.erase("calculation");Cookie.erase("powerCompanyField");Cookie.erase("currentPowerRateField");Cookie.erase("solarPowerRateField");window.location.reload(true)});$("save-with-name-link").observe("click",function(){if($("save-with-name-link").hasClassName("save-in-progress")){alert("save is in progress...");return }var name=$("name-field").value;if(!name||name==""){name=prompt("What do you want to call this model?")}if(!name||name.strip().length==0){alert("Please enter a name for the model. (Example: Ca Beach House)");return }if(name.match(/[^0-9a-zA-Z-,#().\s+]/)){alert("Please only use letters, numbers and these special characters -,#(). for your Model Name.");return }this.totalOutput.value=this.savings.getSystemSizeAC();var updateParams={name:name,json:this.map.json(),authenticity_token:authenticityToken,zoomlevel:this.map.map.getZoom(),total_output:this.savings.getSystemSizeAC()};this.analysis.addUsageData(updateParams);if(this.map.id){updateParams.id=this.map.id}new Ajax.Request("/calculator/save",{method:"post",parameters:updateParams,onLoading:function(){$("save-with-name-link").addClassName("save-in-progress")},onComplete:function(){$("save-with-name-link").removeClassName("save-in-progress")},onFailure:function(){alert("Solar Array model was not saved. You must create an account before models can be saved.")},onSuccess:function(t){var div=Builder.node("div",{className:"notice"},"RoofRay Model Saved!");$("main").insert({top:div});window.setTimeout(function(){Effect.Fade(div,{duration:3})},1000);if(!calc.map.id){var id=parseInt(t.responseText);if(id){calc.map.id=id;Cookie.set("calculation",calc.map.json());new Ajax.Updater("saved-calculations","/calculator/list",{parameters:{authenticity_token:authenticityToken},requestHeaders:{accept:"text/html"}})}else{alert("No data was returned from the server. The save operation may not have completed successfully.")}}}})}.bind(this));this.powerCompanyField.observe("change",function(e){this.expireReports();this.map.updatePowerRates(e.target)}.bind(this));$("current-power-rate").observe("change",this.expireReports.bind(this));$("solar-power-rate").observe("change",this.expireReports.bind(this));$("zip-code").observe("change",this.expireReports.bind(this));this.customRateUsed.observe("change",this.updateCustomRate.bind(this));this.customRateCost.observe("change",this.updateCustomRate.bind(this));this.updateCustomRate();var toggleStatus=Cookie.get("usage-toggle");if(!toggleStatus){toggleStatus="use-average-bill"}var toggleStatusEl=$(toggleStatus);toggleStatusEl.toggleOn=true;toggleStatusEl.src="/images/usethis-down.gif";Event.observe("use-average-bill","click",function(e){var otherButton=$("use-detailed-bills");otherButton.src="/images/usethis-up.gif";e.target.src="/images/usethis-down.gif";otherButton.toggleOn=false;Cookie.set("usage-toggle","use-average-bill");e.target.toggleOn=true;this.expireReports()}.bind(this));Event.observe("use-detailed-bills","click",function(e){var otherButton=$("use-average-bill");otherButton.src="/images/usethis-up.gif";e.target.src="/images/usethis-down.gif";otherButton.toggleOn=false;Cookie.set("usage-toggle","use-detailed-bills");e.target.toggleOn=true;this.expireReports()}.bind(this));Event.observe("quick-calculation-submit","click",this.roi.refresh.bind(this.roi,true))},expireReports:function(){this.savings.expire();this.analysis.expire()},updatePowerRates:function(E){var F=E.options[E.selectedIndex];var A=F.power_rates;var C={"current-power-rate":"defaultStandardRate","solar-power-rate":"defaultSolarRate"};for(var D in C){var G=$(D);G.innerHTML="";if(A){for(var H=0;H<A.length;H++){var B=Builder.node("option",{value:A[H].name},A[H].name);G.appendChild(B)}G.setValue(F[C[D]]);if(G.cookieName){Cookie.set(G.cookieName,G.value)}}}},updateCustomRate:function(B){var A=this.calcCustomRate();if(A){this.customRateString.innerHTML="$"+A.toFixed(3)+" per kWh"}},calcCustomRate:function(){var B=parseFloat(this.customRateCost.getValue());var A=parseFloat(this.customRateUsed.getValue());if(B&&A){return B/A}},customRate:function(){if(this.averageRateSelector.checked){return this.averageStateRate.getValue()}else{if(this.customRateSelector.checked){return this.calcCustomRate()}}},mergeRateParams:function(A){A.zip_code=this.zipCode.getValue();A.average_electric_bill=this.averageBill.getValue();if(this.selectRateBlock.visible()){A.current_power_rate=this.currentPowerRateField.getValue();A.solar_power_rate=this.solarPowerRateField.getValue();A.power_company_id=this.powerCompanyField.getValue()}else{if(Cookie.get("selectRate")=="true"){A.current_power_rate=Cookie.get("currentPowerRateField");A.solar_power_rate=Cookie.get("solarPowerRateField");A.power_company_id=Cookie.get("powerCompanyField")}else{A.custom_rate=this.customRate()}}},updateLocalData:function(url){var pci=this.powerCompanyField;var qpci=this.quotePowerCompanyField;qpci.innerHTML="";pci.innerHTML="";var center=this.map.map.getCenter();new Ajax.Request(this.findLocalDataURL,{parameters:{latitude:center.lat(),longitude:center.lng(),authenticity_token:authenticityToken},onSuccess:function(t){var data=eval("("+t.responseText+")");this.zipCode.setValue(data.digits);this.noRebate=!data.rebate;removeChildrenFromNode(pci);if(data.power_companies){for(var i=0;i<data.power_companies.length;i++){var pc=data.power_companies[i];if(pc.power_rates.length){var pco=Builder.node("option",{value:pc.id},pc.name);pco.power_rates=pc.power_rates;pco.defaultSolarRate=pc.default_solar_rate;pco.defaultStandardRate=pc.default_standard_rate;pci.appendChild(pco)}var qpco=Builder.node("option",{value:pc.id},pc.name);qpci.appendChild(qpco)}}var other=Builder.node("option",{value:""},"Other/None");qpci.appendChild(other);if(pci.options.length>0){Cookie.set("selectRate","true");this.rateInfoString.innerHTML="Utility Rates Found for this Location - Click Next to Continue";this.averageRateBlock.hide();this.enterRateBlock.hide();this.selectRateBlock.show();pci.setValue(pci.options[0].value);qpci.setValue(qpci.options[0].value);if(pci.cookieName){Cookie.set(pci.cookieName,pci.value)}this.updatePowerRates(pci)}else{if(data.average_rate){this.averageRateString.innerHTML=data.average_rate.state+" @ $"+data.average_rate.average.rate.toFixed(3)+" per kWh";this.averageStateRate.value=data.average_rate.average.rate;this.averageRateSelector.checked=true;this.averageRateBlock.show()}else{this.customRateSelector.checked=true}Cookie.set("selectRate","false");this.rateInfoString.innerHTML="We don't have the Utility Rate for this location yet. Please select from the following options.";this.selectRateBlock.hide();this.enterRateBlock.show()}}.bind(this)})},newPolygon:function(H){var B=H.memo.polygon;var D=Builder.node("td");var E=Builder.node("td");var C=Builder.node("td");var F=Builder.node("td");var A=Builder.node("td");var G=Builder.node("input",{type:"checkbox"});var I=Builder.node("img",{src:"/images/trash-icon.png"});B.dom=Builder.node("tr",[Builder.node("td",[Builder.node("div",{className:"poly-color",style:"background-color:"+B.polyColor})]),D,E,C,F,A,Builder.node("td",[I]),Builder.node("td",[G])]);if(B.rrmap.polygonList.visible()){B.dom.style.display="none";B.rrmap.polygonList.appendChild(B.dom);Effect.Appear(B.dom)}else{B.rrmap.polygonList.appendChild(B.dom);Effect.Appear(B.rrmap.polygonList)}G.setAttribute("checked",true);Event.observe(G,"click",function(J){J.cancelBubble=true;this.rrmap.dom.fire("r:change")}.bind(B));Event.observe(I,"click",function(J){this.dom.fire("r:destroy");J.cancelBubble=true}.bind(B));Event.observe(B.dom,"mouseover",function(J){this.addClassName("on")});Event.observe(B.dom,"mouseout",function(J){this.removeClassName("on")});Event.observe(B.dom,"click",function(J){this.rrmap.selectActivePolygon(this)}.bind(B));B.potentialNode=D;B.powerPerNode=E;B.areaNode=C;B.wattsNode=A;B.calculateNode=G;B.orientation=F;B.dom.observe("r:destroy",function(J){this.rrmap.polygonList.removeChild(this.dom);this.rrmap.clearPolygon(this)}.bind(B))}};function submitLead(){var G=$("quote-form");var A=$("quote-form-container");var H=$("quote-status");var C=Builder.node("div",{className:"loading body"},"Submitting...");$("lead-calculation-id").setValue(calc.map.id);$("lead-data-dump").setValue(calc.map.json());var K=$("quote-power-company");var L=[];for(var D=0;D<K.options.length;D++){L.push([K.options[D].text,K.options[D].value])}var I=K.options[K.selectedIndex].value;var B=function(M){if(M){H.appendChild(C)}else{H.removeChild(C)}};var E=Form.serialize(G);var F;var J=$("total-output").value;if(Cookie){F=Cookie.get("averageBill")}J=$("total-output").value;if(J){E=E+"&total_output="+J}if(F){E=E+"&averageBill="+F}new Ajax.Request("/leads",{asynchronous:true,evalScripts:true,parameters:E,onComplete:function(){B(false)},onFailure:function(M){A.innerHTML=M.responseText;new Effect.Appear(A,{duration:0.1,queue:"end"});K=$("quote-power-company");L.each(function(N){K.appendChild(Builder.node("option",{value:N[1]},N[0]))});K.setValue(I)},onSuccess:function(M){$("get-a-quote-submit").remove();var N=Builder.node("div",{className:"body info"},"");N.innerHTML=M.responseText;H.appendChild(N)},onLoading:function(){B(true);new Effect.Fade(A,{duration:0.2})}})}Event.observe(window,"load",function(){calc=new Calculator({findLocalDataURL:"/calculator/find_local_data",tilt:$("tilt"),customRateString:$("custom-rate"),customRateUsed:$("custom-rate-kwh-used"),customRateCost:$("custom-rate-cost"),averageRateSelector:$("use-state-average"),averageStateRate:$("average-state-rate"),customRateSelector:$("use-custom-rate"),zipCode:$("zip-code"),averageBill:$("average-electric-bill"),selectRateBlock:$("select-rate-info"),powerCompanyField:$("power-company"),currentPowerRateField:$("current-power-rate"),solarPowerRateField:$("solar-power-rate"),quotePowerCompanyField:$("quote-power-company"),averageRateBlock:$("average-state-rate-info"),averageRateString:$("state-average-rate"),rateInfoString:$("rate-info"),enterRateBlock:$("enter-rate-info"),totalOutput:$("total-output")})});