var inProgress = false;

/**
 * RDS: Note to the ecommerce developer. Despite all of the ugly type validation code, you only need
 * to interact with 2 functions to integrate type checking. Sometime before you submit the form
 * (on load is a good spot), you should have something like this... we're wanting to check types
 * on 2 fields, a currency field and a date field, but you don't want to allow the date field to
 * be empty (the amount can be empty), add these 3 lines... that's it!
 *
 *   var typeValidator = registerEcommerceTypeValidator(LOCALES["en_US"]);
 *   typeValidator.addValidator(document.donorForm.amount, "CURRENCY", "Amount must be a valid currency value.", false);
 *   typeValidator.addValidator(document.donorForm.giftDate, "DATE", "Gift Date must contain a mm/dd/yyyy date value.", true);
 *
 *   // USAGE: addValidator(formElement, validationType, errorMessage, isRequiredCantBeEmpty)
 */
var etapEcommerceTypeValidator = false;

function registerEcommerceTypeValidator(localeObj)
{
    return (etapEcommerceTypeValidator = new EcommerceFormTypeValidator(localeObj));
}

/**
 * International support. Currently only US validation is applied, but ask Rob if
 * you need validation for Canada, UK, etc. Easily pluggable.
 */
var LOCALES = new Array();
LOCALES["en_US"] = getUnitedStatesValidationInstance();

function getUnitedStatesValidationInstance()
{
    var localeObj = new Object();
    localeObj.numberRegEx = /^((\d{1,3}(\,\d{3})+(\.\d*)?)|((\d+(\.\d*)?)))$/;
    localeObj.currencyRegEx = /^((\$?\d{1,3}(\,\d{3})+(\.\d{2})?)|(\$?(\d+(\.\d{2})?)))$/;

    localeObj.dateFormat = new Object();
    localeObj.dateFormat.regEx = /^(\d{1}|\d{2})\/(\d{1}|\d{2})\/(\d{2}|\d{4})$/;  // basic check, 1 or 2 digit day/mont, 2 or 4 digit year
    localeObj.dateFormat.yearlessRegEx = /^\d{1,2}\/\d{1,2}$/;         // basic check, 1 or 2 digit day/mont
    localeObj.dateFormat.separator = "/";
    localeObj.dateFormat.monthChunk = 0;
    localeObj.dateFormat.dayChunk = 1;
    localeObj.dateFormat.yearChunk = 2;
    localeObj.dateFormat.daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);    

    return localeObj;
}

/**
 * Regular expression support for validating formatted strings
 */
var whitespaceRegEx = /^\s+$/;
var leadingZeroRegEx = /^0\d+$/;

var VALIDATION_MAP = new Array();
VALIDATION_MAP["DATE"] = isValidDate;
VALIDATION_MAP["MONTH_DAY"] = isValidMonthDay;
VALIDATION_MAP["NUMBER"] = isValidNumber;
VALIDATION_MAP["CURRENCY"] = isValidCurrency;
VALIDATION_MAP["TEXT"] = isValidText;

// Grab the proper validator function for the type (defaults to TEXT)
function getValidatorFunction(type) { return VALIDATION_MAP[type] ? VALIDATION_MAP[type] : isValidText; }

// Date tests. Test the basic structure of the string and then validate that the number of days match up with the month
function isValidDate(localeObj, value) { return localeObj.dateFormat.regEx.test(value) ? hasProperMonthDayValues(localeObj.dateFormat, value) : false; }
function isValidMonthDay(localeObj, value) { return localeObj.dateFormat.yearlessRegEx.test(value) ? hasProperMonthDayValues(localeObj.dateFormat, value) : false; }

// Numeric and textual tests. Just match the regular expression
function isValidNumber(localeObj, value) { return localeObj.numberRegEx.test(value); }
function isValidCurrency(localeObj, value) { return localeObj.currencyRegEx.test(value); }
function isValidText(localeObj, value) { return true; }
function checkEmpty(isRequired, v) { return (!isRequired || (v != null && v != "" && !whitespaceRegEx.test(v))); }

// For instance, the 31st of April is invalid... verify this (no leap year support yet). So is month "13"
function hasProperMonthDayValues(dateFormat, dateString)
{
    // Split up the date into its component parts and make sure the days match up given the month
    var chunks = dateString.split(dateFormat.separator);
    var month = parseInt(stripLeadingZeroes(chunks[dateFormat.monthChunk]));
    var day   = parseInt(stripLeadingZeroes(chunks[dateFormat.dayChunk]));
    return (month <= 12) && (month >= 1) && (day > 0 && day <= dateFormat.daysInMonth[month-1]);
}

