/**
 * @file nouportal-1.0.js
 * @author Soluciones Corporativas IP, SLU (SCIP) <mailto:info@scip.es>
 * @brief Funciones de javascript de nouportal
 * @version 1.0
 * */
$(function() {
	/* **************************************************
	 * Funciones que se cargan al inicio (onload) 
	 * ************************************************** */
	/** Crea sliders financiación */
	$('#slider1').nouSlider({width: '144', tipo: 1});
	$('#slider2').nouSlider({width: '144', tipo: 2});
	$('#slider3').nouSlider({width: '144', tipo: 3});
	
	/** Calcula cuotas al cargar la ficha */
	$('#cuotaresult span').each(function() {
		$(this).html(cuota($('#financiacion').val(),$('#anyos').val(),$('#interes').val()));
	});
	/**
	 * @brief Carga el select segun el tipo de operacion seleccionado
	 * */
	$('#buscador #buscar_precio').ready(
		function() {
			var valor;
			valor = $('#buscador input[@name="buscar_operacion"]:checked').val();
			$('buscar_precio').empty().append('<option value="">Todos</option>');
			if((valor == null) && ($('#buscar_operacion').length > 0 )) {
				valor = $('#buscar_operacion').val();
			}
			if(Precio[valor]) {
				var options = Precio[valor];
				for(var i in options) {
					$('#buscar_precio').append('<option value="' + 1 + '">' + options[i] + '</option>');
				}
			}
		}
	);		
	$('#buscador input[@name="buscar_operacion"]').change(
		function() {
			$('#buscar_precio').empty().append('<option value="">Todos</option>');
			if(Precio[$(this).val()]) {
				var options = Precio[$(this).val()];
				for(var i in options) {
					$('#buscar_precio').append('<option value="' + i + '">' + options[i] + '</option>');
				}
			}
		}
	);

	/**
	 * @brief Carga la imagen al hacer click en el thumbnail
	 * */
	$('#fotolist img').css('cursor','pointer').click(function() {
		var myself = $(this);
		var big = $('#foto .fotomain');
		big.parent().css({height: big.parent().height()});
		big.hide();
		var src = myself.attr('src').replace(/thumbs\//,'img/');
		var imgPreloader =  new Image();
		imgPreloader.onload = function() {
			big.attr('src',src);
			big.parent().animate({height: big.height()+'px'},400, function() {
				big.fadeIn(400);
			});
		}
		imgPreloader.src = src;
	});
	
	/**
	 * @brief Amplia la imagen de la ficha mostrandola en su tamaño real
	 * */
	$('#foto img.fotomain').css('cursor','pointer').click(function() {
		$('#ampliacion').removeAttr('src').attr('src',$(this).attr('src'));
		$('#img_ampliada_bg').css({width: $(window).width(), height: $(window).height()}).fadeTo(1,0.8, function() {
			$('#img_ampliada').show();
			$('#img_ampliada_window').css({top: ($(window).height()-$('#img_ampliada_window').height())/3, left: ($(window).width()-$('#img_ampliada_window').width())/2}).show();
		}).click(function() {
			$('#img_ampliada_window').fadeOut('fast',function() {
				$('#img_ampliada').hide();
			});
		});
	});

	// Area clickable en lista de inmuebles
	$('#house_list > li').not('.list_header').css({cursor: 'pointer'}).click(function() {
		window.location = $('a:first',$(this)).attr('href');
		return false;
	});
});

/**
 * M.
 * */
(function($){
	$.fn.nouSlider = function(o) {
		o = $.extend( {
			width: '100',
			tipo: ''
		}, o || {});
		return this.each(function(){
			var myself = $(this);
			myself.addClass('slider').css({width: o.width+'px'}).append('<div class="sliderbtn"></div>');
			var myselfbtn = myself.children('.sliderbtn');
			var current = myself.parent().children('input');
			var maxval, minval;
			switch(o.tipo) {
				case 1:
					maxval = convertEditable(current.val()) * 2;
					minval = 1;
					break;
				case 2:
					maxval = 50;
					minval = 1;
					break;
				case 3:
					maxval = convertEditable(current.val()) * 2;
					minval = 0.1;
					break;
			}
			myselfbtn.mousedown(function() {
				$('body').
				css({cursor: 'e-resize'}).
				mouseup(function() {
					$(this).unbind('mousemove').
					css({cursor: 'auto'});
				}).
				mousemove(function(e) {
					var newpos = Math.round(((e.pageX - myself.offset().left) * 100) / o.width);
					if (newpos >= 0 && newpos <= 100) {
						myselfbtn.css({left: newpos + '%'});
						var newval = (newpos*maxval)/100;
						if(newval<minval) {
							newval = minval;
						}
						if(newval>maxval) {
							newval = maxval;
						}
						switch(o.tipo) {
							case 1:
								newval = convertAccessible(Math.round(newval));
								break;
							case 2:
								newval = Math.round(newval);
								break;
							case 3:
								newval = convertAccessible(newval);
								break;
						}
						current.val(newval);
						$('#cuotaresult span').html(cuota($('#financiacion').val(),$('#anyos').val(),$('#interes').val()));
					}
				});
			});
			current.change(function() {
				$('#cuotaresult span').html(cuota($('#financiacion').val(),$('#anyos').val(),$('#interes').val()));
				var newval = convertEditable($(this).val());
				if(newval<minval) {
					newval = minval;
				}
				if(newval>maxval) {
					newval = maxval;
				}
				var newpos = Math.round(newval*100/maxval);
				if (newpos <= 100 && newpos >= 0) {
					myselfbtn.css({left: newpos+'%'});
				} else if (newpos > 100) {
					myselfbtn.css({left: '100%'});
				} else if (newpos < 0) {
					myselfbtn.css({left: '0'});
				}
				$(this).val(convertAccessible(newval));
			});
		});
	};
})(jQuery);

function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "," : dec_point;
    var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;  
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}
function convertAccessible(string) {
	return number_format(string,2,',','.');
}
function convertEditable(string) {
	return parseFloat(string.replace(/\./g, '').replace(/,/,'.'));
}
function cuota(total,anyos,interes) {
	total = convertEditable(total);
	interes = convertEditable(interes);
	var meses = anyos*12;
	interes = interes/1200.0;
	var y = 1.0 + interes;
	var cuota = total * interes * Math.pow(y, meses) / ( Math.pow(y, meses) - 1.0 );
	$('#totalinteres strong').html(interestotal($('#financiacion').val(),$('#anyos').val(),Math.round(cuota)));
	return convertAccessible(Math.round(cuota));
}
function interestotal(total,anyos,mensual) {
	return convertAccessible(Math.round(mensual*(anyos*12) - convertEditable(total)));
}
