//	calculadora-hipotecas.js
//	dependencias:	/libjs/prototype.js
//					/libjs/browserdetect_little.js
//					/libjs/tabla-hipotecas.js
//					/libjs/libCookies.js
//					/libjs/validaciones.js
//					/libjs/o.Fader.js
//					/css/calculadora-hipotecas.css

var goSCuota = new Object();
var goSPlazo = new Object();
var goSInteres = new Object();
var goSFinanciacion = new Object();
var goSPrecio = new Object();
var goSAhorros = new Object();
var goSGastos = new Object();

//var gcTitleSlider = '';
//var gcTitleSliderActivo = '';
//var gcTitleValores = ''; 

var gbCalculando = false;

var goIndiceActual = new Object();

var ghSliders = new Object();


//	Cambiar el valor del euribor cada 15 o 30 dias
//	http://www.euribor.org/html/content/euribor_data.html
// se obtiene de euribor.js
// var gfEuribor = 4.09;
//	valor del euro / peseta
var gfEuro = 166.386;

//	valores maximos por defecto, varian segun el precio del inmueble
var giCuotaMaxima = 20000;
var giFinanciacionMaxima = 3000000;
var giPrecioMaximo = 3000000;
//	precio exacto del inmueble solicitado (se modifica desde un parametro jsp)
var giPrecioInmueble = 3000000;

