// JavaScript Document
/*  Autor: Pedro Giacometto
 * --------------------------------------------------------------------------
 */

//funcion para desloguearse y cerrar sesion
function logout(url){
					var conf = true;
					if(confirm("Esta Seguro de Salir?")){
						open(url,"_self");
					}else
						conf = false;
					return conf;
				}

/*
 * --Funcion Generica de validaciones(Valideitor 1.0 beta)--
 *
 * Descripcion: Fucion para validar todos los campos de unformulario valida si existe, tipo, personaliza alert y enfoca el campo.
 *
 * Funcionamiento: Primero el formulario debe tener name="form" obligatoriamente; Se pasa la funcion de la siguiente manera
                             TIPO        id DEL CAMPO           TEXTO DE ALERTA
	   evento="validacion(  'V|AN|'  ,  'campo1|campo2'  , 'falta campo1|falta campo2'    )"
 */
function validacion(idform,tipo,campo,alerta,length)
 {
    t_campo = campo.split("|");
	t_aler  = alerta.split("|");
    t_tipo  = tipo.split("|");
	t_length=length.split("|");
	e=t_campo.length;
	e_=e-1;
for (i=0;i<=e_;i++)
   {
		 switch(t_tipo[i])
			{
		//caso si exite V = tipo,campo,alerta,length / V  ID  ALER  50
				 case 'V': {
							 campo_v=document.getElementById(t_campo[i])
							  if  (campo_v.value=='')
								{
								  alert("Complete el campo: "+ t_aler[i]);
								  campo_v.style.border="1px solid #990000";
								  campo_v.style.color="#990000";
								  campo_v.focus();
								  return false;
								}
		       //restaura el color original
							campo_v.style.border="1px solid  #999999";
							campo_v.style.color="";
						   }
						    break;

		//caso si es alfanumerico AN
      case 'AN': case'N': {
							   campo_v=document.getElementById(t_campo[i])
							   campo_len=campo_v.value.length;

							  if  (campo_v.value=='' || campo_len > t_length[i])
								{
										if (campo_v.value=='')
										  {
											  alert("Complete el campo: "+ t_aler[i]);
										  }
										if (campo_len > t_length[i])
										  {
											  alert("El campo:"+ t_aler[i]+"\n debe contener un máximo de " +t_length[i]+" caracteres");
											  campo_v.value = campo_v.value.substring(0, t_length[i]);
											  campo_v.select()
										  }
									   campo_v.style.border="1px solid #990000"
									   campo_v.focus();
									   return false;
								}
							   else
						//continua y verifica q los valores sean corectos
							   if (t_tipo[i]=='AN')
								 {
									 var checkOK = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚabcdefghijklmnñopqrstuvwxyzáéíóú0123456789,.;:=?¿!¡()% ";
									 texto='Alfanumericos'
								 }
							   if (t_tipo[i]=='N')
								 {
									var checkOK = "0123456789-.";
									texto='Numericos'
								 }

									  var checkStr =campo_v.value;
									  var allValid = true;
									  for (l = 0;  l < checkStr.length;  l++)
									  {
										ch = checkStr.charAt(l);
										for (j = 0;  j < checkOK.length;  j++)
										  if (ch == checkOK.charAt(j))
											break;
										if (j == checkOK.length)
										{
										  allValid = false;
										  break;
										}
									  }
									  if (!allValid)
									  {
										alert("El campo " + t_aler[i] + " solo permite valores "+ texto);
										campo_v.style.border="1px solid #990000";
										campo_v.select();
										campo_v.focus();
										return false;
									  }
								campo_v.style.border="1px solid  #999999";
							}
									break;
//Función que valida que el rango de fechas sea el correcto. Es decir, que la fecha desde sea menor a la fecha hasta, tomando en cuenta día - mes - año
			case 'F':{
							    fechas=t_campo[i].split("/");
							    campo_v=document.getElementById(fechas[1])
							  if  (campo_v.value=='')
								{
								  alert("Complete el campo: "+ t_aler[i]);
								  campo_v.style.border="1px solid #990000";
								  campo_v.style.color="#990000";
								  campo_v.focus();
								  return false
								}
		       //restaura el color original
							campo_v.style.border="1px solid  #999999";
							campo_v.style.color="";

							    obj1=document.getElementById(fechas[0])
								obj2=document.getElementById(fechas[1])

								String1 = obj1.value;
								String2 = obj2.value;
								// Si los dias y los meses llegan con un valor menor que 10
								// Se concatena un 0 a cada valor dentro del string
								if (String1.substring(1,2)=="/")
								{
									String1="0"+String1
								}
								if (String1.substring(4,5)=="/")
								{
									String1=String1.substring(0,3)+"0"+String1.substring(3,9)
								}

								if (String2.substring(1,2)=="/")
								{
									String2="0"+String2
								}
								if (String2.substring(4,5)=="/")
								{
									String2=String2.substring(0,3)+"0"+String2.substring(3,9)
								}

								dia1=String1.substring(0,2);
								mes1=String1.substring(3,5);
								anyo1=String1.substring(6,10);
								dia2=String2.substring(0,2);
								mes2=String2.substring(3,5);
								anyo2=String2.substring(6,10);


								if (dia1 == "08") // parseInt("08") == 10 base octogonal
								dia1 = "8";
								if (dia1 == '09') // parseInt("09") == 11 base octogonal
								dia1 = "9";
								if (mes1 == "08") // parseInt("08") == 10 base octogonal
								mes1 = "8";
								if (mes1 == "09") // parseInt("09") == 11 base octogonal
								mes1 = "9";
								if (dia2 == "08") // parseInt("08") == 10 base octogonal
								dia2 = "8";
								if (dia2 == '09') // parseInt("09") == 11 base octogonal
								dia2 = "9";
								if (mes2 == "08") // parseInt("08") == 10 base octogonal
								mes2 = "8";
								if (mes2 == "09") // parseInt("09") == 11 base octogonal
								mes2 = "9";

								dia1=parseInt(dia1);
								dia2=parseInt(dia2);
								mes1=parseInt(mes1);
								mes2=parseInt(mes2);
								anyo1=parseInt(anyo1);
								anyo2=parseInt(anyo2);

								if (anyo1>anyo2)
								{
									alert("Rango de Fecha no valido")
									campo_v.style.border="1px solid #990000";
								    campo_v.style.color="#990000";
								    campo_v.focus();
									return false;
								}
								if ((anyo1==anyo2) && (mes1>mes2))
								{
									alert("Rango de Fecha no valido")
								    campo_v.style.border="1px solid #990000";
								    campo_v.style.color="#990000";
								    campo_v.focus();
									return false;
								}
								if ((anyo1==anyo2) && (mes1==mes2) && (dia1>dia2))
								{
									alert("Rango de Fecha no valido")
								    campo_v.style.border="1px solid #990000";
									campo_v.style.color="#990000";
									campo_v.focus();
									return false;
								}


					 }
					break;
				//caso solo para comprobar valides de dos pasword
					case 'P':{

								pass1=document.getElementById('agregar_password');
								pass2=document.getElementById('agregar_password2');

								pass_len=pass1.value.length

								if(pass_len < 8 || pass_len > 32){
								alert('El password debe tener minimo 8 y maximo 32 caracteres')
								pass1.style.border="1px solid #990000";
								pass1.style.color="#990000";
								pass1.focus();
								return false;
								}

								if(pass1.value!=pass2.value){
								alert('Reescriba el password')
								pass2.style.border="1px solid #990000";
								pass2.style.color="#990000";
								pass2.focus();
								pass2=document.getElementById('agregar_password2').value='';
								return false;
								}
					}

					break;

					case 'IP':{

									campo_v=document.getElementById(t_campo[i])
									if  (campo_v.value=='')
									{
									alert("Complete el campo: "+ t_aler[i]);
									campo_v.style.border="1px solid #990000";
									campo_v.style.color="#990000";
									campo_v.focus();
									return false;
									}
									//restaura el color original
									campo_v.style.border="1px solid  #999999";
									campo_v.style.color="";
								//pass1=document.getElementById('ip');

									partes=campo_v.value.split('.');
									if (partes.length!=4) {
									alert('IP no valida \n Formato: 199.199.199.199');
									campo_v.style.border="1px solid #990000";
									campo_v.style.color="#990000";
									campo_v.focus();
									return;
									}
									for (i=0;i<4;i++) {
									num=partes[i];
									if (num>255 || num<0 || num.length==0 || isNaN(num)){
									alert('IP no valida \n Formato: 199.199.199.199');
									campo_v.style.border="1px solid #990000";
									campo_v.style.color="#990000";
									campo_v.focus();
									return;
									}
									}
					}

					break;


					case "E":
						 campo_v=document.getElementById(t_campo[i])
						 if (campo_v.value=='')
								  {
									  alert("Complete el campo: "+ t_aler[i]);
									  campo_v.focus();
									   return;
								  }
						if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(campo_v.value)){
							}
						else {
						alert("La dirección de email es incorrecta.");
						campo_v.select();
						campo_v.focus();
						return;
						}

			break


						}
					}
		  document.getElementById(idform).submit();
		 }



		 //funcion para anular botones
		 //onKeyPress="return(formato_campo(this,event,1))"
		function formato_campo(campo,e,t) {

			var aux = aux2 = '';
			var i = j = 0;

			if(t==1)
				var strCheck = '0123456789';
			if(t==2)
				var strCheck = 'AaBbCcDdEeFfGgHhIiJjKkLlÑñNnMmOoPpQqRrSsTtUuVvWwXxYyZzáÁéÉíÍóÓúÚ ';
			if(t==3)
				var strCheck = '0123456789-ext';
			if(t==4)
				var strCheck = '0123456789,.';
			if(t==5)
				var strCheck = '0123456789.';


			var whichCode = (window.Event) ? e.which : e.keyCode;
			if (whichCode == 13) return true; 						// Enter
			if (whichCode == 8) return true; 							// Enter
			//if (whichCode == 46) return true;						// Enter
			if (whichCode == 0) return true; 							// Tab
			key = String.fromCharCode(whichCode); 				// Consigue el valor del codigo de tecla...
			if (strCheck.indexOf(key) == -1) return false; 	// no es una tecla valida
			campo.value += aux2.charAt(i);

		}


		/*
		*Autor= Pedro Giacomtto
		*Funcion generica para los alert de permisos eliminar/modificar/reportes/consultar
		*/
		function acciones(acc,op,url,reg)
		{
			switch (acc)
			{
			  case 'supr':
			  {
					if (op=='t')
					{
						if(confirm("Esta Seguro de Eliminar el Registro:\n\n "+reg))
						{
						open(url,"_top");
						}
					}

				   if (op=='f')
					{
						alert("No Posee Permiso para realizar esta accion!")
					}

			  }
              break;
			}

		}



		/*
		*Autor= Pedro Giacomtto
		*Funcion generica para desavilitar/avilitar, Ver/no ver etc.. los campos
		*La variable opcional se utiliza segun sea el case de no necesitarce pasarla vacia ( '' )
		*/
		function interactuar(tipo,opcional,cambiar)
		 {

			t_cambiar = cambiar.split("|");
			e=t_cambiar.length;
			e_=e-1;
			for(i=0;i<=e_;i++)
			  {

			switch (tipo)
				  {
				case'visible':{

									document.getElementById(t_cambiar[i]).style.display="";
									document.getElementById(t_cambiar[i]).style.visibility="inherit";
									document.getElementById(t_cambiar[i]).focus();
								if(opcional!='')//funcion para cuando no se seleccione nada esconde los visibles
									{
										var campo=opcional; //opcional representa el id del campo para recuperar su valor y evaluar
									if(document.getElementById(campo).value=="")
									   {
										document.getElementById(t_cambiar[i]).style.display="none";
										document.getElementById(t_cambiar[i]).style.visibility="inherit";
									   }
									}
							  }
					  break;

				case 'esconder':
								 {
									document.getElementById(t_cambiar[i]).style.display="none";
									document.getElementById(t_cambiar[i]).style.visibility="inherit";

								 }
						break;

				case 'print':
								 {
									var texto=opcional;//convertimos opcional en el texto a imprimir
									document.getElementById(t_cambiar[i]).innerHTML=texto;

								 }
						break;

				  }
     }
}



