﻿// FUNCIONES UTILITARIAS EN JAVASCRIPT 

var sBrowser;
var sVersion;
  
  //Para todos (saber el tipo de navegador)
  function setBrowserType() {
      var aBrowFull = new Array("opera","msie","netscape","gecko","mozilla");
      var aBrowVers = new Array("opera","msie","netscape","rv","mozilla");
      var aBrowAbrv = new Array("op","ie","ns","mo","ns");
      var sInfo = navigator.userAgent.toLowerCase();

      sBrowser = "";
      for (var i = 0; i < aBrowFull.length; i++) {
          if ((sBrowser == "") && (sInfo.indexOf(aBrowFull[i]) != -1)) {
              sBrowser = aBrowAbrv[i];
              sVersion = String(parseFloat(sInfo.substr(sInfo.indexOf(aBrowVers[i]) + aBrowVers[i].length + 1)));
          }
      }
  }


// Función para eliminar un registro de los catalogos
function  Eliminar(formName,id, mensaje) {
    if(confirm(mensaje)) {
        alert(formName);
	    document.forms[formName].hdfKey.value=id;
		document.forms[formName].submit();
    }
}

// Función para eliminar un registro de los catalogos
function  Eliminar(formName, hdfId, idReg, mensaje, error) {
    if(confirm(mensaje)) {
		hdf = document.getElementById(hdfId);
		if(hdf) {
		    hdf.value = idReg;
		    document.forms[formName].submit();
		} else {
		    if(error)
		        alert(error)
		}
	}
}

// Función para eliminar un registro de los catalogos
function  EliminarDosParam(formName, hdfId, idReg,hdfId1, idReg1, mensaje, error) {
    if(confirm(mensaje)) {
		hdf = document.getElementById(hdfId);
		hdf1 = document.getElementById(hdfId1);
		if(hdf) {
		    hdf.value = idReg;
		    hdf1.value = idReg1;
		    document.forms[formName].submit();
		} else {
		    if(error)
		        alert(error)
		}
	}
}

// Función para seleccionar un item de los gridview
function  EditarItem(formName, hdfId, idReg) {
    hdf = document.getElementById(hdfId);
	if(hdf) {
	    hdf.value = idReg;
		document.forms[formName].submit();
		}
}

// Función para ver un item de los datagrid
function  VerItem(frmNombre,CodItem) {
    document.forms[frmNombre].hdfVer.value=CodItem;
	document.forms[frmNombre].submit();
}
// Función para borrar un item de los datagrid
function  BorrarItem(frmNombre,CodItem,Mensaje) {
    if(confirm(Mensaje)) {
	    document.forms[frmNombre].hdfBorrar.value=CodItem;
		document.forms[frmNombre].submit();
	}
}

// función para presentar un mensaje de confirmación en el caso de eliminar un registro
function  MensajeConfirmaEliminar() {
    if(confirm('¿Desea eliminar el registro?')) 
	    return true;
	else
	    return false;   
}

// Función para validar que los caracteres ingresados en un input
// sean sólo números.
function SoloNumeros(e) 
{ 
tecla = (document.all)?e.keyCode:e.which; 
if (tecla==8) return true; 
patron = /[1234567890]/;
te = String.fromCharCode(tecla); 
return patron.test(te);
}

// Funcion para validar que los caracteres ingresados en un input
// sean sólo numeros con Ext, usado para numeros de telefonos 
function SoloNumerosExt(e) 
{ 
tecla = (document.all)?e.keyCode:e.which; 
if (tecla==8) return true; 
patron = /[1234567890 Eext ]/;
te = String.fromCharCode(tecla); 
return patron.test(te);
}

// Función para validar que los caracteres ingresados en un input 
// sean números y puntos.
function NumerosDecimales(e) 
{ 
tecla = (document.all)?e.keyCode:e.which; 
if (tecla==8) return true; 
patron = /[1234567890.]/;
te = String.fromCharCode(tecla); 
return patron.test(te);
}
//acepta decimales negativos
function NumerosDecimalesNP(e) 
{ 
tecla = (document.all)?e.keyCode:e.which; 
if (tecla==8) return true; 
patron = /[-1234567890.]/;
te = String.fromCharCode(tecla); 
return patron.test(te);
}

// Función para validar que los caracteres ingresados en un input 
// sean sólo números positivos.
function SoloPositivos(CampoForm)
{
 if (CampoForm.value <=0)
	{
 		alert('El valor del campo debe ser mayor que cero !!!');
 		CampoForm.value="";
 		CampoForm.focus();
 		return false;
 	}
}