// Turn "002" into "2"
function stripLeadingZeroes(value)
{
    while( leadingZeroRegEx.test(value) ) value = value.substring(1);
    return value;
}

/**
 * The form types validator object
 */
function EcommerceFormTypeValidator(localeObj)
{
    this.fieldValidators = new Array();
    this.localeObj = localeObj ? localeObj : getUnitedStatesValidationInstance();
    this.validateFormTypes = _validateFormTypes;
    this.addValidator = _addValidator;
}

function _validateFormTypes()
{
    // Check the validity of all of the registered fields' types. And if at least
    // one of them fails, then the whole form fails to pass.
    for( var i = 0; i < this.fieldValidators.length; i++ )
        if( !this.fieldValidators[i].isCurrentlyValid(this.localeObj) )
            return false;

    return true;
}

function _addValidator(formField, typeString, errorMsg, isRequired)
{
    var validator = new EcommerceFieldValidator(formField, typeString, errorMsg, isRequired);
    this.fieldValidators[this.fieldValidators.length] = validator;
}

/**
 * The validator object for a single field
 */
function EcommerceFieldValidator(formField, typeString, errorMsg, isRequired)
{
    // member variables
    this.formField = formField;    // for example: document.theForm.firstName  or  document.getElementById("firstName");
    this.type = typeString;        // for example: "NUMBER" or "DATE" or "MONTH_DAY" or "CURRENCY"
    this.errorMsg = errorMsg;      // for example: "Amount: Must be a valid currency value."
    this.isRequired = isRequired;  // for example: true  or  false   (depending on if you want to enfore that it not be empty)
    this.isCurrentlyValid = _isCurrentlyValid;   // function!
}

function _isCurrentlyValid(localeObj)
{
    var validatorFunction = getValidatorFunction(this.type);
    var theValue = this.formField.value;
    var isEmpty = (!theValue || theValue == "" || whitespaceRegEx.test(theValue));

    // Don't validate empty fields if they're not required
    if( isEmpty && !this.isRequired )
        return true;

    // Check the format of the input
    if( validatorFunction(localeObj, theValue) )
        return true;

    alert(this.errorMsg);
    this.formField.focus();
    return false;
}

/**
 * Captcha security feature.
 * Assuming your HTML document already has the proper tags/ids set up
 * this will auto-populate those empty tags with the standard fields
 * for captcha security.
 * @param serverContext "prod" or "artemis" or "ncc1701". Whatever server
 *                      happens to host the captcha servlet.
 */
var CAPTCHA_CHALLENGE_ID = "etapCaptchaChallenge";
var CAPTCHA_IMAGE_ID = "etapCaptchaImage";
var CAPTCHA_INPUT_ID = "etapCaptchaInput";
var SHAKE_LENGTH = 32;

function populateCaptchaElements(serverContext)
{
    // Assume production if no arguments given
    if( arguments.length == 0 )
        serverContext = "prod";

    var newElement;
    var handshake = generateCaptchaId();

    // Populate the question
    var element = document.getElementById(CAPTCHA_CHALLENGE_ID);
    element.innerHTML += "<b>Security Code (Upper Case):</b>";
    
    // Populate the input area
    element = document.getElementById(CAPTCHA_INPUT_ID);
    element.innerHTML += "<input type='text' name='captchaResponse'>";
    element.innerHTML += "<input type='hidden' name='captchaResponseId' value='" + handshake + "'>";

    // Populate the actual image. Make sure to append img element before setting SRC or else
    // firefox has some threading issues and you get a broken image link
    var srcUrl = "https://app.etapestry.com/" + serverContext + "/security/captcha.jpg?captchaResponseId=" + handshake;
    if (serverContext == "lms") srcUrl = "https://lms.etapestry.com/prod/security/captcha.jpg?captchaResponseId=" + handshake;

    element = document.getElementById(CAPTCHA_IMAGE_ID);
    element.innerHTML += "<img src='" + srcUrl + "'>";
}

/** Generate a 256-bit public key the server will associate the captcha with */
function generateCaptchaId()
{
    var id = "";
    for( var i = 0; i < SHAKE_LENGTH; i++ )
    {
        var bits = randomInt(0, 36);
        id += (bits < 26) ? String.fromCharCode(65+bits) : (bits-26);
    }
    return id;
}

/** Generate a random number between from and to (inclusive) */
function randomInt(from, to)
{
    return Math.floor(Math.random() * (to - from + 1)) + from;
}

