/*
	FUNCIONES AUXILIARES
*/
//Basicamente cambia el punto o coma decimal por una coma, ademas de chequear la entrada
//Checkea que la entrada no tenga puntos de miles (Solo puede haber un punto o una coma que representaria la coma decimal)
function im_chk_In(p_In){
	var resu=p_In.toString().replace(/ /g,"");			//Eliminacion de espacios en blanco
	if (resu.match(/^(\d*)(\.|,)?(\d*)$/g)==null) return ("NOK");	//Comprueba que el contenido de la cadena sea un numero con un solo signo de puntuacion , o .
	else {
		resu=resu.replace(/\./g,",");				//Reemplaza punto por coma si lo hay
		if (resu.match(/^,?$/g)!=null) return ("0");		//Si la cadena empieza y termina por coma se devuelve un 0
		else if (resu.match(/^,/)!=null) return ("0"+resu);	//Si la cadena empieza por coma se devuelve un cero concatenado con el resto de la cadena
		else if (resu.match(/,$/)!=null) return (resu.replace(/,/,"")); //Si la cadena termina por una coma se elimina
		else return(resu);
	}
}

function isEmpty(inputStr){
var numCaracStr = inputStr.length;
var espacios = inputStr.split(" ");
var numEspacios = espacios.length - 1;

   if (inputStr == null || inputStr == ""){
     return true;
   } else {
     if (numEspacios == numCaracStr){
		return true;
	 } else {
		return false;
	 }
   }
}

function maxLen(inputStr, max){
   if (inputStr.length > max){
      return false;
   }
   return true;
}

function isPosInteger(inputVal){
   inputStr = inputVal.toString();
   for (var i = 0; i < inputStr.length; i++){
       var oneChar = inputStr.charAt(i);
       if (oneChar < "0" || oneChar > "9"){
          return false;
       }
   }
   return true;
}

function isInteger(inputVal){
   inputStr = inputVal.toString();
   for (var i = 0; i < inputStr.length; i++){
       var oneChar = inputStr.charAt(i);
       if (i == 0 && oneChar == "-"){
          continue;
       }
       if (oneChar < "0" || oneChar > "9"){
          return false;
       }
   }
   return true;
}

function isNumber(inputVal){
   oneDecimal = false;
   inputStr = inputVal.toString();
   for (var i = 0; i < inputStr.length; i++){
       var oneChar = inputStr.charAt(i);
       if (i == 0 && oneChar == "-"){
          continue;
       }
       if (oneChar == "." && !oneDecimal){
          oneDecimal = true;
          continue;
       }
       if (oneChar < "0" || oneChar > "9"){
          return false;
       }
   }
   return true;
}

function isPosNumber(inputVal){
   oneDecimal = false;
   inputStr = inputVal.toString();
   for (var i = 0; i < inputStr.length; i++){
       var oneChar = inputStr.charAt(i);
       if (oneChar == "." && !oneDecimal){
          oneDecimal = true;
          continue;
       }
       if (oneChar < "0" || oneChar > "9"){
          return false;
       }
   }
   return true;
}

