
//////// Validation library V2
//////////////////////////////
var errored = false;            // Global for validate function
var exClassName = new Object(); // Global for Changed classnames
var styleAdded = false;         // Global for checking sytle status
function validate(elem,type,option){	// Main function
	var option = (option)? option : "";
	if(!styleAdded){			// Add style for Error warnings
		var style = document.createElement('style');
		var sprop = '.error{ border:2px red solid; background:#FCFCFC; }\
		             .Errortext{ color:#FF0000;font-family:"Trebuchet MS"; font-size:11px; }';
		style.setAttribute("type", "text/css");
		if (style.styleSheet){   // for IE
			style.styleSheet.cssText = sprop;
		} else {
			var newStyle = document.createTextNode(sprop);
			style.appendChild(newStyle);
		}
		document.getElementsByTagName('head')[0].appendChild(style);
		styleAdded = true; //don't add again.
	}
	///////////
	//Checking for mail validation
	var checkmail = function(email){
		var splitted = email.match("^(.+)@(.+)$");
			if(splitted == null) return false;
			if(splitted[1] != null )   {
				var regexp_user=/^\"?[\w-_\.]*\"?$/;
				if(splitted[1].match(regexp_user) == null) return false;  
			}
			if(splitted[2] != null)  {
				var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
				if(splitted[2].match(regexp_domain) == null) {
					var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
					if(splitted[2].match(regexp_ip) == null) return false; 
				}
				return true; 
			}
		return false;
	}
	//////////////
	// Function to run onsubmit;
	var onSubmit = function(elem){
		errored = false;
		var form = document.forms[elem];
		for(var node = 0;node < form.length; node++)
			if((""+form[node].onblur).match("validate"))
				form[node].onblur();
		if(errored)	return false; 
		else form.submit();
	}
	
	//////////////
	// Function to set error messages
	var getMsg = function(type){
		switch(type){
			case "LessThan":           return "This field's length should be less than (" + option['LessThan'] + ")"
			case "GreaterThan":        return "This field's length should be greater than (" + option['GreaterThan'] + ")"
			case "Alphabetic":         return "Cannot contain non-alphabetic characters."
			case "RequiredAlphabetic": return "This field is required and cannot contain non-alphabetic characters."
			case "Numeric":            return "Cannot contain non-numeric characters."
			case "RequiredNumeric":    return "This field is required and cannot contain non-numeric characters."
			case "Email":              return "Fyll i en riktig epost-adress."
			case "Required":           return "Du behöver fylla i detta fält."
			case "RequiredTerms":      return "Du måste godkänna villkoren."
      case "confirm":            return "Values should match each other"
			case "Regex":              return "This entry does not match (" + option + ")."
			default:                   return "Undefined Error Message"
		}
	}
	
	/////////////
	// Function to check is error printed?
	var checkForErrorDiv = function(elem){
		for(var node = 0;node < elem.parentNode.childNodes.length; node++)
			if(elem.parentNode.childNodes[node].className == "Errortext")
				return true;
		return false;
	}
	
	/////////////
	// Function to define errors and print messages
	var error = function(elem, type, message){
		correct(elem);
		if(!checkForErrorDiv(elem)){
			div = document.createElement("div");
			div.innerHTML = (message)? message : getMsg(type);
			div.className = "Errortext";
			elem.parentNode.appendChild(div);
			//elem.parentNode.insertBefore(div, elem.nextSibling);
		}
		if(elem.className != "error")
			exClassName[elem.name] = elem.className;
		if(elem.type != "checkbox" && elem.type != "radio"){
			elem.className = "error";
		}
		errored = true;
		return true;
	}
	
	/////////////
	// Function to revert Errored fields
	var correct = function(elem){
		var parent = elem.parentNode;
		for(x = 0; x < parent.childNodes.length; x++){
			var node = parent.childNodes[x];
			if(node){
				if(node.className == "Errortext")
					node.parentNode.removeChild(node);
				if(node.className == "error")
					node.className = exClassName[node.name];
			}
		}
	}
	
	///////////////
	// Check for optional validations
	if(option['LessThan']){
		if(elem.value.length >= option['LessThan']){
			error(elem,"LessThan",option['message']);
			return false;
		}else
			correct(elem);
	}
	if(option['GreaterThan']){
		if(elem.value.length <= option['GreaterThan']){
			error(elem,"GreaterThan", option['message']);
			return false;
		}else
			correct(elem);
	}
    if(option.confirm){
		if(elem.value.toLowerCase() != $(option.confirm).value.toLowerCase()){
			error(elem, "confirm", option['message']);
            error($(option.confirm), "confirm", option['message']);
			return false;
		}else{
            correct(elem);
            correct($(option.confirm));
        }
			
	}
		
	//////////////
	// Make all the validations
	switch(type){
		case "Alphabetic":
			var charpos = elem.value.search(/[^a-zA-Z\s\-\_]/);
			if(charpos >= 0) error(elem,type,option['message']); else correct(elem);
			break;
		case "RequiredAlphabetic":
			if(elem.value.length <= 0) error(elem,type,option['message']); 
			else{
				var charpos = elem.value.search(/[^a-zA-Z\s\-\_]/);
				if(charpos >= 0) error(elem,type,option['message']); else correct(elem);
			}
			break;
		case "Numeric":
			var charpos = elem.value.search(/[^0-9\.\,\s\-\_]/);
			if(charpos >= 0) error(elem,type,option['message']); else correct(elem);
			break;
		case "RequiredNumeric":
			if(elem.value.length <= 0) error(elem,type,option['message']); 
			else{
				var charpos = elem.value.search(/[^0-9\.\,\s\-\_]/);
				if(charpos >= 0) error(elem,type,option['message']); else correct(elem);
			}
			break;
		case "Email":
			if(!checkmail(elem.value)) error(elem,type,option['message']); else correct(elem);
			break;
		case "Required":
			if(elem.type == "checkbox" || elem.type == "radio"){
				var parent = elem.parentNode;
				var ok = false;
				for(x = 0; x < parent.childNodes.length; x++)
					if(parent.childNodes[x].checked == true)
						ok = true;
				if(ok) correct(elem,true); else error(elem,type,option['message']);
			}else{
				if(elem.options)	
					// Here can be edited for checking text to "Please Select one" or similar text
					// in this example it looks for blank <option> to give error
					if(elem.options[elem.selectedIndex].text.length <= 3) error(elem,type,option['message']); else correct(elem);
				else
					if(elem.value.length <= 3) error(elem,type,option['message']); else correct(elem);
			}
			break;
				case "RequiredTerms":
			if(elem.type == "checkbox" || elem.type == "radio"){
				var parent = elem.parentNode;
				var ok = false;
				for(x = 0; x < parent.childNodes.length; x++)
					if(parent.childNodes[x].checked == true)
						ok = true;
				if(ok) correct(elem,true); else error(elem,type,option['message']);
			}else{
				if(elem.options)	
					// Here can be edited for checking text to "Please Select one" or similar text
					// in this example it looks for blank <option> to give error
					if(elem.options[elem.selectedIndex].text.length <= 3) error(elem,type,option['message']); else correct(elem);
				else
					if(elem.value.length <= 3) error(elem,type,option['message']); else correct(elem);
			}
			break;
		case "Regex":
			if(elem.value.match(option['expression'])) correct(elem);
			else error(elem,type,option['message']);
			break;
		default:	// Default is for defining the form and setting onsubmit function
			var form = document.forms[elem]
			form.onsubmit = function(){ onSubmit(elem); return false; };
			break;
	}		
}
