/***********************************************************************
*
*  ppa.js
*  Tioga PPA Tool
*  by Tai Farmer/JT Mudge, LitmusBox LLC
*  June 12, 2008
*
*  Javascript using JQuery
*
************************************************************************/

/* Configuration Variables */
var stateList1 = 'CA, NJ, AZ, CO, OR, HI, MA, CT'; // Favorable States
var stateList2 = 'MD, TX, NV, NM, FL, NC, WA, PA, NY'; // States to Watch
var stateList3 = new Array(); // Two letter codes mapped to full state names
	stateList3["AL"]="Alabama"; 
	stateList3["AK"]="Alaska"; 
	stateList3["AZ"]="Arizona"; 
	stateList3["AR"]="Arkansas"; 
	stateList3["CA"]="California"; 
	stateList3["CO"]="Colorado"; 
	stateList3["CT"]="Connecticut"; 
	stateList3["DE"]="Delaware"; 
	stateList3["DC"]="District of Columbia"; 
	stateList3["FL"]="Florida"; 
	stateList3["GA"]="Georgia"; 
	stateList3["HI"]="Hawaii"; 
	stateList3["ID"]="Idaho"; 
	stateList3["IL"]="Illinois"; 
	stateList3["IN"]="Indiana"; 
	stateList3["IA"]="Iowa"; 
	stateList3["KS"]="Kansas"; 
	stateList3["KY"]="Kentucky"; 
	stateList3["LA"]="Louisiana"; 
	stateList3["ME"]="Maine"; 
	stateList3["MD"]="Maryland"; 
	stateList3["MA"]="Massachusetts"; 
	stateList3["MI"]="Michigan"; 
	stateList3["MN"]="Minnesota"; 
	stateList3["MS"]="Mississippi"; 
	stateList3["MO"]="Missouri"; 
	stateList3["MT"]="Montana"; 
	stateList3["NE"]="Nebraska"; 
	stateList3["NV"]="Nevada"; 
	stateList3["NH"]="New Hampshire"; 
	stateList3["NJ"]="New Jersey"; 
	stateList3["NM"]="New Mexico"; 
	stateList3["NY"]="New York"; 
	stateList3["NC"]="North Carolina"; 
	stateList3["ND"]="North Dakota"; 
	stateList3["OH"]="Ohio"; 
	stateList3["OK"]="Oklahoma"; 
	stateList3["OR"]="Oregon"; 
	stateList3["PA"]="Pennsylvania"; 
	stateList3["RI"]="Rhode Island"; 
	stateList3["SC"]="South Carolina"; 
	stateList3["SD"]="South Dakota"; 
	stateList3["TN"]="Tennessee"; 
	stateList3["TX"]="Texas"; 
	stateList3["UT"]="Utah"; 
	stateList3["VT"]="Vermont"; 
	stateList3["VA"]="Virginia"; 
	stateList3["WA"]="Washington"; 
	stateList3["DC"]="Washington D.C."; 
	stateList3["WV"]="West Virginia"; 
	stateList3["WI"]="Wisconsin"; 
	stateList3["WY"]="Wyoming"; 

	stateList3["AB"]="Alberta"; 
	stateList3["BC"]="British Columbia"; 
	stateList3["MB"]="Manitoba"; 
	stateList3["NB"]="New Brunswick"; 
	stateList3["NF"]="New Foundland"; 
	stateList3["NT"]="Northwest Territories"; 
	stateList3["NS"]="Nova Scotia"; 
	stateList3["ON"]="Ontario"; 
	stateList3["PI"]="Prince Edward Island"; 
	stateList3["PQ"]="Quebec"; 
	stateList3["SA"]="Saskatchewan"; 
	stateList3["YT"]="Yukon Territory"; 
	stateList3["OTHER"]="Other";
	
	

var response = Array();

/* Page 2 response data */
response['page2'] = Array(); 
response['page2']['page_response'] = Array(); // Page 2:  page responses (used when 'continue' button clicked) 
response['page2']['page_response']['option1-1'] = '<ul><li>Economics of solar are driven by a combination of state and federal incentives and some states are currently better markets than others due to these local policies.</li><li>{{state}} has policies and programs that make solar electricity a financially competitive alternative to utility electrical power.</li></ul>';
response['page2']['page_response']['option1-2'] = '<ul><li>Economics of solar are driven by a combination of state and federal incentives and some states are currently better markets than others due to these local policies.</li><li>{{state}} has policies and programs that make solar electricity a financially competitive alternative to utility electrical power.</li></ul>';
response['page2']['page_response']['option1-3'] = '<ul><li>Economics of solar are driven by a combination of state and federal incentives and some states are currently better markets than others due to these local policies.</li><li>{{state}} has policies and programs that make solar electricity a financially competitive alternative to utility electrical power.</li></ul>';
response['page2']['page_response']['option1-4'] = '<ul><li>Economics of solar are driven by a combination of state and federal incentives and some states are currently better markets than others due to these local policies.</li><li>{{state}} has policies and programs that make solar electricity a financially competitive alternative to utility electrical power.</li></ul>';

