//Valida el teléfono para que sólo contenga 9 números
function FiltrarTLF(tlf)
{
	var i, x, num, car, tlfOK;
	tlfOK = '';
	num = new Array ('0','1','2','3','4','5','6','7','8','9');
	
	for (i=0;i<=tlf.length;i++)
	{
		for (x=0;x<=9;x++)
		{
			car = tlf.charAt(i);
			if (car == num[x])
			{
				tlfOK = tlfOK + car;
			}
		}
	}
	
	return tlfOK;
}

function ColocarDatosPob(valores) {

	var datos = valores;
	miArray = datos.split("||");
		
if (miArray[0] == 'R')
		{
	    document.forms[0].RCGRPO.value=miArray[1];
	    document.forms[0].RCGRDT.value=miArray[2];
		}
else
		{
	    document.forms[0].RCGDPO.value=miArray[1];
	    document.forms[0].RCGDDT.value=miArray[2];
		}
}


// Pop-up de consulta de Poblaciones
function Poblaciones(GrdTip){

	var PobCod;
	var PobNom;
	var PobPai;
	switch (GrdTip)
{ 
	case 'R': 	
			PobNom = document.forms[0].RCGRPO.value;
			PobCod = document.forms[0].RCGRDT.value;
			PobPai = document.forms[0].RCGRPP.value;
			break;
	case 'D':
		 	PobNom = document.forms[0].RCGDPO.value;
			PobCod = document.forms[0].RCGDDT.value;
			PobPai = document.forms[0].RCGDPP.value;
			break;
}

// Si no mete 3 caracteres mínimo en el campo C.P. o en el campo Población no 
// se le permite buscar una Población.
	if ((PobCod.length > 2) || (PobNom.length > 2))
	{
		var PobUrl = "PobConsulta.asp?GrdTip=" + GrdTip + "&PobPai="  + PobPai + "&PobCod="  + PobCod + "&PobNom="  + PobNom;;
		window.open(PobUrl,"Poblaciones","height=275,width=525,status=no,toolbar=no,menubar=no,location=no");
	}
	else
	{
		alert('Debe introducir al menos 3 caracteres en el C.P. o en la Población');
	}
}

function ValidaForm () {

		if(
			checkField( document.forms[0].RCGCBU, isNumber, true) &&
	    	checkField( document.forms[0].RCGCKG, isNumber, true) &&
	    	checkField( document.forms[0].RCGRTF, isNumber, true) &&
	    	checkField( document.forms[0].RCGDTF, isNumber, true) &&
      		checkField( document.forms[0].RCGREM, isEmail, true) &&
        	checkField( document.forms[0].RCGDPO, isDescription, true))
        	return true;
		else
	    	return false;
}

