/**
 * 
 * This is the salesforce form validation routine
 * created by Rich Sisco on October 4, 2011
 *
 *
 */
 
 
function AddItem(Value,Text,ElementID)
{

	// Create an Option object                
	var opt = document.createElement("option");
		
	// Add an Option object to Drop Down/List Box
        
	document.getElementById(ElementID).options.add(opt);        
		
	// Assign text and value to Option object
	opt.text = Text;
	opt.value = Value;

}

function createDropdown(dropDownId,dropDownValueArray)
{
	//This function populates the 00N80000004meMg Project Location state/region dropdown
	//
	// The array stores the value than the title so the for each needs to increment by two
	//
	for (i=0;i<=(dropDownValueArray.length -1);i=i+2)
		{
			// uncomment to test
			//alert(document.getElementById(dropDownValueArray[i]).value);
			//alert(document.getElementById(dropDownValueArray[i+1]).value);
			AddItem(dropDownValueArray[i],dropDownValueArray[i+1],dropDownId);

		}	
}

function createRequestObject() {
	//This function creates the http request for the reCaptcha call
	//
	// 
	//


    var tmpXmlHttpObject;
    
    //depending on what the browser supports, use the right way to create the XMLHttpRequest object
    if (window.XMLHttpRequest) { 
        // Mozilla, Safari would use this method ...
        tmpXmlHttpObject = new XMLHttpRequest();
	
    } else if (window.ActiveXObject) { 
        // IE would use this method ...
        tmpXmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    return tmpXmlHttpObject;
}

function createRequiredFieldsArray(formName)
{
	// Uncomment for testing
	//alert("in createRequiredFieldsArray");
	
	
	
	if (formName == "sunedisonBusinessContactUs") {
		formRequiredFields=new Array(
			"first_name",
			"last_name",
			"title",
			"company",
			"recaptcha_response_field",
			"00N300000022Dyb"); 
			
		formDefaultFields=new Array ("email",
			"phone",
			"ext",
			"00N30000001SF0b");	
	
	}

	if (formName == "sunedisonSustainabilityContactUs") {
		formRequiredFields=new Array(
			"first_name",
			"last_name",
			"title",
			"company",
			"00N80000004meMg",
			"00N80000004meMl",
			"recaptcha_response_field",
			"00N300000022Dyb"); 
			
		formDefaultFields=new Array ("email",
			"phone",
			"ext",
			"00N30000001SF0b");	
	
	}	
	
	if (formName == "sunedisonPublicSectorContactUs"){
		formRequiredFields=new Array(
			"first_name",
			"last_name",
			"title",
			"company",
			"recaptcha_response_field",
			"00N300000022Dyb"); 
			
		formDefaultFields=new Array ("email",
			"phone",
			"ext",
			"00N30000001SF0b");
	}
	
	if (formName == "sunedisonPowerCompanyContactUs") {
		formRequiredFields=new Array(
			"first_name",
			"last_name",
			"title",
			"company",
			"00N80000004meMl",
			"state",
			"recaptcha_response_field",
			"00N300000022Dyb"); 
			
		formDefaultFields=new Array ("email",
			"phone",
			"ext",
			"00N30000001SF0b");
	
	}
	if (formName == "sunedisonLandContactUs") {
		formRequiredFields=new Array(
			"first_name",
			"last_name",
			"phone",
			"00N80000004meMg",
			"recaptcha_response_field",
			"00N80000004meMl"); 
	
				
		formDefaultFields=new Array ("email",
			"title",
			"company",
			"00N80000004meMv",
			"ext",
			"00N30000001SF0b");
	
	}
	
	if (formName == "sunedisonHomeOwnerContactUs") 
	{
		formRequiredFields=new Array(
			"first_name",
			"last_name",	
			"email",
			"phone",
			"state",
			"recaptcha_response_field",
			"zip"); 
		
		formDefaultFields=new Array (
			"street",
			"city",
			"00N80000004lybO",
			"00N80000004mq3W",
			"00N80000004mq3W",
			"00N80000004mq3g",
			"00N80000004mq3b",
			"ext",
			"ref_ext",
			"00N30000001SF0b");	
	}

	if (formName == "sunedisonPVEmail") 
	{
		formRequiredFields=new Array(
			"first_name",
			"last_name",	
			"email",
			"email1",
			"phone",
			"state",
			"recaptcha_response_field",
			"zip"); 
		
		formDefaultFields=new Array (
			"street",
			"city",
			"ext",
			"00N30000001SF0b");	
	}
	
	if (formName == "sunedisonPartnerContactUs")
	{
		formRequiredFields=new Array(
			"first_name",
			"last_name",
			"title",
			"company",
			"recaptcha_response_field",
			"00N300000022Dyb"); 
			
		formDefaultFields=new Array ("email",
			"phone",
			"ext",
			"00N30000001SF0b");
	}
	
	if (formName == "sunedisonFinancingPartnersContactUs") {
		formRequiredFields=new Array(
				"first_name",
				"last_name",
				"title",
				"email",
				"phone",
				"Organization",
				"state",
				"country",
				"recaptcha_response_field",
	    		"00N80000004mjQs"); 

			
		formDefaultFields=new Array ("email",
			"phone",
			"ext",
			"00N30000001SF0b");
	}
				
	// Uncomment for testing
	//alert("exiting createRequiredFieldsArray");
	
}


function checkEmail (emailStr) {

	/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

	var checkTLD=1;

	/* The following is the list of known TLDs that an e-mail address must end with. */

	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

	/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

	var emailPat=/^(.+)@(.+)$/;

	/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : \ " . [ ] */

	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

	/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

	var validChars="\[^\\s" + specialChars + "\]";

	/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

	var quotedUser="(\"[^\"]*\")";

	/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

	/* The following string represents an atom (basically a series of non-special characters.) */

	var atom=validChars + '+';

	/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

	var word="(" + atom + "|" + quotedUser + ")";

//	The following pattern describes the structure of the user

	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

	/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

	/* Finally, let's start trying to figure out if the supplied address is valid. */

	/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

	var matchArray=emailStr.match(emailPat);

	if (matchArray==null) {

		/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

		/* alert("Email address seems incorrect (check @ and .'s)"); */
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

//	Start by checking that only basic ASCII characters are in the strings (0-127).

	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			/* alert("Ths username contains invalid characters."); */
			return false;
		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			/* alert("Ths domain name contains invalid characters."); */
			return false;
		}
	}

//	See if "user" is valid 

	if (user.match(userPat)==null) {

//		user is not valid

		/* alert("The username doesn't seem to be valid."); */
		return false;
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {

//		this is an IP address

		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				/* alert("Destination IP address is invalid!"); */
				return false;
			}
		}
		return true;
	}

