/*
Form Validator
Author: Peter Tornstrand <peter[at]tornstrand[dot]com>
Homepage: http://www.tornstrand.com/scripts/javascript-form-validation/
Date: 2006-07-02
Version: 1.21
*/

/*
Set to false if you don't want the error messages
*/
var err = true;

/*
Set to true if you want modal javascript dialogues instead of DOM messages
*/
var modal = false;

/*
Browser detect, need's a little work
*/
var ie;
if (navigator.appVersion.indexOf("MSIE")!=-1) {
	ie = true; 
} else {
	ie = false;
}

/**
* Loops through the page forms and add's onSubmit events to forms
* with the class name 'validate'.
**/
var addOnSubmitEvent = function() {
    var frms = document.getElementsByTagName('form');
    for (var i=0; i<frms.length; i++) {
        if (frms[i].className.indexOf('validate') != -1) {
            frms[i].onsubmit = function() {
                return validate(this);
            }
        }
    }
}

/**
* Function for displaying error message to user.
* @param frm [Object HTMLFormElement] The form
* @param el [Object HTMLInputElement] Source of the error message
**/
var displayErrorMessage = function(frm, el) {
   
    var labels = document.getElementsByTagName('label');
    var errorMsg = '';
   
    if (el.type=='radio'||el.type=='checkbox') {
        for (var i = 0; i<labels.length; i++) {
            if (labels[i].htmlFor== el.name) {
                errorMsg = 'You must enter a value for ' + labels[i].innerHTML.replace('*','');
            }
        }
    } else {
        for (var i = 0; i<labels.length; i++) {
            if (labels[i].htmlFor==el.id) {
                errorMsg = 'You must enter a value for ' + labels[i].innerHTML.replace('*','');
            }
        }
    }
   
    if (err) {
        if (modal) {
            alert(errorMsg);
            el.focus();
        }
        else {
            if (document.getElementById(frm.id+'_errorMessage')) {
                frm.removeChild( document.getElementById (frm.id+'_errorMessage'));
            }
            var errorDiv = document.createElement('div');
            errorDiv.id = frm.id+'_errorMessage';
            errorDiv.className = 'errorMessage';
            errorDiv.innerHTML = errorMsg;
            frm.insertBefore(errorDiv, frm.childNodes[0]);
            el.focus();
        }
    }
}

/**
* Function called to validate form elements.
* @param frm [Object HTMLFormElement] The form to validate
* @return [Boolean] Did the form validate or not
**/
var validate = function(frm) {
	var el = frm.elements;
	for (var i=0; i<el.length; i++) {
    	if (el[i].className.indexOf('req') != -1) {
			
			// Text, Textarea, File
			if (el[i].type=='text'||el[i].type=='textarea'||el[i].type=='file') {
				if (el[i].value=="") {
					el[i].className = el[i].className + ' error';
 					err == true ? displayErrorMessage(frm, el[i]) : null;
					return false;
 				} else {
					el[i].className = el[i].className.replace('error','');
				}

			}

			// Radio
			else if (el[i].type=='radio') {
				var radiogroup = el[el[i].name];
		        var itemchecked = false;
		        for(var j = 0 ; j < radiogroup.length ; ++j) {
					if(radiogroup[j].checked) {
						itemchecked = true;
						break;
					}
		        }
		        if(!itemchecked) { 
					el[i].className = el[i].className + ' error';
 					err == true ? displayErrorMessage(frm, el[i]) : null;
					return false;
		        }
			}
			
			// Checkbox
			else if (el[i].type=='checkbox') {
				var itemchecked = false;
		        var elems = document.getElementsByTagName("input");
		        for(var j=0; j<elems.length; j++) {
					if(elems[j].type=='checkbox'&&elems[j].name==el[i].name) {
		        		if(elems[j].checked) {
		        			itemchecked = true;
		        			break;
		        		}
		        	}
		        }
		        if(!itemchecked) { 
					el[i].className = el[i].className + ' error';
 					err == true ? displayErrorMessage(frm, el[i]) : null;
					return false;
				}
			}
			
			// Select-one
			else if (el[i].type=='select-one') {
				if (el[i].selectedIndex==0) {
					el[i].className = el[i].className + ' error';
 					err == true ? displayErrorMessage(frm, el[i]) : null;
					return false;
		        } else {
		        	el[i].className = el[i].className.replace('error','');
		        }
			}
			
			// Select-multiple
			else if (el[i].type=='select-multiple') {
				var optionselected = false;
		      	for(var j=0;j<el[i].options.length; ++j) {
		      		if (el[i].options[j].selected) {
		      			optionselected = true;
		      			break;
		      		}
		      	}
		      	if (!optionselected) {
					el[i].className = el[i].className + ' error';
 					err == true ? displayErrorMessage(frm, el[i]) : null;
					return false;
		        } else {
		        	el[i].className = el[i].className.replace('error','');
		        }
			}
		}
	}
	frm.btSubmit.style.display = 'none';
	return true;
}