function chkFecha(){
   var testMo,testDay,testYr,inpMo,inpDay,inpYr,msg;
   var inp;
   status = "";

   inp = gField.value;
   // Si existen separadores intentaremos la conversión a fecha
   if (inp.indexOf("/") > 0){

   // Si la longitud es 10, las fechas deben tener separadores   
   } else if (gField.value.length == 10){
      inp = gField.value;

   // Si la longitud es 8, se insertaran separadores
   } else if (gField.value.length == 8){
      if (!isPosNumber(gField.value)){
         alert(gNomField + " solo debe contener números.");
         setTimeout("doSelection(gField)",0);
         return false;
      }
      // Insertar separadores:
      inp = gField.value;
      gField.value = inp.substr(0,2) + "/" + inp.substr(2,2) + "/" + inp.substr(4,4);
      inp = gField.value;

   } else {
      alert(gNomField + ": debe consistir en 8 ó 10 caracteres (DDMMAAAA ó DD/MM/AAAA).");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   //Descomponer los datos de entrada
   inpDay = parseInt(inp.substring(0,inp.indexOf("/")),10);
   inpMo  = parseInt(inp.substring((inp.indexOf("/")+1), inp.lastIndexOf("/")),10);
   inpYr  = parseInt(inp.substring((inp.lastIndexOf("/")+1),inp.length),10);
   var testDate = new Date(inpMo.toString()+"/"+inpDay.toString()+"/"+inpYr.toString());
   //Descomponer el objeto fecha creado
   testMo  = testDate.getMonth()+1;
   testDay = testDate.getDate();
   testYr  = testDate.getFullYear();
   //Comprobar que parseInt() ha funcionado en componentes de entrada
   if (isNaN(inpMo) || isNaN(inpDay) || isNaN(inpYr)){
      msg = "El formato de la " + gNomField + " no es correcto.";
   }
   //Comprobar que la conversion a objeto fecha ha funcionado
   if (isNaN(testMo)||isNaN(testDay)||isNaN(testYr)){
      msg = "Se ha detectado un error en la " + gNomField + ".";
   }
   //Comprobar que los valores coinciden
   if (testMo != inpMo || testDay != inpDay || testYr != inpYr){
      msg = "La " + gNomField + " no es correcta.";
   }
   if (msg){
      //Si hay mensaje es que algo ha fallado
      alert(msg);
      setTimeout("doSelection(gField)",0);
      return false;
   } else {
      //everything ’s OK;if browser supports new date method,
      //show just date string in status bar
      status = (testDate.toLocaleDateString) ? testDate.toLocaleDateString() : gNomField + " correcta!";
      return true;
   }
}

/*  Chequeo para fechas opcionales  */
function chkFechaOpc(){
   if (isEmpty(gField.value)){ return true };
   if (!chkFecha()){
      return false;
   }
   return true;
}

function chkRequerido(){
   status = "";
   if (isEmpty(gField.value)){
      alert(gNomField + " es un campo requerido.");
      setTimeout("doSelection(gField)",0);
      return false;
   } else {
      status = "";
      return true;
   }
}

function chkDivisa(){
   status = "";

   if (isEmpty(gField.value)){
      return true;
   }

   if (gField.value.length != 3){
      alert(gNomField + ": debe escribir 3 caracteres.");
      setTimeout("doSelection(gField)",0);
      return false;
   }
   
   gField.value = gField.value.toUpperCase()
   return true;
}

function chkImporte(){
   status = "";

   if (isEmpty(gField.value)){
      return true;
   }

   // 12 enteros, punto o coma decimal y 2 decimales
   if (gField.value.length > 15){
      alert(gNomField + ": escriba un máximo de 15 caracteres.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   if (im_chk_In(gField.value)=="NOK"){
      alert(gNomField + " en formato incorrecto.");
      setTimeout("doSelection(gField)",0);
      return false;
   }
   
   return true;
}

function chkBanco(){
   status = "";

   if (isEmpty(gField.value)){ return true };

   if (gField.value.length < 10){
      alert(gNomField + ": escriba un mínimo de 10 caracteres.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   return true;
}

function chkSucursal(){
   status = "";

   if (isEmpty(gField.value)){
      return true;
   }

   if (gField.value.length > 4){
      alert(gNomField + ": escriba un máximo de 4 caracteres.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   if (!isPosInteger(gField.value)){
      alert(gNomField + " solo debe contener números.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   return true;
}

function chkProducto(){
   status = "";

   if (isEmpty(gField.value)){
      return true;
   }

   if (gField.value.length > 8){
      alert(gNomField + ": escriba un máximo de 8 caracteres.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   if (!isPosInteger(gField.value)){
      alert(gNomField + " solo debe contener números.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   return true;
}

function chkUsuario(){
   status = "";

   if (isEmpty(gField.value)){
      alert(gNomField + " es un campo requerido.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   if (gField.value != "*" && gField.value.length < 8){
      alert(gNomField + ": debe escribir 8 caracteres ó un * para selecionar todos.");
      setTimeout("doSelection(gField)",0);
      return false;
   }
   
   gField.value = gField.value.toUpperCase()
   return true;
}

function chkPass(){
   status = "";

   if (gField.value != gForm.clave.value){
      alert("Ambas contraseñas deben ser iguales.");
      setTimeout("doSelection(gField)",0);
	  return false;
   } else {
      status = "";
      return true;
   }


   return true;
}

function chkMesAnn(){
   var cTmp, aTmp;

   if (isEmpty(gField.value)){
      alert(gNomField + " es un campo requerido.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   if (gField.value.length > 7){
      alert(gNomField + ": escriba mes y año en el formato MM/AAAA.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   if (gField.value.indexOf("/") != 2){
      alert(gNomField + ": escriba mes y año en el formato MM/AAAA.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   cTmp = gField.value;
   aTmp = cTmp.split("/");

   if (!isPosInteger(aTmp[0]+aTmp[1])){
      alert(gNomField + " solo debe contener números.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   if (parseInt(aTmp[0]) < 1 || parseInt(aTmp[0]) > 12){
      alert(gNomField + " mes incorrecto.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   if (parseInt(aTmp[1]) < 1990 || parseInt(aTmp[1]) > 2999){
      alert(gNomField + " año incorrecto.");
      setTimeout("doSelection(gField)",0);
      return false;
   }

   return true;
}

//separate function to accommodate IE timing problem
function doSelection(fld){
   fld.focus();
   fld.select();
}

/*
<INPUT TYPE="text" NAME="phone" SIZE="10" onChange="parent.validate(window,this,'Telefono',‘isPhone’)">
The first is a reference to the frame containing the document that is calling the
function (passed as a reference to the current window). The second parameter is a
reference to the form control element itself (using the this operator). After that,
you see one or more individual validation function names as strings. This last
design allows more than one type of validation to take place with each call to vali-
date()(for example, in case a field must check for a data type and check that the
field is not empty).
*/

//main validation function called by form event handlers
function validate(frame,field,nomcampo,method){
   gFrame = frame;
   gForm  = window.document.forms[0];
   gField = window.document.forms[0].elements[field.name];
   //gField = window.frames[frame.name].document.forms[0].elements[field.name]
   gNomField = nomcampo;
   var args = validate.arguments;
   for (i = 3; i < args.length; i++){
       if (!dispatchLookup[args[i]].doValidate()){
          return false;
       }
   }
   return true;
}

/*
onSubmit="return checkForm(this)"
And the following code fragment is an example of a checkForm()function. A
separate isDateFormat()validation function called here checks whether the field
contains an entry in the proper format meaning that it has likely survived the
range checking and format shifting of the real-time validation check.
*/

/* Validacion del formulario de Busquedas Incidencias*/
function chkFormBusqueda(form){
   if (!validate(window,form.idproducto,"IdProducto", "chkProducto")){return false};
   return true;
}

/* Validacion del formulario de Alta de información*/
function chkFormAlta(form){
   if (!validate(window,form.company,"Empresa", "chkRequerido")){return false};
   if (!validate(window,form.domici,"Domicilio", "chkRequerido")){return false};
   if (!validate(window,form.postal,"Postal", "chkRequerido")){return false};
   if (!validate(window,form.local,"Localidad", "chkRequerido")){return false};
   if (!validate(window,form.provin,"Provincia", "chkRequerido")){return false};
   if (!validate(window,form.pais,"País", "chkRequerido")){return false};
   if (!validate(window,form.tel,"Teléfono", "chkRequerido")){return false};
   if (!validate(window,form.email,"Email", "chkRequerido")){return false};
   if (!validate(window,form.persona,"Persona de Contacto", "chkRequerido")){return false};
   if (!validate(window,form.message,"Comentario", "chkRequerido")){return false};
   return true;
}

/* Validacion del formulario de Contacto*/
function chkFormContacto(form){
   if (!validate(window,form.name,"Nombre", "chkRequerido")){return false};
   if (!validate(window,form.email,"Email", "chkRequerido")){return false};
   if (!validate(window,form.subject,"Asunto", "chkRequerido")){return false};
   if (!validate(window,form.message,"Comentario", "chkRequerido")){return false};
   return true;
}

/*

Begin validation dispatching mechanism
*/
function dispatcher(validationFunc){
   this.doValidate = validationFunc;
}

var gFrame, gForm, gField, gNomField;

var dispatchLookup = new Array();
dispatchLookup["chkRequerido"]  = new dispatcher(chkRequerido);
dispatchLookup["chkProducto"]   = new dispatcher(chkProducto);
dispatchLookup["chkFecha"]      = new dispatcher(chkFecha);
dispatchLookup["chkDivisa"]     = new dispatcher(chkDivisa);
dispatchLookup["chkImporte"]    = new dispatcher(chkImporte);
dispatchLookup["chkBanco"]      = new dispatcher(chkBanco);
dispatchLookup["chkSucursal"]   = new dispatcher(chkSucursal);
dispatchLookup["chkUsuario"]    = new dispatcher(chkUsuario);
dispatchLookup["chkFechaOpc"]   = new dispatcher(chkFechaOpc);
dispatchLookup["chkPass"]       = new dispatcher(chkPass);
dispatchLookup["chkMesAnn"]     = new dispatcher(chkMesAnn);