/*
 * 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_HisFirstName", "fhscol_HisLastName", "fhscol_HisEmail", "fhscol_HisHomePhone", "fhscol_HisWorkPhone", "fhscol_HisCellPhone", "fhscol_HisAddress", "fhscol_HisCity", "fhscol_HisState", "fhscol_HisZip", "HisBirthMonth", "HisBirthDay", "HisBirthYear", "fhscol_HimStatusID", "fhscol_HimInvolvementID", "fhscol_HimInGroup", "fhscol_HimServing", "fhscol_HimWhatMarriage", "fhscol_HimHasChildren", "fhscol_HerFirstName", "fhscol_HerLastName", "fhscol_HerEmail", "fhscol_HerHomePhone", "fhscol_HerWorkPhone", "fhscol_HerCellPhone", "fhscol_HerAddress", "fhscol_HerCity", "fhscol_HerState", "fhscol_HerZip", "HerBirthMonth", "HerBirthDay", "HerBirthYear", "fhscol_HerStatusID", "fhscol_HerInvolvementID", "fhscol_HerInGroup", "fhscol_HerServing", "fhscol_HerWhatMarriage", "fhscol_HerHasChildren", "WeddingMonth", "WeddingDay", "WeddingYear", "fhscol_Campus", "fhscol_LivingTogetherBefore", "fhscol_MeetingTimes", "fhscol_HimConfidentiality", "fhscol_HerConfidentiality"];

// user-friendly names of required fields to display to user
var properNameList = ["His First Name", "His Last Name", "His E-mail", "His Home Phone", "His Work Phone", "His Cel Phone", "His Address", "His City", "His State", "His Zip", "His Birth Month", "His Birth Day", "His Birth Year", "His Status", "His Involvement", "Him In Group", "Him Serving", "Him What Marriage", "He Has Children?", "Her First Name", "Her Last Name", "Her E-mail", "Her Home Phone", "Her Work Phone", "Her Cel Phone", "Her Address", "Her City", "Her State", "Her Zip", "Her Birth Month", "Her Birth Day", "Her Birth Year", "Her Status", "Her Involvement", "Her In Group", "Her Serving", "Her What Marriage", "She Has Children?", "Wedding Month", "Wedding Day", "Wedding Year", "Campus", "Living Together", "Meeting Times", "Him Confidentiaity", "Her Confidentiality" ];

// his step-family fields
var hisStepFieldList = ["fhscol_HimHowLong", "fhscol_HimDeathOrDivorce", "fhscol_HimSteps", "fhscol_HimDecision", "fhscol_HimFactors", "fhscol_HimResults"];
var hisStepNameList = ["Him How Long", "Him Death or Divorce", "Him Steps", "Him Decision", "Him Factors", "Him Results"];

// her step-family fields
var herStepFieldList = ["fhscol_HerHowLong", "fhscol_HerDeathOrDivorce", "fhscol_HerSteps", "fhscol_HerDecision", "fhscol_HerFactors", "fhscol_HerResults"];
var herStepNameList = ["Her How Long", "Her Death or Divorce", "Her Steps", "Her Decision", "Her Factors", "Her Results"];


/* functions ******************************************************************/

