/*SUBE EL TAMAÑO DE LA PRIMERA LETRA DE CADA PALABRA*/
function ucwords(str) {
	return str.replace(/\b\w/gi, function(c,i,s) { return c.toUpperCase(); }); 
}

function Validator(frmname){
	this.formobj=document.forms[frmname];
	if(this.formobj == undefined){
		//alert("BUG: couldnot get Form object "+frmname);
		//this.formobj = document.getElementById(frmname);
	}
	//guarda el contenido del evento "onsubmit" anterior en otro lugar y lo borra
	//no es importante
	if(this.formobj.onsubmit){
	 this.formobj.old_onsubmit = this.formobj.onsubmit;
	 this.formobj.onsubmit=null;
	}
	else{
	 this.formobj.old_onsubmit = null;
	}
	//asigno los eventos (funciones) cuando llamo a, por ejemplo miValidador.addValidation(param1, param2, etc)
	//cuando hago el submit del form, viene aca
	this.formobj.onsubmit=form_submit_handler;
	//cuando agrego una validacion
	this.addValidation = add_validation;
	//si le paso una funcion para que ejecute al final
	this.setAddnlValidationFunction=set_addnl_vfunction;
	//borra todas las validaciones
	this.clearAllValidations = clear_all_validations;
	//llamo a esta funcion por AJAX cuando no conviene hacer el submit del form
	this.submitById = form_submit_handler;
}

function set_addnl_vfunction(functionname){
  this.formobj.addnlvalidation = functionname;
}

//borra todos los validationset
function clear_all_validations(){
	for(var itr=0;itr < this.formobj.elements.length;itr++){
		this.formobj.elements[itr].validationset = null;
	}
}

//cuando se hace un submit del form (o se llama de afuera), realiza la validación
function form_submit_handler(){
	//si noRet llega a ser verdadero, retorna falso y no hace el submit a otra página
	var noRet = false;
	//defino el div que se llenará con los errores
	var errordiv = new ErrorDiv();
	//callFocus sirve para que haga la función .focus() del primer input que no se pudo validar
	var callFocus = true;
	
	if (this.elements != undefined){
		//cuando NO viene por AJAX, es un submit común y corriente del form
		//uso estos valores para realizar controles y afectar el form
		var container = this.elements;
		var container2 = this;
	}
	else{
		//cuando viene por ajax, el "this" está vacío y tengo que usar el "formobj" who knows why
		var container = this.formobj;
		var container2 = this.formobj;
	}
	for(var itr=0;itr < container.length;itr++){
		//si el elemento actual tiene una validación seteada para hacer
		if(container[itr].validationset){
			//si la validación devuelve FALSE
			if (!container[itr].validationset.validate()){
				//si le asignaron la clase para tomar cuando tenga error Y un string
				//como, por ejemplo, 'Nombre es un campo requerido'
		   		if (container[itr].errorClass && container[itr].strError){
		   			//toma la clase de error (se ve el borde rojo, por ejemplo)
					container[itr].className = container[itr].errorClass;
					//el DIV de error toma el texto de error
					errordiv.addLine(container[itr].strError);
		   		}
		   		//si callFocus es TRUE, llama al ".focus()" y se pone falso
		   		if (callFocus){
		   			container[itr].focus();
		   			callFocus = false;
		   		}
		   		// hay campos que no corresponden; el submit no se hace
				noRet = true;
			} else {
				//el input está bien; toma la class que tuvo antes de ser validado 
				container[itr].className = container[itr].previousClass;
			}
		}
	}
	if (noRet) {
		//creo y muestro el div
		errordiv.createDiv(container2);
		//el submit no se hace
		return false;
	}
	//llamo a una funcion posterior, si hay alguna
	if(this.addnlvalidation){
	  str =" var ret = "+this.addnlvalidation+"()";
	  eval(str);
    if(!ret) return ret;
	}
	return true;
}

