/** Validates the form.  Returns true if valid, false if not. */
function validate()
{
    var isValid = true;


    if (isValid)
    {
        isValid = validateRequirement();
        if (isValid) isValid = validateContents();
        
    }

    return isValid;
}

/**
* makes sure we can check value of 'amount' radio buttons, even when none selected
*/
function updateTotals()
{
	var num; 
	for (var i = 0; i < document.donorForm.radio_amount.length; i++)
	{
		if (document.donorForm.radio_amount[i].checked)
		{
			num = document.donorForm.radio_amount[i].value;
		}		
	}
	if (document.donorForm.formtype.value == "Donation") // no need to do this check on membership form
	{
		if (document.donorForm.cb_otherAmount.checked)
		{
			num = document.donorForm.other_amount.value;
		}
	}
	document.donorForm.amount.value = num;	
}

/**
 * Makes sure a vaild e-mail address was given.
 * Returns true if valid, false if not.
 * based on code from: http://www.chalcedony.com/javascript3e/
 */
function validEmail(email)
{
	invalidChars = " /:,;"
	
	// does it contain any invalid characters?
	for (i=0; i<invalidChars.length; i++)
	{
		badChar = invalidChars.charAt(i)
		if (email.indexOf(badChar,0) > -1)
		{
			return false;
		}
	}

	// there must be one "@" symbol
	atPos = email.indexOf("@", 1)
	if (atPos == -1)
	{
		return false;
	}
	// and only one "@" symbol
	if (email.indexOf("@", atPos+1) != -1)
	{	
		return false;
	}
	
	// and at least one "." after the "@"
	periodPos = email.indexOf(".", atPos)
	if (periodPos == -1)
	{					
		return false;
	}

	// must be at least 2 characters after the "."
	if (periodPos+3 > email.length)
	{	
		return false;
	}
	
	return true;
}


/**
 * Validates the form field requirements.
 * Returns true if valid, false if not.
 */
function validateRequirement()
{
    var isValid = true;

    // check for credit card donation required fields
    if (document.donorForm.formtype.value == "Donation" || document.donorForm.formtype.value == "Membership")
    {
		if(document.donorForm.fname.value == "")
		{
			isValid = false;
			alert("Please enter your first name.");
			document.donorForm.fname.focus();
		}
		else if(document.donorForm.lname.value == "")
		{
			isValid = false;
			alert("Please enter your last name.");
			document.donorForm.lname.focus();
		}
		else if(document.donorForm.address.value == "")
		{
			isValid = false;
			alert("Please enter your address.");
			document.donorForm.address.focus();
		}
		else if(document.donorForm.city.value == "")
		{
			isValid = false;
			alert("Please enter your city.");
			document.donorForm.city.focus();
		}
		else if(document.donorForm.state.selectedIndex == 0)
		{
			isValid = false;
			alert("Please select your state.");
			document.donorForm.state.focus();
		}
		else if(document.donorForm.zip.value == "")
		{
			isValid = false;
			alert("Please enter your zip code.");
			document.donorForm.zip.focus();
		}
		else if(document.donorForm.phone.value == "")
		{
			isValid = false;
			alert("Please enter your phone number.");
			document.donorForm.phone.focus();
		}
		else if( !validEmail(document.donorForm.email.value) )
		{
			isValid = false;
			alert("Please enter a valid e-mail address.");
			document.donorForm.email.focus();
			document.donorForm.email.select();
		}
	
		else if(document.donorForm.cardnumber.value == "")
		{
			isValid = false;
			alert("Please enter your credit card number.");
			document.donorForm.cardnumber.focus();
		}
		else if(document.donorForm.cardExpMonth.value == "")
		{
			isValid = false;
			alert("Please enter the month your credit card expires.");
			document.donorForm.cardExpMonth.focus();
		}
		else if(document.donorForm.cardExpYear.value == "")
		{
			isValid = false;
			alert( "Please enter the year your credit card expires.");
			document.donorForm.cardExpYear.focus();
		}
		//else if(document.donorForm.cardCVV2 != null && document.donorForm.cardCVV2.value == "")
		//{
		//	isValid = false;
		//	alert("Please enter the security (CVV2) code for your credit card.");
		//	document.donorForm.cardCVV2.focus();
		}
		else if(document.donorForm.amount.value == "")
		{
			isValid = false;
			alert("Please enter the amount you wish to donate.");
			// only focus on amount if it is not readOnly
			if(!document.donorForm.amount.readOnly)
			{
				document.donorForm.amount.focus();
			}
		}
		return isValid;
    }
   


/**
 * Validates the form field content.
 * Returns true if valid, false if not.
 */