response['page2']['page_response']['option2'] = '<ul><li>Economics of solar are driven by a combination of state and federal incentives and some states are currently better markets than others due to these local policies.</li><li>{{state}} has recently adopted or is considering adopting policies that may make solar a cost effective option for you</li><li>Tioga Energy is monitoring changes that may affect the financial competitiveness of solar electrical power.</li></ul>';


response['page2']['page_response']['option3'] = '<ul><li>Economics of solar are driven by a combination of state and federal incentives and some states are currently better markets than others due to these local policies.</li><li>While we believe that solar power has great value to {{state}}, {{state}}\'s regulatory environment is not favorable for solar electrical power at this time.</li></ul>';

response['page2']['summary_response'] = Array(); // Page 2:  summary responses (used in summary page 5)
response['page2']['summary_response']['option1-1'] = '<ul>'+'<li>A small solar power system can make financial sense for you, but a solar PPA is not a feasible option for small PV systems.</li>'+'</ul>';
response['page2']['summary_response']['option1-2'] = '<ul>'+'<li>{{state}} has strong incentives in place to encourage solar power production.</li>'+'</ul>';
response['page2']['summary_response']['option1-3'] = '<ul>'+'<li>{{state}} has strong incentives in place to encourage solar power production.</li>'+'</ul>';
response['page2']['summary_response']['option1-4'] = '<ul>'+'<li>{{state}} has strong incentives in place to encourage solar power production.</li>'+'</ul>';

response['page2']['summary_response']['option2'] = '<ul>'+'<li>Tioga Energy is monitoring the development of the market in {{state}} until changes make solar electric power financially competitive.</li>'+'</ul>';

response['page2']['summary_response']['option3'] = '<ul>'+'<li>The current market environment in {{state}} is not favorable for solar power purchase agreements.</li>'+'</ul>';


/* Page 3 response data */
response['page3'] = Array(); 
response['page3']['page_response'] = Array(); // Page 3:  page responses (used when 'continue' button clicked)
response['page3']['page_response']['option1-1'] = '<ul><li>Building rooftops provide ideal locations for solar installations. </li>'+
                        '<li>Rooftop solar electrical systems offer optimal sun exposure, transform underused space into productive real estate and make a visible statement of your company\'s commitment to achieving energy independence and reducing its carbon footprint.</li>'+
                        '<li>You have indicated that you have {{size}} square feet available for a solar installation which is enough space for a solar electrical system of {{kW}} kW, depending on rooftop obstructions, shading, and other factors.</li>'+
                        '<li>A system of this size can offset {{offset}} of your annual electricity needs.</li>'+
                        '<li>However, the optimal system size is determined by a number of factors including your utility and tariff structure, energy usage profiles and your organization\'s individual needs and goals.</li></ul>';
response['page3']['page_response']['option1-2'] = '<ul><li>Building rooftops provide ideal locations for solar installations. </li>'+
                        '<li>Rooftop solar electrical systems offer optimal sun exposure, transform underused space into productive real estate and make a visible statement of your company\'s commitment to achieving energy independence and reducing its carbon footprint.</li>'+
                        '<li>You have indicated that you have {{size}} square feet available for a solar installation which is enough space for a solar electrical system of {{kW}} kW, depending on rooftop obstructions, shading, and other factors.</li>'+
                        '<li>A system of this size could offset your entire electrical usage.</li>'+
                        '<li>However, the ideal system size may not be the maximum possible system size, depending on your organization\'s individual needs and goals, electric usage profile, rate structure, and other factors.</li></ul>';
response['page3']['page_response']['option1-3'] = '<ul><li>Building rooftops provide ideal locations for solar installations. </li>'+
                        '<li>Rooftop solar electrical systems offer optimal sun exposure, transform underused space into productive real estate and make a visible statement of your company\'s commitment to achieving energy independence and reducing its carbon footprint.</li>'+
                        '<li>You have indicated that you have {{size}} square feet available for a solar installation which is enough space for a solar electrical system of {{kW}} kW.</li>'+
                        '<li>However, you do not have enough useful roofspace to offset a significant portion of your electical needs.</li></ul>';
response['page3']['page_response']['option1-4'] = '<ul><li>Building rooftops provide ideal locations for solar installations. </li>'+
                        '<li>Rooftop solar electrical systems offer optimal sun exposure, transform underused space into productive real estate and make a visible statement of your company\'s commitment to achieving energy independence and reducing its carbon footprint.</li>'+
                        '<li>You have indicated that you have {{size}} square feet available for a solar installation which is enough space for a solar electrical system of approximately {{kW}} kW, depending on rooftop obstructions, shading, and other factors.</li>'+
                        '<li>A solar electrical system will offset approximately {{value}} of your load.</li>'+
                        '<li>However, the ideal system size may not be the maximum possible system size, depending on your organization\'s individual needs and goals, electric usage profile, rate structure, and other factors.</li></ul>';

