// -------------------------------------------------------- //
// -------------------------------------------------------- //
//     Codigo Javascript para el control del Formulario     //
// -------------------------------------------------------- //
// -------------------------------------------------------- //


//-------------------------------------------------------------------------------
// Se llama cuando se pulsa el check de 2º solicitante

function enviar()
{
	var F = document.prestamo;
	var sMensajeERROR = '';
	var errores = 0;

	// Chequeos campos Datos Personales
	
	if (trim(F.nombre.value) == '') {
		sMensajeERROR += '\n  > Nombre del solicitante';
		errores += 1;
	}
	if (trim(F.apellido1.value) == '') {
		sMensajeERROR += '\n  > Primer apellido del solicitante';
		errores += 1;
	}
	if (trim(F.apellido2.value) == '') {
		sMensajeERROR += '\n  > Segundo apellido del solicitante';
		errores += 1;
	}
	if (F.estado_civil.selectedIndex == 0) {
		sMensajeERROR += '\n  > Estado civil del solicitante';
		errores += 1
	}
	if (trim(F.fecha_nac.value) == '') {
		sMensajeERROR += '\n  > Fecha de nacimiento del solicitante';
		errores += 1;
	}
	if (trim(F.domicilio.value) == '') {
		sMensajeERROR += '\n  > Domicilio del solicitante';
		errores += 1;
	}
	if (trim(F.cp.value) == '') {
		sMensajeERROR += '\n  > Codigo Postal del solicitante';
		errores += 1;
	}
	if (trim(F.localidad.value) == '') {
		sMensajeERROR += '\n  > Localidad del solicitante';
		errores += 1;
	}
	if (F.provincia.selectedIndex == 0) {
		sMensajeERROR += '\n  > Provincia del solicitante';
		errores += 1;
	}
	if (trim(F.telefono.value) == '') {
		sMensajeERROR += '\n  > Teléfono del solicitante';
		errores += 1;
	}
	if (trim(F.movil.value) == '') {
		sMensajeERROR += '\n  > Telefono movil del solicitante';
		errores += 1;
	}
	if (trim(F.nif.value) == '') {
		sMensajeERROR += '\n  > NIF del solicitante';
		errores += 1;
	}
	if (trim(F.personas_cargo.value) == '') {
		sMensajeERROR += '\n  > Personas a cargo del solicitante';
		errores += 1;
	}
	if (trim(F.email.value) == '') {
		sMensajeERROR += '\n  > Email del solicitante';
		errores += 1;
	}
	if (trim(F.gastos.value) == '') {
		sMensajeERROR += '\n  > Gastos del solicitante';
		errores += 1;
	}



	// Chequeos campos Datos Profesionales
	
	if (trim(F.empresa.value) == '') {
		sMensajeERROR += '\n  > Empresa del solicitante';
		errores += 1;
	}
	if (trim(F.domicilio_prof.value) == '') {
		sMensajeERROR += '\n  > Domicilio de la empresa del solicitante';
		errores += 1;
	}
	if (trim(F.cp_prof.value) == '') {
		sMensajeERROR += '\n  > Codigo Postal de la empresa del solicitante';
		errores += 1;
	}
	if (trim(F.localidad_prof.value) == '') {
		sMensajeERROR += '\n  > Localidad de la empresa del solicitante';
		errores += 1
	}
	if (F.provincia_prof.selectedIndex == 0) {
		sMensajeERROR += '\n  > Provincia de la empresa del solicitante';
		errores += 1;
	}
	if (trim(F.telefono_prof.value) == '') {
		sMensajeERROR += '\n  > Telefono de la empresa del solicitante';
		errores += 1
	}
	if (trim(F.tipocontrato_prof.value) == '') {
		sMensajeERROR += '\n  > Tipo de contrato en la empresa del solicitante';
		errores += 1
	}
	if (trim(F.antiguedad_prof.value) == '') {
		sMensajeERROR += '\n  > Antiguedad en la empresa del solicitante';
		errores += 1
	}
	if (trim(F.ingresos_prof.value) == '') {
		sMensajeERROR += '\n  > Ingresos en la empresa del solicitante';
		errores += 1
	}
	if (trim(F.categoria_prof.value) == '') {
		sMensajeERROR += '\n  > Categoria en la empresa del solicitante';
		errores += 1
	}
	if (trim(F.actividadempresa_prof.value) == '') {
		sMensajeERROR += '\n  > Actividad de la empresa del solicitante';
		errores += 1
	}


	// Chequeos campos Datos de la Compra
	
	if (trim(F.importe_financiar.value) == '') {
		sMensajeERROR += '\n  > Importe a financiar';
		errores += 1;
	}
	if (trim(F.plazos.value) == '') {
		sMensajeERROR += '\n  > Plazos de la compra';
		errores += 1;
	}
	if (trim(F.meses.value) == '') {
		sMensajeERROR += '\n  > Meses de la compra';
		errores += 1;
	}


	// Chequeos campos Datos Bancarios
	
	if (trim(F.numero_cuenta.value) == '') {
		sMensajeERROR += '\n  > Numero de Cuenta';
		errores += 1;
	}
	if (trim(F.antiguedad_cuenta.value) == '') {
		sMensajeERROR += '\n  > Antiguedad de la cuenta bancaria';
		errores += 1;
	}



	// Si hay muchos campos vacios, devolvemos mensaje generico de rellenar los campos
	if(errores > 15) {
		alert("\nDebe rellenar los datos marcados con asterisco (*)\n");
		return;
	}
	// ------------

	if (F.conocido.selectedIndex == 0)
		sMensajeERROR += '\n  > Donde nos has conocido';

	if(!F.acepto.checked)
		 sMensajeERROR += "\n\nDebe ACEPTAR las condiciones.\n";
	
	
	if (sMensajeERROR != '')
	{
		sMensajeERROR = '\nDebe rellenar los datos marcados con asterisco (*):\n' + sMensajeERROR + '\n\n';
		alert(sMensajeERROR);
		return;
	}
	else
	{
		F.estado_civil_txt.value = F.estado_civil.options[F.estado_civil.selectedIndex].text;
		F.provincia_txt.value = F.provincia.options[F.provincia.selectedIndex].text;
		F.provincia_prof_txt.value = F.provincia_prof.options[F.provincia_prof.selectedIndex].text;
		F.provincia_prof_2_txt.value = F.provincia_prof_2.options[F.provincia_prof_2.selectedIndex].text;
		
		document.prestamo.submit();
	}

}



