// --------------------------------------------
// verify
// by John Kepler (jkepler@aha.org)
//
// Classname controls what gets validated
// 		like: r_postcode.  If second part of classname
// 		is found field is validated if filled in.  If 
// 		field is also optional, it can be left blank.
// Switch statement associates second part of classname like
// 		classname = postcode 
// 		use validation function checkPostcode.
// Also checks first part of classname for required
// 		r is required 
// 		o is optional
//
// EXAMPLES:
// o_textarea - Optional. No validation performed.
// o_phone - Optional. Valided to be phone number but can be left blank.
// r_textarea - Required. Must have something entered.
// r_email - Required.  Must validate as email address.
// 
// TO ADD ADDTIONAL VALIDATION
// 1. Add additional classname to verify as user exits field
// 2. Add additional case statements to associate classname with validation function
// 3. Add additional function to check a certain type of field
// --------------------------------------------

// register all possible verification rules
// all rules that apply to verifying data as it is entered
var verifyrules = {
	// START EDITABLE
	// 1. Add additional classname to verify as user types
	'form.ahaform .r_email' : function(el){
		el.onblur = function(){
			var status = chkField(this);
			return status;
		}
	},
	'form.ahaform .o_email' : function(el){
		el.onblur = function(){
			var status = chkField(this);
			return status;
		}
	},
	'form.ahaform .o_phone' : function(el){
		el.onblur = function(){
			var status = chkField(this);
			return status;
		}
	},
	// END EDITABLE
	'form.ahaform input' : function(el){
		if (isReq(el)) {
			el.onblur = function(){
				var status = chkField(this);
				return status;
			}
		}
	}
};
Behaviour.register(verifyrules);
// all rules that apply to submitting the form
var submitrules = {
	
	'form.ahaform #submit' : function(el){
		el.onclick = function(){
			var reqelements = document.getElementsBySelector("form.ahaform input");
			var reqelements2 = document.getElementsBySelector("form.ahaform select");
			var status = true;
			var substatus = true;
			for (i=0;element=reqelements[i];i++){
					substatus = chkField(element);
					//console.log("substatus: "+substatus);
					//console.log("status: "+status);
					if (substatus == false) { status = false; }
			}
			for (i=0;element=reqelements2[i];i++){
					substatus = chkField(element);
					//console.log("substatus: "+substatus);
					//console.log("status: "+status);
					if (substatus == false) { status = false; }
			}
			//console.log("final status: "+status);
			return status;
		}
	}
};
Behaviour.register(submitrules);

// --------------------------------------------
// chkField
// Common code to start validation routines:
// Returns true (validation passed) or 
// 		false (validation failed)
// Classname controls what gets validated
// 		like: r_postcode.  If second part of classname
// 		is found field is validated if filled in.  If 
// 		field is also optional, it can be left blank
// Switch statement associates second part of classname like
// 		classname = postcode)  
// 		use validation function checkPostcode.
// Also checks first part of classname for required
// 		r is required 
// 		o is optional
// --------------------------------------------

function chkField(obj) {
	var val = obj.value;
	//alert('type='+obj.type+'; name='+obj.name+'; val='+val);
	var req = "f";
	if (isReq(obj)) { req = "t"; }
	var status = false;
	var rtn = "";
	var className = new Array();
	className = obj.className.split("_");
	// START EDITABLE
	// 2. Add additional case statements here
	switch (className[1]) {
		case "email": rtn=checkEmail(val,req); break;
		case "phone": rtn=checkPhone(val,req); break;
		case "postcode": rtn=checkPostcode(val,req); break;
		case "username": rtn=checkUsername(val,req); break;
		case "password": rtn=checkPassword(val,req); break;
		default: rtn = "";
	}
	// END EDITABLE
	// Generic check for required values
	if (req == "t" && rtn == "") {
		var objType = obj.type;

		switch (objType) {
			case "text": rtn=isEmpty(val); break;
			case "textarea": rtn=isEmpty(val); break;
			case "checkbox": rtn=checkCheckbox(val); break;
			case "radio": rtn=checkRadio2(obj); break;
			case "hidden": rtn=""; break;
			case "submit": rtn=""; break;
			default: rtn = "";
		}
			//case "select": rtn=checkDropdown(val); break;		
	}
	status = chkError(obj,rtn);
	return status;
}

// 3. Add additional function to check a certain type of field


// email
function checkEmail (strng,req) {
	var error="";
	if (strng == "" && req == "t") {
	   error = "You didn't enter an email address.\n";
	}

    var emailFilter=/^.+@.+\..{2,3}$/;
    if (!(emailFilter.test(strng))) { 
       error = "Please enter a valid email address. It should look like 'username@domain.com'.\n";
    }
    else {
//test email for illegal characters
       var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
         if (strng.match(illegalChars)) {
          error = "The email address contains illegal characters. It should look like 'username@domain.com'.\n";
       }
    }
return error;    
}


