
console.log("single-vehiculos-de-ocasion.js");

var TraduccionesES  = { CLOSE:"Cerrar",NEXT:"Siguiente",PREV:"Anterior",ERROR:"La foto no se pudo cargar.<br/>Inténtalo de nuevo.",PLAY_START:"Comenzar reproducción",
												PLAY_STOP:"Pausar reproducción",FULL_SCREEN:"Pantalla completa",THUMBS:"Miniaturas",DOWNLOAD:"Descargar",SHARE:"Compartir",ZOOM:"Ampliar" };

/*************************************************************************************************/
/***************************************** SLICK SLIDER ******************************************/
/*************************************************************************************************/

jQuery(document).ready(function () {

	jQuery(".sliderGalleryFotos").on("init",function(slick) { //Eliminar fancybox de los slides duplicados
		jQuery(".slick-slide .aFancyBox").attr("data-fancybox","fancybox-slider");
		jQuery(".slick-slide.slick-cloned .aFancyBox").attr("data-fancybox","");
	});

	jQuery(".sliderGalleryFotos").slick({
		infinite: true,
		slidesToShow: 3,
		slidesToScroll: 1,
		prevArrow: "<div class='slick-prev'><i class='fa fa-angle-left'></i></div>",
		nextArrow: "<div class='slick-next'><i class='fa fa-angle-right'></i></div>",
		dots: true,
		responsive: [
			{ breakpoint: 980, settings: { slidesToShow: 2 } },
			{ breakpoint: 580, settings: { slidesToShow: 1 } }
		],
  });

});

/*************************************************************************************************/
/**************************************** FANCYBOX SLIDER ****************************************/
/*************************************************************************************************/

jQuery(document).ready(function () {

	jQuery("[data-fancybox='fancybox-slider']").fancybox({
		        closeExisting : true,
		                 loop : true,
		              infobar : true,
								 smallBtn : true,
									toolbar : false,
		             idleTime : false,
								  protect : true,
		      animationEffect : "zoom",
		    animationDuration : 10,
		     transitionEffect : "slide",
		   transitionDuration : 200,
		                 lang : "es",
		                 i18n : { es: TraduccionesES },
		           fullScreen : { autoStart: (window.matchMedia("(max-width: 980px)").matches) ? true : false },
	});

});

/*************************************************************************************************/
/**************************************** FANCYBOX GALLERY ***************************************/
/*************************************************************************************************/

jQuery(document).ready(function () {

	jQuery("[data-fancybox='fancybox-gallery']").fancybox({
		        closeExisting : true,
		                 loop : true,
		              infobar : true,
								 smallBtn : false,
									toolbar : true,
									buttons : ["close","zoom","share","slideShow","fullScreen","thumbs"],
		             idleTime : false,
								  protect : true,
		               thumbs : { autoStart : true },
		      animationEffect : "zoom",
		    animationDuration : 10,
		     transitionEffect : "slide",
		   transitionDuration : 200,
		                 lang : "es",
		                 i18n : { es: TraduccionesES },
		         //fullScreen : { autoStart: true },
	});

});

/*************************************************************************************************/
/****************************************** FINANCIACION *****************************************/
/*************************************************************************************************/

var Capital     = 0;
var Plazo       = 0;
var Cuota       = 0;
var CuotaFormat = "0";

jQuery(document).ready(function () {

	console.log(MatrizFinanciacion);

	//PARAMETROS INICIALES

	var MaxCapital     = Number(MatrizFinanciacion["precio_oferta"]) - Number(MatrizFinanciacion["min_capital"]);
	var DefaultEntrada = Math.ceil(Number(MatrizFinanciacion["precio_oferta"]) * 20 / 100 / 1000) * 1000;

	jQuery("#inputEntradaRange" ).attr("max",MaxCapital);
	jQuery("#inputEntradaRange" ).val(DefaultEntrada);
	jQuery("#inputEntradaRange" ).attr("value",DefaultEntrada);

	jQuery("#inputEntradaNumber").attr("max",MaxCapital);
	jQuery("#inputEntradaNumber").val(DefaultEntrada);
	jQuery("#inputEntradaNumber").attr("value",DefaultEntrada);

	var MinPlazo = 1;

	for (var i=1; i<11; i++) { if (Number(MatrizFinanciacion[i + "_year"]) > 0) { MinPlazo = i; break; } }

	var MaxPlazo = Math.floor((Number(MatrizFinanciacion["max_plazo"]) - Number(MatrizFinanciacion["antiguedad"])) / 12);
	MaxPlazo     = Math.min(10,MaxPlazo);

	jQuery("#inputPeriodoRange" ).attr("min",MinPlazo);
	jQuery("#inputPeriodoRange" ).attr("max",MaxPlazo);
	jQuery("#inputPeriodoRange" ).val(MaxPlazo);
	jQuery("#inputPeriodoRange" ).attr("value",MaxPlazo);

	jQuery("#inputPeriodoNumber").attr("min",MinPlazo);
	jQuery("#inputPeriodoNumber").attr("max",MaxPlazo);
	jQuery("#inputPeriodoNumber").val(MaxPlazo);
	jQuery("#inputPeriodoNumber").attr("value",MaxPlazo);

	//EVENTOS

	jQuery(".divCuadro").on("click",function() { clickDivCuadro(this); });

	jQuery("#inputEntradaRange" ).on("input",function() { updateForm(this); });
	jQuery("#inputEntradaNumber").on("input",function() { updateForm(this); });
	jQuery("#inputPeriodoRange" ).on("input",function() { updateForm(this); });
	jQuery("#inputPeriodoNumber").on("input",function() { updateForm(this); });
	jQuery(".divFinanciacion i.fa-angle-down").on("click",function() { jQuery("html, body").animate({scrollTop: (jQuery("#divFormularioInteres").offset().top - 80)}, 1000); });

	//INIT

	updateForm(document.getElementById("inputEntradaRange"));
	updateForm(document.getElementById("inputPeriodoRange"));

	var CuotaSinDecimales = Math.ceil(Cuota);

	jQuery(".divCuadroFinanciacion .divPrecio").html(CuotaSinDecimales.toLocaleString("de-DE",{minimumFractionDigits:0,maximumFractionDigits:0}) + "<span>€/mes</span>");

});