//cuando agrego una validación
//itemname: nombre del input
//descriptor: condición para la validación
//errstr: texto de error
//errclass: clase de error
function add_validation(itemname,descriptor,errstr,errclass){
  if(!this.formobj){
	  //alert("BUG: the form object is not set properly");
		return;
	}//if
	var itemobj = this.formobj[itemname];
	if(!itemobj){
		//alert("BUG: Couldnot get the input object named: "+itemname);
		return;
	}
	//si, por ejemplo, el input "nombre" no tiene la propiedad ".validationset", le asigno un objeto "ValidationSet"
	if(!itemobj.validationset){
		itemobj.validationset = new ValidationSet(itemobj);
	}
	//agrego la validación para el input, de forma que un input puede tener varias validaciones
	itemobj.validationset.add(descriptor,errstr);
	if (!itemobj.previousClass) {
		//guardo la clase que tenía el input antes de ser sometido a validación
		itemobj.previousClass = itemobj.className;
	}
	//asigno la clase de error
	itemobj.errorClass = errclass;
}

/*Definición del Objeto ValidationDesc*/
//cada objeto "ValidationSet" puede tener adheridos varios objetos "ValidationDesc"
function ValidationDesc(inputitem,desc,error){
	this.desc=desc;
	this.error=error;
	this.itemobj = inputitem;
	this.validate=vdesc_validate;
}

//cuando se llama a "vset_validate()", cada vez que se llama a "this.vSet[itr].validate()",
//en realidad viene acá, que es donde realmente llama "V2validateData", que hace la validación
function vdesc_validate(){
	if(!V2validateData(this.desc,this.itemobj,this.error)){
//		this.itemobj.focus();
		return false;
 	}
	return true;
}

/*Objeto ValidationSet*/
function ValidationSet(inputitem){
    this.vSet=new Array();
	this.add= add_validationdesc;
	this.validate= vset_validate;
	this.itemobj = inputitem;
}

//crea y agrega un objeto "ValidationDesc" al "ValidationSet"
function add_validationdesc(desc,error){
	this.vSet[this.vSet.length] = new ValidationDesc(this.itemobj,desc,error);
}

//recorre todas las "ValidationDesc" del "ValidationSet", y si alguno devuelve false,
//la función devuelve false
function vset_validate(){
   for(var itr=0;itr<this.vSet.length;itr++){
	   if(!this.vSet[itr].validate()){
		   return false;
		 }
	 }
	 return true;
}

function validateEmailv2(email){
	// a very simple email validation checking. 
	// you can add more complex email checking if it helps 
    if(email.length <= 0){
	  return true;
	}
    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;
      }// if
      return true;
    }
	return false;
}