function PonFormatoHora(Field){
	var Campo;
	var hora;
	var minutos;
	var dospuntos;
	var cuentadospuntos;
	var TCampo;
	var i;
	var horaOk = true;

	dospuntos = false;
	cuentadospuntos = 0;	
	
	Campo = Field.value;
	if (Campo != "")
	{
// Busca los 2 puntos en la cadena
		for (i=0;i<Campo.length;i++)
		{
			if (Campo.substring(i, i+1) == ":")
			{
// Busca si hay más de 1 ":"
				cuentadospuntos = cuentadospuntos + 1;
				dospuntos = true;
			}
			else
			{
// Descarta los espacios en blanco y los signos negativos para el campo hora
				if ((Campo.substring(i, i+1) == "-") || (Campo.substring(i, i+1) == " "))
				{
					horaOk = false;
				}
			}
		}
//			Si el campo de la hora tiene los dos puntos ":" ya metidos
			if (dospuntos)
			{
//				Si sólo se han introducido los dos puntos ":" una vez
				if (cuentadospuntos == 1)
				{
//					Divide el campo para separar las horas y los minutos y chekearlos
					TCampo = Campo.split(":");
					//Pone formato hora de 2 dígitos
					var ThoraOk = false;
					var TminutosOk = false;
					switch (TCampo[0].length){
//								Valida q sea un número el dato introducido								
						case 1: if ((TCampo[0] >= 0) && (TCampo[0] <= 9))
								{
									hora = "0" + TCampo[0];	
									ThoraOk = true;
								}
								else
									ThoraOk = false;
									
								break;
						case 2: if (TCampo[0] <= 23)
								{
									hora = TCampo[0];
									ThoraOk = true;
								}
								else
									ThoraOk = false;
								break;
						default : ThoraOk = false;
					}
		
					//Pone formato minuto de 2 dígitos
					switch (TCampo[1].length){
						case 1: 
								if ((TCampo[1] >= 0) && (TCampo[1] <= 9))
								{
									minutos = "0" + TCampo[1];
									TminutosOk = true;
								}
								else
									TminutosOk = false;
									
								break;
						case 2: if (TCampo[1] <= 59)
								{
									minutos = TCampo[1]; 
									TminutosOk = true;
								}
								else
									TminutosOk = false;
									
								break;
						default: TminutosOk = false;
					}
					// Si el conjunto de las horas y los minutos es correcto ya tenemos OK la hora.
					if ((ThoraOk) && (TminutosOk))
						horaOk = true;
					else
						horaOk = false;
				}
				// Si tiene más de 1 ":" en la hora
				else
				{
					horaOk = false;
				}
			}
			// si no tiene los ":"
			else
			{
				switch (Campo.length){
				case 1: if ((Campo >= 0) && (Campo <= 9)) 
						{
							hora = "0" + Campo;
							minutos ="00"; // Ejm: 9 --> 09:00
							horaOk = true;
						}
						else
							horaOk = false;

						break;
				case 2:	if ((Campo >= 0) && (Campo <= 23)) 	// Ejm: 22 --> 22:00
						{	
							hora = Campo
							minutos = "00";
							horaOk = true;
						}				
						else
						{
							if ((Campo >= 24) && (Campo <=99))
								if (Campo > 23)
								{
									hora = "0" + Campo.substring(0,1);
									if (Campo.substring(1,2) > 5)
										minutos = "0" + Campo.substring(1,2); // Ejm: 25 --> 02:50
									else
										minutos = Campo.substring(1,2) + "0";
									horaOk = true;	// Ejm: 28 --> 02:08
								}
							else
								horaOk = false;
						}
						
						break;
				case 3: if ((Campo.substring(0,2) >= 0) && (Campo.substring(0,2) <= 23))  
						{
							hora = Campo.substring(0,2);
							if (Campo.charAt(2) <= 5)
								minutos = Campo.charAt(2) + "0";	// Ejm: 213 --> 21:30
							else
								minutos = "0" + Campo.charAt(2);
							horaOk = true;			// Ejm: 217 --> 21:07
						}
						else
							horaOk = false;
						
						break;
				case 4: hora = Campo.substring(0,2);			// Ejm: 2158 --> 21:58
						minutos = Campo.substring(2,4);
						horaOk = false;
						if ((hora >= 0) && (hora <= 23))
							if ((minutos >= 0) && (minutos <=59))
								horaOk = true;
						
						break;
				default: horaOk = false;
			}			
		}
		if (horaOk)
		{
			Campo = hora + ":" + minutos;
			Field.value = Campo;
			return (true);
		}
		else
		{
			alert ("La hora no es válida, introduzca un formato para este campo de tipo HH:MM."); // Ejm: 4365 --> no
			Field.focus();
			return(false);
		}
	}
	Campo = "";
	Field.value = Campo;
	return(true);

}

function ValidaHoras()
{
	var valor;
	valor = false;
	if (PonFormatoHora(document.forms[0].RCG1HMI))
		if (PonFormatoHora(document.forms[0].RCG1HMF))
			if (PonFormatoHora(document.forms[0].RCG2HMI))
				if(PonFormatoHora(document.forms[0].RCG2HMF)) 
					valor = true;

	return(valor);
				
}

