// JavaScript Document
//Libreria de validacion y funciones varias de formularios y ventanas V.0.3   
//Avelino Linares avelino.linares@gmail.com
//Modificada 11-agosto-2006  2:00

/*
	*****V.0.3*********
	-Función de validate con múltiples lenguajes
	-Agregada la función para presentar los numeros en formato de moneda con 2 decimales con o sin signo
	-Agregada la función para ocultar y mostrar elementos
	-Arreglado el problema de la validación de textos con acentos en letras mayúsculas
	-Agregada función para agregar celdas
*/

function vacio(formulario,campo,nombreCampo){
/*
***********************************************************************
*Para verificar si el campo definido por formulario y campo esta vacio*
***********************************************************************
*/
	if(document.forms[formulario].elements[campo].value=="" || document.forms[formulario].elements[campo].value==" " || document.forms[formulario].elements[campo].value=="   "){
		falla="El campo "+ nombreCampo +" es requerido";	
	}else{
		falla="ok";	
	}

	return falla;
}

function validate(formulario,campo,tipo,requerido,nombre,lang ){
		if(lang=="eng"){
			elCampo="The field ";	
			required=" is required.";
			onlyLetters=" only allow letters.";
			numberLetters=" only allow number and letters.";
			onlyNumber=" only allow numbers.";
			digit=" only allow numerical characters";
			email=" have and invalid email.";
			dash=" only allow numbers and '-'";
			Select="Please select a value in ";
			phone=" only alow numbers '-','(' and ')' ";
		}
		if(lang=="esp"){
			elCampo="El campo ";	
			required=" es requerido.";
			onlyLetters=" solo admite letras.";
			numberLetters=" solo adminte numeros y letras.";
			onlyNumber=" solo adminte numeros.";
			digit=" solo admite caracteres numéricos";
			email=" tiene un email inválido.";
			dash=" solo admite numeros y '-'";
			Select="Por favor seleccione un valor en ";
			phone=" solo admite '-','(' y ')' ";
		}
	
		//alert(document.forms[formulario].elements[campo].name);
		Error="ok";
		if( requerido && vacio(formulario,campo) != "ok"){
			Error=elCampo + nombre + required;
		}else{
		  if(document.forms[formulario].elements[campo].value!=""){
			 // alert(tipo);	
			switch(tipo){
			
				case "SoloTexto":
										//Comprobando que solo acepte caracteres alfabeticos
										var er= /^([a-z]|[A-Z]|á|é|í|ó|ú|ń|ü|Á|É|Í|Ó|Ú|Ń|\s|)+$/;
										if(!er.test(document.forms[formulario].elements[campo].value)){
											Error=elCampo + nombre + onlyLetters;
										}
				break;
				
				case "Alfanum":						
										var er= /^([a-z]|[A-Z]|á|é|í|ó|ú|ń|ü|Á|É|Í|Ó|Ú|Ń|\s|[0-9])+$/;
										
										if(!er.test(document.forms[formulario].elements[campo].value)){
											Error=elCampo + nombre + numberLetters;
										}
				break;

				case "Signo":						
										var er= /^([a-z]|[A-Z]|á|é|í|ó|ú|ń|ü|Á|É|Í|Ó|Ú|Ń|\s|\.|\,|[0-9])+$/;
										
										if(!er.test(document.forms[formulario].elements[campo].value)){
											Error=elCampo + nombre + numberLetters;
										}
				break;
				
				
				case "Number":						
										if(isNaN(document.forms[formulario].elements[campo].value)){
											Error=elCampo + nombre + onlyNumber;
										}
				break;
				

				case "Digito":						
										var er= /^([0-9])+$/;
										
										if(!er.test(document.forms[formulario].elements[campo].value)){
											Error=elCampo + nombre + digit;
										}
				break;
				
				

				case "Email":						
										var er = /^(.+\@.+\..+)$/;
										
										if(!er.test(document.forms[formulario].elements[campo].value)){
											Error=elCampo + nombre + email ;
										}
				break;
				
				
			
				case "Guion":						
										var er=/^(\-|[0-9])+$/;
										
										if(!er.test(document.forms[formulario].elements[campo].value)){
											Error=elCampo + nombre + dash;
										}
				break;
				
				case "select":						
										//Para validar que un select no quede con su valor default     
										if(document.forms[formulario].elements[campo].options[document.forms[formulario].elements[campo].selectedIndex].value=="Default" && requerido){
											Error=Select+elCampo.toLowerCase()+nombre;
										}
				break;
				case "Telefono":						
										//Para validar telefonos 
										var er=/^(\-|[0-9]|\+|\s|\(|\))+$/;
										
										if(!er.test(document.forms[formulario].elements[campo].value)){
											Error=elCampo+ nombre +phone;
										}
				break;
				
				case "Archivo":		
										var er= /^([a-z]|[A-Z]|\.|\s|\_||[0-9])+$/;
										
										if(!er.test(document.forms[formulario].elements[campo].value)){
											Error="El nombre del archivo "+nombre+" es inválido";
										}

				break;
				
				case "Todo":						

				break;
				
				
				default:
							alert("No se han definido validaciones"+document.forms[formulario].elements[campo].name);
				
				
		}
	  }
	}

return Error;
}


function tamano(formulario,campo,size){
	error=vacio(formulario,campo);
	if(error=="ok"){
		if(document.forms[formulario].elements[campo].value.length > size){
			error="El campo " + document.forms[formulario].elements[campo].name +" solo puede contener "+ size +" caracteres";	
		}
	
	}
	return error;
	
}