// Función para validar que los caracteres ingresados en un input
// sean sólo números y comas
function SoloNumerosyComa(e) 
{ 
tecla = (document.all)?e.keyCode:e.which; 
if (tecla==8 || tecla==44) return true; 
patron = /[1234567890]/;
te = String.fromCharCode(tecla); 
return patron.test(te);
}

// Función para validar que los caracteres ingresados en un input
// sean sólo números, letras y guiones
function SoloNumLetyGuion(e) 
{ 
tecla = (document.all)?e.keyCode:e.which; 
if (tecla==8 || tecla==45) return true; 
patron = /[1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]/;
te = String.fromCharCode(tecla); 
return patron.test(te);
}

// Función para validar que los caracteres ingresados en un input
// sean sólo letras y espacio en blanco
function SoloLetrasyEspacio(e) 
{ 
tecla = (document.all)?e.keyCode:e.which; 
if (tecla==8 || tecla==32) return true; 
patron = /[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]/;
te = String.fromCharCode(tecla); 
return patron.test(te);
}

// Función para validar que los caracteres ingresados en un input
// sean sólo letras
function SoloLetras(e) 
{ 
tecla = (document.all)?e.keyCode:e.which; 
if (tecla==8) return true; 
patron = /[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]/;
te = String.fromCharCode(tecla); 
return patron.test(te);
}

// Función para validar que los caracteres ingresados en un input
// sean sólo números y letras
function SoloNumerosyLetras(e) 
{ 
tecla = (document.all)?e.keyCode:e.which; 
if (tecla==8) return true; 
patron = /[1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]/;
te = String.fromCharCode(tecla); 
return patron.test(te);
}

// Función para validar que los caracteres ingresados en un input
// sean sólo números, paréntesis, guión y espacio
function MascaraTelefonoFax(e) 
{ 
tecla = (document.all)?e.keyCode:e.which; 
if (tecla==8 || tecla==40 || tecla==41 || tecla==45 || tecla==32) return true; 
patron = /[1234567890]/;
te = String.fromCharCode(tecla); 
return patron.test(te);
}

// Funciones para validar el formato de las fechas
// Formato Europeo: (dd/mm/yyyy)
function EW_checkeurodate(source, args)
    {
    var object_value = args.Value;
    if (args.Value.length == 0){
        args.IsValid =  true;
		return true;
    }

	var isplit = object_value.indexOf('/');

	if (isplit == -1)
	{
		isplit = object_value.indexOf('.');
	}

	if (isplit == -1 || isplit == args.Value.length){
		args.IsValid =  false;
		return false;
	}
    var sDay = object_value.substring(0, isplit);

	var monthSplit = isplit + 1;

	isplit = object_value.indexOf('/', monthSplit);

	if (isplit == -1)
	{
		isplit = object_value.indexOf('.', monthSplit);
	}

	if (isplit == -1 ||  (isplit + 1 )  == args.Value.length){
		args.IsValid =  false;
		return false;
	}
    var sMonth = object_value.substring((sDay.length + 1), isplit);

	var sYear = object_value.substring(isplit + 1);

	if (!EW_checkint(sMonth)) {
		args.IsValid =  false;
		return false;
	}
	else
	if (!EW_numberrange(sMonth, 1, 12)) {
		args.IsValid =  false;
		return false;
	}
	else
	if (!EW_checkint(sYear)) {
		args.IsValid =  false;
		return false;
	}
	else
	if (!EW_numberrange(sYear, 0, null)) {
		args.IsValid =  false;
		return false;
	}
	else
	if (!EW_checkint(sDay)) {
		args.IsValid =  false;
		return false;
	}
	else
	if (!EW_checkday(sYear, sMonth, sDay)) {
		args.IsValid =  false;
		return false;
	}
	else{
		args.IsValid =  true;
		return true;
	}
    }

function EW_checkday(checkYear, checkMonth, checkDay)
    {

	var maxDay = 31;

	if (checkMonth == 4 || checkMonth == 6 ||
			checkMonth == 9 || checkMonth == 11)
		maxDay = 30;
	else
	if (checkMonth == 2)
	{
		if (checkYear % 4 > 0)
			maxDay =28;
		else
		if (checkYear % 100 == 0 && checkYear % 400 > 0)
			maxDay = 28;
		else
			maxDay = 29;
	}

	return EW_numberrange(checkDay, 1, maxDay); 
    }