function ValidaRangoHoras()
{
	var valor = true;
	var ConstHoraIni = 8;
	var ConstHoraFin = 17;
	var ConstMinFin = 1;
	var HoraIni = new Array();
	var HoraFin = new Array();
	
	HoraIni = document.forms[0].RCG1HMI.value.split(":");
	HoraFin = document.forms[0].RCG2HMF.value.split(":");
	
	if (HoraIni == '')
		HoraIni = document.forms[0].RCG2HMI.value.split(":");	
	if (HoraFin == '')
		HoraFin = document.forms[0].RCG1HMF.value.split(":");
	
	if (HoraIni[0] < ConstHoraIni)
		valor = false;
		
	if (HoraFin[0] > ConstHoraFin) 
		valor = false;

	if ((HoraFin[0] >= ConstHoraFin) && (HoraFin[1] >= ConstMinFin))
		valor = false;

	return (valor);
		
}

function ValidaContenido()
{
	var contador = 0;
	var errorArray = new Array();    // Array para la descripción del error
	var errorCampo = new Array();   // Array para los campos con error
    var DHM;
    var AHM;
    var DHT;
    var AHT;

	
    	if(document.forms[0].RCGRNO.value=="")
		{
			alert("El nombre del remitente es obligatorio.");
			document.forms[0].RCGRNO.focus();
			return (false);
		}

	    if(document.forms[0].RCGRDO.value=="")
		{
			alert("El domicilio del remitente es obligatorio.");
			document.forms[0].RCGRDO.focus();
			return (false);
	    }
	
		if((document.forms[0].RCGRPO.value.length >= 1) && (document.forms[0].RCGRPO.value.length < 3))
			{
			alert("Introduzca al menos 3 caracteres para la población.");
			document.forms[0].RCGRPO.focus();
			return (false);
	        }
	
	    if(document.forms[0].RCGRPO.value=="" && document.forms[0].RCGRDT.value=="")
		{
			alert("La población o el C.P. del remitente son obligatorios.");
			document.forms[0].RCGRPO.focus();
			return (false);
	    }
	
	    if(document.forms[0].Fecha.value=="")
		{
			alert("La fecha de recogida es obligatoria.");
			document.forms[0].Fecha.focus();
			return (false);
		}
		
		if((document.forms[0].RCGDPO.value.length >= 1) && (document.forms[0].RCGDPO.value.length < 3))
		{
			alert("Introduzca al menos 3 caracteres para la población.");
			document.forms[0].RCGDPO.focus();
			return (false);
        }

        if(document.forms[0].RCGRDT.value!="")
            if(!(document.forms[0].RCGRDT.value>"00999" && document.forms[0].RCGRDT.value<"53000"))
			{
				alert("El C.P. de remitente está fuera de rango.");
				document.forms[0].RCGRDT.focus();
				return (false);
	        }

        if(document.forms[0].RCGDDT.value!="")
            if(!(document.forms[0].RCGDDT.value>"00999" && document.forms[0].RCGDDT.value<"53000"))
			{
				alert("El C.P. del destinatario está fuera de rango.");
				document.forms[0].RCGDDT.focus();
				return (false);
            }
            
	    if((document.forms[0].RCGRTF.value == "") || ((eval(document.forms[0].RCGRTF.value) == 0)))
		{
			alert("El teléfono de contacto del remitente es obligatorio.");
			document.forms[0].RCGRTF.focus();
			return (false);
	    }  
	    
	    if(document.forms[0].RCGRPC.value == "")
		{
			alert("La persona de contacto del remitente es obligatorio.");
			document.forms[0].RCGRPC.focus();
			return (false);
	    } 	              

        DHM=(document.forms[0].RCG1HMI.value=="00:00"?"":document.forms[0].RCG1HMI.value);
        AHM=(document.forms[0].RCG1HMF.value=="00:00"?"":document.forms[0].RCG1HMF.value);
        DHT=(document.forms[0].RCG2HMI.value=="00:00"?"":document.forms[0].RCG2HMI.value);
        AHT=(document.forms[0].RCG2HMF.value=="00:00"?"":document.forms[0].RCG2HMF.value);

		if (((DHM != "") && (AHM == "")) || ((DHT != "") && (AHT == "")))
		{
			alert("Si introduce una hora inicio de recogida, debe introducir una hora fin para la misma.");
			document.forms[0].RCG1HMF.focus();
			return (false);
		}
		else
		if (((DHM == "") && (AHM != "")) || ((DHT == "") && (AHT != "")))
		{
			alert("Si introduce una hora fin de recogida, debe introducir una hora inicio para la misma.");
			document.forms[0].RCG1HMI.focus();
			return (false);
		}
		
        if(AHT!="")
            if(!(AHT>DHM && AHT>AHM && AHT>DHT))
			{
				alert("La última hora de recogida debe ser posterior a todas ellas.");
				document.forms[0].RCG2HMF.focus();
				return(false);
            }

        if(DHT!="")
            if(!(DHT>DHM && DHT>AHM))
			{
				alert("La hora de la tarde debe ser posterior a las de la mañana.");
				document.forms[0].RCG2HMI.focus();
				return (false);
            }

        if(AHM!="")
            if(!(AHM>DHM))
			{
				alert("La última hora de la mañana debe ser posterior a la primera.");
				document.forms[0].RCG1HMF.focus();
				return(false);
            }
            
	return (true);
}