Event.observe(window, 'load', function(e){
	$('form-calc-hipoteca').reset();
	// solucionar bug de firefox 1 de 2
	$('ti-ahorros').style.borderWidth = '2px';
	$('ti-gastos').style.borderWidth = '2px';
	$A(document.getElementsByClassName('valor', $('form-calc-hipoteca'))).each(function(poElemento){
		Event.observe(poElemento, 'focus', function(e){
			if (!Element.hasClassName(poElemento.parentNode.parentNode.parentNode, 'o-activo')
				&& !Element.hasClassName(poElemento.parentNode.parentNode.parentNode, 'o-proxy-indicador')){
				Element.addClassName(poElemento, 'activo');
			}
		}, false);
		Event.observe(poElemento, 'blur', function(e){
			if (!Element.hasClassName(poElemento.parentNode.parentNode.parentNode, 'o-activo')
				&& !Element.hasClassName(poElemento.parentNode.parentNode.parentNode, 'o-proxy-indicador')){
				Element.removeClassName(poElemento, 'hover');
				Element.removeClassName(poElemento, 'activo');
			}
		}, false);
		Event.observe(poElemento, 'mouseover', function(e){
			if (!Element.hasClassName(poElemento.parentNode.parentNode.parentNode, 'o-activo')
				&& !Element.hasClassName(poElemento.parentNode.parentNode.parentNode, 'o-proxy-indicador')){
				Element.addClassName(poElemento, 'hover');
			}
		}, false);
		Event.observe(poElemento, 'mouseout', function(e){
			if (!Element.hasClassName(poElemento.parentNode.parentNode.parentNode, 'o-activo')
				&& !Element.hasClassName(poElemento.parentNode.parentNode.parentNode, 'o-proxy-indicador')){
				Element.removeClassName(poElemento, 'hover');
			}
		}, false);
		Event.observe(poElemento, 'keypress', function(e){
			var cTecla = e.keyCode || e.which;
			
			if (cTecla == goKeyCodes.RETURN){
				// recorre la coleccion de Event.observers para ese elemento y ejecuta el evento onChange
				
				Event.cache[poElemento._eventID]['change'][0]('change');
				//Event.observers.findAll(function(oEl){return oEl[0] == poElemento && oEl[1] == "change"})[0][2]();
			}
		}, false);
	});
	$A(document.getElementsByClassName('o-indicador', $('form-calc-hipoteca'))).each(function(poElemento){
		Event.observe(poElemento, 'mouseover', function(e){
			Element.addClassName(poElemento, 'o-hover');
		}, false);
		Event.observe(poElemento, 'mouseout', function(e){
			Element.removeClassName(poElemento, 'o-hover');
		}, false);
		Event.observe(poElemento, 'mousedown', function(e){
//alert('o-indicador mousedown');
			if (document.getElementsByClassName('o-activo').length == 0){
				// bloqueo del nuevo slider activo
/*				if (document.getElementsByClassName('slider', poElemento)[0].id == 'slider-cuota'){
					// activar el importe
					var oElemento = $('slider-financiacion').parentNode.parentNode;
				} else {
					// activar la cuota
					var oElemento = $('slider-cuota').parentNode.parentNode;
				}*/
				var oElemento = poElemento;
				
				// salgo del modo de inicio
				Element.removeClassName($('calculadora-hipotecas'), 'modo-inicio');
				document.getElementsByClassName('regulador-horizontal', oElemento)[0].title = gcTitleSliderActivo;
				document.getElementsByClassName('valor', oElemento)[0].title = gcTitleSliderActivo;
				
				Element.removeClassName(document.getElementsByClassName('boton-calcular', oElemento)[0].getElementsByTagName('DIV')[0], 'desactivado');
				Element.removeClassName(document.getElementsByClassName('boton-calcular', oElemento)[0].getElementsByTagName('DIV')[0], 'hover');
				document.getElementsByClassName('radio', oElemento)[0].checked = true;
				Element.removeClassName(oElemento, 'fondo-azul');
				Element.addClassName(oElemento, 'o-activo');
				ghSliders.get(document.getElementsByClassName('slider', oElemento)[0].id).bloquear();
				goIndiceActual = oElemento;
			}
		}, false);
		Event.observe(poElemento, 'click', function(e){
//alert('o-indicador click');
			if (!Element.hasClassName(poElemento, 'o-activo')){
				Element.removeClassName(document.getElementsByClassName('alerta', $('form-calc-hipoteca'))[0], 'alerta');
				Element.removeClassName(document.getElementsByClassName('mod-opacidad', $('form-calc-hipoteca'))[0], 'mod-opacidad');
			}
		}, false);
	});
	$A(document.getElementsByClassName('handleBar', $('form-calc-hipoteca'))).each(function(poElemento){
		Event.observe(poElemento, 'click', function(e){
//alert('handleBar click');
			if (!Element.hasClassName(poElemento.parentNode.parentNode.parentNode, 'o-activo')){
				Element.removeClassName(document.getElementsByClassName('alerta', $('form-calc-hipoteca'))[0], 'alerta');
				Element.removeClassName(document.getElementsByClassName('mod-opacidad', $('form-calc-hipoteca'))[0], 'mod-opacidad');
			}
		}, false);
	});
	$A(document.getElementsByClassName('line', $('form-calc-hipoteca'))).each(function(poElemento){
		Event.observe(poElemento, 'click', function(e){
//alert('line click');
			if (!Element.hasClassName(poElemento.parentNode.parentNode.parentNode, 'o-activo')){
				Element.removeClassName(document.getElementsByClassName('alerta', $('form-calc-hipoteca'))[0], 'alerta');
				Element.removeClassName(document.getElementsByClassName('mod-opacidad', $('form-calc-hipoteca'))[0], 'mod-opacidad');
			}
		}, false);
	});
	// botones de calculo y bloqueo
	$A(document.getElementsByClassName('radio', $('form-calc-hipoteca'))).each(function(poElemento){
		Event.observe(poElemento, 'click', function(e){
//alert('radio click');
			if (Element.hasClassName(document.getElementsByClassName('boton-calcular', poElemento.parentNode)[0].getElementsByTagName('DIV')[0], 'desactivado')
				|| Element.hasClassName(document.getElementsByClassName('boton-calcular', poElemento.parentNode)[0].getElementsByTagName('DIV')[0], 'hover')){
				
				ghSliders.get(document.getElementsByClassName('slider', document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0])[0].id).desbloquear();

				Element.addClassName(document.getElementsByClassName('boton-calcular', document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0])[0].getElementsByTagName('DIV')[0], 'desactivado');
				Element.addClassName(document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0], 'fondo-azul');
				document.getElementsByClassName('regulador-horizontal', document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0])[0].title = gcTitleSlider;
				document.getElementsByClassName('valor', document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0])[0].title = gcTitleValores;
				Element.removeClassName(document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0], 'o-activo');
				Element.removeClassName(poElemento.getElementsByTagName('DIV')[0], 'desactivado');
				Element.removeClassName(poElemento.getElementsByTagName('DIV')[0], 'hover');
				Element.removeClassName(poElemento.parentNode, 'fondo-azul');
				Element.addClassName(poElemento.parentNode, 'o-activo');
				document.getElementsByClassName('regulador-horizontal', poElemento.parentNode)[0].title = gcTitleSliderActivo;
				document.getElementsByClassName('valor', poElemento.parentNode)[0].title = gcTitleSliderActivo;
				
				// bloqueo del nuevo slider activo
				poElemento.checked = true;				
				ghSliders.get(document.getElementsByClassName('slider', poElemento.parentNode)[0].id).bloquear();
				goIndiceActual = poElemento.parentNode;
			}
		}, false);
	});
	$A(document.getElementsByClassName('boton-calcular', $('form-calc-hipoteca'))).each(function(poElemento){
		Event.observe(poElemento.getElementsByTagName('DIV')[0], 'mouseover', function(e){
			if (Element.hasClassName(poElemento.getElementsByTagName('DIV')[0], 'desactivado')){
				Element.addClassName(poElemento.getElementsByTagName('DIV')[0], 'hover');
			}
		}, false);
		Event.observe(poElemento.getElementsByTagName('DIV')[0], 'mouseout', function(e){
			if (Element.hasClassName(poElemento.getElementsByTagName('DIV')[0], 'desactivado')){
				Element.removeClassName(poElemento.getElementsByTagName('DIV')[0], 'hover');
			}
		}, false);
		Event.observe(poElemento.getElementsByTagName('DIV')[0], 'click', function(e){
//alert('boton-calcular DIV click');
/*			if (Element.hasClassName(poElemento.getElementsByTagName('DIV')[0], 'desactivado')
				|| Element.hasClassName(poElemento.getElementsByTagName('DIV')[0], 'hover')){
				ghSliders.get(document.getElementsByClassName('slider', document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0])[0].id).desbloquear();

				Element.addClassName(document.getElementsByClassName('boton-calcular', document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0])[0].getElementsByTagName('DIV')[0], 'desactivado');
				Element.addClassName(document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0], 'fondo-azul');
				Element.removeClassName(document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0], 'o-activo');
				Element.removeClassName(poElemento.getElementsByTagName('DIV')[0], 'desactivado');
				Element.removeClassName(poElemento.getElementsByTagName('DIV')[0], 'hover');
				Element.removeClassName(poElemento.parentNode, 'fondo-azul');
				Element.addClassName(poElemento.parentNode, 'o-activo');
				
				// bloqueo del nuevo slider activo
				document.getElementsByClassName('radio', poElemento.parentNode)[0].checked = true;
				ghSliders.get(document.getElementsByClassName('slider', poElemento.parentNode)[0].id).bloquear();
				goIndiceActual = poElemento.parentNode;
			}*/
		}, false);
	});
	
	// slider Cuota
	goSCuota = new Slider($("slider-cuota"), $("slider-input-cuota"));
	goSCuota.setMaximum(giCuotaMaxima);
	goSCuota.setMinimum(1);
	goSCuota.setValue(1000);
	goSCuota.setOldValue(1000);
	goSCuota.setOldTempValue(1000);
	goSCuota.setUnitIncrement(100);
	goSCuota.setBlockIncrement(100);//500
	goSCuota.onchange = function () {
		goSCuota.setOldTempValue(goSCuota.getValue());
		$("ti-cuota").value = formatAsMoney(goSCuota.getValue());
		if ($("ti-cuota").value == "0"){
			Element.addClassName($("ti-cuota"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-cuota"), 'valor-cero');
		}
		if (!gbCalculando){gbCalculando = true; calcular();}
	};
	Event.observe($('ti-cuota'), 'change', function(e){
		var iValor = Number(unFormat($("ti-cuota").value));
		iValor = iValor / goSCuota.getUnitIncrement();
		iValor = iValor.toFixed(0) * goSCuota.getUnitIncrement();
		iValor = (iValor < goSCuota.getUnitIncrement() && iValor != 0) ? goSCuota.getUnitIncrement() : iValor;
		$("ti-cuota").value = formatAsMoney(iValor);
		if ($("ti-cuota").value == "0"){
			Element.addClassName($("ti-cuota"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-cuota"), 'valor-cero');
		}
		goSCuota.setValue(minCero(unFormat($('ti-cuota').value)));
		if (!gbCalculando){gbCalculando = true; calcular();}
	}, false);
	Event.observe($('ti-cuota'), 'keypress', function(e){
		var cTecla = e.keyCode || e.which;
		if ((goSCuota.estaBloqueado() && cTecla != goKeyCodes.TAB) || !soloNumeros(e, 6, false, true)){Event.stop(e);}
	}, false);
	
	// slider Plazo
	goSPlazo = new Slider($("slider-plazo"), $("slider-input-plazo"));
	goSPlazo.setMinimum(100);
	goSPlazo.setMaximum(5000);
	goSPlazo.setValue(2500);
	goSPlazo.setOldValue(2500);
	goSPlazo.setOldTempValue(2500);
	goSPlazo.setUnitIncrement(100);
	goSPlazo.setBlockIncrement(100);//500
	goSPlazo.onchange = function (){
		goSPlazo.setOldTempValue(goSPlazo.getValue());
		var fValue = goSPlazo.getValue() / 100;
		$("ti-plazo").value = fValue.toFixed(0);
		if ($("ti-plazo").value == "0"){
			Element.addClassName($("ti-plazo"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-plazo"), 'valor-cero');
		}
		if (!gbCalculando){gbCalculando = true; calcular();}
	};
	Event.observe($('ti-plazo'), 'change', function(e){
		var fValue = $('ti-plazo').value * 100;
		goSPlazo.setValue(minCero(fValue.toFixed(0)));
		if (!gbCalculando){gbCalculando = true; calcular();}
	}, false);
	Event.observe($('ti-plazo'), 'keypress', function(e){
		var cTecla = e.keyCode || e.which;
		if ((goSPlazo.estaBloqueado() && cTecla != goKeyCodes.TAB) || !soloNumeros(e, 3, false, false)){Event.stop(e);}
	}, false);
	
	// slider Interes
	goSInteres = new Slider($("slider-interes"), $("slider-input-interes"), "horizontal", true);
	goSInteres.setMinimum(100);
	goSInteres.setMaximum(800);
	var iInteres = Number($("ti-interes").value.replace(',', ''));
	goSInteres.setValue(iInteres);
	goSInteres.setOldValue(iInteres);
	goSInteres.setOldTempValue(iInteres);
	goSInteres.setUnitIncrement(10);
	goSInteres.setBlockIncrement(10);//100
	goSInteres.onchange = function (){
		goSInteres.setOldTempValue(goSInteres.getValue());
		var fValue = goSInteres.getValue();
		$("ti-interes").value = formatAsPercentage(fValue);
		if ($("ti-interes").value == "0"){
			Element.addClassName($("ti-interes"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-interes"), 'valor-cero');
			var fInteres = new Number($("ti-interes").value.replace(",", "."));
			if (fInteres < gfEuribor){
				Element.addClassName($("ti-interes"), 'valor-rojo');
			} else {
				Element.removeClassName($("ti-interes"), 'valor-rojo');
			}
		}
		if (!gbCalculando){gbCalculando = true; calcular();}
	};
	Event.observe($('ti-interes'), 'change', function(e){
		var cInteres = minCero($('ti-interes').value);
		if (cInteres.indexOf(',') < 0){
			$('ti-interes').value = cInteres + ',00';
		} else if(cInteres.split(',')[1].length == 0){
			$('ti-interes').value = cInteres + '00';
		} else if(cInteres.split(',')[1].length == 1){
			$('ti-interes').value = cInteres + '0';
		}
		var iValor = Number($('ti-interes').value.replace(',', '.')) * 100;
		iValor = iValor / goSInteres.getUnitIncrement();
		iValor = iValor.toFixed(0) * goSInteres.getUnitIncrement();
		$('ti-interes').value = formatAsPercentage(iValor);
		goSInteres.setValue(minCero(unFormat($('ti-interes').value)));
		if (!gbCalculando){gbCalculando = true; calcular();}
	}, false);
	Event.observe($('ti-interes'), 'keypress', function(e){
		var cTecla = e.keyCode || e.which;
		if ((goSInteres.estaBloqueado() && cTecla != goKeyCodes.TAB) || !soloNumeros(e, 6, true, false)){Event.stop(e);}
	}, false);
	
	// slider Financiacion
	goSFinanciacion = new Slider($("slider-financiacion"), $("slider-input-financiacion"));
	goSFinanciacion.setMaximum(giFinanciacionMaxima);
	goSFinanciacion.setValue(unFormat($("ti-precio").value));// 210000
	goSFinanciacion.setOldValue(Number(unFormat($("ti-precio").value)));
	goSFinanciacion.setOldTempValue(Number(unFormat($("ti-precio").value)));
	goSFinanciacion.setUnitIncrement(1000);//1000
	goSFinanciacion.setBlockIncrement(10000);//50000
	goSFinanciacion.onchange = function () {
		goSFinanciacion.setOldTempValue(goSFinanciacion.getValue());
		var fValue = goSFinanciacion.getValue();
		$("ti-financiacion").value = formatAsMoney(fValue);
		if ($("ti-financiacion").value == "0"){
			Element.addClassName($("ti-financiacion"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-financiacion"), 'valor-cero');
		}
//		if (!gbCalculando){gbCalculando = true; calcularAhorros(); calcular();}
		if (!gbCalculando){
			gbCalculando = true;
			var cIdActivo = document.getElementsByClassName('slider', document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0])[0].id;
///			if (cIdActivo != 'slider-precio' && cIdActivo != 'slider-ahorros' && cIdActivo != 'slider-gastos'){
			if (cIdActivo != 'slider-precio'){
///				calcularAhorros();
				calcularPrecio();
			}
			calcular('slider-financiacion');
		}
	};
	Event.observe($('ti-financiacion'), 'change', function(e){
		var iValor = Number(unFormat($("ti-financiacion").value));
		iValor = iValor / goSFinanciacion.getUnitIncrement();
		iValor = iValor.toFixed(0) * goSFinanciacion.getUnitIncrement();
		iValor = (iValor < goSFinanciacion.getUnitIncrement() && iValor != 0) ? goSFinanciacion.getUnitIncrement() : iValor;
		$("ti-financiacion").value = formatAsMoney(iValor);
		if ($("ti-financiacion").value == "0"){
			Element.addClassName($("ti-financiacion"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-financiacion"), 'valor-cero');
		}
		var fValue = unFormat($('ti-financiacion').value);
		goSFinanciacion.setValue(minCero(fValue));
//		if (!gbCalculando){gbCalculando = true; calcularAhorros(); calcular();}
		if (!gbCalculando){
			gbCalculando = true;
			var cIdActivo = document.getElementsByClassName('slider', document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0])[0].id;
///			if (cIdActivo != 'slider-precio' && cIdActivo != 'slider-ahorros' && cIdActivo != 'slider-gastos'){
			if (cIdActivo != 'slider-precio'){
///				calcularAhorros();
				calcularPrecio();
			}
			calcular('slider-financiacion');
		}
	}, false);
	Event.observe($('ti-financiacion'), 'keypress', function(e){
		var cTecla = e.keyCode || e.which;
		if ((goSFinanciacion.estaBloqueado() && cTecla != goKeyCodes.TAB) || !soloNumeros(e, 10, false, true)){Event.stop(e);}
	}, false);
	
	// slider Precio
	goSPrecio = new Slider($("slider-precio"), $("slider-input-precio"));
	goSPrecio.setMaximum(giPrecioMaximo);
	goSPrecio.setValue(unFormat($("ti-precio").value));// 200000
	goSPrecio.setOldValue(Number(unFormat($("ti-precio").value)));
	goSPrecio.setOldTempValue(Number(unFormat($("ti-precio").value)));
	goSPrecio.setUnitIncrement(1000);//10000
	goSPrecio.setBlockIncrement(10000);//50000
	goSPrecio.onchange = function () {
		goSPrecio.setOldTempValue(goSPrecio.getValue());
		$("ti-precio").value = formatAsMoney(goSPrecio.getValue());
		if ($("ti-precio").value == "0"){
			Element.addClassName($("ti-precio"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-precio"), 'valor-cero');
		}
		if (!gbCalculando){gbCalculando = true; calcularFinanciacion(); calcular('slider-precio');}
	};
	Event.observe($('ti-precio'), 'change', function(e){
		var iValor = Number(unFormat($("ti-precio").value));
		iValor = iValor / goSPrecio.getUnitIncrement();
		iValor = iValor.toFixed(0) * goSPrecio.getUnitIncrement();
		iValor = (iValor < goSPrecio.getUnitIncrement() && iValor != 0) ? goSPrecio.getUnitIncrement() : iValor;
		$("ti-precio").value = formatAsMoney(iValor);
		if ($("ti-precio").value == "0"){
			Element.addClassName($("ti-precio"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-precio"), 'valor-cero');
		}
		goSPrecio.setValue(iValor);
		if (!gbCalculando){gbCalculando = true; calcularFinanciacion(); calcular('slider-precio');}
	}, false);
	Event.observe($('ti-precio'), 'keypress', function(e){
		var cTecla = e.keyCode || e.which;
		if ((goSPrecio.estaBloqueado() && cTecla != goKeyCodes.TAB) || !soloNumeros(e, 10, false, true)){Event.stop(e);}
	}, false);
	
/*	// slider Ahorros
	goSAhorros = new Slider($("slider-ahorros"), $("slider-input-ahorros"));
	goSAhorros.setMaximum(300000);
	goSAhorros.setValue(0);
	goSAhorros.setOldValue(0);
	goSAhorros.setOldTempValue(0);
	goSAhorros.setUnitIncrement(5000);
	goSAhorros.setBlockIncrement(5000);//10000
	goSAhorros.onchange = function (){
		goSAhorros.setOldTempValue(goSAhorros.getValue());
		var fValue = goSAhorros.getValue();
		$("ti-ahorros").value = formatAsMoney(fValue);
		if ($("ti-ahorros").value == "0"){
			Element.addClassName($("ti-ahorros"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-ahorros"), 'valor-cero');
		}
		if (!gbCalculando){gbCalculando = true; calcularFinanciacion(); calcular('slider-ahorros');}
	};
	Event.observe($('ti-ahorros'), 'change', function(e){
		var iValor = Number(unFormat($("ti-ahorros").value));
		iValor = iValor / goSAhorros.getUnitIncrement();
		iValor = iValor.toFixed(0) * goSAhorros.getUnitIncrement();
		iValor = (iValor < goSAhorros.getUnitIncrement() && iValor != 0) ? goSAhorros.getUnitIncrement() : iValor;
		$("ti-ahorros").value = formatAsMoney(iValor);
		goSAhorros.setValue(minCero(unFormat($('ti-ahorros').value)));
		if ($("ti-ahorros").value == "0"){
			Element.addClassName($("ti-ahorros"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-ahorros"), 'valor-cero');
		}
		if (!gbCalculando){gbCalculando = true; calcularFinanciacion(); calcular('slider-ahorros');}
	}, false);
	Event.observe($('ti-ahorros'), 'keypress', function(e){
		var cTecla = e.keyCode || e.which;
		if ((goSAhorros.estaBloqueado() && cTecla != goKeyCodes.TAB) || !soloNumeros(e, 8, false, true)){Event.stop(e);}
	}, false);*/
	// slider Ahorros
	goSAhorros = new ProxySlider($("ti-ahorros"));
	goSAhorros.setValue(0);
	goSAhorros.setOldValue(0);
	goSAhorros.setOldTempValue(0);
	Event.observe($('ti-ahorros'), 'change', function(e){
		if (document.getElementsByClassName('o-activo').length == 0){
			// bloqueo del nuevo slider activo
			// activar la cuota
			var oElemento = $('slider-cuota').parentNode.parentNode;
			
			Element.removeClassName(document.getElementsByClassName('boton-calcular', oElemento)[0].getElementsByTagName('DIV')[0], 'desactivado');
			Element.removeClassName(document.getElementsByClassName('boton-calcular', oElemento)[0].getElementsByTagName('DIV')[0], 'hover');
			Element.removeClassName(oElemento, 'fondo-azul');
			Element.addClassName(oElemento, 'o-activo');
			ghSliders.get(document.getElementsByClassName('slider', oElemento)[0].id).bloquear();
			goIndiceActual = oElemento;
		}

		var iValor = Number(minCero(unFormat($("ti-ahorros").value)));
		goSAhorros.setOldTempValue(iValor);
		$("ti-ahorros").value = formatAsMoney(iValor);
		
		if ($("ti-ahorros").value == "0"){
			Element.addClassName($("ti-ahorros"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-ahorros"), 'valor-cero');
		}
		if (!gbCalculando){gbCalculando = true; calcularFinanciacion(); calcular('slider-ahorros');}
	}, false);
	Event.observe($('ti-ahorros'), 'keypress', function(e){
		var cTecla = e.keyCode || e.which;
		if (!soloNumeros(e, 8, false, true)){Event.stop(e);}
	}, false);
	
/*	// slider Gastos
	goSGastos = new Slider($("slider-gastos"), $("slider-input-gastos"));
	goSGastos.setMinimum(0);
	goSGastos.setMaximum(1500);
	goSGastos.setValue(500);
	goSGastos.setOldValue(500);
	goSGastos.setOldTempValue(500);
	goSGastos.setUnitIncrement(100);
	goSGastos.setBlockIncrement(100);//500
	goSGastos.onchange = function (){
		goSGastos.setOldTempValue(goSGastos.getValue());
		var fValue = goSGastos.getValue() / 100;
		$("ti-gastos").value = fValue.toFixed(0);
		if ($("ti-gastos").value == "0"){
			Element.addClassName($("ti-gastos"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-gastos"), 'valor-cero');
		}
		if (!gbCalculando){gbCalculando = true; calcularFinanciacion(); calcular('slider-gastos');}
	};
	Event.observe($('ti-gastos'), 'change', function(e){
		var fValue = Number($('ti-gastos').value) * 100;
		goSGastos.setValue(minCero(fValue));
		if ($("ti-gastos").value == "0"){
			Element.addClassName($("ti-gastos"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-gastos"), 'valor-cero');
		}
		if (!gbCalculando){gbCalculando = true; calcularFinanciacion(); calcular('slider-gastos');}
	}, false);
	Event.observe($('ti-gastos'), 'keypress', function(e){
		var cTecla = e.keyCode || e.which;
		if ((goSGastos.estaBloqueado() && cTecla != goKeyCodes.TAB) || !soloNumeros(e, 3, false, false)){Event.stop(e);}
	}, false);*/
	// slider Gastos
	goSGastos = new ProxySlider($("ti-gastos"));
	goSGastos.setValue(goSGastosInitValue);
	goSGastos.setOldValue(goSGastosInitValue);
	goSGastos.setOldTempValue(goSGastosInitValue);
	Event.observe($('ti-gastos'), 'change', function(e){
		if (document.getElementsByClassName('o-activo').length == 0){
			// bloqueo del nuevo slider activo
			// activar la cuota
			var oElemento = $('slider-cuota').parentNode.parentNode;
			
			Element.removeClassName(document.getElementsByClassName('boton-calcular', oElemento)[0].getElementsByTagName('DIV')[0], 'desactivado');
			Element.removeClassName(document.getElementsByClassName('boton-calcular', oElemento)[0].getElementsByTagName('DIV')[0], 'hover');
			Element.removeClassName(oElemento, 'fondo-azul');
			Element.addClassName(oElemento, 'o-activo');
			ghSliders.get(document.getElementsByClassName('slider', oElemento)[0].id).bloquear();
			goIndiceActual = oElemento;
		}

		var iValor = minCero($("ti-gastos").value);
		goSGastos.setOldTempValue(iValor);
		$("ti-gastos").value = iValor;
		
		if ($("ti-gastos").value == "0"){
			Element.addClassName($("ti-gastos"), 'valor-cero');
		} else {
			Element.removeClassName($("ti-gastos"), 'valor-cero');
		}
		if (!gbCalculando){gbCalculando = true; calcularFinanciacion(); calcular('slider-gastos');}
	}, false);
	Event.observe($('ti-gastos'), 'keypress', function(e){
		var cTecla = e.keyCode || e.which;
		if (!soloNumeros(e, 3, false, false)){Event.stop(e);}
	}, false);
	
	Event.observe(document.getElementsByClassName('top-arrow', $('o-scroller-gastos'))[0], 'click', function(e){
		$('ti-gastos').value = Number(goSGastos.getValue()) + 1;
		
		Event.cache[$('ti-gastos')._eventID]['change'][0]('change');
		
		/*
		Event.observers.findAll(function(poEventObserver){
			return poEventObserver[0] == $('ti-gastos') && poEventObserver[1] == "change";
		})[0][2]();
		*/
		
		$('ti-gastos').focus();
	}, false);
	Event.observe(document.getElementsByClassName('bottom-arrow', $('o-scroller-gastos'))[0], 'click', function(e){
		var iValor = Number(goSGastos.getValue()) - 1;
		$('ti-gastos').value = (iValor > 0) ? iValor : 0 ;
		
		Event.cache[$('ti-gastos')._eventID]['change'][0]('change');
		
		/*
		Event.observers.findAll(function(poEventObserver){
			return poEventObserver[0] == $('ti-gastos') && poEventObserver[1] == "change";
		})[0][2]();
		*/
		
		$('ti-gastos').focus();
	}, false);

	Element.addClassName($('o-loading'), 'is-hidden');
	Element.removeClassName($('calculadora-hipotecas'), 'is-hidden');

	//	coloco el marcador del euribor
	//	comprobar posicion cuando cambie!!!
	var iPos = Math.round(240 * gfEuribor / 9) - 14;
	$('euribor').style.left = iPos + 'px';
	$('euribor').innerHTML += ' ' + gfEuribor.toString().replace('.', ',');
	document.getElementsByClassName('euriborBar', $('slider-interes'))[0].style.width = (iPos + 2) + 'px';
	document.getElementsByClassName('euriborBar', $('slider-interes'))[0].style.right = (iPos+ 2) + 'px';
	
	
	ghSliders = $H({
		"slider-cuota" : goSCuota,
		"slider-plazo" : goSPlazo,
		"slider-interes" : goSInteres,
		"slider-financiacion" : goSFinanciacion,
		"slider-precio" : goSPrecio
	});
	
	if (document.getElementsByClassName('o-activo', $('form-calc-hipoteca')).length > 0){
		goSCuota.bloquear();
		goIndiceActual = document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0];
	}
	
	gbCalculando = true;

	// si el precio del inmueble es mayor de 1000000, recalcular los maximos
	if (giPrecioInmueble > 5000000){
		var iRatio = giPrecioInmueble / 5000000;
		var iCuotaMaxima = giCuotaMaxima * iRatio * 2;// la cuota aunmenta de una manera no lineal con respecto al precio
		iCuotaMaxima = iCuotaMaxima.toFixed(0);
		var iFinanciacionMaxima = giFinanciacionMaxima * iRatio;
		iFinanciacionMaxima = iFinanciacionMaxima.toFixed(0);
		var iPrecioMaximo = giPrecioMaximo * iRatio;
		iPrecioMaximo = iPrecioMaximo.toFixed(0);
		
		goSCuota.setMaximum(iCuotaMaxima);
//		goSCuota.setValue(iCuotaMaxima);
//		goSCuota.setOldValue(iCuotaMaxima);
//		goSCuota.setOldTempValue(iCuotaMaxima);
		document.getElementsByClassName('maximo', $('slider-cuota').parentNode)[0].innerHTML = formatAsMoney(iCuotaMaxima);
		
		goSFinanciacion.setMaximum(iFinanciacionMaxima);
//		goSFinanciacion.setValue(iFinanciacionMaxima);
//		goSFinanciacion.setOldValue(iFinanciacionMaxima);
//		goSFinanciacion.setOldTempValue(iFinanciacionMaxima);
		document.getElementsByClassName('maximo', $('slider-financiacion').parentNode)[0].innerHTML = formatAsMoney(iFinanciacionMaxima);
		
		goSPrecio.setMaximum(iPrecioMaximo);
		goSPrecio.setValue(iPrecioMaximo);
		goSPrecio.setOldValue(iPrecioMaximo);
		goSPrecio.setOldTempValue(iPrecioMaximo);
		document.getElementsByClassName('maximo', $('slider-precio').parentNode)[0].innerHTML = formatAsMoney(iPrecioMaximo);
		
		calcularFinanciacion();
	}

	// obtiene los valores de las cookies, si fuese necesario:
	if (!getCalcCookies()){// si no tiene los ahorros en las cookies...
		calcularAhorros();
	}
	goSAhorros.setOldValue(Number(unFormat($("ti-ahorros").value)));
	goSAhorros.setOldTempValue(Number(unFormat($("ti-ahorros").value)));
	goSGastos.setOldValue(Number(unFormat($("ti-gastos").value)));
	goSGastos.setOldTempValue(Number(unFormat($("ti-gastos").value)));

	gbCalculando = false;

	calcularFinanciacion();
	calcular();
	// solucionar bug de firefox 2 de 2
	window.setTimeout(function(){$('ti-ahorros').style.borderWidth = '1px';}, 100);
	window.setTimeout(function(){$('ti-gastos').style.borderWidth = '1px';}, 100);
}, false);

Event.observe(window, 'resize', function(){
	recalcular();
}, false);

function recalcular(){
	if (goSCuota.recalculate){goSCuota.recalculate();}
	if (goSPlazo.recalculate){goSPlazo.recalculate();}
	if (goSInteres.recalculate){goSInteres.recalculate();}
	if (goSFinanciacion.recalculate){goSFinanciacion.recalculate();}
	if (goSPrecio.recalculate){goSPrecio.recalculate();}
///	if (goSAhorros.recalculate){goSAhorros.recalculate();}
///	if (goSGastos.recalculate){goSGastos.recalculate();}
}

function calcularPrecio(){
	// se ejecuta antes de calcular()
	// y solo cuando se modifica la financiacion, los ahorros o los gastos de la compra
	var G = parseFloat(unFormat($('ti-gastos').value)); // Gastos compra
	var A = parseFloat(unFormat($('ti-ahorros').value)); // Ahorros iniciales
	var I = parseFloat(unFormat($('ti-financiacion').value)); // importe a financiar
	
	P = (I + A) / (1 + (G/100));
	P = P.toFixed(0);
	$("ti-precio").value = formatAsMoney(P);
	goSPrecio.setValue(P);
}

function calcularAhorros(){
	// se ejecuta antes de calcular()
	// y solo cuando se modifica la financiacion, el precio de la vivienda o los gastos de la compra
	var G = parseFloat(unFormat($('ti-gastos').value)); // Gastos compra
	var P = parseFloat(unFormat($('ti-precio').value));	// Precio de la vivienda
	var I = parseFloat(unFormat($('ti-financiacion').value)); // importe a financiar
	var oSliderActivo = ghSliders.get(document.getElementsByClassName('slider', document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0])[0].id);
	
	A = P * (1 + (G/100)) - I;
	A = A.toFixed(0);
	if (A > 0){
		$("ti-ahorros").value = formatAsMoney(A);
		goSAhorros.setValue(A);
	}
}

function calcularGastos(){
	// se ejecuta antes de calcular()
	// y solo cuando se modifica la financiacion, el precio de la vivienda o los ahorros
	var A = parseFloat(unFormat($('ti-ahorros').value)); // Ahorros iniciales
	var P = parseFloat(unFormat($('ti-precio').value));	// Precio de la vivienda
	var I = parseFloat(unFormat($('ti-financiacion').value)); // importe a financiar
	var oSliderActivo = ghSliders.get(document.getElementsByClassName('slider', document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0])[0].id);
	
	G = (((I + A) / P) - 1) * 100;
	G = G.toFixed(0);
	$("ti-gastos").value = formatAsMoney(G);
	goSGastos.setValue(G);
}

function calcularFinanciacion(){
	// se ejecuta antes de calcular()
	// y solo cuando se modifica el precio de la vivienda, los ahorros o los gastos de la compra
	var G = parseFloat(unFormat($('ti-gastos').value)); // Gastos compra
	var A = parseFloat(unFormat($('ti-ahorros').value)); // Ahorros iniciales
	var P = parseFloat(unFormat($('ti-precio').value));	// Precio de la vivienda
	var oSliderActivo = ghSliders.get(document.getElementsByClassName('slider', document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0])[0].id);

	I = P * (1 + (G/100)) - A;
	I = I.toFixed(0);
	$("ti-financiacion").value = formatAsMoney(I);
	goSFinanciacion.setValue(I);
}

function calcularCuota(){
	var N = parseFloat($('ti-plazo').value); // Anualidades
	var R = parseFloat($('ti-interes').value.replace(',', '.')); // Tipo de interes anual (con euribor incluido)
	var I = parseFloat(unFormat($('ti-financiacion').value)); // importe a financiar
	
	// cuota mensual
    C = Math.round(I*(R/1200)/(1-Math.pow(1+R/1200,-N*12)));
	$("ti-cuota").value = formatAsMoney(C);
	goSCuota.setValue(C);
	
}

function calcular(pbCambiandoSlider){
	var N = parseFloat($('ti-plazo').value); // Anualidades
	var R = parseFloat($('ti-interes').value.replace(',', '.')); // Tipo de interes anual (con euribor incluido)
	var G = parseFloat(unFormat($('ti-gastos').value)); // Gastos compra
	var P = parseFloat(unFormat($('ti-precio').value));	// Precio de la vivienda
	var C = parseFloat(unFormat($('ti-cuota').value)); // Cuota mensual
	var A = parseFloat(unFormat($('ti-ahorros').value)); // Ahorros iniciales
	var I = parseFloat(unFormat($('ti-financiacion').value)); // importe a financiar
	var oSliderActivo = ghSliders.get(document.getElementsByClassName('slider', document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0])[0].id);
	
	// cuota mensual
	if (goSCuota.estaBloqueado()){
	    C = Math.round(I*(R/1200)/(1-Math.pow(1+R/1200,-N*12)));
		$("ti-cuota").value = formatAsMoney(C);
		goSCuota.setValue(C);
		if (goSCuota.getValue() >= goSCuota.getMaximum() || goSCuota.getValue() <= goSCuota.getMinimum()){
			if (document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0].className.indexOf('fade') < 0){
				fadeElement(document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0]);
			}
			goSPlazo.setValue(goSPlazo.getOldValue());
			goSInteres.setValue(goSInteres.getOldValue());
			goSFinanciacion.setValue(goSFinanciacion.getOldValue());
			goSPrecio.setValue(goSPrecio.getOldValue());
			goSAhorros.setValue(goSAhorros.getOldValue());
			goSGastos.setValue(goSGastos.getOldValue());
		} else {
			goSPlazo.setOldValue(goSPlazo.getOldTempValue());
			goSInteres.setOldValue(goSInteres.getOldTempValue());
			goSFinanciacion.setOldValue(goSFinanciacion.getOldTempValue());
			goSPrecio.setOldValue(goSPrecio.getOldTempValue());
			goSAhorros.setOldValue(goSAhorros.getOldTempValue());
			goSGastos.setOldValue(goSGastos.getOldTempValue());
		}
	}
	
	// plazo de la hipoteca
	if (goSPlazo.estaBloqueado()){
		N = encontrarPlazo(R, C/(I/6000));
		$('ti-plazo').value = N;
		goSPlazo.setValue(N*100);
		if (goSPlazo.getValue() >= goSPlazo.getMaximum() || goSPlazo.getValue() <= goSPlazo.getMinimum()){
			if (document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0].className.indexOf('fade') < 0){
				fadeElement(document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0]);
			}
			goSCuota.setValue(goSCuota.getOldValue());
			goSInteres.setValue(goSInteres.getOldValue());
			goSFinanciacion.setValue(goSFinanciacion.getOldValue());
			goSPrecio.setValue(goSPrecio.getOldValue());
			goSAhorros.setValue(goSAhorros.getOldValue());
			goSGastos.setValue(goSGastos.getOldValue());
		} else {
			goSCuota.setOldValue(goSCuota.getOldTempValue());
			goSInteres.setOldValue(goSInteres.getOldTempValue());
			goSFinanciacion.setOldValue(goSFinanciacion.getOldTempValue());
			goSPrecio.setOldValue(goSPrecio.getOldTempValue());
			goSAhorros.setOldValue(goSAhorros.getOldTempValue());
			goSGastos.setOldValue(goSGastos.getOldTempValue());
		}
	}
	
	// tipo de interes
	if (goSInteres.estaBloqueado()){
		R = encontrarInteres(N, C/(I/6000));
		$('ti-interes').value = R.toString().replace('.', ',');
		goSInteres.setValue(R*100);
		if (goSInteres.getValue() >= goSInteres.getMaximum() || goSInteres.getValue() <= goSInteres.getMinimum()){
			if (document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0].className.indexOf('fade') < 0){
				fadeElement(document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0]);
			}
			goSCuota.setValue(goSCuota.getOldValue());
			goSPlazo.setValue(goSPlazo.getOldValue());
			goSFinanciacion.setValue(goSFinanciacion.getOldValue());
			goSPrecio.setValue(goSPrecio.getOldValue());
			goSAhorros.setValue(goSAhorros.getOldValue());
			goSGastos.setValue(goSGastos.getOldValue());
		} else {
			goSCuota.setOldValue(goSCuota.getOldTempValue());
			goSPlazo.setOldValue(goSPlazo.getOldTempValue());
			goSFinanciacion.setOldValue(goSFinanciacion.getOldTempValue());
			goSPrecio.setOldValue(goSPrecio.getOldTempValue());
			goSAhorros.setOldValue(goSAhorros.getOldTempValue());
			goSGastos.setOldValue(goSGastos.getOldTempValue());
		}
	}
	
	// importe a financiar
	if (goSFinanciacion.estaBloqueado()){
		//if (pbCambiandoSlider != 'slider-financiacion'){
		if (pbCambiandoSlider != 'slider-precio' && pbCambiandoSlider != 'slider-ahorros' && pbCambiandoSlider != 'slider-gastos'){
		    I = Math.round(C*((1-Math.pow(1+R/1200,-N*12))/(R/1200)));
			$("ti-financiacion").value = formatAsMoney(I);
			goSFinanciacion.setValue(I);
			calcularPrecio();
		} else {
			I = P * (1 + (G/100)) - A;
			I = I.toFixed(0);
			$("ti-financiacion").value = formatAsMoney(I);
			goSFinanciacion.setValue(I);
		}
		if (goSFinanciacion.getValue() >= goSFinanciacion.getMaximum() || goSFinanciacion.getValue() <= goSFinanciacion.getMinimum()){
			if (document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0].className.indexOf('fade') < 0){
				fadeElement(document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0]);
			}
			goSCuota.setValue(goSCuota.getOldValue());
			goSPlazo.setValue(goSPlazo.getOldValue());
			goSInteres.setValue(goSInteres.getOldValue());
			goSPrecio.setValue(goSPrecio.getOldValue());
			goSAhorros.setValue(goSAhorros.getOldValue());
			goSGastos.setValue(goSGastos.getOldValue());
		} else {
			goSCuota.setOldValue(goSCuota.getOldTempValue());
			goSPlazo.setOldValue(goSPlazo.getOldTempValue());
			goSInteres.setOldValue(goSInteres.getOldTempValue());
			goSPrecio.setOldValue(goSPrecio.getOldTempValue());
			goSAhorros.setOldValue(goSAhorros.getOldTempValue());
			goSGastos.setOldValue(goSGastos.getOldTempValue());
		}
	}
	
	// precio de la vivienda
	if (!goSFinanciacion.estaBloqueado() && goSPrecio.estaBloqueado()){
		// previo: financiacion
		if (oSliderActivo != goSFinanciacion && pbCambiandoSlider != 'slider-financiacion'){
			I = Math.round(C*((1-Math.pow(1+R/1200,-N*12))/(R/1200)));
			$("ti-financiacion").value = formatAsMoney(I);
			goSFinanciacion.setValue(I);
		}// fin financiacion
		P = (I + A) / (1 + (G/100));
		P = P.toFixed(0);
		$("ti-precio").value = formatAsMoney(P);
		goSPrecio.setValue(P);
		if (goSPrecio.getValue() >= goSPrecio.getMaximum() || goSPrecio.getValue() <= goSPrecio.getMinimum()){
			if (document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0].className.indexOf('fade') < 0){
				fadeElement(document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0]);
			}
			goSCuota.setValue(goSCuota.getOldValue());
			goSPlazo.setValue(goSPlazo.getOldValue());
			goSInteres.setValue(goSInteres.getOldValue());
			goSFinanciacion.setValue(goSFinanciacion.getOldValue());
			goSAhorros.setValue(goSAhorros.getOldValue());
			goSGastos.setValue(goSGastos.getOldValue());
		} else {
			goSCuota.setOldValue(goSCuota.getOldTempValue());
			goSPlazo.setOldValue(goSPlazo.getOldTempValue());
			goSInteres.setOldValue(goSInteres.getOldTempValue());
			goSFinanciacion.setOldValue(goSFinanciacion.getOldTempValue());
			goSAhorros.setOldValue(goSAhorros.getOldTempValue());
			goSGastos.setOldValue(goSGastos.getOldTempValue());
		}
	}
	