function EW_checkinteger(src, args)
	{
	args.IsValid = EW_checkint(args.Value);
	}


function EW_checkint(object_value)
    {
    if (object_value.length == 0)
        return true;
	
	var decimal_format = ".";
	var check_char;

	check_char = object_value.indexOf(decimal_format)
    if (check_char < 1)
	return EW_checknum(object_value);
    else
	return false;
    }

function EW_numberrange(object_value, min_value, max_value)
    {
    if (min_value != null)
	{
        if (object_value < min_value)
		return false;
	}

    if (max_value != null)
	{
	if (object_value > max_value)
		return false;
	}
	
    return true;
    }

function EW_checknumber(src,args)
    {
    if (args.Value.length == 0) {
        args.IsValid = true;
        return true;
        }

	var start_format = " .+-0123456789";
	var number_format = " .0123456789";
	var check_char;
	var decimal = false;
	var trailing_blank = false;
	var digits = false;
	var object_value = args.Value;
	check_char = start_format.indexOf(object_value.charAt(0))
	if (check_char == 1)
	    decimal = true;
	else if (check_char < 1) {
		args.IsValid = false;
		return false;
	}
        
	for (var i = 1; i < args.Value.length; i++)
	{
		check_char = number_format.indexOf(object_value.charAt(i))
		if (check_char < 0) {
			args.IsValid = false;
			return false;
		}
		else if (check_char == 1)
		{
			if (decimal) {
				args.IsValid = false;
				return false;
			}
			else
				decimal = true;
		}
		else if (check_char == 0)
		{
			if (decimal || digits)	
				trailing_blank = true;
		}
	    else if (trailing_blank) {
    		args.IsValid = false;
			return false;
		}
		else
			digits = true;
	}	

    args.IsValid = true;
    return true;
    }
    
function EW_checknum(object_value)
    {
    if (object_value.length == 0) {
        return true;
        }

	var start_format = " .+-0123456789";
	var number_format = " .0123456789";
	var check_char;
	var decimal = false;
	var trailing_blank = false;
	var digits = false;
	
	check_char = start_format.indexOf(object_value.charAt(0))
	if (check_char == 1)
	    decimal = true;
	else if (check_char < 1) {
		return false;
	}
        
	for (var i = 1; i < object_value.length; i++)
	{
		check_char = number_format.indexOf(object_value.charAt(i))
		if (check_char < 0) {
			return false;
		}
		else if (check_char == 1)
		{
			if (decimal) {
				return false;
			}
			else
				decimal = true;
		}
		else if (check_char == 0)
		{
			if (decimal || digits)	
				trailing_blank = true;
		}
	    else if (trailing_blank) {
			return false;
		}
		else
			digits = true;
	}	

    return true;
    }
    
// Función para validar que los caracteres ingresados en un input
// sean sólo números y pleca. Ejemplo 12/12/2007
function SoloNumerosyPleca(e) 
{ 
tecla = (document.all)?e.keyCode:e.which; 
if (tecla==8 || tecla==47) return true; 
patron = /[1234567890]/;
te = String.fromCharCode(tecla); 
return patron.test(te);
}
// Función para validar que los caracteres ingresados en un input
// sean sólo números y guiones. Ejemplo 00001-2008
function SoloNumerosyGuion(e) 
{ 
tecla = (document.all)?e.keyCode:e.which; 
if (tecla==8 || tecla==45) return true; 
patron = /[1234567890]/;
te = String.fromCharCode(tecla); 
return patron.test(te);
}

// Función para recuperar el objeto que hace referencia al control en el formulario
function RetornarObjControl(nombre, frm){
    for(var i = 0; i < frm.length; i++) {
        var ele = frm.elements[i];    
        
        if (ele.id.indexOf(nombre) != -1) {
            return ele;
        }	              
    }
    return null;
}

///////////////////////// Mask Input //////////////////////////////////////////////////////////////////
function mask(str,textbox,loc,delim){
var locs = loc.split(',');

for (var i = 0; i <= locs.length; i++){
	for (var k = 0; k <= str.length; k++){
	 if (k == locs[i]){
	  if (str.substring(k, k+1) != delim){
	    str = str.substring(0,k) + delim + str.substring(k,str.length)
	  }
	 }
	}
 }
textbox.value = str
}

