var $j = jQuery.noConflict();
$j(function () {


    /*
    2010 Survey
    */
    /*
    if (!$j.jCookie('seenSurvey') || getQueryString('option') === 'survey') {
    $j('<div id="survey" style="display:none;"><iframe height="350" width="350" allowTransparency="true" frameborder="0" scrolling="no" style="width:350px;border:none"  src="http://energytrustoforegon.wufoo.com/embed/z7x4a3/"><a href="http://energytrustoforegon.wufoo.com/forms/z7x4a3/" title="Energy Trust of Oregon" rel="nofollow">Fill out my Wufoo form!</a></iframe></div>').appendTo('body');
	
    $j('#survey iframe').load(function() {
    $j('#survey iframe').css('display', 'block');
    $j('<a href="#survey" id="survey_link" style="display:none">Take Survey</a>').appendTo('body');

    $j('#survey_link').facebox({
    onLoad: function() {
    $j('#facebox a.close').css({'display':'none'});
    $j('<p style="text-align:center;width:100%;"><a href="#" id="close_survey">Close survey</a></p>').appendTo('#facebox .body');
    $j('#close_survey').click(function(){
    $j('#facebox a.close').click();
    return false;
    });
    }
    });
			
    $j('#survey_link').click();
    jQuery.jCookie('seenSurvey', 'true', 3650, { path: "/", domain: currentLocaiton });
    });
    }
    */


    /*
    if (!$j.jCookie('takenSurvey')) {
    if (window.console && window.console.log)
    console.log('survey taken');
    }*/


    /*
    end survey
    */
    $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>');
    $j(".media_center_entry").fitted();
    $j(".equalHeights").equalHeights(true);
    $j("#offers").equalHeights(true);
    $j(".facebox").facebox();

    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;
        }
    });

    $j(".numbermask").numbermask();

    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(".reviewTips").length) {
        //alert("we have the button...building the popup");

        var html = "<div id=\"taSearch_Tips\" style=\"display:none\">" +
			"<div id=\"header\">" +
				"TIPS FOR SELECTING A CONTACTOR" +
			"</div>" +
			"<div id=\"tipsBox\">" +
				"<p>Choosing a contractor is a key step in making your energy efficiency or renewable energy project a success, whether you are renovating an historic home, building a new office space, or installing a wind system. Hiring a contractor unfamiliar with the requirements of your job or working with an unlicensed installer can lead to a number of problems. Fortunately, there are many resources to help you choose the right contractor for the job.</p>" +
                "<p>Energy Trust recommends working with a trade ally contractor from our list. Trade allies are on the front lines of offering energy-efficiency and renewable energy services and products to help you use energy wisely. When you refer to this network of licensed and insured independent contractors, you are choosing from a group that is up-to-date on the latest Energy Trust standards, quality control requirements and incentives. They can also help you complete your cash incentive applications. Trade allies receive additional training and support that Energy Trust does not provide to nonaffiliated contractors.</p>" +
                "<p><b>Considerations when choosing a contractor:</b></p>" +
                "<ul>" +
                    "<li>Be sure your contractor has the correct licenses. At a minimum, a contractor should hold an Oregon Construction Contractors Board (CCB) license, or for Washington customers, a Washington contractor\'s license. You can verify Oregon CCB information <a href=\"https://ccbed.ccb.state.or.us/ccb_frames/consumer_info/ccb_index.htm\" target=\"_blank\">here</a>, and Washington license information <a href=\"https://fortress.wa.gov/lni/bbip/Search.aspx\" target=\"_blank\">here</a>.</li>" +
                    "<li>Check online resources to see how the contractor is rated. <a href=\"http://www.angieslist.com/\" target=\"_blank\">Angie\'s List</a>, the <a href=\"http://www.ccb.state.or.us/\" target=\"_blank\">Oregon CCB</a>, the <a href=\"http://www.lni.wa.gov/\" target=\"_blank\">Washington State Department of Labor and Industries</a>, the <a href=\"http://alaskaoregonwesternwashington.bbb.org/\" target=\"_blank\">Better Business Bureau of Alaska, Oregon, and Western Washington</a>, and any references provided by the contractor can all be good resources.</li>" +
                    "<li>Review your bid and understand the work to be performed.  Trust, quality, professionalism and a commitment to stand behind the work can be as important as the bid\'s total cost. Consult resources created by the CCB , such as <a href=\"http://ccbed.ccb.state.or.us/WebPDF/CCB/Publications/16-ways.pdf\" target=\"_blank\">\"16 ways to avoid remodeling, repair, and construction problems\"</a>.</li>" +
                    "<li>Ask friends and family for recommendations, and if you don\'t know where to start, Energy Trust can help. We can refer you to highly qualified trade ally contractors from our list. Call 1.866.368.7878 or search our website for local trade allies matching your needs.</li>" +
                "</ul>" +
			"</div>" +
		"</div>";

        $j("body").append(html);

        $j(".reviewTips").click(function (e) {
            e.preventDefault();
            $j('#taSearch_Tips').modal({
                minHeight: 510,
                maxHeight: 530,
                minWidth: 805,
                maxWidth: 805,
                overlayClose: true
            });
        });
    }

    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>*For public + non-profit entities, the maximum incentive for a single site is $37,500 for PacificPower customers and $200,000 for PGE customers.</p>" +
                "<p>For PGE business customers, the maximum incentive for a single site is $499,999 and multiple site installations are eligible for a maximum incentive of $600,000. For Pacificorp business customers, the maximum incentive is $30,000.</p>" +
			"</div>" +
		"</div>";

        $j("body").append(html);

        $j(".solar_calc").click(function (e) {
            e.preventDefault();
            $j('#incentive_estimator').modal({
                maxWidth: 442,
                minHeight: 420,
                minWidth: 442,
                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\" style=\"margin-right:10px;margin-bottom:30px;\" />Trade allies with this rating have met performance criteria based on a combination of quality of work, and a minimal number of completed projects with Energy Trust.</p>" +
                "<p><img src=\"/images/rating-two-noq.gif\" align=\"left\" alt=\"Two Stars\" width=\"59\" height=\"20\" style=\"margin-right:10px;margin-bottom:40px;\" />Trade allies with this rating have met performance criteria based on a combination of quality of work, and an average to above average number of completed projects with Energy Trust.</p>" +
                "<p><img src=\"/images/rating-three-noq.gif\" align=\"left\" alt=\"Three Stars\" width=\"59\" height=\"20\" style=\"margin-right:10px;margin-bottom:30px;\" />Trade allies with this rating have met performance criteria based on a combination of quality of work, and an above average number of completed projects with Energy Trust.</p>" +
			"</div>" +
		"</div>";

        $j("body").append(html);

        $j(".rating_legend").click(function (e) {
            e.preventDefault();
            $j('#rating_legend_desc').modal({
                minHeight: 430,
                minWidth: 442,
                maxWidth: 442,
                overlayClose: true
            });
        });
    }

});

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 (audience == "public") {
	    if (output > 37500 && utility == "pac") {
	        output = 37500;
	    }
	    if (output > 200000 && utility == "pge") {
	        output = 200000;
	    }
	}
	if (audience == "business") {
	    if (output > 30000 && utility == "pac") {
	        output = 30000;
	    }
	    if (output > 600000 && utility == "pge") {
	        output = 600000;
	    }
	}
    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"});
}
var currentLocaiton;
function getLocation() {
	var locationIsIp = document.domain.match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g);
	var locationIs = document.domain.match(/\.([A-Za-z]+)\.([A-Za-z]+)$/g);
	if (locationIsIp) currentLocaiton = locationIsIp.toString();
	if (locationIs) currentLocaiton = locationIs.toString();
	return currentLocaiton;
}
currentLocaiton = getLocation();

function getQueryString(obj) { 
	var string = window.location.search.substring(1); 
	var strings = string.split('&'); 
	for (var i=0; i < strings.length; i++) { 
		var set = strings[i].split('='); 
		if (set[0] == obj) { 
			return set[1];
		} 
	} 
}