function V2validateData(strValidateStr,objValue,strError){ 
    var epos = strValidateStr.search("="); 
    var  command  = ""; 
    var  cmdvalue = ""; 
    var name = ucwords(objValue.name.replace('_',' '));
    if(epos >= 0){ 
     command  = strValidateStr.substring(0,epos); 
     cmdvalue = strValidateStr.substr(epos+1); 
    } 
    else{ 
     command = strValidateStr; 
    } 
    switch(command){ 
        case "req": 
        case "required":{ 
           if(eval(objValue.value.length) == 0){ 
              if(!strError || strError.length ==0){ 
                strError = name + " : Required Field"; 
              }//if 
              objValue.strError = strError;
              return false; 
           }//if 
        break;             
         }//case required 
        case "maxlength": 
        case "maxlen":{ 
             if(eval(objValue.value.length) >  eval(cmdvalue)){ 
               if(!strError || strError.length ==0){ 
                 strError = name + " : "+cmdvalue+" characters maximum "; 
               }//if 
               objValue.strError = strError + "\n[Current length = " + objValue.value.length + " ]"; 
               return false; 
             }//if 
        break; 
          }//case maxlen 
        case "minlength": 
        case "minlen":{ 
             if(eval(objValue.value.length) <  eval(cmdvalue)){ 
               if(!strError || strError.length ==0){ 
                 strError = name + " : " + cmdvalue + " characters minimum  "; 
               }//if               
               objValue.strError = strError + "\n[Current length = " + objValue.value.length + " ]";
               return false;                 
             }//if 
        break; 
            }//case minlen 
        case "alnum": 
        case "alphanumeric":{ 
              var charpos = objValue.value.search("[^A-Za-z0-9]"); 
              if(objValue.value.length > 0 &&  charpos >= 0){ 
               if(!strError || strError.length ==0){ 
                  strError = name+": Only alpha-numeric characters allowed "; 
                }//if 
                objValue.strError = strError;// + "\n [Error character position " + eval(charpos+1)+"]"; 
                return false; 
              }//if 
              break; 
           }//case alphanumeric 
        case "num": 
        case "numeric":{ 
              var charpos = objValue.value.search("[^0-9]"); 
              if(objValue.value.length > 0 &&  charpos >= 0){ 
                if(!strError || strError.length ==0){ 
                  strError = name+": Only digits allowed "; 
                }//if               
                objValue.strError = strError;// + "\n [Error character position " + eval(charpos+1)+"]"; 
                return false; 
              }//if 
        break;
           }//numeric 
        case "alphabetic": 
        case "alpha":{ 
              var charpos = objValue.value.search("[^A-Za-z]"); 
              if(objValue.value.length > 0 &&  charpos >= 0){ 
                  if(!strError || strError.length ==0) 
                { 
                  strError = name+": Only alphabetic characters allowed "; 
                }//if                             
                objValue.strError = strError;// + "\n [Error character position " + eval(charpos+1)+"]"; 
                return false; 
              }//if 
        break; 
           }//alpha 
		case "alnumhyphen":{
              var charpos = objValue.value.search("[^A-Za-z0-9\-_]"); 
              if(objValue.value.length > 0 &&  charpos >= 0){ 
                  if(!strError || strError.length ==0) 
                { 
                  strError = name+": characters allowed are A-Z,a-z,0-9,- and _"; 
                }//if                             
                objValue.strError = strError;// + "\n [Error character position " + eval(charpos+1)+"]"; 
                return false; 
              }//if 			
		break;
			}
        case "email":{ 
               if(!validateEmailv2(objValue.value)){ 
                 if(!strError || strError.length ==0){ 
                    strError = name+": Enter a valid Email address "; 
                 }//if                                               
                 objValue.strError = strError; 
                 return false; 
               }//if 
        break;
          }//case email 
        case "lt": 
        case "lessthan":{ 
            if(isNaN(objValue.value)){ 
              objValue.strError = name+": Should be a number "; 
              return false; 
            }//if 
            if(eval(objValue.value) >=  eval(cmdvalue)){ 
              if(!strError || strError.length ==0){ 
                strError = name + " : value should be less than "+ cmdvalue; 
              }//if               
              objValue.strError = strError; 
              return false;                 
             }//if             
        break; 
         }//case lessthan 
        case "gt": 
        case "greaterthan":{ 
            if(isNaN(objValue.value)){ 
              objValue.strError = name+": Should be a number "; 
              return false; 
            }//if 
             if(eval(objValue.value) <=  eval(cmdvalue)){ 
               if(!strError || strError.length ==0){ 
                 strError = name + " : value should be greater than "+ cmdvalue; 
               }//if               
               objValue.strError = strError; 
               return false;                 
             }//if             
        break; 
         }//case greaterthan 
        case "regexp":{ 
		 	if(objValue.value.length > 0){
	            if(!objValue.value.match(cmdvalue)){ 
	              if(!strError || strError.length ==0){ 
	                strError = name+": Invalid characters found "; 
	              }//if                                                               
	              objValue.strError = strError; 
	              return false;                   
	            }//if 
			}
        break; 
         }//case regexp 
        case "dontselect":{ 
            if(objValue.selectedIndex == null){ 
              alert("BUG: dontselect command for non-select Item"); 
              return false; 
            } 
            if(objValue.selectedIndex == eval(cmdvalue)){ 
             if(!strError || strError.length ==0){ 
              strError = name+": Please Select one option "; 
              }//if                                                               
              objValue.strError = strError; 
              return false;                                   
             } 
         break; 
         }//case dontselect 
        case "tel":{ 
              var charpos = objValue.value.search("^[0-9-\.\s\(\)\/#\*\+]*$"); 
              if(objValue.value.length > 0 &&  charpos < 0){ 
                  if(!strError || strError.length ==0) 
                { 
                  strError = name+": Only numbers, '-()/' and whitespaces are allowed "; 
                }//if     
                objValue.strError = strError; 
                return false; 
              }//if 
        break; 
           }//tel 
        case "date":{ 
              var charpos = objValue.value.search("^[0-9]{4}\-(0[0-9]|1[0,1,2])\-(0[0-9]|[1,2][0-9]|3[0,1])$"); 
              if(objValue.value.length > 0 &&  charpos < 0){ 
                  if(!strError || strError.length ==0) 
                { 
                  strError = name+": Must have a format like 'YYYY-MM-DD'";
                }//if     
                objValue.strError = strError; 
                return false; 
              }//date 
        break; 
           }//tel 
        case "money":{ 
//              var charpos = objValue.value.search("^[\$](.)?[0-9\.\,]+$"); 
              var charpos = objValue.value.search("^[0-9\.\,]+$"); 
              if(objValue.value.length > 0 &&  charpos < 0){ 
                  if(!strError || strError.length ==0){ 
                  strError = name+": Invalid characters found";
                }//if     
                objValue.strError = strError; 
                return false; 
              }//if 
        break; 
           }//money 
    }//switch 
    return true; 
}