// Funcion para mostrar calendario
function mostrarCalendario(obj,nomEle){
        var frm = window.document.forms[0];
        
        for(var i = 0; i < frm.length; i++){
            var ele = frm.elements[i];    
            
            if (ele.id.indexOf(nomEle) != -1){
                popUpCalendar(obj,ele,'dd/mm/yyyy');
            }
        }        
}

   
/*funcion para seter el selectedValue de un dropdownlist*/
function SetDDLValue(control,valor)
{
   
    for(var i=0;i<=control.length-1;i=i+1)
    {
        var ddlValue=control.options[i].value;
        if(ddlValue==valor)
        {
            control.selectedIndex=i;
            break;
       }
    } 
}

// Función para verificar que la fecha final sea mayor o igual a la fecha de inicio.
// Retorna True si la fecha final es mayor o igual a la fecha de inicio.
// Retorna False si la fecha final es menor que la fecha de inicio.
function CompararFechas(source,args,strFechaInicio,strFechaFinal)
{
    if ((strFechaInicio != "" && strFechaInicio != null) && (strFechaFinal != "" && strFechaFinal != null))
    {
    // Fecha de inicio
    var ArrFechaInicio = strFechaInicio.value.split("/");
    var strDiaInicio = new String(ArrFechaInicio[0]);
    if (strDiaInicio.length == 1) strDiaInicio = "0" + strDiaInicio;
    var strMesInicio = new String(ArrFechaInicio[1]);
    if (strMesInicio.length == 1) strMesInicio = "0" + strMesInicio;
    strFechaInicio = ArrFechaInicio[2] + strMesInicio + strDiaInicio;
    // Fecha final
    var ArrFechaFinal = strFechaFinal.value.split("/");
    var strDiaFinal = new String(ArrFechaFinal[0]);
    if (strDiaFinal.length == 1) strDiaFinal = "0" + strDiaFinal;
    var strMesFinal = new String(ArrFechaFinal[1]);
    if (strMesFinal.length == 1) strMesFinal = "0" + strMesFinal;
    strFechaFinal = ArrFechaFinal[2] + strMesFinal + strDiaFinal;
    // Comparando las fechas
    if (parseFloat(strFechaFinal) < parseFloat(strFechaInicio)) 
      {
        args.IsValid =  false;
        return false;
      }
    args.IsValid =  true;
    return true;  
    }
}
// Función para verificar que una fecha ingresada por el usuario sea menor o igual a la fecha del sistema.
// Retorna True si la fecha proporcionada es menor o igual a la fecha del sistema.
// Retorna False si la fecha proporcionada es mayor que la fecha del sistema.
function CompararFechaSistema(source,args,strFechaSistema,strFechaInput)
{
    if ((strFechaSistema != "" && strFechaSistema != null) && (strFechaInput != "" && strFechaInput != null))
    {
    // Fecha del sistema
    var ArrFechaSistema = strFechaSistema.value.split("/");
    var strDia = new String(ArrFechaSistema[0]);
    if (strDia.length == 1) strDia = "0" + strDia;
    var strMes = new String(ArrFechaSistema[1]);
    if (strMes.length == 1) strMes = "0" + strMes;
    strFechaSistema = ArrFechaSistema[2] + strMes + strDia;
    // Fecha proporcionada
    var ArrFechaInput = strFechaInput.value.split("/");
    var strDiaInput = new String(ArrFechaInput[0]);
    if (strDiaInput.length == 1) strDiaInput = "0" + strDiaInput;
    var strMesInput = new String(ArrFechaInput[1]);
    if (strMesInput.length == 1) strMesInput = "0" + strMesInput;
    strFechaInput = ArrFechaInput[2] + strMesInput + strDiaInput;
    // Comparando las fechas
    if (parseFloat(strFechaInput) > parseFloat(strFechaSistema)) 
      {
        args.IsValid =  false;
        return false;
      }
    args.IsValid =  true;
    return true;  
    }
}

