﻿String.prototype.trim = function() { return this.replace(/^s+|s+$/g, ""); };

function validar_contactos() 
{
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_nombre_contacto').value).length <= 0) 
    {
        alert("Ingrese todos los campos requeridos");
        document.getElementById('ctl00_ContentPlaceHolder1_txt_nombre_contacto').focus();
        return (false);
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_telefono').value).length <= 0) 
    {
        alert("Ingrese todos los campos requeridos");
        document.getElementById('ctl00_ContentPlaceHolder1_txt_telefono').focus();
        return (false);
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_cargo').value).length <= 0) 
    {
        alert("Ingrese todos los campos requeridos");
        document.getElementById('ctl00_ContentPlaceHolder1_txt_cargo').focus();
        return (false);
    }
    document.getElementById('ctl00_ContentPlaceHolder1_hf_nombre_contacto').value = document.getElementById('ctl00_ContentPlaceHolder1_txt_nombre_contacto').value;
    document.getElementById('ctl00_ContentPlaceHolder1_hf_telefono_contacto').value = document.getElementById('ctl00_ContentPlaceHolder1_txt_telefono').value;
    document.getElementById('ctl00_ContentPlaceHolder1_hf_cargo_contacto').value = document.getElementById('ctl00_ContentPlaceHolder1_txt_cargo').value;
    return (true);
}

function confirm_contacto() 
{
    if (confirm("Desea agregar otro contacto?")) {
        document.getElementById('ctl00_ContentPlaceHolder1_hf_Agregar').value = '1';
        document.getElementById('ctl00_ContentPlaceHolder1_hf_Agregar_Tipo').value = 'C';
        document.getElementById('ctl00_ContentPlaceHolder1_lnk_Insertar_Contacto').click();
        return (true);
    }
    else {
        document.getElementById('ctl00_ContentPlaceHolder1_hf_Agregar').value = '-1';
        document.getElementById('ctl00_ContentPlaceHolder1_lnk_Insertar_Contacto').click();
        return (false);
    }
}

function validar_documentos() 
{
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_flu_Documento').value).length <= 0) 
    {
        alert("Ingrese todos los campos requeridos");
        document.getElementById('ctl00_ContentPlaceHolder1_flu_Documento').focus();
        return (false);
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_nombre_documento').value).length <= 0) 
    {
        alert("Ingrese todos los campos requeridos");
        document.getElementById('ctl00_ContentPlaceHolder1_txt_nombre_documento').focus();
        return (false);
    }
    document.getElementById('ctl00_ContentPlaceHolder1_hf_nombre_documento').value = document.getElementById('ctl00_ContentPlaceHolder1_txt_nombre_documento').value;
    return (true);
}

function confirm_documento() 
{
    if (confirm("Desea agregar otro documento?"))
    {
        document.getElementById('ctl00_ContentPlaceHolder1_hf_Agregar').value = '1';
        document.getElementById('ctl00_ContentPlaceHolder1_hf_Agregar_Tipo').value = 'D';
        document.getElementById('ctl00_ContentPlaceHolder1_lnk_Insertar_Documento').click();
        return (true);
    }
    else 
    {
        document.getElementById('ctl00_ContentPlaceHolder1_hf_Agregar').value = '-1';
        document.getElementById('ctl00_ContentPlaceHolder1_lnk_Insertar_Documento').click();
        return (false);
    }
}

function validar_asegurado() 
{
    if (document.getElementById('ctl00_ContentPlaceHolder1_ddl_Tipo').value == 0) {
        alert("Ingrese todos los campos requeridos");
        document.getElementById('ctl00_ContentPlaceHolder1_ddl_Tipo').focus();
        return (false);
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Cedula').value).length <= 0) {
        alert("Ingrese todos los campos requeridos");
        document.getElementById('ctl00_ContentPlaceHolder1_txt_Cedula').focus();
        return (false);
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Cedula').value).length < 5) {
        alert("Formato Inválido");
        document.getElementById('ctl00_ContentPlaceHolder1_txt_Cedula').focus();
        return (false);
    }
    if (document.getElementById('ctl00_ContentPlaceHolder1_ddl_Tipo').value == 3) {
        if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Terminal_Rif').value).length <= 0) {
            alert("Ingrese todos los campos requeridos");
            document.getElementById('ctl00_ContentPlaceHolder1_txt_Terminal_Rif').focus();
            return (false);
        }
    }
    
    var cedula=document.getElementById('ctl00_ContentPlaceHolder1_txt_Cedula').value + document.getElementById('ctl00_ContentPlaceHolder1_txt_Terminal_Rif').value;
    if (parseInt(cedula)<=0) {
        alert("Formato Inválido");
        document.getElementById('ctl00_ContentPlaceHolder1_txt_Cedula').focus();
        return (false);
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_nombre').value).length <= 0) {
        alert("Ingrese todos los campos requeridos");
        document.getElementById('ctl00_ContentPlaceHolder1_txt_nombre').focus();
        return (false);
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Apellido').value).length <= 0) {
        alert("Ingrese todos los campos requeridos");
        document.getElementById('ctl00_ContentPlaceHolder1_txt_Apellido').focus();
        return (false);
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Fecha_Nacimiento').value).length <= 0) {
        alert("Ingrese todos los campos requeridos");
        document.getElementById('ctl00_ContentPlaceHolder1_txt_Fecha_Nacimiento').focus();
        return (false);
    }
    if (document.getElementById('ctl00_ContentPlaceHolder1_ddl_Estado_Civil').value == 0) {
        alert("Ingrese todos los campos requeridos");
        document.getElementById('ctl00_ContentPlaceHolder1_ddl_Estado_Civil').focus();
        return (false);
    }
    if (document.getElementById('ctl00_ContentPlaceHolder1_ddl_Profesion').value == 0) {
        alert("Ingrese todos los campos requeridos");
        document.getElementById('ctl00_ContentPlaceHolder1_ddl_Profesion').focus();
        return (false);
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Telefono_Habitacion').value).length <= 0 && trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Telefono_Oficina').value).length <= 0 && trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Codigo_Movil').value).length <= 0) {
        alert("Ingrese al menos un número telefónico.");
        document.getElementById('ctl00_ContentPlaceHolder1_txt_Telefono_Habitacion').focus();
        return (false);
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Codigo_Habitacion').value).length > 0) {
        if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Telefono_Habitacion').value).length <= 0) {
            alert("Ingrese todos los campos requeridos");
            document.getElementById('ctl00_ContentPlaceHolder1_txt_Telefono_Habitacion').focus();
            return (false);
        }
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Telefono_Habitacion').value).length > 0) {
        if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Codigo_Habitacion').value).length <= 0) {
            alert("Ingrese todos los campos requeridos");
            document.getElementById('ctl00_ContentPlaceHolder1_txt_Codigo_Habitacion').focus();
            return (false);
        }
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Codigo_Oficina').value).length > 0) {
        if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Telefono_Oficina').value).length <= 0) {
            alert("Ingrese todos los campos requeridos");
            document.getElementById('ctl00_ContentPlaceHolder1_txt_Telefono_Oficina').focus();
            return (false);
        }
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Telefono_Oficina').value).length > 0) {
        if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Codigo_Oficina').value).length <= 0) {
            alert("Ingrese todos los campos requeridos");
            document.getElementById('ctl00_ContentPlaceHolder1_txt_Codigo_Oficina').focus();
            return (false);
        }
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Codigo_Movil').value).length > 0) {
        if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Telefono_Movil').value).length <= 0) {
            alert("Ingrese todos los campos requeridos");
            document.getElementById('ctl00_ContentPlaceHolder1_txt_Telefono_Movil').focus();
            return (false);
        }
    }
    if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Telefono_Movil').value).length > 0) {
        if (trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Codigo_Movil').value).length <= 0) {
            alert("Ingrese todos los campos requeridos");
            document.getElementById('ctl00_ContentPlaceHolder1_txt_Codigo_Movil').focus();
            return (false);
        }
        }
    if (parseInt(calcular_edad(trim(document.getElementById('ctl00_ContentPlaceHolder1_txt_Fecha_Nacimiento').value)), 10) < 18) {
        alert("El asegurado debe ser mayor a 18 años");
        document.getElementById('ctl00_ContentPlaceHolder1_txt_Fecha_Nacimiento').focus();
        return (false);
    }                         
    return (true);
}

