var contentWin;
Date.prototype.getDiff = function(date, interval){
	  if (typeof date == "string"){
	     date = new Date(date);
	  }
	  if (isNaN(date) || !(date instanceof Date)){
	     return NaN; 
	  }
	  if (typeof interval == "undefined") interval = "ms"; 
	  var diff = this - date; 
	  switch(interval.toLowerCase()){
	    case "s": 
	      diff = diff/1000; break;
	    case "n": 
	      diff = diff/(1000*60); break;
	    case "h": 
	      diff = diff/(1000*60*60); break;
	    case "d": 
	      diff = diff/(1000*60*60*24); break;
	    case "m": 
	      diff = diff/(1000*60*60*24*30); break;
	    case "y": 
	      diff = diff/(1000*60*60*24*365); break;
	    default:
	      ; 
	  }
	  return Math.floor(diff);
	}
function concatCollections() {
	var c, k, j, i = arguments.length;
	var a = [];
	for ( j=0; j<i; j++ ) {
		c = arguments[j];
		h = c.length;
		for ( k=0; k<h; k++ ){
			a.push(c[k]);
		}
	}
	return a;
}
//is form valid, submit to server
function validate(form) {
	today = new Date();
	agelimit = new Date(parseInt(today.getMonth())+1 + '/' + parseInt(today.getDate()) + '/' + parseInt(today.getFullYear()-18));		
	hphone = $F('hphone1') + '-' + $F('hphone2') + '-' + $F('hphone3');
	$('hphone').value = hphone;
	wphone = $F('wphone1') + '-' + $F('wphone2') + '-' + $F('wphone3');
	$('wphone').value = wphone;
	cphone = $F('cphone1') + '-' + $F('cphone2') + '-' + $F('cphone3');
	$('cphone').value = cphone;	
	refphone0 = $F('ref1phone1') + '-' + $F('ref1phone2') + '-' + $F('ref1phone3');
	$('refphone0').value = refphone0;
	refphone1 = $F('ref2phone1') + '-' + $F('ref2phone2') + '-' + $F('ref2phone3');
	$('refphone1').value = refphone1;
	dob = $F('birth_month') + '/' + $F('birth_day') + '/' + $F('birth_year');
	$('dob').value = dob;
	bday = new Date(dob);	
	
	if (validRegistration.validate()) {
		if (contentWin != null) {
			contentWin.close(); 
		}		
		if(!validateBDay(dob)){
			alert('Please enter valid birthdate');
			return false;
		}else if(agelimit<bday){
			alert('You must be 18 or over.');	
			return false;
		}
		
		if(!checkLength()){
			return false;
		}
		content_id = 'adult-waiver';	
		//open dialog with waiver
		contentWin = Dialog.confirm($(content_id).innerHTML, {zIndex:1000,className:"alphacube", width:640, height:450, okLabel: "Submit", cancelLabel: "Cancel", onOk:function(win){ validateWaiver(content_id); return false;}});
	}
	//prevent form submit action
	return false;
}

function validateWaiver(content_id) {
	var success = true;
	var inputs = document.getElementById(content_id).getElementsByTagName("INPUT");
	var fields = concatCollections(inputs);
	for (i=0; i<fields.length; i++){
		if (Validation.get('IsEmpty').test($F(fields[i].id))) {
			success = false;
			alert('Please accept all of the terms and conditions at the bottom of this waiver.');
			break;
		}
	}
	//validation success
	if (success) {
			$('ADULT_WAIVER_REQUIRED_CHECKBOX_1_hd').value = $F('ADULT_WAIVER_REQUIRED_CHECKBOX_1');
			$('ADULT_WAIVER_REQUIRED_CHECKBOX_2_hd').value = $F('ADULT_WAIVER_REQUIRED_CHECKBOX_2');
		contentWin.close();
		$('delegates').submit();
	}
}
function setValue(e) {
	switch (e.id) {
		case ('MINOR_NAME_1'):
			$('MINOR_NAME_2').value = e.value;
			break;	
		case ('MINOR_NAME_2'):
			$('MINOR_NAME_1').value = e.value;
			break;
		case ('GUARDIAN_NAME_1'):
			$('GUARDIAN_NAME_2').value = e.value;
			break;	
		case ('GUARDIAN_NAME_2'):
			$('GUARDIAN_NAME_1').value = e.value;
			break;
		case ('RELATIONSHIP_WITH_MINOR_1'):
			$('RELATIONSHIP_WITH_MINOR_2').value = e.value;
			break;	
		case ('RELATIONSHIP_WITH_MINOR_2'):
			$('RELATIONSHIP_WITH_MINOR_1').value = e.value;
			break;
	}
}
function checkLength(){    
    if ($('involvement').value.length > 3000){ 	 
        alert(' Community Involvement Text (' + $('involvement').value.length +') too long. Must be 3000 characters or less.');    
	 return false;  
    }
    if($('biography').value.length > 3000){
	 alert(' Personal Biography Text (' + $('biography').value.length + ') too long. Must be 3000 characters or less.');
	 return false;
    }     
    return true;
}

