var $j = jQuery.noConflict();
$j(function() {
    $j('#left .container').before('<span class="corner tr"></span>');
    $j('#left .container').after('<span class="corner br"></span>');
    $j('#left .container ul:first').before('<span class="corner t"></span>');
    $j('#left .container ul:first').after('<span class="corner b"></span>');
    //This turns the entire div into a clickable link. If used incorrectly, (as in a div surrounding a listview) it can cause the entire list view to go to one link. See ticket #839.
    //Leaving this in in-case we want to turn it back on in a more narrow implementation.
    //	$j(".entry").fitted(); 
	$j(".equalheights").equalheights();

    if ($j('#our-story').length) {
        $j('.our-story-container').css('display', 'block');
        $j("#our-story").slidingPanels({
            slideDuration: 250
        });
        $j('#our-story .slide.one').trigger('click');
        var html = "<img src=\"/images/corners.png\" width=\"10\" height=\"312\" class=\"rounded\" alt=\"Background\" />";
        $j("#our-story").after(html);
    }

    $j('#footer ul li:last').css({ 'background': 'none' });

    if ($j('#incentive-tabs').length) {
        $j('#incentive-tabs').simpleTabs();
    }

    if ($j('.expand').length) {
        $j('.expand .button,.expand h3').click(function() {
            var obj = $j(this).parent().parent();
            if ($j(obj).hasClass('expanded')) {
                $j(obj).removeClass('expanded');
                $j('.content', obj).slideUp('fast').fadeOut('slow');
            } else {
                $j(obj).addClass('expanded');
                $j('.content', obj).slideDown('fast').fadeIn('fast');
            }
        });
    }


    if ($j('.update-project').length) {
        $j('.update-project:not(.open) .content').css('display', 'none');
        $j('.update-project:not(.open) .button,.update-project h3').click(function() {
            if ($j('.update-project').hasClass('expanded')) {
                $j('.update-project').removeClass('expanded');
                $j('.update-project .content').slideUp('fast').fadeOut('slow');
            } else {
                $j('.update-project').parent().addClass('open');
                $j('.update-project').addClass('expanded');
                $j('.update-project .content').slideDown('fast').fadeIn('fast');
            }
        });
    }


    if ($j('#changeVideo').length) {
        $j('#changeVideo').changeVideo();
    }

    if ($j('#solar-gallery').length) {
        $j('#solar-gallery').loopedSlider({
            descriptionFade: true
        });
    }

    if ($j('#equalize').length) {
        $j('#equalize').equalHeights();
    }

    $j('#sa').click(function() {
        SearchSite();
        return false;
    });
    $j('#q').keypress(function(e) {
        if (e.which == 13 || e.which == 10) {
            SearchSite();
            return false;
        }
    });

    if ($j('.solar-calculator').length) {
        $j('.solar-calculator #continue').click(function() {
            var versionName = $j('#versionName').val();
            var zipCode = $j('#zipCode').val();
            var url;
            if (versionName == "residential") {
                url = '/shared-resources/solar-calculator/search/?siteName=energytrust2&versionName=residential&zipCode=' + zipCode + ''
            };
            if (versionName == "commercial") {
                url = '/shared-resources/solar-calculator/search/?siteName=energytrust2&versionName=commercial&versionOption=1&zipCode=' + zipCode + ''
            };
            if (versionName == "public") {
                url = '/shared-resources/solar-calculator/search/?siteName=energytrust2&versionName=commercial&versionOption=2&zipCode=' + zipCode + ''
            };
            window.open(url, "cal", "location=1, status=1, scrollbars=1, width=1200A, height=768");
            return false;
        });
        $j('#zipCode').keypress(function(e) {
            if (e.which == 13 || e.which == 10) {
                var versionName = $j('#versionName').val();
                var zipCode = $j('#zipCode').val();
                if (versionName == "residential") {
                    url = '/shared-resources/solar-calculator/search/?siteName=energytrust2&versionName=residential&zipCode=' + zipCode + ''
                };
                if (versionName == "commercial") {
                    url = '/shared-resources/solar-calculator/search/?siteName=energytrust2&versionName=commercial&versionOption=1&zipCode=' + zipCode + ''
                };
                if (versionName == "public") {
                    url = '/shared-resources/solar-calculator/search/?siteName=energytrust2&versionName=commercial&versionOption=2&zipCode=' + zipCode + ''
                };
                window.open(url, "cal", "location=1, status=1, scrollbars=1, width=1200, height=768");
                return false;
            }
        });
    }

    if ($j(".solar_calc").length) {
        var html = "<div id=\"incentive_estimator\" style=\"display:none\">" +
			"<div id=\"header\">" +
				"<img src=\"/images/incentive_estimator.png\" width=\"442\" height=\"31\" alt=\"Incentive Estimator\" />" +
			"</div>" +
			"<div id=\"calculator\">" +
				"<div class=\"row clearfix\">" +
					"<div class=\"left_col\">" +
						"<h3>This for a</h3>" +
					"</div>" +
					"<div class=\"right_col\">" +
					"<div class=\"clearfix\">" +
							"<input type=\"radio\" name=\"audience\" value=\"business\" id=\"business\" />" +
							"<label for=\"business\">Business / Third-party</label>" +
					"</div>" +
					"<div class=\"clearfix\">" +
							"<input type=\"radio\" name=\"audience\" value=\"public\" id=\"public\" />" +
							"<label for=\"public\">Public or Nonprofit</label>" +
					"</div>" +
					"</div>" +
				"</div>" +
				"<div class=\"row clearfix\">" +
					"<div class=\"left_col\">" +
						"<h3>Select utility</h3>" +
					"</div>" +
					"<div class=\"right_col\">" +
						"<div class=\"clearfix\">" +
							"<input type=\"radio\" name=\"utility\" value=\"pge\" id=\"pge\" />" +
							"<label for=\"pge\">PGE</label>" +
						"</div>" +
						"<div class=\"clearfix\">" +
							"<input type=\"radio\" name=\"utility\" value=\"pac\" id=\"pac\" />" +
							"<label for=\"pac\">Pacific Power</label>" +
						"</div>" +
					"</div>" +
				"</div>" +
				"<div class=\"row clearfix\">" +
					"<div class=\"left_col\">" +
						"<h3><label for=\"enter_system_size_in_kilowatts\">System Size</label></h3>" +
					"</div>" +
					"<div class=\"right_col\">" +
						"<input type=\"text\" name=\"system_size\" value=\"\" id=\"system_size\" /> <small>(kW)</small>" +
					"</div>" +
				"</div>" +
				"<input type=\"submit\" name=\"submit\" value=\"Calculate Incentive\" id=\"submit\" />" +
			"</div>" +
			"<div id=\"incentive_amount\" class=\"clearfix\">" +
				"<div class=\"left_col\">" +
					"<h3>Incentive Amount</h3>" +
				"</div>" +
				"<div class=\"center_col\">" +
					"$0.00" +
				"</div>" +
			"</div>" +
			"<div class=\"disclaimer\">" +
				"<p>*The maximum incentive for a single site is $500,000. Multiple site installations are eligible for a maximum incentive of $600,000.</p>" +
			"</div>" +
		"</div>";

        $j("body").append(html);

        $j(".solar_calc").click(function(e) {
            e.preventDefault();
            $j('#incentive_estimator').modal({
                minHeight: 355,
                overlayClose: true,
                onShow: function() {
                    $j("#system_size").val("");
                    $j("input[name=utility],input[name=audience]").removeAttr('checked');
                    $j("#submit").click(function() {
                        var kilowatts = $j("#system_size").val();
                        var utility = $j("input[name=utility]:checked").val();
                        var audience = $j("input[name=audience]:checked").val();
                        if (utility && audience) {
                            calculate(kilowatts, utility, audience);
                        }
                    });
                    $j("#system_size").keyup(function() {
                        var kilowatts = $j("#system_size").val();
                        var utility = $j("input[name=utility]:checked").val();
                        var audience = $j("input[name=audience]:checked").val();
                        if (utility && audience) {
                            calculate(kilowatts, utility, audience);
                        }
                    });
                }
            });
        });
    };

    if ($j(".update-project").length) {
        var html = "<div id=\"projecttype_desc\" style=\"display:none\">" +
			"<div id=\"desc\">" +
			    "<h3>Project Type Definitions</h3>" +
			    "<p><b>Equipment Upgrades</b><br />Projects that involve non-structural improvements to an existing space such as the upgrade of lighting, HVAC, kitchen, and laundry equipment.</p>" +
			    "<p><b>Major Renovation or Addition</b><br />Major construction projects that include the replacement of 50% of both lighting and HVAC equipment or projects that increase a building's total square footage and include efficiency upgrades such as lighting, HVAC, kitchen, and laundry equipment.</p>" +
			    "<p><b>New Construction</b><br />The construction of a new, high-efficiency and sustainably designed commercial building or other facility.</p>" +
			    "<p><b>Remodel</b><br />Projects that involve non-structural improvements to an existing space such as the upgrade of lighting, HVAC, kitchen, and laundry equipment.</p>" +
			    "<p><b>Tenant Improvements</b><br />An interior build-out for a new tenant of a commercial space that includes efficiency upgrades such as lighting, HVAC, kitchen and laundry equipment.</p>" +
			"</div>" +
		"</div>";

        $j("body").append(html);
    };

    if ($j(".rating_legend").length) {
        var html = "<div id=\"rating_legend_desc\" style=\"display:none;\">" +
			"<div id=\"desc\">" +
			    "<h3>Trade Ally Rating System</h3>" +
			    "<p>Existing Homes contractors are rated to simplify the selection process. Ratings&#8212;indicated by one, two or three stars&#8212;are based on Energy Trust's experience with each contractor, and do not reflect their complete quality of work. Our rating criteria include the number of completed Energy Trust projects, observed quality of work and commitment to customer service. Only Existing Homes contractors have been rated at this time. Energy Trust will institute a rating system for other contractors in 2011.</p>" +
			    "<h4>Legend</h4>" +
			    "<p><img src=\"/images/rating-one-noq.gif\" align=\"left\" alt=\"One Star\" width=\"59\" height=\"20\" title=\"Ratings are based on contractor activity levels with Energy Trust, observed commitment to quality work and customer feedback. This trade ally has met all of the minimum criteria.\" style=\"margin-right:10px;margin-bottom:10px;\" />Good commitment to quality service with a small number of Energy Trust projects completed.</p>" +
                "<p><img src=\"/images/rating-two-noq.gif\" align=\"left\" alt=\"Two Stars\" width=\"59\" height=\"20\" title=\"Ratings are based on contractor activity levels with Energy Trust, observed commitment to quality work and customer feedback. This trade ally has met enhanced performance criteria.\" style=\"margin-right:10px;margin-bottom:10px;\" />Enhanced commitment to quality service with many Energy Trust projects completed.</p>" +
                "<p><img src=\"/images/rating-three-noq.gif\" align=\"left\" alt=\"Three Stars\" width=\"59\" height=\"20\" title=\"Ratings are based on contractor activity levels with Energy Trust, observed commitment to quality work and customer feedback. This trade ally has met top performance criteria.\" style=\"margin-right:10px;margin-bottom:10px;\" />Superior commitment to quality service with a large number of Energy Trust projects completed.</p>" +
			"</div>" +
		"</div>";

        $j("body").append(html);
    };

});