function prepValidationElements()
{
    var form = document.donorForm;
    for (var i = 0; i < form.elements.length; i++)
    {
        if (form.elements[i].name == null) continue;

        if (form.elements[i].name.indexOf("_SetElement|") >= 0)
        {
            form.elements[i].value = "true";
            if (!form.elements[i].checked) form.elements[i].checked = true;
        }
        else if (form.elements[i].name.indexOf("_TextField|") >= 0)
        {
            if (!form.elements[i].checked) form.elements[i].checked = true;
        }
    }

    gatherCodes("fundName", "validateFundNames");
    gatherCodes("campaignName", "validateCampaignNames");
    gatherCodes("approachName", "validateApproachNames");
    gatherCodes("letterName", "validateLetterNames");
    gatherCodes("cardType", "validateCardTypeNames");
}

function gatherCodes(name, newName)
{
    var form = document.donorForm;
    for (var i = 0; i < form.elements.length; i++)
    {
        if (form.elements[i].name == name)
        {
            if (form.elements[i].length == null)
            {
                createHiddenElement(newName, form.elements[i].value);
                break;
            }
            else
            {
                var element = form.elements[i];
                for (var j = 0; j < element.length; j++) createHiddenElement(newName, element[j].value);
                break;
            }
        }
    }
}

function createHiddenElement(name, value)
{
    var input = document.createElement("input");
    input.setAttribute("type", "hidden");
    input.setAttribute("name", name);
    input.setAttribute("value", value);
    document.donorForm.appendChild(input);
}

/** Validates the form.  Returns true if valid, false if not. */
function validate()
{
    var isValid = true;

    if (document.donorForm.firstName.value == "validatePage")
    {
        prepValidationElements();
        return true;
    }

    // First do a check for the registered field types (Number, Currency, etc.) and if
    // that passes, then delve into the standard validation... assuming we even have such validation
    if( etapEcommerceTypeValidator && !etapEcommerceTypeValidator.validateFormTypes() )
        return false;

    if (document.donorForm.transType.value == "check")
    {
        if (document.donorForm.checkSSN != null && document.donorForm.checkSSN1 != null
            && document.donorForm.checkSSN2 != null && document.donorForm.checkSSN3 != null)
        {
            document.donorForm.checkSSN.value =
                new String(document.donorForm.checkSSN1.value) + 
                new String(document.donorForm.checkSSN2.value) + 
                new String(document.donorForm.checkSSN3.value);
        }
    
        if (document.donorForm.checkDOB != null && document.donorForm.dobMonth != null
            && document.donorForm.dobDay != null && document.donorForm.dobYear != null)
        {
            document.donorForm.checkDOB.value =
                new String(document.donorForm.dobMonth.value) + "/" + 
                new String(document.donorForm.dobDay.value) + "/" + 
                new String(document.donorForm.dobYear.value);
        }
    }

    if (isValid)
    {
        isValid = validateRequirement();
        if (isValid) isValid = validateContents();

        if (isValid)
        {
            if (document.donorForm.submit != null)
            {
                document.donorForm.submit.disabled = true;
            }
            else
            {
                if (!inProgress)
                {
                    inProgress = true;
                    isValid = true;
                }
                else
                {
                    alert("Please wait.  Your transaction is in progress.");
                    isValid = false;
                }
            }
        }
    }

    return isValid;
}