function txt_observaciones_keyPress(event) 
{
    if (event.keyCode == 13)
    {
        if (document.getElementById('ctl00_ContentPlaceHolder1_hf_Cantidad_Contactos').value <= 0) 
        {
            document.getElementById('ctl00_ContentPlaceHolder1_lnk_Agregar_Contacto').click();
            return (false);
        }
        else {

            document.getElementById('ctl00_ContentPlaceHolder1_hf_row_selected_number').value = 1;
            document.getElementById('ctl00_ContentPlaceHolder1_lnk_Editar_Contacto').click();
            return (false);
        }
    }
}

function txt_cargo_keyPress(event) 
{
    if (event.keyCode == 13) 
    {
        if (!validar_contactos()) {return (false)}
        confirm_contacto();
    }
}



function txt_nombre_documento_keypress(event) 
{
    if (event.keyCode == 13) 
    {
        if (!validar_documentos()) {return (false)}
        confirm_documento();
    }
}

function imprimir_lst() {
    document.getElementById('bottom_bar').style.display = 'none';
    var var_tamano = document.getElementById('ctl00_ContentPlaceHolder1_gv_Listado').rows.length; var_tamano--;
    for (j = 0; j <= var_tamano; j++) {
        document.getElementById('ctl00_ContentPlaceHolder1_gv_Listado').rows[j].cells[0].style.display = 'none';
    }
    window.print();
    for (j = 0; j <= var_tamano; j++) {
        document.getElementById('ctl00_ContentPlaceHolder1_gv_Listado').rows[j].cells[0].style.display = 'inline';
    }
    document.getElementById('bottom_bar').style.display = 'inline';
}

function forma_pago(obj) {
    var var_fp = obj.value;
    var_XML = document.getElementById('var_Xml_Forma_Pago');
    var_Tamano = var_XML.getElementsByTagName('tbl_formas').length; var_Tamano--;

    for (k = 0; k <= var_Tamano; k++) {
        if (var_XML.getElementsByTagName('id_forma_pago')[k].firstChild.data == var_fp) {
            if (var_XML.getElementsByTagName('documento')[k].firstChild.data == 'false') {
                document.getElementById(obj.id + '_banco').style.display = 'none';
                document.getElementById(obj.id + '_doc').style.display = 'none';
            }
            else {
                document.getElementById(obj.id + '_banco').style.display = 'block';
                document.getElementById(obj.id + '_doc').style.display = 'block';
            }
            return false;
        }
    }
}

//function calcular_edad(fecha)
//{ 
//    if(!es_Fecha(fecha))
//        {         
//         return 0
//        }
//        hoy = new Date(); //alert(hoy)
//    var array_fecha = fecha.split("/") 
//    //si el array no tiene tres partes, la fecha es incorrecta 
//    //if (array_fecha.length!=3) 
//    //   return false 
//    //compruebo que los ano, mes, dia son correctos 
//    var ano 
//    ano = parseInt(array_fecha[2]); 
//    //if (isNaN(ano)) 
//    //   return false 
//    var mes 
//    mes = parseInt(array_fecha[1]); 
//    //if (isNaN(mes)) 
//    //   return false 
//    var dia 
//    dia = parseInt(array_fecha[0]); 
//    //if (isNaN(dia)) 
//    //   return false
//    //si el año de la fecha que recibo solo tiene 2 cifras hay que cambiarlo a 4 
//    //if (ano<=99) 
//    //   ano +=1900
//    //resto los años de las dos fechas
//    edad = hoy.getYear() - ano - 1; alert('año = ' + hoy.getYear())//-1 porque no se si ha cumplido años ya este año
//    //si resto los meses y me da menor que 0 entonces no ha cumplido años. Si da mayor si ha cumplido 
//    if (hoy.getMonth() + 1 - mes < 0) //+ 1 porque los meses empiezan en 0 
//       return edad 
//    if (hoy.getMonth() + 1 - mes > 0) 
//       return edad+1 
//    //entonces es que eran iguales. miro los dias 
//    //si resto los dias y me da menor que 0 entonces no ha cumplido años. Si da mayor o igual si ha cumplido 
//    if (hoy.getUTCDate() - dia >= 0) 
//       return edad + 1 
//    return edad 
//} 
 
 function Filtrar(var_Id,var_Filtro,var_es_grid)
        {       
         var var_desde = 0;
         if(var_es_grid == 'si'){var_desde = 1}
         var_Filtro = var_Filtro.toUpperCase();
         var obj_Tabla = document.getElementById(var_Id)
         var var_cant_Filas = obj_Tabla.rows.length; var_cant_Filas--;
         var var_cant_Celdas = 0;
         var var_Encontrado = false;
         var var_Texto = '';

         for(j=var_desde;j<=var_cant_Filas;j++)
            {
             if(var_Filtro=='')
                {
                 obj_Tabla.rows[j].style.display="block";
                }
             else
                {
                 var_cant_Celdas = obj_Tabla.rows[j].cells.length; var_cant_Celdas--;
                 var_Encontrado = false; 
      
                 for(k=0;k<=var_cant_Celdas;k++)
                    {
                     var_Texto=obj_Tabla.rows[j].cells[k].innerHTML;
                     var_Texto=var_Texto.toUpperCase();
                     if(var_Texto.indexOf(var_Filtro)>=0)
                        {
                         var_Encontrado = true; break;
                        }                 
                    }
                 if(var_Encontrado)
                    {
                     obj_Tabla.rows[j].style.display="block";
                    }             
                 else
                    {
                     obj_Tabla.rows[j].style.display="none";
                    }
                }
            }

        }
        


    function Comparar_Fecha(fecha, fecha2)   
  {   
    var xMonth=fecha.substring(3, 5);   
    var xDay=fecha.substring(0, 2);   
    var xYear=fecha.substring(6,10);   
    var yMonth=fecha2.substring(3, 5);   
    var yDay=fecha2.substring(0, 2);   
    var yYear=fecha2.substring(6,10);   
    if (xYear> yYear)   
    {   
        return(true)   
    }   
    else  
   {   
      if (xYear == yYear)   
      {    
        if (xMonth> yMonth)   
      {   
           return(true)   
      }   
       else  
       {    
       if (xMonth == yMonth)   
          {   
            if (xDay>= yDay)   
             return(true);   
            else  
              return(false);   
          }   
          else  
            return(false);   
      }   
      }   
      else  
        return(false);   
  }   
} 

function es_Fecha(Cadena)
    {   
     var Fecha= new String(Cadena)   
     var RealFecha= new Date()  
     var Ano= new String(Fecha.substring(Fecha.lastIndexOf("/")+1,Fecha.length))   
     var Mes= new String(Fecha.substring(Fecha.indexOf("/")+1,Fecha.lastIndexOf("/"))) 
     var Dia= new String(Fecha.substring(0,Fecha.indexOf("/")))   
  
     if (isNaN(Ano) || Ano.length<4 || parseFloat(Ano)<1900)
        {    
         return false   
        }   
     if (isNaN(Mes) || parseFloat(Mes)<1 || parseFloat(Mes)>12)
        {     
         return false   
        }   
     if (isNaN(Dia) || parseInt(Dia, 10)<1 || parseInt(Dia, 10)>31)
        {     
         return false   
        }   
     if (Mes==4 || Mes==6 || Mes==9 || Mes==11) 
        {   
         if (Dia>30) 
            {      
             return false   
            }
        } 
     if (Mes==2) 
        {   
         if (es_Bisiesto(Ano))
            {
             if (Dia>28) 
                {   
                 return false   
                }
             }
         else
            {
             if (Dia>27) 
                {   
                 return false   
                }             
            
            }
        }  
     return true;
    }   


function es_Bisiesto(ano) 
    { 
        var BISIESTO; 
        if(parseInt(ano)%4==0)
            { 
             if(parseInt(ano)%100==0)
                { 
                 if(parseInt(ano)%400==0)
                    { 
                     BISIESTO=true; 
                    } 
                else
                    { 
                     BISIESTO=false; 
                    } 
                } 
            else
                { 
                 BISIESTO=true; 
                } 
            } 
        else
            { 
             BISIESTO=false; 
            }
        return BISIESTO; 
    } 



function es_Email(var_Correo)
    {
        var var_filtro=/^[A-Za-z][-_\w\.]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/;
        if (var_Correo.length == 0 ) {return true;}
        if (var_filtro.test(var_Correo))
            {
             return true;
            }
        else        
            {
             return false;
            }
        }

