// /shared/tools/scripts/formvalidator.js
// author: Hamish Wright
// created: 01/12/2007
// modified: 01/12/2007
// Works with form.php to dynamically validate specific types of input - i.e. email address
// Assumes there is only one formbuilder form


var gValidatorFields = new Array();


// change the style class of a div to indicate valid or not valid
function validator_SetDivValidClass(id,newClassName)
{
	var div = document.getElementById(id);
	if(div)
	{
		var divClassName = div.className;
		
		divClassName = divClassName.replace(/formfieldnotvalid/,'');
		divClassName = divClassName.replace(/formfieldvalid/,'');
		
		div.className = divClassName + ' ' + newClassName;
	}
}


function validator_AddField(type, fid, args, required, fldtype)
{
	//alert(type+ fid+ args+ required+ fldtype)
	if(type.length > 0)
	{
		var values = new Array(type,fid,args,required,fldtype);
		gValidatorFields.push(values); 
		validator_ValidateField(type,fid,args,required,fldtype);
	}
}


function validator_ValidateForm()
{
	var isValid = true;
	for(var i=0;i < gValidatorFields.length; i++)
	{
		var retVal = validator_ValidateField(gValidatorFields[i][0],gValidatorFields[i][1],gValidatorFields[i][2], gValidatorFields[i][3], gValidatorFields[i][4])
		if(retVal.code == 1) {isValid = false};
	}
	return isValid;
}


// New validation types should be added here and a corresponding evaluation function
function validator_ValidateField(type, fid, args, required, fldtype)
{
	var retVal = {code:0, msg:""};
	switch(type)
	{
	case "textonly":
		retVal = validator_ValidateTextOnly(fid, args, required, fldtype);
		break;
		
	case "text":
		retVal = validator_ValidateText(fid, args, required, fldtype);
		break;
	
	case "value":
		retVal = validator_ValidateValue(fid, args, required, fldtype);
		break;
	
	case "filename":
		retVal = validator_ValidateFilename(fid, args, required, fldtype);
		break;
		
	case "email":
		retVal = validator_ValidateEmail(fid, args, required, fldtype);
		break;
		
	case "email2":
		retVal = validator_ValidateEmail2(fid, args, required, fldtype);
		break;
	
	case "password":
		retVal = validator_ValidatePassword(fid, args, required, fldtype);
		break;
		
	case "password2":
		retVal = validator_ValidatePassword2(fid, args, required, fldtype);
		break;
	
	case "phone":
		retVal = validator_ValidatePhone(fid, args, required, fldtype);
		break;
	
	case "username":
		retVal = validator_ValidateUsername(fid, args, required, fldtype);
		break;
	
	case "custom":
		retVal = validator_ValidateCustom(fid, args, required, fldtype);
		break;
		
	default:
		break;
	}
	document.getElementById('validatoroutput-'+fid).innerHTML = retVal.msg;
	
	return retVal;
}


function validator_ValidateTextOnly(fid, args, required, fldtype) 
{	
    var error={code:0, msg:"Text is valid."};
    var fld = document.getElementById('field-'+fid);
    var output = document.getElementById('validatoroutput-'+fid);
    var illegalChars = /\W/; // allow letters, numbers, and underscores  

	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldnotvalid'); 
	
    if (fld.value == "" && !(required == "true" || required == true)) { 
    	error={code:0, msg:""};
    	validator_SetDivValidClass('validatoroutput-'+fid,'');
    } else if (fld.value == "") {
        error = {code:1, msg:"Please enter some text"};
    } else if (illegalChars.test(fld.value)) {
        error = {code:1, msg:"Text contains illegal characters."};
    } else {
        validator_SetDivValidClass('validatoroutput-'+fid,'formfieldvalid');
    }
    return error;
}