/*
 * 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 new_win(myForm,myText){

	window.open('includes/calendar.html?form=' + myForm + '&field=' + myText + '&bgcolor=cccccc&txtcolor=Blue&hdrcolor=a2b59f&todaycolor=White&offset=0&format=s','cal','noresize,width=225,height=160');
} 
 
function checkFields (theForm)
{
	var errorText = "";
	var sixMonthError = "";
	var curField = "";
	var curFieldProp = "";
	var count = 0; // number of empty fields
	
	// check fields
	for (var i = 0; i < checkFieldList.length; i++)
	{
		curField = checkFieldList[i];
		curFieldProp = properNameList[i];
		//alert(curField);
		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

	// check sometimes required fields
	if( theForm["fhscol_HimInGroup"].value==1 && isEmpty( theForm["fhscol_HimGroupLeaderName"] ) )
	{
		hilite( theForm["fhscol_HimGroupLeaderName"] );
		errorText += "His Group Leader Name, ";
		count++;
	}
	if( theForm["fhscol_HimServing"].value==1 && isEmpty( theForm["fhscol_HimServiceArea"] ) )
	{
		hilite( theForm["fhscol_HimServiceArea"] );
		errorText += "His Service Area, ";
		count++;
	}
	if( theForm["fhscol_HerInGroup"].value==1 && isEmpty( theForm["fhscol_HerGroupLeaderName"] ) )
	{
		hilite( theForm["fhscol_HerGroupLeaderName"] );
		errorText += "Her Group Leader Name, ";
		count++;
	}
	if( theForm["fhscol_HerServing"].value==1 && isEmpty( theForm["fhscol_HerServiceArea"] ) )
	{
		hilite( theForm["fhscol_HerServiceArea"] );
		errorText += "Her Service Area, ";
		count++;
	}
	if( theForm["fhscol_HimHasChildren"].value==1 )
	{
		for (var i = 0; i < hisStepFieldList.length; i++)
		{
			curField = hisStepFieldList[i];
			curFieldProp = hisStepNameList[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
	}
	if( theForm["fhscol_HerHasChildren"].value==1 )
	{
		for (var i = 0; i < herStepFieldList.length; i++)
		{
			curField = herStepFieldList[i];
			curFieldProp = herStepNameList[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
	}

	// convert dates
	if( null == (theForm["fhscol_HimBirthDate"].value =
		combineDate( 
			theForm["HisBirthYear"].value,
			theForm["HisBirthMonth"].value,
			theForm["HisBirthDay" ].value ) ))
	{
		errorText += "His Birth Date, ";
		count++;
	}
	if( null == (theForm["fhscol_HerBirthDate"].value =
		combineDate( 
			theForm["HerBirthYear"].value,
			theForm["HerBirthMonth"].value,
			theForm["HerBirthDay" ].value ) ))
	{
		errorText += "Her Birth Date, ";
		count++;
	}
	if( null == (theForm["fhscol_Wedding"].value =
		combineDate( 
			theForm["WeddingYear"].value,
			theForm["WeddingMonth"].value,
			theForm["WeddingDay" ].value ) ))
	{
		errorText += "Wedding Date, ";
		count++;
	}
	
	//alert(theForm["fhscol_Wedding"].value);
	
	if(!checkOverSixMonth(theForm["fhscol_Wedding"].value)){
			sixMonthError += "Your wedding date must be atleast six months away in order to register.";
	}

	// if any errors, display
        if (sixMonthError != ""){
        	alert(sixMonthError);
        	return false;
        }
        else 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
*/
	
	
    	return true;
	
    	
} // end checkFields

function checkOverSixMonth(weddingDate){
	
	var month = new Date(weddingDate);
	var year = month.getFullYear();
	var day = month.getDate();
	month = month.getMonth();
	
	//alert(month + "/" + day + "/" + year);
	
	//month = month - 1;
	var result = false;
	var currentMonth = new Date();
	var currentYear = currentMonth.getYear();
	currentMonth = currentMonth.getMonth();
	
	var checkMonth = (currentMonth + 6)%12;
	var checkYear = currentYear;
	if(checkYear < 2000){
		checkYear = checkYear + 1900;
	}
	if(checkMonth < 6){
		checkYear++;
	}
	if(checkYear < year){
		result = true;
	}
	else if(checkYear == year && checkMonth < month){
		result = true;
	}
	else if(checkMonth == month){
		var now = new Date();
		var checkDay = now.getDate();
		if(day > checkDay){
			result = true;
		}
	}
	
	return result;	
}
/*
 * Combines separate year/day/month fields into a date, and returns null if invalid date.
 */
function combineDate( year, month, day )
{
	year	= parseInt(year);
	month	= parseInt(month);
	day	= parseInt(day);
	
	if( isNaN(year) || year < 1900 || year > 2011 ||
			isNaN(month) || month < 1 || month > 12 ||
			isNaN(day) || day < 1 || day > 31 )
			return null;
	else
		return '' + month + '/' + day + '/' + year;
} // end combineDate

/*
 * 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 isNumberKey(evt)
{
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
	
	return true;

}

var campus = "";
var campusNameArr = new Array();
campusNameArr["NP"] = "North Point";
campusNameArr["BC"] = "Buckhead Church";
campusNameArr["BB"] = "Browns Bridge";
function setCampus(theForm) {
	campus = theForm["fhscol_Campus"].value;
	c_him = document.getElementById("campusNameDiv_him");
	c_him.innerHTML = campusNameArr[campus];
	c_her = document.getElementById("campusNameDiv_her");
	c_her.innerHTML = campusNameArr[campus];
	
}

function showDivorceCopy(v) {
	if (v > 1) {
		document.getElementById("divorce-copy").style.display = 'block';
	}
}