function Validar()
    {
     var tamano = document.forms[0].elements.length-1;
     for(x=0;x<=tamano;x++)
        {
		 if (document.forms[0].elements[x].validar=="1")
		    {			
			 if (trim(document.forms[0].elements[x].value).length == 0)
			    {
			     try
			        {
			         if(parseInt(document.forms[0].elements[x].Tab,10)>0)
			            {
			             Cargar_Tab(document.forms[0].elements[x].Tab);
			            }			        
			        }
			     catch(Err)
			        {			        
			        }
			     alert("Ingrese todos los datos requeridos del formulario");
			     document.forms[0].elements[x].focus();
			     return false;
			     break;			
			    }			    
			}
		 if ((document.forms[0].elements[x].tagName=='SELECT') && (document.forms[0].elements[x].validar=="1"))
		    {
		     if(document.forms[0].elements[x].value<=0)
			    {
			     try
			        {
			         if(parseInt(document.forms[0].elements[x].Tab,10)>0)
			            {
			             Cargar_Tab(document.forms[0].elements[x].Tab);
			            }			        
			        }
			     catch(Err)
			        {			        
			        }
			     alert("Seleccione una opción");
			     document.forms[0].elements[x].focus();
			     return false;
			     break;			
			    }
		    }
		 if (document.forms[0].elements[x].Tipo_Dato=='4')
		    {
		     if(!es_Email(document.forms[0].elements[x].value) && (document.forms[0].elements[x].value != ''))
			    {
			     try
			        {
			         if(parseInt(document.forms[0].elements[x].Tab,10)>0) {
			             Cargar_Tab(document.forms[0].elements[x].Tab); 
			            }			        
			        }
			     catch(Err)
			        {			        
			        }
			     alert("Ingrese un correo Válido");
			     document.forms[0].elements[x].focus();
			     return false;
			     break;			
			    }
		    }	
		 if (document.forms[0].elements[x].Tipo_Dato=='2')
		    {
		     if(!es_Fecha(document.forms[0].elements[x].value) && (document.forms[0].elements[x].value != ''))
			    {
			     try
			        {
			         if(parseInt(document.forms[0].elements[x].Tab,10)>0)
			            {
			             Cargar_Tab(document.forms[0].elements[x].Tab);
			            }			        
			        }
			     catch(Err)
			        {			        
			        }
			     alert("Ingrese una fecha Válida");
			     document.forms[0].elements[x].focus();
			     return false;
			     break;			
			    }
		    }  	
		 if (document.forms[0].elements[x].Tipo_Dato=='6')
		    {
		     if(!es_Fecha(document.forms[0].elements[x].value) && (document.forms[0].elements[x].value != ''))
			    {
			     try
			        {
			         if(parseInt(document.forms[0].elements[x].Tab,10)>0)
			            {
			             Cargar_Tab(document.forms[0].elements[x].Tab);
			            }			        
			        }
			     catch(Err)
			        {			        
			        }
			     alert("Ingrese una fecha Válida");
			     document.form1.elements[x].focus();
			     return false;
			     break;			
			    }
		    }    
		}	 
     return true;
    }
    


 function show_resume() 
 {
     
     document.getElementById('sp_Tomador').innerHTML = document.getElementById('txt_tomador').value
     document.getElementById('sp_Asegurado').innerHTML = document.getElementById('ddl_Cliente').options[document.getElementById('ddl_Cliente').selectedIndex].text 
     document.getElementById('sp_Cedula').innerHTML = document.getElementById('lbl_cedula').innerHTML
     document.getElementById('sp_Nacimiento').innerHTML = document.getElementById('lbl_fecha_nacimiento').innerHTML
     document.getElementById('sp_Aseguradora').innerHTML = document.getElementById('ddl_Aseguradora').options[document.getElementById('ddl_Aseguradora').selectedIndex].text 
     document.getElementById('sp_Ramo').innerHTML = document.getElementById('ddl_Ramo').value
     document.getElementById('sp_Moneda').innerHTML = document.getElementById('ddl_Moneda').options[document.getElementById('ddl_Moneda').selectedIndex].text 
     document.getElementById('sp_Poliza').innerHTML = document.getElementById('tx_Numero_Poliza').value
     document.getElementById('sp_Tipo_Poliza').innerHTML = document.getElementById('ddl_Tipo_Poliza').options[document.getElementById('ddl_Tipo_Poliza').selectedIndex].text 
     document.getElementById('sp_Periodo').innerHTML = document.getElementById('ddl_Periodo').options[document.getElementById('ddl_Periodo').selectedIndex].text 
     document.getElementById('sp_Desde').innerHTML = document.getElementById('tx_fecha_inicio').value
     document.getElementById('sp_Hasta').innerHTML = document.getElementById('tx_fecha_fin').value
     document.getElementById('sp_Emision').innerHTML = document.getElementById('tx_Fecha_emision').value
     document.getElementById('sp_Descuento').innerHTML = document.getElementById('txt_descuento').value
     document.getElementById('sp_Suma').innerHTML = document.getElementById('txt_Suma').innerHTML
     document.getElementById('sp_Prima').innerHTML = document.getElementById('txt_Prima').innerHTML
     document.getElementById('sp_Registro').innerHTML = document.getElementById('tx_Fecha_Registro').innerHTML
     tb_show('', '#TB_inline?height=400&width=610&inlineId=dv_resume_content&modal=true', 'null')
 }

 function siguienteFoco(sigObj, event) 
 {
     //alert(sigObj)
     var var_Argumentos = sigObj.split("|"); 
     sigObj=var_Argumentos[0];
     var var_Tipo = var_Argumentos[1]; //alert(var_Tipo)
     if(event.keyCode == 13 && !event.shiftKey) 
        {
         if(sigObj != '') {
             try 
             {
                 if (document.getElementById(sigObj).disabled)
                {
                    //siguienteFoco(document.getElementById(sigObj).Siguiente_Control, event);
                    siguienteFoco(document.getElementById(sigObj).getAttribute("Siguiente_Control"), event)
                 return false;
                }
                else
                {
                    document.getElementById(sigObj).focus();
                }     
             }
             catch (e) 
             {
                 //alert("sigObj = " + sigObj); alert(document.getElementById(sigObj).Siguiente_Control)
                 //siguienteFoco(document.getElementById(sigObj).Siguiente_Control, event);
                 siguienteFoco(document.getElementById(sigObj).getAttribute("Siguiente_Control"), event)
                 return false;
             }
                   
            }
         return false;           
        }     
     else
        {
         if(var_Tipo=="1")
            {
                //return SoloDecimales(event);
                return SoloNumeros(event); /* Cambio por SFUNG */
            }
        if(var_Tipo=="2")
            {
             return SoloTexto(null,event);
            }   
        if(var_Tipo=="3")
            {
             return SoloFecha(event);
            } 
        if(var_Tipo=="4")
            {
             return SoloNumeros(event);
            }   
        if(var_Tipo=="6")
            {
             return SoloLetras(event);
            }  
        }     
    }
    

  function Reemplazar(var_Obj,var_Tipo,var_Minimo)
    {
     var var_Value=var_Obj.value;
     var var_Tamano=var_Value.length;var_Tamano--;
       if(var_Tipo=="1")
          {
           var_Value=Formato_Numero_Usuario(var_Value);
          }
       if(var_Tipo=="2")
          {
           for(i=0;i<=var_Tamano;i++)
             {
              var_Value=var_Value.replace("|","");
              var_Value=var_Value.replace("¥","");
              var_Value=var_Value.replace("§","");
             }   
           var_Value=trim(var_Value) 
                     
          }
        if(var_Tipo=="3")
          {
              var_Value = Formato_Fecha(var_Value, var_Obj);                  
          }
       if(var_Tipo=="4")
          {
           for(i=0;i<=var_Tamano;i++)
             {
             if(!es_Numero(var_Value.charAt(i)))
               {
                var_Value=0;
               }              
             }     
          }
       if(var_Tipo=="6")
          {
           for(i=0;i<=var_Tamano;i++)
             {
             if(!es_Letra(var_Value.charAt(i)))
               {
                var_Value='';
               }              
             }     
          }
       if(var_Tipo=="5") {
           if (trim(var_Value) != '') {
               while (var_Value.indexOf("-") > 0) {
                   var_Value = var_Value.replace("-", "");
               }
               var_Tamano = var_Value.length; var_Tamano--;
               for (i = 0; i <= var_Tamano; i++) {
                   if (!es_Numero(var_Value.charAt(i))) {
                       var_Value = '';
                       alert("Formato inválido. Debe introducir solo números");
                       break;
                   }
               }
               var var_formato = var_Obj.formato;
               if (trim(var_formato) == '') {
                   //var_Value='';
                   //alert("La aseguradora no tiene formato de poliza.");
               }
               else {
                   ///////////////////////////////////////////////////////////////////////////////////////////////////
                   var var_formato2 = var_Obj.formato;
                   while (var_formato2.indexOf("-") > 0) {
                       var_formato2 = var_formato2.replace("-", "");
                   }
                   var var_tamano2 = var_formato2.length;
                   var var_tamano3 = var_Value.length;
                   if (var_tamano3 != var_tamano2) {
                       var_Value = '';
                       alert("Formato inválido. Debe introducir " + var_tamano2 + " digitos");
                       var_Obj.focus();
                   }
                   ///////////////////////////////////////////////////////////////////////////////////////////////////
                   var_Tamano = var_Value.length; var_Tamano--;
                   for (j = 0; j <= var_Tamano; j++) {
                       if (var_formato.charAt(j) == '-') {
                           if (var_Value.charAt(j) != '-') {
                               var_Value = var_Value.substring(0, j) + '-' + var_Value.substring(j)
                           }
                       }
                   }
               }
           }   
          }
     if(var_Minimo>0 && var_Value.length>0){var_Value=Completar(var_Value,var_Minimo);}
     var_Obj.value=var_Value;
    }
    
  function ltrim(s) 
    {  
     return s.replace(/^\s+/, "");
    }
    
  function rtrim(s) 
    {  
     return s.replace(/\s+$/, "");
    }
    
  function trim(s) 
    {  
     return rtrim(ltrim(s));
    }


  function es_Decimal(var_Numero)
    {
      switch (var_Numero)
	      {
	        case '-':
	        case ',':
	        case '1':
	        case '2':
	        case '3':
	        case '4':
	        case '5':
	        case '6':
	        case '7':
	        case '8':
	        case '9':
	        case '0':
	            {
	             return true;
		         break;
	            }
	        default:
	            {
                 return false;
          		 break;  
	            }
        }
    }
    
  function es_Numero(var_Numero)
    {
      switch (var_Numero)
	      {
	        case '0':
	        case '1':
	        case '2':
	        case '3':
	        case '4':
	        case '5':
	        case '6':
	        case '7':
	        case '8':
	        case '9':
	            {
	             return true;
		         break;
	            }
	        default:
	            {
                 return false;
          		 break;  
	            }
        }
    }
    
  function es_Letra(var_Numero)
    {
      switch (var_Numero)
	      {
	        case ' ':
	        case 'a':
	        case 'b':
	        case 'c':
	        case 'd':
	        case 'e':
	        case 'f':
	        case 'g':
	        case 'h':
	        case 'i':
	        case 'j':
	        case 'k':
	        case 'l':
	        case 'm':
	        case 'n':
	        case 'ñ':
	        case 'o':
	        case 'p':
	        case 'q':
	        case 'r':
	        case 's':
	        case 't':
	        case 'u':
	        case 'v':
	        case 'w':
	        case 'x':
	        case 'y':
	        case 'z':
	        case 'A':
	        case 'B':
	        case 'C':
	        case 'D':
	        case 'E':
	        case 'F':
	        case 'G':
	        case 'H':
	        case 'I':
	        case 'J':
	        case 'K':
	        case 'L':
	        case 'M':
	        case 'N':
	        case 'Ñ':
	        case 'O':
	        case 'P':
	        case 'Q':
	        case 'R':
	        case 'S':
	        case 'T':
	        case 'U':
	        case 'V':
	        case 'W':
	        case 'X':
	        case 'Y':
	        case 'Z':
	            {
	             return true;
		         break;
	            }
	        default:
	            {
                 return false;
          		 break;  
	            }
        }
    }

  function SoloTexto(var_Obj,event)
    {
     switch (event.keyCode)
	      {
           case 124:
           case 165:
	       case 167:
	          {
               /*event.keyCode = 0;*/
               return false;
		       break;
	          }
	      default:
	          {
	           return true;
     		   break;  
	          }
        }
    }

