//ABCversionCBA
//version=20060328085237#Z:/VOB_ODPPUB/ODPPUB/Web Content/ODPPUB/docs/ODP/js/campos.js@@/main/RSUidamr2006032404/1;
//XYZversionZYX


//--------------------------funciones globales (camuflan la existencia del objeto global)-------------------------------------------

//función para validar todas las fechas (antes del submit)
function fechasValidar(){
	return gobjetoGlobal.validar();
}
//establece el idioma de la aplicación
function idiomaEstablecer(cIdma){
	gobjetoGlobal.setIdioma(cIdma);
}


//--------------------------objeto global (al que acceden las funciones globales)-------------------------------------------
//creamos un objeto único para almacenar todos los objetos fecha
if (gobjetoGlobal==null){
   var gobjetoGlobal= new objetoGlobal();
}


//objeto global (solo existe uno)
function objetoGlobal(){
	this.objetosFecha =[];
	this.cIdioma="ESP";
}

//establece el idioma
objetoGlobal.prototype.setIdioma= function (cIdioma){
	 this.cIdioma = cIdioma;
}

//añade un objeto fecha a la lista de objetos
objetoGlobal.prototype.anadir= function (objetoFecha){
	 n= this.objetosFecha.length;
	 this.objetosFecha[n] = objetoFecha;
}


//validamos todos los objetos fecha de la pantalla
objetoGlobal.prototype.validar= function(){
	for(i=0;i<this.objetosFecha.length; i++){
		if (! this.objetosFecha[i].validarFecha()){  //si un objeto fecha no es válido terminamos
		   return false;
		}
	}
	return true;						   
}

//--------------------------objeto fecha-------------------------------------------
//constructor 
//	obj objeto sobre el que se define
//	Parámetros
//		objDia	campo del dia (puede no existir y en ese caso se pasa null)
//		objMes	campo del mes
//		objAno	campo del año
//		tError	el mensaje de error a mostrar en caso de error
//      tErrorAno mensaje a mostrar si el año tiene menos de 4 dígitos (si no se especifican funciona un defecto según el idioma)
function campoFecha(objDia, objMes, objAno, tError, tErrorAno) {
   gobjetoGlobal.anadir(this);

   this.objDia = objDia;   
   this.objMes = objMes;
   this.objAno = objAno;
   this.tError  = tError;
   this.tErrorAno  = (tErrorAno!=null)? tErrorAno: (gobjetoGlobal.cIdioma=="ESP")? "el año debe de tener 4 dígitos":"o ano debe de ter 4 díxitos" ;
   objAno.tagFecha=this;  //guardamos una referencia al objeto

   //definimos los cmapos individuales como numéricos
   if (objDia!=null){   
   	  new campoNumerico(objDia);
   }
   if (objMes!=null){      
      new campoNumerico(objMes);
   }	  
   new campoNumerico(objAno);

   this.oldonblur=objAno.onblur; //capturamos el evento por si existiera
   this.objAno.onblur= this.validarFecha;

}


//retorna el valor de una fecha en formato aaaammdd
campoFecha.prototype.valor= function (e){
	//cuando se produce el evento this es el objeto del evento, pero si se llama directamente, this es el objeto campoFecha,
    //luego en el caso de métodos sobre eventos, hay que unificar el objeto this para que funcione en ambos casos							   
	var objeto;
	if (this.objAno){
	   objeto=this.objAno;
	}else{
	  objeto=this;
	}  			


	var retorno="";
	retorno+= (objeto.tagFecha.objAno==null)?"": objeto.tagFecha.objAno.value;
	retorno+= (objeto.tagFecha.objMes==null)?"": (objeto.tagFecha.objMes.value!="")?  "/"+objeto.tagFecha.objMes.value: "";	
	retorno+= (objeto.tagFecha.objDia==null)?"": (objeto.tagFecha.objDia.value!="")? "/"+objeto.tagFecha.objDia.value: "";	
	return retorno;
}

