var thisRaceDayCount = 0;
var compareYear = 2012;
var compareMonth = 02;
var compareDay = 29;

var minBirthDate = new Date();
minBirthDate.setYear(compareYear-18);
minBirthDate.setMonth(compareMonth);
minBirthDate.setDate(compareDay);
minBirthDate.setHours(0);
minBirthDate.setMinutes(0);
minBirthDate.setSeconds(0);
minBirthDate.setMilliseconds(0);

var minParentalBirthDate = new Date();
minParentalBirthDate.setYear(compareYear-13);
minParentalBirthDate.setMonth(compareMonth);
minParentalBirthDate.setDate(compareDay);
minParentalBirthDate.setHours(0);
minParentalBirthDate.setMinutes(0);
minParentalBirthDate.setSeconds(0);
minParentalBirthDate.setMilliseconds(0);

function AdditionalFormValidation() {
	CheckAge();
	CheckAtLeastOneShiftChoosen();
	CheckRaceDayCount();
	CheckOverlappingShifts();
	CheckPasswordRequiredShifts();
}

function CheckAge() {
	$j("#ParentalWaiverWpr").hide();
	$j(".parentContactInfoField").hide();	
	$j("#UnderAgeWpr").hide();
	$j("#WaiverWpr").hide();
	$j("#SubmitButtonWpr").show();
		
	var birthDate = new Date();
	birthDate.setFullYear($j('#birthYear').val());
	birthDate.setMonth($j('#birthMonth').val());
	birthDate.setHours(0);
	birthDate.setMinutes(0);
	birthDate.setSeconds(0);
	birthDate.setMilliseconds(0);
	if(birthDate.valueOf() > minParentalBirthDate.valueOf()) {
		//alert('under 13 years old.');
		$j("#UnderAgeWpr").show();
		$j("#SubmitButtonWpr").hide();
		frm.birthYear.throwError('You must be at least 13 years old to register online.');
	} else if (birthDate.valueOf() <= minParentalBirthDate.valueOf() && birthDate.valueOf() > minBirthDate.valueOf()) {
		//alert('13-17 years old.');
		$j("#ParentalWaiverWpr").show();
		$j(".parentContactInfoField").show();
		frm.agree.required = false;
		frm.parentalAgree.required = true;
		frm.parentFirstName.required = true;
		frm.parentLastName.required = true;
		frm.parentPhone.required = true;
	} else {
		//alert('over 18 ys old.');
		$j("#WaiverWpr").show();
		frm.agree.required = true;
		frm.parentalAgree.required = false;
		frm.parentFirstName.required = false;
		frm.parentLastName.required = false;
		$j("#parentPhone").val('');
		$j("#parentalAgree").attr('checked', false);
		frm.parentPhone.required = false;
	}
}

function CheckRaceDayCount() {
	var maxRaceDayShifts = 1;
	if($j('.shifts .raceDayShift .field input:checked').length > maxRaceDayShifts) {
		frm.volunteercategoryId.throwError('You can only select ' + maxRaceDayShifts + ' race day shift.');
	}
}

function CheckAtLeastOneShiftChoosen() {
	if(!$j('.shifts .field input:checked').length) {
		frm.volunteercategoryId.throwError('At least one Volunteer Shift is required.');
	}
}

function CheckOverlappingShifts() {
	$j('.shifts .field input:checked').each(function() {
		if(DoesShiftOverlap($j(this).attr("beginTime"), $j(this).attr("endTime"), $j(this).val())) {
			frm.volunteercategoryId.throwError('Overlapping shifts are not allowed.');
		}
	});
}

function DoesShiftOverlap(beginTime, endTime, categoryId) {
	var overlaps = false;
	var gracePeriodMinutes = 32; // shifts can overlap by this many minutes. from sarah horn on 8/14/09
	
	$j('.shifts .field input:checked').each(function() {
		if($j(this).val() != categoryId && 
										(
											IsValueBetween(parseInt(beginTime)+gracePeriodMinutes, parseInt($j(this).attr("beginTime")), parseInt($j(this).attr("endTime"))) 
											|| 
											IsValueBetween(parseInt(endTime)-gracePeriodMinutes, parseInt($j(this).attr("beginTime")), parseInt($j(this).attr("endTime")))
										)
		) {
			overlaps = true;
		}
	});

	return overlaps;
}

function IsValueBetween(value, start, end) {
	if(parseInt(value) > parseInt(start) && parseInt(value) < parseInt(end)) {
		return true;
	} else {
		return false;
	}
}

function CheckPasswordRequiredShifts() {
	var shiftId;
	var shiftPassword;
	var passwordFieldName;
	
	for(var i=0; i < $j('.shifts .passwordRequiredShift .field input').length; i++) {
		if($j('.shifts .passwordRequiredShift .field input')[i].checked) {
			passwordFieldName = $j('.shifts .passwordRequiredShift .shiftPassword input')[i].name;
			if(!$j('.shifts .passwordRequiredShift .shiftPassword input')[i].value.length) {
				frm[passwordFieldName].throwError("A Password is required for this shift.");
			} else {
				shiftId = $j('.shifts .passwordRequiredShift .field input')[i].value;
				shiftPassword = $j('.shifts .passwordRequiredShift .shiftPassword input')[i].value;
				$j.ajax({
					async: false,
					type: 'GET',
					url: 'index.cfm?fuseaction=volunteer.validateShiftPassword',
					data: 'shiftId='+shiftId+'&shiftPassword='+escape(shiftPassword)+'&x='+Math.floor(Math.random()*100000),
					success: function(resp) {
						if(resp == 0) {
							frm[passwordFieldName].throwError('The Password is incorrect for this shift.');
						}
					},
					error: function() {
						alert('password validation error: unable to connect');
					}
				});
			}
		}
	}
}

function checkEmail(email) {
	var _ajaxObject;
	var pars = 'email=' + email;
	var _ajaxUrl = 'index.cfm?fuseaction=volunteer.validateemail';
		_ajaxObject = new Ajax.Request(_ajaxUrl,{method: 'get', parameters: pars, onSuccess: _evaluateSuccess, onFailure: _evaluateFailure });
}

_evaluateSuccess = function(originalRequest) {
	var requestObj = originalRequest;
	originalRequest.responseText.evalScripts();
}

_evaluateFailure = function(originalRequest) {
	alert('failed');
}

_existingEmailPopup = function() {
	var confirmObj = confirm('You have already registered as a volunteer with this email address. If you are registering for someone else, click OK to continue.  Otherwise, click Cancel to return to the volunteer information page.');
	if (confirmObj == true) {

	} else {
		window.location = 'http://www.breastcancermarathon.com/support/volunteer/';
	}
}

function handleSelect(elem,content_id){
	if (elem.checked == true) {
		processAction = "add";
		$j("#div_AddThisEvent_" + content_id).addClass('isChecked');
	} else {
		processAction = "remove";	
		$j("#div_AddThisEvent_" + content_id).removeClass('isChecked');	
	}
	$j.ajax({    
		type:    'POST',    
		url:     'index.cfm?fuseaction=itinerary.processSelection',   
		data:    'content_id=' + content_id + '&processAction=' + processAction,    
		error:   function(){ alert("Error getting location data!"); },    
		success: function(data) {showLocation(data,elem,content_id,processAction);}    
	});
}

function showLocation(data,elem,content_id,processAction){	
	if (content_id == 0) {
		$j(".AddThisEventWpr .checkbox").attr('checked', false);
		$j(".AddThisEventWpr .fieldContainer.checkbox").removeClass('isChecked');	
	}	
	$j('#EventsSelectedCount').html(data);		
}