//  function SoloFecha(var_Obj,event) // 05/31/2005
//    {
//		  switch (event.keyCode)
//		  {
//              case 47:
//              case 48:
//		      case 49:
//		      case 50:
//		      case 51:
//		      case 52:
//		      case 53:
//		      case 54:
//		      case 55:
//		      case 56:
//		      case 57:
//		          {
//		              return true;
//			          break;
//		          }
//		      default:
//		          {
//		           return false;
//                   /*event.keyCode = 0;*/
//         		   break;  
//		          }
//          }
//    }
    
//  function SoloNumeros(event) 
//    {
//		  switch (event.keyCode)
//		  {
//              case 48:
//		      case 49:
//		      case 50:
//		      case 51:
//		      case 52:
//		      case 53:
//		      case 54:
//		      case 55:
//		      case 56:
//		      case 57:
//		          {
//		              return true;
//			          break;
//		          }
//		      default:
//		          {
//		           return false;
//                   /*event.keyCode = 0;*/
//         		      break;  
//		          }
//          }
//    }
    
  function SoloLetras(event) 
    {
		  switch (event.keyCode)
		  {
              case 32:
              case 65:
		      case 66:
		      case 67:
		      case 68:
		      case 69:
		      case 70:
		      case 71:
		      case 72:
		      case 73:
		      case 74:
		      case 75:
		      case 76:
		      case 77:
		      case 78:
		      case 79:
		      case 80:
		      case 81:
		      case 82:
		      case 83:
		      case 84:
		      case 85:
		      case 86:
		      case 87:
		      case 88:
		      case 89:
		      case 90:
		      case 97:
		      case 98:
		      case 99:
		      case 100:
		      case 101:
		      case 102:
		      case 103:
		      case 104:
		      case 105:
		      case 106:
		      case 107:
		      case 108:
		      case 109:
		      case 110:
		      case 111:
		      case 112:
		      case 113:
		      case 114:
		      case 115:
		      case 116:
		      case 117:
		      case 118:
		      case 119:
		      case 120:
		      case 121:
		      case 122:		      	      
		          {
		              return true;
			          break;
		          }
		      default:
		          {
		           return false;
                   /*event.keyCode = 0;*/
         		      break;  
		          }
          }
    }
    
  function SoloDecimales(event) 
    {//alert('entre en SoloDecimales')
		 switch (event.keyCode)
		  {
		      case 46:
		          {
                 event.keyCode = 44;
		              return true;
			          break;
		          }
              case 44:
              case 45:
              case 48:
		      case 49:
		      case 50:
		      case 51:
		      case 52:
		      case 53:
		      case 54:
		      case 55:
		      case 56:
		      case 57:
		          {
		              return true;
			          break;
		          }
		      default:
		          {
		           return false;
                   /*event.keyCode = 0;*/
         		   break;  
		          }
          }        
          return false;
    }

    function Formato_Fecha(var_Fecha, var_obj)
  {
    if(var_Fecha=='')
        {
         return ''
        }
    while(var_Fecha.indexOf("/")>0)
        {
         var_Fecha=var_Fecha.replace("/","");                     
        }                                          
    var var_Dia=var_Fecha.substring(0,2);
    var var_Mes=var_Fecha.substring(2,4);
    var var_Año=var_Fecha.substring(4,8);
    var var_Respuesta = var_Dia + '/' + var_Mes + '/' + var_Año;
    if(!es_Fecha(var_Respuesta))
        {
            alert("Formato de fecha invalido!");
            try {
                var_obj.focus();
            }
            catch (e) {                
            }
         var_Respuesta = '';
        }
    
    return var_Respuesta 
  }
  
function Redondear(var_Cantidad, var_Decimales)
  {
    var var_Cantidad = parseFloat(var_Cantidad);
    var var_Decimales = parseFloat(var_Decimales);
    var_Decimales = (!var_Decimales ? 2 : var_Decimales);
    return Math.round(var_Cantidad * Math.pow(10, var_Decimales)) / Math.pow(10, var_Decimales);
  }
  
 function Completar(var_Texto, var_Cantidad)  
    {
     var var_Tamano = var_Texto.length;
     if(var_Tamano<var_Cantidad)
        {
         var var_Faltante = var_Cantidad - var_Tamano; var_Faltante--;
         for(i=0;i<=var_Faltante;i++)
            {
             var_Texto='0' + var_Texto
            }
        }
      return var_Texto
    }
    