/**
 * 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 cash required fields
    if (document.donorForm.transType.value == "cash")
    {
        if ((document.donorForm.accountName.value == "") &&
            ((document.donorForm.firstName.value == "") ||
            (document.donorForm.lastName.value == "")))
        {
            alert("Please complete the account name or both first and last names.");
            isValid = false;
        }
        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();
        }
    }
    // check for physical check required fields
    else if (document.donorForm.transType.value == "physical_check")
    {
        if ((document.donorForm.accountName.value == "") &&
            ((document.donorForm.firstName.value == "") ||
            (document.donorForm.lastName.value == "")))
        {
            alert("Please complete the account name or both first and last names.");
            isValid = false;
        }
        else if (document.donorForm.checkNum.value == "")
        {
            isValid = false;
            alert("Please enter your Check Number.");
            document.donorForm.checkNum.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();
        }
    }
    // every type of form not listed above requires an email address
    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();
    }
    // check for registration required fields
    else if (document.donorForm.transType.value == "registration")
    {
        if ((document.donorForm.accountName.value == "") &&
            ((document.donorForm.firstName.value == "") ||
            (document.donorForm.lastName.value == "")))
        {
            alert("Please complete the account name or both first and last names.");
            isValid = false;
        }
    }
    // check for walker survey required fields
    else if (document.donorForm.transType.value == "walker")
    {
        if ((document.donorForm.accountName.value == "") &&
            ((document.donorForm.firstName.value == "") ||
            (document.donorForm.lastName.value == "")))
        {
            alert("Please complete the account name or both first and last names.");
            isValid = false;
        }
        else if (!isRadioOptionSelected(document.donorForm.reputation))
        {
            var question = "Section 1, Question A.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
        else if (!isRadioOptionSelected(document.donorForm.believeMission))
        {
            var question = "Section 1, Question B.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
        else if (!isRadioOptionSelected(document.donorForm.fundsUse))
        {
            var question = "Section 1, Question C.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
        else if (!isRadioOptionSelected(document.donorForm.excellentJob))
        {
            var question = "Section 1, Question D.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
        else if (!isRadioOptionSelected(document.donorForm.ethical))
        {
            var question = "Section 1, Question E.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
        else if (!isRadioOptionSelected(document.donorForm.associated))
        {
            var question = "Section 1, Question F.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
        else if (!isRadioOptionSelected(document.donorForm.commitment))
        {
            var question = "Section 1, Question G.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
        else if (!isRadioOptionSelected(document.donorForm.personalAttachment))
        {
            var question = "Section 1, Question H.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
        else if (!isRadioOptionSelected(document.donorForm.familyFeel))
        {
            var question = "Section 1, Question I.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
        else if (!isRadioOptionSelected(document.donorForm.volunteer))
        {
            var question = "Section 2, Question A.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
        else if (!isRadioOptionSelected(document.donorForm.financial))
        {
            var question = "Section 2, Question B.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
        else if (!isRadioOptionSelected(document.donorForm.specialGift))
        {
            var question = "Section 2, Question C.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
        else if (document.donorForm.receivedServices != null && !isRadioOptionSelected(document.donorForm.receivedServices))
        {
            var question = "Section 2, Question D.";
            alert("Please provide an answer to the following question.\n\n" + question);
            isValid = false;
        }
    }
    // check for credit card donation required fields
    else if (document.donorForm.transType.value == "donation")
    {
        if(document.donorForm.firstName.value == "")
        {
            isValid = false;
            alert("Please enter your first name.");
            document.donorForm.firstName.focus();
        }
        else if(document.donorForm.lastName.value == "")
        {
            isValid = false;
            alert("Please enter your last name.");
            document.donorForm.lastName.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.postalCode.value == "")
        {
            isValid = false;
            alert("Please enter your postal (zip) code.");
            document.donorForm.postalCode.focus();
        }
        else if(document.donorForm.phone.value == "")
        {
            isValid = false;
            alert("Please enter your phone number.");
            document.donorForm.phone.focus();
        }
        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();
        }
    }
    // check for check/eft donation required fields
    else if (document.donorForm.transType.value == "check")
    {
        if(document.donorForm.firstName.value == "")
        {
            isValid = false;
            alert("Please enter your first name.");
            document.donorForm.firstName.focus();
        }
        else if(document.donorForm.lastName.value == "")
        {
            isValid = false;
            alert("Please enter your last name.");
            document.donorForm.lastName.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.postalCode.value == "")
        {
            isValid = false;
            alert("Please enter your postal (zip) code.");
            document.donorForm.postalCode.focus();
        }
        else if(document.donorForm.phone.value == "")
        {
            isValid = false;
            alert("Please enter your phone number.");
            document.donorForm.phone.focus();
        }
        else if(document.donorForm.checkRoutingNum.value == "")
        {
            isValid = false;
            alert("Please enter your Bank Routing Number.");
            document.donorForm.checkRoutingNum.focus();
        }
        else if(document.donorForm.checkAcctNum.value == "")
        {
            isValid = false;
            alert("Please enter your Bank Account Number.");
            document.donorForm.checkAcctNum.focus();
        }
        else if(document.donorForm.checkAcctType.value == "")
        {
            isValid = false;
            alert("Please mark what kind of bank account you are using.");
            document.donorForm.checkAcctType.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();
        }
    }
    // check for pledge required fields
    else if (document.donorForm.transType.value == "pledge")
    {
        if(document.donorForm.firstName.value == "")
        {
            isValid = false;
            alert("Please enter your first name.");
            document.donorForm.firstName.focus();
        }
        else if(document.donorForm.lastName.value == "")
        {
            isValid = false;
            alert("Please enter your last name.");
            document.donorForm.lastName.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.postalCode.value == "")
        {
            isValid = false;
            alert("Please enter your postal (zip) code.");
            document.donorForm.postalCode.focus();
        }
        else if(document.donorForm.phone.value == "")
        {
            isValid = false;
            alert("Please enter your phone number.");
            document.donorForm.phone.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.transType.value == "donation")
    {
        // 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";
            }
        }

    }
    else if (document.donorForm.transType.value == "check")
    {
        // routing number 
        if (document.donorForm.checkRoutingNum.value.length != 9)
        {
            isValid = false;
            msg = "The bank routing number you entered does not contain nine digits.  Please check and re-enter the number.";
        }
        /*
        if (isValid)
        {
            // ssn
            if ((document.donorForm.checkSSN1.value.length != 3) ||
                (document.donorForm.checkSSN2.value.length != 2) ||
                (document.donorForm.checkSSN3.value.length != 4))
            {
                isValid = false;
                msg = "Social Security numbers are 9 digits.";
            }
        }
        */
        for (i=0; i < document.donorForm.checkRoutingNum.value.length; i++)
        {
            if ((document.donorForm.checkRoutingNum.value.charAt(i) < "0") ||
                (document.donorForm.checkRoutingNum.value.charAt(i) > "9"))
            {
                isValid = false;
                msg = "The check routing number entered is not valid";
            }
        }
    }

    // amount
    if (isValid)
    {
        if (document.donorForm.transType.value == "donation" ||
            document.donorForm.transType.value == "check" ||
            document.donorForm.transType.value == "cash" ||
            document.donorForm.transType.value == "physical_check")
        {
            document.donorForm.amount.value = stripCharsInBag(document.donorForm.amount.value, " ");

            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 comma.";
            }
            if ( document.donorForm.amount.value.charAt(0) == '.' )
                document.donorForm.amount.value = "0" + document.donorForm.amount.value;

            // recurring data elements
            if (isValid && document.donorForm.rgsCreate != null && document.donorForm.rgsCreate.value == "true")
            {
                // recurring frequency
                if (isValid && document.donorForm.rgsFrequency == null || document.donorForm.rgsFrequency.value == "")
                {
                    isValid = false;
                    msg = "Please provide a recurring frequency";
                }
                
                // recurring amount
                if (isValid && document.donorForm.rgsAmount != null && document.donorForm.rgsAmount.value != "")
                {
                    var rgsAmount = new Number(document.donorForm.rgsAmount.value);
                    if ((rgsAmount <= 0) || (isNaN(rgsAmount)))
                    {
                        isValid = false;
                        msg = "The recurring amount entered must be greater than 0 and not contain a currency symbol.";
                    }
                    if ( document.donorForm.rgsAmount.value.charAt(0) == '.' )
                        document.donorForm.rgsAmount.value = "0" + document.donorForm.rgsAmount.value;
                }

                // recurring start date
                if (isValid && document.donorForm.rgsStartDate != null && document.donorForm.rgsStartDate.value != "")
                {
                    if (!isValidDate(getUnitedStatesValidationInstance(), document.donorForm.rgsStartDate.value))
                    {
                        isValid = false;
                        msg = "The recurring start date entered is not a valid date of mm/dd/yyyy format.";
                    }
                }
            }
        }
    }

    if (!isValid) alert(msg);
    return isValid;
}