//	Domain is symbolic name.  Check if it's valid.

	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			/* alert("The domain name does not seem to be valid.");*/
			return false;
		}
	}

	/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */

	if (checkTLD && domArr[domArr.length-1].length!=2 && 
			domArr[domArr.length-1].search(knownDomsPat)==-1) {
		/* alert("The address must end in a well-known domain or two letter " + "country."); */
		return false;
	}

//	Make sure there's a host name preceding the domain.

	if (len<2) {
		/* alert("This address is missing a hostname!"); */
		return false;
	}

//	If we've gotten this far, everything's valid!
	return true;
}

function checkFormElement(elementName,formName)
{
	// This code checks a form input to see if the value is present
	// 
	//
	// Uncomment out this to test
	// alert(elementName);
	
	var salesforceForm=document.forms[formName];
	var salesforceFormElement = salesforceForm.elements[elementName];
	var x = salesforceFormElement.value;	
	var y = salesforceFormElement.title;
	
	// Uncomment out this to test
	// alert(x);
	// alert(y);
	
	
	//
	// This if statement checks to make sure the value exists and that the value is empty
	//
	if (x==null || x=="")
	{
		return "doNotSubmit";
	}

	//
	// This if statement checks to make sure the value is not the same as the title which is used for the label
	//	
	if (x==y)
	{
		return "doNotSubmit";
	}

	return "";
}




function makeGetRequest(challenge,response) {
    //make a connection to the recaptcha jsp ... specifying that you intend to make a POST request 
    //to the server. Specifiy the page name and the URL parameters to send

	
    //http.open('post', 'http://www.google.com/recaptcha/api/verify?privatekey=' + privatekey + '&remoteip=' + remoteip + '&challenge=' + challenge + '&response=' + response);
	//http.open('post', 'http://localhost:8085/test/reCaptcha.jsp?recaptcha_challenge_field=' + challenge + '&recaptcha_response_field=' + response);
 
 
 	//http.open('post', 'http://107.20.187.34/wps/MEMCRightSidePromo/jsp/html/reCaptcha.jsp?recaptcha_challenge_field=' + challenge + '&recaptcha_response_field=' + response);
 
 	http.open('post', 'http://www.sunedison.com/wps/MEMCRightSidePromo/jsp/html/reCaptcha.jsp?recaptcha_challenge_field=' + challenge + '&recaptcha_response_field=' + response);    //assign a handler for the response
    http.onreadystatechange = processResponse;
	//Uncomment for testing
	//alert(response);
	
    //actually send the request to the server
    http.send(null);

}