response['page3']['page_response']['option2-1'] = '<ul><li>Carports and other elevated structures provide attractive locations for solar electrical installations.</li>'+
                        '<li>A solar installation on a carport roof or elevated structure gets optimal sun exposure, transforms underused space into productive real estate and makes a visible statement of your company\'s commitment to achieving energy independence and reducing its carbon footprint.</li>'+
                        '<li>You have indicated that you have {{size}} square feet available for a solar installation which is enough space for a solar electrical system of {{kW}} kW, depending on shading, and other factors.</li>'+
                        '<li>A system of this size can offset {{offset}} of your annual electricity needs.</li>'+
                        '<li>However, the optimal system size is determined by a number of factors including your utility and tariff structure, energy usage profiles and your organization\'s individual needs and goals.  </li></ul>'; 
response['page3']['page_response']['option2-2'] = '<ul><li>Carports and other elevated structures provide attractive locations for solar electrical installations.</li>'+
                        '<li>A solar installation on a carport roof or elevated structure gets optimal sun exposure, transforms underused space into productive real estate and makes a visible statement of your company\'s commitment to achieving energy independence and reducing its carbon footprint.</li>'+
                        '<li>You have indicated that you have {{size}} square feet available for a solar installation which is enough space for a solar electrical system of {{kW}} kW, depending on obstructions and other factors.</li>'+
                        '<li>A system of this size could offset your entire electrical usage.</li>'+
                        '<li>However, the ideal system size may not be the maximum possible system size, depending on your organization\'s individual needs and goals, electric usage profile, rate structure, and other factors.</li></ul>'; 
response['page3']['page_response']['option2-3'] = '<ul><li>Carports and other elevated structures provide attractive locations for solar electrical installations.</li>'+
                        '<li>A solar installation on a carport roof or elevated structure gets optimal sun exposure, transforms underused space into productive real estate and makes a visible statement of your company\'s commitment to achieving energy independence and reducing its carbon footprint.</li>'+
                        '<li>You have indicated that you have {{size}} square feet available for a solar installation which is enough space for a solar electrical system of {{kW}} kW.</li>'+
                        '<li>However, you do not have enough useful roof space to offset a significant portion of your electical needs.</li></ul>'; 
response['page3']['page_response']['option2-4'] = '<ul><li>Carports and other elevated structures provide attractive locations for solar electrical installations.</li>'+
                        '<li>A solar installation on a carport roof or elevated structure gets optimal sun exposure, transforms underused space into productive real estate and makes a visible statement of your company\'s commitment to achieving energy independence and reducing its carbon footprint.</li>'+
                        '<li>You have indicated that you have {{size}} square feet available for a solar installation which is enough space for a solar electrical system of {{kW}} kW, depending on shading and other factors. A solar electrical system will offset approximately +value+ of your load.</li>'+
                        '<li>However, the ideal system size may not be the maximum possible system size, depending on your organization\'s individual needs and goals, electric usage profile, rate structure, and other factors.</li></ul>'; 

response['page3']['page_response']['option3-1'] = '<ul><li>Ground mounted solar installations are generally the most cost effective means of generating solar electricity and are an excellent choice if land is available.</li>'+
                        '<li>A ground mounted solar installation is usually the most efficient, has the least impact on ongoing building operations, and makes a visible statement of your company\'s commitment to achieving energy independence and reducing its carbon footprint.</li>'+
                        '<li>You have indicated that you have {{size}} square feet available for a solar installation which is enough space for a solar electrical system of {{kW}} kW, depending on obstructions, shading, and other factors.</li>'+
                        '<li>A system of this size can offset {{offset}} of your annual electricity needs.</li>'+ 
                        '<li>However, the optimal system size is determined by a number of factors including your utility and tariff structure, energy usage profiles and your organization\'s individual needs and goals.</li></ul>';
response['page3']['page_response']['option3-2'] = '<ul><li>Ground mounted solar installations are generally the most cost effective means of generating solar electricity and are an excellent choice if land is available.</li>'+
                        '<li>A ground mounted solar installation is usually the most efficient, has the least impact on ongoing building operations, and makes a visible statement of your company\'s commitment to achieving energy independence and reducing its carbon footprint.</li>'+
                        '<li>You have indicated that you have {{size}} square feet available for a solar installation which is enough space for a solar electrical system of {{kW}} kW, depending on obstructions and other factors.</li>'+
                        '<li>A system of this size could offset your entire electrical usage.</li>'+ 
                        '<li>However, the ideal system size may not be the maximum possible system size, depending on your organization\'s individual needs and goals, electric usage profile, rate structure, and other factors.</li></ul>';
response['page3']['page_response']['option3-3'] = '<ul><li>Ground mounted solar installations are generally the most cost effective means of generating solar electricity and are an excellent choice if land is available.</li>'+
                        '<li>A ground mounted solar installation is usually the most efficient, has the least impact on ongoing building operations, and makes a visible statement of your company\'s commitment to achieving energy independence and reducing its carbon footprint.</li>'+
                        '<li>You have indicated that you have {{size}} square feet available for a solar installation which is enough space for a solar electrical system of {{kW}} kW.</li>'+
                        '<li>However you do not have enough useful space to offset a significant portion of your electrical needs.</li>';
