/*****
 * The validateForm() function checks to make sure that every field in
 * the order form has something in it.  It does not check the validity
 * of the the form entries; more rigorous validation is done on the
 * server side
 *****/
function validateForm()
{
	// The order form
	var orderForm = document.forms[0];
	// Flag to tell us if the form passed validation
	var validated = true;
	// Flag to tell us if the user filled in one of the two amounts
	var hasPledgeAmt = false;
	// The message displayed to the user if the form is missing input
	var errorMsg = "The following fields are required:\n\n";

	// This hash maps the form elements' html names to their user-friendly names
	var formElementNames = new Object();
	formElementNames.firstNameReq = "First name";
	formElementNames.lastNameReq = "Last name";
	formElementNames.addressReq = "Address";
	formElementNames.cityReq = "City";
	formElementNames.stateReq = "State";
	formElementNames.zipReq = "Zip code";
	formElementNames.emailReq = "Email";
	formElementNames.grantTypeReq = "Gift destination";
	formElementNames.oneTimeAmt = "One-time gift";
	formElementNames.paymentTypeReq = "Payment type";
	formElementNames.ccNumberReq = "Credit Card Number";
	formElementNames.expMonthReq = "Expiration Month";
	formElementNames.expYearReq = "Expiration Year";
	formElementNames.cccodeReq = "Card Security Code";

	for (var i = 0; i < orderForm.elements.length; i++)
	{
		// For each form element, check to see if it is required.
		//	If it is, make sure that it's filled out
		if (orderForm.elements[i].name.match(/Req$/) &&
			!orderForm.elements[i].value)
		{
			errorMsg += "* " + formElementNames[orderForm.elements[i].name] + "\n";
			validated = false;
		}
	}

	// If any of the sub-pledge fields is enabled, then it is required
	if (document.getElementById("grantTypeReq") &&
		document.getElementById("grantTypeReq").value == "endowIndSchool" && 
		!document.getElementById("school").value)
	{
		errorMsg += "* School\n";
		validated = false;
	}
		
	if (document.getElementById("grantTypeReq") &&
		document.getElementById("grantTypeReq").value == "fieldIntFund" &&
		!document.getElementById("foi").value)
	{
		errorMsg += "* Field of Interest Fund\n";
		validated = false;
	}

	if (document.getElementById("grantTypeReq") &&
		document.getElementById("grantTypeReq").value == "passFund" &&
		!document.getElementById("passthrough").value)
	{
		errorMsg += "* Passthrough Fund\n";
		validated = false;
	}

	// Also, the user has to fill out either a one-time gift amount, a semi-annual pledge,
	//	or an annual pledge
	if (document.getElementById("oneTimeAmt") &&
		document.getElementById("oneTimeAmt").value)
	{
		hasPledgeAmt = true;
	}
	else if (document.getElementById("oneTimeAmt") &&
			(document.getElementById("annualAmt").value &&
			document.getElementById("annualNum").value))
	{
		hasPledgeAmt = true;
	}
	
	// This if statement is just an ugly hack necessitated by the fact that I 
	//	use the same javascript file for both donor and donation forms.  If we
	//	are on the donor form, i.e. there is no oneTimeAmt or annualAmt field,
	//	then set hasPledgeAmt to true just to make the validator happy.
	if (!document.getElementById("oneTimeAmt") &&
		!document.getElementById("annualAmt") &&
		!document.getElementById("annualNum"))
	{
		hasPledgeAmt = true;
	}
	
	if (!hasPledgeAmt)
	{
		errorMsg += "* One-time gift, Semi-annual pledge, or Annual pledge\n";
		validated = false;
	}
	
	if (validated)
	{
		orderForm.submit();
	}
	else
	{
		errorMsg += "\nPlease correct the fields and re-submit the form";
		alert(errorMsg);
	}
}

/*****
 * The setSubFunds() method is called when the Gift Destination combo box value is changed.  It checks the value of the
 * Gift Destination, and if it is either:
 *	1) Endowment Fund for an individual school
 *	2) Field of Interest Fund
 *	3) Passthrough Fund
 *
 * then the appropriate sub-fund list should be unhidden and marked as bold
 *****/