function processResponse() {
    //check if the response has been received from the server
    if(http.readyState == 4){
	
        //read and assign the response from the server
        var response = http.responseText;
	    var correctResponse = response.match("Correct");
	    var incorrectResponse = response.match("Incorrect");
		
        //do additional parsing of the response, if needed
		//alert(response);
        //in this case simply assign the response to the contents of the <div> on the page. 
        if (incorrectResponse == null)
			document.getElementById('recaptcha_correct').value = "Correct";
		else
			document.getElementById('recaptcha_correct').value = "Incorrect";
		
        //If the server returned an error message like a 404 error, that message would be shown within the div tag!!. 
        //So it may be worth doing some basic error before setting the contents of the <div>
    }
}


function removeFormErrors(requiredFields) 
{ 
	// uncomment out this code for testing
	//alert("right before showFieldInErro ");

	for(i in formRequiredFields) 
	{ 

		removeFieldInError(formRequiredFields[i]);
		// uncomment out this code for testing
		// alert(formRequiredFields[i]);

	} 
}

function removeFieldInError(errorField){

	// uncomment out this code for testing
	//alert("removeFieldInError");
	if (browserType == "Internet Explorer")
		//document.getElementById(errorField).style.removeAttribute("background-color");
		document.getElementById(errorField).style.backgroundColor="#ffffff";
	else
		document.getElementById(errorField).style.removeProperty("background-color");	
}








function setDefaultValues() {

	for (i=0;i<=(formDefaultFields.length -1);i=i+1)
		{
			// uncomment to test
			//alert(document.getElementById(formDefaultFields[i]).value);
			//alert(document.getElementById(formDefaultFields[i]).title);
			if (document.getElementById(formDefaultFields[i]).value == document.getElementById(formDefaultFields[i]).title)
				document.getElementById(formDefaultFields[i]).value = "";
		}
}

function setUpReturnURL(formName,section,subSection)
{
	//var URLBase = "/wps/portal/memc/";

	//QA Server
	var URLBase = "http://www.sunedison.com/wps/portal/memc/";
	
	//Testing Server
	//var URLBase = "http://107.20.187.34/wps/portal/memc/";
	var URLsection = section.toLowerCase();
	
	if (URLsection == "home owner")
		URLsection = "homeowners";
	
	var URLSubSection = ""; 
	var returnURL = "";
	
	// This section is for Business
	
	if (subSection == "Commercial") 
		URLSubSection = "commercialretail";
		
	if (subSection == "Industrial") 
		URLSubSection = "commercialindustrial";	
		
	if (subSection == "Small Business") 
		URLSubSection = "smallbusiness";
		
	if (subSection == "Real Estate") 
		URLSubSection = "realestate";
		
	if (subSection == "Land Owner") 
		URLSubSection = "landowners";
				
	if (subSection == "Sustainability") 
		URLSubSection = "sustainablity";
	
	// This section for public sectoe
		
	if ((section == "Municipality") && (subSection == "Municipality"))
		URLSubSection = "municipalities/municipal";
		
	if (subSection == "School/University")
		URLSubSection = "schoolsuniversities/municipal";
		
	if (subSection == "Water Agency")
		URLSubSection = "wateragencies/municipal";
		
	if (subSection == "Federal Government")
		URLSubSection = "federalgovt";
		
	if (subSection == "State Government")
		URLSubSection = "government";
		
	// Power company form area	

	if (subSection == "Investor Owned Utility")
		URLSubSection = "investorowned";

	if ((section == "PowerCompanies") && (subSection == "Municipality"))
		URLSubSection = "municipal";

	if (subSection == "Co-op")
		URLSubSection = "coop";			

	if (subSection == "Independent Power Producer")
		URLSubSection = "powerproducers";				

	// This section is for partners

	if (subSection == "Dealer")
		URLSubSection = "dealers";				

	if (subSection == "Distributor")
		URLSubSection = "distributors";				

	if (subSection == "Commercial Partner")
		URLSubSection = "commercialpartners";				

	if (subSection == "Partner")
		URLSubSection = "solarconsultant";				

	if (subSection == "Solar Consultant")
		URLSubSection = "solarconsultant";	

	if (subSection == "Financial Partner")
		URLSubSection = "financialpartners";	

	// This section is for homeowners
					
	if (subSection == "SolarHome")
	{
		URLSubSection = "solarhome";
		
	}

	if (subSection == "GettingStarted")
	{
		URLSubSection = "gettingstarted";
		
	}
	
	//
	// This is to take care of the special marketing form
	//
	//
	if (subSection == "marketingcampaign")
	{
		subSection = "Municipality";
	}
	
						
	returnURL = URLBase + URLsection + "/" + URLSubSection;
	
	// uncomment to test
	//alert(returnURL);
	
	document.forms[formName]["retURL"].value = returnURL;
	
	document.forms[formName]["00N300000022Dyb"].value = subSection;
		
} 