response['page3']['page_response']['option3-4'] = '<ul><li>Ground mounted solar installations are generally the most cost effective means of generating solar electricity and are an excellent choice if land is available.</li>'+
                        '<li>A ground mounted solar installation is usually the most efficient, has the least impact on ongoing building operations, and makes a visible statement of your company\'s commitment to achieving energy independence and reducing its carbon footprint.</li>'+
                        '<li>You have indicated that you have {{size}} square feet available for a solar installation which is enough space for a solar electrical system of {{kW}} kW, depending on obstructions shading and other factors. </li>'+
                        '<li>A solar electrical system will offset approximately {{value}} of your load.</li>'+ 
                        '<li>However, the ideal system size may not be the maximum possible system size, depending on your organization\'s individual needs and goals, electric usage profile, rate structure, and other factors. </li></ul>';


response['page3']['summary_response'] = Array(); // Page 3:  summary responses (used in summary page 5)
response['page3']['summary_response']['option1-1'] = '<ul>'+'<li>You may be able to utilize your rooftop to generate {{offset}} of your annual electricity needs.</li>'+'</ul>';
response['page3']['summary_response']['option1-2'] = '<ul>'+'<li>You may be able to utilize your rooftop to offset your entire annual electric needs.</li>'+'</ul>';
response['page3']['summary_response']['option1-3'] = '<ul>'+'<li>You do not have enough useful roof space to generate a significant portion of your annual electric needs. </li>'+'</ul>';
response['page3']['summary_response']['option1-4'] = '<ul>'+'<li>You may be able to utilize your rooftop to generate approximately {{kW_high}} of your annual electric needs.</li>'+'</ul>';

response['page3']['summary_response']['option2-1'] = '<ul>'+'<li>You may be able to utilize your parking lot to generate {{offset}} of your annual electricity needs and provide covered parking at the same time.</li>'+'</ul>';
response['page3']['summary_response']['option2-2'] = '<ul>'+'<li>You may be able to utilize your parking lot to offset your entire electricy needs and provide covered parking at the same time.</li>'+'</ul>';
response['page3']['summary_response']['option2-3'] = '<ul>'+'<li>You do not have enough useful parking area for a PV system to offset a significant portion of your electrical needs.</li>'+'</ul>';
response['page3']['summary_response']['option2-4'] = '<ul>'+'<li>You may be able to use your parking lot to generate approximately {{kW_high}} of your load and provide covered parking at the same time.</li>'+'</ul>';

response['page3']['summary_response']['option3-1'] = '<ul>'+'<li>You may be able to utilize your open land area to generate {{offset}} of your annual electricity needs.</li>'+'</ul>';
response['page3']['summary_response']['option3-2'] = '<ul>'+'<li>You may be able to utilize your open land area to offset your entire electricy needs.</li>'+'</ul>';
response['page3']['summary_response']['option3-3'] = '<ul>'+'<li>You do not have enough useful space for a PV system to offset a significant portion of your electrical needs. </li>'+'</ul>';
response['page3']['summary_response']['option3-4'] = '<ul>'+'<li>You may be able to utilize your open land area to generate approximately {{kW_high}} of your electrical needs.</li>'+'</ul>';


/* Page 4 response data */
response['page4'] = Array(); 
response['page4']['page_response'] = Array(); // Page 4:  page responses (used when 'continue' button clicked)
response['page4']['page_response']['option1'] = '<ul><li>Solar PPAs are ideal for publicly traded companies.</li>'+
                        '<li>They enable these companies to lower operating expenses, hedge against the risk of future increases in electricity costs, and demonstrate corporate responsibility while minimizing the distraction from core business activities associated with the implementation of a solar power project.</li>'+
                        '</ul>';
response['page4']['page_response']['option2'] = '<ul><li>Solar PPAs are ideal for private companies.</li>'+
                        '<li>They enable these companies to lower operating expenses, hedge against the risk of future increases in electricity costs, and demonstrate corporate responsibility while minimizing the distraction from core business activities associated with the implementation of a solar power project.</li>'+
                        '</ul>';                  
response['page4']['page_response']['option3'] = '<ul>'+
                        '<li>Solar PPAs are ideal for most non-profit organizations.</li>'+
                        '<li>Because they do not pay taxes, non-profits cannot take advantage of state and federal tax incentive programs directly.</li>'+
                        '<li>However, with a solar PPA, these benefits can be passed through by the PPA provider to the non-profit, because the PPA provider owns the system and can take advantage of the tax credit.</li>'+
                        '</ul>';
response['page4']['page_response']['option4'] = '<ul>'+
                        '<li>Solar PPAs are ideal for most government agencies.</li>'+
                        '<li>Because they do not pay taxes, government agencies cannot take advantage of state and federal tax incentive programs directly.</li>'+
                        '<li>However, with a solar PPA, these benefits can be passed through to the government agency by the PPA provider, because the PPA provider owns the system and can take advantage of the tax credit.</li>'+
                        '</ul>';
