/**
 * Form checker v 0.1
 * @author: Gulam Moledina - gulam.moledina@transcontinental.ca
 *
 **/   


//************************************
// USER FUNCTIONS :
function addRequiredElement(id){
	requiredElementsById[requiredElementsById.length] = id;
}
function addMatchingFields(array_fields){
	emailMatchingFields = array_fields;
}
function setStatusMssgId(id){
	status_mssg_id = id;
}
function setErrorMssgId(id){
	error_mssg_id = id;
}
//************************************



//************************************
// INTERNAL VARIABLES :
var status_mssg_id = null;
var error_mssg_id = null;
var error_mssg = "";
var requiredElementsById = Array();
var emailMatchingFields = Array();
var requiredFilled = false;
var matchingOK = false;
var emailsValid = false;
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var maxWords = 300;
var maxWordsTreshold = 15;
var currentKey;
var currentWordCount;
//************************************



//************************************
// SETTINGS :
var fieldBorder_ok = "1px green solid" ;
var fieldBorder_nok = "1px red solid";
//************************************



//************************************
// INTERNAL FUNCTIONS :
function checkRequired(){
	requiredFilled = true;
	for (var e = 0; e < requiredElementsById.length; e++){
		var element = document.getElementById(requiredElementsById[e]);
		if((element.value == "")||(element.selectedIndex==0) ) {
			element.style.border = fieldBorder_nok;
			requiredFilled = false;
		}
		else {
			element.style.border = fieldBorder_ok;
		}
	}
	if(! requiredFilled)
		error_mssg += "All required fields must be completed <br />";
		 
	return requiredFilled;
}

function emailsMatching(){
	matchingOK = true;
	var el1 = document.getElementById(emailMatchingFields[0]);
	var el2 = document.getElementById(emailMatchingFields[1]);
	
	if( el1 == null ){
		return true;
	}
	else if( el2 == null ){
		return true;
	}
	else {
		//var el1 = document.getElementById(emailMatchingFields[0]);
		//var el2 = document.getElementById(emailMatchingFields[1]);
		
			if(el1.value !== el2.value){
				//alert("diff");
				matchingOK = false;
				el1.style.border = fieldBorder_nok;
				el2.style.border = fieldBorder_nok;
			}
		
		if(! matchingOK)
			error_mssg += "Email fields should match<br />";
			
		return matchingOK;
	}
}

function emailsValidation(){
		var email1Valid = true;
		var email2Valid = true;
		var el1 = document.getElementById(emailMatchingFields[0]);
		var el2 = document.getElementById(emailMatchingFields[1]);
		
		if(el1 == null){
			email1Valid = true;
		}
		else {
			email1Valid = validEmail(el1.value);
		}
		if(el2 == null){
			email2Valid = true;
		}
		else {
			email2Valid = validEmail(el2.value);
		}
		
		emailsValid = (email1Valid && email2Valid );
		
		if(! emailsValid) {
			error_mssg += "Email(s) are not valid<br />";
			emailsValid = false; //to have boolean 'false' value, not null
		}
			
		if(! email1Valid)
			el1.style.border = fieldBorder_nok;
			
		if(! email2Valid)
			el2.style.border = fieldBorder_nok;
		
		return emailsValid;
}

function validEmail(email){
	return email.match(emailExp);
}

function init(){
	error_mssg = "";
}

function checkAll(){
	//return false;
	if(status_mssg_id != null)
		document.getElementById(status_mssg_id).innerHTML = "Processing...";
		
	init();
	
	requiredFilled = checkRequired();
	matchingOK = emailsMatching();
	emailsValid = emailsValidation();

	
	
	var status = requiredFilled && matchingOK && emailsValid;
	
	if(! status && error_mssg_id ){
		if(status_mssg_id != null)
			document.getElementById(status_mssg_id).innerHTML = "Errors :"
		if(error_mssg_id )
			document.getElementById(error_mssg_id ).innerHTML = "<div>" + error_mssg + "</div>"
	}
	else {
		if(status_mssg_id != null)
			document.getElementById(status_mssg_id).innerHTML = "Sending submission..."
	}
	return  status;
}
//************************************
// Max words functions:

/**
 * 
 * in the textarea tag : id="primary_text" onkeyup="CountWords("primary_text","word_count")" onkeypress="checkKeycode(event);" 
 */ 
function CountWords(fieldid, displayid){
	var this_field = document.getElementById(fieldid);
	
	var fullStr = this_field.value + " ";
	var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
	var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
	var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
	var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
	var splitString = cleanedStr.split(" ");
	currentWordCount = splitString.length -1;
	
	var displayText = currentWordCount + " ";
	
	if(currentWordCount <= 1 )
		displayText += "word";
	else
		displayText += "words";
	
	if(currentWordCount > maxWords + maxWordsTreshold - 1 ){
		displayText = "<span style=\"color:red;\">"+displayText+"</span>";
	}
	else if(currentWordCount > maxWords ){
		displayText = "<span style=\"color:orange;\">"+displayText+"</span>";
	}
	else{
		displayText = "<span style=\"color:green;\">"+displayText+"</span>";
	}
	document.getElementById(displayid).innerHTML = displayText;
}

function checkKeycode(e){
	// if aEvent is null, means the Internet Explorer event model,
	// so get window.event.
	var IE5 = false;

	if (!e) var e = window.event;
	if (e.keyCode) { 
		IE5= true; 
		code = e.keyCode;
	}
	else if (e.which) 
		code = e.which ;

	if(this.currentWordCount > this.maxWords + this.maxWordsTreshold ){
		if((code != 57) && (code != 8)){
			if(IE5) e.returnValue = false;
			else e.preventDefault(); 
		}
		else {
			return true;
		}
	}		
}