function validateContents()
{
    var isValid = true;
    var msg = "";

    // check credit card donation content 
    if (document.donorForm.formtype.value == "Donation" || document.donorForm.formtype.value == "Membership")
    {
	    // cvv2 code
		if(document.donorForm.cardCVV2 != null)   // skip if not implemented on the page yet
        {
            // Validate that the field is the right length
            if( document.donorForm.cardCVV2.value.length < 3 || document.donorForm.cardCVV2.value.length > 4 )
            {
                isValid = false;
                msg = "Valid security (CVV2) codes are 3 or 4 digits.";
            }
 
            // If we're still okay, make sure all characters in the code are numbers.
            if( isValid )
            {
                 for( i = 0; i < document.donorForm.cardCVV2.value.length; i++ )
                 {
                      if ((document.donorForm.cardCVV2.value.charAt(i) < "0") ||
                          (document.donorForm.cardCVV2.value.charAt(i) > "9"))
                      {
                          isValid = false;
                          msg = "The security (CVV2) code entered is not a valid 3 or 4 digit number.";
                      }
                 }
            }
        }   
		
        // card expiration month 
        if (document.donorForm.cardExpMonth.value.length < 2)
        {
            isValid = false;
            msg = "Valid credit card expiration month values are 01-12.";
        }
        if (isValid)
        {
            var month = new Number(document.donorForm.cardExpMonth.value);
            if ((month <= 0) || (month > 12))
            {
                isValid = false;
                msg = "Valid credit card expiration month values are 01-12.";
            }
            if (isNaN(month))
            {
                isValid = false;
                msg = "The credit card expiration month entered is not valid.";
            }
        }

        // card expiration year
        if (isValid)
        {
            var year = new Number(document.donorForm.cardExpYear.value);
            var now = new Date();
            if (year < now.getYear())
            {
                isValid = false;
                msg = "The credit card expiration year entered is in the past.";
            }
            if (isNaN(year))
            {
                isValid = false;
                msg = "The credit card expiration year entered is not valid.";
            }
        }
		
		// credit card number
		if (document.donorForm.cardnumber.value.length < 14)
		{
			isValid = false;
			msg = "Valid credit card numbers are at least 14 digits.";
		}
	
		for (i=0; i < document.donorForm.cardnumber.value.length; i++)
		{
			if ((document.donorForm.cardnumber.value.charAt(i) < "0") ||
				(document.donorForm.cardnumber.value.charAt(i) > "9"))
			{
				isValid = false;
				msg = "The credit card number entered is not valid";
			}
		}

    }

    // amount
    if (isValid)
    {
        if (document.donorForm.formtype.value == "Donation" || document.donorForm.formtype.value == "Membership") 
        {
            var amount = new Number(document.donorForm.amount.value);
            if ((amount <= 0) || (isNaN(amount)))
            {
                isValid = false;
                msg = "The amount entered must be greater than 0 and not contain a currency symbol or commas.";
            }
			if ( document.donorForm.amount.value.charAt(0) == '.' )
            	document.donorForm.amount.value = "0" + document.donorForm.amount.value;
        }
    }

    if (!isValid) alert(msg);
    return isValid;
}

var states = [ 
    new Array("Please Select", ""),
    new Array("Alabama", "AL"),
    new Array("Alaska", "AK"),
    new Array("Alberta", "AB"),
    new Array("Arizona", "AZ"),
    new Array("Arkansas", "AR"),
    new Array("California", "CA"),
    new Array("Colorado", "CO"),
    new Array("Connecticut", "CT"),
    new Array("Delaware", "DE"),
    new Array("District Of Columbia", "DC"),
    new Array("Florida", "FL"),
    new Array("Georgia", "GA"),
    new Array("Hawaii", "HI"),
    new Array("Idaho", "ID"),
    new Array("Illinois", "IL"),
    new Array("Indiana", "IN"),
    new Array("Iowa", "IA"),
    new Array("Kansas", "KS"),
    new Array("Kentucky", "KY"),
    new Array("Louisiana", "LA"),
    new Array("Maine", "ME"),
    new Array("Maryland", "MD"),
    new Array("Massachusetts", "MA"),
    new Array("Michigan", "MI"),
    new Array("Minnesota", "MN"),
    new Array("Mississippi", "MS"),
    new Array("Missouri", "MO"),
    new Array("Montana", "MT"),
    new Array("Nebraska", "NE"),
    new Array("Nevada", "NV"),
    new Array("New Hampshire", "NH"),
    new Array("New Jersey", "NJ"),
    new Array("New Mexico", "NM"),
    new Array("New York", "NY"),
    new Array("North Carolina", "NC"),
    new Array("North Dakota", "ND"),
    new Array("Ohio", "OH"),
    new Array("Oklahoma", "OK"),
    new Array("Oregon", "OR"),
    new Array("Pennsylvania", "PA"),
    new Array("Rhode Island", "RI"),
    new Array("South Carolina", "SC"),
    new Array("South Dakota", "SD"),
    new Array("Tennessee", "TN"),
    new Array("Texas", "TX"),
    new Array("Utah", "UT"),
    new Array("Vermont", "VT"),
    new Array("Virginia", "VA"),
    new Array("Washington", "WA"),
    new Array("West Virginia", "WV"),
    new Array("Wisconsin", "WI"),
    new Array("Wyoming", "WY")];