response['page4']['page_response']['option5'] = '<ul>'+
                        '<li>Solar PPAs enable most organizations to lower operating expenses and hedge against the risk of future increases in electricity costs.</li>'+
                        '<li>A conversation with Tioga can help you determine what other benefits you may achieve with a solar PPA.</li>'+
                        '</ul>';
                        
response['page4']['summary_response'] = Array(); // Page 4:  summary responses (used in summary page 5)
response['page4']['summary_response']['option1'] = '<ul>'+
                        '<li>A solar PPA can lower operating expenses, hedge against the risk of future increases in electricity costs, and demonstrate corporate responsibility without creating a distraction from core business activities.</li>'+
                        '</ul>';
response['page4']['summary_response']['option2'] = '<ul>'+
                        '<li>A solar PPA can lower operating expenses, hedge against the risk of future increases in electricity costs, and demonstrate corporate responsibility without creating a distraction from core business activities.</li>'+
                        '</ul>';
response['page4']['summary_response']['option3'] = '<ul>'+
                        '<li>A solar PPA can enable you to take advantage of generous tax credits,  lower operating expenses, hedge against the risk of future increases in electricity costs, and demonstrate commitment to sustainability.</li>'+
                        '</ul>';
response['page4']['summary_response']['option4'] = '<ul>'+
                        '<li>A solar PPA can enable you to take advantage of generous tax credits,  lower operating expenses, hedge against the risk of future increases in electricity costs, and demonstrate commitment to sustainability.</li>'+
                        '</ul>';
response['page4']['summary_response']['option5'] = '<ul>'+
                        '<li>A solar PPA can lower operating expenses, hedge against future increases in electricity costs and provide other benefits depending upon your organization structure.</li>'+
                        '</ul>';


/* Page 5 response data */
response['page5'] = Array(); 
response['page5']['page_response'] = Array(); // Page 5:  page responses (used when 'continue' button clicked)

//good sate - good load
response['page5']['page_response']['option1'] = '<p>'+
                        'From the information you provided in this survey, a solar PPA is an alternative energy option for your company.</p>'+
                        '{{summary_pg1}}'+
                        '{{summary_pg2}}'+
                        '{{summary_pg3}}'+
                        '<p>Tioga Energy will contact you to discuss how a SurePath&#8480; Solar PPA offers fast, simple access to the financial and environmental benefits of solar power.</p>'+
                        '';
//bad state - low load
response['page5']['page_response']['option2'] = '<p>'+
                        'From the information you provided in this survey, a solar PPA does not appear to be the right solution for your organization at this time.</p>'+
                        '{{summary_pg1}}'+
                        '{{summary_pg2}}'+
                        '{{summary_pg3}}'+
                        '<p>Tioga Energy continually monitors federal and state legislation for changes in energy policies. We will be in touch if these changes improve your organization\'s ability to benefit from solar power and a SurePath&#8480; Solar PPA.'+
                        '</p>';

						
//good state - low load
response['page5']['page_response']['option3'] = '<p>'+
                        'From the information you provided in this survey, a solar PPA does not appear to be the right solution for your organization at this time. Your annual energy consumpton is too low to support a solar PPA.</p>'+
                        '{{summary_pg1}}'+
                        '{{summary_pg2}}'+
                        '{{summary_pg3}}'+
                        '<p>Tioga Energy will contact you if conditions change to make a SurePath&#8480; Solar PPA a viable option for you.'+
                        '</p>';

//bad state - good load
response['page5']['page_response']['option4'] = '<p>'+
                        'From the information you provided in this survey,  solar power has potential as an alternative energy solution for you, however your state\'s energy policies limit your options at this time.</p>'+
                        '{{summary_pg1}}'+
                        '{{summary_pg2}}'+
                        '{{summary_pg3}}'+
                        '<p>Tioga Energy continually monitors federal and state legislation for changes in energy policies. We will be in touch if these changes improve your organization\'s ability to benefit from solar power and a SurePath&#8480; Solar PPA.'+
                        '</p>';

response['page5']['summary_response'] = Array(); // Page 5:  summary responses (dynamically updated)