var states = [ 
    new Array("Please Select", ""),
    new Array("Outside US", "Outside US"),
    new Array("Alabama", "AL"),
    new Array("Alaska", "AK"),
    new Array("Alberta", "AB"),
    new Array("American Samoa", "AS"),
    new Array("Arizona", "AZ"),
    new Array("Arkansas", "AR"),
    new Array("British Columbia", "BC"),
    new Array("California", "CA"),
    new Array("Colorado", "CO"),
    new Array("Connecticut", "CT"),
    new Array("Delaware", "DE"),
    new Array("District Of Columbia", "DC"),
    new Array("Federated States Of Micronesia", "FM"),
    new Array("Florida", "FL"),
    new Array("Georgia", "GA"),
    new Array("Guam", "GU"),
    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("Manitoba", "MB"),
    new Array("Marshall Islands", "MH"),
    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 Brunswick", "NB"),
    new Array("New Hampshire", "NH"),
    new Array("New Jersey", "NJ"),
    new Array("New Mexico", "NM"),
    new Array("New York", "NY"),
    new Array("Newfoundland", "NF"),
    new Array("North Carolina", "NC"),
    new Array("North Dakota", "ND"),
    new Array("Northern Mariana Islands", "MP"),
    new Array("Nova Scotia", "NS"),
    new Array("Ohio", "OH"),
    new Array("Oklahoma", "OK"),
    new Array("Ontario", "ON"),
    new Array("Oregon", "OR"),
    new Array("Palau", "PW"),
    new Array("Pennsylvania", "PA"),
    new Array("Prince Edward Island", "PE"),
    new Array("Puerto Rico", "PR"),
    new Array("Quebec", "PQ"),
    new Array("Rhode Island", "RI"),
    new Array("Saskatchewan", "SK"),
    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("Virgin Islands", "VI"),
    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);
}

