PageSourceSearch

https://www.hotelflamingo.it/wp-content/plugins/mybooking/js/mybooking.js?ver=9.0

js hotelflamingo.it collected 2026-10-04 13:26:14 UTC 54,747 bytes, 1,652 lines download raw bytes

1/* global calendaryear, periods, periodsDays, mgc_idvendor, _gaq, mgc_searchintovendor_enabled, mbWsUser, minimumStayCheckin */
2
3LOCAL_STORAGE_ACC_KEY = 'accomodation';
4
5//--------------------------Library functions--------------------------
6function getFormParameters(formSelector){
7	var parameters = {};
8	jQuery(formSelector).find('input,select,textarea').each(function(){
9		var dis =jQuery(this).attr('disabled');
10		if((!dis || dis!=true) && (jQuery(this).attr('type')!='radio' && jQuery(this).attr('type')!='checkbox' || jQuery(this).attr('checked')))
11			parameters[jQuery(this).attr('name')] = jQuery(this).val();
12		}
13	);
14	return parameters;
15}
16language = 'it';
17icl_lang = 'it';
18function bindOutDatePicker(selettore){
19	jQuery(selettore).datepicker({
20		   onSelect: function(dateText, inst) { 
21			   var date = jQuery(this).datepicker("getDate");
22			   var attr = jQuery(this).attr('datein');
23			   if(typeof attr !== 'undefined' && attr !== false){
24				   var valueDOut = jQuery('#' + jQuery(this).attr('datein')).val();
25				   if(valueDOut!=''){
26					   var dateDOut = jQuery('#' + jQuery(this).attr('datein')).datepicker("getDate");
27					   if(dateDOut > date)
28						   jQuery('#' + jQuery(this).attr('datein')).val(jQuery(this).val());
29				   }
30				   else{
31					   jQuery('#' + jQuery(this).attr('datein')).val(jQuery(this).val());
32				   }
33			   }
34		}
35	});
36}
37
38function bindInDatePicker(selettore){
39	jQuery(selettore).datepicker({
40		   onSelect: function(dateText, inst) { 
41			   var date = jQuery(this).datepicker("getDate");
42			   var attr = jQuery(this).attr('dateout');
43			   if(typeof attr !== 'undefined' && attr !== false){
44				   var valueDOut = jQuery('#' + jQuery(this).attr('dateout')).val();
45				   if(valueDOut!=''){
46					   var dateDOut = jQuery('#' + jQuery(this).attr('dateout')).datepicker("getDate");
47					   if(dateDOut < date)
48						   jQuery('#' + jQuery(this).attr('dateout')).val(jQuery(this).val());
49				   }
50				   else{
51					   jQuery('#' + jQuery(this).attr('dateout')).val(jQuery(this).val());
52				   }
53			   }
54		}
55	});
56}
57
58/**
59 * Classe Period, rappresentazione in javascript di wsPeriod del webservice
60 * @argument {Date} init 
61 * @argument {Date} end
62 * @argument {Boolean} canCheckinBitmask
63 */
64function Period (init,end,canCheckinBitmask) {
65    this.init = init;
66    this.end = end;
67    this.canCheckinBitmask = canCheckinBitmask;
68    
69    this.isInPeriod = function(date){
70    	return date >=init && date<=end;
71    };
72    
73    this.getInitFormatted = function(){
74    	return this.init.toString('dd/MM/yyyy');  
75    };
76    
77    this.getEndFormatted = function(){
78    	return this.end.toString('dd/MM/yyyy');  
79    };
80    
81    this.isCheckinValid = function(date){
82		if(!this.isInPeriod(date))
83			return false;
84		
85		var dayOfWeek = date.getDay();
86		
87		//Per javascript i giorni iniziano da domenica ma a me mi servono che inizino da lunedi
88		if(dayOfWeek === 0){
89                    dayOfWeek = 6;
90                }
91		else {
92                    dayOfWeek = dayOfWeek - 1;
93                }
94		
95		dayOfWeek = Math.pow(2,dayOfWeek);
96		
97		return (this.canCheckinBitmask & dayOfWeek) > 0;    	
98    };
99    
100    this.isCheckOutDate = function(date){
101    	var tomorrow = new Date();   
102    	tomorrow.setTime(this.end.getTime());
103    	tomorrow.setDate(this.end.getDate() + 1);
104    	tomorrow.setHours(0);
105    	tomorrow.setMilliseconds(0);
106    	tomorrow.setMinutes(0);
107    	tomorrow.setSeconds(0);
108    	return tomorrow.getTime() === date.getTime();
109    };
110}
111
112/*
113function bindBalloon(){
114	 jQuery(".balloon").tooltip({
115		  	delay: 0, 
116		  	track: true,
117		  	showURL: false, 
118		  	extraClass: "cont-balloon",
119		   bodyHandler: function() {
120		     return jQuery('#' + jQuery(this).attr('rel')).html();
121		   }
122		});
123}
124*/
125
126//Array in cui vengono inseriti i vari periodi
127periods = new Array();
128periodsDays = new Array();
129
130jQuery(function(){
131	
132	jQuery.validator.addMethod(
133		    "italianDate",
134		    function(value, element) {
135		        // put your own logic here, this is just a (crappy) example
136		        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
137		    },
138		    "Inserire una data in formato dd/mm/yyyy"
139		);
140	
141	jQuery('form.validate').each(function () {
142	    jQuery(this).validate();
143	});
144	
145	//bindInDatePicker('.datein');
146	//bindOutDatePicker('.dateout');
147	
148	
149	jQuery('.dateout').datepicker({
150		   onSelect: function(dateText, inst) { 
151			   return false;
152		}
153	});
154	
155
156	//L'aggiornamento del motorino lo faccio solo se il motorino esiste
157	if(jQuery('#corpoboxricerca').length > 0){
158		jQuery("#plusrooms a").click(function() {
159			
160			var newStanze = jQuery('#stanze').val()*1 + 1;
161			jQuery('#stanze').val(newStanze);
162			
163			var i;
164			for(i=1;i <= maxStanze; i=i+1){
165				if (i <= jQuery('#stanze').val())
166					jQuery("#stanza" + i).show();
167				else
168					jQuery("#stanza" + i).hide();
169					//alert( i );
170			}
171			return false;
172		});
173		
174		var i;
175		for(i=1;i <= maxStanze; i=i+1){
176                    jQuery("#bambini" + i).change(function() {
177                            var indexBb = jQuery(this).attr('id').replace('bambini','');
178                            if (jQuery(this).val()==0)
179                                    jQuery("#containBambini" + indexBb).hide();
180                            else{
181                                    jQuery("#containBambini" + indexBb).show();
182                            }
183                            var j;
184                            for(j=1;j <= maxBambini; j=j+1){
185                                    if (j <= jQuery(this).val()){
186                                            jQuery("#etabambino" + indexBb + j).show();
187                                            jQuery("#etabambino" + indexBb + j).attr("disabled",false);
188                                    }
189                                    else{
190                                            jQuery("#etabambino" + indexBb + j).hide();
191                                            jQuery("#etabambino" + indexBb + j).attr("disabled",true);
192
193                                            //alert( indexBb + " . " + j );
194                                    }
195                            }
196                    });
197
198                    if(jQuery("#stanze").length > 0 && jQuery('#stanze').val() >= i)
199                            jQuery("#stanza" + i).show();
200                    else if(i > 1)
201                            jQuery("#stanza" + i).hide();
202
203                    if(jQuery("#bambini" + i).length > 0 && jQuery("#bambini" + i).val() > 0){
204                            var indexBb = jQuery("#bambini" + i).attr('id').replace('bambini','');
205                            if ( jQuery("#bambini" + i).val()==0)
206                                    jQuery("#containBambini" + indexBb).hide();
207                            else{
208                                    jQuery("#containBambini" + indexBb).show();
209                            }
210                            var j;
211                            for(j=1;j <= maxBambini; j=j+1){
212                                    if (j <=  jQuery("#bambini" + i).val()){
213                                            jQuery("#etabambino" + indexBb + j).show();
214                                            jQuery("#etabambino" + indexBb + j).attr("disabled",false);
215                                    }
216                                    else{
217                                            jQuery("#etabambino" + indexBb + j).hide();
218                                            jQuery("#etabambino" + indexBb + j).attr("disabled",true);
219                                    }
220                            }
221                    }
222		}
223		
224		jQuery("a.minusrooms").click(function(){			
225                    var newStanze = jQuery('#stanze').val()*1 - 1;
226                    jQuery('#stanze').val(newStanze);
227
228                    var contStanza = jQuery(this).parents('fieldset.stanze');
229                    contStanza.hide();
230//			contStanza.find('.cchildn').hide();
231//			contStanza.find('select.etabambini').hide().attr("disabled",true);
232
233                    return false;			
234		});
235		
236		jQuery(".stanze").live('mouseenter',function(){
237			jQuery(this).addClass('active');
238		});
239		jQuery(".stanze").live('mouseleave',function(){
240			jQuery(this).removeClass('active');
241		});
242                
243                
244                
245                //Precarico i campi del motorino di ricerca con eventuali valori presi dal localStorage
246                fillBookingEngineFromLocalStorage();
247                if(typeof mgc_idvendor!=='undefined' && mgc_idvendor!==null && typeof mgc_searchintovendor_enabled!=='undefined'){
248                    var accJson = sessionStorage.getItem(LOCAL_STORAGE_ACC_KEY);
249                    if(accJson!==null){
250                        searchResultIntoVendor();
251                    }   
252                    else {
253                        //Non ho una ricerca preventivo. Carico le condizioni di default
254                        jQuery("[data-mb_prid] .mbdefault").show();
255                        jQuery("[data-mb_changerqbutton]").hide();
256                        jQuery("[data-mb_pridbutton]").hide();
257                    }
258                }                            
259            }
260	
261	
262	comboYear = '2015:2020';
263	if (typeof calendaryear !== 'undefined') {
264		prevYear = calendaryear - 1;
265		comboYear = prevYear + ':' + calendaryear;
266	}
267	
268	//console.log('year cal ' + comboYear);
269	
270	jQuery.datepicker.setDefaults(jQuery.extend(
271			jQuery.datepicker.regional[icl_lang],{ changeMonth: true },{ changeYear: true },{ yearRange: comboYear },{ dateFormat: 'dd/mm/yy' }, {minDate: new Date()},{ showOn: 'both' },{ buttonImageOnly: true },
272			{ buttonText: '' }
273	));
274	
275	var calManager = new CalendarManager('arrivo','partenza');
276	calManager.init();
277	
278	//Aggiunta del preventivo da backoffice
279	jQuery('#scontrino-actions .mybooking-addquote').live('click',function(){
280		//metto i parametri del form nella variabile data
281		var parameters = getFormParameters('#mybooking-searchform');
282		parameters['action']='mybooking-addquote';
283		jQuery.post(ajaxurl, parameters,
284				 function(data) {						
285					jQuery('#scontrino-actions').html(data);
286				});
287		return false;
288	});
289	
290	//Quando clicco in un radio del prodotto controllo se sono in backoffice. In tal caso cancello l'eventuale messaggio di un salvataggio precedente e 
291	//rifaccio vedere il bottone per il salvataggio
292	if(jQuery('#mybooking-bsearch.addquote').length > 0){
293            jQuery('#mybooking-searchform').find('input:radio').click(function(){
294                jQuery('#mybooking-bsearch.addquote').find('input').show();
295                jQuery('#mybooking-bsearch.addquote').find('p.message').remove();
296            });
297	}
298	
299	
300	/*------------------Gestione scontrino--------------------------------------------*/
301
302	/*	
303	jQuery('input.checkproduct').live('click',function(){
304		
305		//metto i parametri del form nella variabile data
306		var parameters = getFormParameters('#mybooking-searchform');
307		parameters['action']='mybooking-scontrino';
308		jQuery.post(ajaxurl, parameters,
309				function(data) {	
310					jQuery('#scontrino').html(data);
311				});
312	});
313 	*/	
314	
315	
316	jQuery(".accomitems").live('mouseover',function () {
317		jQuery(this).addClass('hover');
318	});
319	jQuery(".accomitems").live('mouseleave',function () {
320		jQuery(this).removeClass('hover');
321	});
322	
323	jQuery('.accomitems').live('click',function(){
324		
325		jQuery(this).parent('.listresults').find('.accomitems').removeClass('active').find('input.checkproduct').attr('checked',false);
326		jQuery(this).addClass('active').find('input.checkproduct').attr('checked',true);
327		loadLoader('scontrino');
328		//metto i parametri del form nella variabile data
329		var parameters = getFormParameters('#mybooking-searchform');
330		parameters['action']='mybooking-scontrino';
331		jQuery.post(ajaxurl, parameters,
332				function(data) {	
333					jQuery('#scontrino').html(data);
334				});
335		
336		//Registro l'azione scontrino su google analitycs
337		if(_gaq!=undefined){
338			var lang= '';
339			if(language && language!='it')
340				lang = language + '/';
341			
342			if(typeof _gaq != 'undefined') {	
343				_gaq.push(['_trackPageview', '/' + lang + 'mybooking-scontrino?idvendor=' + parameters['idvendor']]);
344			}
345		}
346	});
347	
348	jQuery('#summarycontent').on('change',' #summary-selpagamento',function(){
349		
350		loadLoader('scontrino');
351		//metto i parametri del form nella variabile data
352		var parameters = getFormParameters('#formoptrequest');
353		parameters['action']='mybooking-scontrino';
354		
355		var paymentBalanceTime = jQuery(this).find('option:selected').attr('rel');
356		parameters['paymentbalancetime'] = paymentBalanceTime;
357		parameters['hidePrenota'] = '1';
358		parameters['showDaPagare'] = '1';
359		jQuery('#mybooking-paymentbalance').val(paymentBalanceTime);
360		if(paymentBalanceTime == 2){
361			jQuery('#formpren .daticartacredito').show();
362		}
363		else{
364			jQuery('#formpren .daticartacredito').hide();
365		}
366		
367		jQuery.post(ajaxurl, parameters,
368				function(data) {	
369					jQuery('#scontrino').html(data);
370				});
371	});
372
373// ---- Da riattivare solo se si prevvede il pagamento con lo scontrino	
374//	jQuery('#formpren.quoteavailable').submit(function(){
375//		if(jQuery('#mybooking-paymentbalance').length > 0){
376//			if(jQuery('#mybooking-paymentbalance').val() == 0 || jQuery('#mybooking-paymentbalance').val()==''){
377//				alert('Inserisci la modalità di pagamento preferita prima di procedere con la prenotazione');
378//				return false;
379//			}
380//		}
381//		else
382//			return true;
383//	});
384
385	jQuery('input.spfcltv').live('click',function(){
386		//metto i parametri del form nella variabile data
387		var parameters = getFormParameters('#mybooking-searchform');
388		parameters['action']='mybooking-scontrino';
389		loadLoader('scontrino');
390		jQuery.post(ajaxurl, parameters,
391				 function(data) {	
392					jQuery('#scontrino').html(data);
393				});
394	});
395	
396	/*------------------Gestione result strutture ajax--------------------------------------------*/
397	jQuery('#corpoboxricerca form.struttura').submit(function(e){
398		e.preventDefault();
399		//Sto facendo una richiesta informazioni
400		if(jQuery('#corpoboxricerca form.struttura #mbrichinfo').is(':checked'))
401                    return true;
402		
403		if(validateRicercaEsperienza(this)){                        
404                    setAccomodationInLocalStorage();    
405                    var idV = 0;
406                    if(typeof mgc_idvendor!=='undefined' && mgc_idvendor!==null && typeof mgc_searchintovendor_enabled!=='undefined'){
407                        searchResultIntoVendor();
408                        idV = mgc_idvendor;
409                        jQuery(this).closest('.modal').modal('hide');
410                    }
411                    else {
412                        idV = searchStrutturaIntoVendor();
413                    }
414                    //Registro l'azione result strutture su google analitycs
415                    if(typeof _gaq!=='undefined'){
416                        var lang= '';
417                        if(language && language!=='it'){
418                            lang = language + '/';
419                        }
420
421                        _gaq.push(['_trackPageview', '/' + lang + 'mybooking-result-strutture?idvendor=' + idV]);
422                    }
423		}
424		
425		return false;
426	});
427	
428	jQuery('#corpoboxricerca form').submit(function(){
429            if(!jQuery(this).hasClass('struttura')){
430                if(!validateRicercaEsperienza(this)){
431                    return false;
432                }
433            }
434            setAccomodationInLocalStorage();
435	});
436	
437	
438	jQuery('#scegprenota').click(searchStrutturaIntoVendor);
439	
440
441	
442	jQuery('a.trgspcollpse').live('click',function(){
443		
444		var SpLocoTrigger = jQuery(this);		
445		idCurr = jQuery(this).attr('id');
446		
447		jQuery('tr.spcollpse').each(function(){
448			if(jQuery(this).hasClass(idCurr)){
449				if(jQuery(this).css('display') != 'none') {
450					jQuery(this).hide();
451					SpLocoTrigger.css('background-image','url("'+ rootTheme +'/images/nav-blue-small-bx.png"');
452			
453				} else {
454					jQuery(this).show();
455					SpLocoTrigger.css('background-image','url("'+ rootTheme +'/images/nav-blue-small-tx.png"');
456				}
457			}
458		});
459		return false;
460	});
461	
462	jQuery('#corpoboxricerca #chooseform .radio,#corpoboxricerca #btnmbrichinfo,#corpoboxricerca #btnmbrichpren').click(function(){
463		jQuery('#ricercaEsperienza').attr('action',jQuery(this).attr('lnk'));
464		var method = jQuery(this).attr('data-method');
465		if(typeof method!='undefined'){
466			jQuery('#ricercaEsperienza').attr('method',method);
467		}
468	});
469	
470	jQuery('#corpoboxricerca #chooseformula').change(function(){
471		try{
472			var ad_bb = jQuery(this).find('option:selected').attr('rel');
473			ad_bb = ad_bb.split("-");
474			if(ad_bb.length == 2){
475				jQuery('.cadlts select option').each(function(){
476						if(jQuery(this).val() > ad_bb[0])
477							jQuery(this).hide();
478						else
479							jQuery(this).show();
480				});
481				
482				jQuery('.cchildn select option').each(function(){
483					if(jQuery(this).val() > ad_bb[1])
484						jQuery(this).hide();
485					else
486						jQuery(this).show();
487			});
488				
489				
490			}
491		}
492		catch(e){}
493	});
494	
495	/*
496	jQuery('a.trgspcollpse').live("click",(function(){  
497		idCurr = jQuery(this).attr('id');
498		
499		alert(idCurr);
500		
501		jQuery('tr.spcollpse').each(function(){
502			if(jQuery(this).hasClass(idCurr)){
503				if(jQuery(this).css('display') != 'none')
504					jQuery(this).hide();
505				else
506					jQuery(this).show();
507			}
508		});
509		return false;
510	});
511	*/
512	
513	/*
514	jQuery('a.trgspcollpsepren').click(function(){
515		jQuery('tr.spcollpsepren').each(function(){
516			if(jQuery(this).is(':visible'))
517				jQuery(this).hide();
518			else
519				jQuery(this).show();
520		});
521		return false;
522	});
523	*/
524	
525	/* 
526	bindBalloon();
527	
528	jQuery(document).ajaxComplete( 
529			function(){
530				bindBalloon();
531			}
532		);
533	*/
534	
535	
536	/*
537	 * Hotel + Nave
538	 */
539	// change IBE to "Hotel + Nave"
540	jQuery('.tabhotelnave').click(function(e){
541		var divCorpoBoxRicerca = jQuery(this).parents('#corpoboxricerca');
542		
543		divCorpoBoxRicerca.find('.tab').removeClass('active');
544		jQuery(this).addClass('active');
545
546		divCorpoBoxRicerca.find('.mybooking_action').val('comparepricesships');
547		
548		divCorpoBoxRicerca.find('form').removeClass('form-accom').removeClass('form-flight').addClass('form-ferry');
549		/*  replaced with css styles
550		divCorpoBoxRicerca.find('#plusrooms').hide();
551		divCorpoBoxRicerca.find('#chooseform').hide();
552		divCorpoBoxRicerca.find('#chooseroute').show();
553		divCorpoBoxRicerca.find('legend').show();
554		*/
555		
556		var formAction = divCorpoBoxRicerca.find('#ricercaEsperienza');		
557		if(divCorpoBoxRicerca.find('#mbrichpren').length > 0) {
558			formAction.attr('action',divCorpoBoxRicerca.find('#mbrichpren').attr('lnk'));	
559		}
560		
561		formAction.data('originaltarget',formAction.attr('target'));
562		var action = formAction.attr('action');
563		if(!mybooking_endsWith(action,'&compareships=1')){
564			formAction.data('originalaction',formAction.attr('action'));
565			formAction.attr('action',action + '&compareships=1')
566		}
567		formAction.attr('target','');
568		
569		e.preventDefault();
570	});
571	
572	jQuery('.tabhotelaereo').click(function(e){
573		var divCorpoBoxRicerca = jQuery(this).parents('#corpoboxricerca');
574		
575		divCorpoBoxRicerca.find('.tab').removeClass('active');
576		jQuery(this).addClass('active');
577
578		divCorpoBoxRicerca.find('.mybooking_action').val('findflight');
579		
580		divCorpoBoxRicerca.find('form').removeClass('form-accom').removeClass('form-ferry').addClass('form-flight');
581		/*  replaced with css styles
582		divCorpoBoxRicerca.find('#plusrooms').hide();
583		divCorpoBoxRicerca.find('#chooseform').hide();
584		divCorpoBoxRicerca.find('#chooseroute').show();
585		divCorpoBoxRicerca.find('legend').show();
586		*/
587		
588		var formAction = divCorpoBoxRicerca.find('#ricercaEsperienza');		
589		if(divCorpoBoxRicerca.find('#mbrichpren').length > 0) {
590			formAction.attr('action',divCorpoBoxRicerca.find('#mbrichpren').attr('lnk'));	
591		}
592		
593		formAction.data('originaltarget',formAction.attr('target'));
594		var action = formAction.attr('action');
595		if(!mybooking_endsWith(action,'&compareships=1')){
596			formAction.data('originalaction',formAction.attr('action'));
597			formAction.attr('action',action + '&findflight=1')
598		}
599		formAction.attr('target','');
600		
601		e.preventDefault();
602	});
603	
604	// change IBE to "Hotel" (only)
605	jQuery('.tabhotel').click(function(e){
606		var divCorpoBoxRicerca = jQuery(this).parents('#corpoboxricerca');
607		
608		divCorpoBoxRicerca.find('.tab').removeClass('active');
609		jQuery(this).addClass('active');
610		
611		divCorpoBoxRicerca.find('.mybooking_action').val('result-strutture');
612		
613		divCorpoBoxRicerca.find('form').removeClass('form-ferry').removeClass('form-flight').addClass('form-accom');
614		/* replaced with css styles
615		divCorpoBoxRicerca.find('#chooseroute').hide();
616		divCorpoBoxRicerca.find('legend').hide();
617		divCorpoBoxRicerca.find('#plusrooms').show();
618		divCorpoBoxRicerca.find('#chooseform').show();
619		*/
620		
621		var formAction = divCorpoBoxRicerca.find('#ricercaEsperienza');		
622		if(divCorpoBoxRicerca.find('#mbrichpren').length > 0) {
623			if(divCorpoBoxRicerca.find('#mbrichpren').is(':checked')) {
624				formAction.attr('action',divCorpoBoxRicerca.find('#mbrichpren').attr('lnk'));
625			}
626			else if(divCorpoBoxRicerca.find('#mbrichinfo').is(':checked')) {
627				formAction.attr('action',divCorpoBoxRicerca.find('#mbrichinfo').attr('lnk'));
628			}
629		}
630		
631		var origTarget = formAction.data('originaltarget');
632		if(origTarget)
633			formAction.attr('target',origTarget);
634		
635		var origAction = formAction.data('originalaction');
636		if(origAction)
637			formAction.attr('action',origAction);
638			
639		e.preventDefault();
640	});
641	
642	jQuery('body').on('submit','#ricercaEsperienza.form-ferry,#ricercaEsperienza.form-flight',function(){
643		jQuery('#mb-waitingwrapper').show().removeClass('hidden');
644		return true;
645	});
646	
647	jQuery('#mb-waitingwrapper .close').live('click',function(e){
648		jQuery('#mb-waitingwrapper ').fadeOut(300).addClass('hidden');
649		e.preventDefault();
650	});
651	
652	//----immagine track newslettet
653	mgcpp = mb_getUrlParameter('mgcpp');
654	if(mgcpp!=null){
655		var params = "&idcliente=" + idCliente + "&mgcpp=" + mgcpp;
656		//alert(params);
657		jQuery('body').append('<img id="voidImg" src="' + rootUrl +'/marketing?action=setAnalyticsId' + params + '"  />');
658	}
659	
660	// ----- autocomplete del modulo hotel+voli
661	/*
662	var availableTags = [	                     
663	     #foreach ($entry in $airportMap.entrySet())
664	     	{"id":"$entry.key","value":"$entry.value"},
665	     #end
666    ];
667    $( "#departureAirport" ).autocomplete({
668        source: availableTags,
669        select: function( event, ui ) {
670        	$(this).val(ui.item.value);
671        	var v_id = ui.item.id;
672        	$("#fromCode").val(v_id);
673        		return false;
674        }
675    });
676	*/
677	if(typeof aeroporti!='undefined'){
678		jQuery("#aeroportopartenza").autocomplete({
679		      source: aeroporti,
680		      select: function( event, ui ) {
681		    	    jQuery(this).val(ui.item.value);
682		        	var v_id = ui.item.id;
683		        	jQuery("#fromFlightCode").val(v_id);
684		            return false;
685		      }
686		    });
687	}
688	
689	var searchLang = '';
690	if(typeof language != 'undefined'){
691		searchLang = '&lang=' + language;
692	}
693	
694	//Gestione autocompletamento località e zone
695	if(jQuery('#mgc-locality-autocomplete').length > 0){
696		jQuery('#mgc-locality-autocomplete').autocomplete({
697			source: '/wp-content/plugins/mybooking/autocompletelocality.php?exczones=1' + searchLang,
698			//source: '/admin-ajax.php?action=mybooking-ajax-showlocality',
699			//source: "search.php",
700			minLength: 2,
701			select: function( event, ui ) {
702				if(ui.item.type == 1) { //località
703					jQuery('#autocompletelocality').val(ui.item.id);
704					jQuery('#autocompletevendor').val('');
705				}				
706				else if(ui.item.type == 2) { //vendor
707					jQuery('#autocompletevendor').val(ui.item.id);
708					jQuery('#autocompletelocality').val('');
709				}
710			  }
711			/* source: function (request, callback) {
712            jQuery.ajax({
713                type: "POST",
714                url: ajaxurl + '?callback=?&action=mybooking-ajax-showlocality',
715                data: "{'cityname':'" + request.term + "'}",
716                contentType: "application/json; charset=utf-8",
717                dataType: "json",
718                success: function (data) {					
719				   alert('aaaaaa');				
720                }
721            })},
722			*/
723		}).off('blur').on('blur', function(e) {
724			
725    }).data("ui-autocomplete")._renderItem = function(ul, item) {
726			
727			var listItem = jQuery("<li></li>").data("item.autocomplete", item).appendTo(ul);
728			if(item.type != 4){			
729				listItem.append( '<span>' + item.label + '</span>' );
730			}
731			else {
732				listItem.addClass('ui-state-disabled');
733				listItem.append(item.label);
734			}
735			
736			if (item.type == 1) {
737				listItem.addClass("item-locality");
738			}
739			else if (item.type == 2) {
740				listItem.addClass("item-accommodation");
741			}
742			else if (item.type == 3) {
743				listItem.addClass("item-zone");
744			}
745			else if (item.type == 4) {
746				listItem.addClass("item-label");
747			}
748			return listItem;
749		};
750		jQuery('body').click(function(){
751			jQuery('#mgc-locality-autocomplete').autocomplete('close');
752		});
753	}	
754});
755
756
757jQuery(window).load(function() {
758	if(typeof customUserId !== "undefined"){
759		var srcAttr = jQuery("#voidImg").attr('src');
760		srcAttr = srcAttr + "&analyticId=" + customUserId;
761		jQuery("#voidImg").attr('src',srcAttr);
762	}
763});
764
765function mb_getUrlParameter(sParam) {
766    var sPageURL = window.location.search.substring(1);
767    var sURLVariables = sPageURL.split('&');
768    for (var i = 0; i < sURLVariables.length; i++) 
769    {
770        var sParameterName = sURLVariables[i].split('=');
771        if (sParameterName[0] == sParam) 
772        {
773            return sParameterName[1];
774        }
775    }
776}
777
778/**
779 * Ritorna il vendor_id così lo posso usare
780 * @returns {Boolean}
781 */
782function searchStrutturaIntoVendor(){	
783	jQuery('#pricesummary').hide();
784	//metto i parametri del form nella variabile data
785	var parameters = getFormParameters('#ricercaEsperienza');
786	parameters['action'] = 'mybooking-ajax-result-strutture';
787	loadLoader('mybooking-ajax-result-strutture');
788	jQuery.post(ajaxurl, parameters,
789			function(data) {
790				jQuery('#mybooking-ajax-result-strutture').html(data);
791			}
792	);
793	return parameters['idvendor'];
794}
795
796function validateRicercaEsperienza(formRicercaEsperienza){
797	try{
798		jQuery(formRicercaEsperienza).validate();
799		var isValid = jQuery(formRicercaEsperienza).valid();
800		if(!isValid){
801			textError = '';
802			jQuery(formRicercaEsperienza).find('label.error').each(function(){
803				textError = textError + jQuery(this).html() + '\n';
804			});
805			alert(textError);
806			return false;
807		}
808		else {
809			var dateDOut = jQuery('#partenza').datepicker("getDate");
810			var dateIn = jQuery('#arrivo').datepicker("getDate");
811			if(dateIn >= dateDOut ){
812				jQuery('#partenza').addClass('error');
813				jQuery('#arrivo').addClass('error');
814				var lang= 'it';
815				var msg = {
816						it: 'Inserisci una data di partenza posteriore alla data di arrivo',
817						en: 'Insert a departure date subsequent to the date of arrival',
818						fr: 'Entrez une date de départ à la suite de la date d\'arrivée',
819						de: 'Geben Sie eine Start Zeitpunkt nach dem Datum der Ankunft',
820						es:	'Introduzca una fecha de salida posterior a la fecha de llegada',
821						ru:	'Введите даты вылета после даты заезда'					
822				}
823				if(language && language!='it')
824					lang = language;
825				
826					
827					
828				 alert(msg[lang]);
829				 return false;
830			}
831				
832			return true;
833		}
834	}
835	catch(e){
836		alert(e.message);
837	}
838}
839function loadLoader(id){
840	jQuery('#' + id).html('<p class="loader">' + jQuery('#loader').html() + '</p>');
841}
842
843window.onload = function() {
844	if(typeof Piwik !=  'undefined' && typeof Piwik.getAsyncTracker === 'function'){
845		var piwikTracker = Piwik.getAsyncTracker();
846		if(piwikTracker){
847			var visitorId = piwikTracker.getVisitorId();
848			if(visitorId!=null && visitorId.length > 0){
849				if(jQuery('#ricercaEsperienza #visitorid').length == 0){
850					jQuery('#ricercaEsperienza').append('<input type="hidden" id="visitorid" name="visitor_id" value="" />');
851				}
852				jQuery('#ricercaEsperienza #visitorid').val(visitorId);
853			}
854		}
855	}	
856}
857
858function trackGaEvent(category,action,message){
859	//alert('cat: ' + category +  ' - action: ' + action + ' - message: ' + message );
860	try{
861		//analitycs		
862		if(typeof _gaq != 'undefined') {		
863			_gaq.push(['_trackEvent', category, action, message]);
864		}
865		//Analitycs universal
866		else if(typeof ga != 'undefined') {
867			ga('send', 'event', category, action, message);
868		}		
869	}
870	catch(e){
871		//alert(e.message);
872	}
873}
874
875function mybooking_checkEmail(emailAddress) {
876	  var sQtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]';
877	  var sDtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]';
878	  var sAtom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+';
879	  var sQuotedPair = '\\x5c[\\x00-\\x7f]';
880	  var sDomainLiteral = '\\x5b(' + sDtext + '|' + sQuotedPair + ')*\\x5d';
881	  var sQuotedString = '\\x22(' + sQtext + '|' + sQuotedPair + ')*\\x22';
882	  var sDomain_ref = sAtom;
883	  var sSubDomain = '(' + sDomain_ref + '|' + sDomainLiteral + ')';
884	  var sWord = '(' + sAtom + '|' + sQuotedString + ')';
885	  var sDomain = sSubDomain + '(\\x2e' + sSubDomain + ')*';
886	  var sLocalPart = sWord + '(\\x2e' + sWord + ')*';
887	  var sAddrSpec = sLocalPart + '\\x40' + sDomain; // complete RFC822 email address spec
888	  var sValidEmail = '^' + sAddrSpec + '$'; // as whole string
889
890	  var reValidEmail = new RegExp(sValidEmail);
891
892	  if (reValidEmail.test(emailAddress)) {
893	    return true;
894	  }
895
896	  return false;
897	}
898
899function mybooking_endsWith(str, suffix) {
900    return str.indexOf(suffix, str.length - suffix.length) !== -1;
901}
902
903/**
904 * Classe DayStatus, rappresentazione dello stato nel giorno, checkin valido, checkout valido, min stay, data aperta, sleeping day
905 * 
906 */
907function DayMgcStatus (date,canCheckin,canCheckOut,open,minStay,sleepingDay) {
908    this.date = date;
909    this.canCheckin = canCheckin;
910    this.canCheckOut = canCheckOut;
911    this.open = open;
912    this.minStay = minStay;
913    this.sleepingDay = sleepingDay;
914    
915    this.getDateFormatted = function(){
916    	return this.date.toString('dd/MM/yyyy');  
917    }
918}
919
920
921
922function CalendarManager(idArrivo,idPartenza){
923	this.idArrivo = idArrivo;
924	this.idPartenza = idPartenza;
925
926	this.init = function(){
927		var calendarManager = this;
928		jQuery("#" + this.idArrivo).datepicker({
929		onSelect: function(dateText, inst) {
930			 calendarManager.selezionaDataPartenza(dateText);
931		},
932		beforeShow: function(input, inst) {
933			if( 
934				(typeof periods == 'undefined' || periods==null || periods.length == 0) &&
935				(typeof periodsDays == 'undefined' || periodsDays == null || periodsDays.length == 0)
936			)
937                            return;
938			 
939			var arrivoDate = jQuery('#' + calendarManager.idArrivo).val();
940                        if(arrivoDate===''){
941				if(typeof periodsDays !== 'undefined' && periodsDays !== null && periodsDays.length > 0){
942					var tmpDate = new Date();
943					var i = 0;
944					for (i = 0; i < 365; i++) {						
945                                            var periodDay = calendarManager.searchPeriodDay(tmpDate);
946						if(periodDay!=null && periodDay.canCheckin && periodDay.open && periodDay.sleepingDay) {
947                                                    arrivoDate = tmpDate;
948                                                    jQuery(input).datepicker('setDate', tmpDate);
949                                                    break;
950                                            }
951                                            tmpDate.setDate(tmpDate.getDate() + 1);
952					}
953				}
954				else {
955					arrivoDate = periods[0].getInitFormatted();
956					jQuery(input).datepicker('setDate', periods[0].init);
957				}
958                        }
959		},
960		beforeShowDay: function(date) {
961			//Così abilito solo martedì e sabato
962	        var day = date.getDay();
963	        var defaultResult = [true];
964	        
965			 if(typeof periodsDays != 'undefined' && periodsDays != null && periodsDays.length > 0){
966			  //Nuova gestione giornaliera
967		    	   var periodDay = calendarManager.searchPeriodDay(date);
968		    	   if(periodDay!=null && periodDay.canCheckin && periodDay.open && periodDay.sleepingDay)
969		    		   return [true];
970		    	   else
971		    		   return [false];
972			}
973	        else if(typeof periods == 'undefined' || periods==null || periods.length == 0)
974	        	return defaultResult;
975	        else{	        	
976	        	var i = 0;
977	        	for(i = 0; i<periods.length;i = i+1){
978	        		var period = periods[i];
979	        		if(period.isInPeriod(date)){
980	        			if(period.isCheckinValid(date))
981	        				return [true];	 	        		
982	        		}
983	        	}	        	
984	        	return [false];
985	        }
986	    }
987	});	
988
989	jQuery('#' + idPartenza).datepicker({
990		  onSelect: function(dateText, inst) { 
991			  return calendarManager.selezionaDataArrivo(dateText);
992		  },
993		  beforeShow: function(input, inst) {
994				 if(periods==undefined || periods==null || periods.length == 0)
995			        	return;
996				 
997				var arrivoDate = jQuery('#' + idPartenza).val();
998	        	if(arrivoDate===''){
999	        		arrivoDate = periods[0].getInitFormatted();
1000	        		jQuery(input).datepicker('setDate', periods[0].init);
1001	        	}
1002		  },
1003		  beforeShowDay: function(date) {
1004			//Così abilito solo martedì e sabato
1005                        var day = date.getDay();
1006                        var defaultResult = [true];
1007	        
1008			if(typeof periodsDays != 'undefined' && periodsDays != null && periodsDays.length > 0){
1009		    	   //Nuova gestione giornaliera
1010		    	   if(calendarManager.canCheckOut(date))
1011					   return [true];
1012				   else
1013					   return [false];
1014		       }
1015		       else if(periods==undefined || periods==null || periods.length == 0) {
1016					return defaultResult;
1017				}
1018				else{
1019					var i = 0;
1020					var noPeriods = true;
1021					for(i = 0; i<periods.length;i = i+1){
1022						var period = periods[i];
1023						if(period.isInPeriod(date)){
1024							if(period.isCheckinValid(date))
1025								return [true];
1026							noPeriods = false;
1027						}	        		
1028					}
1029					
1030					//Se non ho nessun periodo controllo che non sia in un giorno successivo al periodo (in tal caso ho un true perchè sono in checkout)
1031					if(noPeriods){
1032						for(i = 0; i<periods.length;i = i+1){
1033							var period = periods[i];
1034							if(period.isCheckOutDate(date)){
1035								return [true];	 
1036							}
1037						}
1038					}	        	
1039					return [false];
1040				}
1041		  }
1042	});	
1043	}
1044	/**
1045	 * return DayMgcStatus
1046	 */
1047	this.searchPeriodDay = function(date){
1048		if(periodsDays == null)
1049			return null;
1050		var i =0;
1051		for(i == 0 ; i < periodsDays.length;i++){
1052			if(periodsDays[i].date.setHours(0,0,0,0) == date.setHours(0,0,0,0))
1053				return periodsDays[i];
1054		}
1055		return null;
1056	} 
1057
1058	this.canCheckOut = function(date){
1059		var dataArrivo = this.getDataArrivo();
1060		if(date <=dataArrivo)
1061			return false;
1062		
1063		dayPeriod = this.searchPeriodDay(date);
1064		if(dayPeriod==null || !dayPeriod.canCheckOut && dayPeriod.open){
1065			return false;
1066		}
1067		
1068		maxStay = 365;
1069		var currentMinStay = 1;
1070		
1071		
1072		var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
1073		
1074		var diffDays = Math.round(Math.abs((dataArrivo.getTime() - date.getTime())/(oneDay)));
1075		
1076		//Se oggi non è aperto controllo che ieri non fosse aperto
1077		if(!dayPeriod.open){
1078			var tmpDate = new Date(date);
1079			tmpDate.setDate(tmpDate.getDate() - 1);
1080			dayPeriodTmp = this.searchPeriodDay(tmpDate);
1081			if(dayPeriodTmp == null || !dayPeriodTmp.open)
1082				return false;
1083		}
1084		
1085		//Controllo che tutte le date dalla data arrivo sino ad oggi abbiano sleepingDay > 0 altrimenti non posso dormire
1086                
1087                var minStayPeriodCheckin = typeof minimumStayCheckin !== 'undefined' && minimumStayCheckin === true;
1088                
1089		var tmpDate = new Date(dataArrivo);
1090                var firstDate = true;
1091		for (var tmpDate = dataArrivo; tmpDate < date; tmpDate.setDate(tmpDate.getDate() + 1)) {
1092			dayPeriod = this.searchPeriodDay(tmpDate);
1093			if(dayPeriod===null || !dayPeriod.sleepingDay){
1094				return false;
1095			}
1096			
1097                        if( !minStayPeriodCheckin || firstDate){
1098                            if(currentMinStay < dayPeriod.minStay){
1099                                    currentMinStay = dayPeriod.minStay;
1100                            }
1101                        }
1102                        
1103                        firstDate = false;
1104		}
1105		
1106		if(currentMinStay > diffDays){
1107			return false;
1108		}
1109		return true;
1110	}
1111
1112	this.getDataArrivo = function(){
1113	//	var arrivo = $('#arrivo').val();
1114	//	var arrivSp = arrivo.split('/');
1115	//	
1116	//	if(arrivo.length == 0)
1117	//		return null;
1118	//	
1119	//	var arrivoDate = new Date(arrivSp[2],arrivSp[1] - 1,arrivSp[0]);
1120	//	return arrivoDate;
1121		
1122		return jQuery('#' + this.idArrivo).datepicker("getDate");
1123	};
1124
1125
1126	/**
1127	 * 
1128	 * @param isDown true se sto diminuendo false se sto aumentando
1129	 * @param incr true se sono in incremento usando il touchspin
1130	 * @return true se ho trovato, false altrimenti 
1131	 * 
1132	 */
1133	 this.updatePartenza = function(){
1134		
1135		var addDay = 1;
1136		var initVal = 1;
1137		
1138		
1139		packetMaxStay = 365;
1140		var maxLength = 30;
1141		
1142		var dataArrivo = this.getDataArrivo();
1143		var dataPartenza = this.getDataArrivo();
1144		dataPartenza.setDate(dataArrivo.getDate() + initVal * 1);
1145			
1146		var found = this.canCheckOut(dataPartenza);
1147
1148		if(!found){
1149			var i = 0;
1150			for(i=0;i<maxLength;i=i+1){
1151				dataPartenza.setDate(dataPartenza.getDate() + addDay);		
1152				initVal = initVal * 1 + addDay;
1153				if(this.canCheckOut(dataPartenza)){
1154					found = true;
1155					break;
1156				}
1157			}
1158		}
1159		else {
1160			found = true;
1161		}
1162		
1163		if(initVal > packetMaxStay){
1164			found = false;
1165		}
1166			
1167			
1168		if(dataPartenza <= dataArrivo)
1169			found = false;
1170		
1171		if(dataPartenza != null && found){		 
1172			
1173			jQuery('#' + this.idPartenza).datepicker('setDate',dataPartenza);
1174		}
1175		
1176		
1177		return found;
1178	}
1179	
1180	
1181	//-----Fine jQuery.ready Inizio funzioni
1182	this.selezionaDataPartenza = function(dateText){
1183	
1184	if(typeof periodsDays !== 'undefined' && periodsDays !== null && periodsDays.length > 0){
1185		this.updatePartenza();
1186	}
1187	else if(jQuery('#' + this.idPartenza).val() || jQuery('#' + this.idPartenza).val()===''){
1188		var d=dateText.substr(0,2) * 1;
1189		var m=dateText.substr(3,2) * 1 - 1;
1190		var y=dateText.substr(6,4) * 1;
1191		var dataArrivo = new Date(y,m,d,0,0,0);
1192		
1193		var check = /^([0-9]{2})([\/]{1})([0-9]{2})([\/]{1})([0-9]{4})$/;
1194		var result = check.test ( jQuery('#' + this.idPartenza).val() );
1195		if(result){
1196			var textDPart = jQuery('#' + this.idPartenza).val();
1197			var mPar = textDPart.substr(3,2) * 1 - 1;
1198			var dataPartenza = new Date(textDPart.substr(6,4),mPar,textDPart.substr(0,2),0,0,0);
1199			if(dataPartenza.getTime() > dataArrivo.getTime())
1200				return false;
1201		}
1202		
1203		dataArrivo.setDate(dataArrivo.getDate());		
1204		
1205		d = dataArrivo.getDate();
1206		m = dataArrivo.getMonth() + 1;
1207		y = dataArrivo.getYear();
1208	
1209		if(y < 1900)
1210			y = 1900 + y;
1211		if(m < 10)
1212			m = '0' + m;
1213		if(d < 10)
1214			d= '0' + d;		
1215	
1216		var parText = d + '/' + m 
1217		+ '/' + y;
1218		jQuery('#' + this.idPartenza).val(parText);
1219	}
1220	return false;
1221};
1222
1223
1224	this.selezionaDataArrivo = function(dateText){
1225		if(jQuery('#' + this.idArrivo).val() || jQuery('#' + this.idArrivo).val()===''){
1226			var d=dateText.substr(0,2) * 1;
1227			var m=dateText.substr(3,2) * 1 - 1;
1228			var y=dateText.substr(6,4) * 1;
1229			var dataPartenza = new Date(y,m,d,0,0,0);
1230			
1231			var check = /^([0-9]{2})([\/]{1})([0-9]{2})([\/]{1})([0-9]{4})$/;
1232			var result = check.test ( jQuery('#' + this.idArrivo).val() );
1233			if(result){
1234				var textDPart = jQuery('#' + this.idArrivo).val();
1235				var mPar = textDPart.substr(3,2) * 1 - 1;
1236				var dataArrivo = new Date(textDPart.substr(6,4),mPar,textDPart.substr(0,2),0,0,0);
1237				if(dataPartenza.getTime() > dataArrivo.getTime())
1238					return false;
1239			}
1240			
1241			dataPartenza.setDate(dataPartenza.getDate());		
1242			
1243			d = dataPartenza.getDate();
1244			m = dataPartenza.getMonth() + 1;
1245			y = dataPartenza.getYear();
1246		
1247			if(y < 1900)
1248				y = 1900 + y;
1249			if(m < 10)
1250				m = '0' + m;
1251			if(d < 10)
1252				d= '0' + d;
1253			
1254		
1255			var parText = d + '/' + m 
1256			+ '/' + y;
1257			jQuery('#' + this.idArrivo).val(parText);
1258		}
1259		
1260		
1261		return false;
1262	};
1263}
1264
1265function setAccomodationInLocalStorage(){    
1266    var camere = jQuery('#stanze').val();
1267    var fullProducts = new Array();
1268        
1269    var i = 0;
1270    for(i=1;i<=camere;i=i+1){
1271        var numBambini = jQuery('#bambini' + i).val();
1272        var numAdulti = jQuery('#adulti' + i).val();
1273        var arrayBb = new Array();
1274        
1275        var bb = 0;
1276        for(bb=0;bb<numBambini;bb=bb+1){
1277            var idxBbHtml = bb + 1;
1278            arrayBb.push(jQuery('#etabambino' + i + idxBbHtml ).val());
1279        }
1280        
1281        fullProducts.push(new FullProduct(numAdulti,arrayBb,0));        
1282    }
1283    
1284    var acc = new Accomodation(jQuery('#arrivo').datepicker( "getDate").getTime(),jQuery('#partenza').datepicker("getDate").getTime(),fullProducts);
1285    sessionStorage.setItem(LOCAL_STORAGE_ACC_KEY, JSON.stringify(acc));
1286    
1287    return acc;
1288}
1289
1290function fillBookingEngineFromLocalStorage(){
1291    try {
1292        var accJson = sessionStorage.getItem(LOCAL_STORAGE_ACC_KEY);
1293        if(accJson!==null){
1294            var acc = JSON.parse(accJson);
1295            jQuery('#arrivo').val(jQuery.datepicker.formatDate('dd/mm/yy',new Date(acc.checkin)));
1296            jQuery('#partenza').val(jQuery.datepicker.formatDate('dd/mm/yy',new Date(acc.checkout)));
1297            jQuery('#stanze').val(acc.wsFullProduct.length);
1298            var i = 0;
1299            for(i=0; i < acc.wsFullProduct.length;i=i+1){
1300                var idxHtml = i + 1;
1301                jQuery('#adulti' + idxHtml).val(acc.wsFullProduct[i].adults);
1302                jQuery('#bambini' + idxHtml).val(acc.wsFullProduct[i].ageOfChildren.length);
1303                jQuery('#stanza' + idxHtml).show();
1304                if(acc.wsFullProduct[i].ageOfChildren.length > 0){
1305                    jQuery('#containBambini' + idxHtml).show();
1306                }
1307                for(var j=1;j<=acc.wsFullProduct[i].ageOfChildren.length;j=j+1){                    
1308                    jQuery('#etabambino' + idxHtml + j).show().val(acc.wsFullProduct[i].ageOfChildren[j - 1]);
1309                }
1310            }
1311        }
1312    }
1313    catch(e){
1314        console.log(e);
1315    }
1316}
1317
1318function searchResultIntoVendor(callBack){
1319		
1320	if( typeof callBack === 'undefined' ) {
1321    callBack = null;
1322  }
1323   
1324   var accJson = sessionStorage.getItem(LOCAL_STORAGE_ACC_KEY);
1325   var acc = JSON.parse(accJson);
1326   acc.idVendor = mgc_idvendor;
1327   var searchRequest = new SearchRequest(acc,getWSUser());
1328   
1329    jQuery.ajax({
1330         type: 'POST',
1331         url: '/rest/mybooking/searchintovendor',
1332         data: JSON.stringify (searchRequest),
1333         success: function(wsAccRes) {                        
1334            if(callBack!==null)
1335                callBack(acc,wsAccRes);
1336            else {
1337            var wsFullProductFound = Array();
1338            if(typeof wsAccRes.wsFullProduct !== 'undefined'){             
1339                wsFullProductFound = wsAccRes.wsFullProduct[0].wsFullProductFound;
1340            }         
1341            
1342            renderProductWithResults(acc,wsFullProductFound,wsAccRes.wsErrorCause);         
1343            }
1344         },
1345         error: function(a,b,wsAccRes) {
1346            if(callBack!==null)
1347                callBack(acc,wsAccRes);
1348            else {
1349                var wsFullProductFound = Array();
1350                renderProductWithResults(acc,wsFullProductFound,wsAccRes.wsErrorCause);
1351            }
1352         },
1353         contentType: "application/json" ,
1354         dataType: 'json'
1355    });
1356}
1357
1358
1359function mbGetIdLanguage(){    
1360    if(typeof(language)!== 'undefined'){
1361        switch (language){
1362            case 'it': return 1;
1363            case 'en': return 2;
1364            case 'fr': return 3;
1365            case 'de': return 4;
1366            case 'es': return 5;
1367            case 'nl': return 6;
1368        }
1369    }
1370    return 0;
1371}
1372
1373function mbSearchResult(callBackFnc,treatment){
1374    
1375    if( typeof treatment === 'undefined' ) {
1376        treatment = 0;
1377    }
1378    var accJson = sessionStorage.getItem(LOCAL_STORAGE_ACC_KEY);
1379    var acc = JSON.parse(accJson);
1380    
1381    acc.idLanguage = mbGetIdLanguage();
1382    if(treatment > 0){
1383        acc.wsFullProduct.forEach(function(element){
1384            element.treatment = treatment;
1385        });
1386    }
1387     
1388     var searchRequest = new SearchRequest(acc,getWSUser());
1389    jQuery.ajax({
1390        type: 'POST',
1391        url: '/rest/mybooking/search',
1392        data: JSON.stringify (searchRequest),
1393        success: function(wsAccRes) {                        
1394           callBackFnc(wsAccRes,acc);         
1395        },
1396        contentType: "application/json" ,
1397        dataType: 'json'
1398    });
1399}
1400
1401
1402function mbShowDetailAccomodation(callBackFnc,acc){
1403     
1404    var searchRequest = new SearchRequest(acc,getWSUser());
1405    jQuery.ajax({
1406        type: 'POST',
1407        url: '/rest/mybooking/showDetailsAccomodation',
1408        data: JSON.stringify (searchRequest),
1409        success: function(wsAccRes) {                        
1410           callBackFnc(wsAccRes,acc);         
1411        },
1412        contentType: "application/json" ,
1413        dataType: 'json'
1414    });
1415}
1416
1417function mbBook(callBackFnc,wsQuote,wsContact){
1418     
1419    var quoteRequest = new Object();
1420    quoteRequest.wsQuote = wsQuote;
1421    quoteRequest.wsContact = wsContact;
1422    quoteRequest.noSendEmailToCustomer = false;
1423    quoteRequest.test = false;
1424    quoteRequest.wsUser = getWSUser();
1425    
1426    
1427    jQuery.ajax({
1428        type: 'POST',
1429        url: '/rest/mybooking/book',
1430        data: JSON.stringify (quoteRequest),
1431        success: function(res) {                        
1432           callBackFnc(res,quoteRequest);         
1433        },
1434        contentType: "application/json" ,
1435        dataType: 'json'
1436    });
1437}
1438
1439function mbViewQuote(callBackFnc,quote_id,code){
1440    var quoteRequest = new Object();
1441    quoteRequest.quote_id = quote_id;
1442    quoteRequest.key_code = code;
1443    quoteRequest.wsUser = getWSUser();
1444    
1445    jQuery.ajax({
1446        type: 'POST',
1447        url: '/rest/mybooking/viewQuote',
1448        data: JSON.stringify (quoteRequest),
1449        success: function(res) {                        
1450           callBackFnc(res,quoteRequest);         
1451        },
1452        contentType: "application/json" ,
1453        dataType: 'json'
1454    });
1455}
1456
1457function mbPenalties(callBackFnc,vendor_id,idLang){
1458    var vendorRequest = new Object();
1459    vendorRequest.idVendor = vendor_id;
1460    vendorRequest.idLanguage = idLang;
1461    vendorRequest.onlyPenalties = true;
1462    vendorRequest.wsUser = getWSUser();
1463    
1464    jQuery.ajax({
1465        type: 'POST',
1466        url: '/rest/mybooking/getVendorDescription',
1467        data: JSON.stringify (vendorRequest),
1468        success: function(res) {                        
1469           callBackFnc(res,vendorRequest);         
1470        },
1471        contentType: "application/json" ,
1472        dataType: 'json'
1473    });
1474}
1475
1476
1477function mbGetBeLink(checkin,checkout,initLnk,acc){
1478    var beLnk = initLnk + '&arrivo=' + checkin + '&partenza=' + checkout + '&stanze=' + acc.wsFullProduct.length;
1479       
1480    var j = 0;
1481    for(j=0; j < acc.wsFullProduct.length;j=j+1){
1482        var idxlnk = j + 1;
1483        var wfp = acc.wsFullProduct[j];
1484        beLnk = beLnk + '&adulti' + idxlnk + '=' + wfp.adults;
1485        beLnk = beLnk + '&bambini' + idxlnk + '=' + wfp.ageOfChildren.length;
1486        if(wfp.ageOfChildren.length > 0){
1487            for (var bb = 0, bb = 0; bb < wfp.ageOfChildren.length; bb++) {
1488                var idxbb = bb + 1;
1489                beLnk = beLnk + '&etabambino' + idxlnk + idxbb + '=' + wfp.ageOfChildren[bb];
1490            }
1491        }
1492        
1493        if(wfp.treatment > 0){
1494            beLnk = beLnk + '&treatment' + idxlnk + '=' + wfp.treatment;
1495        }
1496
1497        if(wfp.treatment > 0){
1498            beLnk = beLnk + '&product_id' + idxlnk + '=' + wfp.product_id;
1499        }
1500    }
1501    
1502    return beLnk;
1503}
1504
1505
1506function mbFindGetParameter(parameterName) {
1507    var result = null,
1508        tmp = [];
1509    location.search
1510        .substr(1)
1511        .split("&")
1512        .forEach(function (item) {
1513          tmp = item.split("=");
1514          if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
1515        });
1516    return result;
1517}
1518
1519function mbGetAccomodationFromLink(){
1520    var arrivo = mbFindGetParameter('arrivo');
1521    var partenza = mbFindGetParameter('partenza');
1522    var stanze = mbFindGetParameter('stanze');
1523    
1524    var acc = new Accomodation();
1525    acc.checkin =  jQuery.datepicker.parseDate('dd/mm/yy',arrivo);
1526    acc.checkout =  jQuery.datepicker.parseDate('dd/mm/yy',partenza);
1527    
1528    var idxStanza = 0;
1529    
1530    var fullProducts = new Array();
1531    acc.wsFullProduct = fullProducts;
1532    for(idxStanza=0; idxStanza < stanze; idxStanza=idxStanza+1){
1533        var stanza = idxStanza + 1;
1534        
1535        var tratt = mbFindGetParameter('treatment' + stanza);
1536        
1537        var product_id = mbFindGetParameter('product_id' + stanza);               
1538        
1539        var adulti = mbFindGetParameter('adulti' + stanza);
1540        var bambini = 1 * mbFindGetParameter('bambini' + stanza);
1541        
1542        var idxBb = 0;
1543        var ageOfChildren = new Array();
1544        for(idxBb=0; idxBb < bambini; idxBb=idxBb+1){
1545            var bb = idxBb + 1;
1546            var age = mbFindGetParameter('etabambino' + stanza + bb);
1547            ageOfChildren.push(age);
1548        }
1549        
1550        fullProducts.push(new FullProduct(adulti,ageOfChildren,tratt,product_id));
1551    }
1552    
1553    return acc;
1554}
1555
1556function renderProductWithResults(acc,wsFullProductFound,wsErrorCause){
1557    
1558    var i = i;
1559    var persons = 0;
1560    for(i=0; i < acc.wsFullProduct.length;i=i+1){
1561
1562        var wp = acc.wsFullProduct[i];
1563        persons += 1*wp.adults + 1*wp.ageOfChildren.length;
1564    }
1565    
1566    var checkin = jQuery.datepicker.formatDate('dd/mm/yy',new Date(acc.checkin));
1567    var checkout = jQuery.datepicker.formatDate('dd/mm/yy',new Date(acc.checkout));
1568    
1569    jQuery("[data-mb_prid]").fadeOut(300);
1570    jQuery("[data-mb_prid]").each(function(){       
1571        var product_id = 1 * jQuery(this).attr('data-mb_prid');
1572        var i = 0;
1573        
1574        var elButton = jQuery('[data-mb_pridbutton="' + product_id + '"]');
1575        var initLnk = elButton.attr('data-mb_be_href');
1576        var beLink = mbGetBeLink(checkin,checkout,initLnk,acc);
1577        
1578        elButton.attr('href',beLink);
1579        jQuery('[data-mb_prnotfound="' + product_id + '"] a').attr('href',beLink);
1580        
1581        
1582        var resultFound = false;
1583        for(i=0;i<wsFullProductFound.length;i = i +1){
1584            var wsFound = wsFullProductFound[i];
1585            if(wsFound.product_id === product_id || wsFound.product_parent_id === product_id){
1586                jQuery(this).find('[data-mb_print="price"]').html(wsFound.totalPrice);
1587                jQuery(this).find('[data-mb_print="persons"]').html(persons);
1588                jQuery(this).find('[data-mb_print="checkin"]').html(checkin);
1589                jQuery(this).find('[data-mb_print="checkout"]').html(checkout);
1590                jQuery(this).find('.mbdefault').hide();
1591                jQuery(this).find('.mbwithquote').show();
1592                resultFound = true;
1593                break;
1594            }
1595        }    
1596        if(!resultFound){
1597            //Non ho una ricerca preventivo. Carico le condizioni di default
1598            jQuery('[data-mb_changerqbutton="' + product_id + '"]').show();
1599            jQuery('[data-mb_pridbutton="' + product_id + '"]').hide();
1600            jQuery('[data-mb_verbutton="' + product_id + '"]').hide();
1601            jQuery('[data-mb_prnotfound="' + product_id + '"]').show();   
1602            jQuery('[data-mb_prnotfound="' + product_id + '"] [data-mb_type]').hide();
1603            if(wsErrorCause!==null && typeof wsErrorCause!=='undefined' && wsErrorCause.length > 0){
1604                var typeSpan = jQuery('[data-mb_prnotfound="' + product_id + '"] [data-mb_type="' + wsErrorCause[0].type);
1605                if(typeSpan!==null && typeSpan.length > 0){
1606                   typeSpan.show(); 
1607                   jQuery('[data-mb_prnotfound="' + product_id + '"] [data-mb_default]').hide();
1608                }
1609            }   
1610        }
1611        else{
1612            jQuery('[data-mb_changerqbutton="' + product_id + '"]').show();
1613            jQuery('[data-mb_pridbutton="' + product_id + '"]').show();
1614            jQuery('[data-mb_verbutton="' + product_id + '"]').hide();
1615            jQuery('[data-mb_prnotfound="' + product_id + '"]').hide();
1616        }
1617        
1618        jQuery("[data-mb_prid]").fadeIn(300);
1619    });
1620}
1621
1622function SearchRequest(accomodation, wsUser){
1623    this.wsUser = wsUser;
1624    this.wsAccomodation = accomodation;
1625}
1626
1627function Accomodation(checkin,checkout,wsFullProduct){
1628    this.checkin = checkin;
1629    this.checkout = checkout;
1630    this.wsFullProduct = wsFullProduct;
1631    this.idLanguage = 0;
1632}
1633
1634function mbFormatNumber(number,locale){
1635    return number.toLocaleString(locale,{minimumFractionDigits: 2,maximumFractionDigits:2});
1636}
1637
1638function FullProduct(adults,ageOfChildren,treatment,product_id){
1639    if( typeof product_id === 'undefined' ) {
1640        product_id = 0;
1641    }
1642    this.adults = adults;
1643    this.ageOfChildren = ageOfChildren;
1644    this.treatment = treatment;
1645    this.product_id = product_id;
1646}
1647
1648function getWSUser(){
1649    return mbWsUser;
1650}
1651
1652

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.