/*	// ahorros iniciales
	if (!goSFinanciacion.estaBloqueado() && goSAhorros.estaBloqueado()){
		// previo: financiacion
		if (oSliderActivo != goSFinanciacion && pbCambiandoSlider != 'slider-financiacion'){
			I = Math.round(C*((1-Math.pow(1+R/1200,-N*12))/(R/1200)));
			$("ti-financiacion").value = formatAsMoney(I);
			goSFinanciacion.setValue(I);
		}// fin financiacion
		A = P * (1 + (G/100)) - I;
		A = A.toFixed(0);
		$("ti-ahorros").value = formatAsMoney(A);
		goSAhorros.setValue(A);
		if (goSAhorros.getValue() >= goSAhorros.getMaximum() || goSAhorros.getValue() <= goSAhorros.getMinimum()){
			if (document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0].className.indexOf('fade') < 0){
				fadeElement(document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0]);
			}
			goSCuota.setValue(goSCuota.getOldValue());
			goSPlazo.setValue(goSPlazo.getOldValue());
			goSInteres.setValue(goSInteres.getOldValue());
			goSFinanciacion.setValue(goSFinanciacion.getOldValue());
			goSPrecio.setValue(goSPrecio.getOldValue());
			goSGastos.setValue(goSGastos.getOldValue());
		} else {
			goSCuota.setOldValue(goSCuota.getOldTempValue());
			goSPlazo.setOldValue(goSPlazo.getOldTempValue());
			goSInteres.setOldValue(goSInteres.getOldTempValue());
			goSFinanciacion.setOldValue(goSFinanciacion.getOldTempValue());
			goSPrecio.setOldValue(goSPrecio.getOldTempValue());
			goSGastos.setOldValue(goSGastos.getOldTempValue());
		}
	}*/
	