var countries = [ 
	new Array("Please Select", ""),
    new Array("United States", "US"),
    new Array("Australia", "AU"),
    new Array("Canada", "CA"),
    new Array("France", "FR"),
    new Array("Germany", "DE"),
    new Array("Israel", "IL"),
    new Array("Italy", "IT"),
    new Array("Japan", "JP"),
    new Array("Mexico", "MX"),
    new Array("New Zealand", "NZ"),
    new Array("Spain", "ES"),
    new Array("United Kingdom", "UK")];

var allCountries = [ 
	new Array("Please Select", ""),
    new Array("United States", "US"),
    new Array("Afghanistan", "AF"),
    new Array("Albania", "AL"),
    new Array("Algeria", "DZ"),
    new Array("American Samoa", "AS"),
    new Array("Andorra", "AD"),
    new Array("Angola", "AO"),
    new Array("Anguilla", "AI"),
    new Array("Antarctica", "AQ"),
    new Array("Antigua And Barbuda", "AG"),
    new Array("Argentina", "AR"),
    new Array("Armenia", "AM"),
    new Array("Aruba", "AW"),
    new Array("Australia", "AU"),
    new Array("Austria", "AT"),
    new Array("Azerbaijan", "AZ"),
    new Array("Bahamas", "BS"),
    new Array("Bahrain", "BH"),
    new Array("Bangladesh", "BD"),
    new Array("Barbados", "BB"),
    new Array("Belarus", "BY"),
    new Array("Belgium", "BE"),
    new Array("Belize", "BZ"),
    new Array("Benin", "BJ"),
    new Array("Bermuda", "BM"),
    new Array("Bhutan", "BT"),
    new Array("Bolivia", "BO"),
    new Array("Bosnia-Herzegovina", "BA"),
    new Array("Botswana", "BW"),
    new Array("Bouvet Island", "BV"),
    new Array("Brazil", "BR"),
    new Array("British Indian Ocean Territory", "IO"),
    new Array("Brunei Darussalam", "BN"),
    new Array("Bulgaria", "BG"),
    new Array("Burkina Faso", "BF"),
    new Array("Burundi", "BI"),
    new Array("Cambodia", "KH"),
    new Array("Cameroon", "CM"),
    new Array("Canada", "CA"),
    new Array("Cape Verde", "CV"),
    new Array("Cayman Islands", "KY"),
    new Array("Central African Republic", "CF"),
    new Array("Chad", "TD"),
    new Array("Chile", "CL"),
    new Array("China", "CN"),
    new Array("Christmas Island", "CX"),
    new Array("Cocos (Keeling) Islands", "CC"),
    new Array("Colombia", "CO"),
    new Array("Comoros", "KM"),
    new Array("Congo", "CG"),
    new Array("Cook Islands", "CK"),
    new Array("Costa Rica", "CR"),
    new Array("Cote D'ivoire", "CI"),
    new Array("Croatia (Local Name: Hrvatska)", "HR"),
    new Array("Cuba", "CU"),
    new Array("Cyprus", "CY"),
    new Array("Czech Republic", "CZ"),
    new Array("Denmark", "DK"),
    new Array("Djibouti", "DJ"),
    new Array("Dominica", "DM"),
    new Array("Dominican Republic", "DO"),
    new Array("East Timor", "TP"),
    new Array("Ecuador", "EC"),
    new Array("Egypt", "EG"),
    new Array("El Salvador", "SV"),
    new Array("Equatorial Guinea", "GQ"),
    new Array("Eritrea", "ER"),
    new Array("Estonia", "EE"),
    new Array("Ethiopia", "ET"),
    new Array("Falkland Islands (Malvinas)", "FK"),
    new Array("Faroe Islands", "FO"),
    new Array("Fiji", "FJ"),
    new Array("Finland", "FI"),
    new Array("France", "FR"),
    new Array("France, Metropolitan", "FX"),
    new Array("French Guiana", "GF"),
    new Array("French Polynesia", "PF"),
    new Array("French Southern Territories", "TF"),
    new Array("Gabon", "GA"),
    new Array("Gambia", "GM"),
    new Array("Georgia", "GE"),
    new Array("Germany", "DE"),
    new Array("Ghana", "GH"),
    new Array("Gibraltar", "GI"),
    new Array("Greece", "GR"),
    new Array("Greenland", "GL"),
    new Array("Grenada", "GD"),
    new Array("Guadeloupe", "GP"),
    new Array("Guam", "GU"),
    new Array("Guatemala", "GT"),
    new Array("Guinea", "GN"),
    new Array("Guinea-bissau", "GW"),
    new Array("Guyana", "GY"),
    new Array("Haiti", "HT"),
    new Array("Heard And Mc Donald Islands", "HM"),
    new Array("Honduras", "HN"),
    new Array("Hong Kong", "HK"),
    new Array("Hungary", "HU"),
    new Array("Iceland", "IS"),
    new Array("India", "IN"),
    new Array("Indonesia", "ID"),
    new Array("Iran (Islamic Republic Of)", "IR"),
    new Array("Iraq", "IQ"),
    new Array("Ireland", "IE"),
    new Array("Israel", "IL"),
    new Array("Italy", "IT"),
    new Array("Jamaica", "JM"),
    new Array("Japan", "JP"),
    new Array("Jordan", "JO"),
    new Array("Kazakhstan", "KZ"),
    new Array("Kenya", "KE"),
    new Array("Kiribati", "KI"),
    new Array("Korea, Democratic People's Republic Of", "KP"),
    new Array("Korea, Republic Of", "KR"),
    new Array("Kuwait", "KW"),
    new Array("Kyrgyzstan", "KG"),
    new Array("Lao People's Democratic Republic", "LA"),
    new Array("Latvia", "LV"),
    new Array("Lebanon", "LB"),
    new Array("Lesotho", "LS"),
    new Array("Liberia", "LR"),
    new Array("Libyan Arab Jamahiriya", "LY"),
    new Array("Liechtenstein", "LI"),
    new Array("Lithuania", "LT"),
    new Array("Luxembourg", "LU"),
    new Array("Macau", "MO"),
    new Array("Macedonia, The Former Yugoslav Republic Of", "MK"),
    new Array("Madagascar", "MG"),
    new Array("Malawi", "MW"),
    new Array("Malaysia", "MY"),
    new Array("Maldives", "MV"),
    new Array("Mali", "ML"),
    new Array("Malta", "MT"),
    new Array("Marshall Islands", "MH"),
    new Array("Martinique", "MQ"),
    new Array("Mauritania", "MR"),
    new Array("Mauritius", "MU"),
    new Array("Mayotte", "YT"),
    new Array("Mexico", "MX"),
    new Array("Micronesia, Federated States Of", "FM"),
    new Array("Moldova, Republic Of", "MD"),
    new Array("Monaco", "MC"),
    new Array("Mongolia", "MN"),
    new Array("Montserrat", "MS"),
    new Array("Morocco", "MA"),
    new Array("Mozambique", "MZ"),
    new Array("Myanmar", "MM"),
    new Array("Namibia", "NA"),
    new Array("Nauru", "NR"),
    new Array("Nepal", "NP"),
    new Array("Netherlands", "NL"),
    new Array("Netherlands Antilles", "AN"),
    new Array("New Caledonia", "NC"),
    new Array("New Zealand", "NZ"),
    new Array("Nicaragua", "NI"),
    new Array("Niger", "NE"),
    new Array("Nigeria", "NG"),
    new Array("Niue", "NU"),
    new Array("Norfolk Island", "NF"),
    new Array("Northern Mariana Islands", "MP"),
    new Array("Norway", "NO"),
    new Array("Oman", "OM"),
    new Array("Pakistan", "PK"),
    new Array("Palau", "PW"),
    new Array("Panama", "PA"),
    new Array("Papua New Guinea", "PG"),
    new Array("Paraguay", "PY"),
    new Array("Peru", "PE"),
    new Array("Philippines", "PH"),
    new Array("Pitcairn", "PN"),
    new Array("Poland", "PL"),
    new Array("Portugal", "PT"),
    new Array("Puerto Rico", "PR"),
    new Array("Qatar", "QA"),
    new Array("Reunion", "RE"),
    new Array("Romania", "RO"),
    new Array("Russian Federation", "RU"),
    new Array("Rwanda", "RW"),
    new Array("Saint Kitts And Nevis", "KN"),
    new Array("Saint Lucia", "LC"),
    new Array("Saint Vincent And The Grenadines", "VC"),
    new Array("Samoa", "WS"),
    new Array("San Marino", "SM"),
    new Array("Sao Tome And Principe", "ST"),
    new Array("Saudi Arabia", "SA"),
    new Array("Senegal", "SN"),
    new Array("Seychelles", "SC"),
    new Array("Sierra Leone", "SL"),
    new Array("Singapore", "SG"),
    new Array("Slovakia (Slovak Republic)", "SK"),
    new Array("Slovenia", "SI"),
    new Array("Solomon Islands", "SB"),
    new Array("Somalia", "SO"),
    new Array("South Africa", "ZA"),
    new Array("South Georgia And The South Sandwich Islands", "GS"),
    new Array("Spain", "ES"),
    new Array("Sri Lanka", "LK"),
    new Array("St. Helena", "SH"),
    new Array("St. Pierre And Miquelon", "PM"),
    new Array("Sudan", "SD"),
    new Array("Suriname", "SR"),
    new Array("Svalbard And Jan Mayen Islands", "SJ"),
    new Array("Swaziland", "SZ"),
    new Array("Sweden", "SE"),
    new Array("Switzerland", "CH"),
    new Array("Syrian Arab Republic", "SY"),
    new Array("Taiwan, Republic Of China", "TW"),
    new Array("Tajikistan", "TJ"),
    new Array("Tanzania, United Republic Of", "TZ"),
    new Array("Thailand", "TH"),
    new Array("Togo", "TG"),
    new Array("Tokelau", "TK"),
    new Array("Tonga", "TO"),
    new Array("Trinidad And Tobago", "TT"),
    new Array("Tunisia", "TN"),
    new Array("Turkey", "TR"),
    new Array("Turkmenistan", "TM"),
    new Array("Turks And Caicos Islands", "TC"),
    new Array("Tuvalu", "TV"),
    new Array("Uganda", "UG"),
    new Array("Ukraine", "UA"),
    new Array("United Arab Emirates", "AE"),
    new Array("United Kingdom", "UK"),
    new Array("United States Minor Outlying Islands", "UM"),
    new Array("Uruguay", "UY"),
    new Array("Uzbekistan", "UZ"),
    new Array("Vanuatu", "VU"),
    new Array("Vatican City State (Holy See)", "VA"),
    new Array("Venezuela", "VE"),
    new Array("Viet Nam", "VN"),
    new Array("Virgin Islands (British)", "VG"),
    new Array("Virgin Islands (U S)", "VI"),
    new Array("Wallis And Futuna Islands", "WF"),
    new Array("Western Sahara", "EH"),
    new Array("Yemen", "YE"),
    new Array("Zaire", "ZR"),
    new Array("Zambia", "ZM"),
    new Array("Zimbabwe", "ZW")];