/* Functions */
var currentPage = 1;
function nextPage(next){
    function closeDialog(obj, next) {
        $(obj).dialog('destroy'); 
        $('#page'+currentPage+' > div > input').attr('disabled', '');
        $('#page'+currentPage+' > div > select').attr('disabled', '');
		if (next)
		{
			changePage(next);
		}
    }
    if (validate(currentPage)) {
        $('#page'+currentPage+' > div > input').attr('disabled', 'disabled');
        $('#page'+currentPage+' > div > select').attr('disabled', 'disabled');
		if (currentPage == 1)
		{
			$('#page'+currentPage+' > div > input').attr('disabled', '');
			$('#page'+currentPage+' > div > select').attr('disabled', '');
			changePage(next);
			return;
		}
        $('#page'+currentPage+'_results').html(getResults(currentPage)).css('display', 'block');

		if (next == 5) {
			$('#page'+currentPage+'_results').dialog({
				modal:true, 
				height:400,
				width:400,
				bgiframe: true,
				close:function(i,j) { closeDialog(this, next); },
				buttons:
				{
					'Continue': function() {
						closeDialog(this, false);
						$('#page'+next+'_results').html(getResults(next)).css('display', 'block');
						$('#final_results').val(getResults(next));
						$('#page'+next+'_results').dialog({
							modal:true, 
							height:400,
							width:400,
							bgiframe: true,
							close:function(i,j) { $("#ppa_form").submit(); },
							buttons:{ 'Finish': function() { $("#ppa_form").submit() } }
						});
					}
				}
			});
			

		} else {
			$('#page'+currentPage+'_results').dialog({
				modal:true, 
				height:400,
				width:400,
				bgiframe: true,
				close:function(i,j) { closeDialog(this, next); },
				buttons:{ 'Continue': function() { closeDialog(this, next); } }
			});
		}
    }
}


function prevPage(prev){
    changePage(prev)
}

function changePage(page){ 
    $('#page'+currentPage).fadeOut('slow', function() {
	//	document.getElementById('page'+currentPage).style.removeAttribute('filter');
       // document.getElementById('page'+page).style.removeAttribute('filter');
        $('#page'+page).fadeIn('slow');
        
		$('#page'+page).css('visibility', 'visible');
        $('#pagination'+page).addClass('current')
    });
    $('#pagination'+currentPage).removeClass('current')
    currentPage = page;
}

function validate(page) {
    var status = true;
    fields = $('#page'+page+' input[type!="button"], #page'+page+' select');
    re_number = RegExp("^[0-9]+(,[0-9]{3})*(\.[0-9]+)?$");
    re_email = RegExp("^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$");
    fields.each(function (i) {
        if ((this.value == '') && ! $(this).hasClass('optional') ) {
            $(this).css('background-color', 'yellow');
            status = false;
        }
        else if ($(this).hasClass('email') &&  ! $(this).hasClass('optional') && ! re_email.test(this.value)) {
            $(this).css('background-color', 'red');
            status = false;
        }
        else if ($(this).hasClass('number') &&  ! $(this).hasClass('optional') && ! re_number.test(this.value)) {
            $(this).css('background-color', 'red');
            status = false;
        }
        else {
             $(this).css('background-color', 'white');
         }
    });
    // Assuming only one radio button group per page
    var radios = $('#page'+page+' input:radio');
    var radios_selected = $('#page'+page+' input:radio:checked');
    if ((radios.size() != 0) && (radios_selected.size() == 0)) {
        $(radios).next().css('background-color', 'yellow');
        status = false;
    }
    else if (radios.size()) { 
        $(radios).next().css('background-color', 'white');
    }
    return status;
}

function modify_form(value, type) {
    switch(type) {
        case 'where_to_install':
            if (value == 'roof') {
                $('#roof_details').slideDown('slow');
                $('#roof_details').css('display', 'block');
                $('#roof_details input, #roof_details select').removeClass('optional');

				if ($('#roof_type').val() == '2') {
					$('#location_details_pitched').slideDown('slow');
					$('#location_details_pitched').css('display', 'inline');
				}
            }
            else {
                $('#roof_details').slideUp('slow');
                $('#roof_details input, #roof_details select').addClass('optional');
			    $('#location_details_pitched').css('display', 'none');
            }

			if (value == 'structure')
			{
                $('#location_details_carport').slideDown('slow');
                $('#location_details_carport').css('display', 'inline');
			} else {
                $('#location_details_carport').slideUp('slow');
			    $('#location_details_carport').css('display', 'none');
			}

			$('#location_details').slideDown('slow');
			$('#location_details').css('display', 'block');
            break;
            
        case 'roof_type':
            if (value == '2') {
                $('#location_details_pitched').slideDown('slow');
                $('#location_details_pitched').css('display', 'inline');
			} else {
                $('#location_details_pitched').slideUp('slow');
			    $('#location_details_pitched').css('display', 'none');
			}
			break;
        
		case 'own_or_lease':
            if (value == 'lease') {
                $('#lease_info').slideDown('slow');
                $('#lease_info').css('display', 'block');
                $('#lease_info input, #lease_info select').removeClass('optional');
            }
            else {
                $('#lease_info').slideUp('slow');
                $('#lease_info input, #lease_info select').addClass('optional');
            }
            break;
	}
}