function setUniqueId(formName)
{
	var d = new Date();
	var uniqueID = document.forms[formName]["last_name"].value + d.getTime();
	document.forms[formName]["00N80000004mikc"].value = uniqueID;
	document.forms[formName]["oid"].value = "00D300000006hWL";
	

	//Uncomment to test
	//alert(document.forms[formName]["00N300000022Dyb"].value);
	
}

function setDefaultValues() {

	for (i=0;i<=(formDefaultFields.length -1);i=i+1)
		{
			// uncomment to test
			//alert(document.getElementById(formDefaultFields[i]).value);
			//alert(document.getElementById(formDefaultFields[i]).title);
			if (document.getElementById(formDefaultFields[i]).value == document.getElementById(formDefaultFields[i]).title)
				document.getElementById(formDefaultFields[i]).value = "";
		}
}

function ShowFormErrors(requiredFields, errorArray) 
{ 
	// uncomment out this code for testing
	//alert("right before showFieldInErro ");

	for(i in errorArray) 
	{ 
		var errors = errorArray[i].split(":", 2);
		var field = errors[0];
		showFieldInError(field);
		// uncomment out this code for testing
		// alert(field);

	} 
}

function showFieldInError(errorField){

	// uncomment out this code for testing
	//alert("showFieldInError");
	
	document.getElementById(errorField).style.backgroundColor="#999900";		
}

function submitForm(formNameParameter)
{
	if (validateForm(formNameParameter))
	{
		alert(" Thank You! Your submission has been accepted.");
		document.getElementById(formNameParameter).submit()
	}
}