function writeCountries()
{
    writeSelectOptions(countries);
}

function writeAllCountries()
{
    writeSelectOptions(allCountries);
}

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.transType.value = "donation";
    }
    else if (document.donorForm.paymentType[1].checked)
    {
        document.donorForm.transType.value = "check";
    }
}

function updateTransType(type)
{
    document.donorForm.transType.value = type;
}

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 form = document.donorForm;
    var total = parseFloat(baseFee);
    for (var i = 0; i < costs.length; i++)
    {
        for (var c = 0; c < (form.elements.length - 1); c++)
        {
            if (form.elements[c+1].name == costs[i][3])
            {
                if (form.elements[c].checked)
                {
                    form.elements[c+1].value = "true";
                    total = total + parseFloat(form.elements[c].value);
                }
                else if (form.elements[c].checked != true)
                {
                    form.elements[c+1].value = "false";
                }
            }
        }
    }
    form.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 (var i = 0; i < fieldName.length; i++)
    {
        if (fieldName[i].checked || fieldName[i].selected)
        {
            var form = document.donorForm;
            for (var c = 0; c < form.elements.length; c++)
            {
                if (form.elements[c].name == null) continue;
                if (form.elements[c].name.indexOf("_SetElement|" + eventName + "|" + fieldName[i].value) >= 0)
                {
                    form.elements[c].value = "true";
                }
            }
        }
        else if (fieldName[i].checked != true && fieldName[i].selected != true)
        {
            var form = document.donorForm;
            for (var c = 0; c < form.elements.length; c++)
            {
                if (form.elements[c].name == null) continue;
                if (form.elements[c].name.indexOf("_SetElement|" + eventName + "|" + fieldName[i].value) >= 0)
                {
                    form.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 (var i = 0; i < radioField.length; i++)
    {
        if (radioField[i].checked) return true;
    }

    return false;
}

// Removes all characters which appear in string bag from string s.
function stripCharsInBag(s, bag)
{
    if (s == null) return "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    var returnString = "";
    for (var i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

//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 -->');
}
