PageSourceSearch

https://sede.getafe.es/sta/pages/webapps/js/webAppsFwk.js?ver=2605.0.3

js getafe.es collected 2026-10-02 03:12:59 UTC 86,696 bytes, 2,448 lines download raw bytes

1function showImg(uri)
2{
3	//if (!uri.toLowerCase().startsWith('http'))
4	if (!uri.toLowerCase().lastIndexOf('http', 0) === 0)
5		uri = document.location.protocol +"//"+ document.location.hostname + uri;
6	
7	if (!sta.kiosco)
8	{
9		jQuery("<a>").prop({ target: "_blank", href: uri })[0].click();
10	}
11	else
12	{
13		jQuery('.iziModal').iziModal('close');
14		
15		
16		ops = {
17				title :"Imagen de muestra",
18				iframe: true,
19				iframeURL: uri,
20				fullscreen: true,
21				openFullscreen: false,
22				iframeHeight: 800,
23					
24					
25				headerColor: '#666'
26		};
27		var modal = jQuery('<div class="iModal-message light" />');
28		
29		modal.prependTo('body');
30		modal.iziModal(ops);
31		modal.iziModal('open');
32	}
33}
34//--------------------------------------------------------------------------------------
35function sessionAlert(callback, cancelCallback)
36{
37	console.log('--- timeout to  alert session!!!');
38
39	//Condiciones para activar el alert:
40//	if (sta.sessionTimeOut.active &&
41//	   (sta.sessionTimeOut.sessionRequired || sta.identificado))
42	{
43		var ops = {
44			    title: sta.literales.ses_Titulo,
45			    headerColor: '',
46				padding: '',
47				claseCss: '',
48				icon: 'alarm',
49				status:'warning',
50				
51			    transitionIn: 'bounceInDown',
52			    transitionOut: 'comingOut',
53			    onClosing:function(oModal){
54			    	if (oModal.closeSession != true)
55			    		if (sta.sessionTimeOut.expired == true)
56			    			jQuery("<a>").prop('href',sta.sessionTimeOut.url)[0].click();
57			    		else
58			    			sessionTimeOutOnContinue();
59			    },
60			    onClosed: function(oModal){
61			    	oModal.$element.remove();
62			    	freeModalWAIA(oModal);
63			    },
64			    onOpened: function(oModal){
65			    	
66			    	sta.sessionTimeOut.alertTime = sta.sessionTimeOut.alertTimeCfg;
67			    	sessionTimeOutPaintCountdown();
68			    	sta.sessionTimeOut.countdown = setInterval(sessionTimeOutAlertCountdown,1000,oModal);
69			    	
70		 			setModalWAIA(oModal);
71				}		    
72			};	
73		
74		var footer = '<div class="modal-footer session-alert">' +
75		'<a href="#" class="ui-btn medio confirmar primary default-focus" ><span class="a-text">' + sta.literales.ses_continue + '</span></a>' +				
76		'<a href="#" class="ui-btn medio cancelar secondary" ><span class="a-text">' + sta.literales.ses_logout + '</span></a>' + 					
77		'</div>';
78		
79		var modal = jQuery('<div class="iModal-session">' +
80					'<div class="contenido-mensaje ' + ops.claseCss  + '">' +
81					//'<svg class="icon warning"><use xlink:href="#icon-warning"></use></svg>' +
82					'<div class="session-body"><div class="session-body-info">' + sta.literales.ses_msg + '</div>'+
83					'<div id="session-body-time" class="session-body-time"></div>' + 
84					'<div class="session-body-question">' + sta.literales.ses_question + '</div></div></div>' + footer + '</div>');
85		
86		modal.prependTo('body');
87		modal.iziModal(ops);
88		var oModal = modal.data('iziModal')
89		oModal.oldFocus = document.activeElement;	
90		document.activeElement.blur();
91		modal.iziModal('open');
92		
93		jQuery("#" + modal.prop('id') + " a.cancelar").on("click",function() {
94			event.preventDefault();
95			modal.data('iziModal').closeSession=true;
96			sessionTimeOutOnCancel();
97			modal.iziModal('close');
98	    });
99		oModal.$element.on("click","a.confirmar",function() {
100			console.log('confirmar!');
101			event.preventDefault();
102			modal.iziModal('close');
103	    });
104	}
105}
106//--------------------------------------------------------------------------------------
107
108function messageDialog(opciones, message,closeCallback)
109{	
110	if (opciones.ajax != null)
111	{
112		
113	}
114	else if (message == null)
115	{
116		message = opciones.titulo;
117		opciones.titulo = sta.literales.msg_Titulo;
118	}
119	
120	if (opciones.status == 'ok')
121	{
122		opciones.titulo =  sta.literales.ok_Titulo;
123		if (!opciones.bigIcon)
124			opciones.icon = 'ok';
125		opciones.boton = 'secondary';
126	}
127	if (opciones.status == 'info')
128	{
129		opciones.titulo =  'Info';
130		if (!opciones.bigIcon)
131			opciones.icon = 'info';
132		opciones.boton = 'secondary';
133	}	
134	else if (opciones.status == 'warning')
135	{
136		opciones.titulo =  sta.literales.warning_Titulo;
137		if (!opciones.bigIcon)
138			opciones.icon = 'warning';
139		opciones.boton = 'secondary';
140	}
141	else if (opciones.status == 'error')
142	{
143		if (!opciones.bigIcon)
144			opciones.icon = 'error';
145		opciones.titulo = sta.literales.error_Titulo;
146		opciones.boton = 'secondary';
147	}
148	if (opciones.status == 'cesta')
149	{
150		if (!opciones.bigIcon)
151			opciones.icon = 'cart';
152		opciones.titulo =  '';
153		opciones.boton = 'secondary';
154	}
155	else if (opciones.titulo == null)
156		opciones.titulo = sta.literales.msg_Titulo;
157		
158	if (opciones.light)
159	{
160		// Cerrar abiertos:
161		jQuery('.iziModal').iziModal('close');
162		
163		opciones.titulo = message;
164	    
165		var words = message.split(' ');
166	    //var time = 4000 + words.length * 150;
167		var time = ((words.length/200 * 60000) +  (message.length * 40))/2
168		
169	    if (words.length < 8)
170	    	time = 1500;
171		
172		
173	    opciones.timeout = time;
174		
175		opciones.timeoutProgressbar = true;
176		opciones.pauseOnHover = true;
177		opciones.top = 0;
178		opciones.overlay= false;
179		opciones.overlayClose= true;
180		opciones.transitionIn= 'fadeInDown';
181		opciones.transitionOut= 'fadeOutUp';	
182	}
183		
184	var ops = jQuery.extend({},{
185		    title: opciones.titulo,
186		    status: 'normal',
187		    headerColor: '',
188			padding: '',
189		    transitionIn: 'bounceInDown',
190		    transitionOut: 'bounceOutDown',
191		    boton: 'secondary',
192		    
193		    onClosing:function(oModal){
194		    	if (closeCallback)
195		    		closeCallback();
196		    },
197		    onClosed: function(oModal){
198		    	oModal.$element.remove();
199		    	if (!opciones.light)
200		    		freeModalWAIA(oModal);		    	
201		    },
202		    onOpening: function(oModal){
203		    	
204		    	if (opciones.ajax != null)
205		    	{
206		    		oModal.startLoading();
207		        	jQuery.get(opciones.ajax,
208		        			   jQuery(document.forms["webAppPageForm"]).serialize() + '&noPageCall=true',
209		        			   function(data) {
210		        		jQuery("#" + oModal.id + " .message-text").html(data);
211		        		oModal.stopLoading();
212		        	});	
213		    	}
214		    },
215		    onOpened: function(oModal){
216		    	if (!opciones.light)
217		    		setModalWAIA(oModal);
218			}		    
219		},
220		opciones);
221	
222	
223	
224	var modal = jQuery('<div class="iModal-message light ' + ops.status + '"/>');
225	if (!opciones.light)
226	{
227		var footer = '<div class="modal-footer">' +
228		'<a href="#" class="ui-btn medio cerrar default-focus ' + ops.boton + '" ><span class="a-text">' + sta.literales.msg_Cerrar + '</span></a>' + 					
229		'</div>';
230
231		var bigIcon = '';
232		if (opciones.bigIcon)
233			bigIcon = '<svg class="icon ' + ops.status + '"><use xlink:href="#icon-' + ops.status + '"></use></svg>';
234
235		modal = jQuery('<div class="iModal-message ' + ops.status + '">' +
236				    '<div class="contenido-mensaje">' +  bigIcon +				
237					'<div class="message-text">' + message + '</div></div>' + 
238					footer + '</div>');
239	}
240	
241	modal.prependTo('body');
242	modal.iziModal(ops);
243	if (!opciones.light)
244	{
245		modal.data('iziModal').oldFocus = document.activeElement;	
246		document.activeElement.blur();
247	}
248	modal.iziModal('open');
249	
250	jQuery("#" + modal.prop('id') + " a.cerrar").on("click",function() {
251		event.preventDefault();
252		modal.iziModal('close');
253    });
254}
255function pedirConfirmacion(opciones,message, callback, cancelCallback, precondition)
256{
257	if (precondition != null && precondition!='' && window[precondition]() == false)
258	{
259		callback();
260		return true;
261	}
262	var ops = jQuery.extend({},{
263		    title: sta.literales.conf_Titulo,
264		    headerColor: '',
265			padding: '',
266			claseCss: '',
267			
268		    transitionIn: 'bounceInDown',
269		    transitionOut: 'comingOut',
270		    onClosing:function(oModal){
271		    	
272		    	if (oModal.confirm != true &&  cancelCallback)
273		    		cancelCallback();
274		    },
275		    onClosed: function(oModal){
276		    	oModal.$element.remove();
277		    	freeModalWAIA(oModal);
278		    },
279		    onOpened: function(oModal){
280	 			setModalWAIA(oModal);
281			}		    
282		},
283		opciones);	
284	
285	var footer = '<div class="modal-footer">' +
286	'<a href="#" class="ui-btn medio cancelar secondary default-focus" ><span class="a-text">' + sta.literales.conf_Cancelar + '</span></a>' + 					
287	'<a href="#" class="ui-btn medio confirmar primary" ><span class="a-text">' + sta.literales.conf_Aceptar + '</span></a>';					
288	'</div>';
289	
290	var modal = jQuery('<div class="iModal-confirm">' +
291				'<div class="contenido-mensaje ' + ops.claseCss  + '">' +
292				'<svg class="icon warning"><use xlink:href="#icon-warning"></use></svg>' +
293				'<div class="confirm-text">' + message + '</div></div>' + 
294				footer + '</div>');
295	
296	modal.prependTo('body');
297	modal.iziModal(ops);
298	modal.data('iziModal').oldFocus = document.activeElement;	
299	document.activeElement.blur();
300	modal.iziModal('open');
301	
302	jQuery("#" + modal.prop('id') + " a.cancelar").on("click",function() {
303		event.preventDefault();
304		modal.iziModal('close');
305    });
306	jQuery("#" + modal.prop('id') + " a.confirmar").on("click",function() {
307		event.preventDefault();
308		callback();
309		modal.data('iziModal').confirm=true;
310		modal.iziModal('close');
311    });
312}
313
314function modalDialog(opciones,bodyId,callbackOptions,cancelCallback,openCallback)
315{
316	var ops = jQuery.extend({},{
317	    headerColor: '',
318		padding: '',
319		claseCss: '',
320		overlayClose: false,
321		closeOnEscape: false,
322	    transitionIn: 'bounceInDown',
323	    transitionOut: 'bounceOutDown',
324	    onClosing:function(oModal){	    	
325	    	if (oModal.confirm != true &&  cancelCallback)
326	    		cancelCallback(opciones.data);
327	    },
328	    onClosed: function(oModal){
329	    	oModal.$element.remove();
330	    	freeModalWAIA(oModal);
331	    },
332	    onOpening: function(oModal){
333	    	if (openCallback)
334				openCallback(opciones.data);
335		},
336	    onOpened: function(oModal){
337	    	setModalWAIA(oModal);
338		}
339	},
340	opciones);	
341	
342	var footer = '<div class="modal-footer">' +
343	'<a href="#" class="ui-btn medio cancelar secondary" ><span class="a-text">' + sta.literales.conf_Cancelar + '</span></a>' + 					
344	'<a href="#" class="ui-btn medio confirmar primary" ><span class="a-text">' + (opciones.literals?.conf_Aceptar ?? sta.literales.conf_Aceptar) + '</span></a>';					
345	'</div>';
346	
347	var modal = jQuery('<form id="webAppPageForm2" class="' + opciones.className + '" name="webAppPageForm2" action="submitAjax.aa" accept-charset="utf-8" method="post">' +
348							footer + '</form>');
349	
350	modal.prependTo('body');
351	
352	// Se recupera el contenido del modal desde un template y se añade al formulario del modal. Se hace así para que el contenido del modal pueda contener elementos como selectores de fecha, tablas, etc que necesitan estar en el DOM para inicializarse correctamente. Además, de esta forma se pueden reutilizar templates ya existentes en la página para mostrar su contenido en un modal sin necesidad de duplicar código.
353	const template = document.getElementById(bodyId);
354	if (template != undefined && template.content != undefined)
355	{
356		const clone = template.content.cloneNode(true);
357		var myClone = clone.querySelector('.content2Modal');
358		if (myClone.length == 0)
359			alert('No se ha encontrado el template con el contenido del modal: ' + bodyId);
360		myClone.id = "modalForm";
361		document.getElementById('webAppPageForm2').prepend(myClone);
362	}
363	else // si no hay template
364	{
365		var myClone = jQuery(bodyId + ' > .content2Modal').clone();
366		if (myClone.length == 0)
367			alert('No se ha encontrado el contenido del modal: ' + bodyId);
368		myClone.attr("id", "modalForm");
369		myClone.prependTo('#webAppPageForm2');
370	}
371		
372	// si se trata de una acción de postback, se activa la validación del formulario
373	const postbackAction = (callbackOptions.eventAction !== undefined);
374	
375	if (postbackAction)
376		window._FormValidator2 = modal.validate(
377		{
378			errorClass: "invalidMessage",
379			errorElement: "div",
380			errorPlacement: sta.customValidation.customErrorPlacement,
381			showErrors: sta.customValidation.customErrorShow,
382			success: sta.customValidation.customErrorSuccess			
383		});	
384	
385
386	modal.iziModal(ops);
387	modal.data('iziModal').oldFocus = document.activeElement;
388	document.activeElement.blur();
389	modal.iziModal('open');
390	//modal.iziModal('startLoading');
391	
392
393	
394	jQuery("#" + modal.prop('id') + " a.cancelar").on("click",function() {
395		event.preventDefault();
396		modal.iziModal('close');
397    });
398	jQuery("#" + modal.prop('id') + " a.confirmar").on("click",function() {
399		event.preventDefault();
400
401		if (postbackAction && window._FormValidator2.form())
402		{
403			// Si no hay función de validación o si la función de validación devuelve true, se hace la llamada ajax, sino se mantiene el modal abierto para que el usuario pueda corregir los errores.
404			if (typeof opciones.onValidateAsync === "function")
405			{
406				//modal.iziModal('startLoading');
407				opciones.onValidateAsync(opciones.data,modal)
408				  .then(res => { 
409					console.log("Resultado:", res);
410					callbackOptions.eventArguments = callbackOptions.eventArguments +='&validationResponse=' + JSON.stringify(res);  	
411					callWidgetEventAjaxForm2(callbackOptions,modal);
412				})
413				  .catch(err => console.error("No se procede con la acción del modal ya que la validación a fallado:", err));
414			}
415			else if (typeof opciones.onValidate !== "function" || 
416					(opciones.onValidate(opciones.data,modal)))
417			{	
418				callWidgetEventAjaxForm2(callbackOptions,modal);
419			}				 					
420		}
421		else
422		{
423			if (typeof callbackOptions.onAccept  === "function")
424			{
425				modal.data('iziModal').confirm=true;
426				modal.iziModal('close');
427				callbackOptions.onAccept(opciones.data);
428			}
429		}
430    });
431
432}
433var alertOk= function (mensaje,callback){
434	messageDialog({status:'ok',bigIcon: true},mensaje,callback);
435}
436var alertInfo= function (mensaje,callback){
437	messageDialog({status:'info',bigIcon: true},mensaje,callback);
438}
439var alertAviso= function (mensaje,callback){
440	messageDialog({status:'warning',bigIcon: true},mensaje,callback);
441}
442var alertError = function (mensaje,callback){
443	messageDialog({status:'error',bigIcon: true},mensaje,callback);
444}
445var informarOk= function (mensaje,callback){
446	messageDialog({status:'ok',light: true},mensaje,callback);	
447}
448var informarCesta= function (mensaje,callback){
449	messageDialog({status:'cesta',width: 350 ,light: true},mensaje,callback);	
450}
451var informarAviso= function (mensaje,callback){
452	messageDialog({status:'warning',light: true},mensaje,callback);	
453}
454var informarError= function (mensaje,callback){
455	messageDialog({status:'error',light: true},mensaje,callback);	
456}
457
458const getAjaxData = function (extraData){
459	 	return jQuery(document.forms["webAppPageForm"]).serialize() + '&noPageCall=true' + (extraData? '&' + extraData : '');
460	 }
461
462const waAjaxOpcionesDefecto = {
463	    url: "submitAjax.aa",
464	    data: getAjaxData,
465		contentType: "application/x-www-form-urlencoded;charset=utf-8",        
466	    type: "POST",
467	    dataType: "json",
468	    timeout: 400000
469	};
470
471var waAjax = function(opciones)
472{
473	waAjaxOpcionesDefecto.data = getAjaxData(opciones.extraData)
474	return jQuery.ajax(jQuery.extend(true,{},waAjaxOpcionesDefecto,opciones));
475	
476};	
477var waJSON = function(op,params,success,opciones)
478{
479	var opcionesDefecto = {
480	    url: "/sta/waresources",
481		data:  "op=" + op + params,
482		contentType: "application/x-www-form-urlencoded;charset=utf-8",        
483	    type: "POST",
484	    dataType: "json",
485	    timeout: 60000,
486	    success: function(data){
487			if (data != null)
488			{
489				success(data);
490			}
491			else
492			{
493				console.log('Error en la llamada AJAX a waresources:' + data)
494			}
495	    
496	    }
497	}
498	jQuery.extend(true,opciones,opcionesDefecto);
499	return jQuery.ajax(opciones);
500};	
501
502
503callWidgetEventAjaxForm2 = function(options,modal){
504
505	var form2 = jQuery('#webAppPageForm2');
506	jQuery("<input>").attr({'type':'hidden','name':'eventScreenId'}).val(options.eventScreenId).appendTo(form2);
507	jQuery("<input>").attr({'type':'hidden','name':'eventObject'}).val(options.eventObject).appendTo(form2);
508	jQuery("<input>").attr({'type':'hidden','name':'eventAction'}).val(options.eventAction).appendTo(form2);
509	jQuery("<input>").attr({'type':'hidden','name':'eventArguments'}).val(options.eventArguments).appendTo(form2);
510	jQuery("<input>").attr({'type':'hidden','name':'eventComponent'}).val(options.eventComponent).appendTo(form2);
511	jQuery("<input>").attr({'type':'hidden','name':'PAGE_CODE'}).val(jQuery("#PAGE_CODE").val()).appendTo(form2);
512	jQuery("<input>").attr({'type':'hidden','name':'APP_CODE'}).val(jQuery("#APP_CODE").val()).appendTo(form2);
513	jQuery("<input>").attr({'type':'hidden','name':'PAGE_COMPLETE'}).val(jQuery("#PAGE_COMPLETE").val()).appendTo(form2);
514	jQuery("<input>").attr({'type':'hidden','name':'ROOTID'}).val(jQuery("#ROOTID").val()).appendTo(form2);
515	jQuery("<input>").attr({'type':'hidden','name':'HFC'}).val(jQuery("#HFC").val()).appendTo(form2);
516	jQuery("<input>").attr({'type':'hidden','name':'SESSION_REQUIRED'}).val(jQuery("#SESSION_REQUIRED").val()).appendTo(form2);
517	jQuery("<input>").attr({'type':'hidden','name':'noPageCall'}).val(true).appendTo(form2);
518
519	//mostrarCargando();	//mostramos el div de "buscando"
520	
521	modal.iziModal('startLoading');
522	
523	jQuery.ajax({
524					type: "POST",
525					url: "submitAjax.aa",
526					data: form2.serialize(),
527					contentType: "application/x-www-form-urlencoded;charset=UTF-8",
528					success: function( json ) {
529						jQuery("#webAppPageForm2 .content2Modal > div.Informativo").remove();
530						
531						if (json.result)
532						{
533							modal.data('iziModal').confirm=true;
534							modal.iziModal('close');
535							options.success(json.data,options);
536						}
537						else
538						{
539							if (json.errorMessage == undefined)
540								json.errorMessage = "Se ha producido un error (" + json.errorCode+ ")";
541							jQuery('<div class="Informativo warning">' + 
542									(sta.responsive?'<svg class="icon icon-warning"><use xlink:href="#icon-warning"></use></svg>':'') 
543									+
544								   '<div class="Informativo-body">' + json.errorMessage + '</div>').prependTo(jQuery('#webAppPageForm2 .content2Modal'));
545						}
546						modal.iziModal('stopLoading');
547					},
548					dataType: 'json',
549					error: function( jqxhr, textStatus, error ) {
550						modal.iziModal('stopLoading');
551						var err = textStatus + ", " + error;
552						alert( "Se ha producido un error: " + err );
553					}
554	});
555}
556
557// seleccionar o crear cuenta bancaria:
558function initDomCuentas(prefixSelector)
559{
560	if (prefixSelector == undefined)
561		prefixSelector='';
562	console.log('Se inicializa el form de cuentas con el prefijo:'+ prefixSelector);
563	jQuery(prefixSelector + 'input[name="op-cuenta"]').each(function(){
564		console.log('input cuentas checked.attr=' + jQuery(this).attr( "checked" ) + ' ,prop = ' +  jQuery(this).prop( "checked" ) );
565		jQuery(this).prop('id', jQuery(this).prop('id').replace('TEMPLATE_','')); 
566		jQuery(this).change(function(e) {
567			e.preventDefault();
568			var opcion = jQuery(prefixSelector + 'input[name="op-cuenta"]:checked').val(); 
569			var speed = 300;
570			if (opcion == 1)
571			{
572				jQuery(prefixSelector + '.box-nueva-cuenta').slideUp(speed,function(){jQuery(this).addClass('ocultar')});
573				jQuery(prefixSelector + '.box-lista-cuentas').removeClass('ocultar').slideDown(speed);
574			}
575			else if (opcion == 2)
576			{
577				jQuery(prefixSelector + '.box-lista-cuentas').slideUp(speed,function(){jQuery(this).addClass('ocultar')});
578				jQuery(prefixSelector + '.box-nueva-cuenta').removeClass('ocultar').slideDown(speed);
579			}
580		});	
581	});
582	
583	// ya que en IE se pierde el checked y hay que forzarlo por código.
584	if (jQuery('#webAppPageForm2 #lista-cuentas input[name="op-cuenta"]').length > 0)
585		jQuery('#webAppPageForm2 #lista-cuentas input[name="op-cuenta"]').prop('checked',true);
586	else
587		jQuery('#webAppPageForm2 #nueva-cuenta input[name="op-cuenta"]').prop('checked',true);
588	
589	
590	
591//	jQuery('#iban_select').change(function() {
592//		var checkSelector = jQuery(this);
593//		checkSelector.attr("disabled", true);
594//	    if(jQuery(this).is(":checked")) {
595//	        jQuery('#nueva-cuenta-old').slideUp(200,function(){jQuery('#nueva-cuenta-iban').slideDown(200,function(){checkSelector.removeAttr("disabled");});});
596//	    }
597//	    else
598//	    {
599//	    	jQuery('#nueva-cuenta-iban').slideUp(200,function(){jQuery('#nueva-cuenta-old').slideDown(200,function(){checkSelector.removeAttr("disabled");});});   
600//	    }
601//	});
602	/*
603	 var jump = false;
604	 jQuery(".iban input, #nueva-cuenta-old input").keydown(function(e) {
605		 	jump = false;
606		    var charLimit = this.maxLength;
607	        var keys = [8, 9, 16, 17, 18, 19, 20, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 144, 145];
608
609	        if (e.ctrlKey && ( e.keyCode == 67  || e.keyCode == 86 || e.keyCode == 88 ))
610	        	return true;
611	        else if (e.which == 8 && this.value.length == 0)
612	        	focusPrev(this);
613	        else if (jQuery.inArray(e.which, keys) >= 0)
614	            return true;
615	        else if (e.shiftKey)
616	            return false;
617	        else if ((e.which >= 48 && e.which <= 57) || // Si es un numerico normal
618	        		 (e.which >= 96 && e.which <= 105))
619        	{ 
620	        	if (this.value.length >= charLimit-1) // Si falta un caracter se puede saltar al siguiente
621	        		jump = true;
622        		return true;
623	        }
624    		return false;
625	    }).keyup (function (e) {
626	    	if (e.which == 9)
627	    		return true;
628	    	else if (jump && this.value.length >= this.maxLength)
629	    	{
630	    		focusNext(this);
631	            return false;
632	        }
633	    	else
634	    		return true;
635	    });	
636	 
637	 */
638}
639function focusNext(ele)
640{
641	if (jQuery(ele).parent().is("td"))
642		jQuery(ele).parent().next().children().focus();
643	else
644		jQuery(ele).next().focus();
645}
646function focusPrev(ele)
647{
648	if (jQuery(ele).parent().is("td"))
649		jQuery(ele).parent().prev().children().focus();
650	else
651		jQuery(ele).prev().focus();
652}
653
654
655/* ----------------
656ResponsiveTabs.js
657Author: Pete Love | www.petelove.com
658Version: 1.10
659------------------- */
660
661var RESPONSIVEUI = {};
662
663(function($) {
664
665	RESPONSIVEUI.responsiveTabs = function () {
666		var $tabSets = jQuery('.responsive-tabs:not(.template)');
667
668		if (!$tabSets.hasClass('responsive-tabs--enabled')) {	// if we haven't already called this function and enabled tabs
669			$tabSets.addClass('responsive-tabs--enabled'); 
670			$tabSets.prop('hidden',false); 
671
672			//loop through all sets of tabs on the page
673			var tablistcount = 1;
674
675			$tabSets.each(function() {
676
677				var $tabs = jQuery(this);
678
679				// add tab heading and tab panel classes
680				$tabs.children('.htab').addClass('responsive-tabs__heading');
681				$tabs.children('div:not(.htab)').addClass('responsive-tabs__panel');
682
683				// determine if markup already identifies the active tab panel for this set of tabs
684				// if not then set first heading and tab to be the active one
685				var $activePanel = $tabs.find('.responsive-tabs__panel--active');
686				if(!$activePanel.length) {
687					$activePanel = $tabs.find('.responsive-tabs__panel').first().addClass('responsive-tabs__panel--active');
688				}
689
690				$tabs.find('.responsive-tabs__panel').not('.responsive-tabs__panel--active').hide().attr('aria-hidden','true'); //hide all except active panel
691				$activePanel.attr('aria-hidden', 'false');
692				/* make active tab panel hidden for mobile */
693				$activePanel.addClass('responsive-tabs__panel--closed-accordion-only');
694
695				// wrap tabs in container - to be dynamically resized to help prevent page jump
696				var $tabsWrapper = jQuery('<div/>', {'class': 'responsive-tabs-wrapper' });
697				$tabs.wrap($tabsWrapper);
698
699				var highestHeight = 0;
700
701				// determine height of tallest tab panel. Used later to prevent page jump when tabs are clicked
702				$tabs.find('.responsive-tabs__panel').each(function() {
703					var tabHeight = jQuery(this).height();
704					if (tabHeight > highestHeight) {
705						highestHeight = tabHeight;
706					}
707				});
708
709				//create the tab list
710				var $tabList = jQuery('<ul/>', { 'class': 'responsive-tabs__list', 'role': 'tablist' });
711
712				//loop through each heading in set
713				var tabcount = 1;
714				$tabs.find('.responsive-tabs__heading').each(function() {
715
716					var $tabHeading = jQuery(this);
717					var $tabPanel = jQuery(this).next();
718
719					$tabHeading.attr('tabindex', 0);
720
721					// CREATE TAB ITEMS (VISIBLE ON DESKTOP)
722					//create tab list item from heading
723					//associate tab list item with tab panel
724					var $tabListItem = jQuery('<li/>', { 
725						'class': 'responsive-tabs__list__item',
726						id: 'tablist' + tablistcount + '-tab' + tabcount,
727						'aria-controls': 'tablist' + tablistcount +'-panel' + tabcount,
728						'role': 'tab',
729						tabindex: 0,
730						text: $tabHeading.text(),
731						keydown: function (objEvent) {
732							if (objEvent.keyCode === 13) { // if user presses 'enter'
733								$tabListItem.click();
734							}
735						},
736						click: function() {
737							//Show associated panel
738
739							//set height of tab container to highest panel height to avoid page jump
740							$tabsWrapper.css('height', highestHeight);
741
742							// remove hidden mobile class from any other panel as we'll want that panel to be open at mobile size
743							$tabs.find('.responsive-tabs__panel--closed-accordion-only').removeClass('responsive-tabs__panel--closed-accordion-only');
744							
745							// close current panel and remove active state from its (hidden on desktop) heading
746							$tabs.find('.responsive-tabs__panel--active').toggle().removeClass('responsive-tabs__panel--active').attr('aria-hidden','true').prev().removeClass('responsive-tabs__heading--active');
747							
748							//make this tab panel active
749							$tabPanel.toggle().addClass('responsive-tabs__panel--active').attr('aria-hidden','false');
750
751							//make the hidden heading active
752							$tabHeading.addClass('responsive-tabs__heading--active');
753
754							//remove active state from currently active tab list item
755							$tabList.find('.responsive-tabs__list__item--active').removeClass('responsive-tabs__list__item--active');
756
757							//make this tab active
758							$tabListItem.addClass('responsive-tabs__list__item--active');
759
760							//reset height of tab panels to auto
761							$tabsWrapper.css('height', 'auto');
762						}
763					});
764					
765					//associate tab panel with tab list item
766					$tabPanel.attr({
767						'role': 'tabpanel',
768						'aria-labelledby': $tabListItem.attr('id'),
769						id: 'tablist' + tablistcount + '-panel' + tabcount
770					});
771
772					// if this is the active panel then make it the active tab item
773					if($tabPanel.hasClass('responsive-tabs__panel--active')) {
774						$tabListItem.addClass('responsive-tabs__list__item--active');
775						$tabHeading.addClass('responsive-tabs__heading--active');
776					}
777
778					// add tab item
779					$tabList.append($tabListItem);
780
781					
782					// TAB HEADINGS (VISIBLE ON MOBILE)
783					// if user presses 'enter' on tab heading trigger the click event
784					$tabHeading.keydown(function(objEvent) {
785						if (objEvent.keyCode === 13) {
786							$tabHeading.click();
787						}
788					});
789
790					//toggle tab panel if click heading (on mobile)
791					$tabHeading.click(function() {
792
793						// remove any hidden mobile class
794						$tabs.find('.responsive-tabs__panel--closed-accordion-only').removeClass('responsive-tabs__panel--closed-accordion-only');
795
796						// if this isn't currently active
797						if (!$tabHeading.hasClass('responsive-tabs__heading--active')){
798
799							var oldActivePos,
800								$activeHeading = $tabs.find('.responsive-tabs__heading--active');
801								
802							// if there is an active heading, get its position
803							if($activeHeading.length) {
804								oldActivePos = $activeHeading.offset().top;
805							}
806							
807							// close currently active panel and remove active state from any hidden heading
808							$tabs.find('.responsive-tabs__panel--active').slideToggle().removeClass('responsive-tabs__panel--active').prev().removeClass('responsive-tabs__heading--active');
809							
810							//close all tabs
811							$tabs.find('.responsive-tabs__panel').hide().attr('aria-hidden','true');
812
813							//open this panel
814							$tabPanel.slideToggle().addClass('responsive-tabs__panel--active').attr('aria-hidden','false');
815
816							// make this heading active
817							$tabHeading.addClass('responsive-tabs__heading--active');
818
819							var $currentActive = $tabs.find('.responsive-tabs__list__item--active');
820
821							//set the active tab list item (for desktop)
822							$currentActive.removeClass('responsive-tabs__list__item--active');
823							var panelId = $tabPanel.attr('id');
824							var tabId = panelId.replace('panel','tab');
825							jQuery('#' + tabId).addClass('responsive-tabs__list__item--active');
826
827							//scroll to active heading only if it is below previous one
828							var tabsPos = $tabs.offset().top;
829							var newActivePos = ($tabHeading.offset().top) - 15;
830							if(oldActivePos < newActivePos) {
831								jQuery('html, body').animate({ scrollTop: tabsPos }, 0).animate({ scrollTop: newActivePos }, 400);
832							}
833							
834						}
835
836						// if this tab panel is already active
837						else {
838
839							// hide panel but give it special responsive-tabs__panel--closed-accordion-only class so that it can be visible at desktop size
840						//	$tabPanel.removeClass('responsive-tabs__panel--active').slideToggle(function () { jQuery(this).addClass('responsive-tabs__panel--closed-accordion-only'); });
841
842							//remove active heading class
843						//	$tabHeading.removeClass('responsive-tabs__heading--active');
844
845							//don't alter classes on tabs as we want it active if put back to desktop size
846						}
847						
848					});
849
850					tabcount ++;
851
852				});
853
854				// add finished tab list to its container
855				$tabs.prepend($tabList);
856
857				// next set of tabs on page
858				tablistcount ++;
859			});
860		}
861	};
862})(jQuery);
863
864
865
866/*** FUNCION GENERICA PARA RECUPERAR REGISTROS CON FILTRO **********/
867/*******************************************************************/
868function buscarRegistros(origin,event,screenid, objeto, accion, params)
869{
870	console.log('buscar Registros:');
871	jQuery("input[name=eventScreenId]").val(origin.closest('.widget').attr('id'));
872	jQuery("input[name=eventAction]").val(accion);
873	jQuery("input[name=eventArguments]").val(params);
874	
875	var widget = origin.closest('.widget');
876	var resultado = widget.find('.resultado-busqueda');
877	var registros = widget.find('.registros');
878	var noRegistros = widget.find('.no-records');
879	var table = widget.find('.registros .dataTable').DataTable();
880	
881	registros.addClass('dim');
882	noRegistros.addClass('dim');
883	resultado.append('<div class="put-on ajax-loader"></div>');
884	
885	waAjax({   success: function(data){
886						if (data != null)
887						{
888							if (data.result == true)
889		    				{
890								if (data.data.length > 0 )
891								{
892									table.clear();
893									sta.funcMaximo(data.data.length);
894									
895									table.rows.add(data.data);
896									table.draw();
897									registros.prop('hidden',false);
898									noRegistros.prop('hidden',true);
899								}
900								else
901								{
902									registros.prop('hidden',true);
903									noRegistros.prop('hidden',false);
904									widget.find('.info-maximo').addClass('ocultar');
905								}
906		    				}
907							else
908							{
909								alert(data.errorMessage);
910							}
911						}
912				},
913				complete: function (data) {
914				    console.log('always!');
915					table.draw();
916
917				    resultado.children().removeClass('dim');
918				    setTimeout(function () {
919				    	resultado.find('.put-on.ajax-loader').remove();
920				    }, 100);
921				},		
922				error: function (data) {
923				    console.log('error!');
924				    alert('Se ha producido un error.');
925				    resultado.html('');
926				},		        		
927	});
928	table.clear();
929}
930
931
932
933
934
935
936
937/*
938	if (jQuery('#DIR_MUNICIPIO_ID').data("valor-input") != '')
939{ 
940	if(jQuery('#DIR_PROVINCIA_ID').val() == jQuery('#DIR_MUNICIPIO_ID').data( "combo-padre-id" ))
941	{
942		municipio.val(jQuery('#DIR_MUNICIPIO_ID').data('valor-input'));	
943		console.log('El valor del municipio se mantiene por tener el mismo padre que antes.');
944	}
945	else
946	{
947		jQuery('#DIR_MUNICIPIO_ID').data('valor-input','');
948		municipio.val('');
949	}
950}
951*/
952
953/////////// FUNCIONES DIRECCIONES ///////////////////////////////////
954/*******************************************************************/
955
956function AddressCtrl(id,municipio,required) {
957	  this.id = id;
958	  this.municipioFijo = municipio;
959	  this.inicializado = false;
960	  this.required = required;
961
962	  this.municipios_data = [];
963	  this.calles_data = [];
964	  this.numeros_data = [];
965	  this.direcciones_data = [];
966
967	  this.provincia = null;
968	  this.municipio = null;
969	  this.calle = null;
970	  this.numero = null;
971	  this.direcciones = null;
972
973	  this.provincia_hid = null;
974	  this.municipio_hid = null;
975	  this.calle_hid = null;
976	  this.numero_hid = null;
977	  this.direcciones_hid = null;
978	  
979	  
980	}
981
982AddressCtrl.prototype.prepararMunicipios = function(key,origen)
983{
984	var that = this;
985	var municipio = that.municipio;
986	
987	municipio.autocomplete( "option", "source", [] );
988	this.municipio_hid.val('');
989	this.municipio.val('');
990	
991 	this.setCamposDireccion();
992 	municipio.attr("placeholder", sta.literales.msg_cargando_municipios);
993 	
994 	municipio.parent().addClass('loading');
995 	
996	console.log('Obtener municipios!---------------------------');
997	waJSON("dir_municipios","&DIR_PROVINCIA_ID=" + that.provincia_hid.val() ,
998		   function(data){
999					//sta.address.provincia_id = provincia_hid.val();
1000					that.municipios_data = data;
1001					municipio.autocomplete( "option", "source", that.municipios_data );
1002					municipio.attr("placeholder", sta.literales.msg_Seleccione_municipio);
1003					if (municipio.is(":focus"))
1004						municipio.autocomplete("search", municipio.val());
1005			},{complete:function(){
1006				municipio.parent().removeClass('loading');
1007			}});
1008}
1009
1010AddressCtrl.prototype.prepararCalles = function(codificada)
1011{	
1012	var that = this;
1013	
1014	if (codificada)
1015	{
1016		// Hacer visible la sección de dirección codificada
1017		jQuery('#'+ this.id + '.address-control .direccion-codificada').removeClass('ocultar');
1018		jQuery('#'+ this.id + '.address-control .direccion-no-codificada').addClass('ocultar');
1019		jQuery('#'+ this.id + '.address-control .MUN-CP').removeClass('size-xxlarge').addClass('size-large');
1020		jQuery('#'+ this.id + '.address-control .direccion-no-codificada input.required').prop('disabled', true);
1021		jQuery('#'+ this.id + '.address-control .direccion-codificada input.required').prop('disabled', false);
1022		jQuery('#'+ this.id + ' .required_hidden').removeClass('required_hidden').addClass('required_hidden_disabled');
1023		
1024	 	var calle = that.calle;
1025	 	//calle.autocomplete( "option", "source", [] );
1026	 	calle.val('');
1027	 	calle.parent().addClass('loading');
1028	 		 	
1029	 	this.calle_hid.val('');
1030	 	
1031	 	this.setCamposDireccion();
1032	 	calle.attr("placeholder", sta.literales.msg_cargando_calles);
1033		
1034		console.log('Obtener Calles!---------------------------');
1035		waJSON("dir_calles","&DIR_MUNICIPIO_ID=" + that.municipio_hid.val() ,
1036			   function(data){
1037					//sta.address.municipio_id = jQuery('#DIR_MUNICIPIO_ID').val();
1038					that.calles_data = data;
1039					 
1040					calle.autocomplete( "option", "minLength", that.calles_data.length > sta.address.thresholdFluid ? 2 : 0 );
1041					//calle.autocomplete( "option", "source", that.calles_data ); // se filtra a partir de los datos en la funcion 'source'
1042					calle.attr("placeholder", sta.literales.msg_Seleccione_calle);
1043				 	
1044					//if (jQuery(document.activeElement).prop('id') == that.id + "_DIR_CP")
1045					//	calle.focus();
1046					//if (calle.prop('id') == jQuery(document.activeElement).prop('id'))
1047					//	setTimeout(function(){calle.autocomplete("search", calle.val());},300);
1048					
1049					if (calle.prop('id') == jQuery(document.activeElement).prop('id'))
1050						calle.autocomplete("search", calle.val());
1051					
1052						
1053				},{complete:function(){
1054					calle.parent().removeClass('loading');
1055				}});
1056	}
1057	else
1058	{
1059		// Hacer visible la sección de dirección NO-codificada
1060		jQuery('#'+ this.id + '.address-control .direccion-no-codificada').removeClass('ocultar');
1061		jQuery('#'+ this.id + '.address-control .direccion-codificada').addClass('ocultar');
1062		jQuery('#'+ this.id + '.address-control .MUN-CP').addClass('size-xxlarge').removeClass('size-large');
1063		jQuery('#'+ this.id + '.address-control .direccion-codificada input.required').prop('disabled', true);
1064		jQuery('#'+ this.id + '.address-control .direccion-no-codificada input.required').prop('disabled', false);
1065		jQuery('#'+ this.id + '	.required_hidden_disabled').removeClass('required_hidden_disabled').addClass('required_hidden');
1066	}
1067}
1068
1069AddressCtrl.prototype.prepararNumeros = function(item,origen)
1070{
1071	var that = this;
1072	var numero = that.numero;	
1073 	numero.autocomplete( "option", "source", [] );
1074 	numero.val('');
1075
1076 	this.numero_hid.val('');
1077 	
1078 	this.setCamposDireccion();
1079 	numero.attr("placeholder", sta.literales.msg_cargando_numeros);
1080 	
1081 	numero.parent().addClass('loading');
1082 	
1083	console.log('Obtener Numeros ---------------------------');
1084	waJSON("dir_numeros","&DIR_CALLE_ID=" + this.calle_hid.val() ,
1085		   function(data){
1086				
1087				//sta.address.calle_id = jQuery('#DIR_CALLE_ID').val();
1088				that.numeros_data = data;		
1089		
1090				numero.autocomplete( "option", "source", that.numeros_data );
1091				numero.attr("placeholder", sta.literales.msg_Seleccione_numero);
1092				if (numero.is(":focus"))
1093					numero.autocomplete("search", numero.val());    					
1094			},{
1095				complete:function(){
1096				numero.parent().removeClass('loading');
1097			}});   
1098}
1099
1100AddressCtrl.prototype.prepararDirecciones = function(item,origen)
1101{
1102	var that = this;
1103 	var direccion = this.direccion;
1104 	
1105 	direccion.autocomplete( "option", "source", [] );
1106 	direccion.val('');
1107 	direccion.parent().addClass('loading');
1108	
1109 	this.setCamposDireccion();
1110 	
1111 	this.direccion_hid.val('');
1112 	
1113 	direccion.attr("placeholder", sta.literales.msg_cargando_direcciones);
1114 	
1115	console.log('Obtener Direcciones ---------------------------');
1116	waJSON("dir_direcciones","&DIR_NUMERO_ID=" + this.numero_hid.val() + 
1117						     "&DIR_CALLE_ID=" + this.calle_hid.val() +
1118						     "&DIR_MUNICIPIO_ID=" + this.municipio_hid.val(),
1119		   function(data){
1120				//sta.address.numero_id = jQuery('#DIR_NUMERO_ID').val();
1121				that.direcciones_data = data;		
1122		
1123				if ( !Array.isArray(data) || data.length == 0)
1124				{
1125					direccion.attr("placeholder", sta.literales.msg_No_direcciones_numero_indicado);
1126					direccion.autocomplete( "option", "disabled", true).addClass( "no-data", true ); //.prop( "disabled", true );
1127				}
1128				else
1129				{	
1130					jQuery('input[name='+ that.id + '_DIR_CP]').val(data[0].zip)
1131					direccion.autocomplete( "option", "source", that.direcciones_data );
1132					direccion.attr("placeholder", sta.literales.msg_Seleccione_escalera_planta_puerta); //.prop( "disabled", false );
1133					if (direccion.is(":focus"))
1134						direccion.autocomplete("search", direccion.val());
1135				}
1136			},{complete:function(){
1137				direccion.parent().removeClass('loading');
1138			}});
1139}
1140
1141
1142AddressCtrl.prototype.setCamposDireccion = function()
1143{
1144	console.log("Se invalida los campos segun estado (valor del hidden).");
1145	
1146	if (this.municipioFijo == '' || this.municipioFijo == false)
1147	{
1148		if (this.provincia_hid.val() == '')
1149		{
1150			this.municipio.autocomplete( "option", "disabled", true); //.prop( "disabled", true );
1151		 	this.municipio_hid.val('');
1152		 	this.municipio.val('').attr("placeholder", sta.literales.msg_Primero_seleccionar_provincia);
1153		 	this.calle_hid.val('');
1154		 	this.calle.val('');
1155		 	this.numero_hid.val('');
1156		 	this.numero.val('');
1157		 	this.direccion_hid.val('');
1158		 	this.direccion.val('');
1159
1160		 	// Se quita el required y se limpia el campo, se deja ENABLED para poder recibir el foco y esperar a que se carguen los valores
1161		 	this.municipio.rules('add',{ 'adr_required': false});
1162		 	window._FormValidator.cleanElement(this.id + '_DIR_MUNICIPIO');		 	
1163		}
1164		else
1165			this.municipio.autocomplete( "option", "disabled", false)
1166									.prop( "disabled", false )
1167									.attr("placeholder", sta.literales.msg_Seleccione_municipio)
1168									.rules("add","adr_required");
1169	}
1170	
1171	if (this.municipio_hid.val() == '')
1172	{
1173		this.calle.autocomplete( "option", "disabled", true); //.prop( "disabled", true );
1174		this.calle_hid.val('');
1175		this.calle.val('').attr("placeholder", sta.literales.msg_Primero_seleccionar_municipio);
1176		this.numero_hid.val('');
1177		this.numero.val('');
1178		this.direccion_hid.val('');
1179		this.direccion.val('');
1180
1181	 	// Se quita el required y se limpia el campo, se deja ENABLED para poder recibir el foco y esperar a que se carguen los valores
1182		this.calle.rules('add',{ 'adr_required': false});
1183	 	window._FormValidator.cleanElement(this.id + '_DIR_CALLE');
1184	}
1185	else
1186		this.calle.autocomplete( "option", "disabled", false)
1187							.prop( "disabled", false )
1188							.attr("placeholder", sta.literales.msg_Seleccione_calle)
1189							.rules("add","adr_required");
1190	
1191	if (this.calle_hid.val() == '')
1192	{
1193		this.numero.autocomplete( "option", "disabled", true); //.prop( "disabled", true );
1194		this.numero_hid.val('');
1195		this.numero.val('').attr("placeholder", sta.literales.msg_Primero_seleccionar_c
1195alle);
1196		this.direccion_hid.val('');
1197		this.direccion.val('');
1198	 	
1199	 	// Se quita el required y se limpia el campo, se deja ENABLED para poder recibir el foco y esperar a que se carguen los valores
1200	 	this.numero.rules('add',{ 'adr_required': false});
1201	 	window._FormValidator.cleanElement(this.id + '_DIR_NUMERO');
1202	 	
1203	}
1204	else
1205		this.numero.autocomplete( "option", "disabled", false)
1206							 //.prop( "disabled", false )
1207							 //.attr("placeholder", "Seleccione el numero")
1208							 .rules("add","adr_required");
1209
1210	if (this.numero_hid.val() == '')
1211	{
1212		this.direccion.autocomplete( "option", "disabled", true); //.prop( "disabled", true );
1213		this.direccion_hid.val('');
1214		this.direccion.val('').attr("placeholder", sta.literales.msg_Primero_seleccionar_numero);
1215	 	
1216	 	// Se quita el required y se limpia el campo, se deja ENABLED para poder recibir el foco y esperar a que se carguen los valores
1217		this.direccion.rules('add',{ 'adr_required': false});
1218	 	window._FormValidator.cleanElement(this.id + '_DIR_DIRECCION');
1219	 	
1220	}
1221	else
1222		this.direccion.autocomplete( "option", "disabled", false)
1223								//.prop( "disabled", false )
1224								//.attr("placeholder", "Seleccione escalera/planta/puerta")
1225								.rules("add","adr_required");
1226	
1227 	
1228}
1229/*
1230// Función que controla si todos los datos del sistema de direcciones estan cargados
1231// para proceder con la inicialización del control especifico
1232var isAllDataLoad = function(id)
1233{
1234	console.log('Check que todos los datos de direccion estan cargados:')
1235	if (
1236		sta.address.acronimos_opt != null
1237			
1238	
1239		)
1240	{
1241		// ya estan todos los datos cargados:
1242		jQuery(document).ready(function(){updateAddress(id);});
1243	}
1244}
1245*/
1246
1247//FUNCION DE INICIALIZACION que se ejecuta al instante
1248var initAddress = function(id, municipio, required)
1249{
1250	// se inserta el control de dirección en el sistema
1251	sta.address.addresses[id] = new AddressCtrl(id,municipio,required);
1252	/*
1253	sta.address.addresses[id] = {
1254							 'id': id ,
1255							 'municipioFijo': municipio,
1256							 'municipios_data': [],
1257							 'calles_data': [],
1258							 'numeros_data': [],
1259							 'direcciones_data': [],
1260							 'inicializado': false,
1261							 'required': required							 
1262						    };	
1263	 */
1264	
1265	// Se inicializa el sistema de direcciones si no lo esta:
1266	if (!sta.address.inicializado)
1267	{
1268		sta.address.inicializado = true;
1269
1270		//Si no hay hash o es diferente se recargan los datos del sistema de direcciones
1271		var hashData = localStorage.getItem('address_hashData');
1272		if (hashData == null || hashData != sta.address.hashData)
1273		{
1274			waJSON("dir_baseData",'',
1275					   function(data){
1276							localStorage.setItem('address_hashData', sta.address.hashData);
1277							
1278							/* ACRONIMOS */
1279							sta.address.acronimos_opt = '<option value="-1"></option>';
1280							jQuery.each(data.acronimos , function(index, obj){
1281								if (obj.acronymnam == undefined)
1282									obj.acronymnam = obj.acronymcod;
1283								
1284								sta.address.acronimos_opt += '<option value="' + obj.acronymcod + '">' + obj.acronymnam + '</option>';
1285							});
1286							localStorage.setItem('acronimos', sta.address.acronimos_opt);
1287
1288							/* BIS */
1289							sta.address.bis_opt = '<option value=""></option>';
1290							jQuery.each(data.bis , function(index, obj){
1291								sta.address.bis_opt += '<option value=' + obj + '>' + obj + '</option>';
1292						 	});	
1293							localStorage.setItem('bis', sta.address.bis_opt);							
1294							
1295							/* PROVINCIAS */
1296							localStorage.setItem('provincias', JSON.stringify(data.provincias));				
1297							
1298							/* ESCALERAS */
1299							sta.address.escaleras_opt = '<option value=""></option>';
1300							jQuery.each(data.escaleras , function(index, obj){
1301								sta.address.escaleras_opt += '<option value=' + obj + '>' + obj + '</option>';
1302						 	});	
1303							localStorage.setItem('escaleras', sta.address.escaleras_opt);							
1304														
1305							/* PISOS */
1306							sta.address.pisos_opt = '<option value=""></option>';
1307							jQuery.each(data.pisos , function(index, obj){
1308								sta.address.pisos_opt += '<option value=' + obj + '>' + obj + '</option>';
1309						 	});	
1310							localStorage.setItem('pisos', sta.address.pisos_opt);							
1311							
1312							/* PUERTAS */
1313							sta.address.puertas_opt = '<option value=""></option>';
1314							jQuery.each(data.puertas , function(index, obj){
1315								sta.address.puertas_opt += '<option value=' + obj + '>' + obj + '</option>';
1316						 	});	
1317							localStorage.setItem('puertas', sta.address.puertas_opt);							
1318							
1319							// ya estan todos los datos cargados:
1320							console.log('Se han cargado los datos'); //isAllDataLoad(id);
1321							sta.address.loadedData = true;
1322							jQuery(document).ready(function(){
1323							
1324								jQuery('.address-control').each(function(){
1325									sta.address.addresses[jQuery(this).attr('id')].init();
1326								});
1327								
1328							});
1329	    				},{});		
1330		}
1331		else
1332		{
1333			sta.address.acronimos_opt = localStorage.getItem('acronimos');
1334			sta.address.bis_opt = localStorage.getItem('bis');
1335			sta.address.escaleras_opt = localStorage.getItem('escaleras');
1336			sta.address.pisos_opt = localStorage.getItem('pisos');
1337			sta.address.puertas_opt = localStorage.getItem('puertas');
1338
1339			sta.address.loadedData = true;
1340			jQuery(document).ready(function(){sta.address.addresses[id].init();});
1341		}
1342	}
1343	else
1344	{
1345		if (sta.address.loadedData == true)
1346			jQuery(document).ready(function(){sta.address.addresses[id].init();});
1347	}
1348
1349	
1350	// Se lanza por si ya todos los datos estan cargados
1351	//isAllDataLoad(id);	
1352}
1353
1354
1355//FUNCION DE INICIALIZACION que se ejecuta una vez cargada la pagina
1356AddressCtrl.prototype.init = function(){
1357	//var setAddressControl = function(id, required)
1358	var id = this.id;
1359	var that = this;
1360	
1361	console.log('Se procede a montar el control (hay que tener todos los datos estaticos cargados: ' + id);
1362	
1363	/* ACRONIMOS */
1364	jQuery("select[name='"+ id + "_DIR_NOCOD_VIA']").append(sta.address.acronimos_opt).selectmenu();
1365
1366	/* BIS */
1367	jQuery("select[name='"+ id + "_DIR_NOCOD_BIS']").append(sta.address.bis_opt).selectmenu();
1368	
1369	/* ESCALERAS */
1370	jQuery("select[name='"+ id + "_DIR_NOCOD_ESCALERA']").append(sta.address.escaleras_opt).selectmenu();
1371
1372	/* PISOS */
1373	jQuery("select[name='"+ id + "_DIR_NOCOD_PLANTA']").append(sta.address.pisos_opt).selectmenu();
1374
1375	/* PUERTAS */
1376	jQuery("select[name='"+ id + "_DIR_NOCOD_PUERTA']").append(sta.address.puertas_opt).selectmenu();
1377
1378	jQuery('#'+this.id + ' .ui-in > select').each(function(){
1379		let hiddenSelect = jQuery(this);
1380		if (hiddenSelect.siblings('.ui-selectmenu-button').length > 0)
1381			hiddenSelect.parent().prepend(jQuery('<label for="' + hiddenSelect.prop('id') + '" style="display:none;">etiqueta para select</label>'));
1382	});
1383		
1384//	// Se configura que al recibir el foco se abra el combo , SOLO si está activo el autocompletar
1385//	console.log("SE PROCEDE A RECORRER");
1386//	jQuery('.autocompletar').each(function(){
1387//		var self = jQuery(this);
1388//		self.attr('autocomplete','new-password');
1389//		self.on("focus", function () {
1390//			console.log("ADR: FOCUS => Se recibe el FOCO.");
1391//			console.trace();
1392//			if (self.autocomplete( "option", "disabled") != true &&
1393//				self.autocomplete( "option", "source").length > 0)
1394//			{
1395//				console.log("ADR: Set timeout to launch search");
1396//				self.parent().addClass('opening');
1397//				setTimeout(function () {
1398//					console.log("Se lanza el search por recibir el FOCO pasados 50ms.");
1399//					self.autocomplete("search", self.val());
1400//				}, 50);
1401//			}
1402//		});
1403//	});	
1404//	
1405	
1406	//we assume that user will not start fill-in the form immediately
1407//	setTimeout(function(){sta.address.flagAutoCompleteInitDone =true;}, 1000);
1408	jQuery('#'+this.id +' .autocompletar').each(function(){
1409		// IE11 hack
1410		// first we handle 'input' event and prevent its further propagation
1411		// until our variable is initialized with setTimeout() handler call
1412		var self = jQuery(this);
1413		console.log( self.prop('id') +  ": add listener input");
1414		self.attr('autocomplete','new-password');
1415		jQuery(this).on('input', 
1416		   	function(event, ui){   
1417//		       	if( sta.address.flagAutoCompleteInitDone != true)
1418//			    	event.stopImmediatePropagation();
1419//		       	else
1420			    {
1421		  		  console.log(  jQuery(this).attr('id') + ": Invalidar valor");
1422				  jQuery("#" + jQuery(this).attr('id') + "_ID").val('');		
1423				}
1424		   }).
1425		   on("autocompleteopen",
1426			 function(event,ui){
1427				  console.log('Se abre el combo');
1428				  jQuery(this).parent().removeClass('opening');
1429		   	 }
1430		   ).on( "focusout",function(event,ui){
1431			   
1432			   // Si no hay selección se mira si hay un solo candidato
1433			   // o si hay varios si una coincide plenamente
1434			   // para autoseleccionarlo
1435			   try
1436			   {
1437				   that.setCamposDireccion();
1438				   jQuery(this).parent().removeClass('opening');
1439				   console.log('ADR: FOCUSOUT => se busca si hay que seleccionar el elemento marcado');
1440	
1441					var valorInput = jQuery('#' + jQuery(this).attr('name')).val().toUpperCase();
1442
1443					
1444				   if (jQuery('#' + jQuery(this).attr('name') + '_ID').val() == '' && 
1445					   valorInput != '')
1446				   {
1447						var items = Array.from(jQuery(this).autocomplete("widget").find( "li" ), function (element, index) {
1448							try{
1449								console.log('ADR: ' + index + ' item on menu: ' + jQuery(element).data("ui-autocomplete-item").value);
1450								return jQuery(element).data("ui-autocomplete-item");
1451							}
1452						 catch (error) {
1453							  console.log('ERROR ADR >>>>> index: ' + index  + " Error:" + error);
1454							  // expected output: ReferenceError: nonExistentFunction is not defined
1455							  // Note - error messages will vary depending on browser
1456							}
1457							
1458						});
1459						//var valor = null;
1460						var item2Select = null; 
1461						
1462						// Si hay un solo elemento ( sino es nulo debe coincidir en parte sino no pasaria el filtro)
1463						if (items.length == 1)
1464				    	{	
1465				    		//if (items[0].find( "div" ).html().toUpperCase().search(valorInput) != -1)
1466				    		//	valor = jQuery(this).attr('name')).val().toUpperCase();
1467							if (valorInput != '')
1468								item2Select = items[0];
1469				    	
1470				    	} else if (items.length > 1)
1471				    	{	
1472				    		item2Select =  items.find(element => element.value == valorInput);
1473	//			    		jQuery.each( items , function( index, item ){
1474	//			      			if (item == valorInput)		
1475	//			      				
1476	//			      				elemento = item;
1477	//			    		 });	    		
1478	//						var valor = jQuery(this).autocomplete("widget").find( "li > div" ).html();
1479				    	}
1480						
1481						// si hay un valor se busca y se selecciona
1482			    		if (item2Select != null)
1483			    		{
1484	//		    			const elemento = jQuery(this).autocomplete( "option", "source").find(element => element.value == valor);
1485			    			
1486			    			
1487	//			    		jQuery.each( jQuery(this).autocomplete( "option", "source") , function( index, item ){
1488	//			      			if (item.value == valor)				
1489	//			      				elemento = item;
1490	//			    		 });
1491	//			    		
1492	//			    		if (elemento != null)
1493	//			    		{
1494					    		console.log("se intenta autoseleccionar :"+item2Select);
1495					    		jQuery(this).data('ui-autocomplete')._trigger('select', 'autocompleteselect', {item: item2Select});
1496					    		jQuery(this).val(item2Select.value);
1497					    		jQuery(this).valid();
1498					    		return;
1499	//			    		}
1500			    		}
1501						
1502						
1503						
1504						// Si no hay un valor valido se BORRA el campo por ser invalido
1505						jQuery(this).val('');
1506					}
1507			   }
1508			   finally {
1509				   setTimeout(function () {self.autocomplete("widget").empty();},0);		  	
1510				   
1511			   }
1512		   }).on("focus", function () {
1513				console.log("ADR: FOCUS => Se recibe el FOCO.");
1514				//console.trace();
1515				if (self.autocomplete( "option", "disabled") != true 
1516						 // && 					self.autocomplete( "option", "source").length > 0
1517					)
1518				{
1519					console.log("ADR: Set timeout to launch search");
1520					//self.parent().addClass('opening');
1521					setTimeout(function () {
1522						console.log("Se lanza el search por recibir el FOCO pasados 50ms.  filtrado por="+ self.val());
1523						self.autocomplete("search", self.val());
1524					}, 50);
1525				}
1526			});   
1527	});
1528	
1529	
1530	
1531	
1532	/////////// PROVINCIAS -----------------------------------------
1533	this.provincia_hid = jQuery('#'+id+'_DIR_PROVINCIA_ID');
1534	var provincia_hid = this.provincia_hid;
1535	
1536	this.provincia = jQuery('#'+id+'_DIR_PROVINCIA');
1537	this.provincia.after(sta.address.loading);
1538	this.provincia.autocomplete({
1539	  source: JSON.parse(localStorage.getItem('provincias')),
1540	  //open: function( event, ui ) {  console.log('provincias: se abre el combo');},
1541	  minLength: 0,
1542	  autoFocus: true,
1543	  select: function( event, ui ) {
1544				  console.log( "provincias: valor valido:" + ui.item.key);
1545				  provincia_hid.val(ui.item.key);		
1546				  jQuery(this).valid();
1547				  that.prepararMunicipios(ui.item.key,this);
1548			  }			  
1549		}).attr("placeholder", sta.literales.msg_Seleccione_provincia);
1550	
1551	/////////// MUNICIPIOS -----------------------------------------
1552	this.municipio_hid = jQuery('#'+id+'_DIR_MUNICIPIO_ID');
1553	var municipio_hid = this.municipio_hid;
1554 	
1555	this.municipio = jQuery('#'+id+'_DIR_MUNICIPIO');
1556	this.municipio.after(sta.address.loading);
1557	this.municipio.autocomplete({
1558		  source: this.municipios_data,
1559		  //open: function( event, ui ) {
1560		//	    	var len = jQuery(this).autocomplete("widget").find( "li" ).length;
1561		//	    	console.log('municipios: se abre el combo con # opciones:' + len);
1562		//	    },
1563		  minLength: 0,
1564		  disabled: true,
1565		  select: function( event, ui ) {
1566					  console.log( "municipios: seleccionado key:" + ui.item.key);
1567					  municipio_hid.val(ui.item.key);
1568					  jQuery(this).valid();
1569					  	//	.data( "combo-padre-id", jQuery('#DIR_PROVINCIA_ID').val() )
1570					  	//	.data( "valor-input", jQuery(this).val());		
1571					  that.prepararCalles(ui.item.codif);
1572					  
1573				  }			  
1574		}); //.attr("placeholder", "Seleccione el municipio");
1575		
1576	
1577	/////////// CALLES -----------------------------------------
1578	this.calle_hid = jQuery('#'+id+'_DIR_CALLE_ID');
1579	var calle_hid = this.calle_hid; 
1580	this.calle = jQuery('#'+id+'_DIR_CALLE');
1581	var calle = this.calle; 
1582	this.calle.after(sta.address.loading);
1583	
1584	this.calle.autocomplete({
1585//		  source: this.calles_data,
1586		  source: function(request, response) {
1587		        var results = jQuery.ui.autocomplete.filter(that.calles_data, request.term);
1588		        var show;
1589		  		if (that.calles_data.length > sta.address.thresholdFluid)
1590		        	show = results.slice(0, sta.address.thresholdFluid);
1591		        else
1592		        	show = results;
1593		  		calle.parent().removeClass('opening');
1594		  		console.log('ADR: calles: ' + that.calles_data.length + ' => filtradas: ' + results.length +' mostradas: '+ show.length);
1595		  		 
1596		  		// Se limpian los resultados del menu items ya que si no da resultados se quedan ahí
1597		  		if (results.length == 0)
1598		  		{
1599		  			var ul = jQuery(this)[0].menu.element;
1600				    setTimeout(function () {ul.empty();},200);		  			
1601		  			
1602		  		}
1603		  		response(show)
1604		  },
1605		  minLength: 0,
1606		  delay: 300,
1607		  disabled: true,
1608		  
1609		  search: function(e,ui){
1610			  		
1611			  		calle.parent().addClass('opening');
1612			  		var temp = jQuery(this).data("ui-autocomplete").menu.bindings.length;
1613			  		jQuery(this).data("ui-autocomplete").menu.bindings = jQuery();
1614			  		console.log('---> SEARCH_CALLE_ID: before:' + temp + ' after clean: ' + jQuery(this).data("ui-autocomplete").menu.bindings.length);
1615				  },
1616		  select: function( event, ui ) {
1617					  console.log( "calles: valor valido:" + ui.item.key);
1618					  calle_hid.val(ui.item.key);	
1619					  jQuery(this).valid();
1620					  that.prepararNumeros(ui.item,this);
1621				  }			  
1622		}); //.attr("placeholder", "Seleccione la calle").prop( "disabled", true );
1623		
1624	/////////// NUMEROS -----------------------------------------
1625	this.numero_hid = jQuery('#'+id+'_DIR_NUMERO_ID');
1626	var numero_hid = this.numero_hid; 	
1627	
1628	this.numero = jQuery('#'+id+'_DIR_NUMERO');
1629	this.numero.after(sta.address.loading);
1630	this.numero.autocomplete({
1631		  source: this.numeros_data,
1632		  //open: function( event, ui ) {  console.log('Numeros: se abre el combo');},
1633		  minLength: 0,
1634		  disabled: true,
1635		  select: function( event, ui ) {
1636					  console.log( "Numeros: valor valido:" + ui.item.key);
1637					  numero_hid.val(ui.item.key);		
1638					  jQuery(this).valid();
1639					  that.prepararDirecciones(ui.item,this);
1640				  }			  
1641		}); //.attr("placeholder", "Seleccione el numero").prop( "disabled", true );
1642	
1643	
1644	/////////// DIRECCION -----------------------------------------
1645	this.direccion_hid = jQuery('#'+id+'_DIR_DIRECCION_ID');
1646	var direccion_hid = this.direccion_hid; 
1647	
1648	this.direccion = jQuery('#'+id+'_DIR_DIRECCION');
1649	this.direccion.after(sta.address.loading);
1650	this.direccion.autocomplete({
1651		  source: this.direcciones_data,
1652		  open: function( event, ui ) {  console.log('Direcciones: se abre el combo');},
1653		  minLength: 0,
1654		  disabled: true,
1655		  select: function( event, ui ) { 
1656					  console.log( "Direcciones: valor valido:" + ui.item.key);
1657					  direccion_hid.val(ui.item.key);
1658					  jQuery(this).valid();
1659				  }			  
1660		}); //.attr("placeholder", "Seleccione escalera/planta/puerta"); //.prop( "disabled", true );
1661	
1662	
1663	/////////// ACRONIMOS: TIPOS DE V�A -----------------------------------------
1664	/*
1665	jQuery('#DIR_NOCOD_VIA').autocomplete({
1666	  source: JSON.parse(localStorage.getItem('acronimos')),
1667	  //open: function( event, ui ) {  console.log('provincias: se abre el combo');},
1668	  minLength: 0,
1669	  autoFocus: true,
1670	  select: function( event, ui ) {
1671				  //console.log( "provincias: valor valido:" + ui.item.key);
1672				  //jQuery('#DIR_PROVINCIA_ID').val(ui.item.key);		
1673				  //prepararMunicipios(ui.item.key,this);
1674			  }			  
1675		}).attr("placeholder", "Seleccione el tipo de v�a");
1676	*/
1677	
1678	
1679	
1680	
1681
1682	
1683	
1684    if (this.inicializado  == false)
1685    {
1686    	if (this.municipioFijo != '')
1687    		this.prepararCalles(true);
1688    }
1689    else
1690	{
1691    	this.setCamposDireccion();
1692	}
1693    
1694    // Se pone la validación si se requiere obligatoriamente
1695    if (this.required)
1696    {
1697    	console.log('se añade la validación a la dirección');
1698    	if (this.municipioFijo == '')
1699    	{
1700	    	this.provincia.rules("add","adr_required");
1701	    	this.municipio.rules("add","adr_required");
1702    	}
1703    	this.calle.rules("add","adr_required");
1704    	this.numero.rules("add","adr_required");
1705    	this.direccion.rules("add","adr_required");
1706    	jQuery("select[name='"+ id + "_DIR_NOCOD_VIA']").rules("add","adr_required");
1707    }
1708    this.inicializado = true;
1709}
1710
1711
1712// ALTA DE TERCEROS
1713//---------------------
1714
1715function crearPerson(screenId,titulo,finishOk,data)
1716{
1717	modalDialog({
1718				 width:'800px',
1719				 title: titulo,
1720				 icon: 'profile',
1721				 'data': data,
1722				 onValidate: checkStatePersonForm 
1723				},
1724				'.crearPersona',
1725				{ eventScreenId: screenId,
1726				  eventObject: data != undefined ? (data.persontype != undefined? data.persontype :'') : '',
1727				  eventAction: 'DO_CREAR',
1728				  eventArguments: '',
1729				  eventComponent: '',
1730				  success: finishOk == undefined ? rellenarNuevaPersona : finishOk,
1731				  'data' : data		  
1732				},
1733				null,
1734				initDialogCreatePerson
1735	);
1736}
1737function checkStatePersonForm()
1738{
1739	jQuery("<input>").attr({'type':'hidden','name':'persontype'}).val((jQuery('#modalForm input[name="j_idnumber"]').is(':visible')?'J':'F')).appendTo(jQuery('#webAppPageForm2'));
1740	return true;
1741}
1742
1743function initDialogCreatePerson(data)
1744{
1745	jQuery('#modalForm .responsive-tabs.template').removeClass('template');
1746	RESPONSIVEUI.responsiveTabs();	
1747	// Se recoge con el filter porque sino falla la seguna vez en IE8
1748	//var inputs  = jQuery('#modalForm input').filter(function(index){return jQuery(this).attr("name")==="TIPO_PERSONA"});
1749	//inputs.change(function() {radioSelectPersona(jQuery(this));});
1750	
1751	//var inputPersona1 = inputs.eq(0);
1752	//inputPersona1.prop('checked',true);
1753	//radioSelectPersona(inputPersona1);
1754	//inputPersona1.prop('id','tipoPersona1');
1755	
1756	//inputs.eq(1).prop('id','tipoPersona2');
1757	jQuery('#modalForm select[name="tipodoc"]').on('change',function(){
1758		selectDoc(jQuery(this));
1759	});		
1760
1761	if (data != undefined)
1762	{
1763		if (data.id != undefined && window._NIFValidator.checkAll(data.id))
1764		{
1765			if (window._NIFValidator.isJuridica(data.id))
1766			{
1767				jQuery('#modalForm input[name="j_idnumber"]').val(data.id.slice(0, -1));
1768				jQuery('#modalForm input[name="j_ctrlDigit"]').val(data.id.slice(-1));
1769				jQuery('#tablist1-tab2').click();
1770			
1771			}
1772			else
1773			{
1774				jQuery('#modalForm input[name="idnumber"]').val(data.id.slice(0, -1));
1775				jQuery('#modalForm input[name="ctrlDigit"]').val(data.id.slice(-1));
1776			}
1777		}	
1778		else if (data.person != undefined)
1779		{
1780			if (data.person.person.persontype == 'J')
1781			{
1782				jQuery('#modalForm input[name="j_idnumber"]').val(data.person.person.idnumber);
1783				jQuery('#modalForm input[name="j_ctrlDigit"]').val(data.person.person.ctrldigit);
1784				jQuery('#modalForm input[name="j_nombre"]').val(data.person.person.fullname);
1785				jQuery('#modalForm input[name="j_cianame"]').val(data.person.person.cianame);
1786				jQuery('#tablist1-tab2').click();
1787			}
1788			else
1789			{
1790				if (data.person.person.vatacronym != 'ES')
1791				{
1792					var sel = jQuery('#modalForm input[name="tipodoc"]');
1793					sel.val(2);
1794					selectDoc(sel);
1795				}
1796	
1797				jQuery('#modalForm input[name="idnumber"]').val(data.person.person.idnumber);
1798				jQuery('#modalForm input[name="ctrlDigit"]').val(data.person.person.ctrldigit);
1799				jQuery('#modalForm input[name="nombre"]').val(data.person.person.name);
1800				jQuery('#modalForm input[name="apellido1"]').val(data.person.person.familyname);
1801				jQuery('#modalForm input[name="apellido2"]').val(data.person.person.secondname);
1802			}
1803		}
1804	}
1805	pasteIdnumber(jQuery('#modalForm input[name="idnumber"]'));
1806	pasteIdnumber(jQuery('#modalForm input[name="j_idnumber"]'));
1807}
1808
1809function pasteIdnumber(primercampo)
1810{
1811	primercampo.on('paste',function(e){
1812		var id = e.originalEvent.clipboardData.getData('text/plain');
1813		if (id.length > 8)
1814		{
1815			primercampo.val(id.slice(0, -1));
1816			primercampo.closest('.field-body').find('.ui-in').last().find('input').val(id.slice(-1));			
1817		}
1818	});
1819}
1820
1821function rellenarNuevaPersona(datos,opciones)
1822{
1823	var formid= "form-representate";
1824	var sectionid= "datos-representado";
1825	if (opciones.data != undefined && opciones.data.formid != undefined)
1826	{
1827		formid= opciones.data.formid;
1828		sectionid= opciones.data.sectionid;		
1829	}
1830		
1831	console.log('Se ha creado la person, informar a la interfaz');
1832	jQuery('#' + sectionid + ' .data-line').html(datos.nombre + ' - (' + datos.DNI + ')');
1833	jQuery('#' + sectionid).prop('hidden',false);
1834	jQuery('#' + formid).prop('hidden',true);		
1835	sta.personaCreada = datos;
1836}
1837
1838
1839
1840/** Array.From POLLYFILL **/
1841/**
1842 * @param "arr" (required) - array-like or iterable object to convert it to an array.
1843 * @param "callbackFn" (optional) - function to call on every element of the array.
1844 * @param "thisArg" (optional) - value to use as this when executing callback
1845 * Return value - new Array instance
1846 *
1847 * The callbackFn argument usage is like in Array.map() callback.
1848 * The callbackFn function accepts the following arguments:
1849 *      @param "currentValue" (required) - the current element being processed in the array.
1850 *      @param "index" (optional) - the index of the current element being processed in the array.
1851 *      @param "array" (optional) - he array map was called upon.
1852 * Callback function that is called for every element of "arr". Each time callback executes, the returned value is added to new array ("arNew").
1853 */
1854function arrayFrom(arr, callbackFn, thisArg)
1855{
1856    //if you need you can uncomment the following line
1857    //if(!arr || typeof arr == 'function')throw new Error('This function requires an array-like object - not null, undefined or a function');
1858
1859    var arNew = [],
1860        k = [], // used for convert Set to an Array
1861        i = 0;
1862
1863    //if you do not need a Set object support then
1864    //you can comment or delete the following if statement
1865    if(window.Set && arr instanceof Set)
1866    {
1867        //we use forEach from Set object
1868        arr.forEach(function(v){k.push(v)});
1869        arr = k
1870    }
1871
1872    for(; i < arr.length; i++)
1873        arNew[i] = callbackFn
1874            ? callbackFn.call(thisArg, arr[i], i, arr)
1875            : arr[i];
1876
1877    return arNew
1878}
1879
1880//You could also use it without the following line, but it is not recommended because native function is faster.
1881Array.from = Array.from || arrayFrom; //We set it as polyfill
1882
1883
1884if (!String.prototype.includes) {
1885  String.prototype.includes = function(search, start) {
1886    'use strict';
1887
1888    if (search instanceof RegExp) {
1889      throw TypeError('first argument must not be a RegExp');
1890    }
1891    if (start === undefined) { start = 0; }
1892    return this.indexOf(search, start) !== -1;
1893  };
1894}
1895
1896if (!Array.prototype.includes) {
1897    Object.defineProperty(Array.prototype, "includes", {
1898        enumerable: false,
1899        writable: true,
1900        value: function(searchElement /*, fromIndex*/ ) {
1901            'use strict';
1902            var O = Object(this);
1903            var len = parseInt(O.length) || 0;
1904            if (len === 0) {
1905                return false;
1906            }
1907            var n = parseInt(arguments[1]) || 0;
1908            var k;
1909            if (n >= 0) {
1910                k = n;
1911            } else {
1912                k = len + n;
1913                if (k < 0) {k = 0;}
1914            }
1915            var currentElement;
1916            while (k < len) {
1917                currentElement = O[k];
1918                if (searchElement === currentElement ||
1919                    (searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
1920                        return true;
1921                    }
1922                    k++;
1923                }
1924                return false;
1925            }
1926        });
1927    }
1928
1929//TRAP FOCUS
1930//***********************************************************************
1931
1932'use strict';
1933
1934function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
1935
1936var isTabPressed = function isTabPressed(e) {
1937	return e.key === 'Tab' || e.keyCode === 9;
1938};
1939
1940var focusableElements = function focusableElements() {
1941
1942	var rootElement = jQuery(".iziModal:last")[0];
1943	//const rootElement = document.activeElement.closest(".iziModal") != null ? document.activeElement.closest(".iziModal") : document.body;
1944
1945	return [].concat(_toConsumableArray(rootElement.querySelectorAll('button, ' + 'select, ' + 'a[href], ' + 'area[href], ' + '[contentEditable=""], ' + '[contentEditable="true"], ' + '[contentEditable="TRUE"], ' + 'textarea, ' + 'iframe, ' + 'input, ' + 'summary, ' + '[tabindex]:not
1945([tabindex="-1"]'))).filter(function (element) {
1946		return !element.disabled;
1947	}) // se filtran los disableds
1948	.filter(function (el) {
1949		return window.getComputedStyle(el).display !== 'none' && !el.classList.contains('element-invisible');
1950	}); // se filtran los invisibles
1951	//.filter(element => rootElement.tagName === 'DIALOG' ? true : element.closest(".iziModal") === null); 
1952};
1953
1954var lastFocusableElements = function lastFocusableElements() {
1955	return radioElementsOrElement(focusableElements()[focusableElements().length - 1]);
1956};
1957
1958var lastFocusableElement = function lastFocusableElement() {
1959	return getFirstElement(lastFocusableElements());
1960};
1961
1962var firstFocusableElements = function firstFocusableElements() {
1963	return radioElementsOrElement(focusableElements()[0]);
1964};
1965
1966var firstFocusableElement = function firstFocusableElement() {
1967	return getFirstElement(firstFocusableElements());
1968};
1969
1970var getFirstElement = function getFirstElement(elements) {
1971	return Array.isArray(elements) ? elements[0] : elements;
1972};
1973
1974var radioElementsOrElement = function radioElementsOrElement(element) {
1975	return element.type === 'radio' ? [].concat(_toConsumableArray(document.querySelectorAll('input[type="radio"]:not([disabled])'))).filter(function (item) {
1976		return item.name === element.name;
1977	}) : element;
1978};
1979
1980var focusableIsActive = function focusableIsActive(elements) {
1981	return Array.isArray(elements) ? elements.includes(document.activeElement) : elements.contains(document.activeElement);
1982};
1983
1984var smartFocus = function smartFocus(modal) {
1985
1986	if (modal.find('.default-focus:visible').length == 1) // se mira si hay marcado en el dialogo un elemento explicitamente
1987		modal.find('.default-focus:visible').focus();else if (modal.find(':input:not(button):enabled:visible:first').length == 1) // sino se mira el primer input
1988		modal.find(':input:not(button):enabled:visible:first').focus();else firstFocusableElement().focus(); // sino se pone el primero de la lista.  		
1989};
1990
1991var recibirFoco = function recibirFoco(e) {
1992	// Si al obtener foco hay ventana modal sin foco hay que reestablecerlo:
1993	var izi = jQuery(".iziModal:last");
1994	if (izi.length == 1 && !jQuery(".iziModal:last")[0].contains(document.activeElement)) //jQuery(".iziModal:visible").find(":focus").length == 0 )
1995		smartFocus(izi);
1996};
1997
1998var controlarTab = function controlarTab(e) {
1999
2000	if (!isTabPressed(e)) {
2001		return;
2002	}
2003
2004	if (jQuery(".iziModal:visible").length == 0) {
2005		console.log('NEVER SHOULD BE HERE __________________________________________!!!!!!!!!!!!!!!!!!!!');
2006		freeModalWAIA(jQuery(".iziModal:visible").data('iziModal'));
2007	} else {
2008		if (!focusableIsActive(focusableElements())) {
2009			if (e.shiftKey) /* shift + tab */{
2010					lastFocusableElement().focus();
2011					e.preventDefault();
2012				} else {
2013				smartFocus(jQuery(".iziModal:last"));
2014				e.preventDefault();
2015			}
2016		} else {
2017			if (e.shiftKey) /* shift + tab */{
2018					if (focusableIsActive(firstFocusableElements())) {
2019						lastFocusableElement().focus();
2020						e.preventDefault();
2021					}
2022				} else /* tab */{
2023					if (focusableIsActive(lastFocusableElements())) {
2024						firstFocusableElement().focus();
2025						e.preventDefault();
2026					}
2027				}
2028		}
2029	}
2030};
2031
2032var setModalWAIA = function setModalWAIA(modal) {
2033	jQuery('.page').attr('aria-hidden', true);
2034	modal.$overlay.attr('tabindex', '-1');
2035
2036	if (!focusableIsActive(focusableElements())) if (modal.$element.find('.default-focus:visible').length == 1) modal.$element.find('.default-focus:visible').focus();else firstFocusableElement().focus();
2037
2038	jQuery(document).on('focus.focustrap', recibirFoco);
2039	jQuery(document).on('keydown.focustrap', controlarTab);
2040};
2041var freeModalWAIA = function freeModalWAIA(modal) {
2042	jQuery('.page').attr('aria-hidden', false);
2043	modal.oldFocus.focus();
2044	jQuery(document).off('focus.focustrap');
2045	jQuery(document).off('keydown.focustrap');
2046};
2047
2048
2049var firstFocusableElement = function firstFocusableElement() {
2050  return getFirstElement(firstFocusableElements());
2051};
2052
2053var getFirstElement = function getFirstElement(elements) {
2054  return Array.isArray(elements) ? elements[0] : elements;
2055};
2056
2057var radioElementsOrElement = function radioElementsOrElement(element) {
2058  return element.type === "radio"
2059    ? _toConsumableArray(
2060        document.querySelectorAll('input[type="radio"]:not([disabled])')
2061      ).filter(function (item) {
2062        return item.name === element.name;
2063      })
2064    : element;
2065};
2066
2067var focusableIsActive = function focusableIsActive(elements) {
2068  return Array.isArray(elements)
2069    ? elements.includes(document.activeElement)
2070    : elements.contains(document.activeElement);
2071};
2072
2073var smartFocus = function smartFocus(modal) {
2074  if (modal.find(".default-focus:visible").length == 1)
2075    // se mira si hay marcado en el dialogo un elemento explicitamente
2076    modal.find(".default-focus:visible").focus();
2077  else if (modal.find(":input:not(button):enabled:visible:first").length == 1)
2078    // sino se mira el primer input
2079    modal.find(":input:not(button):enabled:visible:first").focus();
2080  else firstFocusableElement().focus(); // sino se pone el primero de la lista.
2081};
2082
2083var recibirFoco = function recibirFoco(e) {
2084  // Si al obtener foco hay ventana modal sin foco hay que reestablecerlo:
2085  var izi = jQuery(".iziModal:last");
2086  if (
2087    izi.length == 1 &&
2088    !jQuery(".iziModal:last")[0].contains(document.activeElement)
2089  )
2090    //jQuery(".iziModal:visible").find(":focus").length == 0 )
2091    smartFocus(izi);
2092};
2093
2094var controlarTab = function controlarTab(e) {
2095  if (!isTabPressed(e)) {
2096    return;
2097  }
2098
2099  if (jQuery(".iziModal:visible").length == 0) {
2100    console.log(
2101      "NEVER SHOULD BE HERE __________________________________________!!!!!!!!!!!!!!!!!!!!"
2102    );
2103    freeModalWAIA(jQuery(".iziModal:visible").data("iziModal"));
2104  } else {
2105    if (!focusableIsActive(focusableElements())) {
2106      if (e.shiftKey) {
2107        /* shift + tab */
2108        lastFocusableElement().focus();
2109        e.preventDefault();
2110      } else {
2111        smartFocus(jQuery(".iziModal:last"));
2112        e.preventDefault();
2113      }
2114    } else {
2115      if (e.shiftKey) {
2116        /* shift + tab */
2117        if (focusableIsActive(firstFocusableElements())) {
2118          lastFocusableElement().focus();
2119          e.preventDefault();
2120        }
2121      } else {
2122      /* tab */
2123        if (focusableIsActive(lastFocusableElements())) {
2124          firstFocusableElement().focus();
2125          e.preventDefault();
2126        }
2127      }
2128    }
2129  }
2130};
2131
2132var setModalWAIA = function setModalWAIA(modal) {
2133  jQuery(".page").attr("aria-hidden", true);
2134  modal.$overlay.attr("tabindex", "-1");
2135  if (!focusableIsActive(focusableElements()))
2136    if (modal.$element.find(".default-focus:visible").length == 1)
2137      modal.$element.find(".default-focus:visible").focus();
2138    else firstFocusableElement().focus();
2139  jQuery(document).on("focus.focustrap", recibirFoco);
2140  jQuery(document).on("keydown.focustrap", controlarTab);
2141};
2142
2143var freeModalWAIA = function freeModalWAIA(modal) {
2144  jQuery(".page").attr("aria-hidden", false);
2145  modal.oldFocus.focus();
2146  jQuery(document).off("focus.focustrap");
2147  jQuery(document).off("keydown.focustrap");
2148};
2149
2150
2151
2152//* Funciones para el modal de firma */
2153//********************************** */
2154var appAfirmaLoaded = false;
2155function cargarAppAfirmaSeguro() {
2156    if (appAfirmaLoaded) {
2157        console.log("cargarAppAfirma ya fue llamada anteriormente.");
2158        return;
2159    }
2160    appAfirmaLoaded = true;
2161	AutoScript.cargarAppAfirma();
2162}	
2163
2164
2165function prepareSignature(origin,event,screenId, businessObject, action, params)
2166{
2167	mostrarCargando();
2168	// Si el origin sigue en loading...
2169	if (origin.length > 0)
2170	{
2171		jQuery("input[name=eventScreenId]").val(screenId);
2172		jQuery("input[name=eventAction]").val(action);
2173		
2174		//jQuery("input[name=eventArguments]").val('KEY='+ origin.attr('data-key'));
2175		
2176		waAjax({
2177	        success: function(data){
2178		    			if (data != null)
2179		    			{
2180		    				//var ancho = origin.parent().width();
2181		    				//origin.parent().width(ancho);
2182		    				
2183		    				//var htmlOutput;
2184							if (data.result == true)
2185							{
2186							    console.log('=== data.data recibido del backend ===');
2187							    console.log(JSON.stringify(data.data, null, 2));
2188								data.data.screendId = screenId; // Se añade el screenId para que esté disponible para el post final 
2189							    modalInfoFirma(data.data);
2190							}
2191		    				else
2192		    					alertError(data.errorMessage);
2193		    				
2194		    				//origin.html(htmlOutput);
2195		    				//origin.prev().show();
2196		    				//origin.removeClass('get-ajax-content');
2197		    				//origin.addClass('importe pendiente');
2198		    			}
2199	        		},
2200					complete: function (data) {
2201						StopModalWaitingFullScreen();
2202					},		
2203					error: function (data) {
2204					    alertError('Se ha producido un error.');
2205					}					
2206					
2207	   });
2208	}
2209}
2210
2211
2212function modalInfoFirma(parameters)
2213{
2214	modalDialog({
2215				
2216				 width:'auto',
2217		 		 heigth:'auto',
2218				 title: sta.literales.formFirma_title,
2219				 literals: {conf_Aceptar: sta.literales.formFirma_aceptar}, 
2220				 icon: 'firmaExterna',
2221				 className: 'modal-info-firma',
2222				 data: parameters,
2223				},
2224				'#modalInfoFirma',
2225				{onAccept: startFirma},
2226				cancelFirma,
2227				initDialogInfoFirma
2228	);
2229}
2230function cancelFirma(signInfo)
2231{
2232	console.log('El modal de firma ha sido cancelado por el usuario.');
2233}
2234
2235function startFirma(signInfo)
2236{
2237    // LOG COMPLETO del objeto que se envía a AutoFirma
2238    console.log('=== startFirma - signInfo completo ===');
2239    console.log(JSON.stringify(signInfo, null, 2));
2240
2241	//modal.addClass('blocked-by-autofirma');
2242	
2243        STAAutofirmaLote.firmarLote(
2244            signInfo,
2245            function(resultado) {
2246				//StopModalWaitingFullScreen();
2247                //informarOk('Firma completada correctamente');
2248
2249				callWidgetEvent(signInfo.screendId,
2250								'',
2251								'PRESENTAR_FIRMA',
2252								'&validationResponse=' + JSON.stringify(resultado),
2253								'');
2254				
2255            },
2256            function(error,message) {
2257                console.error('Error en Autofirma:', error + ", description: " +  message);
2258				StopModalWaitingFullScreen();
2259				
2260				if (error === 'es.gob.afirma.core.AOCancelledOperationException')
2261					alertAviso(message);
2262                
2263	            else
2264					alertAviso(sta.literales.error_firma + ": " + message);
2265            }
2266        );
2267		mostrarCargando();
2268		//alertAviso('PROCESO DE AUTOFIRMA INICIADO............... ');
2269}
2270
2271
2272function initDialogInfoFirma(data)
2273{
2274	// find form pdf
2275	const formDoc = data.documentos.find(doc => doc.id === data.formDoc);
2276
2277	if (formDoc)
2278	{
2279		//const URLFile = "https://test.tao.es:8090/sta/upload?getfile=" + formDoc.fileName;
2280		const URLFile = new URL("/sta/upload?getfile=" + formDoc.fileName, window.location.origin);
2281		//loadScriptOnce("https://unpkg.com/pdfobject").then(() => {
2282		loadScriptOnce("/sta/resources/js/pdfobject.2.3.1.min.js").then(() => {
2283			PDFObject.embed(URLFile.href, ".iziModal .pdfContainer",
2284				{
2285					title: sta.literales.FormularioPDF_tooltip,
2286					fallbackLink: sta.literales.InfoAcceso_URL_PDF
2287				}
2288			);
2289		}).catch(error => {
2290			informarError("No se ha podido cargar el visor de PDF. No se podrá mostrar el documento a firmar.");
2291			console.log('Error al cargar PDFObject:', error);
2292		})
2293	}	
2294	//se carga autoFirma
2295	cargarAppAfirmaSeguro();
2296	console.log('Dialogo de info firma abierto');	
2297}
2298
2299/****************REPRESENTACION *************************/
2300
2301function modalRepresentacion(origin,event,screenId, businessObject, action, params)
2302{
2303	modalDialog({
2304				 width:'650px',
2305		 		 heigth:'auto',
2306				 title: 'Representar a otro interesado', //sta.literales['GLOBAL_PERSON_TITULO_CUENTA'],	 //sta.widgets['LIQSEC_DATOSPER'].literales['ALTA_PERSON_TITLE'],
2307				 icon: 'user_add',
2308				 className: 'modal-representacion',
2309				 data: params,		
2310				 onValidate: checkRepreFormState 		 
2311				},
2312				'modalRepresentacion',
2313				{
2314				  eventScreenId: jQuery('.HEADER ').prop('id'),
2315				  eventObject: '',
2316				  eventAction: 'REPRESENTAR',
2317				  eventArguments: '',
2318				  eventComponent: '',
2319				  success: setRepresentacion
2320				},
2321				null,
2322				initModalRepresentacion
2323	);	
2324}
2325
2326
2327function validarEnPlataforma(origin,event,screenId, businessObject, action, params)
2328{
2329	sta.representacionValidada = false;
2330	sta.representacionRequiereNombre = undefined; 
2331	if (origin.length > 0)
2332	{
2333		jQuery("input[name=eventScreenId]").val(screenId);
2334		jQuery("input[name=eventAction]").val(action);
2335		//jQuery("input[name=nif]").val('KEY='+ origin.attr('data-key'));
2336		
2337		//Mostrar snipet loading representación y ocultar botón de validar
2338		jQuery('#repre-validacion-obligatoria').removeClass('visible').addClass('oculto');
2339		jQuery("#repre-loading").removeClass('oculto').addClass('visible');
2340		jQuery("#botonValidarBox").attr('hidden', true);
2341		
2342		waAjax({
2343			extraData: jQuery('#webAppPageForm2').serialize(), 
2344	        success: function(data){
2345		    			if (data != null)
2346		    			{
2347							if (data.result == true)
2348							{
2349								console.log('Validacion exitosa, data.data= ' + data.data);
2350								sta.representacionValidada = true; // Se marca la representación como validada para que se pueda usar en la firma
2351								sta.representacionRequiereNombre = data.data == 2; 
2352								// 0 no representa
2353								// 1 representa y no necesito datos
2354								// 2 representa y necesita datos persona
2355								// 3 es empresa y necesita nombre empresa
2356								if (data.data == 0) {
2357									
2358									jQuery('.iziModal #repre-plataforma-validate-response-ko').removeClass('oculto').addClass('visible');
2359									jQuery('.iziModal #repre-plataforma-validate-response-ok').removeClass('visible').addClass('oculto');
2360								}else if (data.data == 1 || data.data == 2 || data.data == 3) {
2361									jQuery('.iziModal #repre-plataforma-validate-response-ko').removeClass('visible').addClass('oculto');
2362									jQuery('.iziModal #repre-plataforma-validate-response-ok').removeClass('oculto').addClass('visible');
2363									jQuery('.iziModal #representationSelectorBox').addClass('oculto');
2364								}
2365								
2366								if (data.data == 2) {
2367									jQuery('.iziModal #repre-plataforma-persona-fisica').removeClass('oculto').addClass('visible');
2368									jQuery('.iziModal #repre-plataforma-persona-juridica').addClass('oculto').removeClass('visible');
2369								}else if (data.data == 3) {
2370									jQuery('.iziModal #repre-plataforma-persona-juridica').removeClass('oculto').addClass('visible');
2371									jQuery('.iziModal #repre-plataforma-persona-fisica').addClass('oculto').removeClass('visible');
2372								}else{
2373									jQuery('.iziModal #repre-plataforma-persona-fisica').addClass('oculto').removeClass('visible');
2374									jQuery('.iziModal #repre-plataforma-persona-juridica').addClass('oculto').removeClass('visible');
2375								}
2376							}
2377		    				else
2378							{
2379								//Mostrar botón de validar para permitir reintentos
2380								jQuery("#botonValidarBox").removeAttr('hidden');
2381		    					alertError(data.errorMessage);
2382		    				}
2383		    				//origin.html(htmlOutput);
2384		    				//origin.prev().show();
2385		    				//origin.removeClass('get-ajax-content');
2386		    				//origin.addClass('importe pendiente');
2387		    			}
2388	        		},
2389					complete: function (data) {
2390						//Ocultar snipet loading representación
2391						jQuery("#repre-loading").removeClass('visible').addClass('oculto');
2392						//Mostrar botón de validar para permitir reintentos
2393						if (data.data == 0) { jQuery("#botonValidarBox").removeAttr('hidden'); }
2394					},		
2395					error: function (data) {
2396						//Mostrar botón de validar para permitir reintentos
2397						jQuery("#botonValidarBox").removeAttr('hidden');
2398					    alertError('Se ha producido un error.');
2399					}					
2400	   });
2401	}
2402}
2403
2404function checkRepreFormState(data,modal)
2405{
2406	var $representationSelectorBox = modal.find('#representationSelectorBox');
2407	var existeSelector = $representationSelectorBox.length > 0;
2408	var newSeleccionado = modal.find('#representado-NEW').is(':checked');
2409
2410	// Si existe el selector y NO está seleccionado NEW,
2411	// no hace falta exigir que sta.representacionValidada sea true
2412	if (existeSelector && !newSeleccionado) {
2413		return true;
2414	}
2415
2416	// Si existe el selector y está seleccionado NEW,
2417	// sí hay que exigir validación
2418	// Y si el selector no existe, también se exige validación
2419	if (sta.representacionValidada !== true) {
2420		jQuery("#repre-validacion-obligatoria").removeClass('oculto').addClass('visible');
2421		return false;
2422	}
2423
2424	return true;
2425}
2426
2427function setRepresentacion(data,options)
2428{
2429	console.log('El interesado ha sido representado, se recarga la página para actualizar. Hay que cerrar el modal y refrescar l');
2430	// hay que recargar el header para actualizar el nombre del interesado representado
2431	callWidgetEvent(jQuery('.HEADER ').prop('id'), '', 'REFRESH_DOMI', '');	
2432	
2433}
2434
2435function initModalRepresentacion(params)
2436{
2437	jQuery('.iziModal input[name="representadoSeleccionado"]').on('change', function() {
2438		var valor = jQuery(this).val();
2439		var $reprePlataforma = jQuery('.iziModal').find('[id="repre-plataforma"]');
2440		if (valor === 'NEW') {
2441			$reprePlataforma.removeAttr('hidden');
2442		} else {
2443			$reprePlataforma.attr('hidden', true);
2444		}
2445	});	
2446}
2447 
2448

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.