function PonPobRem(){
        var aux;
        aux=document.forms[0].lstPobRem.value.split('\t');
        document.forms[0].RCGRPP.value=aux[0];
        document.forms[0].RCGRDT.value=aux[1];
        document.forms[0].RCGRPO.value=aux[2];
    } 
    
function PonPobDes(){
        var aux;
        aux=document.forms[0].lstPobDes.value.split('\t');
        document.forms[0].RCGDPP.value=aux[0];
        document.forms[0].RCGDDT.value=aux[1];
        document.forms[0].RCGDPO.value=aux[2];
    }   
//-----------------------------------------------------------------------------------------------

function igualaPOBCP(poblacion, cp, tipo)
{
	var miArray;
	switch (tipo)
	{
		case "R":
			miArray = document.forms[0].sPobCpoR.value.split('|');
			document.forms[0].RCGRDT.value = miArray[0];
			document.forms[0].RCGRPO.value = miArray[1];
			break;
		case "D":
			miArray = document.forms[0].sPobCpoD.value.split('|');
			document.forms[0].RCGDDT.value = miArray[0];
			document.forms[0].RCGDPO.value = miArray[1];
			break;
	}
}

function modoVer()
{
	document.getElementById('btnBuscarRem').style.visibility  = 'hidden';
	document.getElementById('btnBuscarDes').style.visibility  = 'hidden';
	document.getElementById('btnBuscarPobR').style.visibility = 'hidden';
	document.getElementById('btnBuscarPobD').style.visibility = 'hidden';
}


// Esta función se valida en el caso que haya un recogida:
// solicitada por el ORDENANTE
// Pagada por el REMITENTE (ya que en este caso el cliente es un usuario sin cuenta)
// Se necesita saber al menos la Población y el Código Postal de destino para poder valorar y cargar esa recogida al remitente
function ValidaTasacion() 
{
	if (document.forms[0].RCGCBU.value == '') 
		{
		alert('Debe introducir los Bultos a recoger.')
		document.forms[0].RCGCBU.focus();
		return (false);
		}
	else
		{
		if (document.forms[0].RCGCKG.value == '') 
			{
			alert('Debe introducir los Kilos aproximados a recoger.')
			document.forms[0].RCGCKG.focus();
			return (false);
			}
		else
			{
			if (document.forms[0].RCGDPO.value == '') 
				{
				alert('Debe introducir la Poblacion de Entrega.')
				document.forms[0].RCGDPO.focus();
				return (false);
				}
			else
				{
				if (document.forms[0].RCGDDT.value == '') 
					{
					alert('Debe introducir el Codigo Postal de Entrega.')
					document.forms[0].RCGDDT.focus();
					return (false);
					}
				else
					{
					return (true)
					}
				}
			}	
		}				
}