/*****************************************************************************
Copyright (C) 2006  Nick Baicoianu

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*****************************************************************************/
//constructor for the main Epoch class (SPANISH VERSION)
function Epoch(name,mode,targetelement,multiselect)
{
	this.state = 0;
	this.name = name;
	this.curDate = new Date();
	this.mode = mode;
	this.selectMultiple = (multiselect == true); //'false' is not true or not set at all
	
	//the various calendar variables
	//this.selectedDate = this.curDate;
	this.selectedDates = new Array();
	this.calendar;
	this.calHeading;
	this.calCells;
	this.rows;
	this.cols;
	this.cells = new Array();
	
	//The controls
	this.monthSelect;
	this.yearSelect;
	
	//standard initializations
	this.mousein = false;
	this.calConfig();
	this.setDays();
	this.displayYear = this.displayYearInitial;
	this.displayMonth = this.displayMonthInitial;
	
	this.createCalendar(); //create the calendar DOM element and its children, and their related objects
	
	if(this.mode == 'popup' && targetelement && targetelement.type == 'text') //if the target element has been set to be an input text box
	{

		this.tgt = targetelement;
		this.calendar.style.position = 'absolute';
		this.topOffset = this.tgt.offsetHeight;// the vertical distance (in pixels) to display the calendar from the Top of its input element
		this.leftOffset = 0;// the horizontal distance (in pixels) to display the calendar from the Left of its input element
        this.calendar.style.top = this.getTop(targetelement) + this.topOffset + 'px';
		this.calendar.style.left = this.getLeft(targetelement) + this.leftOffset + 'px';
		
         this.calendar.style.zIndex=5;
		document.body.appendChild(this.calendar);
		this.tgt.calendar = this;
  	    this.tgt.onfocus = function () {this.calendar.show();}; //the calendar will popup when the input element is focused
	    this.tgt.onblur = function () {if(!this.calendar.mousein){this.calendar.hide();}}; //the calendar will popup when the input element is focused
	}
	else
	{
		this.container = targetelement;
		this.container.appendChild(this.calendar);
	}
	
	this.state = 2; //0: initializing, 1: redrawing, 2: finished!
	this.visible ? this.show() : this.hide();
}
//-----------------------------------------------------------------------------
Epoch.prototype.calConfig = function () //PRIVATE: initialize calendar variables
{
	//this.mode = 'flat'; //can be 'flat' or 'popup'
	this.displayYearInitial = this.curDate.getFullYear(); //the initial year to display on load
	this.displayMonthInitial = this.curDate.getMonth(); //the initial month to display on load (0-11)
	this.rangeYearLower = 1910;
	this.rangeYearUpper = 2037;
	this.minDate = new Date(1910,0,1);
	this.maxDate = new Date(2037,0,1);
	this.startDay = 1; // the day the week will 'start' on: 0(Sun) to 6(Sat)
	this.showWeeks = true; //whether the week numbers will be shown
	this.selCurMonthOnly = false; //allow user to only select dates in the currently displayed month
	this.clearSelectedOnChange = true; //whether to clear all selected dates when changing months
	
	//flat mode-only settings:
	//this.selectMultiple = true; //whether the user can select multiple dates (flat mode only)

	switch(this.mode) //set the variables based on the calendar mode
	{
		case 'popup': //popup options
			this.visible = false;
			break;
		case 'flat':
			this.visible = true;
			
			break;
	}
	this.setLang();
};
//-----------------------------------------------------------------------------
Epoch.prototype.setLang = function()  //all language settings for Epoch are made here.  Check Date.dateFormat() for the Date object's language settings
{
	this.daylist = new Array('Do','Lu','Ma','Mi','Ju','Vi','Sa','Do','Lu','Ma','Mi','Ju','Vi','Sa');
	this.months_sh = new Array('Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic');
	this.monthup_title = 'Ir al mes siguiente';
	this.monthdn_title = 'Ir al mes anterior';
	this.clearbtn_caption = 'Cerrar';
	this.clearbtn_title = 'Limpiar todas las fechas seleccionadas en el calendario';
	this.maxrange_caption = 'Este es el rango máximo';
};
//-----------------------------------------------------------------------------
Epoch.prototype.getTop = function (element) //PRIVATE: returns the absolute Top value of element, in pixels
{
    var oNode = element;
    var iTop = 0;
    
    while(oNode.tagName != 'HTML') 
        {
          iTop += oNode.offsetTop;
          if (oNode.tagName == 'BODY'){break}
          oNode = oNode.offsetParent;
        }
    
    return iTop;
};
//-----------------------------------------------------------------------------
Epoch.prototype.getLeft = function (element) //PRIVATE: returns the absolute Left value of element, in pixels
{
    var oNode = element;
    var iLeft = 0;
    
    while(oNode.tagName != 'HTML') 
        {
         iLeft += oNode.offsetLeft;
         if(oNode.tagName == 'BODY'){break}   
         oNode = oNode.offsetParent;     
        }
    
    return iLeft;
};
//-----------------------------------------------------------------------------
Epoch.prototype.show = function () //PUBLIC: displays the calendar
{
	this.calendar.style.display = 'block';
	this.visible = true;
};
//-----------------------------------------------------------------------------
Epoch.prototype.hide = function () //PUBLIC: Hides the calendar
{
	this.calendar.style.display = 'none';
	this.visible = false;
};
//-----------------------------------------------------------------------------
Epoch.prototype.toggle = function () //PUBLIC: Toggles (shows/hides) the calendar depending on its current state
{
	if(this.visible) {
		this.hide();
	}
	else {
		this.show();
	}
};
//-----------------------------------------------------------------------------
Epoch.prototype.setDays = function ()  //PRIVATE: initializes the standard Gregorian Calendar parameters
{
	this.daynames = new Array();
	var j=0;
	for(var i=this.startDay; i< this.startDay + 7;i++) {
		this.daynames[j++] = this.daylist[i];
	}
		
	this.monthDayCount = new Array(31,((this.curDate.getFullYear() - 2000) % 4 ? 28 : 29),31,30,31,30,31,31,30,31,30,31);
};
//-----------------------------------------------------------------------------
Epoch.prototype.setClass = function (element,className) //PRIVATE: sets the CSS class of the element, W3C & IE
{
	element.setAttribute('class',className);
	element.setAttribute('className',className); //<iehack>
};
//-----------------------------------------------------------------------------
Epoch.prototype.createCalendar = function ()  //PRIVATE: creates the full DOM implementation of the calendar
{
	var tbody, tr, td, iFrame;
	this.calendar = document.createElement('table');
 /* this.calendar.style.border='0';*/
	this.calendar.setAttribute('id',this.name+'_calendar');
	this.setClass(this.calendar,'calendar');
	//to prevent IE from selecting text when clicking on the calendar
	this.calendar.onselectstart = function() {return false;};
	this.calendar.ondrag = function() {return false;};

	tbody = document.createElement('tbody');
	

	//create iframe
  iFrame = document.createElement('iframe');  
  iFrame.id="ifrm_calendar";
  iFrame.setClass=(this.iFrame,'iframe');
  iFrame.style.height='207px';
  iFrame.style.width='200px';
  iFrame.frameborder='0'; 
 
	tr = document.createElement('tr');
	td = document.createElement('td');
	td.appendChild(iFrame);
	tr.appendChild(td);
	tr.style.position = 'absolute';
  tr.style.top = '-1';
  tr.style.left = '-1';
  tr.style.zIndex='-1';
	tbody.appendChild(tr);
	

	//create the Main Calendar Heading
	tr = document.createElement('tr');
	td = document.createElement('td');
	td.appendChild(this.createMainHeading());
	tr.appendChild(td);
  //tr.style.top = '0';
  //tr.style.left = '0';
	//tr.style.position = 'absolute';
	tbody.appendChild(tr);
	
	//create the calendar Day Heading
	tr = document.createElement('tr');
	td = document.createElement('td');
	td.appendChild(this.createDayHeading());
	tr.appendChild(td);
 // tr.style.top = '25';
  //tr.style.left = '0';
	//tr.style.position = 'absolute';
	tbody.appendChild(tr);

	//create the calendar Day Cells
	tr = document.createElement('tr');
	td = document.createElement('td');
	td.setAttribute('id',this.name+'_cell_td');
	this.calCellContainer = td;	//used as a handle for manipulating the calendar cells as a whole
	td.appendChild(this.createCalCells());
	tr.appendChild(td);
  //tr.style.top = '40';
  //tr.style.left = '0';
	//tr.style.position = 'absolute';
	tbody.appendChild(tr);
	
	//create the calendar footer
	tr = document.createElement('tr');
	td = document.createElement('td');
	td.appendChild(this.createFooter());
	tr.appendChild(td);
  //tr.style.top = '180';
  //tr.style.left = '0';
	//tr.style.position = 'absolute';
	tbody.appendChild(tr);
	
	//add the tbody element to the main calendar table
  this.calendar.appendChild(tbody);

	//and add the onmouseover events to the calendar table
	this.calendar.owner = this;
	this.calendar.onmouseover = function() {this.owner.mousein = true;};
	this.calendar.onmouseout = function() {this.owner.mousein = false;};

};
//-----------------------------------------------------------------------------
Epoch.prototype.createMainHeading = function () //PRIVATE: Creates the primary calendar heading, with months & years
{
	//create the containing <div> element
	var container = document.createElement('div');
	container.setAttribute('id',this.name+'_mainheading');
	this.setClass(container,'mainheading');
	//create the child elements and other variables
	this.monthSelect = document.createElement('select');
	this.yearSelect = document.createElement('select');
	var monthDn = document.createElement('input'), monthUp = document.createElement('input');  
	var opt, i;
	
	//fill the month select box
	for(i=0;i<12;i++)
	{
		opt = document.createElement('option');
		opt.setAttribute('value',i);
		if(this.state == 0 && this.displayMonth == i) {
			opt.setAttribute('selected','selected');
		}
		opt.appendChild(document.createTextNode(this.months_sh[i]));
		this.monthSelect.appendChild(opt);
	}
	//and fill the year select box
	for(i=this.rangeYearLower;i<=this.rangeYearUpper;i++)
	{
		opt = document.createElement('option');
		opt.setAttribute('value',i);
		if(this.state == 0 && this.displayYear == i) {
			opt.setAttribute('selected','selected');
		}
		opt.appendChild(document.createTextNode(i));
		this.yearSelect.appendChild(opt);		
	}
	//add the appropriate children for the month buttons
	monthUp.setAttribute('type','button');
	monthUp.setAttribute('value','>');
	monthUp.setAttribute('title',this.monthup_title);
	monthDn.setAttribute('type','button');
	monthDn.setAttribute('value','<');
	monthDn.setAttribute('title',this.monthdn_title);
	this.monthSelect.owner = this.yearSelect.owner = monthUp.owner = monthDn.owner = this;  //hack to allow us to access this calendar in the events (<fix>??)
	
	//assign the event handlers for the controls
	monthUp.onmouseup = function () {this.owner.nextMonth();};
	monthDn.onmouseup = function () {this.owner.prevMonth();};
	this.monthSelect.onchange = function() {
		this.owner.displayMonth = this.value;
		this.owner.displayYear = this.owner.yearSelect.value; 
		this.owner.goToMonth(this.owner.displayYear,this.owner.displayMonth);
	};
	this.yearSelect.onchange = function() {
		this.owner.displayMonth = this.owner.monthSelect.value;
		this.owner.displayYear = this.value; 
		this.owner.goToMonth(this.owner.displayYear,this.owner.displayMonth);
	};
	
	//and finally add the elements to the containing div
	container.appendChild(monthDn);
	container.appendChild(this.monthSelect);
	container.appendChild(this.yearSelect);
	container.appendChild(monthUp);
	return container;
};
//-----------------------------------------------------------------------------
Epoch.prototype.createFooter = function () //PRIVATE: creates the footer of the calendar - goes under the calendar cells
{
	var container = document.createElement('div');
	var clearSelected = document.createElement('input'); clearSelected.className='pestana_btn';
	clearSelected.setAttribute('type','button');
	clearSelected.setAttribute('value',this.clearbtn_caption);
	clearSelected.setAttribute('title',this.clearbtn_title);
	clearSelected.owner = this;
	clearSelected.onclick = function() { this.owner.resetSelections(false);};
	container.appendChild(clearSelected);
	return container;
};
//-----------------------------------------------------------------------------
Epoch.prototype.resetSelections = function (returnToDefaultMonth)  //PRIVATE: reset the calendar's selection variables to defaults
{
	this.selectedDates = new Array();
	this.rows = new Array(false,false,false,false,false,false,false);
	this.cols = new Array(false,false,false,false,false,false,false);
	if(this.tgt)  //if there is a target element, clear it too
	{
		this.tgt.value = '';
		if(this.mode == 'popup') {//hide the calendar if in popup mode
			this.hide();
		}
	}
		
	if(returnToDefaultMonth == true) {
		this.goToMonth(this.displayYearInitial,this.displayMonthInitial);
	}
	else {
		this.reDraw();
	}
};
//-----------------------------------------------------------------------------
Epoch.prototype.createDayHeading = function ()  //PRIVATE: creates the heading containing the day names
{
	//create the table element
	this.calHeading = document.createElement('table');
	this.calHeading.setAttribute('id',this.name+'_caldayheading');
	this.setClass(this.calHeading,'caldayheading');
	var tbody,tr,td;
	tbody = document.createElement('tbody');
	tr = document.createElement('tr');
	this.cols = new Array(false,false,false,false,false,false,false);
	
	//if we're showing the week headings, create an empty <td> for filler
	if(this.showWeeks)
	{
		td = document.createElement('td');
		td.setAttribute('class','wkhead');
		td.setAttribute('className','wkhead'); //<iehack>
		tr.appendChild(td);
	}
	//populate the day titles
	for(var dow=0;dow<7;dow++)
	{
		td = document.createElement('td');
		td.appendChild(document.createTextNode(this.daynames[dow]));
		if(this.selectMultiple) { //if selectMultiple is true, assign the cell a CalHeading Object to handle all events
			td.headObj = new CalHeading(this,td,(dow + this.startDay < 7 ? dow + this.startDay : dow + this.startDay - 7));
		}
		tr.appendChild(td);
	}
	tbody.appendChild(tr);
	this.calHeading.appendChild(tbody);
	return this.calHeading;	
};
//-----------------------------------------------------------------------------
Epoch.prototype.createCalCells = function ()  //PRIVATE: creates the table containing the calendar day cells
{
	this.rows = new Array(false,false,false,false,false,false);
	this.cells = new Array();
	var row = -1, totalCells = (this.showWeeks ? 48 : 42);
	var beginDate = new Date(this.displayYear,this.displayMonth,1);
	var endDate = new Date(this.displayYear,this.displayMonth,this.monthDayCount[this.displayMonth]);
	var sdt = new Date(beginDate);
	sdt.setDate(sdt.getDate() + (this.startDay - beginDate.getDay()) - (this.startDay - beginDate.getDay() > 0 ? 7 : 0) );
	//create the table element
	this.calCells = document.createElement('table');
	this.calCells.setAttribute('id',this.name+'_calcells');
	this.setClass(this.calCells,'calcells');
	var tbody,tr,td;
	tbody = document.createElement('tbody');
	for(var i=0;i<totalCells;i++)
	{
		if(this.showWeeks) //if we are showing the week headings
		{
			if(i % 8 == 0)
			{
				row++;
				tr = document.createElement('tr');
				td = document.createElement('td');
				if(this.selectMultiple) { //if selectMultiple is enabled, create the associated weekObj objects
					td.weekObj = new WeekHeading(this,td,sdt.getWeek(),row)
				}
				else //otherwise just set the class of the td for consistent look
				{
					td.setAttribute('class','wkhead');
					td.setAttribute('className','wkhead'); //<iehack>
				}
				td.appendChild(document.createTextNode(sdt.getWeek()));			
				tr.appendChild(td);
				i++;
			}
		}
		else if(i % 7 == 0) //otherwise, new row every 7 cells
		{
			row++;
			tr = document.createElement('tr');
		}
		//create the day cells
		td = document.createElement('td');
		td.appendChild(document.createTextNode(sdt.getDate()));// +' ' +sdt.getUeDay()));
		var cell = new CalCell(this,td,sdt,row);
		this.cells.push(cell);
		td.cellObj = cell;
		sdt.setDate(sdt.getDate() + 1); //increment the date
		tr.appendChild(td);
		tbody.appendChild(tr);
	}
	this.calCells.appendChild(tbody);
	this.reDraw();
	return this.calCells;
};
//-----------------------------------------------------------------------------
Epoch.prototype.reDraw = function () //PRIVATE: reapplies all the CSS classes for the calendar cells, usually called after chaning their state
{
	this.state = 1;
	var i,j;
	for(i=0;i<this.cells.length;i++) {
		this.cells[i].selected = false;
	}
	for(i=0;i<this.cells.length;i++)
	{
		for(j=0;j<this.selectedDates.length;j++) { //if the cell's date is in the selectedDates array, set its selected property to true
			if(this.cells[i].date.getUeDay() == this.selectedDates[j].getUeDay() ) {
				this.cells[i].selected = true;
			}
		}

		this.cells[i].setClass();
	}
	//alert(this.selectedDates);
	this.state = 2;
};
//-----------------------------------------------------------------------------
Epoch.prototype.deleteCells = function () //PRIVATE: removes the calendar cells from the DOM (does not delete the cell objects associated with them
{
	this.calCellContainer.removeChild(this.calCellContainer.firstChild); //get a handle on the cell table (optional - for less indirection)
	this.cells = new Array(); //reset the cells array
};
//-----------------------------------------------------------------------------
Epoch.prototype.goToMonth = function (year,month) //PUBLIC: sets the calendar to display the requested month/year
{
	this.monthSelect.value = this.displayMonth = month;
	this.yearSelect.value = this.displayYear = year;
	this.deleteCells();
	this.calCellContainer.appendChild(this.createCalCells());
};
//-----------------------------------------------------------------------------
Epoch.prototype.nextMonth = function () //PUBLIC: go to the next month.  if the month is december, go to january of the next year
{
	
	//increment the month/year values, provided they're within the min/max ranges
	if(this.monthSelect.value < 11) {
		this.monthSelect.value++;
	}
	else
	{
		if(this.yearSelect.value < this.rangeYearUpper)
		{
			this.monthSelect.value = 0;
			this.yearSelect.value++;
		}
		else {
			alert(this.maxrange_caption);
		}
	}
	//assign the currently displaying month/year values
	this.displayMonth = this.monthSelect.value;
	this.displayYear = this.yearSelect.value;
	
	//and refresh the calendar for the new month/year
	this.deleteCells();
	this.calCellContainer.appendChild(this.createCalCells());
};
//-----------------------------------------------------------------------------
Epoch.prototype.prevMonth = function () //PUBLIC: go to the previous month.  if the month is january, go to december of the previous year
{
	//increment the month/year values, provided they're within the min/max ranges
	if(this.monthSelect.value > 0)
		this.monthSelect.value--;
	else
	{
		if(this.yearSelect.value > this.rangeYearLower)
		{
			this.monthSelect.value = 11;
			this.yearSelect.value--;
		}
		else {
			alert(this.maxrange_caption);
		}
	}
	
	//assign the currently displaying month/year values
	this.displayMonth = this.monthSelect.value;
	this.displayYear = this.yearSelect.value;
	
	//and refresh the calendar for the new month/year
	this.deleteCells();
	this.calCellContainer.appendChild(this.createCalCells());
};
//-----------------------------------------------------------------------------
Epoch.prototype.addZero = function (vNumber) //PRIVATE: pads a 2 digit number with a leading zero
{
	return ((vNumber < 10) ? '0' : '') + vNumber;
};
//-----------------------------------------------------------------------------
Epoch.prototype.addDates = function (dates,redraw)  //PUBLIC: adds the array "dates" to the calendars selectedDates array (no duplicate dates) and redraws the calendar
{
	var j,in_sd;
	for(var i=0;i<dates.length;i++)
	{	
		in_sd = false;
		for(j=0;j<this.selectedDates.length;j++)
		{
			if(dates[i].getUeDay() == this.selectedDates[j].getUeDay())
			{
				in_sd = true;
				break;
			}
		}
		if(!in_sd) { //if the date isn't already in the array, add it!
			this.selectedDates.push(dates[i]);
		}
	}
	if(redraw != false) {//redraw  the calendar if "redraw" is false or undefined
		this.reDraw();
	}
};
//-----------------------------------------------------------------------------
Epoch.prototype.removeDates = function (dates,redraw)  //PUBLIC: adds the dates to the calendars selectedDates array and redraws the calendar
{
	var j;
	for(var i=0;i<dates.length;i++)
	{
		for(j=0;j<this.selectedDates.length;j++)
		{
			if(dates[i].getUeDay() == this.selectedDates[j].getUeDay()) { //search for the dates in the selectedDates array, removing them if the dates match
				this.selectedDates.splice(j,1);
			}
		}
	}
	if(redraw != false) { //redraw  the calendar if "redraw" is false or undefined
		this.reDraw();
	}
};
//-----------------------------------------------------------------------------
Epoch.prototype.outputDate = function (vDate, vFormat) //PUBLIC: outputs a date in the appropriate format (DEPRECATED)
{
	var vDay			= this.addZero(vDate.getDate()); 
	var vMonth			= this.addZero(vDate.getMonth() + 1); 
	var vYearLong		= this.addZero(vDate.getFullYear()); 
	var vYearShort		= this.addZero(vDate.getFullYear().toString().substring(3,4)); 
	var vYear			= (vFormat.indexOf('yyyy') > -1 ? vYearLong : vYearShort);
	var vHour			= this.addZero(vDate.getHours()); 
	var vMinute			= this.addZero(vDate.getMinutes()); 
	var vSecond			= this.addZero(vDate.getSeconds()); 
	return vFormat.replace(/dd/g, vDay).replace(/mm/g, vMonth).replace(/y{1,4}/g, vYear).replace(/hh/g, vHour).replace(/nn/g, vMinute).replace(/ss/g, vSecond);
};
//-----------------------------------------------------------------------------
Epoch.prototype.updatePos = function (target) //PUBLIC: moves the calendar's position to target's location (popup mode only)
{
	this.calendar.style.top = this.getTop(target) + this.topOffset + 'px'
	this.calendar.style.left = this.getLeft(target) + this.leftOffset + 'px'
}
//-----------------------------------------------------------------------------