function writeStates()
{
    writeSelectOptions(states);
}



function writeSelectOptions(selectData)
{
    for (var i = 0; i < selectData.length; i++)
    {
        document.write("<option value=\"" + selectData[i][1] + "\"");
        if ((selectData[i][2] != null) && (selectData[i][2] == "true"))
        {
            document.write(" selected");
        }
        document.writeln(">" + selectData[i][0] + "</option>");
    }
}

function writeDays()
{
    for (var i = 1; i <= 31; i++)
    {
        var s = new Number(i).toString();
        if (s.length == 1)
        {
            s = new String("0") + s;
        }
        document.writeln("<option value=\"" + s + "\">" + s + "</option>");
    }
}

function writeMonths()
{
    for (var i = 1; i <= 12; i++)
    {
        var s = new Number(i).toString();
        if (s.length == 1)
        {
            s = new String("0") + s;
        }
        document.writeln("<option value=\"" + s + "\">" + s + "</option>");
    }
}

function writeYears(start, num)
{
    var startYear;
    if (Number(start) == -1)	// start at current year
    {
        startYear = getCurrentYear();
    }
    else
    {
        startYear = start;
    }

    for (var i = startYear; i <= startYear+num; i++)
    {
        document.writeln("<option value=\"" + i + "\">" + i + "</option>");
    }
}

function getCurrentYear()
{
    var year;

    var d = new Date();
    if (navigator.appName.indexOf("Netscape") >= 0)
    {
        var str = new Number(d.getYear()).toString();
        str = "20" + str.substring(1);
        year = new Number(str);
    }
    else
    {
        year = new Number(d.getYear());
    }

    return year;
}

function getStringDate()
{
    var d = new Date();
    return (d.getMonth()+1) + "/" + d.getDate() + "/" + getCurrentYear();
}

function updatePaymentType()
{
    if (document.donorForm.paymentType[0].checked)
    {
        document.donorForm.formtype.value = "Donation";
    }
    else if (document.donorForm.paymentType[1].checked)
    {
        document.donorForm.formtype.value = "check";
    }
}

function setFrequency()
{
	if (document.donorForm.rgsFrequency.value != "")
	{
		document.donorForm.rgsCreate.value = "true";
	}
	else
	{
		document.donorForm.rgsCreate.value = "";
	}
}

function getElementByName(eName)
{
    var e = null;

    for (var i = 0; i < document.donorForm.elements.length; i++)
    {
        if (document.donorForm.elements[i].name == eName)
        {
            e = document.donorForm.elements[i];
            break;
        }
    }

    return e;
}

function getElementStartsWithName(eName)
{
    var e = null;

    for (var i = 0; i < document.donorForm.elements.length; i++)
    {
        if (document.donorForm.elements[i].name.indexOf(eName) >= 0)
        {
            e = document.donorForm.elements[i];
            break;
        }
    }

    return e;
}

// page author must write a matrix variable "costs" as such
//
// var costs = new Array();
// costs[i] = new Array(amount, eventName, variableName, UDFname);
//
// e.g.
// var costs = new Array();
// costs[0] = new Array(25, "Event 1", "Activities", "Entity_SetElement|Activities|Event 1");
// costs[1] = new Array(50, "Event 2", "Activities", "Entity_SetElement|Activities|Event 2");
//
// in the page call writeCosts(costs, start, end, inputType)
// e.g. <script>writeCosts(costs, 0, 1, "radio")</script>
//
// in validation call getCosts(costs, baseFee)
function writeCosts(costs, start, end, inputType)
{
	for(i=start; i<(end + 1); i++)
	{
		document.write("<input type= \"" + inputType + "\" name=\"" + costs[i][2] + "\" value=\"" + costs[i][0] + "\">" + costs[i][1] + " - $" + costs[i][0] + "<br>");
		document.write("<input type=\"hidden\" name=\"" + costs[i][3] + "\">");
	}
}