function setSubFunds()
{
	var selectedValue = document.getElementById("grantTypeReq").options[document.getElementById("grantTypeReq").selectedIndex].childNodes[0].nodeValue;
	
	if (selectedValue == "Endowment Fund for an individual school")
	{
		document.getElementById("school").disabled = false;
		document.getElementById("school").style.backgroundColor = "#C39BCF";
		document.getElementById("schoolLabel").style.fontWeight = "bold";
	}
	else
	{
		document.getElementById("school").selectedIndex = 0;
		document.getElementById("school").disabled = true;
		document.getElementById("school").style.backgroundColor = "#aaaaaa";
		document.getElementById("schoolLabel").style.fontWeight = "normal";
	}
	
	if (selectedValue == "Field of Interest Fund")
	{
		document.getElementById("foi").disabled = false;
		document.getElementById("foi").style.backgroundColor = "#C39BCF";
		document.getElementById("foiLabel").style.fontWeight = "bold";
	}
	else
	{
		document.getElementById("foi").selectedIndex = 0;
		document.getElementById("foi").disabled = true;
		document.getElementById("foi").style.backgroundColor = "#aaaaaa";
		document.getElementById("foiLabel").style.fontWeight = "normal";
	}
	
	if (selectedValue == "Passthrough Fund")
	{
		document.getElementById("passthrough").disabled = false;
		document.getElementById("passthrough").style.backgroundColor = "#C39BCF";
		document.getElementById("passthroughLabel").style.fontWeight = "bold";
	}
	else
	{
		document.getElementById("passthrough").selectedIndex = 0;
		document.getElementById("passthrough").disabled = true;
		document.getElementById("passthrough").style.backgroundColor = "#aaaaaa";
		document.getElementById("passthroughLabel").style.fontWeight = "normal";
	}
}

/*****
 * The calculateTotal() method calculates the total amount of an annual or semi-annual pledge and sets
 * the value of either the semiAnnualTotal or annualTotal field.  The installmentType argument is a string
 * that should be either "semiAnnual" or "annual", which specifies which installment type is to be calculated.
 *****/
function calculateTotal(installmentType)
{
	var amount = document.getElementById(installmentType + "Amt").value;
	var numInstallments = document.getElementById(installmentType + "Num").value;
	var total = amount * numInstallments;
	document.getElementById(installmentType + "Total").value = total.toFixed(2);
}

/*****
 * Searches the URL after the question mark and looks for a "name=value" pair
 * where "name" is the argName argument.  So, if we expect a url like
 * "http://www.fmps.org/edonate.html?type=isei", then to get the type parameter
 * we would call getUrlArg("type").  In this example, the return value would be
 * "isei".
 *
 * @param argName   The name of the URL parameter to retrieve.
 * @return  The value of the parameter specified in argName, or undefined if the
 *          specified parameter does not exist in the document's URL.
 *****/
function getUrlArg(argName)
{
    var argValue = undefined;   /* This is the value we will return */
    var urlArgs = location.search.substring(1);
    var pairs = urlArgs.split("&");
    for (var i = 0; i < pairs.length; i++)
    {
        var pos = pairs[i].indexOf("=");
        if (pos != -1 && pairs[i].substring(0, pos) == argName)
        {
            argValue = pairs[i].substring(pos + 1);
        }
    }
    
    return argValue;
}

/*****
 * The purpose of this function is to allow users to specify the default value
 * for certain form elements by passing arguments in the page URL.  Currently,
 * only the logic for individual school endowment funds is implemented.
 *****/