//valida que la fecha sea correcta
campoFecha.prototype.validarFecha= function (e){
	//cuando se produce el evento this es el objeto del evento, pero si se llama directamente, this es el objeto campoFecha,
    //luego en el caso de métodos sobre eventos, hay que unificar el objeto this para que funcione en ambos casos							   
	var objeto;
	if (this.objAno){
	   objeto=this.objAno;
	}else{
	  objeto=this;
	}  			
	
	control= (objeto.tagFecha.objDia!=null)?  objeto.tagFecha.objDia:(objeto.tagFecha.objMes!=null)?  objeto.tagFecha.objMes: (objeto.tagFecha.objAno!=null)?  objeto.tagFecha.objAno:"";

	//comprobación de que el año tiene 4 caracteres
	if ((objeto.value.length<4)&&(objeto.value.length>0)){
		alert(objeto.tagFecha.tErrorAno);
		setTimeout("control.focus()", 100);		
		return false;			
	}
	//si solo hay año la validación ha acabado
    if ((objeto.tagFecha.objDia == null) && (objeto.tagFecha.objMes == null)){
	   //valida que la fecha sea correcta
	   if (objeto.tagFecha.oldonblur != null)	{
    	  resultado=objeto.tagFecha.oldonblur(e);
   	   }
	   if (!resultado){
		  setTimeout("control.focus()", 100);	   
	   }
	   return resultado;
	}

	dia= (objeto.tagFecha.objDia==null)? "": objeto.tagFecha.objDia.value;
	//si se dejan en blanco se aceptan como válidas
    if ( (objeto.tagFecha.objAno.value == "") &&
         (objeto.tagFecha.objMes.value == "") &&
         (dia == "") ) {
	   //valida que la fecha sea correcta
	   if (objeto.tagFecha.oldonblur != null)	{
    	  resultado=objeto.tagFecha.oldonblur(e);
   	   }
	   if (!resultado){
		  setTimeout("control.focus()", 100);	   
	   }
	   
	   return resultado;

    }

	dia= (objeto.tagFecha.objDia==null)? "01": objeto.tagFecha.objDia.value;
    var test = new Date(objeto.tagFecha.objAno.value, objeto.tagFecha.objMes.value-1, dia);
    ano=test.getYear();
    ano= (ano<1000)?1900+ano:ano;
    if ( (objeto.tagFecha.objAno.value == ano) &&
         (objeto.tagFecha.objMes.value == test.getMonth()+1) &&
         (dia == test.getDate()) ){
	   //valida que la fecha sea correcta
	   if (objeto.tagFecha.oldonblur != null)	{
    	  resultado=objeto.tagFecha.oldonblur(e);
   	   }
	   if (!resultado){
		  setTimeout("control.focus()", 100);	   
	   }
	   
	   return resultado;

        }
    else{
		alert(objeto.tagFecha.tError);
		setTimeout("control.focus()", 100);
//		setTimeout("document.form1.dmtrclcn.focus()", 100);		
		
        return false;	
     }
 
} 


//--------------------------fin objeto fecha-------------------------------------------

//--------------------------objeto campo numérico-------------------------------------------
//constructor 
//	obj objeto sobre el que se define
//	siCerosIzq: si se rellena con ceros por la izquierda o no. Por defecto se rellena
// align: si se quiere expresar el alineamiento (y no aceptar el de defecto)
function campoNumerico(obj, siCerosIzq, align) {

   this.obj = obj;
   obj.tag=this;  //guardamos una referencia al objeto
   this.siCerosIzq=  (typeof(siCerosIzq) == 'undefined')? true: siCerosIzq;             

   obj.style.textAlign =(typeof(align) != 'undefined')? align:   this.siCerosIzq  ? "left": "right";



   
   this.numbersonly= o_numbersonly;   
   
   //campos definidos para utilizar la rutina de control de carácteres tecleados común con campoImporte	   
   this.qDecimales =  0;
   this.cSepDec    =  '';
   this.cSepMiles  =  '';

   if (this.siCerosIzq){	   	   
   	  this.oldonblur=obj.onblur; //capturamos el evento por si existiera
   	  this.obj.onblur= this.numeroConCeros;
  	  this.oldonfocus=obj.onfocus; //capturamos el evento por si existiera
   	  this.obj.onfocus= this.numeroSinCeros;		   
   }

   //se deja este evento con el modelo antiguo debido a un error que parece tener el mozilla para tratar el nuevo
   this.oldonkeypress=obj.onkeypress; //capturamos el evento por si existiera
   this.obj.onkeypress= this.numbersonly;

}


//controlo que solo se puedan teclear caracteres numéricos
//myfield campo a controlar
//la variable this hace referencia al control que produce el evento
function o_numbersonly(e)
{
	var key;
	var keychar;
	var retorno;

	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	   

	keychar = String.fromCharCode(key);


	// control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) )
	   retorno= true
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	   retorno= true
	// decimal 
	else if (this.tag.qDecimales && (keychar == this.tag.cSepDec)){
	     if (this.tag.obj.value.search("["+this.tag.cSepDec+"*]") == -1 && this.tag.obj.value.length != 0)
		   retorno= true;	   
	     else
		   retorno= false;	   
	}
	else
    	retorno= false;	   

	if (retorno){
    	if (this.tag.oldonkeypress != null)	    {
   	    	retorno= this.tag.oldonkeypress(e);
	   	}
	}
  	return retorno;
}

//incorpora ceros por la izquierda al abandonar un campo
campoNumerico.prototype.numeroConCeros=  function (e){

	var objeto;
	if (this.objAno){
	   objeto=this.objAno;
	}else{
	  objeto=this;
	}  			
	

	if ((objeto.value.length>0) && (objeto.value.length<objeto.size)){
		objeto.value=repeatString("0", (objeto.size-objeto.value.length) )+objeto.value;
	}
//   this.value= 	importeConFormato(num,numDec, decSep, thousandSep);
	retorno=true; 
  	if (objeto.tag.oldonblur != null)	    {
    	retorno= objeto.tag.oldonblur(e);
   	}
   return retorno;
  
} 