function validator_ValidateFilename(fid, args, required, fldtype)
{
	var error={code:0, msg:"Filename is valid."};
    var fld = document.getElementById('field-'+fid);
    var output = document.getElementById('validatoroutput-'+fid);
	var illegalChars = /[^\w\.]/; // allow letters, numbers, dots, and underscores
	var fullpath = fld.value
	var filename = fullpath.substr(fullpath.lastIndexOf('\\')+1)
	
	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldnotvalid');
	
  	if (fld.value == "" && !(required == "true" || required == true)) { 
    	error={code:0, msg:""};
    	validator_SetDivValidClass('validatoroutput-'+fid,'');
    } else if (fld.value == "") {
      	error = {code:1, msg:"Please press the browse button and select a file."};
	} else if (illegalChars.test(filename)) { 
  		error = {code:1, msg:"Filename must contain only letters, numbers, and underscores."};
	} else { 
		validator_SetDivValidClass('validatoroutput-'+fid,'formfieldvalid');
  	}
    
  	return error;
}


function validator_ValidateUsername(fid, args, required, fldtype) 
{
	var argArray = args.split(",");
	var min = 5;
	if(argArray[0] != null) { if(argArray[0] > 0) { min = argArray[0]; } }
	var max = 15;
	if(argArray[1] != null) { if(argArray[1] > 0) { max = argArray[1]; } }
	
    var error={code:0, msg:"Username is valid."};
    var fld = document.getElementById('field-'+fid);
    var output = document.getElementById('validatoroutput-'+fid);
    var illegalChars = /\W/; // allow letters, numbers, and underscores  

	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldnotvalid'); 
	
    if (fld.value == "" && !(required == "true" || required == true)) { 
    	error={code:0, msg:""};
    	validator_SetDivValidClass('validatoroutput-'+fid,'');
    } else if (fld.value == "") {
        error = {code:1, msg:"Please enter a username."};
    } else if ((fld.value.length < min) || (fld.value.length > max)) {
        error = {code:1, msg:"Username must be between "+min+" and "+max+" characters long."};
    } else if (illegalChars.test(fld.value)) {
        error = {code:1, msg:"Username contains illegal characters."};
    } else {
        validator_SetDivValidClass('validatoroutput-'+fid,'formfieldvalid');
    }
    return error;
}


<!-- args: (pswdId) -->
function validator_ValidatePassword2(fid, args, required, fldtype) 
{
	var argArray = args.split(",");
	var pswdId;
	if(argArray[0] != null) { pswdId = argArray[0]; }
	
	var error = {code:0, msg:"Passwords match."};
    var fld = document.getElementById('field-'+fid);
    var output = document.getElementById('validatoroutput-'+fid);
	var pswd1 = document.getElementById('field-'+pswdId);
	
	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldnotvalid');
	
	if (fld.value == "" && !(required == "true" || required == true)) { 
    	error={code:0, msg:""};
    	validator_SetDivValidClass('validatoroutput-'+fid,'');
    } else if (fld.value == "") {
        error = {code:1, msg:"Re-enter your password."};
    } else if (pswd1.value != fld.value) {
    	error = {code:1, msg:"Passwords do not match."};
    } else {
    	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldvalid');
    }
    
	return error;
}


<!-- args: (minLength,maxLength,numueralsRequired) -->
function validator_ValidatePassword(fid, args, required, fldtype) 
{
	var argArray = args.split(",");
	var min = 7;
	if(argArray[0] != null) { if(argArray[0] > 0) { min = argArray[0]; } }
	var max = 15;
	if(argArray[1] != null) { if(argArray[1] > 0) { max = argArray[1]; } }
	var isNumsrequired = 1;
	if(argArray[2] != null) { isNumsrequired = argArray[2]; }
 
    var error = {code:0, msg:"Password is valid."};
    var fld = document.getElementById('field-'+fid);
    var output = document.getElementById('validatoroutput-'+fid);
    var illegalChars = /[\W_]/; // allow only letters and numbers
    var regexletters = /[a-zA-Z]+/;
    var regexnumbers = /[0-9]+/;
 
 	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldnotvalid');
 	
    if (fld.value == "" && !(required == "true" || required == true)) { 
    	error={code:0, msg:""};
    	validator_SetDivValidClass('validatoroutput-'+fid,'');
    } else if (fld.value == "") {  
        error = {code:1, msg:"Please enter a password."};
    } else if ((fld.value.length < min) || (fld.value.length > max)) {
        error = {code:1, msg:"Password must be between "+min+" and "+max+" characters long."};
    } else if (illegalChars.test(fld.value)) {
        error = {code:1, msg:"Password contains illegal characters."};
    } else if ((isNumsrequired == 1) && !((regexletters.test(fld.value)) && (regexnumbers.test(fld.value)))) {
   		error = {code:1, msg:"Password must be a combination of letters AND numbers."};
	} else {
        validator_SetDivValidClass('validatoroutput-'+fid,'formfieldvalid');
    }
    
   	return error;
}  