//-------------------------------------------------------------------------------
// Validacion de los campos

function euro_keypress() 
{
	restringirNumero(10000000, 2);
}

function euro_blur(obj)
{
	esNumeroEntre(obj, 10000000, 2);
}

// ----------

function cp_keypress()
{
	restringirNumero(10000000, -2, false, false, true);
}


function cp_blur(obj)
{
	esNumeroEntre(obj, 10000000, -2, false, false, true);
}

// ----------

function personas_keypress()
{
	restringirNumero(10000, -2, false, false, false);
}

function personas_blur(obj)
{
	esNumeroEntre(obj, 10000, -2, false, false, false);
}

// ----------

function gastos_keypress()
{
	restringirNumero(10000000);
}

function gastos_blur(obj)
{
	esNumeroEntre(obj, 10000000);
}

// ----------

function antiguedad_keypress()
{
	restringirNumero(100, -2, false, false, false);
}

function antiguedad_blur(obj)
{
	esNumeroEntre(obj, 100, -2, false, false, false);
}
// ----------

// ----------

function ccc_keypress()
{
	restringirNumero(1000000000000, -2, false, false, false);
}

// ----------

function tel_keypress()
{
	restringirNumero(999999999, -2, false, false, false);
}





function markElem(o, b)
{
	if (!document.all) return;
	var bgcolor;
	if (b)
		bgcolor = 'white';
	else
		bgcolor = 'orange';
	o.style.backgroundColor = bgcolor;
}


function openTargetWin(winname)
{
	var tw = window.open('', winname, 'top=50,left=50,width=370,height=400,resizable=1;scroll=auto'); 
	tw.focus();
	return tw;
}

function trim(s)
{
	return s.replace(/(^\s*)|(\s*$)/g, ''); //[ \f\n\r\t\v]
}

function resetear()
{
	if (confirm('¡Se borrarán todos los datos que haya introducido!'))
	{
		document.prestamo.reset();
			
	}
}





function validTel(obj)
{
	var val = stripCharsInBag(obj.value, " .-\t");
	if (val == '' || (esNumero(val) && val.length == 9 && (val.substr(0,1) == '6' || val.substr(0,1) == '9' || val.substr(0,1) == '8')))
	{
		markElem(obj, true);
		return true;
	}
	
	alert("El 'Teléfono' debe ser un número de teléfono válido.");
	obj.focus();
	obj.select();
	return false;
}

