PageSourceSearch

https://www.subastassegre.es/js/common.js?a=1785226905

js subastassegre.es collected 2026-10-02 11:39:22 UTC 53,268 bytes, 2,188 lines download raw bytes

1let audioIsActived = false;
2let project = {
3	theme: 'demo',
4	version: 1
5};
6//cleanUrl();
7
8$(document).ready(function () {
9
10	activedAudio(true);
11
12	$('.view_password')
13		.on('mousedown touchstart', function () {
14			$(this).siblings('input').attr('type', 'text');
15		})
16		.on('mouseup touchend mouseleave', function () {
17			$(this).siblings('input').attr('type', 'password');
18		});
19
20	$('.view-password-group')
21		.on('mousedown touchstart', function () {
22			//reuperamos el .input-group padre
23			$(this).closest('.input-group').find('input').attr('type', 'text');
24		})
25		.on('mouseup touchend mouseleave', function () {
26			$(this).closest('.input-group').find('input').attr('type', 'password');
27		});
28
29	$(".control-number").keydown(function (event) {
30		if (event.shiftKey) {
31			event.preventDefault();
32		}
33
34		if (event.keyCode == 46 || event.keyCode == 8) {
35		} else {
36			if (event.keyCode < 95) {
37				if (event.keyCode < 48 || event.keyCode > 57) {
38					event.preventDefault();
39				}
40			} else {
41				if (event.keyCode < 96 || event.keyCode > 105) {
42					event.preventDefault();
43				}
44			}
45		}
46	});
47
48	/*
49	 |--------------------------------------------------------------------------
50	 | Autocompletar de pujas
51	 |--------------------------------------------------------------------------
52	 */
53
54	if ($('#bid_amount').length) {
55		if ($('#bid_amount').hasClass("NoAutoComplete_JS") == false) {
56
57
58			$('#bid_amount').autoComplete({
59				minChars: 1,
60				cache: false,
61
62				source: function (term, response) {
63					try {
64						xhr.abort();
65					} catch (e) {
66					}
67					$.getJSON('/api-ajax/calculate_bids/' + auction_info.lote_actual.importe_escalado_siguiente + '/' + term + '?cod_sub=' + auction_info.subasta.cod_sub, function (data) {
68						var matches = [];
69						for (i = 0; i < data.length; i++) {
70							matches.push(data[i].toString());
71						}
72
73						response(matches);
74					});
75				},
76			});
77		}
78
79	}
80
81
82
83	/*
84	 |--------------------------------------------------------------------------
85	 | Auto completar
86	 |--------------------------------------------------------------------------
87	 */
88
89
90
91
92	if ($('#bid_modal_pujar').length) {
93		$('#bid_modal_pujar').autoComplete({
94			minChars: 1,
95			cache: false,
96			source: function (term, response) {
97				try {
98					xhr.abort();
99				} catch (e) {
100				}
101				$.getJSON('/api-ajax/calculate_bids/' + auction_info.lote_actual.actual_bid + '/' + term + '?cod_sub=' + auction_info.subasta.cod_sub, function (data) {
102					var matches = [];
103					for (i = 0; i < data.length; i++) {
104						matches.push(data[i].toString());
105					}
106					response(matches);
107				});
108			}
109		});
110	}
111
112
113	//solamente se utiliza en la página del tiempo real
114	$().timeago && $("time.timeago").timeago();
115
116	/*
117	 |--------------------------------------------------------------------------
118	 | Selectmenu de selector de idioma ubicado en languages
119	 |--------------------------------------------------------------------------
120	 */
121	// Seleccion del idioma por defecto en el desplegable
122	$('#selectorIdioma option').each(function () {
123		if ('/' + $(this).val() + '/' == $('#selectorIdioma').attr('actualLang')) {
124			$(this).prop('selected', 'selected');
125		}
126	});
127
128	$('#selectorIdioma').on('change', function () {
129
130
131		var seleccionado = $(this).val();
132		/*
133		 var url 			= $(location).attr('href');		// Url actual total
134		 old 				= $(this).attr('actualLang');	// Idioma actual
135		 nuevo 				= '/' + seleccionado + '/';		// Idioma nuevo
136		 lastChar 			= url.substr(url.length - 1);	// Obtenemos el último carácter
137		 sessionVar 			= '?setlng='+seleccionado;
138
139		 // Detectamos si hay la barra al final
140		 if(lastChar != '/') {
141		 url += '/';
142		 }
143
144		 if(url.indexOf(old) == -1) {
145		 url += seleccionado;
146		 } else {
147		 // Reemplazamos el valor viejo por el nuevo idioma
148		 url = url.replace(old,nuevo);
149		 }
150
151		 //document.location.href=url+sessionVar;
152		 document.location.href=url;
153		 */
154		document.location.href = '/' + seleccionado;
155	});
156
157	/*
158	 |--------------------------------------------------------------------------
159	 | Filter Order By en la ficha de subasta, responsive options
160	 |--------------------------------------------------------------------------
161	 */
162	if ($(window).width() <= '992') {
163		$('#filter_order_by').css('margin-top', '20px');
164	} else {
165		$('#filter_order_by').css('margin-top', '-48px');
166	}
167
168	$(window).resize(function () {
169		if ($(window).width() <= '992') {
170			$('#filter_order_by').css('margin-top', '20px');
171		} else {
172			$('#filter_order_by').css('margin-top', '-48px');
173		}
174	});
175
176	function load_ajax_content(url, text) {
177		//var url = $(this).data().ref;
178		var loader = $('.loader.copyme').clone().removeClass('hidden');
179
180		$('#modalAjax .modal-content .modal-title').html(text);
181
182
183		$.ajax({
184			url: url,
185			dataType: "text",
186
187			beforeSend: function (xhr) {
188				$('#modalAjax .modal-content .modal-body').html(loader);
189			},
190
191			success: function (data) {
192
193				try {
194
195					info = $.parseJSON(data);
196
197					if (info.status == 'error') {
198						window.location.href = '/';
199					}
200
201					//$('#modalAjax .modal-content .modal-body').html("<div style='padding:20px;'>"+info.msg+"</div>");
202
203				} catch (e) {
204					// not json
205					$('#modalAjax .modal-content .modal-body').html("<div style='padding:20px;'>" + data + "</div>");
206				}
207
208				$('#modalAjax .modal-content .loader.copyme').remove();
209			}
210		});
211
212	}
213
214
215	$(".c_bordered").on('click', function () {
216		var url = $(this).data().ref;
217		load_ajax_content(url, $(this).data().title);
218	});
219
220	$(".b_header").on('click', function () {
221		var url = $(this).data().ref;
222		load_ajax_content(url, $(this).data().title);
223	});
224
225	// Pujas de usuario en el panel de usuario
226	$('#panel').on('click', '#my_bids .pagination a', function (e) {
227		e.preventDefault();
228		load_ajax_content($(this).attr('href'), $(this).data().title);
229	});
230
231	// Ordenes de licitacion de usuario en el panel de usuario
232	$('#panel').on('click', '#my_orders .pagination a', function (e) {
233		e.preventDefault();
234		load_ajax_content($(this).attr('href'), $(this).data().title);
235	});
236
237	// Ordenes de licitacion de usuario en el panel de usuario
238	$('#panel').on('click', '#my_allotments .pagination a', function (e) {
239		e.preventDefault();
240		load_ajax_content($(this).attr('href'), $(this).data().title);
241	});
242
243	// Ordenes de licitacion de usuario en el panel de usuario
244	$('#panel').on('click', '#my_favorites .pagination a', function (e) {
245		e.preventDefault();
246		load_ajax_content($(this).attr('href'), $(this).data().title);
247	});
248
249
250	/*
251	 |--------------------------------------------------------------------------
252	 | Boxes / header
253	 |--------------------------------------------------------------------------
254	 */
255
256	//Abre una box con contenido.
257	$('.open_own_box').on('click', function (e) {
258		e.stopPropagation();
259		var $this = $(this);
260
261		if ($('html').find('.ob_disp').length && $this.hasClass('opened')) {
262			closeBox();
263			return;
264		}
265
266		closeBox();
267
268		var this_object = {
269			height: $this.height(),
270			padding_left: parseInt($this.css('padding-left').replace("px", "")),
271			padding_right: parseInt($this.css('padding-right').replace("px", "")),
272			center: $this.offset().left + $this.width() / 2
273		};
274
275		var $ref_to = $("[data-rel='" + $this.data().ref + "']:not(.ob_disp)")
276		var ref_object = {
277			width: $ref_to.width(),
278			padding_left: parseInt($ref_to.css('padding-left').replace("px", "")),
279			padding_right: parseInt($ref_to.css('padding-right').replace("px", ""))
280		};
281
282		var calculo = {
283			x: this_object.center - (ref_object.width + ref_object.padding_right + ref_object.padding_left - this_object.padding_right - this_object.padding_left) / 2,
284			y: $this.offset().top + 50
285		}
286
287		$ref_to.clone().appendTo('body').addClass('ob_disp').css('top', calculo.y).css('left', calculo.x);
288		$this.addClass('opened');
289
290		//Añade la validación al form si hay
291		if ($('.own_box.ob_disp form').length && $('.own_box.ob_disp form').data().toggle == 'validator') {
292			$('.own_box.ob_disp form').validator();
293		}
294	});
295
296	function closeBox() {
297		$('.opened').removeClass('opened');
298		$('.ob_disp').remove();
299	}
300
301	//Cierra las box que estén abiertas.
302	$('html').on('click', function (e) {
303
304		var p_classes = $(e.target).parents().map(function () {
305			return this.className;
306		}).get();
307
308		if ($.inArray("own_box ob_disp", p_classes) === -1 && (!$(e.target).hasClass('own_box') && !$(e.target).hasClass('ob_disp'))) {
309			closeBox();
310		}
311	});
312
313	//$('.frmLogin').validator();
314
315	/*
316	 |--------------------------------------------------------------------------
317	 | Registro de usuarios / login.blade / Login
318	 |--------------------------------------------------------------------------
319	 */
320	$("#regCallback").hide();
321
322
323	$('#btnRegister').on('click', function () {
324		if (!$('#condiciones_registro').prop('checked')) {
325			alert('Debes aceptar las condiciones de registro');
326			return false;
327		}
328	});
329
330	$('#frmRegister').validator().on('submit', function (e) {
331
332		if (e.isDefaultPrevented()) {
333			// formulario incorrecto
334		} else {
335
336			e.preventDefault();
337			var $this = $(this);
338
339			$('button', $this).attr('disabled', 'disabled');
340			// Datos correctos enviamos ajax
341			$.ajax({
342				type: "POST",
343				url: routing.registro,
344				data: $('#frmRegister').serialize(),
345				beforeSend: function () {
346					$('#btnRegister').prepend(' <i class="fa fa-spinner fa-pulse fa-fw margin-bottom"></i> ');
347				},
348				success: function (response) {
349
350					//$('button', $this).attr('disabled', false);
351
352					res = jQuery.parseJSON(response);
353
354					$('#btnRegister').find('i').hide();
355
356					if (res.err == 1) {
357						$("#regCallback").show().html(res.msg);
358					} else {
359						$('.col_reg_form').html(res.msg);
360						//$('.col_login_form').removeClass('col-lg-6');
361						//$('.col_login_form').addClass('col-lg-12');
362
363					}
364
365				}
366			});
367
368		}
369	});
370
371
372	$('#frmUpdateUserInfo').validator().on('submit', function (e) {
373
374		if (e.isDefaultPrevented()) {
375			// formulario incorrecto
376		} else {
377
378			e.preventDefault();
379			var $this = $(this);
380
381			$('button', $this).attr('disabled', 'disabled');
382			// Datos correctos enviamos ajax
383			$.ajax({
384				type: "POST",
385				url: '/api-ajax/client/update',
386				data: $('#frmUpdateUserInfo').serialize(),
387				beforeSend: function () {
388					$('#btnRegister').prepend(' <i class="fa fa-spinner fa-pulse fa-fw margin-bottom"></i> ');
389				},
390				success: function (response) {
391
392					//$('button', $this).attr('disabled', false);
393
394					res = jQuery.parseJSON(response);
395
396					$('#btnRegister').find('i').hide();
397
398					if (res.err == 1) {
399						$("#regCallback").show().html(res.msg);
400					} else {
401						$('.insert_msg').html(res.msg);
402						$.magnificPopup.open({ items: { src: '#genericPopup' }, type: 'inline' }, 0);
403
404						//$('.col_reg_form').html(res.msg);
405					}
406
407				}
408			});
409
410		}
411	});
412
413	$('#frmUpdateUserPassword').validator().on('submit', function (e) {
414
415		if (e.isDefaultPrevented()) {
416			// formulario incorrecto
417		} else {
418
419			e.preventDefault();
420			var $this = $(this);
421
422			$('button', $this).attr('disabled', 'disabled');
423			// Datos correctos enviamos ajax
424			$.ajax({
425				type: "POST",
426				url: '/api-ajax/client/update/password',
427				data: $('#frmUpdateUserPassword').serialize(),
428				beforeSend: function () {
429					//$('#btnRegister').prepend(' <i class="fa fa-spinner fa-pulse fa-fw margin-bottom"></i> ');
430				},
431				success: function (response) {
432
433					//$('button', $this).attr('disabled', false);
434
435					res = jQuery.parseJSON(response);
436
437					//$('#btnRegister').find('i').hide();
438
439					if (res.err == 1) {
440						$("#regCallback").show().html(res.msg);
441					} else {
442						$('.insert_msg').html(res.msg);
443						$.magnificPopup.open({ items: { src: '#genericPopup' }, type: 'inline' }, 0);
444
445						//$('.col_reg_form').html(res.msg);
446					}
447
448				}
449			});
450
451		}
452	});
453
454	/*
455	 |--------------------------------------------------------------------------
456	 | Botones grandes de la home / bigButtons
457	 |--------------------------------------------------------------------------
458	 */
459
460	// Default
461	$('.col2').addClass('stage2');
462
463	$('.col1').hover(function () {
464		$(this).addClass('stage2');
465		$('.col2').removeClass('stage2');
466	});
467
468	$('.col2').hover(function () {
469		$(this).addClass('stage2');
470		$('.col1').removeClass('stage2');
471	});
472
473	/*
474	 |--------------------------------------------------------------------------
475	 | Controles de pujar o guardar en subastas permanentes / permanentAuctions
476	 |--------------------------------------------------------------------------
477	 */
478
479	// Mostramos el overlay de opciones con los controles de la subastas
480	$('.permanentAuctions #subastas').on('mouseenter', '#content .item .img', function () {
481		$(this).find('.options').show();
482	});
483
484	$('.permanentAuctions #subastas').on('mouseleave', '#content .item .img', function () {
485		$(this).find('.options').hide();
486	});
487
488
489	/*
490	 |--------------------------------------------------------------------------
491	 | Subastas de la Home / permanentAuctions.blade
492	 |--------------------------------------------------------------------------
493	 */
494	page = 1;
495	var is_home = 1;
496
497	// Control de la derecha
498	$('.permanentAuctions').find('.control.right').click(function () {
499
500		var max_lot = $('.permanentAuctions').find('#maxPages').val();
501		var currentPage = $('.permanentAuctions').find('#currentPage').val();
502
503		//console.log("value: "+$('.permanentAuctions').find('.control.right').attr('value'));
504		//console.log("currentPage: "+currentPage);
505		//console.log("max_lot: "+max_lot);
506
507		if ((page + 1) < max_lot) {
508			page = (page * 1) + 1;
509
510			if (page == 1) {
511				page = (page + 1);
512			}
513
514			//console.log(page);
515			//console.log(max_lot);
516
517			//console.log("Next: " +page);
518
519			if (page < max_lot) {
520				//console.log('Item Load');
521				$.ajax({
522					type: "GET",
523					url: routing.subastashome + '/' + page + '/' + is_home,
524					beforeSend: function () {
525						$(".loteHome").addClass('opacity');
526					},
527					success: function (msg) {
528						$("#subastas").html("<div>" + msg + "</div>");
529					}
530				});
531			}
532		}
533	});
534
535	page = 0;
536
537	// Control de la izquierda
538	$('.permanentAuctions').find('.control.left').click(function () {
539
540		var max_lot = $('.permanentAuctions').find('#maxPages').val();
541		var currentPage = $('.permanentAuctions').find('#currentPage').val();
542
543		if (currentPage < max_lot && page > 0) {
544			page = (page * 1) - 1;
545
546			if (page == 1) {
547				page = (page - 1);
548			}
549
550			//console.log("Next: " +page);
551
552			if (page < max_lot) {
553				//console.log('Item Load');
554				$.ajax({
555					type: "GET",
556					url: routing.subastashome + '/' + page + '/' + is_home,
557					beforeSend: function () {
558						$(".loteHome").addClass('opacity');
559					},
560					success: function (msg) {
561						$("#subastas").html("<div>" + msg + "</div>");
562					}
563				});
564			}
565		}
566	});
567
568
569
570	$('.modal-block').on('click', '.modal-confirm', function (e) {
571		e.stopPropagation();
572		e.preventDefault();
573		var func = $(this).closest('.modal-block').data('to');
574		var errors = 0;
575
576		if (typeof func != 'undefined') {
577			var fn = window[func];
578			if (typeof fn === 'function') {
579				fn();
580			} else {
581				errors++;
582			}
583		} else {
584			errors++;
585		}
586
587		$.magnificPopup.close();
588
589		if (errors > 0) {
590			displayAlert(0, messages.error.generic);
591		}
592
593	}).on('click', '.modal-dismiss', function (e) {
594		e.stopPropagation();
595		e.preventDefault();
596		$.magnificPopup.close();
597	});
598
599
600
601	$('.submit_on_change').on('change', function () {
602
603		$(this).closest('form').submit();
604
605	});
606
607
608	//Bloquea los elementos del form mientras carga la página para evitar posibles errores.
609	/*$('.permanentAuctions form').submit(function(){
610	 $('select, input', $(this)).prop( "disabled", true );
611	 });*/
612
613
614	//eliminamos todos los filtros para que el goto busque en toda la web
615	$('#filer_submit').on('click', function () {
616		$('#filter_main  :input').val('');
617		$(this).closest('form').submit();
618	});
619
620	// Facebook share.
621	var fb_share = $('#fbShareBtn');
622	if (fb_share.length) {
623		fb_share.on('click', function () {
624			var fb_href = $(this).data().href,
625				fb_picture = $(this).data().picture,
626				fb_caption = $(this).data().caption,
627				fb_title = $(this).data().title,
628				fb_description = $(this).data().description;
629
630			FB.ui({
631				method: 'share',
632				display: 'popup',
633				mobile_iframe: true,
634				href: fb_href,
635				picture: fb_picture,
636				caption: fb_caption,
637				title: fb_title,
638				description: fb_description
639			}, function (response) {
640				if (typeof response != 'undefined') {
641					alert('callback compartido');
642				}
643			});
644		});
645	}
646
647	//Twitter share.
648	$('#twShareBtn').click(function (event) {
649		var width = 575,
650			height = 450,
651			left = ($(window).width() - width) / 2,
652			top = ($(window).height() - height) / 2,
653			url = this.href,
654			opts = 'status=1' +
655				',width=' + width +
656				',height=' + height +
657				',top=' + top +
658				',left=' + left;
659
660		window.open(url, 'Twitter', opts);
661
662		return false;
663	});
664
665	$('[data-countdown]').each(function (event) {
666
667		var countdown = $(this);
668		countdown.data('ini', new Date().getTime());
669		countdown_timer(countdown)
670
671
672	});
673	$('[data-countdownficha]').each(function (event) {
674
675
676		var countdown = $(this);
677		countdown.data('ini', new Date().getTime());
678		countdown_timer_ficha(countdown)
679
680
681	});
682
683	//countdown_timer_ficha($("[data-countdown-ficha]"));
684
685	$("#frmRegister-adv input, #frmRegister-adv select").blur(function () {
686		verifyFormLoginContent();
687	});
688
689
690
691	$('.seoAction_JS').click(function (event) {
692		seoEvent = $(this).data("event");
693		registerSeoEvent(seoEvent);
694	})
695});
696//SE PUEDE AÑADIR LA CLASE seoAction_JS Y UN CAMPO DATA-EVENT CON EL NOMBRE DEL EVENTO PARA QUE LO REGISTRE GRACIAS A UNA FUNCION CREADA
697function registerSeoEvent(seoEvent) {
698	console.log(seoEvent);
699	$.ajax({
700		type: "GET",
701
702		url: '/seo_event/' + seoEvent,
703	});
704}
705
706function emailSobrePuja(cod, licit, lote) {
707
708	$.ajax({
709		type: "POST",
710		data: { cod: cod, licit: licit, lote: lote },
711		url: '/api-ajax/email_sobrepuja',
712		beforeSend: function () {
713		},
714		success: function (msg) {
715			var hola = "" + msg;
716			hola = "hola";
717			//$('.insert_msg').html(msg.msg);
718			//$.magnificPopup.open({items: {src: '#newsletterModal'}, type: 'inline'}, 0);
719		}
720	});
721}
722
723function toggleFullScreen() {
724	if ((document.fullScreenElement && document.fullScreenElement !== null) ||
725		(!document.mozFullScreen && !document.webkitIsFullScreen)) {
726		if (document.documentElement.requestFullScreen) {
727			document.documentElement.requestFullScreen();
728		} else if (document.documentElement.mozRequestFullScreen) {
729			document.documentElement.mozRequestFullScreen();
730		} else if (document.documentElement.webkitRequestFullScreen) {
731			document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
732		}
733	} else {
734		if (document.cancelFullScreen) {
735			document.cancelFullScreen();
736		} else if (document.mozCancelFullScreen) {
737			document.mozCancelFullScreen();
738		} else if (document.webkitCancelFullScreen) {
739			document.webkitCancelFullScreen();
740		}
741	}
742}
743
744/*
745 |--------------------------------------------------------------------------
746 | Configuración notificaciones
747 |--------------------------------------------------------------------------
748 */
749(function ($) {
750
751	'use strict';
752
753	// use font awesome icons if available
754	if (typeof PNotify != 'undefined') {
755		PNotify.prototype.options.styling = "fontawesome";
756
757		$.extend(true, PNotify.prototype.options, {
758			shadow: false,
759			stack: {
760				spacing1: 15,
761				spacing2: 15
762			}
763		});
764
765		$.extend(PNotify.styling.fontawesome, {
766			// classes
767			container: "notification",
768			notice: "notification-warning",
769			info: "notification-info",
770			success: "notification-success",
771			error: "notification-danger",
772
773			// icons
774			notice_icon: "fa fa-exclamation",
775			info_icon: "fa fa-info",
776			success_icon: "fa fa-check",
777			error_icon: "fa fa-times"
778		});
779	}
780
781}).apply(this, [jQuery]);
782/*
783 |--------------------------------------------------------------------------
784 | END Configuración notificaciones
785 |--------------------------------------------------------------------------
786 */
787
788/*
789 |--------------------------------------------------------------------------
790 | Selectmenu de selector de idioma ubicado en languages
791 |--------------------------------------------------------------------------
792 */
793
794function seleccionar_idioma(actualLang, seleccionado) {
795	/*
796	 var url 			= $(location).attr ('href');		// Url actual total
797	 old 					= '/' + actualLang;										// Idioma actual
798	 nuevo 				= '/' + seleccionado + '/';			// Idioma nuevo
799	 lastChar 			= url.substr (url.length - 1);	// Obtenemos el último carácter
800	 sessionVar 		= '?setlng=' + seleccionado;
801
802	 // Detectamos si hay la barra al final
803	 if (lastChar != '/')
804	 {
805	 url += '/';
806	 }
807
808	 if (url.indexOf (old) == -1)
809	 {
810	 url += seleccionado;
811	 }
812	 else
813	 {
814	 // Reemplazamos el valor viejo por el nuevo idioma
815	 url = url.replace (old, nuevo);
816	 }
817	 */
818	document.location.href = '/' + seleccionado;// url;
819}
820
821
822
823
824/*
825 |--------------------------------------------------------------------------
826 | Alerta sonora
827 |--------------------------------------------------------------------------
828 */
829
830
831
832function playAlert(arr_items) {
833
834	if (typeof auction_info == 'undefined' || typeof auction_info.subasta.nextLotes == 'undefined') {
835		return;
836	}
837
838
839	if ($.inArray('favs', arr_items) !== -1) {
840		if (alertForFavs()) {
841			playAudio('#alarm_fav_lot');
842		}
843	}
844	if ($.inArray('new_bid', arr_items) !== -1) {
845		playAudio('#new_bid');
846	}
847	if ($.inArray('end_lot', arr_items) !== -1) {
848		playAudio('#end_lot');
849	}
850	if ($.inArray('new_ol', arr_items) !== -1) {
851		playAudio('#new_ol');
852	}
853
854	if ($.inArray('countdown', arr_items) !== -1) {
855		/*$('#alarm_end_lot').trigger('play').prop("volume", 0.1);*/
856	}
857
858	if ($.inArray('notification', arr_items) !== -1) {
859		playAudio('#alarm_notification');
860
861	}
862}
863
864
865function activedAudio(actived) {
866
867	if (!actived) {
868		audioIsActived = false;
869		return;
870	}
871
872	audioIsActived = true;
873	playAudio("#alarm_notification", 0);
874}
875
876
877function playAudio(selector, volume = 0.5) {
878
879	if (!audioIsActived) {
880		return;
881	}
882
883	var sound = document.querySelector(selector); //.play();
884
885	if (sound == null) {
886		return;
887	}
888
889	sound.volume = volume;
890
891	var playPromise = sound.play();
892
893	// In browsers that don’t yet support this functionality,
894	// playPromise won’t be defined.
895	if (playPromise !== undefined) {
896		playPromise.then(function () {
897			// Automatic playback started!
898		}).catch(function (error) {
899			// Automatic playback failed.
900			// Show a UI element to let the user manually start playback.
901			console.log(error)
902		});
903	}
904}
905
906function alertForFavs() {
907	var found = false;
908	var lot = 0;
909	var lot_order = 9999;
910	var match_actual = false;
911
912	if (typeof auction_info.user == 'undefined' || typeof auction_info.user.favorites == 'undefined' || auction_info.user.is_gestor == true) {
913		return;
914	}
915
916	$.each(auction_info.user.favorites, function (key, item) {
917
918		if (typeof item == 'undefined') {
919			return true;
920		}
921
922		if ($.inArray(item.ref_asigl0, auction_info.subasta.nextLotes) !== -1) {
923			found = true;
924
925			if (lot == 0 || item.orden_hces1 < lot_order) {
926				lot = parseInt(item.ref_asigl0);
927				lot_order = item.orden_hces1;
928			}
929		}
930
931		if (item.ref_asigl0 == auction_info.lote_actual.ref_asigl0) {
932			match_actual = true;
933		}
934
935	});
936	if (match_actual) {
937		displayAlert(1, messages.neutral.match_fav_actual_lot);
938	}
939
940	if (found) {
941		displayAlert(3, messages.neutral.subasted_fav_lot_soon + lot);
942	}
943
944	return found;
945}
946/*
947 |--------------------------------------------------------------------------
948 | END Alerta sonora
949 |--------------------------------------------------------------------------
950 */
951
952
953
954function calculate_exchange(currency, price) {
955	var calc_exchange = price * exchanges[currency];
956	calc_exchange = format_money(calc_exchange);
957	return calc_exchange;
958}
959
960function format_money(money) {
961	let formatPrice = parseFloat(money)
962		.toFixed(2)
963		.replace(".", ",");
964
965	return formatPrice.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");
966}
967
968function formatMoney({ money = 0, decimals = 2, symbol = '€' }) {
969
970	money = money.toFixed(decimals);
971	money = money.replace('.', ',');
972	money = money.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.");
973
974	return money + ' ' + symbol;
975}
976
977function popup_frame(url) {
978	$('#modal_info').magnificPopup(
979		{
980			src: 'http://vimeo.com/123123',
981			type: 'iframe' // this overrides default type
982		}
983	);
984}
985
986/*
987 |--------------------------------------------------------------------------
988 | Mostrar alertas
989 |--------------------------------------------------------------------------
990 */
991function displayAlert(type, msg) {
992	if (auction_info.lote_actual.tipo_sub == 'O' || auction_info.lote_actual.tipo_sub == 'P') {
993		displayAlertPopUp(type, msg)
994	} else if (auction_info.lote_actual.tipo_sub == 'W') {
995		displayAlertNotice(type, msg)
996	}
997}
998function displayAlertNotice(type, msg) {
999	if (type == null || typeof type == 'undefined' || !$.isNumeric(type))
1000		return false;
1001
1002	/*var type = ''; */
1003
1004	switch (type) {
1005		case 0:
1006			type = 'error';
1007			break;
1008		case 1:
1009			type = 'success';
1010			break;
1011		case 2:
1012			type = 'info';
1013			break;
1014		case 3:
1015			type = 'alert';
1016			break;
1017	}
1018
1019	playAlert(['notification']);
1020
1021	var notice = new PNotify({
1022		title: messages.neutral.notification,
1023		text: msg,
1024		type: type,
1025		shadow: true,
1026		addclass: 'stack-topleft'
1027	});
1028}
1029
1030function displayAlertPopUp(type, msg) {
1031	$("#insert_msg_title").html("Notificación");
1032	$("#insert_msg").html(msg);
1033	$.magnificPopup.open({ items: { src: '#modalMensaje' }, type: 'inline' }, 0);
1034
1035}
1036/*
1037 |--------------------------------------------------------------------------
1038 | END Mostrar alertas
1039 |--------------------------------------------------------------------------
1040 */
1041
1042
1043
1044function verifyFormLoginContent() {
1045
1046
1047	var valor = $("#frmRegister-adv #dni").val();
1048	valor = valor.toUpperCase();
1049	$("#frmRegister-adv #dni").val(valor);
1050	//cogemos el pais
1051	var selected_country = $("#frmRegister-adv select#country").val();
1052	//si el pais es Spain verificar el DNI
1053	if (selected_country == "ES") {
1054
1055		validateDNI(valor);
1056	} else {
1057		$("#frmRegister-adv input#dni").parent().removeClass("has-error");
1058		$("#frmRegister-adv input#dni").parent().addClass("has-success");
1059	}
1060
1061	var has_input_errors = 0;
1062
1063	$("#frmRegister-adv input").each(function () {
1064		if ($(this).parent().hasClass("has-error")) {
1065
1066			has_input_errors++;
1067		}
1068	});
1069
1070	$("#frmRegister-adv select").each(function () {
1071		if ($(this).parent().hasClass("has-error")) {
1072
1073			has_input_errors++;
1074		}
1075	});
1076
1077	if (!$("#erroremail").hasClass("hidden")) {
1078		has_input_errors++;
1079	}
1080
1081	if (has_input_errors == 0) {
1082		$(".btn-registro").removeAttr("disabled");
1083		return false;
1084	} else {
1085		$(".btn-registro").attr("disabled", "disabled");
1086		return true;
1087	}
1088}
1089
1090
1091function validateDNI(dni) {
1092	console.log(dni)
1093	var validated = false;
1094	//miramos si tiene errores para devolver el error
1095	if (dni.trim().length == 9) {
1096		var arrLetras = ['T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E'];
1097		var arrResto = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22'];
1098
1099		var first_char = dni.trim().charAt(0);
1100		var last_char = dni.trim().charAt(8);
1101
1102
1103
1104		//si la primera y la ultima no son numericas, es una de las del NIE X,Y,Z
1105		if (isNaN(first_char) && isNaN(last_char) && (first_char == 'X' || first_char == 'Y' || first_char == 'Z')) {
1106			//ES NIE
1107			var middle_string = dni.trim().substr(1, 7);
1108			var first_char_replaced = "0";//POR DEFECTO ESPERAMOS LA X
1109			if (first_char == "Y") {
1110				first_char_replaced = "1";
1111			} else {
1112				if (first_char == "Z") {
1113					first_char_replaced = "2";
1114				}
1115			}
1116
1117			var final_string = first_char_replaced + middle_string;
1118
1119			//SI NO ES NUMERICO NO ES VALIDO
1120			if (!isNaN(final_string)) {
1121				//DIVIDIR EL CODIGO ENTRE 23
1122				var number_to_divide = Number(final_string);
1123				var resto = number_to_divide % 23;
1124
1125				for (i = 0; i < arrResto.length; i++) {
1126					if (arrResto[i] == resto && arrLetras[i] == last_char) {
1127						validated = true;
1128					}
1129				}
1130			}
1131
1132		} else {
1133
1134			//si la ultima no es numerica, es un NIF
1135			if (!isNaN(first_char) && isNaN(last_char)) {
1136				//ES NIE
1137				var middle_string = dni.trim().substr(0, 8);
1138
1139				//SI NO ES NUMERICO NO ES VALIDO
1140				if (!isNaN(middle_string)) {
1141					//DIVIDIR EL CODIGO ENTRE 23
1142					var number_to_divide = Number(middle_string);
1143					var resto = number_to_divide % 23;
1144
1145					for (i = 0; i < arrResto.length; i++) {
1146						if (arrResto[i] == resto && arrLetras[i] == last_char) {
1147							validated = true;
1148						}
1149					}
1150				}
1151			}
1152			//es un CIF de empresa
1153			else if (isNaN(first_char) && first_char != 'X' && first_char != 'Y' && first_char != 'Z') {
1154				validated = true;
1155			}
1156		}
1157
1158	}
1159
1160	if (validated) {
1161		//HACER LO QUE SEA PARA QUE SE NOTE QUE ES VALIDO
1162		//alert("VALIDO");
1163		$("#frmRegister-adv input#dni").parent().removeClass("has-error");
1164		$("#frmRegister-adv input#dni").parent().addClass("has-success");
1165	} else {
1166		//HACER LO QUE SEA PARA QUE SE NOTE QUE NO ES VALIDO
1167		//alert("NO VALIDO");
1168		if ($("#frmRegister-adv input#dni").parent().hasClass("has-error")) {
1169			$("#frmRegister-adv input#dni").parent().removeClass("has-error");
1170		}
1171
1172		if ($("#frmRegister-adv input#dni").parent().hasClass("has-success")) {
1173			$("#frmRegister-adv input#dni").parent().removeClass("has-success");
1174		}
1175
1176
1177		$("#frmRegister-adv input#dni").parent().addClass("has-error");
1178	}
1179
1180}
1181
1182
1183window.modalDeletAddress = function modalDeletAddress() {
1184	var token = $("#modalDeletAddress #_token").val();
1185	var cod = $("#modalDeletAddress #cod_delete").val();
1186	var lang = $("#modalDeletAddress #lang").val();
1187
1188	$.ajax({
1189		type: "POST",
1190		url: '/delete_address_shipping',
1191		data: { _token: token, cod: cod },
1192		success: function (response) {
1193			if (response.status == 'success') {
1194				$("#modalMensaje #insert_msg").html('');
1195				$("#modalMensaje #insert_msg").html(messages.success.success_delete);
1196				$.magnificPopup.open({ items: { src: '#modalMensaje' }, type: 'inline' }, 0);
1197				ajax_shipping('W1', lang);
1198			}
1199		}
1200	})
1201};
1202
1203function fav_addres(thi) {
1204	var cod = $(thi).attr('cod');
1205	return $.ajax({
1206		type: "POST",
1207		url: '/api-ajax/add_favorite_address_shipping',
1208		data: { codd_clid: cod },
1209		success: function (response) {
1210			if (response.status == 'success') {
1211				$("#modalMensaje #insert_msg").html('');
1212				$("#modalMensaje #insert_msg").html(messages.success.success_saved);
1213				$.magnificPopup.open({ items: { src: '#modalMensaje' }, type: 'inline' }, 0);
1214				ajax_shipping(response.codd_clid, cod);
1215				return response;
1216			}
1217
1218		}
1219	}).then((response) => {
1220		return response;
1221	});
1222}
1223
1224function delete_shipping_addres(thi) {
1225	var cod = $(thi).attr('cod');
1226	$("#cod_delete").val(cod);
1227	$.magnificPopup.open({ items: { src: '#modalDeletAddress' }, type: 'inline' }, 0);
1228}
1229
1230function submit_shipping_addres(event, thi) {
1231	event.preventDefault();
1232	return $.ajax({
1233		type: "POST",
1234		context: thi,
1235		url: '/change_address_shipping',
1236		data: $(thi).serialize(),
1237		success: function (response) {
1238			if (response.status == 'success' || response.status == 'new') {
1239
1240				$("#modalMensaje #insert_msg").html('');
1241				$("#modalMensaje #insert_msg").html(messages.success.success_saved);
1242				$.magnificPopup.open({ items: { src: '#modalMensaje' }, type: 'inline' }, 0);
1243				ajax_shipping(response.codd_clid, $("#lang_dirreciones").val());
1244				return response;
1245			}
1246		}
1247	}).then((response) => {
1248		return response;
1249	});
1250}
1251
1252
1253function countdown_timer_ficha(countdown) {
1254	//SI ESTA PARADO NO DEBE HACER NADA
1255	if (typeof countdown.data('stop') != 'undefined' && countdown.data('stop') == 'stop') {
1256		return;
1257	}
1258
1259	ToFinish = countdown.data('countdownficha') - Math.round(((new Date().getTime() - countdown.data('ini')) / 1000));
1260
1261	if (ToFinish < 0) {
1262		ToFinish = 0;
1263		$.ajax({
1264			type: "GET",
1265			url: '/' + auction_info.lang_code.toLowerCase() + '/reload_lot',
1266			data: { cod_sub: auction_info.lote_actual.cod_sub, ref: auction_info.lote_actual.ref_asigl0 },
1267			success: function (response) {
1268				if (response != 'error') {
1269					$("#reload_inf_lot").html('');
1270					$("#reload_inf_lot").html(response);
1271					reloadPujasList_O();
1272					countdown.data('stop', 'stop');
1273					if (typeof countdown.data('txtend') != 'undefined') {
1274						countdown.html(countdown.data('txtend'));
1275
1276					}
1277				}
1278			}
1279		});
1280
1281	}
1282
1283
1284	var timeFormat = time_format(ToFinish, countdown.data('format'));
1285	countdown.html(timeFormat);
1286	setTimeout(function () {
1287		countdown_timer_ficha(countdown);
1288	}, 1000);
1289
1290}
1291
1292function countdown_timer(countdown) {
1293
1294
1295	//SI ESTA PARADO NO DEBE HACER NADA
1296	if (typeof countdown.data('stop') != 'undefined' && countdown.data('stop') == 'stop') {
1297		return;
1298	}
1299
1300	ToFinish = countdown.data('countdown') - Math.round(((new Date().getTime() - countdown.data('ini')) / 1000));
1301
1302	if (ToFinish < 0) {
1303		ToFinish = 0;
1304		//SI HAY TEXTO DE FIN, PONEMOS EL TEXTO Y PARAMOS EL BUCLE
1305		if (typeof countdown.data('txtend') != 'undefined') {
1306			countdown.html(countdown.data('txtend'));
1307			countdown.data('stop', 'stop');
1308			//paramos el contador
1309			return
1310		}
1311
1312		//add callback
1313		if (typeof countdown.data('callback') != 'undefined') {
1314			var callback = window[countdown.data('callback')];
1315			if (typeof callback === 'function') {
1316				callback(countdown, countdown.data('callback-params'));
1317				countdown.data('stop', 'stop');
1318				return;
1319			}
1320		}
1321	}
1322
1323	var timeFormat = time_format(ToFinish, countdown.data('format'));
1324	countdown.html(timeFormat);
1325	setTimeout(function () {
1326		countdown_timer(countdown);
1327	}, 1000);
1328
1329}
1330
1331function time_format(timer, format) {
1332
1333
1334
1335	if (format.indexOf('%D') > -1) {
1336		format = format.replace('%D', calc_day(timer));
1337	}
1338	if (format.indexOf('%H') > -1) {
1339		format = format.replace('%H', calc_hour(timer));
1340	}
1341
1342	if (format.indexOf('%M') > -1) {
1343		format = format.replace('%M', calc_minute(timer));
1344	}
1345
1346	if (format.indexOf('%S') > -1) {
1347		format = format.replace('%S', calc_seconds(timer));
1348	}
1349
1350	return format;
1351}
1352
1353function calc_day(timer) {
1354	var days = parseInt(timer / 86400);
1355	days = days < 10 ? "0" + days : days;
1356	return days
1357}
1358
1359function calc_hour(timer) {
1360	var hours = parseInt((timer % 86400) / 3600);
1361	hours = hours < 10 ? "0" + hours : hours;
1362	return hours
1363}
1364
1365
1366function calc_minute(timer) {
1367	var minutes = parseInt((timer % 3600) / 60);
1368	minutes = minutes < 10 ? "0" + minutes : minutes;
1369	return minutes
1370}
1371
1372
1373function calc_seconds(timer) {
1374	var seconds = parseInt((timer % 60));
1375	seconds = seconds < 10 ? "0" + seconds : seconds;
1376	return seconds
1377
1378}
1379
1380
1381$(document).ready(function () {
1382
1383
1384	$('[name="cpostal"]').blur(function () {
1385		var country = $('[name="pais"]').val();
1386		var zip = $(this).val();
1387		if (country != '') {
1388			$.ajax({
1389				type: "POST",
1390				data: { zip: zip, country: country },
1391				url: '/api-ajax/cod-zip',
1392				success: function (msg) {
1393					if (msg.status == 'success') {
1394						$('[name="poblacion"]').val(msg.pob);
1395						$('[name="provincia"]').val(msg.des_prv);
1396					}
1397				}
1398			});
1399		}
1400	});
1401
1402	$("#codigo_postal").blur(function () {
1403		var country = $("#country_envio").val();
1404		var zip = $(this).val();
1405		if (country != '') {
1406			$.ajax({
1407				type: "POST",
1408				data: { zip: zip, country: country },
1409				url: '/api-ajax/cod-zip',
1410				success: function (msg) {
1411					if (msg.status == 'success') {
1412						$("#clid_provincia").val(msg.des_prv);
1413						$("#clid_poblacion").val(msg.pob);
1414					}
1415				}
1416			});
1417		}
1418	});
1419
1420	$(".change_job").click(function () {
1421		var job = $(this).val();
1422		if (job == 'J') {
1423			$('.rsoc_cli').removeClass('hidden');
1424			$('.rsoc_cli input').attr('data-checking', 'true');
1425			$('.gener-group').addClass('hidden');
1426			$('.fech_nac').addClass('hidden');
1427			$('.fech_nac input').attr('data-checking', 'false');
1428			$(".rsoc_cli input").prop("required", 'true');
1429			$(".rsoc_cli").attr('data-checking', 'true');
1430			$('.name_client').addClass('hidden');
1431			$('.name_client input').attr('data-checking', 'false');
1432			//$(".name_client input").removeAttr("required");
1433			$(".name_client input").attr("required", false);
1434			$('.cif_txt').removeClass('hidden');
1435			$('.cif_txt input').attr('data-checking', 'true');
1436			$('.dni_txt').addClass('hidden');
1437			$('.dni_txt input').attr('data-checking', 'false');
1438			$("#dni").attr("placeholder", $('.cif_txt').html());
1439
1440
1441		} else {
1442			$('.gener-group').removeClass('hidden');
1443
1444			$('.fech_nac').removeClass('hidden');
1445			$('.fech_nac input').attr('data-checking', 'true');
1446
1447			$('.rsoc_cli').addClass('hidden');
1448			$('.rsoc_cli').attr('data-checking', 'false');
1449			$(".rsoc_cli input").removeAttr("required");
1450			$('.name_client').removeClass('hidden');
1451			$(".name_client input").prop("required", true);
1452			$(".name_client input").attr('data-checking', 'true');
1453			$('.cif_txt').addClass('hidden');
1454			$('.cif_txt input').attr('data-checking', 'false');
1455			$('.dni_txt').removeClass('hidden');
1456			$('.dni_txt input').attr('data-checking', 'true');
1457			$("#dni").attr("placeholder", $('.dni_txt').html());
1458		}
1459
1460	});
1461
1462	$("#email").blur(function () {
1463		var email = $(this).val();
1464		var regex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
1465		if (regex.test(email) == true) {
1466			$.ajax({
1467				type: "POST",
1468				data: { email: email },
1469				url: '/api-ajax/exist-email',
1470				success: function (msg) {
1471					if (msg.status == 'error') {
1472						emailExistErrorLoginPage();
1473						return;
1474					}
1475
1476					$("#erroremail").addClass("hidden");
1477				},
1478				error: function (response) {
1479					emailExistErrorLoginPage();
1480				}
1481			});
1482		} else {
1483			$("#erroremail").html(messages.error.email_invalid);
1484			$("#erroremail").removeClass("hidden");
1485		}
1486	});
1487
1488	$('#passRecovered').validator().on('submit', function (e) {
1489
1490		if (e.isDefaultPrevented()) {
1491			// formulario incorrecto
1492		} else {
1493			e.preventDefault();
1494			var $this = $(this);
1495
1496			$('button', $this).attr('disabled', 'disabled');
1497
1498			$.ajax({
1499				type: "POST",
1500				url: '/change-passw-user',
1501				data: $('#passRecovered').serialize(),
1502				success: function (response) {
1503					if (response.status == 'success') {
1504
1505						$("#modalMensaje #insert_msg").html(messages.success[response.msg]);
1506
1507						if ($("#login").val() == true) {
1508
1509							$.ajax({
1510								type: "POST",
1511								url: '/login_post_ajax',
1512								data: $('#passRecovered').serialize(),
1513								success: function (response) {
1514									if (response.status == 'success') {
1515										location.href = '/';
1516									} else {
1517										$(".message-error-log").text('').append(messages.error[response.msg]);
1518									}
1519
1520								}
1521							});
1522
1523						} else {
1524							setTimeout(function () {
1525								location.href = '/';
1526							}, 2000);
1527						}
1528
1529					} else {
1530						$('button', $this).removeAttr('disabled');
1531						$("#modalMensaje #insert_msg").html(messages.error[response.msg]);
1532					}
1533					$.magnificPopup.open({ items: { src: '#modalMensaje' }, type: 'inline' }, 0);
1534
1535				},
1536				error: function (response) {
1537					$('button', $this).removeAttr('disabled');
1538
1539					const errors = response.responseJSON.message;
1540					const html = errors.map(error => `<p>${error}</p>`).join('');
1541					$.magnificPopup.open({ items: { src: '#modalMensaje' }, type: 'inline' }, 0);
1542					$("#modalMensaje #insert_msg").html(html);
1543				}
1544			});
1545
1546		}
1547	});
1548});
1549
1550function emailExistErrorLoginPage() {
1551	if (typeof specificModalEmailExist === "function") {
1552		specificModalEmailExist();
1553		$("#erroremail").addClass("hidden");
1554		return;
1555	}
1556
1557	$("#erroremail").html(messages.error.email_exist);
1558	$("#erroremail").removeClass("hidden");
1559
1560}
1561
1562function emailExistErrorRegisterPage(response) {
1563	if (typeof specificModalEmailExist === "function") {
1564		specificModalEmailExist();
1565		return;
1566	}
1567
1568	muestra_error_input(document.getElementById("email__1__email"));
1569	$("#email__1__email").addClass("email-error");
1570
1571	let message = messages.error.email_exist;
1572	if (response.responseJSON && response.responseJSON.message) {
1573		message = response.responseJSON;
1574	}
1575
1576	showMessage(message);
1577}
1578
1579function cambiarDireccion(thi) {
1580	var idInput = $(thi).parents('.tab-pane').attr('id')
1581	var inputCambiar = $('.content-tabs').find('a[href="#' + idInput + '"]')
1582	var value = $(thi).val()
1583
1584	$(inputCambiar).find('.change_address').html(value);
1585
1586
1587}
1588
1589function ajax_shipping(cod_ship, lang) {
1590	return $.ajax({
1591		type: "GET",
1592		url: '/' + lang + '/seeShippingAddress',
1593		data: { codd_clid: cod_ship },
1594		success: function (response) {
1595			$("#ajax_shipping_add").html('');
1596			$("#ajax_shipping_add").html(response);
1597		}
1598	})
1599		.then((response) => {
1600			return response;
1601		});
1602}
1603
1604function changeCurrency(price, exchange, object) {
1605	price = Math.round(price * currency[exchange].impd_div * 100) / 100;
1606	if (typeof sindecimales != 'undefined' && sindecimales == true) {
1607		newPrice = numeral(price).format('0,0');
1608	} else {
1609		newPrice = numeral(price).format('0,0.00');
1610	}
1611	if (currency[exchange].pos_div == 'R') {
1612		newPrice += " " + currency[exchange].symbolhtml_div;
1613	} else {
1614		newPrice = currency[exchange].symbolhtml_div + newPrice;
1615	}
1616	$("#" + object).html(newPrice);
1617
1618}
1619
1620function changeCurrencyNew(price, exchange, object) {
1621	price = Math.round(price * currency[exchange].impd_div * 100) / 100;
1622
1623	newPrice = numeral(price).format('0,0.00');
1624
1625	if (currency[exchange].pos_div == 'R') {
1626		newPrice += " " + currency[exchange].symbolhtml_div;
1627	} else {
1628		newPrice = currency[exchange].symbolhtml_div + newPrice;
1629	}
1630	$(object).html(newPrice);
1631
1632}
1633
1634
1635function changeCurrencyWithElement(price, exchange, element) {
1636	price = Math.round(price * currency[exchange].impd_div * 100) / 100;
1637
1638	let newPrice = numeral(price).format('0,0.00');
1639	if (typeof sindecimales != 'undefined' && sindecimales == true) {
1640		newPrice = numeral(price).format('0,0');
1641	}
1642
1643	if (currency[exchange].pos_div == 'R') {
1644		newPrice += " " + currency[exchange].symbolhtml_div;
1645	} else {
1646		newPrice = currency[exchange].symbolhtml_div + newPrice;
1647	}
1648
1649	element.innerHTML = newPrice;
1650}
1651
1652function refreshCurrency() {
1653	$(".js-divisa").each(function () {
1654		let value = $(this).attr('value');
1655		if (value != "undefined") {
1656			changeCurrencyNew(value, $('#actual_currency').val(), $(this));
1657		}
1658	});
1659}
1660
1661$(document).ready(function () {
1662
1663	$("#actual_currency").change(function () {
1664
1665		refreshCurrency();
1666
1667		$.ajax({
1668			type: "POST",
1669			url: "/api-ajax/updateDivisa",
1670			data: { divisa: $("#actual_currency").val() },
1671			success: function (data) {
1672				console.log(data);
1673			}
1674		});
1675
1676
1677	});
1678});
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720/***************************************************************************************/
1721/*************************** FUNCIONES SOBRE MODAL DE COOKIES **************************/
1722/***************************************************************************************/
1723function acceptAllCookies() {
1724	updateConsent();
1725	fetch('/accept-all-cookies', {
1726		method: 'POST',
1727		headers: {
1728			'Content-Type': 'application/json',
1729			'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
1730		}
1731	}).then(function (response) {
1732		if (response.ok) {
1733			$(".cookies").fadeOut(500);
1734			$(".modal-cookies").modal('hide');
1735			location.reload();
1736		}
1737	});
1738}
1739
1740function rejectAllCookies() {
1741	fetch('/reject-all-cookies', {
1742		method: 'POST',
1743		headers: {
1744			'Content-Type': 'application/json',
1745			'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
1746		}
1747	}).then(function (response) {
1748		if (response.ok) {
1749			$(".cookies").fadeOut(500);
1750			$(".modal-cookies").modal('hide');
1751		}
1752	});
1753}
1754
1755function savePreferencesCookies() {
1756
1757	const isAnalysisActive = $("[name='permission_analysis']").is(":checked");
1758	const isAdvertisingActive = $("[name='permission_advertising']").is(":checked");
1759	if (isAnalysisActive) {
1760		updateConsent();
1761	}
1762	const data = {
1763		'analysis': isAnalysisActive ? 1 : 0,
1764		'advertising': isAdvertisingActive ? 1 : 0
1765	};
1766
1767	fetch('/save-preferences-cookies', {
1768		method: 'POST',
1769		headers: {
1770			'Content-Type': 'application/json',
1771			'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
1772		},
1773		body: JSON.stringify({ preferences: data })
1774	}).then(function (response) {
1775		if (response.ok) {
1776			$(".modal-cookies").modal('hide');
1777			location.reload();
1778		}
1779	});
1780}
1781
1782function saveConfigurationCookies(data) {
1783	fetch('/add-configurations-cookies', {
1784		method: 'POST',
1785		headers: {
1786			'Content-Type': 'application/json',
1787			'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
1788		},
1789		body: JSON.stringify({ configurations: data })
1790	}).catch(function (error) {
1791		console.log(error);
1792	});
1793}
1794
1795function updateConsent() {
1796	if (typeof gtag === 'function') {
1797		gtag('consent', 'update', {
1798			'ad_storage': 'granted',
1799			'ad_user_data': 'granted',
1800			'ad_personalization': 'granted',
1801			'analytics_storage': 'granted'
1802		});
1803	}
1804
1805}
1806
1807//
1808//  Función creada para poder debugar mostrando objetos
1809//
1810//  @obj - Objeto a mostrar
1811//
1812
1813function dump(obj) {
1814	var out = '';
1815	for (var i in obj) {
1816		out += i + ": " + obj[i] + "\n";
1817	}
1818
1819	showMessage(out, "DUMP");
1820
1821}
1822
1823
1824//
1825//  Función creada para agilizar los mensajes de modales. Es como un alert pero en modal y con la posibilidad de usar
1826//  los parametros de la libreria MessageLib
1827//
1828//  @data - Campo obligatorio donde recibimos un objeto de mensaje o un simple texto
1829//  @title - Titulo para el modal
1830//  @method - funcion a la que llamamos en caso de que se acepte.
1831//
1832
1833function showMessage(data, title, callbacks) {
1834
1835	let text = "";
1836	callbacks = callbacks || {};
1837
1838
1839	// TRATAMOS EL MENSAJE
1840	// Miramos si existe el mensaje traducido
1841
1842	if (typeof (data) != "undefined" && typeof (data.status) != "undefined" && typeof (data.message) != "undefined") {
1843		text = eval("messages." + data.status + "." + data.message);
1844	}
1845
1846	// Si no existe la traducción, miramos si podemos mostrar el mensaje tal cual
1847	if ((typeof (text) == "undefined" || text == "") && typeof (data) != "undefined" && typeof (data.message) != "undefined") {
1848		text = data.message;
1849	}
1850
1851	// Si no existe el objeto data y es solo un texto lo mostramos
1852	if ((typeof (text) == "undefined" || text == "") && data != "") {
1853		text = data;
1854	}
1855
1856	if (typeof (title) != "undefined") {
1857		$("#insert_msg_title").html(title);
1858	}
1859
1860	setTimeout("$('.popover').fadeOut(1000)", 4000);
1861
1862	$("#insert_msgweb").html(text);
1863	$.magnificPopup.open({
1864		items: { src: '#modalMensajeWeb' },
1865		type: 'inline',
1866		callbacks: callbacks
1867	}
1868		, 0);
1869
1870}
1871
1872
1873
1874
1875
1876
1877
1878
1879/****************************************************************************************/
1880/*************************** FUNCIONES SOBRE PANTALLA CONTACTO **************************/
1881/****************************************************************************************/
1882
1883async function sendContact() {
1884
1885	validateCaptchaMiddleware(() => {
1886		$.ajax({
1887			type: "POST",
1888			url: "/contactSendmail",
1889			data: $(contactForm).serialize(),
1890			success: function (response) {
1891				if (response.status == "error") {
1892					showMessage(response.message);
1893				} else {
1894					showMessage(response, "");
1895					setTimeout("location.reload()", 4000);
1896				}
1897			},
1898			error: function (response) {
1899				showMessage("Error");
1900			}
1901		});
1902	});
1903}
1904
1905
1906
1907
1908/****************************************************************************************/
1909/******************************* FUNCIONES SOBRE PANTALLA FAQS **************************/
1910/****************************************************************************************/
1911
1912
1913function FaqshowContent(id) {
1914	$(".faq").hide(500);
1915	$('#' + id).toggle('Drop');
1916
1917}
1918
1919function muestraSub(id) {
1920
1921	$(".subfamily").hide();
1922	$(".parent" + id).toggle('Drop');
1923	$(".parentFaq").hide();
1924}
1925
1926function muestraFaq(id) {
1927
1928	$(".parentFaq").hide();
1929	$(".parentFaq" + id).toggle('Blind');
1930}
1931
1932
1933
1934$(document).ready(function () {
1935	$(".signIn").on("click", function () {
1936
1937		$(".login_desktop").fadeIn();
1938	});
1939});
1940
1941
1942function trans(key = null, replace = {}, locale = null) {
1943
1944	const keys = key.split('.');
1945	const existTranslate = typeof translates != 'undefined' && typeof translates[keys[0]] != 'undefined' && typeof translates[keys[0]][keys[1]] != 'undefined';
1946
1947	if (!existTranslate) {
1948		return key;
1949	}
1950
1951	let string = translates[keys[0]][keys[1]];
1952	Object.keys(replace).map(function (value) {
1953
1954		let str1 = `:${value}`;
1955		let re = new RegExp(str1, "i");
1956		string = string.replace(re, replace[value]);
1957
1958	});
1959
1960
1961	return string;
1962}
1963
1964function openLogin() {
1965	//por si venimos de un moda, no afecta a nada mas
1966	$.magnificPopup.close();
1967	$('.login_desktop').fadeToggle("fast");
1968	$('.login_desktop [name=email]').focus();
1969}
1970
1971
1972function markCurrentPageHeader(exceptions) {
1973
1974	const urlArray = window.location.pathname.split('/');
1975	const section = urlArray[2];
1976	var menuItems = $('.menu-principal-content').find('li');
1977
1978	for (const value of exceptions) {
1979		if (section == value) {
1980			return;
1981		}
1982	}
1983
1984	menuItems.each(function () {
1985
1986		$(this).find('a').attr('href')
1987		var link = $(this).find('a').attr('href').includes(section)
1988		if (link) {
1989			$(this).find('a').addClass('color-brand')
1990		}
1991	});
1992}
1993
1994function sharePage({ text, title, url }) {
1995
1996	if (navigator.share) {
1997		navigator.share({ title, text, url })
1998			.then(() => console.log('Successful share'))
1999			.catch((error) => console.log('Error sharing', error));
2000	}
2001	else {
2002		const shareUrl = `mailto:?subject=${title}&body=${text} ${url}`;
2003		window.open(shareUrl, '_blank');
2004	}
2005}
2006
2007
2008// Retrasar la ejecución de una función hasta que el usuario deje de escribir
2009let debounceTimeoutId;
2010function debounce(func, delay) {
2011	clearTimeout(debounceTimeoutId);
2012	debounceTimeoutId = setTimeout(func, delay);
2013}
2014
2015/* inputElement.addEventListener('input', function() {
2016   debounce(function() {
2017	   // Aquí puedes agregar el código para enviar el formulario
2018	   console.log('Enviar formulario');
2019   }, 500); // 500 milisegundos (0.5 segundos) de pausa
2020}); */
2021
2022function validateCaptchaMiddleware(callback, arg) {
2023	isValidCaptcha().then((result) => {
2024		if (result) {
2025			callback(arg);
2026			return;
2027		}
2028
2029		showMessage(messages.error.recaptcha_incorrect);
2030	});
2031}
2032
2033
2034async function isValidCaptcha() {
2035
2036	// Si es un captcha v3
2037	if (isV3Captcha()) {
2038		return await checkCaptchaV3();
2039	}
2040
2041	// Si es un captcha v2
2042	$(".g-recaptcha").find("iframe").removeClass("has-error");
2043	const resutl = Boolean($("#g-recaptcha-response").val());
2044	if (!resutl) {
2045		$(".g-recaptcha").find("iframe").addClass("has-error");
2046	}
2047
2048	return resutl;
2049}
2050
2051function isV3Captcha() {
2052	return $("[name=captcha_token]").length > 0;
2053}
2054
2055async function checkCaptchaV3() {
2056	await executeCaptchaV3();
2057
2058	const response = document.querySelector('[name="g-recaptcha-response"]').value;
2059	return Boolean(response);
2060}
2061
2062async function executeCaptchaV3() {
2063	const captchaElemenent = document.querySelector('[name="captcha_token"]');
2064
2065	if (!captchaElemenent) return;
2066
2067	const key = captchaElemenent.getAttribute('data-sitekey');
2068
2069	return new Promise((resolve, reject) => {
2070
2071		grecaptcha.ready(function () {
2072			grecaptcha.execute(key, { action: 'submit' })
2073				.then(function (token) {
2074
2075					if (!token) reject('No token found');
2076
2077					//recorrecmos todos para que en paginas con varios formularios se rellenen todos
2078					document.querySelectorAll('[name="captcha_token"]')
2079						.forEach(captchaElemenent => {
2080							captchaElemenent.value = token;
2081						});
2082
2083					resolve();
2084				});
2085		});
2086	});
2087}
2088
2089function cleanUrl() {
2090	// Obtén la URL actual
2091	const url = new URL(window.location.href);
2092	const params = new URLSearchParams(url.search);
2093
2094	const paramsObject = Object.fromEntries(params);
2095	const emptyKeys = Object.entries(paramsObject).filter(([_, value]) => value === '');
2096
2097	emptyKeys.forEach(([key]) => params.delete(key));
2098
2099	// Actualiza la URL sin recargar la página
2100	url.search = params.toString();
2101	window.history.replaceState({}, '', url.toString());
2102}
2103
2104async function getCarousel(key, data) {
2105
2106	const locale = getLocale()
2107	const url = `/${locale}/carousel/${key}`;
2108
2109	return fetch(url, {
2110		method: 'POST',
2111		headers: {
2112			'Content-Type': 'application/json',
2113			'Accept': 'application/json',
2114			'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
2115		},
2116		body: JSON.stringify(data)
2117	})
2118	.then(response => response.text())
2119}
2120
2121function getLocale() {
2122	const meta = document
2123		.querySelector('meta[name="app-locale"]');
2124
2125	if(!meta) {
2126		return 'es';
2127	}
2128
2129	return meta.getAttribute('content');
2130}
2131
2132async function initPush() {
2133	try {
2134		const vapidKey = getVapidKey();
2135
2136		if (!isPushSupported()) return;
2137
2138		await registerServiceWorker();
2139
2140		const permission = await requestNotificationPermission();
2141		console.log('Notification permission:', permission);
2142
2143		if (permission !== 'granted') return;
2144
2145		const subscription = await subscribeUser(vapidKey);
2146		await sendSubscriptionToServer(subscription);
2147
2148		console.log('Push subscription completed:', subscription);
2149
2150	} catch (error) {
2151		console.error('Push setup error:', error);
2152	}
2153}
2154
2155function getVapidKey() {
2156	return document
2157		.querySelector('meta[name="vapid-public-key"]')
2158		.getAttribute('content');
2159}
2160
2161function isPushSupported() {
2162	return 'serviceWorker' in navigator && 'PushManager' in window;
2163}
2164
2165async function requestNotificationPermission() {
2166	return await Notification.requestPermission();
2167}
2168
2169async function subscribeUser(vapidKey) {
2170	const reg = await navigator.serviceWorker.ready;
2171
2172	const subscription = await reg.pushManager.subscribe({
2173		userVisibleOnly: true,
2174		applicationServerKey: vapidKey
2175	});
2176
2177	return subscription;
2178}
2179
2180async function sendSubscriptionToServer(subscription) {
2181	await fetch('/api/push/subscribe', {
2182		method: 'POST',
2183		headers: {
2184			'Content-Type': 'application/json'
2185		},
2186		body: JSON.stringify(subscription)
2187	});
2188}

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.