function validator_Trim(s)
{
	return s.replace(/^\s+|\s+$/, '');
}


function validator_ValidateEmail(fid, args, required, fldtype) 
{
    var error={code:0, msg:"Email is valid."};
    var fld = document.getElementById('field-'+fid);
    var output = document.getElementById('validatoroutput-'+fid);
    var tfld = validator_Trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
   	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldnotvalid');
   	
    if (fld.value == "" && !(required == "true" || required == true)) { 
    	error={code:0, msg:""};
    	validator_SetDivValidClass('validatoroutput-'+fid,'');
    } else if (fld.value == "") {  
        error = {code:1, msg:"Please enter an email address."};
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        error = {code:1, msg:"Email address is not valid."};
    } else if (fld.value.match(illegalChars)) {
        error = {code:1, msg:"Email address contains illegal characters."};
    } else {
        validator_SetDivValidClass('validatoroutput-'+fid,'formfieldvalid');
    }
    return error;
}


<!-- args: (emlId) -->
function validator_ValidateEmail2(fid, args, required, fldtype) 
{
	var argArray = args.split(",");
	var emlId;
	if(argArray[0] != null) { emlId = argArray[0]; }
	
	var error = {code:0, msg:"Email addresses match."};
    var fld = document.getElementById('field-'+fid);
    var output = document.getElementById('validatoroutput-'+fid);
	var pswd1 = document.getElementById('field-'+emlId);
	
	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldnotvalid');
	
	if (fld.value == "" && !(required == "true" || required == true)) { 
    	error={code:0, msg:""};
    	validator_SetDivValidClass('validatoroutput-'+fid,'');
    } else if (fld.value == "") {
        error = {code:1, msg:"Re-enter your email address."};
    } else if (pswd1.value != fld.value) {
    	error = {code:1, msg:"Email addresses do not match."};
    } else {
    	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldvalid');
    }
    
	return error;
}


<!-- args: (length) -->
function validator_ValidatePhone(fid, args, required, fldtype) 
{
	var argArray = args.split(",");
	var phoneLength;
	if(argArray[0] != null) { phoneLength = argArray[0]; }
	
    var error={code:0, msg:"Phone number is valid."};
    var fld = document.getElementById('field-'+fid);
    var output = document.getElementById('validatoroutput-'+fid);
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');

//	~validator_SetDivValidClass('fieldbox-'+fid,'formfieldnotvalid');
	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldnotvalid');
	
	if (fld.value == "" && !(required == "true" || required == true)) {
    	error={code:0, msg:""};
//    	~validator_SetDivValidClass('fieldbox-'+fid,'');
    	validator_SetDivValidClass('validatoroutput-'+fid,'');
    } else if (fld.value == "") {
        error = {code:1, msg:"Please enter a phone number."};
    } else if (isNaN(parseInt(stripped))) {
        error = {code:1, msg:"Phone number contains illegal characters."};
    } else if (!(stripped.length == phoneLength) && (phoneLength.length > 0)) {
        error = {code:1, msg:"Phone number must be "+phoneLength+" digits long. Please include the area code."};
    } else {
//    	~validator_SetDivValidClass('fieldbox-'+fid,'formfieldvalid');
    	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldvalid');
    }
    
    return error;
}