function restringirNumero(max, decimales, bSign, bThousand, bAllow_leading_zeros)
{
	if (!document.all) return;
	var objTxt = event.srcElement;
	var objValue = objTxt.value;
	var keyCode = event.keyCode;
	
	if (decimales == null) decimales = -2;
	if (bSign == null) bSign = false;
	if (bThousand == null) bThousand = true;
	if (bAllow_leading_zeros == null) bAllow_leading_zeros = false;


	if ((keyCode == 43 || keyCode == 45) && objValue.indexOf('+') == -1 && objValue.indexOf('-') == -1 && bSign)
	{
		// Se ponga donde se ponga un signo siempre aparece al principio y
		// después el cursor se va al final del objeto.
		event.returnValue = false;
		objTxt.value = String.fromCharCode(keyCode) + objTxt.value;
		return false;
	}
	if ((keyCode > 57 || keyCode < 43 || keyCode == 47) || (keyCode == 43 || keyCode == 45) && (objValue.indexOf('+') > -1 || objValue.indexOf('-') > -1 || !bSign) || ((keyCode == 44 || keyCode == 46) && (objValue.indexOf(',') > -1 || decimales == -2)))
	{
		event.returnValue = false;
		esNumeroEntre(objTxt, max, decimales, bSign, bThousand, bAllow_leading_zeros);
		return false;
	}
	if (keyCode == 46) // punto (.)
		event.keyCode = 44; // coma (,)
}

function formatNum(valor, decimales, bSign, bThousand, bAllow_leading_zeros)
{
	var val = stripSpaces(valor);

	if (decimales == null) decimales = -2;
	if (bThousand == null) bThousand = true;
	if (bSign == null) bSign = false;
	if (bAllow_leading_zeros == null) bAllow_leading_zeros = false;

	if (bSign)
		val = comprobarSigno(val); 
	else
	{
		val = val.replace(/[+-]/g , '');
		if (!(bAllow_leading_zeros && (decimales == -2 || decimales == 0) && !bThousand))
			val = stripLeadingZeros(val);
	}

	if (decimales > -2)
		val = limpiarDecimal(val, decimales);

	if (bThousand)
		val = ponerPuntos(val);
	
	if (isNaN(quitarFormatoNumero(val))) 
		val = valor;
		
	return val;
}

function esNumeroEntre(objTxt, max, decimales, bSign, bThousand, bAllow_leading_zeros)
{
	if (decimales == null) decimales = -2;
	if (bThousand == null) bThousand = true;
	if (bSign == null) bSign = false;
	if (bAllow_leading_zeros == null) bAllow_leading_zeros = false;

	var num = objTxt.value;
	if (decimales == -2)
	{
		num = num.replace(/[,]/g , '');
		objTxt.value = num;
	}
	num = quitarFormatoNumero(num);
	if (trim(num) == '' || trim(num) == '.')
	{
		objTxt.value = '';
		markElem(objTxt, true);
		return true;
	}

	var mensaje = "Debe ser un número menor que " + ponerPuntos(max);
	
	if (!bAllow_leading_zeros)
		num = (num == '')? num: parseFloat(num);

	if (num == '' || (esNumero(num) && num <= max))
	{
		num += '';
		num = num.replace(/[.]/g, ',');
		objTxt.value = formatNum(num, decimales, bSign, bThousand, bAllow_leading_zeros);
		markElem(objTxt, true);
		return true;
	}

	alert(mensaje);
	objTxt.focus();
	objTxt.select();
	return false;
}

function esNumero(dato)
{
	dato = '' + dato
	return (dato != '' && !isNaN(dato) && dato.indexOf('E') == -1 && dato.indexOf('e') == -1);
}


function ponerPuntos(num)
{
	num = '' + num;
	var aux_i = '';
	var aux_d = '';
	var numero = num.replace(/[.]/g, ''); // limpiar formato pero dejar la coma (,)
	var num_sin_dec;
	var decimales = '';
	var num_puntos = '';
	var signo = numero.charAt(0);
	if (signo == '-' || signo == '+')
		numero = numero.substr(1);
	else
		signo = '';
	if (numero.indexOf(',') != -1)
	{
		num_sin_dec = numero.substring(0, numero.indexOf(','));
		decimales = numero.substr(numero.indexOf(','));
	}
	else
		num_sin_dec = numero;

	if (num_sin_dec.length > 3)
	{
		aux_i = num_sin_dec;
		while (aux_i.length > 3)
		{
			aux_d = aux_i.substr(aux_i.length - 3);
			aux_i = aux_i.substr(0, aux_i.length - 3);
			num_puntos = '.' + aux_d + num_puntos;
		}
		num = signo + aux_i + num_puntos + decimales;
	}
	else
		num = signo + numero;
	return num;
}


function quitarFormatoNumero(dato)
{
	dato = '' + dato;
	dato = dato.replace(/[.]/g, '');
	dato = dato.replace(/\,/g, '.');
	return dato;
}

function esTextoEntre (obj, max, min)
{
	var val = trim(obj.value);
	obj.value = val;
	var sLength = val.length;
	var m = 'El campo debe tener una longitud entre ' + min + ' y  ' + max + ' caracteres.\n' +
				'Has escrito ' + sLength + ' caracteres.';
	if (min == 0)
	{
		m = 'El campo debe tener una longitud máxima de ' + max + ' caracteres.\n' +
				'Has escrito ' + sLength + ' caracteres.';
		min = 0;
	}
	var desfase = textoEntre(val, max, min);
	if (sLength > 0 && desfase != 0)
	{
		alert(m);
		obj.focus();
		return false;
	}
	markElem(obj, true);
	return true;
}