function smoothScroll() {
	$j('html,body').animate({ scrollTop: 150 }, 500);
}

function SearchSite() {
    window.location.replace('/search-results.aspx?cx=013611428640276922521%3Ayddain6z308&cof=FORID%3A10&ie=UTF-8&q=' + document.getElementById('q').value + '+site:energytrust.org -site:archive.energytrust.org&sa=Search');
}

/*
CSS Browser Selector v0.3.3 (Sep 09, 2009)
Rafael Lima (http://rafael.adm.br)
http://rafael.adm.br/css_browser_selector
License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3')?g+' ff3':is('gecko/')?g:/opera(\s|\/)(\d+)/.test(ua)?'opera opera'+RegExp.$2:is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);

 /*
 	Google Analytics tracking of downloads
 */
function getLinkName() {
	var a = document.getElementsByTagName("a");
	for (var i=0; i < a.length; i++) {
	    var href = a[i].getAttribute("href");
	    if (href != null) {
	        if (href.match(/\.(doc|pdf|xls|ppt|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)$/)) {
	            addtrackerlistener(a[i]);
	        }
	    }
	};
}
function addtrackerlistener(obj) {
	var href = obj.getAttribute("href");
	if (obj.addEventListener) {
		obj.addEventListener("click",function () {
			pageTracker._trackPageview(href);
		},false)
	} else if (obj.attachEvent) {
		obj.attachEvent("on" + "click",function () {
			pageTracker._trackPageview(href);
		},false)
	}
}
window.onload=function(){
 getLinkName();
}
// Solar Estimate Calculator
function calculate(kilowatts,utility,audience) {
	var units = "";
	var capacity = kilowatts;
	var efficiency = capacity;

	if(utility=="pac") units = 1;
	if(utility=="pge") units = 1.25;
	if(audience=="public") units = units+.25;
	if (efficiency > 200){ efficiency = 200 }
	if (efficiency > 30) {
		efficiency = units - (.5*(efficiency - 30)/170);
	} else{
		efficiency = units;
	}
	if (efficiency < 0){ efficiency = 0 }

	var rounded = Math.round(efficiency*10000)/10000;
	var output = capacity * rounded * 1000;

	if (output > 100000 && utility=="pac" && audience=="business"){
	  output = 100000;
	}
	if (output > 150000 && utility=="pac" && audience=="public"){
	  output = 150000;
	}
	if (output > 600000 && utility=="pge"){
	  output = 600000;
	}
	if (output > 200000 && utility=="pge" && audience=="public"){
	  output = 200000;
	}
	formatCurrency(output);
}
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,"");
	num = Math.round(num);
	if(isNaN(num))
		num = "0";
		sign = (num == (num = Math.abs(num)));
		num = Math.floor(num*100+0.50000000001);
		cents = num%100;
		num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+","+
		num.substring(num.length-(4*i+3));
		cents = "00"
		append(((sign)?"":"-") + "$" + num + "." + cents);
}
function append(obj) {
	$j("#incentive_amount .center_col").html("").append(obj);
	$j("#incentive_amount").css({backgroundColor:"#FFFCDC",border:"1px solid #FCF3B6",color:"#655C2E"});
}