/*****************************************************************************/
function CalHeading(owner,tableCell,dow)
{
	this.owner = owner;
	this.tableCell = tableCell;
	this.dayOfWeek = dow;
	
	//the event handlers
	this.tableCell.onclick = this.onclick;
}
//-----------------------------------------------------------------------------
CalHeading.prototype.onclick = function ()
{
	//reduce indirection:
	var owner = this.headObj.owner;
	var sdates = owner.selectedDates;
	var cells = owner.cells;
	
	owner.cols[this.headObj.dayOfWeek] = !owner.cols[this.headObj.dayOfWeek];
	for(var i=0;i<cells.length;i++) //cycle through all the cells in the calendar, selecting all cells with the same dayOfWeek as this heading
	{
		if(cells[i].dayOfWeek == this.headObj.dayOfWeek && (!owner.selCurMonthOnly || cells[i].date.getMonth() == owner.displayMonth && cells[i].date.getFullYear() == owner.displayYear)) //if the cell's DoW matches, with other conditions
		{
			if(owner.cols[this.headObj.dayOfWeek]) 		//if selecting, add the cell's date to the selectedDates array
			{
				if(owner.selectedDates.arrayIndex(cells[i].date) == -1) { //if the date isn't already in the array
					sdates.push(cells[i].date);
				}
			}
			else										//otherwise, remove it
			{
				for(var j=0;j<sdates.length;j++) 
				{
					if(cells[i].dayOfWeek == sdates[j].getDay())
					{
						sdates.splice(j,1);	//remove dates that are within the displaying month/year that have the same day of week as the day cell
						break;
					}
				}
			}
			cells[i].selected = owner.cols[this.headObj.dayOfWeek];
		}
	}
	owner.reDraw();
};
/*****************************************************************************/
function WeekHeading(owner,tableCell,week,row)
{
	this.owner = owner;
	this.tableCell = tableCell;
	this.week = week;
	this.tableRow = row;
	this.tableCell.setAttribute('class','wkhead');
	this.tableCell.setAttribute('className','wkhead'); //<iehack>
	//the event handlers
	this.tableCell.onclick = this.onclick;
}
//-----------------------------------------------------------------------------
WeekHeading.prototype.onclick = function ()
{
	//reduce indirection:
	var owner = this.weekObj.owner;
	var cells = owner.cells;
	var sdates = owner.selectedDates;
	var i,j;
	owner.rows[this.weekObj.tableRow] = !owner.rows[this.weekObj.tableRow];
	for(i=0;i<cells.length;i++)
	{
		if(cells[i].tableRow == this.weekObj.tableRow)
		{
			if(owner.rows[this.weekObj.tableRow] && (!owner.selCurMonthOnly || cells[i].date.getMonth() == owner.displayMonth && cells[i].date.getFullYear() == owner.displayYear)) //match all cells in the current row, with option to restrict to current month only
			{
				if(owner.selectedDates.arrayIndex(cells[i].date) == -1) {//if the date isn't already in the array
					sdates.push(cells[i].date);
				}
			}
			else										//otherwise, remove it
			{
				for(j=0;j<sdates.length;j++)
				{
					if(sdates[j].getTime() == cells[i].date.getTime())  //this.weekObj.tableRow && sdates[j].getMonth() == owner.displayMonth && sdates[j].getFullYear() == owner.displayYear)
					{
						sdates.splice(j,1);	//remove dates that are within the displaying month/year that have the same day of week as the day cell
						break;
					}
				}
			}
		}
	}
	owner.reDraw();
};
/*****************************************************************************/
//-----------------------------------------------------------------------------
function CalCell(owner,tableCell,dateObj,row)
{
	this.owner = owner;		//used primarily for event handling
	this.tableCell = tableCell; 			//the link to this cell object's table cell in the DOM
	this.cellClass;			//the CSS class of the cell
	this.selected = false;	//whether the cell is selected (and is therefore stored in the owner's selectedDates array)
	this.date = new Date(dateObj);
	this.dayOfWeek = this.date.getDay();
	this.week = this.date.getWeek();
	this.tableRow = row;
	
	//assign the event handlers for the table cell element
	this.tableCell.onclick = this.onclick;
	this.tableCell.onmouseover = this.onmouseover;
	this.tableCell.onmouseout = this.onmouseout;
	
	//and set the CSS class of the table cell
	this.setClass();
}
//-----------------------------------------------------------------------------
CalCell.prototype.onmouseover = function () //replicate CSS :hover effect for non-supporting browsers <iehack>
{
	this.setAttribute('class',this.cellClass + ' hover');
	this.setAttribute('className',this.cellClass + ' hover');
};
//-----------------------------------------------------------------------------
CalCell.prototype.onmouseout = function () //replicate CSS :hover effect for non-supporting browsers <iehack>
{
	this.cellObj.setClass();
};
//-----------------------------------------------------------------------------
CalCell.prototype.onclick = function () 
{
	//reduce indirection:
	var cell = this.cellObj;
	var owner = cell.owner;
	if(!owner.selCurMonthOnly || cell.date.getMonth() == owner.displayMonth && cell.date.getFullYear() == owner.displayYear)
	{
		if(owner.selectMultiple == true)  //if we can select multiple cells simultaneously, add the currently selected cell's date to the selectedDates array
		{
			if(!cell.selected) //if this cell has been selected
			{
				if(owner.selectedDates.arrayIndex(cell.date) == -1) {
					owner.selectedDates.push(cell.date);
				}
			}
			else		
			{
				var tmp = owner.selectedDates; // to reduce indirection
				//if the cell has been deselected, remove it from the owner calendar's selectedDates array
				for(var i=0;i<tmp.length;i++)
				{
					if(tmp[i].getUeDay() == cell.date.getUeDay()) {
						tmp.splice(i,1);
					}
				}
			}
		}
		else //if we can only select one cell at a time
		{
			owner.selectedDates = new Array(cell.date);
			if(owner.tgt) //if there is a target element to place the value in, do so
			{
				owner.tgt.value = owner.selectedDates[0].dateFormat();
				if(owner.mode == 'popup') {
					owner.hide();
				}
			}
		}
		owner.reDraw(); //redraw the calendar cell styles to reflect the changes
	}
};
//-----------------------------------------------------------------------------
CalCell.prototype.setClass = function ()  //private: sets the CSS class of the cell based on the specified criteria
{
	if(this.selected) {
		this.cellClass = 'cell_selected';
	}
	else if(this.owner.displayMonth != this.date.getMonth() ) {
		this.cellClass = 'notmnth';	
	}
	else if(this.date.getDay() > 0 && this.date.getDay() < 6) {
		this.cellClass = 'wkday';
	}
	else {
		this.cellClass = 'wkend';
	}
	
	if(this.date.getFullYear() == this.owner.curDate.getFullYear() && this.date.getMonth() == this.owner.curDate.getMonth() && this.date.getDate() == this.owner.curDate.getDate()) {
		this.cellClass = this.cellClass + ' curdate';
	}

	this.tableCell.setAttribute('class',this.cellClass);
	this.tableCell.setAttribute('className',this.cellClass); //<iehack>
};
/*****************************************************************************/
Date.prototype.getDayOfYear = function () //returns the day of the year for this date
{
	return parseInt((this.getTime() - new Date(this.getFullYear(),0,1).getTime())/86400000 + 1);
};
//-----------------------------------------------------------------------------
Date.prototype.getWeek = function () //returns the day of the year for this date
{
	return parseInt((this.getTime() - new Date(this.getFullYear(),0,1).getTime())/604800000 + 1);
};
/*function getISOWeek()
{
	var newYear = new Date(this.getFullYear(),0,1);
	var modDay = newYear.getDay();
	if (modDay == 0) modDay=6; else modDay--;
	
	var daynum = ((Date.UTC(this.getFullYear(),this.getMonth(),this.getDate(),0,0,0) - Date.UTC(this.getFullYear()),0,1,0,0,0)) /1000/60/60/24) + 1;
	
	if (modDay < 4 ) {
	    var weeknum = Math.floor((daynum+modDay-1)/7)+1;
	}
	else {
	    var weeknum = Math.floor((daynum+modDay-1)/7);
	    if (weeknum == 0) {
	        year--;
	        var prevNewYear = new Date(this.getFullYear(),0,1);
	        var prevmodDay = prevNewYear.getDay();
	        if (prevmodDay == 0) prevmodDay = 6; else prevmodDay--;
	        if (prevmodDay < 4) weeknum = 53; else weeknum = 52;
	    }
	}
	
	return + weeknum;
}*/
//-----------------------------------------------------------------------------
Date.prototype.getUeDay = function () //returns the number of DAYS since the UNIX Epoch - good for comparing the date portion
{
	return parseInt(Math.floor((this.getTime() - this.getTimezoneOffset() * 60000)/86400000)); //must take into account the local timezone
};
//-----------------------------------------------------------------------------
Date.prototype.dateFormat = function(format)
{
	if(!format) { // the default date format to use - can be customized to the current locale
//		var var_CR = navigator.userLanguage;
//		if(var_CR.substring(0,2)=='es')
//		  {
		   format = 'd/m/Y';
//		  }
//		else
//		  {
//		   format = 'm/d/Y';
//		  }        		
	}
	LZ = function(x) {return(x < 0 || x > 9 ? '' : '0') + x};
	var MONTH_NAMES = new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	var DAY_NAMES = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
	format = format + "";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=this.getFullYear().toString();
	var M=this.getMonth()+1;
	var d=this.getDate();
	var E=this.getDay();
	var H=this.getHours();
	var m=this.getMinutes();
	var s=this.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real this parts into formatted versions
	var value = new Object();
	//if (y.length < 4) {y=''+(y-0+1900);}
	value['Y'] = y.toString();
	value['y'] = y.substring(2);
	value['n'] = M;
	value['m'] = LZ(M);
	value['F'] = MONTH_NAMES[M-1];
	value['M'] = MONTH_NAMES[M+11];
	value['j'] = d;
	value['d'] = LZ(d);
	value['D'] = DAY_NAMES[E+7];
	value['l'] = DAY_NAMES[E];
	value['G'] = H;
	value['H'] = LZ(H);
	if (H==0) {value['g']=12;}
	else if (H>12){value['g']=H-12;}
	else {value['g']=H;}
	value['h']=LZ(value['g']);
	if (H > 11) {value['a']='pm'; value['A'] = 'PM';}
	else { value['a']='am'; value['A'] = 'AM';}
	value['i']=LZ(m);
	value['s']=LZ(s);
	//construct the result string
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
};
/*****************************************************************************/
Array.prototype.arrayIndex = function(searchVal,startIndex) //similar to array.indexOf() - created to fix IE deficiencies
{
	startIndex = (startIndex != null ? startIndex : 0); //default startIndex to 0, if not set
	for(var i=startIndex;i<this.length;i++)
	{
		if(searchVal == this[i]) {
			return i;
		}
	}
	return -1;
};
/*****************************************************************************/