//elimina los ceros por la izquierda al entrar en un campo
campoNumerico.prototype.numeroSinCeros=  function (e){
//eliminado temporalmente ya que el explorer 6 parece no ser capaz de recuperar el foco si el juega con el valor en campo al recibir el foco
//	while (this.value.substring(0,1)=='0')
//	{
//		this.value=this.value.substring(1);
//	}
  	if (this.tag.oldonfocus != null)    {
   	    	this.tag.oldonfocus(e);
   	}    
}


//repite un string n veces
function repeatString(string, count){
	var buffer="";
	for( i=0; i < count; i++ ) buffer += string;
	return buffer;
}


//--------------------------fin métodos y funciones del objeto campo numérico-------------------------------------------

//--------------------------objeto campo importe-------------------------------------------
//constructor 
//	obj objeto sobre el que se define
//	qDecimales: cantidad de decimales si los tuviera
//	cSepDec: caracter de separador decimal, por defecto  coma
//  cSepMiles caracter de separador de miles, por defecto punto
function campoImporte(obj, qDecimales, cSepDec, cSepMiles) {

   this.obj = obj;
   obj.tag=this;  //guardamos una referencia al objeto
   
   	
   this.qDecimales =  (typeof(qDecimales)== 'undefined')? 0: qDecimales;
   this.cSepDec    =  (typeof(cSepDec) == 'undefined')? ',': cSepDec;   
   this.cSepMiles  =  (typeof(cSepMiles) == 'undefined')? '.': cSepMiles;      

   this.numbersonly= o_numbersonly;
    

   //pinchamos los eventos preferiblemente con dom
   // DOM2
   this.oldonblur=null;
   this.oldonfocus=null;	   
   this.oldonkeypress=null;
   if ( typeof obj.addEventListener != "undefined" ){
      //if (this.siCerosIzq){	   
   	  	 obj.addEventListener( "blur", this.importeConFormato, false );
   	  	 obj.addEventListener( "focus", this.importeSinFormato, false );		  
	  //}
//	  obj.addEventListener( "keypress", this.numbersonly, true );		  		     		  
   }else {
       //if (this.siCerosIzq){	   	   
   	   	  this.oldonblur=obj.onblur; //capturamos el evento por si existiera
   	   	  this.obj.onblur= this.importeConFormato;
	   	  this.oldonfocus=obj.onfocus; //capturamos el evento por si existiera
   	   	  this.obj.onfocus= this.importeSinFormato;		   
	   //}
   }	  
   //se deja este evento con el modelo antiguo debido a un error que parece tener el mozilla para tratar el nuevo
   this.oldonkeypress=obj.onkeypress; //capturamos el evento por si existiera
   this.obj.onkeypress= this.numbersonly;
   
}


//elimina los separadores de miles al entrar en un campo
campoImporte.prototype.importeSinFormato= function (e){
    this.value=  StrReplace(this.value, this.tag.cSepMiles, '');

  	if (this.tag.oldonfocus != null)    {
   	    	this.tag.oldonfocus(e);
   	}    
}


//establece el formáto numérico al salir de un campo   
campoImporte.prototype.importeConFormato=  function (e){
   var	num=this.value; 
   var	numDec= this.tag.qDecimales;
   var  decSep= this.tag.cSepDec;
   var  thousandSep= this.tag.cSepMiles;

   this.value= 	importeConFormato(num,numDec, decSep, thousandSep);

  	if (this.tag.oldonblur != null)	    {
   	    	this.tag.oldonblur(e);
   	}
   
} 


function importeConFormato(num,numDec, decSep, thousandSep){
   if (num==""){
   		return num;
   }

    var  valor;
    var Dec;

    Dec = Math.pow(10, numDec); 

	num= StrReplace(num.toString(), thousandSep, '');
	num= StrReplace(num.toString(), decSep, '.');	

    if (isNaN(num)) {
	    num = "0";
    }

    sign = (num == (num = Math.abs(num)));

    num = Math.floor(num * Dec + 0.50000000001);

    cents = num % Dec;

    num = Math.floor(num/Dec).toString(); 

    if (cents < (Dec / 10)) cents = "0" + cents; 

    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)

     num = num.substring(0, num.length - (4 * i + 3)) + thousandSep + num.substring(num.length - (4 * i + 3));

    if (Dec == 1)

     valor=  (((sign)? '': '-') + num);

    else

     valor= (((sign)? '': '-') + num + decSep + cents);

   return valor; 
}

function StrReplace(str1, str2, str3)
{
  str1 = str1.split(str2).join(str3);
  return str1;
}


//--------------------------fin métodos y funciones del objeto campo importe-------------------------------------------