/*Objeto ErrorDiv sirve para acumular lineas con errores*/
function ErrorDiv(){
	this.errstr = new Array();
	this.addLine = ed_addline;
	this.createDiv = ed_creatediv;
}

function ed_addline(str){
	this.errstr[this.errstr.length] = str;
}

/*crea y muestra el div*/
/*
hacen falta varias clases como:

.td_alert{
	color: FF3333;
	font-family: Verdana;
	font-weight: bolder;
}

.td_vitems{
	padding-left: 25px;
	font-size: 10px;
	
}

.divx{
	cursor: pointer;
	font-size: 10px;
}

.show-errors{
	background-color: #DDDDDD;
	height: 45px;
	width: 400px;
	color: reg(80,80,80);
	position: absolute;
	font-family: Verdana;
	border: 1px solid grey;
	padding: 5px 5px 5px 5px;
	filter:alpha(opacity=95);
	opacity: 0.95;
	-moz-opacity:0.95;
	margin: auto auto 0px auto;
	left: 50%;
	margin-left: -200px;
	top: 108px;
	overflow: auto;
}

IMPORTANTE: evitar el uso del id "errdiv" ya que está usado aquí
*/
function ed_creatediv(obj){
	inputs = obj.getElementsByTagName('input');
	len = inputs.length;
	errdivName = 'errdiv';
	errdiv = document.getElementById(errdivName);
	ahead = '<table><tr><td valign="top" width="10%"><font class="td_alert">ALERT:</font></td><td class="td_vitems" width="87%">';
	afoot = '</td><td valign="top" width="3%"><div onclick="document.getElementById(\''+errdivName+'\').style.display = \'none\'" class="divx">X</div></td></tr></table>';
	
	errstr = '';
	var first = true;
	//acoplo todas las lineas
	for (i = 0; i < this.errstr.length; i++){
		if (first){
			first = false;
		} else {
			errstr = errstr + '<br>';
		}
		errstr = errstr + this.errstr[i];
	}
	if (!errdiv){
		//si el div no existe, lo creo
		var errdiv = document.createElement('div');
		errdiv.setAttribute('id',errdivName);
		//'class' sirve para Firefox+
		errdiv.setAttribute('class','show-errors');
		//'className' sirve para Explorer+
		errdiv.setAttribute('className','show-errors');
		errdiv.innerHTML = ahead + errstr + afoot;
		errdiv.style.display = '';
		obj.appendChild(errdiv);
	} else {
		//si el div existe, le cambio el texto de adentro
		errdiv.innerHTML = ahead + errstr + afoot;
		errdiv.style.display = '';
	}
}