// Función para verificar que la resta entre la fecha actual y una fecha ingresada por el usuario
// sea mayor o igual a 18.
// Retorna True si el resultado de la resta entre las fechas es mayor o igual a 18.
// Retorna False si el resultado de la resta entre las fechas es menor a 18.
function CalcularMayordeEdad(source,args,strFechaInput)
{
if ((strFechaInput != "" && strFechaInput != null))
    {
    var Band = 0;
    var ArrFechaInput = strFechaInput.value.split("/");
    var strDiaInput = new String(ArrFechaInput[0]);
    if (strDiaInput.length == 1) strDiaInput = "0" + strDiaInput;
    var strMesInput = new String(ArrFechaInput[1]);
    if (strMesInput.length == 1) strMesInput = "0" + strMesInput;
    strFechaInput = strMesInput + "/" + strDiaInput + "/" + ArrFechaInput[2];
    
    // Fecha proporcionada
    fecha = new Date(strFechaInput);
    // Fecha de hoy
    hoy = new Date();    
    
    // Resto los años de ambas fechas
    var Anio = hoy.getFullYear() - fecha.getFullYear();
    if (Anio > 18)
       Band = 1
    else
          if (Anio == 18)
            {
             // Verifico los meses
             var Mes = hoy.getMonth() -  fecha.getMonth();
             if (Mes > 0)
               Band = 1
             else
                 if (Mes == 0)
                    {
                    // Verifico los días
                    var Dia = hoy.getDate() - fecha.getDate();
                    if (Dia >= 0)
                        Band = 1
                    else
                        Band = 0 
                    }
                 else
                     Band = 0
            }
          else
               Band = 0
    // Si Band = 0 quiere decir que es menor de edad           
    if (Band == 0) 
      {
        args.IsValid =  false;
        return false;
      }
    args.IsValid =  true;
    return true;          
    }
}

//Funciones para validar valores monetarios
function currencyFormatKeyPress(fld, milSep, decSep, e, cantNumeros) {

	var key = '';
	var cantidadNumeros = parseInt(cantNumeros);
	var longitud = fld.value.length; 
			
	var strCheck = '0123456789.';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) return true;  
	key = String.fromCharCode(whichCode); 
	
	if (longitud > cantidadNumeros - 2){
		var num = fld.value.indexOf(decSep);
		if (num == -1){
			fld.value = fld.value.substring(0,cantidadNumeros - 3) + decSep + fld.value.substring(cantidadNumeros - 2,cantidadNumeros);
			return true;
		}
	}
	
	if (strCheck.indexOf(key) == -1) return false; 
	
	if (longitud > cantidadNumeros){ 
		window.event.keyCode = 0; 
		return false; 
	} 	
}

function currencyFormatKeyUp(fld, milSep, decSep, e, cantNumeros) {
	var longitud = fld.value.length; 		
	var cantidadNumeros = parseInt(cantNumeros);
	var whichCode = (window.Event) ? e.which : e.keyCode;	
	if (whichCode == 8 || whichCode == 46){
		if (longitud > cantidadNumeros - 2){
			var num = fld.value.indexOf(decSep);
			if (num == -1){
					fld.value = fld.value.substring(0,cantidadNumeros - 2) + decSep + fld.value.substring(cantidadNumeros - 2,longitud);
					return true;
			}		
		} 
	}
	
	if (longitud > cantidadNumeros - 2){
		var num = fld.value.indexOf(decSep);
		if (num > cantidadNumeros - 2){		
			var carac = fld.value.substring(longitud - 1,longitud);	
			fld.value = fld.value.substring(0,cantidadNumeros - 2) + decSep + fld.value.substring(cantidadNumeros - 2,cantidadNumeros - 1);
			if (carac != decSep){				
				fld.value = fld.value + carac;
			}
			return true;
		}
	}
	
	if (longitud == cantidadNumeros - 1){			
		var num = fld.value.indexOf(decSep);
		if (num == -1){			
			fld.value = fld.value.substring(0,cantidadNumeros - 2) + decSep + fld.value.substring(cantidadNumeros - 2,cantidadNumeros - 1);
		}
	}		
}
        
// Mostrar ventanas popup para ver archivos
function ventanaPopup(Pagina)
{ 
 window.open(Pagina,"popup","toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,left=80px,top=60px,width=1000px,height=800px");
 return false;
 
} 

// Mostrar ventanas popup para mostrar plantillas word
function ventanaPlantilla(Pagina,Titulo)
{ 
 window.open(Pagina,Titulo,"toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,left=80px,top=60px,width=1000px,height=800px");
 return false;
 
} 