//== Determine which result (defined above) to display
function getResults(page) {
    switch(page) {
        case 2: 
            var state = $('#state').val();
            var usage = $('#usage').val();

            if (stateList1.indexOf(state) != -1) {
                if (usage < 2) {
					result = 'option1-1';
				} else if (usage > 1 && usage < 6) {
					result = 'option1-2';
				} else if (usage > 5 && usage < 10) {
					result = 'option1-3';
				} else if (usage > 9) {
					result = 'option1-4';
				}
            } 
            else if (stateList2.indexOf(state) != -1) {
                result = 'option2'; 
            }
            else result = 'option3';
            
			state = (stateList3[state]);
			
			response_msg = response['page2']['page_response'][result];
			response_msg = response_msg.replace(/\{\{state\}\}/, state);
			response_msg = response_msg.replace(/\{\{state\}\}/, state);  //Since there are two uses of {{state}} in msg

			summary_msg = response['page2']['summary_response'][result];
			summary_msg = summary_msg.replace(/\{\{state\}\}/, state);
			summary_msg = summary_msg.replace(/\{\{state\}\}/, state);

            // Set for final page summary_response
            response['page5']['summary_response']['pg2'] = summary_msg;
            response['page5']['summary_response']['pg2_var_result'] = result; //= variable used in summary page logic
           
            return(response_msg);
            break;
        case 3: 
            var response_msg = '';
            var location = $('#install_location').val();
            var size = $('#location_size').val();
            var usage_option = parseInt($('#usage').val());

            var usage_low;
			var usage_high;

			//== Determine the high and low range if the usage per year in kWh
            switch(usage_option) {
				case 1:
					usage_low = 1;
					usage_high = 199999;
					break;
				case 2:
					usage_low = 200000;
					usage_high = 299999;
					break;
				case 3:
					usage_low = 300000;
					usage_high = 399999;
					break;
				case 4:
					usage_low = 400000;
					usage_high = 499999;
					break;
				case 5:
					usage_low = 500000;
					usage_high = 599999;
					break;
				case 6:
					usage_low = 600000;
					usage_high = 699999;
					break;
				case 7:
					usage_low = 700000;
					usage_high = 799999;
					break;
				case 8:
					usage_low = 800000;
					usage_high = 899999;
					break;
				case 9:
					usage_low = 900000;
					usage_high = 999999;
					break;
				case 10:
					usage_low = 1000000;
					usage_high = 1000000;
					break;
			}

			var result, kW_low, kW_high, offset_low, offset_high, offset, value;
            
			//Determine equation based on roof type
			if (location == 'roof') { 
                result = 'option1-1'; 

				//Roof Mount (low value) = square feet * 60% usable space adjustment * 8 watts per square foot / 1000 units adjustment * 1300 kWh per kW
				//Roof Mount (high value) = square feet * 80% usable space adjustment * 10 watts per square foot / 1000 units adjustment * 1400 kWh per kW

                kW_low = cleanNumber(size) * 0.6 * 8  / 1000;
                kW_high = cleanNumber(size) * 0.8 * 10  / 1000;
                offset_low = Math.min(Math.max(Math.round(kW_low * 1300 / usage_high * 100), 0), 100);
                offset_high = Math.max(Math.min(Math.round(kW_high * 1400 / usage_low * 100), 100), 0);


				//== If min percentage and max are the same...
				if (offset_low == offset_high) {
					value = offset_low;
					
					if (value == 100) {
						result = 'option1-2'; 
					}
					else if (value == 0) {
						result = 'option1-3'; 
					}
					else {
						result = 'option1-4'; 
					}

				}// == end min = max?
            }
            else if (location == 'structure') { 
                result = 'option2-1'; 

				//Carport (low value) = square feet * 9 watts per square foot   / 1000 units adjustment * 1300 kWh per kW
				//Carport (high value) = square feet * 11 watts per square foot / 1000 units adjustment * 1400 kWh per kW
			
                kW_low = cleanNumber(size) * 9  / 1000;
                kW_high = cleanNumber(size) * 11 / 1000;
                offset_low = Math.min(Math.max(Math.round(kW_low * 1300 / usage_high * 100), 0) ,100);
                offset_high = Math.max(Math.min(Math.round(kW_high  * 1400 / usage_low * 100), 100), 0);


				//== If min percentage and max are the same...
				if (offset_low == offset_high) {
					value = offset_low;
					
					if (value == 100) {
						result = 'option2-2'; 
					}
					else if (value == 0) {
						result = 'option2-3'; 
					}
					else {
						result = 'option2-4'; 
					}

				}// == end min = max?

			}
            else if (location == 'ground') { 
                result = 'option3-1'; 

				//Ground Mount (low value) = square feet * 4 watts per square foot / 1000 units adjustments * 1,400 kWh per kW
				//Ground Mount (low value) = square feet * 5 watts per square foot / 1000 units adjustments * 2,200 kWh per kW

                kW_low = cleanNumber(size) * 4 / 1000;
                kW_high = cleanNumber(size) * 5 / 1000;
                offset_low = Math.min(Math.max(Math.round(kW_low * 1400 / usage_high * 100), 0), 100);
                offset_high = Math.max(Math.min(Math.round(kW_high * 2200 / usage_low * 100), 100), 0);

				//== If min percentage and max are the same...
				if (offset_low == offset_high) {
					value = offset_low;
					
					if (value == 100) {
						result = 'option3-2'; 
					}
					else if (value == 0) {
						result = 'option3-3'; 
					}
					else {
						result = 'option3-4'; 
					}

				}// == end min = max?
            } 


			if (kW_low != kW_high) kW = "between " + addCommas(kW_low) + " and " + addCommas(kW_high) + " ";
            else kW = addCommas(kW_low) + " ";
            
			if (offset_low != offset_high) offset = "between " + addCommas(offset_low) + "% and " + addCommas(offset_high) + "% ";
            else offset = addCommas(offset_low) +"% ";
            
			value = value + '%';

            response_msg = response['page3']['page_response'][result];
            response_msg = response_msg.replace(/\{\{size\}\}/, size);
            response_msg = response_msg.replace(/\{\{kW\}\}/, kW);
            response_msg = response_msg.replace(/\{\{value\}\}/, value);
            response_msg = response_msg.replace(/\{\{offset\}\}/, offset);
            
            // Set for final page summary_response
            summary_msg = response['page3']['summary_response'][result];
            summary_msg = summary_msg.replace(/\{\{size\}\}/, size);
            summary_msg = summary_msg.replace(/\{\{kW\}\}/, kW);
            summary_msg = summary_msg.replace(/\{\{offset\}\}/, offset);
			summary_msg = summary_msg.replace(/\{\{value\}\}/, value);
			summary_msg = summary_msg.replace(/\{\{kW_high\}\}/, kW_high);
            response['page5']['summary_response']['pg3'] = summary_msg;
            response['page5']['summary_response']['pg3_var_result'] = result; //= variable used in summary page logic
            
            return response_msg;         
            break;
        case 4: 
            var result;
            switch($('#org_type').val()) {
                case 'public' :     result = 'option1'; break;
                case 'private':     result = 'option2'; break;
                case 'non-profit':  result = 'option3'; break;
                case 'government':  result = 'option4'; break;
                case 'other':       result = 'option5'; break;
            }
            
            // Set for final page summary_response
            response['page5']['summary_response']['pg4'] = response['page4']['summary_response'][result];
            
            return response['page4']['page_response'][result];
            break;
        case 5:
            var response_msg;
			usage_option = parseInt($('#usage').val());
			usage_result = response['page5']['summary_response']['pg3_var_result'];
			
			//alert(usage_result);
			//== Determine type of response...

			// Bad State
            if (response['page5']['summary_response']['pg2_var_result'] == 'option3') {

				// Bad Load
				if(usage_result == 'option1-3' || usage_result == 'option2-3' || usage_result == 'option3-3' ) {
					response_msg = response['page5']['page_response']['option2']; //not qualified
				} 
				// Good Load
				else {
					response_msg = response['page5']['page_response']['option4']; //not qualified
				}
			}
			// Good State
            else {
				// Bad Load
				if(usage_result == 'option1-3' || usage_result == 'option2-3' || usage_result == 'option3-3' ) {
					response_msg = response['page5']['page_response']['option3']; //not qualified
				} 
				// Good Load
				else {
					response_msg = response['page5']['page_response']['option1']; //not qualified
				}
			}

            response_msg = response_msg.replace(/\{\{summary_pg1\}\}/, response['page5']['summary_response']['pg2']);
            response_msg = response_msg.replace(/\{\{summary_pg2\}\}/, response['page5']['summary_response']['pg3']);
            response_msg = response_msg.replace(/\{\{summary_pg3\}\}/, response['page5']['summary_response']['pg4']);
            
            return response_msg;
            break;
        default: return('Warning:  No results available for page '+page); break;
    }
}