/**
* Function called when a element changes it's value.
**/
var evaluate = function() {
	for (i=0; i<conds.length; i++) {
		var element = document.getElementsByName(conds[i][0]);
		var elemVal = conds[i][1];
		var elements = document.getElementsByName(conds[i][2]);
		var bol = conds[i][3];
		
		if (ie) {
		/* For Internet Explorer */
			for (var k=0; k<element.length; k++) {
				if (element[k].name==event.srcElement.name) {
					if (event.srcElement.type=='select-one') {
						if(event.srcElement[event.srcElement.selectedIndex].value==elemVal) {
							setState(elements, bol);
						} else {
							setState(elements, !bol);
						}
					} else if (event.srcElement.type=='select-multiple') {
						var optionselected = false;
						for(var j=0; j<event.srcElement.options.length; j++) {
		      				if (event.srcElement.options[j].value==elemVal&&event.srcElement.options[j].selected) {
		      					optionselected = true;
		      					break;
		      				}
		      			}
						if (optionselected) {
							setState(elements, bol);
						} else {
							setState(elements, !bol);
						}
					} else {
						if(event.srcElement.value==elemVal) {
							setState(elements, bol);
						} else {
							setState(elements, !bol);
						}
					}
				}
			}
		} else {
		/* For other browsers */
			for (var k=0; k<element.length; k++) {
				if (element[k].name==this.name) {
					if (this.type=='select-one') {
						if(this[this.selectedIndex].value==elemVal) {
							setState(elements, bol);
						} else {
							setState(elements, !bol);
						}
					} else if (this.type=='select-multiple') {
						var optionselected = false;
						for(var j=0; j<this.options.length; j++) {
		      				if (this.options[j].value==elemVal&&this.options[j].selected) {
		      					optionselected = true;
		      					break;
		      				}
		      			}
						if (optionselected) {
							setState(elements, bol);
						} else {
							setState(elements, !bol);
						}
					} else {
						if(this.value==elemVal) {
							setState(elements, bol);
						} else {
							setState(elements, !bol);
						}
					}
				}
			}
		}
	}
}

/**
* Set a single or a group of elements to required or not required.
* @param elements [Object HTMLCollection] The elements to set required states on
* @param bol [Boolean] Set elements required or not required
**/
var setState = function(elements, bol) {
	if (bol) {
		for (var j=0; j<elements.length; j++) {
			if (elements[j].className.indexOf('req')==-1) {
				elements[j].className += ' req';
			}
		}
	} else {
		for (var j=0; j<elements.length; j++) {
			newClassName = elements[j].className.replace('req','');
			elements[j].className = newClassName;
		}
	}
}

/**
* Attach conditions to form elements.
**/
var attachConditions = function() {
	attachBlurs(document.getElementsByTagName('input'));
	attachBlurs(document.getElementsByTagName('select'));
}

/**
* Attach onBlur or onClick to elements depending on element type.
* @param elements [Object HTLMCollection] The elements to attach onBlur events to
**/
var attachBlurs = function(elements) {
	for (var i=0; i<elements.length; i++) {
		if (elements[i].type=='checkbox'||elements[i].type=='radio') {
			if (ie) {
				elements[i].attachEvent('onclick', evaluate, false);
			} else {
				elements[i].addEventListener('click', evaluate, false);
			}
		} else {
			if (ie) {
				elements[i].attachEvent('onblur', evaluate, false);
			} else {
				elements[i].addEventListener('blur', evaluate, false);
			}
		}
	}
}

/*
Conditions
Syntax: conds.push(Array('element name','element value','element name', false));
You should put your conditions in a seperate file and include in the page.
*/
var conds = Array();

