// -------------------------------------------------------- //
// -------------------------------------------------------- //
//     Codigo Javascript para el control del Formulario     //
// -------------------------------------------------------- //
// -------------------------------------------------------- //

var SOLIC_2 = 0;


//-------------------------------------------------------------------------------
// Se ejecuta al cargar la pagina para establecer propiedades iniciales

function iniciar()
{
document.hipoteca.sol2.checked = false;
if (document.all) document.all.Tsol2.style.display = 'none';

}


//-------------------------------------------------------------------------------
// Abre ventana para el calculo de cuota de hipoteca

function calculaCuota()  { 

  	var popupWin = window.open("calculo_hipoteca.asp?cantidad=" + document.hipoteca.importe_financiar_inmueble.value + "&plazo=" + document.hipoteca.plazo_inmueble.value + "", "", "resizable=no,toolbar=no,scrollbars,width=500,height=300");
	popupWin.focus();
}


//-------------------------------------------------------------------------------
// Ante cualquier cambio de un campo, se marca la casilla de 2º solicitante

function solic2_change()
{
	document.hipoteca.sol2.checked = true;
	SOLIC_2 = 1;
}


//-------------------------------------------------------------------------------
// Se llama cuando se pulsa el check de 2º solicitante

function mostrarsol2()
{
	if (SOLIC_2 == null) SOLIC_2 = 0;
		
	// Cuando se desmarca el 2º solicitante
	if (!document.hipoteca.sol2.checked && SOLIC_2 == 1)
	{
		var elems = document.hipoteca.elements;
		var numelems = elems.length;
		for (var i = 0; i < numelems; ++i)  
			if (elems[i].name.indexOf('_2') > 0)  
				if (elems[i].type == 'select-one') 
					elems[i].selectedIndex = 0;
				else 					
					elems[i].value = '';

		
		SOLIC_2 = 0;
	}
	// Cuando se marca el 2º solicitante
	else if (SOLIC_2 == 0) {
		document.hipoteca.domicilio_2.value = document.hipoteca.domicilio.value;
		document.hipoteca.cp_2.value = document.hipoteca.cp.value;
		document.hipoteca.telefono_2.value = document.hipoteca.telefono.value;
		document.hipoteca.provincia_2.selectedIndex = document.hipoteca.provincia.selectedIndex;
		document.hipoteca.vivienda_habitual_2.selectedIndex = document.hipoteca.vivienda_habitual.selectedIndex;
		
		SOLIC_2 = 1;
	}
	
	// Mostramos o escondemos los campos del 2º solicitante
	if (document.all)
		if (!document.all.sol2.checked) {
			document.all.Tsol2.style.display = 'none';
			alert('Esta casilla debe estar marcada para que se envíen los datos del 2º solicitante.');
		} else	{
			document.all.Tsol2.style.display = 'block';
			alert('Debe rellenar los datos del 2º solicitante marcados con asterisco (*)');
		}
	else 
		if (document.hipoteca.sol2.checked)
			alert('Debe rellenar los datos del 2º solicitante marcados con asterisco (*)');
		else
			alert('Esta casilla debe estar marcada para que se envíen los datos del 2º solicitante.');
}


//-------------------------------------------------------------------------------
// Se llama cuando se pulsa el check de 2º solicitante