/*	// gastos de la compra
	if (!goSFinanciacion.estaBloqueado() && goSGastos.estaBloqueado()){
		// previo: financiacion
		if (oSliderActivo != goSFinanciacion && pbCambiandoSlider != 'slider-financiacion'){
			I = Math.round(C*((1-Math.pow(1+R/1200,-N*12))/(R/1200)));
			$("ti-financiacion").value = formatAsMoney(I);
			goSFinanciacion.setValue(I);
		}// fin financiacion
		if (P == 0){// podria dar "infinity"
			G = 15;
		} else {
			G = (((I + A) / P) - 1) * 100;
			G = G.toFixed(0);
			G = (G < 0) ? 0 : G;
		}
		$("ti-gastos").value = G;
		goSGastos.setValue(G * 100);
		if (goSGastos.getValue() >= goSGastos.getMaximum() || goSGastos.getValue() <= goSGastos.getMinimum()){
			if (document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0].className.indexOf('fade') < 0){
				fadeElement(document.getElementsByClassName('o-activo', $('form-calc-hipoteca'))[0]);
			}
			goSCuota.setValue(goSCuota.getOldValue());
			goSPlazo.setValue(goSPlazo.getOldValue());
			goSInteres.setValue(goSInteres.getOldValue());
			goSFinanciacion.setValue(goSFinanciacion.getOldValue());
			goSPrecio.setValue(goSPrecio.getOldValue());
			goSAhorros.setValue(goSAhorros.getOldValue());
		} else {
			goSCuota.setOldValue(goSCuota.getOldTempValue());
			goSPlazo.setOldValue(goSPlazo.getOldTempValue());
			goSInteres.setOldValue(goSInteres.getOldTempValue());
			goSFinanciacion.setOldValue(goSFinanciacion.getOldTempValue());
			goSPrecio.setOldValue(goSPrecio.getOldTempValue());
			goSAhorros.setOldValue(goSAhorros.getOldTempValue());
		}
	}*/
	
	// limpio los estilos de los valores cero
	var aInputsValor = $A(document.getElementsByClassName('valor', $('form-calc-hipoteca')));
	
	aInputsValor.each(function(poElemento){
		if (poElemento.value == "0"){
			Element.addClassName(poElemento, 'valor-cero');
		} else {
			Element.removeClassName(poElemento, 'valor-cero');
		}
	});
	
	// recalculo la cuota, en el caso de que se haya modificado el importe a financiar:
	if (oSliderActivo != goSCuota && oSliderActivo != goSPlazo && oSliderActivo != goSInteres
		 && (pbCambiandoSlider == 'slider-financiacion' || pbCambiandoSlider == 'slider-precio' || pbCambiandoSlider == 'slider-ahorros' || pbCambiandoSlider == 'slider-gastos')){
		calcularCuota();
	}
	
	// retardo de 10 milisegundos para guardar las cookies:
	window.setTimeout(setCalcCookies, 100);
	
	gbCalculando = false;
}

