//CONSTANTES
LETTERS = "áéíóúÁÉÍÓÚabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
LETRAS = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ";
LETRAS_AMADEUS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
DIGITS = "0123456789";
ZIP_VALID = DIGITS;
PHONE_VALID = DIGITS + "+- ()";
PASSPORT_VALID = "!\"#$%&'()*+,-./0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
PVP = DIGITS + ".,";
MAIL_VALID = LETTERS + DIGITS + ";._@-";
SELECTED = "Xx";
//INVALID_FOR_TEXT = DIGITS + "!·\\\"$%&/=?¿|@#`+*^[]{}´¨_<>:;";
INVALID_FOR_TEXT = "!·\\\"'$%&=?¿|@#`+*^[]{}´¨_<>;";
INVALID_FOR_URL = "!·\\\"'$%()¿|@#`+*^[]{}´¨<>;";
INVALID_FOR_MAIL = "!·\\\"'$%()¿|#`+*^[]{}´¨<>;";
INVALID_NAME = "!·\\\"'$%()¿|#`+*^[]{}´¨<>:áéíóúÁÉÍÓÚäëïöüÄËÏÖÜâêîôûÂÊÎÔÛ";
INVALID_DATE = LETRAS+"!·\\\"'$%()¿|#`+*^[]{}´¨<>:áéíóúÁÉÍÓÚäëïöüÄËÏÖÜâêîôûÂÊÎÔÛ";
INVALID_TIME = "&/€!·\\\"'$%()¿|#`+*^[]{}´¨<>;áéíóúÁÉÍÓÚäëïöüÄËÏÖÜâêîôûÂÊÎÔÛ ";
INVALID_AMADEUS= "áéíóúÁÉÍÓÚàèìòùÀÈÌÒÙäëïöüÄËÏÖÜâêîôûÂÊÎÔÛ`";
INVALID_NONE="";
INVALID_NUMBER = ":+-()" + LETRAS + INVALID_FOR_TEXT+"ºª€¬¡ç*/";
DATE_VALID=DIGITS + "/";
CIF_CODE = "1";
NIF_CODE = "2";

function getNextDate(date,days){
	if(date.substring(0,1) == "0"){
		day = parseInt (date.substring (1, 2),10);
	}else{
		day = parseInt (date.substring (0, 2),10);
	}
	if(date.substring(3,4) == "0"){
		month = parseInt (date.substring (4, 5),10) -1;
	}else{
		month = parseInt (date.substring (3, 5),10)-1;
	}
	year = parseInt (date.substring (6, 10),10);
	actualDate = new Date(year,month,day);
	millis = actualDate.getTime()+12*60*60*1000+days*24*60*60*1000;
	actualDate.setTime(millis);
	nday = new Number(actualDate.getDate());
	nmonth = new Number(actualDate.getMonth())+1;
	nyear = new Number(actualDate.getYear());
	if(nyear < 1000){
		nyear += 1900;
	}
	if(nday < 10){
		aux = "0"+nday.toString()+"/";
	}else{
		aux = nday.toString()+"/";
	}
	if(nmonth < 10){
		aux = aux + "0"+nmonth.toString()+"/";
	}else{
		aux = aux + nmonth.toString()+"/";
	}
	aux = aux+nyear.toString();
	return aux;
}

function getDays(date1,date2){
	if (!date2) { //Si no se manda el segundo parámetro tomamos el día actual
		actualDate1 = new Date();
		actualDate1 = new Date(actualDate1.getYear(), actualDate1.getMonth(), actualDate1.getDate());
		millis1 = actualDate1.getTime();
		date2 = date1;
	} else {
		if(date1.substring (0, 1) == "0"){
			day1 = parseInt (date1.substring (1, 2),10);
		}else{
			day1 = parseInt (date1.substring (0, 2),10);
		}
		if(date1.substring (3, 4) == "0"){
			month1 = parseInt (date1.substring (4, 5),10)-1;
		}else{
			month1 = parseInt (date1.substring (3, 5),10)-1;
		}
		year1 = parseInt (date1.substring (6, 10),10);
		actualDate1 = new Date(year1,month1,day1);
		millis1 = actualDate1.getTime();
	}
	if(date2.substring (0, 1) == "0"){
		day2 = parseInt (date2.substring (1, 2),10);
	}else{
		day2 = parseInt (date2.substring (0, 2),10);
	}
	if(date2.substring (3, 4) == "0"){
		month2 = parseInt (date2.substring (4, 5),10)-1;
	}else{
		month2 = parseInt (date2.substring (3, 5),10)-1;
	}
	year2 = parseInt (date2.substring (6, 10),10);
	actualDate2 = new Date(year2,month2,day2);
	millis2 = actualDate2.getTime();
	dif = millis2-millis1;
	days = dif/(24*60*60*1000);
	var resultado = ""+days;
	if(resultado.indexOf(".")!=-1){
		var aux = resultado.substring(resultado.indexOf(".")+1,resultado.indexOf(".")+2);
		if(parseInt(aux,10)>5){
			days = Math.ceil(days);
		}else{
			days = Math.floor(days);
		}
	}
	return days;
	//return Math.ceil(days);
}