/*
Add onLoad events to start the whole thing
*/
if (ie) {
	window.attachEvent("onload", addOnSubmitEvent, false);
	window.attachEvent("onload", attachConditions, false);
} else {
	window.addEventListener("load", addOnSubmitEvent, false);
	window.addEventListener("load", attachConditions, false);
}
function LimitArea (elementt, limit){
	var v = elementt.value
	if (v.length >= limit){
		elementt.value = v.substring(0,limit-1);
	}
}
function emailCheck (emailStr) {
	/* The following pattern is used to check if the entered e-mail address
   		fits the user@domain format.  It also is used to separate the username
   		from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
   		characters.  We don't want to allow special characters in the address. 
   		These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a 
   		username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
   		which case, there are no rules about which characters are allowed
   		and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   		is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
   		rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   		e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
   		non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
   		For example, in john.doe@somewhere.com, john and doe are words.
   		Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
   		domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	/* Finally, let's start trying to figure out if the supplied address is
   		valid. */
	/* Begin with the coarse pattern to simply break up user@domain into
   		different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
  		/* Too many/few @'s or something; basically, this address doesn't
     	even fit the general mould of a valid e-mail address. */
		alert("E-mail entry looks incorrect (please check @ and .'s)")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	// See if "user" is valid 
	if (user.match(userPat)==null) {
    	// user is not valid
    	alert("User name looks incorrect.")
    	return false
	}
	/* if the e-mail address is at an IP address (as opposed to a symbolic
   		host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
    // this is an IP address
		for (var i=1;i<=4;i++){
	    	if (IPArray[i]>255){
	        	alert("IP address not valid!")
				return false
	    	}
    	}
    	return true
	}
	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		alert("Domain name looks incorrect.")
    	return false
	}
	/* domain name seems valid, but now make sure that it ends in a
   		three-letter word (like com, edu, gov) or a two-letter word,
   		representing country (uk, nl), and that there's a hostname preceding 
   		the domain or country. */
	/* Now we need to break up the domain to get a count of how many atoms
   		it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
    	domArr[domArr.length-1].length>3) {
   		// the address must end in a two letter or three letter word.
   		alert("Email address must end with a 3 character domain name or a 2 character country code.")
   		return false
	}
	// Make sure there's a host name preceding the domain.
	if (len<2) {
   		var errStr="This is an unknown IP address!"
   		alert(errStr)
   		return false
	}
	// If we've gotten this far, everything's valid!
	//alert('La direccion de e-mail introducida parace correcta. Gracias');
}
//Función que determina si un campo está vacío o no
function hasdata(Valor) { 
	for (var i=0; i<Valor.length; i++) { 
   		if ((" \t\n\r").indexOf(Valor.charAt(i))==-1) return true; 
	} 
 	return false; 
}
//Función que confirma la eliminación de registros de los listados
function ValidateDelete (form){
	if (ExistDelete (form)){
		if (confirm('Are you sure to delete?')){
			form.submit();
		}else{
			form.reset();
		}
	}
}
//Función que determina si existen registros chequeados para eliminar
function ExistDelete (form){
	for (i = 0; i < form.elements.length; i++) {
		if (form.elements[i].type == "checkbox" && form.elements[i].checked){  
			return true; 
		}
	}
	return false;
}
//Función que Valida los elementos requeridos en un formulario y si es numerico
function checkform (form){
	var cnjFORM = form.elements; 
	for (var i=0; i<cnjFORM.length; i++){
		if (cnjFORM[i].className.indexOf('requerido')!=-1){ 
			//alert ("campo: " + cnjFORM[i].value);
			if(cnjFORM[i].type != "radio"){
				if (!hasdata(cnjFORM[i].value)){
					alert("You must enter a value for " + cnjFORM[i].name); 
					cnjFORM[i].focus();
					return false;
				}
			}else{
				var radiogroup = cnjFORM[cnjFORM[i].name];
				var itemchecked = false;
				for(var j = 0 ; j < radiogroup.length ; ++j) {
    				if(radiogroup[j].checked) {
	 					itemchecked = true;
	 					break;
					}
   				}
				if(!itemchecked){
					alert("You must enter a value for " + radiogroup[0].name);
					radiogroup[0].focus();
					return false;
				}
			}
		}
		if (cnjFORM[i].className.indexOf('numeric')!=-1){ 
				// Colocar codigo de validacion numerico
	        if (isNaN(cnjFORM[i].value) == true){
				alert (cnjFORM[i].value + " is not NUMBER");	
				cnjFORM[i].focus();
				return false;
			}	
		}	 
	}
	return true;
}
function LimitAttach(file){
	extArray = new Array(".doc", ".docx", ".pdf", ".xls", ".xlsx", ".ppt",".pps",".rtf",".rar",".xml",".zip",".tiff");
	allowSubmit = false;
	while (file.indexOf("\\") != -1)
		file = file.slice(file.indexOf("\\") + 1);
	ext = file.slice(file.indexOf(".")).toLowerCase();
	for (var i = 0; i < extArray.length; i++) {
		if (extArray[i] == ext) { allowSubmit = true; break; }
	}
	if (!allowSubmit){
		alert("You can upload only the following type of files :  " 
		+ (extArray.join("  ")) + "\nPlease, choose a new file "
		+ "check for only one dots (.) in file name");
	}
	return allowSubmit;
}
function LimitImage(file){
	extArray = new Array(".jpg", ".gif",".bmp");
	allowSubmit = false;
	while (file.indexOf("\\") != -1)
		file = file.slice(file.indexOf("\\") + 1);
	ext = file.slice(file.indexOf(".")).toLowerCase();
	for (var i = 0; i < extArray.length; i++) {
		if (extArray[i] == ext) { allowSubmit = true; break; }
	}
	if (!allowSubmit){
		alert("You can upload only the following type of files :  " 
		+ (extArray.join("  ")) + "\nPlease, choose a new file "
		+ "check for only one dots (.) in file name");
	}
	return allowSubmit;
}

	<!--
	// FUNCION DE SOLO NUMEROS
	var nav4 = window.Event ? true : false;
	function acceptNum(evt){ 
	// NOTE: Backspace = 8, Enter = 13, '0' = 48, '9' = 57 
	var key = nav4 ? evt.which : evt.keyCode; 
	return (key <= 13 || (key >= 48 && key <= 57));
	}
	
	//-->



