/*
 * contactUs.js
 * 
 *
 * Form validation and utility code for the bulletin request form.
 *
 * copyright	2004 North Point Ministries
 * author	Josh Justice <josh.justice@northpoint.org>
 * modified	David Wallace <david.wallace@4-integrity.com>
 * version	1.0
 */
    
/* global variables ***********************************************************/

// list of form names of required fields
var checkFieldList = ["fhscol_app_firstName", "fhscol_app_lastName", "fhscol_app_address", "fhscol_app_city", "fhscol_app_state", "fhscol_app_zip", "fhscol_app_cellPhone", "fhscol_app_email", "fhscol_app_heaven", "fhscol_app_q1", "fhscol_app_q2", "fhscol_app_christianlife", "fhscol_app_status"];

// user-friendly names of required fields to display to user
var properNameList = ["First Name", "Last Name", "Address", "City", "State", "ZIP", "Cell Phone", "Email", "Do you believe you are going to heaven?", "How and when you accepted Christ", "Why you want to get baptized", "Is your lifestyle reflective of your life in Christ", "Ready/Contact"];

/* functions ******************************************************************/

/*
 * Copies the contact information entered in the top of the form, to the billing
 * fields at the bottom of the form.
 *
 * param theForm   the form object
 *

function copyContactInfoToBilling(theForm)
{
	theForm["pps_first_name"].value = theForm["fhscol_FirstName"].value;
	theForm["pps_last_name"].value = theForm["fhscol_LastName"].value;
	theForm["pps_address"].value = theForm["fhscol_Address"].value;
	theForm["pps_city"].value = theForm["fhscol_City"].value;
	theForm["pps_state"].value = theForm["fhscol_State"].value;
	theForm["pps_zip_code"].value = theForm["fhscol_Zip"].value;
	theForm["pps_email"].value = theForm["fhscol_Email"].value;
	theForm["ppsEmailConfirm"].value = theForm["EmailConfirm"].value;
}
 */
/*
 * Checks all required fields to ensure that a value has been entered for them.
 * If any are missing, an error dialog is displayed to the user and the form is
 * not submitted. If none are missing, the form is submitted.
 *
 * param theForm   the form object
 */
function checkFields (theForm)
{
	var errorText = "";
	var curField = "";
	var curFieldProp = "";
	var count = 0; // number of empty fields
	

	// set receipient
	//theForm["fhs_recipients"].value = theForm["fhscol_recipients"].value;
	

	// check fields
	for (var i = 0; i < checkFieldList.length; i++)
	{
		curField = checkFieldList[i];
		curFieldProp = properNameList[i];
		unhilite( theForm[curField] );
		if ( isEmpty( theForm[curField] ) || theForm[curField].value == "--" )
		{
			// add field to error list
			hilite( theForm[curField] );
			errorText += curFieldProp + ", ";
			count++;
		} // end if
	} // end for

	var dt=theForm.fhscol_app_birthdate;
	unhilite(theForm.fhscol_app_birthdate);
	if (isDate(dt.value)==false){
		count++;
		errorText += "Valid Birth Date";
		hilite(theForm.fhscol_app_birthdate);
	}

	// if any errors, display
        if (errorText != "")
        {
            errorText = errorText.substring(0, errorText.length - 2);
            alert ("The following " + count + " field(s) must be completed:\n\n" + errorText + "\n\nPlease complete all required fields before submitting again.");
            return false;
        }
/*        else
        {
            theForm.submit.value = 'Submitting...';
            theForm.submit.disabled = true;
	} // end if
*/
		
		errorText = "";

		if ( theForm["fhscol_app_heaven"].value.length > theForm["fhscol_app_heaven"].getAttribute('maxlength') ) {
			errorText += "-- Do you believe you are going to heaven?\n";
		}
		if ( theForm["fhscol_app_q1"].value.length > theForm["fhscol_app_q1"].getAttribute('maxlength') ) {
			errorText += "-- How and when you accepted Christ\n";
		}
		if ( theForm["fhscol_app_q2"].value.length > theForm["fhscol_app_q2"].getAttribute('maxlength') ) {
			errorText += "-- Why you want to get baptized?\n";
		}
		
		if (errorText != "")
        {
            errorText = errorText.substring(0, errorText.length - 1);
            alert ("The following answers are too long:\n\n" + errorText + "\n\nPlease edit your answers to keep them to a max of 2000 characters.");
            return false;
        }
		
    	return true;
	
    	
} // end checkFields

/*
 * Returns true if a field is empty, false otherwise. Handles text fields,
 * select fields, checkboxes, and radio buttons.
 *
 * param formElement   the form element object
 */
function isEmpty( formElement )
{
	// checkboxes
	if( formElement.type == 'checkbox' )
	{
	    return !formElement.checked;
	}

	// text fields
	else if( formElement.type == 'text' )
	{
	    return formElement.value == "";
	}

	// text areas
	else if( formElement.type == 'textarea' )
	{
	    return formElement.value == "";
	}

	// select fields
	else if( formElement.type == 'select-one' )
	{
	    return formElement.selectedIndex <= 0;
	}

	// radio buttons
	else
	{
	    for( var i = 0; i < formElement.length; i++ )
	    {
		if( formElement[i].checked )
		    return false;
	    }
	    return true;
	} // end if
} // end isEmpty

/*
 * Highlights a text field or select box by changing its background color to
 * yellow.
 *
 * param formElement   the form element object
 */
function hilite( formElement )
{
	// can't hilite radio groups
	if( typeof formElement[0] != 'undefined' )
		return;

	if( typeof formElement.style != 'undefined' )
		formElement.style.background = "#FFFF99";
} // end hilite

/*
 * Removes highlighting a text field or select box by changing its background
 * color to white.
 *
 * param formElement   the form element object
 */
function unhilite( formElement )
{
	// can't unhilite radio groups
	if( typeof formElement[0] != 'undefined' )
		return;

	if( typeof formElement.style != 'undefined' )
		formElement.style.background = "#FFFFFF";
} // end unhilite

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The birth date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid birth month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid birth day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit birth year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid birth date")
		return false
	}
return true
}


function setMaxLength() {
	var x = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'counter';
	for (var i=0;i<x.length;i++) {
		if (x[i].getAttribute('maxlength')) {
			var counterClone = counter.cloneNode(true);
			counterClone.relatedElement = x[i];
			counterClone.innerHTML = '('+x[i].getAttribute('maxlength') + ' Characters Max) - <span>0</span>/'+x[i].getAttribute('maxlength');
			x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
			x[i].relatedElement = counterClone.getElementsByTagName('span')[0];

			x[i].onkeyup = x[i].onchange = checkMaxLength;
			x[i].onkeyup();
		}
	}
}

function checkMaxLength() {
	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
	if (currentLength > maxLength)
		this.relatedElement.className = 'toomuch';
	else
		this.relatedElement.className = '';

	this.relatedElement.firstChild.nodeValue = currentLength;
	
	// not innerHTML
}