function validateForm(formNameParameter)
{
	
	// Uncomment for testing
	//alert("in validateForm");
	var submitForm = "submit";
	var formFieldCheck = "";
	var errors = [];
	var emailValid = "";
	var phoneValid = "";
	var salesforceFormForEmail=document.forms[formNameParameter];
	var salesforceEmailElement = salesforceFormForEmail.elements["email"];
	var salesforcePhoneElement = salesforceFormForEmail.elements["phone"];
	var salesforcereCaptchaElement = salesforceFormForEmail.elements["recaptcha_response_field"];
	var salesforcereCaptchaChallengeElement = salesforceFormForEmail.elements["recaptcha_challenge_field"] ;
	var emailValue = salesforceEmailElement.value;	
	var emailTitle = salesforceEmailElement.title;
	var phoneValue = salesforcePhoneElement.value;	
	var phoneTitle = salesforcePhoneElement.title;
	var recaptchaValue = salesforcereCaptchaElement.value;
	var recaptchaTitle = salesforcereCaptchaElement.title;
	var recaptchaChallengeValue = salesforcereCaptchaChallengeElement  ;
	
	createRequiredFieldsArray(formNameParameter);
	removeFormErrors(formRequiredFields)
	setUniqueId(formNameParameter);
	if (formRequiredFields.length > 0)
	{
		// uncomment out this code for testing
		// alert("in validateForm.formRequiredFields.length > 0");
		for (i=0;i<=(formRequiredFields.length -1);i=i+1)
		{

			formFieldCheck = "";
			formFieldCheck = checkFormElement(formRequiredFields[i],formNameParameter);
			// uncomment out this code for testing		
			// alert(formFieldCheck);
			if (formFieldCheck == "doNotSubmit")
				{
					errors[errors.length] = formRequiredFields[i] + ":" + "This is a required field";
					submitForm = "doNotSubmit";
				}
		}

	}

	// Check email and phone number. A new requirement was added to bypass the 
	// error if one is present and valid
	
	//
	// This if statement checks to see if the email address is well formed
	//		
	

		
	if (!checkEmail(emailValue.toLowerCase()))
		{
			emailValid = "no";
		}
	else
		{
			if (formNameParameter == "sunedisonPVEmail") 
			{
				if ((email1 == null) || (email1 == "") || (document.getElementById("email").value != document.getElementById("email1")))
				{
					emailValid = "no";
					errors[errors.length] = "email1" + ":" + "This is a required field";
				}
			}
		}
		
	//
	// This if statement checks to make sure the phone is formatted correctly
	//	
	if (!validatePhoneNumber(phoneValue))
		{
			phoneValid = "no";
		}
	
	if ((emailValid == "no")&&(phoneValid == "no"))
		{
			submitForm = "doNotSubmit";
			if (emailValid == "no") 
			{
				errors[errors.length] = "email" + ":" + "This is a required field";
			}
			if (phoneValid == "no") 
			{
				errors[errors.length] = "phone" + ":" + "This is a required field";
			}
		}
	
	if ((recaptchaValue == null) || (recaptchaValue == "")) 
		{
			submitForm = "doNotSubmit";
			errors[errors.length] = "recaptcha_response_field" + ":" + "This is a required field";
		}
		else
		{
			// Uncoment for testing
			//alert("calling jsp");

			reCaptchaChallenge = Recaptcha.get_challenge();
			// Uncoment for testing
        	//alert(reCaptchaChallenge);
			var challenge = reCaptchaChallenge ;
			// Uncoment for testing
			//alert (challenge);
			var response = recaptchaValue;
			var httpResponse = makeGetRequest(challenge,response);
			if (document.getElementById('recaptcha_correct').value == "Incorrect") {
				submitForm = "doNotSubmit";
				errors[errors.length] = "recaptcha_response_field" + ":" + "This is a required field";
			}

		}
		// uncomment out this code for testing
		// alert("right before submitForm validateForm");

	if (submitForm == "submit") 
	{
		setUniqueId(formNameParameter);
		setDefaultValues();
		if ((document.getElementById("ext").value == null) || (document.getElementById("ext").value == "") || (document.getElementById("ext").value.toLowerCase() == "ext."))
			document.getElementById("phone").value =  document.getElementById("phone").value;
		else		
			document.getElementById("phone").value =  document.getElementById("phone").value + " ext " + document.getElementById("ext").value;
		if (formNameParameter == "sunedisonHomeOwnerContactUs") {
			if ((document.getElementById("ref_ext").value == null) || (document.getElementById("ref_ext").value == "")  || (document.getElementById("ref_ext").value.toLowerCase() == "ext."))
				document.getElementById("00N80000004mq3g").value =  document.getElementById("00N80000004mq3g").value;
			else		
				document.getElementById("00N80000004mq3g").value =  document.getElementById("00N80000004mq3g").value + " ext " + document.getElementById("ref_ext").value;	
		
		// Uncomment for testing

		
		//alert(document.getElementById("00N80000004mq3g").value);
		//alert(document.getElementById("phone").value);
						
		}
		if ((formNameParameter == "sunedisonBusinessContactUs") ||  (formNameParameter == "sunedisonPublicSectorContactUs"))
		{
		
			if (document.getElementById("land").checked)
				document.getElementById("00N80000004mtlq").value = "land";
			if (document.getElementById("roof").checked)
				document.getElementById("00N80000004mtlq").value = "roof";
			if (document.getElementById("both").checked)
				document.getElementById("00N80000004mtlq").value = "both";
		
		
		}
		if (formNameParameter == "sunedisonSustainabilityContactUs") {
			if (document.getElementById("00N80000002e4bK").value == "SOCommercial")
					document.getElementById("00N300000022Dyb").value = "Commercial";

			if (document.getElementById("00N80000002e4bK").value == "SORealEstate")
					document.getElementById("00N300000022Dyb").value = "Real Estate";

			if (document.getElementById("00N80000002e4bK").value == "SOSmallBusiness")
					document.getElementById("00N300000022Dyb").value = "Small Roof";

			if (document.getElementById("00N80000002e4bK").value == "SOIndustrial")
					document.getElementById("00N300000022Dyb").value = "Industrial";

			if (document.getElementById("00N80000002e4bK").value == "SOLandOwner")
					document.getElementById("00N300000022Dyb").value = "Land Owner";

			if (document.getElementById("00N80000002e4bK").value == "SOGovernment")
					document.getElementById("00N300000022Dyb").value = "State of Federal Government";

			if (document.getElementById("00N80000002e4bK").value == "SOMunicipality")
					document.getElementById("00N300000022Dyb").value = "Municipality";

			if (document.getElementById("00N80000002e4bK").value == "SOSchoolUniversity")
					document.getElementById("00N300000022Dyb").value = "School/University";

			if (document.getElementById("00N80000002e4bK").value == "SOWaterAgency")
					document.getElementById("00N300000022Dyb").value = "Water Agency";

			if (document.getElementById("00N80000002e4bK").value == "SOInvestorOwned")
					document.getElementById("00N300000022Dyb").value = "Investor Owned Utility";

			if (document.getElementById("00N80000002e4bK").value == "SOIndependentPowerProducer")
					document.getElementById("00N300000022Dyb").value = "Independent Power Producer";

			if (document.getElementById("00N80000002e4bK").value == "")
			{
					document.getElementById("00N80000002e4bK").value = "SOCommercial";
					document.getElementById("00N300000022Dyb").value = "Commercial";
			}
			// Uncomment to test
			//alert(document.getElementById("00N80000002e4bK").value);
		}
		if ((document.getElementById("00N80000004lzG8").value == "homeowners/solarhome/requestaquote/") || (document.getElementById("00N80000004lzG8").value == "homeowners/gettingstarted/getaquote/"))
			document.getElementById("00N300000022Dyb").value = "Residential";

		if ((document.getElementById("00N80000004lzG8").value == "publicsector/federalgovt/contactus/") || (document.getElementById("00N80000004lzG8").value == "publicsector/government/contactus/"))
			document.getElementById("00N300000022Dyb").value = "State/Federal Government";

		if (document.getElementById("00N80000004lzG8").value == "publicsector/schoolsuniversities/contactus/") 
			document.getElementById("00N300000022Dyb").value = "School/University";
		
		// uncomment to test
		//alert("00N300000022Dyb");
		//alert(document.getElementById("00N300000022Dyb").value);
		
	
		return true;
	}
	else
	{
		ShowFormErrors(formRequiredFields,errors);
		Recaptcha.reload();
		return false;
	}
}