// phone number - strip out delimiters and check for 10 digits
function checkPhone (strng,req) {
	var error = "";
	if (strng == "" && req == "t") {
	   error = "You didn't enter a phone number.\n";
	} else {
		if (strng != "") {
			var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
			if (isNaN(parseInt(stripped))) {
			   error = "The phone number contains illegal characters. It should look like '(555) 555-5555' or '5555555555'.\n";
		  
			}
			if (!(stripped.length == 10) && strng != "") {
				error = "The phone number is the wrong length. Make sure you included an area code.\n";
			} 
		}
    }
return error;
}

// postcode number - strip out delimiters and check for 10 digits
function checkPostcode (strng,req) {
	var error = "";
	if (strng == "" && req == "t") {
	   error = "You didn't enter a postal code.\n";
	} else {
		if (strng != "") {
			var stripped = strng.replace(/[\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
			if (isNaN(parseInt(stripped))) {
			   error = "The postal code contains illegal characters. It should look like '60606' or '60606-1001'.";
		  
			}
			//if ((!(stripped.length == 5) && strng != "") || (!(stripped.length == 9) && strng != "") ){
			//	error = "The postal code is the wrong length. It should be 5 or 9 digits.\n";
			//}
			if (strng == "") {
				error = "";
			} else if ((stripped.length < 5 || stripped.length > 9) || (stripped.length > 5 && stripped.length < 9)) {
				error = "The postal code is the wrong length. It should be 5 or 9 digits.\n";
			}
		}
    }
return error;
}

// password - between 6-8 chars, uppercase, lowercase, and numeral

function checkPassword (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a password.\n";
}

    var illegalChars = /[\W_]/; // allow only letters and numbers
    
    if ((strng.length < 6) || (strng.length > 8)) {
       error = "The password is the wrong length.\n";
    }
    else if (illegalChars.test(strng)) {
      error = "The password contains illegal characters.\n";
    } 
    else if (!((strng.search(/(a-z)+/)) && (strng.search(/(A-Z)+/)) && (strng.search(/(0-9)+/)))) {
       error = "The password must contain at least one uppercase letter, one lowercase letter, and one numeral.\n";
    }  
return error;    
}    


// username - 4-10 chars, uc, lc, and underscore only.

function checkUsername (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a username.\n";
}


    var illegalChars = /\W/; // allow letters, numbers, and underscores
    if ((strng.length < 4) || (strng.length > 10)) {
       error = "The username is the wrong length.\n";
    }
    else if (illegalChars.test(strng)) {
    error = "The username contains illegal characters.\n";
    } 
return error;
}       


// non-empty textbox

function isEmpty(strng) {
var error = "";
  if (strng.length == 0) {
     error = "This required text area has not been filled in.\n"
  }
return error;	  
}

// was textbox altered

function isDifferent(strng) {
var error = ""; 
  if (strng != "Can\'t touch this!") {
     error = "You altered the inviolate text area.\n";
  }
return error;
}

// exactly one radio button is chosen
function checkRadio(checkvalue) {
var error = "";
   if (!(checkvalue)) {
       error = "Please check a radio button.\n";
    }
return error;
}

// checkRadio does not funtion properly
// checkRadio2 was created to replace checkRadio functionality
function checkRadio2(obj) {
var error = "";
var rg = document.getElementsByName(obj.name);
var checkvalue = 0;
for (var i=0; i<rg.length; ++i){
	if (rg[i].checked) { checkvalue = 1;}
}
   if (checkvalue == 0) {
       error = "Please check a radio button.\n";
    }
return error;
}

// exactly one radio button is chosen ...?
function checkCheckbox(checkvalue) {
var error = "";
   if (!(checkvalue)) {
       error = "Please check a radio button.\n";
    }
return error;
}


// valid selector from dropdown list
function checkDropdown(choice) {
var error = "";
    if (choice == 0) {
    error = "You didn't choose an option from the drop-down list.\n";
    }    
return error;
}

// check the object classname to see if it is required (starts with "r_")
function isReq(obj) {
	var reqMatch = /^r_.*$/; 
	if (reqMatch.test(obj.className)) {
		return true;
	} else {
		return false;	
	}
}

// check the error string for error message
function chkError(obj,strng) {
	if (strng == "") {
		rmError(obj);
		return true;			
	} else {
		rmError(obj);
		mkError(obj,strng);
		return false;
	}
}

// add error message
function mkError(obj,strng) {
	element = Builder.node('div',{className:'formerror'},strng);
	newobj = $(obj).parentNode.appendChild(element);
	new Effect.Highlight(newobj, {duration: 8});
	return false;
}

// remove error message
function rmError(obj) {
	var elements = obj.parentNode.getElementsByTagName("div");
	//if (elements.length < 0) {
	try {
		//Run some code here
		for (var j = 0; j < elements.length; j++) {
			var removed = obj.parentNode.removeChild(elements[j]);
		}
	} catch(err) {
		//Handle errors here
		//console.log(err);
	}
	//}
}