function getCosts(costs, baseFee)
{
	var total = parseFloat(baseFee);
	for(i=0; i<costs.length; i++)
	{
		for(c=0; c<(document.donorForm.elements.length - 1); c++)
		{
			if(document.donorForm.elements[c+1].name == costs[i][3])
			{
				if(document.donorForm.elements[c].checked)
				{
					document.donorForm.elements[c+1].value = "true";
					total = total + parseFloat(document.donorForm.elements[c].value);
				}
				if(document.donorForm.elements[c].checked != true)
				{
						document.donorForm.elements[c+1].value = "false"
				}
			}
		}
	}
	document.donorForm.amount.value = total;
}

// this function changes fields from the donorForm into UDF format
// this will most likely be use when a UDF can only take one value
// 
// form requirements: hidden fields for the UDF's which follow the UDF naming conventions
//
// naming conventions: the UDF category will be the name and the UDF value will be the value.
// e.g. if a company has a UDF named Grades with values A, B, C, D, and F
// <input type="radio" name="Grades" value="A">A
// <input type="radio" name="Grades" value="B">B
// <input type="radio" name="Grades" value="C">C
// <input type="radio" name="Grades" value="D">D
// <input type="radio" name="Grades" value="F">F
// <input type="hidden" name="Entity_SetElement|Grades|A">
// <input type="hidden" name="Entity_SetElement|Grades|B">
// <input type="hidden" name="Entity_SetElement|Grades|C">
// <input type="hidden" name="Entity_SetElement|Grades|D">
// <input type="hidden" name="Entity_SetElement|Grades|F">
//
// possible input types are radio and select box
//
// <script>setUDFValue(document.donorForm.Grades, "Grades");</script>

function setUDFValue(fieldName, eventName)
{
	for (i=0; i < fieldName.length; i++)
	{
		if (fieldName[i].checked || fieldName[i].selected)
		{
			for (var c = 0; c < document.donorForm.elements.length; c++)
			{
				if (document.donorForm.elements[c].name.indexOf("_SetElement|" + eventName + "|" + fieldName[i].value) >= 0)
				{
					document.donorForm.elements[c].value = "true";
				}
			}
		}
		else if(fieldName[i].checked != true && fieldName[i].selected != true)
		{
			for (var c = 0; c < document.donorForm.elements.length; c++)
			{
				if (document.donorForm.elements[c].name.indexOf("_SetElement|" + eventName + "|" + fieldName[i].value) >= 0)
				{
					document.donorForm.elements[c].value = "false";
				}
			}
		}
	}
}

// this function changes fields from the donorForm into UDF format.
// this should only be used when a UDF can only take one value.
// 
// form requirements: hidden div for the udf
// Acceptable third parameters: Entity, Persona, JournalEntry
//
// naming conventions: the UDF category will be the name and the UDF value will be the value.
// e.g. if a org has a UDF named Grades with values A, B, C, D, and F
// <input type="radio" name="Grades" value="A">A
// <input type="radio" name="Grades" value="B">B
// <input type="radio" name="Grades" value="C">C
// <input type="radio" name="Grades" value="D">D
// <input type="radio" name="Grades" value="F">F
//
// possible input types are radio and select box
//
// <script>createUDFValue(document.donorForm.Grades, "Grades", "Entity", "gradesDiv");</script>
//
// The fourth parameter should be an unused element name.  This name will be used to dynamically
// create a div that will be appended to the form if the UDF has a selected value.

function createUDFValue(fieldName, udfName, appliesTo, divName)
{
	// Locate and clear div if found
	var udfDiv = document.getElementById(divName);
	if (udfDiv != null)
	{
		var copy = new Array();
		for (var i=0; i < udfDiv.childNodes.length; i++) copy.push(udfDiv.childNodes[i]);
		for (var i=0; i < copy.length; i++) udfDiv.removeChild(copy[i]);

		document.donorForm.appendChild(udfDiv);
	}

	for (i = 0; i < fieldName.length; i++)
	{
		if (fieldName[i].checked || fieldName[i].selected)
		{
			if (fieldName[i].value != "")
			{
				// Create div & append to form if not found
				if (udfDiv == null)
				{
					udfDiv = document.createElement("div");
					udfDiv.setAttribute("id", divName);
					document.donorForm.appendChild(udfDiv);
				}

				var name = appliesTo + "_SetElement|" + udfName + "|" + fieldName[i].value;
				
				// Append element to div
				var input = document.createElement("input");
				input.setAttribute("type", "hidden");
				input.setAttribute("name", name);
				input.setAttribute("value", "true");
				udfDiv.appendChild(input);
			}
			break;
		}
	}
}

function isRadioOptionSelected(radioField)
{
	for (i=0; i < radioField.length; i++)
	{
		if (radioField[i].checked) return true;
	}

	return false;
}


//This function writes the ssl certificate image to the page
function getSSL()
{
	document.write('<script src="https://siteseal.thawte.com/cgi/server/thawte_seal_generator.exe"><\/script>');
	//document.write('<!-- SSL -->');
}