function validatePhoneNumber(elementValue){
	var phoneNumberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/; 
	if ((elementValue.substring(3,4) == '-')&& (elementValue.substring(7,8) == '-'))
	{
		return phoneNumberPattern.test(elementValue);
	}

	else
		{
		return false;
		}
		
}  

// Browser Detection Javascript
// copyright 1 February 2003, by Stephen Chapman, Felgall Pty Ltd

// You have permission to copy and use this javascript provided that
// the content of the script is not changed in any way.

function whichBrs() {
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("opera") != -1) return 'Opera';
	if (agt.indexOf("staroffice") != -1) return 'Star Office';
	if (agt.indexOf("webtv") != -1) return 'WebTV';
	if (agt.indexOf("beonex") != -1) return 'Beonex';
	if (agt.indexOf("chimera") != -1) return 'Chimera';
	if (agt.indexOf("netpositive") != -1) return 'NetPositive';
	if (agt.indexOf("phoenix") != -1) return 'Phoenix';
	if (agt.indexOf("firefox") != -1) return 'Firefox';
	if (agt.indexOf("safari") != -1) return 'Safari';
	if (agt.indexOf("skipstone") != -1) return 'SkipStone';
	if (agt.indexOf("msie") != -1) return 'Internet Explorer';
	if (agt.indexOf("netscape") != -1) return 'Netscape';
	if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
	if (agt.indexOf('\/') != -1) {
		if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
			return navigator.userAgent.substr(0,agt.indexOf('\/'));
		}
		else 
			return 'Netscape';
			} 
	else 
		if (agt.indexOf(' ') != -1)
			return navigator.userAgent.substr(0,agt.indexOf(' '));
		else 
			return navigator.userAgent;
	}


var RecaptchaOptions = {     
	theme : 'custom',     
	custom_theme_widget: 'recaptcha_widget'}; 


var stateRegionArray=new Array (
                "AL","Alabama",
                "AK","Alaska",
                "AZ","Arizona",
                "AR","Arkansas",
                "CA","California",
                "CO","Colorado",
                "CT","Connecticut",
                "DE","Delaware",
                "DC","District of Columbia",
                "FL","Florida",
                "GA","Georgia",
                "HI","Hawaii",
                "ID","Idaho",
                "IL","Illinois",
                "IN","Indiana",
                "IA","Iowa",
                "KS","Kansas",
                "KY","Kentucky",
                "LA","Louisiana",
                "ME","Maine",
                "MD","Maryland",
                "MA","Massachusetts",
                "MI","Michigan",
                "MN","Minnesota",
                "MS","Mississippi",
                "MO","Missouri",
                "MT","Montana",
                "NE","Nebraska",
                "NV","Nevada",
                "NH","New Hampshire",
                "NJ","New Jersey",
                "NM","New Mexico",
                "NY","New York",
                "NC","North Carolina",
                "ND","North Dakota",
                "OH","Ohio",
                "OK","Oklahoma",
                "OR","Oregon",
                "PA","Pennsylvania",
                "RI","Rhode Island",
                "SC","South Carolina",
                "SD","South Dakota",
                "TN","Tennessee",
                "TX","Texas",
                "UT","Utah",
                "VT","Vermont",
                "VA","Virginia",
                "WA","Washington",
                "WV","West Virginia",
                "WI","Wisconsin",
                "WY","Wyoming",
                "Africa","Africa",
                "Asia","Asia",
                "Canada","Canada",
                "Europe","Europe",
                "Latin America","Latin America" );
		