function canonica(fecha,destino){
/* Valida la fecha y la convierte a canonica 
	aaaa-mm-dd Formati usado por MySql*/
			var cano=new Array;
			var flag=new Boolean;
			flag=true;
			alerta="Fecha Inválida";
			//alert(fecha);
			cano = fecha.split("-"); 
				if(cano.length>=4){
					alerta+="\n-Demasiados Argumentos";
					flag=false;
				}else{
					dia=cano[0];
					mes=cano[1];
					year=cano[2];
					//dia=parseInt(dia);
					//mes=parseInt(mes);
					//year=parseInt(year);
					
					if(mes>12){
						alerta+="\n-Mes inválido";
						flag=false;
					}
					
					if(mes==1 || mes==3 || mes==5 || mes==7 || mes==8 || mes==10 || mes==12){
						if(dia>31){
						alerta+="\n-Dia inválido \n";
							flag=false;
						}	
					}
					if(mes==4 || mes==6 || mes==9 || mes==11){
						if(dia > 30){
						alerta +="\n-Dia inválido \n";
							flag=false;
						}	
					}
					
			
			bici=year/4;
			bic=String(bici);
	
			var esto=new Array;
			esto=bic.split(".");
					
			if(esto.length<=1){
				if(mes==2){
					if(dia>29){
						alerta+="\n-Dia inválido \n";
						flag=false;
				
					}
				}
			
			}else{
				if(mes==2){
					if(dia>28){
						alerta+="\n-Dia inválido \n";
						flag=false;

					}
				}
			}
					if(year<1930){
						alerta+="\n-Por favor use ańos de 4 digitos \n";
						flag=false;
					}
				}
		
		var meses=new Array();
		
		meses[1]="Jan";		
		meses[2]="Feb";		
		meses[3]="Mar";		
		meses[4]="Apr";	
		meses[5]="May";	
		meses[6]="Jun";	
		meses[7]="Jul";	
		meses[8]="Aug";	
		meses[9]="Sep";	
		meses[10]="Oct";	
		meses[11]="Nov";	
		meses[12]="Dec";	
		
		
		if(flag && !isNaN(year) && !isNaN(mes) && !isNaN(dia)){
				destino.value=year+"-"+meses[mes]+"-"+dia;
				alerta="ok";
				//document.anios.anho.value=year;
		}else{
				destino.value="Fecha Inválida";
		}
			
		//alert(document.f1.FechaCanonica.value);
		flag=false;
		return alerta;

}


function textCounter(campo, contador, limite) {
/*
	Cuenta la longitud de text area y la limita
*/	
if (campo.value.length > limite){ // if too long...trim it!
	campo.value = campo.value.substring(0,limite);

	}else{
		if (limite - campo.value.length == 0){
			document.getElementById(contador).style.color="#FFB442";	
			document.getElementById(contador).innerHTML="ha llegado al m&aacute;ximo de caracteres";
		}else{
			document.getElementById(contador).style.color="#FFB442";	
			document.getElementById(contador).innerHTML = limite - campo.value.length +" caracteres restantes."; 
		}
	}
}

function mostrarErrores(errores,formulario){
	//	alert("comienza mostrar errores");
	cuentaErrores=0;  //Contador de todos los errores
	alerta="Se han encontrado los siguientes errores: \n";
	for(i=0;i<=errores.length-1;i++){
		if(errores[i]!="ok"){
			cuentaErrores++;
			alerta+="-"+errores[i]+"\n";
//			alert(alerta);
		
		}					
	}

	 if(cuentaErrores==0){
		//alert(formulario.name);
		if(formulario){
			return true;
		}else{
			return true;	
		}
	}else{
		alert(alerta);	
		return false;
	}
}

function convertirFecha(fecha){
	var date=new Array();
	date=fecha.split("-");
	document.frm.fecha.value=date[2]+"-"+date[1]+"-"+date[0];
}


function abrirVentana(url,title,width,height){

  var left = (screen.width/2) - width/2;
  var top = (screen.height/2) - height/2;

  var styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbar=no,resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+',top='+top+',screenX='+left+',screenY='+top;

  window.open(url,title, styleStr);


}
	
function fondoUno(src,color_entrada) { 
    src.style.background=color_entrada;
	src.style.cursor="pointer";

} 
function fondoDos(src,color_default) { 
    src.style.background=color_default;
	src.style.cursor="default";
}
function dolar(num,symbol) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
		cents = Math.floor((num*100+0.5)%100); 
		num = Math.floor(num).toString();
		if(cents < 10) cents = "0" + cents; 

		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
				num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3)); 
		}
		if(symbol){
			return ('$'+num + '.' + cents);
		}else{
			return (num + '.' + cents); 
		}
}
function capas(actuales,clase1,destinos,clase2){
	//actuales y destinos tienen que ser arreglos	
//	alert(actuales.length);
	for(i=0;i<=actuales.length-1;i++){
		document.getElementById(actuales[i]).className=clase1;		
//		alert(document.getElementById(actuales[0]).className);
	}
	
	for(i=0;i<=destinos.length-1;i++){
		document.getElementById(destinos[i]).className=clase2;		
	}
	

}

function capa(id,clase){
	document.getElementById(id).className=clase;		
}

function getHTTPObject() {
	
	  var xmlhttp;
	
	  /*@cc_on
	
	  @if (@_jscript_version >= 5)
	
		try {
	
		  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	
		} catch (e) {
	
		  try {
	
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	
		  } catch (E) {
	
			xmlhttp = false;
	
		  }
	
		}
	
	  @else
	
	  xmlhttp = false;
	
	  @end @*/
	
	  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
	
		try {
	
		  xmlhttp = new XMLHttpRequest();
	
		} catch (e) {
	
		  xmlhttp = false;
	
		}
	
	  }
	
	  return xmlhttp;
	
	}
							
							
var http = getHTTPObject();
// We create the HTTP Object