//	guarda en las cookies los valores seleccionados por el usuario
function setCalcCookies(){
	// formato: GuardaCookie(nombre, valor, caducidad)
	if (!gbCalculando){
		GuardaCookie('plazoCookie', $('ti-plazo').value, 30);
		GuardaCookie('tipoCookie', $('ti-interes').value.replace(',', '.'), 30);
		GuardaCookie('gastosCookie', $('ti-gastos').value, 30);
		GuardaCookie('ahorrosCookie', $('ti-ahorros').value.replace('.', ''), 30);
	} else {
		window.setTimeout(setCalcCookies, 100);
	}
}

//	lee los valores por defecto de las cookies
function getCalcCookies(){
	if (obtieneCookie("plazoCookie") == null || obtieneCookie("plazoCookie") == ""){
		addCookie(30, "plazoCookie");
		addCookie(4.00, "tipoCookie");
		addCookie(0, "gastosCookie");
		addCookie(0, "ahorrosCookie");
		addCookie("T", "personalizada");
		
		return false;
	} else {
		goSPlazo.setValue(obtieneCookie("plazoCookie") * 100);
		goSInteres.setValue(Number(obtieneCookie("tipoCookie") * 100).toFixed(0));
///		goSGastos.setValue(obtieneCookie("gastosCookie") * 100);
		goSGastos.setValue(obtieneCookie("gastosCookie"));
		goSAhorros.setValue(obtieneCookie("ahorrosCookie"));
		
		return true;
	}
}