//Ejecutado al hacer click en el boton ok, en una lista de valores(LOV) utilizando un modal popup extender,
//recupera el id del item seleccionado y nombre o descripcion. 
//ctrlCodigoItem:       Nombre del control al que se le asignara ID de item seleccionado
//ctrlDescripcionItem:  Nombre del control al que se le asignara nombre o descripcion de item seleccionado
//ctrlCodItemSelec:     Nombre del control que contiene ID del elemento seleccionado.
//ctrlDescItemSelec:    Nombre del control que contiene el nombre o descripcion del elemento seleccionado.
function onOkItem(ctrlCodigoItem,ctrlDescripcionItem,ctrlCodItemSelec,ctrlDescItemSelec)
{       
     var _codigoItem=$get(ctrlCodigoItem);
     var _descripcionItem=$get(ctrlDescripcionItem);
     var _codItemSelec=$get(ctrlCodItemSelec);
     var _descItemSelec=$get(ctrlDescItemSelec);
        
     if ((_codItemSelec!=null && _codItemSelec.value!='') && (_descItemSelec!=null && _descItemSelec.value!=''))
      {                    
          _codigoItem.value = _codItemSelec.value;
          _descripcionItem.value = _descItemSelec.value;                 
          _codItemSelec.value = "";
          _descItemSelec.value = "";
          _descripcionItem.className="InputNoEditable";
      }
}

//Ejecutado al hacer click en el boton ok, en una lista de valores(LOV) utilizando un modal popup extender,
//recupera el id del item seleccionado y número a mostrarse. Utilizado para cuando se cargan valores numéricos.
//ctrlCodigoItem:       Nombre del control al que se le asignara ID de item seleccionado
//ctrlDescripcionItem:  Nombre del control al que se le asignara nombre o descripcion de item seleccionado
//ctrlCodItemSelec:     Nombre del control que contiene ID del elemento seleccionado.
//ctrlDescItemSelec:    Nombre del control que contiene el nombre o descripcion del elemento seleccionado.
function onOkItemNum(ctrlCodigoItem,ctrlDescripcionItem,ctrlCodItemSelec,ctrlDescItemSelec)
{       
     var _codigoItem=$get(ctrlCodigoItem);
     var _descripcionItem=$get(ctrlDescripcionItem);
     var _codItemSelec=$get(ctrlCodItemSelec);
     var _descItemSelec=$get(ctrlDescItemSelec);
        
     if ((_codItemSelec!=null && _codItemSelec.value!='') && (_descItemSelec!=null && _descItemSelec.value!=''))
      {                    
          _codigoItem.value = _codItemSelec.value;
          _descripcionItem.value = _descItemSelec.value;                 
          _codItemSelec.value = "";
          _descItemSelec.value = "";
          _descripcionItem.className="InputNoEditableNum";
      }
}

//Ejecutado al hacer click en el boton ok, en una lista de valores(LOV) utilizando un modal popup extender,
//recupera el id del item seleccionado y dato a mostrarse. Utilizado para realizar un postback al asignar .
//ctrlCodigoItem:       Nombre del control al que se le asignara ID de item seleccionado
//ctrlDescripcionItem:  Nombre del control al que se le asignara nombre o descripción de item seleccionado
//ctrlCodItemSelec:     Nombre del control que contiene ID del elemento seleccionado.
//ctrlDescItemSelec:    Nombre del control que contiene el nombre o descripcion del elemento seleccionado.
//ctrlOculto:           Nombre del control al que se le asignará valor que indica que el item ha sido seleccionado.
//OcultoValue:          Contiene valor o descripción que indica que el item ha sido seleccionado.
//CssClassName:         Nombre de clase aplicado al control que contiene nombre o descripción de item seleccionado.
function onOkItemPostback(ctrlCodigoItem,ctrlDescripcionItem,ctrlCodItemSelec,ctrlDescItemSelec,ctrlOculto,OcultoValue,CssClassName)
{  
     var _ocultoValor = $get(ctrlOculto);
     
     var _codigoItem=$get(ctrlCodigoItem);
     var _descripcionItem=$get(ctrlDescripcionItem);
     var _codItemSelec=$get(ctrlCodItemSelec);
     var _descItemSelec=$get(ctrlDescItemSelec);          
            
     if ((_codItemSelec!=null && _codItemSelec.value!='') && (_descItemSelec!=null && _descItemSelec.value!=''))
     {
          _codigoItem.value = _codItemSelec.value;
          _descripcionItem.value = _descItemSelec.value;                 
          _codItemSelec.value = "";
          _descItemSelec.value = "";
          _descripcionItem.className = CssClassName;                   
        // Seteando el valor de un campo oculto para mandar a ejecuttar
        // una función de servidor
        _ocultoValor.value = OcultoValue;        
        document.forms[0].submit();
     }                                                                                             
}