function validateDate (str, desc, compulsory, canBeInTheFuture, mostrar, noFechaPasada)
{
	mensaje = "La fecha debe ser de la forma\ndd/mm/aaaa";

	if (compulsory && (!isFilled (str) || str=='dd/mm/aaaa'))
	{
		        if (mostrar)
			alert (desc + " es un campo obligatorio.");
			return false;
	}
	
	if (str.length > 0)
	{
		if (!validate (str, DATE_VALID))
		{
		        if (mostrar)
			alert (desc + " no es una fecha valida.\n"+mensaje);
			return false;
		}
		if((str.length < 6) || (str.length == 7) || (str.length == 9))
		{
			if (mostrar)
				alert (desc + " debe ser de la forma ddmmaa, ddmmaaaa, dd/mm/aa o dd/mm/aaaa.\n");
			return false;
		
		}
		if(str.length == 10){
			if(str.substring(2,3) == "/" && str.substring(5,6) == "/"){
				compactedDate = str.substring (0, 2) + str.substring (3, 5) + str.substring (6, 10);
			}else{
				if (mostrar) 
					alert (desc + " no es una fecha valida.\n"+mensaje);
				return false;
			}
		}else if(str.length == 8){
			if(str.substring(2,3) == "/" && str.substring(5,6) == "/"){
				compactedDate = str.substring (0, 2) + str.substring (3, 5) + "20"+ str.substring (6, 8);
			}else{
				if (str.substring(2,3) != "/" && str.substring(5,6) != "/"){
					compactedDate = str;
				}else {
					return false;
				}
			}
		}else if(str.length == 6){
			compactedDate = str.substring (0, 4) +"20"+ str.substring (4, 6);
		}
		if (!validate (compactedDate, DIGITS))
		{
		        if (mostrar)
			alert (desc + " no es una fecha valida.\n"+mensaje);
			return false;
		}
		if(compactedDate.substring (0, 1) == "0"){
			day = parseInt (compactedDate.substring (1, 2),10);
		}else{
			day = parseInt (compactedDate.substring (0, 2),10);
		}
		if(compactedDate.substring (2, 3) == "0"){
			month = parseInt (compactedDate.substring (3, 4),10);
		}else{
			month = parseInt (compactedDate.substring (2, 4),10);
		}
		year = parseInt (compactedDate.substring (4, 8),10);
		REGULAR_MONTHS = new Array (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
		LEAP_MONTHS = new Array (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
		curDate = new Date ();

		if((month < 1) || (month > 12)){
		        if (mostrar)
			alert("Mes no valido.\nDebe estar entre 1 y 12.");
			return false;
		}
		if (!canBeInTheFuture)
		{
			curYear = curDate.getYear();
			curMonth = curDate.getMonth () + 1;
			if (curYear < year || 
			    curYear == year && curMonth < month ||
			    curYear == year && curMonth == month  && curDate.getDate()<day)
			{
	        if (mostrar) alert (desc + " es posterior a la fecha actual.");
			return false;
			}
		}
		if(noFechaPasada){
			//Si es true (o existe) no hay que permitir que la fecha sea a pasado
			curYear = curDate.getYear();
			curMonth = curDate.getMonth () + 1;
			if ((curYear > year) ||
					(curYear == year && curMonth > month) ||
					(curYear == year && curMonth == month && curDate.getDate() > day)) {
				if (mostrar) alert (desc + " es anterior a la fecha actual.");
				return false;
			}		
		}

		if (isLeapYear (year))
		{
			if (day < 1 || day > LEAP_MONTHS[month-1])
			{
        		        if (mostrar)
				alert (desc + " no es una fecha válida. 1");
				return false;
			}
		}
		else
		{
			if (day < 1 || day > REGULAR_MONTHS[month-1])
			{
        		        if (mostrar)
				alert (desc + " no es una fecha válida. 2");
				return false;
			}
		}	
	}
	return true;
}

function parseDate(str){
 var compactedDate = str;
 if(str.length == 10){
  compactedDate = str;
 } else {
   var index = str.indexOf("/");
   if (index == -1) {
     if(str.length == 8) {
       if(str.substring(2,3) == "/"){
         compactedDate = str.substring (0, 6) + "20"+ str.substring (6, 8);
       } else {
         compactedDate = str.substring (0, 2)+"/"+str.substring (2, 4)+"/" + str.substring (4, 8);
       }
     } else if(str.length == 6){
       compactedDate = str.substring (0, 2)+"/" +str.substring (2, 4)+"/" +"20"+ str.substring (4, 6);
     }
   } else {	
     index = compactedDate.indexOf("/");
     var newFecha = compactedDate.substring(0,index)+"/";
     if (index == 1) {
       newFecha = "0"+newFecha;       
     }
     compactedDate = compactedDate.substring(index+1);
     index = compactedDate.indexOf("/");
     var saux = compactedDate.substring(0,index);
     compactedDate = compactedDate.substring(index+1);
     if (index == 1) {
       newFecha = newFecha+"0"+saux;       
     } else {
       newFecha = newFecha+saux;
     }
     if (compactedDate.length == 2) {
       compactedDate = newFecha + "/20" + compactedDate;
     } else {
       compactedDate = newFecha + "/" + compactedDate;
     }
   }
 }
 return compactedDate;
}

function isFilled (str)
{
	for (c = 0; c < str.length; c++)
	{
		if (str.charAt(c) != " ")
		{
			return true;
		}
	}
	return false;
}

function validate (str, valStr)
{
	for (c = 0; c < str.length; c++)
	{
		if (valStr.indexOf (str.charAt (c)) == -1)
		return false;
	}
	return true;
}

function isLeapYear (year)
{
	return ((((year%4)==0) && !((year%100)==0)) || (((year%4)==0) && ((year%400)==0)));
}

function validateNIF (nif, desc)
{
	numeros=nif.substring (0, nif.length-1);
	letra=nif.substring (nif.length-1).toUpperCase();
	if (!validate (numeros, DIGITS) || !validate (letra, LETTERS))
	{
		//alert (desc + " no es correcto");
		return false;
	}
	ctrlLetters = new Array ("T", "R", "W", "A", "G", "M", "Y", "F", "P", "D", "X", "B", "N", "J", "Z", "S", "Q", "V", "H", "L", "C", "K", "E","T");
	index = numeros - (parseInt (numeros/23,10)*23);
	if (ctrlLetters[index] != letra)
	{
		//alert (desc + " no es correcto");
		return false;
	}
	return true;
}

function validateCIF (cif, desc) {
	var letras = "ABCDEFGHPQS";
	var letras2 = "ABCDEFGHIJ";
	var numeros = "0123456789";
    
	// Comprobar la longitud
	if (cif.length != 9)
	{
		//alert (desc + " no tiene una longitud correcta");
		return false;
	}
	
	// Comprobar la primera letra
	if (letras.indexOf (cif.toUpperCase().charAt (0)) == -1)
	{
		//alert (desc + " no es correcto.");
		return false;
	}
	
	// Comprobar que el resto son numeros (salvo el ultimo)
	for (var n = 1; n < (cif.length - 1); n++)
	{
		if (numeros.indexOf (cif.charAt (n)) == -1)
		{
			//alert (desc + " no es correcto.");
			return false;
		}
	}    
	
	// Calcular los pesos
	var i1 = 2 * parseInt (cif.charAt (1),10);
	if (i1 > 9)
	{
		i1 = 1 + i1 % 10;
	}
	var i3 = 2 * parseInt (cif.charAt (3),10);
	if (i3 > 9)
	{
		i3 = 1 + i3 % 10;
	}
	var i5 = 2 * parseInt (cif.charAt (5),10);
	if (i5 > 9)
	{
		i5 = 1 + i5 % 10;
	}
	var i7 = 2 * parseInt (cif.charAt (7),10);
	if (i7 > 9)
	{
		i7 = 1 + i7 % 10;
	}    
	
	// Sumar cifras y quedarnos con la ultima
	var suma = i1 + parseInt (cif.charAt (2),10) +
	           i3 + parseInt (cif.charAt (4),10) +
	           i5 + parseInt (cif.charAt (6),10) +
	           i7;
	suma = suma.toString().charAt (suma.toString().length - 1);
	
	// Comprobar la letra o el digito de control
	var digito = 10 - suma;
	if (digito == 10)
	{
		digito = 0;
	}
	var letra = 10 - suma;
	if (letra == 0)
	{
		letra = 10;
	}
	var letraOk = letras2.toUpperCase().charAt (letra - 1);
	if ((cif.toUpperCase().charAt (8) == letraOk) || (cif.charAt (8) == digito))
	{
		return true;
	}
	
	//alert (desc + " no es correcto");
	return false;
}

function validateNIE (nie, desc)
{
		 letras = "XYZxyz";		 
		 car = nie.substring(0,1);
		 
		 // acepta solo los nie con caracter inicial validos
		 if(letras.indexOf(car)==-1) return false;
		 
		 // reemplaza caracter inicial con equivalente numerico
		 nie = nie.replace(/^[xX]/,'0');
		 nie = nie.replace(/^[yY]/,'1');
		 nie = nie.replace(/^[zZ]/,'2');		 		 		 
		 
		 //valida igual que NIF
		 return validateNIF(nie,desc);
}

function emailChecker(email){
 var index_of_at = email.indexOf("@");
 var index_of_last_dot = email.lastIndexOf(".");
 var extension = email.substring((index_of_last_dot+1)).length;
 var length = email.length;
 if ((index_of_at < 1) || (index_of_last_dot < index_of_at) || (index_of_last_dot > length - 3) || (index_of_last_dot +1 < length - extension)){
 	return false;
 }else{	
 	return true;
 }
}

function unvalidate (str, valStr)
{
	for (c = 0; c < str.length; c++)
	{
		if (valStr.indexOf (str.charAt (c)) != -1)
		{
			return false;
		}
	}
	return true;
}

function URLEncode(url) {
  return (URLEncode(url,"N"));
}

function URLEncode(url, todo) {
  if (url == null) {
    return(null);
  }
  var newUrl = "";
	var nocambia = "";
	var cambiar = "";
	var NO_URL = "!·\\\"$()?¿|#`+*^[]{}´¨_<>:;áéíóúÁÉÍÓÚäëïöüÄËÏÖÜâêîôûÂÊÎÔÛ \n\r";
	if (todo == "S") {
	  if (url.indexOf("http://") == 0) {
	    nocambia = "http://";
	    cambiar = url.substring(7);
	  } else {
            nocambia = "";
            cambiar = url.substring(0);
          }
          NO_URL = NO_URL+"&";
	} else {
	  if (url.indexOf("?") == -1) {
	    nocambia = url;
	    cambiar = "";
	  } else {
	    nocambia = url.substring(0,url.indexOf("?")+1);
	    cambiar = url.substring(url.indexOf("?")+1);
	  }
	}
	// Primera pasada para cambiar el % y el + que son casos especiales
	var index = 0;
	var caracter = "%";
	index = cambiar.indexOf(caracter);
	while (index != -1){
		cambiar = cambiar.substring(0,index)+"%25"+cambiar.substring(index+1);
		index = cambiar.indexOf(caracter,index+1);
	}
	caracter = "+";
	index = cambiar.indexOf(caracter);
	while (index != -1){
		cambiar = cambiar.substring(0,index)+"%2b"+cambiar.substring(index+1);
		index = cambiar.indexOf(caracter,index+1);
	}
	caracter = " ";
	index = cambiar.indexOf(caracter);
	while (index != -1){
		cambiar = cambiar.substring(0,index)+"%20"+cambiar.substring(index+1);
		index = cambiar.indexOf(caracter,index+1);
	}
	for (i=0;i<cambiar.length;i++){
		if (NO_URL.indexOf(cambiar.charAt(i))!= -1){
			cambiar = cambiar.substring(0,cambiar.indexOf(cambiar.charAt(i)))+escape(cambiar.charAt(i))+cambiar.substring(cambiar.indexOf(cambiar.charAt(i))+1);
		}
	}
	newUrl = nocambia+cambiar;
	return newUrl;
}
function pop(obj,ancho,alto,parametros){
if(!parametros)parametros='scrollbars = yes';
ventana=window.open(obj.href,obj.target,'width='+ancho+',height='+alto+','+parametros);
ventana.focus();}
function msgShow(msgId,message){
  var msgDiv = document.getElementById(msgId);
	if(msgDiv){
		msgDiv.style.visibility='visible';
		msgDiv.style.height='auto';
		msgDiv.style.display='block';
		if(message!=null){
			msgDiv.innerHTML = message;
		}
	}
	window.scrollTo(0,0);
}
	
function msgHide(msgId){
	var msgDiv = document.getElementById(msgId);
	if(msgDiv){
		msgDiv.style.visibility='hidden';
		msgDiv.style.height='0';
		msgDiv.style.display='none';
	}
	return true;
}

function calcular_edad_fechas(fechaCompara,fecha){
	var hoy = new Date();
	var array_fechaC = fechaCompara.split("/");
	if (array_fechaC.length==3) 
	{
		var fano = parseInt(array_fechaC[2],10);
		var fmes = parseInt(array_fechaC[1],10);
		var fdia = parseInt(array_fechaC[0],10);
		if (isNaN(fano) || isNaN(fmes) || isNaN(fdia)) 
		{
			hoy = new Date();
		}
		else 
		{
			if (fano<=99) fano +=1900;
			hoy.setFullYear(fano);
			hoy.setDate(fdia);
			hoy.setMonth(fmes-1);
		}
	} 
	var array_fecha = fecha.split("/");
	if (array_fecha.length!=3) return "";
	var ano;
	ano = parseInt(array_fecha[2],10);
  if (isNaN(ano)) return "";
	var mes;
	mes = parseInt(array_fecha[1],10);
	if (isNaN(mes)) return "";
	var dia;
  dia = parseInt(array_fecha[0],10);
	if (isNaN(dia)) return "";
	if (ano<=99) ano +=1900;
	edad=hoy.getFullYear()- ano - 1; //-1 porque no se si ha cumplido años ya este año				
	if (hoy.getMonth() + 1 - mes < 0){ //+ 1 porque los meses empiezan en 0
		//No los ha cumplido aún
		return edad;
	}
	if (hoy.getMonth() + 1 - mes > 0){
  	//Sí que los ha cumplido
		return edad+1;
	}
	if (hoy.getMonth() + 1 - mes == 0){
		//Los cumple este mes
	  if (hoy.getUTCDate() - dia >= 0){
			//Ya los ha cumplido
		  return edad + 1;
		}else{
			return edad;
		}
	}
	return edad;
}	

function calcular_edad(fecha){
	var hoy = new Date();
	var array_fecha = fecha.split("/");
	if (array_fecha.length!=3) return "";
	var ano;
	ano = parseInt(array_fecha[2],10);
  if (isNaN(ano)) return "";
	var mes;
	mes = parseInt(array_fecha[1],10);
	if (isNaN(mes)) return "";
	var dia;
  dia = parseInt(array_fecha[0],10);
	if (isNaN(dia)) return "";
	if (ano<=99) ano +=1900;
	edad=hoy.getFullYear()- ano - 1; //-1 porque no se si ha cumplido años ya este año				
	if (hoy.getMonth() + 1 - mes < 0){ //+ 1 porque los meses empiezan en 0
		//No los ha cumplido aún
		return edad;
	}
	if (hoy.getMonth() + 1 - mes > 0){
  	//Sí que los ha cumplido
		return edad+1;
	}
	if (hoy.getMonth() + 1 - mes == 0){
		//Los cumple este mes
	  if (hoy.getUTCDate() - dia >= 0){
			//Ya los ha cumplido
		  return edad + 1;
		}else{
			return edad;
		}
	}
	return edad;
}