function updateForm(objDom) {
	var Tipo     = objDom.id.substr(5,7);
	var Type     = objDom.id.substr(12);
	var objField = jQuery(objDom);
	var Min      = Number(objField.attr("min"));
	var Max      = Number(objField.attr("max"));
	var Value    = Number(objField.val());
	if (Type == "Number" && Value < Min) { Value = Min; }
	if (Type == "Number" && Value > Max) { Value = Max; }
	jQuery("#input" + Tipo + "Range" ).val(Value); jQuery("#input" + Tipo + "Range" ).attr("value",Value);
	jQuery("#input" + Tipo + "Number").val(Value); jQuery("#input" + Tipo + "Number").attr("value",Value);
	jQuery("#input" + Tipo + "Range" ).css("backgroundSize",(Value - Min) * 100 / (Max - Min) + "% 100%");
	updateResultado();
}

function updateResultado() {
	Capital     = Number(MatrizFinanciacion["precio_oferta"]) - jQuery("#inputEntradaNumber").val();
	Plazo       = jQuery("#inputPeriodoNumber").val();
	Cuota       = Capital * Number(MatrizFinanciacion[Plazo + "_year"]);
	CuotaFormat = Cuota.toLocaleString("de-DE",{minimumFractionDigits:2,maximumFractionDigits:2});
	jQuery(".divCantidadesResultado").text(CuotaFormat + " €/mes a " + Plazo + ((Plazo > 1) ? " años" : " año"));
}

function clickDivCuadro(objDom) {
	var DivCuadroObj = jQuery(objDom);
	if (DivCuadroObj.hasClass("active")) return;
	switch (DivCuadroObj.attr("type")) {
		case "precios" :
			jQuery(".divCuadroPrecios"     ).removeClass("inactive").addClass("active"  );
			jQuery(".divCuadroFinanciacion").removeClass("active"  ).addClass("inactive");
			jQuery(".divFinanciacion").slideUp(function() { jQuery(".divCuentas").slideDown(); });
			jQuery(".divFieldInteres input[value='Financiar la compra']").attr("checked",false);
			break;
		case "financiacion" :
			jQuery(".divCuadroPrecios"     ).removeClass("active"  ).addClass("inactive");
			jQuery(".divCuadroFinanciacion").removeClass("inactive").addClass("active"  );
			jQuery(".divCuentas").slideUp(function() { jQuery(".divFinanciacion").slideDown(); });
			jQuery(".divFieldInteres input[value='Financiar la compra']").attr("checked",true);
			break;
	}
}

/*************************************************************************************************/
/***************************** PESTAÑAS EQUIPAMIENTO / BOTONES LLAMAR ****************************/
/*************************************************************************************************/

var ContenidoActual = "Observaciones";

jQuery(document).ready(function () {

	//***** PESTAÑAS

	jQuery("#rowEquipamiento .divPestaña").on("click",function() {
		if (jQuery(this).hasClass("activa")) return false;
		var ContenidoMostrar = jQuery(this).attr("class").split(" ")[1].substr(10);
		jQuery("#rowEquipamiento .divPestaña"   + ContenidoActual ).removeClass("activa");
		jQuery("#rowEquipamiento .divPestaña"   + ContenidoMostrar).addClass("activa");
		jQuery("#rowEquipamiento .divContenido" + ContenidoActual ).slideUp();
		jQuery("#rowEquipamiento .divContenido" + ContenidoMostrar).slideDown();
		ContenidoActual = ContenidoMostrar;
		setTimeout(checkSizePestañas,500);
	});

	//***** BOTONES LLAMAR

	var TfnoAtencion = jQuery(".divBotonLlamanos").attr("data-tel");

	jQuery("#rowCuadroInfo .divBotonLlamanos"  ).on("click",function() { window.location.href = "tel://" + TfnoAtencion; });
	jQuery("#rowCuadroInfo .divBotonTeLlamamos").on("click",function() { jQuery("#rowTeLlamamos").fadeIn();        });
	jQuery("#rowTeLlamamos .divMascara"        ).on("click",function() { jQuery("#rowTeLlamamos").fadeOut();       });
	jQuery("#rowTeLlamamos .divClose"          ).on("click",function() { jQuery("#rowTeLlamamos").fadeOut();       });

});

/*************************************************************************************************/
/******************************************* FUNCTIONS *******************************************/
/*************************************************************************************************/

function checkSizePestañas() {

	var AltoIzda  = jQuery("#rowGalleryFotos").height() + jQuery("#rowCaracteristicas").height() + jQuery("#rowEquipamiento").height() + jQuery("#rowCertificacion").height();
	var AltoDcha  = jQuery("#rowCuadroInfo").height();
	var AltoFalta = AltoDcha - AltoIzda;

	if (!window.matchMedia("(max-width: 580px)").matches && AltoFalta > 0) {
		jQuery("#rowCertificacion .divCertificacion").css("min-height",jQuery("#rowCertificacion").height() + AltoFalta + 20);
	} else {
		jQuery("#rowCertificacion .divCertificacion").css("min-height","auto");
	}

}

/*************************************************************************************************/