// Función para convertir fecha al formato dd/mm/aaaa,retornando la fecha
function FormatearFecha(FechaTmp){
   var strdia_mes = ""; 
   var strmes  = ""; 
   var dia_mes = FechaTmp.getDate(); 		        //dia del mes
   if (dia_mes <= 9)
      strdia_mes = "0" + dia_mes 
   else
      strdia_mes = dia_mes
                      
   var mes = FechaTmp.getMonth() + 1;          //Mes
   if (mes <= 9)
      strmes =  "0" + mes
   else
      strmes = mes
                        
   var anio = FechaTmp.getYear();              //Año
      if (anio < 100) anio = "19" + anio			//pasa el año a 4 digitos
      else if ( ( anio > 100 ) && ( anio < 999 ) ) {	//efecto 2000
             var cadena_anio = new String(anio);
             anio = "20" + cadena_anio.substring(1,3);
      }
   return strdia_mes + "/" + strmes + "/" + anio;
}

//Función para completar mascara de valores numericos
function completarMascaraNumerica(objectID,cantNumeros,TipoAlign) {

    var object = $get(objectID); 
    var longitud = object.value.length; 
	var cantidadNumeros = parseInt(cantNumeros);
	var object_value = object.value;		
    var strCadenaNum = '';
    
    if (longitud == 0)
        object_value = '';
    else
        if (longitud != cantidadNumeros){
                for(var i=0;i<(cantidadNumeros-longitud);i=i+1){
                   strCadenaNum = strCadenaNum + "0";
                } 
                if (TipoAlign == 'RightToLeft') {
                    object_value = strCadenaNum + object_value; 
                }
                else
                    if (TipoAlign == 'LeftToRight') {
                        object_value = object_value + strCadenaNum;
                    }    
                if (object_value == '000')
	                object_value = ''                               
	    }   
	    else
	        if (object_value == '000')
	            object_value = ''
	    
	//Asignar valor numerico formateado       
	object.value = object_value;           
}	

//Función para obtener fecha de caducidad en formato dd/mm/yyyy 
//deacuerdo a fecha de inicio y período de caducidad en años
function ObtenerFechaCaducidad(strFechaInicio,PeriodoCaduca){
   var fecha_array = strFechaInicio.value.split("/");
          
   var myFechaCaduca = new Date(fecha_array[2],fecha_array[1] - 1,fecha_array[0]);             
   
   // Sumar años de caducidad a fecha de inicio  
    myFechaCaduca.setFullYear(myFechaCaduca.getFullYear() + parseInt(PeriodoCaduca)); 
    myFechaCaduca.setDate(myFechaCaduca.getDate() - 1);

    var dia = myFechaCaduca.getDate(); 
    if (dia < 10)
        dia = "0" + dia 

    var mes = myFechaCaduca.getMonth(); 
    mes+=1;
    if (mes < 10)
        mes = "0" + mes 
    
    return dia + "/" + mes + "/" + myFechaCaduca.getFullYear();
}


    /////////////////solo números con cantidad de decimales/////////////////////////////
    function NumerosDecimalesExactos(e, ctlId, numDecimales) {
        var cadena = ctlId.value;
        var cantPuntos = 1;
        var teclaPermitida= true;
        var d;
        var pos;
		var tecla;
		
		setBrowserType();
		
        //tecla = (document.all) ? e.keyCode : e.which;
        
		if (sBrowser == "ie") { //Internet Explorer
            tecla=window.event.keyCode 
		  
		} else if (sBrowser == "mo"){ //Mozilla Firefox
		    tecla=e.which;
		    keyCode=e.keyCode;
			//Fin, Inicio, Izquierda, Derecha, Delete, BackSpace, Tab
			if (keyCode == 35 | keyCode == 36 | keyCode == 37 | keyCode == 39 | keyCode == 46 | keyCode == 8 | keyCode == 9)
				tecla=keyCode;
		}
		
		
		//if (tecla == 8) return true;
		if ((tecla < 48 || tecla > 57) & tecla != 35 & tecla != 36 & tecla != 37 & tecla != 39 & tecla != 46 & tecla != 8 & tecla != 9){
		    if (sBrowser == "ie") {
		        window.event.keyCode = 0;
		        //teclaPermitida = false;
		    }
	        else {
	            return false;
	            //teclaPermitida = false;
	        }
	    }
		
        //patron = /[1234567890.]/;

        //te = String.fromCharCode(tecla);
        
        if (tecla == 46) {
            //////valida que solo se permita un punto decimal   
            for (var i = 0; i <= cadena.length; i++) {
                if ((cadena.charAt(i) == ".")) {
                    cantPuntos = cantPuntos + 1;
                    if (cantPuntos > 1) {
                        return false;
                    }
                }
            }
        }

        //valida que la cantidad de decimales
        var decimales = cadena.split(".");
        
        var totalEnteros = ctlId.maxLength-(numDecimales+1);
       
       //valida los números antes del punto
        if (totalEnteros > 1 ) {
            if (decimales.length > 1){
                d = cadena.length - (decimales[1].length+1);
            }
            else{
                d= totalEnteros-1;
            }    
  
            if (document.selection)
                pos = getPosCaret(ctlId);
            else
                pos = ctlId.selectionStart;
              
            if ((decimales[0].length >= totalEnteros)) {
                if (tecla != 46 & tecla != 8 & tecla != 37 & tecla != 39){
                    if ((pos = d) && (decimales.length == 1)){
                        return false;
                    }
                    else if (pos<d){
                            return false;
                    }
                 }
            }
        }
        
        //valida los números despues del punto
        if (decimales.length > 1) {
            d = cadena.length - (decimales[1].length+1);
           
            if (document.selection)
                pos = getPosCaret(ctlId);
            else
                pos = ctlId.selectionStart;

            //alert(decimales[1].length + ">" + s + "y" + pos + ">" + d);

            if ((decimales[1].length > numDecimales - 1) && (pos > d)) {
                if (tecla != 46 & tecla != 8 & tecla != 37 & tecla != 39){
                     return false;
                }
            }
        }
        //return patron.test(te);
    }

    /////////////////////////Obtiene la posición del cursor en el textbox///////////////////////////////
    function getPosCaret(input) {
        var range = document.selection.createRange(); //document
        var range2 = input.createTextRange();

        range2.collapse(true);

        range2.moveEnd('character', 0);
        range2.setEndPoint('EndToStart', range);

        distancia = range2.text.length;
        //alert(distancia);
        //pos_final = parseFloat(input.value.length) - parseFloat(distancia);
        //range2.move('character', pos_final);
        //alert(distancia);
        return distancia;
    }
    