function minCero(pcValor){
	return (pcValor == "") ? "0" : pcValor;
}

function unFormat(pcValor){
	return pcValor.replace('.', '').replace('.', '').replace('.', '').replace(',', '').replace(',', '');
}

function formatAsMoney(valor){
	var puntos;
	var resultado = "";
	cadena = String(valor).replace('.', '');
	puntos = cadena.length;
	var j=0;
	for (i=puntos;i>0;i--){
		if (((j % 3)==0) && (j!=0))	{
			resultado = "." + resultado;
		}
		j++;
		append = cadena.substring(i-1,i);
		resultado = append + resultado;
	}
	return resultado;
}


function formatAsPercentage(piValor){
	var iValor = piValor / 100;
	iValor = iValor.toFixed(2);
	var cValor = iValor + '';
	
	return cValor.replace('.', ',');
}

/*----------------------------------------------------------------------------\
|                                Range Class                                  |
|-----------------------------------------------------------------------------|
|                         Created by Erik Arvidsson                           |
|                  (http://webfx.eae.net/contact.html#erik)                   |
|                      For WebFX (http://webfx.eae.net/)                      |
|-----------------------------------------------------------------------------|
| Used to model the data used when working with sliders, scrollbars and       |
| progress bars. Based on the ideas of the javax.swing.BoundedRangeModel      |
| interface defined by Sun for Java. http://java.sun.com/products/jfc/        |
| swingdoc-api-1.0.3/com/sun/java/swing/BoundedRangeModel.html                |                                                              |
|-----------------------------------------------------------------------------|
|                  Copyright (c) 1999 - 2002 Erik Arvidsson                   |
|-----------------------------------------------------------------------------|
| This software is provided "as is", without warranty of any kind, express or |
| implied, including  but not limited  to the warranties of  merchantability, |
| fitness for a particular purpose and noninfringement. In no event shall the |
| authors or  copyright  holders be  liable for any claim,  damages or  other |
| liability, whether  in an  action of  contract, tort  or otherwise, arising |
| from,  out of  or in  connection with  the software or  the  use  or  other |
| dealings in the software.                                                   |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| This  software is  available under the  three different licenses  mentioned |
| below.  To use this software you must chose, and qualify, for one of those. |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Non-Commercial License          http://webfx.eae.net/license.html |
| Permits  anyone the right to use the  software in a  non-commercial context |
| free of charge.                                                             |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Commercial license           http://webfx.eae.net/commercial.html |
| Permits the  license holder the right to use  the software in a  commercial |
| context. Such license must be specifically obtained, however it's valid for |
| any number of  implementations of the licensed software.                    |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| GPL - The GNU General Public License    http://www.gnu.org/licenses/gpl.txt |
| Permits anyone the right to use and modify the software without limitations |
| as long as proper  credits are given  and the original  and modified source |
| code are included. Requires  that the final product, software derivate from |
| the original  source or any  software  utilizing a GPL  component, such  as |
| this, is also licensed under the GPL license.                               |
|-----------------------------------------------------------------------------|
| 2002-10-14 | Original version released                                      |
|-----------------------------------------------------------------------------|
| Created 2002-10-14 | All changes are in the log above. | Updated 2002-10-14 |
\----------------------------------------------------------------------------*/

// Range object
function Range() {
	this._value = 0;
	this._minimum = 0;
	this._maximum = 101;
	this._extent = 0;
	
	this._isChanging = false;
}

Range.prototype.setValue = function (value) {
	value = parseInt(value);
	if (isNaN(value)) return;
	if (this._value != value) {
		if (value + this._extent > this._maximum)
			this._value = this._maximum - this._extent;
		else if (value < this._minimum)
			this._value = this._minimum;
		else
			this._value = value;
		if (!this._isChanging && typeof this.onchange == "function")
			 this.onchange();
	}
};

Range.prototype.getValue = function () {
	return this._value;
};

Range.prototype.setExtent = function (extent) {
	if (this._extent != extent) {
		if (extent < 0)
			this._extent = 0;
		else if (this._value + extent > this._maximum)
			this._extent = this._maximum - this._value;
		else
			this._extent = extent;
		if (!this._isChanging && typeof this.onchange == "function")
			this.onchange();
	}
};

Range.prototype.getExtent = function () {
	return this._extent;
};

Range.prototype.setMinimum = function (minimum) {
	if (this._minimum != minimum) {
		var oldIsChanging = this._isChanging;
		this._isChanging = true;

		this._minimum = minimum;
		
		if (minimum > this._value)
			this.setValue(minimum);
		if (minimum > this._maximum) {
			this._extent = 0;
			this.setMaximum(minimum);
			this.setValue(minimum)
		}
		if (minimum + this._extent > this._maximum)
			this._extent = this._maximum - this._minimum;

		this._isChanging = oldIsChanging;
		if (!this._isChanging && typeof this.onchange == "function")
			this.onchange();
	}
};

Range.prototype.getMinimum = function () {
	return this._minimum;
};

Range.prototype.setMaximum = function (maximum) {
	if (this._maximum != maximum) {
		var oldIsChanging = this._isChanging;
		this._isChanging = true;

		this._maximum = maximum;		
		
		if (maximum < this._value)
			this.setValue(maximum - this._extent);
		if (maximum < this._minimum) {
			this._extent = 0;
			this.setMinimum(maximum);
			this.setValue(this._maximum);
		}		
		if (maximum < this._minimum + this._extent)
			this._extent = this._maximum - this._minimum;
		if (maximum < this._value + this._extent)
			this._extent = this._maximum - this._value;
		
		this._isChanging = oldIsChanging;
		if (!this._isChanging && typeof this.onchange == "function")
			this.onchange();
	}
};

Range.prototype.getMaximum = function () {
	return this._maximum;
};

/*----------------------------------------------------------------------------\
|                                 Timer Class                                 |
|-----------------------------------------------------------------------------|
|                         Created by Erik Arvidsson                           |
|                  (http://webfx.eae.net/contact.html#erik)                   |
|                      For WebFX (http://webfx.eae.net/)                      |
|-----------------------------------------------------------------------------|
| Object Oriented Encapsulation of setTimeout fires ontimer when the timer    |
| is triggered. Does not work in IE5.00                                       |                     
|-----------------------------------------------------------------------------|
|                  Copyright (c) 1999 - 2002 Erik Arvidsson                   |
|-----------------------------------------------------------------------------|
| This software is provided "as is", without warranty of any kind, express or |
| implied, including  but not limited  to the warranties of  merchantability, |
| fitness for a particular purpose and noninfringement. In no event shall the |
| authors or  copyright  holders be  liable for any claim,  damages or  other |
| liability, whether  in an  action of  contract, tort  or otherwise, arising |
| from,  out of  or in  connection with  the software or  the  use  or  other |
| dealings in the software.                                                   |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| This  software is  available under the  three different licenses  mentioned |
| below.  To use this software you must chose, and qualify, for one of those. |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Non-Commercial License          http://webfx.eae.net/license.html |
| Permits  anyone the right to use the  software in a  non-commercial context |
| free of charge.                                                             |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Commercial license           http://webfx.eae.net/commercial.html |
| Permits the  license holder the right to use  the software in a  commercial |
| context. Such license must be specifically obtained, however it's valid for |
| any number of  implementations of the licensed software.                    |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| GPL - The GNU General Public License    http://www.gnu.org/licenses/gpl.txt |
| Permits anyone the right to use and modify the software without limitations |
| as long as proper  credits are given  and the original  and modified source |
| code are included. Requires  that the final product, software derivate from |
| the original  source or any  software  utilizing a GPL  component, such  as |
| this, is also licensed under the GPL license.                               |
|-----------------------------------------------------------------------------|
| 2002-10-14 | Original version released                                      |
|-----------------------------------------------------------------------------|
| Created 2002-10-14 | All changes are in the log above. | Updated 2002-10-14 |
\----------------------------------------------------------------------------*/

// Timer object
function Timer(nPauseTime) {
	this._pauseTime = typeof nPauseTime == "undefined" ? 1000 : nPauseTime;
	this._timer = null;
	this._isStarted = false;
}

Timer.prototype.start = function () {
	if (this.isStarted())
		this.stop();
	var oThis = this;
	this._timer = window.setTimeout(function () {
		if (typeof oThis.ontimer == "function")
			oThis.ontimer();
	}, this._pauseTime);
	this._isStarted = false;
};

Timer.prototype.stop = function () {
	if (this._timer != null)
		window.clearTimeout(this._timer);
	this._isStarted = false;
};

Timer.prototype.isStarted = function () {
	return this._isStarted;
};

Timer.prototype.getPauseTime = function () {
	return this._pauseTime;
};

Timer.prototype.setPauseTime = function (nPauseTime) {
	this._pauseTime = nPauseTime;
};