var countryArray=new Array (
				"USA","United States",
                "Afghanistan","Afghanistan",
                "Albania","Albania",
                "Algeria","Algeria",
                "American Samoa","American Samoa",
                "Andorra","Andorra",
                "Angola","Angola",
                "Anguilla","Anguilla",
                "Antarctica","Antarctica",
                "Antigua and Barbuda","Antigua and Barbuda",
                "Argentina","Argentina",
                "Armenia","Armenia",
                "Aruba","Aruba",
                "Australia","Australia",
                "Austria","Austria",
                "Azerbaijan","Azerbaijan",
                "Bahamas","Bahamas",
                "Bahrain","Bahrain",
                "Bangladesh","Bangladesh",
                "Barbados","Barbados",
                "Belarus","Belarus",
                "Belgium","Belgium",
                "Belize","Belize",
                "Benin","Benin",
                "Bermuda","Bermuda",
                "Bhutan","Bhutan",
                "Bolivia","Bolivia",
                "Bosnia and Herzegovina","Bosnia and Herzegovina",
                "Botswana","Botswana",
                "Bouvet Island","Bouvet Island",
                "Brazil","Brazil",
                "Brunei","Brunei",
                "Bulgaria","Bulgaria",
                "Burkina Faso","Burkina Faso",
                "Burundi","Burundi",
                "Cambodia","Cambodia",
                "Cameroon","Cameroon",
                "Canada","Canada",
                "Cape Verde","Cape Verde",
                "Cayman Islands","Cayman Islands",
                "Central African Republic","Central African Republic",
                "Chad","Chad",
                "Chile","Chile",
                "China","China",
                "Christmas Island","Christmas Island",
                "Colombia","Colombia",
                "Comoros","Comoros",
                "Congo","Congo",
                "Cook Islands","Cook Islands",
                "Costa Rica","Costa Rica",
                "Croatia","Croatia",
                "Cuba","Cuba",
                "Cyprus","Cyprus",
                "Czech Republic","Czech Republic",
                "Denmark","Denmark",
                "Djibouti","Djibouti",
                "Dominica","Dominica",
                "Dominican Republic","Dominican Republic",
                "East Timor","East Timor",
                "Ecuador","Ecuador",
                "Egypt","Egypt",
                "El Salvador","El Salvador",
                "Equatorial Guinea","Equatorial Guinea",
                "Eritrea","Eritrea",
                "Estonia","Estonia",
                "Ethiopia","Ethiopia",
                "Falkland Islands","Falkland Islands",
                "Faroe Islands","Faroe Islands",
                "Fiji Islands","Fiji Islands",
                "Finland","Finland",
                "France","France",
                "French Guiana","French Guiana",
                "French Polynesia","French Polynesia",
                "French Southern territories","French Southern territories",
                "Gabon","Gabon",
                "Gambia","Gambia",
                "Georgia","Georgia",
                "Germany","Germany",
                "Ghana","Ghana",
                "Gibraltar","Gibraltar",
                "Greece","Greece",
                "Greenland","Greenland",
                "Grenada","Grenada",
                "Guadeloupe","Guadeloupe",
                "Guam","Guam",
                "Guatemala","Guatemala",
                "Guinea","Guinea",
                "Guinea-Bissau","Guinea-Bissau",
                "Guyana","Guyana",
                "Haiti","Haiti",
                "Heard Island and McDonald Islands","Heard Island and McDonald Islands",
                "Honduras","Honduras",
                "Hong Kong","Hong Kong",
                "Hungary","Hungary",
                "Iceland","Iceland",
                "India","India",
                "Indonesia","Indonesia",
                "Iran","Iran",
                "Iraq","Iraq",
                "Ireland","Ireland",
                "Israel","Israel",
                "Italy","Italy",
                "Jamaica","Jamaica",
                "Japan","Japan",
                "Jordan","Jordan",
                "Kazakstan","Kazakstan",
                "Kenya","Kenya",
                "Kiribati","Kiribati",
                "Kuwait","Kuwait",
                "Kyrgyzstan","Kyrgyzstan",
                "Laos","Laos",
                "Latvia","Latvia",
                "Lebanon","Lebanon",
                "Lesotho","Lesotho",
                "Liberia","Liberia",
                "Libyan Arab Jamahiriya","Libyan Arab Jamahiriya",
                "Liechtenstein","Liechtenstein",
                "Lithuania","Lithuania",
                "Luxembourg","Luxembourg",
                "Macao","Macao",
                "Macedonia","Macedonia",
                "Madagascar","Madagascar",
                "Malawi","Malawi",
                "Malaysia","Malaysia",
                "Maldives","Maldives",
                "Mali","Mali",
                "Malta","Malta",
                "Marshall Islands","Marshall Islands",
                "Martinique","Martinique",
                "Mauritania","Mauritania",
                "Mauritius","Mauritius",
                "Mayotte","Mayotte",
                "Mexico","Mexico",
                "Moldova","Moldova",
                "Monaco","Monaco",
                "Mongolia","Mongolia",
                "Montserrat","Montserrat",
                "Morocco","Morocco",
                "Mozambique","Mozambique",
                "Myanmar","Myanmar",
                "Namibia","Namibia",
                "Nauruv","Nauruv",
                "Nepal","Nepal",
                "Netherlands","Netherlands",
                "New Caledonia","New Caledonia",
                "New Zealand","New Zealand",
                "Nicaragua","Nicaragua",
                "Niger","Niger",
                "Nigeria","Nigeria",
                "Niue","Niue",
                "Norfolk Island","Norfolk Island",
                "North Korea","North Korea",
                "Northern Mariana Islands","Northern Mariana Islands",
                "Norway","Norway",
                "Oman","Oman",
                "Pakistan","Pakistan",
                "Palau","Palau",
                "Palestine","Palestine",
                "Panama","Panama",
                "Papua New Guinea","Papua New Guinea",
                "Paraguay","Paraguay",
                "Peru","Peru",
                "Philippines","Philippines",
                "Pitcairn","Pitcairn",
                "Poland","Poland",
                "Portugal","Portugal",
                "Puerto Rico","Puerto Rico",
                "Qatar","Qatar",
                "Romania","Romania",
                "Russian Federation","Russian Federation",
                "Rwanda","Rwanda",
                "Saint Helena","Saint Helena",
                "Saint Kitts and Nevis","Saint Kitts and Nevis",
                "Saint Lucia","Saint Lucia",
                "Saint Pierre and Miquelon","Saint Pierre and Miquelon",
                "Saint Vincent and the Grenadines","Saint Vincent and the Grenadines",
                "Samoa","Samoa",
                "San Marino","San Marino",
                "Sao Tome and Principe","Sao Tome and Principe",
                "Saudi Arabia","Saudi Arabia",
                "Senegal","Senegal",
                "Seychelles","Seychelles",
                "Sierra Leone","Sierra Leone",
                "Singapore","Singapore",
                "Slovakia","Slovakia",
                "Slovenia","Slovenia",
                "Solomon Islands","Solomon Islands",
                "Somalia","Somalia",
                "South Africa","South Africa",
                "South Korea","South Korea",
                "Spain","Spain",
                "Sri Lanka","Sri Lanka",
                "Sudan","Sudan",
                "Suriname","Suriname",
                "Svalbard and Jan Mayen","Svalbard and Jan Mayen",
                "Swaziland","Swaziland",
                "Sweden","Sweden",
                "Switzerland","Switzerland",
                "Syria","Syria",
                "Taiwan","Taiwan",
                "Tajikistan","Tajikistan",
                "Tanzania","Tanzania",
                "Thailand","Thailand",
                "The Netherlands","The Netherlands",
                "Togo","Togo",
                "Tokelau","Tokelau",
                "Tonga","Tonga",
                "Trinidad and Tobago","Trinidad and Tobago",
                "Tunisia","Tunisia",
                "Turkey","Turkey",
                "Turkmenistan","Turkmenistan",
                "Turks and Caicos Islands","Turks and Caicos Islands",
                "Tuvalu","Tuvalu",
                "UAE","UAE",
                "Uganda","Uganda",
                "Ukraine","Ukraine",
                "United Arab Emirates","United Arab Emirates",
                "United Kingdom","United Kingdom",
                "Uruguay","Uruguay",
                "Uzbekistan","Uzbekistan",
                "Vanuatu","Vanuatu",
                "Venezuela","Venezuela",
                "Vietnam","Vietnam",
                "Virgin Islands","Virgin Islands",
                "Wallis and Futuna","Wallis and Futuna",
                "Western Sahara","Western Sahara",
                "Yemen","Yemen",
                "Yugoslavia","Yugoslavia",
                "Zambia","Yugoslavia",
                "Zimbabwe","Zimbabwe");

var sustainabilityOrganizationArray=new Array (
				"SOCommercial","Commercial",
				"SORealEstate","Real Estate",
				"SOSmallBusiness","Small Roof",
				"SOIndustrial","Industrial",
				"SOLandOwner","Land Owner",
				"SOGovernment","State/Federal Government",
				"SOMunicipality","Municipality",
				"SOSchoolUniversity","School/University",
				"SOWaterAgency","Water Agency",
				"SOInvestorOwned","Investor Owned",
				"SOCoop","Co-op",
				"SOIndependentPowerProducer","Independent Power Producer");
//
// The following sets up the reCaptcha validation
//
//call to create the XMLHttpRequest object
//
var http = createRequestObject();
var reCaptchaChallenge = "";
var browserType = whichBrs();

