window.onload = initJavascript;

/****************
################# declare and instantiate vars objects arrays ###########################
****************/

var arrayErrors = new Array();
var legalChars1 = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
var legalChars2 = "ABCDEFGHIJKLMNOPQRSTUVXYZ0123456789";
var legalChars3 = "ABCDEFGHIJKLMNOPQRSTUVXYZ0123456789-_.";
var legalChars5 = "ABCDEFGHIJKLMNOPQRSTUVXYZ ";
var legalChars4 = "0123456789";


/****************
################# function to initiate form submission ###################################################
****************/

function initJavascript(){
	for(var i = 0; i < document.forms.length; i++){
		document.forms[i].onsubmit = function () { return validateForm(this); }	
	}
}

/****************
################# function to call functions to validate form returns true or false #######################
****************/

function validateForm(form){
	arrayErrors = new Array();
	
	
	/****************
	################# validates empty select sltTitle then validates text for the select
	****************/
	
	if(isSelectEmpty(form.sltTitle)){
		manageErrorHighLights("sltTitle","input",true,"Please, choose a Title!");
	}else{
		manageErrorHighLights("sltTitle","input",false);
	}

	
	/****************
	################# validates empty txtName then check if it is valid
	****************/
	
	if(isEmpty(form.txtName)){
		manageErrorHighLights("txtName","input",true,"Please, give us your Name!");
	}else{
		if(validateString(form.txtName,legalChars1)){
			manageErrorHighLights("txtName","input",true,"Your name is invalid!");
		}else{
			manageErrorHighLights("txtName","input",false);
		}
	}
	
	
	/****************
	################# validates empty txtSurname then check if it is valid
	****************/
	
	if(isEmpty(form.txtSurname)){
		manageErrorHighLights("txtSurname","input",true,"Please, give us your Surename!");
	}else{
		if(validateString(form.txtSurname,legalChars1,true)){
			manageErrorHighLights("txtSurname","input",true,"Your surename is invalid!");
		}else{
			manageErrorHighLights("txtSurname","input",false);
		}
	}
	
	/****************
	################# call to function to validate valid email
	****************/
	
	if(isEmpty(form.txtEmail)){
		manageErrorHighLights("txtEmail","input",true,"Please, give us your email!");
	}else{
		if(isInvalidEmail(form.txtEmail,legalChars3)) {
			manageErrorHighLights("txtEmail","input",true,"Your email is invalid!");	
		}else{
			manageErrorHighLights("txtEmail","input",false);
		}
	}
		
	/****************
	################# validates empty gender
	****************/
	
	if(validateRadiobuttons(form.gender)){
		manageErrorHighLights("txtGender","input",true,"Please, choose your Gender!");
	}else{
		manageErrorHighLights("txtGender","input",false);
	}
	
	/****************
	################# validates empty select cboDay then validates day for the select
	****************/
	
	if(isSelectEmpty(form.cboDay)){
		manageErrorHighLights("sltdob","input",true,"Please, choose a Day");
	}else{
		manageErrorHighLights("sltdob","input",false);
	}
	
	/****************
	################# validates empty select cboMonth then validates Month for the select
	****************/
	
	if(isSelectEmpty(form.cboMonth)){
		manageErrorHighLights("sltdob","input",true,"Please, choose a Month");
	}else{
		manageErrorHighLights("sltdob","input",false);
	}
	
	/****************
	################# validates empty select cboYear then validates year for the select
	****************/
	
	if(isSelectEmpty(form.cboYear)){
		manageErrorHighLights("sltdob","input",true,"Please, choose a Year");
	}else{
		manageErrorHighLights("sltdob","input",false);
	}
	
	/****************
	################# validates age and check parental
	****************/
	
	if(!isSelectEmpty(form.cboYear) && !isSelectEmpty(form.cboMonth) && !isSelectEmpty(form.cboDay)){
		if(validateAge(form.cboDay,form.cboMonth,form.cboYear) == 14){
			manageErrorHighLights("sltdob","input",true,"Unfortunately we're unable to register anyone under the age of 14. Please ask your parents to write to us on your behalf.");
		}else if(validateAge(form.cboDay,form.cboMonth,form.cboYear) == 16){
			if(!document.getElementById("txtParental").checked){
				//alert(document.getElementById("txtParental").checked);
				manageErrorHighLights("sltdob","input",true,"You need parental consentement!");
			}else{
				//alert("2");
				manageErrorHighLights("sltdob","input",false); 
			}
			//manageErrorHighLights("sltdob","input",false);
		}else{
			manageErrorHighLights("sltdob","input",false);
		}
	}


	//alert(arrayErrors);
	if(arrayErrors.length != 0){
		adicionaErros(arrayErrors);
		return false;	
	}else{
		return true;	
	}
}

/****************
################# function to validate empty input field #############################################
****************/

function isEmpty(field){
	if(field.value.length == 0){
		return true;	
	}else{
		return false;	
	}
}

/****************
################# function to validate empty select #####################################################
****************/

function isSelectEmpty(field){
	if(field.selectedIndex == 0){
		return true
	}
	return false;
}

/****************
################# function to validate valid email ###################################################
****************/