function validator_getvalue(fid, type)
{
	var value;
	
	switch(type)
	{
		case 'radio':
			value = radio_getvalue(fid); 
		break;
		
		case 'checkbox': case 'disclaimer':
			var fld = document.getElementById('field-'+fid);
			if(fld != null) value = fld.checked;  
		break;
		
		case 'multicheckbox':
			value = multicheckbox_getvalue(fid);
		break;
		
		default:
			var fld = document.getElementById('field-'+fid);
			if(fld != null) value = fld.value; 
		break;
	}
	
	return value;
}


function validator_ValidateValue(fid, args, required, fldtype) 
{	
    var error={code:0, msg:""};
    var value = validator_getvalue(fid,fldtype);
    var output = document.getElementById('validatoroutput-'+fid);

	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldnotvalid'); 
	
	// alert(fldtype);
	
    if (value == "" && !(required == "true" || required == true)) { 
    	error={code:0, msg:""};
    	validator_SetDivValidClass('validatoroutput-'+fid,'');
    } else if (value == "") {
    	if (fldtype == "checkbox" || fldtype == "disclaimer")
    	{
    		error = {code:1, msg:"Please tick the box"};
    	}
    	else if (fldtype == "multicheckbox")
    	{
    		error = {code:1, msg:"Please tick at one or more boxes"};
    	}
    	else
    	{
        	error = {code:1, msg:"Please enter some text"};
        }
    } else {
        validator_SetDivValidClass('validatoroutput-'+fid,'formfieldvalid');
    }
    return error;
}


function validator_ValidateText(fid, args, required, fldtype) 
{	
    var error={code:0, msg:"Text is valid."};
	var value = validator_getvalue(fid,fldtype);
    var output = document.getElementById('validatoroutput-'+fid);

	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldnotvalid'); 
	
    if (value == "" && !(required == "true" || required == true)) { 
    	error={code:0, msg:""};
    	validator_SetDivValidClass('validatoroutput-'+fid,'');
    } else if (value == "") {
        error = {code:1, msg:"Please enter some text"};
    } else {
        validator_SetDivValidClass('validatoroutput-'+fid,'formfieldvalid');
    }
    return error;
}


function validator_ValidateCustom(fid, args, required, fldtype) 
{
//	var argArray = args.split(",");
//	var regex = new RegExp("");
//	if(argArray[0] != null) { regex = new RegExp(argArray[0]); }
	var testPositive = true;
//	if(argArray[1] != null) { if(argArray[1] == false || argArray[1] == "false") { testPositive = false; } }
	var validMsg = "Field is valid.";
//	if(argArray[2] != null) { validMsg = argArray[2]; }
	var errorMsg = "Field is invalid.";
//	if(argArray[3] != null) { errorMsg = argArray[3]; }
	var emptyMsg = "Please enter some text.";
//	if(argArray[4] != null) { emptyMsg = argArray[4]; }

	//no options allowed
	var regex = new RegExp(args);
	
    var error={code:0, msg:validMsg};
    var fld = document.getElementById('field-'+fid);
    var output = document.getElementById('validatoroutput-'+fid);

	validator_SetDivValidClass('validatoroutput-'+fid,'formfieldnotvalid'); 
	
	regexResult = regex.test(fld.value);
	if(!testPositive) regexResult = !regexResult;
	
    if (fld.value == "" && !(required == "true" || required == true)) { 
    	error={code:0, msg:""};
    	validator_SetDivValidClass('validatoroutput-'+fid,'');
   	} else if (fld.value == "") {
       	error = {code:1, msg:emptyMsg};
    } else if (!regexResult) {
        error = {code:1, msg:errorMsg};
    } else {
        validator_SetDivValidClass('validatoroutput-'+fid,'formfieldvalid');
    }
    return error;
}