function enviar()
{
	var F = document.hipoteca;
	var sMensajeERROR = '';

	if (trim(F.entrada_inmueble.value) == '')
		sMensajeERROR += '\n  > Entrada, ponga 0 si no tiene';
	if (trim(F.precio_inmueble.value) == '')
		sMensajeERROR += '\n  > Precio del inmueble';
	if (trim(F.nombre.value) == '')
		sMensajeERROR += '\n  > Nombre del primer solicitante';
	if (trim(F.apellido1.value) == '')
		sMensajeERROR += '\n  > Primer apellido del 1er solicitante';
	if (trim(F.nif1.value) == '')
		sMensajeERROR += '\n  > NIF del 1er solicitante';
	if (trim(F.fecha_nac.value) == '')
		sMensajeERROR += '\n  > Fecha de nacimiento del 1er solicitante';
	if (trim(F.email.value) == '')
		sMensajeERROR += '\n  > Email del 1er solicitante';
	if (trim(F.telefono.value) == '')
		sMensajeERROR += '\n  > Teléfono del 1er solicitante';
	if (F.provincia.selectedIndex == 0)
		sMensajeERROR += '\n  > Provincia del 1er solicitante';
	if (F.vivienda_habitual.selectedIndex == 0)
		sMensajeERROR += '\n  > Vivienda habitual del 1er solicitante';
	if (F.tipo_contrato.selectedIndex == 0)
		sMensajeERROR += '\n  > Tipo de Contrato del 1er solicitante';
	if (document.getElementById('clausula').checked == false)
		sMensajeERROR += '\n  > Debe aceptar la clausula del contrato';
	if (trim(F.importe_financiar_inmueble.value) == '')
		sMensajeERROR += '\n  > Importe de inmueble a financiar';
	if (trim(F.superficie_inmueble.value) == '')
		sMensajeERROR += '\n  > Superficie del inmueble';
	if (trim(F.plazo_inmueble.value) == '')
		sMensajeERROR += '\n  > Plazo de amortización';
	if (trim(F.duracion_trabajo.value) == '')
		sMensajeERROR += '\n  > Duración meses trabajo';
	if (trim(F.nomina.value) == '' || trim(F.numero_pagas.value) == '')
		sMensajeERROR += '\n  > Ingresos';

	if (document.hipoteca.sol2.checked) // comprobar los datos obligatorios del 2º solicitante si procede.
	{
		if (trim(F.nombre_2.value) == '')
			sMensajeERROR += '\n  > Nombre del 2o solicitante';
		if (trim(F.apellido1_2.value) == '')
			sMensajeERROR += '\n  > Primer apellido del 2o solicitante';
		if (trim(F.nif2.value) == '')
			sMensajeERROR += '\n  > NIF del 2o solicitante';
		if (trim(F.fecha_nac_2.value) == '')
			sMensajeERROR += '\n  > Fecha de nacimiento del 2o solicitante';
		if (trim(F.email_2.value) == '')
			sMensajeERROR += '\n  > Email del 2o solicitante';
		if (trim(F.telefono_2.value) == '')
			sMensajeERROR += '\n  > Teléfono del 2o solicitante';
		if (F.provincia_2.selectedIndex == 0)
			sMensajeERROR += '\n  > Provincia del 2o solicitante';
		if (F.vivienda_habitual_2.selectedIndex == 0)
			sMensajeERROR += '\n  > Vivienda habitual del 2o solicitante';			
		if (F.tipo_contrato_2.selectedIndex == 0)
			sMensajeERROR += '\n  > Tipo de Contrato del 2o solicitante';
		if (trim(F.duracion_trabajo_2.value) == '')
			sMensajeERROR += '\n  > Duración meses trabajo';
		if (trim(F.nomina_2.value) == '' || trim(F.numero_pagas_2.value) == '')
			sMensajeERROR += '\n  > Ingresos';
		
	}
	
	if (F.conocido.selectedIndex == 0)
		sMensajeERROR += '\n  > Donde nos has conocido';

	
	if (sMensajeERROR != '')
	{
		sMensajeERROR = '\nDebe rellenar los datos marcados con asterisco (*):\n' + sMensajeERROR + '\n\n';
		alert(sMensajeERROR);
		return;
	}
	else
	{
		F.tipo_inmueble_txt.value = F.tipo_inmueble.options[F.tipo_inmueble.selectedIndex].text;
		F.estado_inmueble_txt.value = F.estado_inmueble.options[F.estado_inmueble.selectedIndex].text;
		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.vivienda_habitual_txt.value = F.vivienda_habitual.options[F.vivienda_habitual.selectedIndex].text;
		F.tipo_contrato_txt.value = F.tipo_contrato.options[F.tipo_contrato.selectedIndex].text;
		F.estado_civil_2_txt.value = F.estado_civil_2.options[F.estado_civil_2.selectedIndex].text;
		F.provincia_2_txt.value = F.provincia_2.options[F.provincia_2.selectedIndex].text;
		F.vivienda_habitual_2_txt.value = F.vivienda_habitual_2.options[F.vivienda_habitual_2.selectedIndex].text;
		F.tipo_contrato_2_txt.value = F.tipo_contrato_2.options[F.tipo_contrato_2.selectedIndex].text;
		
		document.hipoteca.submit();
	}

}



//-------------------------------------------------------------------------------
// Validacion de los campos

function euro_keypress() 
{
	restringirNumero(10000000, 2);
}

function euro_blur(obj)
{
	esNumeroEntre(obj, 10000000, 2);
}

function edad_keypress()
{
	restringirNumero(255);
}

function edad_blur(obj)
{
	esNumeroEntre(obj, 255);
}

function superf_keypress()
{
	restringirNumero(10000000, 1);
}

function superf_blur(obj)
{
	esNumeroEntre(obj, 10000000, 1);
}

function cp_keypress()
{
	restringirNumero(10000000, -2, false, false, true);
}

function cp_blur(obj)
{
	esNumeroEntre(obj, 10000000, -2, false, false, true);
}

function plazo_keypress()
{
	restringirNumero(50);
}

function plazo_blur(obj)
{
	esNumeroEntre(obj, 50);
}

function duracion_keypress()
{
	restringirNumero(30000);
}

function duracion_blur(obj)
{
	esNumeroEntre(obj, 30000);
}

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.hipoteca.reset();
		SOLIC_2 = 0;
		
		if (document.all)
			document.all.Tsol2.style.display = 'none';
	}
}





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;
			}
		}
	}
}