function submit_debug(form){
    var values = '';
    var len = form.length - 1; //Leave off Submit Button
    for(i=0; i<len; i++) {
        if(form[i].id.indexOf("C")!=-1||form[i].id.indexOf("B")!=-1)//Skip Continue and Back Buttons
            continue;
        values += form[i].id;
        values += ': ';
        values += form[i].value;
        values += '\n';
    }
    alert(values);
}

function submitForm() {
    if (validate(4)) {
        document.ppaForm.submit();
    }
}

// The following is for the jquery form plugin
$(document).ready(function() { 
    // prepare Options Object,
    // bind 'ppa_form', and provide a simple callback function 
    var options = { 
        dataType:       'json', 
        beforeSubmit:   request,  // pre-submit callback 
        success:        displayResponse,  // post-submit callback 
        resetForm:      false 
    }; 
    //$('#ppa_form').ajaxForm(options);
    //getResponse();       
}); 
function request(formData, jqForm, options) {
    //alert('Got here.'); 
    return true;
}
function getResponse() {
    $.getJSON('ppa/test_results.php', displayResponse);
}
function displayResponse(responseItems)  {
    //== Used to display for testing
	
	var text = '';
    for (id in responseItems) {
        text = text + "\nAJAX response ["+id+"]: "+ responseItems[id];
    }
    document.getElementById('final_results').value += text;
}

function cleanNumber(aNum) {

	//remove any commas
	aNum=aNum.replace(/,/g,"");

	//remove any spaces
	aNum=aNum.replace(/\s/g,"");

	return aNum;
}

function addCommas(nStr)
{
	nStr += '';
	
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	
	var rgx = /(\d+)(\d{3})/;
	
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}

	return x1 + x2;
}