function loadDefaults()
{
    var typeArg = getUrlArg("type");
    
    /* If the 'type' argument is 'isei' or 'pass', then we will set the Gift
        Designation form element */
    if (typeArg == "isei")
    {
        listValue = "endowIndSchool";
    }
    else if (typeArg == "pass")
    {
        listValue = "passFund"
    }
    
    if (listValue != undefined)
    {
        var listIndex;
        for (var i = 1; i < document.getElementById("grantTypeReq").options.length; i++)
        {
            if (document.getElementById("grantTypeReq").options[i].value == listValue)
            {
                listIndex = i;
            }
        }
        
        if (listIndex)
        {
            document.getElementById("grantTypeReq").selectedIndex = listIndex;
        }
    }
    
    /* If the URL also includes a 'school' argument, then we'll attempt to set
        the proper school as well */
    if (listValue = "endowIndSchool" && getUrlArg("school"))
    {
        var schoolArg = getUrlArg("school");
        /* Build an array of valid school arguments and their corresponding
            form values */
        var schoolValues = new Object();
        schoolValues.affiliated = "Affiliated Alternatives";
        schoolValues.allis = "Allis Elementary";
        schoolValues.blackhawk = "Black Hawk Middle";
        schoolValues.chavez = "Chavez Elementary";
        schoolValues.cherokee = "Cherokee Middle ";
        schoolValues.crestwood = "Crestwood Elementary";
        schoolValues.east = "East High";
        schoolValues.elvehjem = "Elvehjem Elementary";
        schoolValues.emerson = "Emerson Elementary";
        schoolValues.falk = "Falk Elementary";
        schoolValues.franklin = "Franklin-Randall Elementary";
        schoolValues.glendale = "Glendale Elementary";
        schoolValues.gompers = "Gompers Elementary";
        schoolValues.hamilton = "Hamilton Middle";
        schoolValues.hawthorne = "Hawthorne Elementary";
        schoolValues.huegel = "Huegel Elementary";
        schoolValues.jefferson = "Jefferson Middle";
        schoolValues.kennedy = "Kennedy Elementary";
        schoolValues.lafollete = "LaFollette High";
        schoolValues.lakeview = "Lake View Elementary";
        schoolValues.lapham = "Lapham-Marquette Elementary";
        schoolValues.leopole = "Leopold Elementary";
        schoolValues.lindbergh = "Lindbergh Elementary";
        schoolValues.lowell = "Lowell Elementary";
        schoolValues.memorial = "Memorial High";
        schoolValues.mendota = "Mendota Elementary";
        schoolValues.midvale = "Midvale-Lincoln Elementary";
        schoolValues.muir = "Muir Elementary";
        schoolValues.nuestro = "Nuestro Mundo";
        schoolValues.okeeffe = "O'Keeffe Middle ";
        schoolValues.orchard = "Orchard Ridge Elementary";
        schoolValues.sandburg = "Sandburg Elementary";
        schoolValues.schenk = "Schenk Elementary";
        schoolValues.sennett = "Sennett Middle";
        schoolValues.shabazz = "Shabazz High ";
        schoolValues.sherman = "Sherman Middle";
        schoolValues.shorewood = "Shorewood Elementary";
        schoolValues.springharbor = "Spring Harbor Middle";
        schoolValues.stephens = "Stephens Elementary";
        schoolValues.thoreau = "Thoreau Elementary ";
        schoolValues.toki = "Toki Middle";
        schoolValues.vanhise = "Van Hise Elementary";
        schoolValues.west = "West High";
        schoolValues.whitehorse = "Whitehorse Middle";
        schoolValues.wright = "Wright Middle";
        
        if (schoolValues[schoolArg])
        {
            /* Find a matching school in the list */
            for (var i = 1; i < document.getElementById("school").options.length; i++)
            {
                if (document.getElementById("school").options[i].value == schoolValues[schoolArg])
                {
                    document.getElementById("school").selectedIndex = i;
                }
            }
        }
    }
        
    /* If the URL includes a passthrough fund, then set it */
    if (typeArg == "pass" && getUrlArg("fund"))
    {
        var fundArg = getUrlArg("fund");
        var fundValues = new Object();
        
        fundValues.allisalfa = "Allis ALFA Fund";
        fundValues.allissign = "Allis School Sign Board";
        fundValues.aristosscholar = "Aristos Scholars Program";
        fundValues.carp = "Classroom Action Research Program";
        fundValues.easttheater = "East High Theater Renovation";
        fundValues.elvplayground = "Elvehjem Playground Improvement Club";
        fundValues.westdrama = "Friends of West High Drama Fund";
        fundValues.westsoccer = "Friends of West High Soccer Fund";
        fundValues.principals = "Grow Our Own Principals Fund";
        fundValues.marypburke = "Mary P. Burke Fund";
        fundValues.memorialart = "Memorial Art Dept";
        fundValues.memorialgym = "Memorial Gym Floor Resurfacing";
        fundValues.childhealth = "Neighborhood Child Health Coalition Fund";
        fundValues.leadtheway = "Project Lead The Way";
        fundValues.west61 = "West Class of '61 Education";
        fundValues.west75 = "West High 75th Anniversary Fund";
        fundValues.westcapital = "West High Capital Campaign";
        fundValues.westpool = "West High Community Pool";
        fundValues.westtennis = "West High Tennis Courts Fund";
        
        if (fundValues[fundArg])
        {
            /* Find a matching passthrough fund in the list */
            for (var i = 1; i < document.getElementById("passthrough").options.length; i++)
            {
                if (document.getElementById("passthrough").options[i].value == fundValues[fundArg])
                {
                    document.getElementById("passthrough").selectedIndex = i;
                }
            }
        }
    }
    
    /* Setting the selectedIndex property does not trigger the onchange
    event, so we have to manually call setSubFunds() */
    setSubFunds();
}

function CSCodeHelp() {
	newwindow=window.open('cardseccode.html','CreditCardSec','height=485,width=400');
	if (window.focus) {newwindow.focus()}
	return false;
}