function isInvalidEmail(field,extraChars) {
	if(isEmpty(field)) { return true; }
	
	var erro ="";
    var tfld = removeFieldSpaces(field.value);		// substitui alguns caracteres nao essenciais
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ; 	//regular expression
    var carIlegais= /[\(\)\<\>\,\;\:\\\"\[\]]/ ; 		//regular expression
   
    if(!emailFilter.test(tfld)) {		//testa o campo em busca caracteres especiais
       return true;
    }else if(field.value.match(carIlegais)) {
       return true;
    }else{
       return false; 
    }
}

/****************
################# function to validate valid string receiving a variable of strings ##################
****************/

function validateString(field,extraChars,removeWhiteSpaces){
	var newValue;
	if (typeof removeWhiteSpaces == "undefined"){
		newValue = field.value;
	}else{
		newValue = removeFieldSpaces(field.value);
	}
	var newLength = newValue.length;
	var searchString;
	
	for(var i = 0; i < newLength; i++) {
		aChar = newValue.substring(i,i+1);
		aChar = aChar.toUpperCase();
		searchString = extraChars.indexOf(aChar);
		if(searchString == -1) {return true;}
	}
	return false;
}

/****************
############################ function to validate valid radiobuttons ############################################
****************/

function validateRadiobuttons(field){
	
	if((field[0].checked == false) && (field[1].checked == false)){ return true; }
	return false;
}

/****************
####### function to manage errors, change label color, change field color ############################################
****************/

function manageErrorHighLights(fieldName,fieldType,status,errorObject,globalLabel){
	if(status == true){ 
		if (typeof errorObject == "undefined" || errorObject == false){ 
			arrayErrors.push(fieldName);  
		}else{
			arrayErrors.push(errorObject); 
		}
	}
	if (typeof globalLabel == "undefined"){
		changeLabelColor(fieldName,status);
		changeFieldColor(fieldName,fieldType,status);
	}else{
		changeLabelColor(globalLabel,status);
		changeFieldColor(globalLabel,fieldType,status);
	}	
}

/****************
################# function to change label color ##########################################################
****************/

function changeLabelColor(field,error){
	var newColor = "#F00";
	var defaultColor = "#FFF";
	var labels = document.getElementsByTagName("label");
	for(var i = 0; i < labels.length; i++ ){
		var labelText = "lbl" + field.substr(3);
		if(labels[i].id == labelText){
			if(error == true){
				labels[i].style.color = newColor;
			}else if(error == false){
				labels[i].style.color = defaultColor;	
			}
		}
	}
}

/****************
################# function to change input field color ################################################### 
****************/

function changeFieldColor(field,typeOfField,error){
	var newColor = "#CCC";
	var defaultColor = "#FFF";
	var inputs = document.getElementsByTagName(typeOfField);
	for(var i = 0; i < inputs.length; i++ ){
		if(inputs[i].id == field){
			if(error == true){
				inputs[i].style.backgroundColor = newColor;
			}else if(error == false){
				inputs[i].style.backgroundColor = defaultColor;	
			}
		}
	}
}

/****************
################# function to validate age under 18 ################# 
****************/

function validateAge(formDay,formMonth,formYear){

	var year = parseInt(formYear.value);
	var month = parseInt(formMonth.value);
	var day = parseInt(formDay.value);
	var theirDate = new Date(year, month, day);
	var today = new Date();

	var firstDate = Date.parse(theirDate);
	var secondDate= Date.parse(today);
	
	msPerDay = 24 * 60 * 60 * 1000;
	dbd = Math.round((secondDate.valueOf()-firstDate.valueOf())/ msPerDay) + 1;

	//alert(dbd);
	var age;
	
	if (dbd < 5085) {
		age = 14;
		return age;
	}else{
		if (dbd <= 5676) {
			age = 16;
			return age;
		}else{
			age = 0;
			return age;
		}
	}

}

/****************
#################   funcao adicionar erros à div    ################# 
****************/


/* manda escrever na div mostraErros */

function adicionaErros(campo){
	if(document.createTextNode){
		var contentor = document.getElementById("msgError");
		contentor.innerHTML = "";

		for(var i = 0; i < campo.length; i++){
			contentor.appendChild(document.createTextNode(campo[i]));
			contentor.appendChild(document.createElement("br"));
		}
	}
}

/****************
#################   Show tickBox    ################# 
****************/

function tickBox(bool_in){
	if(bool_in)
	{
		if(document.createTextNode){
			if(!document.getElementById("txtParental"))
			{
				var contentor = document.getElementById("tickBox");
				contentor.innerHTML = "<input type=\"checkbox\" value=\"yes\" name=\"txtParental\" id=\"txtParental\" /> Please, confirm you have parental consent.";
			}
		}
	}
	else
	{
		var contentor = document.getElementById("tickBox");
		contentor.innerHTML = "";
	}
}

/****************
#################   Validate tickBox    ################# 
****************/

function validateTickBox ()
{
	if(!isSelectEmpty(document.getElementById("cboYear")) && !isSelectEmpty(document.getElementById("cboMonth")) && !isSelectEmpty(document.getElementById("cboDay"))){
		if(validateAge(document.getElementById("cboDay"),document.getElementById("cboMonth"),document.getElementById("cboYear")) == 16){
			tickBox(true);
		}
		else
		{
			tickBox(false);
		}
		
	}
}

/****************
################# function to remove white spaces from field ###############################################
****************/

function removeFieldSpaces(string) {
	return string.replace(/^\s+|\s+$/, '');
}