function textoEntre(s, max, min)
{
	var sLength = s.length;

	if (sLength > max) 
		return sLength - max;
	if (sLength < min) 
		return sLength - min;
	return 0; 
}

function stripSpaces(s)
{
	return stripCharsInBag(s, " \t\n\r"); 
}

function stripCharsInBag (s, bag)
{
	s += '';
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++)
	{   
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}


function comprobarSigno(value)
{
	value = stripLeadingZeros(value);
	if (value == '-' || value == '+') return '';
	if (value.lastIndexOf('+') > 0)
		return value.replace(/[+]/g, '');
	if (value.lastIndexOf('-') > 0)
		return value.replace(/[-]/g, '');
	return value;
}


function stripLeadingZeros(s)
{
	var signo = s.charAt(0);
	if (signo == '-' || signo == '+')
		s = s.substr(1);
	else
		signo = '';

	for (var i = 0; i < s.length; ++i)
		if (s.charAt(i) != '0' || s.charAt(i+1) == ',' || s.charAt(i+1) == '')
			return signo + s.substr(i);
	return signo + s;
}

function redondear(numero, decimales)
{
	if (numero == null || numero == '-' || numero == '+')
		return '';
	if (numero > 99999999999) 
		return numero;
	if (decimales == null) decimales = 0;
	var aux = Math.pow(10, decimales);

	return (Math.round(numero * aux)/aux);
}


function limpiarDecimal(numero, decimales)
{
	if (decimales == null) decimales = -2;
	numero = '' + numero;
	var signo = numero.charAt(0);
	if (signo == '-' || signo == '+')
		numero = numero.substr(1);
	else
		signo = '';

	if (decimales > -1)
	{
		numero = '' + redondear(quitarFormatoNumero(numero), decimales);
		numero = numero.replace(/[.]/g, ',');
	}

	var coma_index = numero.indexOf(',');
	if (coma_index == (numero.length - 1))
		numero = numero.substr(0, coma_index);
	else if (coma_index == 0)
		numero = '0' + numero;

	numero = signo + numero;

	return numero;
}

function esEmail(s)
{
	s = '' + s;
	
   	var r, re;
   	re = /^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z0-9_]+$/g;
   	r = s.match(re);
	
   	return (r != null);
}

function validateEmail(obj)
{
	obj.value = trim(obj.value);
	
	var MAX_LENGTH = 150;
	var s = obj.value;
	if ((esEmail(s) && parseInt(s.length) <= MAX_LENGTH) || s == '')
	{
		markElem(obj, true);
		return true;
	}
		
	alert("Debe ser una DIRECCIÓN DE CORREO ELECTRÓNICO correcta.\n\n" +
					"Puede contener letras, números, puntos (.) y caracteres de subrayado (_),\n" +
					"pero no espacios u otros caracteres.\n" +
					"En la parte posterior al símbolo @ debe haber al menos un punto antes del final.");
	
	obj.focus();
	obj.select();
	return false;
}

function validaFechaNac (obj) {
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
	var fecha = obj.value;

	if (fecha != "") {

		var matchArray = fecha.match(datePat); // is the format ok?

		if (matchArray == null) {
			alert("El formato de fecha no es correcto.");
				obj.focus();
				obj.select();
				return false;
		} 

		day = matchArray[1]; // parse date into variables
		month = matchArray[3];
		year = matchArray[4];

		if (day < 1 || day > 31) {
			alert("El dia debe estar comprendido entre 1 y 31.");
			obj.focus();
			obj.select();
			return false;
		}

		if (month < 1 || month > 12) { // check month range
			alert("El mes debe estar comprendido entre 1 y 12.");
			obj.focus();
			obj.select();
			return false;
		}
		

		if ((month==4 || month==6 || month==9 || month==11) && day==31) {
			alert("El mes indicado en la fecha no tiene 31 dias.");
			obj.focus();
			obj.select();
			return false;
		}
		if (month == 2) { // check for february 29th
			var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
			if (day>29 || (day==29 && !isleap)) {
				alert("El mes de Febrero no puede tener mas de 29 dias.");
				obj.focus();
				obj.select();
				return false;
			}
		}
	}
}




function comprueba_ccc (ccc)
{
	var numeros = '0123456789';
	var exp = new RegExp ("^[0-9]{20}$");
		
	if(ccc.value != "") {
		if (!exp.test(ccc.value)) {
			alert("CCC no valido, un CCC valido son 20 digitos");
			ccc.focus();
			return false;
		}
	
	}
	
	return true;
}