function validateBDay(v){
	var matchArray = v.match(/^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/); 	
	month = matchArray[1]; 
	day = matchArray[3];
	year = matchArray[4];
	today = new Date();
	bday = new Date($('dob').value);
				
	if (matchArray == null) {
		return false;
	}else if (month < 1 || month > 12) { 	
		return false;
	}else if (day < 1 || day > 31) {
		return false;
	}else if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}else if (month == 2) { // check for february 29th
		isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			return false;
   		}
	}else if(today<bday){
		alert('not valid');
		return false;
	}
	return true	
}
//not used for delegates
function isAdult(dob) {
	if( !/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.test(dob) ) {
		//alert( "Invalid date supplied - must be format MM/DD/YYYY" );
		return false;
	}
	
	var d = new Date(today);
	var d2 = new Date(RegExp.$3, (RegExp.$1 - 1), RegExp.$2);

	var diff = d.getDiff(d2, "y");
	switch (true) {
		case ( isNaN(diff) ):
			//Invalid date supplied
			return false;
		case ( diff == 18 ):
			var myDate = new Date(d.getFullYear(), (RegExp.$1 - 1), RegExp.$2);	
			if (myDate > d) {
				return false;
			}
			break;
		case ( diff < 18 ):
			//under 18
			return false;
	}
	return true;
}
myObserver = {
    onDestroy: function(eventName, win) {
      if (win == contentWin) {
        contentWin = null;
        Windows.removeObserver(this);
      }
    }
}
var defaultvalue  = Class.create();

defaultvalue .prototype = {
	
    initialize: function(ctrl, v) {
		var v;    
		this.ctrl = ctrl;
		this.v = v;

        if (this.ctrl == null) return;
        if (this.ctrl.value == '') this.ctrl.value = v;
        Event.observe(this.ctrl, 'focus', this.clear.bindAsEventListener(this), false);
        Event.observe(this.ctrl, 'blur', this.reset.bindAsEventListener(this), false);
    },

    clear: function() {
        if (this.ctrl.value == this.v) {
        	this.ctrl.value = "";
        }
    },
    
    reset: function() {
        if (this.ctrl.value == "") {
        	this.ctrl.value = this.v;
        }
    }
}

function initMainEvents() {	
	if ($('saved').value == 'true'){	       
		openThankyou();
	}
	Windows.addObserver(myObserver);
	new defaultvalue ($('first_name'), "First Name");
	new defaultvalue ($('last_name'), "Last Name");	
}

function autoTab(element, nextElement,evt) {
	var keyCode = 0;
	if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ 
	 	keyCode = (window.event) ? evt.keyCode : evt.which;
	}else{
		keyCode = window.event.keyCode;
	}
	if (keyCode != 9){
		if (element.value.length == element.maxLength && nextElement != null) {
       		element.form.elements[nextElement].focus();
       	}
	}		
}
function openThankyou(){
	var contentmessage = "";//"<h1 style='color:#4A0B38; padding-top:100px; text-align:center; font-size:24px;'>THANK YOU </h1><h4 style='text-align:center; font-size:14px; color:#272621;'>FOR SUBMITTING YOUR APPLICATION.</h4>";
	contentWin = Dialog.info(contentmessage, {zIndex:1000,className:"alphacube", width:400, height:300 });	
}

Event.observe(window, "load", initMainEvents);