/*----------------------------------------------------------------------------\
|                                Slider 1.02                                  |
|-----------------------------------------------------------------------------|
|                         Created by Erik Arvidsson                           |
|                  (http://webfx.eae.net/contact.html#erik)                   |
|                      For WebFX (http://webfx.eae.net/)                      |
|-----------------------------------------------------------------------------|
| A slider control that degrades to an input control for non supported        |
| browsers.                                                                   |
|-----------------------------------------------------------------------------|
|                  Copyright (c) 1999 - 2002 Erik Arvidsson                   |
|-----------------------------------------------------------------------------|
| This software is provided "as is", without warranty of any kind, express or |
| implied, including  but not limited  to the warranties of  merchantability, |
| fitness for a particular purpose and noninfringement. In no event shall the |
| authors or  copyright  holders be  liable for any claim,  damages or  other |
| liability, whether  in an  action of  contract, tort  or otherwise, arising |
| from,  out of  or in  connection with  the software or  the  use  or  other |
| dealings in the software.                                                   |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| This  software is  available under the  three different licenses  mentioned |
| below.  To use this software you must chose, and qualify, for one of those. |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Non-Commercial License          http://webfx.eae.net/license.html |
| Permits  anyone the right to use the  software in a  non-commercial context |
| free of charge.                                                             |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| The WebFX Commercial license           http://webfx.eae.net/commercial.html |
| Permits the  license holder the right to use  the software in a  commercial |
| context. Such license must be specifically obtained, however it's valid for |
| any number of  implementations of the licensed software.                    |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| GPL - The GNU General Public License    http://www.gnu.org/licenses/gpl.txt |
| Permits anyone the right to use and modify the software without limitations |
| as long as proper  credits are given  and the original  and modified source |
| code are included. Requires  that the final product, software derivate from |
| the original  source or any  software  utilizing a GPL  component, such  as |
| this, is also licensed under the GPL license.                               |
|-----------------------------------------------------------------------------|
| 2002-10-14 | Original version released                                      |
| 2003-03-27 | Added a test in the constructor for missing oElement arg       |
| 2003-11-27 | Only use mousewheel when focused                               |
|-----------------------------------------------------------------------------|
| Dependencies: timer.js - an OO abstraction of timers                        |
|               range.js - provides the data model for the slider             |
|               winclassic.css or any other css file describing the look      |
|-----------------------------------------------------------------------------|
| Created 2002-10-14 | All changes are in the log above. | Updated 2003-1-27 |
\----------------------------------------------------------------------------*/


Slider.isSupported = typeof document.createElement != "undefined" &&
	typeof document.documentElement != "undefined" &&
	typeof document.documentElement.offsetWidth == "number";

// Slider object
function Slider(oElement, oInput, sOrientation, pbEuriborBar) {
	if (!oElement) return;
	this._orientation = sOrientation || "horizontal";
	this._range = new Range();
	this._range.setExtent(0);
	this._blockIncrement = 10;
	this._unitIncrement = 1;
	this._timer = new Timer(0);
	

	if (Slider.isSupported && oElement) {

		this.document = oElement.ownerDocument || oElement.document;

		this.element = oElement;
		this.element.slider = this;
		this.element.unselectable = "on";

		// add class name tag to class name
		this.element.className = this._orientation + " " + this.classNameTag + " " + this.element.className;

		// create line
		this.line = this.document.createElement("DIV");
		this.line.className = "line";
		this.line.unselectable = "on";
		this.line.appendChild(this.document.createElement("DIV"));
		this.element.appendChild(this.line);

		// create handle
		this.handle = this.document.createElement("DIV");
		this.handle.className = "handle";
		this.handle.unselectable = "on";
		this.handle.appendChild(this.document.createElement("DIV"));
		this.handle.firstChild.appendChild(this.document.createTextNode(String.fromCharCode(160)));
		this.element.appendChild(this.handle);
		
		// create handleBar
		this.handleBar = this.document.createElement("DIV");
		this.handleBar.className = "handleBar";
		this.handleBar.unselectable = "on";
		this.handleBar.appendChild(this.document.createElement("DIV"));
		this.handleBar.firstChild.appendChild(this.document.createTextNode(String.fromCharCode(160)));
		this.element.appendChild(this.handleBar);
		
		if (pbEuriborBar){
			// create euriborBar
			this.euriborBar = this.document.createElement("DIV");
			this.euriborBar.className = "euriborBar";
			this.euriborBar.unselectable = "on";
			this.euriborBar.appendChild(this.document.createElement("DIV"));
			this.euriborBar.firstChild.appendChild(this.document.createTextNode(String.fromCharCode(160)));
			this.element.appendChild(this.euriborBar);
		}
	}

	this.input = oInput;

	// events
	var oThis = this;
	this._range.onchange = function () {
		oThis.recalculate();
		if (typeof oThis.onchange == "function")
			oThis.onchange();
	};

	if (Slider.isSupported && oElement) {
		this.element.onfocus		= Slider.eventHandlers.onfocus;
		this.element.onblur			= Slider.eventHandlers.onblur;
		this.element.onmousedown	= Slider.eventHandlers.onmousedown;
		this.element.onmouseover	= Slider.eventHandlers.onmouseover;
		this.element.onmouseout		= Slider.eventHandlers.onmouseout;
		this.element.onkeydown		= Slider.eventHandlers.onkeydown;
		this.element.onkeypress		= Slider.eventHandlers.onkeypress;
		this.element.onmousewheel	= Slider.eventHandlers.onmousewheel;
		this.handle.onselectstart	=
		this.element.onselectstart	= function () { return false; };

		this._timer.ontimer = function () {
			oThis.ontimer();
		};

		// extra recalculate for ie
		window.setTimeout(function() {
			oThis.recalculate();
		}, 1);
	}
	else {
		this.input.onchange = function (e) {
			oThis.setValue(oThis.input.value);
		};
	}
}

Slider.eventHandlers = {

	// helpers to make events a bit easier
	getEvent:	function (e, el) {
		if (!e) {
			if (el)
				e = el.document.parentWindow.event;
			else
				e = window.event;
		}
		if (!e.srcElement) {
			var el = e.target;
			while (el != null && el.nodeType != 1)
				el = el.parentNode;
			e.srcElement = el;
		}
		if (typeof e.offsetX == "undefined") {
			e.offsetX = e.layerX;
			e.offsetY = e.layerY;
		}

		return e;
	},

	getDocument:	function (e) {
		if (e.target)
			return e.target.ownerDocument;
		return e.srcElement.document;
	},

	getSlider:	function (e) {
		var el = e.target || e.srcElement;
		while (el != null && el.slider == null)	{
			el = el.parentNode;
		}
		if (el)
			return el.slider;
		return null;
	},

	getLine:	function (e) {
		var el = e.target || e.srcElement;
		while (el != null && el.className != "line")	{
			el = el.parentNode;
		}
		return el;
	},

	getHandle:	function (e) {
		var el = e.target || e.srcElement;
		var re = /handle/;
		while (el != null && !re.test(el.className))	{
			el = el.parentNode;
		}
		return el;
	},

	getHandleBar:	function (e) {
		var el = e.target || e.srcElement;
		var re = /handleBar/;
		while (el != null && !re.test(el.className))	{
			el = el.parentNode;
		}
		return el;
	},
	// end helpers

	onfocus:	function (e) {
		var s = this.slider;
		if(!s._bloqueado){
			s._focused = true;
			s.handle.className = "handle hover";
		} else {return false;}
	},

	onblur:	function (e) {
		var s = this.slider;
		if(!s._bloqueado){
			s._focused = false;
			s.handle.className = "handle";
		} else {return false;}
	},

	onmouseover:	function (e) {
		e = Slider.eventHandlers.getEvent(e, this);
		var s = this.slider;
		if(!s._bloqueado){
			if (e.srcElement == s.handle)
				s.handle.className = "handle hover";
		} else {return false;}
	},

	onmouseout:	function (e) {
		e = Slider.eventHandlers.getEvent(e, this);
		var s = this.slider;
		if(!s._bloqueado){
			if (e.srcElement == s.handle && !s._focused)
				s.handle.className = "handle";
		} else {return false;}
	},

	onmousedown:	function (e) {
//alert('Slider mousedown');
		e = Slider.eventHandlers.getEvent(e, this);
		var s = this.slider;
		if(!s._bloqueado){
			$A(document.getElementsByClassName('handleBar', $('form-calc-hipoteca'))).each(function(poElemento){
				if (!Element.hasClassName(poElemento.parentNode.parentNode.parentNode, 'o-activo')){
					Element.removeClassName(document.getElementsByClassName('alerta', $('form-calc-hipoteca'))[0], 'alerta');
					Element.removeClassName(document.getElementsByClassName('mod-opacidad', $('form-calc-hipoteca'))[0], 'mod-opacidad');
				}
			});
			if (s.element.focus)
				s.element.focus();
	
			Slider._currentInstance = s;
			var doc = s.document;
	
			if (doc.addEventListener) {
				doc.addEventListener("mousemove", Slider.eventHandlers.onmousemove, true);
				doc.addEventListener("mouseup", Slider.eventHandlers.onmouseup, true);
			}
			else if (doc.attachEvent) {
				doc.attachEvent("onmousemove", Slider.eventHandlers.onmousemove);
				doc.attachEvent("onmouseup", Slider.eventHandlers.onmouseup);
				doc.attachEvent("onlosecapture", Slider.eventHandlers.onmouseup);
				s.element.setCapture();
			}
	
			if (Slider.eventHandlers.getHandleBar(e)) {// start drag
				s._mouseX = s.handleBar.offsetLeft - e.screenX;
				s._mouseY = s.handleBar.offsetTop - e.screenY;
				s._increasing = null;
				s.ontimer();
			} else if (Slider.eventHandlers.getHandle(e)) {// start drag
				//	control de tiempos, para retardar la llamada entre drag y drag
				var dFecha = new Date();
				Slider._sliderDragData = {
					screenX:	e.screenX,
					screenY:	e.screenY,
					dx:			e.screenX - s.handle.offsetLeft,
					dy:			e.screenY - s.handle.offsetTop,
					startValue:	s.getValue(),
					slider:		s
				};
			}
			else {
				var lineEl = Slider.eventHandlers.getLine(e);
				s._mouseX = e.offsetX + (lineEl ? s.line.offsetLeft : 0);
				s._mouseY = e.offsetY + (lineEl ? s.line.offsetTop : 0);
				s._increasing = null;
				s.ontimer();
			}
		} else {
			var lineEl = s.line;
			
			Element.addClassName(document.getElementsByClassName('boton-calcular', lineEl.parentNode.parentNode.parentNode)[0].getElementsByTagName('SPAN')[0], 'alerta');
			Element.addClassName(document.getElementsByClassName('alerta')[0].parentNode.parentNode.parentNode, 'mod-opacidad');
			if (Element.hasClassName(lineEl.parentNode.parentNode.parentNode, 'o-activo') && lineEl.parentNode.parentNode.parentNode.className.indexOf('fade') < 0){
				fadeElement(document.getElementsByClassName('alerta', lineEl.parentNode.parentNode.parentNode)[0]);
			}

			return false;
		}
	},

	onmousemove:	function (e) {
		e = Slider.eventHandlers.getEvent(e, this);
		if (Slider._sliderDragData) {	// drag
			var s = Slider._sliderDragData.slider;
			if(!s._bloqueado){
				var boundSize = s.getMaximum() - s.getMinimum();
				var size, pos, reset;
	
				if (s._orientation == "horizontal") {
					size = s.element.offsetWidth - s.handle.offsetWidth;
					pos = e.screenX - Slider._sliderDragData.dx;
					reset = Math.abs(e.screenY - Slider._sliderDragData.screenY) > 100;
				}
				else {
					size = s.element.offsetHeight - s.handle.offsetHeight;
					pos = s.element.offsetHeight - s.handle.offsetHeight -
						(e.screenY - Slider._sliderDragData.dy);
					reset = Math.abs(e.screenX - Slider._sliderDragData.screenX) > 100;
				}
//				ORIGINAL:
//				s.setValue(reset ? Slider._sliderDragData.startValue :	s.getMinimum() + boundSize * pos / size);
//				NUEVO:
				var iValor = (s.getMinimum() + boundSize * pos / size) / s.getUnitIncrement();
				iValor = iValor.toFixed(0) * s.getUnitIncrement();
				iValor = reset ? Slider._sliderDragData.startValue : iValor;
				s.setValue(iValor);
//				FIN NUEVO
				return false;
			} else {
				return false;
			}
		} else {
			var s = Slider._currentInstance;
			if (s != null) {
				if(!s._bloqueado){
					var lineEl = Slider.eventHandlers.getLine(e);
					s._mouseX = e.offsetX + (lineEl ? s.line.offsetLeft : 0);
					s._mouseY = e.offsetY + (lineEl ? s.line.offsetTop : 0);
				}
			}
		}
	},

	onmouseup:	function (e) {
		e = Slider.eventHandlers.getEvent(e, this);
		var s = Slider._currentInstance;
		if(s && !s._bloqueado){
			var doc = s.document;
			if (doc.removeEventListener) {
				doc.removeEventListener("mousemove", Slider.eventHandlers.onmousemove, true);
				doc.removeEventListener("mouseup", Slider.eventHandlers.onmouseup, true);
			}
			else if (doc.detachEvent) {
				doc.detachEvent("onmousemove", Slider.eventHandlers.onmousemove);
				doc.detachEvent("onmouseup", Slider.eventHandlers.onmouseup);
				doc.detachEvent("onlosecapture", Slider.eventHandlers.onmouseup);
				s.element.releaseCapture();
			}
	
			if (Slider._sliderDragData) {	// end drag
				Slider._sliderDragData = null;
			}
			else {
				s._timer.stop();
				s._increasing = null;
			}
			Slider._currentInstance = null;
		} else {return false;}
	},

	onkeydown:	function (e) {
		e = Slider.eventHandlers.getEvent(e, this);
		var s = this.slider;
		if(!s._bloqueado){
			var kc = e.keyCode;
			switch (kc) {
				case 33:	// page up
					s.setValue(s.getValue() + s.getBlockIncrement());
					break;
				case 34:	// page down
					s.setValue(s.getValue() - s.getBlockIncrement());
					break;
				case 35:	// end
					s.setValue(s.getOrientation() == "horizontal" ?
						s.getMaximum() :
						s.getMinimum());
					break;
				case 36:	// home
					s.setValue(s.getOrientation() == "horizontal" ?
						s.getMinimum() :
						s.getMaximum());
					break;
				case 38:	// up
				case 39:	// right
					s.setValue(s.getValue() + s.getUnitIncrement());
					break;
	
				case 37:	// left
				case 40:	// down
					s.setValue(s.getValue() - s.getUnitIncrement());
					break;
			}
	
			if (kc >= 33 && kc <= 40) {
				return false;
			}
		} else {return false;}
	},

	onkeypress:	function (e) {
		e = Slider.eventHandlers.getEvent(e, this);
		var s = this.slider;
		if(!s._bloqueado){
			var kc = e.keyCode;
			if (kc >= 33 && kc <= 40) {
				return false;
			}
		} else {return false;}
	},

	onmousewheel:	function (e) {
		e = Slider.eventHandlers.getEvent(e, this);
		var s = this.slider;
		if(!s._bloqueado){
			if (s._focused) {
				s.setValue(s.getValue() + e.wheelDelta / 120 * s.getUnitIncrement());
				// windows inverts this on horizontal sliders. That does not
				// make sense to me
				return false;
			}
		} else {return false;}
	}
};