// Función para eliminar los valores asociados a la selección en un control LOV (List Of Values)
function EliminarSeleccionLOV(ctrlCodigoItem,ctrlDescripcionItem)
{       
     var CodItem=$get(ctrlCodigoItem);
     var DesItem=$get(ctrlDescripcionItem);
     if ((CodItem!=null && CodItem.value!='') && (DesItem!=null && DesItem.value!=''))
      {                    
          CodItem.value = "";
          DesItem.value = "";
      }
      return false;
}

// Funcion para mostrar un tooltip en los comboboxes que son muy pequeños para los
// valores que muestran al usuario.
function MostrarTooltip(idObject, container) 
{ 			
	var obj = document.getElementById( idObject ); 
	document.getElementById(container).innerHTML = obj.options[obj.selectedIndex].text;

	if(obj.options[obj.selectedIndex].value !="") 
	{
		//Formato Tooltip 
 		document.getElementById(container).style.zIndex = 9999999;
  		document.getElementById(container).style.display = "inline";
  		document.getElementById(container).style.position = "absolute";
 		document.getElementById(container).style.border =  "ActiveBorder  1px	solid";
		document.getElementById(container).style.padding =   "3px";
		document.getElementById(container).style.fontSize =  "10px";
		document.getElementById(container).style.fontFamily = "Verdana";
		document.getElementById(container).style.backgroundColor = "LemonChiffon";
	}      
} 

// Funcion para ocultar el tooltip que se le asocia a los comboboxes que son muy pequeños para los
// valores que muestran al usuario.
function OcultarTooltip(container)
{ 
  document.getElementById(container).style.display = "none"; 
}

//función para colocar 2 decimales 
function ColocaDecimales(txt){
    var value=txt.value;
    if(value=='.' || value=='')
        txt.value =''
    else
        txt.value = parseFloat(value).toFixed(2);
}

//función para validar los CheckBoxList
function ValidadorChk(Nombrechk) {
    var chktable = document.getElementById(Nombrechk);
    if (chktable) {
        var chktr = chktable.getElementsByTagName('tr');
        for (i = 0; i < chktr.length; i++) {
            var chk = document.getElementById(Nombrechk + '_' + i);
            if (chk.checked)
                return true;
        }
    }
    return false;
}