//Funcion para contar caracteres q faltan
//onKeyDown="caracteres('campo a evaluar','id q muestra el Nº', maximo de caracteres,evento :envent)"
function caracteres(campo,poner,maxi,e)
{
	interactuar('visible','',poner)

 n = document.getElementById(campo).value.length;
 t=maxi;
	restan=(t-n);
	{
	restan_t=restan-1;
	if(restan_t=='-1'){
	 restan_t='0';}
	document.getElementById(poner).innerHTML=('restantes: '+ restan_t);
	}

if(restan==0)
 {

    var aux = aux2 = '';
	var i = j = 0;


    var strCheck = '';

    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13) return true; 						//habilita Enter
	if (whichCode == 8) return true; 						//habilita Borrar
	if (whichCode == 0) return true; 					    //habilita Tab
    key = String.fromCharCode(whichCode); 				// Consigue el valor del codigo de tecla...
    if (strCheck.indexOf(key) == -1) return false; 	// no es una tecla valida
	document.getElementById(campo).value += aux2.charAt(i);
   }


if (n > t)
            {
			alert ("Disculpa, la cantidad de carateres por mensaje es solo de " + t + ".");
			document.getElementById(campo).value = document.getElementById(campo).value.substring(0, t);
             }
  }

// funcion para hora actual
function time(){
if (!document.layers&&!document.all&&!document.getElementById)
return
var Digital=new Date()
var hours=Digital.getHours()
var minutes=Digital.getMinutes()
var seconds=Digital.getSeconds()
var dn="AM"
if (hours>12){
dn="PM"
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
//change font size here to your desire
myclock="<font size='1' face='verdana' >&nbsp;&nbsp;&nbsp;&nbsp;Hora: <b>"+hours+":"+minutes+":"
+seconds+" "+dn+"&nbsp;&nbsp;</font>"
if (document.layers){
document.layers.liveclock.document.write(myclock)
document.layers.liveclock.document.close()
}
else if (document.all)
liveclock.innerHTML=myclock
else if (document.getElementById)
document.getElementById("liveclock").innerHTML=myclock
setTimeout("time()",1000)
}