Slider.prototype.classNameTag = "dynamic-slider-control",

Slider.prototype.setValue = function (v) {
	this._range.setValue(v);
	this.input.value = this.getValue();
};

Slider.prototype.getValue = function () {
	return this._range.getValue();
};

Slider.prototype.setMinimum = function (v) {
	this._range.setMinimum(v);
	this.input.value = this.getValue();
};

Slider.prototype.getMinimum = function () {
	return this._range.getMinimum();
};

Slider.prototype.setMaximum = function (v) {
	this._range.setMaximum(v);
	this.input.value = this.getValue();
};

Slider.prototype.getMaximum = function () {
	return this._range.getMaximum();
};

Slider.prototype.setUnitIncrement = function (v) {
	this._unitIncrement = v;
};

Slider.prototype.getUnitIncrement = function () {
	return this._unitIncrement;
};

Slider.prototype.setBlockIncrement = function (v) {
	this._blockIncrement = v;
};

Slider.prototype.getBlockIncrement = function () {
	return this._blockIncrement;
};

Slider.prototype.getOrientation = function () {
	return this._orientation;
};

Slider.prototype.setOrientation = function (sOrientation) {
	if (sOrientation != this._orientation) {
		if (Slider.isSupported && this.element) {
			// add class name tag to class name
			this.element.className = this.element.className.replace(this._orientation,
									sOrientation);
		}
		this._orientation = sOrientation;
		this.recalculate();

	}
};

Slider.prototype.recalculate = function() {
	if (!Slider.isSupported || !this.element) return;

	var w = this.element.offsetWidth;
	var h = this.element.offsetHeight;
	var hw = this.handle.offsetWidth;
	var hh = this.handle.offsetHeight;
	var lw = this.line.offsetWidth;
	var lh = this.line.offsetHeight;

	// this assumes a border-box layout

	if (this._orientation == "horizontal") {
		this.handle.style.left = (w - hw) * (this.getValue() - this.getMinimum()) /	(this.getMaximum() - this.getMinimum()) + "px";
		this.handle.style.top = (h - hh) / 2 + "px";
		var iHandleBarInset = (browser.isIE55 || browser.isIE6up) ? 396: 394;
		this.handleBar.style.left = ((w - hw) * (this.getValue() - this.getMinimum()) /	(this.getMaximum() - this.getMinimum()) - iHandleBarInset) + "px";
		this.handleBar.style.top = (h - hh) / 2 + "px";
		if (this.euriborBar){
			this.euriborBar.style.left = 0 + "px";
			this.euriborBar.style.top = (h - hh) / 2 + "px";
		}

		this.line.style.top = (h - lh) / 2 + "px";
		this.line.style.left = hw / 2 + "px";
		//this.line.style.right = hw / 2 + "px";
		this.line.style.width = Math.max(0, w - hw - 2)+ "px";
		this.line.firstChild.style.width = Math.max(0, w - hw - 4)+ "px";
	}
	else {
		this.handle.style.left = (w - hw) / 2 + "px";
		this.handle.style.top = h - hh - (h - hh) * (this.getValue() - this.getMinimum()) /	(this.getMaximum() - this.getMinimum()) + "px";

		this.line.style.left = (w - lw) / 2 + "px";
		this.line.style.top = hh / 2 + "px";
		this.line.style.height = Math.max(0, h - hh - 2) + "px";	//hard coded border width
		//this.line.style.bottom = hh / 2 + "px";
		this.line.firstChild.style.height = Math.max(0, h - hh - 4) + "px";	//hard coded border width
	}
};

Slider.prototype.ontimer = function () {
	var hw = this.handle.offsetWidth;
	var hh = this.handle.offsetHeight;
	var hl = this.handle.offsetLeft;
	var ht = this.handle.offsetTop;

	if (this._orientation == "horizontal") {
		if (this._mouseX > hl + hw &&
			(this._increasing == null || this._increasing)) {
			this.setValue(this.getValue() + this.getBlockIncrement());
			this._increasing = true;
		}
		else if (this._mouseX < hl &&
			(this._increasing == null || !this._increasing)) {
			this.setValue(this.getValue() - this.getBlockIncrement());
			this._increasing = false;
		}
	}
	else {
		if (this._mouseY > ht + hh &&
			(this._increasing == null || !this._increasing)) {
			this.setValue(this.getValue() - this.getBlockIncrement());
			this._increasing = false;
		}
		else if (this._mouseY < ht &&
			(this._increasing == null || this._increasing)) {
			this.setValue(this.getValue() + this.getBlockIncrement());
			this._increasing = true;
		}
	}

	this._timer.start();
};

//  Slider object customization
Slider.prototype._bloqueado = false;

Slider.prototype.bloquear = function(){
	this._bloqueado = true;
};

Slider.prototype.desbloquear = function(){
	this._bloqueado = false;
};

Slider.prototype.estaBloqueado = function(){
	return this._bloqueado;
};

Slider.prototype._oldValue = 0;

Slider.prototype.setOldValue = function(pValue){
	this._oldValue = pValue;
};

Slider.prototype.getOldValue = function(){
	return this._oldValue;
};

Slider.prototype._oldTempValue = 0;

Slider.prototype.setOldTempValue = function(pValue){
	this._oldTempValue = pValue;
};

Slider.prototype.getOldTempValue = function(){
	return this._oldTempValue;
};


/*----------------------------------------------------------------------------\
|                              Proxy Slider Class                             |
|-----------------------------------------------------------------------------*/

function ProxySlider(oInput){
	this.input = oInput;
}

ProxySlider.prototype.setValue = function (v) {
	this.input.value = v;
};

ProxySlider.prototype.getValue = function () {
	return this.input.value;
};

ProxySlider.prototype._oldValue = 0;

ProxySlider.prototype.setOldValue = function(pValue){
	this._oldValue = pValue;
};

ProxySlider.prototype.getOldValue = function(){
	return this._oldValue;
};

ProxySlider.prototype._oldTempValue = 0;

ProxySlider.prototype.setOldTempValue = function(pValue){
	this._oldTempValue = pValue;
};

ProxySlider.prototype.getOldTempValue = function(){
	return this._oldTempValue;
};
