PageSourceSearch

https://www.autoviacao1001.com.br/etc.clientlibs/jca-v2/clientlibs/clientlib-site.min.js?5465664645645645

js autoviacao1001.com.br collected 2026-10-02 07:53:02 UTC 2,090,065 bytes, 53,133 lines download raw bytes

1(function () {
2	"use strict";
3	$( document ).ready(function() {
4		try {
5			var $cards =  $('.cmp-teaser');
6			var defaultCard = $($cards).first();
7			var override = $(defaultCard).attr('data-attr-override');
8			
9			var borderRadiusProp = $(defaultCard).attr('data-attr-border-override');
10			var borderStylesProp = $(defaultCard).attr('data-attr-border-styles-override');
11			var paddingProp = $(defaultCard).attr('data-attr-padding-override');
12			var shadowProp = $(defaultCard).attr('data-attr-shadow-override');
13			
14			$( $cards ).each(function( index, element ) {
15				if (override && override == 'true') {
16					var styles = [];
17					var stylesCmpTeaser= [];
18					
19					if (borderRadiusProp) {
20						styles.push('border-radius: ' + borderRadiusProp);
21						styles.push('border-top-left-radius: ' + borderRadiusProp);
22						styles.push('border-top-right-radius: ' + borderRadiusProp);
23						
24						$(element).find('.cmp-image').css('border-top-left-radius', borderRadiusProp);
25						$(element).find('.cmp-image').css('border-top-right-radius', borderRadiusProp);
26						$(element).find('.cmp-image__image').css('border-top-left-radius', borderRadiusProp);
27						$(element).find('.cmp-image__image').css('border-top-right-radius', borderRadiusProp);
28					}
29					
30					if (borderStylesProp) {
31						styles.push('border: ' + borderStylesProp);
32					}
33					
34					if (shadowProp) {
35						styles.push('box-shadow: ' + shadowProp);
36					}
37					
38					if (paddingProp) {
39						$(element).parent().attr('style', 'padding:' + paddingProp + ' !important');
40						$(element).parent().addClass('cmp-teaser-remove-padding');
41					}
42					var styleString = styles.join('; ');
43					$(element).attr('style', styleString + ' !important');
44				} else {
45					if ($(element).attr('data-attr-padding-current')) {
46						$(element).parent().attr('style','padding:' + $(element).attr('data-attr-padding-current') + ' !important');
47					}
48				}
49				
50				var actions = $(element).find('.cmp-teaser__action-link');
51				$( actions ).each(function( index, action ) {
52					if ( !$(action).attr('data-attr-hover-button-color') &&
53							!$(action).attr('data-attr-hover-font-color') && 
54							!$(action).attr('data-attr-hover-button-outline-color') &&
55							!$(action).attr('data-attr-button-color') &&
56							!$(action).attr('data-attr-font-color') &&
57							! $(action).attr('data-attr-button-outline-color')) {
58					} else {
59						$( element ).hover(
60								function() {
61									if ( $(action).attr('data-attr-hover-button-color') != '' ) {
62										$( action ).css('background-color', $(action).attr('data-attr-hover-button-color') );									
63									}
64									if ( $(action).attr('data-attr-hover-font-color') != '' ) {
65										$( action ).css('color', $(action).attr('data-attr-hover-font-color') );									
66									}
67									if ( $(action).attr('data-attr-hover-button-outline-color') != '' ) {
68										$( action ).css('border-color', $(action).attr('data-attr-hover-button-outline-color') );									
69									}
70								}, function() {
71									if ( $(action).attr('data-attr-button-color') != '' ) {
72										$( action ).css('background-color', $(action).attr('data-attr-button-color') );
73									}
74									if ( $(action).attr('data-attr-font-color') != '' ) {
75										$( action ).css('color', $(action).attr('data-attr-font-color') );									
76									}
77									if ( $(action).attr('data-attr-button-outline-color') != '' ) {
78										$( action ).css('border-color', $(action).attr('data-attr-button-outline-color') );									
79									}
80								}
81						);
82					}
83				});
84			});				
85			
86		} catch(error){console.log(error);}
87    });
88})();
89(function ($) {
90	
91	$( window ).load(function() {
92		
93		if ( !$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false' ) {
94			var logged = localStorage.getItem('logged');
95			if (!logged || false && (!SessionStorage.get('passenger'))) {
96				if ( $('#hasLogin').val() ) {
97					localStorage.setItem("referrer", $(location).attr('href'));
98					$(location).attr('href', $('#loginPage').val() );
99				}		
100			}
101		}
102	});
103})(jQuery);
104	
105
106
107$( document ).ready(function() {
108	 $('[data-js="button-register-continue"]').click(function(){
109 		var logged = localStorage.getItem('logged');
110		if (logged && localStorage.getItem('referrer')) {
111			$(location).attr('href', localStorage.getItem('referrer') );
112		} else {
113			$(location).attr('href', $('#loginPage').val() );
114		}
115    });
116 	
117	 $('[data-js="button-register-return"]').click(function(){
118 		localStorage.setItem("logged", false);
119 		$(location).attr('href', $('#loginPage').val() );
120    });
121});
122	
123
124'use strict';
125
126var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
127
128function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
129
130var Address = function () {
131  function Address(zipcode, street, number, complement, neighborhood, city, state) {
132    _classCallCheck(this, Address);
133
134    this._zipCode = zipcode;
135    this._city = city;
136    this._complement = complement;
137    this._neighborhood = neighborhood;
138    this._number = number;
139    this._street = street;
140    this._state = state;
141  }
142
143  _createClass(Address, [{
144    key: 'fromJSON',
145    value: function fromJSON(addressJSON) {
146      $.each(addressJSON, function (index, value) {
147        if (typeof value === 'string') addressJSON[index] = value.replace(/%20/g, ' ');
148      });
149      this._zipCode = addressJSON.zipCode;
150      this._street = addressJSON.street;
151      this._number = addressJSON.number;
152      this._complement = addressJSON.complement;
153      this._neighborhood = addressJSON.neighborhood;
154      this._city = addressJSON.city;
155      this._state = addressJSON.state;
156    }
157  }, {
158    key: 'toJSON',
159    value: function toJSON() {
160      return {
161        zipCode: this._zipCode,
162        street: this._street,
163        number: this._number,
164        complement: this._complement,
165        neighborhood: this._neighborhood,
166        city: this._city,
167        state: this._state
168      };
169    }
170  }, {
171    key: 'serviceJSON',
172    get: function get() {
173      return {
174        birthDate: this.birthDate,
175        cpf: this.cpf,
176        cnpj: this.cnpj,
177        passport: this.passport,
178        name: this.name,
179        familyName: this.familyName,
180        login: this.login,
181        email: this.email,
182        phone: this.phone,
183        areaCode: this.areaCode,
184        phoneType: this.phoneType,
185        password: this.password,
186        optin: this.optin,
187        company: $("#siteName").val(),
188        registrationCampaign: this.registrationCampaign,
189        addresses: this.addresses
190      };
191    }
192  }, {
193    key: 'zipCode',
194    get: function get() {
195      return this._zipCode;
196    },
197    set: function set(zipCode) {
198      this._zipCode = zipCode;
199    }
200  }, {
201    key: 'street',
202    get: function get() {
203      return this._street;
204    },
205    set: function set(street) {
206      this._street = street;
207    }
208  }, {
209    key: 'number',
210    get: function get() {
211      return this._number;
212    },
213    set: function set(number) {
214      this._number = number;
215    }
216  }, {
217    key: 'complement',
218    get: function get() {
219      return this._complement;
220    },
221    set: function set(complement) {
222      this._complement = complement;
223    }
224  }, {
225    key: 'neighborhood',
226    get: function get() {
227      return this._neighborhood;
228    },
229    set: function set(neighborhood) {
230      this._neighborhood = neighborhood;
231    }
232  }, {
233    key: 'city',
234    get: function get() {
235      return this._city;
236    },
237    set: function set(city) {
238      this._city = city;
239    }
240  }, {
241    key: 'state',
242    get: function get() {
243      return this._state;
244    },
245    set: function set(state) {
246      this._state = state;
247    }
248  }]);
249
250  return Address;
251}();
252'use strict';
253
254var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
255
256function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
257
258var Cart = function () {
259  function Cart() {
260    _classCallCheck(this, Cart);
261
262    this._listPassengers = [];
263    this._listOffer = [];
264    this._departureOnly = true;
265    this._dateAcquisition = {};
266    this._totalConvenienceFee = 0;
267    this._insurance = {
268      hired: false,
269      price: null
270    };
271    this._subTotal = 0;
272    this._totalPrice = 0;
273    this._percentagePix = 0;
274    this._totalPix = 0;
275    this._subTotalPix = 0;
276  }
277
278  _createClass(Cart, [{
279    key: 'fromJSON',
280    value: function fromJSON(cartObject) {
281      for (var i = 0; i < cartObject._listOffer.length; i++) {
282        var offer = new Offer();
283        offer.fromJSON(cartObject._listOffer[i]);
284        this._listOffer.push(offer);
285      }
286
287      for (var _i = 0; _i < cartObject._listPassengers.length; _i++) {
288        var passenger = new Passenger();
289        passenger.fromJSON(cartObject._listPassengers[_i]);
290        this._listPassengers.push(passenger);
291      }
292
293      this._departureOnly = cartObject._departureOnly;
294      this._dateAcquisition = cartObject._dateAcquisition;
295      this._insurance = cartObject._insurance;
296    }
297  }, {
298    key: 'addInsurance',
299    value: function addInsurance(price) {
300      this._insurance = {
301        hired: true,
302        price: price
303      };
304    }
305  }, {
306    key: 'removeInsurance',
307    value: function removeInsurance() {
308      this._insurance = {
309        hired: false,
310        price: null
311      };
312    }
313  }, {
314    key: 'addDepartOffer',
315    value: function addDepartOffer(offer) {
316      this._listOffer[0] = offer;
317      this._listOffer[0].isDeparture = true;
318    }
319  }, {
320    key: 'addReturnOffer',
321    value: function addReturnOffer(offer) {
322      this._listOffer[1] = offer;
323      this._listOffer[1].isDeparture = false;
324    }
325  }, {
326    key: 'removeOffer',
327    value: function removeOffer(offer) {
328      var index = this._listOffer.indexOf(offer);
329      if (index != -1) this._listOffer.splice(index, 1);
330    }
331  }, {
332    key: 'addPassengers',
333    value: function addPassengers(amount) {
334      for (var i = 0; i < amount; i++) {
335        this._listPassengers.push(new Passenger());
336      }
337    }
338  }, {
339    key: 'addPassenger',
340    value: function addPassenger(passenger) {
341      this._listPassengers.push(passenger);
342    }
343  }, {
344    key: 'removePassenger',
345    value: function removePassenger(passenger) {
346      var index = this._listPassengers.indexOf(passenger);
347      if (index != -1) this._listPassengers.splice(index, 1);
348    }
349  }, {
350    key: 'updatePassengersPriceValues',
351    value: function updatePassengersPriceValues(serviceResponseArray, isReturn) {
352      var _this = this;
353
354      if (isReturn) {
355        serviceResponseArray.forEach(function (data, i) {
356          var passenger = _this._listPassengers[i];
357          passenger.seatReturn.price = data.price;
358          passenger.seatReturn._convenienceFee = data.convenienceFee;
359          passenger.seatReturn.toll = data.tollTax;
360          passenger.seatReturn.insurance = data.insurancePrice;
361          passenger.seatReturn.other = data.otherTax;
362        });
363      } else {
364        serviceResponseArray.forEach(function (data, i) {
365          var passenger = _this._listPassengers[i];
366          passenger.seatDeparture.price = data.price;
367          passenger.seatDeparture._convenienceFee = data.convenienceFee;
368          passenger.seatDeparture.toll = data.tollTax;
369          passenger.seatDeparture.insurance = data.insurancePrice;
370          passenger.seatDeparture.other = data.otherTax;
371        });
372      }
373    }
374  }, {
375    key: 'getTotal',
376    value: function getTotal(isConvenienceFee) {
377      if (!isConvenienceFee) return this.total;
378
379      return this.getWithTotalWithConvenienceFee;
380    }
381  }, {
382    key: 'total',
383    get: function get() {
384      var isAgencyFlow = SessionStorage.get('isAgencyFlow');
385      var insurancePrice = this.insurance ? this.insurance.price : 0;
386      var discount = 0;
387      var roundedTotal = 0.00;
388      var total = 0.0;
389
390      for (var i = 0; i < this.listOffer.length; i++) {
391        var offer = this.listOffer[i];
392
393        for (var j = 0; j < this.listPassengers.length; j++) {
394          var passenger = this.listPassengers[j];
395
396          var seat = void 0;
397          var seatConnection = void 0;
398          var seatConnection2 = void 0;
399
400          if (i == 0) {
401            seat = passenger._seatDeparture;
402            seatConnection = passenger._seatDepartureConnection;
403            seatConnection2 = passenger._seatDepartureConnection2;
404          } else {
405            seat = passenger._seatReturn;
406            seatConnection = passenger._seatReturnConnection;
407            seatConnection2 = passenger._seatReturnConnection2;
408          }
409
410          if (passenger._type.toUpperCase() !== 'CHILD') {
411            total += seat && seat._price ? parseFloat(seat._price || 0) + parseFloat(seatConnection && seatConnection._price ? seatConnection._price : 0) + parseFloat(seatConnection2 && seatConnection2._price ? seatConnection2._price : 0) : parseFloat(offer._price);
412          }
413        }
414      }
415
416      roundedTotal = total + insurancePrice + discount;
417      roundedTotal = Math.round((roundedTotal + 0.00001) * 100) / 100;
418      return roundedTotal;
419    }
420  }, {
421    key: 'getWithTotalWithConvenienceFee',
422    get: function get() {
423      var insurancePrice = this.insurance ? this.insurance.price : 0;
424      var discount = 0;
425      var roundedTotal = 0.00;
426      var total = 0.0;
427      this._totalConvenienceFee = 0;
428
429      for (var i = 0; i < this.listOffer.length; i++) {
430        var offer = this.listOffer[i];
431
432        for (var j = 0; j < this.listPassengers.length; j++) {
433          var passenger = this.listPassengers[j];
434
435          if (passenger._type.toUpperCase() == 'CHILD') {
436            continue;
437          }
438
439          var seat = void 0;
440          var seatConnection = void 0;
441          var seatConnection2 = void 0;
442
443          if (i == 0) {
444            seat = passenger._seatDeparture;
445            seatConnection = passenger._seatDepartureConnection;
446            seatConnection2 = passenger._seatDepartureConnection2;
447          } else {
448            seat = passenger._seatReturn;
449            seatConnection = passenger._seatReturnConnection;
450            seatConnection2 = passenger._seatReturnConnection2;
451          }
452
453          this._totalConvenienceFee += (seat.convenienceFee || 0) + (seatConnection.convenienceFee || 0) + (seatConnection2.convenienceFee || 0);
454
455          total += seat && seat._price ? parseFloat(seat._price || 0) + parseFloat(seatConnection && seatConnection._price ? seatConnection._price : 0) + parseFloat(seatConnection2 && seatConnection2._price ? seatConnection2._price : 0) + (seat._convenienceFee > 0 ? parseFloat(seat._convenienceFee) : 0) + (seatConnection && seatConnection._convenienceFee > 0 ? parseFloat(seatConnection._convenienceFee) : 0) + (seatConnection2 && seatConnection2._convenienceFee > 0 ? parseFloat(seatConnection2._convenienceFee) : 0) : parseFloat(offer._price) + (seat && seat._convenienceFee ? parseFloat(seat._convenienceFee) : 0);
456        }
457      }
458
459      roundedTotal = total + insurancePrice + discount;
460      //Rounding value to two decimal digits
461      roundedTotal = Math.round((roundedTotal + 0.00001) * 100) / 100;
462      return roundedTotal;
463    }
464  }, {
465    key: 'totalConvenienceFee',
466    get: function get() {
467      return this._totalConvenienceFee;
468    },
469    set: function set(totalConvenienceFee) {
470      this._totalConvenienceFee = totalConvenienceFee;
471    }
472  }, {
473    key: 'totalDiscount',
474    get: function get() {
475      var discount = 0;
476      var roundedTotalDiscount = 0;
477
478      for (var i = 0; i < this.listOffer.length; i++) {
479        var offer = this.listOffer[i];
480        for (var j = 0; j < this.listPassengers.length; j++) {
481          var passenger = this.listPassengers[j];
482
483          if (i == 0) {
484            discount += parseFloat(passenger.seatDeparture.priceWithDiscount);
485
486            if (passenger.seatDepartureConnection.seatNumber) discount += parseFloat(passenger.seatDepartureConnection.priceWithDiscount);
487
488            if (passenger.seatDepartureConnection2.seatNumber) discount += parseFloat(passenger.seatDepartureConnection2.priceWithDiscount);
489          } else {
490            discount += parseFloat(passenger.seatReturn.priceWithDiscount);
491
492            if (passenger.seatReturnConnection.seatNumber) discount += parseFloat(passenger.seatReturnConnection.priceWithDiscount);
493
494            if (passenger.seatReturnConnection2.seatNumber) discount += parseFloat(passenger.seatReturnConnection2.priceWithDiscount);
495          }
496        }
497      }
498
499      roundedTotalDiscount = Math.round((discount + 0.00001) * 100) / 100;
500      return roundedTotalDiscount;
501    }
502  }, {
503    key: 'totalByPassenger',
504    get: function get() {
505      var total = this.total;
506      var amountPassengers = this.listPassengers.length;
507      var roundedTotal = total / amountPassengers;
508      //Rounding value to two decimal digits
509      roundedTotal = Math.round((roundedTotal + 0.00001) * 100) / 100;
510      return roundedTotal;
511    }
512  }, {
513    key: 'totalRoutes',
514    get: function get() {
515      var departureTicket = this.listPassengers.reduce(function (acc, passenger) {
516        acc += +passenger._seatDeparture._price;
517        return acc;
518      }, 0);
519
520      var returnTicket = this.listPassengers.reduce(function (acc, passenger) {
521        acc += +passenger._seatReturn._price;
522        return acc;
523      }, 0);
524
525      return { departureTicket: departureTicket, returnTicket: returnTicket };
526    }
527  }, {
528    key: 'balanceTotal',
529    get: function get() {
530      var insurancePrice = this.insurance ? this.insurance.price : 0;
531      var discount = 0;
532      var roundedTotal = 0.00;
533      var total = 0.0;
534
535      for (var i = 0; i < this.listOffer.length; i++) {
536        var offer = this.listOffer[i];
537
538        for (var j = 0; j < this.listPassengers.length; j++) {
539          var passenger = this.listPassengers[j];
540
541          if (passenger._type.toUpperCase() == 'CHILD') {
542            continue;
543          }
544
545          var seat = void 0;
546          var seatConnection = void 0;
547          var seatConnection2 = void 0;
548
549          if (i == 0) {
550            seat = passenger._seatDeparture;
551            seatConnection = passenger._seatDepartureConnection;
552            seatConnection2 = passenger._seatDepartureConnection2;
553          } else {
554            seat = passenger._seatReturn;
555            seatConnection = passenger._seatReturnConnection;
556            seatConnection2 = passenger._seatReturnConnection2;
557          }
558
559          total += parseFloat(seat._balanceAmount || 0) + parseFloat(seatConnection._balanceAmount || 0) + parseFloat(seatConnection2._balanceAmount || 0);
560        }
561      }
562
563      roundedTotal = total + insurancePrice + discount;
564      //Rounding value to two decimal digits
565      roundedTotal = Math.round((roundedTotal + 0.00001) * 100) / 100;
566      return roundedTotal;
567    }
568  }, {
569    key: 'totalPassengers',
570    get: function get() {
571      return this._listPassengers.length;
572    }
573  }, {
574    key: 'insurance',
575    get: function get() {
576      return this._insurance;
577    }
578  }, {
579    key: 'dateAcquisition',
580    get: function get() {
581      return this._dateAcquisition;
582    },
583    set: function set(dateAcquisition) {
584      this._dateAcquisition = dateAcquisition;
585    }
586  }, {
587    key: 'departureOnly',
588    get: function get() {
589      return this._departureOnly;
590    },
591    set: function set(departureOnly) {
592      this._departureOnly = departureOnly;
593    }
594  }, {
595    key: 'listOffer',
596    get: function get() {
597      return this._listOffer;
598    },
599    set: function set(listOffer) {
600      this._listOffer = listOffer;
601    }
602  }, {
603    key: 'listPassengers',
604    get: function get() {
605      return this._listPassengers;
606    },
607    set: function set(listPassengers) {
608      this._listPassengers = listPassengers;
609    }
610  }, {
611    key: 'subTotal',
612    get: function get() {
613      return this._subTotal;
614    },
615    set: function set(subTotal) {
616      this._subTotal = subTotal;
617    }
618  }, {
619    key: 'totalPrice',
620    get: function get() {
621      return this._totalPrice;
622    },
623    set: function set(totalPrice) {
624      this._totalPrice = totalPrice;
625    }
626  }, {
627    key: 'percentagePix',
628    get: function get() {
629      return this._percentagePix;
630    },
631    set: function set(percentagePix) {
632      this._percentagePix = percentagePix;
633    }
634  }, {
635    key: 'totalPix',
636    get: function get() {
637      return this._totalPix;
638    },
639    set: function set(totalPix) {
640      this._totalPix = totalPix;
641    }
642  }, {
643    key: 'subTotalPix',
644    get: function get() {
645      return this._subTotalPix;
646    },
647    set: function set(subTotalPix) {
648      this._subTotalPix = subTotalPix;
649    }
650  }]);
651
652  return Cart;
653}();
654"use strict";
655
656var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
657
658function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
659
660var Child = function () {
661  function Child(_ref) {
662    var birthday = _ref.birthday,
663      documentType = _ref.documentType,
664      document = _ref.document,
665      name = _ref.name;
666
667    _classCallCheck(this, Child);
668
669    this._birthday = birthday;
670    this._documentType = documentType;
671    this._document = document;
672    this._name = name;
673  }
674
675  _createClass(Child, [{
676    key: "toJSON",
677    value: function toJSON() {
678      return {
679        birthday: this.birthday,
680        documentType: this.documentType,
681        document: this.document,
682        name: this.name
683      };
684    }
685  }, {
686    key: "fromJSON",
687    value: function fromJSON(childJSON) {
688      this.birthday = childJSON._birthday;
689      this.documentType = childJSON._documentType;
690      this.document = childJSON._document;
691      this.name = childJSON._name;
692    }
693  }, {
694    key: "birthday",
695    get: function get() {
696      return this._birthday;
697    },
698    set: function set(birthday) {
699      this._birthday = birthday;
700    }
701  }, {
702    key: "documentType",
703    get: function get() {
704      return this._documentType;
705    },
706    set: function set(documentType) {
707      this._documentType = documentType;
708    }
709  }, {
710    key: "document",
711    get: function get() {
712      return this._document;
713    },
714    set: function set(document) {
715      this._document = document;
716    }
717  }, {
718    key: "name",
719    get: function get() {
720      return this._name;
721    },
722    set: function set(name) {
723      this._name = name;
724    }
725  }]);
726
727  return Child;
728}();
729'use strict';
730
731var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
732
733function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
734
735/**
736 * INICIO
737 * CLASSTYPE MODEL
738 *
739*/
740var Classtype = function () {
741  function Classtype(classname) {
742    _classCallCheck(this, Classtype);
743
744    this._className = classname;
745    this._friendlyName = '';
746    this._classImage = '';
747    this._classAltTextImage = '';
748    this._details = [];
749  }
750
751  _createClass(Classtype, [{
752    key: 'fromJSON',
753    value: function fromJSON(classtypeJSON) {
754      this._className = classtypeJSON._className;
755      this._classImage = classtypeJSON._classImage;
756      this._friendlyName = classtypeJSON._friendlyName;
757
758      for (var i = 0; i < classtypeJSON._details.length; i++) {
759        var detail = new ClasstypeDetails();
760        detail.fromJSON(classtypeJSON._details[i]);
761      }
762    }
763  }, {
764    key: 'className',
765    get: function get() {
766      return this._className;
767    },
768    set: function set(className) {
769      this._className = className;
770    }
771  }, {
772    key: 'friendlyName',
773    get: function get() {
774      return this._friendlyName;
775    },
776    set: function set(friendlyName) {
777      this._friendlyName = friendlyName;
778    }
779  }, {
780    key: 'classImage',
781    get: function get() {
782      return this._classImage;
783    },
784    set: function set(classImage) {
785      this._classImage = classImage;
786    }
787  }, {
788    key: 'details',
789    get: function get() {
790      return this._details;
791    },
792    set: function set(details) {
793      this._details = details;
794    }
795  }, {
796    key: 'classAltTextImage',
797    get: function get() {
798      return this._classAltTextImage;
799    },
800    set: function set(classAltTextImage) {
801      this._classAltTextImage = classAltTextImage;
802    }
803  }, {
804    key: 'name',
805    get: function get() {
806      return this._friendlyName ? this._friendlyName : this._className;
807    }
808  }]);
809
810  return Classtype;
811}();
812/**
813 * FIM
814 * CLASSTYPE MODEL
815 *
816*/
817'use strict';
818
819var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
820
821function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
822
823/**
824 * INICIO
825 * CLASSTYPE DETAILS MODEL
826 *
827*/
828var ClasstypeDetails = function () {
829  function ClasstypeDetails() {
830    _classCallCheck(this, ClasstypeDetails);
831
832    this._classDetailName = '';
833    this._classDetailDifferential = 'false';
834    this._altTextDetail = '';
835    this._classDetailDescription = '';
836    this._classDetailImage = '';
837  }
838
839  _createClass(ClasstypeDetails, [{
840    key: 'fromJSON',
841    value: function fromJSON(classtypeDetailJSON) {
842      this._classDetailName = classtypeDetailJSON._classDetailName;
843      this._classDetailDifferential = classtypeDetailJSON._classDetailDifferential;
844      this._altTextDetail = classtypeDetailJSON._altTextDetail;
845      this._classDetailDescription = classtypeDetailJSON._classDetailDescription;
846      this._classDetailImage = classtypeDetailJSON._classDetailImage;
847    }
848  }, {
849    key: 'classDetailName',
850    get: function get() {
851      return this._classDetailName;
852    },
853    set: function set(classDetailName) {
854      this._classDetailName = classDetailName;
855    }
856  }, {
857    key: 'classDetailDifferential',
858    get: function get() {
859      return this._classDetailDifferential;
860    },
861    set: function set(classDiff) {
862      this._classDetailDifferential = classDiff;
863    }
864  }, {
865    key: 'altTextDetail',
866    get: function get() {
867      return this._altTextDetail;
868    },
869    set: function set(altTextDetail) {
870      this._altTextDetail = altTextDetail;
871    }
872  }, {
873    key: 'classDetailDescription',
874    get: function get() {
875      return this._classDetailDescription;
876    },
877    set: function set(classDetailDescription) {
878      this._classDetailDescription = classDetailDescription;
879    }
880  }, {
881    key: 'classDetailImage',
882    get: function get() {
883      return this._classDetailImage;
884    },
885    set: function set(classDetailImage) {
886      this._classDetailImage = classDetailImage;
887    }
888  }]);
889
890  return ClasstypeDetails;
891}();
892
893/**
894 * FIM
895 * CLASSTYPE DETAILS MODEL
896 *
897*/
898'use strict';
899
900var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
901
902var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
903
904function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
905
906/**
907 * INICIO
908 * COMPANY MODEL
909 *
910*/
911var Company = function () {
912  function Company() {
913    _classCallCheck(this, Company);
914
915    this._companyId = null;
916    this._departureDate = '';
917    this._arrivingDate = '';
918    this._companyName = '';
919    this._companyLogo = '';
920    this._companyAltTextLogo = '';
921    this._origin = {};
922    this._destination = {};
923    this._listOffer = [];
924    this._favPurchase = false;
925  }
926
927  _createClass(Company, [{
928    key: 'fromJSON',
929    value: function fromJSON(companyJSON) {
930      this._companyId = companyJSON._companyId;
931      this._arrivingDate = companyJSON._arrivingDate;
932      this._departureDate = companyJSON._departureDate;
933      this._companyName = companyJSON._companyName;
934      this._companyLogo = companyJSON._companyLogo;
935      this._origin = companyJSON._origin;
936      this._destination = companyJSON._destination;
937      this._companyAltTextLogo = companyJSON._companyAltTextLogo;
938      this._favPurchase = companyJSON._favPurchase;
939    }
940  }, {
941    key: 'companyId',
942    get: function get() {
943      return this._companyId;
944    },
945    set: function set(companyId) {
946      this._companyId = companyId;
947    }
948  }, {
949    key: 'departureDate',
950    get: function get() {
951      return this._departureDate;
952    },
953    set: function set(departureDate) {
954      this._departureDate = departureDate;
955    }
956  }, {
957    key: 'arrivingDate',
958    get: function get() {
959      return this._arrivingDate;
960    },
961    set: function set(arrivingDate) {
962      this._arrivingDate = arrivingDate;
963    }
964  }, {
965    key: 'companyName',
966    get: function get() {
967      return this._companyName;
968    },
969    set: function set(companyName) {
970      this._companyName = companyName;
971    }
972  }, {
973    key: 'companyLogo',
974    get: function get() {
975      return this._companyLogo;
976    },
977    set: function set(companyLogo) {
978      this._companyLogo = companyLogo;
979    }
980  }, {
981    key: 'listOffer',
982    get: function get() {
983      return this._listOffer;
984    },
985    set: function set(listOffer) {
986      this._listOffer = listOffer;
987    }
988  }, {
989    key: 'origin',
990    get: function get() {
991      return this._origin;
992    },
993    set: function set(location) {
994      this._origin = location;
995    }
996  }, {
997    key: 'destination',
998    get: function get() {
999      return this._destination;
1000    },
1001    set: function set(location) {
1002      this._destination = location;
1003    }
1004  }, {
1005    key: 'favPurchase',
1006    get: function get() {
1007      return this._favPurchase;
1008    },
1009    set: function set(favPurchase) {
1010      this._favPurchase = favPurchase;
1011    }
1012  }, {
1013    key: 'companyAltTextLogo',
1014    get: function get() {
1015      return this._companyAltTextLogo;
1016    },
1017    set: function set(companyAltTextLogo) {
1018      this._companyAltTextLogo = companyAltTextLogo;
1019    }
1020  }, {
1021    key: 'connection',
1022    get: function get() {
1023        for (var i = 0; i < this._listOffer.length; i++) {
1024            var offer = this._listOffer[i];
1025            var conn = offer.connection;
1026
1027            if (!conn || (typeof conn === 'undefined' ? 'undefined' : _typeof(conn)) !== "object") continue;
1028
1029            if (conn.secondLeg) return conn;
1030            if (conn.thirdLeg) return conn;
1031        }
1032        return null;
1033    }
1034  }]);
1035
1036	return Company;
1037}();
1038
1039/**
1040 * FIM
1041 * COMPANY MODEL
1042 *
1043*/
1044'use strict';
1045
1046var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
1047
1048function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1049
1050var Connection = function () {
1051  function Connection() {
1052    _classCallCheck(this, Connection);
1053
1054    this._service = '';
1055    this._location = null;
1056    this._destination = null;
1057    this._classtype = new Classtype();
1058    this._company = '';
1059    this._arrivingDate = '';
1060    this._departureDate = '';
1061    this._price = '';
1062    this._freeSeats = '';
1063    this._token = '';
1064  }
1065
1066  _createClass(Connection, [{
1067    key: 'fromJSON',
1068    value: function fromJSON(connectionJSON) {
1069      this._service = connectionJSON._service;
1070      this._location = connectionJSON._location;
1071      this._destination = connectionJSON._destination;
1072      this._classtype = connectionJSON._classtype;
1073      this._arrivingDate = connectionJSON._arrivingDate;
1074      this._departureDate = connectionJSON._departureDate;
1075      this._price = connectionJSON._price;
1076      this._company = connectionJSON._company;
1077      this._freeSeats = connectionJSON._freeSeats;
1078      this._token = connectionJSON._token;
1079    }
1080  }, {
1081    key: 'service',
1082    get: function get() {
1083      return this._service;
1084    },
1085    set: function set(service) {
1086      this._service = service;
1087    }
1088  }, {
1089    key: 'location',
1090    get: function get() {
1091      return this._location;
1092    },
1093    set: function set(location) {
1094      this._location = new Location(location.id, location.label);
1095    }
1096  }, {
1097    key: 'destination',
1098    get: function get() {
1099      return this._destination;
1100    },
1101    set: function set(destination) {
1102      this._destination = new Location(destination.id, destination.label);
1103    }
1104  }, {
1105    key: 'classtype',
1106    get: function get() {
1107      return this._classtype;
1108    },
1109    set: function set(classtype) {
1110      this._classtype = classtype;
1111    }
1112  }, {
1113    key: 'company',
1114    get: function get() {
1115      return this._company;
1116    },
1117    set: function set(company) {
1118      this._company = company;
1119    }
1120  }, {
1121    key: 'price',
1122    get: function get() {
1123      return this._price;
1124    },
1125    set: function set(price) {
1126      this._price = price;
1127    }
1128  }, {
1129    key: 'arrivingDate',
1130    get: function get() {
1131      return this._arrivingDate;
1132    },
1133    set: function set(dateAndHour) {
1134      this._arrivingDate = dateAndHour;
1135    }
1136  }, {
1137    key: 'departureDate',
1138    get: function get() {
1139      return this._departureDate;
1140    },
1141    set: function set(dateAndHour) {
1142      this._departureDate = dateAndHour;
1143    }
1144  }, {
1145    key: 'freeSeats',
1146    get: function get() {
1147      return this._freeSeats;
1148    },
1149    set: function set(freeSeats) {
1150      this._freeSeats = freeSeats;
1151    }
1152  }, {
1153    key: 'token',
1154    get: function get() {
1155      return this._token;
1156    },
1157    set: function set(token) {
1158      this._token = token;
1159    }
1160  }]);
1161
1162  return Connection;
1163}();
1164"use strict";
1165
1166var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
1167
1168function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1169
1170var Location = function () {
1171  function Location(id, label) {
1172    _classCallCheck(this, Location);
1173
1174    this._id = id;
1175    this._label = label;
1176  }
1177
1178  _createClass(Location, [{
1179    key: "id",
1180    get: function get() {
1181      return this._id;
1182    }
1183  }, {
1184    key: "label",
1185    get: function get() {
1186      return this._label;
1187    }
1188  }]);
1189
1190  return Location;
1191}();
1192'use strict';
1193
1194var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
1195
1196function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1197
1198var Offer = function () {
1199	function Offer() {
1200		_classCallCheck(this, Offer);
1201
1202		this._classtype = new Classtype();
1203		this._price = 0.0;
1204		this._fare = 0.0;
1205		this._priceWithDiscountPix = 0.0;
1206		this._percentagePix = 0;
1207		this._boardingFee = 0.0;
1208		this._toll = 0.0;
1209		this._insurance = 0.0;
1210		this._others = 0.0;
1211		this._service = 0;
1212		this._freeArmchairs = 0;
1213		this._totalArmchairs = 0;
1214		this._sells = false;
1215		this._cheapest = false;
1216		this._group = '';
1217		this._token = '';
1218		this._company = new Company();
1219		this._isDeparture = true;
1220		this._connection = null;
1221		this._routeId = null;
1222        this._index = 0;
1223  }
1224
1225	_createClass(Offer, [{
1226		key: 'fromJSON',
1227		value: function fromJSON(offerJSON) {
1228			this._price = offerJSON._price;
1229			this._fare = offerJSON._fare;
1230			this._priceWithDiscountPix = offerJSON._priceWithDiscountPix;
1231			this._percentagePix = offerJSON._percentagePix;
1232			this._boardingFee = offerJSON._boardingFee;
1233			this._toll = offerJSON._toll;
1234			this._insurance = offerJSON._insurance;
1235			this._others = offerJSON._others;
1236			this._service = offerJSON._service;
1237			this._freeArmchairs = offerJSON._freeArmchairs;
1238			this._totalArmchairs = offerJSON._totalArmchairs;
1239			this._sells = offerJSON._sells;
1240			this._cheapest = offerJSON._cheapest;
1241			this._group = offerJSON._group;
1242			this._token = offerJSON._token;
1243			this._isDeparture = offerJSON._isDeparture;
1244			this._company.fromJSON(offerJSON._company);
1245			this._classtype.fromJSON(offerJSON._classtype);
1246			this._connection = offerJSON._connection || null;
1247            this._routeId = offerJSON._routeId;
1248            this._index = offerJSON._index;
1249        }
1250	}, {
1251		key: 'routeId',
1252		get: function get() {
1253			return this._routeId;
1254		},
1255		set: function set(routeId) {
1256			this._routeId = routeId;
1257		}
1258	}, {
1259		key: 'serviceType',
1260		get: function get() {
1261			return parseInt(this._service.charAt(0));
1262		}
1263	}, {
1264		key: 'company',
1265		get: function get() {
1266			return this._company;
1267		},
1268		set: function set(company) {
1269			this._company.departureDate = company.departureDate;
1270			this._company.arrivingDate = company.arrivingDate;
1271			this._company.companyLogo = company.companyLogo;
1272			this._company.companyName = company.companyName;
1273			this._company.origin = company.origin;
1274			this._company.destination = company.destination;
1275			this._company.companyId = company.companyId;
1276		}
1277	}, {
1278		key: 'group',
1279		get: function get() {
1280			return this._group;
1281		},
1282		set: function set(group) {
1283			this._group = group;
1284		}
1285	}, {
1286		key: 'token',
1287		get: function get() {
1288			return this._token;
1289		},
1290		set: function set(token) {
1291			this._token = token;
1292		}
1293	}, {
1294		key: 'classtype',
1295		get: function get() {
1296			return this._classtype;
1297		},
1298		set: function set(classtype) {
1299			this._classtype = classtype;
1300		}
1301	}, {
1302		key: 'price',
1303		get: function get() {
1304			return this._price;
1305		},
1306		set: function set(price) {
1307			this._price = price;
1308		}
1309	}, {
1310		key: 'priceWithDiscountPix',
1311		get: function get() {
1312			return this._priceWithDiscountPix;
1313		},
1314		set: function set(priceWithDiscountPix) {
1315			this._priceWithDiscountPix = priceWithDiscountPix;
1316		}
1317	}, {
1318		key: 'percentagePix',
1319		get: function get() {
1320			return this._percentagePix;
1321		},
1322		set: function set(percentagePix) {
1323			this._percentagePix = percentagePix;
1324		}
1325	}, {
1326		key: 'service',
1327		get: function get() {
1328			return this._service;
1329		},
1330		set: function set(service) {
1331			this._service = service;
1332		}
1333	}, {
1334		key: 'freeArmchairs',
1335		get: function get() {
1336			return this._freeArmchairs;
1337		},
1338		set: function set(freeArmchairs) {
1339			this._freeArmchairs = freeArmchairs;
1340		}
1341	}, {
1342		key: 'totalArmchairs',
1343		get: function get() {
1344			return this._totalArmchairs;
1345		},
1346		set: function set(totalArmchairs) {
1347			this._totalArmchairs = totalArmchairs;
1348		}
1349	}, {
1350		key: 'sell',
1351		get: function get() {
1352			return this._sells;
1353		},
1354		set: function set(sells) {
1355			this._sells = sells;
1356		}
1357	}, {
1358		key: 'cheapest',
1359		get: function get() {
1360			return this._cheapest;
1361		},
1362		set: function set(cheapest) {
1363			this._cheapest = cheapest;
1364		}
1365	}, {
1366		key: 'isDeparture',
1367		get: function get() {
1368			return this._isDeparture;
1369		},
1370		set: function set(isDeparture) {
1371			this._isDeparture = isDeparture;
1372		}
1373	}, {
1374		key: 'connection',
1375		get: function get() {
1376			return this._connection;
1377		},
1378		set: function set(connection) {
1379			this._connection = connection;
1380		}
1381	}, {
1382		key: 'fare',
1383		get: function get() {
1384			return this._fare;
1385		},
1386		set: function set(fare) {
1387			this._fare = fare;
1388		}
1389	}, {
1390		key: 'boardingFee',
1391		get: function get() {
1392			return this._boardingFee;
1393		},
1394		set: function set(boardingFee) {
1395			this._boardingFee = boardingFee;
1396		}
1397	}, {
1398		key: 'toll',
1399		get: function get() {
1400			return this._toll;
1401		},
1402		set: function set(toll) {
1403			this._toll = toll;
1404		}
1405	}, {
1406		key: 'insurance',
1407		get: function get() {
1408			return this._insurance;
1409		},
1410		set: function set(insurance) {
1411			this._insurance = insurance;
1412		}
1413    }, {
1414        key: 'index',
1415        get: function get() {
1416          return this._index;
1417        },
1418        set: function set(index) {
1419          this._index = index;
1420        }
1421    }, {
1422		key: 'others',
1423		get: function get() {
1424			return this._others;
1425		},
1426		set: function set(others) {
1427			this._others = others;
1428		}
1429	}]);
1430
1431	return Offer;
1432}();
1433"use strict";
1434
1435var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
1436
1437function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1438
1439var PassengerGiro = function () {
1440  function PassengerGiro() {
1441    _classCallCheck(this, PassengerGiro);
1442
1443    this._name = null;
1444    this._login = null;
1445    this._birthDate = null;
1446    this._email = null;
1447    this._cpf = null;
1448    this._cnpj = null;
1449    this._passport = null;
1450    this._documentNumber = null;
1451    this._phoneType = null;
1452    this._areaCode = null;
1453    this._phone = null;
1454    this._id = null;
1455    this._password = null;
1456    this._type = null;
1457    this._optin = false;
1458    this._registrationCampaign = null;
1459    this._addresses = null;
1460    this._groups = null;
1461    this._familyName = null;
1462  }
1463
1464  _createClass(PassengerGiro, [{
1465    key: "toJSON",
1466    value: function toJSON() {
1467      return {
1468        _name: this._name,
1469        _familyName: this._familyName,
1470        _login: this._login,
1471        _birthDate: this._birthDate,
1472        _email: this._email,
1473        _cpf: this._cpf,
1474        _cnpj: this._cnpj,
1475        _passport: this._passport,
1476        _documentNumber: this._documentNumber,
1477        _optin: this._optin,
1478        _areaCode: this._areaCode,
1479        _phone: this._phone,
1480        _phoneType: this._phoneType,
1481        _id: this._id,
1482        _type: this._type,
1483        _addresses: this._addresses ? this._addresses.toJSON() : new Address(),
1484        _groups: this._groups
1485      };
1486    }
1487  }, {
1488    key: "fromJSON",
1489    value: function fromJSON(passengerJSON) {
1490      $.each(passengerJSON, function (index, value) {
1491        if (typeof value === "string") passengerJSON[index] = value.replace(/%20/g, " ");
1492      });
1493
1494      this._login = passengerJSON._login;
1495      this._name = passengerJSON._name;
1496      this._familyName = passengerJSON._familyName;
1497      this._birthDate = passengerJSON._birthDate;
1498      this._email = passengerJSON._email;
1499      this._cpf = passengerJSON._cpf;
1500      this._cnpj = passengerJSON._cnpj;
1501      this._passport = passengerJSON._passport;
1502      this._documentNumber = passengerJSON._documentNumber;
1503      this._optin = passengerJSON._optin;
1504      this._areaCode = passengerJSON._areaCode;
1505      this._phone = passengerJSON._phone;
1506      this._phoneType = passengerJSON._phoneType;
1507      this._id = passengerJSON._id;
1508      this._groups = passengerJSON._groups;
1509      this._hasDiscount = passengerJSON._hasDiscount;
1510      this._type = passengerJSON._type;
1511      this._child = this.setChildValue(passengerJSON);
1512
1513      if (!Utils.isEmptyObj(passengerJSON._addresses)) {
1514        !this._addresses ? this._addresses = new Address() : '';
1515
1516        this._addresses.fromJSON(passengerJSON._addresses);
1517      }
1518    }
1519  }, {
1520    key: "passport",
1521    get: function get() {
1522      return this._passport;
1523    },
1524    set: function set(passport) {
1525      this._passport = passport;
1526    }
1527  }, {
1528    key: "login",
1529    get: function get() {
1530      return this._login;
1531    },
1532    set: function set(login) {
1533      this._login = login;
1534    }
1535  }, {
1536    key: "name",
1537    get: function get() {
1538      return this._name;
1539    },
1540    set: function set(name) {
1541      this._name = name;
1542    }
1543  }, {
1544    key: "familyName",
1545    get: function get() {
1546      return this._familyName;
1547    },
1548    set: function set(familyName) {
1549      this._familyName = familyName;
1550    }
1551  }, {
1552    key: "password",
1553    get: function get() {
1554      return this._password;
1555    },
1556    set: function set(password) {
1557      this._password = password;
1558    }
1559  }, {
1560    key: "areaCode",
1561    get: function get() {
1562      return this._areaCode;
1563    },
1564    set: function set(areaCode) {
1565      this._areaCode = areaCode;
1566    }
1567  }, {
1568    key: "birthDate",
1569    get: function get() {
1570      return this._birthDate;
1571    },
1572    set: function set(birthDate) {
1573      this._birthDate = birthDate;
1574    }
1575  }, {
1576    key: "email",
1577    get: function get() {
1578      return this._email;
1579    },
1580    set: function set(email) {
1581      this._email = email;
1582    }
1583  }, {
1584    key: "cpf",
1585    get: function get() {
1586      return this._cpf;
1587    },
1588    set: function set(cpf) {
1589      this._cpf = cpf;
1590    }
1591  }, {
1592    key: "cnpj",
1593    get: function get() {
1594      return this._cnpj;
1595    },
1596    set: function set(cnpj) {
1597      this._cnpj = cnpj;
1598    }
1599  }, {
1600    key: "documentNumber",
1601    get: function get() {
1602      return this._documentNumber;
1603    },
1604    set: function set(documentNumber) {
1605      this._documentNumber = documentNumber;
1606    }
1607  }, {
1608    key: "phone",
1609    get: function get() {
1610      return this._phone;
1611    },
1612    set: function set(phone) {
1613      this._phone = phone;
1614    }
1615  }, {
1616    key: "phoneType",
1617    get: function get() {
1618      return this._phoneType;
1619    },
1620    set: function set(phoneType) {
1621      this._phoneType = phoneType;
1622    }
1623  }, {
1624    key: "optin",
1625    get: function get() {
1626      return this._optin;
1627    },
1628    set: function set(optin) {
1629      this._optin = optin;
1630    }
1631  }, {
1632    key: "id",
1633    get: function get() {
1634      return this._id;
1635    },
1636    set: function set(id) {
1637      this._id = id;
1638    }
1639  }, {
1640    key: "type",
1641    get: function get() {
1642      return this._type;
1643    },
1644    set: function set(type) {
1645      this._type = type;
1646    }
1647  }, {
1648    key: "registrationCampaign",
1649    get: function get() {
1650      return this._registrationCampaign;
1651    },
1652    set: function set(registrationCampaign) {
1653      this._registrationCampaign = registrationCampaign;
1654    }
1655  }, {
1656    key: "addresses",
1657    get: function get() {
1658      return this._addresses;
1659    },
1660    set: function set(address) {
1661      this._addresses = address;
1662    }
1663  }, {
1664    key: "groups",
1665    get: function get() {
1666      return this._groups;
1667    },
1668    set: function set(groups) {
1669      this._groups = groups;
1670    }
1671  }, {
1672    key: "serviceJSON",
1673    get: function get() {
1674      return {
1675        birthDate: this.birthDate,
1676        cpf: this.cpf,
1677        cnpj: this.cnpj,
1678        passport: this.passport,
1679        name: this.name,
1680        familyName: this.familyName,
1681        login: this.login,
1682        email: this.email,
1683        phone: this.phone,
1684        areaCode: this.areaCode,
1685        phoneType: this.phoneType,
1686        password: this.password,
1687        optin: this.optin,
1688        company: 'cometa',
1689        registrationCampaign: this.registrationCampaign,
1690        groups: this.groups
1691      };
1692    }
1693  }]);
1694
1695  return PassengerGiro;
1696}();
1697"use strict";
1698
1699var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
1700
1701function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1702
1703var Passenger = function () {
1704  function Passenger() {
1705    _classCallCheck(this, Passenger);
1706
1707    this._name = null;
1708    this._login = null;
1709    this._image = null;
1710    this._birthDate = null;
1711    this._email = null;
1712    this._cpf = null;
1713    this._cnpj = null;
1714    this._passport = null;
1715    this._documentNumber = null;
1716    this._phoneType = null;
1717    this._areaCode = null;
1718    this._phone = null;
1719    this._id = null;
1720    this._password = null;
1721    this._hasDiscount = false;
1722    this._type = null;
1723    this._optin = false;
1724    this._child = null;
1725    this._specialService = "NORMAL";
1726    this._registrationCampaign = null;
1727    this._seatDeparture = new Seat();
1728    this._seatReturn = new Seat();
1729    this._seatDepartureConnection = new Seat();
1730    this._seatReturnConnection = new Seat();
1731    this._emailPrimaryStatus = null;
1732    this._emailSecondaryStatus = null;
1733    this._addresses = null;
1734    this._groups = null;
1735    this._validated = null;
1736    this._seatDepartureConnection2 = new Seat();
1737    this._seatReturnConnection2 = new Seat();
1738  }
1739
1740  _createClass(Passenger, [{
1741    key: "toJSON",
1742    value: function toJSON() {
1743      return {
1744        _name: this._name,
1745        _login: this._login,
1746        _image: this._image,
1747        _birthDate: this._birthDate,
1748        _email: this._email,
1749        _cpf: this._cpf,
1750        _cnpj: this._cnpj,
1751        _passport: this._passport,
1752        _documentNumber: this._documentNumber,
1753        _optin: this._optin,
1754        _areaCode: this._areaCode,
1755        _phone: this._phone,
1756        _phoneType: this._phoneType,
1757        _id: this._id,
1758        _child: this._child ? this._child.toJSON() : null,
1759        _hasDiscount: this._hasDiscount,
1760        _seatDeparture: this._seatDeparture.toJSON(),
1761        _seatReturn: this._seatReturn.toJSON(),
1762        _seatDepartureConnection: this._seatDepartureConnection.toJSON(),
1763        _seatReturnConnection: this._seatReturnConnection.toJSON(),
1764        _type: this._type,
1765        _specialService: this._specialService,
1766        _validated: this._validated,
1767        _summaryDeparture: this._summaryDeparture,
1768        _summaryReturn: this._summaryReturn,
1769        _addresses: this._addresses ? this._addresses.toJSON() : new Address(),
1770        _emailPrimaryStatus: this._emailPrimaryStatus,
1771        _emailSecondaryStatus: this._emailSecondaryStatus,
1772        _groups: this._groups,
1773        _seatDepartureConnection2: this._seatDepartureConnection2.toJSON(),
1774        _seatReturnConnection2: this._seatReturnConnection2.toJSON()
1775      };
1776    }
1777  }, {
1778    key: "fromJSON",
1779    value: function fromJSON(passengerJSON) {
1780      $.each(passengerJSON, function (index, value) {
1781        if (typeof value === "string") passengerJSON[index] = value.replace(/%20/g, " ");
1782      });
1783
1784      this._login = passengerJSON._login;
1785      this._name = passengerJSON._name;
1786      this._birthDate = passengerJSON._birthDate;
1787      this._image = passengerJSON._image, this._email = passengerJSON._email;
1788      this._cpf = passengerJSON._cpf;
1789      this._cnpj = passengerJSON._cnpj;
1790      this._passport = passengerJSON._passport;
1791      this._documentNumber = passengerJSON._documentNumber;
1792      this._optin = passengerJSON._optin;
1793      this._areaCode = passengerJSON._areaCode;
1794      this._phone = passengerJSON._phone;
1795      this._phoneType = passengerJSON._phoneType;
1796      this._id = passengerJSON._id;
1797      this._groups = passengerJSON._groups;
1798      this._hasDiscount = passengerJSON._hasDiscount;
1799      this._seatDeparture.fromJSON(passengerJSON._seatDeparture);
1800      this._seatReturn.fromJSON(passengerJSON._seatReturn);
1801      this._seatDepartureConnection.fromJSON(passengerJSON._seatDepartureConnection);
1802      this._seatReturnConnection.fromJSON(passengerJSON._seatReturnConnection);
1803      this._type = passengerJSON._type;
1804      this._specialService = passengerJSON._specialService;
1805      this.emailPrimaryStatus = passengerJSON._emailPrimaryStatus;
1806      this.emailSecondaryStatus = passengerJSON._emailSecondaryStatus;
1807      this.validated = passengerJSON._validated;
1808      this._child = this.setChildValue(passengerJSON);
1809      this._seatDepartureConnection2.fromJSON(passengerJSON._seatDepartureConnection2);
1810      this._seatReturnConnection2.fromJSON(passengerJSON._seatReturnConnection2);
1811
1812      if (!Utils.isEmptyObj(passengerJSON._addresses)) {
1813        !this._addresses ? this._addresses = new Address() : '';
1814
1815        this._addresses.fromJSON(passengerJSON._addresses);
1816      }
1817    }
1818  }, {
1819    key: "setChildValue",
1820    value: function setChildValue(passengerJSON) {
1821      if (passengerJSON._child) {
1822        return new Child(passengerJSON._child);
1823      } else {
1824        return passengerJSON._child;
1825      }
1826    }
1827  }, {
1828    key: "personDiff",
1829    value: function personDiff(originalPassenger) {
1830      var _this = this;
1831
1832      var diffPassenger = {};
1833
1834      $.each(originalPassenger.serviceJSON, function (i, originalValue) {
1835        $.each(_this.serviceJSON, function (j, value) {
1836          if (i == j && originalValue != value) {
1837            diffPassenger[i] = value;
1838            return false;
1839          }
1840        });
1841      });
1842
1843      var objWithoutFalsey = {};
1844      objWithoutFalsey = {};
1845
1846      for (var i in diffPassenger) {
1847        var value = diffPassenger[i];
1848        if (value != null) objWithoutFalsey[i] = value;
1849      }
1850
1851      return objWithoutFalsey;
1852    }
1853  }, {
1854    key: "passport",
1855    get: function get() {
1856      return this._passport;
1857    },
1858    set: function set(passport) {
1859      this._passport = passport;
1860    }
1861  }, {
1862    key: "emailPrimaryStatus",
1863    get: function get() {
1864      return this._emailPrimaryStatus;
1865    },
1866    set: function set(emailPrimaryStatus) {
1867      this._emailPrimaryStatus = emailPrimaryStatus;
1868    }
1869  }, {
1870    key: "emailSecondaryStatus",
1871    get: function get() {
1872      return this._emailSecondaryStatus;
1873    },
1874    set: function set(emailPrimaryStatus) {
1875      this._emailSecondaryStatus = emailPrimaryStatus;
1876    }
1877  }, {
1878    key: "login",
1879    get: function get() {
1880      return this._login;
1881    },
1882    set: function set(login) {
1883      this._login = login;
1884    }
1885  }, {
1886    key: "name",
1887    get: function get() {
1888      return this._name;
1889    },
1890    set: function set(name) {
1891      this._name = name;
1892    }
1893  }, {
1894    key: "password",
1895    get: function get() {
1896      return this._password;
1897    },
1898    set: function set(password) {
1899      this._password = password;
1900    }
1901  }, {
1902    key: "areaCode",
1903    get: function get() {
1904      return this._areaCode;
1905    },
1906    set: function set(areaCode) {
1907      this._areaCode = areaCode;
1908    }
1909  }, {
1910    key: "birthDate",
1911    get: function get() {
1912      return this._birthDate;
1913    },
1914    set: function set(birthDate) {
1915      this._birthDate = birthDate;
1916    }
1917  }, {
1918    key: "email",
1919    get: function get() {
1920      return this._email;
1921    },
1922    set: function set(email) {
1923      this._email = email;
1924    }
1925  }, {
1926    key: "cpf",
1927    get: function get() {
1928      return this._cpf;
1929    },
1930    set: function set(cpf) {
1931      this._cpf = cpf;
1932    }
1933  }, {
1934    key: "cnpj",
1935    get: function get() {
1936      return this._cnpj;
1937    },
1938    set: function set(cnpj) {
1939      this._cnpj = cnpj;
1940    }
1941  }, {
1942    key: "documentNumber",
1943    get: function get() {
1944      return this._documentNumber;
1945    },
1946    set: function set(documentNumber) {
1947      this._documentNumber = documentNumber;
1948    }
1949  }, {
1950    key: "phone",
1951    get: function get() {
1952      return this._phone;
1953    },
1954    set: function set(phone) {
1955      this._phone = phone;
1956    }
1957  }, {
1958    key: "phoneType",
1959    get: function get() {
1960      return this._phoneType;
1961    },
1962    set: function set(phoneType) {
1963      this._phoneType = phoneType;
1964    }
1965  }, {
1966    key: "optin",
1967    get: function get() {
1968      return this._optin;
1969    },
1970    set: function set(optin) {
1971      this._optin = optin;
1972    }
1973  }, {
1974    key: "id",
1975    get: function get() {
1976      return this._id;
1977    },
1978    set: function set(id) {
1979      this._id = id;
1980    }
1981  }, {
1982    key: "familyName",
1983    get: function get() {
1984      return this._familyName;
1985    },
1986    set: function set(familyName) {
1987      this._familyName = familyName;
1988    }
1989  }, {
1990    key: "hasDiscount",
1991    get: function get() {
1992      return this._hasDiscount;
1993    },
1994    set: function set(hasDiscount) {
1995      this._hasDiscount = hasDiscount;
1996    }
1997  }, {
1998    key: "seatDeparture",
1999    get: function get() {
2000      return this._seatDeparture;
2001    },
2002    set: function set(seatDeparture) {
2003      this._seatDeparture = seatDeparture;
2004    }
2005  }, {
2006    key: "seatReturn",
2007    get: function get() {
2008      return this._seatReturn;
2009    },
2010    set: function set(seatReturn) {
2011      this._seatReturn = seatReturn;
2012    }
2013  }, {
2014    key: "seatDepartureConnection",
2015    get: function get() {
2016      return this._seatDepartureConnection;
2017    },
2018    set: function set(seatDepartureConnection) {
2019      this._seatDepartureConnection = seatDepartureConnection;
2020    }
2021  }, {
2022    key: "seatReturnConnection",
2023    get: function get() {
2024      return this._seatReturnConnection;
2025    },
2026    set: function set(seatReturnConnection) {
2027      this._seatReturnConnection = seatReturnConnection;
2028    }
2029  }, {
2030    key: "seatDepartureConnection2",
2031    get: function get() {
2032      return this._seatDepartureConnection2;
2033    },
2034    set: function set(seatDepartureConnection2) {
2035      this._seatDepartureConnection2 = seatDepartureConnection2;
2036    }
2037  }, {
2038    key: "seatReturnConnection2",
2039    get: function get() {
2040      return this._seatReturnConnection2;
2041    },
2042    set: function set(seatReturnConnection2) {
2043      this._seatReturnConnection2 = seatReturnConnection2;
2044    }
2045  }, {
2046    key: "type",
2047    get: function get() {
2048      return this._type;
2049    },
2050    set: function set(type) {
2051      this._type = type;
2052    }
2053  }, {
2054    key: "specialService",
2055    get: function get() {
2056      return this._specialService;
2057    },
2058    set: function set(specialService) {
2059      this._specialService = specialService;
2060    }
2061  }, {
2062    key: "image",
2063    get: function get() {
2064      return this._image;
2065    },
2066    set: function set(image) {
2067      this._image = image;
2068    }
2069  }, {
2070    key: "child",
2071    get: function get() {
2072      return this._child;
2073    },
2074    set: function set(child) {
2075      this._child = child;
2076    }
2077  }, {
2078    key: "registrationCampaign",
2079    get: function get() {
2080      return this._registrationCampaign;
2081    },
2082    set: function set(registrationCampaign) {
2083      this._registrationCampaign = registrationCampaign;
2084    }
2085  }, {
2086    key: "referredCode",
2087    get: function get() {
2088      return this._referredCode;
2089    },
2090    set: function set(referredCode) {
2091      this._referredCode = referredCode;
2092    }
2093  }, {
2094    key: "addresses",
2095    get: function get() {
2096      return this._addresses;
2097    },
2098    set: function set(address) {
2099      this._addresses = address;
2100    }
2101  }, {
2102    key: "groups",
2103    get: function get() {
2104      return this._groups;
2105    },
2106    set: function set(groups) {
2107      this._groups = groups;
2108    }
2109  }, {
2110    key: "validated",
2111    get: function get() {
2112      return this._validated;
2113    },
2114    set: function set(validated) {
2115      this._validated = validated;
2116    }
2117  }, {
2118    key: "serviceJSON",
2119    get: function get() {
2120      return {
2121        birthDate: this.birthDate,
2122        cpf: this.cpf,
2123        cnpj: this.cnpj,
2124        passport: this.passport,
2125        name: this.name,
2126        familyName: this.familyName,
2127        login: this.login,
2128        email: this.email,
2129        phone: this.phone,
2130        areaCode: this.areaCode,
2131        phoneType: this.phoneType,
2132        password: this.password,
2133        optin: this.optin,
2134        company: $('#siteName').val(),
2135        registrationCampaign: this.registrationCampaign,
2136        addresses: this.addresses,
2137        groups: this.groups,
2138        image: this.image,
2139        emailPrimaryStatus: this.emailPrimaryStatus,
2140        emailSecondaryStatus: this._emailSecondaryStatus,
2141        validated: this.validated
2142      };
2143    }
2144  }]);
2145
2146  return Passenger;
2147}();
2148'use strict';
2149
2150var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
2151
2152function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2153
2154var PaymentBankTransfer = function () {
2155  function PaymentBankTransfer(branch, account, paymentMethod, document, deviceFingerprint, passengers, hasInsurance, hasInsuranceW2i, ip, salePlatform) {
2156    _classCallCheck(this, PaymentBankTransfer);
2157
2158    this._branch = branch, this._account = account;
2159    this._paymentMethod = paymentMethod, this._document = document, this._deviceFingerprint = deviceFingerprint;
2160    this._passengers = passengers;
2161    this._hasInsurance = hasInsurance;
2162    this._hasInsuranceW2i = hasInsuranceW2i;
2163    this._ip = ip;
2164    this._salePlatform = salePlatform;
2165  }
2166
2167  _createClass(PaymentBankTransfer, [{
2168    key: 'getSeats',
2169    value: function getSeats(passenger) {
2170      var seats = [];
2171      seats.push({
2172        Service: passenger._seatDeparture._service,
2173        Seat: passenger._seatDeparture._seatNumber
2174      });
2175
2176      if (passenger._seatDepartureConnection._service != null) {
2177        seats.push({
2178          Service: passenger._seatDepartureConnection._service,
2179          Seat: passenger._seatDepartureConnection._seatNumber
2180        });
2181      }
2182
2183      if (passenger._seatDepartureConnection2._service != null) {
2184        seats.push({
2185          Service: passenger._seatDepartureConnection2._service,
2186          Seat: passenger._seatDepartureConnection2._seatNumber
2187        });
2188      }
2189
2190      if (passenger._seatReturn._service != null) {
2191        seats.push({
2192          Service: passenger._seatReturn._service,
2193          Seat: passenger._seatReturn._seatNumber
2194        });
2195      }
2196
2197      if (passenger._seatReturnConnection._service != null) {
2198        seats.push({
2199          Service: passenger._seatReturnConnection._service,
2200          Seat: passenger._seatReturnConnection._seatNumber
2201        });
2202      }
2203
2204      if (passenger._seatReturnConnection2._service != null) {
2205        seats.push({
2206          Service: passenger._seatReturnConnection2._service,
2207          Seat: passenger._seatReturnConnection2._seatNumber
2208        });
2209      }
2210
2211      return seats;
2212    }
2213  }, {
2214    key: 'toJSON',
2215    value: function toJSON() {
2216      var json = {
2217        "Branch": this.branch,
2218        "Account": this.account,
2219        "PaymentMethod": this.paymentMethod,
2220        "Document": this.document,
2221        "DeviceFingerPrint": this.deviceFingerprint,
2222        "Passengers": this.passengers,
2223        "ShopperIP": this.ip,
2224        "Insurance": this.hasInsurance,
2225        "W2iInsurance": this.hasInsuranceW2i
2226      };
2227
2228      if (this.salePlatform) {
2229        json["SalePlatform"] = this.salePlatform;
2230      }
2231
2232      if (this._cardCvv) {
2233        json.CardCvv = this._cardCvv;
2234      }
2235
2236      return json;
2237    }
2238  }, {
2239    key: 'paymentMethod',
2240    get: function get() {
2241      return this._paymentMethod;
2242    }
2243  }, {
2244    key: 'branch',
2245    get: function get() {
2246      return this._branch;
2247    }
2248  }, {
2249    key: 'document',
2250    get: function get() {
2251      return this._document;
2252    }
2253  }, {
2254    key: 'account',
2255    get: function get() {
2256      var account = this._account;
2257      var position = this._account.length - 1;
2258
2259      return [account.slice(0, position), '-', account.slice(position)].join('');
2260    }
2261  }, {
2262    key: 'deviceFingerprint',
2263    get: function get() {
2264      return this._deviceFingerprint;
2265    }
2266  }, {
2267    key: 'hasInsurance',
2268    get: function get() {
2269      return this._hasInsurance;
2270    }
2271  }, {
2272    key: 'hasInsuranceW2i',
2273    get: function get() {
2274      return this._hasInsuranceW2i;
2275    }
2276  }, {
2277    key: 'ip',
2278    get: function get() {
2279      return this._ip;
2280    }
2281  }, {
2282    key: 'salePlatform',
2283    get: function get() {
2284      return this._salePlatform;
2285    }
2286  }, {
2287    key: 'passengers',
2288    get: function get() {
2289      var _this = this;
2290
2291      return this._passengers.reduce(function (acc, passenger, _, arr) {
2292        var psgr = {
2293          Name: passenger.name,
2294          birthday: passenger.birthDate != null ? Utils.formatDateToISO(passenger.birthDate) : "",
2295          Document: passenger.documentNumber,
2296          Type: passenger.type,
2297          Seats: _this.getSeats(passenger, arr)
2298        };
2299
2300        if (passenger.child) {
2301          psgr.child = {
2302            birthday: passenger.child.birthday,
2303            documentType: passenger.child.documentType,
2304            document: passenger.child.document,
2305            name: passenger.child.name
2306          };
2307        }
2308
2309        if (passenger.type !== "CHILD") acc.push(psgr);
2310
2311        return acc;
2312      }, []);
2313    }
2314  }]);
2315
2316  return PaymentBankTransfer;
2317}();
2318"use strict";
2319
2320var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
2321
2322function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2323
2324var PaymentLivelo = function () {
2325  function PaymentLivelo(passengers, hasInsuranceW2i, token, type) {
2326    _classCallCheck(this, PaymentLivelo);
2327
2328    this._passengers = passengers;
2329    this._token = token;
2330    this._type = type;
2331  }
2332
2333  _createClass(PaymentLivelo, [{
2334    key: "getSeats",
2335    value: function getSeats(passenger) {
2336      var seats = [];
2337      seats.push({
2338        Service: passenger._seatDeparture._service,
2339        Seat: passenger._seatDeparture._seatNumber
2340      });
2341
2342      if (passenger._seatDepartureConnection._service != null) {
2343        seats.push({
2344          Service: passenger._seatDepartureConnection._service,
2345          Seat: passenger._seatDepartureConnection._seatNumber
2346        });
2347      }
2348
2349      if (passenger._seatDepartureConnection2._service != null) {
2350        seats.push({
2351          Service: passenger._seatDepartureConnection2._service,
2352          Seat: passenger._seatDepartureConnection2._seatNumber
2353        });
2354      }
2355
2356      if (passenger._seatReturn._service != null) {
2357        seats.push({
2358          Service: passenger._seatReturn._service,
2359          Seat: passenger._seatReturn._seatNumber
2360        });
2361      }
2362
2363      if (passenger._seatReturnConnection._service != null) {
2364        seats.push({
2365          Service: passenger._seatReturnConnection._service,
2366          Seat: passenger._seatReturnConnection._seatNumber
2367        });
2368      }
2369
2370      if (passenger._seatReturnConnection2._service != null) {
2371        seats.push({
2372          Service: passenger._seatReturnConnection2._service,
2373          Seat: passenger._seatReturnConnection2._seatNumber
2374        });
2375      }
2376
2377      return seats;
2378    }
2379  }, {
2380    key: "toJSON",
2381    value: function toJSON() {
2382      return {
2383        "W2iInsurance": this.hasInsuranceW2i,
2384        "Passengers": this.passengers,
2385        "Token": this.token,
2386        "Type": this.type
2387      };
2388    }
2389  }, {
2390    key: "hasInsuranceW2i",
2391    get: function get() {
2392      return this._hasInsuranceW2i;
2393    }
2394  }, {
2395    key: "token",
2396    get: function get() {
2397      return this._token;
2398    }
2399  }, {
2400    key: "type",
2401    get: function get() {
2402      return this._type;
2403    }
2404  }, {
2405    key: "passengers",
2406    get: function get() {
2407      var _this = this;
2408
2409      return this._passengers.reduce(function (acc, passenger, _, arr) {
2410        var psgr = {
2411          Name: passenger.name,
2412          Document: passenger.documentNumber,
2413          birthday: passenger.birthDate != null ? Utils.formatDateToISO(passenger.birthDate) : "",
2414          Type: passenger.type,
2415          Seats: _this.getSeats(passenger, arr)
2416        };
2417
2418        acc.push(psgr);
2419        return acc;
2420      }, []);
2421    }
2422  }]);
2423
2424  return PaymentLivelo;
2425}();
2426"use strict";
2427
2428var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
2429
2430function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2431
2432/**
2433 * INICIO
2434 * PAYMENT MODEL
2435 *
2436*/
2437var PaymentMalga = function () {
2438  function PaymentMalga(tokenId, holderName, recurring, installments, deviceFingerprint, passengers, merchantAccountId, merchantAccount, hasInsurance, ip, salePlatform, deviceId, cardCvv) {
2439    _classCallCheck(this, PaymentMalga);
2440
2441    this._tokenId = tokenId;
2442    this._holderName = holderName;
2443    this._recurring = recurring;
2444    this._installments = installments;
2445    this._deviceFingerprint = deviceFingerprint;
2446    this._passengers = passengers;
2447    this._merchantAccountId = merchantAccountId;
2448    this._merchantAccount = merchantAccount;
2449    this._hasInsurance = hasInsurance;
2450    this._ip = ip;
2451    this._salePlatform = salePlatform;
2452    this._deviceId = deviceId;
2453    this._cardCvv = cardCvv;
2454  }
2455
2456  _createClass(PaymentMalga, [{
2457    key: 'getSeats',
2458    value: function getSeats(passenger) {
2459      var seats = [];
2460      seats.push({
2461        Service: passenger._seatDeparture._service,
2462        Seat: passenger._seatDeparture._seatNumber
2463      });
2464
2465      if (passenger._seatDepartureConnection._service != null) {
2466        seats.push({
2467          Service: passenger._seatDepartureConnection._service,
2468          Seat: passenger._seatDepartureConnection._seatNumber
2469        });
2470      }
2471
2472      if (passenger._seatDepartureConnection2._service != null) {
2473        seats.push({
2474          Service: passenger._seatDepartureConnection2._service,
2475          Seat: passenger._seatDepartureConnection2._seatNumber
2476        });
2477      }
2478
2479      if (passenger._seatReturn._service != null) {
2480        seats.push({
2481          Service: passenger._seatReturn._service,
2482          Seat: passenger._seatReturn._seatNumber
2483        });
2484      }
2485
2486      if (passenger._seatReturnConnection._service != null) {
2487        seats.push({
2488          Service: passenger._seatReturnConnection._service,
2489          Seat: passenger._seatReturnConnection._seatNumber
2490        });
2491      }
2492
2493      if (passenger._seatReturnConnection2._service != null) {
2494        seats.push({
2495          Service: passenger._seatReturnConnection2._service,
2496          Seat: passenger._seatReturnConnection2._seatNumber
2497        });
2498      }
2499
2500      return seats;
2501    }
2502  }, {
2503    key: 'isPassengersWhatsapp',
2504    value: function isPassengersWhatsapp(array) {
2505      var isValidFormat = array.every(function (obj) {
2506        return typeof obj.name === "string" && typeof obj.document === "string" && typeof obj.type === "string" && typeof obj.birthday === "string" && Array.isArray(obj.seats) && obj.seats.every(function (seat) {
2507          return typeof seat.service === "number" && typeof seat.seat === "string";
2508        });
2509      });
2510
2511      return isValidFormat;
2512    }
2513  }, {
2514    key: 'toJSON',
2515    value: function toJSON() {
2516      var json = {
2517        "Installments": this.installments,
2518        "MerchantAccount": this.merchantAccount,
2519        "CardId": this.tokenId,
2520        "HolderName": this.holderName,
2521        "merchan_account_id": this.merchantAccountId,
2522        "DeviceFingerPrint": this.deviceFingerprint,
2523        "ShopperIP": this.ip,
2524        "Passengers": this.passengers,
2525        "Insurance": this.hasInsurance,
2526        "Recurring": this.recurring,
2527        "DeviceId": this.deviceId
2528      };
2529
2530      if (this._cardCvv) {
2531        json.CardCvv = this._cardCvv;
2532      }
2533
2534      if (this.salePlatform) {
2535        json["SalePlatform"] = this.salePlatform;
2536      }
2537
2538      return json;
2539    }
2540  }, {
2541    key: 'tokenId',
2542    get: function get() {
2543      return this._tokenId;
2544    }
2545  }, {
2546    key: 'recurring',
2547    get: function get() {
2548      return this._recurring;
2549    }
2550  }, {
2551    key: 'holderName',
2552    get: function get() {
2553      return this._holderName;
2554    }
2555  }, {
2556    key: 'deviceFingerprint',
2557    get: function get() {
2558      return this._deviceFingerprint;
2559    }
2560  }, {
2561    key: 'installments',
2562    get: function get() {
2563      return this._installments;
2564    }
2565  }, {
2566    key: 'merchantAccountId',
2567    get: function get() {
2568      return this._merchantAccountId;
2569    }
2570  }, {
2571    key: 'merchantAccount',
2572    get: function get() {
2573      return this._merchantAccount;
2574    }
2575  }, {
2576    key: 'hasInsurance',
2577    get: function get() {
2578      return this._hasInsurance;
2579    }
2580  }, {
2581    key: 'ip',
2582    get: function get() {
2583      return this._ip;
2584    }
2585  }, {
2586    key: 'salePlatform',
2587    get: function get() {
2588      return this._salePlatform;
2589    }
2590  }, {
2591    key: 'deviceId',
2592    get: function get() {
2593      return this._deviceId;
2594    }
2595  }, {
2596    key: 'CardCvv',
2597    get: function get() {
2598      return this._cardCvv;
2599    }
2600  }, {
2601    key: 'passengers',
2602    get: function get() {
2603      var _this = this;
2604
2605      var passengersToRepricing = SessionStorage.get('passengersToRepricing');
2606      var repricingV2 = SessionStorage.get('repricingv2');
2607
2608      if (this.isPassengersWhatsapp(this._passengers)) {
2609        var formattedArray = this._passengers.map(function (obj) {
2610          if (typeof obj.birthday === "string") {
2611            obj.birthday = Utils.formatDateToISO(obj.birthday);
2612          }
2613          return obj;
2614        });
2615
2616        return formattedArray;
2617      } else if (this.repricingV2) {
2618        var childIndex = 0;
2619
2620        return this._passengers.reduce(function (acc, passenger, index, arr) {
2621          var passengerTo = passengersToRepricing.passengers[index];
2622          var children = passengersToRepricing.passengers.filter(function (passenger) {
2623            return passenger.type === "CHILD";
2624          });
2625
2626          var psgr = {
2627            Name: passenger.name,
2628            birthday: passengerTo.birthday,
2629            Document: passengerTo.document,
2630            Type: passengerTo.type,
2631            Seats: _this.getSeats(passenger, arr)
2632          };
2633
2634          if (passenger.type === "ADULT" && childIndex < children.length) {
2635            var childPassenger = children[childIndex];
2636            psgr.child = {
2637              birthday: childPassenger.birthday,
2638              document: childPassenger.document,
2639              name: childPassenger.name
2640            };
2641          }
2642
2643          if (passenger.type !== "CHILD") acc.push(psgr);
2644
2645          return acc;
2646        }, []);
2647      } else {
2648        return this._passengers.reduce(function (acc, passenger, _, arr) {
2649          var psgr = {
2650            Name: passenger.name,
2651            Document: passenger.documentNumber,
2652            Type: passenger.type,
2653            Seats: _this.getSeats(passenger, arr)
2654          };
2655
2656          if (!repricingV2) {
2657            psgr.birthday = Utils.formatDateToISO(passenger.birthDate);
2658          }
2659
2660          if (passenger.child) {
2661            psgr.child = {
2662              birthday: passenger.child.birthday,
2663              documentType: passenger.child.documentType,
2664              document: passenger.child.document,
2665              name: passenger.child.name
2666            };
2667          }
2668
2669          if (passenger.type !== "CHILD") acc.push(psgr);
2670
2671          return acc;
2672        }, []);
2673      }
2674    }
2675  }]);
2676
2677  return PaymentMalga;
2678}();
2679
2680/**
2681 * FIM
2682 * PAYMENT MODEL
2683 *
2684*/
2685"use strict";
2686
2687var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
2688
2689function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2690
2691/**
2692 * INICIO
2693 * PAYMENT MODEL
2694 *
2695*/
2696var PaymentNegative = function () {
2697  function PaymentNegative(recurring, installments, passengers, merchantAccountId, hasInsurance, ip, refundInformation) {
2698    _classCallCheck(this, PaymentNegative);
2699
2700    this._recurring = recurring;
2701    this._installments = installments;
2702    this._passengers = passengers;
2703    this._merchantAccountId = merchantAccountId;
2704    this._hasInsurance = hasInsurance;
2705    this._ip = ip;
2706    this._refundInformation = refundInformation;
2707  }
2708
2709  _createClass(PaymentNegative, [{
2710    key: "getSeats",
2711    value: function getSeats(passenger, passengersArr) {
2712      var seats = [];
2713
2714      if (passenger.type === "CHILD") {
2715        var child = passengersArr[0];
2716
2717        var departureSeat = { Service: child._seatDeparture._service, Seat: child._seatDeparture._seatNumber };
2718        seats.push(departureSeat);
2719
2720        if (child._seatDepartureConnection._service != null) {
2721          seats.push({
2722            Service: child._seatDepartureConnection._service,
2723            Seat: child._seatDepartureConnection._seatNumber
2724          });
2725        }
2726
2727        if (child._seatDepartureConnection2._service != null) {
2728          seats.push({
2729            Service: child._seatDepartureConnection2._service,
2730            Seat: child._seatDepartureConnection2._seatNumber
2731          });
2732        }
2733
2734        if (child._seatReturn._service != null) {
2735          var returnSeat = { Service: child._seatReturn._service, Seat: child._seatReturn._seatNumber };
2736          seats.push(returnSeat);
2737        }
2738
2739        if (child._seatReturnConnection._service != null) {
2740          seats.push({
2741            Service: child._seatReturnConnection._service,
2742            Seat: child._seatReturnConnection._seatNumber
2743          });
2744        }
2745
2746        if (child._seatReturnConnection2._service != null) {
2747          seats.push({
2748            Service: child._seatReturnConnection2._service,
2749            Seat: child._seatReturnConnection2._seatNumber
2750          });
2751        }
2752      } else {
2753        var _departureSeat = { Service: passenger._seatDeparture._service, Seat: passenger._seatDeparture._seatNumber };
2754        seats.push(_departureSeat);
2755
2756        if (passenger._seatDepartureConnection._service != null) {
2757          seats.push({
2758            Service: passenger._seatDepartureConnection._service,
2759            Seat: passenger._seatDepartureConnection._seatNumber
2760          });
2761        }
2762
2763        if (passenger._seatDepartureConnection2._service != null) {
2764          seats.push({
2765            Service: passenger._seatDepartureConnection2._service,
2766            Seat: passenger._seatDepartureConnection2._seatNumber
2767          });
2768        }
2769
2770        if (passenger._seatReturn._service != null) {
2771          var _returnSeat = { Service: passenger._seatReturn._service, Seat: passenger._seatReturn._seatNumber };
2772          seats.push(_returnSeat);
2773        }
2774
2775        if (passenger._seatReturnConnection._service != null) {
2776          seats.push({
2777            Service: passenger._seatReturnConnection._service,
2778            Seat: passenger._seatReturnConnection._seatNumber
2779          });
2780        }
2781
2782        if (passenger._seatReturnConnection2._service != null) {
2783          seats.push({
2784            Service: passenger._seatReturnConnection2._service,
2785            Seat: passenger._seatReturnConnection2._seatNumber
2786          });
2787        }
2788      }
2789
2790      return seats;
2791    }
2792  }, {
2793    key: "toJSON",
2794    value: function toJSON() {
2795      var payment = {
2796        "Recurring": this.recurring,
2797        "DeviceId": this.deviceId,
2798        "Insurance": this.hasInsurance,
2799        "Installments": '1',
2800        "Passengers": this.passengers,
2801        "MerchantAccountId": this.merchantAccountId,
2802        "ShopperIP": this.ip
2803      };
2804
2805      if (this.refundInformation) payment.RefundInformation = this.refundInformation;
2806
2807      return payment;
2808    }
2809  }, {
2810    key: "recurring",
2811    get: function get() {
2812      return this._recurring;
2813    }
2814  }, {
2815    key: "installments",
2816    get: function get() {
2817      return this._installments;
2818    }
2819  }, {
2820    key: "merchantAccountId",
2821    get: function get() {
2822      return this._merchantAccountId;
2823    }
2824  }, {
2825    key: "hasInsurance",
2826    get: function get() {
2827      return this._hasInsurance;
2828    }
2829  }, {
2830    key: "ip",
2831    get: function get() {
2832      return this._ip;
2833    }
2834  }, {
2835    key: "refundInformation",
2836    get: function get() {
2837      return this._refundInformation;
2838    }
2839  }, {
2840    key: "passengers",
2841    get: function get() {
2842      var _this = this;
2843
2844      return this._passengers.reduce(function (acc, passenger, _, arr) {
2845        var psgr = {
2846          Name: passenger.name,
2847          Document: passenger.documentNumber,
2848          birthday: passenger.birthDate != null ? Utils.formatDateToISO(passenger.birthDate) : "",
2849          Type: passenger.type,
2850          Seats: _this.getSeats(passenger, arr)
2851        };
2852
2853        if (passenger.child) {
2854          psgr.child = {
2855            birthday: passenger.child.birthday,
2856            documentType: passenger.child.documentType,
2857            document: passenger.child.document,
2858            name: passenger.child.name
2859          };
2860        }
2861
2862        if (passenger.type !== "CHILD") acc.push(psgr);
2863
2864        return acc;
2865      }, []);
2866    }
2867  }]);
2868
2869  return PaymentNegative;
2870}();
2871
2872/**
2873 * FIM
2874 * PAYMENT MODEL
2875 *
2876*/
2877"use strict";
2878
2879var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
2880
2881function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
2882
2883var PaymentNupay = function () {
2884  function PaymentNupay(additionalFields, branch, account, document, paymentMethod, deviceFingerprint, passengers, hasInsurance, hasInsuranceW2i, ip, salePlatform) {
2885    _classCallCheck(this, PaymentNupay);
2886
2887    this._additionalFields = additionalFields;
2888    this._branch = branch;
2889    this._account = account;
2890    this._document = document;
2891    this._paymentMethod = paymentMethod;
2892    this._deviceFingerprint = deviceFingerprint;
2893    this._passengers = passengers;
2894    this._hasInsurance = hasInsurance;
2895    this._hasInsuranceW2i = hasInsuranceW2i;
2896    this._ip = ip;
2897    this._salePlatform = salePlatform;
2898  }
2899
2900  _createClass(PaymentNupay, [{
2901    key: "getSeats",
2902    value: function getSeats(passenger) {
2903      var seats = [];
2904
2905      seats.push({
2906        Service: passenger._seatDeparture._service,
2907        Seat: passenger._seatDeparture._seatNumber
2908      });
2909
2910      if (passenger._seatDepartureConnection._service != null) {
2911        seats.push({
2912          Service: passenger._seatDepartureConnection._service,
2913          Seat: passenger._seatDepartureConnection._seatNumber
2914        });
2915      }
2916
2917      if (passenger._seatDepartureConnection2._service != null) {
2918        seats.push({
2919          Service: passenger._seatDepartureConnection2._service,
2920          Seat: passenger._seatDepartureConnection2._seatNumber
2921        });
2922      }
2923
2924      if (passenger._seatReturn._service != null) {
2925        seats.push({
2926          Service: passenger._seatReturn._service,
2927          Seat: passenger._seatReturn._seatNumber
2928        });
2929      }
2930
2931      if (passenger._seatReturnConnection._service != null) {
2932        seats.push({
2933          Service: passenger._seatReturnConnection._service,
2934          Seat: passenger._seatReturnConnection._seatNumber
2935        });
2936      }
2937
2938      if (passenger._seatReturnConnection2._service != null) {
2939        seats.push({
2940          Service: passenger._seatReturnConnection2._service,
2941          Seat: passenger._seatReturnConnection2._seatNumber
2942        });
2943      }
2944
2945      return seats;
2946    }
2947  }, {
2948    key: "toJSON",
2949    value: function toJSON() {
2950      var json = {
2951        "AdditionalFields": this.additionalFields,
2952        "Branch": this.branch,
2953        "Account": this.account,
2954        "PaymentMethod": this.paymentMethod,
2955        "Document": this.document,
2956        "DeviceFingerPrint": this.deviceFingerprint,
2957        "Passengers": this.passengers,
2958        "ShopperIP": this.ip,
2959        "Insurance": this.hasInsurance,
2960        "W2iInsurance": this.hasInsuranceW2i
2961      };
2962
2963      if (this.salePlatform) {
2964        json["SalePlatform"] = this.salePlatform;
2965      }
2966
2967      return json;
2968    }
2969  }, {
2970    key: "additionalFields",
2971    get: function get() {
2972      return this._additionalFields;
2973    }
2974  }, {
2975    key: "branch",
2976    get: function get() {
2977      return this._branch;
2978    }
2979  }, {
2980    key: "document",
2981    get: function get() {
2982      return this._document;
2983    }
2984  }, {
2985    key: "account",
2986    get: function get() {
2987      return this._account;
2988    }
2989  }, {
2990    key: "paymentMethod",
2991    get: function get() {
2992      return this._paymentMethod;
2993    }
2994  }, {
2995    key: "deviceFingerprint",
2996    get: function get() {
2997      return this._deviceFingerprint;
2998    }
2999  }, {
3000    key: "hasInsurance",
3001    get: function get() {
3002      return this._hasInsurance;
3003    }
3004  }, {
3005    key: "hasInsuranceW2i",
3006    get: function get() {
3007      return this._hasInsuranceW2i;
3008    }
3009  }, {
3010    key: "ip",
3011    get: function get() {
3012      return this._ip;
3013    }
3014  }, {
3015    key: "salePlatform",
3016    get: function get() {
3017      return this._salePlatform;
3018    }
3019  }, {
3020    key: "passengers",
3021    get: function get() {
3022      var _this = this;
3023
3024      var repricingV2 = SessionStorage.get('repricingv2');
3025
3026      return this._passengers.reduce(function (acc, passenger, _, arr) {
3027        var psgr = {
3028          Name: passenger.name,
3029          Document: passenger.documentNumber,
3030          Type: passenger.type,
3031          Seats: _this.getSeats(passenger)
3032        };
3033
3034        if (!repricingV2) {
3035          psgr.birthday = Utils.formatDateToISO(passenger.birthDate);
3036        }
3037
3038        if (passenger.child) {
3039          psgr.child = {
3040            birthday: passenger.child.birthday,
3041            documentType: passenger.child.documentType,
3042            document: passenger.child.document,
3043            name: passenger.child.name
3044          };
3045        }
3046
3047        if (passenger.type !== "CHILD") acc.push(psgr);
3048
3049        return acc;
3050      }, []);
3051    }
3052  }]);
3053
3054  return PaymentNupay;
3055}();
3056"use strict";
3057
3058var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
3059
3060function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
3061
3062var PaymentPixWallet = function () {
3063  function PaymentPixWallet(branch, account, document, paymentMethod, deviceFingerprint, passengers, hasInsurance, ip, salePlatform) {
3064    _classCallCheck(this, PaymentPixWallet);
3065
3066    this._branch = branch;
3067    this._account = account;
3068    this._document = document;
3069    this._paymentMethod = paymentMethod;
3070    this._deviceFingerprint = deviceFingerprint;
3071    this._passengers = passengers;
3072    this._hasInsurance = hasInsurance;
3073    this._ip = ip;
3074    this._salePlatform = salePlatform;
3075  }
3076
3077  _createClass(PaymentPixWallet, [{
3078    key: "getSeats",
3079    value: function getSeats(passenger) {
3080      var seats = [];
3081
3082      if (passenger._seatDeparture && passenger._seatDeparture._seatNumber) {
3083        seats.push({
3084          Service: passenger._seatDeparture._service,
3085          Seat: passenger._seatDeparture._seatNumber
3086        });
3087      }
3088
3089      if (passenger._seatDepartureConnection && passenger._seatDepartureConnection._seatNumber) {
3090        seats.push({
3091          Service: passenger._seatDepartureConnection._service,
3092          Seat: passenger._seatDepartureConnection._seatNumber
3093        });
3094      }
3095
3096      if (passenger._seatDepartureConnection2 && passenger._seatDepartureConnection2._seatNumber) {
3097        seats.push({
3098          Service: passenger._seatDepartureConnection2._service,
3099          Seat: passenger._seatDepartureConnection2._seatNumber
3100        });
3101      }
3102
3103      if (passenger._seatReturn && passenger._seatReturn._seatNumber) {
3104        seats.push({
3105          Service: passenger._seatReturn._service,
3106          Seat: passenger._seatReturn._seatNumber
3107        });
3108      }
3109
3110      if (passenger._seatReturnConnection && passenger._seatReturnConnection._seatNumber) {
3111        seats.push({
3112          Service: passenger._seatReturnConnection._service,
3113          Seat: passenger._seatReturnConnection._seatNumber
3114        });
3115      }
3116
3117      if (passenger._seatReturnConnection2 && passenger._seatReturnConnection2._seatNumber) {
3118        seats.push({
3119          Service: passenger._seatReturnConnection2._service,
3120          Seat: passenger._seatReturnConnection2._seatNumber
3121        });
3122      }
3123
3124      return seats;
3125    }
3126  }, {
3127    key: "toJSON",
3128    value: function toJSON() {
3129      var json = {
3130        "Branch": this.branch,
3131        "Account": this.account,
3132        "PaymentMethod": this.paymentMethod,
3133        "Document": this.document,
3134        "DeviceFingerPrint": this.deviceFingerprint,
3135        "Passengers": this.passengers,
3136        "ShopperIP": this.ip,
3137        "Insurance": this.hasInsurance
3138      };
3139
3140      if (this.salePlatform) {
3141        json["SalePlatform"] = this.salePlatform;
3142      }
3143
3144      return json;
3145    }
3146  }, {
3147    key: "branch",
3148    get: function get() {
3149      return this._branch;
3150    }
3151  }, {
3152    key: "document",
3153    get: function get() {
3154      return this._document;
3155    }
3156  }, {
3157    key: "account",
3158    get: function get() {
3159      return this._account;
3160    }
3161  }, {
3162    key: "paymentMethod",
3163    get: function get() {
3164      return this._paymentMethod;
3165    }
3166  }, {
3167    key: "deviceFingerprint",
3168    get: function get() {
3169      return this._deviceFingerprint;
3170    }
3171  }, {
3172    key: "hasInsurance",
3173    get: function get() {
3174      return this._hasInsurance;
3175    }
3176  }, {
3177    key: "ip",
3178    get: function get() {
3179      return this._ip;
3180    }
3181  }, {
3182    key: "salePlatform",
3183    get: function get() {
3184      return this._salePlatform;
3185    }
3186  }, {
3187    key: "passengers",
3188    get: function get() {
3189      var _this = this;
3190
3191      var repricingV2 = SessionStorage.get('repricingv2');
3192
3193      return this._passengers.reduce(function (acc, passenger) {
3194        var psgr = {
3195          Name: passenger._name,
3196          Document: passenger._documentNumber,
3197          Type: passenger._type,
3198          Seats: _this.getSeats(passenger)
3199        };
3200
3201        if (!repricingV2) {
3202          psgr.birthday = Utils.formatDateToISO(passenger._birthDate);
3203        }
3204
3205        acc.push(psgr);
3206
3207        return acc;
3208      }, []);
3209    }
3210  }]);
3211
3212  return PaymentPixWallet;
3213}();
3214"use strict";
3215
3216var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
3217
3218function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
3219
3220var PaymentLiveloDevice = function () {
3221  function PaymentLiveloDevice(passengers, hasInsuranceW2i, token, type, deviceId) {
3222    _classCallCheck(this, PaymentLiveloDevice);
3223
3224    this._passengers = passengers;
3225    this._token = token;
3226    this._type = type;
3227    this._deviceId = deviceId;
3228  }
3229
3230  _createClass(PaymentLiveloDevice, [{
3231    key: "getSeats",
3232    value: function getSeats(passenger) {
3233      var seats = [];
3234      seats.push({
3235        Service: passenger._seatDeparture._service,
3236        Seat: passenger._seatDeparture._seatNumber
3237      });
3238
3239      if (passenger._seatDepartureConnection._service != null) {
3240        seats.push({
3241          Service: passenger._seatDepartureConnection._service,
3242          Seat: passenger._seatDepartureConnection._seatNumber
3243        });
3244      }
3245
3246      if (passenger._seatDepartureConnection2._service != null) {
3247        seats.push({
3248          Service: passenger._seatDepartureConnection2._service,
3249          Seat: passenger._seatDepartureConnection2._seatNumber
3250        });
3251      }
3252
3253      if (passenger._seatReturn._service != null) {
3254        seats.push({
3255          Service: passenger._seatReturn._service,
3256          Seat: passenger._seatReturn._seatNumber
3257        });
3258      }
3259
3260      if (passenger._seatReturnConnection._service != null) {
3261        seats.push({
3262          Service: passenger._seatReturnConnection._service,
3263          Seat: passenger._seatReturnConnection._seatNumber
3264        });
3265      }
3266
3267      if (passenger._seatReturnConnection2._service != null) {
3268        seats.push({
3269          Service: passenger._seatReturnConnection2._service,
3270          Seat: passenger._seatReturnConnection2._seatNumber
3271        });
3272      }
3273
3274      return seats;
3275    }
3276  }, {
3277    key: "toJSON",
3278    value: function toJSON() {
3279      return {
3280        "Passengers": this.passengers,
3281        "Token": this.token,
3282        "Type": this.type,
3283        "DeviceId": this.deviceId
3284      };
3285    }
3286  }, {
3287    key: "hasInsuranceW2i",
3288    get: function get() {
3289      return this._hasInsuranceW2i;
3290    }
3291  }, {
3292    key: "token",
3293    get: function get() {
3294      return this._token;
3295    }
3296  }, {
3297    key: "type",
3298    get: function get() {
3299      return this._type;
3300    }
3301  }, {
3302    key: "deviceId",
3303    get: function get() {
3304      return this._deviceId;
3305    }
3306  }, {
3307    key: "passengers",
3308    get: function get() {
3309      var _this = this;
3310
3311      return this._passengers.reduce(function (acc, passenger, _, arr) {
3312        var psgr = {
3313          Name: passenger.name,
3314          Document: passenger.documentNumber,
3315          birthday: passenger.birthDate != null ? Utils.formatDateToISO(passenger.birthDate) : "",
3316          Type: passenger.type,
3317          Seats: _this.getSeats(passenger, arr)
3318        };
3319
3320        acc.push(psgr);
3321        return acc;
3322      }, []);
3323    }
3324  }]);
3325
3326  return PaymentLiveloDevice;
3327}();
3328"use strict";
3329
3330var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
3331
3332function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
3333
3334var PaymentPix = function () {
3335  function PaymentPix(branch, account, document, paymentMethod, deviceFingerprint, passengers, hasInsurance, ip, salePlatform) {
3336    _classCallCheck(this, PaymentPix);
3337
3338    this._branch = branch;
3339    this._account = account;
3340    this._document = document;
3341    this._paymentMethod = paymentMethod;
3342    this._deviceFingerprint = deviceFingerprint;
3343    this._passengers = passengers;
3344    this._hasInsurance = hasInsurance;
3345    this._ip = ip;
3346    this._salePlatform = salePlatform;
3347  }
3348
3349  _createClass(PaymentPix, [{
3350    key: "getSeats",
3351    value: function getSeats(passenger) {
3352      var seats = [];
3353
3354      seats.push({
3355        Service: passenger._seatDeparture._service,
3356        Seat: passenger._seatDeparture._seatNumber
3357      });
3358
3359      if (passenger._seatDepartureConnection._service != null) {
3360        seats.push({
3361          Service: passenger._seatDepartureConnection._service,
3362          Seat: passenger._seatDepartureConnection._seatNumber
3363        });
3364      }
3365
3366      if (passenger._seatDepartureConnection2._service != null) {
3367        seats.push({
3368          Service: passenger._seatDepartureConnection2._service,
3369          Seat: passenger._seatDepartureConnection2._seatNumber
3370        });
3371      }
3372
3373      if (passenger._seatReturn._service != null) {
3374        seats.push({
3375          Service: passenger._seatReturn._service,
3376          Seat: passenger._seatReturn._seatNumber
3377        });
3378      }
3379
3380      if (passenger._seatReturnConnection._service != null) {
3381        seats.push({
3382          Service: passenger._seatReturnConnection._service,
3383          Seat: passenger._seatReturnConnection._seatNumber
3384        });
3385      }
3386
3387      if (passenger._seatReturnConnection2._service != null) {
3388        seats.push({
3389          Service: passenger._seatReturnConnection2._service,
3390          Seat: passenger._seatReturnConnection2._seatNumber
3391        });
3392      }
3393
3394      return seats;
3395    }
3396  }, {
3397    key: "toJSON",
3398    value: function toJSON() {
3399      var json = {
3400        "Branch": this.branch,
3401        "Account": this.account,
3402        "PaymentMethod": this.paymentMethod,
3403        "Document": this.document,
3404        "DeviceFingerPrint": this.deviceFingerprint,
3405        "Passengers": this.passengers,
3406        "ShopperIP": this.ip,
3407        "Insurance": this.hasInsurance
3408      };
3409
3410      if (this.salePlatform) {
3411        json["SalePlatform"] = this.salePlatform;
3412      }
3413
3414      return json;
3415    }
3416  }, {
3417    key: "branch",
3418    get: function get() {
3419      return this._branch;
3420    }
3421  }, {
3422    key: "document",
3423    get: function get() {
3424      return this._document;
3425    }
3426  }, {
3427    key: "account",
3428    get: function get() {
3429      return this._account;
3430    }
3431  }, {
3432    key: "paymentMethod",
3433    get: function get() {
3434      return this._paymentMethod;
3435    }
3436  }, {
3437    key: "deviceFingerprint",
3438    get: function get() {
3439      return this._deviceFingerprint;
3440    }
3441  }, {
3442    key: "hasInsurance",
3443    get: function get() {
3444      return this._hasInsurance;
3445    }
3446  }, {
3447    key: "ip",
3448    get: function get() {
3449      return this._ip;
3450    }
3451  }, {
3452    key: "salePlatform",
3453    get: function get() {
3454      return this._salePlatform;
3455    }
3456  }, {
3457    key: "passengers",
3458    get: function get() {
3459      var _this = this;
3460
3461      var repricingV2 = SessionStorage.get('repricingv2');
3462
3463      return this._passengers.reduce(function (acc, passenger, _, arr) {
3464        var psgr = {
3465          Name: passenger.name,
3466          Document: passenger.documentNumber,
3467          Type: passenger.type,
3468          Seats: _this.getSeats(passenger, arr)
3469        };
3470
3471        if (!repricingV2) {
3472          psgr.birthday = Utils.formatDateToISO(passenger.birthDate);
3473        }
3474
3475        if (passenger.child) {
3476          psgr.child = {
3477            birthday: passenger.child.birthday,
3478            documentType: passenger.child.documentType,
3479            document: passenger.child.document,
3480            name: passenger.child.name
3481          };
3482        }
3483
3484        if (passenger.type !== "CHILD") acc.push(psgr);
3485
3486        return acc;
3487      }, []);
3488    }
3489  }]);
3490
3491  return PaymentPix;
3492}();
3493"use strict";
3494
3495var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
3496
3497function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
3498
3499/**
3500 * INICIO
3501 * PAYMENT MODEL
3502 *
3503*/
3504var PaymentToken = function () {
3505  function PaymentToken(securityCode, holderName, recurring, installments, token, deviceFingerprint, passengers, merchantAccountId, hasInsurance, hasInsuranceW2i, ip, salePlatform) {
3506    _classCallCheck(this, PaymentToken);
3507
3508    this._securityCode = securityCode;
3509    this._holderName = holderName;
3510    this._recurring = recurring;
3511    this._installments = installments;
3512    this._token = token;
3513    this._deviceFingerprint = deviceFingerprint;
3514    this._passengers = passengers;
3515    this._merchantAccountId = merchantAccountId;
3516    this._hasInsurance = hasInsurance;
3517    this._ip = ip;
3518    this._salePlatform = salePlatform;
3519  }
3520
3521  _createClass(PaymentToken, [{
3522    key: "getSeats",
3523    value: function getSeats(passenger) {
3524      var seats = [];
3525      seats.push({
3526        Service: passenger._seatDeparture._service,
3527        Seat: passenger._seatDeparture._seatNumber
3528      });
3529
3530      if (passenger._seatDepartureConnection._service != null) {
3531        seats.push({
3532          Service: passenger._seatDepartureConnection._service,
3533          Seat: passenger._seatDepartureConnection._seatNumber
3534        });
3535      }
3536
3537      if (passenger._seatDepartureConnection2._service != null) {
3538        seats.push({
3539          Service: passenger._seatDepartureConnection2._service,
3540          Seat: passenger._seatDepartureConnection2._seatNumber
3541        });
3542      }
3543
3544      if (passenger._seatReturn._service != null) {
3545        seats.push({
3546          Service: passenger._seatReturn._service,
3547          Seat: passenger._seatReturn._seatNumber
3548        });
3549      }
3550
3551      if (passenger._seatReturnConnection._service != null) {
3552        seats.push({
3553          Service: passenger._seatReturnConnection._service,
3554          Seat: passenger._seatReturnConnection._seatNumber
3555        });
3556      }
3557
3558      if (passenger._seatReturnConnection2._service != null) {
3559        seats.push({
3560          Service: passenger._seatReturnConnection2._service,
3561          Seat: passenger._seatReturnConnection2._seatNumber
3562        });
3563      }
3564
3565      return seats;
3566    }
3567  }, {
3568    key: "isPassengersWhatsapp",
3569    value: function isPassengersWhatsapp(array) {
3570      var isValidFormat = array.every(function (obj) {
3571        return typeof obj.name === "string" && typeof obj.document === "string" && typeof obj.type === "string" && typeof obj.birthday === "string" && Array.isArray(obj.seats) && obj.seats.every(function (seat) {
3572          return typeof seat.service === "number" && typeof seat.seat === "string";
3573        });
3574      });
3575
3576      return isValidFormat;
3577    }
3578  }, {
3579    key: "toJSON",
3580    value: function toJSON() {
3581      var json = {
3582        "SecurityCode": this.securityCode,
3583        "HolderName": this.holderName,
3584        "Recurring": this.recurring,
3585        "Insurance": this.hasInsurance,
3586        "DeviceFingerPrint": this.deviceFingerprint,
3587        "Installments": this.installments,
3588        "Token": this.token,
3589        "Passengers": this.passengers,
3590        "MerchantAccountId": this.merchantAccountId,
3591        "ShopperIP": this.ip
3592      };
3593
3594      if (this.salePlatform) {
3595        json["SalePlatform"] = this.salePlatform;
3596      }
3597
3598      return json;
3599    }
3600  }, {
3601    key: "recurring",
3602    get: function get() {
3603      return this._recurring;
3604    }
3605  }, {
3606    key: "token",
3607    get: function get() {
3608      return this._token;
3609    }
3610  }, {
3611    key: "securityCode",
3612    get: function get() {
3613      return this._securityCode;
3614    }
3615  }, {
3616    key: "holderName",
3617    get: function get() {
3618      return this._holderName;
3619    }
3620  }, {
3621    key: "deviceFingerprint",
3622    get: function get() {
3623      return this._deviceFingerprint;
3624    }
3625  }, {
3626    key: "installments",
3627    get: function get() {
3628      return this._installments;
3629    }
3630  }, {
3631    key: "merchantAccountId",
3632    get: function get() {
3633      return this._merchantAccountId;
3634    }
3635  }, {
3636    key: "hasInsurance",
3637    get: function get() {
3638      return this._hasInsurance;
3639    }
3640  }, {
3641    key: "ip",
3642    get: function get() {
3643      return this._ip;
3644    }
3645  }, {
3646    key: "salePlatform",
3647    get: function get() {
3648      return this._salePlatform;
3649    }
3650  }, {
3651    key: "passengers",
3652    get: function get() {
3653      var _this = this;
3654
3655      if (this.isPassengersWhatsapp(this._passengers)) {
3656        var formattedArray = this._passengers.map(function (obj) {
3657          if (typeof obj.birthday === "string") {
3658            obj.birthday = Utils.formatDateToISO(obj.birthday);
3659          }
3660          return obj;
3661        });
3662
3663        return formattedArray;
3664      } else {
3665        return this._passengers.reduce(function (acc, passenger, _, arr) {
3666          var psgr = {
3667            Name: passenger.name,
3668            Document: passenger.documentNumber,
3669            Type: passenger.type,
3670            Seats: _this.getSeats(passenger, arr)
3671          };
3672
3673          if (passenger.child) {
3674            psgr.child = {
3675              birthday: passenger.child.birthday,
3676              documentType: passenger.child.documentType,
3677              document: passenger.child.document,
3678              name: passenger.child.name
3679            };
3680          }
3681
3682          if (passenger.type !== "CHILD") acc.push(psgr);
3683
3684          return acc;
3685        }, []);
3686      }
3687    }
3688  }]);
3689
3690  return PaymentToken;
3691}();
3692
3693/**
3694 * FIM
3695 * PAYMENT MODEL
3696 *
3697*/
3698"use strict";
3699
3700var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
3701
3702function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
3703
3704/**
3705 * INICIO
3706 * PAYMENT MODEL
3707 *
3708*/
3709var PaymentTotalDiscount = function () {
3710  function PaymentTotalDiscount(passengers, ip, salePlatform) {
3711    _classCallCheck(this, PaymentTotalDiscount);
3712
3713    this._passengers = passengers;
3714    this._ip = ip;
3715    this._salePlatform = salePlatform;
3716  }
3717
3718  _createClass(PaymentTotalDiscount, [{
3719    key: "getSeats",
3720    value: function getSeats(passenger, passengersArr) {
3721      var seats = [];
3722
3723      if (passenger.type === "CHILD") {
3724        var child = passengersArr[0];
3725
3726        var departureSeat = { Service: child._seatDeparture._service, Seat: child._seatDeparture._seatNumber };
3727        seats.push(departureSeat);
3728
3729        if (child._seatDepartureConnection._service != null) {
3730          seats.push({
3731            Service: child._seatDepartureConnection._service,
3732            Seat: child._seatDepartureConnection._seatNumber
3733          });
3734        }
3735
3736        if (child._seatDepartureConnection2._service != null) {
3737          seats.push({
3738            Service: child._seatDepartureConnection2._service,
3739            Seat: child._seatDepartureConnection2._seatNumber
3740          });
3741        }
3742
3743        if (child._seatReturn._service != null) {
3744          var returnSeat = { Service: child._seatReturn._service, Seat: child._seatReturn._seatNumber };
3745          seats.push(returnSeat);
3746        }
3747
3748        if (child._seatReturnConnection._service != null) {
3749          seats.push({
3750            Service: child._seatReturnConnection._service,
3751            Seat: child._seatReturnConnection._seatNumber
3752          });
3753        }
3754
3755        if (child._seatReturnConnection2._service != null) {
3756          seats.push({
3757            Service: child._seatReturnConnection2._service,
3758            Seat: child._seatReturnConnection2._seatNumber
3759          });
3760        }
3761      } else {
3762        var _departureSeat = { Service: passenger._seatDeparture._service, Seat: passenger._seatDeparture._seatNumber };
3763        seats.push(_departureSeat);
3764
3765        if (passenger._seatDepartureConnection._service != null) {
3766          seats.push({
3767            Service: passenger._seatDepartureConnection._service,
3768            Seat: passenger._seatDepartureConnection._seatNumber
3769          });
3770        }
3771
3772        if (passenger._seatDepartureConnection2._service != null) {
3773          seats.push({
3774            Service: passenger._seatDepartureConnection2._service,
3775            Seat: passenger._seatDepartureConnection2._seatNumber
3776          });
3777        }
3778
3779        if (passenger._seatReturn._service != null) {
3780          var _returnSeat = { Service: passenger._seatReturn._service, Seat: passenger._seatReturn._seatNumber };
3781          seats.push(_returnSeat);
3782        }
3783
3784        if (passenger._seatReturnConnection._service != null) {
3785          seats.push({
3786            Service: passenger._seatReturnConnection._service,
3787            Seat: passenger._seatReturnConnection._seatNumber
3788          });
3789        }
3790
3791        if (passenger._seatReturnConnection2._service != null) {
3792          seats.push({
3793            Service: passenger._seatReturnConnection2._service,
3794            Seat: passenger._seatReturnConnection2._seatNumber
3795          });
3796        }
3797      }
3798
3799      return seats;
3800    }
3801  }, {
3802    key: "toJSON",
3803    value: function toJSON() {
3804      var json = {
3805        "Passengers": this.passengers,
3806        "ShopperIP": this.ip
3807      };
3808
3809      if (this.salePlatform) {
3810        json["SalePlatform"] = this.salePlatform;
3811      }
3812
3813      return json;
3814    }
3815  }, {
3816    key: "salePlatform",
3817    get: function get() {
3818      return this._salePlatform;
3819    }
3820  }, {
3821    key: "ip",
3822    get: function get() {
3823      return this._ip;
3824    }
3825  }, {
3826    key: "passengers",
3827    get: function get() {
3828      var _this = this;
3829
3830      return this._passengers.reduce(function (acc, passenger, _, arr) {
3831        var psgr = {
3832          Name: passenger.name,
3833          Document: passenger.documentNumber,
3834          birthday: passenger.birthDate != null ? Utils.formatDateToISO(passenger.birthDate) : "",
3835          Type: passenger.type,
3836          Seats: _this.getSeats(passenger, arr)
3837        };
3838
3839        if (passenger.child) {
3840          psgr.child = {
3841            birthday: passenger.child.birthday,
3842            documentType: passenger.child.documentType,
3843            document: passenger.child.document,
3844            name: passenger.child.name
3845          };
3846        }
3847
3848        if (passenger.type !== "CHILD") acc.push(psgr);
3849
3850        return acc;
3851      }, []);
3852    }
3853  }]);
3854
3855  return PaymentTotalDiscount;
3856}();
3857
3858/**
3859 * FIM
3860 * PAYMENT MODEL
3861 *
3862*/
3863"use strict";
3864
3865var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
3866
3867function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
3868
3869/**
3870 * INICIO
3871 * PAYMENT MODEL
3872 *
3873*/
3874var Payment = function () {
3875  function Payment(cardNumber, expiryMont, expiryYear, securityCode, holderName, recurring, installments, deviceFingerprint, passengers, merchantAccountId, hasInsurance, ip, salePlatform) {
3876    _classCallCheck(this, Payment);
3877
3878    this._holderName = holderName;
3879    this._recurring = recurring;
3880    this._cardNumber = cardNumber;
3881    this._expiryMont = expiryMont;
3882    this._expiryYear = expiryYear;
3883    this._securityCode = securityCode;
3884    this._deviceFingerprint = deviceFingerprint;
3885    this._installments = installments;
3886    this._passengers = passengers;
3887    this._merchantAccountId = merchantAccountId;
3888    this._hasInsurance = hasInsurance;
3889    this.repricingV2 = SessionStorage.get('repricingv2');
3890    this._ip = ip;
3891    this._salePlatform = salePlatform;
3892  }
3893
3894  _createClass(Payment, [{
3895    key: 'getSeats',
3896    value: function getSeats(passenger) {
3897      var seats = [];
3898      seats.push({
3899        Service: passenger._seatDeparture._service,
3900        Seat: passenger._seatDeparture._seatNumber
3901      });
3902
3903      if (passenger._seatDepartureConnection._service != null) {
3904        seats.push({
3905          Service: passenger._seatDepartureConnection._service,
3906          Seat: passenger._seatDepartureConnection._seatNumber
3907        });
3908      }
3909
3910      if (passenger._seatDepartureConnection2._service != null) {
3911        seats.push({
3912          Service: passenger._seatDepartureConnection2._service,
3913          Seat: passenger._seatDepartureConnection2._seatNumber
3914        });
3915      }
3916
3917      if (passenger._seatReturn._service != null) {
3918        seats.push({
3919          Service: passenger._seatReturn._service,
3920          Seat: passenger._seatReturn._seatNumber
3921        });
3922      }
3923
3924      if (passenger._seatReturnConnection._service != null) {
3925        seats.push({
3926          Service: passenger._seatReturnConnection._service,
3927          Seat: passenger._seatReturnConnection._seatNumber
3928        });
3929      }
3930
3931      if (passenger._seatReturnConnection2._service != null) {
3932        seats.push({
3933          Service: passenger._seatReturnConnection2._service,
3934          Seat: passenger._seatReturnConnection2._seatNumber
3935        });
3936      }
3937
3938      return seats;
3939    }
3940  }, {
3941    key: 'isPassengersWhatsapp',
3942    value: function isPassengersWhatsapp(array) {
3943      var isValidFormat = array.every(function (obj) {
3944        return typeof obj.name === "string" && typeof obj.document === "string" && typeof obj.type === "string" && typeof obj.birthday === "string" && Array.isArray(obj.seats) && obj.seats.every(function (seat) {
3945          return typeof seat.service === "number" && typeof seat.seat === "string";
3946        });
3947      });
3948
3949      return isValidFormat;
3950    }
3951  }, {
3952    key: 'toJSON',
3953    value: function toJSON() {
3954      var json = {
3955        "CardNumber": this.cardNumber,
3956        "ExpiryMont": this.expiryMont,
3957        "ExpiryYear": this.expiryYear,
3958        "SecurityCode": this.securityCode,
3959        "HolderName": this.holderName,
3960        "Recurring": this.recurring,
3961        "Insurance": this.hasInsurance,
3962        "DeviceFingerPrint": this.deviceFingerprint,
3963        "Installments": this.installments,
3964        "Passengers": this.passengers,
3965        "MerchantAccountId": this.merchantAccountId,
3966        "ShopperIP": this.ip
3967      };
3968
3969      if (this.salePlatform) {
3970        json["SalePlatform"] = this.salePlatform;
3971      }
3972
3973      return json;
3974    }
3975  }, {
3976    key: 'recurring',
3977    get: function get() {
3978      return this._recurring;
3979    }
3980  }, {
3981    key: 'cardNumber',
3982    get: function get() {
3983      return this._cardNumber;
3984    }
3985  }, {
3986    key: 'expiryMont',
3987    get: function get() {
3988      return this._expiryMont;
3989    }
3990  }, {
3991    key: 'expiryYear',
3992    get: function get() {
3993      return this._expiryYear;
3994    }
3995  }, {
3996    key: 'securityCode',
3997    get: function get() {
3998      return this._securityCode;
3999    }
4000  }, {
4001    key: 'holderName',
4002    get: function get() {
4003      return this._holderName;
4004    }
4005  }, {
4006    key: 'deviceFingerprint',
4007    get: function get() {
4008      return this._deviceFingerprint;
4009    }
4010  }, {
4011    key: 'installments',
4012    get: function get() {
4013      return this._installments;
4014    }
4015  }, {
4016    key: 'merchantAccountId',
4017    get: function get() {
4018      return this._merchantAccountId;
4019    }
4020  }, {
4021    key: 'hasInsurance',
4022    get: function get() {
4023      return this._hasInsurance;
4024    }
4025  }, {
4026    key: 'ip',
4027    get: function get() {
4028      return this._ip;
4029    }
4030  }, {
4031    key: 'salePlatform',
4032    get: function get() {
4033      return this._salePlatform;
4034    }
4035  }, {
4036    key: 'passengers',
4037    get: function get() {
4038      var _this = this;
4039
4040      var passengersToRepricing = SessionStorage.get('passengersToRepricing');
4041
4042      if (this.isPassengersWhatsapp(this._passengers)) {
4043        var formattedArray = this._passengers.map(function (obj) {
4044          if (typeof obj.birthday === "string") {
4045            obj.birthday = Utils.formatDateToISO(obj.birthday);
4046          }
4047          return obj;
4048        });
4049
4050        return formattedArray;
4051      } else if (this.repricingV2) {
4052        var childIndex = 0;
4053
4054        return this._passengers.reduce(function (acc, passenger, index, arr) {
4055          var passengerTo = passengersToRepricing.passengers[index];
4056          var children = passengersToRepricing.passengers.filter(function (passenger) {
4057            return passenger.type === "CHILD";
4058          });
4059
4060          var psgr = {
4061            Name: passenger.name,
4062            birthday: passengerTo.birthday,
4063            Document: passengerTo.document,
4064            Type: passengerTo.type,
4065            Seats: _this.getSeats(passenger, arr)
4066          };
4067
4068          if (passenger.type === "ADULT" && childIndex < children.length) {
4069            var childPassenger = children[childIndex];
4070            psgr.child = {
4071              birthday: childPassenger.birthday,
4072              document: childPassenger.document,
4073              name: childPassenger.name
4074            };
4075          }
4076
4077          if (passenger.type !== "CHILD") acc.push(psgr);
4078
4079          return acc;
4080        }, []);
4081      } else {
4082        return this._passengers.reduce(function (acc, passenger, _, arr) {
4083          var psgr = {
4084            Name: passenger.name,
4085            birthday: passenger.birthDate != null ? Utils.formatDateToISO(passenger.birthDate) : "",
4086            Document: passenger.documentNumber,
4087            Type: passenger.type,
4088            Seats: _this.getSeats(passenger, arr)
4089          };
4090
4091          if (passenger.child) {
4092            psgr.child = {
4093              birthday: passenger.child.birthday,
4094              documentType: passenger.child.documentType,
4095              document: passenger.child.document,
4096              name: passenger.child.name
4097            };
4098          }
4099
4100          if (passenger.type !== "CHILD") acc.push(psgr);
4101
4102          return acc;
4103        }, []);
4104      }
4105    }
4106  }]);
4107
4108  return Payment;
4109}();
4110
4111/**
4112 * FIM
4113 * PAYMENT MODEL
4114 *
4115*/
4116"use strict";
4117
4118var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
4119
4120function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
4121
4122var Seat = function () {
4123  function Seat(seatNumber) {
4124    _classCallCheck(this, Seat);
4125
4126    this._seatNumber = seatNumber;
4127    this._price = 0;
4128    this._rate = 0;
4129    this._tax = 0;
4130    this._other = 0;
4131    this._insurance = 0;
4132    this._toll = 0;
4133    this._priceWithDiscount = 0;
4134    this._convenienceFee = 0;
4135    this._vouchValue = null;
4136    this._transactionId = null;
4137    this._service = null;
4138    this._boardingFee = 0;
4139    this._balanceAmount = 0;
4140    this._actualAmount = 0;
4141    this._newTicketAmount = 0;
4142    this._penaltyAmount = 0;
4143    this._token = null;
4144    this._commission = 0;
4145    this._subTotalPix = 0;
4146  }
4147
4148
4149  _createClass(Seat, [{
4150    key: "toJSON",
4151    value: function toJSON() {
4152      return {
4153        _seatNumber: this._seatNumber,
4154        _transactionId: this._transactionId,
4155        _price: this._price,
4156        _rate: this._rate,
4157        _tax: this._tax,
4158        _priceWithDiscount: this._priceWithDiscount,
4159        _convenienceFee: this._convenienceFee,
4160        _other: this._other,
4161        _insurance: this._insurance,
4162        _vouchValue: this._vouchValue,
4163        _toll: this._toll,
4164        _service: this._service,
4165        _boardingFee: this._boardingFee,
4166        _balanceAmount: this._balanceAmount,
4167        _actualAmount: this._actualAmount,
4168        _newTicketAmount: this._newTicketAmount,
4169        _penaltyAmount: this._penaltyAmount,
4170        _token: this._token,
4171        _commission: this._commission,
4172        _subTotalPix: this._subTotalPix
4173      };
4174    }
4175  }, {
4176    key: "fromJSON",
4177    value: function fromJSON(seatJSON) {
4178      this._seatNumber = seatJSON._seatNumber;
4179      this._transactionId = seatJSON._transactionId;
4180      this._price = seatJSON._price;
4181      this._rate = seatJSON._rate;
4182      this._tax = seatJSON._tax;
4183      this._priceWithDiscount = seatJSON._priceWithDiscount;
4184      this._convenienceFee = seatJSON._convenienceFee;
4185      this._other = seatJSON._other;
4186      this._insurance = seatJSON._insurance;
4187      this._vouchValue = seatJSON._vouchValue;
4188      this._toll = seatJSON._toll;
4189      this._service = seatJSON._service;
4190      this._boardingFee = seatJSON._boardingFee;
4191      this._balanceAmount = seatJSON._balanceAmount;
4192      this._actualAmount = seatJSON._actualAmount;
4193      this._newTicketAmount = seatJSON._newTicketAmount;
4194      this._penaltyAmount = seatJSON._penaltyAmount;
4195      this._token = seatJSON._token;
4196      this._subTotalPix = seatJSON._subTotalPix;
4197    }
4198  }, {
4199    key: "seatNumber",
4200    get: function get() {
4201      return this._seatNumber;
4202    },
4203    set: function set(seatNumber) {
4204      this._seatNumber = seatNumber;
4205    }
4206  }, {
4207    key: "transactionId",
4208    get: function get() {
4209      return this._transactionId;
4210    },
4211    set: function set(transactionId) {
4212      this._transactionId = transactionId;
4213    }
4214  }, {
4215    key: "price",
4216    get: function get() {
4217      return this._price;
4218    },
4219    set: function set(price) {
4220      this._price = price;
4221    }
4222  }, {
4223    key: "rate",
4224    get: function get() {
4225      return this._rate;
4226    },
4227    set: function set(rate) {
4228      this._rate = rate;
4229    }
4230  }, {
4231    key: "tax",
4232    get: function get() {
4233      return this._tax;
4234    },
4235    set: function set(tax) {
4236      this._tax = tax;
4237    }
4238  }, {
4239    key: "other",
4240    get: function get() {
4241      return this._other;
4242    },
4243    set: function set(other) {
4244      this._other = other;
4245    }
4246  }, {
4247    key: "insurance",
4248    get: function get() {
4249      return this._insurance;
4250    },
4251    set: function set(insurance) {
4252      this._insurance = insurance;
4253    }
4254  }, {
4255    key: "toll",
4256    get: function get() {
4257      return this._toll;
4258    },
4259    set: function set(toll) {
4260      this._toll = toll;
4261    }
4262  }, {
4263    key: "service",
4264    get: function get() {
4265      return this._service;
4266    },
4267    set: function set(service) {
4268      this._service = service;
4269    }
4270  }, {
4271    key: "priceWithDiscount",
4272    get: function get() {
4273      return this._priceWithDiscount;
4274    },
4275    set: function set(priceWithDiscount) {
4276      this._priceWithDiscount = priceWithDiscount;
4277    }
4278  }, {
4279    key: "convenienceFee",
4280    get: function get() {
4281      return this._convenienceFee;
4282    },
4283    set: function set(convenienceFee) {
4284      this._convenienceFee = convenienceFee;
4285    }
4286  }, {
4287    key: "vouchValue",
4288    get: function get() {
4289      return this._vouchValue;
4290    },
4291    set: function set(_vouchValue) {
4292      this._vouchValue = vouchValue;
4293    }
4294  }, {
4295    key: "boardingFee",
4296    get: function get() {
4297      return this._boardingFee;
4298    },
4299    set: function set(boardingFee) {
4300      this._boardingFee = boardingFee;
4301    }
4302  }, {
4303    key: "balanceAmount",
4304    get: function get() {
4305      return this._balanceAmount;
4306    },
4307    set: function set(balanceAmount) {
4308      this._balanceAmount = balanceAmount;
4309    }
4310  }, {
4311    key: "actualAmount",
4312    get: function get() {
4313      return this._actualAmount;
4314    },
4315    set: function set(actualAmount) {
4316      this._actualAmount = actualAmount;
4317    }
4318  }, {
4319    key: "newTicketAmount",
4320    get: function get() {
4321      return this._newTicketAmount;
4322    },
4323    set: function set(newTicketAmount) {
4324      this._newTicketAmount = newTicketAmount;
4325    }
4326  }, {
4327    key: "penaltyAmount",
4328    get: function get() {
4329      return this._penaltyAmount;
4330    },
4331    set: function set(penaltyAmount) {
4332      this._penaltyAmount = penaltyAmount;
4333    }
4334  }, {
4335    key: "token",
4336    get: function get() {
4337      return this._token;
4338    },
4339    set: function set(token) {
4340      this._token = token;
4341    }
4342  }, {
4343    key: "commission",
4344    get: function get() {
4345      return this._commission;
4346    },
4347    set: function set(commission) {
4348      this._commission = commission;
4349    }
4350  }, {
4351    key: "subTotalPix",
4352    get: function get() {
4353      return this._subTotalPix;
4354    },
4355    set: function set(subTotalPix) {
4356      this.subTotalPix = subTotalPix;
4357    }
4358  }]);
4359
4360  return Seat;
4361}();
4362"use strict";
4363
4364function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
4365
4366var Timer = function Timer(remainingTime, middleTime) {
4367  _classCallCheck(this, Timer);
4368
4369  this._remainingTime = remainingTime;
4370  this._middleTime = middleTime;
4371};
4372"use strict";
4373
4374var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
4375
4376function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
4377
4378var Trip = function () {
4379  function Trip(service, going, originId, originLabel, destinationId, destinationLabel, arrivingDate, departureDate, hourDestination, hourArrival, title, token) {
4380    var connLocationId = arguments.length > 12 && arguments[12] !== undefined ? arguments[12] : null;
4381    var connService = arguments.length > 13 && arguments[13] !== undefined ? arguments[13] : null;
4382    var connSequence = arguments.length > 14 && arguments[14] !== undefined ? arguments[14] : null;
4383
4384    _classCallCheck(this, Trip);
4385
4386    this._service = service;
4387    this._going = going;
4388    this._originId = originId;
4389    this._originLabel = originLabel;
4390    this._destinationId = destinationId;
4391    this._destinationLabel = destinationLabel;
4392    this._arrivingDate = arrivingDate;
4393    this._departureDate = departureDate;
4394    this._title = title;
4395    this._token = token;
4396    this._connLocationId = connLocationId;
4397    this._connService = connService;
4398    this._connSequence = connSequence;
4399    this._hourDestination = hourDestination;
4400    this._hourArrival = hourArrival;
4401  }
4402
4403  _createClass(Trip, [{
4404    key: "service",
4405    get: function get() {
4406      return this._service;
4407    }
4408  }, {
4409    key: "originId",
4410    get: function get() {
4411      return this._originId;
4412    }
4413  }, {
4414    key: "destinationId",
4415    get: function get() {
4416      return this._destinationId;
4417    }
4418  }, {
4419    key: "originLabel",
4420    get: function get() {
4421      return this._originLabel;
4422    },
4423    set: function set(originLabel) {
4424      this._originLabel = originLabel;
4425    }
4426  }, {
4427    key: "destinationLabel",
4428    get: function get() {
4429      return this._destinationLabel;
4430    },
4431    set: function set(destinationLabel) {
4432      this._destinationLabel = destinationLabel;
4433    }
4434  }, {
4435    key: "arrivingDate",
4436    get: function get() {
4437      return this._arrivingDate;
4438    }
4439  }, {
4440    key: "departureDate",
4441    get: function get() {
4442      return this._departureDate;
4443    }
4444  }, {
4445    key: "going",
4446    get: function get() {
4447      return this._going;
4448    }
4449  }, {
4450    key: "title",
4451    get: function get() {
4452      return this._title;
4453    }
4454  }, {
4455    key: "token",
4456    get: function get() {
4457      return this._token;
4458    }
4459  }, {
4460    key: "connLocationId",
4461    get: function get() {
4462      return this._connLocationId;
4463    },
4464    set: function set(connLocationId) {
4465      this._connLocationId = connLocationId;
4466    }
4467  }, {
4468    key: "connService",
4469    get: function get() {
4470      return this._connService;
4471    },
4472    set: function set(connService) {
4473      this._connService = connService;
4474    }
4475  }, {
4476    key: "connSequence",
4477    get: function get() {
4478      return this._connSequence;
4479    },
4480    set: function set(connSequence) {
4481      this._connSequence = connSequence;
4482    }
4483  }, {
4484    key: "hourDestination",
4485    get: function get() {
4486      return this._hourDestination;
4487    },
4488    set: function set(hourDestination) {
4489      this._hourDestination = hourDestination;
4490    }
4491  }, {
4492    key: "hourArrival",
4493    get: function get() {
4494      return this._hourArrival;
4495    },
4496    set: function set(hourArrival) {
4497      this._hourArrival = hourArrival;
4498    }
4499  }]);
4500
4501  return Trip;
4502}();
4503"use strict";
4504
4505/**
4506 * Analytics Config
4507 * (Global Scope)
4508 *
4509 */
4510var send2Analytics = function send2Analytics(msg) {
4511  data_layer.page.pageInfo.error.msg = msg;
4512  document.dispatchEvent(new Event('genericError'));
4513};
4514"use strict";
4515
4516var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
4517
4518function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
4519
4520var AccssesTokenService = function () {
4521  function AccssesTokenService() {
4522    _classCallCheck(this, AccssesTokenService);
4523    this._clientId = $("#clientId").val();
4524  }
4525
4526  _createClass(AccssesTokenService, [{
4527    key: "getAccssesToken",
4528    value: function getAccssesToken() {
4529      var _this = this;
4530
4531      if ($('#wcmmodeedit').val() != 'true' && $('#baseUrl').val() != undefined) {
4532        if (!this.isTokenValid() ||
4533            ($('#siteName').val() != 'cometa' && $('#siteName').val() != 'rapidoribeirao' &&
4534            $('#siteName').val() != 'catarinense' && $('#siteName').val() != 'expressodosul' &&
4535            $('#siteName').val() != '1001')) {
4536          sessionStorage.removeItem('access_token');
4537          sessionStorage.removeItem('expires_in');
4538          sessionStorage.removeItem('TokenTimeInitial');
4539
4540          var body = { grant_type: "client_credentials" };
4541          var headers = {
4542            Authorization: sessionStorage.getItem('authorizationId'),
4543            "x-site-company-id": Utils.getCompanyId()
4544          };
4545
4546          return new Promise(function (resolve, reject) {
4547            $.ajax({
4548              url: $('#baseUrl').val() + targetConfig.EXT.endpoints.accessToken,
4549              dataType: 'json',
4550              contentType: "application/json",
4551              type: 'POST',
4552              headers: headers,
4553              data: JSON.stringify(body),
4554              async: false,
4555              statusCode: statusThrown
4556            }).success(function (data) {
4557              sessionStorage.setItem('access_token', data.access_token);
4558              sessionStorage.setItem('expires_in', data.expires_in);
4559              sessionStorage.setItem('TokenTimeInitial', _this.setTimeTokenLimit($("#authenticationTime").val() ? $("#authenticationTime").val() : Utils.convertSecundsToMinuts(data.expires_in)));
4560              resolve();
4561            }).catch(function (error) {
4562              console.error('Error:', error);
4563              reject(error);
4564            });
4565          });
4566        }
4567      }
4568    }
4569  }, {
4570    key: "verifyToken",
4571    value: function verifyToken() {
4572      if ($('#wcmmodeedit').val() != 'true' && $('#baseUrl').val() != undefined) {
4573        if (!this.isTokenValid() ||
4574          ($('#siteName').val() != 'cometa' && $('#siteName').val() != 'rapidoribeirao' &&
4575            $('#siteName').val() != 'catarinense' && $('#siteName').val() != 'expressodosul' &&
4576            $('#siteName').val() != '1001')) {
4577
4578          return false;
4579        } else {
4580          return true;
4581        }
4582      }
4583    }
4584  }, {
4585    key: "authorization",
4586    value: function authorization() {
4587      var _this1 = this;
4588      var url = $('#rootPath').val() + '/jcr:content.authorization.json?clear=1';
4589
4590      return new Promise(function (resolve, reject) {
4591        $.ajax({
4592          url: url,
4593          dataType: 'json',
4594          async: false,
4595          method: 'GET'
4596        }).success(function (data) {
4597          sessionStorage.setItem('authorizationId', data.result.authorizationId);
4598          resolve();
4599        }).catch(function (error) {
4600          console.error('Error:', error);
4601          reject(error);
4602        });
4603      });
4604    }
4605  }, {
4606    key: "isTokenValid",
4607    value: function isTokenValid() {
4608      if (sessionStorage.getItem('access_token')) {
4609
4610        var tokenTimeInitial = new Date(sessionStorage.getItem('TokenTimeInitial'));
4611        if (tokenTimeInitial >= new Date()) return true; else return false;
4612      } else return false;
4613    }
4614  }, {
4615    key: "setTimeTokenLimit",
4616    value: function setTimeTokenLimit(expires_in) {
4617      var hourInitial = new Date();
4618      return new Date(hourInitial.getTime() + expires_in / 60 * 60 * 60 * 1000);
4619    }
4620  }]);
4621
4622  return AccssesTokenService;
4623}();
4624"use strict";
4625
4626var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
4627
4628function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
4629
4630var AccssesTokenServiceGiro = function () {
4631  function AccssesTokenServiceGiro() {
4632    _classCallCheck(this, AccssesTokenServiceGiro);
4633    this._clientId = $("#clientIdGiro").val();
4634  }
4635
4636  _createClass(AccssesTokenServiceGiro, [{
4637    key: "getAccssesToken",
4638    value: function AccssesTokenServiceGiro() {
4639      var _this = this;
4640
4641      if ($('#wcmmodeedit').val() != 'true' && $('#baseUrl').val() != undefined) {
4642        if (!this.isTokenValid() ||
4643          ($('#siteName').val() != 'cometa' && $('#siteName').val() != 'rapidoribeirao' &&
4644            $('#siteName').val() != 'catarinense' && $('#siteName').val() != 'expressodosul' &&
4645            $('#siteName').val() != '1001')) {
4646          sessionStorage.removeItem('access_token_giro');
4647          sessionStorage.removeItem('expires_in_giro');
4648          sessionStorage.removeItem('TokenTimeInitialGiro');
4649
4650          var body = { grant_type: "client_credentials" };
4651          var headers = { Authorization: sessionStorage.getItem('authorizationIdGiro') };
4652
4653          return new Promise(function (resolve, reject) {
4654            $.ajax({
4655              url: $('#baseGiroUrl').val() + targetConfig.EXT.endpoints.accessToken,
4656              dataType: 'json',
4657              contentType: "application/json",
4658              type: 'POST',
4659              headers: headers,
4660              data: JSON.stringify(body),
4661              async: false,
4662              statusCode: statusThrown
4663            }).success(function (data) {
4664              sessionStorage.setItem('access_token_giro', data.access_token);
4665              sessionStorage.setItem('expires_in_giro', data.expires_in);
4666              sessionStorage.setItem('TokenTimeInitialGiro', _this.setTimeTokenLimit($("#authenticationTime").val() ? $("#authenticationTime").val() : Utils.convertSecundsToMinuts(data.expires_in)));
4667              resolve();
4668            }).catch(function (error) {
4669              console.error('Error:', error);
4670              reject(error);
4671            });
4672          });
4673        }
4674      }
4675    }
4676  }, {
4677    key: "verifyToken",
4678    value: function verifyToken() {
4679      if ($('#wcmmodeedit').val() != 'true' && $('#baseUrl').val() != undefined) {
4680        if (!this.isTokenValid() ||
4681          ($('#siteName').val() != 'cometa' && $('#siteName').val() != 'rapidoribeirao' &&
4682            $('#siteName').val() != 'catarinense' && $('#siteName').val() != 'expressodosul' &&
4683            $('#siteName').val() != '1001')) {
4684
4685          return false;
4686        } else {
4687          return true;
4688        }
4689      }
4690    }
4691  }, {
4692    key: "authorization",
4693    value: function authorization() {
4694      var _this1 = this;
4695      var url = $('#rootPath').val() + '/jcr:content.authorization.json?giro=1&clear=1';
4696
4697      return new Promise(function (resolve, reject) {
4698        $.ajax({
4699          url: url,
4700          dataType: 'json',
4701          async: false,
4702          method: 'GET'
4703        }).success(function (data) {
4704          sessionStorage.setItem('authorizationIdGiro', data.result.authorizationId);
4705          resolve();
4706        }).catch(function (error) {
4707          console.error('Error:', error);
4708          reject(error);
4709        });
4710      });
4711    }
4712  }, {
4713    key: "isTokenValid",
4714    value: function isTokenValid() {
4715      if (sessionStorage.getItem('access_token_giro')) {
4716
4717        var tokenTimeInitial = new Date(sessionStorage.getItem('TokenTimeInitialGiro'));
4718        if (tokenTimeInitial >= new Date()) return true; else return false;
4719      } else return false;
4720    }
4721  }, {
4722    key: "setTimeTokenLimit",
4723    value: function setTimeTokenLimit(expires_in) {
4724      var hourInitial = new Date();
4725      return new Date(hourInitial.getTime() + expires_in / 60 * 60 * 60 * 1000);
4726    }
4727  }]);
4728
4729  return AccssesTokenServiceGiro;
4730}();
4731"use strict";
4732
4733var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
4734
4735function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
4736
4737var APIUtils = function () {
4738  function APIUtils() {
4739    _classCallCheck(this, APIUtils);
4740  }
4741
4742  _createClass(APIUtils, null, [{
4743    key: 'getAvailableTrips',
4744    value: function getAvailableTrips(origin, destination, departureDate) {
4745      var isRemoveConnection = $('[data-js="remove-connection"]').val() == 'true';
4746      var saleplatform = SessionStorage.get('utm_saleplatform');
4747
4748      var removeConnections = function removeConnections(data) {
4749        try {
4750          var servicesListFiltered = data.result.servicesList.filter(function (service) {
4751            return service.connection == null;
4752          });
4753          data.result.servicesList = servicesListFiltered;
4754
4755          if (!servicesListFiltered.length) {
4756            throw Exception();
4757          }
4758
4759          return data;
4760        } catch (err) {
4761          return false;
4762        }
4763      };
4764
4765      return new Promise(function (resolve, reject) {
4766        var headers = { version: 2 };
4767        var body = { origin: origin, destination: destination, departureDate: departureDate, availability: true };
4768
4769        var saleplatform = SessionStorage.get('utm_saleplatform');
4770        saleplatform ? body.SalePlatform = this.saleplatform : body.SalePlatform = "SITES-UTP";
4771
4772        LoaderService.show();
4773        HttpService.post('getRoutes', body, headers).done(function (data) {
4774          if (isRemoveConnection) {
4775            resolve(removeConnections(data));
4776          } else {
4777            resolve(data);
4778          }
4779        }).fail(function (error) {
4780          // Analytics - Triggers an event when there is an error on service.
4781          var originLabel = $('#input-departure').val().toUpperCase();
4782          var destinationLabel = $('#input-destination').val().toUpperCase();
4783          if (typeof _satellite != "undefined") {
4784            _satellite.track('serviceError', {
4785              service: 'getAvailableTrips',
4786              serviceType: 'getRoutes',
4787              statusCode: error.status,
4788              customMessageError: { origin: originLabel, destination: destinationLabel, date: departureDate },
4789              messageError: error.responseJSON.result
4790            });
4791          }
4792          return reject(error);
4793        }).always(function () {
4794          return LoaderService.hide();
4795        });
4796      });
4797    }
4798  }, {
4799    key: 'getAvailableTripsRepricing',
4800    value: function getAvailableTripsRepricing(origin, destination, departureDate, companyId) {
4801      var isRemoveConnection = $('[data-js="remove-connection"]').val() == 'true';
4802
4803      var removeConnections = function removeConnections(data) {
4804        try {
4805          var servicesListFiltered = data.result.servicesList.filter(function (service) {
4806            return service.connection == null;
4807          });
4808          data.result.servicesList = servicesListFiltered;
4809
4810          if (!servicesListFiltered.length) {
4811            throw Exception();
4812          }
4813
4814          return data;
4815        } catch (err) {
4816          return false;
4817        }
4818      };
4819
4820      return new Promise(function (resolve, reject) {
4821        var headers = {
4822          'Authorization': '' + SessionStorage.get('jca_token')
4823        };
4824
4825        var body = { origin: origin, destination: destination, departureDate: departureDate, companyId: companyId };
4826
4827        LoaderService.show();
4828        HttpService.post('returnAvailability', body, headers).done(function (data) {
4829          if (isRemoveConnection) resolve(removeConnections(data)); else resolve(data);
4830        }).fail(function (err) {
4831          return reject(err);
4832        }).always(function () {
4833          return LoaderService.hide();
4834        });
4835      });
4836    }
4837  }]);
4838
4839  return APIUtils;
4840}();
4841'use strict';
4842
4843var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
4844
4845function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
4846
4847var CartService = function () {
4848  function CartService(cartObject, cartComponent) {
4849    _classCallCheck(this, CartService);
4850
4851    this.formData = SessionStorage.get('formData');
4852    this._cart = new Cart();
4853    this._cartComponent = cartComponent;
4854
4855    if (cartObject) this._cart.fromJSON(cartObject);
4856
4857    if (this._cart.listOffer.length === 0) this._cartComponent.hideCart(); else this._cartComponent.showCart();
4858  }
4859
4860  _createClass(CartService, [{
4861    key: 'updateStorageByObject',
4862    value: function updateStorageByObject(cartObject) {
4863      SessionStorage.set('cart', cartObject);
4864    }
4865  }, {
4866    key: 'addDepartOffer',
4867    value: function addDepartOffer(offer) {
4868      if (this._cart.listOffer.length === 0) {
4869        this._cartComponent.showCart();
4870      }
4871      this._cart.addDepartOffer(offer);
4872    }
4873  }, {
4874    key: 'addReturnOffer',
4875    value: function addReturnOffer(offer) {
4876      if (this._cart.listOffer.length === 0) {
4877        this._cartComponent.showCart();
4878      }
4879      this._cart.addReturnOffer(offer);
4880    }
4881  }, {
4882    key: 'removeOffer',
4883    value: function removeOffer(offer) {
4884      this._cart.removeOffer(offer);
4885      if (this._cart.listOffer.length === 0) this.cartComponent.hideCart();
4886    }
4887  }, {
4888    key: 'setAmountPassengers',
4889    value: function setAmountPassengers(amount) {
4890      for (var i = 0; i < amount; i++) {
4891        this._cart.addPassenger(new Passenger());
4892      }
4893    }
4894  }, {
4895    key: 'updateStorage',
4896    value: function updateStorage() {
4897      SessionStorage.set('cart', this._cart);
4898    }
4899  }, {
4900    key: 'totalByPassenger',
4901    value: function totalByPassenger() {
4902      return this._cart.totalByPassenger;
4903    }
4904  }, {
4905    key: 'clearPassengers',
4906    value: function clearPassengers() {
4907      this._cart.listPassengers.splice(0, this._cart.totalPassengers);
4908    }
4909  }, {
4910    key: 'clearOffers',
4911    value: function clearOffers() {
4912      this._cart.listOffer.splice(0, this._cart.listOffer.length);
4913    }
4914  }, {
4915    key: 'addPassengers',
4916    value: function addPassengers(passengers) {
4917      var _this = this;
4918
4919      if (typeof passengers === 'number') {
4920        var amount = passengers;
4921        this._cart.addPassengers(amount);
4922      }
4923
4924      if (passengers instanceof Array) {
4925        passengers.forEach(function (el) {
4926          if (el.quantity == null) {
4927            var passenger = new Passenger();
4928            passenger.name = el.name;
4929            passenger.documentNumber = el.doc;
4930            passenger.birthDate = el.birthDate;
4931            passenger.cpf = el.cpf;
4932            passenger.hasDiscount = el.hasDiscount;
4933            passenger.child = el.child ? new Child(el.child) : null;
4934            passenger.type = el.type;
4935            passenger.specialService = el.specialService;
4936            _this._cart.addPassenger(passenger);
4937          } else {
4938            for (var i = 0; i < el.quantity; i++) {
4939              var _passenger = new Passenger();
4940              _passenger.name = el.name;
4941              _passenger.documentNumber = el.doc;
4942              _passenger.cpf = el.cpf;
4943              _passenger.hasDiscount = el.hasDiscount;
4944              _passenger.type = el.type;
4945              _passenger.specialService = el.specialService;
4946              _this._cart.addPassenger(_passenger);
4947            }
4948          }
4949        });
4950      }
4951    }
4952  }, {
4953    key: 'getTotal',
4954    value: function getTotal(isConvenienceFee) {
4955      return this._cart.getTotal(isConvenienceFee);
4956    }
4957  }, {
4958    key: 'amountOffers',
4959    get: function get() {
4960      return this._cart.listOffer.length * this._cart.listPassengers.length;
4961    }
4962  }, {
4963    key: 'departureOffer',
4964    get: function get() {
4965      return this._cart.listOffer[0];
4966    }
4967  }, {
4968    key: 'returnOffer',
4969    get: function get() {
4970      return this._cart.listOffer[1];
4971    }
4972  }, {
4973    key: 'minHourDep',
4974    get: function get() {
4975      return this._minHourDep;
4976    },
4977    set: function set(minHourDep) {
4978      this._minHourDep = minHourDep;
4979    }
4980  }, {
4981    key: 'minHourBack',
4982    get: function get() {
4983      return this._minHourBack;
4984    },
4985    set: function set(minHourBack) {
4986      this._minHourBack = minHourBack;
4987    }
4988  }, {
4989    key: 'total',
4990    get: function get() {
4991      return this._cart.total;
4992    }
4993  }, {
4994    key: 'totalConvenienceFee',
4995    get: function get() {
4996      return this._cart.totalConvenienceFee;
4997    }
4998  }, {
4999    key: 'totalDiscount',
5000    get: function get() {
5001      return this._cart.totalDiscount;
5002    }
5003  }, {
5004    key: 'passengers',
5005    get: function get() {
5006      return this._cart.listPassengers;
5007    }
5008  }, {
5009    key: 'departureOnly',
5010    get: function get() {
5011      return this._cart.departureOnly;
5012    },
5013    set: function set(departureOnly) {
5014      this._cart.departureOnly = departureOnly;
5015    }
5016  }, {
5017    key: 'cart',
5018    get: function get() {
5019      return this._cart;
5020    }
5021  }, {
5022    key: 'listOffer',
5023    get: function get() {
5024      return this._cart.listOffer.slice(0);
5025    }
5026  }, {
5027    key: 'balanceTotal',
5028    get: function get() {
5029      return this._cart.balanceTotal;
5030    }
5031  }]);
5032
5033  return CartService;
5034}();
5035'use strict';
5036
5037
5038var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
5039
5040function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
5041
5042var FormFields = function () {
5043  function FormFields() {
5044    _classCallCheck(this, FormFields);
5045  }
5046
5047  _createClass(FormFields, null, [{
5048    key: 'compareEmail',
5049    value: function compareEmail(emailField, validEmailField) {
5050      var $tip = validEmailField.parent().siblings().find('.tip');
5051
5052      if (emailField.val() === validEmailField.val()) {
5053        this.removeInvalidClass(emailField);
5054        this.removeInvalidClass(validEmailField, $tip);
5055      } else {
5056        this.addInvalidClass(emailField);
5057        this.addInvalidClass(validEmailField, i18n('email_distinct'), $tip);
5058      }
5059    }
5060  }, {
5061    key: 'checkoutEmail',
5062    value: function checkoutEmail(email, emailField, msg) {
5063      var regex = new RegExp(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/gm);
5064      var $tip = emailField.parent().siblings().find('.tip');
5065      var tipText = msg ? msg : i18n('email_invalid');
5066
5067      if (!regex.test(email)) {
5068        this.addInvalidClass(emailField, tipText, $tip);
5069        return false;
5070      }
5071
5072      this.removeInvalidClass(emailField, $tip);
5073      return true;
5074    }
5075  }, {
5076    key: 'validateName',
5077    value: function validateName(nameField, msg) {
5078      var name = nameField.val().trim();
5079      var $tip = nameField.parent().siblings().find('.tip');
5080      var isValidName = name.indexOf(' ') !== -1;
5081      var tipText = msg ? msg : i18n('name_required');
5082
5083      isValidName ? this.removeInvalidClass(nameField, $tip) : this.addInvalidClass(nameField, tipText, $tip);
5084
5085      return isValidName;
5086    }
5087  }, {
5088    key: 'validationCaracterName',
5089    value: function validationCaracterName(nameField) {
5090      var regex = /[^a-zA-Z\u00C0-\u00FF ]+/ig;
5091      nameField.on("input", function (e) {
5092        $(this).val($(this).val().replace(regex, ""));
5093      });
5094    }
5095  }, {
5096    key: 'isDocumentValid',
5097    value: function isDocumentValid(docTypeField, docField, msg) {
5098      var ignoreAlert = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
5099
5100      var documentNumber = docField.val().trim().replace(/[.]|[-]|[/]/g, '');
5101      var documentType = docTypeField.val();
5102      var evaluation = false;
5103      var $tip = docField.parent().siblings().find('.tip');
5104      var tipText = msg ? msg : i18n('cpf_error');
5105
5106      if (documentType === 'CPF') {
5107        evaluation = Utils.validateCPF(documentNumber);
5108
5109        if (!evaluation) {
5110          this.addInvalidClass(docField, tipText, $tip);
5111        } else {
5112          this.removeInvalidClass(docField, $tip);
5113        }
5114      } else if (documentType === 'CNPJ') {
5115        evaluation = Utils.validateCNPJ(documentNumber);
5116
5117        if (!evaluation) {
5118          this.addInvalidClass(docField, i18n('cnpj_error'), $tip);
5119        } else {
5120          this.removeInvalidClass(docField, $tip);
5121        }
5122      }
5123      return evaluation;
5124    }
5125  }, {
5126    key: 'addInvalidClass',
5127    value: function addInvalidClass(el, msg, tip) {
5128      var $links = el.parent().siblings().find('.link');
5129      if (!this.isSelectCustom(el)) $(el).addClass("invalid"); else $(el).siblings('.select-selected').addClass('invalid');
5130      if (tip && tip.hasClass('warning')) {
5131        if (msg) tip.text(msg);
5132        tip.fadeIn();
5133        $links.hide();
5134      }
5135    }
5136  }, {
5137    key: 'validateDDDfield',
5138    value: function validateDDDfield(dddField) {
5139      var number = dddField.val().replace(/\D/g, '');
5140
5141      dddField.val(number);
5142
5143      if (dddField.val().length === 2) {
5144        this.removeInvalidClass(dddField);
5145        return;
5146      }
5147
5148      this.addInvalidClass(dddField);
5149    }
5150  }, {
5151    key: 'validatePhonefield',
5152    value: function validatePhonefield(phoneField) {
5153      var number = phoneField.val().replace(/\D/g, '');
5154
5155      phoneField.val(number);
5156
5157      if (phoneField.val().length > 8) {
5158        this.removeInvalidClass(phoneField);
5159        return;
5160      }
5161
5162      this.addInvalidClass(phoneField);
5163    }
5164  }, {
5165    key: 'removeInvalidClass',
5166    value: function removeInvalidClass(el, tip) {
5167      var $links = el.parent().siblings().find('.link');
5168      if (!this.isSelectCustom(el)) $(el).removeClass("invalid"); else $(el).siblings('.select-selected').removeClass('invalid');
5169      if (tip && tip.hasClass('warning')) {
5170        tip.fadeOut();
5171        $links.show();
5172      }
5173    }
5174  }, {
5175    key: 'isSelectCustom',
5176    value: function isSelectCustom(el) {
5177      return $(el).attr('data-js') === 'input-doc-type' || $(el).attr('data-js') === 'input-phone-type';
5178    }
5179  }, {
5180    key: 'emptyValidation',
5181    value: function emptyValidation(selector) {
5182      var allFieldsValid = true;
5183      var self = this;
5184
5185      $('' + selector + '').find('input[required], select[required]').each(function (idx, el) {
5186        var value = $(el).val() ? $(el).val() : '';
5187        if (self.isEmpty(value)) {
5188          // self.addInvalidClass($(el))
5189          allFieldsValid = false;
5190        }
5191      });
5192      return allFieldsValid;
5193    }
5194  }, {
5195    key: 'isEmpty',
5196    value: function isEmpty(value) {
5197      return value === null || value.trim() === '';
5198    }
5199  }, {
5200    key: 'blockNotNumbers',
5201    value: function blockNotNumbers(e) {
5202      var key = e.key;
5203      var isNotANumber = isNaN(key);
5204      var allowedChars = ['Backspace', 'Tab', 'Alt', 'Control', 'Delete', 'Enter', 'Shift', 'Meta', 'CapsLock'];
5205      var isAllowed = allowedChars.includes(key);
5206
5207      if (isAllowed) {
5208        return;
5209      }
5210
5211      if (isNotANumber) {
5212        // e.preventDefault();
5213        return;
5214      }
5215    }
5216  }]);
5217
5218  return FormFields;
5219}();
5220'use strict';
5221
5222var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
5223
5224function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
5225
5226/**
5227 * MAIN
5228 *
5229 * INICIO
5230 * LOGICA HTTP SERVICE
5231 *
5232 */
5233
5234var targetConfig = {
5235  AEM: {
5236    baseUrl: $('#rootPath').val() + '/jcr:content.',
5237    endpoints: {
5238      searchOrigin: 'jcaholding_buscaOrigem.json',
5239      searchDestination: 'jcaholding_buscaDestino.json',
5240      getRoutes: 'jcaholding_buscaCorrida.json',
5241      getVehicles: 'jcaholding_buscaOnibus.json',
5242      lockSeat: 'jcaholding_bloquerCancelarPoltrona.json',
5243      confirmSale: 'jcaholding_confirmaVenda.json',
5244      loginUser: 'jcaholding_login.json',
5245      registerUser: 'jcaholding_cadastro.json',
5246      editUser: 'jcaholding_update.json',
5247      changePassword: 'jcaholding_atualizarSenha.json',
5248      resetPassword: 'jcaholding_resetarSenha.json',
5249      cancelSale: 'jcaholding_cancelarVenda.json',
5250      getHistoric: 'jcaholding_historicoCompra.json',
5251      sendTicket: 'jcaholding_reenviarEmail.json',
5252      salesforce: {
5253        authentication: {
5254          auth_uri: 'salesforceauth.json'
5255        },
5256        protocol: {
5257          case_uri: 'protocolopenregistercase.json',
5258          content_version_uri: 'protocolcontentversion.json',
5259          content_document_uri: 'protocolcontentversion.json?q=',
5260          content_link_uri: 'protocoldocumentlink.json',
5261          owner_id: '0053m00000BC4qVAAT'
5262        }
5263      }
5264    }
5265  },
5266  EXT: {
5267    baseUrl: $('#baseUrl').val(),
5268    endpoints: {
5269      searchOrigin: '/place/v1/searchOrigin',
5270      searchDestination: '/place/v1/searchDestination',
5271      getRoutes: '/route/v1/getRoutes',
5272      getVehicles: '/vehicle/v1/getVehicles',
5273      lockSeat: '/seat/v1/transactSeat',
5274      confirmSale: '/sale/v1/confirmsale',
5275      loginUser: '/customer/v1/account',
5276      tokenMalga: '/hub/v1/tokens',
5277      loginWpp: '/customer/v1/account/loginWhatsapp',
5278      registerUser: '/customer/v1/user',
5279      editUser: '/customer/v1/user',
5280      changePassword: '/customer/v1/user/changepassword',
5281      changePasswordLink: '/customer/v1/user/newpassword',
5282      resetPassword: '/customer/v1/user/resetpassword',
5283      cancelAsyncSale: '/sale/v1/cancel-async',
5284      refundDetails: '/sale/v1/refund-detail',
5285      getHistoric: '/sale/v1/gethistoric',
5286      sendTicket: '/sale/v1/sendTicket',
5287      voucherDiscount: '/voucher/v1/validatetoken',
5288      voucherValidation: '/voucher/v1/applytoken',
5289      editPassenger: '/paxroute/v1/updatePax',
5290      removePassenger: '/paxroute/v1/removePax',
5291      savefrequentpassenger: '/paxroute/v1/addPax',
5292      returnfrequentpassengers: '/paxroute/v1/searchPax',
5293      getImage: '/customer/photo/getbyuser',
5294      registerImage: '/customer/photo',
5295      updateImage: '/customer/photo',
5296      paymentBank: '/sale/v1/createasyncsale',
5297      paymentPix: '/sale/v2/create-async-sale',
5298      saleSummary: '/sale/v2/summary',
5299      paymentNupay: '/sale/v2/sale/create-sale',
5300      nupayPaymentStatus: '/sale/v2/sale/sale-summary',
5301      changesAuthorization: '/sale/v2/changes-authorization',
5302      getCard: '/payment/v1/financial/getcard',
5303      getCardMalga: '/payment-hub/v1/paymenthub/getCardsByClient',
5304      removeCard: '/payment/v1/financial/removeCard',
5305      removeCardMalga: '/payment-hub/v1/paymenthub/deleteCard',
5306      getPaymeePayment: '/payment/v1/financial/getpaymeepayment',
5307      getPaymentMethod: '/payment/v1/financial/getpaymentmethod',
5308      itinerary: '/itinerary/v1/getitinerary',
5309      getEmailRegistered: '/customer/v1/user/existemail',
5310      getCPFRegistered: '/customer/v1/user/existcpf',
5311      validateStudent: '/sale/v1/validatestudent',
5312      getServiceCategory: '/route/v1/getServiceCategory',
5313      validationCPF: '/customer/v1/user/validate-data',
5314      accessToken: '/oauth/v3/login',
5315      checkEligibility: '/exchange/v1/Exchange/checkeligibility',
5316      returnAvailability: '/exchange/v1/Exchange/returnAvailability',
5317      lockSeatRemark: '/seat/v1/transactSeatExchange',
5318      paymentRemark: '/sale/v1/confirmsaleexchange',
5319      installment: '/installment/v1/Installment',
5320      paymentPixRemark: '/exchange/v1/SaleExchange/createasyncsale',
5321      getSale: '/sale-card/v1/sale/getsale',
5322      confirmSaleWpp: '/sale-card/v1/sale/confirmsale',
5323      checkWalletExists: '/wallet/v1/exists/:cpf',
5324      getWalletBalance: '/wallet/v1/:walletId/balance',
5325      paymentPixWallet: '/sale/v2/wallet/create-async-sale',
5326      paymentComplementPixCheck: '/sale/v2/sale/status/finder/:finder/user/:user',
5327      cancelSaleWallet: '/sale/v1/cancel-sale-wallet',
5328      paymentAvailability: '/payment-availability/v1/availability',
5329      termsAcceptance: '/terms-acceptance/v1/term-acceptance/create',
5330      createWallet: '/wallet/v1/create',
5331      briteEmailValidate: '/customer/v1/user/email-validade',
5332      loginWallet: '/wallet/v1/pin-auth',
5333      resetPin: '/wallet/v1/pin-auth/reset-pin',
5334      changePin: '/wallet/v1/pin-auth/change-pin',
5335      validateCode: '/wallet/v1/pin-auth/reset-pin/validate',
5336      openProtocol: '/hub-integration/v1/sales-force/OpenProtocol',
5337      contentVersion: '/hub-integration/v1/sales-force/contentversion',
5338      contentLink: '/hub-integration/v1/sales-force/contentlink',
5339      getDynamicServiceOffer: '/route/v1/getDynamicServiceOffer',
5340      getDynamicServiceOfferByDestination: '/route/v1/dynamic-offer-by-destination',
5341      authorizationWhatsapp: '/sale/v2/changes-authorization/'
5342    }
5343  }
5344};
5345
5346var statusThrown = {
5347  500: function _() {
5348    return Alert.show("Houve uma falha na requisição. Tente mais tarde.");
5349  },
5350  504: function _() {
5351    return Alert.show("Houve uma falha na requisição. Tente mais tarde.");
5352  },
5353  0: function _() {
5354    return Alert.show("Houve uma falha na requisição. Tente mais tarde.");
5355  }
5356};
5357
5358$.ajaxSetup({
5359  complete: function complete(jqXHR, textStatus) {
5360    var url = this && this.url ? this.url : '';
5361    if (url.indexOf('changes-authorization') !== -1) return;
5362    // retorno NuPay (pendente/confirmacao): 401/token invalido nao pode deslogar e mandar pra home
5363    if (HttpService._nupayPendingFlow) return;
5364
5365    var responseText = jqXHR && jqXHR.responseText ? jqXHR.responseText : '';
5366
5367    if (!responseText) return;
5368
5369    try {
5370      var responseJson = jqXHR.responseJSON || JSON.parse(responseText);
5371      if (HttpService.isInvalidTokenResponse(responseJson)) {
5372        HttpService.redirectToLogin();
5373      }
5374    } catch (error) {
5375      console.debug('HttpService invalid token parse ignored', error);
5376    }
5377  }
5378});
5379
5380var fetchURL = function fetchURL(content) {
5381  var _content$split = content.split('?'),
5382    _content$split2 = _slicedToArray(_content$split, 2),
5383    endpointName = _content$split2[0],
5384    queryParams = _content$split2[1];
5385
5386  var target = $('#aemEnvironmentServices').val() == "" ? "AEM" : $('#aemEnvironmentServices').val();
5387  var baseUrl = targetConfig[target].baseUrl;
5388  var endpoints = targetConfig[target].endpoints;
5389
5390  var uri = endpoints[endpointName];
5391
5392  if (!uri) {
5393    var _baseUrl = targetConfig['AEM'].baseUrl;
5394
5395    return queryParams ? '' + _baseUrl + endpointName + '?' + queryParams : '' + _baseUrl + endpointName;
5396  }
5397
5398  var params = new URLSearchParams(queryParams);
5399
5400  uri = uri.replace(/:([^/]+)/g, function (_, key) {
5401    var value = params.get(key);
5402    if (value) {
5403      params.delete(key);
5404      return value;
5405    }
5406    return ':' + key;
5407  });
5408
5409  var queryString = params.toString();
5410  return queryString ? '' + baseUrl + uri + '?' + queryString : '' + baseUrl + uri;
5411};
5412
5413var fetchURLContent = function fetchURLContent(content) {
5414  var _content$split = content.split('#'),
5415    _content$split2 = _slicedToArray(_content$split, 2),
5416    endpointName = _content$split2[0],
5417    queryParams = _content$split2[1];
5418
5419  var target = $('#aemEnvironmentServices').val();
5420  var baseUrl = targetConfig[target].baseUrl;
5421  var endpoints = targetConfig[target].endpoints;
5422  var uri = endpoints[endpointName];
5423
5424  return baseUrl + uri + queryParams;
5425};
5426
5427var HttpService = function () {
5428  function HttpService() {
5429    _classCallCheck(this, HttpService);
5430  }
5431
5432  _createClass(HttpService, null, [{
5433    key: 'isInvalidTokenResponse',
5434    value: function isInvalidTokenResponse(responseData) {
5435      if (HttpService._restoringCustomerSession || HttpService._nupayPendingFlow) {
5436        return false;
5437      }
5438      if (responseData.success == false && responseData.message == "Token invalido") {
5439        return true;
5440      }
5441      return false;
5442    }
5443  }, {
5444    key: 'getAEM',
5445    value: function getAEM(content) {
5446      var headers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
5447
5448      return $.ajax({
5449        url: fetchURL(content),
5450        contentType: 'json',
5451        type: 'GET',
5452        headers: headers,
5453        statusCode: statusThrown
5454      });
5455    }
5456  }, {
5457    key: 'get',
5458    value: function get(content) {
5459      var headers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
5460
5461      var headersRequest = this.getSession(headers);
5462
5463      return $.ajax({
5464        url: fetchURL(content),
5465        contentType: 'json',
5466        type: 'GET',
5467        headers: headersRequest,
5468        statusCode: statusThrown
5469      });
5470    }
5471  }, {
5472    key: 'getToken',
5473    value: function get(content) {
5474      var headers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
5475
5476      var headersRequest = this.getSession(headers);
5477
5478      return $.ajax({
5479        url: fetchURLContent(content),
5480        contentType: 'json',
5481        type: 'GET',
5482        headers: headersRequest,
5483        statusCode: statusThrown
5484      });
5485    }
5486  }, {
5487    key: 'postAEM',
5488    value: function postAEM(content, data) {
5489      var headers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
5490
5491      return $.ajax({
5492        url: fetchURL(content),
5493        dataType: 'json',
5494        contentType: "application/json",
5495        type: 'POST',
5496        headers: headers,
5497        data: JSON.stringify(data),
5498        statusCode: statusThrown
5499      });
5500    }
5501  }, {
5502    key: 'post',
5503    value: function post(content, data) {
5504      var headers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
5505
5506      var headersRequest = this.getSession(headers);
5507
5508      return $.ajax({
5509        url: fetchURL(content),
5510        dataType: 'json',
5511        contentType: "application/json",
5512        type: 'POST',
5513        headers: headersRequest,
5514        data: JSON.stringify(data),
5515        statusCode: statusThrown
5516      });
5517    }
5518  }, {
5519    key: 'put',
5520    value: function put(content, data) {
5521      var headers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
5522
5523      var headersRequest = this.getSession(headers);
5524
5525      return $.ajax({
5526        url: fetchURL(content),
5527        dataType: 'json',
5528        contentType: "application/json",
5529        type: 'PUT',
5530        headers: headersRequest,
5531        data: JSON.stringify(data),
5532        statusCode: statusThrown
5533      });
5534    }
5535  }, {
5536    key: 'delete',
5537    value: function _delete(content) {
5538      var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
5539      var additionalHeaders = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
5540
5541      var clientid = this._accssesToken._clientId;
5542      var accessToken = sessionStorage.getItem('access_token');
5543
5544      var headersRequest = {
5545        client_id: clientid,
5546        access_token: accessToken
5547      };
5548
5549      Object.assign(headersRequest, additionalHeaders);
5550
5551      return $.ajax({
5552        url: fetchURL(content),
5553        dataType: 'json',
5554        contentType: "application/json",
5555        type: 'DELETE',
5556        headers: headersRequest,
5557        data: JSON.stringify(data)
5558      });
5559    }
5560  }, {
5561    key: 'getSession',
5562    value: function getSession(headers) {
5563      this._accssesToken = new AccssesTokenService();
5564      var clientid = this._accssesToken._clientId;
5565      var accessToken = sessionStorage.getItem('access_token');
5566      var walletToken = SessionStorage.get("user_wallet");
5567
5568      if (accessToken == null || !this._accssesToken.verifyToken()) {
5569        Promise.all([this._accssesToken.authorization(), this._accssesToken.getAccssesToken()]).then(function () {
5570          sessionStorage.removeItem('authorizationId');
5571        }).catch(function (err) {
5572          console.error(err);
5573        });
5574
5575        accessToken = sessionStorage.getItem('access_token');
5576      }
5577
5578      var headersRequest = {
5579        client_id: clientid,
5580        access_token: accessToken,
5581        "x-site-company-id": Utils.getCompanyId()
5582      };
5583
5584      if (walletToken && walletToken.token) {
5585        headersRequest['x-authorization-wallet'] = walletToken.token;
5586      }
5587
5588      if (headers) {
5589        if (headers.version) headersRequest.version = headers.version;
5590
5591        if (headers.Authorization) headersRequest.Authorization = headers.Authorization;
5592
5593        if (headers.sessionseatlock) headersRequest.sessionseatlock = headers.sessionseatlock;
5594
5595        if (headers.flow) headersRequest.flow = headers.flow;
5596
5597        if (headers.flowPayment) headersRequest.flowPayment = headers.flowPayment;
5598
5599        if (headers.channel) headersRequest.channel = headers.channel;
5600
5601        if (headers.sessiondispolock) headersRequest.sessiondispolock = headers.sessiondispolock;
5602
5603        if (headers['X-meli-session-id']) headersRequest['X-meli-session-id'] = headers['X-meli-session-id'];
5604      }
5605
5606      return headersRequest;
5607    }
5608  }, {
5609    key: 'getSessionGiro',
5610    value: function getSessionGiro() {
5611      this._accssesToken = new AccssesTokenServiceGiro();
5612      var clientid = this._accssesToken._clientId;
5613      var accessToken = sessionStorage.getItem('access_token_giro');
5614
5615      if (accessToken == null || !this._accssesToken.verifyToken()) {
5616        Promise.all([this._accssesToken.authorization(), this._accssesToken.getAccssesToken()]).then(function () {
5617          sessionStorage.removeItem('authorizationIdGiro');
5618        }).catch(function (err) {
5619          console.error(err);
5620        });
5621
5622        accessToken = sessionStorage.getItem('access_token_giro');
5623      }
5624
5625      var headersRequest = {
5626        client_id: clientid,
5627        access_token: accessToken
5628      };
5629
5630      return headersRequest;
5631    }
5632  }, {
5633    key: 'getEndpointUrl',
5634    value: function getEndpointUrl(endpointName) {
5635      var endpoint = targetConfig['EXT'].endpoints[endpointName];
5636      if (endpoint) {
5637        return '' + targetConfig['EXT'].baseUrl + endpoint;
5638      }
5639      return null;
5640    }
5641  }, {
5642    key: 'restorePaymentSession',
5643    value: function restorePaymentSession(paymentId) {
5644      var _this = this;
5645
5646      var existingToken = SessionStorage.get('jca_token');
5647
5648      if (!paymentId) {
5649        if (existingToken) HttpService.applyRestoredCustomer(existingToken);
5650        return Promise.resolve(false);
5651      }
5652
5653      HttpService._restoringCustomerSession = true;
5654
5655      var delay = function delay(ms) {
5656        return new Promise(function (resolve) {
5657          return setTimeout(resolve, ms);
5658        });
5659      };
5660
5661      var headers = {
5662        version: "2"
5663      };
5664
5665      var headersRequest = HttpService.getSession(headers);
5666
5667      var requestOnce = function requestOnce() {
5668        return new Promise(function (resolve, reject) {
5669          $.ajax({
5670            url: _this.getEndpointUrl('changesAuthorization') + '/' + paymentId,
5671            contentType: 'json',
5672            type: 'GET',
5673            timeout: 8000,
5674            headers: headersRequest
5675          }).then(function (data) {
5676            var session = data && data.result;
5677            if (!session || !session.token) {
5678              reject(new Error('empty-session'));
5679              return;
5680            }
5681            resolve(session.token);
5682          }).fail(function () {
5683            return reject(new Error('restore-failed'));
5684          });
5685        });
5686      };
5687
5688      var tryRestore = function tryRestore(attempt) {
5689        return requestOnce().catch(function (error) {
5690          if (attempt >= 3) throw error;
5691          return delay(700 * attempt).then(function () {
5692            return tryRestore(attempt + 1);
5693          });
5694        });
5695      };
5696
5697      return tryRestore(1).then(function (token) {
5698        SessionStorage.set('jca_token', token);
5699        HttpService.applyRestoredCustomer(token);
5700        return true;
5701      }).catch(function () {
5702        if (existingToken) HttpService.applyRestoredCustomer(existingToken);
5703        return false;
5704      }).then(function (restored) {
5705        setTimeout(function () {
5706          HttpService._restoringCustomerSession = false;
5707        }, 0);
5708        return restored;
5709      });
5710    }
5711  }, {
5712    key: 'applyRestoredCustomer',
5713    value: function applyRestoredCustomer(token) {
5714      if (!token) return;
5715
5716      if (SessionStorage.get('passenger')) {
5717        HttpService.refreshLoggedHeader();
5718        return;
5719      }
5720
5721      var payload = Utils.extractJWTData(token);
5722      if (!payload) {
5723        HttpService.refreshLoggedHeader();
5724        return;
5725      }
5726
5727      var passenger = new Passenger();
5728      var name = [payload.user_Name, payload.user_FamilyName].filter(Boolean).join(' ').trim();
5729      passenger.name = name;
5730      passenger.login = payload.user_Login;
5731      passenger.email = payload.user_Email;
5732      passenger.image = payload.user_Image;
5733      passenger.cpf = payload.user_Cpf;
5734      passenger.passport = payload.user_Passport;
5735      passenger.documentNumber = payload.user_Cpf || payload.user_Document;
5736      passenger.phone = payload.user_Phone;
5737      passenger.areaCode = payload.user_AreaCode;
5738      passenger.id = payload.user_Id;
5739      passenger.optin = payload.user_Optin;
5740      passenger.validated = payload.user_Validated;
5741
5742      var phoneType = payload.user_PhoneType;
5743      if (phoneType) {
5744        passenger.phoneType = String(phoneType).toLowerCase() === 'mobile' ? 1 : 2;
5745      }
5746
5747      if (payload.user_BirthDate && typeof DateFormatter !== 'undefined') {
5748        try {
5749          passenger.birthDate = DateFormatter.reverseDate(String(payload.user_BirthDate).split(' ')[0]);
5750        } catch (e) {}
5751      }
5752
5753      SessionStorage.set('passenger', passenger);
5754      HttpService.refreshLoggedHeader();
5755    }
5756  }, {
5757    key: 'refreshLoggedHeader',
5758    value: function refreshLoggedHeader() {
5759      var passenger = SessionStorage.get('passenger');
5760      if (!passenger) return;
5761
5762      $('[data-js="logged-in-section"]').show();
5763      $('[data-js="logged-out-section"]').hide();
5764      $('[data-js="nav-button-login"]').hide();
5765      $('[data-js="nav-button-logout"]').show();
5766      $('[data-js="my-account"]').parent().show();
5767      $('[data-js="edit-data"]').parent().show();
5768
5769      if (passenger._name) {
5770        var firstName = Utils.getFirstName(passenger._name);
5771        $('[data-js="user-name"]').text(firstName);
5772        $('[data-js="name-account"]').text(passenger._name);
5773      }
5774    }
5775  }, {
5776    key: 'getFromCompany',
5777    value: function getFromCompany(content) {
5778      return $.ajax({
5779        url: $('#companyRootPath').val() + '/jcr:content.' + content,
5780        contentType: 'json',
5781        type: 'GET'
5782      });
5783    }
5784  }, {
5785    key: 'getFromRoot',
5786    value: function getFromRoot(content) {
5787      return $.ajax({
5788        url: '/content/jca/jcr:content.' + content,
5789        contentType: 'json',
5790        type: 'GET'
5791      });
5792    }
5793  }
5794  ]);
5795
5796  return HttpService;
5797}();
5798
5799/**
5800 * MAIN
5801 *
5802 * FIM
5803 * LOGICA HTTP SERVICE
5804 *
5805 */
5806'use strict';
5807
5808var strings = {
5809  "pt-br": {
5810    search_component_child_less: 'O número de crianças não pode ultrapassar o de adultos.',
5811    payment_generic_error: 'Houve um erro ao processar o pagamento. Verifique novamente os dados inseridos.',
5812    user_name_invalid: 'Você deve inserir seu nome completo para completar o registro.',
5813    birth_invalid: 'Data inválida.',
5814    document_invalid: 'Verificamos que o número informado não é valido. Revise antes de finalizar seu cadastro.',
5815    document_number_invalid: 'Verificamos que o número informado não é valido. Revise antes de finalizar seu cadastro.',
5816    document_exists: 'Documento e/ou email já cadastrado(s).',
5817    email_invalid: $('[data-js="msg-input-invalids"]').data('email-invalid') != undefined ? $('[data-js="msg-input-invalids"]').data('email-invalid') : 'Endereço de email não é válido.',
5818    email_exists: 'Email já cadastrado.',
5819    email_distinct: 'Endereços de email não coincidem.',
5820    edit_success: 'Dados editados com sucesso',
5821    password_invalid: 'As senhas não coincidem',
5822    phone_invalid: 'Telefone inválido',
5823    empty_fields: 'Alguns campos estão vazios. Preencha os campos faltantes assinalados em vermelho antes de prosseguir.',
5824    field_min_caracter: 'Alguns campos estão com menos caracteres do que o mínimo. Preencha os campos faltantes assinalados em vermelho antes de prosseguir.',
5825    cpf_exists: 'CPF já cadastrado na base',
5826    status_error: 'Houve um problema. Tente novamente.',
5827    protocol_error: 'Não foi possível enviar sua solicitação. Por favor, refaça a tentativa!',
5828    protocol_success: 'Solicitação enviada com sucesso!',
5829    sending: 'Enviando...',
5830    discount_error: 'Este cupom não é válido.',
5831    discount_success: 'Desconto aplicado com sucesso.',
5832    discount_sucess_number_passengers: 'Desconto aplicado para alguns passageiros.',
5833    discount_sucess_rote: 'Desconto aplicado apenas um dos trechos.',
5834    discount_sucess_rote_passenger: 'Desconto aplicado para alguns passageiro e apenas um dos trechos.',
5835    message_no_result_filters: 'Nenhum resultado encontrado com os filtros selecionados',
5836    select_document: 'Selecione o documento',
5837    birth_child_invalid: 'Atenção! A data de nascimento inserida é maior que 5 anos de idade.',
5838    data_future_invalid: 'Datas futuras não são válidas.',
5839    data_format_invalid: 'Data de formato inválido.',
5840    document_used: 'O documento informado já foi usado.',
5841    save_passenger: 'Salvar como passageiro frequente.',
5842    select: 'Selecione',
5843    name_placeholder: 'Nome completo',
5844    document_placeholder: 'Número do documento',
5845    seat_selected: 'Assento selecionado',
5846    seat_child: 'Sem ocupar assento',
5847    register_image_success: 'Imagem cadastrada com sucesso!',
5848    register_image_fail: 'Houve um erro ao registrar imagem de usuário',
5849    update_image_success: 'Imagem atualizada com sucesso!',
5850    update_image_fail: 'Houve um erro ao atualizar usuário',
5851    webcam_error: 'Verifique se seu dispositivo de video está conectado.',
5852    inputfield_invalid: 'Algum campo está inválido.',
5853    cpf_email_exists: 'O CPF e/ou e-mail informados já foram cadastrados em nossa base de dados anteriormente.',
5854    conf_message_title: 'Tudo certo!',
5855    conf_message_subtitle: 'Seus dados foram salvos com sucesso.',
5856    conf_password_subtitle: 'Senha atualizada com sucesso.',
5857    conf_register_subtitle: 'Cadastro realizado com sucesso!',
5858    conf_register_title2: 'Seja bem-vindo',
5859    field_important: 'Preenchimento obrigatório',
5860    remove_card_error: 'Erro ao remover cartão. Tente novamente.',
5861    resend_ticket_confirmation: 'Foi enviado um email para o seu endereço cadastrado. Caso não tenha recebido, verifique seu spam ou faça a ',
5862    update_email_ticket: 'alteração do seu email.',
5863    link_email_ticket: '#',
5864    name_required: $('[data-js="msg-input-invalids"]').data('name-invalid') != undefined ? $('[data-js="msg-input-invalids"]').data('name-invalid') : 'Digite nome completo.',
5865    cpf_error: $('[data-js="msg-input-invalids"]').data('cpf-invalid') != undefined ? $('[data-js="msg-input-invalids"]').data('cpf-invalid') : 'CPF inválido.',
5866    cnpj_error: 'CNPJ inválidO',
5867    remarkable: 'REMARCÁVEL',
5868    pending: 'PENDENTE',
5869    active: 'ATIVA',
5870    canceled: 'CANCELADA',
5871    expired: 'EXPIRADA',
5872    relocated_canceled: $('[data-js="my-travels-status-label"]').attr('data-relocated-canceled') ? $('[data-js="my-travels-status-label"]').attr('data-relocated-canceled') : 'REACOMODAÇÃO CANCELADA',
5873    sale_relocated: $('[data-js="my-travels-status-label"]').attr('data-sale-relocated') ? $('[data-js="my-travels-status-label"]').attr('data-sale-relocated') : 'REACOMODADA',
5874    cancelation_error: $('[data-js="my-travels-status-label"]').attr('data-cancelation-error') ? $('[data-js="my-travels-status-label"]').attr('data-cancelation-error') : 'ERRO CANCELAMENTO',
5875    message_sent: 'Sua mensagem foi enviada. Aguarde nosso retorno.',
5876    payment_error: 'Erro no pagamento!',
5877    payment_error_purchase: 'Não foi possível concluir a compra.',
5878    ticket_no_result: 'Sem tarifas',
5879    no_ticket: 'Sem passagem.',
5880    err_msg_cancel: 'Para cancelar este adulto, deverá ser cancelada a passagem da criança primeiro ou cancelar todos os passageiros de
5880sse trecho',
5881    err_msg_passenger_canceled: 'Algum passageiro já foi cancelado em uma das rotas.',
5882    err_msg_passenger_return_canceled: 'Algum passageiro já foi cancelado na rota de retorno.',
5883    available: 'Indisponível',
5884    brite_unavailable_msg: $('[data-js="msg-input-invalids"]').attr('data-brite-verify-error'),
5885    trip_departure_label: 'Passagem de ida',
5886    trip_return_label: 'Passagem de volta',
5887    show_resume: 'Ver resumo',
5888    message_error_wpp: $('[data-js="login-whatsapp-text"]').data('message-error-wpp') ? $('[data-js="login-whatsapp-text"]').data('message-error-wpp') : 'O email ou senha inseridos não constam em nosso cadastro. Digite novamente o email e senha ou efetue o cadastro abaixo.',
5889    err_msg_impossible_to_login: $('[data-js="aem-custom-err-msg-login"]').data('err-msg-impossible-to-login') ? $('[data-js="aem-custom-err-msg-login"]').data('err-msg-impossible-to-login') : 'Não foi possível efetuar o login',
5890    err_msg_login: $('[data-js="aem-custom-err-msg-login"]').data('err-msg-login') ? $('[data-js="aem-custom-err-msg-login"]').data('err-msg-login') : 'O email ou senha inseridos não constam em nosso cadastro. Digite novamente o email e senha ou efetue o cadastro abaixo.',
5891    placeholder_contact_us_default: 'Conte para nós o que aconteceu.',
5892    convenience_fee: $('[data-js="cart-details-text-values"]').data('text-convenience-fee') ? $('[data-js="cart-details-text-values"]').data('text-convenience-fee') : 'Taxa de conveniência',
5893    msg_faq_convenience_fee: $('[data-js="cart-details-text-values"]').data('text-msg-faq-convenience-fee') ? $('[data-js="cart-details-text-values"]').data('text-msg-faq-convenience-fee') : 'Opa, através dessa taxa podemos prover tecnologia para você garantir a sua passagem de ônibus online e com antecedência.',
5894    message_modal_confirm_msg_strech_one: $('[data-js="acceptance-term-modal"]').attr('first-message'),
5895    message_modal_confirm_msg_strech_two: $('[data-js="acceptance-term-modal"]').attr('second-message'),
5896    msg_faq_tax_service: $('[data-js="tooltip-service"]').val(),
5897    tooltip_service_tx_convenience: $('[data-js="tooltip-service-tx-convenience"]').val() ? $('[data-js="tooltip-service-tx-convenience"]').val() : 'Opa, através dessa taxa podemos prover tecnologia para você garantir a sua passagem de ônibus online e com antecedência.',
5898    msg_faq_penaltyAmount: $('[data-js="cart-details-text-values"]').data('text-msg-fac-penalty') ? $('[data-js="cart-details-text-values"]').data('text-msg-fac-penalty') : 'Esse valor corresponde a 20% do valor da tarifa da passagem original. Valor aplicado em remarcações realizadas com menos de 3h para o embarque ou após a data de embarque da passagem original',
5899    msg_label_penaltyAmount: $('[data-js="cart-details-text-values"]').data('text-label-penalty') ? $('[data-js="cart-details-text-values"]').data('text-label-penalty') : 'Multa de remarcação',
5900    error_seat_title: 'Erro ao finalizar compra!',
5901    error_seat_message: 'Por favor, realize a compra de uma nova passagem em apenas uma aba do navegador.',
5902    service_fee_message: $('[data-js="service-fee-message"]').val() ? $('[data-js="service-fee-message"]').val() : 'Essa taxa nos ajuda a manter nossa plataforma e a oferecer os serviços para você :) Em casos de cancelamento, esta taxa não é reembolsável.',
5903    cancel_trip_page: $('#cancelTripPath').val(),
5904    cancel_trip_wallet_page: $('#walletCancelTripPagePath').val(),
5905    my_account_page: $('#myAccountPath').val(),
5906    refund_processing_title: 'Estamos finalizando o seu reembolso',
5907    refund_processing_subtitle: 'O valor da passagem será creditado na sua Conta Giro instantaneamente após a confirmação.',
5908    refund_processing_card_subtitle: 'O valor da passagem será creditado na fatura do seu cartão de crédito, seguindo o prazo e regras da sua operadora de cartão.',
5909    refund_processing_paymee_subtitle: 'O valor da passagem será creditado na sua conta, seguindo o prazo e regras do seu banco.',
5910    register_giro_page: $('#walletRegisterPagePath').val(),
5911    register_terms_page: $('#walletTermosPagePath').val(),
5912    register_wallet_page: $('#walletPinPagePath').val(),
5913    refund_redirect_subtitle: 'Redirecionando você para a criação da sua conta Giro!',
5914    refund_redirect_wallet_subtitle: 'Redirecionando você para a criação da sua carteira Giro!',
5915    payment_link_redirect: $('#homePagePath').val(),
5916    wallet_creation_error: 'Erro ao criar carteira.',
5917    error_change_pin: 'Erro ao alterar PIN.',
5918    error_code_verification: 'Erro ao verificar o código. Tente novamente.',
5919    refund_pix_title: $('[data-js="refund-title-pix"]').val(),
5920    refund_pix_message: $('[data-js="refund-message-pix]').val()
5921  }
5922};
5923
5924var i18n = function i18n(key) {
5925  var language = 'pt-br'; // Utils.getCurrentLang();
5926  if (!language || !strings[language][key]) return key;
5927  return strings[language][key];
5928};
5929'use strict';
5930
5931var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
5932
5933function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
5934
5935/**
5936 * MAIN
5937 *
5938 * INICIO LOGICA LOADER
5939 *
5940 */
5941
5942var _requests = 0;
5943
5944var LoaderService = function () {
5945  function LoaderService() {
5946    _classCallCheck(this, LoaderService);
5947  }
5948
5949  _createClass(LoaderService, null, [{
5950    key: 'show',
5951    value: function show() {
5952      var site = $("#siteName").val();
5953      var file = site === "cometa" ? "jca-v2" :
5954        site === "expressodosul" ? "expresso-sul-v2" :
5955          site === "rapidoribeirao" ? "rapido-ribeirao-v2" :
5956            site === "1001" ? "viacao1001-v2" :
5957              site === "catarinense" ? "catarinense-v2" :
5958                site + "-v2";
5959
5960      $('[data-js="container-custom-trigger"]').val();
5961      var customAemLoader = $('[data-js="custom-aem-loader"]').val();
5962      if (customAemLoader) {
5963        var loaderDiv = $('\n    <div class="application-loader" id="loader">
5963\n      <span>\n      <img alt="loader" title="loader wemobi" src="' + customAemLoader + '" />\n      </span>\n    </div>\n    ');
5964      } else {
5965        var loaderDiv = $('\n      <div class="application-loader" id="loader">\n        <span>\n          <img alt="loader" title="loader" src="/etc.clientlibs/' + file + '/clientlibs/clientlib-site/resources/images/loader.gif" onerror="LoaderService.handleImageError()" />\n        </span>\n      </div>\n    ');
5966      };
5967
5968      if (!_requests) {
5969        if ($('[data-js="change-way-overlay"]:visible').length >= 1) loaderDiv.css({ 'z-index': 999 });
5970        if ($('body #loader').length <= 1) {
5971          loaderDiv.appendTo('body');
5972        }
5973      }
5974
5975      _requests++;
5976    }
5977  }, {
5978    key: 'hide',
5979    value: function hide() {
5980      if (_requests > 0) {
5981        _requests--;
5982      }
5983
5984      if (!_requests) {
5985        $('#loader').remove();
5986      }
5987    }
5988  }, {
5989    key: 'handleImageError',
5990    value: function handleImageError() {
5991      var defaultLoaderDiv = $('<div id="loader" class="loader loader-default is-active"></div>');
5992      $('#loader').replaceWith(defaultLoaderDiv);
5993    }
5994  }]);
5995
5996  return LoaderService;
5997}();
5998
5999/**
6000 * MAIN
6001 *
6002 * FIM LOGICA LOADER
6003 *
6004 */
6005'use strict';
6006
6007var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
6008
6009function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6010
6011var LoginDatalayerService = function () {
6012  function LoginDatalayerService($) {
6013    _classCallCheck(this, LoginDatalayerService);
6014
6015    this.passenger = SessionStorage.get('passenger');
6016    this.init();
6017  }
6018
6019  _createClass(LoginDatalayerService, [{
6020    key: 'init',
6021    value: function init() {
6022    }
6023  }, {
6024    key: 'sendLoginViewToAnalytics',
6025    value: function sendLoginViewToAnalytics(status) {
6026      var passenger = SessionStorage.get('passenger') || {};
6027
6028      if (Object.keys(passenger).length > 0) {
6029        var fullName = passenger._name || null;
6030        var nameParts = fullName ? fullName.split(' ') : [];
6031        var firstName = nameParts[0] || null;
6032        var lastName = nameParts.slice(1).join(' ') || null;
6033        var fullPhone = passenger._areaCode && passenger._phone ? "+55" + passenger._areaCode + passenger._phone : null;
6034        var currentUrl = window.location.href.replace(/\/$/, '');
6035        var isHomePage = $('#homePagePath').val() && currentUrl === $('#homePagePath').val();
6036        var userData = null;
6037
6038
6039        var userData = {
6040          user_id: passenger._id || null,
6041          phone: fullPhone || null,
6042          email: passenger._email || null,
6043          birthdate: passenger._birthDate || null,
6044          cpf: passenger._cpf || null,
6045          passport: null,
6046          cnpj: null,
6047          user_status: null,
6048          address: null,
6049          first_name: firstName || null,
6050          last_name: lastName || null,
6051          street: null,
6052          neighborhood: null,
6053          city: null,
6054          state: null,
6055          country: null,
6056          zipcode: null
6057        };
6058      }
6059
6060      var loginOrigin;
6061      if (isHomePage) {
6062        loginOrigin = 'home';
6063      } else {
6064        loginOrigin = window.location.pathname;
6065      }
6066      window.dataLayer = window.dataLayer || [];
6067      window.dataLayer.push({
6068        event: "login",
6069        affiliation: $("#siteName").val(),
6070        device: Utils.getDevice(),
6071        login_origin: loginOrigin,
6072        status: status,
6073        user_data: userData
6074      });
6075    }
6076  }]);
6077
6078  return LoginDatalayerService;
6079}();
6080'use strict';
6081
6082
6083var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
6084
6085function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6086
6087/**
6088 * MAIN
6089 *
6090 * INICIO LOGICA OVERLAY
6091 *
6092 */
6093
6094var OverlayService = function () {
6095  function OverlayService() {
6096    _classCallCheck(this, OverlayService);
6097  }
6098
6099  _createClass(OverlayService, null, [{
6100    key: 'show',
6101    value: function show() {
6102      var size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
6103      var blockBody = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
6104
6105      var overlay_div = '<div id="overlay" class="overlay ' + size + ' active" data-js="overlay"></div>';
6106      var body = $("body");
6107
6108      var _Utils$getWindowSize = Utils.getWindowSize(),
6109        width = _Utils$getWindowSize.width,
6110        breakpoints = _Utils$getWindowSize.breakpoints;
6111
6112      if (body.has("#overlay").length === 0) {
6113        $(overlay_div).appendTo(body);
6114
6115        if (width <= breakpoints.MD || blockBody) {
6116          body.css('overflow-y', 'hidden');
6117        }
6118
6119        return this;
6120      }
6121    }
6122  }, {
6123    key: 'hide',
6124    value: function hide() {
6125      $("#overlay").remove();
6126      $("body").css('overflow-y', 'auto');
6127      return this;
6128    }
6129  }, {
6130    key: 'addClass',
6131    value: function addClass(className) {
6132      $("#overlay").addClass(className);
6133      return this;
6134    }
6135  }, {
6136    key: 'removeClass',
6137    value: function removeClass(className) {
6138      $("#overlay").removeClass(className);
6139      return this;
6140    }
6141  }]);
6142
6143  return OverlayService;
6144}();
6145
6146/**
6147 * MAIN
6148 *
6149 * FIM LOGICA OVERLAY
6150 *
6151 */
6152'use strict';
6153
6154var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
6155
6156function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6157
6158var PageViewController = function () {
6159  function PageViewController($) {
6160    _classCallCheck(this, PageViewController);
6161
6162    this.passenger = SessionStorage.get('passenger');
6163    this.init();
6164  }
6165
6166  _createClass(PageViewController, [{
6167    key: 'init',
6168    value: function init() {
6169      this.sendPageViewToAnalytics();
6170    }
6171  }, {
6172    key: 'sendPageViewToAnalytics',
6173    value: function sendPageViewToAnalytics() {
6174      var passenger = this.passenger || {};
6175
6176      if (Object.keys(passenger).length > 0) {
6177        var fullName = passenger._name || null;
6178        var nameParts = fullName ? fullName.split(' ') : null;
6179        var firstName = nameParts[0] || null;
6180        var lastName = nameParts.slice(1).join(' ') || null;
6181        var fullPhone = "+55" + passenger._areaCode + passenger._phone;
6182        var userData = null;
6183
6184        var userData = {
6185          user_id: passenger._id || null,
6186          phone: fullPhone || null,
6187          email: passenger._email || null,
6188          birthdate: passenger._birthDate || null,
6189          cpf: passenger._cpf || null,
6190          passport: null,
6191          cnpj: null,
6192          user_status: null,
6193          address: null,
6194          first_name: firstName || null,
6195          last_name: lastName || null,
6196          street: null,
6197          neighborhood: null,
6198          city: null,
6199          state: null,
6200          country: null,
6201          zipcode: null
6202
6203        };
6204      }
6205
6206      window.dataLayer = window.dataLayer || [];
6207      window.dataLayer.push({
6208        event: "page_view",
6209        page: {
6210          pagePath: window.location.pathname
6211        },
6212        user_data: userData,
6213        device: Utils.getDevice(),
6214        screen_resolution: window.screen.width + 'x' + window.screen.height
6215      });
6216    }
6217  }]);
6218
6219  return PageViewController;
6220}();
6221
6222'use strict';
6223
6224/**
6225 * MAIN
6226 *
6227 */
6228
6229(function ($) {
6230  'use strict';
6231
6232  // Old general-config.js
6233
6234  $(window).resize(function () {
6235    var body = $('body');
6236    var windowWidth = $(window).width();
6237    if (body.css('position') === 'fixed') {
6238      body.width(windowWidth);
6239    } else {
6240      if (body.css('position') === 'relative' && body.css('width')) {
6241        body.width('');
6242      }
6243    }
6244  });
6245
6246  setTimeout(function () {
6247    var formData = SessionStorage.get('formData');
6248    var breadcrumb = $('[data-js="breadcrumb"]');
6249    var breadcrumb_mobile = $('[data-js="breadcrumb-mobile"]');
6250    var steps = breadcrumb.children().find('.breadcrumb-section');
6251    var stepsArrow = breadcrumb.children().find('.breadcrumb-section .arrow-icon');
6252    var steps_mobile = breadcrumb_mobile.children().find('.breadcrumb-mobile-section a.breadcrumb-mobile-text');
6253    var steps_mobile_section = breadcrumb_mobile.children().find('.breadcrumb-mobile-section');
6254    var steps_mobile_circle = breadcrumb_mobile.children().find('.breadcrumb-mobile-section .breadcrumb-mobile-circle');
6255    var active_step = breadcrumb.children().find('.active');
6256
6257    var page = $('#jca-identifier-page').val();
6258
6259    if (formData) {
6260      switch (page) {
6261        case 'jca-costumer-registration-page-flow':
6262          // $(active_step).removeClass('active')
6263          $(steps_mobile_circle[0]).addClass('previous');
6264          $(steps_mobile_circle[1]).addClass('active');
6265          $(steps_mobile_section[1]).addClass('active');
6266          $(steps_mobile[1]).addClass('active');
6267          $(steps[0]).addClass('active');
6268          $(stepsArrow[0]).addClass('active');
6269          $(steps[1]).addClass('active');
6270          $(stepsArrow[1]).addClass('active');
6271
6272          // Hide optional form in register page during payment workflow
6273          if ($('[data-js="register-form"]').is(':visible')) {
6274            $('[data-js="register-form"]').find('.optional-data-container').hide();
6275          }
6276
6277          break;
6278        case 'jca-search-result-page':
6279          // $(active_step).removeClass('active')
6280          $(steps_mobile[0]).addClass('active');
6281          $(steps_mobile_section[0]).addClass('active');
6282          $(steps_mobile_circle[0]).addClass('active');
6283          $(steps[0]).addClass('active');
6284          break;
6285        case 'jca-login-page':
6286        case 'jca-costumer-registration-page':
6287        case 'jca-register-passengers-page':
6288          $(steps_mobile_circle[0]).addClass('previous');
6289          $(steps_mobile_circle[1]).addClass('active');
6290          $(steps_mobile_section[1]).addClass('active');
6291          $(steps_mobile[1]).addClass('active');
6292          $(steps[0]).addClass('active');
6293          $(stepsArrow[0]).addClass('active');
6294          $(steps[1]).addClass('active');
6295          $(stepsArrow[1]).addClass('active');
6296
6297          // Hide optional form in register page during payment workflow
6298          if ($('[data-js="register-form"]').is(':visible')) {
6299            $('[data-js="register-form"]').find('.optional-data-container').hide();
6300          }
6301
6302          break;
6303        case 'jca-seat-reservation-page':
6304          $(steps_mobile_circle[0]).addClass('previous');
6305          $(steps_mobile_circle[1]).addClass('previous');
6306          $(steps_mobile_circle[2]).addClass('active');
6307          $(steps_mobile_section[2]).addClass('active');
6308          $(steps_mobile[2]).addClass('active');
6309          $(steps[0]).addClass('active');
6310          $(steps[1]).addClass('active');
6311          $(steps[2]).addClass('active');
6312          $(stepsArrow[0]).addClass('active');
6313          $(stepsArrow[1]).addClass('active');
6314          $(stepsArrow[2]).addClass('active');
6315          break;
6316        case 'jca-payment-page':
6317          $(steps_mobile_circle[0]).addClass('previous');
6318          $(steps_mobile_circle[1]).addClass('previous');
6319          $(steps_mobile_circle[2]).addClass('previous');
6320          $(steps_mobile_circle[3]).addClass('active');
6321          $(steps_mobile_section[3]).addClass('active');
6322          $(steps_mobile[3]).addClass('active');
6323          $(steps[0]).addClass('active');
6324          $(steps[1]).addClass('active');
6325          $(steps[2]).addClass('active');
6326          $(steps[3]).addClass('active');
6327          $(stepsArrow[0]).addClass('active');
6328          $(stepsArrow[1]).addClass('active');
6329          $(stepsArrow[2]).addClass('active');
6330          $(stepsArrow[3]).addClass('active');
6331          break;
6332        case 'jca-checkout-bank-page':
6333          // $(active_step).removeClass('active')
6334          $(steps_mobile_circle[0]).addClass('previous');
6335          $(steps_mobile_circle[1]).addClass('previous');
6336          $(steps_mobile_circle[2]).addClass('previous');
6337          $(steps_mobile_circle[3]).addClass('previous');
6338          $(steps_mobile_circle[4]).addClass('active');
6339          $(steps_mobile_section[4]).addClass('active');
6340          $(steps_mobile[4]).addClass('active');
6341          $(steps[0]).addClass('active');
6342          $(steps[1]).addClass('active');
6343          $(steps[2]).addClass('active');
6344          $(steps[3]).addClass('active');
6345          $(steps[4]).addClass('active');
6346          $(stepsArrow[0]).addClass('active');
6347          $(stepsArrow[1]).addClass('active');
6348          $(stepsArrow[2]).addClass('active');
6349          $(stepsArrow[3]).addClass('active');
6350          $(stepsArrow[4]).addClass('active');
6351          break;
6352        case 'jca-checkout-pix-page':
6353          $(steps_mobile_circle[0]).addClass('previous');
6354          $(steps_mobile_circle[1]).addClass('previous');
6355          $(steps_mobile_circle[2]).addClass('previous');
6356          $(steps_mobile_circle[3]).addClass('previous');
6357          $(steps_mobile_circle[4]).addClass('active');
6358          $(steps_mobile_section[4]).addClass('active');
6359          $(steps_mobile[4]).addClass('active');
6360          $(steps[0]).addClass('active');
6361          $(steps[1]).addClass('active');
6362          $(steps[2]).addClass('active');
6363          $(steps[3]).addClass('active');
6364          $(steps[4]).addClass('active');
6365          $(stepsArrow[0]).addClass('active');
6366          $(stepsArrow[1]).addClass('active');
6367          $(stepsArrow[2]).addClass('active');
6368          $(stepsArrow[3]).addClass('active');
6369          $(stepsArrow[4]).addClass('active');
6370          break;
6371        case 'jca-checkout-livelo-page':
6372          // $(active_step).removeClass('active')
6373          $(steps_mobile_circle[0]).addClass('previous');
6374          $(steps_mobile_circle[1]).addClass('previous');
6375          $(steps_mobile_circle[2]).addClass('previous');
6376          $(steps_mobile_circle[3]).addClass('previous');
6377          $(steps_mobile_circle[4]).addClass('active');
6378          $(steps_mobile_section[4]).addClass('active');
6379          $(steps_mobile[4]).addClass('active');
6380          $(steps[0]).addClass('active');
6381          $(steps[1]).addClass('active');
6382          $(steps[2]).addClass('active');
6383          $(steps[3]).addClass('active');
6384          $(steps[4]).addClass('active');
6385          $(stepsArrow[0]).addClass('active');
6386          $(stepsArrow[1]).addClass('active');
6387          $(stepsArrow[2]).addClass('active');
6388          $(stepsArrow[3]).addClass('active');
6389          $(stepsArrow[4]).addClass('active');
6390          break;
6391        case 'jca-checkout-page':
6392          // $(active_step).removeClass('active')
6393          $(steps_mobile_circle[0]).addClass('previous');
6394          $(steps_mobile_circle[1]).addClass('previous');
6395          $(steps_mobile_circle[2]).addClass('previous');
6396          $(steps_mobile_circle[3]).addClass('previous');
6397          $(steps_mobile_circle[4]).addClass('active');
6398          $(steps_mobile_section[4]).addClass('active');
6399          $(steps_mobile[4]).addClass('active');
6400          $(steps[0]).addClass('active');
6401          $(steps[1]).addClass('active');
6402          $(steps[2]).addClass('active');
6403          $(steps[3]).addClass('active');
6404          $(steps[4]).addClass('active');
6405          $(stepsArrow[0]).addClass('active');
6406          $(stepsArrow[1]).addClass('active');
6407          $(stepsArrow[2]).addClass('active');
6408          $(stepsArrow[3]).addClass('active');
6409          $(stepsArrow[4]).addClass('active');
6410          break;
6411        default:
6412          breadcrumb.hide();
6413          break;
6414      }
6415    }
6416  }, 500);
6417  var page = $('#jca-identifier-page').val();
6418  var hicons = $('[data-js="header-icons"]');
6419  var cartIcon = $('[data-js="cart-btn"]');
6420
6421  switch (page) {
6422    case 'jca-search-result-page':
6423      cartIcon.hide();
6424      hicons.show();
6425      break;
6426    case 'jca-login-page':
6427    case 'jca-costumer-registration-page':
6428    case 'jca-costumer-registration-confirm-page':
6429    case 'jca-costumer-registration-return-page':
6430    case 'jca-register-passengers-page':
6431      $('[data-js="nav-button-logout"]').css('right', '40px');
6432      cartIcon.show();
6433      hicons.show();
6434      break;
6435    case 'jca-seat-reservation-page':
6436      $('[data-js="nav-button-logout"]').css('right', '40px');
6437      cartIcon.show();
6438      hicons.show();
6439      break;
6440    case 'jca-payment-page':
6441      $('[data-js="nav-button-logout"]').css('right', '40px');
6442      cartIcon.show();
6443      hicons.show();
6444      break;
6445    case 'jca-edit-costumer-registration-page':
6446      cartIcon.hide();
6447      hicons.show();
6448      break;
6449    case 'jca-checkout-page':
6450      hicons.hide();
6451      break;
6452    case 'jca-update-password-page':
6453      cartIcon.hide();
6454      hicons.show();
6455      break;
6456    case 'wemobi-update-password-page':
6457      cartIcon.hide();
6458      hicons.show();
6459      break;
6460    default:
6461      hicons.show();
6462      break;
6463  }
6464
6465  // removing link titles
6466  $(document).ready(function () {
6467    $('.nav-link, .dropdown-item').hover(function () {
6468      $(this).attr('tooltip-data', $(this).attr('titl'));
6469      $(this).removeAttr('title');
6470    }, function () {
6471      $(this).attr('title', $(this).attr('tooltip-data'));
6472      $(this).removeAttr('tooltip-data');
6473    });
6474    if ($('.breadcrumb-mobile-text.active') && $('.breadcrumb-mobile-text.active').text()) {
6475      try {
6476        var currentBreadcrumbLabel = $('.breadcrumb-mobile-text.active').text().trim();
6477        if (currentBreadcrumbLabel) {
6478          var length = currentBreadcrumbLabel.length;
6479          if (length > 14) $('.breadcrumb-mobile-text.active').css('font-size', '9px')
6480        }
6481      } catch (error) { }
6482    }
6483  });
6484})(jQuery);
6485
6486/**
6487 * MAIN
6488 *
6489 */
6490'use strict';
6491
6492var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
6493
6494function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6495
6496var PopOver = function () {
6497  function PopOver() {
6498    _classCallCheck(this, PopOver);
6499  }
6500
6501  _createClass(PopOver, null, [{
6502    key: 'show',
6503    value: function show() {
6504      var location = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'right';
6505
6506      var options = {
6507        container: 'body',
6508        placement: function placement() {
6509          var windowSize = Utils.getWindowSize();
6510          var width = windowSize.width;
6511          if (width <= windowSize.breakpoints.LG) return 'top';
6512          return location;
6513        }
6514      };
6515
6516      var selectors = '#extra-time-input, #img-best-price, #img-class-detail';
6517      var elements = document.querySelectorAll(selectors);
6518
6519      elements.forEach(function (el) {
6520        var instance = new bootstrap.Popover(el, {
6521          container: 'body',
6522          placement: options.placement,
6523          trigger: 'manual'
6524        });
6525
6526        el.addEventListener('mouseenter', function () {
6527          instance.show();
6528        });
6529
6530        el.addEventListener('mouseleave', function () {
6531          instance.hide();
6532        });
6533      });
6534    }
6535  }]);
6536
6537  return PopOver;
6538}();
6539"use strict";
6540
6541var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
6542
6543function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6544
6545/**
6546 * MAIN
6547 *
6548 * INICIO LOGICA STORAGE
6549 *
6550*/
6551
6552var SessionStorage = function () {
6553  function SessionStorage() {
6554    _classCallCheck(this, SessionStorage);
6555  }
6556
6557  _createClass(SessionStorage, null, [{
6558    key: "get",
6559    value: function get(name) {
6560      var value = window.sessionStorage.getItem(name);
6561      if (value instanceof Object) return value;
6562      return JSON.parse(value);
6563    }
6564  }, {
6565    key: "set",
6566    value: function set(name, data) {
6567      window.sessionStorage.setItem(name, JSON.stringify(data));
6568    }
6569  }, {
6570    key: "remove",
6571    value: function remove(name) {
6572      window.sessionStorage.removeItem(name);
6573    }
6574  }]);
6575
6576  return SessionStorage;
6577}();
6578
6579/**
6580 * MAIN
6581 *
6582 * FIM LOGICA STORAGE
6583 *
6584*/
6585'use strict';
6586
6587var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
6588
6589function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6590
6591/**
6592 * MAIN
6593 *
6594 */
6595var Utils = function () {
6596  function Utils() {
6597    _classCallCheck(this, Utils);
6598  }
6599
6600  _createClass(Utils, null, [{
6601    key: 'getFirstName',
6602    value: function getFirstName(str) {
6603      // no last name
6604      if (!str.includes(' ')) {
6605        return str;
6606      }
6607
6608      return str.substr(0, str.trim().indexOf(' '));
6609    }
6610  }, {
6611    key: "validEmail",
6612    value: function validEmail(email) {
6613      return (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
6614      );
6615    }
6616  }, {
6617    key: 'validateCardNumber',
6618    value: function validateCardNumber(cardNumber) {
6619      var cleanedCardNumber = cardNumber.toString().replace(/\s/g, '');
6620
6621      // Expressões regulares para verificar o tipo de cartão
6622      var visaRegex = /^4[0-9]{12}(?:[0-9]{3})?$/;
6623      var mastercardRegex = /^5[1-5][0-9]{14}$/;
6624      var newMasterCardRegex = /^2[1-5][0-9]{14}$/;
6625      var amexRegex = /^3[47][0-9]{13}$/;
6626      var discoverRegex = /^6(?:011|5[0-9]{2})[0-9]{12}$/;
6627      var eloRegex = /^(?:636368|438935|504175|451416|636297)\d{10}$/;
6628      var dinersRegex = /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/;
6629      var jcbRegex = /^(?:2131|1800|35\d{3})\d{11}$/;
6630      var vrRegex = /^627416[0-9]{10}$/;
6631      var sodexoRegex = /^606070[0-9]{10}$/;
6632      var hipercard = /^(606282\d{10}(\d{3})?)|(3841\d{15})$/;
6633
6634      // Verifica o tipo de cartão com base nas expressões regulares
6635      if (visaRegex.test(cleanedCardNumber) && cleanedCardNumber.length === 13 || visaRegex.test(cleanedCardNumber) && cleanedCardNumber.length === 16) {
6636        return true;
6637      } else if ((mastercardRegex.test(cleanedCardNumber) || newMasterCardRegex.test(cleanedCardNumber)) && cleanedCardNumber.length === 16) {
6638        return true;
6639      } else if (amexRegex.test(cleanedCardNumber) && cleanedCardNumber.length === 15) {
6640        return true;
6641      } else if (discoverRegex.test(cleanedCardNumber) && cleanedCardNumber.length === 16) {
6642        return true;
6643      } else if (eloRegex.test(cleanedCardNumber) && cleanedCardNumber.length === 16) {
6644        return true;
6645      } else if (dinersRegex.test(cleanedCardNumber) && cleanedCardNumber.length === 14) {
6646        return true;
6647      } else if (jcbRegex.test(cleanedCardNumber) && cleanedCardNumber.length === 16) {
6648        return true;
6649      } else if (vrRegex.test(cleanedCardNumber) && cleanedCardNumber.length === 16) {
6650        return true;
6651      } else if (sodexoRegex.test(cleanedCardNumber) && cleanedCardNumber.length === 16) {
6652        return true;
6653      } else if (hipercard.test(cleanedCardNumber) && cleanedCardNumber.length === 16) {
6654        return true;
6655      } else {
6656        return false;
6657      }
6658    }
6659  }, {
6660    key: "validateCVV",
6661    value: function validateCVV(cvv) {
6662      var regex = /^[0-9]{3,4}$/;
6663      return regex.test(cvv);
6664    }
6665  }, {
6666    key: "getOwnerId",
6667    value: function validEmail(id) {
6668      var splitId = id.split("/");
6669      var ownerId = null;
6670
6671      if (splitId.length > 0) {
6672        ownerId = splitId[splitId.length - 1];
6673      }
6674
6675      return ownerId;
6676    }
6677  }, {
6678    key: "isEmptyObj",
6679    value: function isEmptyObj(obj) {
6680      for (var prop in obj) {
6681        if (obj.hasOwnProperty(prop)) return false;
6682      }
6683
6684      return true;
6685    }
6686  }, {
6687    key: 'getFamilyName',
6688    value: function getFamilyName(str) {
6689      return str.substring(str.indexOf(' '), str.length).trim();
6690    }
6691  }, {
6692    key: 'getSiteName',
6693    value: function getSiteName() {
6694      var siteId = $('#siteName').val();
6695
6696      if (siteId === 'rapidoribeirao') {
6697        return "RápidoRibeirão";
6698      } else if (siteId === 'catarinense') {
6699        return "Catarinense";
6700      } else if (siteId === '1001') {
6701        return "1001"
6702      } else if (siteId === 'expressodosul') {
6703        return "ExpressodoSul"
6704      } else if (siteId === 'cometa') {
6705        return "Cometa"
6706      }
6707    }
6708  }, {
6709    key: 'getCompanyId',
6710    value: function getCompanyId() {
6711      var siteComparationName = this.getSiteName();
6712      var companyId = this.getCompanyInfo(siteComparationName).id;
6713
6714      return companyId;
6715    }
6716  }, {
6717    key: "getCompanyInfo",
6718    value: function getCompanyInfo(siteName) {
6719      var companyEmpresas = [{
6720        id: 2,
6721        nameService: "1001"
6722      }, {
6723        id: 3,
6724        nameService: "Catarinense"
6725      }, {
6726        id: 4,
6727        nameService: "ExpressodoSul"
6728      }, {
6729        id: 6,
6730        nameService: "RápidoRibeirão"
6731      }, {
6732        id: 7,
6733        nameService: "Cometa"
6734      }];
6735
6736      var companyInfo = companyEmpresas.find(function (company) {
6737        return company.nameService === siteName;
6738      });
6739
6740      return companyInfo;
6741    }
6742  }, {
6743    key: "getChannelTitle",
6744    value: function getChannelTitle(isPaymentWhatsapp, saleplatform) {
6745      if (isPaymentWhatsapp) {
6746        return 'wpp';
6747      } else if (saleplatform) {
6748        if (saleplatform === 'APP') {
6749          return saleplatform.toLowerCase();
6750        }
6751      }
6752      return 'site';
6753    }
6754  }, {
6755    key: 'getSiteNameForClasses',
6756    value: function getSiteName() {
6757      var siteId = $('#siteName').val();
6758
6759      if (siteId === 'rapidoribeirao') {
6760        return "rapido-ribeirao";
6761      } else if (siteId === 'catarinense') {
6762        return "catarinense";
6763      } else if (siteId === '1001') {
6764        return "viacao1001"
6765      } else if (siteId === 'expressodosul') {
6766        return "expresso-sul"
6767      } else if (siteId === 'cometa') {
6768        return "cometa"
6769      }
6770    }
6771  }, {
6772    key: 'capitalize',
6773    value: function capitalize(str, separator) {
6774      if (!str) {
6775        return '';
6776      }
6777
6778      var isPreposition = function isPreposition(str) {
6779        return ["DE", "DO", "DA", "DOS", "DAS"].includes(str);
6780      };
6781
6782      var strArray = str.split(separator ? separator : " ").filter(
6782Boolean);
6783      var regex = /\(/ig;
6784
6785      for (var i = 0; i < strArray.length; i++) {
6786        if (!isPreposition(strArray[i])) {
6787          if (strArray[i].charAt(0).match(regex)) strArray[i] = "(" + strArray[i].charAt(1).toUpperCase() + strArray[i].slice(2).toLowerCase(); else strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].slice(1).toLowerCase();
6788        } else {
6789          strArray[i] = strArray[i].toLowerCase();
6790        }
6791      }
6792
6793      return strArray.join(separator ? separator : " ");
6794    }
6795  }, {
6796    key: 'splitLocation',
6797    value: function splitLocation(location) {
6798      var hiphenUnicodes = [8211, 8208, 8209, 8210, 8212, 8213];
6799      for (var i = 0; i < location.length; i++) {
6800        if (hiphenUnicodes.includes(location.charCodeAt(i))) {
6801          location = location.replace(location[i], '-');
6802        }
6803      }
6804      return location.split('-');
6805    }
6806  }, {
6807    key: 'isScrolledIntoView',
6808    value: function isScrolledIntoView($elem) {
6809      var $window = $(window);
6810
6811      var docViewTop = $window.scrollTop();
6812      var docViewBottom = docViewTop + $window.height();
6813
6814      var elemTop = $elem.offset() ? $elem.offset().top : 0;
6815      var elemBottom = elemTop + $elem.height();
6816
6817      return elemBottom <= docViewBottom && elemTop >= docViewTop;
6818    }
6819  }, {
6820    key: 'scrollDown',
6821    value: function scrollDown() {
6822      var elem = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "html, body";
6823
6824      $(elem).scrollTop($(document).height());
6825    }
6826  }, {
6827    key: 'scrollTop',
6828    value: function scrollTop() {
6829      var elem = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "html, body";
6830
6831      window.scroll({
6832        top: 0,
6833        behavior: 'smooth'
6834      });
6835      // $(elem).animate({
6836      //   scrollTop: 0
6837      // }, "fast")
6838    }
6839  }, {
6840    key: "parseAddress",
6841    value: function parseAddress(data) {
6842      var addresses = new Address();
6843      addresses.zipCode = data.zipCode;
6844      addresses.street = data.street;
6845      addresses.complement = data.complement;
6846      addresses.neighborhood = data.neighborhood;
6847      addresses.city = data.city;
6848      addresses.state = data.state;
6849      addresses.number = data.number;
6850      return addresses;
6851    }
6852  }, {
6853    key: 'formatPrice',
6854    value: function formatPrice(price) {
6855      if (price === 0) return "0,00"; else {
6856        //Converting float to string and taking the numbers before and after the dot
6857        var priceStringArray = price.toFixed(2).toString().split(".");
6858        var integerPart = priceStringArray[0];
6859        var floatPart = priceStringArray[1];
6860        if (floatPart) {
6861          //Preppending a 0 if the float part only has one digit
6862          floatPart = floatPart.charAt(1) ? floatPart : floatPart + "0";
6863        }
6864        //If the float part is undefined, set it as 00
6865        else floatPart = "00";
6866        //Logic to input dots every three digits
6867        var count = 0;
6868        var onlyNumbers = new RegExp(/^\d+$/);
6869        for (var i = integerPart.length - 1; i > 0; i--) {
6870          count++;
6871          if (count === 3 && onlyNumbers.test(integerPart[0])) {
6872            count = 0;
6873            integerPart = integerPart.slice(0, i) + "." + integerPart.slice(i);
6874          }
6875        }
6876        //Setting price separating integer and float parts by a comma
6877        return integerPart + "," + floatPart;
6878      }
6879    }
6880  }, {
6881    key: 'groupArrayBy',
6882    value: function groupArrayBy(array, prop) {
6883      return array.reduce(function (groups, item, idx) {
6884        var val = item[prop];
6885        groups[val] = groups[val] || [];
6886        groups[val].push(item);
6887        return groups;
6888      }, {});
6889    }
6890  }, {
6891    key: "sortArray",
6892    value: function sortArray(array) {
6893      return array.sort(function (first, second) {
6894        var a = first.departureDate;
6895        var b = second.departureDate;
6896        if (a > b) {
6897          return 1;
6898        } else if (a < b) {
6899          return -1;
6900        } else {
6901          return 0;
6902        }
6903      });
6904    }
6905  }, {
6906    key: 'sortArrayReverse',
6907    value: function sortArrayReverse(array) {
6908      return array.sort(function (first, second) {
6909        var a = first[0].departureDate;
6910        var b = second[0].departureDate;
6911        if (a < b) {
6912          return 1;
6913        } else if (a > b) {
6914          return -1;
6915        } else {
6916          return 0;
6917        }
6918      });
6919    }
6920  }, {
6921    key: "conditionTernary",
6922    value: function conditionTernary(condition) {
6923      var errorCondition = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
6924
6925      return condition ? condition : errorCondition;
6926    }
6927  }, {
6928    key: "sortArrayResultsWay",
6929    value: function sortArrayResultsWay(objResult) {
6930      var date = objResult.date,
6931        servicesList = objResult.servicesList;
6932
6933      var arraySortResult = this.sortArray(servicesList);
6934      var originObj = this.conditionTernary(objResult.origin);
6935      var destinationObj = this.conditionTernary(objResult.destination);
6936
6937      return {
6938        date: date,
6939        origin: originObj,
6940        destination: destinationObj,
6941        servicesList: arraySortResult
6942      };
6943    }
6944  }, {
6945    key: 'convertSecundsToMinuts',
6946    value: function convertSecundsToMinuts(secunds) {
6947      return Math.floor(secunds / 60);
6948    }
6949  }, {
6950    key: 'getWindowSize',
6951    value: function getWindowSize() {
6952      var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
6953
6954      var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
6955
6956      return {
6957        width: width,
6958        height: height,
6959        breakpoints: { // Breakpoints according to the variables.sass values
6960          XS: 320,
6961          SM: 425,
6962          MD: 768,
6963          LG: 950,
6964          LGR: 992,
6965          XL: 1200,
6966          XXL: 1400
6967        }
6968      };
6969    }
6970  }, {
6971    key: 'getCurrentLang',
6972    value: function getCurrentLang() {
6973      return $('html').attr('lang') ? $('html').attr('lang').toLowerCase() : 'pt-br';
6974    }
6975  }, {
6976    key: "checkWalletGroup",
6977    value: function checkWalletGroup() {
6978      var passenger = SessionStorage.get('passenger');
6979
6980      if (!passenger) {
6981        if ((!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false')) {
6982          localStorage.setItem("referrer", $(location).attr('href'));
6983          $(location).attr('href', $('#loginPage').val());
6984        }
6985      }
6986
6987      if (!passenger._groups || !passenger._groups.split(',').map(function (group) {
6988        return group.trim();
6989      }).includes('wallet')) {
6990        $(location).attr('href', $('#homePagePath').val());
6991      }
6992    }
6993  }, {
6994    key: "listenRedirectWallet",
6995    value: function listenRedirectWallet() {
6996      $('[data-js="wallet-giro"]').on('click', function () {
6997        var walletExists = SessionStorage.get('walletExists');
6998        var userWallet = SessionStorage.get('user_wallet');
6999
7000        if (walletExists === false && !userWallet) {
7001          $(location).attr('href', $('#walletTermosPagePath').val());
7002        }
7003
7004        if (walletExists === true && userWallet) {
7005          $(location).attr('href', $('#walletHomePagePath').val());
7006        }
7007
7008        if (walletExists === true && !userWallet) {
7009          $(location).attr('href', $('#walletLoginPagePath').val());
7010        }
7011      });
7012    }
7013  }, {
7014    key: 'roundFloatToPrice',
7015    value: function roundFloatToPrice(value) {
7016      return parseFloat(value.toFixed(2));
7017    }
7018  }, {
7019    key: 'parseDateDeepLinkFormat',
7020    value: function parseDateDeepLinkFormat(date) {
7021      if (date && date.length == 8) {
7022        var day = date.split('')[0] + date.split('')[1];
7023        var month = date.split('')[2] + date.split('')[3];
7024        var year = date.split('')[4] + date.split('')[5] + date.split('')[6] + date.split('')[7];
7025        return year + '-' + month + '-' + day;
7026      }
7027      return date;
7028    }
7029  }, {
7030    key: 'parseToDayMonthYearFormat',
7031    value: function parseToDayMonthYearFormat(date) {
7032      if (date && date.length === 10) {
7033        date = date.split('-');
7034        var day = date[2];
7035        var month = date[1];
7036        var year = date[0];
7037        return day + month + year;
7038      }
7039    }
7040  }, {
7041    key: 'getBankImage',
7042    value: function getBankImage(bankName) {
7043      return {
7044        'banco_do_brasil': 'banco_do_brasil.png',
7045        'bradesco': 'bradesco.png',
7046        'itau': 'itau.png',
7047        'bs2': 'bs2.png',
7048        'original': 'original.png',
7049        'caixa': 'caixa.png',
7050        'santander': 'santander.png',
7051        'inter': 'inter.png'
7052      }[bankName] || 'bradesco.png';
7053    }
7054  }, {
7055    key: 'removeEmptyAttributes',
7056    value: function removeEmptyAttributes(chosenObject) {
7057      Object.keys(chosenObject).forEach(function (key) {
7058        return chosenObject[key] === undefined ? delete chosenObject[key] : '';
7059      });
7060    }
7061  }, {
7062    key: 'keyIsNumber',
7063    value: function keyIsNumber(key) {
7064      return key >= 48 && key <= 57;
7065    }
7066  }, {
7067    key: 'keyIsUppercase',
7068    value: function keyIsUppercase(key) {
7069      return key >= 65 && key <= 90;
7070    }
7071  }, {
7072    key: 'keyIsLowerCase',
7073    value: function keyIsLowerCase(key) {
7074      return key >= 97 && key <= 122;
7075    }
7076  }, {
7077    key: 'keyIsDigit',
7078    value: function keyIsDigit(key) {
7079      return Utils.keyIsLowerCase(key) || Utils.keyIsUppercase(key) || Utils.keyIsNumber(key);
7080    }
7081  }, {
7082    key: 'setCookie',
7083    value: function setCookie(cookieName, cookieData, cookieExpires) {
7084      var stringfiedData = JSON.stringify(cookieData);
7085      document.cookie = cookieName + '=' + encodeURIComponent(stringfiedData) + '; expires=' + cookieExpires;
7086    }
7087  }, {
7088    key: 'decodeCookie',
7089    value: function decodeCookie(cookieName) {
7090      var cookieArray = decodeURIComponent(document.cookie).split(';');
7091      for (var i = 0; i < cookieArray.length; i++) {
7092        var cookieDataArray = cookieArray[i].split('=');
7093        if (cookieDataArray[0].trim() == cookieName) {
7094          var cookieData = JSON.parse(cookieDataArray[1]);
7095          return cookieData;
7096        }
7097      }
7098    }
7099  }, {
7100    key: 'areAllDigitsTheSame',
7101    value: function areAllDigitsTheSame(sequence) {
7102      var first = sequence[0];
7103      for (var i = 1; i < sequence.length; i++) {
7104        var digit = sequence[i];
7105        if (digit !== first) return false;
7106      }
7107      return true;
7108    }
7109  }, {
7110    key: 'validateCNPJ',
7111    value: function validateCNPJ(cnpj) {
7112      if (Utils.areAllDigitsTheSame(cnpj)) return false; else {
7113        var firstPassWeight = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
7114        var secondPassWeight = [].concat(6, firstPassWeight);
7115        var firstPass = 0,
7116          secondPass = 0;
7117        var verifiedDigits = [];
7118        for (var i = 0; i < firstPassWeight.length; i++) {
7119          firstPass += firstPassWeight[i] * parseInt(cnpj[i]);
7120        } for (var _i = 0; _i < secondPassWeight.length; _i++) {
7121          secondPass += secondPassWeight[_i] * parseInt(cnpj[_i]);
7122        } verifiedDigits.push(firstPass % 11 < 2 ? 0 : 11 - firstPass % 11);
7123        verifiedDigits.push(secondPass % 11 < 2 ? 0 : 11 - secondPass % 11);
7124        return verifiedDigits[0] === parseInt(cnpj[12]) && verifiedDigits[1] === parseInt(cnpj[13]);
7125      }
7126    }
7127  }, {
7128    key: 'validateCPF',
7129    value: function validateCPF(cpf) {
7130      if (Utils.areAllDigitsTheSame(cpf)) return false; else {
7131        var firstPass = 0,
7132          secondPass = 0;
7133        var verifiedDigits = [];
7134        for (var i = 0; i < 9; i++) {
7135          firstPass += (10 - i) * parseInt(cpf[i]);
7136        } for (var _i2 = 0; _i2 < 10; _i2++) {
7137          secondPass += (11 - _i2) * parseInt(cpf[_i2]);
7138        } verifiedDigits.push(11 - firstPass % 11 > 9 ? 0 : 11 - firstPass % 11);
7139        verifiedDigits.push(11 - secondPass % 11 > 9 ? 0 : 11 - secondPass % 11);
7140        return verifiedDigits[0] === parseInt(cpf[9]) && verifiedDigits[1] === parseInt(cpf[10]);
7141      }
7142    }
7143  }, {
7144    key: 'luhn',
7145    value: function luhn(sequence) {
7146      var acc = 0;
7147      var lastDigit = parseInt(sequence[sequence.length - 1]);
7148      var shouldSumRegularValue = false;
7149      for (var i = sequence.length - 2; i >= 0; i--) {
7150        var value = parseInt(sequence[i]);
7151        if (!shouldSumRegularValue) {
7152          var doubleVal = 2 * value;
7153          var units = doubleVal % 10;
7154          var tens = parseInt(doubleVal / 10);
7155          acc += units + tens;
7156        } else acc += value;
7157        shouldSumRegularValue = !shouldSumRegularValue;
7158      }
7159      return 9 * acc % 10 === lastDigit;
7160    }
7161  }, {
7162    key: 'getSeatPassengers',
7163    value: function getSeatPassengers(passengersArray) {
7164      return passengersArray.reduce(function (acc, passType) {
7165        if (passType.type !== 'CHILD') acc = acc + parseInt(passType.quantity);
7166
7167        return acc;
7168      }, 0);
7169    }
7170  }, {
7171    key: 'getPassengersQuantity',
7172    value: function getPassengersQuantity(passengersArray) {
7173      return passengersArray.reduce(function (acc, passType) {
7174        return acc + parseInt(passType.quantity);
7175      }, 0);
7176    }
7177  }, {
7178    key: 'isMobile',
7179    value: function isMobile() {
7180      return Utils.getWindowSize().width <= Utils.getWindowSize().breakpoints.LG;
7181    }
7182  }, {
7183    key: 'addInvalidClass',
7184    value: function addInvalidClass(el, msg, tip) {
7185      var $links = el.parent().siblings().find('.link');
7186      if (!this.isSelectCustom(el)) $(el).addClass("invalid"); else $(el).siblings('.select-selected').addClass('invalid');
7187      if (tip && tip.hasClass('warning')) {
7188        if (msg) tip.text(msg);
7189        tip.fadeIn();
7190        $links.hide();
7191      }
7192    }
7193  }, {
7194    key: 'removeInvalidClass',
7195    value: function removeInvalidClass(el, tip) {
7196      var $links = el.parent().siblings().find('.link');
7197      if (!this.isSelectCustom(el)) $(el).removeClass("invalid"); else $(el).siblings('.select-selected').removeClass('invalid');
7198      if (tip && tip.hasClass('warning')) {
7199        tip.fadeOut();
7200        $links.show();
7201      }
7202    }
7203  }, {
7204    key: 'isSelectCustom',
7205    value: function isSelectCustom(el) {
7206      return $(el).attr('data-js') === 'input-doc-type' || $(el).attr('data-js') === 'input-phone-type';
7207    }
7208  }, {
7209    key: 'getDeviceOS',
7210    value: function getDeviceOS() {
7211      var userAgent = window.navigator.userAgent,
7212        platform = window.navigator.platform,
7213        macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
7214        windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
7215        iosPlatforms = ['iPhone', 'iPad', 'iPod'],
7216        os = null;
7217
7218      if (macosPlatforms.indexOf(platform) !== -1) {
7219        os = 'MACOS';
7220      } else if (iosPlatforms.indexOf(platform) !== -1) {
7221        os = 'IOS';
7222      } else if (windowsPlatforms.indexOf(platform) !== -1) {
7223        os = 'WINDOWS';
7224      } else if (/Android/.test(userAgent)) {
7225        os = 'ANDROID';
7226      } else if (!os && /Linux/.test(platform)) {
7227        os = 'LINUX';
7228      }
7229
7230      return os;
7231    }
7232  }, {
7233    key: 'getDevice',
7234    value: function getDevice() {
7235      return /Mobi|Android/i.test(navigator.userAgent) ? 'mobile' : 'desktop';
7236    }
7237  }, {
7238    key: 'getPromotionParam',
7239    value: function getPromotionParam(sParam) {
7240      var sPageURL = window.location.search.substring(1);
7241      var sURLVariables = sPageURL ? sPageURL.split('&') : SessionStorage.get('deepLinkParameters');
7242      if (sURLVariables != null) {
7243        for (var i = 0; i < sURLVariables.length; i++) {
7244          var sParameterName = sURLVariables[i].split("=");
7245          if (sParameterName[0] == sParam) return sParameterName[1];
7246        }
7247      }
7248    }
7249  }, {
7250    key: 'removeBodyOverFlow',
7251    value: function removeBodyOverFlow() {
7252      if (Utils.isMobile()) {
7253        $('html, body').css('overflow-y', 'hidden');
7254      }
7255    }
7256  }, {
7257    key: "replaceToNumbers",
7258    value: function replaceToNumbers(replaceNum) {
7259      return replaceNum.replace(/\D/g, '');
7260    }
7261  }, {
7262    key: 'addBodyOverFlow',
7263    value: function addBodyOverFlow() {
7264      if (Utils.isMobile()) {
7265        $('html, body').css('overflow-y', 'auto');
7266      }
7267    }
7268  }, {
7269    key: 'renderCreditCardImage',
7270    value: function renderCreditCardImage(card) {
7271      if ($('[data-card-id="' + card + '"]').length > 0) {
7272        return $('[data-card-id="' + card + '"]').attr('src');
7273      } else {
7274        return '/etc.clientlibs/wemobi/clientlibs/clientlib-site/resources/images/generic-card-icon.png';
7275      }
7276      /*return {
7277        visa: 'visa.png',
7278        mc: 'masterCard.png',
7279        elo: 'elo.png',
7280        hipercard: 'hipercard.png'
7281      }[card];*/
7282    }
7283  }, {
7284    key: 'verifiedState',
7285    value: function verifiedState(uf) {
7286      return {
7287        'AC': 'Acre',
7288        'AL': 'Alagoas',
7289        'AP': 'Amapá',
7290        'AM': 'Amazonas',
7291        'BA': 'Bahia',
7292        'CE': 'Ceará',
7293        'DF': 'Distrito Federal',
7294        'ES': 'Espírito Santo',
7295        'GO': 'Goiás',
7296        'MA': 'Maranhão',
7297        'MT': 'Mato Grosso',
7298        'MS': 'Mato Grosso do Sul',
7299        'MG': 'Minas Gerais',
7300        'PA': 'Pará',
7301        'PB': 'Paraíba',
7302        'PR': 'Paraná',
7303        'PE': 'Pernambuco',
7304        'PI': 'Piauí',
7305        'RJ': 'Rio de Janeiro',
7306        'RN': 'Rio Grande do Norte',
7307        'RS': 'Rio Grande do Sul',
7308        'RO': 'Rondônia',
7309        'RR': 'Roraima',
7310        'SC': 'Santa Catarina',
7311        'SP': 'São Paulo',
7312        'SE': 'Sergipe',
7313        'TO': 'Tocantins',
7314        'ASS': 'PY - Paraguay',
7315        'PY': 'Paraguay'
7316      }[uf];
7317    }
7318  }, {
7319    key: "formatDateToISO",
7320    value: function formatDateToISO(dateString) {
7321      if (dateString.includes('T')) {
7322        dateString = dateString.split('T')[0];
7323      }
7324
7325      if (dateString.includes('/')) {
7326        var _dateString$split = dateString.split('/'),
7327          _dateString$split2 = _slicedToArray(_dateString$split, 3),
7328          day = _dateString$split2[0],
7329          month = _dateString$split2[1],
7330          year = _dateString$split2[2];
7331
7332        return year + "-" + month + "-" + day;
7333      }
7334
7335      return dateString;
7336    }
7337  }, {
7338    key: 'isObjectEquivalent',
7339    value: function isObjectEquivalent(a, b) {
7340      var firstObject = Object.getOwnPropertyNames(a);
7341      var secondObject = Object.getOwnPropertyNames(b);
7342
7343      if (firstObject.length != secondObject.length) return false;
7344
7345      for (var i = 0; i < firstObject.length; i++) {
7346        var propName = firstObject[i];
7347
7348        if (a[propName] !== b[propName]) return false;
7349      }
7350
7351      return true;
7352    }
7353  }, {
7354    key: 'applyAemTextContent',
7355    value: function applyAemTextContent($element, dataJs, text) {
7356      if (!$element) return 'empty';
7357
7358      if ($($element).find('[data-js="' + dataJs + '"]').find('.cmp-text').length > 0) {
7359        $($element).find('[data-js="' + dataJs + '"]').find('.cmp-text').text(text);
7360      } else {
7361        $($element).find('[data-js="' + dataJs + '"]').text(text);
7362      }
7363    }
7364  }, {
7365    key: 'appendAemTextContent',
7366    value: function appendAemTextContent($element, dataJs, text) {
7367      if (!$element) return 'empty';
7368
7369      if ($($element).find('[data-js="' + dataJs + '"]').find('.cmp-text').length > 0) {
7370        $($element).find('[data-js="' + dataJs + '"]').find('.cmp-text').empty().append(text);
7371      } else {
7372        $($element).find('[data-js="' + dataJs + '"]').empty().append(text);
7373      }
7374    }
7375  }, {
7376    key: 'getParamsUrl',
7377    value: function getParamsUrl(sParam) {
7378      var sPageURL = window.location.search.substring(1);
7379
7380      if (sPageURL === "") return;
7381
7382      var sURLVariables = sPageURL ? sPageURL.split('&') : SessionStorage.get('deepLinkParameters');
7383      for (var i = 0; i < sURLVariables.length; i++) {
7384        var sParameterName = sURLVariables[i].split("=");
7385        if (sParameterName[0] == sParam) return sParameterName[1];
7386      }
7387    }
7388  }, {
7389    key: "decodeJWT",
7390    value: function decodeJWT(token) {
7391      var decodeParam = "";
7392
7393      try {
7394        decodeParam = decodeURIComponent(atob(token));
7395      } catch (e) {
7396        decodeParam = token;
7397      }
7398
7399      SessionStorage.set("jca_token", decodeParam);
7400
7401      var base64Url = decodeParam.split(".")[1];
7402      var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
7403      var jsonPayload = decodeURIComponent(atob(base64).split("").map(function (c) {
7404        return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
7405      }).join(""));
7406
7407      return JSON.parse(jsonPayload);
7408    }
7409  }, {
7410    key: "extractJWTData",
7411    value: function extractJWTData(token) {
7412      try {
7413        var base64Url = token.split('.')[1];
7414        var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
7415        var jsonPayload = atob(base64).split('').map(function (c) {
7416          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
7417        }).join('');
7418
7419        return JSON.parse(decodeURIComponent(jsonPayload));
7420      } catch (error) {
7421        return null;
7422      }
7423    }
7424  }, {
7425    key: "quotesBlock",
7426    value: function quotesBlock(datas) {
7427      $(datas.join(",")).on('keydown', function (e) {
7428        if (e.keyCode === 192) e.preventDefault();
7429      });
7430    }
7431  }, {
7432    key: 'checkChar',
7433    value: function checkChar(e) {
7434      var char = String.fromCharCode(e.keyCode);
7435
7436      var pattern = '[a-zA-Z0-9-@-_-.]';
7437      if (char == "^") return false;
7438      if (char.match(pattern)) return true;
7439    }
7440  }, {
7441    key: 'getSearchData',
7442    value: function getSearchData(formData, context) {
7443	  if(formData != null) {
7444		  var cart = SessionStorage.get('cart')
7445		  var quantityPassengers = formData.passengers[0].quantity +
7446			formData.passengers[2].quantity + formData.passengers[1].quantity;
7447
7448		  var searchData = {
7449			search_origin: window.location.pathname === "/" ? "Home" : window.location.pathname, // Origem da busca com lógica condicional
7450			origin: formData.depart.origin.label,
7451			destination: formData.depart.destination.label,
7452			departure_date: formData.depart.date,
7453			return_trip_date: formData.departureOnly === false ? formData.return.date : null,
7454			adults_passengers: formData.passengers[0].quantity, // Quantidade de passageiros adultos
7455			infants_passengers: formData.passengers[2].quantity, // Quantidade de passageiros crianças de colo (não pagantes)
7456			children_passengers: formData.passengers[1].quantity, // Quantidade de passageiros crianças (pagantes)
7457			passengers: quantityPassengers,
7458			search_type: "default"
7459		  };
7460
7461		  if (context === 'add_to_cart' && cart && cart._listOffer && cart._listOffer.length > 1) {
7462         searchData.origin = formData.return.origin.label;
7463         searchData.destination = formData.return.destination.label;
7464      }
7465
7466		  return searchData;
7467	  } else {
7468	      return null;
7469	  }
7470    }
7471  }, {
7472    key: 'getSearchParameters',
7473    value: function getSearchParameters(formData) {
7474      if(formData != null) {
7475		  var searchParameters = {
7476			departure_date: Utils.getPromotionParam("data_ida") && Utils.getPromotionParam("data_ida").length == 8 ? Utils.getPromotionParam("data_ida").substring(4, 8) + "-" + Utils.getPromotionParam("data_ida").substring(2, 4) + "-" + Utils.getPromotionParam("data_ida").substring(0, 2) : null,
7477			return_date: Utils.getPromotionParam("data_volta") && Utils.getPromotionParam("data_volta").length == 8 ? Utils.getPromotionParam("data_volta").substring(4, 8) + "-" + Utils.getPromotionParam("data_volta").substring(2, 4) + "-" + Utils.getPromotionParam("data_volta").substring(0, 2) : null,
7478			origin_id: Utils.getPromotionParam("origem_id"),
7479			destination_id: Utils.getPromotionParam("destino_id"),
7480			adults: formData.passengers[0].quantity,
7481			infants: formData.passengers[2].quantity,
7482			children: formData.passengers[1].quantity,
7483			deep_link: Utils.getPromotionParam("deep"),
7484			device_origin: Utils.getPromotionParam("device_origin") != undefined ? Utils.getPromotionParam("device_origin") : null,
7485			search_component: Utils.getPromotionParam("component") != undefined ? Utils.getPromotionParam("component") : null
7486		  };
7487
7488		  return searchParameters;
7489	  } else {
7490	      return null;
7491	  }
7492    }
7493  }, {
7494    key: 'getUserData',
7495    value: function getUserData() {
7496      var passenger = SessionStorage.get('passenger') || {};
7497      var fullName = passenger._name || '';
7498      var nameParts = fullName.split(' ');
7499      var firstName = nameParts[0] || null;
7500      var lastName = nameParts.slice(1).join(' ') || null;
7501      var fullPhone = passenger._areaCode && passenger._phone ? "+55" + passenger._areaCode + passenger._phone : null;
7502
7503      var userData = {
7504        user_id: passenger._id ? passenger._id : null,
7505        phone: fullPhone,
7506        email: passenger._email ? passenger._email : null,
7507        birthdate: passenger._birthDate ? passenger._birthDate : null,
7508        cpf: passenger._cpf ? passenger._cpf : null,
7509        passport: null,
7510        cnpj: null,
7511        user_status: null,
7512        address: {
7513          first_name: firstName || null,
7514          last_name: lastName || null,
7515          street: passenger._addresses && passenger._addresses.street ? passenger._addresses.street : null,
7516          neighborhood: passenger._addresses && passenger._addresses.neighborhood ? passenger._addresses.neighborhood : null,
7517          city: passenger._addresses && passenger._addresses.city ? passenger._addresses.city : null,
7518          state: null,
7519          country: null,
7520          zipcode: passenger._addresses && passenger._addresses.zipCode ? passenger._addresses.zipCode : null
7521        }
7522      };
7523
7524      return userData;
7525    }
7526  }, {
7527    key: 'calculePercent',
7528    value: function calculePercent(value, percent) {
7529      return value * (percent / 100);
7530    }
7531  }, {
7532    key: "clearFirstCharacter",
7533    value: function clearFirstCharacter(seatNumber) {
7534      if (seatNumber[0] == '0') {
7535        var seatNumberRemoved = seatNumber;
7536        return seatNumberRemoved.slice(1);
7537      }
7538
7539      return seatNumber;
7540    }
7541  }, {
7542    key: "getUserLocation",
7543    value: function getUserLocation(callback, errorCallback) {
7544      if (navigator.geolocation) {
7545        navigator.geolocation.getCurrentPosition(function (position) {
7546          var latitude = position.coords.latitude;
7547          var longitude = position.coords.longitude;
7548          callback(latitude, longitude);
7549        }, function (error) {
7550          if (errorCallback) {
7551            errorCallback(error);
7552          }
7553        });
7554      } else {
7555        console.error("Geolocalização não é suportada por este navegador.");
7556      }
7557    }
7558  }]);
7559
7560  return Utils;
7561}();
7562
7563Utils.keyCodes = {
7564  BACKSPACE: 8,
7565  TAB: 9,
7566  ENTER: 13,
7567  DELETE: 46,
7568  AT: 50,
7569  UP: 38,
7570  DOWN: 40,
7571  PLUS: 107,
7572  MINUS: 109,
7573  SPACEBAR: 32
7574};
7575
7576Utils.defaultHelperMessages = {
7577  noResultMessage: "Nenhuma cidade encontrada.",
7578  singleResultMessage: "Foi encontrada 1 cidade",
7579  protip: "Utilize as setas para cima ou para baixo do mouse para selecionar a cidade e pressione a tecla ENTER.",
7580  multipleResultMessage: "Foram encontradas #amount cidades."
7581};
7582
7583function removeAcento(text) {
7584  text = text.replace(new RegExp('[ÁÀÂÃ]', 'gi'), 'A');
7585  text = text.replace(new RegExp('[ÉÈÊ]', 'gi'), 'E');
7586  text = text.replace(new RegExp('[ÍÌÎ]', 'gi'), 'I');
7587  text = text.replace(new RegExp('[ÓÒÔÕ]', 'gi'), 'O');
7588  text = text.replace(new RegExp('[ÚÙÛ]', 'gi'), 'U');
7589  text = text.replace(new RegExp('[Ç]', 'gi'), 'C');
7590  text = text.replace(new RegExp('[áàâã]', 'gi'), 'a');
7591  text = text.replace(new RegExp('[éèê]', 'gi'), 'e');
7592  text = text.replace(new RegExp('[íìî]', 'gi'), 'i');
7593  text = text.replace(new RegExp('[óòôõ]', 'gi'), 'o');
7594  text = text.replace(new RegExp('[úùû]', 'gi'), 'u');
7595  text = text.replace(new RegExp('[ç]', 'gi'), 'c');
7596  return text;
7597}
7598
7599// Third part solution
7600function generateMD5(string) {
7601
7602  function RotateLeft(lValue, iShiftBits) {
7603    return lValue << iShiftBits | lValue >>> 32 - iShiftBits;
7604  }
7605
7606  function AddUnsigned(lX, lY) {
7607    var lX4, lY4, lX8, lY8, lResult;
7608    lX8 = lX & 0x80000000;
7609    lY8 = lY & 0x80000000;
7610    lX4 = lX & 0x40000000;
7611    lY4 = lY & 0x40000000;
7612    lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
7613    if (lX4 & lY4) {
7614      return lResult ^ 0x80000000 ^ lX8 ^ lY8;
7615    }
7616    if (lX4 | lY4) {
7617      if (lResult & 0x40000000) {
7618        return lResult ^ 0xC0000000 ^ lX8 ^ lY8;
7619      } else {
7620        return lResult ^ 0x40000000 ^ lX8 ^ lY8;
7621      }
7622    } else {
7623      return lResult ^ lX8 ^ lY8;
7624    }
7625  }
7626
7627  function F(x, y, z) {
7628    return x & y | ~x & z;
7629  }
7630  function G(x, y, z) {
7631    return x & z | y & ~z;
7632  }
7633  function H(x, y, z) {
7634    return x ^ y ^ z;
7635  }
7636  function I(x, y, z) {
7637    return y ^ (x | ~z);
7638  }
7639
7640  function FF(a, b, c, d, x, s, ac) {
7641    a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
7642    return AddUnsigned(RotateLeft(a, s), b);
7643  };
7644
7645  function GG(a, b, c, d, x, s, ac) {
7646    a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
7647    return AddUnsigned(RotateLeft(a, s), b);
7648  };
7649
7650  function HH(a, b, c, d, x, s, ac) {
7651    a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
7652    return AddUnsigned(RotateLeft(a, s), b);
7653  };
7654
7655  function II(a, b, c, d, x, s, ac) {
7656    a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
7657    return AddUnsigned(RotateLeft(a, s), b);
7658  };
7659
7660  function ConvertToWordArray(string) {
7661    var lWordCount;
7662    var lMessageLength = string.length;
7663    var lNumberOfWords_temp1 = lMessageLength + 8;
7664    var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - lNumberOfWords_temp1 % 64) / 64;
7665    var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
7666    var lWordArray = Array(lNumberOfWords - 1);
7667    var lBytePosition = 0;
7668    var lByteCount = 0;
7669    while (lByteCount < lMessageLength) {
7670      lWordCount = (lByteCount - lByteCount % 4) / 4;
7671      lBytePosition = lByteCount % 4 * 8;
7672      lWordArray[lWordCount] = lWordArray[lWordCount] | string.charCodeAt(lByteCount) << lBytePosition;
7673      lByteCount++;
7674    }
7675    lWordCount = (lByteCount - lByteCount % 4) / 4;
7676    lBytePosition = lByteCount % 4 * 8;
7677    lWordArray[lWordCount] = lWordArray[lWordCount] | 0x80 << lBytePosition;
7678    lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
7679    lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
7680    return lWordArray;
7681  };
7682
7683  function WordToHex(lValue) {
7684    var WordToHexValue = "",
7685      WordToHexValue_temp = "",
7686      lByte,
7687      lCount;
7688    for (lCount = 0; lCount <= 3; lCount++) {
7689      lByte = lValue >>> lCount * 8 & 255;
7690      WordToHexValue_temp = "0" + lByte.toString(16);
7691      WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2);
7692    }
7693    return WordToHexValue;
7694  };
7695
7696  function Utf8Encode(string) {
7697    string = string.replace(/\r\n/g, "\n");
7698    var utftext = "";
7699
7700    for (var n = 0; n < string.length; n++) {
7701
7702      var c = string.charCodeAt(n);
7703
7704      if (c < 128) {
7705        utftext += String.fromCharCode(c);
7706      } else if (c > 127 && c < 2048) {
7707        utftext += String.fromCharCode(c >> 6 | 192);
7708        utftext += String.fromCharCode(c & 63 | 128);
7709      } else {
7710        utftext += String.fromCharCode(c >> 12 | 224);
7711        utftext += String.fromCharCode(c >> 6 & 63 | 128);
7712        utftext += String.fromCharCode(c & 63 | 128);
7713      }
7714    }
7715
7716    return utftext;
7717  };
7718
7719  var x = Array();
7720  var k, AA, BB, CC, DD, a, b, c, d;
7721  var S11 = 7,
7722    S12 = 12,
7723    S13 = 17,
7724    S14 = 22;
7725  var S21 = 5,
7726    S22 = 9,
7727    S23 = 14,
7728    S24 = 20;
7729  var S31 = 4,
7730    S32 = 11,
7731    S33 = 16,
7732    S34 = 23;
7733  var S41 = 6,
7734    S42 = 10,
7735    S43 = 15,
7736    S44 = 21;
7737
7738  string = Utf8Encode(string);
7739
7740  x = ConvertToWordArray(string);
7741
7742  a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
7743
7744  for (k = 0; k < x.length; k += 16) {
7745    AA = a; BB = b; CC = c; DD = d;
7746    a = FF(a, b, c, d, x[k + 0], S11, 0xD76AA478);
7747    d = FF(d, a, b, c, x[k + 1], S12, 0xE8C7B756);
7748    c = FF(c, d, a, b, x[k + 2], S13, 0x242070DB);
7749    b = FF(b, c, d, a, x[k + 3], S14, 0xC1BDCEEE);
7750    a = FF(a, b, c, d, x[k + 4], S11, 0xF57C0FAF);
7751    d = FF(d, a, b, c, x[k + 5], S12, 0x4787C62A);
7752    c = FF(c, d, a, b, x[k + 6], S13, 0xA8304613);
7753    b = FF(b, c, d, a, x[k + 7], S14, 0xFD469501);
7754    a = FF(a, b, c, d, x[k + 8], S11, 0x698098D8);
7755    d = FF(d, a, b, c, x[k + 9], S12, 0x8B44F7AF);
7756    c = FF(c, d, a, b, x[k + 10], S13, 0xFFFF5BB1);
7757    b = FF(b, c, d, a, x[k + 11], S14, 0x895CD7BE);
7758    a = FF(a, b, c, d, x[k + 12], S11, 0x6B901122);
7759    d = FF(d, a, b, c, x[k + 13], S12, 0xFD987193);
7760    c = FF(c, d, a, b, x[k + 14], S13, 0xA679438E);
7761    b = FF(b, c, d, a, x[k + 15], S14, 0x49B40821);
7762    a = GG(a, b, c, d, x[k + 1], S21, 0xF61E2562);
7763    d = GG(d, a, b, c, x[k + 6], S22, 0xC040B340);
7764    c = GG(c, d, a, b, x[k + 11], S23, 0x265E5A51);
7765    b = GG(b, c, d, a, x[k + 0], S24, 0xE9B6C7AA);
7766    a = GG(a, b, c, d, x[k + 5], S21, 0xD62F105D);
7767    d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
7768    c = GG(c, d, a, b, x[k + 15], S23, 0xD8A1E681);
7769    b = GG(b, c, d, a, x[k + 4], S24, 0xE7D3FBC8);
7770    a = GG(a, b, c, d, x[k + 9], S21, 0x21E1CDE6);
7771    d = GG(d, a, b, c, x[k + 14], S22, 0xC33707D6);
7772    c = GG(c, d, a, b, x[k + 3], S23, 0xF4D50D87);
7773    b = GG(b, c, d, a, x[k + 8], S24, 0x455A14ED);
7774    a = GG(a, b, c, d, x[k + 13], S21, 0xA9E3E905);
7775    d = GG(d, a, b, c, x[k + 2], S22, 0xFCEFA3F8);
7776    c = GG(c, d, a, b, x[k + 7], S23, 0x676F02D9);
7777    b = GG(b, c, d, a, x[k + 12], S24, 0x8D2A4C8A);
7778    a = HH(a, b, c, d, x[k + 5], S31, 0xFFFA3942);
7779    d = HH(d, a, b, c, x[k + 8], S32, 0x8771F681);
7780    c = HH(c, d, a, b, x[k + 11], S33, 0x6D9D6122);
7781    b = HH(b, c, d, a, x[k + 14], S34, 0xFDE5380C);
7782    a = HH(a, b, c, d, x[k + 1], S31, 0xA4BEEA44);
7783    d = HH(d, a, b, c, x[k + 4], S32, 0x4BDECFA9);
7784    c = HH(c, d, a, b, x[k + 7], S33, 0xF6BB4B60);
7785    b = HH(b, c, d, a, x[k + 10], S34, 0xBEBFBC70);
7786    a = HH(a, b, c, d, x[k + 13], S31, 0x289B7EC6);
7787    d = HH(d, a, b, c, x[k + 0], S32, 0xEAA127FA);
7788    c = HH(c, d, a, b, x[k + 3], S33, 0xD4EF3085);
7789    b = HH(b, c, d, a, x[k + 6], S34, 0x4881D05);
7790    a = HH(a, b, c, d, x[k + 9], S31, 0xD9D4D039);
7791    d = HH(d, a, b, c, x[k + 12], S32, 0xE6DB99E5);
7792    c = HH(c, d, a, b, x[k + 15], S33, 0x1FA27CF8);
7793    b = HH(b, c, d, a, x[k + 2], S34, 0xC4AC5665);
7794    a = II(a, b, c, d, x[k + 0], S41, 0xF4292244);
7795    d = II(d, a, b, c, x[k + 7], S42, 0x432AFF97);
7796    c = II(c, d, a, b, x[k + 14], S43, 0xAB9423A7);
7797    b = II(b, c, d, a, x[k + 5], S44, 0xFC93A039);
7798    a = II(a, b, c, d, x[k + 12], S41, 0x655B59C3);
7799    d = II(d, a, b, c, x[k + 3], S42, 0x8F0CCC92);
7800    c = II(c, d, a, b, x[k + 10], S43, 0xFFEFF47D);
7801    b = II(b, c, d, a, x[k + 1], S44, 0x85845DD1);
7802    a = II(a, b, c, d, x[k + 8], S41, 0x6FA87E4F);
7803    d = II(d, a, b, c, x[k + 15], S42, 0xFE2CE6E0);
7804    c = II(c, d, a, b, x[k + 6], S43, 0xA3014314);
7805    b = II(b, c, d, a, x[k + 13], S44, 0x4E0811A1);
7806    a = II(a, b, c, d, x[k + 4], S41, 0xF7537E82);
7807    d = II(d, a, b, c, x[k + 11], S42, 0xBD3AF235);
7808    c = II(c, d, a, b, x[k + 2], S43, 0x2AD7D2BB);
7809    b = II(b, c, d, a, x[k + 9], S44, 0xEB86D391);
7810    a = AddUnsigned(a, AA);
7811    b = AddUnsigned(b, BB);
7812    c = AddUnsigned(c, CC);
7813    d = AddUnsigned(d, DD);
7814  }
7815
7816  var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
7817
7818  return temp.toLowerCase();
7819}
7820
7821/**
7822 *
7823 * MAIN
7824 */
7825'use strict';
7826
7827var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
7828
7829function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
7830
7831var ValidationService = function () {
7832  function ValidationService() {
7833    _classCallCheck(this, ValidationService);
7834  }
7835
7836  _createClass(ValidationService, null, [{
7837    key: 'open',
7838    value: function open(message, callback, lastComponent) {
7839      ValidationService.lastComponent = lastComponent;
7840      $('[data-js="message-validation"]').text(message);
7841      $("body").css('overflow-y', 'hidden');
7842      $('[data-js="alert-validation"]').fadeIn(function () {
7843        $('[data-js="close-alert-validation"]').focus();
7844        if (callback) callback();
7845      });
7846    }
7847  }, {
7848    key: 'close',
7849    value: function close(callback) {
7850      $("body").css('overflow-y', 'auto');
7851      $('[data-js="alert-validation"]').fadeOut(function () {
7852        if (callback) callback();
7853      });
7854    }
7855  }]);
7856
7857  return ValidationService;
7858}();
7859
7860$('[data-js="close-alert-validation"]').click(function () {
7861  ValidationService.close();
7862  if (ValidationService.lastComponent) ValidationService.lastComponent.focus();
7863});
7864
7865$('[data-js="close-alert-validation"]').focusout(function (e) {
7866  var relatedTarget = $(e.relatedTarget);
7867  if (relatedTarget.length > 0 && relatedTarget.closest('[data-js="alert-validation"]').length == 0) {
7868    ValidationService.close();
7869    if (ValidationService.lastComponent) ValidationService.lastComponent.focus();
7870  }
7871});
7872'use strict';
7873
7874var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
7875
7876function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
7877
7878var WalletService = function () {
7879  function WalletService() {
7880    _classCallCheck(this, WalletService);
7881  }
7882
7883  _createClass(WalletService, null, [{
7884    key: 'checkWalletExists',
7885    value: function checkWalletExists() {
7886      try {
7887        var passenger = this.getPassenger();
7888        if (!passenger || !passenger._cpf) {
7889          throw new Error('Passenger or CPF not available');
7890        }
7891
7892        var cpf = passenger._cpf;
7893        var url = $('#baseGiroUrl').val() + '/wallet/v1/exists/' + cpf;
7894        var headers = {
7895          Authorization: '' + SessionStorage.get("jca_token")
7896        };
7897        var headers = HttpService.getSession(headers);
7898
7899
7900        return this.ajaxGet(url, headers).then(function (data) {
7901          if (data.success === false) {
7902            SessionStorage.set('walletExists', false);
7903          } else {
7904            SessionStorage.set('walletExists', true);
7905          }
7906
7907          return data;
7908        }).catch(function (err) {
7909          console.error('Error checking wallet existence:', err);
7910          return Promise.reject(err);
7911        });
7912      } catch (err) {
7913        console.error('Error checking wallet existence:', err);
7914        return Promise.reject(err);
7915      }
7916    }
7917  }, {
7918    key: 'getPassenger',
7919    value: function getPassenger() {
7920      var passenger = SessionStorage.get('passenger');
7921      if (!passenger || !passenger._cpf) {
7922        throw new Error('Passenger or CPF not available');
7923      }
7924      return passenger;
7925    }
7926  }, {
7927    key: 'checkGiroAccountExists',
7928    value: function checkGiroAccountExists() {
7929      try {
7930        var passenger = this.getPassenger();
7931        if (!passenger || !passenger._cpf) {
7932          throw new Error('Passenger or CPF not available');
7933        }
7934
7935        var cpf = passenger._cpf;
7936        var url = $('#baseGiroUrl').val() + '/customer/v1/user/getlike?filter.cpf=' + cpf;
7937        var headers = {
7938          Authorization: '' + SessionStorage.get("jca_token")
7939        };
7940        var headers = HttpService.getSession(headers);
7941        
7942        return this.ajaxGet(url, headers).catch(function (err) {
7943          console.error('Error checking Giro account existence:', err);
7944          return Promise.reject(err);
7945        });
7946      } catch (err) {
7947        console.error('Error checking Giro account existence:', err);
7948        return Promise.reject(err);
7949      }
7950    }
7951  }, {
7952    key: 'ajaxGet',
7953    value: function ajaxGet(url, headers) {
7954      return new Promise(function (resolve, reject) {
7955        $.ajax({
7956          type: "GET",
7957          url: url,
7958          headers: headers,
7959          dataType: 'json',
7960          contentType: "application/json",
7961          success: resolve,
7962          error: reject
7963        });
7964      });
7965    }
7966  }]);
7967
7968  return WalletService;
7969}();
7970'use strict';
7971
7972var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
7973
7974function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
7975
7976/**
7977 *
7978 *
7979 * INICIO SESSION SERVICE
7980 *
7981 */
7982
7983var SessionService = function () {
7984  function SessionService() {
7985    _classCallCheck(this, SessionService);
7986  }
7987
7988  _createClass(SessionService, null, [{
7989    key: 'start',
7990    value: function start(timer) {
7991      var _this = this;
7992
7993      if (timer) {
7994        var now = new Date().getTime();
7995        var remainingTime = timer._remainingTime - now;
7996        var middleTime = timer._middleTime - now;
7997
7998        this.handleEvents();
7999        this.myInterval(timer);
8000
8001        if (middleTime > 0) setTimeout(function () {
8002          return _this.sessionExpireEvent(false);
8003        }, middleTime);
8004
8005        setTimeout(function () {
8006          return _this.sessionExpireEvent(true);
8007        }, remainingTime);
8008      }
8009    }
8010  }, {
8011    key: 'handleEvents',
8012    value: function handleEvents() {
8013      var _this2 = this;
8014
8015      $(document).ready(function () {
8016        var repricingV2 = SessionStorage.get('repricingv2');
8017        $('[data-js="renew-search"]').click(function () {
8018          if (repricingV2) {
8019            $(location).attr('href', $('#myAccountPath').val());
8020          } else {
8021            $(location).attr('href', $('#homePagePath').val());
8022          }
8023        });
8024
8025        $('[data-js="close-session-overlay"]').click(function () {
8026          $('[data-js="session-overlay-container"]').hide();
8027        });
8028
8029        $('[data-js="use-same-search"]').click(function () {
8030          var parameters = SessionStorage.get('deepLinkParameters');
8031          var parametersSplit = parameters.toString().replace(/,/g, "&");
8032          _this2.clearPartialStorage();
8033          if (repricingV2) {
8034            if ($('#rescheduleSearchResultPathV2') && $('#rescheduleSearchResultPathV2').val()) {
8035              $(location).attr('href', $('#rescheduleSearchResultPathV2').val() + "?" + parametersSplit);
8036            }
8037          } else {
8038            if ($('#searchResultPath') && $('#searchResultPath').val()) {
8039              $(location).attr('href', $('#searchResultPath').val() + "?" + parametersSplit);
8040            }
8041          }
8042        });
8043
8044        $('.session-screen').children().focusout(function (e) {
8045          var $target = $(e.relatedTarget);
8046          if ($target.length > 0 && $target.closest('.session-screen').length == 0) $('.session-screen:visible').find('a').click();
8047        });
8048      });
8049    }
8050  }, {
8051    key: 'myInterval',
8052    value: function myInterval(timer) {
8053      var remainingTime = timer._remainingTime;
8054
8055      return setInterval(function () {
8056        // Get todays date and time
8057        var now = new Date().getTime();
8058
8059        // Find the distance between now and the count down time
8060        var distance = remainingTime - now;
8061
8062        // Time calculations for minutes and seconds
8063        var minutes = Math.floor(distance % (1000 * 60 * 60) / (1000 * 60));
8064        var seconds = Math.floor(distance % (1000 * 60) / 1000);
8065
8066        if (distance > 0) {
8067          if (seconds.toString().length === 1) seconds = "0" + seconds;
8068
8069          if (minutes.toString().length === 1) minutes = "0" + minutes;
8070          // Output the result in an element
8071          $('[data-js="session-timer"]').text(minutes + ":" + seconds);
8072        }
8073      }, 1000);
8074    }
8075  }, {
8076    key: 'sessionExpireEvent',
8077    value: function sessionExpireEvent(expired) {
8078      var checkSite = Utils.getSiteNameForClasses();
8079      if ((checkSite == 'catarinense') || (checkSite == 'viacao1001')) {
8080        $('[data-js="session-overlay-container"]').show();
8081        if (expired) {
8082          $('[data-js="session-middletime-screen"]').hide();
8083          $('[data-js="session-expired-screen"]').show();
8084          $('[data-js="use-same-search"]').focus();
8085          this.clearPartialStorage();
8086        } else {
8087          $('[data-js="session-expired-screen"]').hide();
8088          $('[data-js="session-middletime-screen"]').show();
8089          $('[data-js="close-session-overlay"]').focus();
8090        }
8091      } else {
8092        if (expired) {
8093          AlertConfirmation.showAEM('data-js="cometa-expired-session-alert"');
8094          $('.main-content:not(.edit-profile-page) .confirmation-alert:not(.cq-Editable-dom) .container-confirmation.active').css('top', '3rem')
8095          OverlayService.show();
8096          this.clearPartialStorage();
8097        } else {
8098          AlertConfirmation.showAEM('data-js="cometa-middletime-alert"');
8099          $('.main-content:not(.edit-profile-page) .confirmation-alert:not(.cq-Editable-dom) .container-confirmation.active').css('top', '3rem')
8100          OverlayService.show();
8101        }
8102      }
8103    }
8104  }, {
8105    key: 'clearPartialStorage',
8106    value: function clearPartialStorage() {
8107      SessionStorage.remove('nextResult');
8108      SessionStorage.remove('prevResult');
8109      SessionStorage.remove('cart');
8110      SessionStorage.remove('remainingTime');
8111      SessionStorage.remove('middleTime');
8112    }
8113  }]);
8114
8115  return SessionService;
8116}();
8117
8118(function () {
8119  var page = $('#jca-identifier-page').val();
8120  var alertTimeout = 17;
8121  var totalTimeout = 20;
8122
8123  if ($('#alertTimeout') && $('#alertTimeout').val()) {
8124    alertTimeout = $('#alertTimeout').val();
8125  }
8126
8127  if ($('#totalTimeout') && $('#totalTimeout').val()) {
8128    totalTimeout = $('#totalTimeout').val();
8129  }
8130  var nextTwentyMin = new Date().getTime() + totalTimeout * 60 * 1000;
8131  var lastThreeMin = new Date().getTime() + alertTimeout * 60 * 1000;
8132  var timer = new Timer(nextTwentyMin, lastThreeMin);
8133
8134  switch (page) {
8135    case 'jca-search-result-page':
8136      SessionStorage.set('timer', timer);
8137      SessionService.start(timer)
8138      break;
8139    case 'reschedule-trip-search-result-page-v2':
8140      SessionStorage.set('timer', timer);
8141      SessionService.start(timer);
8142      break;
8143    case 'jca-costumer-registration-page':
8144    case 'jca-costumer-registration-confirm-page':
8145    case 'jca-costumer-registration-return-page':
8146    case 'jca-login-page':
8147      if (SessionStorage.get('formData'))
8148        SessionService.start(SessionStorage.get('timer'))
8149      break;
8150    case 'reschedule-trip-page':
8151      SessionStorage.set('timer', timer);
8152      SessionService.start(timer)
8153      break;
8154    case 'jca-register-passengers-page':
8155      SessionStorage.set('timer', timer);
8156      SessionService.start(timer)
8157      break;
8158    case 'jca-seat-reservation-page':
8159      SessionStorage.set('timer', timer);
8160      SessionService.start(timer);
8161      break;
8162    case 'jca-seat-reservation-remark-page':
8163      SessionStorage.set('timer', timer);
8164      SessionService.start(timer);
8165      break;
8166    case 'jca-payment-page':
8167      SessionService.start(SessionStorage.get('timer'))
8168      break;
8169
8170    case 'jca-checkout-page':
8171    default:
8172      break;
8173  }
8174})(jQuery);
8175/**
8176 *
8177 *
8178 * FIM SESSION SERVICE
8179 *
8180 */
8181'use strict';
8182
8183var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
8184
8185function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
8186
8187var BusesCarousel = function () {
8188  function BusesCarousel($) {
8189    _classCallCheck(this, BusesCarousel);
8190
8191    this.carousel = $('[data-js="buses-carousel"]');
8192    this.list = $('[data-js="buses-carousel-list"]');
8193    this.items = $('[data-js="buses-carousel-item"]');
8194    this.tabs = $('[data-js="buses-carousel-tab"]');
8195
8196    this.init();
8197  }
8198
8199  _createClass(BusesCarousel, [{
8200    key: 'init',
8201    value: function init() {
8202      this.handleEvents();
8203      var n = this.list.children('li').length || 0;
8204      if (n > 4) {
8205        this.list.css({
8206          width: n * 100 + '%'
8207        });
8208      }
8209    }
8210  }, {
8211    key: 'changeSlide',
8212    value: function changeSlide(num, list) {
8213      var n = list.children('li').length || 0;
8214      list.css({
8215        transform: 'translateX(' + -100 / n * num + '%)'
8216      });
8217    }
8218  }, {
8219    key: 'handleEvents',
8220    value: function handleEvents() {
8221      var changeSlide = this.changeSlide;
8222      var list = this.list;
8223      var tabs = this.tabs;
8224
8225      this.tabs.on('click', function () {
8226        var tab = $(this);
8227        var index = tab.index();
8228
8229        tabs.removeClass('active');
8230        tab.addClass('active');
8231
8232        changeSlide(index, list);
8233      });
8234    }
8235  }]);
8236
8237  return BusesCarousel;
8238}();
8239
8240var AlertCovidWarning = function () {
8241  function AlertCovidWarning() {
8242    var _this = this;
8243
8244    _classCallCheck(this, AlertCovidWarning);
8245
8246    this.alertCovidContainer = $('[data-js="alert-covid"]');
8247    this.header = $('#header-navbar');
8248    this.contentTextHeader = $('.header-container-text');
8249    this.init();
8250
8251    $(window).on('resize', function () {
8252      var isDesktop = _this.isDesktop;
8253      _this.checkWindowSize();
8254
8255      if (isDesktop != _this.isDesktop) {
8256        _this.hideAlertCovidWarning();
8257        _this.showAlertCovidWarning();
8258      }
8259    });
8260  }
8261
8262  _createClass(AlertCovidWarning, [{
8263    key: 'checkWindowSize',
8264    value: function checkWindowSize() {
8265      var windowSizeObject = Utils.getWindowSize();
8266      if (windowSizeObject.width > windowSizeObject.breakpoints.LG) this.isDesktop = true; else this.isDesktop = false;
8267    }
8268  }, {
8269    key: 'init',
8270    value: function init() {
8271      this.showAlertCovidWarning();
8272    }
8273  }, {
8274    key: 'isAboveHeader',
8275    value: function isAboveHeader() {
8276      return this.alertCovidContainer.next().is('header') || this.alertCovidContainer.parent().find('header').length > 0;
8277    }
8278  }, {
8279    key: 'showAlertCovidWarning',
8280    value: function showAlertCovidWarning() {
8281      this.alertCovidContainer.show();
8282
8283      var body = $('body');
8284      var paddingTop = parseFloat($('.main-content').css('padding-top'));
8285      var height = parseFloat(this.alertCovidContainer.css('height'));
8286      $('.header-site').css('top', height + 'px');
8287      $('.header-navbar.header-navbar-fixed.active').css('margin-top', height + 'px');
8288      $('#header-navbar').css('margin-top', height + 'px');
8289      $('.main-content').css('padding-top', paddingTop + height + 'px');
8290      $('.chosen-lang').css('top', height + 'px');
8291      if (body.has("#cookie-warning-container").length > 0 && $("#cookie-warning-container").is(':visible')) {
8292        if ($('[data-js="alert-covid"]').length > 0) {
8293          var alertCovidHeight = $('[data-js="alert-covid"]').height();
8294          var cookieAlert = $("#cookie-warning-container").height();
8295
8296          $('#cookie-warning-container').css('margin-top', cookieAlert + 'px');
8297          $('#header-navbar').css('margin-top', alertCovidHeight + cookieAlert + 'px');
8298        }
8299      }
8300      this.alertCovidContainer.addClass('is-above-header');
8301      this.header.addClass('active');
8302      this.contentTextHeader.addClass('active');
8303    }
8304  }, {
8305    key: 'adjustPasswordOverlay',
8306    value: function adjustPasswordOverlay() {
8307      var headerCurrentTop = parseInt($('.header-site').css('top'));
8308      var overlayComponent = $('[data-js="bottom-password"]');
8309
8310      if (overlayComponent.is(':visible')) {
8311        var top = parseInt(overlayComponent.css('top')) - headerCurrentTop;
8312        overlayComponent.css('top', top);
8313      }
8314    }
8315  }, {
8316    key: 'hideAlertCovidWarning',
8317    value: function hideAlertCovidWarning() {
8318      this.alertCovidContainer.hide();
8319      this.adjustPasswordOverlay();
8320      $('.header-site').css('top', 0);
8321      $('.main-content').css('padding-top', '');
8322      $('.chosen-lang').css('top', 0);
8323      this.alertCovidContainer.removeClass('is-above-header');
8324      this.header.removeClass('active');
8325      this.contentTextHeader.removeClass('active');
8326    }
8327  }, {
8328    key: 'setBackgroundColor',
8329    value: function setBackgroundColor() {
8330      var backgroundColor = $("[data-js='cookie-warning-background-color']").val();
8331      this.alertCovidContainer.css('background-color', backgroundColor);
8332    }
8333  }]);
8334
8335  return AlertCovidWarning;
8336}();
8337'use strict';
8338
8339var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
8340
8341function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
8342
8343var CancelTripController = function () {
8344  function CancelTripController($) {
8345    _classCallCheck(this, CancelTripController);
8346
8347    this.user = SessionStorage.get('passenger');
8348    this.tripToCancel = SessionStorage.get('tripToCancel');
8349    this.linkReturn = $('[data-js="link-return"]');
8350    this.highlightUser = $('[data-js="highlight-user"]');
8351    this.selectAllDepartCheck = $('[data-js="select-all-depart-check"]');
8352    this.selectAllReturnCheck = $('[data-js="select-all-return-check"]');
8353    this.checkConfirmation = $('[data-js="check-confirmation"]');
8354    this.btnOpenConfirm = $('[data-js="btn-open-confirm"]');
8355    this.btnRequireCancelTrip = $('[data-js="trip-cancel-next"]');
8356    this.btnSubmit = $('[data-js="btn-submit"]');
8357    this.closeConfiration = $('[data-js="close-confirmation"]');
8358    this.cancelGoingText = $('[data-js="cancel-going-text"]');
8359    this.cancelReturnText = $('[data-js="cancel-return-text"]');
8360    this.passGoingList = $('[data-js="passengers-going-list"]');
8361    this.passReturnList = $('[data-js="passengers-return-list"]');
8362    this.confirmContainerOverlay = $('[data-js="cancel-trip-confirmation-overlay"]');
8363    this.confirmContainer = $('[data-js="cancel-trip-confirmation"]');
8364    this.detailsContainer = $('[data-js="cancel-trip-details"]');
8365    this.checkboxGoingTrip = $('[data-js="check-going-trip"]');
8366    this.checkboxReturnTrip = $('[data-js="check-return-trip"]');
8367    this.btnBackTripCancelSelect = $('[data-js="back-trip-cancel-select"]');
8368    this.btnConfCancelTrip = $('[data-js="trip-cancel-confirm"]');
8369    this.errMsgPassengerStatus = $('[data-js="msg-error-status-cancel"]');
8370    this.errMsgChildCancelTrip = $('[data-js="msg-child-error-cancel"]');
8371    this.convenienceFee = $('[data-js="convenience-fee"]').attr('value') == 'true';
8372    this.isQuantityGoingChecked = true;
8373    this.isQuantityReturnChecked = true;
8374    this.listPassengersToCancel;
8375    this.usersToCancel = [];
8376    this.listPassengerCancelGoing = 0;
8377    this.listPassengerCancelReturn = 0;
8378    this.isPassengerAlreadyCancelGoing;
8379    this.isPassengerAlreadyCancelReturn;
8380    this.isTripPayedPaymee = false;
8381    this.isPaymentLivelo = false;
8382    this.resumeCancelTrip = new ResumeCancelTripController($);
8383    new AlertCreditCard($);
8384    this.init();
8385  }
8386
8387  _createClass(CancelTripController, [{
8388    key: 'init',
8389    value: function init() {
8390      this.linsteClick();
8391      this.modalEditable();
8392      if (this.tripToCancel) {
8393        this.displayDetails(this.tripToCancel);
8394        this.handleReturn();
8395        this.handleCheckboxes();
8396        this.handleCancelTrip();
8397        this.setTaxRefund();
8398        this.handleBreadCrumbCancelTrip();
8399        this.removeListPassengerResumeTrip();
8400        this.handlePassengerStatus();
8401        this.handleConvenienceFee();
8402        this.blockedPassCheckbox();
8403      } else {
8404        $(location).attr('href', $('#myAccountPath').val());
8405      }
8406    }
8407  }, {
8408    key: "handleConvenienceFee",
8409    value: function handleConvenienceFee() {
8410      if (this.convenienceFee) {
8411        $('.convenienceFee').removeClass('d-none');
8412      } else $(".convenience-.convenience-fee").addClass("d-none");
8413    }
8414  }, {
8415    key: 'handleBreadCrumbCancelTrip',
8416    value: function handleBreadCrumbCancelTrip() {
8417      var cancelPhase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
8418
8419      var breadcrumb = $('[data-js="breadcrumb-cancel"]');
8420      var breadcrumb_mobile = $('[data-js="breadcrumb-cancel-mobile"]');
8421      var steps = breadcrumb.children().find('.breadcrumb-section');
8422      var stepsArrow = breadcrumb.children().find('.breadcrumb-section .arrow-icon');
8423      var steps_mobile = breadcrumb_mobile.children().find('.breadcrumb-mobile-section a.breadcrumb-mobile-text');
8424      var steps_mobile_section = breadcrumb_mobile.children().find('.breadcrumb-mobile-section');
8425      var steps_mobile_circle = breadcrumb_mobile.children().find('.breadcrumb-mobile-section .breadcrumb-mobile-circle');
8426
8427      if (cancelPhase == 1) {
8428        $(steps_mobile[0]).addClass('active');
8429        $(steps_mobile_section[0]).addClass('active');
8430        $(steps_mobile_circle[0]).addClass('active');
8431        $(steps_mobile_section[1]).removeClass('active');
8432        $(steps_mobile[1]).removeClass('active');
8433        $(steps[0]).addClass('active');
8434        $(steps[1]).removeClass('active');
8435        $(stepsArrow[1]).removeClass('active');
8436      }
8437
8438      if (cancelPhase == 2) {
8439        $(steps_mobile_circle[0]).addClass('previous');
8440        $(steps_mobile_section[0]).removeClass('active');
8441        $(steps_mobile_circle[1]).addClass('active');
8442        $(steps_mobile_section[1]).addClass('active');
8443        $(steps_mobile[0]).removeClass('active');
8444        $(steps_mobile[1]).addClass('active');
8445        $(steps[0]).addClass('active');
8446        $(stepsArrow[0]).addClass('active');
8447        $(steps[1]).addClass('active');
8448        $(stepsArrow[1]).addClass('active');
8449      }
8450
8451      if (cancelPhase == 3) {
8452        $(steps_mobile_circle[0]).addClass('previous');
8453        $(steps_mobile_circle[1]).addClass('previous');
8454        $(steps_mobile_section[1]).removeClass('active');
8455        $(steps_mobile[1]).removeClass('active');
8456        $(steps_mobile_circle[2]).addClass('active');
8457        $(steps_mobile_section[2]).addClass('active');
8458        $(steps_mobile[2]).addClass('active');
8459        $(steps[0]).addClass('active');
8460        $(steps[1]).addClass('active');
8461        $(steps[2]).addClass('active');
8462        $(stepsArrow[0]).addClass('active');
8463        $(stepsArrow[1]).addClass('active');
8464        $(stepsArrow[2]).addClass('active');
8465      }
8466    }
8467  }, {
8468    key: 'displayDetails',
8469    value: function displayDetails(parsedHistory) {
8470      var _this = this;
8471
8472      var goingArr = parsedHistory[0];
8473      var goingConnectionArr = parsedHistory[1];
8474      var returnArr = parsedHistory[2];
8475      var returnConnectionArr = parsedHistory[3];
8476
8477      var firstElemGoing = goingArr[0];
8478      var firstElemGoingConnection = goingConnectionArr ? goingConnectionArr[0] : null;
8479      var firstElemReturn = returnArr ? returnArr[0] : null;
8480      var firstElemReturnConnection = returnConnectionArr ? returnConnectionArr[0] : null;
8481
8482      var mainRegisterCode = firstElemGoing.finder;
8483      var origin = Utils.capitalize(firstElemGoing.originDescription);
8484
8485      var destination = Utils.capitalize(firstElemGoingConnection ? firstElemGoingConnection.destinationDescription : firstElemGoing.destinationDescription);
8486
8487      var dateInit = firstElemGoing.departureDate;
8488      var dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(dateInit));
8489      var hourDepart = DateFormatter.extractHour(firstElemGoing.departureDate);
8490      var hourArrival = DateFormatter.extractHour(firstElemGoing.arivalDate);
8491
8492      $('[data-js="num-code"]').text(mainRegisterCode);
8493      $('[data-js="going-summary"]').text('IDA - ' + dateDepart);
8494      $('[data-js="going-hour-depart"]').text(hourDepart);
8495      $('[data-js="going-summary-origin"]').text(origin);
8496      $('[data-js="going-hour-arrival"]').text(hourArrival);
8497      $('[data-js="going-summary-destination"]').text(destination);
8498      $('[data-js="going-summary-date-depart"]').text(DateFormatter.reverseDate(DateFormatter.extractDate(firstElemGoing.departureDate)));
8499      var content = [];
8500      var passengers = goingArr;
8501      var count = 0;
8502
8503      var getTypeNameById = function getTypeNameById(typeId) {
8504        switch (typeId) {
8505          case 1:
8506            return "CHILD";
8507          case 2:
8508            return "ADULT";
8509          case 5:
8510            return "CHILD_A";
8511        }
8512      };
8513
8514      var checkTripPayment = function checkTripPayment(passenger) {
8515        var paymentForm = passenger[0].paymentForm;
8516        _this.isTripPayedPaymee = paymentForm.toLowerCase().includes('pix') || paymentForm === 'PAYMEE';
8517
8518        _this.isPaymentLivelo = paymentForm === "LIVELO";
8519      };
8520
8521      checkTripPayment(passengers);
8522
8523      $.each(passengers, function (i, el) {
8524        if (el.status || el.typeId === 1) {
8525          content.push("\n          <li class=\"passenger-item-list\">\n          <div class=\"custom-control custom-checkbox\">\n            <input class=\"check-confimation custom-control-input check-passenger-trip\" id=\"check-passenger-trip-" + i + "\" data-status=\"" + el.status + "\" data-status-return=\"\" \n        data-type=\"" + getTypeNameById(el.typeId) + "\" data-price-return=\"\" data-price=\"" + (el.typeId === 1 ? 0 : el.amount) + "\" data-saleid=\"" + el.id + "\" data-saleid-return=\"\" \n      data-seat=\"" + el.seat + "\" data-seat-return=\"\" type=\"checkbox\" data-js=\"check-passenger-trip\" data-insurance=\"" + (el.insurance ? el.insurance.insuranceValue : 0) + "\" \n  data-insurance-return=\"\" data-conveniencefee=\"" + el.convenienceFee + "\" data-conveniencefee-return=\"\" data-livelo-points=\"" + el.amountInPoints + "\" data-livelo-points-return=\"\">\n              <label class=\"custom-control-label\" for=\"check-passenger-trip-" + i + "\">\n                " + el.passengerName + "\n              </label>\n            </div>\n          </li>\n        ");
8526        } else if (el.status === 'SALE_NON_REFUNDABLE') {
8527          count++;
8528        }
8529      });
8530
8531      if (count === passengers.length) {
8532        $('.trip-going').find('.checkbox-all .left').empty();
8533        $('.trip-going').find('.checkbox-all .right').empty();
8534        $('.trip-going').find('.attention').show();
8535      } else {
8536        $('[data-js="passenger-list-cancel"]').prepend(content.join(''));
8537      }
8538
8539      //Going Connection Details
8540      if (goingConnectionArr) {
8541        passengers = goingConnectionArr;
8542
8543        $.each(passengers, function (i, el) {
8544          if (el.status || el.typeId === 1) {
8545            $("#check-passenger-trip-" + i).attr("data-seat-going-connection", el.seat);
8546            $("#check-passenger-trip-" + i).attr("data-price-going-connection", el.typeId === 1 ? 0 : el.amount);
8547            $("#check-passenger-trip-" + i).attr("data-status-going-connection", el.status);
8548            $("#check-passenger-trip-" + i).attr("data-saleid-going-connection", el.id);
8549            $("#check-passenger-trip-" + i).attr("data-insurance-going-connection", el.insurance ? el.insurance.insuranceValue : 0);
8550            $("#check-passenger-trip-" + i).attr("data-conveniencefee-going-connection", el.convenienceFee);
8551            $("#check-passenger-trip-" + i).attr("data-livelo-points-going-connection", el.amountInPoints);
8552          }
8553        });
8554      }
8555
8556      //Return Details
8557      if (returnArr) {
8558        origin = Utils.capitalize(firstElemReturn.originDescription);
8559
8560        destination = Utils.capitalize(firstElemReturnConnection ? firstElemReturnConnection.destinationDescription : firstElemReturn.destinationDescription);
8561
8562        dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(firstElemReturn.departureDate));
8563        hourDepart = DateFormatter.extractHour(firstElemReturn.departureDate);
8564        hourArrival = DateFormatter.extractHour(firstElemReturn.arivalDate);
8565
8566        $('[data-js="trip-cancel-return"]').show();
8567        $('[data-js="trip-return"]').show();
8568        $('[data-js="return-summary"]').text('VOLTA - ' + dateDepart);
8569        $('[data-js="return-hour-depart"]').text(hourDepart);
8570        $('[data-js="return-summary-origin"]').text(origin);
8571        $('[data-js="return-hour-arrival"]').text(hourArrival);
8572        $('[data-js="return-summary-destination"]').text(destination);
8573        $('[data-js="going-summary-date-return"]').text(DateFormatter.reverseDate(DateFormatter.extractDate(firstElemReturn.departureDate)));
8574
8575        passengers = returnArr;
8576
8577        $.each(passengers, function (i, el) {
8578          if (el.status || el.typeId === 1) {
8579            $('#check-passenger-trip-' + i).attr('data-seat-return', el.seat);
8580            $('#check-passenger-trip-' + i).attr('data-price-return', el.typeId === 1 ? 0 : el.amount);
8581            $('#check-passenger-trip-' + i).attr('data-status-return', el.status);
8582            $('#check-passenger-trip-' + i).attr('data-saleid-return', el.id);
8583            $('#check-passenger-trip-' + i).attr('data-insurance-return', el.insurance ? el.insurance.insuranceValue : 0);
8584            $('#check-passenger-trip-' + i).attr('data-conveniencefee-return', el.convenienceFee);
8585            $("#check-passenger-trip-" + i).attr("data-livelo-points-return", el.amountInPoints);
8586          }
8587        });
8588      }
8589
8590      //Return Connection Details
8591      if (returnConnectionArr) {
8592        passengers = returnConnectionArr;
8593
8594        $.each(passengers, function (i, el) {
8595          if (el.status || el.typeId === 1) {
8596            $("#check-passenger-trip-" + i).attr("data-seat-return-connection", el.seat);
8597            $("#check-passenger-trip-" + i).attr("data-price-return-connection", el.typeId === 1 ? 0 : el.amount);
8598            $("#check-passenger-trip-" + i).attr("data-status-return-connection", el.status);
8599            $("#check-passenger-trip-" + i).attr("data-saleid-return-connection", el.id);
8600            $("#check-passenger-trip-" + i).attr("data-insurance-return-connection", el.insurance ? el.insurance.insuranceValue : 0);
8601            $("#check-passenger-trip-" + i).attr("data-convenienceFee-return-connection", el.convenienceFee);
8602            $("#check-passenger-trip-" + i).attr("data-livelo-points-return-connection", el.amountInPoints);
8603          }
8604        });
8605      }
8606
8607      this.handlePassengerStatusTripToShowInList();
8608    }
8609  }, {
8610    key: 'displayCancelResults',
8611    value: function displayCancelResults(usersCancelled, usersNotCancelled) {
8612      var totalPriceCancel = 0;
8613      Utils.scrollTop();
8614      OverlayService.hide();
8615      this.confirmContainerOverlay.hide();
8616      this.detailsContainer.hide();
8617      this.confirmContainer.show().focus();
8618      SessionStorage.remove('tripToCancel');
8619
8620      usersCancelled.forEach(function (user) {
8621        $('[data-js="message-success"]').show();
8622        $('[data-js="cancel-passenger-list"]').append('<li> ' + user.name + ' </li>');
8623        totalPriceCancel += parseFloat(user.price);
8624        $('[data-js="cancel-price"]').empty().append('R$ ' + totalPriceCancel.toFixed(2).replace('.', ','));
8625      });
8626
8627      usersNotCancelled.forEach(function (user) {
8628        $('[data-js="cancel-error"]').show();
8629        $('[data-js="cancel-passenger-list-error"]').append('<li> ' + user.name + ' </li>');
8630      });
8631    }
8632  }, {
8633    key: 'handlePassengerStatusTripToShowInList',
8634    value: function handlePassengerStatusTripToShowInList() {
8635      $('[data-js="check-passenger-trip"]').each(function (_, el) {
8636        if ($(el).data("status") !== "SALE_APPROVED" && $(el).data("status-return") !== "SALE_APPROVED" && $(el).data("status") !== "SALE_RELOCATED" && $(el).data("status-return") !== "SALE_RELOCATED") {
8637          $(el).closest('.passenger-item-list').remove();
8638        }
8639      });
8640    }
8641  }, {
8642    key: 'handleReturn',
8643    value: function handleReturn() {
8644      this.linkReturn.click(function () {
8645        $(location).attr('href', $('#myAccountPath').val());
8646      });
8647    }
8648  }, {
8649    key: 'handleCheckboxes',
8650    value: function handleCheckboxes() {
8651      var _this2 = this;
8652
8653      this.selectAllDepartCheck.prop('checked', false);
8654      this.selectAllReturnCheck.prop('checked', false);
8655      this.checkConfirmation.prop('checked', false);
8656
8657      //Check Quantity
8658      this.handlePa
8658ssengersQuantity();
8659
8660      // Select All
8661      this.selectAllDepartCheck.change(function () {
8662        var selectAll = $(this);
8663
8664        $('body').find('.check-passenger-going').each(function () {
8665          $(this).prop('checked', selectAll.is(':checked'));
8666        });
8667      });
8668
8669      // Select All
8670      this.selectAllReturnCheck.change(function () {
8671        var selectAll = $(this);
8672
8673        $('body').find('.check-passenger-return').each(function () {
8674          $(this).prop('checked', selectAll.is(':checked'));
8675        });
8676      });
8677
8678      //Select Single
8679      $('[data-js="passenger-list-going"]').find('input[type="checkbox"]').change(function () {
8680        var goingCheckBoxes = $('[data-js="passenger-list-going"]').find('input[type="checkbox"]');
8681
8682        if (goingCheckBoxes.not(':checked').length > 0) {
8683          _this2.selectAllDepartCheck.prop('checked', false);
8684        } else {
8685          _this2.selectAllDepartCheck.prop('checked', true);
8686        }
8687      });
8688
8689      $('[data-js="passenger-list-return"]').find('input[type="checkbox"]').change(function () {
8690        var returnCheckBoxes = $('[data-js="passenger-list-return"]').find('input[type="checkbox"]');
8691
8692        if (returnCheckBoxes.not(':checked').length > 0) {
8693          _this2.selectAllReturnCheck.prop('checked', false);
8694        } else {
8695          _this2.selectAllReturnCheck.prop('checked', true);
8696        }
8697      });
8698
8699      $('body').find('input[type="checkbox"]').change(function () {
8700        var atLeastOneCancel = false;
8701
8702        $('body').find('.check-passenger').each(function () {
8703          if ($(this).is(':checked')) {
8704            atLeastOneCancel = true;
8705          }
8706        });
8707      });
8708
8709      this.checkboxGoingTrip.on('change', function (e) {
8710        if ($(e.target).is(':checked')) {
8711          _this2.handlePassengerStatusForDep();
8712        } else {
8713          _this2.isPassengerAlreadyCancelGoing = false;
8714        }
8715
8716        _this2.handleNextStepToCancel();
8717      });
8718
8719      this.checkboxReturnTrip.on('change', function (e) {
8720        if ($(e.target).is(':checked')) {
8721          _this2.handlePassengerStatusForReturn();
8722        } else {
8723          _this2.isPassengerAlreadyCancelReturn = false;
8724        }
8725
8726        _this2.handleNextStepToCancel();
8727      });
8728
8729      $('[data-js="check-all-passenger-cancel-trip"]').change(function (e) {
8730        if ($(e.target).is(':checked')) {
8731          $('[data-js="check-passenger-trip"]:not(:checked)').trigger('click');
8732          return;
8733        } else {
8734          $('[data-js="check-passenger-trip"]:checked').trigger('click');
8735        }
8736      });
8737
8738      this.handlePassengerStatus();
8739    }
8740  }, {
8741    key: 'handleNextStepToCancel',
8742    value: function handleNextStepToCancel() {
8743      var isPassengerSelected = $('[data-js="check-passenger-trip"]').is(':checked');
8744
8745      if (this.checkboxGoingTrip.is(':checked') || this.checkboxReturnTrip.is(':checked')) {
8746        if (this.handleChildCancel() && this.handlePassengerCanceled() && isPassengerSelected) {
8747          this.eneableBtnNextStep();
8748        } else {
8749          this.disableBtnNextStep();
8750        }
8751      } else {
8752        this.disableBtnNextStep();
8753        this.hideChildMsgErrorCancelTrip();
8754        this.hideMsgErrorPassengerAlreadyCanceled();
8755      }
8756    }
8757  }, {
8758    key: 'handleCancelTrip',
8759    value: function handleCancelTrip() {
8760      var _this3 = this;
8761
8762      this.btnRequireCancelTrip.click(function () {
8763        _this3.loadValuesModalPassenger();
8764        _this3.loadConfirmationPage();
8765        _this3.advanceToReviewCancelTrip();
8766        _this3.refundDetails();
8767      });
8768
8769      this.btnConfCancelTrip.click(function () {
8770        if (_this3.isTripPayedPaymee) _this3.cancelAsyncSale();
8771        else _this3.cancelSyncSale();
8772      });
8773
8774      this.btnBackTripCancelSelect.on('click', function () {
8775        _this3.resumeCancelTrip.updateResumeCancelTrip(_this3.listPassengersToCancel);
8776        _this3.handleBreadCrumbCancelTrip(1);
8777        _this3.removeListPassengerResumeTrip();
8778        $('[data-js="cancel-trip-refund"]').removeClass('d-none');
8779        $('[data-js="cancel-trip-revision"]').addClass('d-none');
8780
8781        if ($('[data-js="trip-cancel-return"]').is(':visible')) {
8782          $('[data-js="return-section"]').show();
8783        }
8784        $('[data-js="departure-section"]').show();
8785      });
8786    }
8787  }, {
8788    key: 'linsteClick',
8789    value: function linsteClick() {
8790      var refundOpenDetailsText = $('[data-js="refund-open-details-text"]').val();
8791      var refundCloseDetailsText = $('[data-js="refund-close-details-text"]').val();
8792      $(".arrow-details").on("click", function () {
8793        $(".hidden-details").toggleClass("d-none");
8794        if ($(".hidden-details").hasClass("d-none")) {
8795          $("#ver-detalhes").text(refundOpenDetailsText);
8796        } else {
8797          $("#ver-detalhes").text(refundCloseDetailsText);
8798        }
8799      });
8800    }
8801  }, {
8802    key: 'isCommissionFeeValues',
8803    value: function isCommissionFeeValues() {
8804      return $('[data-js="is-commission-fee"]').val() == 'true' ? true : false;
8805    }
8806  }, {
8807    key: 'isCancelationFeeValues',
8808    value: function isCancelationFeeValues() {
8809      return $('[data-js="is-cancellation-fee"]').val() == 'true' ? true : false;
8810    }
8811  }, {
8812    key: 'isServiceFeeValues',
8813    value: function isServiceFeeValues() {
8814      return $('[data-js="is-service-fee"]').val() == 'true' ? true : false;
8815    }
8816  }, {
8817    key: 'isInstallmentValues',
8818    value: function isInstallmentValues() {
8819      return $('[data-js="installment-fee"]').val() == 'true' ? true : false;
8820    }
8821  }, {
8822    key: 'atualizarValores',
8823    value: function atualizarValores(data) {
8824      var totalPayment = data.refunds.totalPayment;
8825      var cancelationFee = data.refunds.penalty.cancellationPenalty + data.refunds.penalty.cancellationPolicy;
8826      var serviceFee = data.refunds.convenienceFee;
8827      var installmentFee = data.refunds.interestAmount - data.refunds.interestAmountToRefund;
8828      var commissionFee = data.refunds.commissionFee;
8829      var totalRefund = data.refunds.refundValue;
8830      var refundConvenienceFee = data.refunds.refundConvenienceFee;
8831      var refundCommissionFee = data.refunds.refundCommissionFee;
8832      var nonRefund = 0;
8833
8834      $('[data-js="refund-total"]').text('R$ ' + Utils.formatPrice(totalPayment));
8835      $('[data-js="non-refund"]').text('-' + 'R$ ' + Utils.formatPrice(nonRefund));
8836      $('[data-js="cancellation-fee"]').text('-' + 'R$ ' + Utils.formatPrice(cancelationFee));
8837      $('[data-js="service-fee"]').text('-' + 'R$ ' + Utils.formatPrice(serviceFee));
8838      $('[data-js="installment-fee"]').text('-' + 'R$ ' + Utils.formatPrice(installmentFee));
8839      $('[data-js="comission-fee"]').text('-' + 'R$ ' + Utils.formatPrice(commissionFee));
8840      $('[data-js="total-refund"]').text('R$ ' + Utils.formatPrice(totalRefund));
8841
8842      if (!refundConvenienceFee) {
8843        nonRefund += data.refunds.convenienceFee;
8844      }
8845
8846      if (!refundCommissionFee) {
8847        nonRefund += data.refunds.commissionFee;
8848      }
8849
8850      nonRefund += data.refunds.interestAmount - data.refunds.interestAmountToRefund;
8851      $('[data-js="non-refund"]').text('-' + 'R$ ' + Utils.formatPrice(nonRefund));
8852
8853      if (refundCommissionFee) {
8854        $('[data-js="comission-fee"]').text('-' + 'R$ ' + Utils.formatPrice(0));
8855      } else {
8856        $('[data-js="comission-fee-value"]').show();
8857      }
8858
8859      if (refundConvenienceFee) {
8860        $('[data-js="service-fee"]').text('-' + 'R$ ' + Utils.formatPrice(0));
8861      } else {
8862        $('[data-js="service-fee-value"]').show();
8863      }
8864    }
8865  }, {
8866    key: 'modalEditable',
8867    value: function modalEditable() {
8868      if ($('[data-js="modal-container-cancel"]').val() == "true") {
8869        new Modal($);
8870        ModalCancel.show();
8871      }
8872
8873      $('[data-js="modal-btn-cancel"]').on('click', function () {
8874        $('[data-js="modal-close"]').click();
8875      });
8876    }
8877  }, {
8878    key: 'loadValuesModalPassenger',
8879    value: function loadValuesModalPassenger() {
8880      $('[data-js="detail-email"]').removeClass("d-none");
8881      var text = $('[data-js="refund-confirmation-email-text"]').val();
8882      var email = $(".main-alert-credit-card").find("p.text span.email").text();
8883      var newText = text + " " + email;
8884      $(".main-alert-credit-card").find("p.text").eq(1).text(newText);
8885      $(".main-alert-credit-card").find("p.text").eq(0).remove();
8886    }
8887  }, {
8888    key: 'refundDetails',
8889    value: function refundDetails() {
8890      var _this4 = this;
8891
8892      var headers = {
8893        Authorization: "" + SessionStorage.get("jca_token"),
8894        version: "2",
8895        channel: Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform)
8896      };
8897
8898      var arrSaleIds = this.usersToCancel.map(function (el, _) {
8899        return el.saleId;
8900      });
8901      var salesIdsParam = arrSaleIds.join(',');
8902
8903      var queryString = 'salesIds=' + salesIdsParam;
8904
8905      LoaderService.show();
8906      HttpService.get('refundDetails?' + queryString, headers).then(function (data) {
8907        LoaderService.hide();
8908        SessionStorage.set("refundDetails", data.result);
8909        _this4.atualizarValores(data.result);
8910      }).catch(function (err) {
8911        LoaderService.hide();
8912        OverlayService.show();
8913        AlertConfirmation.show(i18n("error_cancel"), i18n("error_cancel_try"), true);
8914        $('#overlay, [data-js="close-menu"]').on("click", function () {
8915          $(location).attr('href', $('#homePagePath').val());
8916        });
8917      });
8918    }
8919  }, {
8920    key: "cancelSyncSale",
8921    value: function cancelSyncSale() {
8922      var _this5 = this;
8923
8924      var goingArr = this.tripToCancel[0];
8925      var returnArr = this.tripToCancel[1];
8926      var firstElemGoing = goingArr[0];
8927      var firstElemReturn = returnArr ? returnArr[0] : null;
8928
8929      var paymentForms = ["MALGA", "NUPAY_MALGA", "PIX_BB", "PIX"];
8930
8931      var headers = {
8932        Authorization: "" + SessionStorage.get("jca_token"),
8933        channel: Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform)
8934      };
8935
8936      if (firstElemGoing && firstElemGoing.paymentForm === "MALGA" || firstElemReturn && firstElemReturn.paymentForm === "MALGA") {
8937        headers.flow = 'malga';
8938      }
8939
8940      var arrSaleIds = this.usersToCancel.map(function (el, _) {
8941        return el.saleId;
8942      });
8943
8944      var body = { saleIds: arrSaleIds };
8945
8946      LoaderService.show();
8947      HttpService.post("cancelAsyncSale", body, headers).then(function (response) {
8948        LoaderService.hide();
8949        _this5.handleCancelUsers(response.result);
8950      }).catch(function (err) {
8951        LoaderService.hide();
8952        OverlayService.show();
8953        if (err.responseJSON.result[0].message === $('[data-js="msg-response-confirmation-alert"]').data('cancel-text-response')) {
8954          _this5.handleTicketsAlreadyCanceled(err.responseJSON.result);
8955        } else {
8956          _this5.handleCancelUsers(err.responseJSON.result);
8957        }
8958      });
8959    }
8960  }, {
8961    key: "cancelAsyncSaleLivelo",
8962    value: function cancelAsyncSaleLivelo() {
8963      var _this5 = this;
8964
8965      var headers = {
8966        Authorization: "" + SessionStorage.get("jca_token")
8967      };
8968
8969      var arrSaleIds = this.usersToCancel.map(function (el, _) {
8970        return el.saleId;
8971      });
8972
8973      var body = { SaleIdS: arrSaleIds };
8974
8975      LoaderService.show();
8976      HttpService.post("cancelAsyncSaleLivelo", body, headers).then(function (response) {
8977        LoaderService.hide();
8978        _this5.handleCancelUsers(response.result);
8979      }).catch(function (err) {
8980        LoaderService.hide();
8981        OverlayService.show();
8982        var errorMsgCode = JSON.parse(err.responseJSON.result)
8983        if (errorMsgCode.message === $('[data-js="msg-response-confirmation-alert"]').data('cancel-text-response')) {
8984          _this5.handleTicketsAlreadyCanceled(errorMsgCode);
8985        } else {
8986          _this5.handleCancelUsers(errorMsgCode);
8987        }
8988      });
8989    }
8990  }, {
8991    key: 'cancelAsyncSale',
8992    value: function cancelAsyncSale() {
8993      var _this6 = this;
8994
8995      var headers = {
8996        Authorization: "" + SessionStorage.get("jca_token"),
8997        version: "2",
8998        channel: Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform)
8999      };
9000
9001      var arrSaleIds = this.usersToCancel.map(function (el, _) {
9002        return el.saleId;
9003      });
9004
9005      var body = { saleIds: arrSaleIds };
9006
9007      LoaderService.show();
9008      HttpService.post("cancelAsyncSale", body, headers).then(function (response) {
9009        LoaderService.hide();
9010        _this6.handleCancelUsers(response.result);
9011      }).catch(function (err) {
9012        LoaderService.hide();
9013        OverlayService.show();
9014        if (err.responseJSON.result[0].message === $('[data-js="msg-response-confirmation-alert"]').data('cancel-text-response')) {
9015          _this6.handleTicketsAlreadyCanceled(err.responseJSON.result);
9016        } else {
9017          _this6.handleCancelUsers(err.responseJSON.result);
9018        }
9019      });
9020    }
9021  }, {
9022    key: 'handleTicketsAlreadyCanceled',
9023    value: function handleTicketsAlreadyCanceled(data) {
9024      var arr = data.filter(function (el) {
9025        return el.message == $('[data-js="msg-response-confirmation-alert"]').data('cancel-text-response');
9026      });
9027
9028      if (arr.length == data.length) {
9029        AlertConfirmation.showAEMCancelTrip('data-js="alert-protocol-sending-error"');
9030      } else {
9031        this.handleCancelUsers(data);
9032      }
9033    }
9034  }, {
9035    key: 'handleCancelUsers',
9036    value: function handleCancelUsers(data) {
9037      if (data.length) {
9038
9039        var usersNoCancel = data.filter(function (cancelObj) {
9040          return cancelObj.status != 200;
9041        });
9042
9043        if (usersNoCancel.length) {
9044          var userNoCancelInfo = usersNoCancel.reduce(function (acc, el) {
9045            var obj = { 'name': el.sale.passengerName, 'seat': el.sale.seat, 'destination': el.sale.destinationDescription, 'origin': el.sale.originDescription, 'going': el.sale.going };
9046
9047            acc.push(obj);
9048            return acc;
9049          }, []);
9050
9051          this.renderInfoUserNoCancel(userNoCancelInfo);
9052        } else {
9053          this.successCancel();
9054        }
9055      } else {
9056        AlertConfirmation.showAEMCancelTrip('data-js="alert-protocol-sending-error"');
9057      }
9058    }
9059  }, {
9060    key: 'renderInfoUserNoCancel',
9061    value: function renderInfoUserNoCancel(userNoCancelInfo) {
9062      var content = [];
9063      var passengerGoTrip = userNoCancelInfo.filter(function (user) {
9064        return user.going == true;
9065      });
9066      var passengerBackTrip = userNoCancelInfo.filter(function (user) {
9067        return user.going == false;
9068      });
9069
9070      var generateInformations = function generateInformations(passengerArrWay) {
9071        content.push('\n        <div class="container-description-origin-destination">\n          <p>Origem: ' + passengerArrWay[0].origin + '</p>\n          <p>Destino: ' + passengerArrWay[0].destination + '</p>\n        </div>\n      ');
9072
9073        passengerArrWay.forEach(function (passenger, index) {
9074          content.push('\n          <div>
9074\n            <span>' + passenger.name + '</span>\n            <span> - </span>\n            <span>' + passenger.seat + '</span>\n          </div>\n        ');
9075        });
9076      };
9077
9078      generateInformations(passengerGoTrip);
9079
9080      if (passengerBackTrip.length) generateInformations(passengerBackTrip);
9081
9082      AlertConfirmation.showAEM('data-js="alert-protocol-sending-error"');
9083      $('[data-js="message-confir-subtitle"]').empty().append(content.join(''));
9084    }
9085  }, {
9086    key: 'handlePassengersQuantity',
9087    value: function handlePassengersQuantity() {
9088      var passengersGoingRequirements = this.getPassengerTypeQttListGoing();
9089      var passengersReturnRequirements = this.getPassengerTypeQttListReturn();
9090
9091      this.sumQuantityGoing(passengersGoingRequirements);
9092      this.sumQuantityReturn(passengersReturnRequirements);
9093    }
9094  }, {
9095    key: 'getSelectedPassengers',
9096    value: function getSelectedPassengers() {
9097      self = this;
9098      self.usersToCancel = [];
9099      var selectedPassengers = { going: [], return: [] };
9100
9101      $('[data-js="passenger-list-cancel"]').find('.check-passenger-trip').each(function () {
9102        if ($(this).is(':checked') && !selectedPassengers.going.includes($(this).next().text()) && !selectedPassengers.return.includes($(this).next().text())) {
9103          if ($('[data-js="check-going-trip"]').is(':checked')) {
9104            selectedPassengers.going.push({
9105              "name": $(this).next().text().trim(),
9106              "seat": $(this).data('seat'),
9107              "price": $(this).data('price'),
9108              "type": $(this).data('type'),
9109              "priceConnection": $(this).data('price-going-connection'),
9110              "seatConnection": $(this).data('seat-going-connection'),
9111              "insurance": $(this).data('insurance'),
9112              "insuranceConnection": $(this).data('insurance-going-connection'),
9113              "convenienceFee": $(this).data('conveniencefee'),
9114              "convenienceFeeConnection": $(this).data('conveniencefee-going-connection'),
9115              "liveloPoints": $(this).data('livelo-points'),
9116              "liveloPointsConnection": $(this).data('livelo-points-going-connection')
9117            });
9118            self.usersToCancel.push({
9119              "name": $(this).next().text() + ' - Passagem de ida',
9120              "saleId": $(this).data('saleid'),
9121              "price": $(this).data('price'),
9122              "insurance": $(this).data('insurance'),
9123              "convenienceFee": $(this).data('conveniencefee'),
9124              "liveloPoints": $(this).data('livelo-points')
9125            });
9126
9127            if ($(this).data('price-going-connection')) {
9128              self.usersToCancel.push({
9129                "name": $(this).next().text() + ' - Passagem de ida',
9130                "saleId": $(this).data('saleid-going-connection'),
9131                "price": $(this).data('price-going-connection'),
9132                "insurance": $(this).data('insurance-going-connection'),
9133                "convenienceFee": $(this).data('conveniencefee-going-connection'),
9134                "liveloPoints": $(this).data('livelo-points-going-connection')
9135              });
9136            }
9137          }
9138
9139          if ($('[data-js="check-return-trip"]').is(':checked')) {
9140            selectedPassengers.return.push({
9141              "name": $(this).next().text().trim(),
9142              "seat": $(this).data('seat-return'),
9143              "price": $(this).data('price-return'),
9144              "priceConnection": $(this).data('price-return-connection'),
9145              "seatConnection": $(this).data('seat-return-connection'),
9146              "insuranceReturn": $(this).data('insurance-return'),
9147              "insuranceReturnConnection": $(this).data('insurance-return-connection'),
9148              "convenienceFeeReturn": $(this).data('conveniencefee-return'),
9149              "convenienceFeeReturnConnection": $(this).data('conveniencefee-return-connection'),
9150              "liveloPointsReturn": $(this).data("livelo-points-return"),
9151              "liveloPointsReturnConnection": $(this).data("livelo-points-return-connection")
9152            });
9153            self.usersToCancel.push({
9154              "name": $(this).next().text() + ' - Passagem de volta',
9155              "saleId": $(this).data('saleid-return'),
9156              "price": $(this).data('price-return'),
9157              "insurance": $(this).data('insurance-return'),
9158              "convenienceFee": $(this).data('conveniencefee-return'),
9159              "liveloPoints": $(this).data("livelo-points-return")
9160            });
9161
9162            if ($(this).data('price-return-connection')) {
9163              self.usersToCancel.push({
9164                "name": $(this).next().text() + ' - Passagem de volta',
9165                "saleId": $(this).data('saleid-return-connection'),
9166                "price": $(this).data('price-return-connection'),
9167                "insurance": $(this).data('insurance-return-connection'),
9168                "convenienceFee": $(this).data('conveniencefee-return-connection'),
9169                "liveloPoints": $(this).data("livelo-points-return-connection")
9170              });
9171            }
9172          }
9173        }
9174      });
9175
9176      return selectedPassengers;
9177    }
9178  }, {
9179    key: 'getPassengerTypeQttListGoing',
9180    value: function getPassengerTypeQttListGoing() {
9181      var reg_qtt_going = 0;
9182      var chd_a_qtt_going = 0;
9183      var chd_qtt_going = 0;
9184
9185      $('[data-js="check-passenger-trip"]').each(function (_, el) {
9186        if ($(el).data('status') == 'SALE_APPROVED' || $(el).data('status') == 'SALE_RELOCATED') {
9187          reg_qtt_going += $(el).data('type') === 'ADULT' ? 1 : 0;
9188          chd_a_qtt_going += $(el).data('type') === 'CHILD_A' ? 1 : 0;
9189          chd_qtt_going += $(el).data('type') === 'CHILD' ? 1 : 0;
9190        }
9191      });
9192
9193      return { reg_qtt_going: reg_qtt_going, chd_a_qtt_going: chd_a_qtt_going, chd_qtt_going: chd_qtt_going };
9194    }
9195  }, {
9196    key: 'getPassengerTypeQttListReturn',
9197    value: function getPassengerTypeQttListReturn() {
9198      var reg_qtt_return = 0;
9199      var chd_a_qtt_return = 0;
9200      var chd_qtt_return = 0;
9201
9202      $('[data-js="check-passenger-trip"]').each(function (_, el) {
9203        if ($(el).data('status-return') == 'SALE_APPROVED' || $(el).data('status-return') == 'SALE_RELOCATED') {
9204          reg_qtt_return += $(el).data('type') === 'ADULT' ? 1 : 0;
9205          chd_a_qtt_return += $(el).data('type') === 'CHILD_A' ? 1 : 0;
9206          chd_qtt_return += $(el).data('type') === 'CHILD' ? 1 : 0;
9207        }
9208      });
9209
9210      return { reg_qtt_return: reg_qtt_return, chd_a_qtt_return: chd_a_qtt_return, chd_qtt_return: chd_qtt_return };
9211    }
9212  }, {
9213    key: 'sumQuantityGoing',
9214    value: function sumQuantityGoing(requirements) {
9215      var _this4 = this;
9216
9217      var reg_qtt_going = requirements.reg_qtt_going,
9218        chd_a_qtt_going = requirements.chd_a_qtt_going,
9219        chd_qtt_going = requirements.chd_qtt_going;
9220
9221
9222      $('[data-js="passenger-list-cancel"]').find('input[type="checkbox"]').change(function (e) {
9223        if ($(e.target).data("status") === "SALE_APPROVED" || $(e.target).data("status") === "SALE_RELOCATED") {
9224          var passengerType = $(e.target).data('type');
9225          var isChecked = $(e.target).is(':checked');
9226
9227          switch (passengerType) {
9228            case 'ADULT':
9229              if (isChecked) {
9230                reg_qtt_going--;
9231              } else {
9232                reg_qtt_going++;
9233              }
9234              break;
9235
9236            case 'CHILD_A':
9237              if (isChecked) {
9238                chd_a_qtt_going--;
9239              } else {
9240                chd_a_qtt_going++;
9241              }
9242              break;
9243
9244            case 'CHILD':
9245              if (isChecked) {
9246                chd_qtt_going--;
9247              } else {
9248                chd_qtt_going++;
9249              }
9250              break;
9251          }
9252
9253          if (reg_qtt_going < chd_a_qtt_going || reg_qtt_going < chd_qtt_going) {
9254            _this4.isQuantityGoingChecked = false;
9255          } else {
9256            _this4.isQuantityGoingChecked = true;
9257          }
9258        }
9259      });
9260    }
9261  }, {
9262    key: 'sumQuantityReturn',
9263    value: function sumQuantityReturn(requirements) {
9264      var _this5 = this;
9265
9266      var reg_qtt_return = requirements.reg_qtt_return,
9267        chd_a_qtt_return = requirements.chd_a_qtt_return,
9268        chd_qtt_return = requirements.chd_qtt_return;
9269
9270
9271      $('[data-js="passenger-list-cancel"]').find('input[type="checkbox"]').change(function (e) {
9272        if ($(e.target).data("status-return") === "SALE_APPROVED" || $(e.target).data("status-return") === "SALE_RELOCATED") {
9273          var passengerType = $(e.target).data('type');
9274          var isChecked = $(e.target).is(':checked');
9275
9276          switch (passengerType) {
9277            case 'ADULT':
9278              if (isChecked) {
9279                reg_qtt_return--;
9280              } else {
9281                reg_qtt_return++;
9282              }
9283              break;
9284
9285            case 'CHILD_A':
9286              if (isChecked) {
9287                chd_a_qtt_return--;
9288              } else {
9289                chd_a_qtt_return++;
9290              }
9291              break;
9292
9293            case 'CHILD':
9294              if (isChecked) {
9295                chd_qtt_return--;
9296              } else {
9297                chd_qtt_return++;
9298              }
9299              break;
9300          }
9301
9302          if (reg_qtt_return < chd_a_qtt_return || reg_qtt_return < chd_qtt_return) {
9303            _this5.isQuantityReturnChecked = false;
9304          } else {
9305            _this5.isQuantityReturnChecked = true;
9306          }
9307        }
9308      });
9309    }
9310  }, {
9311    key: "advanceToReviewCancelTrip",
9312    value: function advanceToReviewCancelTrip() {
9313      var isTripGoingSelected = this.checkboxGoingTrip.is(":checked");
9314      var isTripReturnSelected = this.checkboxReturnTrip.is(":checked");
9315
9316      if (!isTripGoingSelected) {
9317        $('[data-js="departure-section"]').hide();
9318      }
9319
9320      if (!isTripReturnSelected) {
9321        $('[data-js="return-section"]').hide();
9322      }
9323
9324      this.resumeCancelTrip.updateResumeCancelTrip(this.listPassengersToCancel, this.convenienceFee);
9325      $('[data-js="cancel-trip-refund"]').addClass("d-none");
9326      $('[data-js="cancel-trip-revision"]').removeClass("d-none");
9327      this.handleBreadCrumbCancelTrip(2);
9328      this.addListPassengerResumeTrip();
9329    }
9330  }, {
9331    key: 'successCancel',
9332    value: function successCancel() {
9333      $('[data-js="cancel-trip-revision"]').addClass('d-none');
9334      $('[data-js="cancel-trip-confirm"]').removeClass('d-none');
9335      $('[data-js="detail-email"]').removeClass('d-none');
9336      $('[data-js="resume-trip-cancel"]').addClass('d-none');
9337      this.handleBreadCrumbCancelTrip(3);
9338      SessionStorage.remove('tripToCancel');
9339    }
9340  }, {
9341    key: 'eneableBtnNextStep',
9342    value: function eneableBtnNextStep() {
9343      this.btnRequireCancelTrip.attr('disabled', false);
9344    }
9345  }, {
9346    key: 'disableBtnNextStep',
9347    value: function disableBtnNextStep() {
9348      this.btnRequireCancelTrip.attr('disabled', true);
9349    }
9350  }, {
9351    key: 'setTaxRefund',
9352    value: function setTaxRefund() {
9353      var taxRefundValue = $('[data-js="tax-refund-attr"]').val();
9354
9355      $('[data-js="tax-refund"]').text(taxRefundValue + '%');
9356    }
9357  }, {
9358    key: 'loadConfirmationPage',
9359    value: function loadConfirmationPage() {
9360      this.listPassengersToCancel = this.getSelectedPassengers();
9361      var goingArr = this.tripToCancel[0];
9362      var returnArr = this.tripToCancel[2];
9363      var firstElemGoing = goingArr[0];
9364      var firstElemReturn = returnArr ? returnArr[0] : null;
9365
9366      this.passGoingList.empty();
9367      this.passReturnList.empty();
9368      $('[data-js="passengers-going"]').hide();
9369      $('[data-js="passengers-return"]').hide();
9370      var content = [];
9371
9372      var origin = firstElemGoing.originDescription;
9373      var destination = firstElemGoing.destinationDescription;
9374      var dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(firstElemGoing.departureDate));
9375      var hourDepart = DateFormatter.extractHour(firstElemGoing.departureDate);
9376
9377      if (this.listPassengersToCancel.going.length > 0) {
9378        $('[data-js="passengers-going"]').show();
9379        this.cancelGoingText.text('(' + origin + ' - ' + destination + ') - ' + dateDepart + ' - ' + hourDepart + '');
9380        $.each(this.listPassengersToCancel.going, function (_, el) {
9381          return content.push('<li class="passenger-name">' + el + '</li>');
9382        });
9383        this.passGoingList.append(content.join(''));
9384      }
9385
9386      if (this.listPassengersToCancel.return.length > 0) {
9387        origin = firstElemReturn.originDescription;
9388        destination = firstElemReturn.destinationDescription;
9389        dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(firstElemReturn.departureDate));
9390        hourDepart = DateFormatter.extractHour(firstElemReturn.departureDate);
9391        content = [];
9392
9393        $('[data-js="passengers-return"]').show();
9394        this.cancelReturnText.text('(' + origin + ' - ' + destination + ') - ' + dateDepart + ' - ' + hourDepart + '');
9395        $.each(this.listPassengersToCancel.return, function (_, el) {
9396          return content.push('<li class="passenger-name">' + el + '</li>');
9397        });
9398        this.passReturnList.append(content.join(''));
9399      }
9400    }
9401  }, {
9402    key: 'addListPassengerResumeTrip',
9403    value: function addListPassengerResumeTrip() {
9404      $('[data-js="departure-section"]').find('[data-js="trip-details-show-passenger"]').show();
9405      $('[data-js="return-section"]').find('[data-js="trip-details-show-passenger"]').show();
9406    }
9407  }, {
9408    key: 'removeListPassengerResumeTrip',
9409    value: function removeListPassengerResumeTrip() {
9410      $('[data-js="departure-section"]').find('[data-js="trip-details-show-passenger"]').hide();
9411      $('[data-js="return-section"]').find('[data-js="trip-details-show-passenger"]').hide();
9412    }
9413  }, {
9414    key: 'showMsgErrorPassengerAlreadyCanceled',
9415    value: function showMsgErrorPassengerAlreadyCanceled(msgError) {
9416      this.errMsgPassengerStatus.text(msgError).parent().show();
9417    }
9418  }, {
9419    key: 'hideMsgErrorPassengerAlreadyCanceled',
9420    value: function hideMsgErrorPassengerAlreadyCanceled() {
9421      this.errMsgPassengerStatus.parent().hide();
9422    }
9423  }, {
9424    key: 'showChildMsgErrorCancelTrip',
9425    value: function showChildMsgErrorCancelTrip() {
9426      this.errMsgChildCancelTrip.text($('[data-js="error-msg-cancel-child"]').val()).parent().show();
9427    }
9428  }, {
9429    key: 'hideChildMsgErrorCancelTrip',
9430    value: function hideChildMsgErrorCancelTrip() {
9431      this.errMsgChildCancelTrip.parent().hide();
9432    }
9433  }, {
9434    key: 'handlePassengerStatus',
9435    value: function handlePassengerStatus() {
9436      var _this6 = this;
9437
9438      $('[data-js="check-passenger-trip"]').on('change', function (e) {
9439        if ($(e.target).is(':checked')) {
9440          $(e.target).data("status") !== "SALE_APPROVED" && $(e.target).data("status") !== "SALE_RELOCATED" ? _this6.listPassengerCancelGoing++ : "";
9441          $(e.target).data("status-return") !== "SALE_APPROVED" && $(e.target).data("status-return") !== "SALE_RELOCATED" ? _this6.listPassengerCancelReturn++ : "";
9442        } else {
9443          $(e.target).data("status") !== "SALE_APPROVED" && $(e.target).data("status") !== "SALE_RELOCATED" ? _this6.listPassengerCancelGoing-- : "";
9444          $(e.target).data("status-return") !== "SALE_APPROVED" && $(e.target).data("status-return") !== "SALE_RELOCATED" ? _this6.listPassengerCancelReturn-- 
9444: "";
9445        }
9446
9447        if (_this6.checkboxGoingTrip.is(':checked')) {
9448          _this6.checkboxGoingTrip.trigger('change');
9449        }
9450
9451        if (_this6.checkboxReturnTrip.is(':checked')) {
9452          _this6.checkboxReturnTrip.trigger('change');
9453        }
9454      });
9455    }
9456  }, {
9457    key: 'handlePassengerStatusForDep',
9458    value: function handlePassengerStatusForDep() {
9459      this.listPassengerCancelGoing > 0 ? this.isPassengerAlreadyCancelGoing = true : this.isPassengerAlreadyCancelGoing = false;
9460    }
9461  }, {
9462    key: 'handlePassengerStatusForReturn',
9463    value: function handlePassengerStatusForReturn() {
9464      this.listPassengerCancelReturn > 0 ? this.isPassengerAlreadyCancelReturn = true : this.isPassengerAlreadyCancelReturn = false;
9465    }
9466  }, {
9467    key: 'handleChildCancel',
9468    value: function handleChildCancel() {
9469      if (this.isQuantityGoingChecked && this.isQuantityReturnChecked) {
9470        this.hideChildMsgErrorCancelTrip();
9471        return true;
9472      } else {
9473        this.showChildMsgErrorCancelTrip();
9474        return false;
9475      }
9476    }
9477  }, {
9478    key: "blockedPassCheckbox",
9479    value: function blockedPassCheckbox() {
9480      var ticketData = SessionStorage.get("tripToCancel");
9481      var statusTicketDep = ticketData[0][0].status;
9482      var statusTicketRet = ticketData[2] ? ticketData[2][0].status : null;
9483
9484      if (statusTicketDep === "SALE_NON_REFUNDABLE") {
9485        $('[data-js="check-going-trip"]').addClass('d-none');
9486        $('[data-js="check-going-trip"]').siblings('label.custom-control-label').css('display', 'none');
9487        $('.no-refundable-message').removeClass('d-none');
9488      }
9489
9490      if (statusTicketRet === "SALE_NON_REFUNDABLE") {
9491        $('[data-js="check-return-trip"]').hide();
9492        $('[data-js="check-return-trip"]').siblings('label.custom-control-label').css('display', 'none');
9493      }
9494    }
9495  }, {
9496    key: 'handlePassengerCanceled',
9497    value: function handlePassengerCanceled() {
9498      if (this.isPassengerAlreadyCancelGoing || this.isPassengerAlreadyCancelReturn) {
9499        this.showMsgErrorPassengerAlreadyCanceled(i18n('err_msg_passenger_canceled'));
9500        return false;
9501      } else {
9502        this.hideMsgErrorPassengerAlreadyCanceled();
9503        return true;
9504      }
9505    }
9506  }]);
9507
9508  return CancelTripController;
9509}();
9510"use strict";
9511
9512var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
9513
9514function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
9515
9516var CancelTripControllerNew = function () {
9517  function CancelTripControllerNew($) {
9518    _classCallCheck(this, CancelTripControllerNew);
9519
9520    this.user = SessionStorage.get("passenger");
9521    this.tripToCancel = SessionStorage.get("tripToCancel");
9522    this.linkReturn = $('[data-js="link-return"]');
9523    this.highlightUser = $('[data-js="highlight-user"]');
9524    this.selectAllDepartCheck = $('[data-js="select-all-depart-check"]');
9525    this.selectAllReturnCheck = $('[data-js="select-all-return-check"]');
9526    this.checkConfirmation = $('[data-js="check-confirmation"]');
9527    this.btnOpenConfirm = $('[data-js="btn-open-confirm"]');
9528    this.btnRequireCancelTrip = $('[data-js="trip-cancel-next"]');
9529    this.btnBackCancelTrip = $('[data-js="trip-cancel-back"]');
9530    this.btnSubmit = $('[data-js="btn-submit"]');
9531    this.closeConfiration = $('[data-js="close-confirmation"]');
9532    this.cancelGoingText = $('[data-js="cancel-going-text"]');
9533    this.cancelReturnText = $('[data-js="cancel-return-text"]');
9534    this.passGoingList = $('[data-js="passengers-going-list"]');
9535    this.passReturnList = $('[data-js="passengers-return-list"]');
9536    this.confirmContainerOverlay = $('[data-js="cancel-trip-confirmation-overlay"]');
9537    this.confirmContainer = $('[data-js="cancel-trip-confirmation"]');
9538    this.detailsContainer = $('[data-js="cancel-trip-details"]');
9539    this.checkboxGoingTrip = $('[data-js="check-going-trip"]');
9540    this.checkboxReturnTrip = $('[data-js="check-return-trip"]');
9541    this.btnBackTripCancelSelect = $('[data-js="back-trip-cancel-select"]');
9542    this.btnConfCancelTrip = $('[data-js="trip-cancel-confirm"]');
9543    this.errMsgPassengerStatus = $('[data-js="msg-error-status-cancel"]');
9544    this.errMsgChildCancelTrip = $('[data-js="msg-child-error-cancel"]');
9545    this.convenienceFee = $('[data-js="convenience-fee"]').attr('value') == 'true';
9546    this.isQuantityGoingChecked = true;
9547    this.isQuantityReturnChecked = true;
9548    this.listPassengersToCancel;
9549    this.usersToCancel = [];
9550    this.listPassengerCancelGoing = 0;
9551    this.listPassengerCancelReturn = 0;
9552    this.isPassengerAlreadyCancelGoing;
9553    this.isPassengerAlreadyCancelReturn;
9554    this.isTripPayedPaymee = false;
9555    this.isPaymentLivelo = false;
9556    this.isPaymentWallet = false;
9557    this.resumeCancelTrip = new ResumeCancelTripController($);
9558    new AlertCreditCard($);
9559    this.init();
9560  }
9561
9562  _createClass(CancelTripControllerNew, [{
9563    key: "init",
9564    value: function init() {
9565      var walletCreatedCancel = SessionStorage.get('walletCreatedCancel');
9566
9567      this.handleRefundMessage();
9568      if (walletCreatedCancel) {
9569        SessionStorage.remove('walletCreatedCancel');
9570        this.restoreLayoutState();
9571        this.showProcessingModal(i18n('refund_processing_subtitle'));
9572        this.cancelSaleWallet();
9573      } else {
9574        this.linsteClick();
9575        this.modalEditable();
9576        if (this.tripToCancel) {
9577          this.displayDetails(this.tripToCancel);
9578          this.handleReturn();
9579          this.handleCheckboxes();
9580          this.handleCancelTrip();
9581          this.setTaxRefund();
9582          this.removeListPassengerResumeTrip();
9583          this.handlePassengerStatus();
9584          this.handleConvenienceFee();
9585          this.blockedPassCheckbox();
9586          this.listenClickChoice();
9587        } else {
9588          $(location).attr("href", i18n('my_account_page'));
9589        }
9590      }
9591    }
9592  }, {
9593    key: "handleRefundMessage",
9594    value: function handleRefundMessage() {
9595      this.isTripPayedPaymee = this.tripToCancel[0][0].paymentForm.toLowerCase().includes("pix") || this.tripToCancel[0][0].paymentForm === "PAYMEE";
9596
9597      if (this.isTripPayedPaymee) {
9598        $('[data-js="refund-title"]').text(i18n('refund_pix_title'));
9599        $('[data-js="refund-message-text"]').text(i18n('refund_pix_message'));
9600      }
9601    }
9602  }, {
9603    key: "restoreLayoutState",
9604    value: function restoreLayoutState() {
9605      if (this.tripToCancel) {
9606        this.usersToCancel = SessionStorage.get('usersToCancel');
9607        this.arrSaleIds = this.usersToCancel.map(function (el, _) {
9608          return el.saleId;
9609        });
9610        this.displayDetails(this.tripToCancel);
9611        this.loadValuesModalPassenger();
9612        this.loadConfirmationPage();
9613        this.advanceToReviewCancelTrip();
9614        this.atualizarValores(SessionStorage.get("refundDetails"));
9615        $('[data-js="passenger-list-cancel"]').parent().removeClass('d-none');
9616      } else {
9617        $(location).attr("href", i18n('my_account_page'));
9618      }
9619    }
9620  }, {
9621    key: "handleConvenienceFee",
9622    value: function handleConvenienceFee() {
9623      if (this.convenienceFee) {
9624        $(".convenience-fee").removeClass("d-none");
9625        $(".txt-convenience-fee").text(i18n("not_refundable_convenience_fee"));
9626      } else $(".convenience-.convenience-fee").addClass("d-none");
9627    }
9628  }, {
9629    key: "displayDetails",
9630    value: function displayDetails(parsedHistory) {
9631      var _this = this;
9632
9633      var goingArr = parsedHistory[0];
9634      var goingConnectionArr = parsedHistory[1];
9635      var returnArr = parsedHistory[2];
9636      var returnConnectionArr = parsedHistory[3];
9637
9638      var firstElemGoing = goingArr[0];
9639      var firstElemGoingConnection = goingConnectionArr ? goingConnectionArr[0] : null;
9640      var firstElemReturn = returnArr ? returnArr[0] : null;
9641      var firstElemReturnConnection = returnConnectionArr ? returnConnectionArr[0] : null;
9642
9643      var mainRegisterCode = firstElemGoing.finder;
9644      var origin = Utils.capitalize(firstElemGoing.originDescription);
9645
9646      var destination = Utils.capitalize(firstElemGoingConnection ? firstElemGoingConnection.destinationDescription : firstElemGoing.destinationDescription);
9647
9648      var dateInit = firstElemGoing.departureDate;
9649      var dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(dateInit));
9650      var hourDepart = DateFormatter.extractHour(firstElemGoing.departureDate);
9651      var hourArrival = DateFormatter.extractHour(firstElemGoing.arivalDate);
9652
9653      $('[data-js="num-code"]').text(mainRegisterCode);
9654      $('[data-js="going-summary"]').text("IDA - " + dateDepart);
9655      $('[data-js="going-hour-depart"]').text(hourDepart);
9656      $('[data-js="going-summary-origin"]').text(origin);
9657      $('[data-js="going-hour-arrival"]').text(hourArrival);
9658      $('[data-js="going-summary-destination"]').text(destination);
9659      $('[data-js="going-summary-date-depart"]').text(DateFormatter.reverseDate(DateFormatter.extractDate(firstElemGoing.departureDate)));
9660      var content = [];
9661      var passengers = goingArr;
9662      var count = 0;
9663
9664      var getTypeNameById = function getTypeNameById(typeId) {
9665        switch (typeId) {
9666          case 1:
9667            return "CHILD";
9668          case 2:
9669            return "ADULT";
9670          case 5:
9671            return "CHILD_A";
9672        }
9673      };
9674
9675      var checkTripPayment = function checkTripPayment(passenger) {
9676        var paymentForm = passenger[0].paymentForm;
9677        _this.isTripPayedPaymee = paymentForm.toLowerCase().includes("pix") || paymentForm === "PAYMEE";
9678
9679        _this.isPaymentLivelo = paymentForm === "LIVELO";
9680        _this.isPaymentWallet = paymentForm.toLowerCase() === "wallet";
9681      };
9682
9683      checkTripPayment(passengers);
9684
9685      $.each(passengers, function (i, el) {
9686        if (el.status || el.typeId === 1) {
9687          content.push("\n          <li class=\"passenger-item-list\">\n            <div class=\"custom-control custom-checkbox\">\n              <input class=\"check-confimation custom-control-input check-passenger-trip\" id=\"check-passenger-trip-" + i + "\" data-status=\"" + el.status + "\" data-status-return=\"\"\n                data-type=\"" + getTypeNameById(el.typeId) + "\" data-price-return=\"\" data-price=\"" + (el.typeId === 1 ? 0 : el.amount) + "\" data-saleid=\"" + el.id + "\" data-saleid-return=\"\"\n                data-seat=\"" + el.seat + "\" data-seat-return=\"\" type=\"checkbox\" data-js=\"check-passenger-trip\" data-insurance=\"" + (el.insurance ? el.insurance.insuranceValue : 0) + "\"\n                data-insurance-return=\"\" data-conveniencefee=\"" + el.convenienceFee + "\" data-conveniencefee-return=\"\" data-livelo-points=\"" + el.amountInPoints + "\" data-livelo-points-return=\"\">\n              <label class=\"custom-control-label\" for=\"check-passenger-trip-" + i + "\">\n                " + el.passengerName + "\n              </label>\n            </div>\n          </li>\n        ");
9688        } else if (el.status === "SALE_NON_REFUNDABLE") {
9689          count++;
9690        }
9691      });
9692
9693      if (count === passengers.length) {
9694        $(".trip-going").find(".checkbox-all .left").empty();
9695        $(".trip-going").find(".checkbox-all .right").empty();
9696        $(".trip-going").find(".attention").show();
9697      } else {
9698        $('[data-js="passenger-list-cancel"]').prepend(content.join(""));
9699      }
9700
9701      //Going Connection Details
9702      if (goingConnectionArr) {
9703        passengers = goingConnectionArr;
9704
9705        $.each(passengers, function (i, el) {
9706          if (el.status || el.typeId === 1) {
9707            $("#check-passenger-trip-" + i).attr("data-seat-going-connection", el.seat);
9708            $("#check-passenger-trip-" + i).attr("data-price-going-connection", el.typeId === 1 ? 0 : el.amount);
9709            $("#check-passenger-trip-" + i).attr("data-status-going-connection", el.status);
9710            $("#check-passenger-trip-" + i).attr("data-saleid-going-connection", el.id);
9711            $("#check-passenger-trip-" + i).attr("data-insurance-going-connection", el.insurance ? el.insurance.insuranceValue : 0);
9712            $("#check-passenger-trip-" + i).attr("data-conveniencefee-going-connection", el.convenienceFee);
9713            $("#check-passenger-trip-" + i).attr("data-livelo-points-going-connection", el.amountInPoints);
9714          }
9715        });
9716      }
9717
9718      //Return Details
9719      if (returnArr) {
9720        origin = Utils.capitalize(firstElemReturn.originDescription);
9721
9722        destination = Utils.capitalize(firstElemReturnConnection ? firstElemReturnConnection.destinationDescription : firstElemReturn.destinationDescription);
9723
9724        dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(firstElemReturn.departureDate));
9725        hourDepart = DateFormatter.extractHour(firstElemReturn.departureDate);
9726        hourArrival = DateFormatter.extractHour(firstElemReturn.arivalDate);
9727
9728        $('[data-js="trip-cancel-return"]').show();
9729        $('[data-js="trip-return"]').show();
9730        $('[data-js="return-summary"]').text("VOLTA - " + dateDepart);
9731        $('[data-js="return-hour-depart"]').text(hourDepart);
9732        $('[data-js="return-summary-origin"]').text(origin);
9733        $('[data-js="return-hour-arrival"]').text(hourArrival);
9734        $('[data-js="return-summary-destination"]').text(destination);
9735        $('[data-js="going-summary-date-return"]').text(DateFormatter.reverseDate(DateFormatter.extractDate(firstElemReturn.departureDate)));
9736
9737        passengers = returnArr;
9738
9739        $.each(passengers, function (i, el) {
9740          if (el.status || el.typeId === 1) {
9741            $("#check-passenger-trip-" + i).attr("data-seat-return", el.seat);
9742            $("#check-passenger-trip-" + i).attr("data-price-return", el.typeId === 1 ? 0 : el.amount);
9743            $("#check-passenger-trip-" + i).attr("data-status-return", el.status);
9744            $("#check-passenger-trip-" + i).attr("data-saleid-return", el.id);
9745            $("#check-passenger-trip-" + i).attr("data-insurance-return", el.insurance ? el.insurance.insuranceValue : 0);
9746            $("#check-passenger-trip-" + i).attr("data-conveniencefee-return", el.convenienceFee);
9747            $("#check-passenger-trip-" + i).attr("data-livelo-points-return", el.amountInPoints);
9748          }
9749        });
9750      }
9751
9752      //Return Connection Details
9753      if (returnConnectionArr) {
9754        passengers = returnConnectionArr;
9755
9756        $.each(passengers, function (i, el) {
9757          if (el.status || el.typeId === 1) {
9758            $("#check-passenger-trip-" + i).attr("data-seat-return-connection", el.seat);
9759            $("#check-passenger-trip-" + i).attr("data-price-return-connection", el.typeId === 1 ? 0 : el.amount);
9760            $("#check-passenger-trip-" + i).attr("data-status-return-connection", el.status);
9761            $("#check-passenger-trip-" + i).attr("data-saleid-return-connection", el.id);
9762            $("#check-passenger-trip-" + i).attr("data-insurance-return-connection", el.insurance ? el.insurance.insuranceValue : 0);
9763            $("#check-passenger-trip-" + i).attr("data-convenienceFee-return-connection", el.convenienceFee);
9764            $("#check-passenger-trip-" + i).attr("data-livelo-points-return-connection", el.amountInPoints);
9765          }
9766        });
9767      }
9768
9769      this.handlePassengerStatusTripToShowInList();
9770    }
9771  }, {
9772    key: "displayCancelResults",
9773    value: function displayCancelResults(usersCancelled, usersNotCancelled) {
9774      var totalPriceCancel = 0;
9775      Utils.scrollTop();
9776      OverlayService.hide();
9777      this.confirmContainerOverlay.hide();
9778      this.detailsContainer.hide();
9779      this.confirmContainer.show().focus();
9780      SessionStorage.remove("tripToCancel");
9781
9782      usersCancelled.forEach(function (user) {
9783        $('[data-js="message-success"]').show();
9784        $('[data-js="cancel-passenger-list"]').append("<li> " + user.name + " </li>");
9785        totalPriceCancel += parseFloat(user.price);
9786        $('[data-js="cancel-price"]').empty().append("R$ " + totalPriceCancel.toFixed(2).replace(".", ","));
9787      });
9788
9789      usersNotCancelled.forEach(function (user) {
9790        $('[data-js="cancel-error"]').show();
9791        $('[data-js="cancel-passenger-list-error"]').append("<li> " + user.name + " </li>");
9792      });
9793    }
9794  }, {
9795    key: "handlePassengerStatusTripToShowInList",
9796    value: function handlePassengerStatusTripToShowInList() {
9797      $('[data-js="check-passenger-trip"]').each(function (_, el) {
9798        if ($(el).data("status") !== "SALE_APPROVED" && $(el).data("status-return") !== "SALE_APPROVED" && $(el).data("status") !== "SALE_RELOCATED" && $(el).data("status-return") !== "SALE_RELOCATED") {
9799          $(el).closest(".passenger-item-list").remove();
9800        }
9801      });
9802    }
9803  }, {
9804    key: "handleReturn",
9805    value: function handleReturn() {
9806      this.linkReturn.click(function () {
9807        $(location).attr("href", i18n('my_account_page'));
9808      });
9809    }
9810  }, {
9811    key: "handleCheckboxes",
9812    value: function handleCheckboxes() {
9813      var _this2 = this;
9814
9815      this.selectAllDepartCheck.prop("checked", false);
9816      this.selectAllReturnCheck.prop("checked", false);
9817      this.checkConfirmation.prop("checked", false);
9818
9819      //Check Quantity
9820      this.handlePassengersQuantity();
9821
9822      // Select All
9823      this.selectAllDepartCheck.change(function () {
9824        var selectAll = $(this);
9825
9826        $("body").find(".check-passenger-going").each(function () {
9827          $(this).prop("checked", selectAll.is(":checked"));
9828        });
9829      });
9830
9831      // Select All
9832      this.selectAllReturnCheck.change(function () {
9833        var selectAll = $(this);
9834
9835        $("body").find(".check-passenger-return").each(function () {
9836          $(this).prop("checked", selectAll.is(":checked"));
9837        });
9838      });
9839
9840      //Select Single
9841      $('[data-js="passenger-list-going"]').find('input[type="checkbox"]').change(function () {
9842        var goingCheckBoxes = $('[data-js="passenger-list-going"]').find('input[type="checkbox"]');
9843
9844        if (goingCheckBoxes.not(":checked").length > 0) {
9845          _this2.selectAllDepartCheck.prop("checked", false);
9846        } else {
9847          _this2.selectAllDepartCheck.prop("checked", true);
9848        }
9849      });
9850
9851      $('[data-js="passenger-list-return"]').find('input[type="checkbox"]').change(function () {
9852        var returnCheckBoxes = $('[data-js="passenger-list-return"]').find('input[type="checkbox"]');
9853
9854        if (returnCheckBoxes.not(":checked").length > 0) {
9855          _this2.selectAllReturnCheck.prop("checked", false);
9856        } else {
9857          _this2.selectAllReturnCheck.prop("checked", true);
9858        }
9859      });
9860
9861      $("body").find('input[type="checkbox"]').change(function () {
9862        var atLeastOneCancel = false;
9863
9864        $("body").find(".check-passenger").each(function () {
9865          if ($(this).is(":checked")) {
9866            atLeastOneCancel = true;
9867          }
9868        });
9869      });
9870
9871      this.checkboxGoingTrip.on("change", function (e) {
9872        if ($(e.target).is(":checked")) {
9873          _this2.handlePassengerStatusForDep();
9874          $('[data-js="passenger-list-cancel"]').parent().removeClass('d-none');
9875        } else {
9876          _this2.isPassengerAlreadyCancelGoing = false;
9877          if (!_this2.checkboxReturnTrip.is(":checked")) {
9878            $('[data-js="passenger-list-cancel"]').parent().addClass('d-none');
9879          }
9880        }
9881
9882        _this2.handleNextStepToCancel();
9883      });
9884
9885      this.checkboxReturnTrip.on("change", function (e) {
9886        if ($(e.target).is(":checked")) {
9887          _this2.handlePassengerStatusForReturn();
9888          $('[data-js="passenger-list-cancel"]').parent().removeClass('d-none');
9889        } else {
9890          _this2.isPassengerAlreadyCancelReturn = false;
9891          if (!_this2.checkboxGoingTrip.is(":checked")) {
9892            $('[data-js="passenger-list-cancel"]').parent().addClass('d-none');
9893          }
9894        }
9895
9896        _this2.handleNextStepToCancel();
9897      });
9898
9899      $('[data-js="check-all-passenger-cancel-trip"]').change(function (e) {
9900        if ($(e.target).is(":checked")) {
9901          $('[data-js="check-passenger-trip"]:not(:checked)').trigger("click");
9902          return;
9903        } else {
9904          $('[data-js="check-passenger-trip"]:checked').trigger("click");
9905        }
9906      });
9907
9908      this.handlePassengerStatus();
9909    }
9910  }, {
9911    key: "handleNextStepToCancel",
9912    value: function handleNextStepToCancel() {
9913      var isPassengerSelected = $('[data-js="check-passenger-trip"]').is(":checked");
9914
9915      if (this.checkboxGoingTrip.is(":checked") || this.checkboxReturnTrip.is(":checked")) {
9916        if (this.handleChildCancel() && this.handlePassengerCanceled() && isPassengerSelected) {
9917          this.eneableBtnNextStep();
9918        } else {
9919          this.disableBtnNextStep();
9920        }
9921      } else {
9922        this.disableBtnNextStep();
9923        this.hideChildMsgErrorCancelTrip();
9924        this.hideMsgErrorPassengerAlreadyCanceled();
9925      }
9926    }
9927  }, {
9928    key: "handleCancelTrip",
9929    value: function handleCancelTrip() {
9930      var _this3 = this;
9931
9932      this.btnRequireCancelTrip.click(function () {
9933        _this3.loadValuesModalPassenger();
9934        _this3.loadConfirmationPage();
9935        _this3.advanceToReviewCancelTrip();
9936        _this3.refundDetails();
9937        _this3.btnRequireCancelTrip.addClass('d-none');
9938        _this3.btnConfCancelTrip.removeClass('d-none');
9939
9940        $('.trip-cancel-container-passengers').addClass('d-none');
9941      });
9942
9943      this.btnBackCancelTrip.click(function () {
9944        $(location).attr('href', i18n('my_account_page'));
9945      });
9946
9947      this.btnConfCancelTrip.click(function () {
9948        _this3.arrSaleIds = _this3.usersToCancel.map(function (el) {
9949          return el.saleId;
9950        });
9951
9952
9953        if (_this3.isWalletRefund) {
9954
9955          // Exibir o modal em "processing"
9956          _this3.showProcessingModal(i18n('refund_processing_subtitle'));
9957
9958          WalletService.checkGiroAccountExists().then(function (giroDataSuccess) {
9959            // Se não existir conta Giro → redireciona
9960            if (giroDataSuccess.length === 0) {
9961              _this3.showProcessingModal(i18n('refund_redirect_subtitle'));
9962              setTimeout(function () {
9963                SessionStorage.set('fromCancelFlow', true);
9964                $(location).attr('href', i18n('register_giro_page'));
9965              }, 3000);
9966              return Promise.reject('NO_GIRO_ACCOUNT'); // impede execução do próximo then
9967            }
9968
9969            // Caso exista → verificar carteira
9970            return WalletService.checkWalletExists();
9971          }).then(function (walletDataSuccess) {
9972            // Se carteira não existe → redireciona
9973            if (!walletDataSuccess || !walletDataSuccess.success) {
9974              _this3.showProcessingModal(i18n('refund_redirect_wallet_subtitle'));
9975              setTimeout(function () {
9976                SessionStorage.set('fromCancelFlow', true);
9977                $(location).attr("href", i18n('register_terms_page'));
9978              }, 3000);
9979            } else {
9980              // Carteira existe → cancelar via wallet
9981              _this3.cancelSaleWallet();
9982            }
9983          }).catch(function (error) {
9984            if (error === 'NO_GIRO_ACCOUNT') return; // evita erro fake do reject
9985            console.error('Erro ao verificar contas:', error);
9986            ModalStateRefund.updateModalState('error');
9987          });
9988        } else {
9989          if (_this3.isTripPayedPaymee) {
9990            _this3.cancelAsyncSale();
9991          } else {
9992            _this3.cancelSyncSale();
9993          }
9994        }
9995      });
9996
9997      this.btnBackTripCancelSelect.on("click", function () {
9998        _this3.resumeCancelTrip.updateResumeCancelTrip(_this3.listPassengersToCancel);
9999        _this3.removeListPassengerResumeTrip();
10000        $('[data-js="cancel-trip-refund"]').removeClass("d-none");
10001        $('[data-js="cancel-trip-revision"]').addClass("d-none");
10002
10003        if ($('[data-js="trip-cancel-return"]').is(":visible")) {
10004          $('[data-js="return-section"]').show();
10005        }
10006        $('[data-js="departure-section"]').show();
10007      });
10008    }
10009  }, {
10010    key: "showProcessingModal",
10011    value: function showProcessingModal(subtitle) {
10012      var modalData = {
10013        title: i18n('refund_processing_title'),
10014        subtitle: subtitle,
10015        showLink: false,
10016        linkBackBtn: i18n('payment_link_redirect')
10017      };
10018      ModalStateRefund.displayRefundModal('processing', modalData, 'wallet');
10019    }
10020  }, {
10021    key: "linsteClick",
10022    value: function linsteClick() {
10023      $(".arrow-details").on("click", function () {
10024        $(".hidden-details").toggleClass("d-none");
10025        if ($(".hidden-details").hasClass("d-none")) {
10026          $("#ver-detalhes").text("Ver Detalhes");
10027        } else {
10028          $("#ver-detalhes").text("Fechar Detalhes");
10029        }
10030      });
10031    }
10032  }, {
10033    key: "isCommissionFeeValues",
10034    value: function isCommissionFeeValues() {
10035      return $('[data-js="is-commission-fee"]').val() == 'true' ? true : false;
10036    }
10037  }, {
10038    key: "isCancelationFeeValues",
10039    value: function isCancelationFeeValues() {
10040      return $('[data-js="is-cancellation-fee"]').val() == 'true' ? true : false;
10041    }
10042  }, {
10043    key: "isServiceFeeValues",
10044    value: function isServiceFeeValues() {
10045      return $('[data-js="is-service-fee"]').val() == 'true' ? true : false;
10046    }
10047  }, {
10048    key: "isInstallmentValues",
10049    value: function isInstallmentValues() {
10050      return $('[data-js="installment-fee"]').val() == 'true' ? true : false;
10051    }
10052  }, {
10053    key: "atualizarValores",
10054    value: function atualizarValores(data) {
10055      var totalPayment = data.refunds.totalPayment;
10056      var cancelationFee = data.refunds.penalty.cancellationPenalty + data.refunds.penalty.cancellationPolicy;
10057      var serviceFee = data.refunds.convenienceFee;
10058      var installmentFee = data.refunds.interestAmount - data.refunds.interestAmountToRefund;
10059      var commissionFee = data.refunds.commissionFee;
10060      var totalRefund = data.refunds.refundValue;
10061      var refundConvenienceFee = data.refunds.refundConvenienceFee;
10062      var refundCommissionFee = data.refunds.refundCommissionFee;
10063      var nonRefund = 0;
10064
10065      var totalTax = cancelationFee - installmentFee;
10066      if (!refundConvenienceFee) {
10067        totalTax -= serviceFee;
10068      }
10069      if (!refundCommissionFee) {
10070        totalTax -= commissionFee;
10071      }
10072
10073      $('[data-js="refund-total"]').text('R$ ' + Utils.formatPrice(totalPayment));
10074      $('[data-js="non-refund"]').text('-' + 'R$ ' + Utils.formatPrice(nonRefund));
10075      $('[data-js="cancellation-fee"]').text('-' + 'R$ ' + Utils.formatPrice(cancelationFee));
10076      $('[data-js="service-fee"]').text('-' + 'R$ ' + Utils.formatPrice(serviceFee));
10077      $('[data-js="installment-fee"]').text('-' + 'R$ ' + Utils.formatPrice(installmentFee));
10078      $('[data-js="comission-fee"]').text('-' + 'R$ ' + Utils.formatPrice(commissionFee));
10079      $('[data-js="total-refund"]').text('R$ ' + Utils.formatPrice(totalRefund));
10080      $('[data-js="total-tax"]').text('-' + 'R$ ' + Utils.formatPrice(totalTax));
10081
10082      if (!refundConvenienceFee) {
10083        nonRefund += data.refunds.convenienceFee;
10084      }
10085
10086      if (!refundCommissionFee) {
10087        nonRefund += data.refunds.commissionFee;
10088      }
10089
10090      nonRefund += data.refunds.interestAmount - data.refunds.interestAmountToRefund;
10091      $('[data-js="non-refund"]').text('-' + 'R$ ' + Utils.formatPrice(nonRefund));
10092
10093      if (refundCommissionFee) {
10094        $('[data-js="comission-fee"]').text('-' + 'R$ ' + Utils.formatPrice(0));
10095      } else {
10096        $('[data-js="comission-fee-value"]').show();
10097      }
10098
10099      if (refundConvenienceFee) {
10100        $('[data-js="service-fee"]').text('-' + 'R$ ' + Utils.formatPrice(0));
10101      } else {
10102        $('[data-js="service-fee-value"]').show();
10103      }
10104    }
10105  }, {
10106    key: "modalEditable",
10107    value: function modalEditable() {
10108      if ($('[data-js="modal-container-cancel"]').val() == "true") {
10109        new Modal($);
10110        ModalCancel.show();
10111      }
10112
10113      $('[data-js="modal-btn-cancel"]').on('click', function () {
10114        $('[data-js="modal-close"]').click();
10115      });
10116    }
10117  }, {
10118    key: "loadValuesModalPassenger",
10119    value: function loadValuesModalPassenger() {
10120      $('[data-js="detail-email"]').removeClass("d-none");
10121      var text = "A confirmação de cancelamento será enviada para o email:";
10122      var email = $(".main-alert-credit-card").find("p.text span.email").text();
10123      var newText = text + " " + email;
10124      $(".main-alert-credit-card").find("p.text").eq(1).text(newText);
10125      $(".main-alert-credit-card").find("p.text").eq(0).remove();
10126    }
10127  }, {
10128    key: "refundDetails",
10129    value: function refundDetails() {
10130      var _this4 = this;
10131
10132      var headers = {
10133        Authorization: "" + SessionStorage.get("jca_token"),
10134        version: "2"
10135      };
10136
10137      var arrSaleIds = this.usersToCancel.map(function (el, _) {
10138        return el.saleId;
10139      });
10140
10141      SessionStorage.set('usersToCancel', this.usersToCancel);
10142
10143      var salesIdsParam = arrSaleIds.join(',');
10144
10145      var queryString = "salesIds=" + salesIdsParam;
10146
10147      LoaderService.show();
10148      HttpService.get("refundDetails?" + queryString, headers).then(function (data) {
10149        LoaderService.hide();
10150        SessionStorage.set("refundDetails", data.result);
10151        _this4.atualizarValores(data.result);
10152      }).catch(function (err) {
10153        LoaderService.hide();
10154        OverlayService.show();
10155        AlertConfirmation.show(i18n("error_cancel"), i18n("error_cancel_try"), true);
10156        $('#overlay, [data-js="close-menu"]').on("click", function () {
10157          $(location).attr("href", $('#homePagePath').val());
10158        });
10159      });
10160    }
10161  }, {
10162    key: "cancelSyncSale",
10163    value: function cancelSyncSale() {
10164      var goingArr = this.tripToCancel[0];
10165      var returnArr = this.tripToCancel[1];
10166      var firstElemGoing = goingArr[0];
10167      var firstElemReturn = returnArr ? returnArr[0] : null;
10168
10169      var headers = {
10170        Authorization: "" + SessionStorage.get("jca_token")
10171      };
10172
10173      if (firstElemGoing && firstElemGoing.paymentForm === "MALGA" || firstElemReturn && firstElemReturn.paymentForm === "MALGA") {
10174        headers.flow = 'malga';
10175      }
10176
10177      var arrSaleIds = this.usersToCancel.map(function (el, _) {
10178        return el.saleId;
10179      });
10180
10181      var body = { saleIds: arrSaleIds };
10182
10183      this.showProcessingModal(i18n('refund_processing_card_subtitle'));
10184
10185      HttpService.post("cancelAsyncSale", body, headers).then(function (response) {
10186        ModalStateRefund.updateModalState('success');
10187      }).catch(function (err) {
10188        if (err.responseJSON.result[0].message === "O bilhete já foi cancelado.") {
10189          var modalData = {
10190            title: i18n("status_error"),
10191            subtitle: i18n("error_cancel"),
10192            showLink: false,
10193            linkBackBtn: i18n('payment_link_redirect')
10194          };
10195
10196          ModalStateRefund.displayRefundModal('error', modalData);
10197        } else {
10198          ModalStateRefund.updateModalState('error');
10199        }
10200      });
10201    }
10202  }, {
10203    key: "cancelAsyncSale",
10204    value: function cancelAsyncSale() {
10205      var headers = {
10206        Authorization: "" + SessionStorage.get("jca_token"),
10207        version: "2"
10208      };
10209
10210      var body = { saleIds: this.arrSaleIds };
10211
10212      this.showProcessingModal(i18n('refund_processing_card_subtitle'));
10213
10214      HttpService.post("cancelAsyncSale", body, headers).then(function (response) {
10215        ModalStateRefund.updateModalState('success');
10216      }).catch(function (err) {
10217        if (err.responseJSON.result[0].message === "O bilhete já foi cancelado.") {
10218          var modalData = {
10219            title: i18n("status_error"),
10220            subtitle: i18n("error_cancel"),
10221            showLink: false,
10222            linkBackBtn: i18n('payment_link_redirect')
10223          };
10224
10225          ModalStateRefund.displayRefundModal('error', modalData);
10226        } else {
10227          ModalStateRefund.updateModalState('error');
10228        }
10229      });
10230    }
10231  }, {
10232    key: "cancelSaleWallet",
10233    value: function cancelSaleWallet() {
10234      var headers = {
10235        Authorization: "" + SessionStorage.get("jca_token")
10236      };
10237
10238      var body = { SaleIds: this.arrSaleIds };
10239
10240      HttpService.post("cancelAsyncSale", body, headers).then(function (response) {
10241        ModalStateRefund.updateModalState('success');
10242      }).catch(function (err) {
10243        ModalStateRefund.updateModalState('error');
10244      });
10245    }
10246  }, {
10247    key: "handleTicketsAlreadyCanceled",
10248    value: function handleTicketsAlreadyCanceled(data) {
10249      var arr = data.filter(function (el) {
10250        return el.message == "O bilhete já foi cancelado.";
10251      });
10252
10253      if (arr.length == data.length) {
10254        AlertConfirmation.showMsgWithLink({
10255          show: true,
10256          title1: "",
10257          subtitle: i18n("error_cancel"),
10258          title2: i18n("status_error")
10259        });
10260      } else {
10261        this.handleCancelUsers(data);
10262      }
10263    }
10264  }, {
10265    key: "handleCancelUsers",
10266    value: function handleCancelUsers(data) {
10267      if (data && data.length === 0) {
10268        this.successCancel();
10269      } else if (data && data.length) {
10270        var usersNoCancel = data.filter(function (cancelObj) {
10271          return Number(cancelObj.status) !== 200;
10272        });
10273
10274        if (usersNoCancel.length) {
10275          var userNoCancelInfo = usersNoCancel.map(function (el) {
10276            return {
10277              name: el.sale.passengerName,
10278              seat: el.sale.seat,
10279              destination: el.sale.destinationDescription,
10280              origin: el.sale.originDescription,
10281              going: el.sale.going
10282            };
10283          });
10284
10285          this.renderInfoUserNoCancel(userNoCancelInfo);
10286        } else {
10287          this.successCancel();
10288        }
10289      } else {
10290        AlertConfirmation.showMsgWithLink({
10291          show: true,
10292          title1: "",
10293          subtitle: i18n("error_cancel"),
10294          title2: i18n("status_error")
10295        });
10296      }
10297    }
10298  }, {
10299    key: "renderInfoUserNoCancel",
10300    value: function renderInfoUserNoCancel(userNoCancelInfo) {
10301      var content = [];
10302      var passengerGoTrip = userNoCancelInfo.filter(function (user) {
10303        return user.going == true;
10304      });
10305      var passengerBackTrip = userNoCancelInfo.filter(function (user) {
10306        return user.going == false;
10307      });
10308
10309      var generateInformations = function generateInformations(passengerArrWay) {
10310        content.push("\n        <div class=\"container-description-origin-destination\">\n          <p>Origem: " + passengerArrWay[0].origin + "</p>\n          <p>Destino: " + passengerArrWay[0].destination + "</p>\n        </div>\n      ");
10311
10312        passengerArrWay.forEach(function (passenger, index) {
10313          content.push("\n          <div>\n            <span>" + passenger.name + "</span>\n            <span> - </span>\n            <span>" + passenger.seat + "</span>\n          </div>\n        ");
10314        });
10315      };
10316
10317      generateInformations(passengerGoTrip);
10318
10319      if (passengerBackTrip.length) generateInformations(passengerBackTrip);
10320
10321      AlertConfirmation.show(i18n("error_cancel_try"));
10322      $('[data-js="message-confir-subtitle"]').empty().append(content.join(""));
10323    }
10324  }, {
10325    key: "handlePassengersQuantity",
10326    value: function handlePassengersQuantity() {
10327      var passengersGoingRequirements = this.getPassengerTypeQttListGoing();
10328      var passengersReturnRequirements = this.getPassengerTypeQttListReturn();
10329
10330      this.sumQuantityGoing(passengersGoingRequirements);
10331      this.sumQuantityReturn(passengersReturnRequirements);
10332    }
10333  }, {
10334    key: "getSelectedPassengers",
10335    value: function getSelectedPassengers() {
10336      self = this;
10337      self.usersToCancel = [];
10338      var selectedPassengers = { going: [], return: [] };
10339
10340      $('[data-js="passenger-list-cancel"]').find(".check-passenger-trip").each(function () {
10341        if ($(this).is(":checked") && !selectedPassengers.going.includes($(this).next().text()) && !selectedPassengers.return.includes($(this).next().text())) {
10342          if ($('[data-js="check-going-trip"]').is(":checked")) {
10343            selectedPassengers.going.push({
10344              name: $(this).next().text().trim(),
10345              seat: $(this).data("seat"),
10346              price: $(this).data("price"),
10347              type: $(this).data("type"),
10348              priceConnection: $(this).data("price-going-connection"),
10349              seatConnection: $(this).data("seat-going-connection"),
10350              insurance: $(this).data("insurance"),
10351              insuranceConnection: $(this).data("insurance-going-connection"),
10352              convenienceFee: $(this).data("conveniencefee"),
10353              convenienceFeeConnection: $(this).data("conveniencefee-going-connection"),
10354              liveloPoints: $(this).data('livelo-points'),
10355              liveloPointsConnection: $(this).data('livelo-points-going-connection')
10356            });
10357            self.usersToCancel.push({
10358              name: $(this).next().text() + " - Passagem de ida",
10359              saleId: $(this).data("saleid"),
10360              price: $(this).data("price"),
10361              insurance: $(this).data("insurance"),
10362              convenienceFee: $(this).data("conveniencefee"),
10363              liveloPoints: $(this).data('livelo-points')
10364            });
10365
10366            if ($(this).data("price-going-connection")) {
10367              self.usersToCancel.push({
10368                name: $(this).next().text() + " - Passagem de ida",
10369                saleId: $(this).data("saleid-going-connection"),
10370                price: $(this).data("price-going-connection"),
10371                insurance: $(this).data("insurance-going-connection"),
10372                convenienceFee: $(this).data("conveniencefee-going-connection"),
10373                liveloPoints: $(this).data('livelo-points-going-connection')
10374              });
10375            }
10376          }
10377
10378          if ($('[data-js="check-return-trip"]').is(":checked")) {
10379            selectedPassengers.return.push({
10380              name: $(this).next().text().trim(),
10381              seat: $(this).data("seat-return"),
10382              price: $(this).data("price-return"),
10383              priceConnection: $(this).data("price-return-connection"),
10384              seatConnection: $(this).data("seat-return-connection"),
10385              insuranceReturn: $(this).data("insurance-return"),
10386              insuranceReturnConnection: $(this).data("insurance-return-connection"),
10387              convenienceFeeReturn: $(this).data("conveniencefee-return"),
10388              convenienceFeeReturnConnection: $(this).data("conveniencefee-return-connection"),
10389              liveloPointsReturn: $(this).data("livelo-points-return"),
10390              liveloPointsReturnConnection: $(this).data("livelo-points-return-connection")
10391            });
10392            self.usersToCancel.push({
10393              name: $(this).next().text() + " - Passagem de volta",
10394              saleId: $(this).data("saleid-return"),
10395              price: $(this).data("price-return"),
10396              insurance: $(this).data("insurance-return"),
10397              convenienceFee: $(this).data("conveniencefee-return"),
10398              liveloPoints: $(this).data("livelo-points-return")
10399            });
10400
10401            if ($(this).data("price-return-connection")) {
10402              self.usersToCancel.push({
10403                name: $(this).next().text() + " - Passagem de volta",
10404                saleId: $(this).data("saleid-return-connection"),
10405                price: $(this).data("price-return-connection"),
10406                insurance: $(this).data("insurance-return-connection"),
10407                convenienceFee: $(this).data("conveniencefee-return-connection"),
10408                liveloPoints: $(this).data("livelo-points-return-connection")
10409              });
10410            }
10411          }
10412        }
10413      });
10414
10415      return selectedPassengers;
10416    }
10417  }, {
10418    key: "getPassengerTypeQttListGoing",
10419    value: function getPassengerTypeQttListGoing() {
10420      var reg_qtt_going = 0;
10421      var chd_a_qtt_going = 0;
10422      var chd_qtt_going = 0;
10423
10424      $('[data-js="check-passenger-trip"]').each(function (_, el) {
10425        if ($(el).data("status") == "SALE_APPROVED" || $(el).data("status") == "SALE_RELOCATED") {
10426          reg_qtt_going += $(el).data("type") === "ADULT" ? 1 : 0;
10427          chd_a_qtt_going += $(el).data("type") === "CHILD_A" ? 1 : 0;
10428          chd_qtt_going += $(el).data("type") === "CHILD" ? 1 : 0;
10429        }
10430      });
10431
10432      return { reg_qtt_going: reg_qtt_going, chd_a_qtt_going: chd_a_qtt_going, chd_qtt_going: chd_qtt_going };
10433    }
10434  }, {
10435    key: "getPassengerTypeQttListReturn",
10436    value: function getPassengerTypeQttListReturn() {
10437      var reg_qtt_return = 0;
10438      var chd_a_qtt_return = 0;
10439      var chd_qtt_return = 0;
10440
10441      $('[data-js="check-passenger-trip"]').each(function (_, el) {
10442        if ($(el).data("status-return") == "SALE_APPROVED" || $(el).data("status-return") == "SALE_RELOCATED") {
10443          reg_qtt_return += $(el).data("type") === "ADULT" ? 1 : 0;
10444          chd_a_qtt_return += $(el).data("type") === "CHILD_A" ? 1 : 0;
10445          chd_qtt_return += $(el).data("type") === "CHILD" ? 1 : 0;
10446        }
10447      });
10448
10449      return { reg_qtt_return: reg_qtt_return, chd_a_qtt_return: chd_a_qtt_return, chd_qtt_return: chd_qtt_return };
10450    }
10451  }, {
10452    key: "sumQuantityGoing",
10453    value: function sumQuantityGoing(requirements) {
10454      var _this5 = this;
10455
10456      var reg_qtt_going = requirements.reg_qtt_going,
10457        chd_a_qtt_going = requirements.chd_a_qtt_going,
10458        chd_qtt_going = requirements.chd_qtt_going;
10459
10460
10461      $('[data-js="passenger-list-cancel"]').find('input[type="checkbox"]').change(function (e) {
10462        if ($(e.target).data("status") === "SALE_APPROVED" || $(e.target).data("status") === "SALE_RELOCATED") {
10463          var passengerType = $(e.target).data("type");
10464          var isChecked = $(e.target).is(":checked");
10465
10466          switch (passengerType) {
10467            case "ADULT":
10468              if (isChecked) {
10469                reg_qtt_going--;
10470              } else {
10471                reg_qtt_going++;
10472              }
10473              break;
10474
10475            case "CHILD_A":
10476              if (isChecked) {
10477                chd_a_qtt_going--;
10478              } else {
10479                chd_a_qtt_going++;
10480              }
10481              break;
10482
10483            case "CHILD":
10484              if (isChecked) {
10485                chd_qtt_going--;
10486              } else {
10487                chd_qtt_going++;
10488              }
10489              break;
10490          }
10491
10492          if (reg_qtt_going < chd_a_qtt_going || reg_qtt_going < chd_qtt_going) {
10493            _this5.isQuantityGoingChecked = false;
10494          } else {
10495            _this5.isQuantityGoingChecked = true;
10496          }
10497        }
10498      });
10499    }
10500  }, {
10501    key: "sumQuantityReturn",
10502    value: function sumQuantityReturn(requirements) {
10503      var _this6 = this;
10504
10505      var reg_qtt_return = requirements.reg_qtt_return,
10506        chd_a_qtt_return = requirements.chd_a_qtt_return,
10507        chd_qtt_return = requirements.chd_qtt_return;
10508
10509
10510      $('[data-js="passenger-list-cancel"]').find('input[type="checkbox"]').change(function (e) {
10511        if ($(e.target).data("status-return") === "SALE_APPROVED" || $(e.target).data("status-return") === "SALE_RELOCATED") {
10512          var passengerType = $(e.target).data("type");
10513          var isChecked = $(e.target).is(":checked");
10514
10515          switch (passengerType) {
10516            case "ADULT":
10517              if (isChecked) {
10518                reg_qtt_return--;
10519              } else {
10520                reg_qtt_return++;
10521              }
10522              break;
10523
10524            case "CHILD_A":
10525              if (isChecked) {
10526                chd_a_qtt_return--;
10527              } else {
10528                chd_a_qtt_return++;
10529              }
10530              break;
10531
10532            case "CHILD":
10533              if (isChecked) {
10534                chd_qtt_return--;
10535              } else {
10536                chd_qtt_return++;
10537              }
10538              break;
10539          }
10540
10541          if (reg_qtt_return < chd_a_qtt_return || reg_qtt_return < chd_qtt_return) {
10542            _this6.isQuantityReturnChecked = false;
10543          } else {
10544            _this6.isQuantityReturnChecked = true;
10545          }
10546        }
10547      });
10548    }
10549  }, {
10550    key: "advanceToReviewCancelTrip",
10551    value: function advanceToReviewCancelTrip() {
10552      var isTripGoingSelected = this.checkboxGoingTrip.is(":checked");
10553      var isTripReturnSelected = this.checkboxReturnTrip.is(":checked");
10554
10555      if (!isTripGoingSelected) {
10556        $('[data-js="departure-section"]').hide();
10557      }
10558
10559      if (!isTripReturnSelected) {
10560        $('[data-js="return-section"]').hide();
10561      }
10562
10563      this.resumeCancelTrip.updateResumeCancelTrip(this.listPassengersToCancel, this.convenienceFee);
10564      $('[data-js="cancel-trip-refund"]').addClass("d-none");
10565      $('[data-js="cancel-trip-revision"]').removeClass("d-none");
10566      this.addListPassengerResumeTrip();
10567    }
10568  }, {
10569    key: "successCancel",
10570    value: function successCancel() {
10571      $('[data-js="cancel-trip-revision"]').addClass("d-none");
10572      $('[data-js="cancel-trip-confirm"]').removeClass("d-none");
10573      $('[data-js="detail-email"]').removeClass("d-none");
10574      $('[data-js="resume-trip-cancel"]').addClass("d-none");
10575      SessionStorage.remove("tripToCancel");
10576    }
10577  }, {
10578    key: "eneableBtnNextStep",
10579    value: function eneableBtnNextStep() {
10580      this.btnRequireCancelTrip.attr("disabled", false);
10581    }
10582  }, {
10583    key: "disableBtnNextStep",
10584    value: function disableBtnNextStep() {
10585      this.btnRequireCancelTrip.attr("disabled", true);
10586    }
10587  }, {
10588    key: "setTaxRefund",
10589    value: function setTaxRefund() {
10590      var taxRefundValue = $('[data-js="tax-refund-attr"]').val();
10591
10592      $('[data-js="tax-refund"]').text(taxRefundValue + "%");
10593    }
10594  }, {
10595    key: "loadConfirmationPage",
10596    value: function loadConfirmationPage() {
10597      this.listPassengersToCancel = this.getSelectedPassengers();
10598      var goingArr = this.tripToCancel[0];
10599      var returnArr = this.tripToCancel[2];
10600      var firstElemGoing = goingArr[0];
10601      var firstElemReturn = returnArr ? returnArr[0] : null;
10602
10603      this.passGoingList.empty();
10604      this.passReturnList.empty();
10605      $('[data-js="passengers-going"]').hide();
10606      $('[data-js="passengers-return"]').hide();
10607      var content = [];
10608
10609      var origin = firstElemGoing.originDescription;
10610      var destination = firstElemGoing.destinationDescription;
10611      var dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(firstElemGoing.departureDate));
10612      var hourDepart = DateFormatter.extractHour(firstElemGoing.departureDate);
10613
10614      if (this.listPassengersToCancel.going.length > 0) {
10615        $('[data-js="passengers-going"]').show();
10616        this.cancelGoingText.text("(" + origin + " - " + destination + ") - " + dateDepart + " - " + hourDepart + "");
10617        $.each(this.listPassengersToCancel.going, function (_, el) {
10618          return content.push('<li class="passenger-name">' + el + "</li>");
10619        });
10620        this.passGoingList.append(content.join(""));
10621      }
10622
10623      if (this.listPassengersToCancel.return.length > 0) {
10624        origin = firstElemReturn.originDescription;
10625        destination = firstElemReturn.destinationDescription;
10626        dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(firstElemReturn.departureDate));
10627        hourDepart = DateFormatter.extractHour(firstElemReturn.departureDate);
10628        content = [];
10629
10630        $('[data-js="passengers-return"]').show();
10631        this.cancelReturnText.text("(" + origin + " - " + destination + ") - " + dateDepart + " - " + hourDepart + "");
10632        $.each(this.listPassengersToCancel.return, function (_, el) {
10633          return content.push('<li class="passenger-name">' + el + "</li>");
10634        });
10635        this.passReturnList.append(content.join(""));
10636      }
10637    }
10638  }, {
10639    key: "addListPassengerResumeTrip",
10640    value: function addListPassengerResumeTrip() {
10641      $('[data-js="departure-section"]').find('[data-js="trip-details-show-passenger"]').show();
10642      $('[data-js="return-section"]').find('[data-js="trip-details-show-passenger"]').show();
10643    }
10644  }, {
10645    key: "removeListPassengerResumeTrip",
10646    value: function removeListPassengerResumeTrip() {
10647      $('[data-js="departure-section"]').find('[data-js="trip-details-show-passenger"]').hide();
10648      $('[data-js="return-section"]').find('[data-js="trip-details-show-passenger"]').hide();
10649    }
10650  }, {
10651    key: "showMsgErrorPassengerAlreadyCanceled",
10652    value: function showMsgErrorPassengerAlreadyCanceled(msgError) {
10653      this.errMsgPassengerStatus.text(msgError).parent().show();
10654    }
10655  }, {
10656    key: "hideMsgErrorPassengerAlreadyCanceled",
10657    value: function hideMsgErrorPassengerAlreadyCanceled() {
10658      this.errMsgPassengerStatus.parent().hide();
10659    }
10660  }, {
10661    key: "showChildMsgErrorCancelTrip",
10662    value: function showChildMsgErrorCancelTrip() {
10663      this.errMsgChildCancelTrip.text(i18n("err_msg_cancel")).parent().show();
10664    }
10665  }, {
10666    key: "hideChildMsgErrorCancelTrip",
10667    value: function hideChildMsgErrorCancelTrip() {
10668      this.errMsgChildCancelTrip.parent().hide();
10669    }
10670  }, {
10671    key: "handlePassengerStatus",
10672    value: function handlePassengerStatus() {
10673      var _this7 = this;
10674
10675      $('[data-js="check-passenger-trip"]').on("change", function (e) {
10676        if ($(e.target).is(":checked")) {
10677          $(e.target).data("status") !== "SALE_APPROVED" && $(e.target).data("status") !== "SALE_RELOCATED" ? _this7.listPassengerCancelGoing++ : "";
10678          $(e.target).data("status-return") !== "SALE_APPROVED" && $(e.target).data("status-return") !== "SALE_RELOCATED" ? _this7.listPassengerCancelReturn++ : "";
10679        } else {
10680          $(e.target).data("status") !== "SALE_APPROVED" && $(e.target).data("status") !== "SALE_RELOCATED" ? _this7.listPassengerCancelGoing-- : "";
10681          $(e.target).data("status-return") !== "SALE_APPROVED" && $(e.target).data("status-return") !== "SALE_RELOCATED" ? _this7.listPassengerCancelReturn-- : "";
10682        }
10683
10684        if (_this7.checkboxGoingTrip.is(":checked")) {
10685          _this7.checkboxGoingTrip.trigger("change");
10686        }
10687
10688        if (_this7.checkboxReturnTrip.is(":checked")) {
10689          _this7.checkboxReturnTrip.trigger("change");
10690        }
10691      });
10692    }
10693  }, {
10694    key: "handlePassengerStatusForDep",
10695    value: function handlePassengerStatusForDep() {
10696      this.listPassengerCancelGoing > 0 ? this.isPassengerAlreadyCancelGoing = true : this.isPassengerAlreadyCancelGoing = false;
10697    }
10698  }, {
10699    key: "handlePassengerStatusForReturn",
10700    value: function handlePassengerStatusForReturn() {
10701      this.listPassengerCancelReturn > 0 ? this.isPassengerAlreadyCancelReturn = true : this.isPassengerAlreadyCancelReturn = false;
10702    }
10703  }, {
10704    key: "handleChildCancel",
10705    value: function handleChildCancel() {
10706      if (this.isQuantityGoingChecked && this.isQuantityReturnChecked) {
10707        this.hideChildMsgErrorCancelTrip();
10708        return true;
10709      } else {
10710        this.showChildMsgErrorCancelTrip();
10711        return false;
10712      }
10713    }
10714  }, {
10715    key: "handlePassengerCanceled",
10716    value: function handlePassengerCanceled() {
10717      if (this.isPassengerAlreadyCancelGoing || this.isPassengerAlreadyCancelReturn) {
10718        this.showMsgErrorPassengerAlreadyCanceled(i18n("err_msg_passenger_canceled"));
10719        return false;
10720      } else {
10721        this.hideMsgErrorPassengerAlreadyCanceled();
10722        return true;
10723      }
10724    }
10725  }, {
10726    key: "blockedPassCheckbox",
10727    value: function blockedPassCheckbox() {
10728      var ticketData = SessionStorage.get("tripToCancel");
10729      var statusTicketDep = ticketData[0][0].status;
10730      var statusTicketRet = ticketData[2] ? ticketData[2][0].status : null;
10731
10732      if (statusTicketDep === "SALE_NON_REFUNDABLE") {
10733        $('[data-js="check-going-trip"]').addClass('d-none');
10734        $('[data-js="check-going-trip"]').siblings('label.custom-control-label').css('display', 'none');
10735        $('.no-refundable-message').removeClass('d-none');
10736      }
10737
10738      if (statusTicketRet === "SALE_NON_REFUNDABLE") {
10739        $('[data-js="check-return-trip"]').hide();
10740        $('[data-js="check-return-trip"]').siblings('label.custom-control-label').css('display', 'none');
10741      }
10742    }
10743  }, {
10744    key: "listenClickChoice",
10745    value: function listenClickChoice() {
10746      var _this8 = this;
10747
10748      var choices = document.querySelectorAll('.trip-cancel-refund-choice');
10749      var removeClasses = function removeClasses(element, isWallet) {
10750        if (isWallet) {
10751          element.classList.remove('refund-selected');
10752        } else {
10753          element.classList.remove('refund-selected-wallet');
10754        }
10755        var pointWallet = element.querySelector('.point-wallet');
10756        if (pointWallet) {
10757          pointWallet.classList.remove('point-wallet-selected');
10758        }
10759      };
10760
10761      var addClasses = function addClasses(element, isWallet) {
10762        if (isWallet) {
10763          element.classList.add('refund-selected-wallet');
10764        } else {
10765          element.classList.add('refund-selected');
10766        }
10767        var pointWallet = element.querySelector('.point-wallet');
10768        if (pointWallet) {
10769          pointWallet.classList.add('point-wallet-selected');
10770        }
10771      };
10772
10773      // Armazena a referência da instância da classe
10774      var self = this;
10775
10776      choices.forEach(function (choice) {
10777        if (_this8.isPaymentWallet) {
10778          if (!(choice.getAttribute('data-refund-wallet') === 'true')) {
10779            choice.style.display = 'none';
10780          }
10781        }
10782
10783        choice.addEventListener('click', function () {
10784          var _this9 = this;
10785
10786          if (!this.classList.contains('refund-selected') && !this.classList.contains('text-refund-selected')) {
10787            // Armazena o valor de data-js em uma variável de instância
10788            self.isWalletRefund = this.getAttribute('data-refund-wallet') === 'true';
10789
10790            choices.forEach(function (otherChoice) {
10791              if (otherChoice !== _this9) {
10792                removeClasses(otherChoice, self.isWalletRefund);
10793              }
10794            });
10795
10796            addClasses(this, self.isWalletRefund);
10797
10798            // Reabilita o botão quando uma opção é selecionada
10799            self.btnConfCancelTrip.attr("disabled", false);
10800          }
10801        });
10802      });
10803    }
10804  }]);
10805
10806  return CancelTripControllerNew;
10807}();
10808'use strict';
10809
10810var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
10811
10812function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
10813
10814var CapturePhoto = function () {
10815  function CapturePhoto($) {
10816    _classCallCheck(this, CapturePhoto);
10817
10818    this.capturePhotoLabel = $('[data-js="capture-photo-label"]');
10819    this.capturePhotoCam = $('[data-js="capture-photo-cam-photo"]');
10820    this.capturePhotoLink = $('[data-js="capture-photo-link"]');
10821    this.capturePhotoDescription = $('[data-js="capture-photo-description"]');
10822    this.modalScreenShot = $('[data-js="modal-screen-shot-container"]');
10823    this.modalScreenBtn = $('[data-js="modal-screen-btn"]');
10824    this.modalTela = $('[data-js="screen-result"]')[0];
10825    this.btnConfir = $('[data-js="screen-btn-conf"]');
10826    this.btnCancel = $('[data-js="screen-btn-cancel"]');
10827    this.btnRotate = $('[data-js="screen-btn-rotate"]');
10828    this.faceMask = $('[data-js="face-mask"]');
10829    this.termsLink = $('[data-js="capture-terms-link"]');
10830    this.overlay = $('[data-js="modal-screen-overlay"]');
10831    this.modalSreenShot = $('.modal-screen-shot-content');
10832    this.modalShowImage = $('.modal-screen-shot-result-content');
10833    this.modalTermsAndConditions = $('.modal-terms-conditions-content');
10834    this.btnCloseOverlay = $('[data-js="modal-close"]');
10835    this.btnModalScreenCloseOverlay = $('[data-js="modal-screen-close"]');
10836    this.btnModalScreenResultCloseOverlay = $('[data-js="modal-screen-result-close"]');
10837    this.mobileCam = $('[data-js="camera-mobile"]');
10838    this.passenger = SessionStorage.get('passenger');
10839    this.stream;
10840    this.url = window.location.href;
10841    this.maxWidth = 480;
10842    this.maxHeight = 640;
10843    this.init();
10844  }
10845
10846  _createClass(CapturePhoto, [{
10847    key: 'init',
10848    value: function init() {
10849      this.capturePhotoCam.attr('data-register', 'false');
10850      this.listenScreenShot();
10851      this.applyPunchMask();
10852      this.listenResize();
10853      this.showCapturePhoto();
10854
10855      if (this.passenger) this.getImage();
10856    }
10857  }, {
10858    key: 'applyPunchMask',
10859    value: function applyPunchMask() {
10860      var heightPunchMask = $('#video').height();
10861
10862      this.faceMask.css({
10863        height: heightPunchMask
10864      });
10865    }
10866  }, {
10867    key: 'renderInVideo',
10868    value: function renderInVideo() {
10869      var _this = this;
10870
10871      var video = $('#video')[0];
10872
10873      navigator.mediaDevices.getUserMedia({ video: { facingMode: "user" } }).then(function (stream) {
10874        video.srcObject = stream;
10875        _this.stream = stream;
10876        setTimeout(function () {
10877          _this.applyPunchMask();
10878        }, 500);
10879      }).catch(function () {
10880        Alert.show(i18n('webcam_error'));
10881      });
10882    }
10883  }, {
10884    key: 'closeCamera',
10885    value: function closeCamera(stream) {
10886      if (!stream) return;
10887
10888      stream.getTracks().forEach(function (track) {
10889        track.stop();
10890      });
10891    }
10892  }, {
10893    key: 'renderImageInSmarthphone',
10894    value: function renderImageInSmarthphone() {
10895      var _this2 = this;
10896
10897      var reader = new FileReader();
10898
10899      reader.onload = function () {
10900        _this2.resizeBase64Image(reader.result, _this2.maxWidth, _this2.maxHeight).then(function (newBase64) {
10901          _this2.capturePhotoCam.attr('src', newBase64);
10902          $('[data-js="screen-result"]').attr('src', newBase64);
10903        });
10904      };
10905
10906      reader.readAsDataURL(this.mobileCam.prop('files')[0]);
10907
10908      this.modalShowImage.addClass('active');
10909      this.capturePhotoCam.addClass('active');
10910      this.capturePhotoCam.attr('data-register', 'true');
10911    }
10912  }, {
10913    key: 'accessGallery',
10914    value: function accessGallery() {
10915      this.mobileCam[0].click();
10916    }
10917  }, {
10918    key: 'listenScreenShot',
10919    value: function listenScreenShot() {
10920      var _this3 = this;
10921
10922      this.mobileCam.on('change', function (e) {
10923        _this3.renderImageInSmarthphone();
10924      });
10925
10926      this.modalScreenBtn.on('click', function () {
10927        _this3.capturePhoto();
10928      });
10929
10930      this.capturePhotoLink.on('click', function (event) {
10931        event.preventDefault();
10932
10933        $('body, html').css('overflow-y', 'hidden');
10934        if (Utils.isMobile()) {
10935          _this3.accessGallery();
10936          return;
10937        }
10938
10939        _this3.modalSreenShot.addClass('active');
10940        _this3.overlay.addClass('active');
10941        _this3.renderInVideo();
10942      });
10943
10944      this.btnConfir.on('click', function () {
10945        var imageBase64 = _this3.modalTela.src;
10946        var isPassengerRegistered = _this3.passenger ? true : false;
10947
10948        _this3.closeOverlay();
10949        _this3.capturePhotoCam.attr('src', imageBase64);
10950        _this3.capturePhotoCam.addClass('active');
10951
10952        if (!isPassengerRegistered) {
10953          _this3.capturePhotoCam.attr('data-register', 'true');
10954          return;
10955        }
10956
10957        _this3.chooseServiceImage(imageBase64);
10958      });
10959
10960      this.btnCancel.on('click', function () {
10961        if (Utils.isMobile()) {
10962          _this3.accessGallery();
10963          return;
10964        }
10965
10966        _this3.modalSreenShot.addClass('active');
10967        _this3.modalShowImage.removeClass('active');
10968        _this3.renderInVideo();
10969      });
10970
10971      this.overlay.on('click', function () {
10972        _this3.closeOverlay();
10973      });
10974
10975      this.termsLink.on('click', function () {
10976        $('#wemobi-header').addClass('opened-overlay');
10977        _this3.modalTermsAndConditions.addClass('active');
10978        _this3.overlay.addClass('active');
10979        $('body, html').css('overflow-y', 'hidden');
10980      });
10981
10982      this.btnCloseOverlay.add(this.btnModalScreenCloseOverlay).add(this.btnModalScreenResultCloseOverlay).on('click', function () {
10983        _this3.closeOverlay();
10984      });
10985
10986      this.btnRotate.click(function () {
10987        _this3.rotateImage();
10988      });
10989    }
10990
10991    // method used when the component is independent
10992
10993  }, {
10994    key: 'chooseServiceImage',
10995    value: function chooseServiceImage(imageBase64) {
10996      var isImage = this.passenger._image;
10997
10998      if (!isImage) {
10999        this.registerImage(imageBase64);
11000        return;
11001      }
11002
11003      this.updateImage(imageBase64);
11004    }
11005  }, {
11006    key: 'listenResize',
11007    value: function listenResize() {
11008      var _this4 = this;
11009
11010      $(window).on("resize", function () {
11011        return _this4.applyPunchMask();
11012      });
11013    }
11014  }, {
11015    key: 'capturePhoto',
11016    value: function capturePhoto() {
11017      var video = document.getElementById('video');
11018      var canvas = document.createElement('canvas');
11019      canvas.width = 640;
11020      canvas.height = 480;
11021
11022      var context = canvas.getContext('2d');
11023
11024      context.drawImage(video, 0, 0, canvas.width, canvas.height);
11025
11026      var dataURL = canvas.toDataURL();
11027      this.modalTela.src = dataURL;
11028      this.modalShowImage.addClass('active');
11029      this.modalSreenShot.removeClass('active');
11030    }
11031  }, {
11032    key: 'closeOverlay',
11033    value: function closeOverlay() {
11034      $('#wemobi-header').removeClass('opened-overlay');
11035      this.overlay.removeClass('active');
11036      this.modalShowImage.removeClass('active');
11037      this.modalSreenShot.removeClass('active');
11038      this.modalTermsAndConditions.removeClass('active');
11039      this.closeCamera(this.stream);
11040      $('body, html').css('overflow-y', 'auto');
11041    }
11042  }, {
11043    key: 'getImage',
11044    value: function getImage() {
11045      var _this5 = this;
11046
11047      var isImage = this.passenger._image;
11048
11049      if (!isImage) return;
11050
11051      var body = {
11052        "userId": this.passenger ? this.passenger._id : ''
11053      };
11054
11055      var headers = {
11056        'Authorization': '' + SessionStorage.get('jca_token')
11057      };
11058
11059      LoaderService.show();
11060      HttpService.get('getImage?' + $.param(body), headers).then(function (data) {
11061        LoaderService.hide();
11062        if (data && data.image) {
11063          var label = $('#text-when-already-photo').val();
11064          var link = $('[data-js="capture-photo-link"]');
11065          if ($(link).find('p') && label) {
11066            if ($(link).find('p').find('a') && label) {
11067              $(link).find('p').find('a').text(label);
11068            } else {
11069              $(link).find('p').text(label);
11070            }
11071          }
11072        }
11073        _this5.setImage(data.image);
11074      }).catch(function () {
11075        LoaderService.hide();
11076      });
11077    }
11078  }, {
11079    key: 'registerImage',
11080    value: function registerImage(imageBase64, userRegisterId) {
11081      var _this6 = this;
11082
11083      var headers = {
11084        'Authorization': '' + SessionStorage.get('jca_token')
11085      };
11086
11087      var body = {
11088        "UserId": this.passenger ? this.passenger._id : userRegisterId,
11089        "Image": imageBase64
11090      };
11091
11092      LoaderService.show();
11093      HttpService.post('registerImage', body, headers).then(function (data) {
11094        LoaderService.hide();
11095        Alert.show(i18n('register_image_success'));
11096        _this6.passenger._image = true;
11097        SessionStorage.set('passenger', _this6.passenger);
11098      }).catch(function () {
11099        LoaderService.hide();
11100        Alert.show(i18n('register_image_fail'));
11101      });
11102    }
11103  }, {
11104    key: 'updateImage',
11105    value: function updateImage(imageBase64) {
11106      var _this7 = this;
11107
11108      var headers = {
11109        'Authorization': '' + SessionStorage.get('jca_token')
11110      };
11111
11112      var body = {
11113        "UserId": this.passenger._id,
11114        "Image": imageBase64
11115      };
11116
11117      LoaderService.show();
11118      HttpService.put('updateImage', body, headers).then(function (data) {
11119        LoaderService.hide();
11120        _this7.setImage(data.image);
11121        _this7.passenger._image = true;
11122        SessionStorage.set('passenger', _this7.passenger);
11123        Alert.show(i18n('update_image_success'));
11124      }).catch(function () {
11125        LoaderService.hide();
11126        Alert.show(i18n('update_image_fail'));
11127      });
11128    }
11129  }, {
11130    key: 'setImage',
11131    value: function setImage(image) {
11132      this.capturePhotoCam.attr('src', image);
11133      this.capturePhotoCam.addClass('active');
11134    }
11135  }, {
11136    key: 'showCapturePhoto',
11137    value: function showCapturePhoto() {
11138      var isFormData = SessionStorage.get('formData');
11139      var isPassenger = SessionStorage.get('passenger');
11140
11141      if (isFormData && !isPassenger) {
11142        $('[data-js="capture-component"]').hide();
11143        $('.text-captura-photo-hide').hide();
11144        return;
11145      }
11146
11147      $('[data-js="capture-component"]').show();
11148      $('.text-captura-photo-hide').show();
11149    }
11150  }, {
11151    key: 'rotateImage',
11152    value: function rotateImage() {
11153      var base64 = $('[data-js="screen-result"]').attr('src');
11154      var image = new Image();
11155      image.src = base64;
11156
11157      var canvas = document.createElement('canvas');
11158      var context = canvas.getContext('2d');
11159      var degrees = 90;
11160
11161      var aux = this.maxWidth;
11162      this.maxWidth = this.maxHeight;
11163      this.maxHeight = aux;
11164
11165      canvas.width = this.maxWidth;
11166      canvas.height = this.maxHeight;
11167
11168      context.clearRect(0, 0, canvas.width, canvas.height);
11169      context.save();
11170      context.translate(canvas.width / 2, canvas.height / 2);
11171      context.rotate(degrees * Math.PI / 180);
11172      context.drawImage(image, -image.width / 2, -image.height / 2);
11173      context.restore();
11174
11175      var rotatedImage = canvas.toDataURL("image/png");
11176      this.capturePhotoCam.attr('src', rotatedImage);
11177      $('[data-js="screen-result"]').attr('src', rotatedImage);
11178    }
11179  }, {
11180    key: 'resizeBase64Image',
11181    value: function resizeBase64Image(base64, maxWidth, maxHeight) {
11182      var deferred = $.Deferred();
11183      var image = new Image();
11184      image.src = base64;
11185
11186      image.onload = function () {
11187        var canvas = document.createElement('canvas');
11188        canvas.width = maxWidth;
11189        canvas.height = maxHeight;
11190        var context = canvas.getContext('2d');
11191        context.drawImage(image, 0, 0, maxWidth, maxHeight);
11192        context.restore();
11193        deferred.resolve(canvas.toDataURL("image/png"));
11194      };
11195
11196      return deferred.promise();
11197    }
11198  }]);
11199
11200  return CapturePhoto;
11201}();
11202'use strict';
11203
11204var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
11205
11206function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
11207
11208var CardAdvantage = function () {
11209  function CardAdvantage($) {
11210    _classCallCheck(this, CardAdvantage);
11211
11212    this.init();
11213  }
11214
11215  _createClass(CardAdvantage, [{
11216    key: 'init',
11217    value: function init() {
11218      $('.slick-carousel').slick({
11219        dots: false,
11220        infinite: false,
11221        arrows: false,
11222        slidesToShow: 3,
11223        responsive: [{
11224          breakpoint: 769,
11225          settings: {
11226            slidesToShow: 1,
11227            slidesToScroll: 1,
11228            infinite: true,
11229            dots: true,
11230            arrows: true
11231          }
11232        }, {
11233          breakpoint: 992,
11234          settings: {
11235            slidesToShow: 2,
11236            slidesToScroll: 1,
11237            infinite: false,
11238            dots: true,
11239            arrows: true
11240          }
11241        }]
11242      });
11243    }
11244  }]);
11245
11246  return CardAdvantage;
11247}();
11248'use strict';
11249
11250var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
11251
11252function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
11253
11254var CartComponent = function () {
11255  function CartComponent($, formData) {
11256    var useSummary = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
11257
11258    _classCallCheck(this, CartComponent);
11259
11260    this.priceCart = $('[data-js="price-cart"]');
11261    this.priceCartLock = 0;
11262    this.priceCartPix = $('[data-js="price-cart-pix"]');
11263    this.subtotalSeats = $('[data-js="subtotal-seats"]');
11264    this.component = $('[data-js="cart"]');
11265    this.buttonClose = $('[data-js="btn-close-cart-details"]');
11266    this.cartDetailsPage = $('.cart-details-container');
11267    this.summaryOrigin = $('[data-js="summary-label-origin"]');
11268    this.summaryDestination = $('[data-js=summary-label-destination]');
11269    this.returnSection = $('[data-js="return-section"]');
11270    this.amountPassengersLabel = $('[data-js="amount-passengers-label"]');
11271    this.tripDetailsReturn = $('[data-js="trip-details-return"]');
11272    this.departureSection = $('[data-js="departure-section"]');
11273    this.returnSection = $('[data-js="return-section"]');
11274    this.innerContainer = $('.inner-container');
11275    this.quantityOffer = $('.quantity-offers');
11276    this.removeTrip = $('[data-js="remove-trip"]');
11277    this.showPriceDetailsLabel = $('[data-js="show-detail
11277s-price-label"]');
11278    this.showPriceBody = $('.show-details-buy');
11279    this.showPriceBody.click(this.showPriceDetailsAction);
11280    this.hashSelected = window.location.href.split("#")[1];
11281    this.discount = $('[data-js="discount-code"]');
11282    this.btnApplyDiscount = $('[data-js="button-apply-discount"]').attr('disabled', true);
11283    this.isDiscount = $('[data-js="discount"]');
11284    this.isDiscount.hide();
11285    this.tripType = $('[data-js="trip-type"]');
11286    this.passengerQuantity = $('[data-js="passenger-quantity"]');
11287    this.pricetotalDiscount = $('[data-js="price-discount"]');
11288    this.pricePixInBottomCart = $('[data-js="price-in-bottom-cart-pix"]');
11289    this.totalPriceBottomCart = $('[data-js="price-in-bottom-cart"]');
11290    this.showResumeBottomCardText = $('[data-js="show-resume-bottom-cart-text"]');
11291    this.convenienceFee = $('[data-js="convenience-fee"]').attr('value') == 'true' ? true : false;
11292    this.labelConvenienceFee = $('[data-js="label-convenience-fee"]');
11293    this.faqConvenienceFee = $('[data-js="faq-convenience-fee"]');
11294    this.totalconvenienceFee = $('[data-js="total-convenience-fee"]');
11295    this.showServiceFeeTooltip = $('[data-js="show-service-fee-tooltip"]').val() == 'true';
11296    this.txTravelInsurance = 0;
11297    this.txTravelInsuranceReturn = 0;
11298    this.subSeat = 0;
11299    this.appliedCoupon = false;
11300    this.txPriceTotalConvenienceFee = 0;
11301    this.hideValues = $('[data-js="cart-component-hide-values"]').val();
11302    this.loadInstallmentsAPI = $('[data-js="installments-api"]').attr('value') == 'true';
11303    this.remarkV2 = SessionStorage.get('repricingv2');
11304    this.isSeatReservationPage = $('#jca-identifier-page').val() == 'jca-seat-reservation-page';
11305    this.totalOffDiscount = false;
11306    this.configImagePoints = $('[data-js="config-image-points-giro-cart"]');
11307    this.configLabelPoints = $('[data-js="config-label-points-giro-cart"]');
11308    this.configModalPoints = $('[data-js="config-modal-points-text-cart"]');
11309    this.saleplataform = null;
11310	this.useSummary = useSummary;
11311    this.init(formData);
11312  }
11313
11314  _createClass(CartComponent, [{
11315    key: 'init',
11316    value: function init(formData) {
11317      this.handleConvenienceFee();
11318      this.saleplatform = SessionStorage.get('utm_saleplatform');
11319      if (formData) {
11320        var cartObject = SessionStorage.get('cart');
11321        this.initLabelShowComponent();
11322        this.initOriginDestinationComponents(formData);
11323        this.handleRemoveTrip();
11324        this.submitDiscount();
11325        this.listenForm();
11326        this.showTicketsInCollapse();
11327
11328        if (cartObject) {
11329          this._cartService = new CartService(cartObject, this);
11330          if (!this.useSummary) {
11331              this.updateCartView();
11332          } else {
11333              this.initCartViewWithoutCalc(cartObject);
11334              cartObject = this._cartService._cart;
11335          }
11336          this.initSummaryComponents();
11337          this.initPassengerList(cartObject, cartObject._insurance && cartObject._insurance.hired);
11338          this.initSections(formData);
11339          this.handleDetailsPage();
11340          this.loadBottomCartInformationTrip(formData);
11341
11342          if (this._cartService.amountOffers > 0) {
11343            this.quantityOffer.text(this._cartService.amountOffers);
11344            this.quantityOffer.show();
11345            $('[data-js="header-search-button"]').hide();
11346          }
11347        } else {
11348          this._cartService = new CartService(null, this);
11349          this._cartService.departureOnly = formData.departureOnly;
11350          this._cartService.addPassengers(formData.passengers);
11351
11352          $('[data-js="header-search-button"]').show();
11353          this.quantityOffer.hide();
11354          $('.cart-icon').removeClass('show');
11355        }
11356      } else {
11357        $('[data-js="header-search-button"]').show();
11358        this.quantityOffer.hide();
11359        $('.cart-icon').removeClass('show');
11360      }
11361      this.clubGiroPoints();
11362      if (this.showServiceFeeTooltip) {
11363        this.initializeServiceFeeTooltip();
11364      }
11365    }
11366  }, {
11367    key: 'initCartViewWithoutCalc',
11368    value: function initCartViewWithoutCalc(cartObject) {
11369        var cartSummary = SessionStorage.get('cartSummary');
11370
11371        if (cartSummary) {
11372            this.updateCartBySummary(cartSummary);
11373        }
11374
11375        this.hideServiceFeeValues();
11376        this.handleConvenienceFee(this._cartService.totalConvenienceFee);
11377        this.initPassengerDivision(cartObject);
11378        this.quantityOffer.show();
11379        $('.cart-icon').addClass('show');
11380        $('[data-js="header-search-button"]').hide();
11381    }
11382  }, {
11383    key: 'handleConvenienceFee',
11384    value: function handleConvenienceFee(totalconvenienceFee) {
11385      if (this.convenienceFee) {
11386        $('.convenienceFee').removeClass('d-none');
11387        this.labelConvenienceFee.text(i18n('convenience_fee'));
11388        if (totalconvenienceFee == 0) $('.convenienceFee').addClass('d-none');
11389        if (totalconvenienceFee > 0) $('.convenienceFee').removeClass('d-none');
11390      } else $('.convenienceFee').addClass('d-none');
11391    }
11392  }, {
11393    key: 'listenForm',
11394    value: function listenForm() {
11395      var _this = this;
11396
11397      this.discount.on('change', function () {
11398        if (_this.discount.val() == '') {
11399          _this.btnApplyDiscount.attr('disabled', true);
11400        } else {
11401          _this.btnApplyDiscount.attr('disabled', false);
11402        }
11403      });
11404
11405      this.discount.on('input', function () {
11406        $(this).val($(this).val().replace(/\s/g, ""));
11407      });
11408
11409      this.faqConvenienceFee.on('click', function () {
11410        var el = _this.faqConvenienceFee[0];
11411
11412				var tooltip = bootstrap.Tooltip.getInstance(el);
11413				if (!tooltip) tooltip = new bootstrap.Tooltip(el);
11414
11415				tooltip.show();
11416      });
11417    }
11418  }, {
11419    key: 'initSeatColors',
11420    value: function initSeatColors() {
11421      var _this2 = this;
11422
11423      var cartDetailsContainer = $('.cart-details-container');
11424      cartDetailsContainer.each(function (index) {
11425        var parent = $(cartDetailsContainer.get(index));
11426        var passengerSeats = parent.find('.icon-seat');
11427        if (_this2.selectedSeatColor) passengerSeats.attr('style', 'color: ' + _this2.selectedSeatColor + ' !important;');
11428        if (_this2.selectedSeatFontColor) passengerSeats.find('.icon-seat-number').attr('style', 'color: ' + _this2.selectedSeatFontColor + ' !important;');
11429      });
11430    }
11431  }, {
11432    key: 'handleDetailsPage',
11433    value: function handleDetailsPage() {
11434      if (this.hashSelected == 'cart') {
11435        var event = {
11436          data: {
11437            'cartDetailsPage': this.cartDetailsPage,
11438            'innerContainer': this.innerContainer
11439          }
11440        };
11441        if ($(window).width() < 950) this.showDetailsPage(event); else CartButton.showModal();
11442      }
11443    }
11444  }, {
11445    key: 'clubGiroPoints',
11446    value: function clubGiroPoints() {
11447      var $changePointsGiroContainer = $('[data-js="points-giro-container-cart"]');
11448      var $sizeImagePointsGiro = $('[data-js="image-points-giro-cart"]');
11449      var isVisible = $('[data-js="config-points-giro-container-cart"]').attr('visible') === 'true';
11450      var $changePointsGiroLabel = $('.points-giro-label');
11451      var $changePointsGiroModal = $('[data-js="text-modal-points-cart"]');
11452      if (!this.remarkV2) {
11453        $sizeImagePointsGiro.css('height', this.configImagePoints.attr('height'));
11454        $sizeImagePointsGiro.css('width', this.configImagePoints.attr('width'));
11455        $changePointsGiroLabel.css('color', this.configLabelPoints.attr('color'));
11456        $changePointsGiroLabel.css('font-family', this.configLabelPoints.attr('fontFamily'));
11457        $changePointsGiroLabel.css('font-size', this.configLabelPoints.attr('fontSize'));
11458        $changePointsGiroLabel.text(this.configLabelPoints.attr('text'));
11459        $changePointsGiroModal.text(this.configModalPoints.attr('text'));
11460        isVisible ? $changePointsGiroContainer.removeClass('d-none') : $changePointsGiroContainer.addClass('d-none');
11461      } else {
11462        $changePointsGiroContainer.addClass('d-none');
11463      }
11464    }
11465  }, {
11466    key: 'loadBottomCartInformationTrip',
11467    value: function loadBottomCartInformationTrip(formData) {
11468      if (formData.departureOnly) this.tripType.text('IDA'); else this.tripType.text('IDA E VOLTA');
11469    }
11470  }, {
11471    key: 'seatInsurance',
11472    value: function seatInsurance(passenger) {
11473        return parseFloat(passenger._seatDeparture._insurance) + parseFloat(passenger._seatDepartureConnection._insurance) + parseFloat(passenger._seatDepartureConnection2._insurance) + parseFloat(passenger._seatReturn._insurance) + parseFloat(passenger._seatReturnConnection._insurance) + parseFloat(passenger._seatReturnConnection2._insurance);
11474    }
11475  }, {
11476    key: 'seatTotal',
11477    value: function seatTotal(passenger) {
11478        var sum = parseFloat(passenger._seatDeparture._rate) + parseFloat(passenger._seatDepartureConnection._rate) + parseFloat(passenger._seatDepartureConnection2._rate) + parseFloat(passenger._seatReturn._rate) + parseFloat(passenger._seatReturnConnection._rate) + parseFloat(passenger._seatReturnConnection2._rate);
11479        return Math.round((sum + 0.00001) * 100) / 100;
11480    }
11481  }, {
11482    key: 'seatTaxesTotal',
11483    value: function seatTaxesTotal(passenger) {
11484        var seat_departure_tax = 0;
11485        var seat_departure_con_tax = 0;
11486        var seat_departure_con2_tax = 0;
11487        var seat_return_tax = 0;
11488        var seat_return_con_tax = 0;
11489        var seat_return_con2_tax = 0;
11490
11491        seat_departure_tax = parseFloat(passenger._seatDeparture._tax) + parseFloat(passenger._seatDeparture._other) + parseFloat(passenger._seatDeparture._insurance) + parseFloat(passenger._seatDeparture._toll) + parseFloat(passenger._seatDeparture._boardingFee);
11492
11493        seat_departure_con_tax = parseFloat(passenger._seatDepartureConnection._tax) + parseFloat(passenger._seatDepartureConnection._other) + parseFloat(passenger._seatDepartureConnection._insurance) + parseFloat(passenger._seatDepartureConnection._toll) + parseFloat(passenger._seatDepartureConnection._boardingFee);
11494
11495        seat_departure_con2_tax = parseFloat(passenger._seatDepartureConnection2._tax) + parseFloat(passenger._seatDepartureConnection2._other) + parseFloat(passenger._seatDepartureConnection2._insurance) + parseFloat(passenger._seatDepartureConnection2._toll) + parseFloat(passenger._seatDepartureConnection2._boardingFee);
11496
11497        seat_return_tax = parseFloat(passenger._seatReturn._tax) + parseFloat(passenger._seatReturn._other) + parseFloat(passenger._seatReturn._insurance) + parseFloat(passenger._seatReturn._toll) + parseFloat(passenger._seatReturn._boardingFee);
11498
11499        seat_return_con_tax = parseFloat(passenger._seatReturnConnection._tax) + parseFloat(passenger._seatReturnConnection._other) + parseFloat(passenger._seatReturnConnection._insurance) + parseFloat(passenger._seatReturnConnection._toll) + parseFloat(passenger._seatReturnConnection._boardingFee);
11500
11501        seat_return_con2_tax = parseFloat(passenger._seatReturnConnection2._tax) + parseFloat(passenger._seatReturnConnection2._other) + parseFloat(passenger._seatReturnConnection2._insurance) + parseFloat(passenger._seatReturnConnection2._toll) + parseFloat(passenger._seatReturnConnection2._boardingFee);
11502
11503        return seat_departure_tax + seat_departure_con_tax + seat_departure_con2_tax + seat_return_tax + seat_return_con_tax + seat_return_con2_tax;
11504    }
11505  }, {
11506    key: 'initPrices',
11507    value: function initPrices(list, offers) {
11508      var total = 0;
11509      var taxes = 0;
11510      var insurance = 0;
11511
11512      var _iteratorNormalCompletion = true;
11513      var _didIteratorError = false;
11514      var _iteratorError = undefined;
11515
11516      try {
11517        for (var _iterator = list[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
11518          var passenger = _step.value;
11519
11520          total = this.seatTotal(passenger);
11521          taxes += this.seatTaxesTotal(passenger);
11522          insurance += this.seatInsurance(passenger);
11523        }
11524      } catch (err) {
11525        _didIteratorError = true;
11526        _iteratorError = err;
11527      } finally {
11528        try {
11529          if (!_iteratorNormalCompletion && _iterator.return) {
11530            _iterator.return();
11531          }
11532        } finally {
11533          if (_didIteratorError) {
11534            throw _iteratorError;
11535          }
11536        }
11537      }
11538
11539      if (total <= 0) {
11540        var _iteratorNormalCompletion2 = true;
11541        var _didIteratorError2 = false;
11542        var _iteratorError2 = undefined;
11543
11544        try {
11545          for (var _iterator2 = offers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
11546            var offer = _step2.value;
11547
11548            insurance += parseFloat(offer.insurance);
11549          }
11550        } catch (err) {
11551          _didIteratorError2 = true;
11552          _iteratorError2 = err;
11553        } finally {
11554          try {
11555            if (!_iteratorNormalCompletion2 && _iterator2.return) {
11556              _iterator2.return();
11557            }
11558          } finally {
11559            if (_didIteratorError2) {
11560              throw _iteratorError2;
11561            }
11562          }
11563        }
11564      }
11565
11566      total = Math.round((total + 0.00001) * 100) / 100;
11567      taxes = Math.round((taxes + 0.00001) * 100) / 100;
11568      insurance = Math.round((insurance + 0.00001) * 100) / 100;
11569
11570      return {
11571        total: total,
11572        taxes: taxes,
11573        insurance: insurance
11574      };
11575    }
11576  }, {
11577    key: 'initPassengerDivision',
11578    value: function initPassengerDivision(cartObject) {
11579      var _this3 = this;
11580
11581      var passTotal = $('[data-js="num-pass-total"]');
11582      var passTotalInBottomCart = this.passengerQuantity;
11583      var passRegular = $('[data-js="num-pass-regular"]');
11584      var passChild = $('[data-js="num-pass-child"]');
11585      var passInfant = $('[data-js="num-pass-infant"]');
11586      var externalReg = $('[data-js="regular"]');
11587      var externalChild = $('[data-js="child"]');
11588      var externalInfant = $('[data-js="infant"]');
11589      var externalTaxes = $('[data-js="taxes"]');
11590      var externalInsurance = $("[data-js='opt-insurance']");
11591      var priceRegular = $("[data-js='price-regular']");
11592      var priceChild = $("[data-js='price-child']");
11593      var priceInfant = $("[data-js='price-infant']");
11594      var priceTaxes = $("[data-js='price-taxes']");
11595      var priceInsurance = $("[data-js='price-opt-insurance']");
11596
11597      var list = cartObject._listPassengers;
11598      var totalTaxes = 0;
11599      var totalInsurance = 0;
11600      var total = void 0,
11601        regular = void 0,
11602        child = void 0,
11603        infant = void 0;
11604      var auxIndex = 0;
11605
11606      total = list.length;
11607      passTotal.text(total == 1 ? total + ' passageiro' : total + ' passageiros');
11608      passTotalInBottomCart.text(total == 1 ? total + ' passageiro' : total + ' passageiros');
11609
11610      for (var i = 0; i < list.length; i++) {
11611        var departure_insurance = parseFloat(list[i]._seatDeparture._insurance);
11612        var departure_con_insurance = parseFloat(list[i]._seatDepartureConnection._insurance);
11613        var return_insurance = parseFloat(list[i]._seatReturn._insurance);
11614        var return_con_insurance = parseFloat(list[i]._seatReturnConnection._insurance);
11615
11616        totalInsurance += departure_insurance + departure_con_insurance + return_insurance + return_con_insurance;
11617      }
11618
11619      child = list.filter(function (el) {
11620        return el._type === "CHILD_A";
11621      });
11622      infant = list.filter(function (el) {
11623        return el._type === "CHILD";
11624      });
11625      regular = list.filter(function (el) {
11626        return el._type == "ADULT" || el._type !== "CHILD_A" && el._type !== "CHILD";
11627      });
11628
11629      if (child.length == 0 && infant.length == 0 && regular.length == 0) {
11630        this.showPriceBody.hide();
11631      } else {
11632        this.showPriceBody.show();
11633
11634        if (regular.length > 0) {
11635          var content = [];
11636          var valuesRegular = this.initPrices(regular, cartObject._listOffer);
11637
11638          regular.forEach(function (passenger, index) {
11639            content.push('<li class="regular-price-row row">\n\t\t\t\t\t<div class="col-8"><strong class="value">' + ++auxIndex + '\xBA </strong>passageiro(a) regular</div>\n\t\t\t\t\t<div class="col-4 nopadding"><strong class="value">R$<span>\n\t\t\t\t\t\t' + (_this3.seatTotal(passenger) > 0 ? Utils.formatPrice(_this3.seatTotal(passenger)) : Utils.formatPrice(valuesRegular.total)) + '\n\t\t\t\t\t</span></strong></div>\n\t\t\t\t\t</li>');
11640          });
11641
11642          $('[data-js="regular-distribution-list"]').empty().append(content.join(''));
11643
11644          $('.regular').show();
11645          externalReg.show();
11646          passRegular.text(regular.length);
11647          totalTaxes += valuesRegular.taxes;
11648          priceRegular.text(Utils.formatPrice(valuesRegular.total));
11649        } else {
11650          externalReg.hide();
11651          $('.regular').hide();
11652        }
11653
11654        if (child.length > 0) {
11655          var contentChild = [];
11656          var valuesChild = this.initPrices(child, cartObject._listOffer);
11657
11658          child.forEach(function (passenger, index) {
11659            contentChild.push('<li class="regular-price-row row">\n\t\t\t\t\t<div class="col-8"><strong class="value">' + ++auxIndex + '\xBA </strong>crian\xE7a com assento</div>\n\t\t\t\t\t<div class="col-4 nopadding"><strong class="value">R$<span>\n\t\t\t\t\t\t' + (_this3.seatTotal(passenger) > 0 ? Utils.formatPrice(_this3.seatTotal(passenger)) : Utils.formatPrice(valuesChild.total)) + '\n\t\t\t\t\t</span></strong></div>\n\t\t\t\t\t</li>');
11660          });
11661
11662          $('[data-js="child-distribution-list"]').empty().append(contentChild.join(''));
11663
11664          $('.child').show();
11665          externalChild.show();
11666          passChild.text(child.length);
11667          totalTaxes += valuesChild.taxes;
11668          priceChild.text(Utils.formatPrice(valuesChild.total));
11669        } else {
11670          externalChild.hide();
11671          $('.child').hide();
11672        }
11673
11674        if (infant.length > 0) {
11675          var contentInfant = [];
11676
11677          infant.forEach(function (passenger, index) {
11678            contentInfant.push('<li class="regular-price-row row">\n\t\t\t\t\t<div class="col-8"><strong class="value">' + ++auxIndex + '\xBA </strong>crian\xE7a sem assento</div>\n\t\t\t\t\t<div class="col-4 nopadding"><strong class="value">R$ <span>\n\t\t\t\t\t\t0,00\n\t\t\t\t\t</span></strong></div>\n\t\t\t\t\t</li>');
11679          });
11680
11681          $('[data-js="infant-distribution-list"]').empty().append(contentInfant.join(''));
11682
11683          $('.infant').show();
11684          externalInfant.show();
11685          passInfant.text(infant.length);
11686          priceInfant.text(Utils.formatPrice(0));
11687        } else {
11688          externalInfant.hide();
11689          $('.infant').hide();
11690        }
11691
11692        if (totalTaxes > 0) {
11693          totalTaxes = Math.round((totalTaxes + 0.00001) * 100) / 100;
11694          priceTaxes.text(' ' + Utils.formatPrice(totalTaxes));
11695          externalTaxes.show();
11696        } else {
11697          externalTaxes.hide();
11698        }
11699
11700        if (cartObject._insurance.hired) {
11701          totalInsurance = Math.round((totalInsurance + 0.00001) * 100) / 100;
11702          priceInsurance.text(Utils.formatPrice(totalInsurance));
11703          externalInsurance.show();
11704        } else {
11705          externalInsurance.hide();
11706        }
11707      }
11708    }
11709  }, {
11710    key: 'initPassengerList',
11711    value: function initPassengerList(cartObject, isTravelInsurance) {
11712      var cartPassList = cartObject._listPassengers;
11713      var cartOfferList = cartObject._listOffer;
11714      var depSection = $('[data-js="departure-section"] [data-js="cart-passenger-list"]');
11715      var retSection = $('[data-js="return-section"] [data-js="cart-passenger-list"]');
11716      depSection.empty();
11717      retSection.empty();
11718
11719      if (this.remarkV2) this.initPassengerListRemarkFlow(cartPassList, cartOfferList, depSection, retSection, isTravelInsurance); else this.initPassengerListNormalFlow(cartPassList, cartOfferList, depSection, retSection, isTravelInsurance);
11720
11721      this.handleRemovePassenger();
11722      new Collapse($);
11723    }
11724	}, {
11725		key: 'initPassengerListNormalFlow',
11726		value: function initPassengerListNormalFlow(cartPassList, cartOfferList, depSection, retSection, isTravelInsurance) {
11727			var _this4 = this;
11728
11729			var itemDeparture = void 0;
11730			var itemReturn = void 0;
11731			var totalInsurance = 0;
11732			var totalInsuranceReturn = 0;
11733			var departureTotalPrice = 0;
11734			var returnTotalPrice = 0;
11735			var subTotalPixDep = 0;
11736			var subTotalPixRet = 0;
11737			var cart = SessionStorage.get('cart');
11738
11739			// Maps each internal seat field to its code in the summary aggregate.
11740			var SUMMARY_CODE_BY_FIELD = {
11741				_rate: "Tariff",
11742				_toll: "Tax",
11743				_seatSaleLockValueCalculate: "SeatSaleLockValueCalculate",
11744				_price: "SubTotal",
11745				_commission: "CommissionFee",
11746				_subTotalPix: "SubTotalPix"
11747			};
11748
11749			// Sums the field across the seat and its connections. For an unselected/random
11750			// seat (outside the summary flow), uses the offer value instead.
11751			var sumSeatsOrOffer = function sumSeatsOrOffer(seats, seatField, offer, offerField) {
11752				var mainSeat = seats[0];
11753				var useOfferValue = !_this4.useSummary && (!mainSeat || !mainSeat._seatNumber);
11754
11755				if (useOfferValue) {
11756					return offer && offer[offerField] ? parseFloat(offer[offerField]) : 0;
11757				}
11758				return seats.reduce(function (sum, seat) {
11759					return sum + (seat[seatField] || 0);
11760				}, 0);
11761			};
11762
11763			// In the summary flow, returns the passenger's ready aggregate value (no front sum);
11764			// otherwise falls back to summing seat + connections (or the offer).
11765			var getSeatValue = function getSeatValue(aggregate, seats, seatField, offer, offerField) {
11766				var summaryCode = SUMMARY_CODE_BY_FIELD[seatField];
11767				var hasAggregateValue = _this4.useSummary && aggregate && summaryCode && aggregate[summaryCode] != null;
11768
11769				if (hasAggregateValue) {
11770					return aggregate[summaryCode];
11771				}
11772
11773				return sumSeatsOrOffer(seats, seatField, offer, offerField);
11774			};
11775
11776			// Insurance (Seguro Viagem) comes from the passenger aggregate, stored on the main
11777			// seat so it survives the storage round-trip; falls back to summing the seats' W2i.
11778			var getInsuranceValue = function getInsuranceValue(mainSeat, aggregate, seats) {
11779				if (_this4.useSummary) {
11780					if (mainSeat && mainSeat._summaryPassengerInsurance != null) {
11781						return mainSeat._summaryPassengerInsurance;
11782					}
11783					if (aggregate && aggregate.Insurance != null) {
11784						return aggregate.Insurance;
11785					}
11786				}
11787
11788				return seats.reduce(function (sum, seat) {
11789					var w2i = seat && seat._insuranceW2i;
11790					if (!w2i) return sum;
11791					return sum + (w2i.value != null ? w2i.value || 0 : w2i || 0);
11792				}, 0);
11793			};
11794
11795            //AEM translations
11796            var tariff = $('[data-js="cart-details-text-values"]').attr('data-text-tariff');
11797            var tax = $('[data-js="cart-details-text-values"]').attr('data-text-tax');
11798            var totalLabel = $('[data-js="cart-details-text-values"]').attr('data-text-total');
11799            var priceDetailsLabel = $('[data-js="cart-details-text-values"]').attr('data-text-price-details');
11800            var travelInsuranceLabel = $('[data-js="cart-details-text-values"]').attr('data-text-travel-insurance');
11801            var textOldTripValue = $('[data-js="cart-details-text-values"]').attr('data-text-old-trip-value');
11802            var textNewTripValue = $('[data-js="cart-details-text-values"]').attr('data-text-new-trip-value');
11803
11804			cartPassList.forEach(function (el, i) {
11805				var seatDeparture = el._seatDeparture;
11806				var seatDepartureConnection = el._seatDepartureConnection;
11807				var seatDepartureConnection2 = el._seatDepartureConnection2;
11808				var departureAggregate = el._summaryDeparture;
11809				var departureServiceAggregate = cart._summaryDepartureService;
11810				var departureSeats = [seatDeparture, seatDepartureConnection, seatDepartureConnection2];
11811
11812				var departureOffer = cartOfferList[0];
11813
11814				var price = getSeatValue(departureAggregate, departureSeats, "_rate", departureOffer, "_rate");
11815
11816				var taxa = getSeatValue(departureAggregate, departureSeats, "_toll", departureOffer, "_toll");
11817
11818				var hasDepartureTaxa = taxa === 0 ? " d-none" : "";
11819
11820				var insurance = isTravelInsurance ? getInsuranceValue(seatDeparture, departureAggregate, departureSeats) : 0;
11821
11822				_this4.txTravelInsurance = totalInsurance;
11823
11824				var convenienceFee = _this4._cartService.cart.totalConvenienceFee;
11825
11826				var totalPrice = getSeatValue(departureAggregate, departureSeats, "_price", departureOffer, "_price");
11827				// Trip-level (trecho) pix subtotal comes from the service valueParts; passenger aggregate is the fallback.
11828				subTotalPixDep = _this4.useSummary && departureServiceAggregate && departureServiceAggregate.SubTotalPix != null ? departureServiceAggregate.SubTotalPix : getSeatValue(departureAggregate, departureSeats, "_subTotalPix", departureOffer, "_subTotalPix");
11829
11830				$('[data-price="price-departure"]').attr('data-price-service-id', el._seatDeparture._service);
11831				$('[data-price="price-departure-pix"]').attr('data-price-service-id', el._seatDeparture._service);
11832
11833				if (el._type === "CHILD") {
11834					totalPrice = 0;
11835				}
11836
11837				// Trip-level (trecho) subtotal comes from the service valueParts; front sum is the fallback.
11838				departureTotalPrice = _this4.useSummary && departureServiceAggregate && departureServiceAggregate.SubTotal != null ? departureServiceAggregate.SubTotal : departureTotalPrice + totalPrice;
11839
11840				if (el._name) {
11841					itemDeparture = '\n\t\t\t\t\t<li data-serviceId="' + el._seatDeparture._service + '-' + el._seatDeparture._seatNumber + '">\n\t\t\t\t\t\t<div class="container-cart-passenger">\n\t\t\t\t\t\t\t<span class="name">' + el._name + '</span>\n\t\t\t\t\t\t\t\t<span class="square-seat">\n\t\t\t\t\t\t\t\t\t<p class="icon-seat-number">' + (el._seatDeparture._seatNumber ? el._seatDeparture._seatNumber : '-') + '</p>\n\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t<span class="seat-subtitle btn-collapse" data-bs-collapse="collapse" id="collapse-' + i + '" data-js="collapse-' + i + '">' + priceDetailsLabel + '<span class="icon-collapse jca-ico-angle-down" data-js="collapse-' + i + '"></span>\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class="container-cart-details collapse-container" data-js="collapse-' + i + '">\n\t\t\t\t\t\t\t<div class="container-cart-details-content">\n\t\t\t\t\t\t\t\t<p class="title"><span class="container-cart-details-title">' + tariff + '</span><span class="container-cart-details-result"> R$ ' + Utils.formatPrice(price) + '</span></p>\n\t\t\t\t\t\t\t\t<p class="title ' + hasDepartureTaxa + '"><span class="container-cart-details-title">' + tax + '</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(taxa) + '</span></p>\n\t\t\t\t\t\t\t\t' + (!cart._listOffer[0]._priceWithDiscountPix || cart._listOffer[0]._priceWithDiscountPix === cart._listOffer[0]._price ? '<p class="title">\n\t\t\t\t\t\t\t\t\t\t<span class="container-cart-details-title total d-none">\n\t\t\t\t\t\t\t\t\t\t\t' + i18n('convenience_fee') + '\n\t\t\t\t\t\t\t\t\t\t\t<a class="icon jca-ico-info-icon tooltip-btn" href="#">\n\t\t\t\t\t\t\t\t\t\t\t\t<span class="tooltiptext">' + i18n('msg_faq_convenience_fee') + '</span>\n\t\t\t\t\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t<span class="container-cart-details-result d-none" data-js="cart-details-departure-convenience-fee">\n\t\t\t\t\t\t\t\t\t\t\tR$ ' + Utils.formatPrice(convenienceFee) + '\n\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t</p>' : '') + '\n                <p class="title ' + (isTravelInsurance ? '' : 'd-none') + '"><span class="container-cart-details-title">Seguro Viagem</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(insurance) + '</span></p>\n                <p class="title total"><span class="container-cart-details-title total">SubTotal</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(totalPrice) + '</span></p>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class="price-ticket-content d-none">\n\t\t\t\t\t\t\t\t<a href="javascript:void(0)" id="remove-passenger-' + i + '" class="icon-close remove-ticket" data-js="remove-passenger" index=' + i + '>Remover item</a>\n\t\t\t\t\t\t\t\t<p><span class="icon">R$</span><span class="total-price">' + Utils.formatPrice(totalPrice) + '</span></p>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</li>\n\t\t\t\t';
11842
11843					if (!cart._listOffer[0]._priceWithDiscountPix || cart._listOffer[0]._priceWithDiscountPix === cart._listOffer[0]._price || _this4.remarkV2) {
11844						$('[data-price="price-departure"]').text(Utils.formatPrice(departureTotalPrice));
11845						$('[data-price="price-departure-pix"]').addClass('d-none');
11846						$('[data-price="price-return-pix"]').addClass('d-none');
11847						$('[data-js="card-price-dep"]').hide();
11848						$('[data-js="card-price-ret"]').hide();
11849						$('span.pix').addClass('d-none');
11850						$('p.line-discount-pix').addClass('d-none');
11851						$('[data-js="convenience-fee-pix-container"]').addClass('d-none');
11852						$('[data-js="price-in-bottom-cart-pix"]').addClass('d-none');
11853						$('.convenienceFee').removeClass('d-none');
11854						$('[data-js="total-pix-container"]').addClass('d-none');
11855
11856						if (_this4.isSeatReservationPage) {
11857							$('.summary-item').addClass('d-none');
11858							$('[data-js="bottom-resume-cart"]').addClass('d-none');
11859							$('[data-js="price-in-bottom-cart"]').addClass('d-none');
11860						}
11861					} else {
11862						$('[data-js="convenience-fee-pix"]').text(Utils.formatPrice(cart._totalConvenienceFee));
11863						$('[data-price="price-departure-pix"]').removeClass('d-none');
11864						$('[data-price="price-return-pix"]').removeClass('d-none');
11865						$('[data-js="message-card-price"]').removeClass('d-none');
11866						if (_this4.useSummary) {
11867							$('[data-price="price-departure-pix"]').text(Utils.formatPrice(subTotalPixDep));
11868							$('[data-js="discount-pix"]').text(cart._percentagePix);
11869						} else {
11870							var percentagePix = cart._listOffer[0]._percentagePix;
11871							var amountTotal = departureTotalPrice;
11872							var priceDeparturePix = amountTotal - amountTotal * (percentagePix / 100);
11873							$('[data-price="price-departure-pix"]').text(Utils.formatPrice(priceDeparturePix));
11874							$('[data-js="discount-pix"]').text(cart._listOffer[0]._percentagePix);
11875						}
11876						$('[data-js="card-price-dep"]').text(Utils.formatPrice(departureTotalPrice));
11877						$('[data-price="price-departure"]').hide();
11878						$('[data-price="price-return"]').hide();
11879						$('span.pix').removeClass('d-none');
11880						$('[data-js="price-in-bottom-cart"]').addClass('d-none');
11881						$('.tablinks').on('click', function () {
11882							if ($(this).data('js') === 'tab-pix') {
11883								$('[data-js="total-pix-container"]').removeClass('d-none');
11884								$('.price-in-bottom-cart-pix').removeClass('d-none');
11885								$('[data-js="price-in-bottom-cart"]').addClass('d-none');
11886							} else {
11887								$('[data-js="total-pix-container"]').addClass('d-none');
11888								$('.price-in-bottom-cart-pix').addClass('d-none');
11889								$('[data-js="price-in-bottom-cart"]').removeClass('d-none');
11890							}
11891						});
11892
11893						if (_this4.isSeatReservationPage) {
11894							$('.summary-item').addClass('d-none');
11895							$('[data-js="bottom-resume-cart"]').addClass('d-none');
11896							$('[data-js="price-in-bottom-cart"]').addClass('d-none');
11897						}
11898
11899						if (_this4.useSummary) {
11900							_this4.priceCartPix.text(Utils.formatPrice(cart._totalPix));
11901						}
11902					}
11903
11904					$('.cart-passenger-list').removeClass('active');
11905				}
11906
11907				document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(function (el) {
11908					new bootstrap.Tooltip(el);
11909				});
11910
11911				if (el._seatReturn) {
11912					var seatReturn = el._seatReturn;
11913					var seatReturnConnection = el._seatReturnConnection;
11914					var seatReturnConnection2 = el._seatReturnConnection2;
11915					var returnAggregate = el._summaryReturn;
11916					var returnServiceAggregate = cart._summaryReturnService;
11917					var returnSeats = [seatReturn, seatReturnConnection, seatReturnConnection2];
11918
11919					var returnOffer = cartOfferList[1];
11920
11921					var priceRet = getSeatValue(returnAggregate, returnSeats, "_rate", returnOffer, "_rate");
11922
11923					var taxaRet = getSeatValue(returnAggregate, returnSeats, "_toll", returnOffer, "_toll");
11924
11925					var hasReturnTaxa = taxa === 0 ? " d-none" : "";
11926
11927					var convenienceFeeRet = _this4._cartService.cart.totalConvenienceFee;
11928
11929					var totalRetPrice = getSeatValue(returnAggregate, returnSeats, "_price", returnOffer, "_price");
11930
11931					// Trip-level (trecho) pix subtotal comes from the service valueParts; passenger aggregate is the fallback.
11932					subTotalPixRet = _this4.useSummary && returnServiceAggregate && returnServiceAggregate.SubTotalPix != null ? returnServiceAggregate.SubTotalPix : getSeatValue(returnAggregate, returnSeats, "_subTotalPix", returnOffer, "_subTotalPix");
11933
11934					var insuranceReturn = isTravelInsurance ? getInsuranceValue(seatReturn, returnAggregate, returnSeats) : 0;
11935					_this4.txTravelInsuranceReturn = totalInsuranceReturn;
11936
11937					if (el._type === "CHILD") {
11938						totalRetPrice = 0;
11939					}
11940
11941					// Trip-level (trecho) subtotal comes from the service valueParts; front sum is the fallback.
11942					returnTotalPrice = _this4.useSummary && returnServiceAggregate && returnServiceAggregate.SubTotal != null ? returnServiceAggregate.SubTotal : returnTotalPrice + totalRetPrice;
11943
11944					itemReturn = '\n\t\t\t\t\t<li data-serviceId="' + el._seatReturn._service + '-' + el._seatReturn._seatNumber + '">\n\t\t\t\t\t\t<div class="container-cart-passenger">\n\t\t\t\t\t\t\t<span class="name">' + el._name + '</span>\n\t\t\t\t\t\t\t\t<span class="square-seat">\n\t\t\t\t\t\t\t\t\t<p class="icon-seat-number">' + (el._seatReturn._seatNumber ? el._seatReturn._seatNumber : '-') + '</p>\n\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t<span id="collapse-return-' + i + '" class="seat-subtitle btn-collapse" data-bs-collapse="collapse" data-js="collapse-return-' + i + '">' + priceDetailsLabel + '<span class="icon-collapse jca-ico-angle-down" data-js="collapse-return-' + i + '"></span>\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class="container-cart-details collapse-container" data-js="collapse-return-' + i + '">\n\t\t\t\t\t\t\t<div class="container-cart-details-content">\n\t\t\t\t\t\t\t\t<p class="title"><span class="container-cart-details-title">' + tariff + '</span><span class="container-cart-details-result"> R$ ' + Utils.formatPrice(priceRet) + '</span></p>\n\t\t\t\t\t\t\t\t<p class="title ' + hasReturnTaxa + '"><span class="container-cart-details-title">' + tax + '</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(taxaRet) + '</span></p>\n\t\t\t\t\t\t\t\t' + (!cart._listOffer[0]._priceWithDiscountPix || cart._listOffer[0]._priceWithDiscountPix === cart._listOffer[0]._price ? '<p class="title ' + (!_this4.convenienceFee ? 'd-none' : '') + '">\n\t\t\t\t\t\t\t\t\t\t<span class="container-cart-details-title total d-none">\n\t\t\t\t\t\t\t\t\t\t\t' + i18n('convenience_fee') + '\n\t\t\t\t\t\t\t\t\t\t\t<a class="icon jca-ico-info-icon tooltip-btn" href="#">\n\t\t\t\t\t\t\t\t\t\t\t\t<span class="tooltiptext">' + i18n('msg_faq_convenience_fee') + '</span>\n\t\t\t\t\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t\t<span class="container-cart-details-result d-none">\n\t\t\t\t\t\t\t\t\t\t\tR$ ' + Utils.formatPrice(convenienceFeeRet) + '\n\t\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t</p>' : '') + '\n                <p class="title ' + (isTravelInsurance ? '' : 'd-none') + '"><span class="container-cart-details-title">Seguro Viagem</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(insuranceReturn) + '</span></p>\n                <p class="title total"><span class="container-cart-details-title total">SubTotal</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(totalRetPrice) + '</span></p>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class="price-ticket-content d-none">\n\t\t\t\t\t\t\t\t<a href="javascript:void(0)" id="remove-passenger-return-' + i + '" class="icon-close remove-ticket" data-js="remove-passenger" index=' + i + '>Remover item</a>\n\t\t\t\t\t\t\t\t<p><span class="icon">R$</span><span class="total-price">' + Utils.formatPrice(totalRetPrice) + '</span></p>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</li>\n\t\t\t\t';
11945
11946					if (!cart._listOffer[0]._priceWithDiscountPix || cart._listOffer[0]._priceWithDiscountPix === cart._listOffer[0]._price) {
11947						$('[data-price="price-return"]').text(Utils.formatPrice(returnTotalPrice));
11948					} else {
11949						$('[data-js="card-price-ret"]').text(returnTotalPrice);
11950						if (_this4.useSummary) {
11951							$('[data-price="price-return-pix"]').text(Utils.formatPrice(subTotalPixRet));
11952						} else {
11953							var percentagePixRet = cart._listOffer[1] ? cart._listOffer[1]._percentagePix : null;
11954							var amountTotalRet = returnTotalPrice;
11955							var priceDeparturePixRet = amountTotalRet - amountTotalRet * (percentagePixRet / 100);
11956							$('[data-price="price-return-pix"]').text(cart._listOffer[1] ? Utils.formatPrice(priceDeparturePixRet) 
11956: null);
11957						}
11958					}
11959				}
11960				depSection.append(itemDeparture);
11961				retSection.append(itemReturn);
11962			});
11963
11964			if (this.totalOffDiscount) $('.seat-subtitle.btn-collapse').hide();
11965		}
11966	}, {
11967    key: 'initPassengerListRemarkFlow',
11968    value: function initPassengerListRemarkFlow(cartPassList, cartOfferList, depSection, retSection, isTravelInsurance) {
11969      var _this5 = this;
11970
11971      var departureTicket = 0;
11972      var returnTicket = 0;
11973      var itemDeparture = void 0;
11974      var itemReturn = void 0;
11975      var departureBalanceAmountTotal = 0;
11976      var returnBalanceAmountTotal = 0;
11977
11978      //AEM translations
11979      var tariff = $('[data-js="cart-details-text-values"]').attr('data-text-tariff');
11980      var tax = $('[data-js="cart-details-text-values"]').attr('data-text-tax');
11981      var totalLabel = $('[data-js="cart-details-text-values"]').attr('data-text-total');
11982      var priceDetailsLabel = $('[data-js="cart-details-text-values"]').attr('data-text-price-details');
11983      var travelInsuranceLabel = $('[data-js="cart-details-text-values"]').attr('data-text-travel-insurance');
11984
11985      cartPassList.forEach(function (el, i) {
11986        var oldPrice = +el._seatDeparture._actualAmount + +el._seatDepartureConnection._actualAmount + +el._seatDepartureConnection2._actualAmount;
11987        var taxa = +el._seatDeparture._toll + +el._seatDepartureConnection._toll + +el._seatDepartureConnection2._toll + +el._seatDeparture._tax + +el._seatDepartureConnection._tax + +el._seatDepartureConnection2._tax + +el._seatDeparture._boardingFee + +el._seatDepartureConnection._boardingFee + +el._seatDepartureConnection2._boardingFee;
11988
11989        var departureBalanceAmount = +el._seatDeparture._balanceAmount + +el._seatDepartureConnection._balanceAmount;
11990        departureBalanceAmountTotal += departureBalanceAmount;
11991
11992        var hasDepartureRate = +el._seatDeparture._rate == 0 ? ' d-none ' : '';
11993        var hasDepartureTaxa = taxa == 0 ? ' d-none' : '';
11994        var price = +el._seatDeparture._rate + +el._seatDepartureConnection._rate;
11995
11996        var convenienceFee = (el._seatDeparture._seatNumber !== "" ? el._seatDeparture._convenienceFee : 0) + (el._seatDepartureConnection._seatNumber !== "" ? el._seatDepartureConnection._convenienceFee : 0);
11997
11998        var currentTotalTickets = el._seatDeparture._price == 0 ? cartOfferList[0]._price : +el._seatDeparture._price + +el._seatDepartureConnection._price;
11999
12000        var insurance = (isTravelInsurance && +el._seatDeparture._insurance ? +el._seatDeparture._insurance : 0) + (isTravelInsurance && +el._seatDepartureConnection._insurance ? el._seatDepartureConnection._insurance : 0);
12001        currentTotalTickets += insurance;
12002
12003        _this5.txTravelInsurance = insurance;
12004
12005        var departurePenaltyAmountTotal = 0;
12006        var departurePenaltyAmount = +el._seatDeparture._penaltyAmount + +el._seatDepartureConnection._penaltyAmount;
12007        departurePenaltyAmountTotal += departurePenaltyAmount;
12008
12009        if (_this5.convenienceFee) currentTotalTickets += convenienceFee;
12010
12011        if (el._type !== 'CHILD') departureTicket += currentTotalTickets;else currentTotalTickets = 0;
12012
12013        if (el._name) {
12014          itemDeparture = '\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<div class="container-cart-passenger">\n\t\t\t\t\t\t\t<span class="name">' + el._name + '</span>\n\t\t\t\t\t\t\t\t<span class="square-seat">\n\t\t\t\t\t\t\t\t\t<p class="icon-seat-number">' + (el._seatDeparture._seatNumber ? el._seatDeparture._seatNumber : '-') + '</p>\n\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t<span class="seat-subtitle btn-collapse" data-bs-collapse="collapse" id="collapse-' + i + '" data-js="collapse-' + i + '">' + priceDetailsLabel + ' <span class="icon-collapse jca-ico-angle-down" data-js="collapse-' + i + '"></span>\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class="container-cart-details collapse-container" data-js="collapse-' + i + '">\n\t\t\t\t\t\t\t<div class="container-cart-details-content">\n\t\t\t\t\t\t\t\t<p class="title"><span class="container-cart-details-title">Valor da passagem antiga</span><span class="container-cart-details-result"> R$ ' + Utils.formatPrice(oldPrice) + '</span></p>\n\t\t\t\t\t\t\t\t<p class="title ' + hasDepartureRate + '"><span class="container-cart-details-title">' + tariff + '</span><span class="container-cart-details-result"> R$ ' + Utils.formatPrice(price) + '</span></p>\n\t\t\t\t\t\t\t\t<p class="title ' + hasDepartureTaxa + '"><span class="container-cart-details-title">' + tax + '</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(taxa) + '</span></p>\n                <p class="title ' + (isTravelInsurance ? '' : 'd-none') + '"><span class="container-cart-details-title">' + travelInsuranceLabel + '</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(insurance) + '</span></p>\n                <p class="title"><span class="container-cart-details-title total">Valor nova passagem</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(currentTotalTickets) + '</span></p>\n\t\t\t\t\t\t\t\t<p class="title">\n\t\t\t\t\t\t\t\t\t<span class="container-cart-details-title total">\n\t\t\t\t\t\t\t\t\t\t' + i18n('msg_label_penaltyAmount') + '\n\t\t\t\t\t\t\t\t\t\t<a class="icon jca-ico-info-icon tooltip-btn" href="#">\n\t\t\t\t\t\t\t\t\t\t\t<span class="tooltiptext">' + i18n('msg_faq_penaltyAmount') + '</span>\n\t\t\t\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t<span class="container-cart-details-result">R$ ' + Utils.formatPrice(departurePenaltyAmountTotal) + '</span>\n\t\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t\t<p class="title total"><span class="container-cart-details-title">' + (Math.sign(departureBalanceAmount) < 0 ? 'Reembolsado' : 'Diferença a ser paga') + '</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(departureBalanceAmount) + '</span><p>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class="price-ticket-content d-none">\n\t\t\t\t\t\t\t\t<a href="javascript:void(0)" id="remove-passenger-' + i + '" class="icon-close remove-ticket" data-js="remove-passenger" index=' + i + '>Remover item</a>\n\t\t\t\t\t\t\t\t<p><span class="icon">R$</span><span class="total-price">' + Utils.formatPrice(departureBalanceAmount) + '</span></p>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</li>\n\t\t\t\t';
12015
12016          if (_this5.remarkV2) {
12017            $('span.pix').addClass('d-none');
12018            $('p.line-discount-pix').addClass('d-none');
12019            $('[data-js="subtotal-seats-container"]').addClass('d-none');
12020            $('[data-js="convenience-fee-pix-container"]').addClass('d-none');
12021            $('[data-js="price-in-bottom-cart-pix"]').addClass('d-none');
12022          }
12023
12024          $('[data-price="price-departure"]').text(Utils.formatPrice(departureBalanceAmountTotal));
12025          $('.cart-passenger-list').removeClass('active');
12026        }
12027
12028        document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(function (el) {
12029					new bootstrap.Tooltip(el);
12030				});
12031        if (el._seatReturn) {
12032            var hasReturnRate = +el._seatReturn._rate == 0 ? ' d-none ' : '';
12033            var hasReturnTaxa = +el._seatReturn._toll == 0 ? ' d-none' : '';
12034            var priceRet = +el._seatReturn._rate + +el._seatReturnConnection._rate;
12035            var oldPriceReturn = +el._seatReturn._actualAmount + +el._seatReturnConnection._actualAmount;
12036            var taxaRet = +el._seatReturn._toll + +el._seatReturnConnection._toll + +el._seatReturn._tax + +el._seatReturnConnection._tax + +el._seatReturn._boardingFee + +el._seatReturnConnection._boardingFee;
12037
12038            var returnBalanceAmount = +el._seatReturn._balanceAmount + +el._seatReturnConnection._balanceAmount + +el._seatReturnConnection2._balanceAmount;
12039            returnBalanceAmountTotal += returnBalanceAmount;
12040
12041            var convenienceFeeRet = (el._seatReturn._seatNumber !== "" ? el._seatReturn._convenienceFee : 0) + (el._seatReturnConnection._seatNumber !== "" ? el._seatReturnConnection._convenienceFee : 0);
12042
12043            var currentTotalTicketsReturn = +el._seatReturn._price == 0 ? cartOfferList[1] ? cartOfferList[1]._price : 0 : +el._seatReturn._price + +el._seatReturnConnection._price;
12044            var insuranceReturn = (isTravelInsurance && +el._seatReturn._insurance ? +el._seatReturn._insurance : 0) + (isTravelInsurance && +el._seatReturnConnection._insurance ? +el._seatReturnConnection._insurance : 0);
12045            currentTotalTicketsReturn += insuranceReturn;
12046
12047            _this5.txTravelInsuranceReturn = insuranceReturn;
12048
12049            var returnPenaltyAmountTotal = 0;
12050            var returnPenaltyAmount = +el._seatReturn._penaltyAmount + +el._seatReturnConnection._penaltyAmount;
12051            returnPenaltyAmountTotal += returnPenaltyAmount;
12052
12053            if (_this5.convenienceFee) currentTotalTicketsReturn += convenienceFeeRet;
12054
12055            if (el._type !== 'CHILD') returnTicket += currentTotalTicketsReturn;else currentTotalTicketsReturn = 0;
12056
12057            itemReturn = '\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<div class="container-cart-passenger">\n\t\t\t\t\t\t\t<span class="name">' + el._name + '</span>\n\t\t\t\t\t\t\t\t<span class="square-seat">\n\t\t\t\t\t\t\t\t\t<p class="icon-seat-number">' + (el._seatReturn._seatNumber ? el._seatReturn._seatNumber : '-') + '</p>\n\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t<span id="collapse-return-' + i + '" class="seat-subtitle btn-collapse" data-bs-collapse="collapse" data-js="collapse-return-' + i + '">' + priceDetailsLabel + ' <span class="icon-collapse jca-ico-angle-down" data-js="collapse-return-' + i + '"></span>\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<div class="container-cart-details collapse-container" data-js="collapse-return-' + i + '">\n\t\t\t\t\t\t\t<div class="container-cart-details-content">\n\t\t\t\t\t\t\t\t<p class="title"><span class="container-cart-details-title">Valor da passagem antiga</span><span class="container-cart-details-result"> R$ ' + Utils.formatPrice(oldPriceReturn) + '</span></p>\n\t\t\t\t\t\t\t\t<p class="title ' + hasReturnRate + '"><span class="container-cart-details-title">' + tariff + '</span><span class="container-cart-details-result"> R$ ' + Utils.formatPrice(priceRet) + '</span></p>\n\t\t\t\t\t\t\t\t<p class="title ' + hasReturnTaxa + '"><span class="container-cart-details-title">' + tax + '</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(taxaRet) + '</span></p>\n                <p class="title ' + (isTravelInsurance ? '' : 'd-none') + '"><span class="container-cart-details-title">' + travelInsuranceLabel + '</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(insuranceReturn) + '</span></p>\n                <p class="title"><span class="container-cart-details-title">Valor nova passagem</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(currentTotalTicketsReturn) + '</span></p>\n\t\t\t\t\t\t\t\t<p class="title">\n\t\t\t\t\t\t\t\t\t<span class="container-cart-details-title total">\n\t\t\t\t\t\t\t\t\t\t' + i18n('msg_label_penaltyAmount') + '\n\t\t\t\t\t\t\t\t\t\t<a class="icon jca-ico-info-icon tooltip-btn" href="#">\n\t\t\t\t\t\t\t\t\t\t\t<span class="tooltiptext">' + i18n('msg_faq_penaltyAmount') + '</span>\n\t\t\t\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t\t\t<span class="container-cart-details-result">R$ ' + Utils.formatPrice(returnPenaltyAmountTotal) + '</span>\n\t\t\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t\t<p class="title total"><span class="container-cart-details-title">' + (Math.sign(returnBalanceAmount) < 0 ? 'Reembolsado' : 'Diferença a ser paga') + '</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(returnBalanceAmount) + '</span><p>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class="price-ticket-content d-none">\n\t\t\t\t\t\t\t\t<a href="javascript:void(0)" id="remove-passenger-return-' + i + '" class="icon-close remove-ticket" data-js="remove-passenger" index=' + i + '>Remover item</a>\n\t\t\t\t\t\t\t\t<p><span class="icon">R$</span><span class="total-price">' + Utils.formatPrice(currentTotalTicketsReturn) + '</span></p>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</li>\n\t\t\t\t';
12058
12059            $('[data-price="price-return"]').text(Utils.formatPrice(returnBalanceAmountTotal));
12060        }
12061        depSection.append(itemDeparture);
12062        retSection.append(itemReturn);
12063      });
12064    }
12065  }, {
12066    key: 'handleRemovePassenger',
12067    value: function handleRemovePassenger() {
12068      var _this4 = this;
12069
12070      var $closeConf = $('[data-js="close-confirmation"]');
12071      var $cancelOvlay = $('[data-js="cancel-passenger-confirmation-overlay"]');
12072      var $passToRem = $('[data-js="passenger-to-remove"]');
12073      var $submitRem = $('[data-js="btn-submit-remove"]');
12074      var $remOnePass = $('[data-js="remove-passenger"]');
12075      var $confirmText = $('[data-js="confirm-text"]');
12076
12077      $cancelOvlay.children().focusout(function (e) {
12078        var $target = $(e.relatedTarget);
12079        if ($target.length > 0 && $target.closest('[data-js="cancel-passenger-confirmation-overlay"]').length == 0) $closeConf.click();
12080      });
12081
12082      $remOnePass.click(function (e) {
12083        var pIndex = $(e.currentTarget).attr("index");
12084        var cartObject = SessionStorage.get('cart');
12085        var listPassengers = cartObject._listPassengers;
12086        var passenger = listPassengers[pIndex];
12087        var type = passenger._type;
12088        var pName = passenger._name;
12089
12090        if (type === 'ADULT') {
12091          var regQtt = listPassengers.filter(function (p) {
12092            return p._type === 'ADULT';
12093          }).length;
12094          var chdQtt = listPassengers.filter(function (p) {
12095            return p._type === 'CHILD_A';
12096          }).length;
12097          var infQtt = listPassengers.filter(function (p) {
12098            return p._type === 'CHILD';
12099          }).length;
12100
12101          if (regQtt === chdQtt || regQtt === infQtt) {
12102            // This message is edited in AEM Dialog
12103            var aemDialogText = $('[data-aem-js="dialog-value"]').attr("data-aem-dialog-value");
12104
12105            $submitRem.attr('disabled', true);
12106            $confirmText.text(aemDialogText);
12107          }
12108        }
12109
12110        $passToRem.text(pName).data('index', pIndex);
12111        $submitRem.click(function (e) {
12112          e.stopImmediatePropagation(); //unbind click event listener
12113          var currentIndex = parseInt($(e.target).parents().find('[data-js="passenger-to-remove"]').data('index'));
12114          _this4.removePassengerFromCart(currentIndex);
12115        });
12116
12117        _this4.lastClickedButton = $(e.currentTarget);
12118        $cancelOvlay.show();
12119        $closeConf.first().focus();
12120        $closeConf.click(function () {
12121          $cancelOvlay.hide();
12122          _this4.lastClickedButton.focus();
12123          $submitRem.attr('disabled', false);
12124          $confirmText.text('Deseja confirmar?');
12125        });
12126      });
12127    }
12128  }, {
12129    key: 'removePassengerFromCart',
12130    value: function removePassengerFromCart(index) {
12131      var cancelGoing = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
12132
12133      var _this5 = this;
12134
12135      var cancelReturn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
12136      var resolve = arguments[3];
12137
12138      var cartObject = SessionStorage.get('cart');
12139      var cartOfferList = cartObject._listOffer;
12140      var cartPassList = cartObject._listPassengers;
12141      var transactionIdDep = cartPassList[index]._seatDeparture._transactionId;
12142
12143      if (this.hasSelectedSeat(transactionIdDep)) {
12144        try {
12145          Promise.all([this.cancelSeatsForDep(cartOfferList, cartPassList, index, cancelGoing), this.cancelSeatsForRet(cartOfferList, cartPassList, index, cancelReturn)]).then(function () {
12146            LoaderService.hide();
12147            if (cancelGoing && cancelReturn) _this5.saveRemovalOnePassenger(index, cartObject); else resolve();
12148          }).catch(function (err) {
12149            LoaderService.hide();
12150            console.error(err);
12151          });
12152        } catch (err) {
12153          console.error(err);
12154        }
12155      } else {
12156        if (cancelGoing && cancelReturn) this.saveRemovalOnePassenger(index, cartObject); else resolve();
12157      }
12158    }
12159  }, {
12160    key: 'showConfirmationRemoveTrip',
12161    value: function showConfirmationRemoveTrip(removeTrip) {
12162      var overlay = removeTrip.closest('.cart-details-container-bottom-cart').find("[data-js='cancel-way-confirmation-overlay']");
12163      var cartObject = SessionStorage.get('cart');
12164      var listPassengers = cartObject._listPassengers;
12165      var way = removeTrip.parent().parent().find('.label').text().trim();
12166      var index = parseInt(removeTrip.parent().attr('index'));
12167      var company = cartObject._listOffer[index]._company;
12168      var origin = company._origin._label;
12169      var destination = company._destination._label;
12170      var departureDateTime = company._departureDate;
12171      var date = DateFormatter.extractDate(departureDateTime);
12172      var time = DateFormatter.extractHour(departureDateTime);
12173      var ulPassengers = overlay.find("[data-js='passengers-list']");
12174      var fullMessage = origin + " - " + destination + " - " + DateFormatter.reverseDate(date) + " às " + time;
12175
12176      $("[data-js='cancel-way']").text(way);
12177      ulPassengers.empty();
12178
12179      for (var i in listPassengers) {
12180        var passenger = listPassengers[i];
12181        if (passenger.name) {
12182          var li = $("<li></li>");
12183          li.text(passenger.name);
12184          ulPassengers.append(li);
12185        }
12186      }
12187
12188      if (ulPassengers.find("li").length == 0) $("[data-js='cancel-text']").hide(); else $("[data-js='cancel-text']").show();
12189
12190      $("[data-js='cancel-trip-datetime']").text(fullMessage);
12191      overlay.fadeIn();
12192      overlay.find("[data-js='close-confirmation']").first().focus();
12193    }
12194  }, {
12195    key: 'handleRemoveTrip',
12196    value: function handleRemoveTrip() {
12197      var self = this;
12198      var overlay = $("[data-js='cancel-way-confirmation-overlay']");
12199      overlay.find("[data-js='close-confirmation']").click(function (e) {
12200        return overlay.fadeOut();
12201      });
12202      overlay.children().focusout(function (e) {
12203        var $target = $(e.relatedTarget);
12204        if ($target.closest("[data-js='cancel-way-confirmation-overlay']").length == 0) overlay.find("[data-js='close-confirmation']").click();
12205      });
12206      this.removeTrip.click(function (e) {
12207        self.showConfirmationRemoveTrip($(e.currentTarget));
12208        var isDep = $(e.target).closest('[data-js="departure-section"]');
12209        var isRet = $(e.target).closest('[data-js="return-section"]');
12210        overlay.find("[data-js='btn-submit']").click(function (e) {
12211          var cartObject = SessionStorage.get('cart');
12212          var cartPassList = cartObject._listPassengers;
12213          if (isDep.length > 0) {
12214            self.removeDepFromStorage(cartPassList);
12215            self.sendRemoveFromCartAnalytics(cartObject._listOffer[0]);
12216          } else if (isRet.length > 0) {
12217            self.removeRetFromStorage(cartPassList);
12218            self.sendRemoveFromCartAnalytics(cartObject._listOffer[1]);
12219          }
12220        });
12221      });
12222    }
12223  }, {
12224    key: 'sendRemoveFromCartAnalytics',
12225    value: function sendRemoveFromCartAnalytics(offer) {
12226      dataLayer.push({ ecommerce: null });
12227      dataLayer.push({
12228        event: "remove_from_cart",
12229        ecommerce: {
12230          items: [{
12231            item_id: offer._service,
12232            price: offer._price,
12233            item_brand: offer._company._companyName,
12234            item_category: offer._company._origin._label,
12235            item_category2: offer._company._destination._label,
12236            item_category3: offer._company._departureDate,
12237            item_category4: offer._company._arrivingDate,
12238            item_variant: offer._classtype._className,
12239            quantity: parseInt($('[data-js="passenger-current-value"]').text())
12240          }]
12241        }
12242      });
12243    }
12244  }, {
12245    key: 'removeDepFromStorage',
12246    value: function removeDepFromStorage(cartPassList) {
12247      var _this6 = this;
12248
12249      if (!cartPassList) return;
12250
12251      var requests = cartPassList.reduce(function (promiseChain, el, idx) {
12252        return promiseChain.then(function () {
12253          return new Promise(function (resolve) {
12254            _this6.removePassengerFromCart(idx, true, false, resolve);
12255          });
12256        });
12257      }, Promise.resolve());
12258
12259      requests.then(function () {
12260        _this6.saveRemovalTrip(0);
12261      });
12262    }
12263  }, {
12264    key: 'removeRetFromStorage',
12265    value: function removeRetFromStorage(cartPassList) {
12266      var _this7 = this;
12267
12268      if (!cartPassList) return;
12269
12270      var requests = cartPassList.reduce(function (promiseChain, el, idx) {
12271        return promiseChain.then(function () {
12272          return new Promise(function (resolve) {
12273            _this7.removePassengerFromCart(idx, false, true, resolve);
12274          });
12275        });
12276      }, Promise.resolve());
12277
12278      requests.then(function () {
12279        _this7.saveRemovalTrip(1);
12280      });
12281    }
12282  }, {
12283    key: 'saveRemovalTrip',
12284    value: function saveRemovalTrip(tripIndex) {
12285      var cart = SessionStorage.get('cart');
12286      var formData = SessionStorage.get('formData');
12287
12288      formData.departureOnly = true;
12289
12290      cart._departureOnly = true;
12291      cart._listOffer.splice(tripIndex, 1);
12292
12293      if (tripIndex == 0) {
12294        cart._listPassengers.forEach(function (el) {
12295          el._seatDeparture = el._seatReturn;
12296          el._seatDepartureConnection = el._seatReturnConnection;
12297          el._seatReturn = new Seat();
12298          el._seatReturnConnection = new Seat();
12299        });
12300        formData.depart = formData.return;
12301      }
12302      if (tripIndex == 1) {
12303        cart._listPassengers.forEach(function (el) {
12304          el._seatReturn = new Seat();
12305          el._seatReturnConnection = new Seat();
12306        });
12307      }
12308
12309      SessionStorage.set('formData', formData);
12310      SessionStorage.set('cart', cart);
12311
12312      if (cart._listOffer.length == 0) {
12313        SessionStorage.remove('cart');
12314        $(location).attr('href', $('#homePagePath').val());
12315      } else {
12316        setTimeout(function () {
12317          if (!this.hashSelected) $(location).attr('href', $(location).attr('href') + '#cart');
12318
12319          location.reload(false);
12320        }, 300)
12321      }
12322    }
12323  }, {
12324    key: 'saveRemovalOnePassenger',
12325    value: function saveRemovalOnePassenger(index, cartObject) {
12326      var cartPassList = cartObject._listPassengers;
12327      if (cartPassList.length == 1) {
12328        SessionStorage.remove('cart');
12329        $(location).attr('href', $('#homePagePath').val());
12330      } else {
12331        cartObject._listPassengers.splice(index, 1);
12332        SessionStorage.set('cart', cartObject);
12333        setTimeout(function () {
12334          if (!this.hashSelected) $(location).attr('href', $(location).attr('href') + '#cart');
12335
12336          location.reload(false);
12337        }, 300)
12338
12339      }
12340    }
12341  }, {
12342    key: 'cancelSeatsForDep',
12343    value: function cancelSeatsForDep(cartOfferList, cartPassList, pIndex, cancelGoing) {
12344        var _this10 = this;
12345
12346        var tripDataDep = cartOfferList[0];
12347        var seatDataDep = cartPassList[pIndex]._seatDeparture;
12348        var seatDataDepConn = cartPassList[pIndex]._seatDepartureC
12348onnection._transactionId ? cartPassList[pIndex]._seatDepartureConnection : null;
12349        var seatDataDepConn2 = cartPassList[pIndex]._seatDepartureConnection2._transactionId ? cartPassList[pIndex]._seatDepartureConnection2 : null;
12350
12351        if (!cancelGoing) return;
12352
12353        LoaderService.show();
12354        return this.cancelSeatDep(tripDataDep, seatDataDep).then(function () {
12355            if (seatDataDepConn) return _this10.cancelSeatDepConn(tripDataDep, seatDataDepConn);
12356            if (seatDataDepConn2) return _this10.cancelSeatDepConn(tripDataDep, seatDataDepConn2);
12357        }).catch(function (err) {
12358            LoaderService.hide();
12359            console.error(err);
12360        });
12361    }
12362  }, {
12363    key: 'cancelSeatsForRet',
12364    value: function cancelSeatsForRet(cartOfferList, cartPassList, pIndex, cancelReturn) {
12365        var _this11 = this;
12366
12367        var tripDataRet = cartOfferList[1];
12368        var seatDataRet = cartPassList[pIndex]._seatReturn._transactionId ? cartPassList[pIndex]._seatReturn : null;
12369        var seatDataRetConn = cartPassList[pIndex]._seatReturnConnection._transactionId ? cartPassList[pIndex]._seatReturn : null;
12370        var seatDataRetConn2 = cartPassList[pIndex]._seatReturnConnection2._transactionId ? cartPassList[pIndex]._seatReturn2 : null;
12371
12372        if (!tripDataRet || !cancelReturn || !seatDataRet) return;
12373
12374        LoaderService.show();
12375        return this.cancelSeatRet(tripDataRet, seatDataRet).then(function () {
12376            if (seatDataRetConn) return _this11.cancelSeatRetConn(tripDataRet, seatDataRetConn);
12377            if (seatDataRetConn2) return _this11.cancelSeatRetConn(tripDataRet, seatDataRetConn2);
12378        }).catch(function (err) {
12379            LoaderService.hide();
12380            console.error(err);
12381        });
12382    }
12383  }, {
12384    key: 'cancelSeatDep',
12385    value: function cancelSeatDep(tripDataDep, seatDataDep) {
12386        var headers = {
12387            'Authorization': '' + SessionStorage.get('jca_token'),
12388            'sessionseatlock': SessionStorage.get('sessionseatlock'),
12389            'version': 2
12390        };
12391
12392        var body = {
12393            SeatModel: {
12394                token: tripDataDep._token,
12395                child: false,
12396                going: true,
12397                category: 1,
12398                seat: seatDataDep._seatNumber
12399            },
12400            LockSeat: false,
12401            SalePlatform: this.saleplatform ? this.saleplatform : "SITES-UTP"
12402        };
12403
12404        return HttpService.post('lockSeat', body, headers);
12405    }
12406  }, {
12407    key: 'cancelSeatDepConn',
12408    value: function cancelSeatDepConn(tripDataDep, seatDataDepConn) {
12409        var headers = {
12410            'Authorization': '' + SessionStorage.get('jca_token'),
12411            'sessionseatlock': SessionStorage.get('sessionseatlock'),
12412            'version': 2
12413        };
12414
12415        var body = {
12416            SeatModel: {
12417                token: seatDataDepConn._token,
12418                child: false,
12419                going: true,
12420                category: 1,
12421                seat: seatDataDepConn._seatNumber
12422            },
12423            LockSeat: false,
12424            SalePlatform: this.saleplatform ? this.saleplatform : "SITES-UTP"
12425        };
12426
12427        return HttpService.post('lockSeat', body, headers);
12428    }
12429  }, {
12430    key: 'cancelSeatRet',
12431    value: function cancelSeatRet(tripDataRet, seatDataRet) {
12432        var headers = {
12433            'Authorization': '' + SessionStorage.get('jca_token'),
12434            'sessionseatlock': SessionStorage.get('sessionseatlock'),
12435            'version': 2
12436        };
12437
12438        var body = {
12439            SeatModel: {
12440                token: tripDataRet._token,
12441                child: false,
12442                going: false,
12443                category: 1,
12444                seat: seatDataRet._seatNumber
12445            },
12446            LockSeat: false,
12447            SalePlatform: this.saleplatform ? this.saleplatform : "SITES-UTP"
12448        };
12449
12450        return HttpService.post('lockSeat', body, headers);
12451    }
12452  }, {
12453    key: 'cancelSeatRetConn',
12454    value: function cancelSeatRetConn(tripDataRet, seatDataRetConn) {
12455        var headers = {
12456            'Authorization': '' + SessionStorage.get('jca_token'),
12457            'sessionseatlock': SessionStorage.get('sessionseatlock'),
12458            'version': 2
12459        };
12460
12461        var body = {
12462            SeatModel: {
12463                token: seatDataRetConn._token,
12464                child: false,
12465                going: false,
12466                category: 1,
12467                seat: seatDataRetConn._seatNumber
12468            },
12469            LockSeat: false,
12470            SalePlatform: this.saleplatform ? this.saleplatform : "SITES-UTP"
12471        };
12472
12473        return HttpService.post('lockSeat', body, headers);
12474    }
12475  }, {
12476    key: 'hasSelectedSeat',
12477    value: function hasSelectedSeat(transactionIdDep) {
12478      return transactionIdDep && transactionIdDep != '';
12479    }
12480  }, {
12481    key: 'initDepartureTripDetails',
12482    value: function initDepartureTripDetails(formData) {
12483      var origin = formData.depart.origin.label;
12484      var destination = formData.depart.destination.label;
12485      var departureOffer = this.cartService.cart.listOffer[0];
12486
12487      this.tripDetailsDeparture = new TripDetails(this.departureSection, 'departure');
12488      this.tripDetailsDeparture.origin = origin;
12489      this.tripDetailsDeparture.destination = destination;
12490      this.tripDetailsDeparture.offer = departureOffer;
12491      this.tripDetailsDeparture.init();
12492      this.tripDetailsDeparture.initData();
12493    }
12494  }, {
12495    key: 'initReturnTripDetails',
12496    value: function initReturnTripDetails(formData) {
12497      var origin = formData.return.origin.label;
12498      var destination = formData.return.destination.label;
12499      var returnOffer = this._cartService.cart.listOffer[1];
12500
12501      this.tripDetailsReturn = new TripDetails(this.returnSection, 'return');
12502      this.tripDetailsReturn.origin = origin;
12503      this.tripDetailsReturn.destination = destination;
12504      this.tripDetailsReturn.offer = returnOffer;
12505      this.tripDetailsReturn.init();
12506      this.tripDetailsReturn.initData();
12507    }
12508  }, {
12509    key: 'initSections',
12510    value: function initSections(formData) {
12511      this.initDepartureTripDetails(formData);
12512      if (this.cartService.cart.listOffer[1]) this.initReturnTripDetails(formData); else this.returnSection.hide();
12513    }
12514  }, {
12515    key: 'initLabelShowComponent',
12516    value: function initLabelShowComponent() {
12517      var _this10 = this;
12518
12519      this.component.unbind('click');
12520      this.buttonClose.unbind('click');
12521      // this.showResumeBottomCardText.text(i18n('show_resume'));
12522      this.component.click(function () {
12523        return _this10.initPassengerList(SessionStorage.get('cart'));
12524      });
12525      this.component.click({
12526        'cartDetailsPage': this.cartDetailsPage,
12527        'innerContainer': this.innerContainer,
12528        'showDetailsPage': this.showDetailsPage,
12529        'hideDetailsPage': this.hideDetailsPage
12530      }, this.handlerCartComponentClick);
12531
12532      this.buttonClose.click({
12533        'cartDetailsPage': this.cartDetailsPage,
12534        'innerContainer': this.innerContainer
12535      }, this.hideDetailsPage);
12536    }
12537  }, {
12538    key: 'initOriginDestinationComponents',
12539    value: function initOriginDestinationComponents(formData) {
12540      var origin = formData.depart.origin.label;
12541      var destination = formData.depart.destination.label;
12542      if (this.summaryOrigin.find('.cmp-text').length > 0) {
12543        this.summaryOrigin.find('.cmp-text').text(Utils.capitalize(origin));
12544      } else {
12545        this.summaryOrigin.text(Utils.capitalize(origin));
12546      }
12547
12548      if (this.summaryDestination.find('.cmp-text').length > 0) {
12549        this.summaryDestination.find('.cmp-text').text(Utils.capitalize(destination));
12550      } else {
12551        this.summaryDestination.text(Utils.capitalize(destination));
12552      }
12553    }
12554  }, {
12555    key: 'initSummaryComponents',
12556    value: function initSummaryComponents() {
12557      var amountPassengers = this.cartService.cart.totalPassengers;
12558      this.amountPassengersLabel.text(amountPassengers);
12559    }
12560  }, {
12561    key: 'hideDetailsPage',
12562    value: function hideDetailsPage(e) {
12563      e.preventDefault();
12564      var cartDetailsPage = e.data.cartDetailsPage;
12565      var innerContainer = e.data.innerContainer;
12566      var body = $('body');
12567
12568      if (innerContainer.hasClass('hide-label')) {
12569        body.css('position', 'relative');
12570        body.css('width', '');
12571        cartDetailsPage.removeClass('show');
12572        innerContainer.removeClass('hide-label');
12573      }
12574    }
12575  }, {
12576    key: 'showDetailsPage',
12577    value: function showDetailsPage(e) {
12578      if (e.originalEvent instanceof Event) e.preventDefault();
12579
12580      var cartDetailsPage = e.data.cartDetailsPage;
12581      var innerContainer = e.data.innerContainer;
12582      var body = $('body');
12583      var width = $(window).width();
12584      body.css('position', 'fixed');
12585      body.css('width', width);
12586      cartDetailsPage.addClass('show');
12587      innerContainer.addClass('hide-label');
12588    }
12589  }, {
12590    key: 'showPriceDetailsAction',
12591    value: function showPriceDetailsAction(e) {
12592      e.preventDefault();
12593      var showPriceBody = $(e.currentTarget);
12594      var summaryDetails = $('.summary-details');
12595      var label = showPriceBody.find('[data-js="show-details-price-label"]');
12596      var arrow = showPriceBody.find('.arrow');
12597      if (summaryDetails.is(":visible")) {
12598        label.text('Exibir detalhes da compra');
12599        arrow.removeClass("jca-ico-angle-top");
12600        arrow.addClass("jca-ico-angle-down");
12601        summaryDetails.slideUp("fast");
12602      } else {
12603        label.text('Ocultar detalhes da compra');
12604        arrow.removeClass("jca-ico-angle-down");
12605        arrow.addClass("jca-ico-angle-top");
12606        summaryDetails.slideDown("fast");
12607      }
12608    }
12609  }, {
12610    key: 'showCart',
12611    value: function showCart() {
12612      this.component.show();
12613    }
12614  }, {
12615    key: 'hideCart',
12616    value: function hideCart() {
12617      this.component.hide();
12618    }
12619  }, {
12620    key: 'hideServiceFeeValues',
12621    value: function hideServiceFeeValues() {
12622      var hideValues = this.hideValues == 'true' ? true : false;
12623      if (!hideValues) return;
12624
12625      var path = ($('#jca-identifier-page').val() == 'jca-register-passengers-page' || $('#jca-identifier-page').val() == 'jca-seat-reservation-page') ? true : false;
12626
12627      if (path == true) {
12628        $('.summary-item').hide();
12629        $('.sumary-description').hide();
12630        $('[data-js="trip-details-show-passenger"]').hide();
12631      } else {
12632        $('.summary-item').show();
12633        $('.sumary-description').show();
12634        $('[trip-details-show-passenger]').show();
12635      }
12636    }
12637  }, {
12638    key: 'updateCartView',
12639    value: function updateCartView(totalValueWithCoupon) {
12640      var total = 0;
12641      var balance = this._cartService.balanceTotal;
12642      var discountDataStorage = SessionStorage.get('discountData');
12643      this.remarkV2 = SessionStorage.get('repricingv2');
12644      var data = this.appliedCoupon == true && discountDataStorage ? discountDataStorage.result.seats.transactions[0] : null;
12645      var cart = SessionStorage.get('cart');
12646      if (this.priceCartLock != 0) {
12647        if ($('[data-js="insurance-check"]').is(':checked') && $('[data-js="discount-code"]').val() != '') {
12648          total = this.priceCartLock;
12649        } else if ($('[data-js="discount-code"]').val() != undefined && $('[data-js="discount-code"]').val() != '') {
12650          total = this.priceCartLock;
12651        }
12652      } else {
12653        total = this.convenienceFee ? this._cartService.getTotal(this.convenienceFee) : this._cartService.total;
12654      }
12655      if (totalValueWithCoupon) {
12656        total = totalValueWithCoupon;
12657      }
12658
12659      var totalConvenienceFeePrice = 0;
12660      if (this.appliedCoupon == true && discountDataStorage && discountDataStorage.result && discountDataStorage.result.seats && discountDataStorage.result.seats.transactions) {
12661        discountDataStorage.result.seats.transactions.forEach(function (transaction) {
12662          if (transaction.seatResponse && transaction.seatResponse.service && transaction.seatResponse.service.convenienceFee) {
12663            totalConvenienceFeePrice += transaction.seatResponse.service.convenienceFee;
12664          }
12665        });
12666      }
12667
12668      var percentagePix = cart._listOffer[0]._percentagePix;
12669      var priceDeparturePix = total - total * (percentagePix / 100);
12670      var totalPix = total;
12671      var priceDeparturePixCoupon = totalPix - totalPix * (percentagePix / 100);
12672      if (this.priceCartLock != 0) {
12673        this.priceCart.text(Utils.formatPrice(this.remarkV2 || this.totalOffDiscount ? balance : total));
12674        this.priceCartPix.text(Utils.formatPrice(priceDeparturePixCoupon));
12675        $('[data-js="convenience-fee-pix"]').text(Utils.formatPrice(totalConvenienceFeePrice));
12676      } else {
12677        this.priceCart.text(Utils.formatPrice(this.remarkV2 || this.totalOffDiscount ? balance : total));
12678        this.priceCartPix.text(Utils.formatPrice(priceDeparturePix));
12679      }
12680      this.subtotalSeats.text(Utils.formatPrice(this._cartService.total));
12681      this.hideServiceFeeValues();
12682      this.totalconvenienceFee.text(Utils.formatPrice(this.appliedCoupon == false ? this._cartService.totalConvenienceFee : totalConvenienceFeePrice));
12683      $('[data-js="convenience-fee-pix"]').text(Utils.formatPrice(this.appliedCoupon == false ? this._cartService.totalConvenienceFee : totalConvenienceFeePrice));
12684      this.handleConvenienceFee(this._cartService.totalConvenienceFee);
12685      this.totalPriceBottomCart.text("R$ " + Utils.formatPrice(this.remarkV2 || this.totalOffDiscount ? balance : total));
12686      this.pricePixInBottomCart.text('R$ ' + Utils.formatPrice(priceDeparturePix));
12687      this.quantityOffer.text(this._cartService.amountOffers);
12688      this.quantityOffer.show();
12689      $('.cart-icon').addClass('show');
12690      $('[data-js="header-search-button"]').hide();
12691      var cartObject = this._cartService.cart;
12692      this.initPassengerDivision(cartObject);
12693      this.formatSummaryDecimals();
12694      this._cartService.updateStorage();
12695    }
12696  }, {
12697    key: 'formatSummaryDecimals',
12698    value: function formatSummaryDecimals() {
12699      var sels = '[data-js="subtotal-seats"], [data-js="convenience-fee-pix"], [data-js="price-discount"], [data-js="price-cart"], [data-js="price-cart-pix"], [data-js="total-convenience-fee"]';
12700      $('.summary-item').find(sels).each(function () {
12701          var raw = $(this).text().replace(/\s/g, '');
12702          var m = raw.match(/^([\d.]+),(\d{2})$/);
12703          if (m) $(this).html(m[1] + '<span class="cart-price-dec">,' + m[2] + '</span>');
12704      });
12705    }
12706  }, {
12707    key: 'handlerCartComponentClick',
12708    value: function handlerCartComponentClick(e) {
12709      var cartDetailsPage = e.data.cartDetailsPage;
12710      if (cartDetailsPage.hasClass('show')) {
12711        e.data.hideDetailsPage(e);
12712      } else {
12713        e.data.showDetailsPage(e);
12714      }
12715    }
12716    }, {
12717        key: 'submitDiscount',
12718        value: function submitDiscount() {
12719            var _this13 = this;
12720
12721            this.btnApplyDiscount.click(function () {
12722
12723                var headers = { 'Authorization': '' + SessionStorage.get('jca_token') };
12724                var body = { "name": _this13.discount.val(), "salePlatform": "SITES-UTP" };
12725
12726                LoaderService.show();
12727                HttpService.post('voucherDiscount', body, headers).then(function (data) {
12728                    LoaderService.hide();
12729
12730                    if (data.success === false && data.errors && data.errors.length) {
12731                        OverlayService.show();
12732                        AlertConfirmation.show(data.errors[0].error, data.errors[0].errorCode, null);
12733                        $('[data-js="discount-code"]').parent().addClass('invalid').removeClass('valid');
12734                        $('[data-js="discount-msg-error"]').text(i18n('discount_error'));
12735                        return;
12736                    }
12737
12738                    $('[data-js="discount-code"]').parent().removeClass('invalid').addClass('valid');
12739                    $('[data-js="discount-code"]').attr('disabled', true);
12740                    $('[data-js="discount-msg-error"]').removeClass('active');
12741                    var payment = PaymentController.getInstance();
12742                    _this13.appliedCoupon = true;
12743                    _this13.btnApplyDiscount.addClass('valid').attr('disabled', true);
12744                    SessionStorage.set('discountData', data);
12745                    // SessionStorage.set('voucher-test', $('[data-js="discount-code"]').val()) // apenas para teste desconto pagamento whatsapp, ignorar na integração
12746                    payment.voucher = data.result.token.name;
12747                    if (payment.useSummary) {
12748                        // When the summary is active, the values (including the coupon discount)
12749                        // come from the saleSummary endpoint; the front end does not recalculate the discount.
12750                        payment.getUpdatedPriceSummary().then(function () {
12751                            if (!payment.useSummary) {
12752                                payment.renderInstallments(data);
12753                                _this13.applyDiscount(data);
12754                                SessionStorage.set('discountData', data);
12755                                return;
12756                            }
12757                            payment.loadInstallments();
12758                            if (payment.loadInstallmentsAPI) {
12759                                payment.setInstallmentsWithInterest();
12760                                $('.interest-amount').remove();
12761                                _this13.applyDiscount(data);
12762                                SessionStorage.set('discountData', data);
12763                            }
12764                        });
12765                    } else {
12766                        payment.renderInstallments(data);
12767                        _this13.applyDiscount(data);
12768                        payment.getUpdatedPriceSummary().catch(function () {
12769                            payment.renderInstallments(data);
12770                            _this13.applyDiscount(data);
12771                            SessionStorage.set('discountData', data);
12772                        });
12773                    }
12774
12775                    if ($('[data-js="tab-livelo"]').hasClass('active')) payment.getLiveloPointsWithDiscount();
12776                }).catch(function (err) {
12777                    LoaderService.hide();
12778                    var errData = err && err.responseJSON ? err.responseJSON : err;
12779                    var errorMsg = i18n('discount_error');
12780                    var errorCode = null;
12781                    try {
12782                        if (errData && errData.errors && errData.errors.length && errData.errors[0].error && errData.errors[0].errorCode) {
12783                            errorMsg = errData.errors[0].error;
12784                            errorCode = errData.errors[0].errorCode;
12785                        }
12786                    } catch (e) {}
12787                    OverlayService.show();
12788                    AlertConfirmation.show(errorMsg, errorCode, null);
12789                    $('[data-js="discount-code"]').parent().addClass('invalid').removeClass('valid');
12790                    $('[data-js="discount-msg-error"]').addClass('active').text(i18
12790n('discount_error'));
12791                });
12792            });
12793        }
12794	}, {
12795		key: 'updateCartBySummary',
12796		value: function updateCartBySummary(summaryObject) {
12797			var cartObject = this.cartService != undefined && this.cartService._cart != undefined ? this.cartService._cart : summaryObject;
12798			this.useSummary = true;
12799
12800			// Turns a { valueParts: [{ code, value }] } object into a { code: value } map.
12801			var extractParts = function extractParts(source) {
12802				return (source.valueParts || []).reduce(function (acc, part) {
12803					acc[part.code] = part.value;
12804					return acc;
12805				}, {});
12806			};
12807
12808			// Copies the summary price parts into a cart seat.
12809			var applyPartsToSeat = function applyPartsToSeat(seat, parts) {
12810				seat._price = parts.SubTotal;
12811				seat._rate = parts.Tariff;
12812				seat._toll = parts.Tax;
12813				seat._insurance = parts.Insurance;
12814				seat._insuranceW2i = parts.Insurance;
12815				seat._seatSaleLockValueCalculate = parts.SeatSaleLockValueCalculate;
12816				seat._comission = parts.CommissionFee;
12817				seat._subTotalPix = parts.SubTotalPix;
12818			};
12819
12820			// Index every selected cart seat by "serviceId-seatNumber" for quick lookup.
12821			var cartSeatRefs = [];
12822            if(cartObject.listPassengers != undefined) {
12823                cartObject.listPassengers.forEach(function (passenger) {
12824                    var addSeatRef = function addSeatRef(seat, direction) {
12825                        if (seat && seat._service && seat._seatNumber) {
12826                            cartSeatRefs.push({ key: seat._service + '-' + seat._seatNumber, seat: seat, passenger: passenger, direction: direction });
12827                        };
12828                    };
12829                    addSeatRef(passenger._seatDeparture, 'departure');
12830                    addSeatRef(passenger._seatDepartureConnection, 'departure');
12831                    addSeatRef(passenger._seatDepartureConnection2, 'departure');
12832                    addSeatRef(passenger._seatReturn, 'return');
12833                    addSeatRef(passenger._seatReturnConnection, 'return');
12834                    addSeatRef(passenger._seatReturnConnection2, 'return');
12835                });
12836                
12837            }
12838
12839			var findCartSeatRef = function findCartSeatRef(serviceId, seatNumber) {
12840				return cartSeatRefs.find(function (ref) {
12841					return ref.key === serviceId + '-' + seatNumber;
12842				});
12843			};
12844
12845			// New payload groups seats under passengers with a per-passenger aggregate;
12846			// legacy keeps seats flat under the service (no aggregate).
12847			(summaryObject.services || []).forEach(function (service) {
12848				var summaryPassengers = Array.isArray(service.passengers) ? service.passengers : [{ seats: service.seats || [], valueParts: null }];
12849
12850				summaryPassengers.forEach(function (summaryPassenger) {
12851					var matchedRef = null;
12852
12853					(summaryPassenger.seats || []).forEach(function (seat) {
12854						var serviceId = seat.serviceId != null ? seat.serviceId : service.serviceId;
12855						var cartSeatRef = findCartSeatRef(serviceId, seat.seat);
12856						if (cartSeatRef) {
12857							applyPartsToSeat(cartSeatRef.seat, extractParts(seat));
12858							matchedRef = cartSeatRef;
12859						}
12860					});
12861
12862					// Store the per-passenger per-direction aggregate so the render reads
12863					// ready totals instead of summing seat + connections on the front.
12864					if (matchedRef && summaryPassenger.valueParts) {
12865						var aggregate = extractParts(summaryPassenger);
12866						if (matchedRef.direction === 'departure') {
12867							matchedRef.passenger._summaryDeparture = aggregate;
12868							// Also store the passenger insurance on the main seat, which survives storage.
12869							if (matchedRef.passenger._seatDeparture) matchedRef.passenger._seatDeparture._summaryPassengerInsurance = aggregate.Insurance;
12870						} else {
12871							matchedRef.passenger._summaryReturn = aggregate;
12872							if (matchedRef.passenger._seatReturn) matchedRef.passenger._seatReturn._summaryPassengerInsurance = aggregate.Insurance;
12873						}
12874					}
12875				});
12876
12877				// Service-level valueParts hold the whole leg (trecho) subtotal.
12878				if (service.valueParts && typeof service.going === 'boolean') {
12879					var serviceAggregate = extractParts(service);
12880					if (service.going) cartObject._summaryDepartureService = serviceAggregate;else cartObject._summaryReturnService = serviceAggregate;
12881				}
12882			});
12883
12884			// Cart-level totals from the summary root.
12885			var totals = extractParts(summaryObject);
12886            if(cartObject._insurance != undefined) {
12887                cartObject._insurance.price = totals.Insurance;
12888			    cartObject._subTotal = totals.TotalPix < totals.Total ? totals.TotalPix : totals.SubTotal;
12889			    cartObject._totalPix = totals.TotalPix;
12890			    cartObject._percentagePix = totals.PercentagePix;
12891
12892			    if (typeof totals.Total === 'number') {
12893				  this.priceCart.text(Utils.formatPrice(totals.Total));
12894				  this.totalPriceBottomCart.text("R$ " + Utils.formatPrice(totals.Total));
12895			    }
12896			    if (typeof totals.TotalPix === 'number') {
12897                  this.priceCartPix.text(Utils.formatPrice(totals.TotalPix))
12898				  this.pricePixInBottomCart.text("R$ " + Utils.formatPrice(totals.TotalPix));
12899			    }
12900
12901			    this.cartService.updateStorageByObject(cartObject);
12902			    this.initPassengerList(cartObject, cartObject._insurance && cartObject._insurance.hired);
12903            }    
12904			
12905		}
12906	}, {
12907    key: 'handleMessageError',
12908    value: function handleMessageError(err) {
12909      var isArr = Array.isArray(err.responseJSON);
12910      var messageError = '';
12911
12912      if (isArr) {
12913        var arrMessage = err.responseJSON;
12914
12915        for (var i = 0; i < arrMessage.length; i++) {
12916          messageError += '<p>' + arrMessage[i] + '\n' + '</p>';
12917        }
12918        $('.card-payment-discount .tips > p.warning').css('display', 'block');
12919        $('.form-discount .input-wrapper .tips.active').css('text-alignt', 'left');
12920      } else {
12921        messageError = err.responseJSON.result ? err.responseJSON.result : i18n('discount_error');
12922      }
12923
12924      return messageError;
12925    }
12926  }, {
12927    key: 'applyDiscount',
12928    value: function applyDiscount(data) {
12929      var listTransactions = data.result.seats.transactions;
12930      var listPassenger = this._cartService.cart._listPassengers;
12931      var listOffer = this._cartService.cart._listOffer;
12932      var qtdPassengersDiscount = this.checkPassengersDiscount(listTransactions);
12933      var qtdRoutesDiscount = this.checkDiscountedRoutes(listTransactions, listOffer);
12934
12935      this.calculateDiscount(data, listTransactions);
12936      this.updatePassengerDiscount(listOffer, listPassenger, listTransactions);
12937      this.msgDiscountApply(qtdPassengersDiscount, listPassenger.length, qtdRoutesDiscount);
12938    }
12939  }, {
12940    key: 'calculateDiscount',
12941    value: function calculateDiscount(data, listTransactions) {
12942      var _this14 = this;
12943
12944      var pricetotalDiscount = 0;
12945      var pricetotalWithDiscount = 0;
12946      var priceTotalConvenienceFee = 0;
12947
12948      for(var i in listTransactions) {
12949        if(listTransactions[i].voucherValue || listTransactions[i].voucherValue == null) {
12950          if(listTransactions[i].voucherValue != undefined) {
12951            pricetotalDiscount += Math.round((listTransactions[i].voucherValue + 0.00001) * 100) / 100;
12952            pricetotalWithDiscount += Math.round((listTransactions[i].seatResponse.service.priceWithDiscount + 0.00001) * 100) / 100;
12953          }
12954          priceTotalConvenienceFee += Math.round((listTransactions[i].seatResponse.service.convenienceFee + 0.00001) * 100) / 100;
12955        }
12956      }
12957
12958      var txPriceTotalConvenienceFee = this._cartService._cart._totalConvenienceFee - priceTotalConvenienceFee;
12959      var cart = SessionStorage.get('cart');
12960      var total = Math.round((this._cartService.total + this._cartService._cart._totalConvenienceFee - pricetotalDiscount - txPriceTotalConvenienceFee + 0.00001) * 100) / 100;
12961      this.priceCart.text(Utils.formatPrice(total));
12962      var percentagePix = cart._listOffer[0]._percentagePix;
12963      var priceDeparturePix = total - total * (percentagePix / 100);
12964      this.priceCartPix.text(Utils.formatPrice(priceDeparturePix));
12965      $('[data-js="convenience-fee-pix"]').text(Utils.formatPrice(priceTotalConvenienceFee));
12966      this.totalconvenienceFee.text(Utils.formatPrice(priceTotalConvenienceFee));
12967      this.pricePixInBottomCart.text('R$ ' + Utils.formatPrice(priceDeparturePix));
12968      this.priceCartLock = total;
12969      this.totalPriceBottomCart.text("R$ " + Utils.formatPrice(total));
12970      this.pricetotalDiscount.text(Utils.formatPrice(pricetotalDiscount));
12971      this.txPriceTotalConvenienceFee = priceTotalConvenienceFee;
12972      var allTicketsFree = this.checkTicketsFree(listTransactions);
12973      var insurance = this._cartService.cart._insurance;
12974
12975      if (allTicketsFree && !(insurance && insurance.hired)) {
12976        this.totalOffDiscount = true;
12977        this.isDiscount.hide();
12978        $('[data-js="message-coupon100"]').removeClass('d-none');
12979        $('[data-js="insurance-container"]').addClass('d-none');
12980        $('[data-js="msgiro-mob"]').addClass('d-none');
12981        $('.form-container').hide();
12982        $('.payment-selector').hide();
12983        $('.payment-selector__header').hide();
12984        $('.payment-selector__grid').hide();
12985        $('.pix-content-container').parent().hide();
12986        $('[data-js="recurring-content"]').hide();
12987        $('.custom-control-label').addClass('mt-4');
12988        $('.with-resume-bottom-cart').hide();
12989        $('.seat-subtitle.btn-collapse').hide();
12990        $('.price-ticket-content').hide();
12991        this.totalPriceBottomCart.hide();
12992        $('.container-cart-details.collapse-container').hide();
12993      } else if (allTicketsFree && insurance && insurance.hired) {
12994        this.totalOffDiscount = true;
12995        $('.seat-subtitle.btn-collapse').hide();
12996        $('.price-ticket-content').hide();
12997        $('.container-cart-details.collapse-container').hide();
12998        $('.sumary-item-content.convenienceFee').hide();
12999        this.priceCart.text(Utils.formatPrice(this._cartService.cart._insurance.price));
13000        this.totalPriceBottomCart.text("R$ " + Utils.formatPrice(this._cartService.cart._insurance.price));
13001      } else {
13002        this.totalOffDiscount = false;
13003        this.isDiscount.show();
13004      }
13005
13006      var payment = PaymentController.getInstance();
13007      if (this.loadInstallmentsAPI) {
13008        setTimeout(function () {
13009          $('.interest-amount').remove();
13010          payment.setInstallmentsWithInterest(data, total, _this14.convenienceFee);
13011        }, 100);
13012      } else setTimeout(payment.renderInstallments(data, total, this.convenienceFee), 100);
13013    }
13014  }, {
13015    key: 'updatePassengerDiscount',
13016    value: function updatePassengerDiscount(listOffer, listPassenger, listTransactions) {
13017      var contTransaction = 0;
13018
13019      listOffer.forEach(function (_, i) {
13020        listPassenger.forEach(function (passenger, _) {
13021          if (passenger.type === "CHILD") return;
13022
13023          if (i == 0) {
13024            passenger._seatDeparture._priceWithDiscount = Math.round((listTransactions[contTransaction++].voucherValue || +0.00001) * 100) / 100 || passenger._seatDeparture.priceWithDiscount;
13025
13026            if (passenger._seatDepartureConnection._seatNumber) passenger._seatDepartureConnection._priceWithDiscount = Math.round((listTransactions[contTransaction++].voucherValue || +0.00001) * 100) / 100 || passenger._seatDepartureConnection.priceWithDiscount;
13027          } else {
13028            passenger._seatReturn._priceWithDiscount = Math.round((listTransactions[contTransaction++].voucherValue || +0.00001) * 100) / 100 || passenger._seatReturn.priceWithDiscount;
13029
13030            if (passenger._seatReturnConnection._seatNumber) passenger._seatReturnConnection._priceWithDiscount = Math.round((listTransactions[contTransaction++].voucherValue || +0.00001) * 100) / 100 || passenger._seatReturnConnection.priceWithDiscount;
13031          }
13032        });
13033      });
13034    }
13035  }, {
13036    key: 'checkPassengersDiscount',
13037    value: function checkPassengersDiscount(listTransactions) {
13038      var idOrigin = listTransactions[0].origem;
13039      var dateOrigin = listTransactions[0].data;
13040      var count = 0;
13041
13042      var passengersWithDiscount = listTransactions.filter(function (transaction) {
13043        return transaction.origem == idOrigin && transaction.data == dateOrigin;
13044      });
13045
13046      return passengersWithDiscount.length;
13047    }
13048  }, {
13049    key: 'checkDiscountedRoutes',
13050    value: function checkDiscountedRoutes(listTransactions, listOffer) {
13051      if (listOffer.length > 1) {
13052        var idDestino = listTransactions[0].destino;
13053
13054        var routesWithDiscount = listTransactions.filter(function (transaction) {
13055          return transaction.origem == idDestino;
13056        });
13057
13058        return routesWithDiscount.length;
13059      } else {
13060        return false;
13061      }
13062    }
13063  }, {
13064    key: 'checkTicketsFree',
13065    value: function checkTicketsFree(listTransactions) {
13066      return listTransactions.every(function (tx) {
13067        var price = tx && tx.seatResponse && tx.seatResponse.service ? tx.seatResponse.service.priceWithDiscount : undefined;
13068
13069        return typeof price === 'number' && price <= 0;
13070      });
13071    }
13072  }, {
13073    key: 'msgDiscountApply',
13074    value: function msgDiscountApply(qtdPassengersDiscount, listPassenger, qtdRoutesDiscount) {
13075      var discountMsgError = $('[data-js="discount-msg-error"]').css('color', 'green');
13076      var linkDiscount = $('[data-js="discount-msg-error-link"]').removeClass('active');
13077
13078      // AEM Message Customization
13079      var successMsg = $('#discountCodeSuccessMessage').val();
13080      var successMsgRoutePassenger = $('#discountCodeSuccessRoutePassengerMessage').val();
13081      var successMsgNumberPassenger = $('#discountCodeSuccessNumberPassengerMessage').val();
13082      var successMsgRoute = $('#discountCodeSuccessRouteMessage').val();
13083
13084
13085      if (qtdPassengersDiscount == listPassenger && (qtdRoutesDiscount == listPassenger || !qtdRoutesDiscount)) {
13086        discountMsgError.addClass('active').html(successMsg);
13087        return;
13088      }
13089
13090      if (qtdPassengersDiscount < listPassenger && qtdRoutesDiscount < listPassenger) {
13091        discountMsgError.html(successMsgRoutePassenger);
13092        linkDiscount.addClass('active');
13093        return;
13094      }
13095
13096      if (qtdPassengersDiscount < listPassenger) {
13097        discountMsgError.html(successMsgNumberPassenger);
13098        linkDiscount.addClass('active');
13099        return;
13100      }
13101
13102      discountMsgError.html(successMsg);
13103      linkDiscount.addClass('active');
13104    }
13105  }, {
13106    key: 'showTicketsInCollapse',
13107    value: function showTicketsInCollapse() {
13108      var ticketOpen = $('[data-js="cart-container"]').attr('data-is-open') == 'true' ? true : false;
13109
13110      if (ticketOpen) {
13111        $('.origin-destination').addClass('collapse-true');
13112        return;
13113      }
13114
13115      $('.container-collapse .icon-collapse').hide();
13116    }
13117  }, {
13118    key: 'initializeServiceFeeTooltip',
13119    value: function initializeServiceFeeTooltip() {
13120      var $tooltipButton = $('<button class="icon jca-ico-info-icon-circle btn-tooltip" type="button" data-bs-toggle="tooltip" data-js="service-fee-tooltip" data-bs-placement="top" title="' + i18n('service_fee_message') + '"></button>');
13121
13122      if ($('button[data-js="service-fee-tooltip"]').length > 0) return;
13123      $('[data-js="section-btn-tooltip"]').each(function () {
13124        var $clonedButton = $tooltipButton.clone();
13125        $(this).append($clonedButton);
13126
13127        var el = $clonedButton[0];
13128
13129        new bootstrap.Tooltip(el, {
13130					template: '<div class="tooltip custom-tooltip-message" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'
13131				});
13132      });
13133    }
13134  }, {
13135    key: 'cartService',
13136    get: function get() {
13137      return this._cartService;
13138    }
13139  }]);
13140
13141  return CartComponent;
13142}();
13143'use strict';
13144
13145var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
13146
13147function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
13148
13149/**
13150 *
13151 * Checkout livelo Controller
13152 *
13153 * INICIO
13154 */
13155
13156var CheckoutLiveloController = function () {
13157  function CheckoutLiveloController($, cartComponentRef) {
13158    _classCallCheck(this, CheckoutLiveloController);
13159
13160    this.formData = SessionStorage.get('formData');
13161    this.checkout = SessionStorage.get('checkout');
13162    this.bookingCode = $('[data-js="booking-code"]');
13163    this.btnReturnHome = $('[data-js="return-home"]');
13164    this.cartService = cartComponentRef.cartService;
13165    this.init();
13166  }
13167
13168  _createClass(CheckoutLiveloController, [{
13169    key: 'init',
13170    value: function init() {
13171      this.handleReturnWindow();
13172      this.loadBookingCode();
13173      this.loadDetails();
13174      this.handleCart();
13175      this.removeCollpase();
13176    }
13177  }, {
13178    key: 'handleCart',
13179    value: function handleCart() {
13180      $('[data-js="cart-btn"]').css('display', 'none');
13181    }
13182  }, {
13183    key: 'handleReturnWindow',
13184    value: function handleReturnWindow() {
13185      if (!this.checkout) {
13186        if ($('#homePagePath') && $('#homePagePath').val() && (!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false')) $(location).attr('href', $('#homePagePath').val());
13187      }
13188
13189      this.btnReturnHome.click(function () {
13190        SessionStorage.remove('checkout');
13191        if ($('#homePagePath') && $('#homePagePath').val()) $(location).attr('href', $('#homePagePath').val());
13192      });
13193
13194      if (window.history && window.history.pushState) {
13195        if ($('#homePagePath') && $('#homePagePath').val() && (!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false')) {
13196          var _location = window.location.pathname.split('/');
13197          var currentPage = './' + _location[_location.length - 1];
13198          window.history.pushState('forward', null, currentPage);
13199          $(window).not('.link-to-page').on('popstate', function () {
13200            SessionStorage.remove('checkout');
13201            window.location.href = $('#homePagePath').val();
13202          });
13203        }
13204      }
13205    }
13206  }, {
13207    key: 'loadDetails',
13208    value: function loadDetails() {
13209		var checkoutTrips = this.checkout.sales ? this.checkout.sales : this.checkout.result && this.checkout.result.sales ? this.checkout.result.sales : null;
13210        var $sectionDeparture = $('[data-js="detail-depart-#INDEX"]');
13211        var $sectionDepartureConnection = $('[data-js="detail-depart-connection-#INDEX"]');
13212        var $sectionDepartureConnection2 = $('[data-js="detail-depart-connection2-#INDEX"]');
13213        var $sectionReturn = $('[data-js="detail-return-#INDEX"]');
13214        var $sectionReturnConnection = $('[data-js="detail-return-connection-#INDEX"]');
13215        var $sectionReturnConnection2 = $('[data-js="detail-return-connection2-#INDEX"]');
13216
13217        checkoutTrips = this.groupArrayByField(checkoutTrips, 'going');
13218
13219        var dep = checkoutTrips[0];
13220        var ret = checkoutTrips[1];
13221
13222        dep = this.groupArrayByField(dep, 'service');
13223        dep.sort(function (a, b) {
13224            return DateFormatter.getValidDateFormat(a[0].departureDate) - DateFormatter.getValidDateFormat(b[0].departureDate);
13225        });
13226
13227        if (ret) {
13228            ret = this.groupArrayByField(ret, 'service');
13229            ret.sort(function (a, b) {
13230                return DateFormatter.getValidDateFormat(a[0].departureDate) - DateFormatter.getValidDateFormat(b[0].departureDate);
13231            });
13232        }
13233
13234        var arr = [];
13235        arr[0] = dep[0];
13236        arr[1] = dep.slice(1);
13237        arr[2] = ret ? ret[0] : null;
13238        arr[3] = ret ? ret.slice(1) : null;
13239
13240        $.each(arr, function (index, trip) {
13241            if (!trip) return;
13242
13243            switch (index) {
13244                case 0:
13245                    new CheckoutDetailsCard({ $parent: $sectionDeparture, trip: trip, isReturn: false });
13246                    break;
13247                case 1:
13248                    if (trip[0]) {
13249                        $sectionDepartureConnection.show();
13250                        new CheckoutDetailsCard({
13251                            $parent: $sectionDepartureConnection,
13252                            trip: trip[0],
13253                            isReturn: false
13254                        });
13255                    }
13256
13257                    if (trip[1]) {
13258                        $sectionDepartureConnection2.show();
13259                        new CheckoutDetailsCard({
13260                            $parent: $sectionDepartureConnection2,
13261                            trip: trip[1],
13262                            isReturn: false
13263                        });
13264                    }
13265                    break;
13266                case 2:
13267                    $sectionReturn.show();
13268                    new CheckoutDetailsCard({ $parent: $sectionReturn, trip: trip, isReturn: true });
13269                    break;
13270                case 3:
13271                    if (trip[0]) {
13272                        $sectionReturnConnection.show();
13273                        new CheckoutDetailsCard({
13274                            $parent: $sectionReturnConnection,
13275                            trip: trip[0],
13276                            isReturn: true
13277                        });
13278                    }
13279
13280                    if (trip[1]) {
13281                        $sectionReturnConnection2.show();
13282                        new CheckoutDetailsCard({
13283                            $parent: $sectionReturnConnection2,
13284                            trip: trip[1],
13285                            isReturn: true
13286                        });
13287                    }
13288                    break;
13289            }
13290        });
13291    }
13292  }, {
13293    key: 'removeCollpase',
13294    value: function removeCollpase() {
13295      $('.card-checkout').find('.card-checkout-header').removeAttr('data-bs-toggle');
13296      $('.card-checkout').find('.card-checkout-header button').hide();
13297      $('.card-checkout').find('.card-checkout-collapsible').addClass('d-block');
13298    }
13299  }, {
13300    key: 'groupArrayByField',
13301    value: function groupArrayByField(filteredHistory, field) {
13302      var arr = [];
13303      var target = Utils.groupArrayBy(filteredHistory, field);
13304
13305      for (var k in target) {
13306        if (target.hasOwnProperty(k)) {
13307          arr.push(target[k]);
13308        }
13309      }
13310
13311      return arr;
13312    }
13313  }, {
13314    key: 'loadBookingCode',
13315    value: function loadBookingCode() {
13316      var finder = void 0;
13317      finder = this.checkout.sales[0] ? this.checkout.sales[0].finder : '';
13318      this.bookingCode.text(finder);
13319    }
13320  }]);
13321
13322  return CheckoutLiveloController;
13323}();
13324/**
13325 *
13326 * Checkout Controller
13327 *
13328 * FIM
13329 */
13330'use strict';
13331
13332var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
13333
13334function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
13335
13336var CheckoutNupayController = function () {
13337  function CheckoutNupayController($) {
13338    _classCallCheck(this, CheckoutNupayController);
13339
13340    this.$ = $;
13341    this.checkout = SessionStorage.get('checkout');
13342    this.passenger = SessionStorage.get('passenger');
13343    this.cart = SessionStorage.get('cart');
13344    var urlPaymentId = new URLSearchParams(window.location.search).get('paymentReferenceId');
13345    var checkoutPaymentId = this.checkout && (this.checkout.paymentId || this.checkout.result && this.checkout.result.paymentId);
13346    this.paymentReferenceId = urlPaymentId || checkoutPaymentId || SessionStorage.get('nupayPaymentReferenceId');
13347    if (this.paymentReferenceId) {
13348      SessionStorage.set('nupayPaymentReferenceId', this.paymentReferenceId);
13349    }
13350    this.nupayPaymentTitle = $('[data-js="nupay-payment-title"]');
13351    this.nupayPaymentValue = $('[data-js="nupay-payment-value"]');
13352    this.nupayReservationEmail = $('[data-js="nupay-reservation-email"]');
13353    this.closeNupayWarning = $('[data-js="close-nupay-warning"]');
13354    this.btnMyReservations = $('[data-js="btn-my-reservations"]');
13355    this.isAgencyFlow = SessionStorage.get('isAgencyFlow');
13356    this.pollingInterval = null;
13357    this.POLLING_DELAY = 10000;
13358    var paymentExpirationMinutes = this.checkout && (this.checkout.paymentExpirationInMinutes || this.checkout.result && this.checkout.result.paymentExpirationInMinutes) || 15;
13359    this.PAYMENT_EXPIRY_MS = paymentExpirationMinutes * 60 * 1000;
13360    this.nupayCreatedAt = null;
13361    this.init();
13362  }
13363
13364  _createClass(CheckoutNupayController, [{
13365    key: 'init',
13366    value: function init() {
13367      var _this = this;
13368
13369      if(Utils.isMobile()) {
13370        $('.container-alert-nupay-reservation').eq(1).remove();
13371      } else {
13372        $('.container-alert-nupay-reservation').eq(1).remove();
13373      }
13374
13375      HttpService._nupayPendingFlow = true;
13376      this.handleReturnWindow();
13377      this.loadNupayData();
13378      this.listenEvents();
13379      this.removeMessageMarketplaceRemark();
13380
13381      var existingToken = SessionStorage.get('jca_token');
13382      if (existingToken) {
13383        HttpService.applyRestoredCustomer(existingToken);
13384        this.passenger = SessionStorage.get('passenger');
13385        this.loadEmail();
13386      }
13387
13388      HttpService.restorePaymentSession(this.paymentReferenceId).then(function () {
13389        var token = SessionStorage.get('jca_token');
13390        if (token) {
13391          HttpService.applyRestoredCustomer(token);
13392          _this.passenger = SessionStorage.get('passenger');
13393          _this.loadEmail();
13394        }
13395      });
13396
13397      this.startPolling();
13398    }
13399  }, {
13400    key: 'handleReturnWindow',
13401    value: function handleReturnWindow() {
13402      if (!this.checkout && !this.paymentReferenceId) {
13403        $(location).attr('href', $('#homePagePath').val());
13404        return
13405      }
13406
13407      if (window.history && window.history.pushState) {
13408        var pathParts = window.location.pathname.split('/');
13409        var currentPage = './' + pathParts[pathParts.length - 1] + (window.location.search || '');
13410        window.history.pushState('forward', null, currentPage);
13411        $(window).not('.link-to-page').on('popstate', function () {
13412          SessionStorage.remove('checkout');
13413          window.location.href = $('#homePagePath').val();
13414        });
13415      }
13416    }
13417  }, {
13418    key: 'removeMessageMarketplaceRemark',
13419    value: function removeMessageMarketplaceRemark() {
13420      var repricingV2 = SessionStorage.get('repricingv2');
13421      if (repricingV2) {
13422        $('[data-js="warning-message-marketplace"]').addClass('d-none');
13423      }
13424    }
13425  }, {
13426    key: 'loadNupayData',
13427    value: function loadNupayData() {
13428      this.loadPaymentValue();
13429      this.loadEmail();
13430    }
13431  }, {
13432    key: 'loadPaymentValue',
13433    value: function loadPaymentValue() {
13434      var total = 0;
13435
13436      try {
13437        if (this.checkout && this.checkout.value) {
13438          total = this.checkout.value;
13439        } else if (this.checkout && this.checkout.result && this.checkout.result.value) {
13440          total = this.checkout.result.value;
13441        } else if (this.cart && this.cart._totalPrice) {
13442          total = this.cart._totalPrice;
13443        }
13444      } catch (e) {
13445        console.error('Erro ao carregar valor NuPay:', e);
13446      }
13447
13448      if (total) {
13449        this.nupayPaymentValue.text(' R$ ' + Utils.formatPrice(total));
13450      }
13451    }
13452  }, {
13453    key: 'loadEmail',
13454    value: function loadEmail() {
13455      if (this.passenger && this.passenger._email) {
13456        this.nupayReservationEmail.text(this.passenger._email);
13457      }
13458    }
13459  }, {
13460    key: 'listenEvents',
13461    value: function listenEvents() {
13462      this.closeNupayWarning.on('click', function () {
13463        $('.container-alert-nupay-reservation').hide();
13464      });
13465
13466      this.btnMyReservations.on('click', function (e) {
13467        e.preventDefault();
13468        $(location).attr('href', $('#myAccountPath').val());
13469      });
13470    }
13471  }, {
13472    key: 'startPolling',
13473    value: function startPolling() {
13474      var _this = this;
13475
13476      if (!this.paymentReferenceId) {
13477        return;
13478      }
13479
13480      this.checkPaymentStatus();
13481      this.pollingInterval = setInterval(function () {
13482        _this.checkPaymentStatus();
13483      }, this.POLLING_DELAY);
13484    }
13485  }, {
13486    key: 'stopPolling',
13487    value: function stopPolling() {
13488      if (this.pollingInterval) {
13489        clearInterval(this.pollingInterval);
13490        this.pollingInterval = null;
13491      }
13492    }
13493  }, {
13494    key: 'checkPaymentStatus',
13495    value: function checkPaymentStatus() {
13496      var _this3 = this;
13497
13498      var nupayCreatedAt = SessionStorage.get('nupayCreatedAt') || this.nupayCreatedAt || Date.now();
13499      if (Date.now() > nupayCreatedAt + this.PAYMENT_EXPIRY_MS) {
13500        this.stopPolling();
13501        ModalNupay.show('expired');
13502        return;
13503      }
13504
13505      var headers = {
13506        'Authorization': '' + SessionStorage.get('jca_token'),
13507        'sessionseatlock': '' + SessionStorage.get('sessionseatlock')
13508      };
13509
13510      HttpService.get("nupayPaymentStatus?paymentReferenceId="+this.paymentReferenceId, headers).then(function (data) {
13511        if (data && data.result && data.result.sales && data.result.sales.length > 0) {
13512          var status = data.result.sales[0].status.toUpperCase();
13513
13514          if (status === 'SALE_APPROVED') {
13515            _this3.stopPolling();
13516            SessionStorage.set('checkout', data);
13517            $(location).attr('href', $('#checkoutPagePath').val())
13518          }
13519        }
13520      }).fail(function (xhr) {
13521        if (xhr.status === 204) {
13522          _this3.stopPolling();
13523          ModalNupay.show('cancelled');
13524        }
13525
13526        if (xhr.status === 401) {
13527          HttpService.restorePaymentSession(_this3.paymentReferenceId);
13528        }
13529      });
13530    }
13531  }]);
13532
13533  return CheckoutNupayController;
13534}();
13535'use strict';
13536
13537var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
13538
13539function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
13540
13541var CheckoutPixController = function () {
13542  function CheckoutPixController($) {
13543    _classCallCheck(this, CheckoutPixController);
13544
13545    this.btnCopyPixKey = $('[data-js="copy-pix-key"]');
13546    this.pixKey = $('[data-js="pix-key"]');
13547    this.maxHour = $('[data-js="bank-transfer-hour"]');
13548    this.favoredTo = $('[data-js="favored-to"]');
13549    this.qrCodePix = $('[data-js="qrcode-pix"]');
13550    this.labelBtnCopyPix = $('[data-js="label-copy-key"]');
13551    this.checkout = SessionStorage.get('checkout');
13552    this.total = $('[data-js="buy-value"]');
13553    this.isPixItau = $('[data-js="is-pix-itau"]').val() == 'true' ? true : false;
13554    this.convenienceFee = $('[data-js="convenience-fee"]').attr('value') == 'true' ? true : false;
13555    this.repricingV2 = SessionStorage.get('repricingv2');
13556    this.init();
13557  }
13558
13559  _createClass(CheckoutPixController, [{
13560    key: 'init',
13561    value: function init() {
13562      this.initBtnTooltip();
13563      this.loadCheckoutPix();
13564      this.handleCheckoutPixEvents();
13565      this.sendPurchaseToAnalytics();
13566    }
13567  }, {
13568     key: 'sendPurchaseToAnalytics',
13569     value: function sendPurchaseToAnalytics() {
13570      var _this = this;
13571      var cart = SessionStorage.get('cart');
13572
13573      var voucher = this.checkout.sales[0].voucherToken;
13574
13575      var revenue = Utils.formatPrice(this.checkout.value);
13576
13577      var dataLayerView = [];
13578      cart._listOffer.forEach(function (offer) {
13579        var aux = {
13580            item_id: offer._service,
13581            price: offer._priceWithDiscountPix,
13582            item_brand: offer._company._companyName,
13583            item_category: offer._company._origin._label,
13584            item_category2: offer._company._destination._label,
13585            item_category3: offer._company._departureDate,
13586            item_category4: offer._company._arrivingDate,
13587            item_variant: offer._classtype._className,
13588            quantity: cart._listPassengers.length
13589        };
13590        dataLayerView.push(aux);
13591      });
13592
13593      dataLayer.push({ ecommerce: null });
13594      dataLayer.push({ event: "purchase_ga4",
13595          ecommerce:{
13596            transaction_id: _this.checkout.finder,
13597            currency: "BRL",
13598            revenue: this.checkout.value,
13599            value: revenue,
13600            coupon: voucher,
13601            affiliation: $("#siteName").val(),
13602            items: dataLayerView
13603          }
13604      });
13605     }
13606   }, {
13607    key: 'initBtnTooltip',
13608    value: function initBtnTooltip() {
13609      this.btnCopyPixKey.each(function (_, el) {
13610        new bootstrap.Tooltip(el);
13611      });
13612    }
13613  }, {
13614    key: 'handleCheckoutPixEvents',
13615    value: function handleCheckoutPixEvents() {
13616      var _this = this;
13617
13618      this.btnCopyPixKey.on('click', function () {
13619        _this.copyPixKey();
13620        _this.activateCopyPixKey();
13621      });
13622    }
13623  }, {
13624    key: 'copyPixKey',
13625    value: function copyPixKey() {
13626      var value = $('[data-js="pix-key"]');
13627
13628      var $temp = $("<input>");
13629      $("body").append($temp);
13630      $temp.val($(value).text()).select();
13631      document.execCommand("copy");
13632      $temp.remove();
13633    }
13634  }, {
13635    key: 'activateCopyPixKey',
13636    value: function activateCopyPixKey() {
13637      this.btnCopyPixKey.addClass('active');
13638      this.labelBtnCopyPix.text('Copiado');
13639
13640      var el = this.btnCopyPixKey[0];
13641
13642      el.setAttribute('data-bs-original-title', 'Chave copiada');
13643      el.setAttribute('title', 'Chave copiada');
13644
13645      var tooltip = bootstrap.Tooltip.getInstance(el);
13646      if (!tooltip) tooltip = new bootstrap.Tooltip(el);
13647
13648      tooltip.show();
13649    }
13650  }, {
13651    key: 'loadCheckoutPix',
13652    value: function loadCheckoutPix() {
13653      this.getMaxTime();
13654      this.loadCardsCheckoutPix();
13655      this.loadQrCodePix();
13656    }
13657  }, {
13658    key: 'loadCardsCheckoutPix',
13659    value: function loadCardsCheckoutPix() {
13660      var total = this.checkout.value;
13661
13662      this.favoredTo.text(this.checkout.favored);
13663      this.pixKey.text(this.checkout.pixKey);
13664      this.total.text('R$ ' + Utils.formatPrice(total));
13665    }
13666  }, {
13667    key: 'loadQrCodePix',
13668    value: function loadQrCodePix() {
13669      var image = "data:image/png;base64," + this.checkout.instructions.qrCode.base64;
13670      this.qrCodePix.attr('src', image);
13671    }
13672  }, {
13673    key: 'hasPixItau',
13674    value: function hasPixItau() {
13675      return this.isPixItau == 'true' ? true : false;
13676    }
13677  }, {
13678    key: 'getMaxTime',
13679    value: function getMaxTime() {
13680      if (this.hasPixItau()) {
13681        var maxTime = new Date(this.checkout.maxAge);
13682        var tzoffset = new Date().getTimezoneOffset();
13683        var localISOTime = new Date(maxTime - tzoffset).toISOString().slice(0, -1);
13684        var maxHour = DateFormatter.extractHour(localISOTime);
13685        var maxDate = DateFormatter.extractDate(localISOTime);
13686
13687        var strTemp = this.maxHour.find('.cmp-text').text();
13688        strTemp = strTemp.replace('${deadline}', ' ' + maxHour + ' de ' + DateFormatter.reverseDate(maxDate))
13689
13690        this.maxHour.find('.cmp-text').text(strTemp);
13691      } else {
13692        var _maxTime = new Date(this.checkout.maxAge);
13693        var _tzoffset = new Date().getTimezoneOffset() * 60000;
13694        var _localISOTime = new Date(_maxTime - _tzoffset).toISOString().slice(0, -1);
13695        var _maxHour = DateFormatter.extractHour(_localISOTime);
13696        var _maxDate = DateFormatter.extractDate(_localISOTime);
13697
13698        var strTemp = this.maxHour.find('.cmp-text').text();
13699        strTemp = strTemp.replace('${deadline}', ' ' + _maxHour + ' de ' + DateFormatter.reverseDate(_maxDate))
13700
13701        this.maxHour.find('.cmp-text').text(strTemp);
13702      }
13703    }
13704  }]);
13705
13706  return CheckoutPixController;
13707}();
13708'use strict';
13709
13710var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
13711
13712function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
13713
13714var CheckoutWalletController = function () {
13715  function CheckoutWalletController($) {
13716    _classCallCheck(this, CheckoutWalletController);
13717
13718    this.btnCopyPixKey = $('[data-js="copy-pix-key"]');
13719    this.pixKey = $('[data-js="pix-key"]');
13720    this.maxHour = $('[data-js="bank-transfer-hour"]');
13721    this.favoredTo = $('[data-js="favored-to"]');
13722    this.qrCodePix = $('[data-js="qrcode-pix"]');
13723    this.labelBtnCopyPix = $('[data-js="label-copy-key"]');
13724    this.checkout = SessionStorage.get('checkout');
13725    this.total = $('[data-js="buy-value"]');
13726    this.isPixItau = $('[data-js="is-pix-itau"]');
13727    this.convenienceFee = $('[data-js="convenience-fee"]').attr('value') == 'true';
13728    this.repricingV2 = SessionStorage.get('repricingv2');
13729    this.capCutIcon = $('[data-js="capcut-key"]');
13730    this.capCutIconMobile = $('[data-js="capcut-key-mobile"]');
13731    this.capCutCopied = $('[data-js="capcut-key-copied"]');
13732    this.goToWallet = $('[data-js="go-to-wallet"]');
13733    this.bookingCode = $('[data-js="booking-code"]');
13734    this.checkoutPixComplet = $('[data-js="checkout-pix-complement"]');
13735    this.checkoutCards = $('[data-js="checkout-wallet-cards"]');
13736    this.checkoutDetails = $('[data-js="checkout-wallet-details"]');
13737    this.complementPix = SessionStorage.get('completementPix');
13738    this.timerValue = $('[data-js="timerValue"]');
13739    this.init();
13740  }
13741
13742  _createClass(CheckoutWalletController, [{
13743    key: 'init',
13744    value: function init() {
13745      this.initBtnTooltip();
13746      this.loadCheckoutPixWallet();
13747      this.handleCheckoutPixEvents();
13748      this.startPaymentStatusPolling();
13749      this.applyApprovedState();
13750    }
13751  }, {
13752    key: 'initBtnTooltip',
13753    value: function initBtnTooltip() {
13754      this.btnCopyPixKey.each(function (_, el) {
13755        new bootstrap.Tooltip(el);
13756      });
13757    }
13758  }, {
13759    key: 'handleCheckoutPixEvents',
13760    value: function handleCheckoutPixEvents() {
13761      var _this = this;
13762
13763      this.btnCopyPixKey.on('click', function () {
13764        _this.copyPixKey();
13765        _this.activateCopyPixKey();
13766      });
13767
13768      this.capCutIcon.on('click', function () {
13769        _this.copyCapcut();
13770      });
13771
13772      this.capCutIconMobile.on('click', function () {
13773        _this.copyCapcutMobile();
13774      });
13775
13776      this.goToWallet.on('click', function () {
13777        $(location).attr("href", "wallet-giro.html");
13778      });
13779    }
13780  }, {
13781    key: 'copyPixKey',
13782    value: function copyPixKey() {
13783      var value = $('[data-js="pix-key"]');
13784      var $temp = $("<input>");
13785      $("body").append($temp);
13786      $temp.val(value[0].textContent).select();
13787      document.execCommand("copy");
13788      $temp.remove();
13789    }
13790  }, {
13791    key: 'copyCapcut',
13792    value: function copyCapcut() {
13793      var pixKeySpan = this.capCutIcon.siblings('span');
13794      var $temp = $("<input>");
13795      $("body").append($temp);
13796      $temp.val(pixKeySpan[0].textContent).select();
13797      document.execCommand("copy");
13798      $temp.remove();
13799      this.capCutCopied.removeClass('d-none');
13800    }
13801  }, {
13802    key: 'copyCapcutMobile',
13803    value: function copyCapcutMobile() {
13804      var pixKeySpan = this.capCutIconMobile.siblings('span');
13805      var $temp = $("<input>");
13806      $("body").append($temp);
13807      if (pixKeySpan != null) {
13808        if (pixKeySpan.length == 1) {
13809          $temp.val(pixKeySpan[0].textContent).select();
13810        } else {
13811          $temp.val(pixKeySpan[2].textContent).select();
13812        }
13813      }
13814
13815      document.execCommand("copy");
13816      $temp.remove();
13817      this.capCutCopied.removeClass('d-none');
13818    }
13819  }, {
13820    key: 'activateCopyPixKey',
13821    value: function activateCopyPixKey() {
13822      this.btnCopyPixKey.addClass('active');
13823      this.labelBtnCopyPix.text('Copiado');
13824
13825      var el = this.btnCopyPixKey[0];
13826
13827      el.setAttribute('data-bs-original-title', 'Chave copiada');
13828      el.setAttribute('title', 'Chave copiada');
13829
13830      var tooltip = bootstrap.Tooltip.getInstance(el);
13831      if (!tooltip) tooltip = new bootstrap.Tooltip(el);
13832
13833      tooltip.show();
13834    }
13835  }, {
13836    key: 'loadCheckoutPixWallet',
13837    value: function loadCheckoutPixWallet() {
13838      this.getMaxTime();
13839      this.loadCardsCheckoutPixWallet();
13840      this.loadQrCodePix();
13841    }
13842  }, {
13843    key: 'loadCardsCheckoutPixWallet',
13844    value: function loadCardsCheckoutPixWallet() {
13845      var total = this.checkout.value;
13846      this.favoredTo.text(this.checkout.favored);
13847      this.pixKey.text(this.checkout.pixKey);
13848      this.total.text(Utils.formatPrice(total));
13849      this.bookingCode.text(this.checkout.finder);
13850    }
13851  }, {
13852    key: 'loadQrCodePix',
13853    value: function loadQrCodePix() {
13854      var image = "data:image/png;base64," + this.checkout.instructions.qrCode.base64;
13855      this.qrCodePix.attr('src', image);
13856    }
13857  }, {
13858    key: 'hasPixItau',
13859    value: function hasPixItau() {
13860      return this.isPixItau.val() == 'true';
13861    }
13862  }, {
13863    key: 'getMaxTime',
13864    value: function getMaxTime() {
13865      var maxTime = new Date(this.checkout.maxAge);
13866      var tzoffset = 3 * 60 * 60 * 1000;
13867      var localISOTime = new Date(maxTime.getTime() - tzoffset).toISOString().slice(0, -1);
13868      var maxHour = DateFormatter.extractHour(localISOTime);
13869      var maxDate = DateFormatter.extractDate(localISOTime);
13870      $('[data-js="depart-date-wallet"]').text(DateFormatter.reverseDate(maxDate));
13871      this.maxHour.text(' ' + maxHour + ' de ' + DateFormatter.reverseDate(maxDate));
13872    }
13873  }, {
13874    key: 'startPaymentStatusPolling',
13875    value: function startPaymentStatusPolling() {
13876      var _this2 = this;
13877
13878      var passengerId = SessionStorage.get('passenger');
13879      if (this.complementPix) {
13880        var checkStatus = function checkStatus() {
13881          var url = 'paymentComplementPixCheck?finder=' + _this2.checkout.finder + '&user=' + passengerId._id;
13882          var headers = {
13883            'Authorization': '' + SessionStorage.get('jca_token')
13884          };
13885
13886          HttpService.get(url, headers).then(function (response) {
13887            var status = response.result.status;
13888            if (status === 'SALE_APPROVED' || status === 'SALE_EXPIRED') {
13889              clearInterval(_this2.pollingInterval);
13890              _this2.handlePaymentStatus(status);
13891            }
13892          }).catch(function (error) {
13893            console.error('Error checking payment status:', error);
13894          });
13895        };
13896
13897        this.pollingInterval = setInterval(checkStatus, this.timerValue.val());
13898      }
13899    }
13900  }, {
13901    key: 'handlePaymentStatus',
13902    value: function handlePaymentStatus(status) {
13903      if (status === 'SALE_APPROVED') {
13904        SessionStorage.set('approved', true);
13905        clearInterval(this.pollingInterval);
13906        this.applyApprovedState();
13907      }
13908    }
13909  }, {
13910    key: 'applyApprovedState',
13911    value: function applyApprovedState() {
13912      var paymentStatus = SessionStorage.get('approved');
13913
13914      if (this.complementPix) {
13915        if (paymentStatus) {
13916          this.checkoutPixComplet.addClass('d-none');
13917          this.checkoutCards.removeClass('d-none');
13918          this.checkoutDetails.removeClass('d-none');
13919          new CardDetailsCheckout($);
13920        } else {
13921          this.checkoutPixComplet.removeClass('d-none');
13922          this.checkoutCards.addClass('d-none');
13923          this.checkoutDetails.addClass('d-none');
13924        }
13925      } else {
13926        this.checkoutPixComplet.remove();
13927        this.checkoutCards.removeClass('d-none');
13928        this.checkoutDetails.removeClass('d-none');
13929        new CardDetailsCheckout($);
13930      }
13931    }
13932  }]);
13933
13934  return CheckoutWalletController;
13935}();
13936'use strict';
13937
13938var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
13939
13940function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
13941
13942/**
13943 *
13944 * Checkout Controller
13945 *
13946 * INICIO
13947 */
13948
13949var CheckoutController = function () {
13950  function CheckoutController($, cartComponentRef) {
13951    _classCallCheck(this, CheckoutController);
13952
13953	this.$ = $;
13954	this.cartComponentRef = cartComponentRef;
13955    this.formData = SessionStorage.get('formData');
13956    this.checkout = SessionStorage.get('checkout');
13957    this.bookingCode = $('[data-js="booking-code"]');
13958    this.btnReturnHome = $('[data-js="return-home"]');
13959    this.cartService = cartComponentRef.cartService;
13960    this.paymentNegative = SessionStorage.get('paymentNegative');
13961    var urlPaymentId = new URLSearchParams(window.location.search).get('paymentReferenceId');
13962    var checkoutAux = SessionStorage.get('checkout_aux');
13963    this.paymentReferenceId = urlPaymentId || SessionStorage.get('nupayPaymentReferenceId');
13964    if (this.paymentReferenceId) {
13965        SessionStorage.set('nupayPaymentReferenceId', this.paymentReferenceId);
13966    }
13967    if (this.paymentReferenceId || checkoutAux && checkoutAux.method === 'NUPAY') {
13968        HttpService._nupayPendingFlow = true;
13969    }
13970    this.init();
13971  }
13972
13973  _createClass(CheckoutController, [{
13974    key: 'init',
13975    value: function init() {
13976	  this.checkout = this.checkout ? this.checkout.result || this.checkout : this.checkout;
13977      this.handleInsurance();
13978      this.handleReturnWindow();
13979
13980      if (!this.checkout && this.paymentReferenceId) {
13981          this.bootstrapNupayConfirmation();
13982          return;
13983      }
13984
13985      this.loadBookingCode();
13986      this.loadDetails();
13987      this.handleCart();
13988      this.removeCollpase();
13989    }
13990  }, {
13991    key: 'bootstrapNupayConfirmation',
13992    value: function bootstrapNupayConfirmation() {
13993        var _this = this;
13994
13995        HttpService.restorePaymentSession(this.paymentReferenceId).then(function () {
13996            var token = SessionStorage.get('jca_token');
13997            if (token) HttpService.applyRestoredCustomer(token);
13998            return _this.fetchNupayCheckout();
13999        }).then(function (data) {
14000            if (data) {
14001                SessionStorage.set('checkout', data);
14002                SessionStorage.set('checkout_aux', { method: 'NUPAY' });
14003                _this.checkout = data.result || data;
14004            }
14005            if (!_this.checkout) return;
14006            _this.loadBookingCode();
14007            _this.loadDetails();
14008            _this.handleCart();
14009            _this.removeCollpase();
14010        });
14011    }
14012  }, {
14013    key: 'fetchNupayCheckout',
14014    value: function fetchNupayCheckout() {
14015        var paymentReferenceId = this.paymentReferenceId;
14016        return new Promise(function (resolve) {
14017            var headers = {
14018                Authorization: '' + SessionStorage.get('jca_token'),
14019                sessionseatlock: SessionStorage.get('sessionseatlock')
14020            };
14021
14022            HttpService.get("nupayPaymentStatus?paymentReferenceId="+paymentReferenceId, headers).then(function (data) {
14023                return resolve(data);
14024            }).fail(function () {
14025                return resolve(null);
14026            });
14027        });
14028    }
14029  }, {
14030    key: 'handleInsurance',
14031    value: function handleCart() {
14032      if (this.checkout.sales != null && this.checkout.sales[0].insurance != null) {
14033        $('[data-js="seguro-viagem"]').css('display', 'block');
14034      }
14035    }
14036  }, {
14037    key: 'handleCart',
14038    value: function handleCart() {
14039      $('[data-js="cart-btn"]').css('display', 'none');
14040    }
14041  }, {
14042    key: 'handleReturnWindow',
14043    value: function handleReturnWindow() {
14044      if (!this.checkout && !this.paymentReferenceId) {
14045        if ($('#homePagePath') && $('#homePagePath').val() && (!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false')) $(location).attr('href', $('#homePagePath').val());
14046      }
14047
14048      this.btnReturnHome.click(function () {
14049        SessionStorage.remove('checkout');
14050        if ($('#homePagePath') && $('#homePagePath').val()) $(location).attr('href', $('#homePagePath').val());
14051      });
14052
14053      if (window.history && window.history.pushState) {
14054        if ( $('#homePagePath') && $('#homePagePath').val() && (!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false' )) {
14055            var pathParts = window.location.pathname.split('/');
14056            var currentPage = './' + pathParts[pathParts.length - 1] + (window.location.search || '');
14057            window.history.pushState('forward', null, currentPage);
14058            $(window).not('.link-to-page').on('popstate', function () {
14059                SessionStorage.remove('checkout');
14060                window.location.href = $('#homePagePath').val();
14061            });
14062        }
14063      }
14064    }
14065  }, {
14066    key: 'loadDetails',
14067    value: function loadDetails() {
14068        if (!this.checkout) return;
14069        var checkoutTrips = this.checkout.sales ? this.checkout.sales : this.checkout.result && this.checkout.result.sales ? this.checkout.result.sales : null;
14070        if (!checkoutTrips) return;
14071        var $sectionDeparture = $('[data-js="detail-depart-#INDEX"]');
14072        var $sectionDepartureConnection = $('[data-js="detail-depart-connection-#INDEX"]');
14073        var $sectionDepartureConnection2 = $('[data-js="detail-depart-connection2-#INDEX"]');
14074        var $sectionReturn = $('[data-js="detail-return-#INDEX"]');
14075        var $sectionReturnConnection = $('[data-js="detail-return-connection-#INDEX"]');
14076        var $sectionReturnConnection2 = $('[data-js="detail-return-connection2-#INDEX"]');
14077
14078        checkoutTrips = this.groupArrayByField(checkoutTrips, 'going');
14079
14080        var dep = checkoutTrips[0];
14081        var ret = checkoutTrips[1];
14082
14083        dep = this.groupArrayByField(dep, 'service');
14084        dep.sort(function (a, b) {
14085            return DateFormatter.getValidDateFormat(a[0].departureDate) - DateFormatter.getValidDateFormat(b[0].departureDate);
14086        });
14087
14088        if (ret) {
14089            ret = this.groupArrayByField(ret, 'service');
14090            ret.sort(function (a, b) {
14091                return DateFormatter.getValidDateFormat(a[0].departureDate) - DateFormatter.getValidDateFormat(b[0].departureDate);
14092            });
14093        }
14094
14095        var arr = [];
14096        arr[0] = dep[0];
14097        arr[1] = dep.slice(1);
14098        arr[2] = ret ? ret[0] : null;
14099        arr[3] = ret ? ret.slice(1) : null;
14100
14101        $.each(arr, function (index, trip) {
14102            if (!trip) return;
14103
14104            switch (index) {
14105                case 0:
14106                    new CheckoutDetailsCard({ $parent: $sectionDeparture, trip: trip, isReturn: false });
14107                    break;
14108                case 1:
14109                    if (trip[0]) {
14110                        $sectionDepartureConnection.show();
14111                        new CheckoutDetailsCard({
14112                            $parent: $sectionDepartureConnection,
14113                            trip: trip[0],
14114                            isReturn: false
14115                        });
14116                    }
14117
14118                    if (trip[1]) {
14119                        $sectionDepartureConnection2.show();
14120                        new CheckoutDetailsCard({
14121                            $parent: $sectionDepartureConnection2,
14122                            trip: trip[1],
14123                            isReturn: false
14124                        });
14125                    }
14126                    break;
14127                case 2:
14128                    $sectionReturn.show();
14129                    new CheckoutDetailsCard({ $parent: $sectionReturn, trip: trip, isReturn: true });
14130                    break;
14131                case 3:
14132                    if (trip[0]) {
14133                        $sectionReturnConnection.show();
14134                        new CheckoutDetailsCard({
14135                            $parent: $sectionReturnConnection,
14136                            trip: trip[0],
14137                            isReturn: true
14138                        });
14139                    }
14140
14141                    if (trip[1]) {
14142                        $sectionReturnConnection2.show();
14143                        new CheckoutDetailsCard({
14144                            $parent: $sectionReturnConnection2,
14145                            trip: trip[1],
14146                            isReturn: true
14147                        });
14148                    }
14149                    break;
14150            }
14151        });
14152    }
14153  }, {
14154    key: 'removeCollpase',
14155    value: function removeCollpase() {
14156      $('.card-checkout').find('.card-checkout-header').removeAttr('data-bs-toggle');
14157      $('.card-checkout').find('.card-checkout-header button').hide();
14158      $('.card-checkout').find('.card-checkout-collapsible').addClass('d-block');
14159    }
14160  }, {
14161    key: 'groupArrayByField',
14162    value: function groupArrayByField(filteredHistory, field) {
14163      var arr = [];
14164      var target = Utils.groupArrayBy(filteredHistory, field);
14165
14166      for (var k in target) {
14167        if (target.hasOwnProperty(k)) {
14168          arr.push(target[k]);
14169        }
14170      }
14171
14172      return arr;
14173    }
14174  }, {
14175    key: 'loadBookingCode',
14176    value: function loadBookingCode() {
14177      if (!this.checkout) return;
14178      var finder = "Código não disponível";
14179
14180      try {
14181        if (this.checkout.result && this.checkout.result.finder) {
14182            finder = this.checkout.result.finder;
14183        } else if (this.checkout.finder) {
14184            finder = this.checkout.finder;
14185        } else if (!this.checkout.payment) {
14186          if (this.checkout.paymee) {
14187            finder = this.checkout.paymee.referenceCode || finder;
14188          } else if (this.checkout.resultAdyen && this.checkout.resultAdyen.result) {
14189            finder = this.checkout.resultAdyen.result.finder || finder;
14190          } else if (this.checkout.sales && this.checkout.sales.length > 0) {
14191            finder = this.checkout.sales[0].finder || finder;
14192          }
14193        } else {
14194          var paymee = this.checkout.payment.paymee;
14195
14196          if (paymee) {
14197            finder = this.checkout.payment.paymee.referenceCode || finder;
14198          } else if (this.paymentNegative) {
14199            finder = this.checkout.sales.map(function (sale) {
14200              return sale.finder;
14201            }).join(", ") || finder;
14202          } else if (this.checkout.payment.result) {
14203            finder = this.checkout.payment.result.finder || finder;
14204          }
14205        }
14206      } catch (error) {
14207        console.error("Erro ao carregar o código de reserva:", error);
14208      }
14209      var jcaIdentifierPage = $('#jca-identifier-page').val();
14210      var checkoutTypePage = jcaIdentifierPage == 'jca-checkout-pix-page' || jcaIdentifierPage == 'jca-checkout-bank-page' ? true : false;
14211      var showBookingCodeAemCheckbox = $('[data-js="show-booking-cod-aem-checkbox"]').val() == 'true' ? true : false;
14212      (showBookingCodeAemCheckbox == true && checkoutTypePage == true) ? $('.card-finder').remove() : this.bookingCode.text(finder);
14213    }
14214  }]);
14215
14216  return CheckoutController;
14217}();
14218/**
14219 *
14220 * Checkout Controller
14221 *
14222 * FIM
14223 */
14224'use strict';
14225
14226var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
14227
14228function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
14229
14230var Collaboration = function () {
14231  function Collaboration($) {
14232    _classCallCheck(this, Collaboration);
14233
14234    this.init();
14235  }
14236
14237  _createClass(Collaboration, [{
14238    key: 'init',
14239    value: function init() {
14240      this.toggleCirclesTab();
14241    }
14242  }, {
14243    key: 'toggleCirclesTab',
14244    value: function toggleCirclesTab() {
14245      var $liTab = $('.collaboration-testimony-circlelinks .testimony-item');
14246      var $contentTab = $('.collabotarion-testimony-text');
14247
14248      $liTab.click(function (e) {
14249        var tetimony_id = $(e.currentTarget).attr('data-tab-circle');
14250
14251        $liTab.removeClass('active');
14252        $contentTab.removeClass('active');
14253
14254        $(e.currentTarget).addClass('active');
14255        $("#" + tetimony_id).addClass('active');
14256      });
14257    }
14258  }]);
14259
14260  return Collaboration;
14261}();
14262'use strict';
14263
14264var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
14265
14266function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
14267
14268var CompanyTabs = function () {
14269  function CompanyTabs($) {
14270    _classCallCheck(this, CompanyTabs);
14271
14272    this.dropdownMenu = new DropdownMenu($, true);
14273    this.init();
14274  }
14275
14276  _createClass(CompanyTabs, [{
14277    key: 'init',
14278    value: function init() {
14279      this.handleEvents();
14280      this.getHashLocation();
14281    }
14282  }, {
14283    key: 'handleEvents',
14284    value: function handleEvents() {
14285      var _this = this;
14286
14287      this.hashSelected = window.location.href.split("#")[1];
14288
14289      this.$list = $('.company-tabs-container').find('li').children();
14290
14291      this.$list.click(function (e) {
14292        e.preventDefault();
14293        var $li = $(e.target).parent();
14294        var dataJs = $li.attr('data-js');
14295        $li.siblings().removeClass('active');
14296        $('section').removeClass('active');
14297        $('[data-js="' + dataJs + '"]').addClass('active');
14298      });
14299
14300      window.addEventListener('hashchange', function () {
14301        var hash = window.location.hash;
14302        if (!$(hash).is(":visible")) _this.$list.parent().not(".active").find('a').trigger('click');
14303      });
14304
14305      $('a').click(function (e) {
14306        if (e.target.hash && e.target.hash.substring(1)) {
14307          _this.hashSelected = e.target.hash.substring(1);
14308          _this.getHashLocation();
14309        }
14310      });
14311    }
14312  }, {
14313    key: 'getHashLocation',
14314    value: function getHashLocation() {
14315      var hash = '#' + this.hashSelected;
14316      var element = $(hash);
14317
14318      if (element.length > 0) {
14319        if (!element.is(":visible")) {
14320          this.$list.parent().not(".active").trigger('click');
14321        }
14322        if (!element.hasClass('active')) {
14323          element.trigger('click');
14324        }
14325      }
14326    }
14327  }]);
14328
14329  return CompanyTabs;
14330}();
14331'use strict';
14332
14333var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
14334
14335function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
14336
14337var DestinationComponentController = function () {
14338  function DestinationComponentController($) {
14339    _classCallCheck(this, DestinationComponentController);
14340
14341    this.originInput = $('[data-js="origin-id"]');
14342    this.destinationInput = $('[data-js="destination-id"]');
14343    this.currentDaysInput = $('[data-js="current-days"]');
14344    this.promoRoutes = $('[data-js="destination-component"]');
14345    this.cityDestinationElement = $('[data-js="city-destination"]');
14346    this.routes = [];
14347    this.displayedRoutesCount = 0;
14348    this.init();
14349  }
14350
14351  _createClass(DestinationComponentController, [{
14352    key: 'init',
14353    value: function init() {
14354      var _this = this;
14355
14356      if (!this.originInput.length) return;
14357
14358      if ((!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false' )) {
14359        _this.getPromoRoutes();
14360
14361        this.promoRoutes.on("click", ".load-more-button", function () {
14362          return _this.loadMoreRoutes();
14363        });
14364      } else {
14365        this.showRoutesGenericOnScreen();
14366      }
14367    }
14368  }, {
14369    key: 'getPromoRoutes',
14370    value: function getPromoRoutes() {
14371      var _this2 = this;
14372
14373      var destinationId = parseInt(this.destinationInput.val());
14374      var originValues = this.originInput.val().split(',').map(Number);
14375      var currentDays = parseInt(this.currentDaysInput.val());
14376
14377      var body = {
14378        currentDays: currentDays,
14379        routes: [{
14380          destinationId: destinationId,
14381          originList: originValues
14382        }]
14383      };
14384
14385      HttpService.post("getDynamicServiceOfferByDestination", body).then(function (data) {
14386        if (!data.success || !data.result || data.result.length === 0) {
14387          throw new Error("No data returned");
14388        }
14389        _this2.handleGetPromoRoutesSuccess(data.result);
14390      }).catch(function (error) {
14391        console.error("Failed to fetch promo routes:", error);
14392        _this2.promoRoutes.addClass('d-none');
14393      });
14394    }
14395  }, {
14396    key: 'handleGetPromoRoutesSuccess',
14397    value: function handleGetPromoRoutesSuccess(result) {
14398      var placeOrigins = result[0].placeOrigins;
14399      this.routes = placeOrigins;
14400
14401      if (placeOrigins.length > 0) {
14402        this.cityDestinationElement.text(placeOrigins[0].destinationDescription);
14403      } else {
14404        this.promoRoutes.addClass('d-none');
14405      }
14406
14407      this.showRoutesOnScreen(5);
14408    }
14409  }, {
14410    key: 'showRoutesOnScreen',
14411    value: function showRoutesOnScreen(limit) {
14412      var _this3 = this;
14413
14414      var textDe = $('[data-js="text-de"]').val();
14415      var textPara = $('[data-js="text-para"]').val();
14416      var textPreco = $('[data-js="text-preco"]').val();
14417      var textComprar = $('[data-js="text-comprar"]').val();
14418
14419      var colorDe = $('[data-js="color-de"]').val();
14420      var colorPara = $('[data-js="color-para"]').val();
14421      var colorOrigin = $('[data-js="color-origin"]').val();
14422      var colorDestination = $('[data-js="color-destination"]').val();
14423      var colorAPartirDe = $('[data-js="color-a-partir-de"]').val();
14424      var colorPreco = $('[data-js="color-preco"]').val();
14425      var colorBotao = $('[data-js="color-botao"]').val();
14426
14427      var cardsContainer = this.promoRoutes.find('.destination-component-cards .card-content');
14428      cardsContainer.empty();
14429
14430      var totalDisplayed = 0;
14431
14432      this.routes.forEach(function (placeOrigin) {
14433        placeOrigin.routePrices.forEach(function (route) {
14434          if (totalDisplayed < _this3.displayedRoutesCount + limit) {
14435            var cardContent = $('\n          <div class="offer-card-simplify" data-origin-id="' + route.originId + '" data-destination-id="' + placeOrigin.destinationId + '">\n            <div class="offer-card-simplify-container">\n              <div class="content-wrapper">\n                <div class="offer-details">\n                  <div class="info-main">\n                    <div class="departure-info">\n                      <div class="time-location">\n                        <span class="time" style="color:'+ colorDe +';">'+ textDe +':</span>\n                        <span class="location" style="color:'+ colorOrigin +';">' + route.originDescription + '</span>\n                      </div>\n                      <div class="time-location">\n                        <span class="time" style="color:'+ colorPara +';">'+ textPara +':</span>\n                        <span class="location" style="color:'+ colorDestination +';">' + placeOrigin.destinationDescription + '</span>\n                      </div>\n                    </div>\n                    <div class="price-and-button">\n                      <div class="price-info">\n                        <span style="color:'+ colorAPartirDe +';">'+ textPreco +':</span>
14435\n                        <span class="price" style="color:'+ colorPreco +';">R$ ' + route.price.toFixed(2) + '</span>\n                      </div>\n                    </div>\n                    <div class="buy-section">\n                      <a class="buy-button" style="background-color:'+ colorBotao +';" href="' + _this3.getRouteUrl(route, placeOrigin) + '">'+ textComprar +'</a>\n                    </div>\n                  </div>\n                </div>\n              </div>\n            </div>\n          </div>\n        ');
14436            cardsContainer.append(cardContent);
14437            totalDisplayed++;
14438          }
14439        });
14440      });
14441
14442      this.displayedRoutesCount += limit;
14443
14444      var totalRoutes = this.routes.reduce(function (acc, placeOrigin) {
14445        return acc + placeOrigin.routePrices.length;
14446      }, 0);
14447      if (this.displayedRoutesCount < totalRoutes) {
14448        this.promoRoutes.find('.load-more-container').show();
14449      } else {
14450        this.promoRoutes.find('.load-more-container').hide();
14451      }
14452    }
14453  }, {
14454    key: 'showRoutesGenericOnScreen',
14455    value: function showRoutesGenericOnScreen() {
14456      var textDe          = $('[data-js="text-de"]').val()           || "De";
14457      var textPara        = $('[data-js="text-para"]').val()         || "Para";
14458      var textPreco       = $('[data-js="text-preco"]').val()        || "A partir de";
14459      var textComprar     = $('[data-js="text-comprar"]').val()      || "COMPRAR";
14460
14461      var colorDe         = $('[data-js="color-de"]').val();
14462      var colorPara       = $('[data-js="color-para"]').val();
14463      var colorOrigin     = $('[data-js="color-origin"]').val();
14464      var colorDestination= $('[data-js="color-destination"]').val();
14465      var colorAPartirDe  = $('[data-js="color-a-partir-de"]').val();
14466      var colorPreco      = $('[data-js="color-preco"]').val();
14467      var colorBotao      = $('[data-js="color-botao"]').val();
14468
14469      var cardsContainer = this.promoRoutes
14470        .find('.destination-component-cards .card-content');
14471
14472      cardsContainer.empty();
14473
14474      var fakeCard = $(`
14475        <div class="offer-card-simplify">
14476          <div class="offer-card-simplify-container">
14477            <div class="content-wrapper">
14478              <div class="offer-details">
14479                <div class="info-main">
14480
14481                  <div class="departure-info">
14482                    <div class="time-location">
14483                      <span class="time" style="color:${colorDe};">${textDe}:</span>
14484                      <span class="location" style="color:${colorOrigin};">SÃO PAULO - SP</span>
14485                    </div>
14486
14487                    <div class="time-location">
14488                      <span class="time" style="color:${colorPara};">${textPara}:</span>
14489                      <span class="location" style="color:${colorDestination};">RIO DE JANEIRO - RJ</span>
14490                    </div>
14491                  </div>
14492
14493                  <div class="price-and-button">
14494                    <div class="price-info">
14495                      <span style="color:${colorAPartirDe};">${textPreco}:</span>
14496                      <span class="price" style="color:${colorPreco};">R$ 199,90</span>
14497                    </div>
14498                  </div>
14499
14500                  <div class="buy-section">
14501                    <a class="buy-button"
14502                      href="#"
14503                      style="background-color:${colorBotao}; pointer-events:none;">
14504                      ${textComprar}
14505                    </a>
14506                  </div>
14507
14508                </div>
14509              </div>
14510            </div>
14511          </div>
14512        </div>
14513      `);
14514
14515      cardsContainer.append(fakeCard);
14516      this.promoRoutes.find(".load-more-container").hide();
14517    }
14518  }, {
14519    key: 'loadMoreRoutes',
14520    value: function loadMoreRoutes() {
14521      this.showRoutesOnScreen(5);
14522    }
14523  }, {
14524    key: 'getRouteUrl',
14525    value: function getRouteUrl(route, placeOrigin) {
14526      var baseUrl = $('#searchResultPath').val()+'?';
14527      var searchParams = '';
14528
14529      var currentDays = parseInt(this.currentDaysInput.val());
14530      var travelDate = new Date();
14531      travelDate.setDate(travelDate.getDate() + currentDays);
14532
14533      var params = {
14534        data_ida: this.formatDate(travelDate),
14535        origem_id: route.originId,
14536        destino_id: placeOrigin.destinationId,
14537        num_psgr: 1,
14538        num_chda: 0,
14539        num_chds: 0,
14540        deep: true
14541      };
14542
14543      for (var key in params) {
14544        if (key.toString() === 'deep') {
14545          searchParams += key + '=' + params[key];
14546        } else {
14547          searchParams += key + '=' + params[key] + '&';
14548        }
14549      }
14550
14551      return baseUrl + searchParams;
14552    }
14553  }, {
14554    key: 'formatDate',
14555    value: function formatDate(date) {
14556      var day = String(date.getDate()).padStart(2, '0');
14557      var month = String(date.getMonth() + 1).padStart(2, '0');
14558      var year = date.getFullYear();
14559
14560      return '' + day + month + year;
14561    }
14562  }]);
14563
14564  return DestinationComponentController;
14565}();
14566'use strict';
14567
14568var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
14569
14570function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
14571
14572var ContactUs = function () {
14573  function ContactUs($) {
14574    _classCallCheck(this, ContactUs);
14575
14576    this.contentFirstForm = $('[data-js="first-form-contact-us"]');
14577    this.contentSecondForm = $('[data-js="second-form-contact-us"]');
14578    this.firstContainer = $('[data-js="contact-us-first-container"]');
14579    this.secondContainer = $('[data-js="contact-us-second-container"]');
14580    this.formProtocol = $('[data-js="protocol-form"]');
14581    this.formDataUser = $('[data-js="form-contact-us"]');
14582    this.btnNext = $('[data-js="btn-contact-us"]');
14583    this.btnSubmitProtocol = $('[data-js="submit-protocol"]');
14584    this.name = $('[data-js="input-name"]');
14585    this.typeDoc = $('[data-js="type-doc"]');
14586    this.docNumberfield = $('[data-js="doc-number"]');
14587    this.email = $('[data-js="input-email"]');
14588    this.confEmail = $('[data-js="input-email-valid"]');
14589    this.dddField = $('[data-js="ddd"]');
14590    this.phoneField = $('[data-js="phone"]');
14591    this.companyField = $('[data-js="input-container-select-company"]');
14592    this.isCancelForm = $('[data-js="is-cancel-form"]').val() === 'true';
14593    this.docValid = false;
14594    this.emailValid = false;
14595    this.selectCustom = new SelectCustom($);
14596    this.init();
14597  }
14598
14599  _createClass(ContactUs, [{
14600    key: 'init',
14601    value: function init() {
14602
14603      $('[data-js="alert-error-close-menu"]').on('click', function () {
14604        $('[data-js="message-confir-error"]').removeClass('active');
14605        $('[data-js="message-confir-error"]').parent().removeClass('active');
14606        $('.form-content').show();
14607        $('.container-stepper-menu').show();
14608      });
14609
14610      this.hideLocalAutoComplete();
14611      this.hideSteppers();
14612      this.handleContactUs();
14613      this.loadMask();
14614      this.showContactContainers();
14615      this.hideCompanyField();
14616      this.handleCancelForm();
14617    }
14618  }, {
14619    key: 'hideCompanyField',
14620    value: function hideCompanyField() {
14621      this.companyField.hide();
14622    }
14623  }, {
14624    key: 'showContactContainers',
14625    value: function showContactContainers() {
14626      var showCardContactUs = this.firstContainer.attr('data-show');
14627
14628      if (showCardContactUs === 'true') {
14629        this.firstContainer.show();
14630        return;
14631      }
14632
14633      this.firstContainer.hide();
14634      this.secondContainer.removeClass('col-lg-6');
14635    }
14636  }, {
14637    key: 'loadMask',
14638    value: function loadMask() {
14639      var _this = this;
14640
14641      {
14642        var masks = ['000.000.000-009', '00.000.000/0000-00'];
14643        var maskBehavior = function maskBehavior(val) {
14644          return val.replace(/\D/g, '').length <= 11 ? masks[0] : masks[1];
14645        },
14646          cpfCnpjpOptions = {
14647            onKeyPress: function onKeyPress(val, e, field, options) {
14648              field.mask(maskBehavior.apply({}, arguments), options);
14649            }
14650          };
14651
14652        this.docNumberfield.keypress(function (e) {
14653          var keyCode = e.keyCode ? e.keyCode : e.which;
14654          var charStr = String.fromCharCode(keyCode);
14655          var isAlphabetic = new RegExp(/\D/g);
14656          var matchMasks = new RegExp(/(\.)|(\/)|(\-)/g);
14657          if (isAlphabetic.test(charStr) || isAlphabetic.test($(e.target).val().replace(matchMasks, ''))) {
14658            _this.docNumberfield.unmask();
14659          } else {
14660            if ($(e.target).val().length >= 10) {
14661              _this.docNumberfield.mask('000.000.000-00');
14662            }
14663          }
14664        });
14665
14666        this.docNumberfield.on('keydown', function (e) {
14667          var isAlphabetic = new RegExp(/\D/g);
14668          var keyCode = e.keyCode ? e.keyCode : e.which;
14669          var matchMasks = new RegExp(/(\.)|(\/)|(\-)/g);
14670          var valueWithoutMask = $(e.target).val().replace(matchMasks, '');
14671          if (keyCode === 8 || keyCode === 46) {
14672            if (!isAlphabetic.test(valueWithoutMask) && valueWithoutMask.length >= 11) _this.docNumberfield.mask('000.000.000-00'); else _this.docNumberfield.unmask();
14673          }
14674        });
14675
14676        this.phoneField.mask('90000-0000');
14677      }
14678    }
14679  }, {
14680    key: 'handleContactUs',
14681    value: function handleContactUs() {
14682      var _this2 = this;
14683
14684      this.formDataUser.on('keyup', function (event) {
14685        var isFormValid = FormFields.emptyValidation('[data-js="form-contact-us"]') && _this2.emailValid && _this2.docValid;
14686
14687        _this2.btnNext.attr('disabled', !isFormValid);
14688        var keyCode = event.keyCode || event.which;
14689        if (keyCode === Utils.keyCodes.ENTER && !_this2.btnNext.is(':disabled')) {
14690          _this2.btnNext.click();
14691        }
14692
14693        if (isFormValid) return;
14694
14695        $('[data-js="stepper-2"').removeClass('active');
14696        _this2.btnNext.attr('disabled', true);
14697        $('[data-js="item-border-1"]').removeClass('active');
14698      });
14699
14700      this.formProtocol.on('change', function () {
14701        var textAreaRequirement = $('[data-js="protocol-form"]').find('textarea[required]').val();
14702        if (_this2.isCancelForm && _this2.isFormProtocolComplete()) {
14703          if (textAreaRequirement == null || textAreaRequirement.length === 0) {
14704              return;
14705          }
14706          _this2.btnSubmitProtocol.addClass('active');
14707          _this2.btnSubmitProtocol.prop('disabled', false);
14708        } else if (!_this2.isCancelForm) {
14709          if (textAreaRequirement == null || textAreaRequirement.length === 0) {
14710              return;
14711          }
14712          _this2.btnSubmitProtocol.addClass('active');
14713        }
14714      });
14715
14716      this.name.on('input autocompleteclose focusout', function () {
14717        FormFields.validationCaracterName(_this2.name);
14718        FormFields.validateName(_this2.name);
14719      });
14720
14721      this.typeDoc.on('change', function () {
14722        _this2.docNumberfield.removeAttr('disabled');
14723      });
14724
14725      this.docNumberfield.on('autocompleteclose focusout', function (e) {
14726        var defaultDoc = $('[data-js="auto-select-document-type"]');
14727
14728        _this2.docValid = FormFields.isDocumentValid(defaultDoc, _this2.docNumberfield);
14729      });
14730
14731      this.docNumberfield.on('input', function () {
14732        _this2.docValid = false;
14733        _this2.docNumberfield.mask('000.000.000-00');
14734      });
14735
14736      this.email.on('input', function () {
14737        _this2.emailValid = false;
14738      });
14739
14740      $('[data-js="input-date-buy"]').on('click', function () {
14741        $('html, body').animate({ scrollTop: $(window).scrollTop() }, 'fast');
14742      });
14743
14744      this.docNumberfield.on('input', function (e) {
14745        _this2.docNumberfield.val($(e.target).val().replace(/\D/g, ''));
14746      });
14747
14748      this.email.add(this.confEmail).on('autocompleteclose focusout', function () {
14749        _this2.emailValid = FormFields.checkoutEmail(_this2.email.val(), _this2.email);
14750      });
14751
14752      this.dddField.on('input autocompleteclose focusout', function () {
14753        FormFields.validateDDDfield(_this2.dddField);
14754        _this2.dddField.attr('maxlength', 2);
14755        _this2.dddField.unmask();
14756      });
14757
14758      this.phoneField.on('keypress autocompleteclose change', function () {
14759        FormFields.validatePhonefield(_this2.phoneField);
14760        _this2.phoneField.mask('90000-0000');
14761      });
14762
14763      this.btnNext.on('click', function () {
14764        _this2.contentFirstForm.hide();
14765        _this2.contentSecondForm.show();
14766        $('[data-js="stepper-1"]').removeClass('current');
14767        $('[data-js="stepper-2"]').addClass('active current');
14768        $('[data-js="item-border-1"]').addClass('active');
14769      });
14770
14771      $('.link-stepper').on('click', function (e) {
14772        if (!$(e.target).hasClass('active')) return;
14773
14774        $('html, body').animate({ scrollTop: $(window).scrollTop() }, 'fast');
14775        var numberStepper = $(e.target).data('js').replace(/\D/g, '');
14776
14777        $('.item-stepper a').removeClass('current');
14778        $('.container-stepper-register').removeClass('active');
14779
14780        $('[data-js="stepper-' + numberStepper + '"]').addClass('current');
14781        $('[data-js="container-stepper-' + numberStepper + '"]').addClass('active');
14782      });
14783
14784      $('[data-js="stepper-1"]').on('click', function () {
14785        _this2.contentFirstForm.show();
14786        _this2.contentSecondForm.hide();
14787      });
14788
14789      $('[data-js="stepper-2"]').on('click', function (e) {
14790        var isActiveStepper = $(e.currentTarget).hasClass('active');
14791
14792        isActiveStepper ? _this2.btnNext.trigger('click') : '';
14793      });
14794    }
14795  }, {
14796    key: 'hideSteppers',
14797    value: function hideSteppers() {
14798      $('[data-js="stepper-3"], [data-js="item-border-2"]').hide();
14799    }
14800  }, {
14801    key: 'hideLocalAutoComplete',
14802    value: function hideLocalAutoComplete() {
14803      $(document).on('click', function (e) {
14804        if ($(e.target).attr('data-js') !== 'input-local' && $('[data-js="input-local"]').is(':focus')) {
14805          $('[data-js="input-local"]').blur();
14806        }
14807      });
14808    }
14809  }, {
14810    key: 'handleCancelForm',
14811    value: function handleCancelForm() {
14812      if (this.isCancelForm) {
14813        this.btnNext.remove();
14814
14815        $('[data-js="occurrence-place"]').addClass('d-none');
14816        $('[data-js="has-bought"]').parents().eq(2).addClass('d-none');
14817        $('[data-js="date-buy"]').toggleClass('d-none');
14818        $('[data-js="input-date-buy"]').parents().eq(2).addClass('d-none');
14819        $('[data-js="description"]').parents().eq(2).addClass('d-none');
14820        $('[data-js="protocol-file"]').parents().eq(2).addClass('d-none');
14821        $('[data-js="input-date-trip"]').parents().eq(2).removeClass('col-lg-6');
14822      }
14823    }
14824  }, {
14825    key: 'isFormProtocolComplete',
14826    value: function isFormProtocolComplete() {
14827      //check if all protocol fields are filled
14828      var isComplete = true;
14829
14830      this.formProtocol.find('input:visible, select:visible').each(function () {
14831        if ($(this).val() === '') {
14832          isComplete = false;
14833          return false;
14834        }
14835      });
14836
14837      return isComplete;
14838    }
14839  }]);
14840
14841  return ContactUs;
14842}();
14843'use strict';
14844
14845var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
14846
14847function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
14848
14849var MyDataController = function () {
14850  function MyDataController($) {
14851    _classCallCheck(this, MyDataController);
14852
14853    var mock = '{"_name":"José da Silva","_login":"53952057304","_documentNumber":"53952057304","_systemId":null,"_birthDate":"0000-00-00","_email":"[email protected]","_cpf":"00000000000","_optin":false,"_refreshPassword":null,"_areaCode":"00","_phone":"000000000","_company":null,"_registrationCampaign":null,"_paymentToken":null,"_documentType":1,"_phoneType":1,"_genre":null,"_groups":null,"_departament":null,"_id":236,"_totalCount":null,"_isRegistered":false,"_hasDiscount":false,"_seatDeparture":{"_transactionId":null,"_price":0,"_rate":0,"_tax":0,"_other":0,"_insurance":0,"_insurance":0,"_toll":0,"_service":null},"_seatReturn":{"_transactionId":null,"_price":0,"_rate":0,"_tax":0,"_other":0,"_insurance":0,"_insurance":0,"_toll":0,"_service":null},"_seatDepartureConnection":{"_transactionId":null,"_price":0,"_rate":0,"_tax":0,"_other":0,"_insurance":0,"_insurance":0,"_toll":0,"_service":null},"_seatReturnConnection":{"_transactionId":null,"_price":0,"_rate":0,"_tax":0,"_other":0,"_insurance":0,"_insurance":0,"_toll":0,"_service":null},"_type":null}';
14854    if ($('#wcmmodeedit').val() == 'true' && SessionStorage.get('passenger') == null) {
14855      window.sessionStorage.setItem('passenger', mock);
14856    }
14857
14858
14859    this.passenger = new Passenger();
14860    this.passenger.fromJSON(SessionStorage.get('passenger'));
14861    this.greetingsText = $('[data-js="greetings"]');
14862    this.checkboxNews = $('[data-js="newsletter-check"]');
14863    this.checkboxNewsLabel = $('[data-js="newsletter-check-label"]');
14864    this.errorContainer = $('.error-overlay-container');
14865    this.fildsName = $('[data-js="fields-name"]').attr('value') == 'true';
14866    this.fildsBirth = $('[data-js="fields-birth"]').attr('value') == 'true';
14867    this.fildsEmail = $('[data-js="fields-email"]').attr('value') == 'true';
14868    this.fildsEmailValid = $('[data-js="fields-email-valid"]').attr('value') == 'true';
14869    this.fildsPass = $('[data-js="fields-pass"]').attr('value') == 'true';
14870    this.fildsPassValid = $('[data-js="fields-pass-valid"]').attr('value') == 'true';
14871    this.fildsFullPhone = $('[data-js="fields-full-phone"]').attr('value') == 'true';
14872    this.fildsPhoneType = $('[data-js="fields-phone-type"]').attr('value') == 'true';
14873    new MenuMyData($);
14874    this.init();
14875  }
14876
14877  _createClass(MyDataController, [{
14878    key: 'init',
14879    value: function init() {
14880      var _this = this;
14881
14882      if (this.passenger) {
14883        this.removePasswordInputs();
14884        this.handleCheckbox();
14885        this.registerData = new RegisterController($, null, this, function () {
14886          _this.loadUserData();
14887          _this.loadDatePicker();
14888          _this.loadMasks();
14889          _this.loadForm();
14890          _this.selectCustom = new SelectCustom($);
14891          new UserDataRequest($);
14892          _this.handleFiledsDisabled();
14893        });
14894      } else {
14895        if ((!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false')) {
14896          localStorage.setItem("referrer", $(location).attr('href'));
14897          $(location).attr('href', $('#loginPage').val());
14898        }
14899      }
14900      this.isEditPage = true;
14901      SessionStorage.set('isEditPage', this.isEditPage);
14902    }
14903  }, {
14904    key: 'handleFiledsDisabled',
14905    value: function handleFiledsDisabled() {
14906      var passengerValidated = SessionStorage.get('passenger');
14907
14908      if (this.fildsName) $('[data-js="input-name"]').attr("disabled", "true");
14909      if (this.fildsBirth || passengerValidated && passengerValidated._validated) {
14910        $('[data-js="input-birth"]').attr("disabled", "true");
14911      } else {
14912        $('[data-js="input-birth"]').removeAttr("disabled");
14913      }
14914      if (this.fildsEmail) $('[data-js="input-email"]').attr("disabled", "true");
14915      if (this.fildsEmailValid) $('[data-js="input-email-valid"]').attr("disabled", "true");
14916      if (this.fildsPass) $('[data-js="input-pass"]').attr("disabled", "true");
14917      if (this.fildsPassValid) $('[data-js="input-pass-valid"]').attr("disabled", "true");
14918      if (this.fildsPhoneType) $('[data-js="input-phone-type"]').attr("disabled", "true");
14919      if (this.fildsFullPhone) $('[data-js="input-full-phone"]').attr("disabled", "true");
14920    }
14921  }, {
14922    key: 'loadUserData',
14923    value: function loadUserData() {
14924      var blankText = this.greetingsText.text();
14925      this.greetingsText.text(blankText.replace('#user', Utils.getFirstName(this.passenger.name)));
14926      this.registerData.loadUserData(this.passenger);
14927    }
14928  }, {
14929    key: 'handleCheckbox',
14930    value: function handleCheckbox() {
14931      if (this.passenger.optin) {
14932        this.checkboxNewsLabel.hide();
14933      }
14934    }
14935  }, {
14936    key: 'loadMasks',
14937    value: function loadMasks() {
14938      switch (this.registerData.inputDocType.val()) {
14939        case "1":
14940          this.registerData.inputDocNumber.attr('minlength', 14);
14941          this.registerData.inputDocNumber.mask('000.000.000-00');
14942          break;
14943        case "2":
14944          this.registerData.inputDocNumber.attr('minlength', 18);
14945          this.registerData.inputDocNumber.mask('00.000.000/0000-00');
14946          break;
14947        case "3":
14948          this.registerData.inputDocNumber.attr('minlength', '');
14949          this.registerData.inputDocNumber.unmask();
14950        default:
14951          break;
14952      }
14953      switch (this.registerData.inputPhoneType.val()) {
14954        case "0":
14955          this.registerData.inputFullPhone.mask("+55 (00) 00000-0000");
14956          break;
14957        case "1":
14958          this.registerData.inputFullPhone.mask("+55 (00) 00000-0000");
14959        default:
14960          break;
14961      }
14962    }
14963  }, {
14964    key: 'loadDatePicker',
14965    value: function loadDatePicker() {
14966      this.registerData.inputBirth.mask('00/00/0000');
14967    }
14968  }, {
14969    key: 'loadForm',
14970    value: function loadForm() {
14971      this.registerData.btnRegister.text('Salvar dados');
14972      this.registerData.enableForm();
14973    }
14974  }, {
14975    key: 'removePasswordInputs',
14976    value: function removePasswordInputs() {
14977      $('[data-js="password-row"]').remove();
14978    }
14979  }, {
14980    key: 'saveUserStorage',
14981    value: function saveUserStorage(data) {
14982      var returnedPassenger = this.parsePassenger(data);
14983      SessionStorage.set('passenger', returnedPassenger);
14984    }
14985  }, {
14986    key: 'sendEditData',
14987    value: function sendEditData(passenger) {
14988      var _this2 = this;
14989
14990      var body = passenger.serviceJSON;
14991      // required fields to update
14992      body.id = this.passenger.id;
14993
14994      var headers = {
14995        'Authorization': '' + SessionStorage.get('jca_token'),
14996        'channel': Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform)
14997      };
14998
14999      HttpService.put('editUser', body, headers).then(function (data) {
15000        $('.text-captura-photo-hide').hide();
15001        LoaderService.hide();
15002        _this2.saveUserStorage(data);
15003        Utils.scrollTop();
15004        AlertConfirmation.showAEM('data-js="alert-profile-edited"');
15005        $('.container-capture, .register-wrapper, .container-capture-edit').addClass('updated-successfully')
15006        if (data.optin) _this2.checkboxNewsLabel.hide();
15007      }).catch(function (error) {
15008        LoaderService.hide();
15009        _this2.handleErrorMessage(error);
15010
15011        // Analytics - Triggers an event when there
15012        _satellite.track('serviceError', { // Service Error
15013          serviceType: 'editUser',
15014          statusCode: error.status,
15015          messageError: error.responseJSON.message.toUpperCase()
15016        });
15017      });
15018    }
15019  }, {
15020    key: 'handleErrorMessage',
15021    value: function handleErrorMessage(error) {
15022      var statusMailCpf = $('[data-js="msg-status-return"]').attr('data-status-email-cpf-already-registred');
15023      var statusCpf = $('[data-js="msg-status-return"]').attr('data-status-cpf-already-registred');
15024      var statusMail = $('[data-js="msg-status-return"]').attr('data-status-email-already-registred');
15025      var statusGeneric = $('[data-js="msg-status-return"]').attr('data-status-generic');
15026
15027      statusMailCpf = statusMailCpf ? statusMailCpf : 'CPF e email já cadastrado!';
15028      statusCpf = statusCpf ? statusCpf : 'CPF já cadastrado!';
15029      statusMail = statusMail ? statusMail : 'Email já cadastrado!';
15030      statusGeneric = statusGeneric ? statusGeneric : 'Houve um problema. Tente novamente.';
15031
15032      if (error.status != 400) {
15033        Alert.show(statusGeneric);
15034        return;
15035      }
15036
15037      try {
15038        var message = error.responseJSON.validations.reduce(function (acc, item) {
15039          return acc += item.message + '</br>';
15040        }, '');
15041
15042        switch (true) {
15043          case message.includes('CPF') && message.includes('e-mail'):
15044            Alert.show(statusMailCpf);
15045            break;
15046          case message.includes('CPF'):
15047            Alert.show(statusCpf);
15048            break;
15049          case message.includes('Email'):
15050            Alert.show(statusMail);
15051            break;
15052          default:
15053            Alert.show(statusGeneric);
15054            break;
15055        }
15056      } catch (e) {
15057        Alert.show(statusGeneric);
15058      }
15059    }
15060  }, {
15061    key: 'showMessage',
15062    value: function showMessage() {
15063      Utils.scrollTop();
15064      Alert.show('Dados editados com sucesso');
15065    }
15066  }, {
15067    key: 'handleDocTypePassengerSessionStorageLogin',
15068    value: function handleDocTypePassengerSessionStorageLogin(data) {
15069      var docType = parseInt($('[data-js="input-doc-type"]').val());
15070
15071      if (docType == 1) {
15072        return data.cpf;
15073      } else {
15074        return data.cnpj;
15075      }
15076    }
15077  }, {
15078    key: 'parsePassenger',
15079    value: function parsePassenger(data) {
15080      var passenger = new Passenger();
15081      var document = this.handleDocTypePassengerSessionStorageLogin(data);
15082      var addresses = data.addresses.length > 0 ? Utils.parseAddress(data.addresses[0]) : null;
15083
15084      passenger.name = String(data.name + ' ' + data.familyName).trim();
15085      passenger.login = data.login;
15086      passenger.image = data.image;
15087      passenger.birthDate = data.birthDate != null ? DateFormatter.extractDate(data.birthDate) : null;
15088      passenger.email = data.email;
15089      passenger.cpf = data.cpf;
15090      passenger.cnpj = data.cnpj;
15091      passenger.documentNumber = data.cpf;
15092      passenger.optin = data.optin;
15093      passenger.areaCode = data.areaCode;
15094      passenger.phone = data.phone;
15095      passenger.phoneType = data.phoneType;
15096      passenger.id = data.id;
15097      passenger.addresses = addresses;
15098      passenger.validated = data.validated;
15099      return passenger;
15100    }
15101  }]);
15102
15103  return MyDataController;
15104}();
15105'use strict';
15106
15107var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
15108
15109function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
15110
15111var ExistsWalletRegister = function () {
15112  function ExistsWalletRegister($) {
15113    _classCallCheck(this, ExistsWalletRegister);
15114
15115    this.buttonCreate = $('[data-js="button-create"]');
15116    this.init();
15117  }
15118
15119  _createClass(ExistsWalletRegister, [{
15120    key: 'init',
15121    value: function init() {
15122      this.handleAccount();
15123    }
15124  }, {
15125    key: 'handleAccount',
15126    value: function handleAccount() {
15127      var walletExists = SessionStorage.get('walletExists');
15128      var accountExists = SessionStorage.get('accountExists');
15129      var userWallet = SessionStorage.get('user_wallet');
15130      var isLoggedIn = SessionStorage.get('isLoggedIn'); // Assuming there's a flag for login status
15131
15132      this.buttonCreate.on('click', function () {
15133        if (accountExists === false) {
15134          $(location).attr('href', i18n('register_giro_page'));
15135        } else if (accountExists === true && walletExists === false) {
15136          $(location).attr('href', i18n('register_terms_page'));
15137        } else if (accountExists === true && walletExists === true && !isLoggedIn) {
15138          $(location).attr('href', $("#walletLoginPagePath").val());
15139        }
15140      });
15141    }
15142  }]);
15143
15144  return ExistsWalletRegister;
15145}();
15146"use strict";
15147
15148var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
15149
15150function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
15151
15152var FreedomCards = function () {
15153  function FreedomCards() {
15154    _classCallCheck(this, FreedomCards);
15155    this.init();
15156    this.carouselInit();
15157    this.applyPositionLeftArrow();
15158  }
15159  _createClass(FreedomCards, [{
15160    key: "init",
15161    value: function init() {
15162      this.toggleTabs();
15163      this.refreshCarousel();
15164      this.handleDotsClick();
15165      this.loadTabStyles();
15166      this.tealeafSlick();
15167    }
15168  }, {
15169    key: "refreshCarousel",
15170    value: function refreshCarousel(e) {
15171      var cardsCarousel;
15172      if (e) {
15173        var el = $(e.currentTarget).closest('.freedom-cards-tab-container').data('js');
15174        cardsCarousel = $('[data-js="' + el + '"]').siblings();
15175      } else {
15176        cardsCarousel = $(".freedom-cards-carousel");
15177      }
15178
15179      cardsCarousel.each(function () {
15180        var $carousel = $(this);
15181        var $cardsCarousel = $('.carousel-cards', $carousel);
15182        var slidesShow = Math.min(2, $cardsCarousel.length);
15183        this.slickProperties = {
15184          dots: true,
15185          arrows: true,
15186          infinite: true,
15187          slidesToShow: 2,
15188          slidesToScroll: 2,
15189          accessibility: true,
15190          responsive: [{
15191            breakpoint: 950,
15192            settings: {
15193              slidesToShow: slidesShow,
15194              slidesToScroll: slidesShow,
15195              dots: $cardsCarousel.length > 2
15196            }
15197          }, {
15198            breakpoint: 768,
15199            settings: {
15200              slidesToShow: 1,
15201              slidesToScroll: 1
15202            }
15203          }]
15204        };
15205        $carousel.slick(this.slickProperties);
15206      });
15207    }
15208  }, {
15209    key: "carouselInit",
15210    value: function carouselInit() {
15211      $("ul.tabs-freedom-cards").slick({
15212        slidesToShow: 5,
15213        accessibility: true,
15214        variableWidth: true,
15215        infinite: false,
15216        arrows: false,
15217        responsive: [{
15218          breakpoint: 950,
15219          settings: {
15220            slidesToShow: 1,
15221            slidesToScroll: 1,
15222            variableWidth: false,
15223            infinite: true,
15224            dots: true,
15225            arrows: true
15226          }
15227        }]
15228      });
15229
15230      $("ul.tabs-freedom-cards").on('afterChange', function (e) {
15231        var $containerTabs = $(e.currentTarget).closest('.freedom-cards-tab-container').data('js');
15232        $('[data-js="' + $containerTabs + '"]').find('.slick-current').click();
15233      });
15234      $("ul.tabs-freedom-cards").on('swipe', function () {
15235        var $containerTabs = $(e.currentTarget).closest('.freedom-cards-tab-container').data('js');
15236        $('[data-js="' + $containerTabs + '"]').find('.slick-current').click();
15237      });
15238    }
15239  }, {
15240    key: "loadTabStyles",
15241    value: function loadTabStyles() {
15242      var carouselTabContainers = $('.freedom-cards-tab-container');
15243      carouselTabContainers.each(function (_, el) {
15244        var colorTab = $(el).data('color');
15245        var borderColorTab = $(el).data('border-color');
15246        $(el).find('.tab-cards.active').css({
15247          "color": colorTab,
15248          "border-color": borderColorTab
15249        });
15250      });
15251    }
15252  }, {
15253    key: "handleDotsClick",
15254    value: function handleDotsClick() {
15255      //AEM CUSTOM FUNCITON --> Used to change slick point colors
15256      this.slickDotsColors = $('.freedom-cards-container');
15257      var dotsInactiveColor = $('[data-js="dotsInactiveColor"]').val();
15258      var dotsActiveColor = $('[data-js="dotsActiveColor"]').val();
15259      this.slickDotsColors.append($('<style>.freedom-cards-container .freedom-cards-main .freedom-cards-tab-container .slick-dots li { background-color: ' + dotsInactiveColor + ' !important } .freedom-cards-container .freedom-cards-main .freedom-cards-tab-container .slick-dots li.slick-active { background-color: ' + dotsActiveColor + ' !important} .freedom-cards-container .freedom-cards-main .freedom-cards-carousel .slick-dots li { background-color: ' + dotsInactiveColor + '}   .freedom-cards-container .freedom-cards-main .freedom-cards-carousel .slick-dots li.slick-active { background-color: ' + dotsActiveColor + '};</style>'));
15260    }
15261  }, {
15262    key: "toggleTabs",
15263    value: function toggleTabs() {
15264      var _this = this;
15265      var $liTab = $('ul.tabs-freedom-cards li');
15266      var $contentTab = $('.freedom-cards-carousel');
15267      $liTab.click(function (e) {
15268        _this.loadTabStyles();
15269        var $containerTabs = $(e.currentTarget).closest('.freedom-cards-tab-container').data('js');
15270        var liTabs = $('[data-js="' + $containerTabs + '"]').find('li.tab-cards');
15271        var tab_id = $(e.currentTarget).attr('data-tab');
15272
15273        // AEM Custom Colors
15274        var colorTab = $('[data-js="' + $containerTabs + '"]').data('color');
15275        var borderColorTab = $('[data-js="' + $containerTabs + '"]').data('border-color');
15276        var colorDeactivated = $('[data-js="' + $containerTabs + '"]').data('color-desactive');
15277        var brothers = $('[data-js="' + $containerTabs + '"]').siblings();
15278
15279        if (brothers.length > 1) {
15280          brothers.removeClass('active');
15281          brothers.slick('unslick');
15282        }
15283
15284        liTabs.removeClass('active');
15285        $(e.currentTarget).addClass('active').css({
15286          "color": colorTab,
15287          "border-bottom": '3px solid ' + borderColorTab
15288        }).siblings().css({
15289          "color": colorDeactivated,
15290          "border": "none"
15291        });
15292        $("#" + tab_id).addClass('active');
15293        _this.refreshCarousel(e);
15294      });
15295    }
15296  }, {
15297    key: "applyPositionLeftArrow",
15298    value: function applyPositionLeftArrow() {
15299      var idTable = $('.tab-cards.active').attr('data-tab');
15300      var elIdContent = $('#' + idTable);
15301
15302      if (Utils.getWindowSize().width >= 950) {
15303        var marginSize = elIdContent.find(".slick-dots li").css('margin');
15304        var liWidth = elIdContent.find(".slick-dots li:visible").width() + +marginSize.replace(/\D/g, '');
15305        var liLength = elIdContent.find(".slick-dots li:visible").length;
15306        var totalSize = liWidth * liLength + 140;
15307
15308        elIdContent.find('.slick-next.slick-arrow').css('left', totalSize + 'px');
15309      }
15310    }
15311  }, {
15312    key: "tealeafSlick",
15313    value: function tealeafSlick() {
15314      $('.slick-prev').each(function (idx, el) {
15315        $(el).attr('id', "slick-prev-" + idx);
15316      });
15317      $('.slick-next').each(function (idx, el) {
15318        $(el).attr('id', "slick-next-" + idx);
15319      });
15320    }
15321  }]);
15322  return FreedomCards;
15323}();
15324'use strict';
15325
15326var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
15327
15328function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
15329
15330var FrequentPassengerController = function () {
15331  function FrequentPassengerController($) {
15332    _classCallCheck(this, FrequentPassengerController);
15333
15334    this.frequentPassengerCardList = $('[data-js="frequent-passenger-card-list"]');
15335    this.inputBirth = $('[data-js="input-date-child-add-frequent-passenger"]');
15336    this.inputDocType = $('[data-js="input-doc-type"]');
15337    this.inputName = $('[data-js="input-name-add-frenquent-passenger"]');
15338    this.inputDocAddPassenger = $('[data-js="input-document-number-add-frequent-passenger"]');
15339    this.frequentPassengerAttrAem = $('[data-js="frequent-passenger-attr-aem"]');
15340    this.frequentPassengerAlert = $('[data-js="frequent-passenger-alert"]');
15341    this.msgFrequentPassengerAlert = $('[data-js="msg-frequent-passenger"]');
15342    this.closeFrequentPassengerAlert = $('[data-js="close-msg-frequent-passenger"]');
15343    this.oldValuesFrequentPassenger = {};
15344    this.currentValuesFrequentPassenger = {};
15345    this.listFrequentPassengers = [];
15346    this.frequentPassengers = [];
15347    this.init();
15348  }
15349
15350  _createClass(FrequentPassengerController, [{
15351    key: 'init',
15352    value: function init() {
15353      var _this = this;
15354
15355      this.getFrequentPassengers(function () {
15356        _this.loadMasks();
15357        _this.listenForm();
15358      });
15359    }
15360  }, {
15361    key: 'getFrequentPassengers',
15362    value: function getFrequentPassengers(callback) {
15363      var _this2 = this;
15364
15365      var headers = {
15366        'Authorization': '' + SessionStorage.get('jca_token')
15367      };
15368
15369      LoaderService.show();
15370      HttpService.get('returnfrequentpassengers', headers).then(function (data) {
15371        LoaderService.hide();
15372        _this2.listFrequentPassengers = data.result;
15373
15374        if (!data.result) {
15375          _this2.showNoMessageError();
15376          $('[data-js="frequent-passenger-card-list"]').removeClass('active');
15377          callback();
15378          return;
15379        }
15380
15381        _this2.frequentPassengers = data.result;
15382        _this2.loadFrequentPassengersCardList(data.result);
15383        _this2.removeNoMessageError();
15384        callback();
15385      }).catch(function (err) {
15386        LoaderService.hide();
15387        console.error(err);
15388        callback();
15389      });
15390    }
15391  }, {
15392    key: 'showFrequentPassengerAlert',
15393    value: function showFrequentPassengerAlert(msg) {
15394      this.msgFrequentPassengerAlert.text(msg);
15395      this.frequentPassengerAlert.addClass('active');
15396    }
15397  }, {
15398    key: 'hideFrequentPassengerAlert',
15399    value: function hideFrequentPassengerAlert() {
15400      this.frequentPassengerAlert.removeClass('active');
15401    }
15402  }, {
15403    key: 'showNoMessageError',
15404    value: function showNoMessageError() {
15405      $('.frequent-passenger-no-message-container').addClass('active');
15406    }
15407  }, {
15408    key: 'removeNoMessageError',
15409    value: function removeNoMessageError() {
15410      $('.frequent-passenger-no-message-container').removeClass('active');
15411    }
15412  }, {
15413    key: 'loadFrequentPassengersCardList',
15414    value: function loadFrequentPassengersCardList(frequentPassengerList) {
15415      var _this3 = this;
15416
15417      var cardFrequentPassenger = void 0;
15418      $('[data-js="frequent-passenger-card-list"]').addClass('active').empty();
15419
15420      frequentPassengerList.forEach(function (el, index) {
15421        cardFrequentPassenger = '\n      <div class="frequent-passenger-card" data-js="frequent-passenger-card-' + index + '" data-type="' + el.typePax + '" data-id="' + el.id + '">\n          <form class="form-frequent-passenger px-0" data-js="form-frequent-passenger-' + index + '" aria-label="form frequent passenger">\n            <div class="row g-0">
15421\n              <div class="col-md-7 col-lg-12 col-xl-7 col-12 pe-md-2 pe-0">\n                <div class="field mt-0">\n                  <div class="input-container d-flex align-items-center">\n                    <label for="input-name-' + index + '" class="d-none"> - </label>\n                    <input id="input-name-' + index + '" class="focusable" title="Nome completo." type="text" data-js="input-name-frequent-passenger-' + index + '" placeholder="Nome completo" required disabled/>\n                  </div>\n                  <div class="tips">\n                    <span class="tip">Insira o nome completo</span>\n                  </div>\n                </div>\n              </div>\n\n              <div class="col-md-5 col-lg-12 col-xl-5 col-12 d-flex justify-content-around ps-md-2 ps-0 mt-3 mt-xl-0 mt-md-0 mt-lg-2 px-2 px-md-0">\n                <div class="custom-control custom-checkbox mt-0 d-flex align-items-center">\n                  <input id="underage-' + index + '" class="underage-check-card custom-control-input" data-js="underage-' + index + '" type="checkbox"/>\n                  <label class="custom-control-label" for=\'underage-' + index + '\'> Menor de idade </label>\n                </div>\n\n                <button type="button" class="edit-frequent-passenger d-flex align-items-center" id="btn-frequent-passenger-edit-' + index + '" data-js="btn-frequent-passenger-edit-' + index + '">\n                  <span class="jca-ico-edit"></span>\n                  Editar\n                </button>\n                \n                <button id="btn-remove-frequent-passenger-' + index + '" class="remove-frequent-passenger d-flex align-items-center" type="button" data-bs-toggle="modal" data-bs-target="#cancel-frequent-passenger-modal" data-js="btn-remove-frequent-passenger-' + index + '">\n                  <span class="jca-ico-trash"></span>\n                  Remover\n                </button>\n              </div>\n            </div>\n            <div class="row g-0">\n              <div class="col-md-6 col-12 pe-md-2 pe-0">\n                <div class="field">\n                  <div class="select-custom focusable">\n                    <label for="input-frequent-passenger-document-' + index + '" class="d-none"> - </label>\n                    <select id="input-frequent-passenger-document-' + index + '" name="input-frequent-passenger-document-\'' + index + '\'" data-js=\'input-frequent-passenger-document-' + index + '\' required disabled>\n                      <option class="select-option" id="doc-regular-' + index + '" value=\'REGULAR\' selected disabled> ESCOLHA O TIPO DE DOCUMENTO </option>\n                      <option class="select-option" id="doc-cpf-' + index + '" value=\'CPF\'>CPF</option>\n                      <option class="select-option" id="doc-rg-' + index + '" value=\'RG\'>RG</option>\n                      <option class="select-option" id="doc-birth-certificate-' + index + '" value=\'DECLARACAO\'>DECLARACAO DE NASCIDO VIVO</option>\n                    </select>\n                  </div>\n                </div>\n              </div>\n              <div class="col-md-6 col-12 ps-md-2 mt-2 mt-md-0 ps-0 d-md-flex d-block justify-content-between align-items-baseline">\n                <div class="field pe-md-2 pe-0 width-60">\n                  <div class="input-container d-flex">\n                    <label for="input-document-number-frequent-passenger-' + index + '" class="d-none"> - </label>\n                    <input id="input-document-number-frequent-passenger-' + index + '" class="focusable" title="N\xFAmero de documento" type="text" data-js="input-document-number-frequent-passenger-' + index + '" placeholder="N\xFAmero documento" value="' + el.document + '" required disabled/>\n                  </div>\n                  <div class="tips">\n                    <span class="tip">\'Insira o documento\'</span>\n                  </div>\n                </div>\n\n                <div class="field ps-md-2 ps-0 width-40 mt-4 mt-md-0">\n                  <div class="input-container d-flex">\n                    <label for="input-date-child-frequent-passenger-' + index + '" class="d-none"> - </label>\n                    <input id="input-date-child-frequent-passenger-' + index + '" class="focusable pe-3 ' + (el.typePax === 'ADULTO' ? 'd-none' : '') + '" title="Data de nascimento" type="text" data-js="input-date-child-frequent-passenger-' + index + '" placeholder="00/00/0000" required disabled/>\n                  </div>\n                  <div class="tips">
15421\n                    <span class="tip">\'Insira uma data v\xE1lida\'</span>\n                  </div>\n                </div>\n              </div>\n            </div>\n\n            <div class="row-custom edit-container-frequent-passenger mt-4" data-js="edit-container-frequent-passenger-' + index + '">\n              <button class="focusable btn-edit-frequent-passenger" id="btn-edit-frequent-passenger-' + index + '" type=\'button\' data-js=\'btn-edit-frequent-passenger-' + index + '\' disabled>\n                Salvar dados\n              </button>\n              <a class="cancel-edit-frequent-passenger" href=\'javascript:void(0)\' data-js="cancel-edit-frequent-passenger-' + index + '" id="btn-cancel-' + index + '"> Cancelar </a>\n            </div>\n          </form>\n        </div>\n      ';
15422
15423        var getBirthDate = function getBirthDate() {
15424          if (el.typePax !== 'ADULTO') {
15425            var birthExtractDate = DateFormatter.extractDate(el.birthDate);
15426            var birthDate = DateFormatter.reverseDate(birthExtractDate);
15427
15428            $('[data-js="input-date-child-frequent-passenger-' + index + '"]').val(birthDate);
15429            $('[data-js="underage-' + index + '"]').trigger('click');
15430          } else {
15431            $('[data-js="input-date-child-frequent-passenger-' + index + '"]').addClass('d-none');
15432          }
15433
15434          $('[data-js="underage-' + index + '"]').attr('disabled', true);
15435        };
15436
15437        var completePassengerData = function completePassengerData() {
15438          var selectDoc = $('[data-js="input-frequent-passenger-document-' + index + '"]');
15439          var typeDocument = el.typeDoc !== 'DECLARACAO' ? el.typeDoc : 'DECLARACAO DE NASCIDO VIVO';
15440
15441          $('[data-js="input-document-number-frequent-passenger-' + index + '"]').val(el.document);
15442          $('[data-js="input-name-frequent-passenger-' + index + '"]').val(el.firstName + ' ' + el.lastName);
15443          _this3.selectCustom.selectDefault(selectDoc, typeDocument);
15444          selectDoc.next().removeClass('same-as-selected');
15445          getBirthDate();
15446        };
15447
15448        _this3.frequentPassengerCardList.append(cardFrequentPassenger);
15449        _this3.selectCustom = new SelectCustom($);
15450        completePassengerData();
15451        _this3.loadMasks();
15452        _this3.handleFrequentPassenger(index);
15453      });
15454    }
15455  }, {
15456    key: 'editFrequentPassengerCard',
15457    value: function editFrequentPassengerCard(index) {
15458      $('[data-js="edit-container-frequent-passenger-' + index + '"]').addClass('active');
15459      $('[data-js="form-frequent-passenger-' + index + '"]').find('input[disabled], select[disabled]').attr('disabled', false);
15460      $('[data-js="form-frequent-passenger-' + index + '"]').find('.select-selected').removeClass('disabled');
15461
15462      this.getOldValues(index);
15463      this.listenFrequentPassengerCardToEdit(index);
15464    }
15465  }, {
15466    key: 'listenFrequentPassengerCardToEdit',
15467    value: function listenFrequentPassengerCardToEdit(index) {
15468      var _this4 = this;
15469
15470      $('[data-js="underage-' + index + '"]').on('change', function () {
15471        _this4.handleBtnSubmitEditFrequentPassenger(index);
15472      });
15473
15474      $('[data-js="form-frequent-passenger-' + index + '"]').find('input[required]').on('input', function () {
15475        _this4.handleBtnSubmitEditFrequentPassenger(index);
15476      });
15477
15478      $('[data-js="input-document-number-frequent-passenger-' + index + '"]').on('input', function (e) {
15479        _this4.validateDocumentNumber($(e.target));
15480      });
15481
15482      $('[data-js="input-date-child-frequent-passenger-' + index + '"]').on('input', function (e) {
15483        _this4.isDateBirthValid($(e.target));
15484      });
15485
15486      $('[data-js="underage-' + index + '"]').on('click', function () {
15487        $('[data-js="form-frequent-passenger-' + index + '"]').find('input[required]').trigger('input');
15488      });
15489    }
15490  }, {
15491    key: 'handleBtnSubmitEditFrequentPassenger',
15492    value: function handleBtnSubmitEditFrequentPassenger(index) {
15493      var isFormValid = this.isFormValidFrequentPassengerCardToEdit(index) && this.isChangeFrequentPassengerToEdit(index);
15494
15495      isFormValid ? $('[data-js="btn-edit-frequent-passenger-' + index + '"]').attr('disabled', false) : $('[data-js="btn-edit-frequent-passenger-' + index + '"]').attr('disabled', true);
15496    }
15497  }, {
15498    key: 'isChangeFrequentPassengerToEdit',
15499    value: function isChangeFrequentPassengerToEdit(index) {
15500      this.currentValuesFrequentPassenger = {
15501        name: $('[data-js="input-name-frequent-passenger-' + index + '"]').val(),
15502        document: $('[data-js="input-document-number-frequent-passenger-' + index + '"]').val(),
15503        birthDate: $('[data-js="input-date-child-frequent-passenger-' + index + '"]').val(),
15504        typeDoc: $('[data-js="input-frequent-passenger-document-' + index + '"]').val(),
15505        isChild: $('[data-js="underage-' + index + '"]').is(':checked')
15506      };
15507
15508      return !Utils.isObjectEquivalent(this.currentValuesFrequentPassenger, this.oldValuesFrequentPassenger);
15509    }
15510  }, {
15511    key: 'isFormValidFrequentPassengerCardToEdit',
15512    value: function isFormValidFrequentPassengerCardToEdit(index) {
15513      var _this5 = this;
15514
15515      var specificValidation = false;
15516
15517      $('[data-js="form-frequent-passenger-' + index + '"]').find('input[required]').each(function (_, el) {
15518        if ($(el).is(':visible')) {
15519          switch ($(el).attr('data-js')) {
15520            case 'input-name-frequent-passenger-' + index:
15521              specificValidation = _this5.validateName($(el));
15522              break;
15523            case 'input-document-number-frequent-passenger-' + index:
15524              specificValidation = _this5.validateDocumentNumber($(el));
15525              break;
15526            case 'input-date-child-frequent-passenger-' + index:
15527              specificValidation = _this5.isDateBirthValid($(el));
15528              break;
15529            default:
15530              break;
15531          }
15532
15533          if (!specificValidation) return false;
15534        }
15535      });
15536      return specificValidation;
15537    }
15538  }, {
15539    key: 'getOldValues',
15540    value: function getOldValues(index) {
15541      this.oldValuesFrequentPassenger = {
15542        name: $('[data-js="input-name-frequent-passenger-' + index + '"]').val(),
15543        isChild: $('[data-js="underage-' + index + '"]').is(':checked'),
15544        typeDoc: $('[data-js="input-frequent-passenger-document-' + index + '"]').val(),
15545        document: $('[data-js="input-document-number-frequent-passenger-' + index + '"]').val(),
15546        birthDate: $('[data-js="input-date-child-frequent-passenger-' + index + '"]').val()
15547      };
15548    }
15549  }, {
15550    key: 'cancelEditFrequentPassengerCard',
15551    value: function cancelEditFrequentPassengerCard(index) {
15552      this.loadOldValuesFrequentPassenger(index);
15553      $('[data-js="edit-container-frequent-passenger-' + index + '"]').removeClass('active');
15554      $('[data-js="form-frequent-passenger-' + index + '"]').find('input[required], select[required]').attr('disabled', true);
15555      $('[data-js="form-frequent-passenger-' + index + '"]').find('.select-selected').addClass('disabled');
15556      this.oldValuesFrequentPassenger = {};
15557    }
15558  }, {
15559    key: 'loadOldValuesFrequentPassenger',
15560    value: function loadOldValuesFrequentPassenger(index) {
15561      var _oldValuesFrequentPas = this.oldValuesFrequentPassenger,
15562        name = _oldValuesFrequentPas.name,
15563        typeDoc = _oldValuesFrequentPas.typeDoc,
15564        document = _oldValuesFrequentPas.document,
15565        birthDate = _oldValuesFrequentPas.birthDate,
15566        isChild = _oldValuesFrequentPas.isChild;
15567
15568      var $checkIsChild = $('[data-js="underage-' + index + '"]');
15569
15570      $('[data-js="input-name-frequent-passenger-' + index + '"]').val(name);
15571      this.selectCustom.selectDefault($('[data-js="input-frequent-passenger-document-' + index + '"]'), typeDoc);
15572      $('[data-js="input-document-number-frequent-passenger-' + index + '"]').val(document);
15573      $('[data-js="input-date-child-frequent-passenger-' + index + '"]').val(birthDate).mask('99/99/9999');
15574
15575      if (isChild !== $checkIsChild.is(':checked')) $checkIsChild.trigger('click');
15576    }
15577  }, {
15578    key: 'closeEditFrequentPassengerAllCards',
15579    value: function closeEditFrequentPassengerAllCards() {
15580      $('[data-js^="edit-container-frequent-passenger"]').removeClass('active');
15581      $('[data-js^="form-frequent-passenger"]').find('input[required], select[required]').attr('disabled', true);
15582      $('[data-js^="form-frequent-passenger"]').find('.select-selected').addClass('disabled');
15583    }
15584  }, {
15585    key: 'handleFrequentPassenger',
15586    value: function handleFrequentPassenger(index) {
15587      var _this6 = this;
15588
15589      $('[data-js="btn-frequent-passenger-edit-' + index + '"]').on('click', function (e) {
15590        var $btnEdit = $('[data-js="btn-frequent-passenger-edit-' + index + '"]');
15591
15592        if ($btnEdit.hasClass('active')) {
15593          $('[data-js="cancel-edit-frequent-passenger-' + index + '"]').trigger('click');
15594          return;
15595        }
15596
15597        _this6.closeEditFrequentPassengerAllCards();
15598        _this6.editFrequentPassengerCard(index);
15599        $btnEdit.toggleClass('active');
15600      });
15601
15602      $('[data-js="cancel-edit-frequent-passenger-' + index + '"]').on('click', function () {
15603        _this6.cancelEditFrequentPassengerCard(index);
15604        $('[data-js^="btn-frequent-passenger-edit"]').removeClass('active');
15605      });
15606
15607      $('[data-js="btn-remove-frequent-passenger-' + index + '"]').on('click', function () {
15608        $('[data-js="cancel-passenger"]').attr('data-index', index);
15609      });
15610
15611      $('[data-js="btn-edit-frequent-passenger-' + index + '"]').on('click', function () {
15612        _this6.editFrequentPassenger(index);
15613      });
15614
15615      $('[data-js="underage-' + index + '"]').on('click', function (e) {
15616        if ($(e.target).is(':checked')) $('[data-js="input-date-child-frequent-passenger-' + index + '"]').removeClass('d-none'); else $('[data-js="input-date-child-frequent-passenger-' + index + '"]').addClass('d-none');
15617      });
15618    }
15619  }, {
15620    key: 'openFrequentPassengerCardAdd',
15621    value: function openFrequentPassengerCardAdd() {
15622      $('[data-js="add-card-frequent-passenger"]').addClass('active');
15623      this.disableBtnAddFrequentPassenger();
15624    }
15625  }, {
15626    key: 'closeFrequentPassengerCardAdd',
15627    value: function closeFrequentPassengerCardAdd() {
15628      var _this7 = this;
15629
15630      $('[data-js="add-card-frequent-passenger"]').removeClass('active');
15631      $('[data-js="form-add-frequent-passenger"]').trigger('reset');
15632      $('[data-js="input-date-child-add-frequent-passenger-container"]').removeClass('active');
15633      $('[data-js="form-add-frequent-passenger"]').find('input').each(function (_, el) {
15634        var $tip = $(el).parent().siblings().find('.tip');
15635        _this7.removeInvalidClass(el, $tip);
15636      });
15637    }
15638  }, {
15639    key: 'isDateBirthValid',
15640    value: function isDateBirthValid($inputBirth) {
15641      if ($inputBirth.val().length < 10) {
15642        this.addInvalidClass($inputBirth, i18n('birth_child_invali
15642d'), $tip);
15643        return false;
15644      }
15645
15646      var $tip = $inputBirth.parent().siblings().find('.tip');
15647      var dateString = DateFormatter.reverseDate($inputBirth.val());
15648      var currentDate = new Date();
15649      var birthDate = new Date(dateString);
15650      var maxYear = currentDate.getFullYear() - 6;
15651      currentDate.setFullYear(maxYear);
15652      var maxBirthYear = currentDate.getTime();
15653      var isBirthValid = false;
15654
15655      if (maxBirthYear > birthDate.getTime()) {
15656        this.addInvalidClass($inputBirth, i18n('birth_child_invalid'), $tip);
15657      } else if (birthDate.getTime() > new Date().getTime()) {
15658        this.addInvalidClass($inputBirth, i18n('data_future_invalid'), $tip);
15659      } else if (birthDate == 'Invalid Date') {
15660        this.addInvalidClass($inputBirth, i18n('birth_invalid'), $tip);
15661      } else {
15662        this.removeInvalidClass($inputBirth, $tip);
15663        isBirthValid = true;
15664      }
15665
15666      return isBirthValid;
15667    }
15668  }, {
15669    key: 'isFrequentPassengerFormValid',
15670    value: function isFrequentPassengerFormValid() {
15671      var _this8 = this;
15672
15673      var specificValidation = false;
15674
15675      $('[data-js="form-add-frequent-passenger"]').find('input[required]').each(function (_, el) {
15676        if ($(el).is(':visible')) {
15677          switch ($(el).attr('data-js')) {
15678            case 'input-name-add-frenquent-passenger':
15679              specificValidation = $(el).val() ? _this8.validateName($(el)) : false;
15680              break;
15681            case 'input-document-number-add-frequent-passenger':
15682              specificValidation = $(el).val() ? _this8.validateDocumentNumber($(el)) : false;
15683              break;
15684            case 'input-date-child-add-frequent-passenger':
15685              specificValidation = $(el).val() ? _this8.isDateBirthValid($(el)) : false;
15686              break;
15687            default:
15688              break;
15689          }
15690
15691          if (!specificValidation) return false;
15692        }
15693      });
15694      return specificValidation;
15695    }
15696  }, {
15697    key: 'eneableBtnAddFrequentPassenger',
15698    value: function eneableBtnAddFrequentPassenger() {
15699      $('[data-js="button-add-frequent-passenger"]').attr('disabled', false);
15700    }
15701  }, {
15702    key: 'disableBtnAddFrequentPassenger',
15703    value: function disableBtnAddFrequentPassenger() {
15704      $('[data-js="button-add-frequent-passenger"]').attr('disabled', true);
15705    }
15706  }, {
15707    key: 'handleSubmitAddPassengerError',
15708    value: function handleSubmitAddPassengerError() {
15709      var _this9 = this;
15710
15711      var document = $('[data-js="input-document-number-add-frequent-passenger"]');
15712      var $tip = document.parent().siblings().find('.tip');
15713      var AEM_doc_alert_message = $('[data-js="doc-alert-message"]').val();
15714
15715      this.frequentPassengers.forEach(function (el) {
15716        if (document.val() == el.document) {
15717          _this9.addInvalidClass(document, AEM_doc_alert_message, $tip);
15718        }
15719      });
15720    }
15721  }, {
15722    key: 'addFrequentPassenger',
15723    value: function addFrequentPassenger() {
15724      var _this9 = this;
15725
15726      var name = $('[data-js="input-name-add-frenquent-passenger"]').val().normalize('NFD').replace(/[\u0300-\u036f]/g, "").trim();
15727      var firstName = Utils.getFirstName(name);
15728      var lastName = Utils.getFamilyName(name);
15729      var typeDoc = $('[data-js="input-type-document-add-frequent-passenger"]').val();
15730      var document = $('[data-js="input-document-number-add-frequent-passenger"]').val();
15731      var birthDate = $('[data-js="input-date-child-add-frequent-passenger"]').val();
15732      var typePax = $('[data-js="input-add-passenger-child"]').is(':checked') ? 'CRIANCA' : 'ADULTO';
15733
15734      var headers = {
15735        'Authorization': '' + SessionStorage.get('jca_token')
15736      };
15737
15738      var body = {
15739        "pax": {
15740          "firstName": firstName,
15741          "lastName": lastName,
15742          "typeDoc": typeDoc,
15743          "document": document,
15744          "typePax": typePax
15745        }
15746      };
15747
15748      if (typePax == 'CRIANCA') body.pax.birthDate = DateFormatter.parseDateApiFormat(birthDate);
15749
15750      // AEM Custom Alert messages
15751      var addPassengerSuccess = $('[data-js="add-passenger-success"]').val();
15752      var addPassengerFail = $('[data-js="add-passenger-fail"]').val();
15753
15754      LoaderService.show();
15755      HttpService.post('savefrequentpassenger', body, headers).then(function () {
15756        LoaderService.hide();
15757
15758        _this9.showFrequentPassengerAlert(addPassengerSuccess);
15759        _this9.closeFrequentPassengerCardAdd();
15760        _this9.reloadFrequentPassengerPage();
15761      }).catch(function (err) {
15762        LoaderService.hide();
15763        _this9.showFrequentPassengerAlert(addPassengerFail);
15764        _this9.handleSubmitAddPassengerError();
15765        console.error(err);
15766      });
15767    }
15768  }, {
15769    key: 'editFrequentPassenger',
15770    value: function editFrequentPassenger(index) {
15771      var _this10 = this;
15772
15773      var name = $('[data-js="input-name-frequent-passenger-' + index + '"]').val().normalize('NFD').replace(/[\u0300-\u036f]/g, "").trim();
15774      var firstName = Utils.getFirstName(name);
15775      var lastName = Utils.getFamilyName(name);
15776      var typeDoc = $('[data-js="input-frequent-passenger-document-' + index + '"]').val();
15777      var document = $('[data-js="input-document-number-frequent-passenger-' + index + '"]').val();
15778      var birthDate = $('[data-js="input-date-child-frequent-passenger-' + index + '"]').val();
15779      var typePax = $('[data-js="underage-' + index + '"]').is(':checked') ? 'CRIANCA' : 'ADULTO';
15780      var id = $('[data-js="frequent-passenger-card-' + index + '"]').attr('data-id');
15781
15782      var headers = {
15783        'Authorization': '' + SessionStorage.get('jca_token')
15784      };
15785
15786      var body = {
15787        "pax": {
15788          "firstName": firstName,
15789          "lastName": lastName,
15790          "typeDoc": typeDoc,
15791          "document": document,
15792          "typePax": typePax,
15793          "id": id
15794        }
15795      };
15796
15797      if (typePax !== 'ADULTO') body.pax.birthDate = DateFormatter.parseDateApiFormat(birthDate);
15798
15799      // AEM Custom Alert messages
15800      var editPassengerSuccess = $('[data-js="edit-passenger-success"]').val();
15801      var editPassengerFail = $('[data-js="edit-passenger-fail"]').val();
15802
15803      LoaderService.show();
15804      HttpService.post('editPassenger', body, headers).then(function () {
15805        LoaderService.hide();
15806        _this10.showFrequentPassengerAlert(editPassengerSuccess);
15807        _this10.closeEditFrequentPassengerAllCards();
15808        _this10.reloadFrequentPassengerPage();
15809      }).catch(function (err) {
15810        LoaderService.hide();
15811        _this10.showFrequentPassengerAlert(editPassengerFail);
15812        console.error(err);
15813      });
15814    }
15815  }, {
15816    key: 'removeFrequentPassenger',
15817    value: function removeFrequentPassenger(index) {
15818      var _this11 = this;
15819
15820      var name = $('[data-js="input-name-frequent-passenger-' + index + '"]').val();
15821      var firstName = Utils.getFirstName(name);
15822      var lastName = Utils.getFamilyName(name);
15823      var typeDoc = $('[data-js="input-frequent-passenger-document-' + index + '"]').val();
15824      var document = $('[data-js="input-document-number-frequent-passenger-' + index + '"]').val();
15825      var birthDate = $('[data-js="input-date-child-frequent-passenger-' + index + '"]').val();
15826      var typePax = $('[data-js="frequent-passenger-card-' + index + '"]').attr('data-type');
15827      var id = $('[data-js="frequent-passenger-card-' + index + '"]').attr('data-id');
15828
15829      var headers = {
15830        'Authorization': '' + SessionStorage.get('jca_token')
15831      };
15832
15833      var body = {
15834        "pax": {
15835          "firstName": firstName,
15836          "lastName": lastName,
15837          "typeDoc": typeDoc,
15838          "document": document,
15839          "typePax": typePax == 'ADULT' ? 'ADULTO' : 'CRIANCA',
15840          "id": id
15841        }
15842      };
15843
15844      if (typePax !== 'ADULTO') body.pax.birthDate = birthDate;
15845
15846      // AEM Custom Alert messages
15847      var removePassengerSuccess = $('[data-js="remove-passenger-success"]').val();
15848      var removePassengerFail = $('[data-js="remove-passenger-fail"]').val();
15849
15850      LoaderService.show();
15851      HttpService.post('removePassenger', body, headers).then(function () {
15852        LoaderService.hide();
15853        _this11.showFrequentPassengerAlert(removePassengerSuccess);
15854        _this11.reloadFrequentPassengerPage();
15855      }).catch(function (err) {
15856        LoaderService.hide();
15857        Alert.show(removePassengerFail);
15858        console.error(err);
15859      });
15860    }
15861  }, {
15862    key: 'reloadFrequentPassengerPage',
15863    value: function reloadFrequentPassengerPage() {
15864      var _this12 = this;
15865
15866      this.getFrequentPassengers(function () {
15867        _this12.loadFrequentPassengersCardList(_this12.listFrequentPassengers);
15868      });
15869    }
15870  }, {
15871    key: 'loadMasks',
15872    value: function loadMasks() {
15873      this.inputBirth.mask('99/99/9999');
15874      $('[data-js^="input-date-child-frequent-passenger"]').mask('99/99/9999');
15875    }
15876  }, {
15877    key: 'listenForm',
15878    value: function listenForm() {
15879      var _this14 = this;
15880
15881      this.inputName.on('keydown', function () {
15882        _this14.validateName(_this14.inputName);
15883      });
15884
15885      this.validationCaracterName();
15886
15887      this.inputDocAddPassenger.on('keydown', function () {
15888        _this14.validateDocumentNumber(_this14.inputDocAddPassenger);
15889      });
15890
15891      $('[data-js="no-cancel-passenger"]').off('click').on('click', function () {
15892        $('[data-js="close-cancel-frequent-passenger"]').trigger('click');
15893      });
15894
15895      $('[data-js="cancel-passenger"]').off('click').on('click', function (e) {
15896        var index = $(e.target).attr('data-index');
15897        _this14.removeFrequentPassenger(+index);
15898        $('[data-js="close-cancel-frequent-passenger"]').trigger('click');
15899      });
15900
15901      $('[data-js="input-name-add-frenquent-passenger"], ' + '[data-js="input-document-number-add-frequent-passenger"]').on('keyup', function (event) {
15902        var keyCode = event.keyCode || event.which;
15903        if (keyCode === Utils.keyCodes.ENTER) {
15904          $('[data-js="button-add-frequent-passenger"]').click();
15905        }
15906      });
15907
15908      $('[data-js="button-add-frequent-passenger"]').off('click').on('click', function () {
15909        _this14.addFrequentPassenger();
15910      });
15911
15912      $('[data-js="input-add-passenger-child"]').off('click').on('click', function (elem) {
15913        var $inputDateChildAddPassengerChild = $('[data-js="input-date-child-add-frequent-passenger-container"]');
15914        var $tip = _this14.inputBirth.parent().siblings().find('.tip');
15915        if ($(elem.target).is(':checked')) {
15916          $inputDateChildAddPassengerChild.addClass('active');
15917          $inputDateChildAddPassengerChild.removeClass('d-none');
15918        } else {
15919          _this14.removeInvalidClass(_this14.inputBirth, $tip);
15920          $inputDateChildAddPassengerChild.removeClass('active');
15921          $inputDateChildAddPassengerChild.addClass('d-none');
15922          $inputDateChildAddPassengerChild.parent().siblings().find('.tip').hide();
15923        }
15924        $('[data-js="form-add-frequent-passenger"]').find('input[required]').trigger('input');
15925      });
15926
15927      $('[data-js="open-frequent-passenger-card"]').off('click').on('click', function () {
15928        _this14.openFrequentPassengerCardAdd();
15929      });
15930
15931      $('[data-js="close-frequent-passenger-card"]').off('click').on('click', function () {
15932        _this14.closeFrequentPassengerCardAdd();
15933      });
15934
15935      $('[data-js="form-add-frequent-passenger"]').find('input[required], select').on('input change', function () {
15936        var isFormValid = _this14.isFrequentPassengerFormValid() && $('[data-js="input-type-document-add-frequent-passenger"]').val();
15937
15938        isFormValid ? _this14.eneableBtnAddFrequentPassenger() : _this14.disableBtnAddFrequentPassenger();
15939      });
15940
15941      this.inputBirth.on('focus', function () {
15942        _this14.isDateBirthValid(_this14.inputBirth);
15943      });
15944
15945      $('[data-js="close-msg-frequent-passenger"]').off('click').on('click', function () {
15946        _this14.hideFrequentPassengerAlert();
15947      });
15948
15949      this.validationDocumentCaracter();
15950    }
15951  }, {
15952    key: 'validateDocumentNumber',
15953    value: function validateDocumentNumber($docNumber) {
15954      var documentNumber = $docNumber.val();
15955      var $tip = $docNumber.parent().siblings().find('.tip');
15956      var minDocLength = this.frequentPassengerAttrAem.data('min-doc-caracter');
15957      var isDocumentValid = false;
15958
15959      // Custom AEM Alert messages
15960      var docMinCaractere = $('[data-js="enter-the-document-number"]').val();
15961      var docInvalidMessage = $('[data-js="enter-a-document-number"]').val();
15962
15963      if (!documentNumber) {
15964        this.addInvalidClass($docNumber, docInvalidMessage, $tip);
15965      } else if (documentNumber.length < minDocLength) {
15966        this.addInvalidClass($docNumber, docMinCaractere, $tip);
15967      } else {
15968        this.removeInvalidClass($docNumber, $tip);
15969        isDocumentValid = true;
15970      }
15971
15972      return isDocumentValid;
15973    }
15974  }, {
15975  }, {
15976    key: 'validationDocumentCaracter',
15977    value: function validationDocumentCaracter() {
15978      this.inputDocAddPassenger.on("input", function () {
15979        $(this).val($(this).val().replace(/\D/g, ""));
15980      });
15981    }
15982  }, {
15983    key: 'validationCaracterName',
15984    value: function validationCaracterName() {
15985      var regex = /[^a-zA-Z\u00C0-\u00FF ]+/ig;
15986      this.inputName.on("input", function () {
15987        $(this).val($(this).val().replace(regex, ""));
15988      });
15989    }
15990  }, {
15991    key: 'validateName',
15992    value: function validateName($inputName) {
15993      var name = $inputName.val().trim();
15994      var $tip = $inputName.parent().siblings().find('.tip');
15995      var isValidName = name.indexOf(' ') !== -1;
15996      var isFrequentPassengerNameValid = false;
15997
15998      if (isValidName) {
15999        this.removeInvalidClass($inputName, $tip);
16000        isFrequentPassengerNameValid = true;
16001      } else {
16002        this.addInvalidClass($inputName, 'Nome inválido', $tip);
16003      }
16004
16005      return isFrequentPassengerNameValid;
16006    }
16007  }, {
16008    key: 'isSelectCustom',
16009    value: function isSelectCustom(el) {
16010      return $(el).attr('data-js') === 'input-doc-type';
16011    }
16012  }, {
16013    key: 'addInvalidClass',
16014    value: function addInvalidClass(el, msg, tip) {
16015      if (!this.isSelectCustom(el)) $(el).addClass("invalid"); else $(el).siblings('.select-selected').addClass('invalid');
16016
16017      if (tip) {
16018        if (msg) tip.text(msg);
16019        tip.fadeIn();
16020      }
16021    }
16022  }, {
16023    key: 'removeInvalidClass',
16024    value: function removeInvalidClass(el, tip) {
16025      if (!this.isSelectCustom(el)) $(el).removeClass("invalid"); else $(el).siblings('.select-selected').removeClass('invalid');
16026
16027      if (tip) {
16028        tip.fadeOut();
16029      }
16030    }
16031  }]);
16032
16033  return FrequentPassengerController;
16034}();
16035'use strict';
16036
16037var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
16038
16039function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16040
16041var AnchorLink = function () {
16042  function AnchorLink($) {
16043    _classCallCheck(this, AnchorLink);
16044
16045    this.init();
16046  }
16047
16048  _createClass(AnchorLink, [{
16049    key: 'init',
16050    value: function init() {
16051      this.anchorScroll();
16052    }
16053  }, {
16054    key: 'anchorScroll',
16055    value: function anchorScroll() {
16056      $('[data-js="anchor-nav"] a[href^="#"]:not(.trip-stepper)').on('click', function (e) {
16057
16058        var targetClick = $(e.target).parent().parent();
16059        if (targetClick && $(targetClick).attr('data-js') && $('.modal-content[data-js="' + $(targetClick).attr('data-js') + '"]')) return;
16060        var id = $(this).attr('href'), targetOffset = $(id).offset().top;
16061        if ($(id) && $(id).length == 0) return;
16062
16063        $('html, body').animate({
16064          scrollTop: targetOffset - 100
16065        }, 250);
16066      });
16067    }
16068  }]);
16069
16070  return AnchorLink;
16071}();
16072'use strict';
16073
16074var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
16075
16076function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16077
16078var HeaderHero = function () {
16079  function HeaderHero($) {
16080    _classCallCheck(this, HeaderHero);
16081
16082    new RegistrationCampaignController($);
16083    this.init();
16084  }
16085
16086  _createClass(HeaderHero, [{
16087    key: 'init',
16088    value: function init() {
16089      var isBannerFixed = $('[data-js="banner-fixed"]').val() == "true" ? true : false;
16090      var $widthWindow = Utils.getWindowSize().width;
16091
16092      var colorWhenBackgroundIsTransparent = $('[data-js="colorWhenBackgroundIsTransparent"]').val();
16093      var buttonTextColorWhenBackgroundIsTransparent = $('[data-js="buttonTextColorWhenBackgroundIsTransparent"]').val();
16094
16095      var colorAfterScroll = $('[data-js="colorAfterScroll"]').val();
16096      var buttonTextColorAfterScroll = $('[data-js="buttonTextColorAfterScroll"]').val();
16097      var buttonBackgroundColorAfterScroll = $('[data-js="buttonBackgroundColorAfterScroll"]').val();
16098      var isLoginPage = $('[data-js="login-component-identifier"]').val() == 'true' ? true : false;
16099
16100      $(document).ready(function () {
16101        if ($(document).scrollTop() >= 60) {
16102
16103          if ($('#wemobi-header').hasClass('header-wemobi-custom') && !isLoginPage) {
16104            $('#header-navbar').addClass('header-navbar-fixed');
16105          }
16106
16107          // link color
16108          if (colorAfterScroll != '') {
16109            $('.header-navbar .header-nav-item.nav-links').find('a').css('color', colorAfterScroll);
16110            $('.header-navbar .header-nav-list li .logged-button .logged-icon').css('color', colorAfterScroll);
16111            $('.header-navbar .header-nav-list li .logged-button .logged-message').css('color', colorAfterScroll);
16112          }
16113
16114          // button colors
16115          if (buttonTextColorAfterScroll != '') {
16116            $('.header-navbar .login-button .logged-out > .button-header').css('border', '3px solid ' + buttonTextColorAfterScroll);
16117            $('.header-navbar .login-button .logged-out > .button-header').css('color', buttonTextColorAfterScroll);
16118            $('.header-navbar.header-navbar-fixed .logged-out .button-header').css('background', buttonBackgroundColorAfterScroll);
16119          }
16120        } else {
16121          // link color
16122          if (colorWhenBackgroundIsTransparent != '') {
16123            $('.header-navbar .header-nav-item.nav-links').find('a').css('color', colorWhenBackgroundIsTransparent);
16124            $('.header-navbar .header-nav-list li .logged-button .logged-icon').css('color', colorWhenBackgroundIsTransparent);
16125            $('.header-navbar .header-nav-list li .logged-button .logged-message').css('color', colorWhenBackgroundIsTransparent);
16126          }
16127
16128          // button colors
16129          if (buttonTextColorWhenBackgroundIsTransparent != '') {
16130            $('.header-navbar .login-button .logged-out > .button-header').css('border', '3px solid ' + buttonTextColorWhenBackgroundIsTransparent);
16131            $('.header-navbar .login-button .logged-out > .button-header').css('color', buttonTextColorWhenBackgroundIsTransparent);
16132          }
16133          //$('.header-navbar.header-navbar-fixed .logged-out .button-header').css('background', 'transparent');
16134        }
16135      });
16136
16137      if (!isBannerFixed) {
16138        if ($widthWindow > 992) {
16139          $(window).scroll(function () {
16140            if ($(this).scrollTop() > 60) {
16141
16142              if (!isLoginPage) {
16143                $('#header-navbar').addClass('header-navbar-fixed');
16144                $('.container-header').addClass('active');
16145              }
16146
16147              // link color
16148              if (colorAfterScroll != '') {
16149                $('.header-navbar.header-navbar-fixed .header-nav-item.nav-links').find('a').css('color', colorAfterScroll);
16150                $('.header-navbar .header-nav-list li .logged-button .logged-icon').css('color', colorAfterScroll);
16151                $('.header-navbar .header-nav-list li .logged-button .logged-message').css('color', colorAfterScroll);
16152              }
16153
16154              // button colors
16155              if (buttonTextColorAfterScroll != '') {
16156                $('.header-navbar .login-button .logged-out > .button-header').css('border', '3px solid ' + buttonTextColorAfterScroll);
16157                $('.header-navbar .login-button .logged-out > .button-header').css('color', buttonTextColorAfterScroll);
16158                $('.header-navbar.header-navbar-fixed .logged-out .button-header').css('background', buttonBackgroundColorAfterScroll);
16159              }
16160            } else {
16161              $('#header-navbar').removeClass('header-navbar-fixed');
16162              $('.container-header').removeClass('active');
16163
16164              // link color
16165              if (colorWhenBackgroundIsTransparent != '') {
16166                $('.header-navbar .header-nav-item.nav-links').find('a').css('color', colorWhenBackgroundIsTransparent);
16167                $('.header-navbar .header-nav-list li .logged-button .logged-icon').css('color', colorWhenBackgroundIsTransparent);
16168                $('.header-navbar .header-nav-list li .logged-button .logged-message').css('color', colorWhenBackgroun
16168dIsTransparent);
16169              }
16170
16171              // button colors
16172              if (buttonTextColorWhenBackgroundIsTransparent != '') {
16173                $('.header-navbar .login-button .logged-out > .button-header').css('border', '3px solid ' + buttonTextColorWhenBackgroundIsTransparent);
16174                $('.header-navbar .login-button .logged-out > .button-header').css('color', buttonTextColorWhenBackgroundIsTransparent);
16175              }
16176            }
16177          });
16178        }
16179        if (Utils.isMobile()) {
16180          $('[data-js="banner-image"]').css('top', '70px');
16181        };
16182      } else {
16183        $('#header-navbar').addClass('header-navbar-fixed');
16184        if (Utils.isMobile()) {
16185          $('[data-js="banner-image"]').css('top', '60px');
16186        } else {
16187          $('[data-js="banner-image"]').css('top', '70px');
16188        }
16189      }
16190    }
16191  }]);
16192
16193  return HeaderHero;
16194}();
16195'use strict';
16196
16197var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
16198
16199function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16200
16201var HeaderWemobi = function () {
16202  function HeaderWemobi($) {
16203    _classCallCheck(this, HeaderWemobi);
16204
16205    this.btnCart = $('[data-js="cart-btn"]');
16206    this.btnBottomCart = $('[data-js="show-resume-bottom-cart"]');
16207    this.bottomResumeCart = $('[data-js="bottom-resume-cart"]');
16208    this.cartContainer = $('[data-js="cart-container"]');
16209    this.cart = SessionStorage.get('cart');
16210    this.closeCart = $('[data-js="close-cart"]');
16211    this.init();
16212  }
16213
16214  _createClass(HeaderWemobi, [{
16215    key: 'init',
16216    value: function init() {
16217      var _this = this;
16218
16219      this.chooseLoginButton();
16220      this.addClassInOtherPages();
16221      this.listenHeader();
16222      this.setCartColor();
16223
16224      $(window).on('resize', function () {
16225        _this.chooseLoginButton();
16226      });
16227    }
16228  }, {
16229    key: 'setCartColor',
16230    value: function setCartColor() {
16231      var cartColor = $('[data-js="cart-color"]').val();
16232
16233      this.btnCart.css('color', cartColor);
16234    }
16235  }, {
16236    key: 'addClassInOtherPages',
16237    value: function addClassInOtherPages() {
16238      var pageIsNavRoot = $('[data-js="pageIsNavRoot"]').val();
16239      if (pageIsNavRoot && pageIsNavRoot === 'false' && $('#jca-identifier-page').val() != 'jca-register-passengers-page') {
16240        $('.header-navbar').addClass('fixed');
16241      }
16242
16243      $('.header-nav-container .header-nav-list .header-nav-item .login-button').addClass('otherPage');
16244      $('.img-header-logo').addClass('active');
16245      $('[data-js="button-menu"]').hide();
16246      $('.header-site .container').addClass('active');
16247
16248      if ($('[data-js="anchor-nav"]').attr('data-show-links') == 'true') {
16249        $('.header-nav-item').addClass('active');
16250      }
16251    }
16252  }, {
16253    key: 'chooseLoginButton',
16254    value: function chooseLoginButton() {
16255      var loginButton = $('[data-js="header-login-button"]:visible');
16256      if (Utils.getWindowSize().width < 951) {
16257        $('.button-header.login-button').hide();
16258      } else {
16259        $('.button-header.login-button').show();
16260      }
16261    }
16262  }, {
16263    key: 'listenHeader',
16264    value: function listenHeader() {
16265      var _this2 = this;
16266
16267      this.btnCart.on('click', function () {
16268        _this2.cartContainer.toggleClass('active');
16269        _this2.bottomResumeCart.toggleClass('active');
16270      });
16271
16272      this.btnBottomCart.on('click', function () {
16273        _this2.cartContainer.toggleClass('active');
16274        _this2.bottomResumeCart.toggleClass('active');
16275      });
16276
16277      this.closeCart.on('click', function () {
16278        _this2.cartContainer.toggleClass('active');
16279        _this2.bottomResumeCart.toggleClass('active');
16280      });
16281    }
16282  }]);
16283
16284  return HeaderWemobi;
16285}();
16286'use strict';
16287
16288var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); }
16288 else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
16289
16290var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
16291
16292function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
16293
16294/**
16295 *
16296 * InformationController
16297 *
16298 * INICIO
16299 *
16300 */
16301
16302var InformationController = function () {
16303  function InformationController($) {
16304    var _this = this;
16305
16306    _classCallCheck(this, InformationController);
16307
16308    this.selectorCollapse = $('[data-js="collapse-item-external"]');
16309    this.selectorCollapseInternalText = $('[data-js="collapse-item-internal-text"]');
16310    this.selectorCollapseInternalLink = $('[data-js="collapse-item-internal-link"]');
16311    this.selectorRadioGps = $('[data-js="radio-gps"]');
16312    this.selectorRadioCep = $('[data-js="radio-cep"]');
16313    this.selectorCheck = $('.outside-cep');
16314    this.buttonSearch = $('[data-js="button-search"]');
16315    this.inputServiceAgency = $("[data-js='input-services-agency']");
16316    this.backButton = $('[data-js="button-back"]');
16317    this.inputCity = $('[data-js="input-city"]');
16318    this.formCity = $('[data-js="form-city"]');
16319    this.protocolForm = $('[data-js="protocol-form"]');
16320    this.submitProtocol = $('[data-js="submit-protocol"]');
16321    this.agencyForm = $('[data-js="agency-box-form"]');
16322    this.selectHasBought = $('[data-js="has-bought"]');
16323    this.ddiField = $('[data-js="ddi"]');
16324    this.dddField = $('[data-js="ddd"]');
16325    this.phoneField = $('[data-js="phone"]');
16326    this.documentType = $('[data-js="type-doc"]');
16327    this.documentNumber = $('[data-js="doc-number"]');
16328    this.companyField = $('[data-js="select-company"]');
16329    this.nameField = $('[data-js="input-name"]');
16330    this.emailField = $('[data-js="input-email"]');
16331    this.protocolType = $('[data-js="type"]');
16332    this.protocolReason = $('[data-js="reason"]');
16333    this.protocolSubreason = $('[data-js="subreason"]');
16334    this.protocolDescription = $('[data-js="description"]');
16335    this.formProtocol = $('[data-js="protocol-form"]');
16336    this.isCancelForm = $('[data-js="is-cancel-form"]').val() === 'true';
16337    this.requestDescription = $('[data-js="request-description"]').val();
16338    this.selectCustom = new SelectCustom($);
16339    this.protocolData = {};
16340    this.currentTop = 0;
16341    this.reasons = null;
16342    new AlertConfirmation($);
16343    this.init();
16344    window.addEventListener('hashchange', function () {
16345      _this.getHashLocation();
16346    });
16347    $('a').click(function (e) {
16348      if (!$(e.target).parent().hasClass('collapse-item-external') && !$(e.target).parent().hasClass('collapse-item-internal')) _this.getHashLocation();
16349    });
16350  }
16351
16352  _createClass(InformationController, [{
16353    key: 'init',
16354    value: function init() {
16355      var _this2 = this;
16356
16357      this.requestHelperTranslation(function () {
16358        _this2.resetForm();
16359        _this2.loadMasks();
16360        _this2.loadTabs();
16361        _this2.verifyRadio();
16362        _this2.loadText();
16363        _this2.loadAgenciesSearch();
16364        _this2.loadServices();
16365        _this2.loadButtonActions();
16366        _this2.handleProtocolForm().then(function () {
16367          return _this2.getDeeplink();
16368        });
16369        _this2.listenForm();
16370        _this2.disableSubreason();
16371
16372        setTimeout(function () {
16373          _this2.getHashLocation();
16374          _this2.setFontSize();
16375        }, 5);
16376      });
16377    }
16378  }, {
16379    key: 'handleMessageReasonInTextArea',
16380    value: function handleMessageReasonInTextArea() {
16381      if (this.reasons) {
16382        var reasonSelect = this.protocolReason.next().text();
16383        var typeReason = this.protocolType.val();
16384        var objReason = this.reasons.filter(function (el) {
16385          return el.text === reasonSelect && el.value === typeReason;
16386        });
16387        var messageReason = objReason[0].description;
16388
16389        this.protocolDescription.attr('placeholder', messageReason && messageReason != '' ? messageReason : i18n('placeholder_contact_us_default')).val('');
16390      }
16391    }
16392  }, {
16393    key: 'listenForm',
16394    value: function listenForm() {
16395      var _this3 = this;
16396
16397      this.formProtocol.on('change', function () {
16398        _this3.areRequiredFieldsSubmitted();
16399        _this3.isFormProtocolValid();
16400        _this3.areLocationsValid();
16401      });
16402
16403      $('[data-js="remove-attachment"]').click(function (e) {
16404        $('[data-js="protocol-file"]').val(null);
16405        $('[data-js="protocol-file-label"]').text('Anexar um arquivo');
16406        $(e.currentTarget).addClass('d-none');
16407      });
16408
16409      $('[data-js="protocol-file"]').change(function (e) {
16410        var target = $(e.currentTarget);
16411        var reader = new FileReader();
16412        var file = target.prop('files')[0];
16413        var maxFileSize = 614400;
16414        $('[data-js="file-size-alert"]').hide();
16415
16416        if (file.size > maxFileSize) {
16417          $('[data-js="remove-attachment"]').click();
16418          $('[data-js="file-size-alert"]').fadeIn();
16419          return;
16420        }
16421
16422        reader.readAsDataURL(file);
16423
16424        reader.onload = function () {
16425          $('[data-js="protocol-file-label"]').text(file.name);
16426          $('[data-js="remove-attachment"]').removeClass('d-none');
16427        };
16428
16429        reader.onerror = function (error) {
16430          console.log('Error: ', error);
16431        };
16432      });
16433
16434      $('.attachment-button').on('keypress', function (e) {
16435        var key = e.which || e.keyCode;
16436
16437        if (key == 13) {
16438          $('#protocol-file').focus().trigger('click');
16439        }
16440      });
16441    }
16442  }, {
16443    key: 'openCollapseDefault',
16444    value: function openCollapseDefault() {
16445      $('[data-js-protocol="collapse-protocol"]').addClass('active').next().css('display', 'block');
16446    }
16447  }, {
16448    key: 'getDeeplink',
16449    value: function getDeeplink() {
16450      if (window.location.search.substring(1) && decodeURI(window.location.search.substring(1)).split('&').length > 8) {
16451        this.openCollapseDefault();
16452
16453        $('[data-js="btn-contact-us"]').attr('disabled', false);
16454
16455        this.nameField.val(this.getParam('name'));
16456        this.emailField.val(this.getParam('email_user').replace('%40', '@'));
16457        this.dddField.val('(' + this.getParam('area_code') + ')');
16458        this.phoneField.val(this.getParam('phone')).mask('00000-0000');
16459        $('[data-js="input-origin"]').val(this.getParam('originTrip')).data('valid', true);
16460        $('[data-js="input-dest"]').val(this.getParam('destinationTrip')).data('valid', true);
16461        $('[data-js="input-date-trip]"').val(this.getParam('tripDate'));
16462        $('[data-js="input-local"]').val(this.getParam('originTrip'));
16463        $('[data-js="type"]').val(this.getParam('type'));
16464        $('[data-js="input-date-trip"]').val(this.getParam('dateDepart').replace(/%2F/g, '/'));
16465        $('[data-js="input-date-buy"]').val(this.getParam('salesTime').replace(/%2F/g, '/'));
16466        $('[data-js="doc-number"]').val(this.getParam('cpf'));
16467
16468        var typeSolicitation = $('[data-js="type"]')[0];
16469        this.selectCustom.selectDefault(typeSolicitation, this.getParam('type'));
16470
16471        var hasBought = $('[data-js="has-bought"]');
16472        if (this.getParam('hasBought') == 'true') {
16473          hasBought.click();
16474        }
16475
16476        var reasonType = $('[data-js="reason"')[0];
16477        var reasonParam = this.getParam('reason').replace(/%2F/g, '/').toUpperCase();
16478
16479        var _protocolData$selects = this.protocolData.selects.motivos.filter(function (reason) {
16480          return reason.crmValue.toUpperCase() == reasonParam;
16481        }),
16482          _protocolData$selects2 = _slicedToArray(_protocolData$selects, 1),
16483          reason = _protocolData$selects2[0];
16484
16485        this.selectCustom.selectDefault(reasonType, reason.text);
16486
16487        $('[data-js="total-price"]').val(this.getParam('total'));
16488        $('[data-js="description"]').text('N° Localizador -' + this.getParam('finder'));
16489        $('[data-js="6-digits"]').mask('000000');
16490        $('[data-js="4-digits"]').mask('0000');
16491        $('[data-js="total-price"]').mask('0.000,00', {
16492          reverse: true
16493        });
16494      }
16495    }
16496  }, {
16497    key: 'getParam',
16498    value: function getParam(sParam) {
16499      var sPageURL = decodeURI(window.location.search.substring(1)).split('&');
16500
16501      for (var i = 0; i < sPageURL.length; i++) {
16502        var sParameterName = sPageURL[i].split("=");
16503        if (sParameterName[0] == sParam) return sParameterName[1].replace(/%20/gi, ' ');
16504      }
16505    }
16506  }, {
16507    key: 'requestHelperTranslation',
16508    value: function requestHelperTranslation(callback) {
16509      var _this4 = this;
16510      var params = '';
16511      if (Utils.getCurrentLang() !== 'pt-br') {
16512        params = '?lang=' + Utils.getCurrentLang();
16513      }
16514
16515      if (!this.noResultMessage || !this.singleResultMessage || !this.protip || !this.multipleResultMessage) {
16516        HttpService.getFromRoot('translations.json' + params).done(function (data) {
16517          if (data.isSuccess) {
16518            _this4.noResultMessage = data.result.translationNoCityMessage;
16519            _this4.singleResultMessage = data.result.translationCityMessage;
16520            _this4.protip = data.result.translationUseUpDownArrowsMessage;
16521            _this4.multipleResultMessage = data.result.translationNumberCitiesFoundMessage;
16522          } else {
16523            _this4.noResultMessage = Utils.defaultHelperMessages.noResultMessage;
16524            _this4.singleResultMessage = Utils.defaultHelperMessages.singleResultMessage;
16525            _this4.protip = Utils.defaultHelperMessages.protip;
16526            _this4.multipleResultMessage = Utils.defaultHelperMessages.multipleResultMessage;
16527          }
16528          if (callback) {
16529            callback();
16530          }
16531        }).fail(function (err) {
16532          _this4.noResultMessage = Utils.defaultHelperMessages.noResultMessage;
16533          _this4.singleResultMessage = Utils.defaultHelperMessages.singleResultMessage;
16534          _this4.protip = Utils.defaultHelperMessages.protip;
16535          _this4.multipleResultMessage = Utils.defaultHelperMessages.multipleResultMessage;
16536          if (callback) {
16537            callback();
16538          }
16539        });
16540      } else {
16541        if (callback) callback();
16542      }
16543    }
16544  }, {
16545    key: 'getHashLocation',
16546    value: function getHashLocation() {
16547      var hash = window.location.hash;
16548      var element = $(hash);
16549      if (element && !element.hasClass('active')) {
16550        var parent = element.parent().prev();
16551        if (parent.hasClass('collapse-item-external') && !parent.hasClass('active')) parent.trigger('click');
16552        element.trigger('click');
16553      }
16554    }
16555  }, {
16556    key: 'loadMasks',
16557    value: function loadMasks() {
16558      var _this5 = this;
16559
16560      this.ddiField.mask('+000');
16561
16562      this.phoneField.keyup(function (e) {
16563        var masks = ['0000-00009', '00000-0000'];
16564        var mask = $(e.currentTarget).val().replace(/\D/g, '').length <= 8 ? masks[0] : masks[1];
16565        $(e.target).mask(mask, {});
16566      });
16567
16568      this.documentNumber.mask('000.000.000-00');
16569      this.documentType.change(function (e) {
16570        _this5.documentNumber.unmask();
16571        switch ($(e.target).val().toUpperCase()) {
16572          case 'CPF':
16573            _this5.documentNumber.mask('000.000.000-00');
16574            break;
16575          case 'CNPJ':
16576            _this5.documentNumber.mask('00.000.000/0000-00');
16577            break;
16578          default:
16579            break;
16580        }
16581      });
16582    }
16583  }, {
16584    key: 'showErrorMessage',
16585    value: function showErrorMessage(msg) {
16586      var $msgError = $('[data-js="message-error"]');
16587      if (!$msgError.is(':visible')) {
16588        $msgError.find('.header').text(msg);
16589        $msgError.fadeIn();
16590      }
16591    }
16592  }, {
16593    key: 'disableSubreason',
16594    value: function disableSubreason() {
16595      $('[data-js="subreason"]').parent().parent().parent().parent().hide();
16596    }
16597  }, {
16598    key: 'hideErrorMessage',
16599    value: function hideErrorMessage() {
16600      var $msgError = $('[data-js="message-error"]');
16601      $msgError.fadeOut();
16602    }
16603  }, {
16604    key: 'handleProtocolForm',
16605    value: function handleProtocolForm() {
16606      var _this6 = this;
16607
16608      return new Promise(function (resolve) {
16609        var self = _this6;
16610        var surl = $('[data-js="is-cancel-form"]').val() != undefined ? 'jcr:content.protocol_utp_fields.json' : 'jcr:content.protocol_fields.json';
16611
16612        LoaderService.show();
16613        $.getJSON(InternalAPIService.aemServiceHost + '/content/jca/' + surl).then(function (data) {
16614          _this6.protocolData = data;
16615          _this6.protocolData = _this6.filterProtocolData(_this6.protocolData);
16616          LoaderService.hide();
16617
16618          var placeholder = textarea.placeholder;
16619          var _protocolData$selects3 = _this6.protocolData.selects,
16620            motivos = _protocolData$selects3.motivos,
16621            submotivos = _protocolData$selects3.submotivos;
16622
16623          // Aux methods
16624          _this6.getOrigin();
16625          _this6.handleDatepicker();
16626          _this6.fillSelectsFromData();
16627          _this6.protocolDescription.attr('placeholder', placeholder.original).val('').blur();
16628          resolve();
16629
16630          // Events methods
16631          _this6.submitProtocol.click(function () {
16632            if (_this6.isFormValid()) {
16633              _this6.openProtocolProcess();
16634            } else {
16635              Utils.scrollTop();
16636              _this6.showErrorMessage('Preencha todos os campos corretamente.');
16637              // fadeout when clicking on form
16638              self.protocolForm.children().find('input, .select-custom').on('focusin', function () {
16639                _this6.hideErrorMessage();
16640              });
16641            }
16642          });
16643
16644          _this6.protocolForm.find('input[required]').keyup(function (e) {
16645            if ($(e.target).hasClass('invalid')) {
16646              $(e.target).removeClass('invalid');
16647            }
16648          });
16649
16650          _this6.protocolForm.find('.select-selected').click(function (e) {
16651            if ($(e.target).hasClass('invalid')) {
16652              $(e.target).removeClass('invalid');
16653            }
16654          });
16655
16656          _this6.protocolType.change(function (e) {
16657            // fillSelectsFromData for 'motivos' and 'submotivos'
16658            _this6.selectTypeReason(e.target, motivos, function () {
16659
16660              var resetState = function resetState(local, subreasonSelect, self) {
16661                //reset select of type of requirements
16662                local.attr('required', false);
16663                local.removeClass('invalid');
16664                subreasonSelect.attr('required', false);
16665                self.removeInvalidClass(subreasonSelect[0]);
16666                subreasonSelect.parent().parent().parent().parent().hide();
16667                self.selectCustom.eraseSelect(subreasonSelect);
16668              };
16669
16670              var resetPlaceHolder = function resetPlaceHolder(self) {
16671                self.protocolDescription.attr('placeholder', placeholder.original).val('').blur();
16672              };
16673
16674              $('.select-custom').click(function (event) {
16675                var reason = $(event.target).text().toUpperCase();
16676                var subreasonSelect = $('[data-js="subreason"]');
16677                var selectName = $(event.target).parent().parent().prev().prev().data('js');
16678                var local = $('[data-js="input-local"]');
16679
16680                if (selectName === 'reason') {
16681                  self.handleMessageReasonInTextArea();
16682                  self.deactivateOptionPayment();
16683                  if (self.protocolType.val().toUpperCase() === 'RECLAMAÇÃO' && reason === 'GUICHÊ/AGÊNCIA') {
16684                    resetState(local, subreasonSelect, self);
16685                  } else if (self.protocolType.val().toUpperCase() === 'RECLAMAÇÃO' && reason === 'CANCELAMENTO/ESTORNO DE PASSAGEM') {
16686                    self.activateOptionPayment();
16687                    $('[data-js="6-digits"]').mask('000000');
16688                    $('[data-js="4-digits"]').mask('0000');
16689                    $('[data-js="total-price"]').mask('0.000,00', {
16690                      reverse: true
16691                    });
16692                  } else {
16693                    resetState(local, subreasonSelect, self);
16694                    var hasSubmotivos = false;
16695
16696                    submotivos.forEach(function (submotivo) {
16697                      if (submotivo.value.toUpperCase() == reason) {
16698                        hasSubmotivos = true;
16699                        var option = new Option(submotivo.text, submotivo.crmValue);
16700                        subreasonSelect.append(option);
16701                      }
16702                    });
16703
16704                    self.selectCustom.initSingle(subreasonSelect.parent(), 'disabled');
16705
16706                    if (hasSubmotivos) {
16707                      subreasonSelect.attr('required', true);
16708                      subreasonSelect.parent().parent().parent().parent().show();
16709                    }
16710                  }
16711                } else if (selectName === 'type') {
16712                  resetState(local, subreasonSelect, self);
16713                  resetPlaceHolder(self);
16714                }
16715              });
16716            });
16717          });
16718
16719          _this6.selectHasBought.change(function (e) {
16720            var chosen = $(e.target).is(':checked');
16721            var $inputList = $('[data-js="input-date-buy"], [data-js="input-date-trip"]');
16722            var $odList = $('[data-js="input-origin"],[data-js="input-dest"]');
16723            $('[data-js="origin-buy"], [data-js="destination-buy"], [data-js="date-buy"]').toggleClass('d-none');
16724
16725            if (chosen) {
16726              $inputList.closest('.input-field').show();
16727              $('[data-js="input-date-buy"]').attr('required', true);
16728              $('[data-js="input-date-trip"]').attr('required', true);
16729              $odList.attr('required', true);
16730              $('[data-js="description"]').val('');
16731            } else {
16732              $inputList.closest('.input-field').hide();
16733              $inputList.val(null);
16734              $inputList.attr('required', false);
16735              $odList.attr('required', false);
16736              $odList.removeClass('invalid');
16737            }
16738
16739            if (chosen && !_this6.areLocationsValid()) {
16740              $('[data-js="submit-protocol"]').prop('disabled', true);
16741            } else if (chosen && _this6.areLocationsValid() && _this6.areRequiredFieldsSubmitted()) {
16742              $('[data-js="submit-protocol"]').prop('disabled', false);
16743            }
16744          });
16745        }).catch(function (err) {
16746          console.log(err);
16747          LoaderService.hide();
16748        });
16749      });
16750    }
16751  }, {
16752    key: 'openProtocolProcess',
16753    value: function openProtocolProcess() {
16754      var _this7 = this;
16755
16756      var baseUrl = $('#baseUrl').val();
16757      var clientid = $("#clientId").val();
16758      var accessToken = sessionStorage.getItem('access_token');
16759      this._accssesToken = new AccssesTokenService();
16760
16761      if (accessToken == null || !this._accssesToken.verifyToken()) {
16762        HttpService.getSession();
16763        accessToken = sessionStorage.getItem('access_token');
16764      }
16765
16766      this.submitProtocol.attr('disabled', true);
16767
16768      var createCase = function createCase() {
16769        LoaderService.show();
16770        var case_uri = targetConfig.EXT.endpoints.openProtocol;
16771
16772        var body = _this7.getFormParameters();
16773
16774        return $.ajax({
16775          type: 'POST',
16776          url: '' + (baseUrl + case_uri),
16777          headers: {
16778            'Access-Control-Allow-Origin': '*',
16779            'client_id': clientid,
16780            'access_token': accessToken
16781          },
16782          contentType: 'application/json',
16783          dataType: 'json',
16784          data: JSON.stringify(body)
16785        }).then(function (data) {
16786          if (!data.success) {
16787            throw new Error(data.message || 'Erro ao criar protocolo');
16788          }
16789
16790          return { caseId: data.result.id };
16791        });
16792      };
16793
16794      var getfileAttached = function getfileAttached(_ref2) {
16795        var caseId = _ref2.caseId;
16796
16797        return new Promise(function (resolve, reject) {
16798          var target = $('[data-js="protocol-file"]');
16799
16800          if ($('[data-js="protocol-file"]').val() === "") reject(null);
16801
16802          var reader = new FileReader();
16803          reader.readAsDataURL(target.prop('files')[0]);
16804          var file = target.prop('files')[0];
16805
16806          reader.onload = function () {
16807            var fileBase64 = reader.result.replace(/[data:](\D*)?base64,/g, '');
16808            resolve({ file: file, fileBase64: fileBase64, caseId: caseId });
16809          };
16810
16811          reader.onerror = function (error) {
16812            return reject(error);
16813          };
16814        });
16815      };
16816
16817      var createContentVersion = function createContentVersion(_ref3) {
16818        var file = _ref3.file,
16819          fileBase64 = _ref3.fileBase64,
16820          caseId = _ref3.caseId;
16821
16822        var content_version_uri = targetConfig.EXT.endpoints.contentVersion;
16823
16824        var body = _this7.parseFormAttachmentRequest(file, fileBase64);
16825
16826        return $.ajax({
16827          type: 'POST',
16828          url: '' + (baseUrl + content_version_uri),
16829          headers: {
16830            'Access-Control-Allow-Origin': '*',
16831            'client_id': clientid,
16832            'access_token': accessToken
16833          },
16834          contentType: 'application/json',
16835          dataType: 'json',
16836          data: JSON.stringify(body)
16837        }).then(function (data) {
16838          if (!data.success) {
16839            throw new Error(data.message || 'Erro ao criar protocolo');
16840          }
16841
16842          return { contentVersionId: data.result.id, caseId: caseId };
16843        });
16844      };
16845
16846      var getContentDocumentId = function getContentDocumentId(_ref4) {
16847        var contentVersionId = _ref4.contentVersionId,
16848          caseId = _ref4.caseId;
16849        var content_version_uri = targetConfig.EXT.endpoints.contentVersion;
16850
16851        return $.ajax({
16852          type: 'GET',
16853          url: '' + (baseUrl + content_version_uri + '/' + contentVersionId),
16854          headers: {
16855            'Access-Control-Allow-Origin': '*',
16856            'client_id': clientid,
16857            'access_token': accessToken
16858          },
16859          contentType: 'application/json',
16860          dataType: 'json'
16861        }).then(function (data) {
16862          if (!data.success) {
16863            throw new Error(data.message || 'Erro ao criar protocolo');
16864          }
16865
16866          var contentDocumentId = data.result.records[0].contentDocumentId;
16867
16868          return { contentDocumentId: contentDocumentId, caseId: caseId };
16869        });
16870      };
16871
16872      var createContentDocumentLink = function createContentDocumentLink(_ref5) {
16873        var contentDocumentId = _ref5.contentDocumentId,
16874          caseId = _ref5.caseId;
16875        var content_link_uri = targetConfig.EXT.endpoints.contentLink;
16876
16877        var body = _this7.parseContentDocumentLink(contentDocumentId, caseId);
16878
16879        return $.ajax({
16880          type: 'POST',
16881          url: '' + (baseUrl + content_link_uri),
16882          headers: {
16883            'Access-Control-Allow-Origin': '*',
16884            'client_id': clientid,
16885            'access_token': accessToken
16886          },
16887          contentType: 'application/json',
16888          dataType: 'json',
16889          data: JSON.stringify(body)
16890        }).then(function (data) {
16891          if (!data.success) {
16892            throw new Error(data.message || 'Erro ao criar protocolo');
16893          }
16894        });
16895      };
16896
16897      var completeChain = function completeChain() {
16898        LoaderService.hide();
16899
16900        _this7.submitProtocol.attr('disabled', false);
16901        _this7.showSuccessOverLay();
16902        _this7.resetForm();
16903        $('[data-js="protocol-file"]').val(null);
16904        $('[data-js="protocol-file-label"]').text('Anexar um arquivo');
16905        $('[data-js="remove-attachment"]').addClass('d-none');
16906      };
16907
16908      var handleErrors = function handleErrors(err) {
16909        if (err) {
16910          LoaderService.hide();
16911          _this7.submitProtocol.attr('disabled', false);
16912          AlertConfirmation.showAEM('data-js="alert-protocol-sending-error"');
16913          return;
16914        }
16915
16916        completeChain();
16917      };
16918      createCase().then(getfileAttached).then(createContentVersion).then(getContentDocumentId).then(createContentDocumentLink).then(completeChain).catch(handleErrors);
16919    }
16920  }, {
16921    key: 'parseContentDocumentLink',
16922    value: function parseContentDocumentLink(contentDocumentId, caseId) {
16923      return {
16924        ContentDocumentId: contentDocumentId,
16925        LinkedEntityId: caseId,
16926        Visibility: "AllUsers"
16927      };
16928    }
16929  }, {
16930    key: 'parseFormAttachmentRequest',
16931    value: function parseFormAttachmentRequest(file, fileBase64) {
16932      return {
16933        title: "Anexo JCA",
16934        PathOnClient: file.name,
16935        ContentLocation: "S",
16936        VersionData: fileBase64
16937      };
16938    }
16939  }, {
16940    key: 'getFormParameters',
16941    value: function getFormParameters() {
16942      var phoneFormatted = '' + (this.dddField.val() + this.phoneField.val().replace(/\D/g, ''));
16943
16944      var getDateBuy = function getDateBuy() {
16945        var dateBuyValue = $('[data-js="input-date-buy"]').val();
16946
16947        if (dateBuyValue === '') return null;
16948
16949        var dateBuyFormatted = DateFormatter.reverseDate(dateBuyValue);
16950        return new Date(dateBuyFormatted).toISOString();
16951      };
16952
16953      var getTripDateTimeFormatted = function getTripDateTimeFormatted() {
16954        var tripDate = $('[data-js="input-date-trip"]').val();
16955
16956        if (tripDate === '') return null;
16957
16958        var tripDateTimeFormatted = DateFormatter.reverseDate(tripDate);
16959        var hour = $('[data-js="trip-hour"]').val() ? $('[data-js="trip-hour"]').val() : '00:00';
16960        var tripDateTime = tripDateTimeFormatted + 'T' + hour;
16961
16962
16963        return new Date(tripDateTime).toISOString();
16964      };
16965
16966      // AEM Cusotm Code
16967      var typeText = this.protocolType.next().text();
16968      var optArr = $('[data-js="type"]').find('option');
16969
16970      var typeValue = optArr.filter(function (index, el) {
16971        return $(el)[0].innerText.toLowerCase() == typeText.toLowerCase();
16972      });
16973
16974      return {
16975        'Origin': "Web",
16976        'RecordTypeId': "0121N000001DlZt",
16977        'NomeEmpresa': this.companyField.next().text(),
16978        'SuppliedName': this.nameField.val(),
16979        'SuppliedEmail': this.emailField.val(),
16980        'SuppliedPhone': phoneFormatted,
16981        'CPF': this.documentNumber.val().replace(/\D/g, ''),
16982        'Type': typeValue.val(),
16983        'Motivo': this.protocolReason.val(),
16984        'SubMotivo': this.protocolSubreason.val(),
16985        'CompraRealizada': ($('[data-js="has-bought"]:checked').length > 0) ? 'Sim' : 'Não',
16986        'LocalFato': $('[data-js="input-local"]').val(),
16987        'DataCompra': getDateBuy(),
16988        'OrigemViagemWeb': $('[data-js="input-origin"]').val(),
16989        'DestinoViagemWeb': $('[data-js="input-dest"]').val(),
16990        'DataHoraViagem': getTripDateTimeFormatted(),
16991        'NomeImpressoCartao': $('[data-js="card-user-name"]').val(),
16992        'BandeiraCartao': $('[data-js="card-flag"]').val(),
16993        'ValorTotalCompra': $('[data-js="total-price"]').val(),
16994        'X4UltimosDigitosCartao': $('[data-js="4-digits"]').val(),
16995        'X6PrimeirosDigitosCartao': $('[data-js="6-digits"]').val(),
16996        'description': this.isCancelForm ? this.requestDescription : this.protocolDescription.val()
16997      };
16998    }
16999  }, {
17000    key: 'filterProtocolData',
17001    value: function filterProtocolData(protocolData) {
17002      var types = protocolData.selects.tipos;
17003      var reasons = protocolData.selects.motivos;
17004      this.reasons = reasons;
17005
17006      if (!this.getParam('type')) {
17007        try {
17008          types = types.filter(function (type) {
17009            return type.specialItem == false;
17010          });
17011        } catch (error) {
17012          console.log(error);
17013        }
17014      }
17015
17016      this.protocolData.selects.tipos = types;
17017      this.protocolData.selects.motivos = reasons;
17018      return this.protocolData;
17019    }
17020  }, {
17021    key: 'fillSelectsFromData',
17022    value: function fillSelectsFromData() {
17023      var _this7 = this;
17024
17025      var _protocolData$selects4 = this.protocolData.selects,
17026        empresas = _protocolData$selects4.empresas,
17027        documentos = _protocolData$selects4.documentos,
17028        tipos = _protocolData$selects4.tipos,
17029        cartoes = _protocolData$selects4.cartoes;
17030
17031
17032      var companySelect = $('[data-js="select-company"]');
17033      var typeSelect = $('[data-js="type"]');
17034      var cardFlagSelect = $('[data-js="card-flag"]');
17035      var typeDocSelect = $('[data-js="type-doc"]');
17036
17037      empresas.forEach(function (company) {
17038        var option = new Option(company.text, company.value);
17039        companySelect.append(option);
17040        _this7.selectCustom.initSingle(companySelect.parent());
17041      });
17042
17043      tipos.forEach(function (type) {
17044        var option = new Option(type.text, type.value);
17045        typeSelect.append(option);
17046        _this7.selectCustom.initSingle(typeSelect.parent());
17047      });
17048
17049      documentos.forEach(function (doc) {
17050        var option = new Option(doc.text, doc.value);
17051        typeDocSelect.append(option);
17052        _this7.selectCustom.initSingle(typeDocSelect.parent());
17053      });
17054
17055      cartoes.forEach(function (card) {
17056        var option = new Option(card.text, card.value);
17057        cardFlagSelect.append(option);
17058        _this7.selectCustom.initSingle(cardFlagSelect.parent());
17059      });
17060    }
17061  }, {
17062    key: 'activateOptionPayment',
17063    value: function activateOptionPayment() {
17064      var optionPayment = $('[data-js="option-payment-container"]');
17065      optionPayment.show();
17066      optionPayment.children().find("input, select").each(function (idx, el) {
17067        $(el).attr('required', true);
17068      });
17069    }
17070  }, {
17071    key: 'deactivateOptionPayment',
17072    value: function deactivateOptionPayment() {
17073      var _this8 = this;
17074
17075      var optionPayment = $('[data-js="option-payment-container"]');
17076      optionPayment.hide();
17077      optionPayment.children().find("input, select").each(function (idx, el) {
17078        $(el).attr('required', false);
17079        _this8.removeInvalidClass(el);
17080      });
17081    }
17082  }, {
17083    key: 'selectTypeReason',
17084    value: function selectTypeReason(motivo, motivos, callback) {
17085      var reasonSelect = $('#reason');
17086      this.selectCustom.eraseSelect(reasonSelect);
17087
17088      var mtvsel = $(motivo).val();
17089      var motivosSelecionados = motivos.filter(function (motivo) {
17090        if (motivo.value.trim() == mtvsel.trim()) {
17091          return motivo;
17092        }
17093      });
17094
17095      motivosSelecionados.forEach(function (motivo) {
17096        var option = new Option(motivo.text, motivo.crmValue);
17097        reasonSelect.append(option);
17098      });
17099      this.selectCustom.initSingle(reasonSelect.parent(), 'disabled');
17100
17101      return callback();
17102    }
17103  }, {
17104    key: 'isFormValid',
17105    value: function isFormValid() {
17106      return this.areRequiredFieldsSubmitted() && this.isCpfValid() && this.isEmailValid() && this.areLocationsValid();
17107    }
17108  }, {
17109    key: 'isFormProtocolValid',
17110    value: function isFormProtocolValid() {
17111      var inputLocalValid = $('[data-js="input-local"]');
17112      var inputLocalValue = inputLocalValid.val().trim();
17113
17114      if (this.areRequiredFieldsSubmitted() && inputLocalValue !== '') {
17115        $('[data-js="submit-protocol"]').prop('disabled', false);
17116      }
17117    }
17118  }, {
17119    key: 'areLocationsValid',
17120    value: function areLocationsValid() {
17121      var _this9 = this;
17122
17123      var origin = $('[data-js="input-origin"]');
17124      var dest = $('[data-js="input-dest"]');
17125      var local = $('[data-js="input-local"]');
17126
17127      var arr = [local, origin, dest];
17128      var allFieldsValid = true;
17129      arr.forEach(function (input) {
17130        if (!input.data("valid") && input.is(':required')) {
17131          _this9.addInvalidClass(input[0]);
17132          allFieldsValid = false;
17133        }
17134      });
17135
17136      if (!allFieldsValid) {
17137        $('[data-js="message-error"]').fadeIn();
17138        Utils.scrollTop();
17139        return false;
17140      }
17141
17142      return true;
17143    }
17144  }, {
17145    key: 'areRequiredFieldsSubmitted',
17146    value: function areRequiredFieldsSubmitted() {
17147      var _this12 = this;
17148
17149      var allFieldsValid = true;
17150      this.protocolForm.find('input[required], select[required], textarea[required]').each(function (idx, el) {
17151        var value = $(el).val();
17152        if (value == null || value.length === 0) {
17153          _this12.addInvalidClass(el);
17154          allFieldsValid = false;
17155        } else {
17156          _this12.removeInvalidClass(el);
17157        }
17158      });
17159      return allFieldsValid;
17160    }
17161  }, {
17162    key: 'addInvalidClass',
17163    value: function addInvalidClass(el, showTip) {
17164      if (el.nodeName === "SELECT") $(el).siblings('.select-selected').addClass('invalid'); else if ($(el).attr('required')) {
17165        $(el).addClass("invalid");
17166      }
17167      if (showTip && $(el).next().hasClass("tips")) {
17168        var $tips = $(el).next();
17169        $tips.find('.tip').show();
17170      }
17171      if (el.nodeName === "TEXTAREA" && $(el).next().hasClass("tips")) {
17172        var _$tips = $(el).next();
17173        _$tips.find('.tip').text($('[data-js="text-area-tip-warning"]').val());
17174      }
17175    }
17176  }, {
17177    key: 'removeInvalidClass',
17178    value: function removeInvalidClass(el) {
17179      if (el.nodeName === "SELECT") $(el).siblings('.select-selected').removeClass('invalid'); else $(el).removeClass("invalid");
17180      if ($(el).next().hasClass("tips")) {
17181        var $tips = $(el).next();
17182        $tips.find('.tip').hide();
17183      }
17184    }
17185  }, {
17186    key: 'isCpfValid',
17187    value: function isCpfValid() {
17188      var inputDoc = $('[data-js="doc-number"]');
17189      var docNumber = $('[data-js="doc-number"]').val().replace(/\D/g, '');
17190      var regex = new RegExp(/^(\d)(?!\1*$)\d+$/gm);
17191
17192      if (!regex.test(docNumber)) {
17193        $('[data-js="message-error"]').fadeIn();
17194        this.addInvalidClass(inputDoc);
17195        Utils.scrollTop();
17196        return false;
17197      } else {
17198        return true;
17199      }
17200    }
17201  }, {
17202    key: 'getOrigin',
17203    value: function getOrigin() {
17204      var _this11 = this;
17205
17206      var localidades = this.protocolData.selects.localidades;
17207
17208
17209      var parsedLocalidades = this.parseToAutoCompleteFormat(localidades);
17210      $('[data-js="input-origin"], [data-js="input-local"]').autocomplete({
17211        messages: {
17212          noResults: this.noResultMessage,
17213          results: function results(amount) {
17214            var singular = _this11.singleResultMessage;
17215            var protip = _this11.protip;
17216            if (amount == 1) return singular + " " + protip; else {
17217              var multipleResultMessage = _this11.multipleResultMessage.replace("#amount", amount);
17218              return multipleResultMessage + " " + protip;
17219            }
17220          }
17221        },
17222        minLength: 0,
17223        source: parsedLocalidades,
17224        select: function select(e, ui) {
17225          $(e.target).data("valid", ui.item.valid);
17226          $(e.target).val(ui.item.label);
17227          $(e.target).removeClass('invalid');
17228          if ($(e.target).data('js') === 'input-origin') _this11.getDestination(localidades, ui.item.label);
17229
17230          return false;
17231        },
17232        focus: function focus(e, ui) {
17233          return false;
17234        }
17235      }).blur(function (e) {
17236        if (!$(e.target).data("valid")) {
17237          _this11.addInvalidClass($(e.target)[0]);
17238          $(e.target).val('');
17239        }
17240      }).change(function (e) {
17241        var localLabel = void 0;
17242        var targetLabel = $(e.target).val().toUpperCase();
17243        var hasInJson = false;
17244
17245        parsedLocalidades.some(function (local, _) {
17246          localLabel = local.label.toUpperCase();
17247          if (targetLabel === localLabel) {
17248            hasInJson = targetLabel === localLabel;
17249            $(e.target).data("valid", local.valid);
17250            return true;
17251          }
17252        });
17253        if (!hasInJson) $(e.target).data("valid", null);
17254      }).focus(function (e) {
17255        var element = $(e.target);
17256        if (element.data("ui-autocomplete") && element.val().trim().length === 0) element.autocomplete("search", "");
17257      });
17258    }
17259  }, {
17260    key: 'getDestination',
17261    value: function getDestination(localidades, origin) {
17262      var _this12 = this;
17263
17264      var parsedLocalidades = this.parseToAutoCompleteFormat(localidades, origin);
17265      $('[data-js="input-dest"]').autocomplete({
17266        minLength: 0,
17267        source: parsedLocalidades,
17268        messages: {
17269          noResults: this.noResultMessage,
17270          results: function results(amount) {
17271            var singular = _this12.singleResultMessage;
17272            var protip = _this12.protip;
17273            if (amount == 1) return singular + " " + protip; else {
17274              var multipleResultMessage = _this12.multipleResultMessage.replace("#amount", amount);
17275              return multipleResultMessage + " " + protip;
17276            }
17277          }
17278        },
17279        select: function select(e, ui) {
17280          $(e.target).data("valid", ui.item.valid);
17281          $(e.target).val(ui.item.label);
17282          $(e.target).removeClass('invalid');
17283          return false;
17284        },
17285        focus: function focus(e, ui) {
17286          return false;
17287        }
17288      }).blur(function (e) {
17289        if (!$(e.target).data("valid")) {
17290          _this12.addInvalidClass($(e.target)[0]);
17291          $(e.target).val('');
17292        }
17293      }).change(function (e) {
17294        var localLabel = void 0;
17295        var targetLabel = $(e.target).val().toUpperCase();
17296        var hasInJson = false;
17297        parsedLocalidades.some(function (local, _) {
17298          localLabel = local.label.toUpperCase();
17299          if (targetLabel === localLabel) {
17300            hasInJson = targetLabel === localLabel;
17301            $(e.target).data("valid", local.valid);
17302            return true;
17303          }
17304        });
17305        if (!hasInJson) $(e.target).data("valid", null);
17306      }).focus(function (e) {
17307        var element = $(e.target);
17308        if (element.data("ui-autocomplete") && element.val().trim().length === 0) element.autocomplete("search", "");
17309      });
17310    }
17311  }, {
17312    key: 'parseToAutoCompleteFormat',
17313    value: function parseToAutoCompleteFormat(array) {
17314      var origin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
17315
17316      return array.reduce(function (acc, el) {
17317        if (origin === el.value) return acc;
17318
17319        acc.push({
17320          "valid": el.valid,
17321          "label": el.value
17322        });
17323        return acc;
17324      }, []);
17325    }
17326  }, {
17327    key: 'resetForm',
17328    value: function resetForm() {
17329      var _this14 = this;
17330
17331      $('[data-js="stepper-1"]').click();
17332      $('[data-js="stepper-2"]').removeClass('active');
17333      $('[data-js="form-contact-us"]').trigger('reset');
17334      $('[data-js="protocol-form"]').trigger('reset');
17335
17336      $('[data-js="protocol-form"], [data-js="form-contact-us"]').find(".select-custom").each(function (idx, el) {
17337        var select = $(el).children()[0];
17338        _this14.selectCustom.refreshSelect(select);
17339      });
17340
17341      $('input[type=radio]').prop('checked', false);
17342      $('input[type=radio]').siblings().removeClass('strong');
17343      $('[data-js="input-city"]').val('');
17344      $('[data-js="button-search"]').prop('disabled', true);
17345
17346      this.agenciesSearch = [];
17347    }
17348  }, {
17349    key: 'scrollToTopPosition',
17350    value: function scrollToTopPosition(top) {
17351      $('html, body').animate({
17352        scrollTop: top,
17353        behavior: 'smooth'
17354      });
17355    }
17356  }, {
17357    key: 'closeDatepicker',
17358    value: function closeDatepicker() {
17359      this.inputDateBuy.add(this.inputDateTrip).datepicker("hide").datepicker("destroy");
17360
17361      this.handleDatepicker();
17362    }
17363  }, {
17364    key: 'closeDatepickerModal',
17365    value: function closeDatepickerModal() {
17366      this.datepickerDiv.removeClass('opened');
17367      $('body, html').css('overflow', 'auto');
17368    }
17369  }, {
17370    key: 'setBackButtonListeners',
17371    value: function setBackButtonListeners() {
17372      var _this14 = this;
17373
17374      $(document).on('click', '.btn-conf-datepicker', function (e) {
17375        e.stopImmediatePropagation();
17376        _this14.closeDatepicker();
17377        _this14.closeDatepickerModal();
17378      });
17379
17380      $(document).on('click', '.datepicker-back-button', function (e) {
17381        e.stopImmediatePropagation();
17382        _this14.closeDatepicker();
17383        _this14.closeDatepickerModal();
17384      });
17385    }
17386  }, {
17387    key: 'insertDatepickerMobile',
17388    value: function insertDatepickerMobile(type) {
17389      var _this15 = this;
17390
17391      $('.datepicker-mobile').remove();
17392
17393      if (!Utils.isMobile()) return;
17394
17395      var labelText = type === 'buy-datepicker' ? 'DATA DA COMPRA:' : 'DATA DA VIAGEM';
17396
17397      var header = $('<div class=\'datepicker-mobile datepicker-header\'>\n        <span class="datepicker-back-button" data-js="datepicker-back-btn">\n          <em class="jca-ico-angle-left" aria-hidden="true"></em>\n        </span>\n        <h4 class=\'header-datepicker\'>\n          ' + labelText + '\n        </h4>\n      </div>');
17398
17399      var footer = $('<div class=\'datepicker-mobile datepicker-footer\'>\n        <button class=\'btn-conf-datepicker\'>\n Selecionar \n        </button>\n      </div>');
17400
17401      $('body, html').css('overflow-y', 'hidden');
17402
17403      setTimeout(function () {
17404        header.prependTo('#ui-datepicker-div');
17405        footer.appendTo('#ui-datepicker-div');
17406        _this15.datepickerDiv.addClass('opened');
17407      }, 5);
17408    }
17409  }, {
17410    key: 'setMonthsDatepicker',
17411    value: function setMonthsDatepicker(mobileNumberOfMonths, deskNumberOfMonths, element) {
17412      element.datepicker("option", "numberOfMonths", Utils.isMobile() ? mobileNumberOfMonths : deskNumberOfMonths);
17413    }
17414  }, {
17415    key: 'setDatePickerReadonly',
17416    value: function setDatePickerReadonly() {
17417      if (Utils.isMobile()) {
17418        this.inputDateBuy.attr('readonly', true);
17419        this.inputDateTrip.attr('readonly', true);
17420      } else {
17421        this.inputDateBuy.removeAttr('readonly');
17422        this.inputDateTrip.removeAttr('readonly');
17423      }
17424    }
17425  }, {
17426    key: 'closeDatepickerAfterSelect',
17427    value: function closeDatepickerAfterSelect(datepicker) {
17428      if (Utils.getWindowSize().width > Utils.getWindowSize().breakpoints.LG) {
17429        return datepicker.inline = false;
17430      }
17431    }
17432  }, {
17433    key: 'handleDatepicker',
17434    value: function handleDatepicker() {
17435      var _this16 = this;
17436
17437      this.setDatePickerReadonly();
17438
17439      this.inputDateBuy.mask('99/99/9999');
17440      this.inputDateBuy.datepicker({
17441        numberOfMonths: 1,
17442        dateFormat: DateFormatter.getDateFormat(),
17443        dayNamesMin: DateFormatter.getDayNamesMin(),
17444        monthNames: DateFormatter.getMonthNames(),
17445        showAnim: Utils.isMobile() ? '' : 'slideDown',
17446        maxDate: new Date(),
17447        autoClose: true,
17448        beforeShow: function beforeShow(_, datepicker) {
17449          _this16.insertDatepickerMobile('buy-datepicker');
17450          _this16.setMonthsDatepicker(12, 1, _this16.inputDateBuy);
17451
17452          $('#wemobi-header').addClass('opened-overlay');
17453          setTimeout(function () {
17454            if (!Utils.isMobile()) {
17455              var datepickerRef = $(datepicker.dpDiv);
17456              var datepickerTopOffset = _this16.inputDateBuy.offset().top + 36;
17457              datepickerRef.offset({ top: datepickerTopOffset });
17458            }
17459          }, 5);
17460        },
17461        onSelect: function onSelect(_, datepicker) {
17462          datepicker.inline = true;
17463          _this16.insertDatepickerMobile('buy-datepicker');
17464          _this16.closeDatepickerAfterSelect(datepicker);
17465        },
17466        onClose: function onClose(_, datepicker) {
17467          _this16.removeInvalidClass(datepicker.input);
17468          $('#wemobi-header').removeClass('opened-overlay');
17469          $('body, html').css('overflow', 'auto');
17470        }
17471      }).on('focus', function () {
17472        $(this).trigger('blur');
17473      });
17474
17475      this.inputDateTrip.mask('99/99/9999');
17476      this.inputDateTrip.datepicker({
17477        numberOfMonths: 1,
17478        dateFormat: DateFormatter.getDateFormat(),
17479        dayNamesMin: DateFormatter.getDayNamesMin(),
17480        monthNames: DateFormatter.getMonthNames(),
17481        showAnim: Utils.isMobile() ? '' : 'slideDown',
17482        beforeShow: function beforeShow(el, datepicker) {
17483          _this16.insertDatepickerMobile('trip-datepicker');
17484          _this16.setMonthsDatepicker(12, 1, _this16.inputDateTrip);
17485
17486          setTimeout(function () {
17487            if (!Utils.isMobile()) {
17488              var datepickerRef = $(datepicker.dpDiv);
17489              var datepickerTopOffset = _this16.inputDateTrip.offset().top + 36;
17490              datepickerRef.offset({ top: datepickerTopOffset });
17491            }
17492          }, 5);
17493        },
17494        onSelect: function onSelect(dateStr, datepicker) {
17495          datepicker.inline = true;
17496          _this16.insertDatepickerMobile('trip-datepicker');
17497          _this16.closeDatepickerAfterSelect(datepicker);
17498        },
17499        onClose: function onClose(el, datepicker) {
17500          _this16.removeInvalidClass(datepicker.input);
17501          $('body, html').css('overflow', 'auto');
17502        }
17503      }).on('focus', function () {
17504        $(this).trigger('blur');
17505      });
17506
17507      this.inputDateTrip.add(this.inputDateBuy).focusout(function (e) {
17508        var input = $(e.currentTarget);
17509        var dateString = input.val().split('/').reverse().join('/');
17510        var date = new Date(dateString);
17511        var today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
17512        if (isNaN(date) || date <= today) date = today;
17513        dateString = DateFormatter.parseDateFormat(date);
17514        if (!input.data("date") || input.data('date') != dateString) {
17515          input.val(dateString);
17516          input.data("date", dateString);
17517        }
17518      });
17519
17520      this.setBackButtonListeners();
17521    }
17522  }, {
17523    key: 'loadButtonActions',
17524    value: function loadButtonActions() {
17525      this.backButton.click(function (e) {
17526        window.history.back();
17527      });
17528    }
17529  }, {
17530    key: 'scrollToElement',
17531    value: function scrollToElement($el) {
17532      var _Utils$getWindowSize = Utils.getWindowSize(),
17533        width = _Utils$getWindowSize.width,
17534        breakpoints = _Utils$getWindowSize.breakpoints;
17535
17536      var headerHeight = $el ? $el.outerHeight() : 0;
17537      headerHeight = width > breakpoints.LG ? headerHeight : 1.5 * headerHeight;
17538      var offset = $el ? $el.offset().top : 0;
17539      this.currentTop = this.currentTop == offset - headerHeight ? 0 : offset - headerHeight;
17540      window.scroll({
17541        top: this.currentTop,
17542        behavior: 'smooth'
17543      });
17544    }
17545  }, {
17546    key: 'loadTabs',
17547    value: function loadTabs() {
17548      var self = this;
17549      this.selectorCollapse.click(function (e) {
17550        var _this17 = this;
17551
17552        e.preventDefault();
17553        var active = $('li').next('#collapse-internal');
17554        var internal = $(this).next('#collapse-internal');
17555        var verifyOpen = $(this).next('#collapse-internal:visible');
17556        var agencyBox = $('.agency-box-content');
17557
17558        agencyBox.empty();
17559        $(active).not(internal).hide();
17560        $(this).next('div').slideToggle('fast', function () {
17561          self.resetForm();
17562          $('span').not($(_this17).find('.arrow-up')).removeClass('arrow-up');
17563          $('.active').removeClass('active');
17564          if (verifyOpen.length == 0) {
17565            $(_this17).find('.arrow-down').addClass('arrow-up');
17566            $(_this17).addClass('active');
17567          } else {
17568            $('.arrow-down').removeClass('arrow-up');
17569          }
17570          var $el = e.target.tagName === 'LI' ? $(e.target) : $(e.currentTarget);
17571          self.scrollToElement($el);
17572        });
17573      });
17574    }
17575  }, {
17576    key: 'loadText',
17577    value: function loadText() {
17578      this.selectorCollapseInternalText.click(function (e) {
17579        e.preventDefault();
17580        var active = $(this).find('li').next('.information-internal-container-text');
17581        var internal = $(this).next('.information-internal-container-text');
17582        var verifyOpen = $(this).next('.information-internal-container-text:visible');
17583
17584        $(active).not(internal).hide();
17585        $(this).next('.information-internal-container-text').slideToggle('slow');
17586        $(this).find('span').not($(this).find('.arrow-up')).removeClass('arrow-up');
17587        $(this).find('li').not($(this)).removeClass('active-tab');
17588        $(this).addClass('active-tab');
17589
17590        if (verifyOpen.length == 0) {
17591          $(this).find('.arrow-down').addClass('arrow-up');
17592        } else {
17593          $(this).find('.arrow-down').removeClass('arrow-up');
17594        }
17595      });
17596    }
17597  }, {
17598    key: 'verifyRadio',
17599    value: function verifyRadio() {
17600      var _this18 = this;
17601
17602      var selectorSeachForm = $('[data-js="search-form"]');
17603
17604      this.selectorRadioCep.click(function () {
17605        if ($(this).is(':checked')) {
17606          selectorSeachForm.slideDown();
17607          $($('[data-js="label-radio-cep"]').children()[2]).addClass('strong');
17608          $($('[data-js="label-radio-gps"]').children()[2]).removeClass('strong');
17609        }
17610      });
17611
17612      this.selectorRadioGps.click(function () {
17613        if ($(this).is(':checked')) {
17614          selectorSeachForm.hide();
17615          $($('[data-js="label-radio-gps"]').children()[2]).addClass('strong');
17616          $($('[data-js="label-radio-cep"]').children()[2]).removeClass('strong');
17617        }
17618      });
17619
17620      $($('[data-js="outside-gps"]').click(function () {
17621        return _this18.selectorRadioGps.click();
17622      }));
17623      $($('[data-js="outside-cep"]').click(function () {
17624        return _this18.selectorRadioCep.click();
17625      }));
17626    }
17627  }, {
17628    key: 'enableSearchButton',
17629    value: function enableSearchButton() {
17630      this.formCity.find('[data-js="button-search"], [data-js="input-services-agency"], .select-selected').each(function () {
17631        $(this).attr('disabled', false);
17632        if ($(this).hasClass('disabled')) $(this).removeClass('disabled');
17633      });
17634    }
17635  }, {
17636    key: 'disableSearchButton',
17637    value: function disableSearchButton() {
17638      this.formCity.find('[data-js="button-search"], [data-js="input-services-agency"], .select-selected').each(function () {
17639        $(this).attr('disabled', true);
17640        if ($(this).hasClass('select-selected')) $(this).addClass('disabled');
17641      });
17642    }
17643  }, {
17644    key: 'loadServices',
17645    value: function loadServices() {
17646      var _this19 = this;
17647
17648      var self = this;
17649      var getUrl = '';
17650      var regra = /^[0-9]+$/;
17651      var regra2 = /[0-9]{5}-[0-9]{3}/;
17652
17653      this.inputCity.on('input', function (e) {
17654        var valInput = $(e.target).val();
17655        $('.agency-box-text').text('');
17656
17657        if (valInput.length >= 3) {
17658          getUrl = valInput.match(regra) || valInput.match(regra2) ? "?zipCode=" + valInput : "?city=" + removeAcento(valInput);
17659          var currentLang = Utils.getCurrentLang();
17660          if (currentLang !== 'pt-br') {
17661            getUrl = getUrl + "&lang=" + currentLang;
17662          }
17663
17664          self.inputServiceAgency.find('option').each(function (index, value) {
17665            if (index > 0) value.remove();
17666          });
17667
17668          HttpService.getFromCompany('agencies.json' + getUrl).done(function (data) {
17669            self.agenciesSearch = data.result;
17670            _this19.selectCustom.eraseSelect(self.inputServiceAgency);
17671
17672            if (self.agenciesSearch.length > 0) {
17673              self.enableSearchButton();
17674              var listServices = [];
17675              self.agenciesSearch.forEach(function (agency) {
17676                var agencyServices = agency.services;
17677                agencyServices.forEach(function (service) {
17678                  if ($.inArray(service, listServices) === -1) {
17679                    listServices.push(service);
17680                  }
17681                });
17682              });
17683
17684              listServices.sort().forEach(function (service, index, arr) {
17685                var option = void 0;
17686                if (index === 0) {
17687                  option = new Option('Todos os serviços', 0);
17688                  self.inputServiceAgency.append($(option));
17689                  _this19.selectCustom.initSingle(self.inputServiceAgency.parent());
17690                }
17691                option = new Option(service, service);
17692                self.inputServiceAgency.append($(option));
17693                _this19.selectCustom.initSingle(self.inputServiceAgency.parent());
17694              });
17695            } else {
17696              if (self.inputServiceAgency.find('option').length <= 1) {
17697                self.disableSearchButton();
17698                $('.agency-box-content').empty();
17699              }
17700            }
17701          });
17702        } else {
17703          if (valInput.trim().length < 3) self.disableSearchButton();
17704          $('.agency-box-content').empty();
17705        }
17706      });
17707    }
17708  }, {
17709    key: 'loadAgenciesSearch',
17710    value: function loadAgenciesSearch() {
17711      var inputServiceAgency = this.inputServiceAgency;
17712      var self = this;
17713      this.buttonSearch.click(function () {
17714        var listAgency = [];
17715        var listService = [];
17716        var countAgency = 0;
17717        var boxAgency = $('.agency-box-content');
17718        boxAgency.empty();
17719
17720        //por cidade
17721        $.each(self.agenciesSearch, function (index, element) {
17722          if ($.inArray(inputServiceAgency.val(), element.services) > -1) {
17723            var servicesItens = element.services.toString();
17724            var itensServiceList = servicesItens.split(',');
17725            listService.push(itensServiceList);
17726            countAgency++;
17727            listAgency.push('<div class="agency-box">' + '<em class="jca-ico-pin-map" aria-hidden="true"></em>' + '<div class="agency-infos">' + '<div class="agency-infos-header">' + '<span class="agency-infos-title">' + element.city + ' - ' + element.local + '</span>' + '<span class="agency-infos-text">' + element.address + '</span>' + '</div>' + '<div class="agency-infos-content">' + '<span class="agency-infos-title">HORÁRIOS DE ATENDIMENTO</span><span class="agency-infos-text">' + element.businessHours + ' </span>' + '<span class="agency-infos-title">SERVIÇOS DISPONÍVEIS</span>' + '<span class="agency-infos-text"><ul><li>' + itensServiceList.join('</li><li>') + '</li></ul></span></div>' + '</div>');
17728          } else if (inputServiceAgency.val() == null || inputServiceAgency.val() === '0') {
17729            var _servicesItens = element.services.toString();
17730            var _itensServiceList = _servicesItens.split(',');
17731            listService.push(_itensServiceList);
17732            countAgency++;
17733            listAgency.push('<div class="agency-box">' + '<em class="jca-ico-pin-map" aria-hidden="true"></em>' + '<div class="agency-infos">' + '<div class="agency-infos-header">' + '<span class="agency-infos-title">' + element.city + ' - ' + element.local + '</span>' + '<span class="agency-infos-text">' + element.address + '</span>' + '</div>' + '<div class="agency-infos-content">' + '<span class="agency-infos-title">HORÁRIOS DE ATENDIMENTO</span><span class="agency-infos-text">' + element.businessHours + ' </span>' + '<span class="agency-infos-title">SERVIÇOS DISPONÍVEIS</span>' + '<span class="agency-infos-text"><ul><li>' + _itensServiceList.join('</li><li>') + '</li></ul></span></div>' + '</div>');
17734          }
17735        });
17736
17737        if (countAgency <= 1) {
17738          $('.agency-box-text').text('Foi encontrada' + ' ' + countAgency + ' ' + 'agência próxima à sua localização');
17739        } else {
17740          $('.agency-box-text').text('Foram encontradas' + ' ' + countAgency + ' ' + ' agências próximas à sua localização.');
17741        }
17742
17743        boxAgency.append(listAgency);
17744        $('.agency-box-content').addClass('flexibilize');
17745      });
17746    }
17747  }, {
17748    key: 'isEmailValid',
17749    value: function isEmailValid() {
17750      var regex = new RegExp(/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/gm);
17751      var emailLowerCase = this.emailField.val().toLowerCase();
17752      if (!regex.test(emailLowerCase)) {
17753        this.showErrorMessage('Endereço de email não é válido.');
17754        this.addInvalidClass(this.emailField, true);
17755        Utils.scrollTop();
17756        return false;
17757      } else {
17758        return true;
17759      }
17760    }
17761  }, {
17762    key: 'setFontSize',
17763    value: function setFontSize() {
17764      $(".information-page").on('DOMSubtreeModified', ".ui-autocomplete", function () {
17765        $('.ui-menu > .ui-menu-item > .ui-menu-item-wrapper').css({
17766          'font-size': '10px'
17767        });
17768      });
17769    }
17770  }, {
17771    key: 'showSuccessOverLay',
17772    value: function showSuccessOverLay(message) {
17773      Utils.scrollTop();
17774      AlertConfirmation.showAEM('data-js="alert-protocol-successfully-sent"');
17775    }
17776  }, {
17777    key: 'datepickerDiv',
17778    get: function get() {
17779      return $('#ui-datepicker-div');
17780    }
17781  }, {
17782    key: 'inputDateBuy',
17783    get: function get() {
17784      return $('[data-js="input-date-buy"]');
17785    }
17786  }, {
17787    key: 'inputDateTrip',
17788    get: function get() {
17789      return $('[data-js="input-date-trip"]');
17790    }
17791  }]);
17792
17793  return InformationController;
17794}();
17795
17796setTimeout(function () {
17797  jQuery.ui.autocomplete.prototype._resizeMenu = function () {
17798    var ul = this.menu.element;
17799    ul.outerWidth(this.element.outerWidth());
17800  };
17801}, 100);
17802
17803var textarea = {
17804  placeholder: {
17805    original: 'Conte para nós o que aconteceu.',
17806    custom: 'Descreva o objeto (cor, marca, tamanho, tipo etc), no caso de documentos, favor informar o tipo de documento (RG, CNH, Passaporte, etc...) e a numeração.'
17807  }
17808}
17809
17810/**
17811 *
17812 * InformationController
17813 *
17814 * FIM
17815 *
17816 */
17817
17818'use strict';
17819
17820var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
17821
17822function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
17823
17824/**
17825 * INICIO
17826 * LOGICA COMPANY SERVICE
17827 *
17828*/
17829var CompanyService = function () {
17830  function CompanyService() {
17831    _classCallCheck(this, CompanyService);
17832  }
17833
17834  _createClass(CompanyService, null, [{
17835    key: 'loadCompanyTemplate',
17836    value: function loadCompanyTemplate(callback) {
17837      var url = '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/assets/company.html';
17838      $.ajax({
17839        url: url,
17840        contentType: 'text/html',
17841        type: 'GET',
17842        headers: {
17843          'grupo_jca_auth': 'OA4XqR0LnBBxFkkToX5pUzcnAI2wX1sxeY4YtwXVyNoZyEt66Hg3Zg=='
17844        },
17845        success: function success(data) {
17846          return callback(null, data);
17847        },
17848        error: function error(_, textStatus, errorThrown) {
17849          console.log(textStatus, errorThrown);
17850          return callback(errorThrown, null);
17851        }
17852      });
17853    }
17854  }]);
17855
17856  return CompanyService;
17857}();
17858/**
17859 * FIM
17860 * LOGICA COMPANY SERVICE
17861 *
17862*/
17863'use strict';
17864
17865var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
17866
17867function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
17868
17869/**
17870 * INICIO
17871 * LOGICA DATE FORMATTER
17872 *
17873 */
17874
17875var DateFormatter = function () {
17876  function DateFormatter() {
17877    _classCallCheck(this, DateFormatter);
17878  }
17879
17880  _createClass(DateFormatter, null, [{
17881    key: 'getNewFormattedDate',
17882    value: function getNewFormattedDate() {
17883      var date = new Date();
17884      var month = ('0' + (1 + date.getMonth())).slice(-2);
17885      var day = ('0' + date.getDate()).slice(-2);
17886      var hour = ('0' + date.getHours()).slice(-2);
17887      var minute = ('0' + date.getMinutes()).slice(-2);
17888      return date.getFullYear() + '-' + month + '-' + day + 'T' + hour + ':' + minute;
17889    }
17890  }, {
17891    key: 'getValidDateFormat',
17892    value: function getValidDateFormat(date) {
17893      var formattedDate = void 0,
17894        dateArray = void 0;
17895      if (typeof date === "string") {
17896        dateArray = date.split('T');
17897        formattedDate = dateArray[0] + 'T' + (dateArray[1] ? dateArray[1] : '12:00:00');
17898        return new Date(formattedDate);
17899      }
17900      if (!date) {
17901        return new Date();
17902      }
17903      return date;
17904    }
17905
17906    //Compares two dates. Returns 0 if they are in the same day. If not, returns 1 if
17907    //the first date is after the second. If not, returns -1
17908
17909  }, {
17910    key: 'isTheSameDay',
17911    value: function isTheSameDay(date1, date2) {
17912      var day1 = DateFormatter.getValidDateFormat(date1);
17913      var day2 = DateFormatter.getValidDateFormat(date2);
17914      var isTheSameDay = day1.getDate() === day2.getDate() && day1.getMonth() === day2.getMonth() && day1.getFullYear() === day2.getFullYear();
17915      if (isTheSameDay) return 0; else {
17916        if (day1.getTime() > day2.getTime()) return 1; else return -1;
17917      }
17918    }
17919  }, {
17920    key: 'compareWithMinTime',
17921    value: function compareWithMinTime(minDateString, dateString) {
17922      var date = DateFormatter.getValidDateFormat(dateString);
17923      var minDate = DateFormatter.getValidDateFormat(minDateString);
17924      return date.getTime() >= minDate.getTime();
17925    }
17926  }, {
17927    key: 'formatTimeString',
17928    value: function formatTimeString(time) {
17929      var hourDigits = time.trim().split(':')[0];
17930      var minutesDigits = time.trim().split(':')[1];
17931      hourDigits = ('0' + hourDigits).slice(-2);
17932      minutesDigits = ('0' + minutesDigits).slice(-2);
17933      return hourDigits + ":" + minutesDigits;
17934    }
17935  }, {
17936    key: 'formatTimeFromString',
17937    value: function formatTimeFromString(dateString) {
17938      var userLang = Utils.getCurrentLang();
17939      var time = dateString.split('T')[1].slice(0, 5);
17940
17941      if (userLang == 'en') {
17942        var hour = parseInt(time.split(':')[0]);
17943        var minute = time.split(':')[1];
17944        var period = 'AM';
17945        if (hour > 12) {
17946          hour = hour % 12;
17947          period = 'PM';
17948        }
17949        hour = ('0' + hour).slice(-2);
17950        return hour + ':' + minute + ' ' + period;
17951      }
17952
17953      return time;
17954    }
17955  }, {
17956    key: 'formatTime',
17957    value: function formatTime(date) {
17958      var cDate = DateFormatter.getValidDateFormat(date);
17959      var hours = cDate.getHours();
17960      hours = ('0' + hours).slice(-2);
17961      var minute = cDate.getMinutes();
17962      minute = ('0' + minute).slice(-2);
17963      return hours + ':' + minute;
17964    }
17965  }, {
17966    key: 'formatDate',
17967    value: function formatDate(date) {
17968      var str = '';
17969      var cDate = DateFormatter.getValidDateFormat(date);
17970      var day = cDate.getDate();
17971      day = ('0' + day).slice(-2);
17972      var month = 1 + cDate.getMonth();
17973      month = ('0' + month).slice(-2);
17974      str = str.concat(day).concat('/').concat(month).concat(' - ').concat(DateFormatter.formatTime(cDate));
17975      return str;
17976    }
17977  }, {
17978    key: 'formatDateFromString',
17979    value: function formatDateFromString(date) {
17980      var datePart = date.split(' ')[0];
17981      var timePart = date.split(' ')[1];
17982      datePart = datePart.split('-').reverse().slice(0, 2).join('/');
17983      return datePart + ' - ' + timePart;
17984    }
17985  }, {
17986    key: 'getDurationLabel',
17987    value: function getDurationLabel(saida, chegada) {
17988      var duration = DateFormatter.getDurationInteger(saida, chegada);
17989      var hours = Math.floor(duration / 3600);
17990      var seconds = duration % 3600;
17991      var minutes = 0;
17992      if (seconds >= 60) minutes = Math.floor(seconds / 60);
17993      var str = '';
17994      str = str.concat(hours).concat('h');
17995      if (minutes > 0) {
17996        minutes = ('0' + minutes).slice(-2);
17997        str = str.concat(minutes).concat('min');
17998      }
17999      return str;
18000    }
18001  }, {
18002    key: 'getDurationInteger',
18003    value: function getDurationInteger(saida, chegada) {
18004      var tDate = DateFormatter.getValidDateFormat(chegada).getTime();
18005      var fDate = DateFormatter.getValidDateFormat(saida).getTime();
18006      var diff = tDate - fDate;
18007      return Math.ceil(diff / 1000);
18008    }
18009  }, {
18010    key: 'extractHour',
18011    value: function extractHour(str) {
18012      var hour = str.replace(/([0-9])+[-]([0-9])+[-]([0-9])+[T]/, '');
18013      return hour.substr(0, 5);
18014    }
18015  }, {
18016    key: 'reverseDate',
18017    value: function reverseDate(str) {
18018      if (!str) return str;
18019      if (str.indexOf('/') > -1) {
18020        return str.split("/").reverse().join("-");
18021      } else {
18022        return str.split("-").reverse().join("/");
18023      }
18024    }
18025  }, {
18026    key: 'extractDate',
18027    value: function extractDate(str) {
18028      if (!str) return str;
18029      return str.split('T')[0];
18030    }
18031  }, {
18032    key: 'getDaysArray',
18033    value: function getDaysArray() {
18034      var userLang = Utils.getCurrentLang();
18035      switch (userLang) {
18036        case 'en':
18037          return ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
18038        case 'es':
18039          return ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'];
18040        default:
18041          return ['domingo', 'segunda', 'terça', 'quarta', 'quinta', 'sexta', 'sábado'];
18042      }
18043    }
18044  }, {
18045    key: 'getMonthsArray',
18046    value: function getMonthsArray() {
18047      var userLang = Utils.getCurrentLang();
18048      switch (userLang) {
18049        case 'en':
18050          return ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
18051        case 'es':
18052          return ["de enero", "de febrero", "de marzo", "de abril", "de mayo", "de junio", "de julio", "de agosto", "de septiembre", "de octubre", "de noviembre", "de diciembre"];
18053        default:
18054          return ["de janeiro", "de fevereiro", "de março", "de abril", "de maio", "de junho", "de julho", "de agosto", "de setembro", "de outubro", "de novembro", "de dezembro"];
18055      }
18056    }
18057  }, {
18058    key: 'daysInMonth',
18059    value: function daysInMonth(m, y) {
18060      switch (m) {
18061        case 1:
18062          return y % 4 == 0 && y % 100 || y % 400 == 0 ? 29 : 28;
18063        case 8:
18064        case 3:
18065        case 5:
18066        case 10:
18067          return 30;
18068        default:
18069          return 31;
18070      }
18071    }
18072  }, {
18073    key: 'isValidDate',
18074    value: function isValidDate(stringDate) {
18075      var date = DateFormatter.getValidDateFormat(stringDate);
18076      var m = date.getMonth();
18077      var d = date.getDate();
18078      var y = date.getFullYear();
18079      return m >= 0 && m < 12 && d > 0 && d <= DateFormatter.daysInMonth(m, y);
18080    }
18081  }, {
18082    key: 'getFullDate',
18083    value: function getFullDate(dateString) {
18084      var userLang = Utils.getCurrentLang();
18085      var dateWithoutTime = dateString.substring(0, 10).split('-');
18086      var month = DateFormatter.getMonthsArray()[parseInt(dateWithoutTime[1]) - 1];
18087      var year = dateWithoutTime[0];
18088      var day = "" + dateWithoutTime[2];
18089      switch (userLang) {
18090        case 'en':
18091          day = ('0' + day).slice(-2);
18092          return month + ' ' + day + ', ' + year;
18093        default:
18094          return day + ' ' + month + ' de ' + year;
18095      }
18096    }
18097  }, {
18098    key: 'getDateFormat',
18099    value: function getDateFormat() {
18100      var userLang = Utils.getCurrentLang();
18101      switch (userLang) {
18102        case "en":
18103          return "dd/mm/yy";
18104        case "es":
18105          return "dd/mm/yy";
18106        default:
18107          return "dd/mm/yy";
18108      }
18109    }
18110  }, {
18111    key: 'getDayNamesMin',
18112    value: function getDayNamesMin() {
18113      var userLang = Utils.getCurrentLang();
18114      switch (userLang) {
18115        case "en":
18116          return ["S", "M", "T", "W", "T", "F", "S"];
18117        case "es":
18118          return ["D", "L", "M", "M", "J", "V", "S"];
18119        default:
18120          return ["D", "S", "T", "Q", "Q", "S", "S"];
18121      }
18122    }
18123  }, {
18124    key: 'getMonthNames',
18125    value: function getMonthNames() {
18126      var userLang = Utils.getCurrentLang();
18127      switch (userLang) {
18128        case "en":
18129          return ["JANUARY /", "FEBRUARY /", "MARCH /", "APRIL /", "MAY /", "JUNE /", "JULY /", "AUGUST /", "SEPTEMBER /", "OCTOBER /", "NOVEM
18129BER /", "DECEMBER /"];
18130        case "es":
18131          return ["ENERO /", "FEBRERO /", "MARZO /", "ABRIL /", "MAYO /", "JUNIO /", "JULIO /", "AGOSTO /", "SEPTIEMBRE /", "OCTUBRE /", "NOVIEMBRE /", "DICIEMBRE /"];
18132        default:
18133          return ["JANEIRO /", "FEVEREIRO /", "MARÇO /", "ABRIL /", "MAIO /", "JUNHO /", "JULHO /", "AGOSTO /", "SETEMBRO /", "OUTUBRO /", "NOVEMBRO /", "DEZEMBRO /"];
18134      }
18135    }
18136  }, {
18137    key: 'parseDateApiFormat',
18138    value: function parseDateApiFormat(date) {
18139      var userLang = Utils.getCurrentLang();
18140      var parts = date.split("/");
18141      switch (userLang) {
18142        case "en":
18143          return parts[2] + "-" + parts[1] + "-" + parts[0];
18144        case "es":
18145          return parts[2] + "-" + parts[1] + "-" + parts[0];
18146        default:
18147          return parts[2] + "-" + parts[1] + "-" + parts[0];
18148      }
18149    }
18150  }, {
18151    key: 'parseDateApiFormatJWT',
18152    value: function parseDateApiFormat(date) {
18153      var parts = date.split("/");
18154      return parts[2] + "-" + parts[0] + "-" + parts[1];
18155    }
18156  }, {
18157    key: 'parseDateFormat',
18158    value: function parseDateFormat(date) {
18159      var parts = ['0'.concat(date.getDate()).slice(-2), '0'.concat(1 + date.getMonth()).slice(-2), date.getFullYear()];
18160      return parts[0] + "/" + parts[1] + "/" + parts[2];
18161    }
18162  }, {
18163    key: 'parseOffSet',
18164    value: function parseOffSet(dateService, offSetService) {
18165      var date = new Date(dateService);
18166      var offSet = +offSetService.split(':')[0].replace(/[-+]/g, '').replace('/^0+/g', '');
18167      date.setHours(date.getHours() + (offSetService.indexOf('-') >= 0 ? offSet : -offSet));
18168
18169      return date.getTime();
18170    }
18171  }, {
18172    key: 'removeToISOStringHoursAdded',
18173    value: function removeToISOStringHoursAdded(date) {
18174      var tzoffset = date.getTimezoneOffset() * 60000;
18175      var dateLocalISOTime = new Date(date - tzoffset).toISOString().slice(0, -1);
18176
18177      return dateLocalISOTime;
18178    }
18179  }, {
18180     key: 'getDateWithHour',
18181     value: function getDateWithHour(date) {
18182
18183       var validDate = DateFormatter.getValidDateFormat(date);
18184       var month = ('0' + (validDate.getMonth() + 1)).slice(-2);
18185       var day = ('0' + validDate.getDate()).slice(-2);
18186       var year = validDate.getFullYear();
18187       var hours = ('0' + validDate.getHours()).slice(-2);
18188       var minutes = ('0' + validDate.getMinutes()).slice(-2);
18189
18190       return month + '/' + day + '/' + year + ' ' + hours + ':' + minutes;
18191     }
18192   }]);
18193
18194  return DateFormatter;
18195}();
18196
18197DateFormatter.A_DAY = 24 * 60 * 60 * 1000;
18198
18199/**
18200 * FIM
18201 * LOGICA DATE FORMATTER
18202 *
18203 */
18204'use strict';
18205
18206var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
18207
18208function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
18209
18210/**
18211 * INICIO
18212 * INTERNAL API SERVICE
18213 *
18214 */
18215var InternalAPIService = function () {
18216  function InternalAPIService() {
18217    _classCallCheck(this, InternalAPIService);
18218  }
18219
18220  _createClass(InternalAPIService, null, [{
18221    key: 'loadInternalAPI',
18222    value: function loadInternalAPI(callback) {
18223      var _this = this;
18224      var siteName = Utils.getSiteNameForClasses();
18225      var contentClassesUrl = InternalAPIService.aemServiceHost + '/content/jca/' + siteName + '/jcr:content.classes.json';
18226      $.ajax({
18227        url: contentClassesUrl,
18228        contentType: 'json',
18229        type: 'GET',
18230        success: function success(data) {
18231          _this._contentClasses = data;
18232          callback(null, data);
18233        },
18234        error: function error(XMLHttpRequest, textStatus, errorThrown) {
18235          callback(errorThrown, null);
18236        }
18237      });
18238    }
18239  }, {
18240    key: 'addDetails',
18241    value: function addDetails(classtype, listDetails) {
18242      for (var i = 0; i < listDetails.length; i++) {
18243        var detail = listDetails[i];
18244        var classtypeDetails = new ClasstypeDetails();
18245        classtypeDetails.classDetailName = detail.classDetailName;
18246        classtypeDetails.classDetailDifferential = detail.classDetailDifferential;
18247        classtypeDetails.altTextDetail = detail.altTextDetail;
18248        classtypeDetails.classDetailDescription = detail.classDetailDescription;
18249        classtypeDetails.classDetailImage = detail.classDetailImage;
18250        classtype.details.push(classtypeDetails);
18251      }
18252    }
18253  }, {
18254    key: 'setCompanyLogo',
18255    value: function setCompanyLogo(company, logoUrl, logoAltText, logoWidth, logoHeight, enableCustomLogo) {
18256      if (company.companyLogo === "") {
18257        company.companyLogo = logoUrl;
18258        company.companyAltTextLogo = logoAltText;
18259        company.companyLogoWidth = logoWidth;
18260        company.companyLogoHeight = logoHeight;
18261        company.useCustomLogo = enableCustomLogo;
18262      }
18263
18264      for (var i = 0; i < company.listOffer.length; i++) {
18265        var offer = company.listOffer[i];
18266        offer.company.companyLogo = logoUrl;
18267        offer.company.companyAltTextLogo = logoAltText;
18268        offer.company.companyLogoWidth = logoWidth;
18269        offer.company.companyLogoHeight = logoHeight;
18270        offer.company.useCustomLogo = enableCustomLogo;
18271      }
18272    }
18273  }, {
18274    key: 'getFullClasstype',
18275    value: function getFullClasstype(cl) {
18276      var baseUrl = InternalAPIService.aemServiceHost;
18277      var classtype = new Classtype();
18278      classtype.className = cl.className.toUpperCase();
18279      classtype.classImage = baseUrl + cl.classImage;
18280      classtype.friendlyName = cl.friendlyName;
18281      classtype.classAltTextImage = cl.altTextClass;
18282      InternalAPIService.addDetails(classtype, cl.details);
18283      return classtype;
18284    }
18285  }, {
18286    key: 'getLogoMap',
18287    value: function getLogoMap(callback) {
18288      InternalAPIService.loadInternalAPI(function (err, data) {
18289        var listCompany = data.result;
18290        var logoMap = {};
18291        for (var i = 0; i < listCompany.length; i++) {
18292          var company = listCompany[i];
18293          company.companyLogo = InternalAPIService.baseUrl + company.companyLogo;
18294          company.companyLogoRouteMap = InternalAPIService.baseUrl + company.companyLogoRouteMap;
18295          logoMap[company.companyName.toUpperCase()] = company;
18296        }
18297        if (callback) callback(logoMap);
18298      });
18299    }
18300  }, {
18301    key: 'convertClasstype',
18302    value: function convertClasstype(company) {
18303      for (var i = 0; i < this._contentClasses.result.length; i++) {
18304        var content = this._contentClasses.result[i];
18305        if (company.companyName.toUpperCase() === content.companyName.toUpperCase()) {
18306          var logoUrl = content.companyLogo;
18307          var logoWidth = content.companyLogoWidth;
18308          var logoHeight = content.companyLogoHeight;
18309          var enableCustomLogo = content.useCustomLogo
18310          InternalAPIService.setCompanyLogo(company, logoUrl, content.altTextLogo, logoWidth, logoHeight, enableCustomLogo);
18311          for (var j = 0; j < content.classes.length; j++) {
18312            var cl = content.classes[j];
18313            for (var k = 0; k < company.listOffer.length; k++) {
18314                var offer = company.listOffer[k];
18315                var classtypeObj = offer.classtype;
18316                if (classtypeObj.className.toUpperCase() === cl.className.toUpperCase()) offer.classtype = InternalAPIService.getFullClasstype(cl);
18317                if (offer.connection && offer.connection.secondLeg) {
18318                    var leg = offer.connection.secondLeg;
18319                    if (leg.classtype && leg.classtype.className.toUpperCase() === cl.className.toUpperCase()) {
18320                        leg.classtype = InternalAPIService.getFullClasstype(cl);
18321                    }
18322                }
18323
18324                if (offer.connection && offer.connection.thirdLeg) {
18325                    var _leg = offer.connection.thirdLeg;
18326                    if (_leg.classtype && _leg.classtype.className.toUpperCase() === cl.className.toUpperCase()) {
18327                        _leg.classtype = InternalAPIService.getFullClasstype(cl);
18328                    }
18329                }
18330            }
18331          }
18332        }
18333      }
18334			return company;
18335		}
18336	}]);
18337
18338	return InternalAPIService;
18339}();
18340
18341InternalAPIService.aemServiceHost = window.location.origin;
18342InternalAPIService.baseUrl = InternalAPIService.aemServiceHost;
18343
18344/**
18345 * FIM
18346 * INTERNAL API SERVICE
18347 *
18348 */
18349'use strict';
18350
18351var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
18352
18353function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
18354
18355/**
18356 * INICIO
18357 * LIST RESULT SERVICE
18358 *
18359*/
18360var ListResultService = function () {
18361  function ListResultService() {
18362    _classCallCheck(this, ListResultService);
18363  }
18364
18365  _createClass(ListResultService, null, [{
18366    key: 'loadRaces',
18367    value: function loadRaces(callback) {
18368      $.ajax({
18369        url: '../../assets/json/corrida.json',
18370        contentType: 'json',
18371        type: 'GET',
18372        headers: {
18373          'grupo_jca_auth': 'OA4XqR0LnBBxFkkToX5pUzcnAI2wX1sxeY4YtwXVyNoZyEt66Hg3Zg=='
18374        },
18375        success: function success(data) {
18376          callback(null, data.consultaServicos.lsServicos);
18377        },
18378        error: function error(XMLHttpRequest, textStatus, errorThrown) {
18379          console.log(textStatus, errorThrown);
18380          callback(errorThrown, null);
18381        }
18382      });
18383    }
18384  }]);
18385
18386  return ListResultService;
18387}();
18388
18389/**
18390 * FIM
18391 * LIST RESULT SERVICE
18392 *
18393*/
18394'use strict';
18395
18396var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); }
18396 else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
18397
18398var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
18399
18400function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
18401
18402/**
18403 * INICIO
18404 * LOGICA LIST RESULT
18405 *
18406 */
18407var ListResult = function () {
18408  function ListResult($, searchResultRef) {
18409    _classCallCheck(this, ListResult);
18410
18411    this.listRaces = [];
18412    this.listCompanies = $('[data-js="list-companies"]');
18413    this.noResultWarning = $('[data-js="no-result-warning"]');
18414    this.containerDate = $('[data-js="nearby-dates-container"]');
18415    this.containerFilterOrder = $('#shopping-filter-container');
18416    this.companyTemplate = '';
18417    this.offerTemplate = '';
18418    this.formData = {};
18419    this.currentResult = {};
18420    this.btnBuyDepart = $('#buy-depart');
18421    this.cartService = searchResultRef.cartService;
18422    this.searchResultRef = searchResultRef;
18423    this.listPriceVisibleInDispo = {};
18424    this.init();
18425    this.orderByComponent = new OrderByComponent($, this);
18426    this.pathOverlay = new PathOverlay($);
18427    this.offerDetails = new OfferDetailsController($);
18428    this.aemCustomText = ($("#aemMessageNoResult").attr("data-js-content") !== undefined) ? $("#aemMessageNoResult").attr("data-js-content") : i18n('ticket_no_result');
18429    this.resultsEvent = new Event('getListResults');
18430    this.configImagePoints = $('[data-js="config-image-points-giro"]');
18431    this.configLabelPoints = $('[data-js="config-label-points-giro"]');
18432    this.configModalPoints = $('[data-js="config-modal-points-text"]');
18433    this.remarkV2 = SessionStorage.get('repricingv2');
18434    this.chunkSize = parseInt($('[data-js="items-per-load"]').val(), 10);
18435    this.currentChunk = 0;
18436    this.indexOffer = 0;
18437    this.isLoading = false;
18438    this.$window = $(window);
18439    this.$document = $(document);
18440    this.$loadingIndicator = $('.results-loading-indicator');
18441    this.isReadyToRender = false;
18442  }
18443
18444  _createClass(ListResult, [{
18445    key: 'init',
18446    value: function init() {
18447      var _this = this;
18448
18449      CompanyService.loadCompanyTemplate(function (errCompanyTemplate, companyTemplate) {
18450        _this.onLoadingCompanyDone(errCompanyTemplate, companyTemplate, OfferService.loadOfferTemplate(function (errOfferTemplate, offerTemplate) {
18451          _this.onLoadingOfferDone(errOfferTemplate, offerTemplate, InternalAPIService.loadInternalAPI(function (errInternalApi, internalApiReturn) {
18452            _this.onLoadingInternalAPIDone(errInternalApi, internalApiReturn, null);
18453          }));
18454        }));
18455      });
18456    }
18457  }, {
18458    key: 'buyTicket',
18459    value: function buyTicket(e) {
18460      e.data.searchResultRef.hideTripStop();
18461      e.data.searchResultRef.buyTicket(e);
18462    }
18463  }, {
18464    key: 'resetOrderBy',
18465    value: function resetOrderBy() {
18466      this.orderByComponent.resetOrderBy();
18467      dispatchEvent(this.resultsEvent);
18468    }
18469  }, {
18470    key: 'maintainOrdering',
18471    value: function maintainOrdering() {
18472      this.orderByComponent.maintainOrdering();
18473      dispatchEvent(this.resultsEvent);
18474    }
18475  }, {
18476    key: 'setListResultView',
18477    value: function setListResultView(calledByApplyFilter) {
18478      this.formData = SessionStorage.get('formData');
18479
18480      if (this.searchResultRef.isReturn()) {
18481        this.currentResult = SessionStorage.get('currentResultRet');
18482      } else {
18483        this.currentResult = SessionStorage.get('currentResultDep');
18484      }
18485
18486      this.filteredResult = SessionStorage.get('filteredResult');
18487      if (this.filteredResult == null || this.filteredResult.length === 0) {
18488        this.setListRaces(this.currentResult, calledByApplyFilter);
18489      } else {
18490        this.setListRaces(this.filteredResult, calledByApplyFilter);
18491      }
18492
18493      if (calledByApplyFilter) {
18494        this.updateListResultView(); // Chama apenas se for chamado pelo applyFilter do result-filer.js
18495      }
18496      this.checkCookies();
18497      this.listPriceVisibleInDispo = {};
18498    }
18499  }, {
18500    key: 'getMinorValueTripVisible',
18501    value: function getMinorValueTripVisible() {
18502      var $currentNearbyCard = $('[data-js="curr-nearby-card"]');
18503      var $fromElement = $currentNearbyCard.find('[data-js="from"]');
18504      var date = this.searchResultRef.isReturn() ? this.formData.return.date : this.formData.depart.date;
18505      var day = this.searchResultRef.parseDateUTCFormat(date);
18506      var minorValue = Math.min.apply(Math, _toConsumableArray(this.listPriceVisibleInDispo));
18507      var priceMinorCurrentDayCard = minorValue !== Infinity ? 'R$ ' + Utils.formatPrice(minorValue) : i18n('no_ticket');
18508      $currentNearbyCard.find('[data-js="price"]').text(priceMinorCurrentDayCard);
18509
18510      if (minorValue !== Infinity) {
18511        $currentNearbyCard.find('[data-js="date"]').text(this.searchResultRef.getDesktopDate(day));
18512        $fromElement.show().text(this.searchResultRef.getFromLabel());
18513        $currentNearbyCard.attr('disabled', false);
18514      } else {
18515        $currentNearbyCard.find('[data-js="date"]').text(this.searchResultRef.getDesktopDate(day));
18516        $fromElement.hide();
18517      }
18518    }
18519  }, {
18520    key: 'checkCookies',
18521    value: function checkCookies() {
18522      var cookieName = 'fav_purchases';
18523      var formData = SessionStorage.get('formData');
18524      var favPurchaseEnabled = $('[data-js="activate-cookie-fav-purchase"]').val() == 'true' ? true : false;
18525
18526      if (!!sessionStorage.passenger && favPurchaseEnabled) {
18527        try {
18528          LoaderService.show();
18529          var url = baseUrl + "favpurchases.json" + "?userSID=" + JSON.parse(sessionStorage.passenger)._clientId + "&originId=" + formData.depart.origin.id + "&destinationId=" + formData.depart.destination.id;
18530          var data = null;
18531          try {
18532            data = $.ajax({ type: "GET", url: url, async: false }).responseText;
18533          } catch (e) {
18534            console.log(e);
18535          }
18536          if (data != null) {
18537            data = jQuery.parseJSON(data);
18538            Utils.setCookie("fav_purchases", data, 15);
18539          }
18540        } catch (err) {
18541          console.log(err);
18542        } finally {
18543          LoaderService.hide();
18544        }
18545      }
18546
18547      var cookieArr = Utils.decodeCookie(cookieName) != null ? Utils.decodeCookie(cookieName) : [];
18548
18549      var favPurchases = [];
18550      var _iteratorNormalCompletion = true;
18551      var _didIteratorError = false;
18552      var _iteratorError = undefined;
18553
18554      try {
18555        for (var _iterator = cookieArr[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
18556          var item = _step.value;
18557
18558          var isReturn = this.isReturn();
18559          if (isReturn) {
18560            if (formData.return.origin.id == item.origin.id && formData.return.destination.id == item.destination.id) {
18561              favPurchases.push(item);
18562            }
18563          } else {
18564            if (formData.depart.origin.id == item.origin.id && formData.depart.destination.id == item.destination.id) {
18565              favPurchases.push(item);
18566            }
18567          }
18568        }
18569      } catch (err) {
18570        _didIteratorError = true;
18571        _iteratorError = err;
18572      } finally {
18573        try {
18574          if (!_iteratorNormalCompletion && _iterator.return) {
18575            _iterator.return();
18576          }
18577        } finally {
18578          if (_didIteratorError) {
18579            throw _iteratorError;
18580          }
18581        }
18582      }
18583
18584      if (favPurchaseEnabled && favPurchases.length > 0 && SessionStorage.get('passenger')) {
18585        setTimeout(function () {
18586          return $('[data-js="favPurchaseAsc"]').click();
18587        }, 100);
18588      }
18589    }
18590  }, {
18591    key: 'setupInfiniteScroll',
18592    value: function setupInfiniteScroll() {
18593      var _this2 = this;
18594
18595      this.$window.off('scroll');
18596
18597      var handleScroll = function handleScroll() {
18598        var listCompaniesOffset = _this2.listCompanies.offset().top + _this2.listCompanies.outerHeight();
18599        var windowOffset = _this2.$window.scrollTop() + _this2.$window.height();
18600
18601        if (windowOffset >= listCompaniesOffset - 100 && !_this2.isLoading && _this2.hasMoreData()) {
18602          _this2.loadMoreData();
18603        }
18604      };
18605
18606      this.$window.on('scroll', handleScroll);
18607
18608      // Chama loadMoreData no primeiro carregamento
18609      if (!this.isLoading && this.hasMoreData()) {
18610        this.loadMoreData();
18611      }
18612      this.sendViewToAnalitics(this.listRaces);
18613    }
18614  }, {
18615    key: 'loadMoreData',
18616    value: function loadMoreData() {
18617      var _this3 = this;
18618
18619      // Impede chamadas paralelas ou duplicadas
18620      if (!this.isReadyToRender || this.isLoading || !this.hasMoreData()) return;
18621
18622      this.isLoading = true;
18623      this.$loadingIndicator.show();
18624
18625      var start = this.currentChunk * this.chunkSize;
18626      var end = start + this.chunkSize;
18627      var chunk = this.listRaces.slice(start, end);
18628
18629      if (chunk.length > 0) {
18630        setTimeout(function () {
18631          _this3.renderChunk(chunk);
18632          _this3.currentChunk++;
18633          _this3.isLoading = false;
18634          _this3.$loadingIndicator.hide();
18635
18636          // Desativa o evento de scroll após o primeiro carregamento
18637          if (!_this3.hasMoreData()) {
18638            _this3.$window.off('scroll');
18639          }
18640        }, 600);
18641      } else {
18642        this.$loadingIndicator.hide();
18643        this.isLoading = false;
18644      }
18645    }
18646  }, {
18647    key: 'hasMoreData',
18648    value: function hasMoreData() {
18649      // Verifica se ainda há mais dados para carregar
18650      return this.currentChunk * this.chunkSize < this.listRaces.length;
18651    }
18652  }, {
18653    key: 'renderChunk',
18654    value: function renderChunk(chunk) {
18655      for (var i = 0; i < chunk.length; i++) {
18656        var globalIndex = this.currentChunk * this.chunkSize + i;
18657        var company = chunk[i];
18658
18659        company = InternalAPIService.convertClasstype(company);
18660        this.appendCompanies(company, globalIndex);
18661      }
18662
18663      //Remove fav purchases texts if list is empty
18664      if ($('.fav-list-companies').children().size() == 0) {
18665        $('.fav-list-companies').siblings('.fav-purchase-msg, .separator').removeClass('visible');
18666      }
18667    }
18668  }, {
18669    key: 'preprocessVisiblePrices',
18670    value: function preprocessVisiblePrices() {
18671      var _this4 = this;
18672
18673      this.listPriceVisibleInDispo = []; // Zera o array
18674
18675      this.listRaces.forEach(function (race) {
18676        var offers = race.listOffer || [];
18677
18678        offers.forEach(function (offer) {
18679          var price = offer.price || offer._price;
18680
18681          // Adiciona apenas se o preço for válido
18682          if (price !== undefined && price !== null && price !== '') {
18683            _this4.listPriceVisibleInDispo.push(Number(price).toFixed(2));
18684          }
18685        });
18686      });
18687    }
18688  }, {
18689    key: 'updateListResultView',
18690    value: function updateListResultView() {
18691      this.listCompanies.empty();
18692      this.preprocessVisiblePrices();
18693      this.getMinorValueTripVisible();
18694      this.currentChunk = 0; // Reset chunk index
18695    }
18696  }, {
18697    key: 'handlePageTitle',
18698    value: function handlePageTitle(company) {
18699      var customPageTitle = $(document).attr('title');
18700      customPageTitle = customPageTitle.split("_");
18701      var depLabel = company.origin.label;
18702      var destLabel = company.destination.label;
18703      document.title = customPageTitle[0] + "_" + depLabel + "_" + destLabel;
18704    }
18705  }, {
18706    key: 'setListRaces',
18707    value: function setListRaces(result, calledByApplyFilter) {
18708      this.listRaces = [];
18709      this.listRaces = this.filterJSON(result);
18710
18711      if (this.listRaces && this.listRaces.length > 0) {
18712        this.containerDate.show();
18713        this.containerFilterOrder.show();
18714        this.noResultWarning.removeClass('active');
18715        this.searchResultRef.orderByContainer.attr('class', 'button-order-by visible');
18716        this.setCheapestOfTheDay();
18717      } else {
18718        this.containerFilterOrder.hide();
18719        if ($('[data-js="no-result-warning-filter"]').hasClass('active')) {
18720          $('[data-js="no-result-warning-filter"]').removeClass('active');
18721        }
18722        this.noResultWarning.addClass('active');
18723        this.searchResultRef.orderByContainer.attr('class', 'button-order-by invisible');
18724      }
18725
18726      if (calledByApplyFilter) {
18727        this.listCompanies.empty();
18728        this.currentChunk = 0;
18729        this.isLoading = false;
18730        this.setupInfiniteScroll();
18731      }
18732    }
18733  }, {
18734    key: 'onLoadingCompanyDone',
18735    value: function onLoadingCompanyDone(errCompanyTemplate, companyTemplate, next) {
18736      if (errCompanyTemplate) console.log(errCompanyTemplate); else {
18737        this.companyTemplate = companyTemplate;
18738
18739        if (next) next();
18740      }
18741    }
18742  }, {
18743    key: 'sendViewToAnalitics',
18744    value: function sendViewToAnalitics(listRaces) {
18745      var formData = SessionStorage.get("formData");
18746      var valueTotal = 0;
18747      var dataLayerView = [];
18748      var index = 1;
18749
18750      function optimizeString(str) {
18751        return str.replace(/[\s\-\(\):]+/g, '');
18752      }
18753
18754      listRaces.forEach(function (company) {
18755        company._listOffer.forEach(function (offer) {
18756          var itemName = [
18757            offer._company._origin._label,
18758            offer._company._destination._label
18759          ].join(' + ');
18760
18761          itemName = optimizeString(itemName);
18762          var aux = {
18763            item_name: itemName,
18764            item_id: offer._service,
18765            item_brand: offer._company._companyName,
18766            item_variant: offer._classtype._className,
18767            item_category: $("#siteName").val(),
18768            item_category2: offer._company._companyName,
18769            item_category3: offer._company._companyName,
18770            benefit: formData.passengers[2].quantity > 0 ? true : false,
18771            departure_date: formData.depart.minDate,
18772            return_date: formData.return.minDate ? formData.return.minDate : null,
18773            price: offer._price,
18774            adults_passengers: formData.passengers[0].quantity, // Quantidade de passageiros adultos
18775            infants_passengers: formData.passengers[2].quantity, // Quantidade de passageiros crianças de colo (não pagantes)
18776            children_passengers: formData.passengers[1].quantity, // Quantidade de passageiros crianças (pagantes)
18777            quantity: offer._freeArmchairs,
18778            index: index
18779          };
18780
18781          dataLayerView.push(aux);
18782          valueTotal += offer._price;
18783          index += 1;
18784        });
18785      });
18786
18787      window.dataLayer = window.dataLayer || [];
18788      window.dataLayer.push({
18789        event: "view_item_list",
18790        device: Utils.getDevice(),
18791        sale_ogirin: $("#siteName").val(),
18792        ecommerce: {
18793          currency: "BRL",
18794          item_list_name: Utils.getPromotionParam("deep") ? "Rotas Promocionais" : "todas as rotas",
18795          value: parseFloat(valueTotal.toFixed(2)),
18796          cart_total: parseFloat(valueTotal.toFixed(2)),
18797          search_data: Utils.getSearchData(formData),
18798          search_parameters: Utils.getSearchParameters(formData),
18799          items: dataLayerView,
18800          user_data: Utils.getUserData()
18801        },
18802      });
18803    }
18804  }, {
18805    key: 'onLoadingOfferDone',
18806    value: function onLoadingOfferDone(errOfferTemplate, offerTemplate, next) {
18807      if (errOfferTemplate) console.log(errOfferTemplate); else {
18808        this.offerTemplate = offerTemplate;
18809        if (next) next();
18810      }
18811    }
18812  }, {
18813    key: 'onLoadingInternalAPIDone',
18814    value: function onLoadingInternalAPIDone(errInternalApi, internalApiReturn, next) {
18815      if (errInternalApi) console.log(errInternalApi); else {
18816        this.setListResultView();
18817        dispatchEvent(this.resultsEvent);
18818        this.setupInfiniteScroll();
18819
18820        if (next) next();
18821      }
18822    }
18823  }, {
18824    key: 'handleMinTimeToBuyTrip',
18825    value: function handleMinTimeToBuyTrip(trip) {
18826      var minTimeToBuyTrip = $('[data-js="min-time-to-buy-ticket"]').val() ? +$('[data-js="min-time-to-buy-ticket"]').val() : 20;
18827      var hourDepartResearch = new Date(this.formData.depart.minDate).getTime() + minTimeToBuyTrip * 60 * 1000;
18828      var dateTrip = new Date(trip.departureDate).getTime();
18829      var isAfterMinTime = hourDepartResearch < dateTrip;
18830
18831      return isAfterMinTime;
18832    }
18833  }, {
18834    key: 'isDataValid',
18835    value: function isDataValid(data, filtered) {
18836      var minDate = this.isReturn() ? this.formData.return.minDate : this.formData.depart.minDate;
18837      var isDateAfterMinDate = DateFormatter.compareWithMinTime(minDate, data.departureDate);
18838      var amount = 0;
18839      if (isDateAfterMinDate) {
18840        for (var i = 0; i < filtered.length; i++) {
18841          var company = filtered[i];
18842          var listOffer = company.listOffer;
18843          for (var j = 0; j < listOffer.length; j++) {
18844            var offer = listOffer[j];
18845            if (data.servico == offer.service) amount++;
18846          }
18847        }
18848        return amount == 0;
18849      }
18850      return false;
18851    }
18852  }, {
18853    key: 'checkAgroupStateInOrigin',
18854    value: function checkAgroupStateInOrigin(origin, data) {
18855      var originIdPlace = Math.sign(origin.id) < 0 ? +data.originId : origin.id;
18856      var cityOriginPlace = Math.sign(origin.id) < 0 ? data.originDesc : origin.city;
18857
18858      return { originIdPlace: originIdPlace, cityOriginPlace: cityOriginPlace };
18859    }
18860  }, {
18861    key: 'checkAgroupStateInDestination',
18862    value: function checkAgroupStateInDestination(destination, data) {
18863      var destinationIdPlace = Math.sign(destination.id) < 0 ? +data.destinationId : destination.id;
18864      var cityDestinationPlace = Math.sign(destination.id) < 0 ? data.destinationDesc : destination.city;
18865
18866      return { destinationIdPlace: destinationIdPlace, cityDestinationPlace: cityDestinationPlace };
18867    }
18868  }, {
18869    key: 'createCompany',
18870    value: function createCompany(origin, destination, data) {
18871      var company = new Company();
18872      company.companyName = data.company;
18873      company.companyId = data.companyId;
18874      company.departureDate = data.departureDate;
18875      company.arrivingDate = data.arrivalDate;
18876
18877      if (data.connection) {
18878        data.arrivalDate = DateFormatter.reverseDate(data.connection.secondLegArrivalDate) + 'T' + DateFormatter.formatTimeString(data.connection.secondLegArrivalHour);
18879      }
18880
18881      var _checkAgroupStateInOr = this.checkAgroupStateInOrigin(origin, data),
18882        originIdPlace = _checkAgroupStateInOr.originIdPlace,
18883        cityOriginPlace = _checkAgroupStateInOr.cityOriginPlace;
18884
18885      var _checkAgroupStateInDe = this.checkAgroupStateInDestination(destination, data),
18886        destinationIdPlace = _checkAgroupStateInDe.destinationIdPlace,
18887        cityDestinationPlace = _checkAgroupStateInDe.cityDestinationPlace;
18888
18889      company.origin = new Location(originIdPlace, cityOriginPlace);
18890      company.destination = new Location(destinationIdPlace, cityDestinationPlace);
18891      return company;
18892    }
18893  }, {
18894    key: 'createConnection',
18895    value: function createConnection(data) {
18896        var base = data.connection;
18897        var tokens = data.tokens;
18898
18899        var connection = {};
18900
18901        var legKeys = Object.keys(base).filter(function (key) {
18902            if (!key.endsWith("LegServiceId")) return false;
18903            if (key.startsWith("firstLeg")) return false;
18904            var serviceId = base[key];
18905            if (!serviceId || serviceId === "0") return false;
18906            return true;
18907        });
18908
18909        legKeys.forEach(function (key, index) {
18910            var prefix = key.replace("LegServiceId", "");
18911            var legName = prefix + "Leg";
18912            var token = tokens[index + 1];
18913
18914            var leg = {};
18915            leg.serviceId = base[key];
18916
18917            var prefixedKeys = Object.keys(base).filter(function (k) {
18918                return k.startsWith(prefix);
18919            });
18920
18921            prefixedKeys.forEach(function (fullKey) {
18922                var raw = fullKey.replace(prefix, "");
18923                var value = base[fullKey];
18924
18925                if (raw === "LegDepartureDate") {
18926                    var hour = base[prefix + 'LegDepartureHour'];
18927                    if (value && hour) {
18928                        leg.departureDate = DateFormatter.reverseDate(value) + 'T' + hour;
18929                    }
18930                    return;
18931                }
18932
18933                if (raw === "LegArrivalDate") {
18934                    var _hour = base[prefix + 'LegArrivalHour'];
18935                    if (value && _hour) {
18936                        leg.arrivingDate = DateFormatter.reverseDate(value) + 'T' + _hour;
18937                    }
18938                    return;
18939                }
18940
18941                if (raw === "LegOrigin") {
18942                    leg.origin = {
18943                        id: value,
18944                        description: base[prefix + 'LegOriginDescription'] || base['' + (prefix === 'second' ? 'segundoTrechoOrigemDescricao' : 'terceiroTrechoOrigemDescricao')] || null
18945                    };
18946                    return;
18947                }
18948
18949                if (raw === "LegDestination") {
18950                    leg.destination = {
18951                        id: value,
18952                        description: base[prefix + 'LegDestinationDescription'] || base['' + (prefix === 'second' ? 'segundoTrechoDestinoDescricao' : 'terceiroTrechoDestinoDescricao')] || null
18953                    };
18954                    return;
18955                }
18956
18957                if (raw === "LegClass") {
18958                    leg.classtype = new Classtype(value);
18959                    return;
18960                }
18961
18962                var cleaned = raw.replace(/^Leg/, "");
18963                var prop = cleaned.charAt(0).toLowerCase() + cleaned.slice(1);
18964
18965                leg[prop] = value;
18966            });
18967
18968            leg.token = token;
18969
18970            connection[legName] = leg;
18971
18972            if (!connection.thirdLeg && tokens.length >= 3 && base.thirdLegSell === true) {
18973
18974                var _token = tokens[2];
18975
18976                connection.thirdLeg = {
18977                    serviceId: base.thirdLegServiceId || null,
18978
18979                    origin: {
18980                        id: base.thirdLegOrigin || null,
18981                        description: base.thirdLegOriginDescription || null
18982                    },
18983
18984                    destination: {
18985                        id: base.thirdLegDestination || null,
18986                        description: base.thirdLegDestinationDescription || null
18987                    },
18988
18989                    departureDate: base.thirdLegDepartureDate && base.thirdLegDepartureHour ? DateFormatter.reverseDate(base.thirdLegDepartureDate) + 'T' + base.thirdLegDepartureHour : null,
18990
18991                    arrivingDate: base.thirdLegArrivalDate && base.thirdLegArrivalHour ? DateFormatter.reverseDate(base.thirdLegArrivalDate) + 'T' + base.thirdLegArrivalHour : null,
18992
18993                    classtype: base.thirdLegClass ? new Classtype(base.thirdLegClass) : new Classtype(""),
18994
18995                    token: _token,
18996
18997                    freeSeats: base.thirdLegFreeSeats || null,
18998                    totalSeats: base.thirdLegTotalSeats || null,
18999
19000                    thirdAdditionalFields: base.thirdAdditionalFields || null
19001                };
19002            }
19003        });
19004
19005        return connection;
19006    }
19007  }, {
19008    key: 'createOffer',
19009    value: function createOffer(data, company) {
19010      var offer = new Offer();
19011      offer.service = data.serviceId;
19012      offer.group = data.group;
19013      offer.token = data.tokens[0];
19014      offer.freeArmchairs = data.freeSeats;
19015      offer.totalArmchairs = data.totalSeats;
19016      offer.price = data.price;
19017      offer.priceWithDiscountPix = data.priceWithDiscountPix;
19018      offer.percentagePix = data.percentagePix;
19019      offer.fare = 0;
19020      offer.boardingFee = 0;
19021      offer.toll = 0;
19022      offer.insurance = 0;
19023      offer.others = 0;
19024      offer.classtype = new Classtype(data.class);
19025      offer.sells = data.sell;
19026      offer.company = company;
19027      offer.routeId = data.routeId;
19028
19029      if (data.connection) offer.connection = this.createConnection(data);
19030
19031      return offer;
19032    }
19033  }, {
19034    key: 'filterJSON',
19035    value: function filterJSON(result) {
19036        var filtered = [];
19037        var servicesList = result ? result.servicesList : null;
19038        this.formData = SessionStorage.get('formData');
19039
19040        if (!servicesList) return filtered;
19041
19042        for (var i = 0; i < servicesList.length; i++) {
19043            if (this.isDataValid(servicesList[i], filtered) && this.handleMinTimeToBuyTrip(servicesList[i])) {
19044                var origin = result.origin,
19045                    destination = result.destination;
19046
19047                var company = this.createCompany(origin, destination, servicesList[i]);
19048                var index = this.hasCompany(filtered, company);
19049
19050                if (index === -1) {
19051                    filtered.push(company);
19052                    index = filtered.length - 1;
19053                } else if (origin.city.includes("TODOS") && index !== -1) {
19054                    filtered.push(company);
19055                    index = filtered.length - 1;
19056                }
19057
19058                var offer = this.createOffer(servicesList[i], filtered[index]);
19059                if (offer.connection && offer.connection.secondLeg) this.searchResultRef.showTripStop();
19060
19061                filtered[index].listOffer.push(offer);
19062            }
19063        }
19064        return filtered;
19065    }
19066  }, {
19067    key: 'isTheSameDay',
19068    value: function isTheSameDay(day1, day2) {
19069      return day1.getDate() === day2.getDate() && day1.getMonth() === day2.getMonth() && day1.getFullYear() === day2.getFullYear();
19070    }
19071  }, {
19072    key: 'setCheapestOfTheDay',
19073    value: function setCheapestOfTheDay() {
19074      var cheapestPrice = Number.MAX_SAFE_INTEGER;
19075      //Searching for the cheapest price
19076      for (var i = 0; i < this.listRaces.length; i++) {
19077        var race = this.listRaces[i];
19078        for (var j = 0; j < race.listOffer.length; j++) {
19079          var offer = race.listOffer[j];
19080          if (offer.freeArmchairs > 0 && parseFloat(offer.price) <= parseFloat(cheapestPrice)) cheapestPrice = offer.price;
19081        }
19082      }
19083
19084      //Looking for equal prices and setting up the flag
19085      for (var _i = 0; _i < this.listRaces.length; _i++) {
19086        var _race = this.listRaces[_i];
19087        for (var _j = 0; _j < _race.listOffer.length; _j++) {
19088          var _offer = _race.listOffer[_j];
19089          if (parseFloat(_offer.price) <= parseFloat(cheapestPrice)) _offer.cheapest = true;
19090        }
19091      }
19092    }
19093  }, {
19094    key: 'hasCompany',
19095    value: function hasCompany(array, company) {
19096      for (var i = 0; i < array.length; i++) {
19097        if (array[i].companyName === company.companyName && array[i].departureDate === company.departureDate && array[i].arrivingDate === company.arrivingDate) {
19098          return i;
19099        }
19100      } return -1;
19101    }
19102  }, {
19103    key: 'getLegsFromCompany',
19104    value: function getLegsFromCompany(company) {
19105        var offer = company.listOffer[0];
19106
19107        var mainLegDeparture = offer._company && offer._company._departureDate ? offer._company._departureDate : company.departureDate;
19108
19109        var mainLeg = {
19110            serviceId: offer.service,
19111            departureDate: mainLegDeparture
19112        };
19113
19114        var connection = offer.connection;
19115
19116        if (!connection || (typeof connection === 'undefined' ? 'undefined' : _typeof(connection)) !== "object") {
19117            return [mainLeg];
19118        }
19119
19120        var legNames = Object.keys(connection).filter(function (key) {
19121            return key.endsWith("Leg");
19122        });
19123
19124        if (legNames.length === 0) {
19125            return [mainLeg];
19126        }
19127
19128        var legs = legNames.map(function (name) {
19129            return {
19130                serviceId: connection[name].serviceId,
19131                departureDate: connection[name].departureDate
19132            };
19133        });
19134
19135        return [mainLeg].concat(_toConsumableArray(legs));
19136    }
19137  }, {
19138    key: 'fetchItinerarySequential',
19139    value: function fetchItinerarySequential(legs, company) {
19140        var _this5 = this;
19141
19142        return legs.reduce(function (promise, leg) {
19143            return promise.then(function (results) {
19144                return _this5.fetchItineraryForLeg(leg, company).then(function (data) {
19145                    results.push(data);
19146                    return results;
19147                }).catch(function (err) {
19148                    console.error("Erro ao buscar itinerário para o leg:", leg, err);
19149                    return results;
19150                });
19151            });
19152        }, Promise.resolve([]));
19153    }
19154  }, {
19155    key: 'fetchItineraryForLeg',
19156    value: function fetchItineraryForLeg(leg, company) {
19157        return new Promise(function (resolve) {
19158            var params = {
19159                service: leg.serviceId,
19160                date: DateFormatter.extractDate(leg.departureDate)
19161            };
19162
19163            ListResult.getItinerario(params, function (data) {
19164                return resolve(data);
19165            });
19166        });
19167    }
19168  }, {
19169    key: 'showPathClick',
19170    value: function showPathClick(company) {
19171        var _this6 = this;
19172
19173        var $listRoute = $('[data-js="container-bus-rote"]');
19174        $listRoute.empty();
19175
19176        var legs = this.getLegsFromCompany(company);
19177
19178        this.fetchItinerarySequential(legs, company).then(function (results) {
19179            results.forEach(function (res, index) {
19180                var stops = res.result.stops;
19181
19182                var nextConnectionPoint = legs[index + 1] ? legs[index + 1].serviceId : null;
19183
19184                _this6.loadListItinerary(stops, nextConnectionPoint);
19185            });
19186        });
19187    }
19188  }, {
19189    key: 'loadDirectItinerary',
19190    value: function loadDirectItinerary(company) {
19191        var _this7 = this;
19192
19193        ListResult.searchPathAToB(company, function (data) {
19194            _this7.loadListItinerary(data.result.stops, null);
19195        });
19196    }
19197  }, {
19198    key: 'appendCompanies',
19199    value: function appendCompanies(company, index) {
19200      var _this8 = this;
19201      // AEM CUSTOM FUNCTION - The entire function is different from the front environment so that it works in a customizable way in AEM
19202
19203      var component = this.companyTemplate.replace(/\$index/g, index);
19204      var isLogoCurrentCompany = company.useCustomLogo;
19205
19206      var handleLogo = function handleLogo() {
19207        if (isLogoCurrentCompany) {
19208          var srcImage = company.companyLogo;
19209          var altImage = company.companyAltTextLogo;
19210          var widthImage = company.companyLogoWidth;
19211          var heightImage = company.companyLogoHeight;
19212
19213          if (srcImage) {
19214            companyEl.find('[data-js="titleCompany"]').addClass('d-none');
19215            companyEl.find('[data-js="imgCompany"]').addClass('active').attr('src', company.companyLogo).attr('alt', company.companyAltTextLogo);
19216            if (widthImage) companyEl.find('[data-js="imgCompany"]').css('width', widthImage);
19217            if (heightImage) companyEl.find('[data-js="imgCompany"]').css('height', heightImage);
19218          } else {
19219            var parsedCompanyName = _this8.parseCompanyName(company.companyName);
19220            companyEl.find('[data-js="titleCompany"]').text(parsedCompanyName);
19221            companyEl.find('[data-js="imgCompany"]').addClass('d-none');
19222          }
19223        } else {
19224          var parsedCompanyName = _this8.parseCompanyName(company.companyName);
19225          companyEl.find('[data-js="titleCompany"]').text(parsedCompanyName);
19226          companyEl.find('[data-js="imgCompany"]').addClass('d-none');
19227        }
19228      };
19229
19230      if (company._favPurchase) {
19231        $('.fav-list-companies').append(component);
19232        var companyElContainer = $('[data-js="list-element-' + index + '"]').parent();
19233        companyElContainer.addClass('fav-purchase');
19234        companyElContainer.siblings('.fav-purchase-msg, .separator').addClass('visible');
19235        var bottomMsgText = $('[data-js="order-by-list"]').find('button.active').text();
19236        companyElContainer.siblings('.fav-purchase-msg.bottom').text(bottomMsgText);
19237      } else {
19238        $('#list-companies').append(component);
19239      }
19240
19241      this.checkManagedBy();
19242
19243      var companyEl = $('[data-js="list-element-' + index + '"]');
19244      var isLogoActive = $('[data-js="logo-enabled-selector"]').val() == "true" ? true : false;
19245      var hasConnection = !!(company._listOffer[0].connection && company._listOffer[0].connection.secondLeg && company._listOffer[0].connection.secondLeg.token);
19246
19247
19248      if (!hasConnection) {
19249        companyEl.find('[data-js="has-connection"]').hide();
19250      }
19251
19252      if (isLogoActive) {
19253        handleLogo();
19254      } else {
19255        var parsedCompanyName = this.parseCompanyName(company.companyName);
19256        companyEl.find('[data-js="titleCompany"]').text(parsedCompanyName);
19257        companyEl.find('[data-js="imgCompany"]').addClass('d-none');
19258      }
19259
19260      if (company.connection && company.connection.company != company.companyName) {
19261        if (isLogoActive) {
19262          companyEl.find('[data-js="imgCompanyConnection"]').addClass('active').attr('src', company.companyLogo).attr('alt', company.companyAltTextLogo);
19263          companyEl.find('[data-js="titleCompany"]').addClass('d-none');
19264        } else {
19265          var _parsedCompanyName = this.parseCompanyName(company.connection.company);
19266          companyEl.find('[data-js="titleCompanyConnection"]').text(_parsedCompanyName);
19267          companyEl.find('[data-js="imgCompany"]').addClass('d-none');
19268        }
19269      }
19270
19271      var depLabel = Utils.splitLocation(company.origin.label)[0];
19272      var depLabelSub = Utils.splitLocation(company.origin.label)[1];
19273
19274      var destLabel = Utils.splitLocation(company.destination.label)[0];
19275      var destLabelSub = Utils.splitLocation(company.destination.label)[1];
19276
19277      companyEl.find('[data-js="departureLabel"]').text(Utils.capitalize(depLabel));
19278      if (depLabelSub) companyEl.find('[data-js="departureLabelSub"]').text(depLabelSub).show();
19279
19280      companyEl.find('[data-js="destinationLabel"]').text(Utils.capitalize(destLabel));
19281      if (destLabelSub) companyEl.find('[data-js="destinationLabelSub"]').text(destLabelSub).show();
19282
19283      companyEl.find('[data-itinerary="itineray-link"]').click(function () {
19284        return _this8.showPathClick(company);
19285      });
19286      companyEl.find('[data-js="fromLabel"]').text(" " + DateFormatter.formatDateFromString(company.departureDate) + " ");
19287      companyEl.find('[data-js="toLabel"]').text(" " + DateFormatter.formatDateFromString(company.arrivingDate) + " ");
19288      companyEl.find('[data-js="fromTime"]').text(" " + DateFormatter.formatTimeFromString(company.departureDate) + " ");
19289      companyEl.find('[data-js="toTime"]').text(" " + DateFormatter.formatTimeFromString(company.arrivingDate) + " ");
19290      companyEl.find('[data-js="durationLabel"]').text(DateFormatter.getDurationLabel(company.departureDate, company.arrivingDate));
19291      companyEl.find('[data-js="list-offer_$index"]').attr('data-js', 'list-offer_' + index);
19292      //Do the same with listOffer data
19293      var parent = $('[data-js="list-offer_' + index + '"]');
19294      var listElementComponent = $('[data-js="list-element-' + index + '"]');
19295      this.appendOffers(parent, company.listOffer, listElementComponent);
19296
19297      $('[data-js="order-by-list"]').find('button').first().focus();
19298      var $link2 = companyEl.find('[data-js="bus-route"]');
19299      new Modal($, $link2);
19300      var $link3 = companyEl.find('[data-js="points-giro-modal"]');
19301      new Modal($, $link3);
19302
19303      var conn = company._listOffer[0].connection;
19304
19305      var firstConn = conn && conn.secondLeg ? conn.secondLeg : null;
19306
19307      var secondConn = conn && conn.thirdLeg ? conn.thirdLeg : null;
19308
19309      if (firstConn && firstConn.departureDate) {
19310          var departureHour = firstConn.departureDate.split('T')[1];
19311          companyEl.find('[data-js="connectionLocation"]').text(Utils.capitalize(firstConn.origin.description));
19312          companyEl.find('[data-js="departureHour"]').text(departureHour);
19313      }
19314
19315      if (secondConn) {
19316          if (secondConn.origin.description) {
19317              companyEl.find('[data-js="connectionB"]').removeClass('d-none');
19318          }
19319          companyEl.find('[data-js="connectionLocationB"]').text(Utils.capitalize(secondConn.origin.description));
19320          var departureHourB = secondConn.departureDate ? secondConn.departureDate.split('T')[1] : '';
19321          companyEl.find('[data-js="departureHourB"]').text(departureHourB);
19322      }
19323
19324        $('a[data-itinerary="itineray-link"]').text($('[data-js="result-cards-edit-texts"]').attr('edit-text-see-route'));
19325        ListResult.applyTranslations();
19326    }
19327  }, {
19328    key: 'checkManagedBy',
19329    value: function checkManagedBy() {
19330      var managedByDesktop = $('.managed-by[data-device="desktop"]');
19331      var managedByMobile = $('.managed-by[data-device="mobile"]');
19332
19333      if (!managedByDesktop.data('show')) managedByDesktop.parent().hide();
19334      if (!managedByMobile.data('show')) managedByMobile.parent().hide();
19335    }
19336  }, {
19337    key: 'parseCompanyName',
19338    value: function parseCompanyName(companyName) {
19339      switch (companyName) {
19340        case 'VIACAO COMETA S A':
19341          return 'Cometa';
19342        case 'AUTO VIACAO 1001 LTDA':
19343          return 'Viação 1001';
19344        case 'EXPRESSO DO SUL S A':
19345          return 'Expresso do Sul';
19346        case 'AUTO VIACAO CATARINENSE LTDA':
19347          return 'Catarinense';
19348        case 'RAPIDO RIBEIRAO PRETO LTDA':
19349          return 'Rápido Ribeirão';
19350        default:
19351          return Utils.capitalize(companyName);
19352      }
19353    }
19354  }, {
19355    key: 'setExpandDetailsEvent',
19356    value: function setExpandDetailsEvent(offerEl, offer) {
19357      var _this4 = this;
19358
19359      var classTypeExpand = offerEl.find('[data-js="details-modal-target"]');
19360      classTypeExpand.click({ "offer": offer }, function (e) {
19361        return _this4.expandDetailsDesktop(e, _this4);
19362      });
19363    }
19364  }, {
19365    key: 'setExpandDetailsEventConnection',
19366    value: function setExpandDetailsEventConnection(parentComponent, offerEl, connection) {
19367        var _this10 = this;
19368
19369        var listElementComponent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
19370        var isSecondConn = arguments[4];
19371
19372        var selector = isSecondConn ? '.connection-info.secondConn' : '.connection-info.firstConn';
19373
19374        var connectionIcon = isSecondConn ? '.connection.secondConn' : '.connection.firstConn';
19375
19376        if (connection && !isSecondConn) {
19377            parentComponent.find('.connection-info.secondConn').hide();
19378            parentComponent.find('.connection.secondConn').hide();
19379
19380            if (listElementComponent) {
19381                listElementComponent.find("#connection-alert").css('visibility', 'hidden');
19382            }
19383        }
19384
19385        if (!connection || !connection.serviceId) {
19386            parentComponent.find(selector).hide();
19387            parentComponent.find(connectionIcon).hide();
19388
19389            if (listElementComponent) {
19390                listElementComponent.find("#connection-alert").css('visibility', 'hidden');
19391            }
19392
19393            return;
19394        }
19395
19396        var $connBlock = offerEl.find(selector);
19397
19398        parentComponent.find(connectionIcon).show();
19399        $connBlock.show();
19400
19401        $connBlock.find('[data-js="classtypeLabel"]').html(connection.classtype.name);
19402
19403        var classTypeExpandConnection = $connBlock.find('[data-js="details-modal-target"]');
19404        classTypeExpandConnection.off("click");
19405
19406        classTypeExpandConnection.click({
19407            "offer": { "offer": connection }
19408        }, function (e) {
19409            return _this10.expandDetailsDesktop(e, _this10);
19410        });
19411
19412        if (listElementComponent) {
19413            listElementComponent.find("#connection-alert").css('visibility', 'visible');
19414        }
19415    }
19416  }, {
19417    key: 'setBuyButtonEvent',
19418    value: function setBuyButtonEvent(offerEl, offer, index) {
19419      var btnBuy = offerEl.find('[data-js="buy-ticket"]');
19420      var btnOfferDetails = offerEl.find('[data-js="offer-details-link-' + index + '"]');
19421      var itinerarySection = offerEl.closest('.offer-container').parent().find('.company-container').find('.itinerary-section');
19422      var origem = itinerarySection.find('[data-js=departureLabel]').text().trim();
19423      var destino = itinerarySection.find('[data-js=destinationLabel]').text().trim();
19424      var horaSaida = itinerarySection.find('[data-js=fromTime]').text().trim();
19425      var horaChegada = itinerarySection.find('[data-js=toTime]').text().trim();
19426      var empresa = offer.company.companyName;
19427      var sentido = $('[data-js="trip-label-way"]').first().text().trim();
19428      var translationbuyticket = $('[data-js="translationbuyticket"]').val() == undefined ? '' : $('[data-js="translationbuyticket"]').val();
19429      var price = offer.price.toFixed(2).toString().replace('.', ',');
19430      var priceWithDiscountPix = offer.priceWithDiscountPix != undefined ? offer.priceWithDiscountPix.toFixed(2).toString().replace('.', ',') : "0,00";
19431      var ariaLabelText = translationbuyticket.replace('#sentido', sentido).replace('#origem', origem).replace('#destino', destino).replace('#horaSaida', horaSaida).replace('#horaChegada', horaChegada).replace('#price', price).replace('#empresa', empresa);
19432      btnBuy.attr('aria-label', ariaLabelText);
19433      btnBuy.click({
19434        'offer': offer,
19435        'searchResultRef': this.searchResultRef
19436      }, this.buyTicket);
19437      btnOfferDetails.click({
19438        'offer': offer,
19439        'offerDetails': this.offerDetails
19440      }, this.showOfferDetails);
19441    }
19442  }, {
19443    key: 'showOfferDetails',
19444    value: function showOfferDetails(e) {
19445      var offer = e.data.offer;
19446
19447      e.data.offerDetails.getOfferDetails(offer);
19448    }
19449  }, {
19450    key: 'setPriceLabel',
19451    value: function setPriceLabel(hasFreeSeats, offerEl, offer, index) {
19452      if (hasFreeSeats) {
19453        var price = offer.price.toFixed(2).toString();
19454        var priceWithDiscountPix = offer.priceWithDiscountPix ? offer.priceWithDiscountPix.toFixed(2).toString().replace('.', ',') : null;
19455
19456        var _price$split = price.split('.'),
19457          _price$split2 = _slicedToArray(_price$split, 2),
19458          integer = _price$split2[0],
19459          decimal = _price$split2[1];
19460
19461        if (offer.priceWithDiscountPix === offer.price || !offer.priceWithDiscountPix) {
19462          offerEl.find('[data-js="priceLabel"]').text(integer);
19463          offerEl.find('[data-js="decimalLabel"]').text(',' + decimal);
19464
19465          offerEl.find('.price-card').addClass('d-none');
19466          offerEl.find('.symbol-money-card').addClass('d-none');
19467          offerEl.find('.payment-card-price').addClass('d-none');
19468          offerEl.find('.decimal-value-card').addClass('d-none');
19469          offerEl.find('.label-card').addClass('d-none');
19470        } else {
19471          var _priceWithDiscountPix = priceWithDiscountPix.split(','),
19472            _priceWithDiscountPix2 = _slicedToArray(_priceWithDiscountPix, 2),
19473            integerPix = _priceWithDiscountPix2[0],
19474            decimalPix = _priceWithDiscountPix2[1];
19475
19476          offerEl.find('[data-js="priceLabel"]').addClass('d-none');
19477          offerEl.find('[data-js="decimalLabel"]').addClass('d-none');
19478          offerEl.find('[data-js="priceLabelPix"]').text(integerPix);
19479          offerEl.find('[data-js="decimalLabelPix"]').text(',' + decimalPix);
19480          offerEl.find('[data-js="priceLabelPix"]').removeClass('d-none');
19481          offerEl.find('[data-js="decimalLabelPix"]').removeClass('d-none');
19482
19483          var _price$split3 = price.split('.'),
19484            _price$split4 = _slicedToArray(_price$split3, 2),
19485            _integer = _price$split4[0],
19486            _decimal = _price$split4[1];
19487
19488          offerEl.find('.price-card').removeClass('d-none');
19489          offerEl.find('.symbol-money-card').removeClass('d-none');
19490          offerEl.find('.payment-card-price').removeClass('d-none');
19491          offerEl.find('.decimal-value-card').removeClass('d-none');
19492          offerEl.find('.label-card').removeClass('d-none');
19493          offerEl.find('.pix-rectangle').removeClass('d-none');
19494
19495          offerEl.find('[data-js="priceLabel"]').text(_integer);
19496          offerEl.find('[data-js="decimalLabel"]').text(',' + _decimal);
19497        }
19498
19499        if (offer.cheapest) offerEl.find('.cheaper-price').addClass('active');
19500        offer.index = this.indexOffer + 1;
19501        this.setBuyButtonEvent(offerEl, offer, index);
19502      } else {
19503        offerEl.find('.available').hide();
19504        offerEl.find('.unavailable').show();
19505      }
19506    }
19507  }, {
19508    key: 'appendOffers',
19509    value: function appendOffers(parentComponent, listOffer) {
19510        var _this11 = this;
19511
19512        var listElementComponent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
19513
19514        var extraTimeWrapperComponent = parentComponent.closest('li').find('.extra-time-wrapper');
19515        $.each(listOffer, function (i, offer) {
19516            var component = _this11.offerTemplate;
19517            component = component.replace(/\$index/g, offer.service + '-' + i);
19518            component = component.replace(/\$id-btn/g, i);
19519            parentComponent.append(component);
19520            var offerEl = parentComponent.find('[data-js="offer-element-' + offer.service + '-' + i + '"]');
19521            var hasFreeSeats = parseInt(offer.freeArmchairs) >= Utils.getSeatPassengers(_this11.formData.passengers);
19522
19523            var firstConn = offer.connection && offer.connection.secondLeg ? offer.connection.secondLeg : null;
19524
19525            var secondConn = offer.connection && offer.connection.thirdLeg ? offer.connection.thirdLeg : null;
19526
19527            if (firstConn && firstConn.serviceId) {
19528                hasFreeSeats = hasFreeSeats && parseInt(firstConn.freeSeats) >= Utils.getSeatPassengers(_this11.formData.passengers);
19529            }
19530
19531            if (secondConn && secondConn.serviceId) {
19532                hasFreeSeats = hasFreeSeats && parseInt(secondConn.freeSeats) >= Utils.getSeatPassengers(_this11.formData.passengers);
19533            }
19534
19535            var disableAlert = $('[data-js="disable-free-seats-alert-min"]').val();
19536            if (disableAlert == 'false') {
19537                var $freeSeatsAlertElem = offerEl.find('[data-js="freeseats-validation-msg"]');
19538                var $changePointsGiroContainer = offerEl.find('[data-js="points-giro-container"]');
19539                var $sizeImagePointsGiro = offerEl.find('[data-js="image-points-giro"]');
19540
19541                var imageSrc = $('[data-js="image-giro-points-src"]').val();
19542                var imageTtl = $('[data-js="image-giro-points-ttl"]').val();
19543                var imageAlt = $('[data-js="image-giro-points-alt"]').val();
19544                var linkTtl = $('[data-js="link-giro-points-ttl"]').val();
19545
19546                var $linkOfferGiroPoints = offerEl.find('.link-target-btn');
19547
19548                var isVisible = $('[data-js="config-points-giro-container"]').attr('visible') === 'true';
19549                var $changePointsGiroLabel = offerEl.find('.points-giro-modal');
19550                var $changePointsGiroModal = $('[data-js="text-modal-points"]');
19551                var freeSeatsAlertVisible = $freeSeatsAlertElem.data('show') ? true : false;
19552                var freeSeatsAlertMin = parseInt($('[data-js="alert-freeseats-min"]').attr('data-freeseatsmin'));
19553
19554                if (freeSeatsAlertVisible && hasFreeSeats && offer.freeArmchairs > 0 && offer.freeArmchairs <= freeSeatsAlertMin) {
19555                    $freeSeatsAlertElem.show();
19556                    var text = offerEl.find('.alert-text').text();
19557                    text = $('[data-js="result-cards-edit-texts"]').attr('edit-text-alert-min-seat-message');
19558                    offerEl.find('.alert-text').text(text.replace('${freeSeats}', offer.freeArmchairs));
19559                }
19560            }
19561
19562            offerEl.find('[data-js="class-type-label"]').html(offer.classtype.name);
19563            _this11.setExpandDetailsEvent(offerEl, offer);
19564            _this11.setExpandDetailsEventConnection(parentComponent, offerEl, offer.connection, listElementComponent);
19565            _this11.setExpandDetailsEventConnection(parentComponent, offerEl, secondConn, listElementComponent, true);
19566            _this11.setPriceLabel(hasFreeSeats, offerEl, offer, i);
19567            _this11.setBusPreviewEvent(offerEl, offer);
19568            _this11.setOfferImage(offerEl, offer);
19569
19570            if (offer.serviceType > 7 && !extraTimeWrapperComponent.is(':visible')) extraTimeWrapperComponent.show();
19571
19572            var parent = parentComponent.find('[data-js="classtype"]');
19573            parent.attr('data-js', 'classtype_' + offer.service);
19574            var $link = offerEl.find('[data-js="details-modal-target"]');
19575            new Modal($, $link);
19576            $sizeImagePointsGiro.css('height', _this11.configImagePoints.attr('height'));
19577            $sizeImagePointsGiro.css('width', _this11.configImagePoints.attr('width'));
19578            $sizeImagePointsGiro.attr('src', imageSrc).attr('alt', imageAlt).attr('title', imageTtl);
19579            $linkOfferGiroPoints.attr('title', linkTtl);
19580            $changePointsGiroLabel.css('color', _this11.configLabelPoints.attr('color'));
19581            $changePointsGiroLabel.css('font-family', _this11.configLabelPoints.attr('fontFamily'));
19582            $changePointsGiroLabel.css('font-size', _this11.configLabelPoints.attr('fontSize'));
19583            $changePointsGiroLabel.text(_this11.configLabelPoints.attr('text'));
19584            $changePointsGiroModal.text(_this11.configModalPoints.attr('text'));
19585            isVisible ? $changePointsGiroContainer.removeClass('d-none') : $changePointsGiroContainer.addClass('d-none');
19586            _this11.remarkV2 ? $changePointsGiroContainer.addClass('d-none') : null;
19587        });
19588    }
19589  }, {
19590    key: 'setBusPreviewEvent',
19591    value: function setBusPreviewEvent(offerEl, offer) {
19592      var btnBusPrev = offerEl.find('[data-js="bus-preview"]');
19593      btnBusPrev.click(function (event) {
19594        $('body, html').css("overflow-y", 'hidden');
19595        new BusPreview($, event, offer);
19596      });
19597    }
19598  }, {
19599    key: 'setOfferImage',
19600    value: function setOfferImage(offerEl, offer) {
19601      var $imageParent = offerEl.find('#image-wrapper');
19602      var friendlyName = offer.classtype.friendlyName;
19603      var classImage = offer.classtype.classImage;
19604      var classAltTextImage = offer.classtype.classAltTextImage;
19605
19606      var $liImg = $('<img id="img-class-detail" src="' + classImage + '" alt="' + classAltTextImage + '" title="' + classAltTextImage + '">');
19607      $imageParent.append($liImg);
19608    }
19609  }, {
19610    key: 'expandDetailsDesktop',
19611    value: function expandDetailsDesktop(e, self) {
19612      e.preventDefault();
19613      var offer = e.data.offer;
19614      var $el = $(e.currentTarget);
19615      var $classTypeDetails = $('[data-js="classtypeDetails"]');
19616      var modal = $('[data-js="details-modal-target"]');
19617
19618      $(modal).fadeIn("slow", function () {
19619        $(modal).addClass('fadein');
19620        $el.toggleClass('active');
19621      });
19622
19623      $el.toggleClass('active');
19624      $classTypeDetails.empty();
19625
19626      LoaderService.show();
19627      for (var index = 0; index < offer.classtype.details.length; index++) {
19628        var detail = offer.classtype.details[index];
19629        self.appendClasstypeDetail(detail, $classTypeDetails);
19630      }
19631
19632      setTimeout(function () {
19633        return LoaderService.hide();
19634      }, 500);
19635    }
19636  }, {
19637    key: 'appendClasstypeDetail',
19638    value: function appendClasstypeDetail(detail, classTypeDetailsComponent) {
19639      if (!detail.classDetailImage) return;
19640
19641      var $li = $('<li class="d-flex justify-content-start align-items-center class-detail
19641s-item">\n\t\t\t<img id="img-class-detail" src="' + detail.classDetailImage + '" alt="' + (detail.altTextDetail || detail.classDetailName) + '" title="' + detail.classDetailName + '" />\n\t\t\t<p>' + detail.classDetailName + '</p>\n\t\t\t</li>\n\t\t');
19642
19643      classTypeDetailsComponent.append($li);
19644    }
19645  }, {
19646    key: 'parseDateApiFormat',
19647    value: function parseDateApiFormat(date) {
19648      return date.split("/").reverse().join("-");
19649    }
19650  }, {
19651    key: 'isReturn',
19652    value: function isReturn() {
19653      return this.searchResultRef.isReturn();
19654    }
19655  }, {
19656    key: 'loadListItinerary',
19657    value: function loadListItinerary(listStops) {
19658      var $listRoute = $('[data-js="container-bus-rote"]');
19659      var $li = void 0;
19660
19661      listStops.forEach(function (el) {
19662        $li = $('<li class="item-bus-route">\n\t\t\t<span class="circle"></span>\n\t\t\t<div class="details">\n\t\t\t<p class="hour-route">' + el.hour + '</p>\n\t\t\t<p class="address">' + el.locality.city + '</p>\n\t\t\t</div>\n\t\t\t</li>\n\t\t');
19663
19664        $listRoute.append($li);
19665      });
19666    }
19667  }, {
19668    key: 'destroy',
19669    value: function destroy() {
19670      // Desativar eventos
19671      this.$window.off('scroll');
19672
19673      // Limpar referência ao elemento do DOM
19674      this.listCompanies.empty();
19675
19676      // Limpar arrays e objetos
19677      this.listRaces = [];
19678      this.listPriceVisibleInDispo = {};
19679      this.currentResult = {};
19680    }
19681  }], [{
19682    key: 'getItinerario',
19683    value: function getItinerario(parameters, callback) {
19684      LoaderService.show();
19685      HttpService.get('itinerary?' + $.param(parameters)).then(function (data) {
19686        LoaderService.hide();
19687        if (callback) return callback(data);
19688      }).catch(function (err) {
19689        LoaderService.hide();
19690        console.log(err);
19691      });
19692    }
19693  }, {
19694    key: 'searchPathAToConnection',
19695    value: function searchPathAToConnection(company, callback) {
19696      var parameters = {
19697        service: +company.listOffer[0].service,
19698        date: DateFormatter.extractDate(company.departureDate)
19699      };
19700
19701      ListResult.getItinerario(parameters, callback);
19702    }
19703  }, {
19704    key: 'searchPathConnectionToB',
19705    value: function searchPathConnectionToB(company, callback) {
19706      var connectionDepartureHour = company.listOffer[0]._connection._departureDate.split(' ');
19707
19708      var parameters = {
19709        service: +company.listOffer[0]._connection._service,
19710        date: DateFormatter.extractDate(connectionDepartureHour[0])
19711      };
19712
19713      ListResult.getItinerario(parameters, callback);
19714    }
19715  }, {
19716    key: 'searchPathAToB',
19717    value: function searchPathAToB(company, callback) {
19718      var parameters = {
19719        service: +company.listOffer[0].service,
19720        date: DateFormatter.extractDate(company.departureDate)
19721      };
19722
19723      ListResult.getItinerario(parameters, callback);
19724    }
19725  }, {
19726    key: 'applyTranslations',
19727    value: function applyTranslations() {
19728      var component = $('[data-js="result-cards-edit-texts"]');
19729
19730      var departureLabel = $(component).attr('edit-text-departure-label');
19731      var arrivedLabel = $(component).attr('edit-text-arrived-label');
19732      var originLabel = $(component).attr('edit-text-origin-label');
19733      var destinyLabel = $(component).attr('edit-text-destiny-label');
19734      var managedByLabel = $(component).attr('edit-text-managed-by-label');
19735      var classDetailsLabel = $(component).attr('edit-text-class-details-label');
19736      var seatingMapLabel = $(component).attr('edit-text-seating-map-label');
19737      var soldOffLabel = $(component).attr('edit-text-sold-off-label');
19738      var bestPriceMessageLabel = $(component).attr('edit-text-best-price-message-label');
19739      var buttonTextNormalPriceLabel = $(component).attr('edit-text-button-text-normal-price-labe');
19740      var buttonTextBestPriceLabel = $(component).attr('edit-text-button-text-best-price-label');
19741      var soldOffLabelButtonTextLabel = $(component).attr('edit-text-sold-off-label-button-text-label');
19742      var bestPriceLabel = $(component).attr('edit-text-best-price-label');
19743      var priceNormalLabel = $(component).attr('edit-text-price-normal-label');
19744      var pixTextLabel = $(component).attr('edit-text-label-pix-message');
19745      var cardTextLabel = $(component).attr('edit-text-label-card-message');
19746
19747      // styles
19748      var boxSoldOffTextShadowColor = $(component).attr('box-sold-off
19748-text-shadow-color');
19749
19750      $('.edit-text-departure-label').text(departureLabel);
19751      $('.edit-text-arrived-label').text(arrivedLabel);
19752      $('.edit-text-origin-label').text(originLabel);
19753      $('.edit-text-destiny-label').text(destinyLabel);
19754      $('.edit-text-class-details-label').text(classDetailsLabel);
19755      $('.edit-text-seating-map-label').text(seatingMapLabel);
19756      $('.edit-text-sold-off-label').text(soldOffLabel);
19757      $('.isBestPrice .edit-text-best-price-message-label').text(bestPriceMessageLabel);
19758      $('.available').not('.isBestPrice').find('button').find('text').text(buttonTextNormalPriceLabel);
19759      $('.available.isBestPrice').find('button').find('text').text(buttonTextBestPriceLabel);
19760      $('.unavailable').find('button').text(soldOffLabelButtonTextLabel);
19761      $('.available.isBestPrice').find('.price').find('.symbol').text(bestPriceLabel);
19762      $('.available').not('.isBestPrice').find('.price').find('.symbol').text(priceNormalLabel);
19763      $('.pix-rectangle').text(pixTextLabel);
19764      $('.label-card').text(cardTextLabel);
19765
19766      //styles
19767      $('.box-sold-off-text-shadow-color').text(boxSoldOffTextShadowColor);
19768
19769      //add title attribute
19770      $('.edit-text-class-details-label-title').attr('title', classDetailsLabel);
19771      $('.edit-text-seating-map-label-title').attr('title', seatingMapLabel);
19772
19773      setTimeout(function () {
19774        if (priceNormalLabel && priceNormalLabel.length >= 8) {
19775          $('.available').not('.isBestPrice').find('.price').addClass('mobile-price-symbol');
19776        }
19777        if (bestPriceLabel && bestPriceLabel.length >= 8) {
19778          $('.available.isBestPrice').find('.price').addClass('mobile-price-symbol');
19779        }
19780      }, 100);
19781    }
19782  }
19783  ]);
19784
19785  return ListResult;
19786}();
19787
19788/**
19789 * FIM
19790 * LOGICA LIST RESULT
19791 *
19792 */
19793'use strict';
19794
19795var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
19796
19797function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
19798
19799/**
19800 * INICIO
19801 * LOGICA OFFER SERVICE
19802 *
19803*/
19804var OfferService = function () {
19805  function OfferService() {
19806    _classCallCheck(this, OfferService);
19807  }
19808
19809  _createClass(OfferService, null, [{
19810    key: 'loadOfferTemplate',
19811    value: function loadOfferTemplate(callback) {
19812      var url = '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/assets/offer.html';
19813
19814      $.ajax({
19815        url: url,
19816        contentType: 'text/html',
19817        type: 'GET',
19818        headers: {
19819          'grupo_jca_auth': 'OA4XqR0LnBBxFkkToX5pUzcnAI2wX1sxeY4YtwXVyNoZyEt66Hg3Zg=='
19820        },
19821        success: function success(data) {
19822          return callback(null, data);
19823        },
19824        error: function error(XMLHttpRequest, textStatus, errorThrown) {
19825          console.log(textStatus, errorThrown);
19826          return callback(errorThrown, null);
19827        }
19828      });
19829    }
19830  }]);
19831
19832  return OfferService;
19833}();
19834/**
19835 * FIM
19836 * LOGICA OFFER SERVICE
19837 *
19838*/
19839'use strict';
19840
19841var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
19842
19843function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
19844
19845var LoginWhatsappController = function () {
19846  function LoginWhatsappController() {
19847    _classCallCheck(this, LoginWhatsappController);
19848
19849    this.loginForm = $('[data-js="login-form"]');
19850    this.inputLogin = $('[data-js="input-login"]');
19851    this.inputPassword = $('[data-js="input-password"]');
19852    this.btnLoginWpp = $('[data-js="button-login-wpp"]');
19853    this.btnShowPassword = $('[data-js="show-password"]');
19854    this.codeVerificationCtn = $('[data-js="code-verification-container"]');
19855    this.messageError = $('[data-js="message-erro-wpp"]');
19856    this.code = $('[data-js="code-verification"]');
19857    this.btnCopyCode = $('[data-js="copy-code-verification"]');
19858    this.labelCopy = $('[data-js="label-copy-key"]');
19859    this.init();
19860  }
19861
19862  _createClass(LoginWhatsappController, [{
19863    key: 'init',
19864    value: function init() {
19865      var _this = this;
19866
19867      this.initBtnTooltip();
19868      this.listenForm();
19869      this.inputLogin.focus();
19870      this.eneableBtnLogin();
19871      this.updateClassLogin();
19872      this.setMessageError();
19873      this.inputLogin.add(this.inputPassword).blur();
19874
19875      $(window).resize(function () {
19876        _this.updateClassLogin();
19877      });
19878    }
19879  }, {
19880    key: 'initBtnTooltip',
19881    value: function initBtnTooltip() {
19882      this.btnCopyCode.tooltip();
19883    }
19884  }, {
19885    key: 'listenForm',
19886    value: function listenForm() {
19887      var _this2 = this;
19888
19889      var masks = ['000.000.000-009', '00.000.000/0000-00'];
19890
19891      var maskBehavior = function maskBehavior(val) {
19892        return val.replace(/\D/g, '').length <= 11 ? masks[0] : masks[1];
19893      },
19894        cpfCnpjpOptions = {
19895          onKeyPress: function onKeyPress(val, e, field, options) {
19896            field.mask(maskBehavior.apply({}, arguments), options);
19897          }
19898        };
19899
19900      this.inputLogin.on('keyup focusout', function (e) {
19901        var isAlphabetic = new RegExp(/\D/g);
19902        var matchMasks = new RegExp(/(\.)|(\/)|(\-)/g);
19903        var valueWithoutMask = $(e.target).val().replace(matchMasks, '');
19904
19905        if (!isAlphabetic.test(valueWithoutMask) && valueWithoutMask.length >= 11) {
19906          _this2.inputLogin.mask('000.000.000-00');
19907        } else {
19908          _this2.inputLogin.unmask();
19909          _this2.inputLogin.attr("maxLength", "45");
19910        }
19911      });
19912
19913      this.btnShowPassword.on('click', function () {
19914        _this2.inputPassword.attr('type') === 'password' ? _this2.inputPassword.attr('type', 'text') : _this2.inputPassword.attr('type', 'password');
19915        _this2.btnShowPassword.toggleClass("active");
19916        _this2.inputPassword.toggleClass("show");
19917      });
19918
19919      $('[data-js="header-login-back-button"]').on('click', function () {
19920        setTimeout(function () {
19921          history.go(-1);
19922        }, 300);
19923      });
19924
19925      this.inputPassword.on('input', function () {
19926        if (_this2.inputPassword.val()) {
19927          _this2.inputPassword.addClass('active');
19928        } else {
19929          _this2.inputPassword.removeClass('active');
19930        }
19931      });
19932
19933      $('[data-js="input-login"], [data-js="input-password"]').on('input', function () {
19934        _this2.eneableBtnLogin();
19935      });
19936
19937      this.btnLoginWpp.on('click', function () {
19938        _this2.submitLoginWpp();
19939      });
19940
19941      this.btnCopyCode.on('click', function () {
19942        _this2.copyKey();
19943        _this2.activateCopyKey();
19944      });
19945    }
19946  }, {
19947    key: 'eneableBtnLogin',
19948    value: function eneableBtnLogin() {
19949      if (this.inputPassword.val() && this.inputLogin.val()) {
19950        this.btnLoginWpp.addClass('active');
19951        this.btnLoginWpp.attr('disabled', false);
19952      } else {
19953        this.btnLoginWpp.removeClass('active');
19954        this.btnLoginWpp.attr('disabled', true);
19955      }
19956    }
19957  }, {
19958    key: 'updateClassLogin',
19959    value: function updateClassLogin() {
19960      var isActiveClass = $('[data-js="login-component-identifier"]').val() == 'true' && Utils.getWindowSize().width > 950;
19961
19962      if (!isActiveClass) {
19963        $('main.main-content').removeClass("align-container");
19964        $('section.login').removeClass('login-box');
19965        $('login-third-part').removeClass('login-footer');
19966      } else {
19967        $('main.main-content').addClass("align-container");
19968        $('section.login').addClass('login-box');
19969        $('login-third-part').addClass('login-footer');
19970      }
19971    }
19972  }, {
19973    key: 'createLoginObject',
19974    value: function createLoginObject(login, password) {
19975      var regex = new RegExp(/^[a-z0-9\.\-\_]+@[a-z0-9]+[-]*[a-z0-9]*\.[a-z]+(\.[a-z]+)?$/gm);
19976      if (regex.test(login.toLowerCase())) {
19977        return {
19978          login: login.toLowerCase(),
19979          password: password
19980        };
19981      } else {
19982        return {
19983          login: this.clearLoginInput(login),
19984          password: password
19985        };
19986      }
19987    }
19988  }, {
19989    key: 'clearLoginInput',
19990    value: function clearLoginInput(str) {
19991      return str.replace(/\D/g, '').length >= 11 && str.replace(/\D/g, '').length <= 14 ? str.replace(/\D/g, '') 
19991: str;
19992    }
19993  }, {
19994    key: 'submitLoginWpp',
19995    value: function submitLoginWpp() {
19996      var _this3 = this;
19997
19998      var login = this.inputLogin.val();
19999      var password = this.inputPassword.val();
20000      var body = this.createLoginObject(login, password);
20001
20002      HttpService.post('loginWpp', body).then(function (data) {
20003        _this3.codeText = data.key;
20004        _this3.code.text(_this3.codeText);
20005        _this3.hideMessageError();
20006      }).catch(function (err) {
20007        console.error(err);
20008        _this3.showMessageError();
20009      });
20010    }
20011  }, {
20012    key: 'setMessageError',
20013    value: function setMessageError() {
20014      $('[data-js="message-error-login-wpp"]').text(i18n($('[data-js="login-whatsapp-text"]').data('message-error-wpp')));
20015    }
20016  }, {
20017    key: 'showMessageError',
20018    value: function showMessageError() {
20019      this.codeVerificationCtn.addClass('d-none');
20020      this.messageError.removeClass('d-none');
20021    }
20022  }, {
20023    key: 'hideMessageError',
20024    value: function hideMessageError() {
20025      this.codeVerificationCtn.removeClass('d-none');
20026      this.messageError.addClass('d-none');
20027    }
20028  }, {
20029    key: 'isFormValid',
20030    value: function isFormValid(event) {
20031      var currentForm = $(event.target).closest('form');
20032      var allFieldsValid = true;
20033      currentForm.find('input[required]').each(function () {
20034        if ($(this).val() == '') {
20035          $(this).addClass("invalid");
20036          allFieldsValid = false;
20037        } else {
20038          $(this).removeClass("invalid");
20039        }
20040      });
20041
20042      if (allFieldsValid) {
20043        return true;
20044      } else {
20045        this.openValidation($('[data-js="login-whatsapp-text"]').data('wrong-fields-wpp'));
20046        return false;
20047      }
20048    }
20049  }, {
20050    key: 'copyKey',
20051    value: function copyKey() {
20052      var value = $('[data-js="code-verification"]');
20053
20054      var $temp = $("<input>");
20055      $("body").append($temp);
20056      $temp.val($(value).text()).select();
20057      document.execCommand("copy");
20058      $temp.remove();
20059    }
20060  }, {
20061    key: 'activateCopyKey',
20062    value: function activateCopyKey() {
20063      this.btnCopyCode.addClass('active');
20064      this.labelCopy.text($('[data-js="login-whatsapp-text"]').data('copied-button-text'));
20065      this.btnCopyCode.attr('data-bs-original-title', $('[data-js="login-whatsapp-text"]').data('copied-tooltip-text')).tooltip('show');
20066    }
20067  }]);
20068
20069  return LoginWhatsappController;
20070}();
20071'use strict';
20072
20073function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
20074
20075var Informative = function Informative($) {
20076  _classCallCheck(this, Informative);
20077
20078  this.informativeComponent = $('[data-js="informative-component"]');
20079  this.isCarousel = this.informativeComponent.attr('is-carousel') == 'true' ? true : false;
20080  this.itemContainer = $('[data-js="informative-item-container"]');
20081  this.carouselContainer = $('[data-js="informative-carousel-container"]');
20082
20083  new InformativeCarousel($);
20084  new InformativeItem($);
20085};
20086'use strict';
20087
20088var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
20089
20090function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
20091
20092/**
20093 *
20094 * Login Controller
20095 *
20096 * INICIO
20097 */
20098
20099var LoginController = function () {
20100  function LoginController($) {
20101    _classCallCheck(this, LoginController);
20102
20103    this.loginForm = $('[data-js="login-form"]');
20104    this.inputLogin = $('[data-js="input-login"]');
20105    this.inputPassword = $('[data-js="input-password"]');
20106    this.openRequestPassword = $('[data-js="open-request-password"]');
20107    this.btnLogin = $('[data-js="button-login"]');
20108    this.btnRegisterUser = $('[data-js="button-register-user"]');
20109    this.errorMessage = $('[data-js="login-error-message"]');
20110    this.passwordRecovery = new PasswordRecoveryOverlay($);
20111    this.formData = SessionStorage.get('formData');
20112    this.modalUpsel = SessionStorage.get('offerModalUpsel');
20113    this.userName = $('[data-js="name-account"]');
20114    this.walletUser = $('[data-js="wallet-account-total"]');
20115    this.btnShowPassword = $('[data-js="show-password"]');
20116    this.btnLoginGoogle = $('[data-js="btn-login-google"]');
20117    this.btnLoginFacebook = $('[data-js="btn-login-facebook"]');
20118    this.btnLoginApple = $('[data-js="btn-login-apple"]');
20119    this.requiredLoggedUser = $('[data-js="login-Dependency-Redirect"]').val() == 'true';
20120    this.cart = SessionStorage.get('cart');
20121    this.captchaChecked = true;
20122    this.loginDatalayerService = new LoginDatalayerService($);
20123    this.countOccurrenceCaptcha = 0;
20124    this.captchaComponent = new CaptchaController($);
20125    this.init();
20126  }
20127
20128  _createClass(LoginController, [{
20129    key: 'init',
20130    value: function init() {
20131      var _this = this;
20132
20133      this.openPasswordModal();
20134      this.submitLogin();
20135      this.register();
20136      this.loadUser();
20137      this.listenForm();
20138      this.inputLogin.focus();
20139      this.eneableBtnLogin();
20140      this.updateClassLogin();
20141      this.handleSocialLogin();
20142
20143      this.inputLogin.add(this.inputPassword).blur();
20144      this.handleModalUpselInPage();
20145
20146      $(window).resize(function () {
20147        _this.updateClassLogin();
20148      });
20149    }
20150  }, {
20151    key: 'handleModalUpselInPage',
20152    value: function handleModalUpselInPage() {
20153      if (this.formData && this.modalUpsel) {
20154        $('[data-js="upsel-login"]').parent().addClass('margin-top--100');
20155
20156        $(window).resize(function () {
20157          if (Utils.getWindowSize().width < 950) {
20158            $('[data-js="upsel-login"]').closest('.main-content').css({
20159              'background-color': '#f5f5f5 !important'
20160            });
20161          }
20162        });
20163      }
20164    }
20165  }, {
20166    key: 'updateClassLogin',
20167    value: function updateClassLogin() {
20168      var isActiveClass = $('[data-js="login-component-identifier"]').val() == 'true' && Utils.getWindowSize().width > 950;
20169
20170      if (!isActiveClass) {
20171        $('main.main-content').removeClass("align-container");
20172        $('section.login').removeClass('login-box');
20173        $('login-third-part').removeClass('login-footer');
20174      } else {
20175        $('main.main-content').addClass("align-container");
20176        $('section.login').addClass('login-box');
20177        $('login-third-part').addClass('login-footer');
20178      }
20179    }
20180  }, {
20181    key: 'eneableBtnLogin',
20182    value: function eneableBtnLogin() {
20183      if (this.inputPassword.val() && this.inputLogin.val()) {
20184        this.btnLogin.addClass('active');
20185        this.btnLogin.attr('disabled', false);
20186      } else {
20187        this.btnLogin.removeClass('active');
20188        this.btnLogin.attr('disabled', true);
20189      }
20190    }
20191  }, {
20192    key: 'loadUser',
20193    value: function loadUser() {
20194      var userAccount = SessionStorage.get('passenger');
20195
20196      if (userAccount) {
20197        this.userName.text(userAccount._name);
20198      }
20199    }
20200  }, {
20201    key: 'listenForm',
20202    value: function listenForm() {
20203      var _this2 = this;
20204
20205      var masks = ['000.000.000-009', '00.000.000/0000-00'];
20206
20207      var maskBehavior = function maskBehavior(val) {
20208        return val.replace(/\D/g, '').length <= 11 ? masks[0] : masks[1];
20209      },
20210        cpfCnpjpOptions = {
20211          onKeyPress: function onKeyPress(val, e, field, options) {
20212            field.mask(maskBehavior.apply({}, arguments), options);
20213          }
20214        };
20215
20216      this.inputLogin.on('keyup', function (e) {
20217        var isAlphabetic = new RegExp(/\D/g);
20218        var matchMasks = new RegExp(/(\.)|(\/)|(\-)/g);
20219        var valueWithoutMask = $(e.target).val().replace(matchMasks, '');
20220
20221        if (!isAlphabetic.test(valueWithoutMask) && valueWithoutMask.length >= 11) {
20222          _this2.inputLogin.mask(maskBehavior, cpfCnpjpOptions);
20223        } else {
20224          _this2.inputLogin.unmask();
20225          _this2.inputLogin.attr("maxLength", "45");
20226        }
20227      });
20228
20229      this.btnShowPassword.on('click', function () {
20230        _this2.inputPassword.attr('type') === 'password' ? _this2.inputPassword.attr('type', 'text') : _this2.inputPassword.attr('type', 'password');
20231        _this2.btnShowPassword.toggleClass("active");
20232        _this2.inputPassword.toggleClass("show");
20233      });
20234
20235      $('[data-js="header-login-back-button"]').on('click', function () {
20236        setTimeout(function () {
20237          history.go(-1);
20238        }, 300);
20239      });
20240
20241      this.inputPassword.on('input', function () {
20242        if (_this2.inputPassword.val()) {
20243          _this2.inputPassword.addClass('active');
20244        } else {
20245          _this2.inputPassword.removeClass('active');
20246        }
20247      });
20248
20249      $('[data-js="input-login"], [data-js="input-password"]').on('keyup', function (event) {
20250        _this2.eneableBtnLogin();
20251        var keyCode = event.keyCode || event.which;
20252        if (keyCode === Utils.keyCodes.ENTER) {
20253          _this2.btnLogin.click();
20254        }
20255      });
20256
20257      this.inputPassword.on('paste', function () {
20258        setTimeout(function () {
20259          _this2.eneableBtnLogin();
20260        }, 100);
20261      });
20262
20263      this.inputLogin.on('paste', function () {
20264        setTimeout(function () {
20265          _this2.eneableBtnLogin();
20266        }, 100);
20267      });
20268      var dataArray = ['[data-js=input-password], [data-js=open-request-password]'];
20269      !Utils.quotesBlock(dataArray);
20270    }
20271  }, {
20272    key: 'openPasswordModal',
20273    value: function openPasswordModal() {
20274      var _this3 = this;
20275
20276      this.openRequestPassword.click(function () {
20277        _this3.passwordRecovery.showOverlay();
20278        _this3.passwordRecovery.inputEmail.focus();
20279        $('section.login').css('visibility', 'hidden');
20280
20281        if (Utils.getWindowSize().width <= Utils.getWindowSize().breakpoints.LG) $('html, body').animate({ scrollTop: 0 }, 'fast');
20282      });
20283    }
20284  }, {
20285    key: 'submitLogin',
20286    value: function submitLogin() {
20287      var _this4 = this;
20288
20289      this.btnLogin.click(function (event) {
20290        _this4.captchaChecked = _this4.captchaComponent.handleCaptcha();
20291
20292        if (_this4.isFormValid(event)) {
20293          var currentForm = $(event.target).closest('form');
20294          var login = currentForm.find('[data-js="input-login"]').val();
20295          var password = currentForm.find('[data-js="input-password"]').val();
20296          var body = _this4.createLoginObject(login, password);
20297
20298          LoaderService.show();
20299          var headers = { 'channel': Utils.getChannelTitle(_this4.isPaymentWhatsapp, _this4.saleplatform) };
20300          HttpService.post('loginUser', body, headers).then(function (data) {
20301            return _this4.handleLoginSuccess(data);
20302          }).catch(function (err) {
20303            return _this4.handleLoginFail(err);
20304          });
20305        }
20306      });
20307    }
20308  }, {
20309    key: 'parseAddress',
20310    value: function parseAddress(data) {
20311      var addresses = new Address();
20312      addresses.zipCode = data.zipCode;
20313      addresses.street = data.street;
20314      addresses.complement = data.complement;
20315      addresses.neighborhood = data.neighborhood;
20316      addresses.city = data.city;
20317      addresses.state = data.state;
20318      addresses.number = data.number;
20319      return addresses;
20320    }
20321  }, {
20322    key: 'handleLoginSuccess',
20323    value: function handleLoginSuccess(data) {
20324      LoaderService.hide();
20325      var passenger = this.parsePassenger(data.user);
20326      SessionStorage.set('passenger', passenger);
20327      SessionStorage.set('jca_token', data.token);
20328      localStorage.setItem("logged", true);
20329      this.loginDatalayerService.sendLoginViewToAnalytics("true");
20330
20331      //apply redirect
20332      var formData = this.formData;
20333      var createSubmitQueryString = function createSubmitQueryString(formData) {
20334        var submitParams = {};
20335        submitParams.data_ida = Utils.parseToDayMonthYearFormat(formData.depart.date);
20336        submitParams.data_volta = Utils.parseToDayMonthYearFormat(formData.return.date);
20337        submitParams.origem_id = formData.depart.origin.id;
20338        submitParams.destino_id = formData.depart.destination.id;
20339        submitParams.num_psgr = formData.passengers[0].quantity;
20340        submitParams.deep = formData.deep;
20341
20342        Utils.removeEmptyAttributes(submitParams);
20343        return $.param(submitParams);
20344      };
20345      var checkLogin = $('[data-js="login-Dependency-Redirect"]').val();
20346
20347      if (formData) {
20348        if (!this.requiredLoggedUser) {
20349          if (this.cart) $(location).attr('href', $('#resourcePathPassengers').val()); else {
20350            var submitQuerySring = createSubmitQueryString(formData);
20351            $(location).attr('href', $('#searchResultPath').val() + '?' + submitQuerySring);
20352          }
20353        } else {
20354          var submitQuerySring = createSubmitQueryString(formData);
20355          $(location).attr('href', $('#searchResultPath').val() + '?' + submitQuerySring);
20356        }
20357      } else {
20358        if (localStorage.getItem("referrer") == null) {
20359          $(location).attr('href', $('#homePagePath').val());
20360        } else {
20361          $(location).attr('href', localStorage.getItem("referrer"));
20362        }
20363      }
20364    }
20365  }, {
20366    key: 'handleLoginFail',
20367    value: function handleLoginFail() {
20368      LoaderService.hide();
20369      this.openValidation('O email ou senha inseridos não constam em nosso cadastro. Digite novamente o email e senha ou efetue o cadastro abaixo.');
20370      this.inputLogin.focus();
20371    }
20372  }, {
20373    key: 'handleLoginFail',
20374    value: function handleLoginFail(err) {
20375      LoaderService.hide();
20376      this.loginDatalayerService.sendLoginViewToAnalytics("false");
20377      this.verifyErr(err);
20378      this.handleMessageError(err);
20379      this.inputLogin.focus();
20380    }
20381  }, {
20382    key: 'handleMessageError',
20383    value: function handleMessageError(errObj) {
20384      var msg = errObj.responseJSON.message;
20385
20386      if (this.countOccurrenceCaptcha == 1) {
20387        this.errorMessage.removeClass('active');
20388        return;
20389      }
20390
20391      if (msg === 'Impossible to login') {
20392        this.openValidation(i18n('err_msg_impossible_to_login'));
20393      } else {
20394        this.openValidation(i18n('err_msg_login'));
20395      }
20396    }
20397  }, {
20398    key: 'verifyErr',
20399    value: function verifyErr(err) {
20400      var messageError = err.responseJSON.message;
20401      var aemEnableCaptchaCheckbox = $('[data-js="aem-enable-captcha-checkbox"]').val();
20402
20403      if (messageError == 'ShowCaptcha' && aemEnableCaptchaCheckbox == 'true') {
20404        $('.login').addClass('active');
20405        this.captchaComponent.showCaptcha();
20406        this.countOccurrenceCaptcha++;
20407      }
20408    }
20409  }, {
20410    key: 'createLoginObject',
20411    value: function createLoginObject(login, password) {
20412      var regex = new RegExp(/^[a-z0-9\.\-\_]+@[a-z0-9]+[-]*[a-z0-9]*\.[a-z]+(\.[a-z]+)?$/gm);
20413      if (regex.test(login.toLowerCase())) {
20414        return {
20415          login: login.toLowerCase(),
20416          password: password
20417        };
20418      } else {
20419        return {
20420          login: this.clearLoginInput(login),
20421          password: password
20422        };
20423      }
20424    }
20425  }, {
20426    key: 'clearLoginInput',
20427    value: function clearLoginInput(str) {
20428      return str.replace(/\D/g, '').length >= 11 && str.replace(/\D/g, '').length <= 14 ? str.replace(/\D/g, '') : str;
20429    }
20430  }, {
20431    key: 'register',
20432    value: function register() {
20433      var _this5 = this;
20434
20435      this.btnRegisterUser.click(function (e) {
20436        if ($(e.target).data('action-url')) {
20437          $(location).attr('href', $(e.target).data('action-url'));
20438        } else if (SessionStorage.get('formData') && $('#registrationWithinTheFlow').val()) {
20439          $(location).attr('href', $('#registrationWithinTheFlow').val());
20440        } else if ($('#registrationOutOfFlow').val()) {
20441          $(location).attr('href', $('#registrationOutOfFlow').val());
20442        }
20443
20444      });
20445    }
20446  }, {
20447    key: 'parsePassenger',
20448    value: function parsePassenger(data) {
20449      var passenger = new Passenger();
20450      var addresses = data.addresses.length > 0 ? this.parseAddress(data.addresses[0]) : null;
20451
20452      passenger.name = String(data.name + ' ' + data.familyName).trim();
20453      passenger.login = data.login;
20454      passenger.email = data.email;
20455      passenger.image = data.image;
20456      passenger.cpf = data.cpf;
20457      passenger.cnpj = data.cnpj;
20458      passenger.passport = data.passport;
20459      passenger.documentNumber = data.cpf;
20460      passenger.birthDate = data.birthDate != null ? DateFormatter.extractDate(data.birthDate) : null;
20461      passenger.phone = data.phone;
20462      passenger.areaCode = data.areaCode;
20463      passenger.phoneType = data.phoneType;
20464      passenger.id = data.id;
20465      passenger.optin = data.optin;
20466      passenger.validated = data.validated;
20467      passenger.addresses = addresses;
20468      passenger.groups = data.groups;
20469      return passenger;
20470    }
20471  }, {
20472    key: 'openValidation',
20473    value: function openValidation(msg) {
20474      var _this6 = this;
20475
20476      this.errorMessage.find('.normal').text(msg);
20477      this.errorMessage.addClass('active');
20478
20479      $('[data-js="input-login"], [data-js="input-password"]').keyup(function (e) {
20480        $(e.target).removeClass('invalid');
20481        if ($(e.target).val().length === 0) {
20482          _this6.errorMessage.removeClass('active');
20483        }
20484      }).click(function (e) {
20485        if ($(e.target).val().length === 0) {
20486          _this6.errorMessage.removeClass('active');
20487        }
20488      });
20489    }
20490  }, {
20491    key: 'isFormValid',
20492    value: function isFormValid(event) {
20493      var currentForm = $(event.target).closest('form');
20494      var allFieldsValid = true;
20495      currentForm.find('input[required]').each(function () {
20496        if ($(this).val() == '') {
20497          $(this).addClass("invalid");
20498          allFieldsValid = false;
20499        } else {
20500          $(this).removeClass("invalid");
20501        }
20502      });
20503
20504      if (allFieldsValid) {
20505        return true;
20506      } else {
20507        this.openValidation('Preencha todos os campos corretamente.');
20508        return false;
20509      }
20510    }
20511  }, {
20512    key: 'handleSocialLogin',
20513    value: function handleSocialLogin() {
20514      var _this7 = this;
20515
20516      this.btnLoginGoogle.click(function () {
20517        return _this7.initSocialLoginGoogle();
20518      });
20519      this.btnLoginFacebook.click(function () {
20520        return _this7.initSocialLoginFacebook();
20521      });
20522      this.btnLoginApple.click(function () {
20523        return _this7.initSocialLoginApple();
20524      });
20525    }
20526  }, {
20527    key: 'initSocialLoginGoogle',
20528    value: function initSocialLoginGoogle() {
20529      var _this8 = this;
20530
20531      var initGoogleSignIn = function initGoogleSignIn() {
20532        var onSuccess = function onSuccess(googleUser) {
20533
20534          var body = { idToken: googleUser.getAuthResponse().id_token };
20535
20536          LoaderService.show();
20537          HttpService.post('loginGoogle', body).then(function (data) {
20538            gapi.auth2.getAuthInstance().signOut();
20539            _this8.handleLoginSuccess(data);
20540          }).catch(function (err) {
20541            console.error(err);
20542            _this8.handleLoginFail();
20543          });
20544        };
20545
20546        var onFailure = function onFailure(err) {
20547          console.error(err);
20548        };
20549
20550        gapi.auth2.init({ client_id: $('[data-js="google-client-id"]').val() }).then(function (authInstance) {
20551          return authInstance.signIn().then(onSuccess, onFailure);
20552        }).catch(function (err) {
20553          return console.error(err);
20554        });
20555      };
20556
20557      gapi.load('auth2', initGoogleSignIn);
20558    }
20559  }, {
20560    key: 'initSocialLoginFacebook',
20561    value: function initSocialLoginFacebook() {
20562      var _this9 = this;
20563
20564      var onSuccess = function onSuccess(facebookRes) {
20565        var accessToken = facebookRes.authResponse.accessToken;
20566
20567
20568        var body = { accessToken: accessToken };
20569
20570        LoaderService.show();
20571        HttpService.post('loginFacebook', body).then(function (data) {
20572          FB.logout(function () {
20573            _this9.handleLoginSuccess(data);
20574          });
20575        }).catch(function (err) {
20576          FB.logout(function () {
20577            console.error(err);
20578            _this9.handleLoginFail();
20579          });
20580        });
20581      };
20582
20583      var onFailure = function onFailure(err) {
20584        console.error(err);
20585      };
20586
20587      FB.init({
20588        appId: $('[data-js="facebook-app-id"]').val(),
20589        autoLogAppEvents: true,
20590        xfbml: true,
20591        version: 'v14.0'
20592      });
20593
20594      FB.login(function (response) {
20595        if (response.status === 'connected') {
20596          onSuccess(response);
20597        } else {
20598          onFailure(response);
20599        }
20600      });
20601    }
20602  }, {
20603    key: 'initSocialLoginApple',
20604    value: function initSocialLoginApple() {
20605      var _this10 = this;
20606
20607      var nonce = new Date().getTime();
20608
20609      AppleID.auth.init({
20610        clientId: $('[data-js="apple-client-id"]').val(),
20611        scope: "name email",
20612        redirectURI: $('[data-js="apple-redirect-url"]').val() + '?page=login',
20613        nonce: '' + nonce,
20614        usePopup: true
20615      });
20616
20617      var onSuccess = function onSuccess(event) {
20618        var body = { idToken: event.detail.authorization.id_token };
20619
20620        LoaderService.show();
20621        HttpService.post('loginApple', body).then(function (data) {
20622          _this10.handleLoginSuccess(data);
20623        }).catch(function (err) {
20624          console.error(err);
20625          _this10.handleLoginFail();
20626        });
20627      };
20628
20629      var onFailure = function onFailure(event) {
20630        console.error(event);
20631      };
20632
20633      document.addEventListener('AppleIDSignInOnSuccess', onSuccess);
20634      document.addEventListener('AppleIDSignInOnFailure', onFailure);
20635      AppleID.auth.signIn();
20636    }
20637  }]);
20638
20639  return LoginController;
20640}();
20641/**
20642 *
20643 * Login Controller
20644 *
20645 * FIM
20646 */
20647'use strict';
20648
20649var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
20650
20651function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
20652
20653var LoginWalletController = function () {
20654  function LoginWalletController($) {
20655    _classCallCheck(this, LoginWalletController);
20656
20657    this.pinInput = $('[data-js="input-password-wallet"]');
20658    this.btnShowPin = $('[data-js="show-pin"]');
20659    this.btnLogin = $('[data-js="button-login-wallet"]');
20660    this.pinDots = $('[data-js="pin-dot"]');
20661    this.homeBack = $('[data-js="home-back"]');
20662    this.errorMessageContainer = $('[data-js="login-error-message-wallet"]');
20663    this.openRequestPassword = $('[data-js="open-request-password-wallet"]');
20664    this.mainPassenger = SessionStorage.get('passenger');
20665    this.createPin = $('[data-js="button-register-user-wallet"]');
20666    this.firstClick = true; // Variable to track the first click
20667    this.qttPaymentErr = 1; // Inicializa contador de erros
20668    this.init();
20669  }
20670
20671  _createClass(LoginWalletController, [{
20672    key: 'init',
20673    value: function init() {
20674      this.clickOnInput();
20675      //Utils.checkWalletGroup();
20676      this.listenForm();
20677    }
20678  }, {
20679    key: 'clickOnInput',
20680    value: function clickOnInput() {
20681      var _this = this;
20682
20683      this.pinInput.on('click', function () {
20684        if (_this.firstClick) {
20685          $(_this.pinDots[0]).addClass('active');
20686          _this.firstClick = false; // Set to false after the first click
20687        }
20688      });
20689    }
20690  }, {
20691    key: 'listenForm',
20692    value: function listenForm() {
20693      var _this2 = this;
20694
20695      this.pinInput.on('input', function () {
20696        _this2.updatePinDots();
20697        _this2.updatePlaceholder();
20698        _this2.enableBtnLogin();
20699        _this2.toggleActiveClass();
20700      });
20701
20702      this.createPin.on('click', function () {
20703        $(location).attr('href', $('#walletPinPagePath').val());
20704      });
20705
20706      this.btnShowPin.on('click', function () {
20707        var isPassword = _this2.pinInput.attr('type') === 'password';
20708        _this2.pinInput.attr('type', isPassword ? 'text' : 'password');
20709        _this2.btnShowPin.toggleClass("active");
20710        _this2.pinInput.toggleClass("show");
20711      });
20712
20713      this.pinInput.on('keyup', function (event) {
20714        var keyCode = event.keyCode || event.which;
20715        if (keyCode === Utils.keyCodes.ENTER && _this2.pinInput.val().length === 6) {
20716          _this2.btnLogin.click();
20717        }
20718      });
20719
20720      this.pinInput.on('paste', function () {
20721        setTimeout(function () {
20722          _this2.enableBtnLogin();
20723          _this2.updatePlaceholder();
20724        }, 100);
20725      });
20726
20727      this.homeBack.on('click', function () {
20728        $(location).attr('href', $('#homePagePath').val());
20729      });
20730
20731      this.openRequestPassword.on('click', function () {
20732        $(location).attr('href', $('#walletPinRecoveryPagePath').val());
20733      });
20734
20735      this.btnLogin.on('click', function () {
20736        _this2.loginWallet(_this2.pinInput.val());
20737      });
20738
20739      this.pinDots.on('click', function (event) {
20740        var clickedDotIndex = _this2.pinDots.index(event.currentTarget);
20741        _this2.highlightClickedDot(clickedDotIndex);
20742      });
20743    }
20744  }, {
20745    key: 'updatePinDots',
20746    value: function updatePinDots() {
20747      var value = this.pinInput.val();
20748      this.pinDots.each(function (index, dot) {
20749        $(dot).toggleClass('filled', index < value.length);
20750        $(dot).toggleClass('active', index === value.length);
20751      });
20752    }
20753  }, {
20754    key: 'updatePlaceholder',
20755    value: function updatePlaceholder() {
20756      var length = this.pinInput.val().length;
20757      var maxLength = this.pinInput.attr('maxlength');
20758      var placeholder = '•'.repeat(Math.max(length, 1)) + '•'.repeat(maxLength - length);
20759      this.pinInput.attr('placeholder', placeholder);
20760    }
20761  }, {
20762    key: 'enableBtnLogin',
20763    value: function enableBtnLogin() {
20764      this.btnLogin.prop('disabled', this.pinInput.val().length !== 6);
20765    }
20766  }, {
20767    key: 'toggleActiveClass',
20768    value: function toggleActiveClass() {
20769      this.pinInput.toggleClass('active', !!this.pinInput.val());
20770    }
20771  }, {
20772    key: 'highlightClickedDot',
20773    value: function highlightClickedDot(index) {
20774      this.pinDots.removeClass('clicked');
20775      $(this.pinDots[index]).addClass('clicked');
20776    }
20777  }, {
20778    key: 'loginWallet',
20779    value: function loginWallet(userPin) {
20780      var _this3 = this;
20781
20782      var payload = {
20783        pin: userPin,
20784        deviceFingerPrint: $("#device-fingerprint").val()
20785      };
20786
20787      var headers = this.getAuthHeaders();
20788
20789      LoaderService.show();
20790
20791      HttpService.post("loginWallet", payload, headers).then(function (data) {
20792        LoaderService.hide();
20793        SessionStorage.set('user_wallet', data.result);
20794        _this3.handleLoginSuccess();
20795      }).catch(function (err) {
20796        LoaderService.hide();
20797        _this3.showErrorMessage(err ? err : i18n("error_login_wallet"));
20798      });
20799    }
20800  }, {
20801    key: 'getAuthHeaders',
20802    value: function getAuthHeaders() {
20803      var token = this.getToken();
20804      return {
20805        Authorization: token || ''
20806      };
20807    }
20808  }, {
20809    key: 'getToken',
20810    value: function getToken() {
20811      var tokenFromStorage = SessionStorage.get("jca_token");
20812      if (tokenFromStorage) {
20813        return tokenFromStorage;
20814      }
20815
20816      var tokenFromUrl = new URLSearchParams(window.location.search).get('jca_token');
20817      return tokenFromUrl ? tokenFromUrl.replace(/^"|"$/g, '') : null;
20818    }
20819  }, {
20820    key: 'handleLoginSuccess',
20821    value: function handleLoginSuccess() {
20822      var completementPix = SessionStorage.get('completementPix');
20823      if (completementPix === true || completementPix === false) {
20824        this.paymentWallet();
20825      } else {
20826        $(location).attr("href", $('#paymentPagePath').val());
20827      }
20828    }
20829  }, {
20830    key: 'showErrorMessage',
20831    value: function showErrorMessage(message) {
20832      var errorMessage = message.responseJSON ? message.responseJSON.Message : i18n("error_login_wallet");
20833      this.errorMessageContainer.find('label.normal').text(errorMessage);
20834      this.errorMessageContainer.addClass('d-flex');
20835    }
20836  }, {
20837    key: 'getIP',
20838    value: function getIP() {
20839      return new Promise(function (resolve, reject) {
20840        $.getJSON('https://api.ipify.org?format=json').then(function (data) {
20841          return resolve(data.ip);
20842        }).catch(function () {
20843          $.getJSON('https://jsonip.com/').then(function (data) {
20844            return resolve(data.ip);
20845          }).catch(function (err) {
20846            return reject(err);
20847          });
20848        });
20849      });
20850    }
20851  }, {
20852    key: 'paymentWallet',
20853    value: function paymentWallet() {
20854      var _this4 = this;
20855
20856      var passengersService = SessionStorage.get('passengers');
20857      var insuranceCheckService = SessionStorage.get('insuranceCheck');
20858      var salePlatform = SessionStorage.get('salePlatform');
20859
20860      var passengers = Array.isArray(passengersService) ? passengersService : [];
20861
20862      var branch = '0001';
20863      var account = '0001-1';
20864      var documentNumber = this.mainPassenger._documentNumber;
20865      var paymentMethod = 'PIX';
20866      var deviceFingerprint = $("#device-fingerprint").val();
20867      var hasInsurance = insuranceCheckService;
20868
20869      LoaderService.show();
20870
20871      this.getIP().then(function (ip) {
20872        var paymentData = new PaymentPixWallet(branch, account, documentNumber, paymentMethod, deviceFingerprint, passengers, hasInsurance, ip, salePlatform);
20873
20874        var headers = {
20875          'Authorization': '' + SessionStorage.get('jca_token'),
20876          'sessionseatlock': SessionStorage.get('sessionseatlock'),
20877          'channel': Utils.getChannelTitle(false, '')
20878        };
20879
20880        HttpService.post('paymentPixWallet', paymentData, headers).then(function (data) {
20881          // Verificar se realmente teve sucesso
20882          if (data.success === false) {
20883            throw {
20884              responseJSON: {
20885                error: data.error || 'Erro ao processar pagamento',
20886                errorCode: data.errorCode || ''
20887              }
20888            };
20889          }
20890
20891          LoaderService.hide();
20892          SessionStorage.set('checkout', data.result);
20893          $(location).attr('href', $('#walletPaymentCheckoutPagePath').val());
20894        }).catch(function (err) {
20895          console.error('Payment error:', err);
20896          LoaderService.hide();
20897
20898          if (_this4.verifySeatErr(err)) {
20899            AlertConfirmation.show(i18n("error_seat_title"), i18n("error_seat_message"), true);
20900
20901            $('#overlay, [data-js="close-menu"]').on("click", function () {
20902              $(location).attr('href', $('#homePagePath').val());
20903            });
20904          } else {
20905            var errorMsg = 'Erro ao processar pagamento';
20906            var errorCode = '';
20907
20908            try {
20909              var response = err.responseJSON;
20910              if (response && response.error) {
20911                errorMsg = response.error;
20912              }
20913              if (response && response.errorCode) {
20914                errorCode = response.errorCode;
20915              }
20916            } catch (e) {
20917              console.error('Error parsing response:', e);
20918            }
20919
20920            console.log('Showing error popup:', errorMsg, errorCode);
20921            _this4.checkQttPaymentErr(errorMsg, errorCode);
20922          }
20923        });
20924      });
20925    }
20926  }, {
20927     key: 'verifySeatErr',
20928     value: function verifySeatErr(err) {
20929       if (err && err.responseJSON && err.responseJSON.error && typeof err.responseJSON.error === 'string') {
20930         if (err.responseJSON.error.toLowerCase().includes('number of passengers and seats, incorrect')) return true;
20931       } else if (err && err.responseJSON && err.responseJSON.result && err.responseJSON.result.toLowerCase().includes('sessão expirada')) {
20932         return true;
20933       }
20934
20935       return false;
20936     }
20937  }, {
20938    key: 'checkQttPaymentErr',
20939    value: function checkQttPaymentErr(msg, errorMsgCode) {
20940      OverlayService.show();
20941
20942      this.showMsgPaymentError(msg, errorMsgCode || 'payment_generic_error');
20943
20944      if (errorMsgCode && errorMsgCode.toString().toLowerCase() === '2b0') {
20945        $('[data-js="link-contact-us-confirmation"]').css('display', 'block');
20946      } else {
20947        $('[data-js="link-contact-us-confirmation"]').css('display', 'none');
20948      }
20949    }
20950  }, {
20951    key: 'showMsgPaymentError',
20952    value: function showMsgPaymentError(text1, text2, redirect) {
20953      AlertConfirmation.show(i18n(text1) || text1, i18n(text2) || text2, redirect);
20954
20955      if (redirect) {
20956        $('#overlay, [data-js="close-menu"]').on('click', function () {
20957          $(location).attr('href', $('#homePagePath').val());
20958        });
20959      }
20960    }
20961  }, {
20962    key: 'verifyErr',
20963    value: function verifyErr(err) {
20964      var isSpecificError = err.responseJSON ? err.responseJSON.result && (err.responseJSON.result.hasOwnProperty('message') || typeof err.responseJSON.result === 'string') : {};
20965
20966      if (isSpecificError) {
20967        return true;
20968      }
20969      return false;
20970    }
20971  }, {
20972    key: 'handleSpecificErr',
20973    value: function handleSpecificErr(err) {
20974      this.errorPurchasePayment();
20975    }
20976  }]);
20977
20978  return LoginWalletController;
20979}();
20980"use strict";
20981
20982var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
20983
20984function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
20985
20986var MessageCpfController = function () {
20987  function MessageCpfController(passenger) {
20988    _classCallCheck(this, MessageCpfController);
20989
20990    this.passenger = passenger;
20991    this.isCpfValidPix = true;
20992    this.isCpfValidTransfer = true;
20993    this.init();
20994  }
20995
20996  _createClass(MessageCpfController, [{
20997    key: "init",
20998    value: function init() {
20999      this.isCpfValidPix = this.handlePassengerCpfPix();
21000      this.isCpfValidTransfer = this.handlePassengerCpfPix();
21001      this.updateMessage();
21002    }
21003  }, {
21004    key: "handlePassengerCpfPix",
21005    value: function handlePassengerCpfPix() {
21006      if (!this.passenger) {
21007        return;
21008      }
21009      var _cpf = this.passenger._cpf;
21010
21011
21012      if (_cpf === null || _cpf === undefined) {
21013        return false;
21014      }
21015
21016      return Utils.validateCPF(_cpf);
21017    }
21018  }, {
21019    key: "showPixMessageCpfInvalid",
21020    value: function showPixMessageCpfInvalid() {
21021      return this.isCpfValidPix;
21022    }
21023  }, {
21024    key: "showTransferMessageCpfInvalid",
21025    value: function showTransferMessageCpfInvalid() {
21026      return this.isCpfValidTransfer;
21027    }
21028  }, {
21029    key: "updateMessage",
21030    value: function updateMessage() {
21031      var messageInput = this.qttShowTrips = $('[data-js="message-cpf-invalid-transfer"]').val();
21032      var messageParagraph = document.querySelector(".message-cpf-invalid--title p");
21033      messageParagraph.textContent = messageInput;
21034    }
21035  }]);
21036
21037  return MessageCpfController;
21038}();
21039'use strict';
21040
21041var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
21042
21043var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
21044
21045function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
21046
21047var ModalUpselController = function () {
21048  function ModalUpselController($, cartComponent) {
21049    _classCallCheck(this, ModalUpselController);
21050
21051    this.modalUpselLabel = $('[data-js="modal-upsel-offer-label"]');
21052    this.modalUpselClassType = $('[data-js="modal-upsel-classtypeLabel"]');
21053    this.modalUpselPrice = $('[data-js="modal-upsel-priceLabel"]:visible');
21054    this.modalUpselDecimal = $('[data-js="modal-upsel-decimalLabel"]:visible');
21055    this.modalUpsel = $('[data-js="modal-upsel"]');
21056    this.btnBusPreview = $('[data-js="bus-preview"]');
21057    this.btnCompany = $('[data-js="details-modal-target"]');
21058    this.hasOverlay = $('[data-js="modal-upsel-overlay"]').val() == 'true';
21059    this.setTimeOpenBackModal = $('[data-js="has-modal-upsel"]').attr('setTimeBack');
21060    this.modalUpselOffer = SessionStorage.get('offerModalUpsel');
21061    this.cart = SessionStorage.get('cart');
21062    this.formData = SessionStorage.get('formData');
21063    this.currentResultDep = SessionStorage.get('currentResultDep');
21064    this.currentResultRet = SessionStorage.get('currentResultRet');
21065    this.isSeatReservationPage = $('#jca-identifier-page').val() == 'jca-seat-reservation-page';
21066    this.cartComponent = cartComponent;
21067    this.isModalUpselReturnClose = false;
21068    this.tripStopRef = null;
21069    this.init();
21070  }
21071
21072  _createClass(ModalUpselController, [{
21073    key: 'init',
21074    value: function init() {
21075      var _this = this;
21076
21077      InternalAPIService.loadInternalAPI(function (errInternalApi, internalApiReturn) {
21078        _this.onLoadingInternalAPIDone(errInternalApi, internalApiReturn, null);
21079      });
21080      this.tripStopRef = new TripStop($);
21081    }
21082  }, {
21083    key: 'onLoadingInternalAPIDone',
21084    value: function onLoadingInternalAPIDone(errInternalApi, internalApiReturn, next) {
21085      if (errInternalApi) console.log(errInternalApi); else {
21086        if (this.formData) this.loadModalUpsel();
21087
21088        this.handleModalUpselEvents();
21089
21090        if (next) next();
21091      }
21092    }
21093  }, {
21094    key: 'loadModalUpsel',
21095    value: function loadModalUpsel() {
21096      var wayTrip = this.modalUpsel.attr('way');
21097
21098      var _ref = this.modalUpselOffer != null ? this.modalUpselOffer : { betterOfferDepart: null, priceCurrentDepartOffer: null, betterOfferReturn: null, priceCurrentReturnOffer: null },
21099        betterOfferDepart = _ref.betterOfferDepart,
21100        priceCurrentDepartOffer = _ref.priceCurrentDepartOffer,
21101        betterOfferReturn = _ref.betterOfferReturn,
21102        priceCurrentReturnOffer = _ref.priceCurrentReturnOffer;
21103
21104      var totalPassengers = this.formData.passengers[0].quantity + this.formData.passengers[1].quantity;
21105
21106      if (betterOfferDepart != null && betterOfferDepart.length > 0 && wayTrip == 'departure') {
21107        var price = betterOfferDepart[0].price;
21108
21109
21110        if (betterOfferDepart[0].freeSeats < totalPassengers) return false;
21111
21112        var priceDifference = '' + (price - priceCurrentDepartOffer).toFixed(2);
21113
21114        var _priceDifference$spli = priceDifference.split('.'),
21115          _priceDifference$spli2 = _slicedToArray(_priceDifference$spli, 2),
21116          integer = _priceDifference$spli2[0],
21117          decimal = _priceDifference$spli2[1];
21118
21119        $('[data-js="modal-upsel-priceLabel"]').text(integer);
21120        $('[data-js="modal-upsel-decimalLabel"]').text(',' + decimal);
21121        this.modalUpsel.attr('way', 'departure');
21122        this.modalUpselLabel.empty();
21123        var modalUpselDepLabel_AEM = $('[data-js="modal-upset-text-header-departure"]').val();
21124        this.modalUpselLabel.append(modalUpselDepLabel_AEM);
21125        this.modalUpselClassType.text(betterOfferDepart[0].class);
21126        this.showModalUpsel();
21127
21128        return;
21129      }
21130
21131      if (betterOfferReturn && (wayTrip == 'return' || !betterOfferDepart)) {
21132        var _price = betterOfferReturn[0].price;
21133
21134
21135        if (betterOfferReturn[0].freeSeats < totalPassengers) return false;
21136
21137        var _priceDifference = '' + (_price - priceCurrentReturnOffer).toFixed(2);
21138
21139        var _priceDifference$spli3 = _priceDifference.split('.'),
21140          _priceDifference$spli4 = _slicedToArray(_priceDifference$spli3, 2),
21141          _integer = _priceDifference$spli4[0],
21142          _decimal = _priceDifference$spli4[1];
21143
21144        $('[data-js="modal-upsel-priceLabel"]').text(_integer);
21145        $('[data-js="modal-upsel-decimalLabel"]').text(',' + _decimal);
21146        this.modalUpsel.attr('way', 'return');
21147        var modalUpselReturnLabel_AEM = $('[data-js="modal-upset-text-header-return"]').val();
21148        this.modalUpselLabel.empty();
21149        this.modalUpselLabel.append(modalUpselReturnLabel_AEM);
21150        this.modalUpselClassType.text(betterOfferReturn[0].class);
21151
21152        if (this.isModalUpselReturnClose == false) this.showModalUpsel();
21153
21154        return;
21155      }
21156    }
21157  }, {
21158    key: 'showOverlay',
21159    value: function showOverlay() {
21160      this.modalUpsel.css({ 'z-index': 25, 'position': 'relative' });
21161      OverlayService.show();
21162    }
21163  }, {
21164    key: 'hideOverlay',
21165    value: function hideOverlay() {
21166      OverlayService.hide();
21167    }
21168  }, {
21169    key: 'handleModalUpselEvents',
21170    value: function handleModalUpselEvents() {
21171      var _this2 = this;
21172
21173      $('[data-js="close-modal-upsel"]').on('click', function () {
21174        _this2.handleNoAcceptBetterOffer();
21175        _this2.hideModalUpsel();
21176        _this2.hideOverlay();
21177
21178        LoaderService.show();
21179        setTimeout(function () {
21180          LoaderService.hide();
21181
21182          _this2.loadModalUpsel();
21183        }, +_this2.setTimeOpenBackModal);
21184      });
21185
21186      $('[data-js="buy-ticket"]').on('click', function () {
21187        _this2.acceptBetterOffer();
21188      });
21189
21190      this.btnBusPreview.on('click', function (event) {
21191        var isReturn = $(event.target).closest(_this2.modalUpsel).attr("way") == "return";
21192        var betterOffer = isReturn ? _this2.modalUpselOffer.betterOfferReturn[0] : _this2.modalUpselOffer.betterOfferDepart[0];
21193
21194        var _getOfferAndCompany = _this2.getOfferAndCompany(betterOffer),
21195          _getOfferAndCompany2 = _slicedToArray(_getOfferAndCompany, 2),
21196          company = _getOfferAndCompany2[0],
21197          offer = _getOfferAndCompany2[1];
21198
21199        var $busPreviewUpsel = $('[data-js="map-bus-modal-upsel"]');
21200
21201        $('body, html').css("overflow-y", 'hidden');
21202        new BusPreview($, event, offer, $busPreviewUpsel);
21203      });
21204
21205      this.btnCompany.on('click', function (e) {
21206        var isReturn = $(event.target).closest(_this2.modalUpsel).attr("way") == "return";
21207        var betterOffer = isReturn ? _this2.modalUpselOffer.betterOfferReturn[0] : _this2.modalUpselOffer.betterOfferDepart[0];
21208
21209        var _getOfferAndCompany3 = _this2.getOfferAndCompany(betterOffer),
21210          _getOfferAndCompany4 = _slicedToArray(_getOfferAndCompany3, 2),
21211          company = _getOfferAndCompany4[0],
21212          offer = _getOfferAndCompany4[1];
21213
21214        _this2.expandDetailsDesktop(e, offer);
21215      });
21216    }
21217  }, {
21218    key: 'expandDetailsDesktop',
21219    value: function expandDetailsDesktop(e, offer) {
21220      e.preventDefault();
21221      var $classTypeDetails = $('[data-js="classtypeDetails"]');
21222
21223      $classTypeDetails.empty();
21224
21225      LoaderService.show();
21226      for (var index = 0; index < offer.classtype.details.length; index++) {
21227        var detail = offer.classtype.details[index];
21228        this.appendClassTypeDetail(detail, $classTypeDetails);
21229      }
21230
21231      setTimeout(function () {
21232        return LoaderService.hide();
21233      }, 500);
21234    }
21235  }, {
21236    key: 'appendClassTypeDetail',
21237    value: function appendClassTypeDetail(detail, classTypeDetailsComponent) {
21238      if (!detail.classDetailImage) return;
21239
21240      var $li = $('<li class="d-flex justify-content-start align-items-center class-detail
21240s-item">\n\t\t\t<img id="img-class-detail" src="' + detail.classDetailImage + '" alt="' + detail.altTextDetail + '" title="' + detail.classDetailName + '" />\n\t\t\t<p>' + (detail.altTextDetail ? detail.altTextDetail : '') + '</p>\n\t\t\t</li>\n\t\t');
21241
21242      classTypeDetailsComponent.append($li);
21243    }
21244  }, {
21245    key: 'handleNoAcceptBetterOffer',
21246    value: function handleNoAcceptBetterOffer() {
21247      var wayTrip = this.modalUpsel.attr('way');
21248
21249      if (wayTrip == 'departure') {
21250        this.modalUpsel.attr('way', 'return');
21251      }
21252
21253      if (wayTrip == 'return') {
21254        this.modalUpsel.attr('way', '');
21255        this.isModalUpselReturnClose = true;
21256      }
21257    }
21258  }, {
21259    key: 'getOfferAndCompany',
21260    value: function getOfferAndCompany(betterOffer) {
21261      var company = this.updateListResultView(betterOffer);
21262      var offer = company._listOffer[0];
21263
21264      return [company, offer];
21265    }
21266  }, {
21267    key: 'removeDepartureBetterOffer',
21268    value: function removeDepartureBetterOffer() {
21269      this.modalUpselOffer.betterOfferDepart = null;
21270      this.modalUpselOffer.priceCurrentDepartOffer = null;
21271      SessionStorage.set('offerModalUpsel', this.modalUpselOffer);
21272    }
21273  }, {
21274    key: 'removeReturnBetterOffer',
21275    value: function removeReturnBetterOffer() {
21276      this.modalUpselOffer.betterOfferReturn = null;
21277      this.modalUpselOffer.priceCurrentReturnOffer = null;
21278      SessionStorage.set('offerModalUpsel', this.modalUpselOffer);
21279    }
21280  }, {
21281    key: 'acceptBetterOffer',
21282    value: function acceptBetterOffer() {
21283      var wayTrip = this.modalUpsel.attr('way');
21284      var passengerList = this.cart._listPassengers;
21285
21286      if (wayTrip == 'departure') {
21287        var betterOffer = this.modalUpselOffer.betterOfferDepart[0];
21288
21289        var _getOfferAndCompany5 = this.getOfferAndCompany(betterOffer),
21290          _getOfferAndCompany6 = _slicedToArray(_getOfferAndCompany5, 2),
21291          company = _getOfferAndCompany6[0],
21292          offer = _getOfferAndCompany6[1];
21293
21294        this.cartComponent.cartService.addDepartOffer(offer);
21295        this.cartComponent.cartService.cart._listPassengers = passengerList;
21296        SessionStorage.set('cart', this.cartComponent.cartService.cart);
21297        this.cartComponent.initSections(this.formData);
21298        this.cartComponent.initSummaryComponents();
21299        this.cartComponent.updateCartView();
21300        this.updateMinDate(offer.arrivingDate);
21301        this.removeDepartureBetterOffer();
21302
21303        if (this.isSeatReservationPage) location.reload();
21304
21305        $('[data-js="close-modal-upsel"]').trigger('click');
21306      }
21307
21308      if (wayTrip == 'return') {
21309        var _betterOffer = this.modalUpselOffer.betterOfferReturn[0];
21310
21311        var _getOfferAndCompany7 = this.getOfferAndCompany(_betterOffer),
21312          _getOfferAndCompany8 = _slicedToArray(_getOfferAndCompany7, 2),
21313          _company = _getOfferAndCompany8[0],
21314          _offer = _getOfferAndCompany8[1];
21315
21316        this.cartComponent.cartService.cart._listPassengers = passengerList;
21317        this.cartComponent.cartService.addReturnOffer(_offer);
21318        SessionStorage.set('cart', this.cartComponent.cartService.cart);
21319        this.cartComponent.updateCartView();
21320        this.removeReturnBetterOffer();
21321
21322        if (this.isSeatReservationPage) location.reload();
21323
21324        $('[data-js="close-modal-upsel"]').trigger('click');
21325      }
21326    }
21327  }, {
21328    key: 'updateMinDate',
21329    value: function updateMinDate(arrivingDate) {
21330      this.formData.return.minDate = arrivingDate;
21331      SessionStorage.set('formData', this.formData);
21332    }
21333  }, {
21334    key: 'setBusPreviewEvent',
21335    value: function setBusPreviewEvent(offer) {
21336      $('[data-js="bus-preview"]').click(function (e) {
21337        $('body, html').css("overflow-y", 'hidden');
21338        new BusPreview($, e, offer);
21339      });
21340    }
21341  }, {
21342    key: 'createConnection',
21343    value: function createConnection(data) {
21344      var connection = new Connection();
21345      connection.service = data.connection.connectionServiceId;
21346      connection.location = new Location(data.connection.connectionPlace, data.connection.localidadeConexao);
21347      connection.classtype = new Classtype(data.connection.secondLegClass);
21348      connection.freeSeats = data.connection.secondLegFreeSeats;
21349      connection.company = data.connection.secondLegCompany;
21350      connection.price = data.connection.secondLegPrice;
21351      connection.arrivingDate = DateFormatter.reverseDate(data.connection.secondLegArrivalDate) + ' ' + data.connection.secondLegDepartureHour;
21352      connection.departureDate = DateFormatter.reverseDate(data.connection.secondLegDepartureDate) + ' ' + data.connection.secondLegDepartureHour;
21353      connection.token = data.tokens[1];
21354      return connection;
21355    }
21356  }, {
21357    key: 'createOffer',
21358    value: function createOffer(data, company) {
21359      var offer = new Offer();
21360      offer.service = data.serviceId;
21361      offer.group = data.group;
21362      offer.token = data.tokens[0];
21363      offer.freeArmchairs = data.freeSeats;
21364      offer.totalArmchairs = data.totalSeats;
21365      offer.price = data.price;
21366      offer.priceWithDiscountPix = data.priceWithDiscountPix;
21367      offer.percentagePix = data.percentagePix;
21368      offer.fare = 0;
21369      offer.boardingFee = 0;
21370      offer.toll = 0;
21371      offer.insurance = 0;
21372      offer.others = 0;
21373      offer.classtype = new Classtype(data.class);
21374      offer.sells = data.sell;
21375      offer.company = company;
21376      offer.routeId = data.routeId;
21377
21378      if (data.connection) offer.connection = this.createConnection(data);
21379
21380      return offer;
21381    }
21382  }, {
21383    key: 'createCompany',
21384    value: function createCompany(origin, destination, data) {
21385      var company = new Company();
21386      company.companyName = data.company;
21387      company.departureDate = data.departureDate;
21388      company.arrivingDate = data.arrivalDate;
21389
21390      if (data.conexao) {
21391        data.chegada = DateFormatter.reverseDate(data.conexao.segundoTrechoDataChegada) + ' ' + DateFormatter.formatTimeString(data.conexao.segundoTrechoHoraChegada);
21392      }
21393
21394      company.origin = new Location(origin.id, origin.city);
21395      company.destination = new Location(destination.id, destination.city);
21396      return company;
21397    }
21398  }, {
21399    key: 'updateListResultView',
21400    value: function updateListResultView(betterOffer) {
21401      var isReturn = this.modalUpsel.attr("way") == "return";
21402      var listRaces = isReturn ? this.currentResultRet : this.currentResultDep;
21403      var serviceId = betterOffer.serviceId;
21404      var trip = this.filterJSON(listRaces, serviceId);
21405      var company = InternalAPIService.convertClasstype(trip[0]);
21406
21407      return company;
21408    }
21409  }, {
21410    key: 'showTripStop',
21411    value: function showTripStop() {
21412      this.tripStopRef.show();
21413    }
21414  }, {
21415    key: 'filterJSON',
21416    value: function filterJSON(result, serviceId) {
21417      var filtered = [];
21418      var servicesList = result ? result.servicesList : null;
21419      this.formData = SessionStorage.get('formData');
21420
21421      if (!servicesList) return filtered;
21422
21423      var tripOffer = servicesList.filter(function (el) {
21424        return el.serviceId == serviceId;
21425      });
21426      var origin = result.origin,
21427        destination = result.destination;
21428
21429      var company = this.createCompany(origin, destination, tripOffer[0]);
21430      var index = this.hasCompany(filtered, company);
21431
21432      if (index === -1) {
21433        filtered.push(company);
21434        index = filtered.length - 1;
21435      }
21436
21437      var offer = this.createOffer(tripOffer[0], filtered[index]);
21438      if (offer.connection && offer.connection.location) this.showTripStop();
21439
21440      filtered[index].listOffer.push(offer);
21441
21442      return filtered;
21443    }
21444  }, {
21445    key: 'hasCompany',
21446    value: function hasCompany(array, company) {
21447      for (var i = 0; i < array.length; i++) {
21448        if (array[i].companyName === company.companyName && array[i].departureDate === company.departureDate && array[i].arrivingDate === company.arrivingDate) {
21449          return i;
21450        }
21451      } return -1;
21452    }
21453  }, {
21454    key: 'hideModalUpsel',
21455    value: function hideModalUpsel() {
21456      this.modalUpsel.hide();
21457    }
21458  }, {
21459    key: 'showModalUpsel',
21460    value: function showModalUpsel() {
21461      this.modalUpsel.show();
21462    }
21463  }]);
21464
21465  return ModalUpselController;
21466}();
21467'use strict';
21468
21469var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
21470
21471var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
21472
21473function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
21474
21475var MyAccountController = function () {
21476  function MyAccountController($) {
21477    _classCallCheck(this, MyAccountController);
21478
21479    this.fullHistory = [];
21480    this.user = SessionStorage.get('passenger');
21481    this.tabTrip = $('.tab-trip');
21482    this.nextTripsTab = $('[data-js="next-trips"]');
21483    this.previousTripsTab = $('[data-js="previous-trips"]');
21484    this.previousTripMsg = $('[data-js="previous-msg"]');
21485    this.inputResCode = $('[data-js="input-res-code"]').filter(':visible');
21486    this.errorMsg = $('[data-js="error-msg"]').filter(':visible');
21487    this.summaryOrigin = $('[data-js="summary-label-origin"]');
21488    this.summaryDestination = $('[data-js=summary-label-destination]');
21489    this.highlightDays = $('[data-js="highlight-days"]');
21490    this.highlightUser = $('[data-js="highlight-user"]');
21491    this.tripList = $('[data-js="trip-list"]');
21492    this.buttonLogout = $('[data-js="button-return"]');
21493    this.priceLabel = $('[data-js="price-total"]');
21494    this.qttShowTrips = $('[data-js="qtt-show-trips"]').val();
21495    this.tripSteppers = $('[data-js="trip-list-steppers"]');
21496    this.arrayTickets = [];
21497    this.convenienceFee = $('[data-js="convenience-fee"]').attr('value');
21498    this.INTERVAL = parseInt($("[data-js='timer-cancel']").val()) * 60 * 60 * 1000; //parameter aem in milliseconds
21499    this.classCompany = null;
21500    this.init();
21501  }
21502
21503  _createClass(MyAccountController, [{
21504    key: 'init',
21505    value: function init() {
21506      var _this = this;
21507
21508      this.getServerTime(function () {
21509        _this.getTripDetailsTemplate(function () {
21510          _this.getClass();
21511          _this.buttonLogout.text('Voltar');
21512          _this.checkUser();
21513          _this.handleTabs();
21514          _this.getUserHistory();
21515        });
21516      });
21517      SessionStorage.set('isNextTrip', true);
21518    }
21519  }, {
21520    key: 'getServerTime',
21521    value: function getServerTime(callback) {
21522      var _this2 = this;
21523
21524      if ($('#wcmmodeedit').val() == 'false') LoaderService.show();
21525      HttpService.getAEM('time.json?cache=1').then(function (data) {
21526        var time = data.result.time;
21527        var offset = data.result.offset;
21528
21529        time = time.replace("Z", "");
21530        var timezoneOffset = new Date(time).getTimezoneOffset();
21531
21532        // 180 is the difference between brasilia timezone and utc-0 in minutes
21533        time = timezoneOffset > 180 ? time : time + offset;
21534        _this2.timeExact = new Date(time).getTime();
21535        LoaderService.hide();
21536        callback(_this2.timeExact);
21537      }).catch(function () {
21538        console.error(err.message);
21539        _this2.timeExact = DateFormatter.getValidDateFormat();
21540        LoaderService.hide();
21541        callback(_this2.timeExact);
21542      });
21543    }
21544  }, {
21545    key: 'getTripDetailsTemplate',
21546    value: function getTripDetailsTemplate(callback) {
21547      var _this3 = this;
21548
21549      /*$.get('/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/assets/trip-detail-my-account-v2.html', function (data) {
21550        _this3.tripDetailsTemplate = data;
21551        if (callback) callback();
21552      });*/
21553
21554      var template = $('[data-js="trip-list"]').html();
21555      _this3.tripDetailsTemplate = template;
21556      if (callback) callback();
21557    }
21558  }, {
21559    key: 'checkUser',
21560    value: function checkUser() {
21561      if ((!this.user) && (!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false')) {
21562        localStorage.setItem("referrer", $(location).attr('href'));
21563        $(location).attr('href', $('#loginPage').val());
21564      }
21565    }
21566  }, {
21567    key: 'loadDays',
21568    value: function loadDays(daysToNextTrip) {
21569      this.previousTripMsg.hide();
21570      this.highlightDays.fadeIn();
21571      if (daysToNextTrip > 0) {
21572        var highlightDaysText = this.highlightDays.html().replace('#days', ' ' + daysToNextTrip + ' ');
21573        this.highlightDays.html(highlightDaysText);
21574      } else this.highlightDays.hide();
21575    }
21576  }, {
21577    key: 'hideDays',
21578    value: function hideDays() {
21579      this.highlightDays.hide();
21580      this.previousTripMsg.fadeIn();
21581    }
21582  }, {
21583    key: 'handleTabs',
21584    value: function handleTabs() {
21585      var _this4 = this;
21586
21587      this.tabTrip.click(function (event) {
21588        LoaderService.show();
21589
21590        _this4.refreshTab();
21591        var tab_active = $(event.currentTarget);
21592        var current_active = $('.tab-trip.active');
21593        var isNextTripTab = tab_active.data('js') === 'tab-1';
21594
21595        SessionStorage.set('isNextTrip', isNextTripTab);
21596
21597        if (tab_active.data('js') === 'tab-1') {
21598          _this4.nextTripsTab.fadeIn();
21599          _this4.previousTripsTab.hide();
21600        } else {
21601          _this4.nextTripsTab.hide();
21602          _this4.previousTripsTab.fadeIn();
21603        }
21604
21605        current_active.removeClass('active');
21606        tab_active.addClass("active");
21607
21608        if (current_active.data('js') !== tab_active.data('js')) {
21609          var currentPage = 1;
21610          _this4.getUserHistory(currentPage);
21611          _this4.displayDetails(_this4.fullHistory, currentPage, _this4.totalPages);
21612        }
21613
21614        setTimeout(function () {
21615          return LoaderService.hide();
21616        }, 200);
21617      });
21618    }
21619  }, {
21620    key: 'createDeeplinkRefundBuy',
21621    value: function createDeeplinkRefundBuy() {
21622      var preDefinedType = $('[data-js="change-trip-params"]').data('type');
21623      var preDefinedReason = $('[data-js="change-trip-params"]').data('reason');
21624
21625      for (var _len = arguments.length, params = Array(_len), _key = 0; _key < _len; _key++) {
21626        params[_key] = arguments[_key];
21627      }
21628
21629      var index = params[0],
21630        _ = params[1],
21631        origin = params[2],
21632        destination = params[3],
21633        hourDepart = params[4],
21634        dateDepart = params[5],
21635        salesTime = params[6],
21636        mainFinder = params[7],
21637        total = params[8];
21638
21639
21640      var deepLinkRefund = {
21641        name: this.user._name.trim(),
21642        email_user: this.user._email.trim(),
21643        area_code: this.user._areaCode.trim(),
21644        phone: this.user._phone.trim(),
21645        originTrip: origin,
21646        destinationTrip: destination,
21647        docType: 'CPF',
21648        hasBought: true,
21649        type: preDefinedType,
21650        reason: preDefinedReason,
21651        hourDepart: hourDepart,
21652        dateDepart: dateDepart,
21653        salesTime: salesTime,
21654        cpf: this.user._documentNumber,
21655        finder: mainFinder,
21656        total: total.toFixed(2)
21657      };
21658
21659      var $elem = $('[data-js="link-buy-refund-' + index + '"]');
21660      if ($($elem).find('.cmp-text').length > 0 && $($elem).find('.cmp-text').find('p').length > 0) {
21661        var link = $elem.find('p').find('a');
21662        if (link.length > 0) {
21663          var temp = $(link).attr('href');
21664          $(link).attr('href', temp + '?' + $.param(deepLinkRefund) + '');
21665          $('[data-js="link-buy-refund-' + index + '"]').attr('href', temp + '?' + $.param(deepLinkRefund) + '');
21666        }
21667      }
21668    }
21669  }, {
21670    key: 'showMsgEmailTrip',
21671    value: function showMsgEmailTrip(_ref, isError) {
21672      var msg1 = _ref.msg1,
21673        msg2 = _ref.msg2;
21674
21675      AlertConfirmation.show(msg1, msg2, isError, false);
21676
21677      $('[data-js="resend-email-ticket"]').addClass('active');
21678    }
21679  }, {
21680    key: 'updateMessageRefund',
21681    value: function updateMessageRefund(messageRefund) {
21682      var hiddenInput = $('input[data-js="cancel-trip-unavailable"]');
21683
21684      if (hiddenInput.val()) {
21685        messageRefund.text(hiddenInput.val());
21686      }
21687
21688      hiddenInput.on('input', function () {
21689        if (hiddenInput.val()) {
21690          messageRefundmessageRefund.text(hiddenInput.val());
21691        }
21692      });
21693    }
21694  }, {
21695    key: 'handleCommands',
21696    value: function handleCommands() {
21697      for (var _len2 = arguments.length, params = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
21698        params[_key2] = arguments[_key2];
21699      }
21700      var showRemarkTripButton = $('[data-js="show-remark-trip-button"]').val();
21701      var index = params[0],
21702          arrTrip = params[1];
21703
21704      var _fetchTimeleft = this.fetchTimeleft(arrTrip),
21705          timeleftGoing = _fetchTimeleft.timeleftGoing,
21706          timeleftReturn = _fetchTimeleft.timeleftReturn;
21707
21708      var cancelTripBtn = $('[data-js="cancel-trip-' + index + '"]');
21709      var tripStatus = $('[data-js="going-summary-status-' + index + '"]');
21710      var linkRefund = $('[data-js="link-buy-refund-' + index + '"]');
21711      var linkResend = $('[data-js="resend-receipt-' + index + '"]');
21712      var messageRefundElement = $('[data-js="message-refund-' + index + '"]');
21713      var messageRefundContainer = $('[data-js="message-refund-container-' + index + '"]');
21714      var iconRefundElement = $('[data-js="icon-refund-' + index + '"]');
21715      var currentDate = new Date();
21716      var departureDate = new Date(arrTrip[0][0].departureDate);
21717
21718      this.arrayTickets[index] = arrTrip;
21719
21720      for (var i = 0; i < arrTrip.length; i++) {
21721        if (arrTrip[i]) {
21722          var hasSaleApproved = arrTrip[i].some(function (sale) {
21723            return sale.status === 'SALE_APPROVED' || sale.status === 'REMARCÁVEL' || sale.status === 'SALE_RELOCATED' && sale.bpeReference.tipoDesconto.toLowerCase() !== 'profissional da empresa';
21724          });
21725
21726          if (hasSaleApproved && showRemarkTripButton == 'true') {
21727            linkRefund.parent().show();
21728            this.handleRepricingTrip(index, arrTrip);
21729            break;
21730          }
21731        }
21732      }
21733
21734      var preTrip = false;
21735      var postTrip = false;
21736
21737      for (var _i = 0; _i < arrTrip.length; _i++) {
21738        if (arrTrip[_i]) {
21739          preTrip = arrTrip[_i].some(function (sale) {
21740            return sale.saleExchange && sale.saleExchange.preTrip === true;
21741          });
21742          postTrip = arrTrip[_i].some(function (sale) {
21743            return sale.saleExchange && sale.saleExchange.preTrip === false;
21744          });
21745          this.updateMessageRefund(messageRefundElement);
21746
21747          if (preTrip) {
21748            messageRefundContainer.hide();
21749            messageRefundElement.hide();
21750            iconRefundElement.hide();
21751            cancelTripBtn.parent().show();
21752            break;
21753          } else if (postTrip) {
21754            messageRefundContainer.show();
21755            messageRefundElement.show();
21756            iconRefundElement.show();
21757            cancelTripBtn.parent().hide();
21758            break;
21759          } else {
21760            messageRefundContainer.hide();
21761            messageRefundElement.hide();
21762            iconRefundElement.hide();
21763          }
21764        }
21765      }
21766
21767      if (tripStatus.hasClass('canceled')) {
21768        cancelTripBtn.parent().remove();
21769      }
21770
21771      if (tripStatus.hasClass('remark')) {
21772        cancelTripBtn.parent().remove();
21773      }
21774
21775      if (tripStatus.hasClass('remarkable')) {
21776        linkResend.parent().show();
21777      }
21778
21779      if (currentDate > departureDate) {
21780        cancelTripBtn.parent().remove();
21781      }
21782
21783      var hasExchangeFalse = arrTrip.some(function (trip) {
21784        return trip && trip.some(function (sale) {
21785          return sale.exchange === false;
21786        });
21787      });
21788
21789      var hasExchangeTrue = arrTrip.some(function (trip) {
21790        return trip && trip.some(function (sale) {
21791          return sale.exchange === true && sale.status === 'SALE_APPROVED';
21792        });
21793      });
21794
21795      if (hasExchangeFalse) {
21796        linkRefund.parent().remove();
21797      }
21798
21799      if (hasExchangeTrue) {
21800        linkRefund.parent().show();
21801      }
21802
21803      this.handleCancelTrip(index, cancelTripBtn, arrTrip, timeleftGoing, timeleftReturn);
21804      this.handleResendTicket(index, arrTrip);
21805      this.handleLinkDetails(index);
21806    }
21807  }, {
21808    key: 'getClass',
21809    value: function getClass() {
21810      var _this5 = this;
21811      var siteName = Utils.getSiteNameForClasses();
21812      var contentClassesUrl = InternalAPIService.aemServiceHost + '/content/jca/' + siteName + '/jcr:content.classes.json';
21813
21814      $.ajax({
21815        url: contentClassesUrl,
21816        contentType: 'json',
21817        type: 'GET',
21818        success: function success(data) {
21819          _this5.classCompany = data.result;
21820          // callback()
21821        },
21822        error: function error(textStatus, errorThrown) {
21823          console.log(textStatus, errorThrown);
21824          callback(errorThrown, null);
21825        }
21826      });
21827    }
21828  }, {
21829    key: 'handleRepricingTrip',
21830    value: function handleRepricingTrip(index, arrTrip) {
21831      var _this7 = this;
21832
21833      $('[data-js="link-buy-refund-' + index + '"]').click(function (e) {
21834        var isInvalidClass = _this7.checkRecricingTriValidClass(arrTrip);
21835
21836        if (!isInvalidClass) {
21837          _this7.handleToRepricingTrip(arrTrip);
21838        } else {
21839          AlertConfirmation.showAEM('data-js="alert-reschedule-block"');
21840          $('[data-js="close-resend-email-ticket"]').off('click').on('click', function () {
21841            if (Utils.isMobile()) {
21842              $('.container-confirmation').removeClass('active');
21843            }
21844          });
21845        }
21846      });
21847    }
21848  }, {
21849    key: 'handleToRepricingTrip',
21850    value: function handleToRepricingTrip(arrTrip) {
21851      var _this8 = this;
21852
21853      var promises = [];
21854
21855      for (var idx = 0; idx < arrTrip.length; idx++) {
21856        if (!arrTrip[idx]) continue;
21857
21858        // Some segments (connections) come nested: [[t1, t2], [t3, t4]]
21859        // If so, flatten them into a single list of tickets
21860        var trips = Array.isArray(arrTrip[idx][0]) ? arrTrip[idx].flat() : arrTrip[idx];
21861
21862        // Create a promise for each ticket to validate repricing eligibility
21863        for (var i = 0; i < trips.length; i++) {
21864          promises.push(this.verifyValidTicketToRepricing(trips[i]));
21865        }
21866      }
21867
21868      var setEligibilitySession = function setEligibilitySession(promiseValues) {
21869        var arrRemarking = [];
21870        var listRemarking = [];
21871        var count = 0;
21872        var countGoing = 0;
21873        var countReturn = 0;
21874
21875        for (var _idx = 0; _idx < arrTrip.length; _idx++) {
21876          if (arrTrip[_idx]) {
21877            arrRemarking[_idx] = [];
21878            for (var _i = 0; _i < arrTrip[_idx].length; _i++) {
21879              if (promiseValues[count].success === true) {
21880                arrRemarking[_idx][_i] = promiseValues[count];
21881              }
21882
21883              if (arrTrip[_idx].length == _i + 1) {
21884
21885                if (arrTrip[_idx][0].going) countGoing++;
21886                if (!arrTrip[_idx][0].going) {
21887                  countGoing = 0;
21888                  countReturn++;
21889                }
21890
21891                listRemarking.push(_this8.handleTrip(arrTrip[_idx], arrRemarking[_idx], countGoing, countReturn));
21892              }
21893
21894              count++;
21895            }
21896          } else {
21897            arrRemarking[_idx] = null;
21898          }
21899        }
21900
21901        SessionStorage.set('remarkingavaibility', listRemarking);
21902        return listRemarking;
21903      };
21904
21905      LoaderService.show();
21906      Promise.all(promises).then(function (promiseValues) {
21907        var allTripsUnavailable = promiseValues.every(function (el) {
21908          return el.success === false;
21909        });
21910        if (allTripsUnavailable) {
21911          LoaderService.hide();
21912          AlertConfirmation.showAEM('data-js="alert-protocol-sending-error"');
21913        } else {
21914          setEligibilitySession(promiseValues);
21915          LoaderService.hide();
21916
21917          var tripsToRepricing = arrTrip.map(function (subArray) {
21918            if (subArray === null || subArray === undefined) {
21919              return [];
21920            } else {
21921              var filteredSubArray = subArray.filter(function (element) {
21922                return element.status === 'SALE_APPROVED' || element.status === 'SALE_RELOCATED' || element.status === 'REMARCÁVEL';
21923              });
21924              return filteredSubArray;
21925            }
21926          });
21927
21928          //if nested array, flat it
21929          var normalize = function normalize(step) {
21930            if (!step) return null;
21931            return Array.isArray(step[0]) ? step.flat() : step;
21932          };
21933
21934          // This ensures all segments (main and connections) are consistently flattened
21935          arrTrip = arrTrip.map(normalize);
21936
21937          // Load the remarking availability structure stored in session.
21938          var remark = SessionStorage.get('remarkingavaibility') || [];
21939
21940          // Some blocks contain nested ticket lists; flatten those to avoid nested arrays
21941          remark = remark.map(function (block) {
21942            return block.map(function (item) {
21943              if (item && item[0] && item[0].tickets) {
21944                item[0].tickets = normalize(item[0].tickets);
21945              }
21946              return item;
21947            });
21948          });
21949
21950          SessionStorage.set('remarkingavaibility', remark);
21951
21952          SessionStorage.set('tripToRepricing', tripsToRepricing);
21953          $(location).attr('href', $('#rescheduleTripPath').val());
21954        }
21955      }).catch(function (err) {
21956        LoaderService.hide();
21957        AlertConfirmation.showAEM('data-js="alert-protocol-sending-error"');
21958        console.error(err);
21959      });
21960    }
21961  }, {
21962    key: 'handleTrip',
21963    value: function handleTrip(listTrip, arrRemarking, countGoing, countReturn) {
21964      return [{
21965        'tickets': listTrip,
21966        'going': countGoing == 1 ? true : false,
21967        'goingConnection': countGoing == 2 ? true : false,
21968        'tripReturn': countReturn == 1 ? true : false,
21969        'tripReturnConnection': countReturn == 2 ? true : false,
21970        'return': arrRemarking
21971      }];
21972    }
21973  }, {
21974    key: 'verifyValidTicketToRepricing',
21975    value: function verifyValidTicketToRepricing(arrTrip) {
21976      return new Promise(function (resolve, reject) {
21977        var originId = arrTrip.originId,
21978          destinationId = arrTrip.destinationId,
21979          departureDate = arrTrip.departureDate,
21980          service = arrTrip.service,
21981          seat = arrTrip.seat,
21982          systemNumber = arrTrip.systemNumber,
21983          id = arrTrip.id;
21984
21985
21986        var body = {
21987          "origin": originId,
21988          "destination": destinationId,
21989          "date": DateFormatter.extractDate(departureDate),
21990          "service": service,
21991          "seat": Utils.clearFirstCharacter(seat),
21992          "systemnumber": systemNumber,
21993          "SaleId": id
21994        };
21995
21996        var headers = {
21997          'Authorization': '' + SessionStorage.get('jca_token')
21998        };
21999
22000        HttpService.post('checkEligibility', body, headers).then(function (response) {
22001          SessionStorage.set('reactivateCheckin', response);
22002          resolve(response);
22003        }).catch(function (err) {
22004          return reject(err);
22005        });
22006      });
22007    }
22008  }, {
22009    key: 'checkRecricingTriValidClass',
22010    value: function checkRecricingTriValidClass(arrTrip) {
22011      var ticketsClass = this.getTikectsClass(arrTrip);
22012
22013      return this.classCompany.find(function (classCompany) {
22014        return classCompany.classes.find(function (el) {
22015          return ticketsClass.find(function (className) {
22016            return el.className === className && el.showClassInMytravels;
22017          });
22018        });
22019      });
22020    }
22021  }, {
22022    key: 'getTikectsClass',
22023    value: function getTikectsClass(arrTrip) {
22024      return arrTrip.reduce(function (acc, el) {
22025        if (el) {
22026          acc.push(el[0].class);
22027        }
22028
22029        return acc;
22030      }, []);
22031    }
22032  }, {
22033    key: 'handleCancelTrip',
22034    value: function handleCancelTrip(index, cancelTripBtn, arrTrip, timeleftGoing, timeleftReturn) {
22035      var _this8 = this;
22036
22037      cancelTripBtn.click(function (e) {
22038        if (_this8.isPaymentLivelo(arrTrip) && $('[data-js="cancel-pts-livelo"]').attr("value") == "false") {
22039          AlertConfirmation.showAEM('data-js="alert-livelo-no-cancel"');
22040        } else {
22041          if (timeleftGoing >= _this8.INTERVAL) {
22042            SessionStorage.set('tripToCancel', arrTrip);
22043            _this8.redirectBasedOnGroup();
22044          } else if (timeleftGoing < _this8.INTERVAL && timeleftReturn >= _this8.INTERVAL && timeleftReturn > 0) {
22045            arrTrip[0].forEach(function (el, i) {
22046              return el.status = 'SALE_NON_REFUNDABLE';
22047            });
22048            SessionStorage.set('tripToCancel', arrTrip);
22049            _this8.redirectBasedOnGroup();
22050          } else {
22051            $('[data-js="message-cancel-error-' + index + '"]').fadeIn().css('display', 'inline-block');
22052          }
22053        }
22054      });
22055    }
22056  }, {
22057    key: 'redirectBasedOnGroup',
22058    value: function redirectBasedOnGroup() {
22059      /*var groups = this.user._groups ? this.user._groups.split(',').map(function (group) {
22060        return group.trim();
22061      }) : [];
22062      if (groups.includes('wallet')) {*/
22063        $(location).attr('href', i18n('cancel_trip_wallet_page'));
22064      /*} else {
22065        $(location).attr('href', i18n('cancel_trip_page'));
22066      }*/
22067    }
22068  }, {
22069    key: 'isPaymentLivelo',
22070    value: function isPaymentLivelo(sales) {
22071      return sales[0][0].paymentForm === 'LIVELO' ? true : false;
22072    }
22073  }, {
22074    key: 'handleLinkDetails',
22075    value: function handleLinkDetails(index) {
22076      $('.link-details-ticket').on('click', function (e) {
22077        e.stopImmediatePropagation();
22078
22079        $('[data-js="trip-detail-outer-body-' + index + '"]').addClass('active');
22080      });
22081
22082      $('[data-js="close-details-tickets"]').on('click', function () {
22083        $('.trip-detail-body').removeClass('active');
22084      });
22085    }
22086  }, {
22087    key: 'handleResendTicket',
22088    value: function handleResendTicket(index, arrTrip) {
22089      var _this6 = this;
22090
22091      $('[data-js="resend-receipt-' + index + '"]').click(function () {
22092        var headers = {
22093          'Authorization': '' + SessionStorage.get('jca_token'),
22094          'channel': Utils.getChannelTitle(_this6.isPaymentWhatsapp, _this6.saleplatform)
22095        };
22096        var salesIds = [];
22097
22098        arrTrip.forEach(function (arr) {
22099          if (!arr) return;
22100
22101          arr.forEach(function (el) {
22102            if (!salesIds.includes(el.id)) {
22103              salesIds.push(el.id);
22104            }
22105          });
22106        });
22107
22108        var body = { SalesId: salesIds };
22109        LoaderService.show();
22110        HttpService.post('sendTicket', body, headers).then(function () {
22111          LoaderService.hide();
22112          //_this6.showMsgEmailTrip({ msg1: i18n('conf_message_title'), msg2: i18n('resend_ticket_confirmation') });
22113          AlertConfirmation.showAEM('data-js="alert-email-resubmit-confirmation"');
22114        }).catch(function (e) {
22115          LoaderService.hide();
22116          _this6.showMsgEmailTrip({ msg1: 'Houve uma falha na requisição. Tente novamente mais tarde.' }, true);
22117        });
22118      });
22119
22120      $('[data-js="close-resend-email-ticket"]').on('click', function () {
22121        $('[data-js="resend-email-ticket"], [data-js="message-confir"]').removeClass('active');
22122        $('[data-js="message-confir"]').parent().removeClass('active');
22123      });
22124    }
22125  }, {
22126    key: 'fetchTimeleft',
22127    value: function fetchTimeleft(arrTrip) {
22128      var timeNow = this.timeExact;
22129      var triptime1 = DateFormatter.getValidDateFormat(arrTrip[0][0].departureDate).getTime();
22130      var timeleftGoing = triptime1 - timeNow;
22131      var timeleftReturn = 0;
22132
22133      if (arrTrip[2]) {
22134        var triptime2 = DateFormatter.getValidDateFormat(arrTrip[2][0].departureDate).getTime();
22135        timeleftReturn = triptime2 - timeNow;
22136      }
22137
22138      return { timeleftGoing: timeleftGoing, timeleftReturn: timeleftReturn };
22139    }
22140  }, {
22141    key: 'refreshTab',
22142    value: function refreshTab() {
22143      $('[data-js="input-res-code"]').removeClass('invalid').val('');
22144      $('[data-js="error-msg"]').hide();
22145      $('[data-js="account-info"]').hide();
22146    }
22147  }, {
22148    key: 'getUserHistory',
22149    value: function getUserHistory() {
22150      var _this10 = this;
22151
22152      var page = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
22153
22154      var isNextTrip = SessionStorage.get('isNextTrip');
22155      if (this.user) {
22156        var headers = {
22157          'Authorization': '' + SessionStorage.get('jca_token'),
22158          'version': isNextTrip ? 3 : 2,
22159          channel: Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform)
22160        };
22161
22162        LoaderService.show();
22163        HttpService.get('getHistoric?page=' + page, headers).then(function (data) {
22164          LoaderService.hide();
22165
22166          if (data.success) {
22167            _this10.fullHistory = data.result.sales;
22168            var currentPage = data.result.page;
22169            var totalPages = data.result.totalPages;
22170
22171            _this10.displayDetails(_this10.fullHistory, currentPage, totalPages);
22172          } else {
22173            Alert.show('Houve uma falha na requisição. Tente novamente mais tarde.');
22174          }
22175        }).catch(function (e) {
22176          console.error(e);
22177          LoaderService.hide();
22178          Alert.show('Houve uma falha na requisição. Tente novamente mais tarde.');
22179        });
22180      }
22181    }
22182  }, {
22183    key: 'removeInvalidHistory',
22184    value: function removeInvalidHistory(fullHistory) {
22185      var sales = fullHistory.result.sales;
22186      return sales.filter(function (sale) {
22187        return sale.status.toUpperCase() !== 'INITIAL_CREATE';
22188      });
22189    }
22190  }, {
22191    key: 'showTrips',
22192    value: function showTrips(groupedHistory) {
22193      var isNextTripTab = this.nextTripsTab.is(':visible');
22194      var arrTripRender = groupedHistory.slice(0, 5);
22195
22196      this.generateCardsTrips(arrTripRender, isNextTripTab);
22197    }
22198  }, {
22199    key: 'displayDetails',
22200    value: function displayDetails(fullHistory, currentPage, totalPages) {
22201      var isNextTripTab = this.nextTripsTab.is(':visible');
22202      var filteredHistory = isNextTripTab ? this.getOnlyNextTrips(fullHistory) : this.getOnlyPreviousTrips(fullHistory);
22203      this.tripSteppers.empty();
22204
22205      $('[data-js="account-info"]').hide();
22206      $('[data-js="trip-list"]').show();
22207
22208      if (filteredHistory.length > 0) {
22209        var groupedHistory = this.groupArrayByField(filteredHistory, isNextTripTab, 'finder');
22210
22211        if (!currentPage || currentPage < 1) {
22212          currentPage = 1;
22213        }
22214
22215        this.showTrips(groupedHistory);
22216        this.renderSteppersSearch(totalPages, currentPage);
22217        this.handleSteppers(currentPage, totalPages);
22218        this.handleSteppersEvents(groupedHistory, currentPage, totalPages);
22219      } else {
22220        $('[data-js="account-info"]').show();
22221        $('[data-js="trip-list"]').hide();
22222      }
22223    }
22224  }, {
22225    key: 'handleSteppers',
22226    value: function handleSteppers(currentPage, totalPages) {
22227      var _this11 = this;
22228
22229      var qttSteppers = Utils.getWindowSize().width > 951 ? parseInt($('[data-js="qtt-show-trips"]').attr('qtt-stepper-desk')) : parseInt($('[data-js="qtt-show-trips"]').attr('qtt-stepper-mobile'));
22230      var maxVisiblePages = Math.min(qttSteppers, 7);
22231
22232      this.tripSteppers.empty();
22233
22234      var pagesToShow = [];
22235
22236      if (totalPages <= maxVisiblePages) {
22237        for (var i = 1; i <= totalPages; i++) {
22238          pagesToShow.push(i);
22239        }
22240      } else {
22241        pagesToShow.push(1);
22242
22243        if (currentPage > 3) {
22244          pagesToShow.push('...');
22245        }
22246
22247        var startPage = Math.max(2, currentPage - 1);
22248        var endPage = Math.min(totalPages - 1, currentPage + 1);
22249
22250        if (currentPage === 2) {
22251          endPage = Math.min(totalPages - 1, currentPage + 2);
22252        } else if (currentPage === totalPages - 1) {
22253          startPage = Math.max(2, currentPage - 2);
22254        }
22255
22256        for (var _i3 = startPage; _i3 <= endPage; _i3++) {
22257          pagesToShow.push(_i3);
22258        }
22259
22260        if (endPage < totalPages - 1) {
22261          pagesToShow.push('...');
22262        }
22263
22264        pagesToShow.push(totalPages);
22265      }
22266
22267      pagesToShow.forEach(function (page) {
22268        var stepperItem = void 0;
22269        if (page === '...') {
22270          stepperItem = $('\n                <li>\n                    <a href="javascript:void(0)" class="trip-stepper disabled" data-js="..." alt="...">...</a>\n                </li>\n            ');
22271        } else {
22272          stepperItem = $('\n                <li class="' + (page === currentPage ? 'active' : '') + '">\n                    <a href="javascript:void(0)" class="trip-stepper" id="stepper-trip-' + page + '" data-js="stepper-trip-' + page + '" alt="' + page + '">' + page + '</a>\n                </li>\n            ');
22273        }
22274        _this11.tripSteppers.append(stepperItem);
22275      });
22276
22277      var prevBtn = $('\n        <button type="button" class="trip-btn trip-prev-btn" id="trip-prev-btn" data-js="trip-prev-btn">
22277\n            <span class="jca-ico-angle-left"></span>\n        </button>\n    ');
22278      var nextBtn = $('\n        <button type="button" class="trip-btn trip-next-btn" id="trip-next-btn" data-js="trip-next-btn">\n            <span class="jca-ico-angle-right"></span>\n        </button>\n    ');
22279
22280      nextBtn.appendTo(this.tripSteppers);
22281      prevBtn.prependTo(this.tripSteppers);
22282
22283      if (totalPages === 0) {
22284        nextBtn.hide();
22285        prevBtn.hide();
22286      } else {
22287        nextBtn.show();
22288        prevBtn.show();
22289      }
22290    }
22291  }, {
22292    key: 'handleSteppersEvents',
22293    value: function handleSteppersEvents(groupedHistory, currentPage, totalPages) {
22294      var _this12 = this;
22295
22296      $('[data-js="trip-next-btn"]').on('click', function (e) {
22297        var nextIndexPage = Math.min(currentPage + 1, totalPages);
22298        _this12.getUserHistory(nextIndexPage);
22299        _this12.handleSteppers(nextIndexPage, totalPages);
22300      });
22301
22302      $('[data-js="trip-prev-btn"]').on('click', function (e) {
22303        var prevIndexPage = Math.max(currentPage - 1, 1);
22304        _this12.getUserHistory(prevIndexPage);
22305        _this12.handleSteppers(prevIndexPage, totalPages);
22306      });
22307
22308      $('.trip-stepper').on('click', function (e) {
22309        if ($(e.target).hasClass('disabled')) return;
22310        var indexClicked = +$(e.target).attr('data-js').replace(/\D/g, '');
22311        _this12.getUserHistory(indexClicked);
22312        _this12.handleSteppers(indexClicked, totalPages);
22313      });
22314    }
22315  }, {
22316    key: 'renderSteppersSearch',
22317    value: function renderSteppersSearch(totalPages, currentPage) {
22318      var qttSteppersMin = Utils.getWindowSize().width > 951 ? $('[data-js="qtt-show-trips"]').attr('qtt-stepper-desk') : $('[data-js="qtt-show-trips"]').attr('qtt-stepper-mobile');
22319
22320      this.tripSteppers.empty();
22321
22322      if (totalPages > 1) {
22323        if (totalPages > qttSteppersMin) {
22324          for (var i = 1; i <= qttSteppersMin; i++) {
22325            var itemsSteppers = void 0;
22326
22327            if (qttSteppersMin == i) {
22328              itemsSteppers = '\n                        <li class="' + (totalPages === currentPage ? 'active' : '') + '">\n                            <a href="javascript:void(0)" class="trip-stepper" data-js="stepper-trip-' + totalPages + '" id="stepper-trip-' + totalPages + '" alt="' + totalPages + '">' + totalPages + '</a>\n                        </li>\n                    ';
22329            } else if (qttSteppersMin - 1 == i) {
22330              itemsSteppers = '\n                        <li class="">\n                            <a href="javascript:void(0)" class="trip-stepper disabled" data-js="..." alt="...">...</a>\n                        </li>\n                    ';
22331            } else {
22332              itemsSteppers = '\n                        <li class="' + (i === currentPage ? 'active' : '') + '">\n                            <a href="javascript:void(0)" class="trip-stepper" id="stepper-trip-' + i + '" data-js="stepper-trip-' + i + '" alt="' + i + '">' + i + '</a>\n                        </li>\n                    ';
22333            }
22334
22335            this.tripSteppers.append(itemsSteppers);
22336          }
22337        } else {
22338          for (var _i4 = 1; _i4 <= totalPages; _i4++) {
22339            var _itemsSteppers = '\n                    <li class="' + (_i4 === currentPage ? 'active' : '') + '">\n                        <a href="#" class="trip-stepper" id="stepper-trip-' + _i4 + '" data-js="stepper-trip-' + _i4 + '" alt="' + _i4 + '">' + _i4 + '</a>\n                    </li>\n                ';
22340
22341            this.tripSteppers.append(_itemsSteppers);
22342          }
22343        }
22344
22345        var prevBtn = $('\n            <button type="button" class="trip-btn trip-prev-btn" id="trip-prev-btn" data-js="trip-prev-btn">\n                <span class="jca-ico-angle-left"></span>\n            </button>\n        ');
22346
22347        var nextBtn = $('\n            <button type="button" class="trip-btn trip-next-btn" id="trip-next-btn" data-js="trip-next-btn">\n                <span class="jca-ico-angle-right"></span>\n            </button>\n        ');
22348
22349        nextBtn.appendTo(this.tripSteppers);
22350        prevBtn.prependTo(this.tripSteppers);
22351      }
22352    }
22353  }, {
22354    key: 'paymentDetails',
22355    value: function paymentDetails(arrayPerService, index) {
22356      var hideDetail = $("[data-js='hide-payment-details']").val();
22357      var tarifa = 0;
22358      var taxas = 0;
22359      var discount = 0;
22360      var insuranceTotal = 0;
22361      var priceTotal = 0;
22362      var convenience = 0;
22363
22364      var flatTrips = arrayPerService.filter(Boolean).flat(2);
22365
22366      flatTrips.forEach(function (trip) {
22367        if (trip) {
22368          var amount = trip.amount,
22369              boardingFee = trip.boardingFee,
22370              commissionFee = trip.commissionFee,
22371              optionalInsurance = trip.optionalInsurance,
22372              insuranceTax = trip.insuranceTax,
22373              otherTax = trip.otherTax,
22374              fullPrice = trip.fullPrice,
22375              tariff = trip.tariff,
22376              tollTax = trip.tollTax,
22377              tax = trip.tax,
22378              voucherValue = trip.voucherValue,
22379              _voucherToken = trip.voucherToken,
22380              convenienceFee = trip.convenienceFee,
22381              discountPix = trip.discountPix;
22382
22383          tarifa += discountPix ? tariff - discountPix : tariff;
22384          taxas += tax + tollTax + boardingFee + otherTax + insuranceTax;
22385          discount += voucherValue;
22386          insuranceTotal += optionalInsurance ? optionalInsurance : 0;
22387          convenience += convenienceFee ? convenienceFee : 0;
22388
22389          priceTotal = tarifa + taxas + convenience + insuranceTotal - discount;
22390        }
22391      });
22392
22393      var _arrayPerService$0$ = arrayPerService[0][0],
22394          paymentForm = _arrayPerService$0$.paymentForm,
22395          voucherToken = _arrayPerService$0$.voucherToken;
22396
22397      var paymentType = paymentForm === "ADYEN" || paymentForm === "MALGA" ? "cartão de crédito" : paymentForm === "NUPAY_MALGA" ? "Nupay"
22398          : paymentForm === "WALLET" ? "Wallet" : "pix/transferência bancária";
22399      var isVoucherToken = voucherToken;
22400
22401      if (hideDetail === 'false') {
22402        if ($('[data-js="trip-detail-payment-' + index + '"] [data-js="value-ticket"]').length > 0) {
22403          $('[data-js="trip-detail-payment-' + index + '"] [data-js="value-ticket"]').find('.cmp-text').find('p').text('R$' + Utils.formatPrice(tarifa));
22404        } else {
22405          $('[data-js="trip-detail-payment-' + index + '"] [data-js="value-ticket"]').text('R$' + Utils.formatPrice(tarifa));
22406        }
22407
22408        if ($('[data-js="trip-detail-payment-' + index + '"] [data-js="value-descount"]').find('.cmp-text').length > 0) {
22409          $('[data-js="trip-detail-payment-' + index + '"] [data-js="value-descount"]').find('.cmp-text').find('p').text('-R$' + Utils.formatPrice(discount));
22410        } else {
22411          $('[data-js="trip-detail-payment-' + index + '"] [data-js="value-descount"]').text('-R$' + Utils.formatPrice(discount));
22412        }
22413
22414        if ($('[data-js="trip-detail-payment-' + index + '"] [data-js="services-ticket"]').length > 0) {
22415          $('[data-js="trip-detail-payment-' + index + '"] [data-js="services-ticket"]').find('.cmp-text').find('p').text('R$' + Utils.formatPrice(taxas));
22416        } else {
22417          $('[data-js="trip-detail-payment-' + index + '"] [data-js="services-ticket"]').text('R$' + Utils.formatPrice(taxas));
22418        }
22419
22420        if ($('[data-js="trip-detail-payment-' + index + '"] [data-js="insurance-value"]').length > 0) {
22421          $('[data-js="trip-detail-payment-' + index + '"] [data-js="insurance-value"]').find('.cmp-text').find('p').text('R$' + Utils.formatPrice(insuranceTotal));
22422        } else {
22423          $('[data-js="trip-detail-payment-' + index + '"] [data-js="insurance-value"]').text('R$' + Utils.formatPrice(insuranceTotal));
22424        }
22425
22426        if ($('[data-js="trip-detail-payment-' + index + '"] [data-js="convenienceFee-value"]').length > 0) {
22427          $('[data-js="trip-detail-payment-' + index + '"] [data-js="convenienceFee-value"]').find('.cmp-text').find('p').text('R$' + Utils.formatPrice(convenience));
22428        } else {
22429          $('[data-js="trip-detail-payment-' + index + '"] [data-js="convenienceFee-value"]').text('R$' + Utils.formatPrice(convenience));
22430        }
22431
22432        if ($('[data-js="trip-detail-payment-' + index + '"] [data-js="trip-value"]').length > 0) {
22433          $('[data-js="trip-detail-payment-' + index + '"] [data-js="trip-value"]').find('.cmp-text').find('p').text('R$' + Utils.formatPrice(priceTotal));
22434        } else {
22435          $('[data-js="trip-detail-payment-' + index + '"] [data-js="trip-value"]').text(Utils.formatPrice(priceTotal));
22436        }
22437
22438        $('[data-js="trip-detail-payment-' + index + '"] [data-js="payment-type"]').parent().removeClass("d-none");
22439        if ($('[data-js="trip-detail-payment-' + index + '"] [data-js="payment-type"]').length > 0) {
22440          $('[data-js="trip-detail-payment-' + index + '"] [data-js="payment-type"]').find('.cmp-text').find('p').text(paymentType);
22441        } else {
22442          $('[data-js="trip-detail-payment-' + index + '"] [data-js="payment-type"]').text(paymentType);
22443        }
22444
22445        $('[data-js="trip-detail-payment-' + index + '"] [data-js="interest-value"]').closest('.item-description').addClass("d-none");
22446
22447        var collapsedContainer = $('[data-js="trip-detail-payment-' + index + '"]').find('.trip-detail-payment').data('inner-collapsed');
22448        if (collapsedContainer) {
22449          $('[data-js="trip-detail-payment-' + index + '"]').find('.trip-detail-payment').find('.trip-detail-payment-header').addClass('collapsed');
22450          $('[data-js="trip-detail-payment-' + index + '"]').find('.trip-detail-payment').find('.trip-detail-payment-collapsible').collapse('hide');
22451        }
22452        if (isVoucherToken) {
22453          if ($('[data-js="trip-detail-payment-' + index + '"] [data-js="value-descount-voucher-text"]').length > 0) {
22454            $('[data-js="trip-detail-payment-' + index + '"] [data-js="value-descount-voucher-text"]').find('.cmp-text').find('p').append('(CUPOM: ' + isVoucherToken + ')');
22455          } else {
22456            $('[data-js="trip-detail-payment-' + index + '"] [data-js="value-descount-voucher-text"]').text('(CUPOM: ' + isVoucherToken + ')');
22457          }
22458        }
22459      } else {
22460        $('[data-js="trip-detail-payment-' + index + '"]').addClass("d-none").removeClass("d-md-flex").removeClass("d-md-flex");
22461      }
22462    }
22463  }, {
22464    key: 'generateCardsTrips',
22465    value: function generateCardsTrips(groupedHistory, isNextTripTab) {
22466      var _this14 = this;
22467
22468      var $currentTripList = isNextTripTab ? $('[data-refer="next-list"]') : $('[data-refer="prev-list"]');
22469      this.tripList.empty();
22470
22471      $.each(groupedHistory, function (index, arrayPerFinder) {
22472        //Separate going and return
22473        var arrayPerWay = _this14.groupArrayByField(arrayPerFinder, isNextTripTab, 'going').sort(function (a, b) {
22474          return DateFormatter.getValidDateFormat(a[0].departureDate) - DateFormatter.getValidDateFormat(b[0].departureDate);
22475        });
22476
22477        var dep = arrayPerWay[0];
22478        var ret = arrayPerWay[1];
22479
22480        //Separate going and going connection
22481        dep = _this14.groupArrayByField(dep, isNextTripTab, 'service');
22482        dep.sort(function (a, b) {
22483          return DateFormatter.getValidDateFormat(a[0].departureDate) - DateFormatter.getValidDateFormat(b[0].departureDate);
22484        });
22485
22486        //Separate return and return connection
22487        if (ret) {
22488          ret = _this14.groupArrayByField(ret, isNextTripTab, 'service');
22489          ret.sort(function (a, b) {
22490            return DateFormatter.getValidDateFormat(a[0].departureDate) - DateFormatter.getValidDateFormat(b[0].departureDate);
22491          });
22492        }
22493
22494        //Fill new array with trip steps
22495        // 0: main departure
22496        // 1: all departure connections
22497        // 2: main return
22498        // 3: all return connections
22499        var arrayPerService = [];
22500        arrayPerService[0] = dep[0];
22501        arrayPerService[1] = dep.length > 1 ? dep.slice(1) : null;
22502        arrayPerService[2] = ret ? ret[0] : null;
22503        arrayPerService[3] = ret && ret.length > 1 ? ret.slice(1) : null;
22504        // arrayPerService = this.groupArrayByField(arrayPerFinder, isNextTripTab, 'service')
22505
22506        //Grabing example objects to extract some info
22507        var goingObj = arrayPerService[0][0];
22508        var goingConnections = Array.isArray(arrayPerService[1]) ? arrayPerService[1] : [];
22509        var lastGoingConnection = null;
22510
22511        if (goingConnections.length > 0) {
22512          var raw = goingConnections[goingConnections.length - 1];
22513
22514          lastGoingConnection = Array.isArray(raw) ? raw[raw.length - 1] : raw;
22515        }
22516        var returnObj = arrayPerService[2] ? arrayPerService[2][0] : null;
22517        var returnConnection = arrayPerService[3] ? arrayPerService[3][0] : null;
22518
22519        var mainFinder = goingObj.finder;
22520        var companyName = goingObj.company;
22521
22522        //Filling the extracted info
22523        var origin = Utils.capitalize(goingObj.originDescription);
22524        var destination = Utils.capitalize(_this14.getDestinationWithConnection(lastGoingConnection, goingObj));
22525        var dateInit = goingObj.departureDate;
22526        var dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(dateInit));
22527        var hourDepart = DateFormatter.extractHour(goingObj.departureDate);
22528
22529        var total = _this14.getTripTotal(arrayPerService);
22530
22531
22532        var dataWithIndexes = _this14.tripDetailsTemplate.replace(/(\#INDEX)/g, index);
22533        $currentTripList.append(dataWithIndexes);
22534        _this14.handleCustomCollapse();
22535        _this14.paymentDetails(arrayPerService, index);
22536        // Going Details
22537        var pendingPaymentAemText = $('[data-js="pending-payment-aem-text"]').data('unavailable');
22538        var pendingPaymentAemTextColor = $('[data-js="my-travels-styles"]').attr('data-style-status-pendingPaymentAemColor');
22539        var showBookingCodeAemCheckbox = $('[data-js="show-booking-cod-aem-checkbox"]').val() == 'true' ? true : false;
22540        var paymentFormValue = goingObj.paymentForm == 'PIX' || goingObj.paymentForm == 'PIX-ITAU' || goingObj.paymentForm === 'Pix' || goingObj.paymentForm == 'PAYMEE' ? true : false;
22541        var paymentStatusValue = goingObj.status;
22542        if (showBookingCodeAemCheckbox == true && paymentFormValue == true && paymentStatusValue == 'SALE_PENDING') {
22543          $('[data-js="going-summary-finder-' + index + '"]').text(pendingPaymentAemText);
22544          _this14.initTooltipUnavailableBookingCode(pendingPaymentAemTextColor, index);
22545          $('[data-js="going-summary-finder-' + index + '"]').css('color', pendingPaymentAemTextColor);
22546        } else {
22547          //$('[data-js="going-summary-finder-' + index + '"]').text(mainFinder);
22548          if ($('[data-js="going-summary-finder-' + index + '"]').find('.cmp-text').length > 0) {
22549            $('[data-js="going-summary-finder-' + index + '"]').find('.cmp-text').find('p').text(mainFinder);
22550          } else {
22551            $('[data-js="going-summary-finder-' + index + '"]').text(mainFinder);
22552          }
22553        }
22554
22555        //$('[data-js="going-summary-date-depart-' + index + '"]').text(dateDepart);
22556        if ($('[data-js="going-summary-date-depart-' + index + '"]').find('.cmp-text').length > 0) {
22557          $('[data-js="going-summary-date-depart-' + index + '"]').find('.cmp-text').find('p').text(dateDepart);
22558        } else {
22559          $('[data-js="going-summary-date-depart-' + index + '"]').text(dateDepart);
22560        }
22561
22562        //$('[data-js="going-summary-origin-' + index + '"]').text(origin);
22563        if ($('[data-js="going-summary-origin-' + index + '"]').find('.cmp-text').length > 0) {
22564          $('[data-js="going-summary-origin-' + index + '"]').find('.cmp-text').find('p').text(origin);
22565        } else {
22566          $('[data-js="going-summary-origin-' + index + '"]').text(origin);
22567        }
22568
22569        //$('[data-js="going-summary-destination-' + index + '"]').text(destination);
22570        if ($('[data-js="going-summary-destination-' + index + '"]').find('.cmp-text').length > 0) {
22571          $('[data-js="going-summary-destination-' + index + '"]').find('.cmp-text').find('p').text(destination);
22572        } else {
22573          $('[data-js="going-summary-destination-' + index + '"]').text(destination);
22574        }
22575
22576        var $a = $('[data-js="going-summary-status-' + index + '"]').find('.cmp-text').length > 0 ? $('[data-js="going-summary-status-' + index + '"]').find('.cmp-text').find('p') : $('[data-js="going-summary-status-' + index + '"]');
22577        $a.text(_this14.getTripStatus($a, arrayPerService, goingObj.paymentForm));
22578        new TripDetailsActions(arrayPerService[0], index, isNextTripTab);
22579
22580        $.each(arrayPerService, function (i, trip) {
22581          if (!trip) return;
22582
22583          switch (i) {
22584            case 0:
22585              var $sectionDeparture = $('[data-js="detail-depart-' + index + '"]');
22586              new CheckoutDetailsCard({ $parent: $sectionDeparture, trip: arrayPerService[0], index: index, subindex: i, isNextTripTab: isNextTripTab });
22587              break;
22588            case 1:
22589              if (trip[0]) {
22590                var $sectionConn1 = $('[data-js="detail-depart-connection-' + index + '"]');
22591                $sectionConn1.show();
22592
22593                new CheckoutDetailsCard({
22594                  $parent: $sectionConn1,
22595                  trip: trip[0],
22596                  index: index,
22597                  subindex: 1,
22598                  isNextTripTab: isNextTripTab
22599                });
22600              }
22601
22602              if (trip[1]) {
22603                var _$sectionConn = $('[data-js="detail-depart-connection2-' + index + '"]');
22604                _$sectionConn.show();
22605
22606                new CheckoutDetailsCard({
22607                  $parent: _$sectionConn,
22608                  trip: trip[1],
22609                  index: index,
22610                  subindex: 2,
22611                  isNextTripTab: isNextTripTab
22612                });
22613              }
22614              break;
22615            case 2:
22616              var $sectionReturn = $('[data-js="detail-return-' + index + '"]');
22617              $sectionReturn.show();
22618              new CheckoutDetailsCard({ $parent: $sectionReturn, trip: arrayPerService[2], index: index, subindex: i, isNextTripTab: isNextTripTab });
22619              break;
22620            case 3:
22621              if (trip[0]) {
22622                var _$sectionConn2 = $('[data-js="detail-return-connection-' + index + '"]');
22623                _$sectionConn2.show();
22624
22625                new CheckoutDetailsCard({
22626                  $parent: _$sectionConn2,
22627                  trip: trip[0],
22628                  index: index,
22629                  subindex: 1,
22630                  isNextTripTab: isNextTripTab
22631                });
22632              }
22633
22634              var $sectionConn2 = $('[data-js="detail-return-connection2-' + index + '"]');
22635              if (trip[1] && $sectionConn2.length) {
22636                $sectionConn2.show();
22637
22638                new CheckoutDetailsCard({
22639                  $parent: $sectionConn2,
22640                  trip: trip[1],
22641                  index: index,
22642                  subindex: 2,
22643                  isNextTripTab: isNextTripTab
22644                });
22645              }
22646              break;
22647          }
22648        });
22649
22650        var salesTime = null;
22651        if (goingObj.saleTransactions != null && goingObj.saleTransactions.length > 0) salesTime = DateFormatter.reverseDate(DateFormatter.extractDate(goingObj.saleTransactions[0].date));
22652
22653        _this14.handleCommands(index, arrayPerService, origin, destination, hourDepart, dateDepart, salesTime, mainFinder, total);
22654      });
22655    }
22656  }, {
22657    key: 'initTooltipUnavailableBookingCode',
22658    value: function initTooltipUnavailableBookingCode(pendingPaymentAemTextColor, index) {
22659      $('[data-js="tootltip-btn-unavaible-' + index + '"]').tooltip();
22660      $('[data-js="tootltip-btn-unavaible-mobile-' + index + '"]').tooltip();
22661      $('[data-js="tootltip-btn-unavaible-' + index + '"]').removeClass('d-none');
22662      $('[data-js="tootltip-btn-unavaible-mobile-' + index + '"]').removeClass('d-none');
22663      var aemUnavailableBookingCodeText = $('[data-js="pending-payment-aem-text"]').data('unavailable-tootlip');
22664      $('[data-js="tootltip-btn-unavaible-' + index + '"]').attr('title', aemUnavailableBookingCodeText);
22665      $('[data-js="tootltip-btn-unavaible-mobile-' + index + '"]').attr('data-bs-original-title', aemUnavailableBookingCodeText);
22666      $('[data-js="tootltip-btn-unavaible-' + index + '"]').css('color', pendingPaymentAemTextColor);
22667      $('[data-js="tootltip-btn-unavaible-mobile-' + index + '"]').css('color', pendingPaymentAemTextColor);
22668    }
22669  }, {
22670    key: 'getDestinationWithConnection',
22671    value: function getDestinationWithConnection(returnTrip, goingTrip) {
22672      if (returnTrip) {
22673        return returnTrip.destinationDescription;
22674      }
22675
22676      return goingTrip.destinationDescription;
22677    }
22678  }, {
22679    key: 'getTripTotal',
22680    value: function getTripTotal(tripArray) {
22681      var _tripArray = _slicedToArray(tripArray, 2),
22682        goingObj = _tripArray[0],
22683        returnObj = _tripArray[1];
22684
22685      var total = goingObj.reduce(function (acc, trip) {
22686        return acc + trip.amount;
22687      }, 0);
22688
22689      if (returnObj) total += returnObj.reduce(function (acc, trip) {
22690        return acc + trip.amount;
22691      }, 0);
22692
22693      return total;
22694    }
22695  }, {
22696    key: 'handleCustomCollapse',
22697    value: function handleCustomCollapse() {
22698      var $tripDetailsTemplateLi = $('[data-js="trip-detail-template"]');
22699      var collapsedContainer = $tripDetailsTemplateLi.data('outer-collapsed');
22700      var bodyEl = $tripDetailsTemplateLi.find('.trip-detail-body')[0];
22701      if (collapsedContainer) {
22702        $tripDetailsTemplateLi.find('.trip-detail-header').addClass('collapsed');
22703        new bootstrap.Collapse(bodyEl, { toggle: false }).hide();
22704      } else {
22705        $tripDetailsTemplateLi.find('.trip-detail-header').removeClass('collapsed');
22706        new bootstrap.Collapse(bodyEl, { toggle: false }).show();
22707      }
22708    }
22709  }, {
22710    key: 'getTripStatus',
22711    value: function getTripStatus($elem, arrTrip, paymentType) {
22712      var normalizedPaymentType = paymentType != null ? paymentType.toLowerCase() : '';
22713      var isPaymee = normalizedPaymentType.includes("pix") || normalizedPaymentType === "paymee" || normalizedPaymentType === "wallet";
22714      return isPaymee ? this.getTripStatusBankTransfer($elem, arrTrip) : this.getTripStatusPaymentCard($elem, arrTrip);
22715    }
22716  }, {
22717    key: 'getTripStatusBankTransfer',
22718    value: function getTripStatusBankTransfer($elem, arrTrip) {
22719      var _fetchTimeleft2 = this.fetchTimeleft(arrTrip),
22720        timeleftGoing = _fetchTimeleft2.timeleftGoing,
22721        timeleftReturn = _fetchTimeleft2.timeleftReturn;
22722      var labelActive = $('[data-js="my-travels-status-label"]').attr('data-active');
22723      var labelRemarkable = $('[data-js="my-travels-status-label"]').attr('data-remarkable');
22724      var labelCanceled = $('[data-js="my-travels-status-label"]').attr('data-canceled');
22725      var labelExpired = $('[data-js="my-travels-status-label"]').attr('data-expired');
22726      var labelTripExpired = $('[data-js="my-travels-status-label"]').attr('data-trip-expired');
22727      var labelPending = $('[data-js="my-travels-status-label"]').attr('data-pending');
22728      var labelRemarked = $('[data-js="my-travels-status-label"]').attr('data-remarked');
22729      var labelRelocatedCanceled = $('[data-js="my-travels-status-label"]').attr('data-relocated-canceled');
22730      var labelSaleRelocated = $('[data-js="my-travels-status-label"]').attr('data-sale-relocated');
22731      var labelCancelationError = $('[data-js="my-travels-status-label"]').attr('data-cancelation-error');
22732
22733      var salesGoing = void 0,
22734        salesReturn = void 0,
22735        salesRemark = void 0;
22736
22737      salesGoing = arrTrip[0].filter(function (trip) {
22738        return trip.status === 'SALE_PENDING' || trip.status === 'SALE_APPROVED' || trip.status === 'SALE_EXPIRED' || trip.status === 'INITIAL_CREATE' || trip.status === 'SALE_RELOCATED' || trip.status === 'RELOCATED_CANCELED' || trip.status === 'CANCELATION_ERROR' || trip.status === 'EXCHANGE_PENDING' || trip.status === 'REMARCÁVEL';
22739      });
22740
22741      salesRemark = arrTrip[0].filter(function (trip) {
22742        return trip.status === 'EXCHANGED';
22743      });
22744
22745      if (salesGoing.length > 0) {
22746        var currentDate = new Date();
22747        var departureDate = new Date(arrTrip[0][0].departureDate);
22748        var exchangeAvailable = salesGoing[0].exchange;
22749
22750        if (timeleftGoing < this.INTERVAL && timeleftReturn < this.INTERVAL) {
22751          if (salesGoing[0].status === 'SALE_EXPIRED' || salesGoing[0].status === 'EXCHANGE_PENDING') {
22752            $elem.addClass('expired');
22753            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-expired');
22754            $($elem).closest('.trip-detail-template').addClass('status-expired');
22755            return labelExpired;
22756          } else if (salesGoing[0].status === 'SALE_PENDING') {
22757            $elem.addClass('pending');
22758            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-pending');
22759            $($elem).closest('.trip-detail-template').addClass('status-pending');
22760            return labelPending;
22761          } else if (salesGoing[0].status === 'SALE_CANCELED' || salesGoing[0].status.toUpperCase() === 'REFUND_PEDING' || salesGoing[0].status.toUpperCase() === 'LATE_REFUND' || salesGoing[0].status.toUpperCase() === 'REFUND_FAILED') {
22762            $elem.addClass('canceled');
22763            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
22764            $($elem).closest('.trip-detail-template').addClass('status-canceled');
22765            return labelCanceled;
22766          } else if (salesGoing[0].status === 'INITIAL_CREATE') {
22767            $elem.addClass('canceled');
22768            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
22769            $($elem).closest('.trip-detail-template').addClass('status-canceled');
22770            return i18n('available');
22771          } else if (salesGoing[0].status.toUpperCase() === 'RELOCATED_CANCELED') {
22772            $elem.addClass('canceled');
22773            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
22774            $($elem).closest('.trip-detail-template').addClass('status-canceled');
22775            return labelRelocatedCanceled;
22776          } else if (salesGoing[0].status === 'CANCELATION_ERROR') {
22777            $elem.addClass('expired');
22778            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-expired');
22779            $($elem).closest('.trip-detail-template').addClass('status-expired');
22780            return labelCancelationError;
22781          } else if (salesGoing[0].status === 'SALE_RELOCATED') {
22782            $elem.addClass('active');
22783            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-active');
22784            $($elem).closest('.trip-detail-template').addClass('status-active');
22785            return labelSaleRelocated;
22786          } else if (salesGoing[0].status === 'SALE_APPROVED' && currentDate > departureDate && exchangeAvailable) {
22787            $elem.addClass('remarkable');
22788            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-remarkable');
22789            $($elem).closest('.trip-detail-template').addClass('status-remarkable');
22790            return labelRemarkable;
22791          } else if (salesGoing[0].status === 'SALE_RELOCATED') {
22792            $elem.addClass('active');
22793            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-active');
22794            $($elem).closest('.trip-detail-template').addClass('status-active');
22795            return labelSaleRelocated;
22796          } else if (salesGoing[0].status.toUpperCase() === 'RELOCATED_CANCELED') {
22797            $elem.addClass('canceled');
22798            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
22799            $($elem).closest('.trip-detail-template').addClass('status-canceled');
22800            return labelRelocatedCanceled;
22801          } else if (currentDate > departureDate && exchangeAvailable == false) {
22802            $elem.addClass('trip-expired');
22803            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-expired');
22804            $($elem).closest('.trip-detail-template').addClass('status-expired');
22805            return labelTripExpired;
22806          } else if (salesGoing[0].status === 'SALE_APPROVED' && currentDate > departureDate && !exchangeAvailable) {
22807            $elem.addClass('active');
22808            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-active');
22809            $($elem).closest('.trip-detail-template').addClass('status-active');
22810            return labelActive;
22811          } else {
22812            $elem.addClass('remarkable');
22813            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-remarkable');
22814            $($elem).closest('.trip-detail-template').addClass('status-remarkable');
22815            return labelRemarkable;
22816          }
22817        } else {
22818          if (salesGoing[0].status === 'SALE_PENDING' || salesGoing[0].status === 'EXCHANGE_PENDING') {
22819            $elem.addClass('pending');
22820            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-pending');
22821            $($elem).closest('.trip-detail-template').addClass('status-pending');
22822            return labelPending;
22823          } else if (salesGoing[0].status === 'SALE_EXPIRED') {
22824            $elem.addClass('expired');
22825            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-expired');
22826            $($elem).closest('.trip-detail-template').addClass('status-expired');
22827            return labelExpired;
22828          } else if (salesGoing[0].status === 'INITIAL_CREATE') {
22829            $elem.addClass('canceled');
22830            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
22831            $($elem).closest('.trip-detail-template').addClass('status-canceled');
22832            return i18n('available');
22833          } else if (salesGoing[0].status.toUpperCase() === 'RELOCATED_CANCELED') {
22834 
22834           $elem.addClass('canceled');
22835            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
22836            $($elem).closest('.trip-detail-template').addClass('status-canceled');
22837            return labelRelocatedCanceled;
22838          } else if (salesGoing[0].status === 'CANCELATION_ERROR') {
22839            $elem.addClass('expired');
22840            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-expired');
22841            $($elem).closest('.trip-detail-template').addClass('status-expired');
22842            return labelCancelationError;
22843          } else if (salesGoing[0].status === 'SALE_RELOCATED') {
22844            $elem.addClass('active');
22845            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-active');
22846            $($elem).closest('.trip-detail-template').addClass('status-active');
22847            return labelSaleRelocated;
22848          } else if (salesGoing[0].status === 'SALE_APPROVED' && currentDate > departureDate) {
22849            $elem.addClass('active');
22850            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-active');
22851            $($elem).closest('.trip-detail-template').addClass('status-active');
22852            return labelActive;
22853          } else if (currentDate > departureDate && exchangeAvailable == false) {
22854            $elem.addClass('trip-expired');
22855            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-expired');
22856            $($elem).closest('.trip-detail-template').addClass('status-expired');
22857            return labelTripExpired;
22858          } else {
22859            $elem.addClass('active');
22860            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-active');
22861            $($elem).closest('.trip-detail-template').addClass('status-active');
22862            return labelActive;
22863          }
22864        }
22865      } else if (salesRemark.length > 0) {
22866        $elem.addClass('remark');
22867        $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-remarked');
22868        $($elem).closest('.trip-detail-template').addClass('status-remarked');
22869        return labelRemarked;
22870      } else {
22871        if (!arrTrip[2]) {
22872          $elem.addClass('canceled');
22873          $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
22874          $($elem).closest('.trip-detail-template').addClass('status-canceled');
22875          return labelCanceled;
22876        }
22877
22878        salesReturn = arrTrip[2].filter(function (trip) {
22879          return trip.status === 'SALE_APPROVED' || trip.status === 'CARD_APPROVED' || trip.status === 'SALE_RELOCATED';
22880        });
22881
22882        if (salesReturn.length > 0) {
22883          $elem.addClass('expired');
22884          $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-expired');
22885          $($elem).closest('.trip-detail-template').addClass('status-expired');
22886          return labelExpired;
22887        } else {
22888          $elem.addClass('canceled');
22889          $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
22890          $($elem).closest('.trip-detail-template').addClass('status-canceled');
22891          return labelCanceled;
22892        }
22893      }
22894    }
22895  }, {
22896    key: 'getTripStatusPaymentCard',
22897    value: function getTripStatusPaymentCard($elem, arrTrip) {
22898      var _fetchTimeleft3 = this.fetchTimeleft(arrTrip),
22899        timeleftGoing = _fetchTimeleft3.timeleftGoing,
22900        timeleftReturn = _fetchTimeleft3.timeleftReturn;
22901
22902      var labelActive = $('[data-js="my-travels-status-label"]').attr('data-active');
22903      var labelRemarkable = $('[data-js="my-travels-status-label"]').attr('data-remarkable');
22904      var labelCanceled = $('[data-js="my-travels-status-label"]').attr('data-canceled');
22905      var labelExpired = $('[data-js="my-travels-status-label"]').attr('data-expired');
22906      var labelTripExpired = $('[data-js="my-travels-status-label"]').attr('data-trip-expired');
22907      var labelPending = $('[data-js="my-travels-status-label"]').attr('data-pending');
22908      var labelRemarked = $('[data-js="my-travels-status-label"]').attr('data-remarked');
22909      var labelRelocatedCanceled = $('[data-js="my-travels-status-label"]').attr('data-relocated-canceled');
22910      var labelSaleRelocated = $('[data-js="my-travels-status-label"]').attr('data-sale-relocated');
22911      var labelCancelationError = $('[data-js="my-travels-status-label"]').attr('data-cancelation-error');
22912
22913      var salesGoing = void 0,
22914        salesReturn = void 0,
22915        salesRemark = void 0;
22916      if (arrTrip[0]) {
22917        salesGoing = arrTrip[0].filter(function (trip) {
22918          return ['SALE_PENDING', 'SALE_APPROVED', 'SALE_EXPIRED', 'INITIAL_CREATE', 'SALE_RELOCATED', 'RELOCATED_CANCELED', 'CANCELATION_ERROR', 'REMARCÁVEL'].includes(trip.status);
22919        });
22920
22921        salesRemark = arrTrip[0].filter(function (trip) {
22922          return trip.status === 'EXCHANGED';
22923        });
22924        if (salesGoing.length > 0) {
22925          var currentDate = new Date();
22926          var departureDate = new Date(arrTrip[0][0].departureDate);
22927          var exchangeAvailable = salesGoing[0].exchange;
22928          if (timeleftGoing < this.INTERVAL && timeleftReturn < this.INTERVAL) {
22929            if (salesGoing[0].status === 'SALE_APPROVED' && currentDate > departureDate && exchangeAvailable) {
22930              $elem.addClass('remarkable');
22931              $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-remarkable');
22932              $($elem).closest('.trip-detail-template').addClass('status-remarkable');
22933              return labelRemarkable;
22934            } else if (exchangeAvailable) {
22935              $elem.addClass('remarkable');
22936              $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-remarkable');
22937              $($elem).closest('.trip-detail-template').addClass('status-remarkable');
22938              return labelRemarkable;
22939            } else if (salesGoing[0].status === 'SALE_RELOCATED') {
22940              $elem.addClass('active');
22941              $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-active');
22942              $($elem).closest('.trip-detail-template').addClass('status-active');
22943              return labelSaleRelocated;
22944            } else if (salesGoing[0].status.toUpperCase() === 'RELOCATED_CANCELED') {
22945              $elem.addClass('canceled');
22946              $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
22947              $($elem).closest('.trip-detail-template').addClass('status-canceled');
22948              return labelRelocatedCanceled;
22949            } else if (currentDate > departureDate && exchangeAvailable == false) {
22950              $elem.addClass('trip-expired');
22951              $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-expired');
22952              $($elem).closest('.trip-detail-template').addClass('status-expired');
22953              return labelTripExpired;
22954            } else if (salesGoing[0].status === 'SALE_APPROVED' && exchangeAvailable == false) {
22955              $elem.addClass('active');
22956              $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-active');
22957              $($elem).closest('.trip-detail-template').addClass('status-active');
22958              return labelActive;
22959            } else if (salesGoing[0].status === 'SALE_PENDING' || salesGoing[0].status === 'SALE_EXPIRED' || salesGoing[0].status === 'EXCHANGE_PENDING') {
22960              $elem.addClass('expired');
22961              $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-expired');
22962              $($elem).closest('.trip-detail-template').addClass('status-expired');
22963              return labelExpired
22964            }
22965          } else if (salesGoing[0].status === 'INITIAL_CREATE') {
22966            $elem.addClass('canceled');
22967            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
22968            $($elem).closest('.trip-detail-template').addClass('status-canceled');
22969            return labelActive;
22970          } else if (salesGoing[0].status === 'SALE_RELOCATED') {
22971            $elem.addClass('active');
22972            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-active');
22973            $($elem).closest('.trip-detail-template').addClass('status-active');
22974            return labelSaleRelocated;
22975          } else if (salesGoing[0].status.toUpperCase() === 'RELOCATED_CANCELED') {
22976            $elem.addClass('canceled');
22977            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
22978            $($elem).closest('.trip-detail-template').addClass('status-canceled');
22979            return labelRelocatedCanceled;
22980          } else if (salesGoing[0].status === 'CANCELATION_ERROR') {
22981            $elem.addClass('expired');
22982            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-expired');
22983            $($elem).closest('.trip-detail-template').addClass('status-expired');
22984            return labelCancelationError;
22985          } else if (salesGoing[0].status === 'SALE_APPROVED' && timeleftGoing > this.INTERVAL && exchangeAvailable) {
22986            $elem.addClass('active');
22987            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-active');
22988            $($elem).closest('.trip-detail-template').addClass('status-active');
22989            return labelActive;
22990          } else if (salesGoing[0].status === 'SALE_APPROVED' && arrTrip[2] ? arrTrip[2][0].status == "SALE_CANCELED" : null && !exchangeAvailable) {
22991            $elem.addClass('trip-expired');
22992            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-expired');
22993            $($elem).closest('.trip-detail-template').addClass('status-expired');
22994            return labelTripExpired;
22995          } else if (salesGoing[0].status === 'SALE_APPROVED' && !exchangeAvailable) {
22996            $elem.addClass('active');
22997            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-active');
22998            $($elem).closest('.trip-detail-template').addClass('status-active');
22999            return labelActive;
23000          } else $elem.addClass('remarkable');
23001          return labelRemarkable;
23002        } else if (salesRemark.length > 0) {
23003          $elem.addClass('remark');
23004          $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-remarked');
23005          $($elem).closest('.trip-detail-template').addClass('status-remarked');
23006          return labelRemarked;
23007        } else {
23008          if (!arrTrip[1]) {
23009            $elem.addClass('canceled');
23010            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
23011            $($elem).closest('.trip-detail-template').addClass('status-canceled');
23012            return labelCanceled;
23013          }
23014          salesReturn = arrTrip[1].filter(function (trip) {
23015            return ['SALE_APPROVED', 'CARD_APPROVED', 'SALE_RELOCATED'].includes(trip.status);
23016          });
23017
23018          if (salesReturn.length > 0) {
23019            $elem.addClass('expired');
23020            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-expired');
23021            $($elem).closest('.trip-detail-template').addClass('status-expired');
23022            return labelExpired;
23023          } else {
23024            $elem.addClass('canceled');
23025            $($elem).closest('.trip-detail-template').find('.trip-detail-actions').addClass('status-canceled');
23026            $($elem).closest('.trip-detail-template').addClass('status-canceled');
23027            return labelCanceled;
23028          }
23029        }
23030      }
23031    }
23032  }, {
23033    key: 'getOnlyNextTrips',
23034    value: function getOnlyNextTrips(fullHistory) {
23035      var _this9 = this;
23036
23037      return fullHistory.filter(function (sale) {
23038        return DateFormatter.getValidDateFormat(sale.departureDate) > _this9.timeExact && !_this9.isFullyCanceled(sale, fullHistory);
23039      });
23040    }
23041  }, {
23042    key: 'getOnlyPreviousTrips',
23043    value: function getOnlyPreviousTrips(fullHistory) {
23044      var _this10 = this;
23045
23046      return fullHistory.filter(function (sale) {
23047        return DateFormatter.getValidDateFormat(sale.departureDate) <= _this10.timeExact || _this10.isFullyCanceled(sale, fullHistory);
23048      });
23049    }
23050  }, {
23051    key: 'isFullyCanceled',
23052    value: function isFullyCanceled(trip, fullHistory) {
23053      if (trip.status !== "SALE_CANCELED" && trip.status !== "SALE_EXPIRED" && trip.status !== "INITIAL_CREATE" && trip.status.toUpperCase() !== 'REFUND_PENDING' && trip.status.toUpperCase() !== 'REFUND_PEDING' && trip.status.toUpperCase() !== 'LATE_REFUND' && trip.status !== "RELOCATED_CANCELED" && trip.status !== "CANCELATION_ERROR" && trip.status !== 'EXCHANGED' && trip.status !== 'REFUND_FAILED') {
23054        return false;
23055      }
23056
23057      var confirmedTrips = fullHistory.filter(function (el) {
23058        return el.finder === trip.finder && el.service === trip.service && el.status !== "SALE_CANCELED" && el.status !== "SALE_EXPIRED" && el.status !== "INITIAL_CREATE" && el.status.toUpperCase() !== 'REFUND_PENDING' && el.status.toUpperCase() !== 'REFUND_PEDING' && el.status.toUpperCase() !== 'LATE_REFUND' && trip.status !== "RELOCATED_CANCELED" && trip.status !== "CANCELATION_ERROR" && el.status !== 'EXCHANGED' && el.status !== 'REFUND_FAILED';
23059      });
23060
23061      return !confirmedTrips.length;
23062    }
23063  }, {
23064    key: 'getDaysToNextTrip',
23065    value: function getDaysToNextTrip(tripDate) {
23066      var oneDay = 24 * 60 * 60 * 1000; //a day in milliseconds
23067      var firstDate = new Date();
23068      var secondDate = DateFormatter.getValidDateFormat(tripDate);
23069      return Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / oneDay));
23070    }
23071  }, {
23072    key: 'groupArrayByField',
23073    value: function groupArrayByField(filteredHistory, isNextTripTab, field) {
23074      var arr = [];
23075      var target = Utils.groupArrayBy(filteredHistory, field);
23076      for (var k in target) {
23077        if (target.hasOwnProperty(k)) {
23078          arr.push(target[k]);
23079        }
23080      }
23081      return isNextTripTab ? arr : Utils.sortArrayReverse(arr);
23082    }
23083  }]);
23084
23085  return MyAccountController;
23086}();
23087'use strict';
23088
23089(function () {
23090  $('[data-js="button-menu"], [data-js="button-menu-close"]').click(function () {
23091    $('.nav').toggleClass('active');
23092    $('body').css('position', 'relative');
23093    $("[data-js='nav-submenu-list']").removeClass('active');
23094  });
23095})();
23096'use strict';
23097
23098(function () {
23099  $('[data-js="button-return"]').click(function () {
23100    var body = $('body');
23101    $('.nav').toggleClass('active');
23102    body.css('position', 'relative');
23103  });
23104})();
23105"use strict";
23106
23107(function ($) {
23108  "use strict";
23109
23110  try {
23111    document.querySelectorAll('.dropdown-toggle').forEach(function (el) {
23112      new bootstrap.Dropdown(el);
23113    });
23114
23115    $(".dropdown-toggle").on("mouseenter", function (e) {
23116      if (!$(this).parent().hasClass("show")) {
23117        $(this).click();
23118      }
23119    });
23120
23121    $(".dropdown-toggle").mousedown(function (e) {
23122      if ($(this).parent().hasClass("show")) {
23123        var href = $(this).attr('href');
23124        location.href = href;
23125      }
23126    });
23127
23128    $(".dropdown-toggle").keydown(function (e) {
23129      var key = e.which || e.keyCode;
23130      if (key === Utils.keyCodes.ENTER) $(this).trigger('mousedown');
23131    });
23132
23133    $(".dropdown-toggle").on("mouseleave", function (e) {
23134      var element = $(e.toElement || e.relatedTarget);
23135      if (!element.hasClass('dropdown-toggle') && !element.hasClass('dropdown-menu') && !element.hasClass('dropdown-item')) {
23136        $(this).click();
23137      }
23138    });
23139
23140    $(".desktop-item-menu-jca").on("mouseout", function (e) {
23141      var element = $(e.toElement || e.relatedTarget);
23142      $(document.activeElement).blur();
23143    });
23144
23145  } catch (error) {
23146    console.log(error);
23147  }
23148
23149  $(".dropdown-menu").on("mouseleave", function () {
23150    if ($(this).hasClass("show")) {
23151      $(this).parent().find(".dropdown-toggle").click();
23152    }
23153  });
23154
23155  $('[data-js="button-menu"]').click(function () {
23156    var body = $('body');
23157    var navMenu = $('[data-js="nav-menu"]');
23158    var width = $(window).width();
23159    if (navMenu.hasClass('active')) {
23160      body.css('position', 'fixed');
23161      body.css('width', width);
23162    }
23163  });
23164  $('[data-js="nav-button-logout"]').click(function () {
23165    var body = $('body');
23166    var navMenu = $('[data-js="nav-submenu-list-logout"]');
23167    var width = $(window).width();
23168    navMenu.toggleClass('active');
23169    if (navMenu.hasClass('active')) {
23170      body.css('position', 'fixed');
23171      body.css('width', width);
23172      navMenu.find('.menu-list').not('.logout').hide();
23173    } else {
23174      body.css('position', '');
23175      body.css('width', '');
23176    }
23177  });
23178
23179  $('.menu-list li').click(function () {
23180    var width = $(window).width();
23181    var body = $('body');
23182    var link = $(this).children('a').data('js');
23183    var navMenu = $('[data-js="nav-submenu-list"]');
23184    var submenu = navMenu.find('[data-js="' + link + '-submenu"]');
23185    if (submenu.length > 0) {
23186      navMenu.toggleClass('active');
23187      if (navMenu.hasClass('active')) {
23188        body.css('position', 'fixed');
23189        body.css('width', width);
23190        navMenu.find('.menu-list').not('.logout').hide();
23191        submenu.show();
23192      }
23193    } else {
23194      if (link === 'logout') {
23195        SessionStorage.remove('passenger');
23196        SessionStorage.remove('cart');
23197        localStorage.setItem("logged", false);
23198        $(location).attr('href', $('#homePagePath').val());
23199      } else if (link === 'my-account') {
23200        $(location).attr('href', $('#myAccountPath').val());
23201      } else if (link === 'edit-data') {
23202        $(location).attr('href', $('#editUserPath').val());
23203      }
23204    }
23205  });
23206
23207  var stripe = function stripe() {
23208    $('.header-site .container-header-hero .nav .menu-list').children().not(':hidden').each(function (idx, el) {
23209      idx % 2 === 0 ? $(el).addClass('stripe-even') : $(el).addClass('stripe-odd');
23210    });
23211  };
23212
23213  if (SessionStorage.get('passenger')) {
23214    $('[data-js="my-account"]').parent().show();
23215    $('[data-js="edit-data"]').parent().show();
23216    $('[data-js="nav-button-login"]').hide();
23217    $('[data-js="nav-button-logout"]').show();
23218    stripe();
23219  } else {
23220    if ($('#wcmmodeedit').val() == false) $('[data-js="my-account"]').parent().hide();
23221    $('[data-js="edit-data"]').parent().hide();
23222    $('[data-js="nav-button-login"]').show();
23223    $('[data-js="nav-button-logout"]').hide();
23224    stripe();
23225  }
23226
23227  $('[data-js="nav-button-login"]').click(function (e) {
23228    e.preventDefault();
23229    if ($(e.target).data('action-url')) {
23230      $(location).attr('href', $(e.target).data('action-url'));
23231    } else {
23232      $(location).attr('href', $('#loginPage').val());
23233    }
23234  });
23235  $(window).on('resize', function () {
23236    stripe();
23237  });
23238})(jQuery);
23239'use strict';
23240
23241var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
23242
23243function _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); } }
23244
23245function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
23246
23247/**
23248 *
23249 * PASSENGER FORM
23250 *
23251 * INICIO
23252 */
23253
23254var PassengerController = function () {
23255  function PassengerController($, cartComponentRef) {
23256    _classCallCheck(this, PassengerController);
23257
23258    this.passengerQuantity = $('[data-js="passenger-quantity"]');
23259    this.blocks = $('[data-js="passenger-blocks"]');
23260    this.formData = SessionStorage.get('formData');
23261    this.mainPassenger = SessionStorage.get('passenger');
23262    this.btnSubmit = $('[data-js="btn-proceed"]');
23263    this.showSpecialService = $('[data-js="show-special-service"]').val() ? $('[data-js="show-special-service"]').val().toLowerCase() === 'true' : '';
23264    this.cartComponentRef = cartComponentRef;
23265    this.cart = cartComponentRef.cartService.cart;
23266    this.listFrequentPassengers;
23267    this.showListPassenger = $('[data-js="autocomplete-list"]').val() == 'true';
23268    this.frequentPassengerAlert = $('[data-js="frequent-passenger-alert"]');
23269    this.msgFrequentPassengerAlert = $('[data-js="msg-frequent-passenger"]');
23270    this.listTripChild;
23271    this.listPassengersToSave = [];
23272    this.frequentPassengers = [];
23273    this.cpfDiscountValue = '';
23274    this.clientId = '';
23275    this.headerBgColor = $('[data-js="headerBgColor"]').val();
23276    this.headerTextColor = $('[data-js="headerTextColor"]').val();
23277    this.shadow = $('[data-js="shadowStyle"]').val();
23278    this.shadowButton = $('[data-js="shadowButtonStyle"]').val();
23279    this.borderRadius = $('[data-js="borderRadius"]').val();
23280    this.buttonColorEnabled = $('[data-js="button-color-enabled"]').val();
23281    this.buttonTextColorEnabled = $('[data-js="button-text-color-enabled"]').val();
23282    this.buttonColorDisabled = $('[data-js="button-color-disabled"]').val();
23283    this.buttonTextColorDisabled = $('[data-js="button-text-color-disabled"]').val();
23284    //this.docTypes = $('[data-js="type-docs"]').val().toUpperCase().normalize('NFD').replace(/[\u0300-\u036f]/g, "").split(',');
23285    this.isValidDate = false;
23286    this.isAlreadyScrolled = false;
23287    this.bottomResumeCart = $('[data-js="bottom-resume-cart"]');
23288    this.init();
23289  }
23290
23291  _createClass(PassengerController, [{
23292    key: 'init',
23293    value: function init() {
23294      var _this = this;
23295
23296      if (!SessionStorage.get('cart')) {
23297        if (!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false' && $('#homePagePath') && $('#homePagePath').val()) {
23298          $(location).attr('href', $('#homePagePath').val());
23299        }
23300      }
23301
23302      if (_this.showListPassenger) {
23303        _this.getFrequentPassengers(function () {
23304          _this.passengerMethods();
23305          _this.selectPassengerComplete();
23306        })
23307      } else {
23308        _this.passengerMethods();
23309      }
23310
23311      sessionStorage.removeItem('_totalConvenienceFee');
23312
23313      if (_this.btnSubmit.prop('disabled') && _this.buttonTextColorDisabled) {
23314        _this.btnSubmit.css('color', _this.buttonTextColorDisabled);
23315        _this.btnSubmit.find('.btn-footer-text').find('style').remove();
23316        _this.btnSubmit.find('.btn-footer-text').append($('<style>.btn-footer-text:after { border-left: 15px solid ' + _this.buttonTextColorDisabled + '!important; }</style>'));
23317      }
23318
23319      this.applyButtonStyle(false);
23320    }
23321  }, {
23322    key: 'applyButtonStyle',
23323    value: function applyButtonStyle(enable) {
23324      var styles = '';
23325
23326      if (this.shadowButton) {
23327        styles += 'box-shadow: ' + this.shadowButton + ';' + '-webkit-box-shadow: ' + this.shadowButton + ';' + '-moz-box-shadow: ' + this.shadowButton + ';';
23328      }
23329
23330      if (enable) {
23331        if (this.buttonColorEnabled) {
23332          styles += 'background-color: ' + this.buttonColorEnabled + ';';
23333        }
23334
23335        if (this.buttonTextColorEnabled) {
23336          styles += 'color: ' + this.buttonTextColorEnabled;
23337        }
23338      } else {
23339        if (this.buttonColorDisabled) {
23340          styles += 'background-color: ' + this.buttonColorDisabled + ';';
23341        }
23342
23343        if (this.buttonTextColorDisabled) {
23344          styles += 'color: ' + this.buttonTextColorDisabled;
23345        }
23346      }
23347
23348      if (styles != '') {
23349        this.btnSubmit.attr('style', styles);
23350      }
23351    }
23352  }, {
23353    key: 'passengerMethods',
23354    value: function passengerMethods() {
23355      this.checkFormData();
23356      this.loadHeader();
23357      this.loadBlocks();
23358      this.handleCheckbox();
23359      this.handleSelectDocType();
23360      this.handleBirthDate();
23361      this.validateDiscount();
23362      this.listenForm();
23363      this.addPassengers();
23364      this.alignInputs();
23365      this.customConfiguration();
23366      this.validationNameRegex();
23367      this.hidePassengerList();
23368      this.listenCheckPassengerFrequent();
23369      this.resetFormStudentUncheck();
23370      this.resetBuyerCheck();
23371    }
23372  }, {
23373    key: 'hidePassengerList',
23374    value: function hidePassengerList() {
23375      $('.cart-passenger-list').hide();
23376      if (!this.cart._listOffer[0]._priceWithDiscountPix || this.cart._listOffer[0]._priceWithDiscountPix === this.cart._listOffer[0]._price) {
23377        $('p.line-discount-pix').addClass('d-none');
23378        $('[data-js="subtotal-seats-container"]').addClass('d-none');
23379        $('.summary-item').addClass('d-none');
23380        $('[data-js="subtotal-seats-container"]').addClass('d-none');
23381        $('[data-js="price-in-bottom-cart-pix"]').addClass('d-none');
23382        $('[data-js="convenience-fee-pix-container"]').addClass('d-none');
23383        $('.convenienceFee').addClass('d-none');
23384      } else {
23385        $('.summary-item').addClass('d-none');
23386        $('[data-js="price-in-bottom-cart"]').addClass('d-none');
23387      }
23388    }
23389  }, {
23390    key: 'resetBuyerCheck',
23391    value: function resetBuyerCheck() {
23392      $('[data-js="buyer-check-1"]').on('change', function () {
23393        if ($(this).prop('checked')) {
23394          $('[data-js="student-check-1"]').prop('checked', false);
23395          $('[data-js^="select-doc-type"]').prop('disabled', false);
23396          $('.select-selected').removeClass('disabled');
23397        }
23398      });
23399    }
23400  }, {
23401    key: 'resetFormStudentUncheck',
23402    value: function resetFormStudentUncheck() {
23403      $('[data-js="student-check-1"]').on('change', function () {
23404        if ($(this).prop('checked')) {
23405          $('[data-js="buyer-check-1"]').prop('checked', false);
23406          $('[data-js^="select-doc-type"]').prop('disabled', false);
23407          $('.select-selected').removeClass('disabled');
23408        }
23409      });
23410    }
23411  }, {
23412    key: 'getSpecialServices',
23413    value: function getSpecialServices(callback) {
23414      var _this2 = this;
23415
23416      var url = "/etc.clientlibs/wemobi/clientlibs/clientlib-site/resources/assets/json/special_service_mock.json";
23417      var param = { originId: this.formData.depart.origin.id };
23418
23419      $.getJSON(url + '?' + $.param(param)).then(function (data) {
23420        if (data.hasSpecialServices) _this2.listServices = data.listServices; else _this2.listServices = null;
23421
23422        callback();
23423      }).catch(function (e) {
23424        console.log(e);
23425        _this2.listServices = null;
23426        callback();
23427      });
23428    }
23429  }, {
23430    key: 'customConfiguration',
23431    value: function customConfiguration() {
23432      var _this3 = this;
23433
23434      this.assignDocument = $("[data-js='autocomplete-list']").val() == 'true';
23435      this.infoIcon = new InfoIcon($('.document-info-container'), 'active', $('[data-js="close-info-container"]'));
23436      $('[data-js="buyer-check-1"]').focus(function (e) {
23437        return CartButton.hideModal();
23438      });
23439      $('.footer-content-desktop').find('.links').find('a').focus(function () {
23440        return _this3.infoIcon.close();
23441      });
23442      this.selectCustom = new SelectCustom($);
23443    }
23444  }, {
23445    key: 'validateName',
23446    value: function validateName($el) {
23447      var name = $el.trim();
23448      var nameSplit = name.split(' ');
23449      var nameLength = nameSplit.length;
23450      var isLastName = nameLength > 1;
23451
23452      if (name != '') if (isLastName) return true;
23453
23454      return false;
23455    }
23456  }, {
23457    key: 'validateDate',
23458    value: function validateDate(dateString) {
23459      var datePattern = /^\d{2}\/\d{2}\/\d{4}$/;
23460      if (!datePattern.test(dateString)) {
23461        return false;
23462      }
23463
23464      var _dateString$split$map = dateString.split('/').map(Number),
23465        _dateString$split$map2 = _slicedToArray(_dateString$split$map, 3),
23466        day = _dateString$split$map2[0],
23467        month = _dateString$split$map2[1],
23468        year = _dateString$split$map2[2];
23469
23470      var date = new Date(year, month - 1, day);
23471
23472      if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
23473        return false;
23474      }
23475
23476      var currentYear = new Date().getFullYear();
23477      if (year < 1900 || year > currentYear) {
23478        return false;
23479      }
23480
23481      var today = new Date();
23482      if (date > today) {
23483        return false;
23484      }
23485
23486      return true;
23487    }
23488  }, {
23489    key: 'showDateErrorMessage',
23490    value: function showDateErrorMessage(input, message) {
23491      var errorMessage = $('<span>').addClass('error-message').text(message).attr('data-js', 'invalid-date');
23492      input.next('.error-message').remove();
23493      input.after(errorMessage);
23494    }
23495  }, {
23496    key: 'removeDateErrorMessage',
23497    value: function removeDateErrorMessage(input) {
23498      input.next('.error-message').remove();
23499    }
23500  }, {
23501    key: 'validationNameRegex',
23502    value: function validationNameRegex() {
23503      var regex = /[^a-zA-Z\u00C0-\u00FF ]+/ig;
23504      var name = $('.input-name');
23505
23506      name.on("input", function () {
23507        $(this).val($(this).val().replace(regex, ''));
23508      });
23509    }
23510  }, {
23511    key: 'addPassengers',
23512    value: function addPassengers() {
23513      var passengersQty = this.cart.listPassengers.length;
23514      this.cartComponentRef.cartService.clearPassengers();
23515      this.cartComponentRef.cartService.addPassengers(passengersQty);
23516    }
23517  }, {
23518    key: 'checkFormData',
23519    value: function checkFormData() {
23520      if (!this.formData) {
23521        if ($('#homePagePath') && $('#homePagePath').val()) $(location).attr('href', $('#homePagePath').val());
23522      }
23523    }
23524  }, {
23525    key: 'loadHeader',
23526    value: function loadHeader() {
23527      var passengers = Utils.getPassengersQuantity(this.formData.passengers);
23528      this.passengerQuantity.text(passengers.toString().concat(passengers === 1 ? ' ' + 'Passageiro' + '.' : ' ' + 'Passageiros' + '.'));
23529
23530      if (passengers < 2) {
23531        $('[data-js="passenger-header-quantity-subtitle"]').text('Para prosseguir com a compra, identifique o passageiro abaixo:');
23532      } else {
23533        $('[data-js="passenger-header-quantity-subtitle"]').text('Para prosseguir com a compra, identifique os passageiros abaixo:');
23534      }
23535    }
23536  }, {
23537    key: 'disableSubmitIfAttendingNotSelected',
23538    value: function disableSubmitIfAttendingNotSelected(blockId, elseFunction) {
23539      var specialCheck = $('[data-js="special-check-' + blockId + '"]');
23540      var serviceType = $('[data-js="input-service-type-' + blockId + '"]');
23541
23542      if (specialCheck.is(':checked') && serviceType.val() === $('#pattern-service-name').val()) this.disableSubmit(); else {
23543        if (elseFunction) elseFunction();
23544      }
23545    }
23546  }, {
23547    key: 'isSpecialChecked',
23548    value: function isSpecialChecked() {
23549      var enableSubmit = [];
23550      var amountPassengers = Utils.getPassengersQuantity(this.formData.passengers);
23551
23552      for (var i = 1; i <= amountPassengers; i++) {
23553        var otherSpecialCheck = $('[data-js="special-check-' + i + '"]');
23554        var otherServiceType = $('[data-js="input-service-type-' + i + '"]');
23555
23556        if (!otherSpecialCheck.is(':checked') || otherSpecialCheck.is(':checked') && otherServiceType.val() !== $('#pattern-service-name').val()) enableSubmit.push(true);
23557      }
23558
23559      if (enableSubmit.length === amountPassengers) return true;
23560
23561      return false;
23562    }
23563  }, {
23564    key: 'handleServiceTypeCheckBox',
23565    value: function handleServiceTypeCheckBox(blockId) {
23566      var _this4 = this;
23567
23568      var specialCheck = $('[data-js="special-check-' + blockId + '"]');
23569      var serviceType = $('[data-js="input-service-type-' + blockId + '"]');
23570      var inputDocument = $('[data-js="input-doc-' + blockId + '"]');
23571      var inputName = $('[data-js="input-name-' + blockId + '"]');
23572
23573      specialCheck.on('change', function (e) {
23574        if ($(e.target).is(':checked')) {
23575          serviceType.removeAttr('disabled');
23576          serviceType.next().removeClass('disabled');
23577          serviceType.parent().addClass('active');
23578          _this4.disableSubmitIfAttendingNotSelected(blockId);
23579        } else {
23580          serviceType.parent().find('.select-items').children().first().find('a').click();
23581          serviceType.attr('disabled', 'disabled');
23582          serviceType.next().addClass('disabled');
23583          serviceType.parent().removeClass('active');
23584          if (_this4.isSpecialChecked()) {
23585            var validateInputDoc = _this4.validateInputDoc(inputDocument);
23586
23587            if (_this4.isFormValid() && validateInputDoc) _this4.enableSubmit();
23588          }
23589        }
23590      });
23591
23592      serviceType.on('change', function (e) {
23593        _this4.disableSubmitIfAttendingNotSelected(blockId, function () {
23594          if (_this4.isSpecialChecked()) {
23595            var validateInputDoc = _this4.validateInputDoc(inputDocument);
23596            var validateName = _this4.validateName($(inputName).val());
23597
23598            if (_this4.isFormValid() && validateInputDoc && validateName) _this4.enableSubmit();
23599          }
23600        });
23601      });
23602    }
23603  }, {
23604    key: 'formatDateToDDMMYYYY',
23605    value: function formatDateToDDMMYYYY(dateString) {
23606      var _dateString$split = dateString.split('-'),
23607        _dateString$split2 = _slicedToArray(_dateString$split, 3),
23608        year = _dateString$split2[0],
23609        month = _dateString$split2[1],
23610        day = _dateString$split2[2];
23611
23612      return day + '/' + month + '/' + year;
23613    }
23614  }, {
23615    key: 'handleBuyerCheckbox',
23616    value: function handleBuyerCheckbox(blockId) {
23617      var _this5 = this;
23618
23619      var main_passenger = this.mainPassenger;
23620      var buyerCheck = $('[data-js="buyer-check-' + blockId + '"]');
23621      var inputName = $('[data-js="input-name-' + blockId + '"]');
23622      var inputDocument = $('[data-js="input-doc-' + blockId + '"]');
23623      var inputBirthDate = $('[data-js="input-birth-' + blockId + '"]');
23624      var name = main_passenger._name;
23625
23626      var studentCheck = buyerCheck.parent().parent().parent().children().find('.student');
23627      var selectType = $('[data-js="input-person-type-' + blockId + '"]');
23628      var inputCpf = $('[data-js="input-cpf-' + blockId + '"]');
23629      var msgElem = $('[data-js="validation-msg-discount-' + blockId + '"]');
23630      var selectDoc = $('[data-js="select-doc-type-' + blockId + '"]');
23631
23632      if (blockId === 1) {
23633        buyerCheck.on('change', function (e) {
23634          if (buyerCheck.is(':checked')) {
23635            inputName.val(name);
23636            inputBirthDate.val(_this5.formatDateToDDMMYYYY(main_passenger._birthDate));
23637
23638            if (_this5.assignDocument == true) {
23639              inputDocument.val(main_passenger._cpf ? main_passenger._cpf : main_passenger._passport ? main_passenger._passport : main_passenger._cnpj);
23640
23641              if (main_passenger._cnpj) {
23642                _this5.selectCustom.selectDefault(selectDoc, 'CNPJ');
23643              }
23644
23645              if (main_passenger._cpf) {
23646                _this5.selectCustom.selectDefault(selectDoc, 'CPF');
23647              }
23648
23649              if (main_passenger._passport) {
23650                _this5.selectCustom.selectDefault(selectDoc, 'PASSAPORTE');
23651              }
23652            }
23653
23654            $('#validation-block-' + blockId).fadeOut('fast', function () {
23655              inputCpf.val('');
23656              inputName.attr('disabled', false);
23657              inputBirthDate.attr('disabled', false);
23658              studentCheck.prop('checked', false);
23659              selectType.next().text(i18n('select_document'));
23660              selectType.val(null);
23661              _this5.openValidation(msgElem, false, '');
23662              _this5.cart.listPassengers[blockId - 1].hasDiscount = false;
23663              _this5.cart.listPassengers[blockId - 1].cpf = null;
23664            });
23665            if (_this5.isFormValid() && _this5.isSpecialChecked()) {
23666              _this5.enableSubmit();
23667            }
23668          } else {
23669            if (!_this5.cart.listPassengers[blockId - 1].hasDiscount) {
23670              inputName.val('');
23671              inputBirthDate.val('');
23672              inputDocument.val('').attr('disabled', true);
23673              _this5.selectCustom.refreshSelect(selectDoc);
23674              _this5.disableSubmit();
23675            }
23676          }
23677        });
23678      }
23679    }
23680  }, {
23681    key: 'handleCheckbox',
23682    value: function handleCheckbox() {
23683      var _this6 = this;
23684
23685      var passengers = Utils.getPassengersQuantity(this.formData.passengers);
23686
23687      for (var i = 1; i <= passengers; i++) {
23688        this.handleServiceTypeCheckBox(i);
23689        this.handleBuyerCheckbox(i);
23690      }
23691
23692      this.blocks.on('click', '.student', function (e) {
23693        var studentCheck = e.target;
23694        var blockId = e.target.id.replace(/\D/g, '');
23695        var inputName = $('[data-js="input-name-' + blockId + '"]');
23696        var inputDocument = $('[data-js="input-doc-' + blockId + '"]');
23697        var inputCpf = $('[data-js="input-cpf-' + blockId + '"]');
23698        var msgElem = $('[data-js="validation-msg-discount-' + blockId + '"]');
23699        var selectType = $('[data-js="input-person-type-' + blockId + '"]');
23700        var buyerCheck = $('[data-js="buyer-check-' + blockId + '"]');
23701        var inputBirth = $('[data-js^="input-birth"]');
23702
23703        if ($(studentCheck).is(':checked')) {
23704          $('#validation-block-' + blockId).fadeIn('fast');
23705          var labelStudent = $('[data-js="label-student"]');
23706          var labelCpf = $('[data-js="label-cpf"]');
23707          if (labelStudent.height() > labelCpf.height()) {
23708            labelCpf.height(labelStudent.height() - 2);
23709          }
23710        } else {
23711          $('#validation-block-' + blockId).fadeOut('fast', function () {
23712            inputDocument.val('');
23713            inputDocument.attr('disabled', false);
23714            inputName.val('');
23715            inputName.attr('disabled', false);
23716            inputCpf.val('');
23717            inputBirth.val('');
23718            buyerCheck.prop('checked', false);
23719            _this6.disableSubmit();
23720            selectType.next().text('SELECIONE');
23721            selectType.val(null);
23722            _this6.openValidation(msgElem, false, '');
23723          });
23724        }
23725      });
23726    }
23727  }, {
23728    key: 'handleSelectDocType',
23729    value: function handleSelectDocType() {
23730      var _this7 = this;
23731
23732      $('[data-js^="select-doc-type"]').change(function (e) {
23733        var index = $(e.currentTarget).data('js').replace(/\D/g, '');
23734        if (_this7.cpfDiscountValue !== '' && $('#input-doc-' + index).val() !== '' && _this7.cpfDiscountValue == $('#input-doc-' + index).val()) {
23735          $('#input-doc-' + index).prop('disabled', true);
23736          $('[data-js^="select-doc-type"]').prop('disabled', true);
23737          $('.select-selected').addClass('disabled');
23738        } else {
23739          $('#input-doc-' + index).prop('disabled', false);
23740          $('[data-js^="select-doc-type"]').prop('disabled', false);
23741          $('.select-selected').removeClass('disabled');
23742        }
23743        var selectedType = $(e.currentTarget).val();
23744        var inputName = $('[data-js^="input-name"]');
23745        var inputClicked = false;
23746        var cpfInput = $('[data-js="input-doc-' + index + '"]');
23747        var cpfInputs = $('[data-js^="input-doc-"]');
23748
23749        var showErrorMessage = function showErrorMessage() {
23750          var selectDocType = $('[data-js="select-doc-type-' + index + '"]').val();
23751          var cpf = cpfInput.val().replace(/\D/g, '');
23752
23753          if (selectDocType === 'CPF' && inputClicked) {
23754            if (cpf.length === 0) {
23755              var errorMessage = $('<span>').addClass('error-message').text($('[data-js="req-doc-alert-message"]').val());
23756              cpfInput.next('.error-message').remove();
23757              cpfInput.after(errorMessage);
23758              _this7.disableSubmit();
23759            } else if (cpf.length !== 11 || !Utils.validateCPF(Utils.replaceToNumbers(cpf))) {
23760              var _errorMessage = $('<span>').addClass('error-message').text($('[data-js="doc-alert-message"]').val()).attr('data-js', 'invalid-cpf');
23761              cpfInput.next('.error-message').remove();
23762              cpfInput.after(_errorMessage);
23763              _this7.disableSubmit();
23764            } else {
23765              cpfInput.next('.error-message').remove();
23766            }
23767          }
23768        };
23769
23770        cpfInput.on('click', function () {
23771          inputClicked = true;
23772        });
23773
23774        cpfInput.on('focus', function () {
23775          inputClicked = true;
23776        });
23777
23778        cpfInput.on('blur', function () {
23779          showErrorMessage();
23780        });
23781
23782        if (selectedType === 'CPF') {
23783          cpfInput.mask('00000000000');
23784          cpfInput.trigger('input');
23785          cpfInput.blur();
23786          cpfInput.on('input', function () {
23787            _this7.disableSubmit;
23788            showErrorMessage();
23789          });
23790        } else {
23791          cpfInput.unmask();
23792          cpfInput.off('input');
23793          $('.cpf-error-message').remove();
23794        }
23795
23796        if (selectedType === 'CPF') {
23797          var isInputNameModified = false;
23798          inputName.on('blur', function () {
23799            isInputNameModified = true;
23800            cpfInput.trigger('blur');
23801          });
23802        }
23803
23804        $('[data-js="buyer-check-1"]').change(function () {
23805          if ($('[data-js="buyer-check-1"]').is(':checked')) {
23806            $('[data-js="input-doc-1"]').next('.cpf-error-message').remove();
23807            cpfInput.trigger('blur');
23808          } else {
23809            $('[data-js="input-doc-1"]').next('.cpf-error-message').remove();
23810            cpfInput.trigger('blur');
23811          }
23812        });
23813
23814        var checkAllCPFsValid = function checkAllCPFsValid() {
23815          var allCPFsValid = true;
23816          cpfInputs.each(function (i, input) {
23817            var cpf = $(input).val().replace(/\D/g, '');
23818            if (selectedType === 'CPF' && (cpf.length !== 11 || !Utils.validateCPF(Utils.replaceToNumbers(cpf)))) {
23819              allCPFsValid = false;
23820              return false;
23821            }
23822          });
23823
23824          if (allCPFsValid) {
23825            _this7.enableSubmit();
23826          } else {
23827            _this7.disableSubmit();
23828          }
23829        };
23830
23831        cpfInputs.on('input', function () {
23832          showErrorMessage();
23833          checkAllCPFsValid();
23834        });
23835        checkAllCPFsValid();
23836      });
23837    }
23838  }, {
23839    key: 'cpfIsValid',
23840    value: function cpfIsValid() {
23841      var messageCpfInvalid = $('[data-js="invalid-cpf"]').text();
23842      if (messageCpfInvalid.length > 0) {
23843        return false;
23844      }
23845    }
23846  }, {
23847    key: 'validateDiscount',
23848    value: function validateDiscount() {
23849      var _this7 = this;
23850
23851      var cpf = $('.input-cpf');
23852
23853      cpf.on('input', function (e) {
23854        var parent = $(e.target).closest('.passenger-block');
23855        var blockId = parseInt(parent.attr('id').replace(/\D/g, ''));
23856        var inputDocument = parent.find('.input-doc');
23857        var inputName = parent.find('.input-name');
23858        var validBtn = parent.find('.validation-btn');
23859        var inputPersonType = parent.find('[data-js="input-person-type-' + blockId + '"]');
23860        var inputVal = $(e.target).val().trim();
23861
23862        if (inputVal === '') {
23863          _this7.cart.listPassengers[blockId - 1].hasDiscount = false;
23864          _this7.cart.listPassengers[blockId - 1].cpf = null;
23865          inputDocument.val('');
23866          inputDocument.attr('disabled', false);
23867          inputName.val('');
23868          inputName.attr('disabled', false);
23869          _this7.disableSubmit();
23870        }
23871
23872        if (inputVal.length < 14) validBtn.attr('disabled', true); else {
23873          if (inputPersonType.val() && inputVal.length == 14) validBtn.attr('disabled', false);
23874        }
23875      });
23876
23877      this.blocks.on('click', '.validation-btn', function (e) {
23878        var main_passenger = _this7.mainPassenger;
23879        var blockId = e.target.id.replace(/\D/g, '');
23880        var person = $('[data-js="input-person-type-' + blockId + '"]');
23881        var cpf = $('[data-js="input-cpf-' + blockId + '"]');
23882        var inputName = $('[data-js="input-name-' + blockId + '"]');
23883        var inputDocument = $('[data-js="input-doc-' + blockId + '"]');
23884        var msgElem = $('[data-js="validation-msg-discount-' + blockId + '"]');
23885        var inputBirthDate = $('[data-js="input-birth-' + blockId + '"]');
23886        var cpfValue = cpf.val().replace(/\D/g, '');
23887        var serviceId = _this7.cart.listOffer[0].service;
23888        var group = _this7.cart.listOffer[0].group;
23889        var origin = _this7.cart.listOffer[0].company.origin._id;
23890        var destination = _this7.cart.listOffer[0].company.destination._id;
23891        var departDate = _this7.formData.depart.date;
23892        var companyId = _this7.cart.listOffer[0].company.companyId;
23893        var routeId = _this7.cart.listOffer[0].routeId;
23894
23895        if (person.val() && cpfValue.length === 11) {
23896          _this7.cart.listPassengers[blockId - 1].hasDiscount = false;
23897          _this7.cart.listPassengers[blockId - 1].cpf = null;
23898
23899          if (_this7.isNewCpfValue(cpfValue, blockId - 1)) {
23900            LoaderService.show();
23901            cpf.removeClass('invalid');
23902
23903            var body = {
23904              "origin": origin,
23905              "destination": destination,
23906              "date": departDate,
23907              "service": serviceId,
23908              "route": routeId,
23909              "company": companyId,
23910              "document": cpfValue
23911            };
23912
23913            HttpService.post('validateStudent', body).then(function (data) {
23914              LoaderService.hide();
23915              var studentData = {
23916                clientId: data.result.clientId,
23917                names: data.result.name,
23918                document: +data.result.document
23919              };
23920
23921              var allStudentData = SessionStorage.get('allStudentData') || [];
23922              var existingStudentIndex = allStudentData.findIndex(function (data) {
23923                return data.document === studentData.document;
23924              });
23925
23926              if (existingStudentIndex !== -1) {
23927                allStudentData[existingStudentIndex] = studentData;
23928              } else {
23929                allStudentData.push(studentData);
23930              }
23931
23932              SessionStorage.set('allStudentData', allStudentData);
23933
23934              var names = data.result.name;
23935              if (names == null) {
23936                cpf.addClass('invalid');
23937                _this7.openValidation(msgElem, false, 'O CPF informado não consta em nosso sistema. Insira um número válido ou pule esta etapa.');
23938              } else {
23939                var selectDoc = $('[data-js="select-doc-type-1"]');
23940                _this7.cart.listPassengers[blockId - 1].hasDiscount = true;
23941                _this7.cart.listPassengers[blockId - 1].cpf = +data.result.document;
23942                inputDocument.val(cpfValue);
23943                _this7.cpfDiscountValue = cpfValue;
23944                inputName.val(names);
23945                _this7.selectCustom.selectDefault(selectDoc, 'CPF');
23946                inputName.attr('disabled', true);
23947                inputDocument.attr('disabled', true);
23948                inputDocument.trigger('input');
23949                _this7.openValidation(msgElem, true, 'CPF VALIDADO COM SUCESSO!! Confira o desconto na página de pagamento.');
23950              }
23951              if (studentData.document && main_passenger._documentNumber && main_passenger._birthDate) {
23952                var studentDoc = +studentData.document;
23953                var mainPassengerDoc = +main_passenger._documentNumber;
23954
23955                if (studentDoc === mainPassengerDoc) {
23956                  inputBirthDate.val(_this7.formatDateToDDMMYYYY(main_passenger._birthDate));
23957                  _this7.enableSubmit();
23958                }
23959              }
23960            }).catch(function () {
23961              LoaderService.hide();
23962              cpf.addClass('invalid');
23963              _this7.openValidation(msgElem, false, $('[data-js="doc-alert-message-estudante-professor"]').val());
23964            });
23965          } else {
23966            cpf.addClass('invalid');
23967            _this7.openValidation(msgElem, false, 'O CPF informado já foi validado. Insira outro número válido ou pule esta etapa.');
23968          }
23969        }
23970      });
23971    }
23972  }, {
23973    key: 'isNewCpfValue',
23974    value: function isNewCpfValue(cpf, blockIdx) {
23975      var result = true;
23976      $.each(this.cart.listPassengers, function (idx, el) {
23977        if (el.cpf === cpf && idx !== blockIdx) result = false;
23978      });
23979      return result;
23980    }
23981  }, {
23982    key: 'parseObjectDiscount',
23983    value: function parseObjectDiscount(person, cpf) {
23984      return {
23985        person: person,
23986        cpf: cpf
23987      };
23988    }
23989  }, {
23990    key: 'alignInputs',
23991    value: function alignInputs() {
23992      var labelStudent = $('[data-js="label-student"]');
23993      var labelCpf = $('[data-js="label-cpf"]');
23994      var labelCpfOrigHeight = labelCpf.height();
23995
23996      $(window).on('resize', function () {
23997        if (labelStudent.height() > labelCpf.height()) {
23998          labelCpf.height(labelStudent.height() - 2);
23999        } else {
24000          labelCpf.height(labelCpfOrigHeight);
24001        }
24002      });
24003    }
24004  }, {
24005    key: 'listenForm',
24006    value: function listenForm() {
24007      var _this9 = this;
24008
24009      this.blocks.find('input[required]').on('input', function (e) {
24010        if (_this9.isInputDocValid(e) && _this9.isSpecialChecked() && _this9.isFormValid() && _this9.cpfIsValid()) {
24011          _this9.enableSubmit();
24012        } else {
24013          _this9.disableSubmit();
24014        }
24015      });
24016
24017      $('[data-js^="input-birth-child"]').on('change', function (e) {
24018        var dateString = DateFormatter.reverseDate($(e.currentTarget).val());
24019        _this9.isDateValid(dateString, $(e.currentTarget));
24020      });
24021
24022      $('[data-js^="input-birth"]').on('change focusout', function (e) {
24023        var dateInput = $(e.target);
24024        var dateValue = dateInput.val();
24025        if (!_this9.validateDate(dateValue)) {
24026          dateInput.addClass('invalid');
24027          _this9.showDateErrorMessage(dateInput, 'Data inválida');
24028          _this9.disableSubmit();
24029        } else {
24030          dateInput.removeClass('invalid');
24031          _this9.removeDateErrorMessage(dateInput);
24032          _this9.enableSubmit();
24033        }
24034      });
24035
24036      $('[data-js^="input-name"]').on('change focusout', function (e) {
24037        if (!_this9.validateName($(e.target).val())) {
24038          $(e.target).addClass('invalid');
24039          _this9.disableSubmit();
24040        } else $(e.target).removeClass('invalid');
24041      });
24042
24043      $('[data-js^="input-name"]').on('click focus', function (e) {
24044        $(e.target).removeClass('invalid');
24045        if ($(e.target).attr('data-js') == 'input-name-1') if ($('[data-js="buyer-check-1"]').is(':checked')) {
24046          $('[data-js="buyer-check-1"]').trigger('click');
24047        }
24048      });
24049
24050      $('[data-js^="select-doc-type"]').on('change', function (e) {
24051        $(e.target).removeClass('invalid');
24052      });
24053
24054      $('[data-js="buyer-check-1"]').on('click', function (e) {
24055        $(e.target).is(':checked') ? $('[data-js="save-passenger-1"]').parent().addClass('d-none') : $('[data-js="save-passenger-1"]').parent().removeClass('d-none');
24056        $('[data-js="input-name-1"]').removeClass('invalid');
24057      });
24058
24059      $('[data-js="close-msg-frequent-passenger"]').off('click').on('click', function () {
24060        _this9.hideFrequentPassengerAlert();
24061      });
24062
24063      this.validationNameRegex();
24064    }
24065  }, {
24066    key: 'isInputDocValid',
24067    value: function isInputDocValid(e) {
24068      if ($(e.target).hasClass('input-doc')) {
24069        var val = $(e.target).val();
24070        $(e.target).val(val.replace(/[ @#$%¨&*()\-=_+{}\[\].,;//?°\\!'"]/g, ''));
24071        return this.validateInputDoc($(e.target));
24072      } else {
24073        var inputDoc = $(e.target).closest('.row').find('.input-doc');
24074        return this.validateInputDoc(inputDoc);
24075      }
24076    }
24077  }, {
24078    key: 'allNamesValid',
24079    value: function allNamesValid() {
24080      var _this9 = this;
24081
24082      var allValid = true;
24083      $('[data-js^="input-name"]').each(function (_, element) {
24084        if (!_this9.validateName($(element).val())) {
24085          allValid = false;
24086          return allValid;
24087        }
24088      });
24089
24090      return allValid;
24091    }
24092  }, {
24093    key: 'allDocsValid',
24094    value: function allDocsValid() {
24095      var _this10 = this;
24096
24097      var allValid = true;
24098      $('[data-js^="input-doc"]').each(function (_, element) {
24099
24100        if (!_this10.validateInputDoc($(element))) {
24101          allValid = false;
24102          return allValid;
24103        }
24104      });
24105
24106      return allValid;
24107    }
24108  }, {
24109    key: 'allBirthDatesValid',
24110    value: function allBirthDatesValid() {
24111      var _this11 = this;
24112
24113      var allValid = true;
24114
24115      $('[data-js^="input-birth-child"]').each(function (_, element) {
24116        var dateString = DateFormatter.reverseDate($(element).val());
24117        if (!_this11.isDateValid(dateString, element)) {
24118          allValid = false;
24119          return;
24120        }
24121      });
24122
24123      $('[data-js^="input-birth"]').each(function (_, element) {
24124        var dateInput = $(element).val();
24125        if (!_this11.validateDate(dateInput)) {
24126          allValid = false;
24127          return;
24128        }
24129      });
24130
24131      return allValid;
24132    }
24133  }, {
24134    key: 'handleBirthDate',
24135    value: function handleBirthDate() {
24136      $('[data-js^="input-birth-child"]').mask("00/00/0000");
24137      $('[data-js^="input-birth"]').mask("00/00/0000");
24138    }
24139  }, {
24140    key: 'disableSubmit',
24141    value: function disableSubmit() {
24142      this.btnSubmit.off('click');
24143      this.btnSubmit.prop('disabled', true);
24144      this.applyButtonStyle(false);
24145    }
24146  }, {
24147    key: 'enableSubmit',
24148    value: function enableSubmit() {
24149      if (this.allBirthDatesValid() && this.allNamesValid() && this.allDocsValid()) {
24150        this.btnSubmit.prop('disabled', false);
24151		this.scrollToSubmitButton();
24152        this.applyButtonStyle(true);
24153
24154        this.submitForm();
24155      }
24156    }
24157  }, {
24158    key: 'scrollToSubmitButton',
24159    value: function scrollToSubmitButton() {
24160      if (!this.isAlreadyScrolled) {
24161        this.isAlreadyScrolled = true;
24162        var elementsHeight = this.btnSubmit.outerHeight() + (this.bottomResumeCart.outerHeight() || 0) + 25;
24163        $("html, body").animate({ scrollTop: this.btnSubmit.offset().top - $(window).height() + elementsHeight }, 500);
24164      }
24165    }
24166  }, {
24167    key: 'isDateValid',
24168    value: function isDateValid(dateString, element) {
24169      if (dateString.length < 10) return false;
24170
24171      var childDataValidationMessage = $('[data-js="child-data-validation-message"]').val();
24172      var validationOfFutureDates = $('[data-js="validation-of-future-dates"]').val();
24173      var validationOfInvalidFormatDates = $('[data-js="validation-of-invalid-format-dates"]').val();
24174
24175      childDataValidationMessage = (childDataValidationMessage && childDataValidationMessage != '') ? childDataValidationMessage : 'A idade da criança é maior que 5 anos.';
24176      validationOfFutureDates = (validationOfFutureDates && validationOfFutureDates != '') ? validationOfFutureDates : 'Datas futuras não são válidas.';
24177      validationOfInvalidFormatDates = (validationOfInvalidFormatDates && validationOfInvalidFormatDates != '') ? validationOfInvalidFormatDates : 'Datas de formato inválido.';
24178
24179      var index = $(element).data('js').replace(/\D/g, '');
24180      var validationMsg = $('#birth-msg-validation-' + index);
24181      var inputBirth = $('#input-birth-child-' + index + '');
24182      var msgWarning = $('#msg-warning' + index + '');
24183      var dateTrip = this.cart._listOffer[0]._company._departureDate;
24184      var currentDate = new Date(dateTrip);
24185      var maxYear = currentDate.getFullYear() - 6;
24186      var birthDate = new Date(dateString);
24187      currentDate.setFullYear(maxYear);
24188      var maxBirthYear = currentDate.getTime();
24189
24190      if (maxBirthYear > birthDate.getTime()) {
24191        validationMsg.addClass('active');
24192        msgWarning.text(i18n('birth_child_invalid'));
24193        inputBirth.addClass('active');
24194        return false;
24195      } else if (birthDate.getTime() > new Date().getTime()) {
24196        validationMsg.addClass('active');
24197        msgWarning.text(validationOfFutureDates);
24198        inputBirth.addClass('active');
24199        return false;
24200      } else if (birthDate == 'Invalid Date') {
24201        validationMsg.addClass('active');
24202        msgWarning.text(validationOfInvalidFormatDates);
24203        inputBirth.addClass('active');
24204        return false;
24205      } else {
24206        validationMsg.removeClass('active');
24207        inputBirth.removeClass('active');
24208        return true;
24209      }
24210    }
24211  }, {
24212    key: 'submitForm',
24213    value: function submitForm() {
24214      var _this12 = this;
24215
24216      $('[data-js="btn-proceed"]').unbind('click');
24217      $('[data-js="btn-proceed"]').click(function (e) {
24218        var passengers = [];
24219        var cart = SessionStorage.get('cart');
24220        var qttChildTrip = _this12.formData.passengers[2].quantity;
24221        var totalPassengersTrip = cart._listPassengers.length;
24222        var childInitialIndex = totalPassengersTrip - qttChildTrip;
24223
24224        _this12.blocks.find('.passenger-block').each(function (index) {
24225          index++;
24226          var name = $('[data-js="input-name-' + index + '"]').val();
24227          var birthChild = $('[data-js="input-birth-child-' + index + '"]').val() ? $('[data-js="input-birth-child-' + index + '"]').val() : null;
24228          var birth = $('[data-js="input-birth-' + index + '"]').val() ? Utils.formatDateToISO($('[data-js="input-birth-' + index + '"]').val()) : birthChild;
24229          var doc = $('[data-js="input-doc-' + index + '"]').val();
24230          var type = $('[data-passenger-type-' + index + ']').data('passengerType-' + index + '');
24231          var specialService = $('[data-js="input-service-type-' + index + '"]').val();
24232          var cpf = _this12.cart.listPassengers[index - 1].cpf;
24233          var hasDiscount = _this12.cart.listPassengers[index - 1].hasDiscount;
24234          var child = null;
24235
24236          if (type === 'ADULT') {
24237            child = _this12.parseObjectChild(++childInitialIndex);
24238          }
24239
24240          passengers.push(_this12.parseObjectPassenger(name, doc, birth, type, cpf, hasDiscount, specialService, child));
24241        });
24242
24243        _this12.cartComponentRef.cartService.clearPassengers();
24244        _this12.cartComponentRef.cartService.addPassengers(passengers);
24245        SessionStorage.set('cart', _this12.cartComponentRef.cartService.cart);
24246
24247        // Analytics
24248        data_layer.page.pageInfo.paymentFlow.paymentFlowChanged = true;
24249        _this12.sendPassengerToSave();
24250      });
24251    }
24252  }, {
24253    key: 'sendPassengerToSave',
24254    value: function sendPassengerToSave() {
24255      var _this13 = this;
24256
24257      var $savePassengerCheckboxList = $('[data-js^="save-passenger"]');
24258      var isErrSaveSomePassenger = [];
24259
24260      $savePassengerCheckboxList.each(function (_, el) {
24261        if ($(el).is(':checked:visible')) {
24262          var index = $(el).attr('data-js').replace(/\D/g, '');
24263          isErrSaveSomePassenger.push(_this13.savePassengerFrequent(index));
24264        }
24265      });
24266
24267      Promise.all(isErrSaveSomePassenger).then(function (data) {
24268        var noExistError = data.filter(function (el) {
24269          return el == false;
24270        });
24271
24272        _this13.redirectPage(noExistError);
24273      }).catch(function (err) {
24274        console.error(err);
24275      });
24276    }
24277  }, {
24278    key: 'redirectPage',
24279    value: function redirectPage(noExistError) {
24280      if (noExistError.length < 1) setTimeout(function () {
24281        $(location).attr('href', $('#seatReservationPath').val());
24282      }, 1500);
24283    }
24284  }, {
24285    key: 'parseObjectChild',
24286    value: function parseObjectChild(index) {
24287      var passengerBlockChild = $('#passenger-block-' + index + '');
24288
24289      if (!passengerBlockChild[0]) {
24290        return null;
24291      }
24292
24293      return {
24294        "birthday": DateFormatter.reverseDate($('#input-birth-child-' + index + '').val()),
24295        "documentType": $('[data-js="select-doc-type-' + index + '"]').val(),
24296        "document": $('#input-doc-' + index + '').val(),
24297        "name": $('#input-name-' + index + '').val()
24298      };
24299    }
24300  }, {
24301    key: 'parseObjectPassenger',
24302    value: function parseObjectPassenger(name, doc, birth, type, cpf, hasDiscount, specialService, child) {
24303      return {
24304        "name": Utils.capitalize(name),
24305        "doc": doc,
24306        "birthDate": DateFormatter.reverseDate(birth),
24307        "type": type,
24308        "cpf": cpf,
24309        "hasDiscount": hasDiscount,
24310        "specialService": specialService ? specialService : "NORMAL",
24311        "child": child
24312      };
24313    }
24314  }, {
24315    key: 'hasDuplicateDoc',
24316    value: function hasDuplicateDoc($list, $el) {
24317      var flag = false;
24318      var doc = $el.val();
24319
24320      $list.each(function (i, value) {
24321        if (!$(value).is($el)) {
24322          if ($list.length > 0 && doc === $(value).val()) {
24323            flag = true;
24324            return;
24325          }
24326        }
24327      });
24328
24329      return flag;
24330    }
24331  }, {
24332    key: 'validateInputDoc',
24333    value: function validateInputDoc($el) {
24334      var result = true;
24335      var openValidation = this.openValidation;
24336      var hasDuplicateDoc = this.hasDuplicateDoc;
24337      var inputList = this.blocks.find('.input-doc');
24338      var msgElem = $el.closest('.container').find('.validation-msg-input');
24339      var regex = new RegExp(/^[a-zA-Z0-9]{4,}$/gm);
24340      var formattedValue = $el.val().replace(/\W/g, '');
24341
24342      if (regex.test(formattedValue)) {
24343        if (!hasDuplicateDoc(inputList, $el)) {
24344          $el.removeClass('invalid');
24345          openValidation(msgElem, false, '');
24346        } else {
24347          $el.addClass('invalid');
24348          result = false;
24349          openValidation(msgElem, false, i18n('document_used'));
24350        }
24351      } else {
24352        result = false;
24353      }
24354
24355      return result;
24356    }
24357  }, {
24358    key: 'isFormValid',
24359    value: function isFormValid() {
24360      var allFieldsValid = true;
24361      this.blocks.find('input[required]').each(function () {
24362        switch ($(this).hasClass()) {
24363          case 'input-name':
24364            allFieldsValid = $(this).val() ? this.validateName($(this)) : false;
24365            break;
24366          case 'input-doc':
24367            allFieldsValid = $(this).val() ? this.validateDocumentNumber($(this)) : false;
24368            break;
24369          default:
24370            break;
24371        }
24372
24373        if (!allFieldsValid) return false;
24374      });
24375
24376      return allFieldsValid;
24377    }
24378  }, {
24379    key: 'openValidation',
24380    value: function openValidation(msgElem, result, text) {
24381      if (result) {
24382        msgElem.removeClass('error');
24383        msgElem.html(text);
24384      } else {
24385        msgElem.addClass('error');
24386        msgElem.html(text);
24387      }
24388    }
24389  }, {
24390    key: 'getFrequentPassengers',
24391    value: function getFrequentPassengers(callback) {
24392      var _this14 = this;
24393
24394      var headers = { 'Authorization': '' + SessionStorage.get('jca_token') };
24395      var autocompleteList = void 0;
24396
24397      HttpService.get('returnfrequentpassengers', headers).then(function (data) {
24398        if (data.result) {
24399          _this14.listFrequentPassengers = data.result;
24400          _this14.frequentPassengers = data.result;
24401          $.when(autocompleteList = data.result.reduce(function (acc, elem) {
24402            return [].concat(_toConsumableArray(acc), [elem.firstName + ' ' + elem.lastName]);
24403          }, [])).then(function () {
24404            _this14.loadAutocompletePassengerFrequent(autocompleteList);
24405          });
24406        }
24407        callback();
24408      }).catch(function (err) {
24409        console.log(err);
24410        callback();
24411      });
24412    }
24413  }, {
24414    key: 'updateListPassenger',
24415    value: function updateListPassenger() {
24416      var _this15 = this;
24417
24418      var headers = { 'Authorization': '' + SessionStorage.get('jca_token') };
24419
24420      HttpService.get('returnfrequentpassengers', headers).then(function (data) {
24421        _this15.listFrequentPassengers = data.result;
24422      });
24423    }
24424  }, {
24425    key: 'loadAutocompletePassengerFrequent',
24426    value: function loadAutocompletePassengerFrequent(autocompleteList) {
24427      $('.input-name').autocomplete({
24428        source: autocompleteList
24429      }, {
24430        autoFocus: false,
24431        minLength: 0
24432      }).focus(function () {
24433        $(this).autocomplete("search");
24434      });
24435    }
24436  }, {
24437    key: 'selectPassengerComplete',
24438    value: function selectPassengerComplete() {
24439      var _this12 = this;
24440
24441      $('.input-name').on('change autocompleteselect autocompleteclose', function (e) {
24442        var selector = $(e.target).attr('data-js');
24443        var index = selector.replace(/\D/g, '');
24444        var namePassenger = $(e.target).val();
24445
24446        _this12.completeCardPassenger(index, namePassenger);
24447
24448        if ($(e.target).empty()) {
24449          $('#save-passenger-' + index + '').closest('.save-passenger-block').show();
24450        }
24451      });
24452    }
24453  }, {
24454    key: 'completeCardPassenger',
24455    value: function completeCardPassenger(index, name) {
24456      var passenger = this.listFrequentPassengers.find(function (elem) {
24457        return elem.firstName + ' ' + elem.lastName == name;
24458      });
24459      var selectDoc = $('[data-js="select-doc-type-' + index + '"]');
24460      var getBirthDate = function getBirthDate() {
24461        if (passenger.typePax !== 'ADULTO') {
24462          var birthExtractDate = DateFormatter.extractDate(passenger.birthDate);
24463          var birthDate = DateFormatter.reverseDate(birthExtractDate);
24464
24465          $('[data-js="input-birth-child-' + index + '"]').val(birthDate);
24466        }
24467      };
24468
24469      if (!passenger) return;
24470
24471      $('[data-js="passenger-id-' + index + '"]').attr('data-id', passenger.id);
24472      $('[data-js="input-doc-' + index + '"]').val(passenger.document).attr('disabled', false).trigger('input');
24473      var typeDocument = passenger.typeDoc !== 'DECLARACAO' ? passenger.typeDoc : 'DECLARAÇÃO DE NASCIDO VIVO';
24474
24475      this.selectCustom.selectDefault(selectDoc, typeDocument);
24476      getBirthDate();
24477      this.hideSaveCheck(index);
24478    }
24479  }, {
24480    key: 'listenCheckPassengerFrequent',
24481    value: function listenCheckPassengerFrequent() {
24482      var _this17 = this;
24483
24484      $('[data-js^="input-name"], [data-js^="input-doc"], [data-js^="select-doc-type"]').on('change', function (e) {
24485        var index = $(e.target).attr('data-js').replace(/\D/g, '');
24486        var idPassenger = +$('[data-js="passenger-id-' + index + '"]').attr('data-id');
24487
24488        if (idPassenger) {
24489          _this17.comparePassenger(idPassenger, index);
24490        }
24491      });
24492    }
24493  }, {
24494    key: 'comparePassenger',
24495    value: function comparePassenger(idPassenger, index) {
24496      var passengerFiltered = this.listFrequentPassengers.filter(function (elem) {
24497        return elem.id === idPassenger;
24498      });
24499      var _passengerFiltered$ = passengerFiltered[0],
24500        firstName = _passengerFiltered$.firstName,
24501        lastName = _passengerFiltered$.lastName,
24502        document = _passengerFiltered$.document,
24503        typeDoc = _passengerFiltered$.typeDoc,
24504        typePax = _passengerFiltered$.typePax,
24505        birthDate = _passengerFiltered$.birthDate;
24506
24507
24508      var currentName = firstName + ' ' + lastName;
24509
24510      var name = $('[data-js="input-name-' + index + '"]').val();
24511      var docType = $('[data-js="select-doc-type-' + index + '"]').val();
24512      var doc = $('[data-js="input-doc-' + index + '"]').val();
24513      var typePassenger = $('#passenger-block-' + index + '').attr('data-passenger-type-' + index + '');
24514      var birthPassenger = $('#input-birth-child-' + index + '').val();
24515
24516      if (name == currentName && docType == typeDoc && doc == document) {
24517        if (typePassenger !== 'ADULT') birthPassenger == birthDate ? this.hideCheckBoxSavePassenger(index) : this.showCheckBoxSavePassenger(index);
24518
24519        this.hideCheckBoxSavePassenger(index);
24520      } else {
24521        this.showCheckBoxSavePassenger(index);
24522      }
24523    }
24524  }, {
24525    key: 'showCheckBoxSavePassenger',
24526    value: function showCheckBoxSavePassenger(index) {
24527      var $saveCheckBox = $('[data-js="save-passenger-' + index + '"]');
24528
24529      $saveCheckBox.parent().removeClass("d-none");
24530    }
24531  }, {
24532    key: 'hideCheckBoxSavePassenger',
24533    value: function hideCheckBoxSavePassenger(index) {
24534      $('[data-js="save-passenger-' + index + '"]').parent().addClass("d-none");
24535    }
24536  }, {
24537    key: 'checkPassengerCardEmpty',
24538    value: function checkPassengerCardEmpty(index) {
24539      var isNameEmpty = $('[data-js="input-name-' + index + '"]').val() !== '';
24540      var isTypeDocumentNoSelect = $('[data-js="select-doc-type-' + index + '"]').val() !== null;
24541      var isDocumentNumberEmpty = $('[data-js="input-doc-' + index + '"]').val() !== '';
24542      var isBirthEmpty = $('#input-birth-child-' + index + '').val() ? $('#input-birth-child-' + index + '').val() !== '' : true;
24543
24544      return isNameEmpty && isTypeDocumentNoSelect && isDocumentNumberEmpty && isBirthEmpty;
24545    }
24546  }, {
24547    key: 'savePassengerFrequent',
24548    value: function savePassengerFrequent(index) {
24549      var _this18 = this;
24550
24551      var headers = { 'Authorization': '' + SessionStorage.get('jca_token') };
24552      var name = $('[data-js="input-name-' + index + '"]').val().normalize('NFD').replace(/[\u0300-\u036f]/g, "").trim();
24553      var firstName = Utils.getFirstName(name);
24554      var lastName = Utils.getFamilyName(name);
24555      var typeDoc = $('[data-js="select-doc-type-' + index + '"]').val();
24556      var document = $('[data-js="input-doc-' + index + '"]').val();
24557      var typePassenger = $('#passenger-block-' + index + '').attr('data-passenger-type-' + index + '');
24558      var birthDateChild = $('#input-birth-child-' + index + '').val();
24559
24560      var getTypePax = function getTypePax(passengerType) {
24561        switch (passengerType) {
24562          case 'ADULT':
24563            return 'ADULTO';
24564          case 'CHILD':
24565            return 'CRIANCA';
24566          case 'CHILD_A':
24567            return 'CRIANCA';
24568          default:
24569            break;
24570        }
24571      };
24572
24573      var setIdToCardPassenger = function setIdToCardPassenger(data, index) {
24574        var idFrequentPassengerAdd = data.result.replace(/\D/g, '');
24575        $('[data-js="passenger-id-' + index + '"]').attr('data-id', idFrequentPassengerAdd);
24576      };
24577
24578      var body = {
24579        "pax": {
24580          "firstName": firstName,
24581          "lastName": lastName,
24582          "typeDoc": typeDoc,
24583          "document": document,
24584          "typePax": getTypePax(typePassenger)
24585        }
24586      };
24587
24588      if (typePassenger !== 'ADULT') body.pax.birthDate = DateFormatter.parseDateApiFormat(birthDateChild);
24589      // AEM Custom Alert messages
24590      var addPassengerFail = $('[data-js="add-passenger-fail"]').val();
24591
24592      return new Promise(function (resolve) {
24593        HttpService.post('savefrequentpassenger', body, headers).then(function (data) {
24594          setIdToCardPassenger(data, index);
24595          _this18.updateListPassenger();
24596          $('[data-js="save-passenger-check-' + index + '"]').addClass('d-none');
24597          resolve(true);
24598        }).catch(function (err) {
24599          $('body, html').animate({
24600            scrollTop: $('[data-js="passenger-blocks"]').offset().top - 150
24601          }, 350);
24602          _this18.showFrequentPassengerAlert(this.msgFrequentPassengerAlert);
24603          _this18.handleSubmitFormMsgError(index, addPassengerFail);
24604          _this18.handleSubmitFormError(index);
24605          console.log(err);
24606          resolve(false);
24607        });
24608      });
24609    }
24610  }, {
24611    key: 'showFrequentPassengerAlert',
24612    value: function showFrequentPassengerAlert(msg) {
24613      this.msgFrequentPassengerAlert.text(msg);
24614      this.frequentPassengerAlert.addClass('active');
24615    }
24616  }, {
24617    key: 'hideFrequentPassengerAlert',
24618    value: function hideFrequentPassengerAlert() {
24619      this.frequentPassengerAlert.removeClass('active');
24620    }
24621  }, {
24622    key: 'handleSubmitFormMsgError',
24623    value: function handleSubmitFormError(index, addPassengerFail) {
24624      $('[data-js="validation-msg-' + index + '"]').addClass('error');
24625      $('[data-js="validation-msg-' + index + '"]').text(addPassengerFail);
24626    }
24627  }, {
24628    key: 'handleSubmitFormError',
24629    value: function handleSubmitFormError(index) {
24630      var _this19 = this;
24631
24632      var document = $('[data-js="input-doc-' + index + '"]');
24633      var docTip = document.closest('.container').find('.validation-msg-input');
24634      var AEM_doc_alert_message = $('[data-js="doc-alert-message"]').val();
24635
24636      this.frequentPassengers.forEach(function (el) {
24637        if (document.val() == el.document) {
24638          document.addClass('invalid');
24639          _this19.openValidation(docTip, false, AEM_doc_alert_message);
24640        }
24641      });
24642    }
24643  }, {
24644    key: 'hideSaveCheck',
24645    value: function hideSaveCheck(index) {
24646      $('#save-passenger-' + index + '').closest('.save-passenger-block').addClass('d-none');
24647    }
24648  }, {
24649    key: 'loadBlocks',
24650    value: function loadBlocks() {
24651      var passengers = this.cart.listPassengers;
24652      var states = ['SP', 'MG', 'SC', 'RS', 'PR'];
24653      var originUf = this.formData.depart.origin.uf.toUpperCase();
24654      var destinationUf = this.formData.depart.destination.uf.toUpperCase();
24655      var linkRegisterPassenger = $('#linkRegisterPassenger').val();
24656      var counterChild = passengers.filter(function (passenger) {
24657        return passenger.type !== 'ADULT';
24658      });
24659      var styles = [];
24660      var stylesCardContainer = [];
24661      var passengerLabel = 'Passageiro';
24662      var formNameField = $('[data-js="formNameField"]').val() ? $('[data-js="formNameField"]').val() : 'Nome completo';
24663      var formSelectField = $('[data-js="formSelectField"]').val() ? $('[data-js="formSelectField"]').val() : 'SELECIONE';
24664      var formDocumentField = $('[data-js="formDocumentField"]').val() ? $('[data-js="formDocumentField"]').val() : 'Número do documento';
24665      var formDateField = $('[data-js="formDateField"]').val() ? $('[data-js="formDateField"]').val() : 'Data de nascimento';
24666      var siteId = $('#siteName').val();
24667      var formStudentCheckbox = 'Desconto para Estudante/Professor cadastrado.';
24668      var formFrequentPassengerField = $('[data-js="formFrequentPassengerField"]').val() ? $('[data-js="formFrequentPassengerField"]').val() : 'Salvar como passageiro frequente.';
24669      var formcheckboxBuyerField = $('[data-js="formcheckboxBuyerField"]').val() ? $('[data-js="formcheckboxBuyerField"]').val() : 'Sou o comprador da viagem e também um dos passageiros.;'
24670
24671      // AEM Custom enable/disable checkboxes.
24672      var isBuyerCheckboxEnabled = $('[data-js="enable-buyer-checkbox"]').val();
24673      var isSavePassengerCheckboxEnabled = $('[data-js="enable-save-passenger-checkbox"]').val();
24674
24675      var childDataValidationMessage = $('[data-js="child-data-validation-message"]').val();
24676      var validationOfFutureDates = $('[data-js="validation-of-future-dates"]').val();
24677      var validationOfInvalidFormatDates = $('[data-js="validation-of-invalid-format-dates"]').val();
24678
24679      childDataValidationMessage = (childDataValidationMessage && childDataValidationMessage != '') ? childDataValidationMessage : 'A idade da criança é maior que 5 anos.';
24680      validationOfFutureDates = (validationOfFutureDates && validationOfFutureDates != '') ? validationOfFutureDates : 'Datas futuras não são válidas.';
24681      validationOfInvalidFormatDates = (validationOfInvalidFormatDates && validationOfInvalidFormatDates != '') ? validationOfInvalidFormatDates : 'Datas de formato inválido.';
24682
24683
24684      for (var i = 1; i <= passengers.length; i++) {
24685        var content = [];
24686
24687        content.push('<div id="passenger-block-' + i + '" class="passenger-block column1" card-type="' + passengers[i - 1].type + '" data-passenger-type-' + i + '="' + passengers[i - 1].type + '">');
24688        switch (passengers[i - 1].type) {
24689          case 'CHILD':
24690            content.push('<div class="tab">' + passengerLabel + ' ' + i + ' <span class="child-passenger">' + $('[data-js="child-without-seat-passenger"]').val() + '</span></div>');
24691            break;
24692          case 'CHILD_A':
24693            content.push('<div class="tab">' + passengerLabel + ' ' + i + ' <span class="child-passenger">' + $('[data-js="child-with-seat-passenger"]').val() + '</span></div>');
24694            break;
24695          case 'ADULT':
24696            content.push('<div class="tab"> ' + passengerLabel + ' ' + i + ' <span class="adult-passenger">' + $('[data-js="regular-passenger"]').val() + '</span></div>');
24697          default:
24698            break;
24699        }
24700
24701        content.push('<div class="container">');
24702
24703        if (isBuyerCheckboxEnabled) {
24704          content.push('<div class="row mt-2 pe-3">');
24705          content.push('<div class="custom-control custom-checkbox buyer-check-wrapper" aria-hidden="' + (i === 1 ? 'false' : 'true') + '"><input class="passenger-check custom-control-input buyer" id="buyer-check-' + i + '" type="checkbox" data-js="buyer-check-' + i + '" /><label class="custom-control-label center" for="buyer-check-' + i + '">' + formcheckboxBuyerField + '</label></div>');
24706          content.push('</div>');
24707        }
24708
24709        if (originUf === destinationUf && $.inArray(originUf, states) !== -1) {
24710          content.push('<div class="row mb-3 pe-3">');
24711          content.push('<div class="custom-control custom-checkbox"><input class="passenger-check custom-control-input student" id="student-check-' + i + '" type="checkbox" data-js="student-check-' + i + '" /><label class="custom-control-label center" for="student-check-' + i + '">' + formStudentCheckbox + '</label></div>');
24712          content.push('<div id="validation-block-' + i + '" class="validation-block">');
24713          content.push('<div class="row g-0">');
24714          content.push('<div class="col-6">');
24715          content.push('<div class="field">');
24716          content.push('<label class="label" for="input-person-type-' + i + '" data-js="label-student">VOCÊ É ESTUDANTE OU PROFESSOR?</lab>');
24717          content.push('</div>');
24718          content.push('</div>');
24719          content.push('<div class="col-6">');
24720          content.push('<div class="field">');
24721          content.push('<label class="label" for="input-cpf-' + i + '" data-js="label-cpf">DIGITE O CPF CADASTRADO</label>');
24722          content.push('</div>');
24723          content.push('</div>');
24724          content.push('</div>');
24725
24726          content.push('<div class="row g-0">');
24727          content.push('<div class="col-6">');
24728          content.push('<div class="field">');
24729          content.push('<div class="select-custom focusable form-group" tabindex="0">');
24730          content.push('<select id="input-person-type-' + i + '" data-js="input-person-type-' + i + '">');
24731          content.push('<option class="select-option" value="REGULAR" selected disabled>SELECIONE</option>');
24732          content.push('<option class="select-option" value="STUDENT">ESTUDANTE</option>');
24733          content.push('<option class="select-option" value="PROFESSOR">PROFESSOR</option>');
24734          content.push('</select>');
24735          content.push('</div>');
24736          content.push('</div>');
24737          content.push('</div>');
24738          content.push('<div class="col-6">');
24739          content.push('<div class="field">');
24740          content.push('<div class="input-container"><input title="Digite seu CPF." class="input-cpf focusable" id="input-cpf-' + i + '" type="text" data-js="input-cpf-' + i + '"/></div>');
24741          content.push('</div>');
24742          content.push('</div>');
24743          content.push('</div>');
24744
24745          content.push('<div class="row g-0 validation">');
24746          content.push('<div class="col-9">');
24747          content.push('<span id="validation-msg-discount-' + i + '" class="validation-msg" data-js="validation-msg-discount-' + i + '"></span>');
24748          content.push('</div>');
24749          content.push('<div class="col-3">');
24750          content.push('<button id="validation-btn-' + i + '" class="validation-btn" data-js="validation-btn-' + i + '" disabled>VALIDAR </button>');
24751          content.push('</div>');
24752          content.push('</div>');
24753
24754          content.push('</div>');
24755          content.push('</div>');
24756          content.push('<div class="row">');
24757          content.push('<p class="link-register" data-js="link-register">(Não é cadastrado? <a id="link-register" href=' + linkRegisterPassenger + ' target="_blank"><em style="border-bottom: 1px solid #3d3d3c; font-style: normal">Clique aqui</em></a> e saiba como fazer o seu cadastro)</p>');
24758          content.push('</div>');
24759        }
24760
24761        content.push('<div class="row mb-3 mb-lg-0">');
24762
24763        content.push('<div class="col-12 px-4">');
24764        content.push('<div class="field"><label for="input-name-' + i + '" class="label">' + formNameField + ':</label><br/>');
24765        content.push('<div class="input-container"><input autocomplete="off" title="' + formNameField + '" class="input-name focusable" id="input-name-' + i + '" type="text" data-js="input-name-' + i + '" minlength="6" maxlength="45" required="required" placeholder="' + formNameField + '"/>');
24766        content.push('</div>');
24767        content.push('</div>');
24768        content.push('</div>');
24769
24770        content.push('<div class="col-12 ps-lg-4 pe-lg-2 px-4">');
24771        content.push('<div class="field"><label for="input-name-' + i + '" class="label">TIPO DE DOCUMENTO:</label><br/>');
24772
24773        if (passengers[i - 1].type == "ADULT") {
24774          var docs = $('[data-js="regular-passenger-docs"]').val();
24775          content.push('<div class="select-custom focusable form-group" tabindex="0">');
24776          content.push('<select id="select-doc-type-' + i + '" name="select-doc-type-' + i + '" data-js="select-doc-type-' + i + '" required="required">');
24777          content.push('<option class="select-option" value="REGULAR" selected disabled>' + formSelectField + '</option>');
24778          try {
24779            if (docs) {
24780              var docsJSON = jQuery.parseJSON(docs);
24781              if (docsJSON) {
24782                for (var i1 = 0; i1 < docsJSON.length; i1++) {
24783                  var doc = docsJSON[i1];
24784                  content.push('<option class="select-option" value="' + doc.value + '">' + doc.name + '</option>');
24785                }
24786              }
24787            }
24788          } catch (e) { console.log(e); }
24789
24790          content.push('</select>');
24791          content.push('</div>');
24792        } else {
24793          var docs = $('[data-js="child-passenger-docs"]').val();
24794          content.push('<div class="select-custom focusable form-group" tabindex="0">');
24795          content.push('<select id="select-doc-type-' + i + '" name="select-doc-type-' + i + '" data-js="select-doc-type-' + i + '" required="required">');
24796          content.push('<option class="select-option" value="REGULAR" selected disabled>' + formSelectField + '</option>');
24797          try {
24798            if (docs) {
24799              var docsJSON = jQuery.parseJSON(docs);
24800              if (docsJSON) {
24801                for (var i2 = 0; i2 < docsJSON.length; i2++) {
24802                  var doc = docsJSON[i2];
24803                  content.push('<option class="select-option" value="' + doc.value + '">' + doc.name + '</option>');
24804                }
24805              }
24806            }
24807          } catch (e) { console.log(e); }
24808
24809          content.push('</select>');
24810          content.push('</div>');
24811        }
24812
24813        content.push('</div>');
24814        content.push('</div>');
24815
24816        content.push('<div class="col-12 px-lg-3 px-4">');
24817        content.push('<div class="field"><label for="input-doc-' + i + '" class="label">' + formDocumentField + '</label>');
24818        content.push('<br/>');
24819        content.push('<div class="input-container" ><input title="' + formDocumentField + '" class="input-doc focusable" id="input-doc-' + i + '" type="text" data-js="input-doc-' + i + '" required="required"  maxlength="20" disabled placeholder="' + formDocumentField + '"/>');
24820        content.push('<span id="validation-msg-' + i + '" class="validation-msg-input" data-js="validation-msg-' + i + '"></span>');
24821        content.push('</div>');
24822        content.push('</div>');
24823        content.push('</div>');
24824
24825        if (passengers[i - 1].type == "ADULT") {
24826          content.push('<div class="col-12 pe-lg-4 ps-lg-2 px-4">');
24827          content.push('<div class="field"><label for="input-birth-' + i + '" class="label">' + formDateField + '</label>');
24828          content.push('<br/>');
24829          content.push('<div class="input-container"><input title="' + formDateField + '" class="input-birth" "focusable" placeholder="' + formDateField + '" id="input-birth-' + i + '" type="tel" data-js="input-birth-' + i + '" required="required"  maxlength="25" />');
24830          content.push('</div>');
24831          content.push('</div>');
24832          content.push('</div>');
24833        }
24834
24835        if (passengers[i - 1].type !== 'ADULT') {
24836          content.push('<div class="col-12 pe-lg-4 ps-lg-2 px-4">');
24837          content.push('<div class="field"><label for="input-birth-child-' + i + '" class="label">' + formDateField + '</label>');
24838          content.push('<br/>');
24839          content.push('<div class="input-container" ><input title="' + formDateField + '" class="input-birth-child focusable" placeholder="' + formDateField + '" id="input-birth-child-' + i + '" type="tel" data-js="input-birth-child-' + i + '" required="required"  maxlength="25" />');
24840          content.push('</div>');
24841          content.push('</div>');
24842          content.push('</div>');
24843        } else if (counterChild.length > 0) {
24844          content.push('<div class="col-12"">');
24845          content.push('</div>');
24846        }
24847        content.push('</div>');
24848
24849
24850        if (passengers[i - 1].type !== 'ADULT') {
24851          content.push('<div class="row mb-0">');
24852          content.push('<div id="birth-msg-validation-' + i + '" class="birth-msg-validation"><span class="msg-warning"><span class="icon-warning">!</span><span id="msg-warning' + i + '">' + childDataValidationMessage + '</span></span></div>');
24853          content.push('</div>');
24854        }
24855
24856        if (isSavePassengerCheckboxEnabled) {
24857          content.push('<div class="row mb-3">');
24858          content.push('<div class="custom-control custom-checkbox save-passenger-block"><input class="passenger-check custom-control-input buyer save-passenger" id="save-passenger-' + i + '" type="checkbox" data-js="save-passenger-' + i + '"><label class="custom-control-label center" for="save-passenger-' + i + '">' + formFrequentPassengerField + '</label></div>');
24859          content.push('</div>');
24860        }
24861        content.push('</div>');
24862
24863        this.blocks.append(content.join(''));
24864        $('[data-js="input-cpf-' + i + '"]').mask('000.000.000-00');
24865      }
24866      this.selectCustom = new SelectCustom($);
24867    }
24868  }]);
24869
24870  return PassengerController;
24871}();
24872
24873/**
24874 *
24875 * PASSENGER FORM
24876 *
24877 * FIM
24878 */
24879'use strict';
24880
24881var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); }
24881 else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
24882
24883var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
24884
24885function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
24886
24887/**
24888 *
24889 * PaymentController
24890 *
24891 * INICIO
24892 */
24893
24894var PaymentController = function () {
24895  function PaymentController($, cartComponentRef) {
24896    var useSummary = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
24897
24898    _classCallCheck(this, PaymentController);
24899
24900    this.formData = SessionStorage.get('formData');
24901    this.cart = SessionStorage.get('cart');
24902    this.mainPassenger = SessionStorage.get('passenger');
24903    this.selectCustom = new SelectCustom($);
24904    this.labelDeparture = $('[data-js="itinerary-label-departure"]');
24905    this.labelDestination = $('[data-js="itinerary-label-destination"]');
24906    this.selectMethod = $('.select-selected:first');
24907    this.inputName = $('[data-js="input-name-card"]');
24908    this.inputCardNumber = $('[data-js="input-number-card"]');
24909    this.inputDoc = $('[data-js="input-doc"]');
24910    this.inputExpiration = $('[data-js="input-expiration"]');
24911    this.buttonSecInfo = $('[data-js="button-info-credit"]');
24912    this.btnSeeCart = $('[data-js="see-cart"]');
24913    this.btnSeeCartDesktop = $('[data-js="see-cart-desktop"]');
24914    this.inputSecurity = $('[data-js="input-sec-code"]');
24915    this.btnInstallment = $('[data-js="btn-installment"]');
24916    this.btnInstallmentText = $('[data-js="btn-installment-text"]');
24917    this.checkConditions = $('[data-js="conditions-check"]');
24918    this.infoConditions = $('[data-js="conditions-info"]');
24919    this.cardForm = $('[data-js="card-form"]');
24920    this.bankForm = $('[data-js="bank-form"]');
24921    this.createWalletForm = $('[data-js="createWallet-form"]');
24922    this.liveloForm = $('[data-js="livelo-form"]');
24923    this.contaGiroForm = $('[data-js="contaGiro-form"]');
24924    this.buttonSubmit = $('[data-js="payment-submit"]');
24925    this.miniFlag = $('[data-js="mini-flag"]');
24926    this.containerSecInfo = $('[data-js="security-info-container"]');
24927    this.containerSelOver = $('[data-js="select-overlay-container"]');
24928    this.containerCondInfo = $('[data-js="conditions-info-container"]');
24929    this.closeSecInfo = $('[data-js="close-sec-info"]');
24930    this.closeSelOver = $('[data-js="select-overlay-close"]');
24931    this.closeCondInfo = $('[data-js="conditions-info-close"]');
24932    this.listInstallment = $('[data-js="list-installments"]');
24933    this.seeDiscount = $('[data-js="see-discount"]');
24934    this.conatainerPayAlert = $('[data-js="payment-alert"]');
24935    this.closePayAlert = $('[data-js="payment-alert-close"]');
24936    this.insuranceContainer = $('[data-js="insurance-container"]');
24937    this.insuranceCheck = $('[data-js="insurance-check"]');
24938    this.cartComponent = cartComponentRef;
24939    this.cartService = cartComponentRef.cartService;
24940    this.insuranceStates = $('[data-js="insurance-states"]');
24941    this.selInstallments = $('[data-js="btn-installment-select"]');
24942    this.maxValidYear = parseInt($('[data-js="max-valid-year"]').val());
24943    this.invalidCardMessage = $('[data-js="invalid-card-msg"]').val();
24944    this.invalidExpirationMessage = $('[data-js="invalid-expiration-date-msg"]').val();
24945    this.invalidCvvMessage = $('[data-js="invalid-cvv-msg"]').val();
24946    this.shouldEraseInsuranceCheck = $('[data-js="should-erase-insurance-check"]').val().toLowerCase() === 'true';
24947    this.shouldEraseInputNameCard = $('[data-js="should-erase-input-name-card"]').val().toLowerCase() === 'true';
24948    this.shouldEraseInputCpf = $('[data-js="should-erase-input-cpf"]').val().toLowerCase() === 'true';
24949    this.shouldEraseBtnInstallment = $('[data-js="should-erase-btn-installment"]').val().toLowerCase() === 'true';
24950    this.shouldEraseConditionsCheck = $('[data-js="should-erase-conditions-check"]').val().toLowerCase() === 'true';
24951    this.shouldIgnoreCardValidation = $('[data-js="shouldIgnoreCardValidation"]').val().toLowerCase() === 'true';
24952    this.shouldIgnoreExpirationValidation = $('[data-js="shouldIgnoreExpirationValidation"]').val().toLowerCase() === 'true';
24953    this.arrBankLogo = $('[data-js="images-names"]').attr('images-name').split(',');
24954    this.listBankLogo = $('[data-js="list-logo-bank"]');
24955    this.bankName = $('[data-js="bank-select"]');
24956    this.document = $('#input-cpf-bank');
24957    this.branch = $('[data-js="input-bank-agency"]');
24958    this.account = $('[data-js="input-bank-account"]');
24959    this.tabBank = $('[data-js="tab-bank"]');
24960    this.tabCard = $('[data-js="tab-card"]');
24961    this.tabPix = $('[data-js="tab-pix"]');
24962    this.tabNupay = $('[data-js="tab-nupay"]');
24963    this.nupayInfo = $('[data-js="nupay-info"]');
24964    this.tabContaGiro = $('[data-js="tab-conta-giro"]');
24965    this.pixContent = $('[data-form="pix-wrapper"]');
24966    this.convenienceFee = $('[data-js="convenience-fee"]').attr('value') == 'true' ? true : false;
24967    this.repricingV2 = SessionStorage.get('repricingv2');
24968    this.loadInstallmentsAPI = $('[data-js="installments-api"]').attr('value') == 'true';
24969    this.priceCart = $('[data-js="price-cart"]');
24970    this.passengersNumber = $('[data-js="passenger-qtd-going"]');
24971    this.seatsPrice = $('[data-js="seats-value-going"]');
24972    this.serviceValue = $('[data-js="service-fee-going"]');
24973    this.convenienceValue = $('[data-js="covenience-fee-going"]');
24974    this.passengersNumberReturn = $('[data-js="passenger-qtd-return"]');
24975    this.seatsPriceReturn = $('[data-js="seats-value-return"]');
24976    this.serviceValueReturn = $('[data-js="service-fee-return"]');
24977    this.convenienceValueReturn = $('[data-js="covenience-fee-return"]');
24978    this.dateGoing = $('[data-js="date-trip-going"]');
24979    this.origingGoing = $('[data-js="origin-going"]');
24980    this.destinationGoing = $('[data-js="destination-going"]');
24981    this.departureGoing = $('[data-js="hour-departure-going"]');
24982    this.arrivalGoing = $('[data-js="hour-arrival-going"]');
24983    this.classGoing = $('[data-js="class-type-going"]');
24984    this.dateReturn = $('[data-js="date-trip-return"]');
24985    this.origingReturn = $('[data-js="origin-return"]');
24986    this.destinationReturn = $('[data-js="destination-return"]');
24987    this.departureReturn = $('[data-js="hour-departure-return"]');
24988    this.arrivalReturn = $('[data-js="hour-arrival-return"]');
24989    this.classReturn = $('[data-js="class-type-return"]');
24990    this.showServiceFee = $('[data-js="service-fee-wpp"]').attr('value') == 'true';
24991    this.showConvenienceFee = $('[data-js="convenience-fee-wpp"]').attr('value') == 'true';
24992
24993    this.installmentsResult = [];
24994    this.installmentsError = false;
24995    this.remarkForm = $('[data-js="remark-form"]');
24996    this.isUseHub = $('[data-js="use-hub"]').val() == 'true';
24997    this.isUseAdyen = $('[data-js="use-adyen"]').val() == 'true';
24998    this.isMalgaActive = false;
24999    this.liveloPoints = 0;
25000    this.isConsultLiveloAPI = false;
25001    this.liveloNoPayment = false;
25002    this.qttPaymentErr = 1;
25003    this.phoneId = '';
25004    this.typeLivelo = '';
25005    this.deviceLiveloId = '';
25006    this.totalSalePrice = 0;
25007    this.isPaymentWhatsapp = false;
25008    this.token = ''
25009    this.whatsParams = {};
25010    this.wppPassengers = [];
25011    this.wppToken = '';
25012    this.saleResult = {};
25013    this.saleplatform = null;
25014    this.storedCardToken = null;
25015    this.cardsLoaded = false;
25016    this.disableStoredCards = $('[data-js="disable-stored-cards"]').val() == 'true';
25017    this.summaryObject = SessionStorage.get('summaryObject') || null;
25018    this.voucher = "";
25019    this.installmentsQnt = 1;
25020    this.isInsuranceActive = false;
25021    this.useSummary = useSummary;
25022    this.hasPixDiscount = false;
25023
25024    {
25025      this.environment = $('#environmentPayment').val();
25026
25027      this.originKey = null;
25028      var urlWcmmode = new URL(window.location.href);
25029
25030      if ($('#wcmmodeedit').val() == 'true' || urlWcmmode.searchParams.get("wcmmode") == "disabled") {
25031        this.originKey = $('#originKeyAuthor').val();
25032      } else {
25033        this.originKey = $('#originKeyPublish').val();
25034      }
25035
25036      this.isIframeValid = false;
25037      this.isIframeTokenValid = false;
25038      this.cardNumberEncrypted = null;
25039      this.expiryMontEncrypted = null;
25040      this.expiryYearEncrypted = null;
25041      this.securityCodeEncrypted = null;
25042      this.totalValueWithCoupon = 0;
25043      this.confirmSaleMsgs = [];
25044    }
25045
25046    this.init();
25047
25048    this.messageCpfController = new MessageCpfController(this.mainPassenger);
25049  }
25050
25051  _createClass(PaymentController, [{
25052    key: 'init',
25053    value: function init() {
25054      var _this = this;
25055
25056      if (this.handleNupayReturn()) return;
25057      SessionStorage.remove('discountData');
25058      this.saleplatform = SessionStorage.get('utm_saleplatform');
25059      _this.sendBeginCheckoutToAnalytics();
25060      this.getServerTime(function () {
25061        _this.initInsuranceCheck();
25062        _this.handlePayWppLayout();
25063
25064        if (_this.isPaymentWhatsapp) {
25065          _this.getAuthorizationToken(function () {
25066              _this.loadAdyenIframe();
25067              _this.loadMasks();
25068              _this.listenForm();
25069              _this.loadInstallments();
25070              _this.handleWhatsappShopping();
25071              _this.closePaymentAlert();
25072              _this.submitPayment();
25073              _this.loadConfirmSaleMessages();
25074              _this.submitPaymentError();
25075              _this.renderBankLogo();
25076              //_this.fillSelectsBank();
25077              _this.controllerPaymentMethods();
25078              _this.initPaymentColors();
25079              //if (_this.loadInstallmentsAPI) _this.renderInstallmentsWithInterest();
25080              //_this.setInstallmentsWithInterest();
25081              /*if (_this.useSummary && _this._summaryPromise) {
25082              _this._summaryPromise.then(function () {
25083                    return _this.setInstallmentsWithInterest();
25084                  }, function () {
25085                    return _this.setInstallmentsWithInterest();
25086                  });
25087                } else {
25088                  _this.renderInstallmentsWithInterest();
25089                }*/
25090          });
25091        } else {
25092          _this.getPaymentAvailability();
25093          _this.handleInsurance();
25094          _this.getUserData();
25095          _this.loadAdyenIframe();
25096          _this.handlePreRequirements();
25097          _this.loadInfo();
25098          _this.loadMasks();
25099          _this.listenForm();
25100          _this.loadInstallments();
25101          _this.loadConditions();
25102          _this.closePaymentAlert();
25103          _this.submitPayment();
25104          _this.loadStateMessages();
25105          _this.loadConfirmSaleMessages();
25106          _this.submitPaymentError();
25107          _this.renderBankLogo();
25108          _this.fillSelectsBank();
25109          _this.validateBtn();
25110          _this.controllerPaymentMethods();
25111          _this.initPaymentColors();
25112          _this.handlePaymentRepricing();
25113          _this.validateInputsRemarkForm();
25114          if (_this.loadInstallmentsAPI && !_this.repricingV2) {
25115            // When using cartSummary, wait for the request already triggered by controllerPaymentMethods
25116            // (via syncSummaryThenUpdateCartView) to avoid duplication; otherwise fall back to the original flow.
25117            if (_this.useSummary && _this._summaryPromise) {
25118              _this._summaryPromise.then(function () {
25119                return _this.setInstallmentsWithInterest();
25120              }, function () {
25121                return _this.setInstallmentsWithInterest();
25122              });
25123            } else {
25124              _this.renderInstallmentsWithInterest();
25125            }
25126          }
25127        }
25128      });
25129
25130      $('[data-js="alert-error-close-menu"]').on('click', function () {
25131        $('[data-js="message-confir-error"]').removeClass('active');
25132        $('[data-js="message-confir-error"]').parent().removeClass('active');
25133        OverlayService.hide();
25134      });
25135        var cartObj = SessionStorage.get('cart');
25136      _this.hasPixDiscount = !(!cartObj._listOffer[0]._priceWithDiscountPix || cartObj._listOffer[0]._priceWithDiscountPix === cartObj._listOffer[0]._price);
25137    }
25138  }, {
25139    key: 'isMobileDevice',
25140    value: function isMobileDevice() {
25141      var os = Utils.getDeviceOS ? Utils.getDeviceOS() : null;
25142      var isMobileOS = os === 'IOS' || os === 'ANDROID';
25143      return isMobileOS || navigator.maxTouchPoints > 0 && Utils.isMobile();
25144    }
25145  }, {
25146    key: 'handleNupayReturn',
25147    value: function handleNupayReturn() {
25148      var _this = this;
25149
25150      var urlParams = new URLSearchParams(window.location.search);
25151      var paymentReferenceId = urlParams.get('paymentReferenceId');
25152      if (!paymentReferenceId) return false;
25153
25154      SessionStorage.set('nupayPaymentReferenceId', paymentReferenceId);
25155
25156      LoaderService.show();
25157
25158      HttpService._nupayPendingFlow = true;
25159      this.loginNupayUser(paymentReferenceId).then(function () {
25160        return _this.requestNupayStatus(paymentReferenceId);
25161      });
25162
25163      return true;
25164    }
25165  }, {
25166    key: 'loginNupayUser',
25167    value: function loginNupayUser(paymentReferenceId) {
25168      return HttpService.restorePaymentSession(paymentReferenceId).then(function () {
25169        var token = SessionStorage.get('jca_token');
25170        if (token) HttpService.applyRestoredCustomer(token);
25171
25172        if (SessionStorage.get('passenger') != null) {
25173          localStorage.setItem('logged', true);
25174        }
25175
25176        return !!SessionStorage.get('jca_token');
25177      });
25178    }
25179  }, {
25180    key: 'goToNupayPending',
25181    value: function goToNupayPending(data, paymentReferenceId) {
25182      SessionStorage.set('checkout', data);
25183      SessionStorage.set('checkout_aux', { method: 'NUPAY' });
25184
25185      var redirectLogged = function redirectLogged() {
25186        var token = SessionStorage.get('jca_token');
25187        if (token) HttpService.applyRestoredCustomer(token);
25188        var pendingPath = $('#checkoutNupayPagePath').val();
25189        var separator = pendingPath.indexOf('?') === -1 ? '?' : '&';
25190        $(location).attr('href', pendingPath + separator + 'paymentReferenceId=' + encodeURIComponent(paymentReferenceId));
25191      };
25192
25193      if (SessionStorage.get('jca_token')) {
25194        redirectLogged();
25195        return;
25196      }
25197
25198      this.loginNupayUser(paymentReferenceId).then(redirectLogged);
25199    }
25200  }, {
25201    key: 'requestNupayStatus',
25202    value: function requestNupayStatus(paymentReferenceId, attempt) {
25203      var _this2 = this;
25204
25205      var tryCount = attempt || 1;
25206      var headers = {
25207        Authorization: '' + SessionStorage.get('jca_token'),
25208        sessionseatlock: SessionStorage.get('sessionseatlock')
25209      };
25210
25211      HttpService.get("nupayPaymentStatus?paymentReferenceId="+paymentReferenceId, headers).then(function (data) {
25212        LoaderService.hide();
25213        if (data && data.result && data.result.sales && data.result.sales.length > 0) {
25214          var status = data.result.sales[0].status.toUpperCase();
25215          if (status === 'SALE_APPROVED') {
25216            SessionStorage.set('checkout', data);
25217            SessionStorage.set('checkout_aux', { method: 'NUPAY' });
25218            SessionStorage.set('nupayPaymentReferenceId', paymentReferenceId);
25219            var token = SessionStorage.get('jca_token');
25220            if (token) HttpService.applyRestoredCustomer(token);
25221            var checkoutPath = $('#checkoutPagePath').val();
25222            var separator = checkoutPath.indexOf('?') === -1 ? '?' : '&';
25223            $(location).attr('href', checkoutPath + separator + 'paymentReferenceId=' + encodeURIComponent(paymentReferenceId));
25224            return;
25225          }
25226          if (status === 'SALE_PENDING') {
25227            _this2.goToNupayPending(data, paymentReferenceId);
25228            return;
25229          }
25230        }
25231        ModalNupay.show('error');
25232      }).fail(function (xhr) {
25233        if (xhr.status === 204) {
25234          LoaderService.hide();
25235          ModalNupay.show('cancelled');
25236          return;
25237        }
25238
25239        if (xhr.status === 401 && tryCount < 3) {
25240          _this2.loginNupayUser(paymentReferenceId).then(function () {
25241            return _this2.requestNupayStatus(paymentReferenceId, tryCount + 1);
25242          });
25243          return;
25244        }
25245
25246        LoaderService.hide();
25247        ModalNupay.show('error');
25248      });
25249    }
25250  }, {
25251    key: 'getUserData',
25252    value: function getUserData() {
25253      var _this2 = this;
25254
25255      var cpf = this.mainPassenger._cpf;
25256      var url = $("#baseGiroUrl").val() + '/customer/v1/user/getlike?filter.cpf=' + cpf;
25257      var headers = {
25258        Authorization: '' + SessionStorage.get("jca_token")
25259      };
25260      var headersRequest = HttpService.getSession(headers);
25261
25262      $.ajax({
25263        url: url,
25264        type: 'GET',
25265        headers: headersRequest
25266      }).then(function (response) {
25267        if (response && Object.keys(response).length > 0) {
25268          SessionStorage.set('accountExists', true);
25269          _this2.checkWalletExists();
25270        } else {
25271          SessionStorage.set('accountExists', false);
25272        }
25273      }).catch(function (error) {
25274        SessionStorage.set('accountExists', false);
25275      });
25276    }
25277  }, {
25278    key: 'checkWalletExists',
25279    value: function checkWalletExists() {
25280      var _this3 = this;
25281
25282      var passenger = SessionStorage.get('passenger');
25283
25284      if (passenger && passenger._cpf) {
25285        var cpf = passenger._cpf;
25286        var url = $("#baseGiroUrl").val() + '/wallet/v1/exists/' + cpf;
25287        var headers = {
25288          Authorization: '' + SessionStorage.get("jca_token")
25289        };
25290        var headersRequest = HttpService.getSession(headers);
25291
25292        LoaderService.show();
25293
25294        $.ajax({
25295          url: url,
25296          type: 'GET',
25297          headers: headersRequest
25298        }).then(function (data) {
25299          LoaderService.hide();
25300          if (data.success === false) {
25301            SessionStorage.set('walletExists', false);
25302          } else {
25303            SessionStorage.set('walletExists', true);
25304            _this3.tabContaGiro.removeClass('d-none');
25305            _this3.getWalletBalance(data.result.walletId);
25306          }
25307        }).catch(function (err) {
25308          LoaderService.hide();
25309          console.error(err);
25310          _this3.tabContaGiro.remove();
25311        });
25312      }
25313    }
25314  }, {
25315    key: 'getWalletBalance',
25316    value: function getWalletBalance(walletId) {
25317      var _this4 = this;
25318
25319      var content = 'getWalletBalance?walletId=' + walletId;
25320      var headers = {
25321        Authorization: '' + SessionStorage.get("jca_token")
25322      };
25323      var headersRequest = HttpService.getSession(headers);
25324
25325      LoaderService.show();
25326      HttpService.get(content, headers).then(function (data) {
25327        LoaderService.hide();
25328        _this4.updateValuesPaymentPending(data.result.availableBalance);
25329      }).catch(function (err) {
25330        LoaderService.hide();
25331        _this4.updateValuesPaymentPending(0);
25332        console.error(err);
25333      });
25334    }
25335  }, {
25336    key: 'handlePaymentPending',
25337    value: function handlePaymentPending() {
25338      var walletExists = SessionStorage.get('walletExists');
25339      var userWallet = SessionStorage.get('user_wallet');
25340      var accountExists = SessionStorage.get('accountExists');
25341      var termsContent = $('[data-js="terms-content"]');
25342      var paymentFooter = $('.payment-footer');
25343      SessionStorage.set('flowWalletPayment', true);
25344
25345      if (accountExists === false) {
25346        this.contaGiroForm.hide();
25347        this.createWalletForm.show();
25348        termsContent.hide();
25349        paymentFooter.hide();
25350      }
25351
25352      if (!userWallet) {
25353        this.contaGiroForm.hide();
25354        this.createWalletForm.show();
25355        termsContent.hide();
25356        paymentFooter.hide();
25357        $('[data-js="button-create"]').text('Logar');
25358      }
25359
25360      if (accountExists === true && walletExists === false) {
25361        this.contaGiroForm.hide();
25362        this.createWalletForm.show();
25363        termsContent.hide();
25364        paymentFooter.hide();
25365      }
25366
25367      if (accountExists === true && walletExists === true && userWallet) {
25368        this.contaGiroForm.show();
25369        this.createWalletForm.hide();
25370        termsContent.show();
25371        paymentFooter.show();
25372      }
25373    }
25374  }, {
25375    key: 'updateValuesPaymentPending',
25376    value: function updateValuesPaymentPending(valueWallet) {
25377      var balanceFormatted = Utils.formatPrice(valueWallet ? valueWallet : 0);
25378      $('[data-js="balance-price"]').text('R$ ' + balanceFormatted);
25379
25380      var balanceFloat = this.parseCurrencyString(balanceFormatted);
25381      var totalFloat = void 0;
25382
25383      if (this.repricingV2 && this.cartService && this.cartService._cart) {
25384        totalFloat = this.cartService._cart.balanceTotal;
25385        $('.payment-pending [data-js="price-cart"]').text(Utils.formatPrice(totalFloat));
25386      } else {
25387        var total = $('[data-js="price-cart"]').first().text();
25388
25389        if (!total.includes(',')) {
25390          total += ',00';
25391        } else {
25392          var parts = total.split(',');
25393          if (parts[1].length < 2) {
25394            total += '0'.repeat(2 - parts[1].length);
25395          } else {
25396            total += ',00';
25397          }
25398        }
25399
25400        totalFloat = this.parseCurrencyString(total);
25401      }
25402
25403      if (balanceFloat >= totalFloat) {
25404        $('[data-js="pix-check"]').prop('disabled', true);
25405        $('[data-js="rectangle-pix"]').addClass('disabled');
25406      } else {
25407        $('[data-js="balance-check"]').prop('disabled', true);
25408        $('[data-js="rectangle-balance"]').addClass('disabled');
25409        var result = totalFloat - balanceFloat;
25410        $('[data-js="pix-pending-value"]').text('R$ ' + Utils.formatPrice(result));
25411        $('[data-js="insuficient-balance"]').removeClass('d-none');
25412      }
25413    }
25414  }, {
25415    key: 'parseCurrencyString',
25416    value: function parseCurrencyString(value) {
25417      return parseFloat(value.replace(/\./g, '').replace(',', '.'));
25418    }
25419  }, {
25420    key: 'isUseHub',
25421    value: function isUseHub() {
25422      return this.UseHub.val() == "true" ? true : false;
25423    }
25424  }, {
25425    key: 'isUseAdyen',
25426    value: function isUseAdyen() {
25427      return this.UseAdyen.val() === "true";
25428    }
25429  }, {
25430    key: 'initInsuranceCheck',
25431    value: function initInsuranceCheck() {
25432      var _this2 = this;
25433
25434      if (sessionStorage.getItem('insuranceChecked') === null) {
25435        sessionStorage.setItem('insuranceChecked', 'false');
25436      }
25437
25438      var insuranceChecked = sessionStorage.getItem('insuranceChecked') === 'true';
25439      this.insuranceCheck.prop('checked', insuranceChecked);
25440
25441      this.insuranceCheck.on('change', function () {
25442        var isChecked = _this2.insuranceCheck.is(':checked');
25443        sessionStorage.setItem('insuranceChecked', isChecked ? 'true' : 'false');
25444
25445        if (isChecked) {
25446          _this2.showInsuranceValue();
25447        } else {
25448          _this2.hideInsuranceValue();
25449        }
25450      });
25451    }
25452  }, {
25453    key: 'showInsuranceValue',
25454    value: function showInsuranceValue() {
25455      return true;
25456    }
25457  }, {
25458    key: 'hideInsuranceValue',
25459    value: function hideInsuranceValue() {
25460      return false;
25461    }
25462  }, {
25463    key: 'handlePayWppLayout',
25464    value: function handlePayWppLayout() {
25465      this.whatsParams = new URLSearchParams(window.location.search);
25466      this.token = this.whatsParams.get('token');
25467
25468      if (this.token && this.token.trim() !== '') {
25469        this.isPaymentWhatsapp = true;
25470
25471        $(".tablinks").parent().parent().remove();
25472        $('.card-payment-insurance').remove();
25473        $('[data-js="total-pix-container"]').remove();
25474        $('.whatsapp-payment-inputs').removeClass('d-none');
25475        $('.payment-overview-wrapper').removeClass('d-none');
25476        if (!this.showServiceFee) {
25477          this.serviceValue.parent().parent().parent().remove();
25478          this.serviceValueReturn.parent().parent().parent().remove();
25479        }
25480      } else {
25481        this.isPaymentWhatsapp = false;
25482      }
25483    }
25484  }, {
25485    key: 'handlePaymentRepricing',
25486    value: function handlePaymentRepricing() {
25487      if (this.repricingV2) {
25488        this.tabBank.hide();
25489        this.tabNupay.hide();
25490        this.nupayInfo.addClass('d-none');
25491        $('span.pix').addClass('d-none');
25492        $('p.line-discount-pix').addClass('d-none');
25493        $('[data-js="subtotal-seats-container"]').addClass('d-none');
25494        $('[data-js="convenience-fee-pix-container"]').addClass('d-none');
25495        $('[data-js="price-in-bottom-cart-pix"]').addClass('d-none');
25496        $('[data-js="card-payment-discount"]').hide();
25497        this.handleCartNegativeValue();
25498      }
25499    }
25500  }, {
25501    key: 'hasRepricingBalanceAmount',
25502    value: function hasRepricingBalanceAmount() {
25503      var cart = this.cartService && this.cartService._cart;
25504      return cart && cart.listPassengers && cart.listPassengers.some(function (passenger) {
25505        var seats = [passenger._seatDeparture, passenger._seatDepartureConnection, passenger._seatDepartureConnection2, passenger._seatReturn, passenger._seatReturnConnection, passenger._seatReturnConnection2];
25506
25507        return seats.some(function (seat) {
25508          return seat && seat._balanceAmount !== undefined && seat._balanceAmount !== null;
25509        });
25510      });
25511    }
25512  }, {
25513    key: 'isRepricingNegativeValue',
25514    value: function isRepricingNegativeValue() {
25515      return this.repricingV2 && this.hasRepricingBalanceAmount() && Math.sign(this.cartService._cart.balanceTotal) < 0;
25516    }
25517  }, {
25518    key: 'isRepricingZeroValue',
25519    value: function isRepricingZeroValue() {
25520      return this.repricingV2 && this.hasRepricingBalanceAmount() && this.cartService._cart.balanceTotal === 0;
25521    }
25522  }, {
25523    key: 'handleCartNegativeValue',
25524    value: function handleCartNegativeValue() {
25525      var _this6 = this;
25526
25527      if (_this6.isRepricingNegativeValue()) {
25528        $('.payment-selector-wrapper').addClass('repricing-negative');
25529        $('.header-text').text('Dados Para Reembolso');
25530        _this6.remarkForm.removeClass("d-none");
25531        _this6.showCheckConditions();
25532        _this6.checkConditions.off('change').on('change', function (e) {
25533          $(e.target).is(':checked') && _this6.validRemarkForm() ? _this6.enableSubmitButton() : _this6.disableSubmitButton();
25534        });
25535        $('[data-js^="input-remark"]').on('input', function () {
25536          _this6.checkConditions.is(':checked') && _this6.validRemarkForm() ? _this6.enableSubmitButton() : _this6.disableSubmitButton();
25537        });
25538        SessionStorage.set('paymentNegative', true);
25539      } else if (this.isRepricingZeroValue()) {
25540        _this6.handleCartZeroValue();
25541      }
25542    }
25543  }, {
25544    key: 'handleCartZeroValue',
25545    value: function handleCartZeroValue() {
25546      var _this7 = this;
25547
25548      $('.payment-selector-wrapper').addClass('repricing-zero');
25549      _this7.insuranceContainer.hide();
25550      $('.card-payment-insurance').hide();
25551      _this7.insuranceCheck.prop('checked', false);
25552      _this7.remarkForm.addClass("d-none");
25553      _this7.showCheckConditions();
25554      SessionStorage.set('paymentNegative', true);
25555      _this7.checkConditions.off('change.repricingZero').on('change.repricingZero', function (e) {
25556        $(e.target).is(':checked') ? _this7.enableSubmitButton() : _this7.disableSubmitButton();
25557      });
25558    }
25559  }, {
25560    key: 'sendBeginCheckoutToAnalytics',
25561    value: function sendBeginCheckoutToAnalytics() {
25562      var passenger = SessionStorage.get("passenger") || {};
25563      var formData = SessionStorage.get("formData");
25564      var cart = SessionStorage.get("cart") || {};
25565      var discountData = SessionStorage.get('discountData') || {};
25566      var tripToRepricing = SessionStorage.get('tripToRepricing');
25567      var fullName = passenger._name || '';
25568      var nameParts = fullName.split(' ');
25569      var firstName = nameParts[0] || '';
25570      var lastName = nameParts.slice(1).join(' ') || '';
25571      var fullPhone = "+55" + (passenger._areaCode || '') + (passenger._phone || '');
25572      var deviceType = /Mobi|Android/i.test(navigator.userAgent) ? 'mobile' : 'web';
25573      var dataLayerView = [];
25574      var orderService = 0;
25575      var passengerType = null;
25576      var valueTotal = 0;
25577      var totalRateDiscount = 0;
25578      var index = 1;
25579      var departDateInitial = SessionStorage.get("departureDate");
25580      var returnDateInitial = SessionStorage.get("returnDate");
25581
25582      function optimizeString(str) {
25583         return str.replace(/[\s\-\(\):]+/g, '');
25584      }
25585
25586      var totals = (cart._listOffer || []).reduce((acc, offer) => {
25587        acc.value += offer._priceWithDiscountPix || 0;
25588        acc.cartValue += offer._price || 0;
25589        return acc;
25590      }, { value: 0, cartValue: 0 });
25591
25592
25593      var allStudentData = SessionStorage.get('allStudentData');
25594
25595      if (cart._listOffer && cart._listPassengers) {
25596        cart._listOffer.forEach(function (offer) {
25597          orderService = offer._service;
25598          cart._listPassengers.forEach(function (listPassengers) {
25599             var passengerType = null;
25600             if (listPassengers._type === "CHILD" || passenger._type === "CHILD_A") {
25601                passengerType = 'Criança';
25602             } else if (listPassengers._type === "ADULT") {
25603                passengerType = 'Adulto';
25604             }
25605
25606             var itemName = [
25607                offer._company._origin._label,
25608                offer._company._destination._label
25609             ].join(' + ');
25610
25611             itemName = optimizeString(itemName);
25612
25613             if (allStudentData) {
25614                var studentData = allStudentData.find(student => student.document === Number(listPassengers._documentNumber));
25615                var studentId = studentData ? studentData.clientId : null;
25616             }
25617
25618            if (studentData) {
25619              if (listPassengers._seatDeparture && listPassengers._seatDeparture._rate) {
25620                totalRateDiscount += parseFloat(listPassengers._seatDeparture._rate);
25621              }
25622              if (listPassengers._seatReturn && listPassengers._seatReturn._rate) {
25623                totalRateDiscount += parseFloat(listPassengers._seatReturn._rate);
25624              }
25625            }
25626
25627            var departureDate = departDateInitial;
25628            var returnDate = returnDateInitial;
25629
25630            var busSeat = null;
25631            var price = 0;
25632            if (Number(offer._service) === listPassengers._seatDeparture._service) {
25633              busSeat = listPassengers._seatDeparture._seatNumber;
25634              price = parseFloat(listPassengers._seatDeparture._price || 0);
25635            } else if (Number(offer._service) === listPassengers._seatReturn._service) {
25636              busSeat = listPassengers._seatReturn._seatNumber;
25637              price = parseFloat(listPassengers._seatReturn._price || 0);
25638            } else if (Number(offer._service) === listPassengers._seatDepartureConnection._service) {
25639               busSeat = listPassengers._seatDepartureConnection._seatNumber;
25640                price = parseFloat(listPassengers._seatDepartureConnection._price || 0);
25641            } else if (Number(offer._service) === listPassengers._seatReturnConnection._service) {
25642               busSeat = listPassengers._seatReturnConnection._seatNumber;
25643               price = parseFloat(listPassengers._seatReturnConnection._price || 0);
25644            }
25645
25646            var aux = {
25647               item_name: itemName,
25648               item_id: offer._service,
25649               item_brand: offer._company._companyName,
25650               item_variant: offer._classtype._className,
25651               item_category: $("#siteName").val(),
25652               item_category2: offer._company._companyName,
25653               item_category3: offer._company._companyName,
25654               benefit: (listPassengers._type === "CHILD") || allStudentData ? true : false,
25655               departure_date: departureDate,
25656               return_date: returnDate,
25657               price: price.toFixed(2),
25658               adults_passengers: formData.passengers[0].quantity, // Quantidade de passageiros adultos
25659               infants_passengers: formData.passengers[2].quantity, // Quantidade de passageiros crianças de colo (não pagantes)
25660               children_passengers: formData.passengers[1].quantity, // Quantidade de passageiros crianças (pagantes)
25661               quantity: 1,
25662               bus_seat: busSeat,
25663               index: index
25664            };
25665
25666            dataLayerView.push(aux);
25667            index += 1;
25668          });
25669        });
25670      }
25671
25672      var couponDiscountValue = 0;
25673      var isChild = false;
25674      if (discountData.result && discountData.result.seats && discountData.result.seats.transactions) {
25675        discountData.result.seats.transactions.forEach(function (transaction) {
25676          isChild = transaction.child;
25677          if (transaction.voucherValue) {
25678            couponDiscountValue += transaction.voucherValue;
25679          }
25680        });
25681      }
25682
25683      var discountDataObj = {
25684        coupon: couponDiscountValue,
25685        ticket_type: isChild ? 'Criança' : 0,
25686        payment_discount: discountData ? couponDiscountValue : 0,
25687        discount_total: couponDiscountValue || 0
25688      };
25689
25690      var fullPriceTotal = 0;
25691      var penaltyTotal = 0;
25692
25693      if (tripToRepricing) {
25694        for (var key in tripToRepricing) {
25695          if (tripToRepricing.hasOwnProperty(key)) {
25696            var array = tripToRepricing[key];
25697            if (Array.isArray(array)) {
25698              array.forEach(function (trip) {
25699                if (trip.fullPrice) {
25700                  fullPriceTotal += trip.fullPrice;
25701                }
25702                if (trip.penalty) {
25703                  penaltyTotal += trip.penalty;
25704                }
25705              });
25706            }
25707          }
25708        }
25709      }
25710
25711      var rescheduleInfo = {
25712        penalty: tripToRepricing ? penaltyTotal : null,
25713        current_ticket_price: tripToRepricing ? totals.cartValue : null,
25714        previous_ticket_price: tripToRepricing ? fullPriceTotal : null,
25715        price_difference: tripToRepricing ? totals.cartValue - fullPriceTotal : null
25716      };
25717
25718      var priceComposition = {
25719          tariff: 0,
25720          fees: {
25721              charge: 0,
25722              toll: 0,
25723              boarding: 0,
25724              insurance: 0,
25725              w2i_insurance: 0,
25726              others: 0,
25727              fees_total: 0
25728          },
25729          seat_lock_total_value: 0,
25730          optional_insurance: 0,
25731          tax: {
25732              convenience_fee: 0,
25733              service_fee: 0,
25734              tax_total: 0
25735          },
25736          price_total: 0
25737      };
25738
25739      (cart._listPassengers || []).forEach(function(passenger) {
25740          var convenienceFee = 0;
25741          var rate = 0;
25742
25743          ['_seatDeparture', '_seatReturn', '_seatDepartureConnection', '_seatReturnConnection'].forEach(function(seatType) {
25744              if (passenger[seatType] && passenger[seatType]._service) {
25745                  rate += parseFloat(passenger[seatType]._rate || 0);
25746                  priceComposition.fees.toll += parseFloat(passenger[seatType]._toll || 0);
25747                  priceComposition.fees.boarding += parseFloat(passenger[seatType]._boardingFee || 0);
25748                  priceComposition.fees.others += 0;
25749                  priceComposition.seat_lock_total_value += parseFloat(passenger[seatType]._seatSaleLockValueCalculate || 0);
25750                  convenienceFee += parseFloat(passenger[seatType]._convenienceFee || 0);
25751              }
25752          });
25753
25754          priceComposition.tariff += rate;
25755          priceComposition.tax.convenience_fee += convenienceFee;
25756      });
25757
25758      priceComposition.fees.fees_total = priceComposition.fees.charge + priceComposition.fees.toll + (priceComposition.fees.boarding + priceComposition.fees.others);
25759
25760      priceComposition.tax.tax_total = priceComposition.tax.convenience_fee + priceComposition.tax.service_fee;
25761
25762      priceComposition.price_total = priceComposition.tariff + priceComposition.fees.fees_total + priceComposition.tax.tax_total + priceComposition.seat_lock_total_value;
25763
25764      priceComposition.tariff = priceComposition.tariff.toFixed(2);
25765      priceComposition.fees.charge = priceComposition.fees.charge.toFixed(2);
25766      priceComposition.fees.toll = priceComposition.fees.toll.toFixed(2);
25767      priceComposition.fees.boarding = priceComposition.fees.boarding.toFixed(2);
25768      priceComposition.fees.insurance = priceComposition.fees.insurance.toFixed(2);
25769      priceComposition.fees.w2i_insurance = priceComposition.fees.w2i_insurance.toFixed(2);
25770      priceComposition.fees.others = priceComposition.fees.others.toFixed(2);
25771      priceComposition.fees.fees_total = priceComposition.fees.fees_total.toFixed(2);
25772      priceComposition.seat_lock_total_value = priceComposition.seat_lock_total_value.toFixed(2);
25773      priceComposition.tax.convenience_fee = priceComposition.tax.convenience_fee.toFixed(2);
25774      priceComposition.tax.service_fee = priceComposition.tax.service_fee.toFixed(2);
25775      priceComposition.tax.tax_total = priceComposition.tax.tax_total.toFixed(2);
25776      priceComposition.price_total = priceComposition.price_total.toFixed(2);
25777
25778      valueTotal = priceComposition.price_total;
25779
25780
25781      window.dataLayer = window.dataLayer || [];
25782      window.dataLayer.push({
25783        event: "begin_checkout",
25784        sales_origin: $("#siteName").val(),
25785        device: deviceType,
25786        ecommerce: {
25787           currency: "BRL",
25788           value: valueTotal,
25789           cart_total: valueTotal,
25790           search_data: Utils.getSearchData(formData),
25791           search_parameters: Utils.getSearchParameters(formData),
25792           discounts: discountDataObj,
25793           price_composition: priceComposition,
25794           reschedule_info: rescheduleInfo,
25795           order_id: orderService,
25796           items: dataLayerView,
25797           user_data: Utils.getUserData()
25798        },
25799      });
25800    }
25801  }, {
25802    key: 'getServerTime',
25803    value: function getServerTime(callback) {
25804      var _this2 = this;
25805
25806      if ( $('#wcmmodeedit').val() == 'true' ) return;
25807
25808      LoaderService.show();
25809      HttpService.getAEM('time.json?cache=1').then(function (data) {
25810        var time = data.result.time;
25811        var offset = data.result.offset;
25812
25813        time = time.replace("Z", "");
25814        var timezoneOffset = new Date(time).getTimezoneOffset();
25815
25816        // 180 is the difference between brasilia timezone and utc-0 in minutes
25817        time = timezoneOffset > 180 ? time : time + offset;
25818        _this2.timeExact = new Date(time).getTime();
25819        LoaderService.hide();
25820        callback(_this2.timeExact);
25821      }).catch(function () {
25822        console.error(err.message);
25823        _this2.timeExact = DateFormatter.getValidDateFormat();
25824        LoaderService.hide();
25825        callback(_this2.timeExact);
25826      });
25827    }
25828  }, {
25829    key: 'getAuthorizationToken',
25830    value: function getServerTime(callback) {
25831      var _this2 = this;
25832
25833      if ( $('#wcmmodeedit').val() == 'true' ) return;
25834
25835      HttpService.getToken('authorizationWhatsapp' + '#' + this.token).then(function (data) {
25836        _this2.wppToken = data.result.token;
25837        SessionStorage.set('jca_token', data.result.token);
25838        callback(_this2.wppToken);
25839      }).catch(function () {
25840
25841      });
25842    }
25843  }, {
25844    key: 'loadStoredCards',
25845    value: function loadStoredCards() {
25846      var _this5 = this;
25847
25848      if (this.cardsLoaded) {
25849        return;
25850      }
25851
25852      LoaderService.show();
25853
25854      var headers = {
25855        'Authorization': '' + SessionStorage.get('jca_token'),
25856        flowPayment: "Adyen"
25857      };
25858
25859      HttpService.get('getCard', headers).then(function (data) {
25860        LoaderService.hide();
25861        _this5.handleStoredCards(data.result);
25862        _this5.cardsLoaded = true;
25863      }).catch(function (err) {
25864        LoaderService.hide();
25865        console.log(err);
25866      });
25867    }
25868  }, {
25869    key: 'loadStoredCardsMalga',
25870    value: function loadStoredCardsMalga() {
25871      var _this6 = this;
25872
25873      LoaderService.show();
25874      var headers = {
25875        'Authorization':  this.isPaymentWhatsapp ? this.wppToken : SessionStorage.get('jca_token'),
25876        flowPayment: "malga"
25877      };
25878
25879      HttpService.get('getCardMalga', headers).then(function (data) {
25880        LoaderService.hide();
25881        _this6.handleStoredCards(data.result);
25882      }).catch(function (err) {
25883        LoaderService.hide();
25884        console.log(err);
25885      });
25886    }
25887  }, {
25888    key: 'initPaymentColors',
25889    value: function initPaymentColors() {
25890      var tabActiveColor = $('[data-js="payment-tab-color-active"]').data('color');
25891      var borderActiveColor = $('[data-js="payment-border-color-active"]').data('color');
25892      var tabColor = $('[data-js="payment-tab-color"]').data('color');
25893
25894      $('.tablinks').css({
25895        'border': 'none'
25896      });
25897
25898      $('.tablinks p').css({
25899        'color': tabColor
25900      });
25901
25902      $('.tablinks.active p').css({
25903        'color': tabActiveColor
25904      });
25905
25906      $('.tablinks.active').css({
25907        'border-bottom': '3px solid ' + borderActiveColor
25908      });
25909    }
25910  }, {
25911    key: 'handleStoredCards',
25912    value: function handleStoredCards(cards) {
25913      var _this4 = this;
25914
25915      var $ul = $('[data-js="stored-cards-list"]');
25916      var content = [];
25917
25918      cards.forEach(function (card) {
25919        var srcImage = Utils.renderCreditCardImage(card.paymentMethod);
25920
25921        content.push('\n            <li>\n                <button type="button" class="stored-cards-item" data-card-token=' + card.token + ' data-holder-name="' + card.holderName + '">  \n                    <img src="' + srcImage + '" title="Logo ' + card.paymentMethod + '" alt="Logotipo ' + card.paymentMethod + '" id="' + card.paymentMethod.replace(/ /g, '-') + '" />\n                    <div class="d-flex mt-2 flex-row align-items-start justify-content-center">\n                        <span>\n                            <p>****</p>\n                            <p>' + card.cardSummary + '</p>\n                        </span>\n                    </div>\n                </button>\n            </li>\n        ');
25922      });
25923
25924      $ul.append(content.join(''));
25925
25926      if (cards.length > 3) {
25927        $ul.slick({
25928          dots: true,
25929          arrows: false,
25930          infinite: false,
25931          speed: 300,
25932          slidesToShow: 4,
25933          slidesToScroll: 1,
25934          centerMode: false,
25935          variableWidth: false
25936        });
25937      }
25938
25939      $('.stored-cards-item').click(function (e) {
25940        $(e.currentTarget).parent().siblings().removeClass('active');
25941        $(e.currentTarget).parent().addClass('active');
25942
25943        if ($(e.currentTarget).parent().hasClass('new-card-item')) return;
25944
25945        var holderName = $(e.currentTarget).data('holder-name');
25946        $('#input-name-card').val(holderName);
25947
25948        _this4.storedCardToken = $(e.currentTarget).data('card-token');
25949
25950        if ($('.card-form-malga').length) {
25951          $('#stored-cvv-wrapper').removeClass('d-none');
25952          $('#securityCode').val('').focus().trigger('input');
25953          $('#securityCode').val('').focus();
25954          $('.card-form-malga .field.col-12').hide();
25955          $('#input-cpf').hide();
25956        } else {
25957          var recurringDetailReference = String($(e.currentTarget).data('card-token'));
25958          var headers = { 'Authorization': '' + SessionStorage.get('jca_token') };
25959
25960          LoaderService.show();
25961          HttpService.get('getPaymentMethod', headers).then(function (data) {
25962            LoaderService.hide();
25963            _this4.loadAdyenIframeToken(data.result, recurringDetailReference);
25964          }).catch(function (err) {
25965            LoaderService.hide();
25966            console.error(err);
25967          });
25968        }
25969        _this4.updateSubmitButtonState();
25970      });
25971    }
25972  }, {
25973    key: 'getCreditCardInputPlaceholderMessages',
25974    value: function getCreditCardInputPlaceholderMessages() {
25975      return {
25976        'numberCreditCardPlaceholderMessage': $('[data-js="credit-card-number-placeholder"]').data('text'),
25977        'expiredDateCreditCardPlaceholderMessage': $('[data-js="credit-card-expired-date-placeholder"]').data('text'),
25978        'cvcCreditCardPlaceholderMessage': $('[data-js="credit-card-cvc-placeholder"]').data('text')
25979      };
25980    }
25981  }, {
25982    key: 'loadAdyenIframeToken',
25983    value: function loadAdyenIframeToken(data, recurringDetailReference) {
25984      var _this5 = this;
25985
25986      this.isIframeValid = false;
25987      this.disableSubmitButton();
25988      var selectedCard = data.filter(function (card) {
25989        return card.recurringDetailReference === recurringDetailReference;
25990      }).shift();
25991      var token = selectedCard.recurringDetailReference;
25992
25993      var parseRecurringCard = function parseRecurringCard(selectedCard) {
25994        var type = selectedCard.type,
25995          name = selectedCard.name;
25996        var _selectedCard$storedD = selectedCard.storedDetails.card,
25997          expiryMonth = _selectedCard$storedD.expiryMonth,
25998          expiryYear = _selectedCard$storedD.expiryYear,
25999          holderName = _selectedCard$storedD.holderName,
26000          number = _selectedCard$storedD.number;
26001
26002        var id = selectedCard.recurringDetailReference;
26003
26004        return {
26005          brand: type,
26006          expiryMonth: expiryMonth,
26007          expiryYear: expiryYear,
26008          holderName: holderName,
26009          id: id,
26010          lastFour: number,
26011          name: name,
26012          type: 'scheme'
26013        };
26014      };
26015
26016      var handleOnChange = function handleOnChange(state) {
26017        _this5.isIframeTokenValid = $('#stored-card').find('.adyen-checkout__card__cvc__input').attr('isvalid') === "true" ? true : false;
26018
26019        if (_this5.isIframeTokenValid) {
26020          _this5.securityCodeEncrypted = state.data.paymentMethod.encryptedSecurityCode;
26021        }
26022      };
26023
26024      var listenIframe = function listenIframe() {
26025        $('body form').find('span.adyen-checkout__input').bind("DOMSubtreeModified", function () {
26026          setTimeout(function () {
26027            if (_this5.isFormValid() && _this5.checkConditions.is(':checked')) {
26028              _this5.enableSubmitButton();
26029            } else {
26030              _this5.disableSubmitButton();
26031            }
26032          }, 100);
26033        });
26034      };
26035
26036      var refreshPaymentForm = function refreshPaymentForm(selectedCard) {
26037        var holderName = selectedCard.storedDetails.card.holderName;
26038
26039
26040        $('#input-cpf').val(' ').closest('div.field').hide();
26041        $('#input-name-card').val(holderName);
26042        $('[data-js="recurring-content"]').hide();
26043        $('[data-js="recurring-content"]').find('input[type="checkbox"]').prop('checked', false);
26044        $('[data-js="new-card-item"]').show();
26045      };
26046
26047      var _getCreditCardInputPl = this.getCreditCardInputPlaceholderMessages(),
26048        numberCreditCardPlaceholderMessage = _getCreditCardInputPl.numberCreditCardPlaceholderMessage,
26049        expiredDateCreditCardPlaceholderMessage = _getCreditCardInputPl.expiredDateCreditCardPlaceholderMessage,
26050        cvcCreditCardPlaceholderMessage = _getCreditCardInputPl.cvcCreditCardPlaceholderMessage;
26051
26052      var translations = {
26053        "pt_BR": {
26054          "creditCard.numberField.placeholder": numberCreditCardPlaceholderMessage,
26055          "creditCard.expiryDateField.placeholder": expiredDateCreditCardPlaceholderMessage,
26056          "creditCard.cvcField.placeholder": cvcCreditCardPlaceholderMessage
26057        }
26058      };
26059
26060      var configuration = {
26061        locale: 'pt_BR',
26062        translations: translations,
26063        environment: this.environment,
26064        originKey: this.originKey,
26065        onChange: handleOnChange
26066      };
26067
26068      var customConfiguration = {
26069        styles: {
26070          base: {
26071            color: "#223B82",
26072            fontSize: "13px",
26073            fontWeight: "700",
26074            letterSpacing: "normal"
26075          },
26076          placeholder: {
26077            color: "rgba(34,59,130,0.7)",
26078            fontWeight: "600"
26079          },
26080          error: {
26081            color: "#E30613"
26082          }
26083        },
26084        onLoad: refreshPaymentForm(selectedCard),
26085        onConfigSuccess: listenIframe
26086      };
26087
26088      $(document).ready(function () {
26089        $('#component-container').remove();
26090        $('#stored-card').remove();
26091        var iframeDiv = $('<div id="stored-card" data-token=' + token + '></div>');
26092        $('[data-js="iframe-wrapper"]').append(iframeDiv);
26093        var checkout = new AdyenCheckout(configuration);
26094        checkout.create('card', customConfiguration, parseRecurringCard(selectedCard)).mount('#stored-card');
26095      });
26096    }
26097  }, {
26098    key: 'loadPaymentMalgaOrAdyen',
26099    value: function loadPaymentMalgaOrAdyen() {
26100      if (!SessionStorage.get('paymentNegative') == true) {
26101        if (this.isUseHub) {
26102          var randomNumber = Math.random() * 100;
26103          if (this.isUseAdyen && randomNumber < 50) {
26104            $('.adyen-only').show();
26105            $('.malga-only').hide();
26106
26107            $('.card-form-malga').detach();
26108            $('#component-container').show();
26109            this.loadStoredCards();
26110            this.checkQtdCreditCard();
26111            this.isMalgaActive = false;
26112          } else {
26113            $('.adyen-only').hide();
26114            $('.malga-only').show();
26115
26116            $('.card-form-malga').show();
26117            $('#component-container').detach();
26118            this.loadStoredCardsMalga();
26119            this.loadMalgaIframe();
26120            this.isMalgaActive = true;
26121          }
26122        } else {
26123          if (this.isUseAdyen) {
26124            $('.adyen-only').show();
26125            $('.malga-only').hide();
26126
26127            $('.card-form-malga').detach();
26128            $('#component-container').show();
26129            this.loadStoredCards();
26130            this.checkQtdCreditCard();
26131            this.isMalgaActive = false;
26132          } else {
26133            $('.adyen-only').hide();
26134            $('.malga-only').show();
26135
26136            $('.card-form-malga').show();
26137            $('#component-container').detach();
26138            this.loadStoredCardsMalga();
26139            this.loadMalgaIframe();
26140            this.isMalgaActive = true;
26141          }
26142        }
26143      }
26144    }
26145  }, {
26146    key: 'loadAdyenIframe',
26147    value: function loadAdyenIframe() {
26148      var _this6 = this;
26149
26150      this.isIframeTokenValid = false;
26151      this.disableSubmitButton();
26152
26153      var handleOnChange = function handleOnChange(state) {
26154        _this6.isIframeValid = state.isValid;
26155
26156        if (state.isValid) {
26157          _this6.cardNumberEncrypted = state.data.paymentMethod.encryptedCardNumber;
26158          _this6.expiryMontEncrypted = state.data.paymentMethod.encryptedExpiryMonth;
26159          _this6.expiryYearEncrypted = state.data.paymentMethod.encryptedExpiryYear;
26160          _this6.securityCodeEncrypted = state.data.paymentMethod.encryptedSecurityCode;
26161        }
26162      };
26163
26164      var listenIframe = function listenIframe() {
26165        var ccvlabel = $('#component-container').find('.adyen-checkout__field__cvc').find('.adyen-checkout__label');
26166        ccvlabel.append('<a class="button-info-i" href="javascript:void(0)" id="button-info-credit" data-js="button-info-credit">	i</a>');
26167        _this6.buttonSecInfo = $('[data-js="button-info-credit"]');
26168
26169        _this6.buttonSecInfo.click(function (e) {
26170          _this6.containerSecInfo.addClass('active');
26171          _this6.containerSecInfo.focus();
26172        });
26173
26174        _this6.closeSecInfo.click(function () {
26175          _this6.containerSecInfo.removeClass('active');
26176        }).blur(function () {
26177          _this6.containerSecInfo.removeClass('active');
26178          _this6.buttonSecInfo.focus();
26179        });
26180
26181        $('body form').find('span.adyen-checkout__input').bind("DOMSubtreeModified", function () {
26182          setTimeout(function () {
26183            if (_this6.isFormValid() && _this6.checkConditions.is(':checked')) {
26184              _this6.enableSubmitButton();
26185            } else {
26186              _this6.disableSubmitButton();
26187            }
26188          }, 100);
26189        });
26190
26191        _this6.loadPaymentMalgaOrAdyen();
26192      };
26193
26194      var _getCreditCardInputPl2 = this.getCreditCardInputPlaceholderMessages(),
26195        numberCreditCardPlaceholderMessage = _getCreditCardInputPl2.numberCreditCardPlaceholderMessage,
26196        expiredDateCreditCardPlaceholderMessage = _getCreditCardInputPl2.expiredDateCreditCardPlaceholderMessage,
26197        cvcCreditCardPlaceholderMessage = _getCreditCardInputPl2.cvcCreditCardPlaceholderMessage;
26198
26199      var translations = {
26200        "pt_BR": {
26201          "creditCard.numberField.placeholder": numberCreditCardPlaceholderMessage,
26202          "creditCard.expiryDateField.placeholder": expiredDateCreditCardPlaceholderMessage,
26203          "creditCard.cvcField.placeholder": cvcCreditCardPlaceholderMessage
26204        }
26205      };
26206
26207      var configuration = {
26208        locale: 'pt_BR',
26209        translations: translations,
26210        environment: this.environment,
26211        originKey: this.originKey,
26212        onChange: handleOnChange
26213      };
26214
26215      var customConfiguration = {
26216        styles: {
26217          base: {
26218            color: "#223B82",
26219            fontSize: "13px",
26220            fontWeight: "700",
26221            letterSpacing: "normal"
26222          },
26223          placeholder: {
26224            color: "rgba(34,59,130,0.7)",
26225            fontWeight: "600"
26226          },
26227          error: {
26228            color: "#E30613"
26229          }
26230        },
26231        onLoad: listenIframe
26232      };
26233
26234      $(document).ready(function () {
26235        $('#stored-card').remove();
26236        var iframeDiv = $('<div id="component-container" data-active=\'true\'></div>');
26237        $('[data-js="iframe-wrapper"]').append(iframeDiv);
26238        var checkout = new AdyenCheckout(configuration);
26239        checkout.create('card', customConfiguration).mount('#component-container');
26240      });
26241    }
26242  }, {
26243    key: 'getMalgaCredentials',
26244    value: function getMalgaCredentials() {
26245      var credentials = {
26246        apiKey: $("#malgaApiKey").val(),
26247        clientId: $("#malgaClientId").val(),
26248        sandbox: $("#malgaSandbox").val(),
26249      };
26250
26251      return credentials;
26252    }
26253  }, {
26254    key: 'loadMalgaIframe',
26255    value: function loadMalgaIframe() {
26256      var _this10 = this;
26257
26258      var _getMalgaCredentials = this.getMalgaCredentials(),
26259        apiKey = _getMalgaCredentials.apiKey,
26260        clientId = _getMalgaCredentials.clientId,
26261        sandbox = _getMalgaCredentials.sandbox;
26262
26263      this.malgaFieldValidity = {
26264        cardNumber: false,
26265        cardExpirationDate: false,
26266        cardCvv: false,
26267        cardHolderName: false
26268      };
26269      this.malgaFieldTouched = {
26270        cardNumber: false,
26271        cardExpirationDate: false,
26272        cardCvv: false,
26273        cardHolderName: false
26274      };
26275
26276      var malga = new MalgaTokenization({
26277        apiKey: apiKey,
26278        clientId: clientId,
26279        options: {
26280          config: {
26281            defaultValidation: true,
26282            fields: {
26283              cardNumber: { container: 'card-number', placeholder: '1234 5678 9012 3456' },
26284              cardHolderName: { container: 'card-holder-name', placeholder: 'Nome do titular' },
26285              cardExpirationDate: { container: 'card-expiration-date', placeholder: 'MM/AA' },
26286              cardCvv: { container: 'card-cvv', placeholder: '123' }
26287            },
26288            styles: {
26289              input: {
26290                width: '100%',
26291                height: '100%',
26292                border: 'none',
26293                background: 'transparent',
26294                padding: '0px !important',
26295                color: '#1e5862',
26296                fontSize: "13px",
26297                fontWeight: "700"
26298              }
26299            },
26300            preventAutofill: false
26301          },
26302          sandbox: sandbox
26303        }
26304
26305      });
26306
26307      var keyId = {
26308        'card-number': 'cardNumber',
26309        'card-expiration-date': 'cardExpirationDate',
26310        'card-cvv': 'cardCvv',
26311        'card-holder-name': 'cardHolderName'
26312      };
26313
26314      var refreshButton = function refreshButton() {
26315        return _this10.updateSubmitButtonState();
26316      };
26317
26318      malga.on('cardTypeChanged', function (_ref) {
26319        var card = _ref.card,
26320          field = _ref.field;
26321
26322        var imgElement = $('#' + field).closest('.input-container').find('.card-image');
26323        var src = card && card.type ? _this10.getCardImagePath(card.type) : '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/nocard.png';
26324        if (!imgElement.attr('src') || imgElement.attr('src').split('/').pop() !== src.split('/').pop()) {
26325          imgElement.attr('src', src).show();
26326        }
26327      });
26328
26329      malga.on('focus', function (_ref2) {
26330        var field = _ref2.field;
26331
26332        _this10.malgaFieldTouched[keyId[field]] = true;
26333        var container = $('#' + field).closest('.input-container');
26334        container.find('.error-message').remove();
26335        container.find('.card-image.checkmark').addClass('d-none');
26336        $('#' + field).removeClass('malga-hosted-field-valid malga-hosted-field-invalid');
26337        container.find('.card-image').removeClass('error-position');
26338      });
26339
26340      malga.on('validity', function (_ref3) {
26341        var valid = _ref3.valid,
26342          field = _ref3.field,
26343          error = _ref3.error,
26344          empty = _ref3.empty;
26345
26346        var key = keyId[field];
26347        var touched = _this10.malgaFieldTouched[key];
26348        var ok = valid && !empty;
26349        _this10.malgaFieldValidity[key] = ok;
26350
26351        var fieldElement = $('#' + field);
26352        var container = fieldElement.closest('.input-container');
26353        var checkmark = container.find('.card-image.checkmark');
26354        var errorMessage = fieldElement.siblings('.error-message');
26355        var cardImage = container.find('.card-image');
26356
26357        if (touched && !ok) {
26358          fieldElement.addClass('malga-hosted-field-invalid').removeClass('malga-hosted-field-valid');
26359          checkmark.addClass('d-none');
26360          if (field === 'card-number') cardImage.addClass('error-position');
26361          if (!errorMessage.length) {
26362            var msg = {
26363              'card-number': 'Número do cartão inválido.',
26364              'card-cvv': 'CVV inválido.',
26365              'card-expiration-date': 'Data de validade inválida.',
26366              'card-holder-name': 'Nome inválido.'
26367            }[field] || error && error.message || 'Erro desconhecido.';
26368            $('<span>').addClass('error-message').text(msg).insertAfter(fieldElement);
26369          }
26370        } else if (ok) {
26371          fieldElement.addClass('malga-hosted-field-valid').removeClass('malga-hosted-field-invalid');
26372          errorMessage.remove();
26373          checkmark.removeClass('d-none');
26374          cardImage.removeClass('error-position');
26375        } else {
26376          fieldElement.removeClass('malga-hosted-field-valid malga-hosted-field-invalid');
26377          checkmark.addClass('d-none');
26378          errorMessage.remove();
26379          cardImage.removeClass('error-position');
26380        }
26381
26382        refreshButton();
26383      });
26384
26385      this.malgaInstance = malga;
26386    }
26387  }, {
26388    key: 'showInvalidMessage',
26389    value: function showInvalidMessage(element, msg) {
26390      element.find('.tip').text(msg);
26391      element.addClass('invalid');
26392    }
26393  }, {
26394    key: 'hideInvalidMessage',
26395    value: function hideInvalidMessage(element) {
26396      element.removeClass('invalid');
26397    }
26398  }, {
26399    key: 'validateIframe',
26400    value: function validateIframe() {
26401      return this.isIframeValid || this.isIframeTokenValid;
26402    }
26403  }, {
26404    key: 'getCardType',
26405    value: function getCardType(cardNumber) {
26406      var cleanedCardNumber = cardNumber.toString().replace(/\s/g, '');
26407
26408      // Expressões regulares para verificar o tipo de cartão
26409      var visaRegex = /^4[0-9]{12}(?:[0-9]{3})?$/;
26410      var mastercardRegex = /^5[1-5][0-9]{14}$/;
26411      var amexRegex = /^3[47][0-9]{13}$/;
26412      var discoverRegex = /^6(?:011|5[0-9]{2})[0-9]{12}$/;
26413      var eloRegex = /^(?:636368|438935|504175|451416|636297)\d{10}$/;
26414      var dinersRegex = /^3(?:0[0-5]|[68][0-9])[0-9]{11}$/;
26415      var jcbRegex = /^(?:2131|1800|35\d{3})\d{11}$/;
26416      var vrRegex = /^627416[0-9]{10}$/;
26417      var sodexoRegex = /^606070[0-9]{10}$/;
26418
26419      // Verifica o tipo de cartão com base nas expressões regulares
26420      if (visaRegex.test(cleanedCardNumber)) {
26421        return 'visa';
26422      } else if (mastercardRegex.test(cleanedCardNumber)) {
26423        return 'mastercard';
26424      } else if (amexRegex.test(cleanedCardNumber)) {
26425        return 'amex';
26426      } else if (discoverRegex.test(cleanedCardNumber)) {
26427        return 'discover';
26428      } else if (eloRegex.test(cleanedCardNumber)) {
26429        return 'elo';
26430      } else if (dinersRegex.test(cleanedCardNumber)) {
26431        return 'dinners';
26432      } else if (jcbRegex.test(cleanedCardNumber)) {
26433        return 'jcb';
26434      } else if (vrRegex.test(cleanedCardNumber)) {
26435        return 'vr';
26436      } else if (sodexoRegex.test(cleanedCardNumber)) {
26437        return 'sodexo';
26438      } else {
26439        return 'unknown';
26440      }
26441    }
26442  }, {
26443    key: 'getCardImagePath',
26444    value: function getCardImagePath(cardType) {
26445      var cardImagePaths = {
26446        visa: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/visa.png',
26447        mastercard: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/mastercard.png',
26448        amex: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/amex.png',
26449        discover: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/discover.png',
26450        elo: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/elo.png',
26451        dinners: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/dinners.png',
26452        jcb: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/jcb.png',
26453        vr: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/vr.png',
26454        sodexo: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/sodexo.jpg',
26455        unknown: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/nocard.png'
26456      };
26457
26458      return cardImagePaths[cardType];
26459    }
26460  }, {
26461    key: 'loadCreditCardMask',
26462    value: function loadCreditCardMask() {
26463      var _this8 = this;
26464
26465      var cardNumberInput = $('#cardNumber');
26466      var expiryDateInput = $('#expiryDate');
26467      var cvvInput = $('#securityCode');
26468      var cardImage = $('.card-image');
26469      var cardNumberWarningMessageElement = cardNumberInput.siblings('.tips').find('.tip.warning');
26470      var expiryDateWarningMessageElement = expiryDateInput.siblings('.tips').find('.tip.warning');
26471      var cvvWarningMessageElement = cvvInput.siblings('.tips').find('.tip.warning');
26472
26473      var numberInvalidMsg = _this8.invalidCardMessage;
26474      var expiryDateMsg = _this8.invalidExpirationMessage;
26475      var cvvInvalidMsg = _this8.invalidCvvMessage;
26476
26477      cardNumberInput.on('focusout', function () {
26478        var cardNumberValue = cardNumberInput.val();
26479        cardNumberValue = cardNumberValue.replace(/\s/g, "");
26480        var cardType = _this8.getCardType(cardNumberValue);
26481        var cardImagePath = _this8.getCardImagePath(cardType);
26482        var isValid = Utils.validateCardNumber(cardNumberValue);
26483
26484        if (!isValid) {
26485          cardNumberInput.addClass('is-invalid');
26486          cardNumberWarningMessageElement.text(numberInvalidMsg).show();
26487          cardImage.css('top', '25px');
26488        } else {
26489          cardNumberInput.removeClass('is-invalid');
26490          cardImage.css('top', '');
26491          cardNumberWarningMessageElement.hide();
26492        }
26493
26494        if (cardType === 'amex') {
26495          $('#cardNumber').mask('0000 000000 00000');
26496        } else {
26497          $('#cardNumber').mask('0000 0000 0000 0000');
26498        }
26499
26500        cardImage.attr('src', cardImagePath);
26501      });
26502
26503      expiryDateInput.on('focusout', function () {
26504        var expiryDateValue = expiryDateInput.val();
26505        var expiryDateParts = expiryDateValue.split('/');
26506        var expiryMonth = parseInt(expiryDateParts[0]);
26507        var expiryYear = parseInt(expiryDateParts[1]);
26508
26509        // Get the current date
26510        var currentDate = new Date();
26511        var currentYear = currentDate.getFullYear();
26512        var currentMonth = currentDate.getMonth() + 1; // January is month 0
26513
26514        if (expiryMonth < 1 || expiryMonth > 12 || isNaN(expiryYear) || expiryYear.toString().length !== 4 || expiryYear < currentYear || expiryYear === currentYear && expiryMonth < currentMonth) {
26515          expiryDateInput.addClass('is-invalid');
26516          expiryDateWarningMessageElement.text(expiryDateMsg).show();
26517        } else {
26518          expiryDateInput.removeClass('is-invalid');
26519          expiryDateWarningMessageElement.hide();
26520        }
26521      });
26522
26523      cvvInput.on('focusout', function () {
26524        var cvvValue = cvvInput.val();
26525        var isValid = Utils.validateCVV(cvvValue);
26526
26527        if (!isValid) {
26528          cvvInput.addClass('is-invalid');
26529          cvvWarningMessageElement.text(cvvInvalidMsg).show();
26530        } else {
26531          cvvInput.removeClass('is-invalid');
26532          cvvWarningMessageElement.hide();
26533        }
26534      });
26535
26536      this.inputExpiration.mask('AB/CD', {
26537        translation: {
26538          A: {
26539            pattern: /[0-1]/
26540          },
26541          B: {
26542            pattern: /[0-9]/
26543          },
26544          C: {
26545            pattern: /[1-3]/
26546          },
26547          D: {
26548            pattern: /[0-9]/
26549          }
26550        },
26551        onKeyPress: function onKeyPress(a, b, c, d) {
26552          if (!a) return;
26553          var m = a.match(/(\d{1})/g);
26554          if (!m) return;
26555          var typedMonth = parseInt(m[0]);
26556          var typedYear = parseInt(m[2]);
26557          // month (max. 12)
26558          if (typedMonth === 1) {
26559            d.translation.B.pattern = /[0-2]/;
26560          } else {
26561            d.translation.B.pattern = /[1-9]/;
26562          }
26563
26564          //year (min. currentYear)
26565          var yearTens = _this8.minValidYear / 10;
26566          if (typedYear == yearTens) {
26567            var min = _this8.minValidYear % 10;
26568            d.translation.D.pattern = new RegExp('[' + min + '-' + '9]');
26569          } else {
26570            d.translation.D.pattern = /[0-9]/;
26571          }
26572
26573          var temp_value = c.val();
26574          c.val('');
26575          c.unmask().mask('AB/CD', d);
26576          c.val(temp_value);
26577        }
26578      });
26579    }
26580  }, {
26581    key: 'areMalgaFieldsValid',
26582    value: function areMalgaFieldsValid() {
26583      if (this.storedCardToken) {
26584        return $('#securityCode').val().length >= 3 && $('[data-js="btn-installment-select"]').val();
26585      }
26586      return Object.values(this.malgaFieldValidity).every(Boolean);
26587    }
26588  }, {
26589    key: 'updateSubmitButtonState',
26590    value: function updateSubmitButtonState() {
26591      var cvvOk = !this.storedCardToken || $('#securityCode').val().length >= 3;
26592
26593      var canSubmit = this.checkConditions.is(':checked') && cvvOk && this.isFormValidMalga();
26594
26595      canSubmit ? this.enableSubmitButton() : this.disableSubmitButton();
26596    }
26597  }, {
26598    key: 'handlePreRequirements',
26599    value: function handlePreRequirements() {
26600      if (!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false') {
26601        var homePagePath = '#';
26602
26603        if ($('#homePagePath') && $('#homePagePath').val()) {
26604          homePagePath = $('#homePagePath').val();
26605        }
26606
26607        if (!this.formData || !this.cart) {
26608          $(location).attr('href', homePagePath);
26609        }
26610
26611        if (SessionStorage.get('checkout')) {
26612          SessionStorage.remove('checkout');
26613          $(location).attr('href', homePagePath);
26614        }
26615      }
26616    }
26617  }, {
26618    key: 'loadInfo',
26619    value: function loadInfo() {
26620      if (this.formData.depart.origin.label && this.formData.depart.destination.label) {
26621        this.labelDeparture.text(Utils.capitalize(this.formData.depart.origin.label));
26622        this.labelDestination.text(Utils.capitalize(this.formData.depart.destination.label));
26623      }
26624    }
26625  }, {
26626    key: 'loadStateMessages',
26627    value: function loadStateMessages() {
26628      LoaderService.show();
26629      var originUf = this.formData.depart.origin.uf;
26630      var parameters = {
26631        lang: Utils.getCurrentLang()
26632      };
26633
26634      if (Utils.getCurrentLang() == 'pt-br') {
26635        parameters = '';
26636      } else {
26637        parameters = '?' + $.param(parameters);
26638      }
26639
26640      HttpService.getFromRoot('insurance-states.json' + parameters).then(function (data) {
26641        LoaderService.hide();
26642        var allservices = data.result;
26643        var content = document.querySelector('[data-js="insurance-states"]');
26644
26645        allservices.map(function (service) {
26646          var insuranceState = service.uf;
26647          if (originUf === insuranceState) {
26648            content.innerHTML = service.msg;
26649          }
26650        });
26651      }).catch(function (err) {
26652        LoaderService.hide();
26653      });
26654    }
26655  }, {
26656    key: 'loadConfirmSaleMessages',
26657    value: function loadConfirmSaleMessages() {
26658      var _this14 = this;
26659
26660      LoaderService.show();
26661      HttpService.getFromCompany('jcaholding_paymentResponse.json').then(function (data) {
26662        LoaderService.hide();
26663        if (data.success) _this14.confirmSaleMsgs = data.list;
26664      }).catch(function () {
26665        return LoaderService.hide();
26666      });
26667    }
26668  }, {
26669    key: 'handleInsurance',
26670    value: function handleInsurance() {
26671      var _this18 = this;
26672
26673      var cartSummary = SessionStorage.get("cartSummary");
26674      var insuranceValue = 0;
26675
26676      if (cartSummary && cartSummary.valueParts && Array.isArray(cartSummary.valueParts)) {
26677        var insuranceItem = cartSummary.valueParts.find(function (item) {
26678          return item.code == "Insurance";
26679        });
26680
26681        if (insuranceItem && insuranceItem.value != null) {
26682          insuranceValue = insuranceItem.value;
26683        }
26684      }
26685
26686      var total = 0;
26687      if (insuranceValue > 0) {
26688        total = insuranceValue;
26689      } else {
26690        total = this.cartService.cart.listPassengers.reduce(function (acc, passenger) {
26691          acc += parseFloat(passenger._seatDeparture._insurance ? passenger._seatDeparture._insurance : 0) + parseFloat(passenger._seatDepartureC
26691onnection._insurance ? passenger._seatDepartureConnection._insurance : 0) + parseFloat(passenger._seatReturn._insurance ? passenger._seatReturn._insurance : 0) + parseFloat(passenger._seatReturnConnection._insurance ? passenger._seatReturnConnection._insurance : 0);
26692
26693          return acc;
26694        }, 0);
26695      }
26696
26697      var _total$toFixed$split = total.toFixed(2).split('.'),
26698          _total$toFixed$split2 = _slicedToArray(_total$toFixed$split, 2),
26699          integer = _total$toFixed$split2[0],
26700          decimal = _total$toFixed$split2[1];
26701
26702      if ($('[data-js="insurance-price-integer"]').find('.cmp-text').length > 0) {
26703        $('[data-js="insurance-price-integer"]').find('.cmp-text').find('p').text(integer);
26704      } else {
26705        $('[data-js="insurance-price-integer"]').find('p').text(integer);
26706      }
26707
26708      if ($('[data-js="insurance-price-decimal"]').find('.cmp-text').length > 0) {
26709        $('[data-js="insurance-price-decimal"]').find('.cmp-text').find('p').text(',' + decimal);
26710      } else {
26711        $('[data-js="insurance-price-decimal"]').find('p').text(',' + decimal);
26712      }
26713
26714      if (total > 0) this.insuranceContainer.show();
26715      // reset cart insurance
26716      this.cartService.cart.removeInsurance();
26717      this.syncSummaryThenUpdateCartView();
26718
26719      this.insuranceCheck.change(function (e) {
26720        _this18.isInsuranceActive = $(e.target).is(":checked");
26721        _this18.isConsultLiveloAPI = false;
26722        _this18.btnInstallment.data('value', null);
26723        _this18.selectCustom.eraseSelect(_this18.selInstallments);
26724        _this18.selInstallments.val(null);
26725        _this18.disableSubmitButton();
26726
26727        if ($(e.target).is(':checked')) {
26728          if (_this18.cartComponent.totalOffDiscount) {
26729            $('[data-js="tab-card"]').closest('.payment-type-container').show();
26730            $('[data-js="card-form"]').parent().show();
26731            $('[data-js="bank-form"]').parent().show();
26732            $('[data-js="recurring-content"]').show();
26733            $('.custom-control-label').removeClass('mt-4');
26734            $('.with-resume-bottom-cart').show();
26735            $('[data-js="price-in-bottom-cart"]').show();
26736            $('.seat-subtitle.btn-collapse').hide();
26737            $('.container-cart-details.collapse-container').hide();
26738          }
26739
26740          _this18.cartService.cart.addInsurance(total);
26741        } else {
26742          if (_this18.cartComponent.totalOffDiscount) {
26743            $('[data-js="tab-card"]').closest('.payment-type-container').hide();
26744            $('[data-js="card-form"]').parent().hide();
26745            $('[data-js="bank-form"]').parent().hide();
26746            $('.pix-content-container').parent().hide();
26747            $('[data-js="recurring-content"]').hide();
26748            $('.custom-control-label').addClass('mt-4');
26749            $('.with-resume-bottom-cart').hide();
26750            $('[data-js="price-in-bottom-cart"]').hide();
26751            $('.seat-subtitle.btn-collapse').hide();
26752            $('.container-cart-details.collapse-container').hide();
26753          }
26754
26755          _this18.cartService.cart.removeInsurance();
26756        }
26757
26758        if ($('[data-js="tab-livelo"]').hasClass('active')) _this18.getLiveloPoints();
26759
26760        _this18.loadInstallments();
26761        _this18.cartComponent.updateCartView(_this18.totalValueWithCoupon);
26762        return Promise.resolve(_this18.getUpdatedPriceSummary()).then(function () {
26763          if (!_this18.useSummary) {
26764            _this18.cartComponent.updateCartView(_this18.totalValueWithCoupon);
26765          }
26766
26767          _this18.cartComponent.initPassengerList(SessionStorage.get('cart'), _this18.isInsuranceActive);
26768          _this18.loadInstallments();
26769          if (_this18.loadInstallmentsAPI) {
26770            _this18.setInstallmentsWithInterest();
26771            $('.interest-amount').remove();
26772          }
26773        });
26774      });
26775    }
26776  }, {
26777    key: 'loadConditions',
26778    value: function loadConditions() {
26779      var _this10 = this;
26780
26781      var self = this;
26782
26783      this.infoConditions.click(function (e) {
26784        e.preventDefault(); //prevent checked box
26785        OverlayService.show('large');
26786        _this10.containerCondInfo.addClass('active');
26787        _this10.conatainerPayAlert.removeClass('active');
26788        _this10.containerCondInfo.focus();
26789      });
26790
26791      this.containerCondInfo.on('focusout', function () {
26792        var $elem = $(this);
26793        setTimeout(function () {
26794          var hasFocus = !!($elem.find(':focus').length > 0);
26795          if (!hasFocus) {
26796            OverlayService.hide();
26797            self.containerCondInfo.removeClass('active');
26798            self.infoConditions.focus();
26799          }
26800        }, 10);
26801      });
26802
26803      this.closeCondInfo.click(function () {
26804        OverlayService.hide();
26805        _this10.containerCondInfo.removeClass('active');
26806      });
26807    }
26808  }, {
26809    key: 'updateCartItemsBySummary',
26810    value: function updateCartItemsBySummary(data) {
26811      var _this18 = this;
26812
26813      var isPaymentPix = $('[data-js="tab-pix"]').hasClass("active");
26814      var code = isPaymentPix ? "SubTotalPix" : "SubTotal";
26815
26816      (data.services || []).forEach(function (service) {
26817        // Supports service.passengers[].seats[] (new) and legacy service.seats[].
26818        var seats = Array.isArray(service.passengers) ? service.passengers.reduce(function (acc, p) {
26819          return acc.concat(p.seats || []);
26820        }, []) : service.seats || [];
26821
26822        var serviceValuePart = service.valueParts ? service.valueParts.find(function (item) {
26823          return item.code === code;
26824        }) : null;
26825        var serviceValue = serviceValuePart ? Utils.formatPrice(serviceValuePart.value) : null;
26826        var serviceIds = [].concat(_toConsumableArray(new Set(seats.map(function (seat) {
26827          return seat.serviceId != null ? seat.serviceId : service.serviceId;
26828        }))));
26829
26830        if (serviceValue != null) {
26831          serviceIds.forEach(function (serviceId) {
26832            var $cartDepartureSegmentPrice = $('[data-price="price-departure"][data-price-service-id="' + serviceId + '"]');
26833            var $cartReturnSegmentPrice = $('[data-price="price-return"][data-price-service-id=' + serviceId + ']');
26834
26835            if ($cartDepartureSegmentPrice.length) {
26836              $cartDepartureSegmentPrice.text(serviceValue);
26837            }
26838
26839            if ($cartReturnSegmentPrice.length) {
26840              $cartReturnSegmentPrice.text(serviceValue);
26841            }
26842          });
26843        }
26844
26845        seats.forEach(function (seat) {
26846          var serviceId = seat.serviceId != null ? seat.serviceId : service.serviceId;
26847          var $serviceItem = $('[data-serviceid="' + serviceId + '-' + seat.seat + '"]');
26848          var $seatSubTotalDeparture = $serviceItem.find('[data-js="cart-details-departure-subtotal"]');
26849          var $seatSubTotalReturn = $serviceItem.find('[data-js="cart-details-return-subtotal"]');
26850          var $seatInsuranceDeparture = $serviceItem.find('[data-js="cart-details-departure-insurance"]');
26851          var $seatInsuranceReturn = $serviceItem.find('[data-js="cart-details-return-insurance"]');
26852
26853          if ($seatSubTotalDeparture.length > 0) {
26854            $seatSubTotalDeparture.text(Utils.formatPrice(seat.valueParts.find(function (item) {
26855              return item.code == "SubTotal";
26856            }).value));
26857          }
26858
26859          if ($seatSubTotalReturn.length > 0) {
26860            $seatSubTotalReturn.text(Utils.formatPrice(seat.valueParts.find(function (item) {
26861              return item.code == "SubTotal";
26862            }).value));
26863          }
26864
26865          if (_this18.isInsuranceActive) {
26866            if ($seatInsuranceDeparture.length > 0) {
26867              $seatInsuranceDeparture.parent().removeClass("d-none");
26868            }
26869
26870            if ($seatInsuranceReturn.length > 0) {
26871              $seatInsuranceReturn.parent().removeClass("d-none");
26872            }
26873          } else {
26874            if ($seatInsuranceReturn.length > 0) {
26875              $seatInsuranceReturn.parent().addClass('d-none');
26876            }
26877            if ($seatInsuranceDeparture.length > 0) {
26878              $seatInsuranceDeparture.parent().addClass("d-none");
26879            }
26880          }
26881        });
26882      });
26883    }
26884  }, {
26885    key: 'updatePriceSummaryElements',
26886    value: function updatePriceSummaryElements(data) {
26887      if (!data) return;
26888
26889      var isPaymentPix = $('[data-js="tab-pix"]').hasClass("active");
26890      var getValuePart = function getValuePart(code, fallbackCode) {
26891        var valuePart = data.valueParts.find(function (item) {
26892          return item.code === code;
26893        }) || fallbackCode && data.valueParts.find(function (item) {
26894          return item.code === fallbackCode;
26895        });
26896        return valuePart ? valuePart.value : 0;
26897      };
26898      var $subtotalSeats = $('[data-js="subtotal-seats"]');
26899      var $discountItem = $('[data-js="discount"]');
26900      var $priceDiscount = $('[data-js="price-discount"]');
26901      var $totalConveniencFee = $('[data-js="total-convenience-fee"]');
26902      var $cartPriceTotal = $('[data-js="price-cart"]');
26903      var $priceCartPix = $('[data-js="price-cart-pix"]');
26904      var interestAmount = getValuePart("InterestAmount");
26905      var voucherDiscount = getValuePart("VoucherDiscount");
26906
26907      if (interestAmount > 0) {
26908        if ($('.interest-amount')) $('.interest-amount').remove();
26909        var $interestAmountElement = '<p class="interest-amount"><span class="price">R$ ' + Utils.formatPrice(interestAmount) + ' de juros</span></p>';
26910        $('.summary-item.with-resume-bottom-cart').append($interestAmountElement);
26911      } else {
26912        $('.interest-amount').remove();
26913      }
26914
26915      if (voucherDiscount > 0) {
26916        $discountItem.show();
26917        $priceDiscount.text(Utils.formatPrice(voucherDiscount));
26918      }
26919
26920      var subtotal = getValuePart("SubTotal");
26921      var convenienceFee = getValuePart("ConvenienceFee");
26922
26923      $subtotalSeats.text(Utils.formatPrice(subtotal));
26924      $('[data-js="convenience-fee-pix"]').text(Utils.formatPrice(convenienceFee));
26925      $('[data-js="total-convenience-fee"]').text(Utils.formatPrice(convenienceFee));
26926      $priceCartPix.text(Utils.formatPrice(getValuePart("TotalPix")));
26927      $totalConveniencFee.text(Utils.formatPrice(getValuePart("ConvenienceFee")));
26928      $cartPriceTotal.text(Utils.formatPrice(getValuePart("Total")));
26929      $('[data-js="convenience-fee-container"]').toggleClass('d-none', isPaymentPix);
26930      $('[data-js="convenience-fee-pix-container"], [data-js="total-pix-container"]').toggleClass('d-none', !(this.hasPixDiscount && isPaymentPix));
26931      this.cartComponent.updateCartBySummary(data);
26932
26933      if ($('[data-js="convenience-fee-pix-container"]').hasClass('d-none')) {
26934        $totalConveniencFee.closest('.sumary-item-content.convenienceFee').removeClass('d-none');
26935      }
26936      this.cartComponent.formatSummaryDecimals();
26937    }
26938  }, {
26939    key: 'getUpdatedPriceSummary',
26940    value: function getUpdatedPriceSummary() {
26941      var _this21 = this;
26942
26943      if (this.repricingV2) {
26944        this.useSummary = false;
26945        return Promise.resolve(null);
26946      }
26947
26948      // Prevents a new call from being triggered while a summary request is still in progress
26949      if (this._summaryInFlight && this._summaryPromise) {
26950        return this._summaryPromise;
26951      }
26952
26953      var params = new URLSearchParams();
26954
26955      if (this.voucher && this.voucher.length > 0) {
26956        params.append("voucher", this.voucher);
26957      }
26958
26959      if (this.installmentsQnt && Number(this.installmentsQnt) > 0) {
26960        params.append("installment", this.installmentsQnt);
26961      }
26962
26963      if (this.isInsuranceActive) {
26964        params.append("insurance", this.isInsuranceActive.toString());
26965      }
26966
26967      var queryString = params.toString();
26968      var url = queryString ? 'saleSummary?' + queryString : "saleSummary";
26969
26970      var headers = {
26971        'Authorization': '' + SessionStorage.get('jca_token'),
26972        'sessionseatlock': '' + SessionStorage.get('sessionseatlock'),
26973        'version': 3
26974      };
26975
26976      this._summaryInFlight = true;
26977      var promise = HttpService.get(url, headers).then(function (data) {
26978        _this21.summaryObject = data.result;
26979        _this21.useSummary = true;
26980        SessionStorage.set("cartSummary", data.result);
26981        _this21.updateCartItemsBySummary(data.result);
26982        _this21.updatePriceSummaryElements(data.result);
26983        return data.result;
26984      }).catch(function (err) {
26985        _this21.useSummary = false;
26986        // throw err;
26987      }).then(function (result) {
26988        _this21._summaryInFlight = false;
26989        return result;
26990      });
26991
26992      // Guarda a promise em curso para que outros pontos possam aguardar
26993      // o summary sem disparar uma chamada duplicada.
26994      this._summaryPromise = promise;
26995      return promise;
26996    }
26997  }, {
26998    key: 'syncSummaryThenUpdateCartView',
26999    value: function syncSummaryThenUpdateCartView(totalValueWithCoupon) {
27000      var _this23 = this;
27001
27002      var handleFallback = function handleFallback() {
27003        if (!_this23.useSummary) {
27004          _this23.cartComponent.useSummary = false;
27005          _this23.cartComponent.updateCartView(totalValueWithCoupon);
27006          _this23.cartComponent.initPassengerList(SessionStorage.get('cart'));
27007          // Sem summary (remarcação/erro) o desconto é redesenhado a partir do
27008          // discountData persistido — nunca de um novo request de voucher.
27009          var discountData = CouponLockService.get() ? SessionStorage.get('discountData') : null;
27010          if (discountData) _this23.cartComponent.applyDiscount(discountData);
27011        }
27012      };
27013      return this.getUpdatedPriceSummary().then(handleFallback, handleFallback);
27014    }
27015  }, {
27016    key: 'loadInstallments',
27017    value: function loadInstallments() {
27018      var _this11 = this;
27019
27020      var content = this.renderInstallments();
27021      this.listInstallment.empty().append(content);
27022
27023      this.btnInstallment.click(function (e) {
27024        OverlayService.show('large');
27025        _this11.containerSelOver.addClass('active');
27026        var content = _this11.renderInstallments();
27027        _this11.listInstallment.empty().append(content);
27028      });
27029
27030      this.closeSelOver.click(function (e) {
27031        _this11.containerSelOver.removeClass('active');
27032        OverlayService.hide();
27033      });
27034
27035      this.listInstallment.click(function (e) {
27036        var li = $(e.target);
27037        var installments = $(e.target)[0].id.replace(/\D/g, '');
27038        _this11.btnInstallment.find('.btn-installment-text').text(li.text());
27039        _this11.btnInstallment.data('value', parseInt(installments));
27040        _this11.containerSelOver.removeClass('active');
27041        OverlayService.hide();
27042        if (_this11.checkConditions.is(':checked') && _this11.isFormValid() && _this11.isFormValidMalga()) {
27043          _this11.enableSubmitButton();
27044        } else {
27045          _this11.disableSubmitButton();
27046        }
27047      });
27048    }
27049  }, {
27050    key: 'enableSubmitButton',
27051    value: function enableSubmitButton() {
27052      this.buttonSubmit.prop('disabled', false);
27053      this.submitPayment();
27054    }
27055  }, {
27056    key: 'disableSubmitButton',
27057    value: function disableSubmitButton() {
27058      this.buttonSubmit.off('click');
27059      this.buttonSubmit.prop('disabled', true);
27060    }
27061  }, {
27062    key: 'calculateTotalValueWithCoupon',
27063    value: function calculateTotalValueWithCoupon(data, totalwithDiscount) {
27064      var _this15 = this;
27065
27066      var discountData = SessionStorage.get('discountData');
27067      var transactions = discountData ? discountData.result.seats.transactions : null;
27068
27069      var getTotal = function getTotal() {
27070        if (data) return data.result.token.voucherId ? totalwithDiscount : 0;
27071
27072        if (_this15.repricingV2) {
27073          return _this15.cartService.balanceTotal;
27074        } else {
27075          if (_this15.cartComponent.totalOffDiscount) {
27076            return _this15.cartService.cart._insurance.hired ? _this15.cartService.cart._insurance.price : 0.0;
27077          } else {
27078            return _this15.convenienceFee ? _this15.cartService.getTotal(_this15.convenienceFee) - (transactions ? _this15.cartService._cart._totalConvenienceFee - _this15.cartComponent.txPriceTotalConvenienceFee : 0) 
27078- Math.round((transactions ? _this15.cartService.totalDiscount + 0.00001 : 0) * 100) / 100 : _this15.cartService.total - Math.round((transactions ? _this15.cartService.totalDiscount + 0.00001 : 0) * 100) / 100;
27079          }
27080        }
27081      };
27082
27083      this.totalValueWithCoupon = this.isPaymentWhatsapp ? this.totalSalePrice : getTotal();
27084
27085      return this.totalValueWithCoupon;
27086    }
27087  }, {
27088    key: 'renderInstallments',
27089    value: function renderInstallments(data, totalwithDiscount) {
27090      var content = [];
27091      var total = this.calculateTotalValueWithCoupon(data, totalwithDiscount);
27092      var numInstallments = this.getNumInstallments(total);
27093      $('option:gt(0)', this.selInstallments).remove();
27094
27095      for (var i = 1; i <= numInstallments; i++) {
27096        var currValue = total / i;
27097        var roundedValue = Math.round((currValue + 0.00001) * 100) / 100;
27098        var formatedValue = i + 'x de R$' + roundedValue.toFixed(2).replace('.', ',');
27099        content.push('<li class="installment-value" id="installment-' + i + '" data-value="' + roundedValue + '"> ' + formatedValue + ' </li>');
27100        var option = new Option(formatedValue, i);
27101        this.selInstallments.append(option);
27102      }
27103
27104      this.selectCustom.initSingle(this.selInstallments.parent());
27105      return content;
27106    }
27107  }, {
27108    key: 'getNumInstallments',
27109    value: function getNumInstallments(total) {
27110      var maxInstallments = parseInt($('[data-js="installments-conditions"]').data('maxinstallments'));
27111      var installmentMinValue = parseInt($('[data-js="installments-conditions"]').data('installmentminvalue'));
27112
27113      var numInstallments = parseInt(total / installmentMinValue);
27114
27115      if (numInstallments === 0) return 1;
27116
27117      if (numInstallments <= maxInstallments) {
27118        return numInstallments;
27119      } else {
27120        return maxInstallments;
27121      }
27122    }
27123  }, {
27124    key: 'openPaymentAlert',
27125    value: function openPaymentAlert(msg) {
27126      var err = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
27127
27128      var errorMsgCode = void 0;
27129
27130      if (err) {
27131        errorMsgCode = +JSON.parse(err.responseJSON.result).RefusalReasonCode;
27132        if (errorMsgCode == 20) $('.payment-alert-link').show();
27133      }
27134
27135      $('[data-js="payment-alert-text"]').text(msg);
27136      OverlayService.show();
27137    }
27138  }, {
27139    key: 'closePaymentAlert',
27140    value: function closePaymentAlert() {
27141      var _this12 = this;
27142
27143      this.closePayAlert.on('click focusout', function (e) {
27144        OverlayService.hide();
27145        _this12.conatainerPayAlert.removeClass('active');
27146        $('.payment-alert-link').hide();
27147      });
27148    }
27149  }, {
27150    key: 'submitPaymentError',
27151    value: function submitPaymentError() {
27152      var _this13 = this;
27153
27154      $('[data-js="submit-payment-error"]').click(function () {
27155        var parameters = {
27156          'encoding': 'UTF-8',
27157          'orgid': '00D1N000002dlIo',
27158          'recordType': '0121N000001DlZt',
27159          'Origin': 'Web',
27160          'Status': 'New',
27161          '00N1N00000FAEW3': 'Novo',
27162          '00N1N00000FAAqo': 'Não',
27163          'name': _this13.mainPassenger._name,
27164          'email': _this13.mainPassenger._email,
27165          'phone': _this13.mainPassenger._phone,
27166          '00N1N00000FBPWu': _this13.mainPassenger._documentNumber,
27167          'type': 'PAGAMENTO',
27168          '00N1N00000FA8oC': 'ERRO_PAGAMENTO',
27169          '00N1N00000P8jjs': Utils.getSiteName(),
27170          '00N1N00000FA8pt': 'Não',
27171          '00N1N00000P9Cij': $('[data-js="departure-date-info"]').text() + ' ' + $('[data-js="departure-depart-time-label"]').text(),
27172          '00N1N00000PEh6m': $('[data-js="origin-info"]').text(),
27173          '00N1N00000PEh6r': $('[data-js="destination-info"]').text(),
27174          'token': SessionStorage.get('jca_token')
27175        };
27176
27177        _this13.closePayAlert.trigger('click');
27178        LoaderService.show();
27179        HttpService.post('openProtocol', parameters).then(function (data) {
27180          LoaderService.hide();
27181          if (!data.success) {
27182            AlertConfirmation.show('', i18n('protocol_error'), true, false);
27183            OverlayService.show();
27184          } else {
27185            $(location).attr('href', $('#homePagePath').val(), false);
27186          }
27187        }).catch(function () {
27188          LoaderService.hide();
27189          AlertConfirmation.show('', i18n('protocol_error'), true, false);
27190        });
27191      });
27192    }
27193  }, {
27194    key: 'loadMasks',
27195    value: function loadMasks() {
27196      var _this15 = this;
27197
27198      {
27199        var masks = ['000.000.000-009', '00.000.000/0000-00'];
27200        var maskBehavior = function maskBehavior(val) {
27201          return val.replace(/\D/g, '').length <= 11 ? masks[0] : masks[1];
27202        },
27203          cpfCnpjpOptions = {
27204            onKeyPress: function onKeyPress(val, e, field, options) {
27205              field.mask(maskBehavior.apply({}, arguments), options);
27206            }
27207          };
27208
27209        this.inputDoc.keypress(function (e) {
27210          if ($(e.target).val().length >= 10) {
27211            _this15.inputDoc.mask(maskBehavior, cpfCnpjpOptions);
27212          }
27213        });
27214
27215        this.inputDoc.on('keydown focusout', function (e) {
27216          var isAlphabetic = new RegExp(/\D/g);
27217          var keyCode = e.keyCode ? e.keyCode : e.which;
27218          var matchMasks = new RegExp(/(\.)|(\/)|(\-)/g);
27219          var valueWithoutMask = $(e.target).val().replace(matchMasks, '');
27220          if (keyCode === 8 || keyCode === 46) {
27221            if (!isAlphabetic.test(valueWithoutMask) && valueWithoutMask.length >= 11) _this15.inputDoc.mask(maskBehavior, cpfCnpjpOptions); else _this15.inputDoc.unmask();
27222          }
27223        });
27224
27225        this.inputName.on('keyup', function (e) {
27226          var invalidMask = new RegExp(/[!#$%¨&*¹²³ªº£¢¬\(\)\[\]\{\}´`~;:°?*+,\-|0-9=§@'"\/\\]+/g);
27227          var name = _this15.inputName.val().replace(invalidMask, '');
27228          _this15.inputName.val(name);
27229        });
27230      }
27231
27232      $('#cardNumber').mask('0000 0000 0000 0000');
27233      $('#expiryDate').mask('00/0000');
27234      $('#securityCode').mask('0000');
27235
27236      this.inputSecurity.mask('0009');
27237      this.inputCardNumber.mask('0000 0000 0000 0000');
27238      this.loadCreditCardMask();
27239    }
27240  }, {
27241    key: 'listenForm',
27242    value: function listenForm() {
27243      var _this28 = this;
27244
27245      $('[data-js="new-card-item"]').click(function (e) {
27246        if ($('.card-form-malga').length) {
27247          $('#input-cpf').show();
27248          $('#securityCode').val('');
27249          $('#input-name-card').val('');
27250          $('.card-form-malga .field.col-12').show();
27251          $('[data-js="new-card-item"]').hide();
27252          $('#stored-cvv-wrapper').addClass('d-none');
27253          $('#securityCode').val('').trigger('input');
27254          $('#securityCode').val('');
27255        } else {
27256          $(e.currentTarget).siblings().removeClass('active');
27257          $(e.currentTarget).hide();
27258          $('#input-cpf').val('').closest('div.field').show();
27259          $('#input-name-card').val('');
27260          $('[data-js="recurring-content"]').show();
27261          _this28.loadAdyenIframe();
27262        }
27263      });
27264
27265      $('body form').find('input[required]').keyup(function () {
27266        if (_this28.isFormValid() && _this28.checkConditions.is(':checked') || _this28.checkConditions.is(":checked") && _this28.isFormValidMalga()) {
27267          _this28.enableSubmitButton();
27268        } else {
27269          _this28.disableSubmitButton();
27270        }
27271      });
27272
27273      this.checkConditions.change(function (e) {
27274        if (!$('[data-js="tab-livelo"]').hasClass('active')) {
27275          if (_this28.isFormValid() && $(e.target).is(':checked') || _this28.isFormValidMalga() && $(e.target).is(":checked")) _this28.enableSubmitButton();else {
27276            _this28.disableSubmitButton();
27277          }
27278        }
27279      });
27280
27281      var self = this;
27282      $('#securityCode').on('input', function () {
27283        var ok = this.value.length >= 3;
27284        $(this).siblings('.card-image.checkmark').toggleClass('d-none', !ok);
27285        self.updateSubmitButtonState();
27286      });
27287
27288      this.btnSeeCart.click({
27289        'cartDetailsPage': this.cartComponent.cartDetailsPage,
27290        'innerContainer': this.cartComponent.innerContainer
27291      }, this.cartComponent.showDetailsPage);
27292
27293      this.btnSeeCartDesktop.click(CartButton.showModal);
27294
27295      this.btnInstallment.bind("DOMSubtreeModified", function (e) {
27296        if (_this28.checkConditions.is(':checked') && _this28.isFormValid() || _this28.checkConditions.is(":checked") && _this28.isFormValidMalga()) {
27297          _this28.enableSubmitButton();
27298        } else {
27299          _this28.disableSubmitButton();
27300        }
27301      });
27302
27303      this.selInstallments.change(function (e) {
27304        _this28.installmentsQnt = $(e.target).val();
27305        if (_this28.checkConditions.is(':checked') && _this28.isFormValid() || _this28.checkConditions.is(":checked") && _this28.isFormValidMalga()) {
27306          _this28.enableSubmitButton();
27307        } else {
27308          _this28.disableSubmitButton();
27309        }
27310        _this28.syncSummaryThenUpdateCartView(_this28.totalValueWithCoupon);
27311      });
27312
27313      $('[data-js="discount-form"]').submit(function (e) {
27314        e.preventDefault();
27315      });
27316
27317      $('#input-cpf-bank').on('input', function (e) {
27318        var text = $(e.target).val().replace(/\D/g, '');
27319
27320        $(e.target).val(text);
27321
27322        _this28.inputDoc.trigger('keydown keypress focusout');
27323      });
27324
27325      $('#input-bank-agency, #input-bank-account').on('input', function (e) {
27326        $(e.target).val($(e.target).val().replace(/\D/g, ''));
27327      });
27328    }
27329  }, {
27330    key: 'validateDiscount',
27331    value: function validateDiscount() {
27332      var _this29 = this;
27333
27334      var isDiscountValid = $('[data-js="button-apply-discount"]').hasClass("val
27334id");
27335
27336      if (!isDiscountValid) return true;
27337
27338      var header = {
27339        'Authorization': '' + SessionStorage.get('jca_token'),
27340        'sessionseatlock': SessionStorage.get('sessionseatlock')
27341      };
27342
27343      var body = {
27344        "name": $('[data-js="discount-code"').val(),
27345        "salePlatform": "SITES-UTP"
27346      };
27347
27348      return HttpService.post('voucherValidation', body, header).then(function (data) {
27349        if (data && data.success === false) {
27350          return $.Deferred().reject(data).promise();
27351        }
27352        return _this29.syncSummaryThenUpdateCartView(_this29.totalValueWithCoupon);
27353      });
27354    }
27355  }, {
27356    key: 'getFormRemarkData',
27357    value: function getFormRemarkData() {
27358      var name = $('[data-js="input-remark-name"]').val();
27359      var cpf = $('[data-js="input-remark-cpf"]').val().replace(/[.-]/g, "");
27360      var phone = $('[data-js="input-remark-phone"]').val();
27361      var email = $('[data-js="input-remark-email"]').val();
27362
27363      return {
27364        name: name,
27365        cpf: cpf,
27366        phone: phone,
27367        email: email
27368      };
27369    }
27370  }, {
27371    key: 'validateInputsRemarkForm',
27372    value: function validateInputsRemarkForm() {
27373      $('[data-js="input-remark-name"]').on('input', function (e) {
27374        var regexp = /[^a-zA-Z\s]/g;
27375        if (this.value.match(regexp)) {
27376          $(this).val(this.value.replace(regexp, ''));
27377        }
27378      });
27379
27380      $('[data-js="input-remark-cpf"]').on('input', function (e) {
27381        var pastedValue = '';
27382
27383        if (e.originalEvent && e.originalEvent.clipboardData) {
27384          pastedValue = e.originalEvent.clipboardData.getData('text/plain');
27385        } else if (window.clipboardData) {
27386          pastedValue = window.clipboardData.getData('Text');
27387        }
27388
27389        var typedValue = e.target.value;
27390        var inputValue = pastedValue || typedValue;
27391        var sanitizedValue = inputValue.replace(/[^0-9.-]/g, '');
27392        $(this).val(sanitizedValue);
27393      });
27394
27395      $('[data-js="input-remark-phone"]').on('input', function (e) {
27396        var pastedValue = '';
27397
27398        if (e.originalEvent && e.originalEvent.clipboardData) {
27399          pastedValue = e.originalEvent.clipboardData.getData('text/plain');
27400        } else if (window.clipboardData) {
27401          pastedValue = window.clipboardData.getData('Text');
27402        }
27403
27404        var typedValue = e.target.value;
27405        var inputValue = pastedValue || typedValue;
27406        var sanitizedValue = inputValue.replace(/[^0-9.-]/g, '');
27407        $(this).val(sanitizedValue);
27408      });
27409    }
27410  }, {
27411    key: 'validRemarkForm',
27412    value: function validRemarkForm() {
27413      var isValid = true;
27414
27415      $('[data-js^="input-remark"]').on('blur', function () {
27416        validateField($(this));
27417      });
27418
27419      function validateField(input) {
27420        var value = input.val();
27421        var fieldName = input.attr('data-js');
27422
27423        switch (fieldName) {
27424          case 'input-remark-name':
27425            isValid = checkValidity(value, fieldName, 6, 45);
27426            break;
27427          case 'input-remark-cpf':
27428            isValid = checkCPFValidity(value, fieldName);
27429            break;
27430          case 'input-remark-email':
27431            isValid = checkEmailValidity(value, fieldName);
27432            break;
27433          case 'input-remark-phone':
27434            isValid = checkValidity(value, fieldName, 9, 11);
27435            break;
27436          default:
27437            break;
27438        }
27439
27440        if (isValid) {
27441          input.removeClass('invalid');
27442        } else {
27443          input.addClass('invalid');
27444        }
27445      }
27446
27447      function checkValidity(value, _fieldName, minLength, maxLength) {
27448        return !value || value.length < minLength || value.length > maxLength ? false : true;
27449      }
27450
27451      function checkCPFValidity(cpf, _fieldName) {
27452        return !cpf || !Utils.validateCPF(Utils.replaceToNumbers(cpf)) ? false : true;
27453      }
27454
27455      function checkEmailValidity(email, _fieldName) {
27456        return !email || !Utils.validEmail(email) ? false : true;
27457      }
27458
27459      function checkAllFields() {
27460        var isNameValid = checkValidity($('[data-js="input-remark-name"]').val(), 'input-remark-name', 6, 45);
27461        var isCPFValid = checkCPFValidity($('[data-js="input-remark-cpf"]').val(), 'input-remark-cpf');
27462        var isEmailValid = checkEmailValidity($('[data-js="input-remark-email"]').val(), 'input-remark-email');
27463        var isPhoneValid = checkValidity($('[data-js="input-remark-phone"]').val(), 'input-remark-phone', 9, 11);
27464
27465        isValid = isNameValid && isCPFValid && isEmailValid && isPhoneValid;
27466
27467        if ($('[data-js="conditions-check"]').is(':checked') && !isValid) {
27468          $('[data-js="error-msg-remark"]').fadeIn();
27469        } else {
27470          $('[data-js="error-msg-remark"]').fadeOut();
27471        }
27472      }
27473
27474      checkAllFields();
27475      return isValid;
27476    }
27477  }, {
27478    key: 'getTokenMalga',
27479    value: function getTokenMalga() {
27480      return this.malgaInstance.tokenize().then(function (_ref4) {
27481        var tokenId = _ref4.tokenId,
27482            error = _ref4.error;
27483
27484        if (error) {
27485          LoaderService.hide();
27486
27487          if (error.message) {
27488            AlertConfirmation.show(error.message, error.message);
27489
27490            $('#overlay, [data-js="close-menu"]').on("click", function () {
27491              $(location).attr("href", $('#homePagePath').val());
27492            });
27493          } else {
27494            AlertConfirmation.show(i18n("payment_error_purchase"), i18n("payment_generic_error"));
27495          }
27496
27497          throw error;
27498        }
27499
27500        return tokenId;
27501      });
27502    }
27503  }, {
27504    key: 'resolvePaymentCardMalga',
27505    value: function resolvePaymentCardMalga() {
27506      var _this20 = this;
27507
27508      return new Promise(function (resolve, reject) {
27509        var isStoredCardVisible = $('[data-js="stored-cards-list"]').is(":visible");
27510
27511        LoaderService.show();
27512
27513        if (isStoredCardVisible && _this20.storedCardToken) {
27514          _this20.processPayment(_this20.storedCardToken, resolve, reject);
27515        } else {
27516          _this20.getTokenMalga().then(function (tokenId) {
27517            _this20.tokenIdMalga = tokenId;
27518            _this20.processPayment(_this20.tokenIdMalga, resolve, reject);
27519          }).catch(function (error) {
27520            LoaderService.hide();
27521            reject(error);
27522          });
27523        }
27524      });
27525    }
27526  }, {
27527    key: 'processPayment',
27528    value: function processPayment(token, resolve, reject) {
27529      var _this22 = this;
27530
27531      var passengers = this.isPaymentWhatsapp ? this.wppPassengers : this.cartService.passengers;
27532      //var passengerData = SessionStorage.get('passenger') != null : 
27532SessionStorage.get('passenger') : passengers[0].name;
27533      var holderName = SessionStorage.get('passenger') != null ? passengers._name : passengers[0].name;
27534      var installments = $('[data-js="btn-installment-select"]').val();
27535      var merchantAccountId = 1;
27536      var merchantAccount = 'utphml';
27537      var recurring = $("#recurring").is(":checked");
27538      var deviceFingerprint = $("#device-fingerprint").val();
27539      var hasInsurance = this.insuranceCheck.is(":checked");
27540      var cardCvv = this.storedCardToken ? $('#securityCode').val() : undefined;
27541      var paymentData = void 0;
27542      _this22.saleplatform = SessionStorage.get('utm_saleplatform') ? SessionStorage.get('utm_saleplatform') : "SITES-UTP";
27543
27544      if (this.isPaymentWhatsapp) {
27545        _this22.saleplatform = "AariM";
27546      }
27547
27548      var deviceId = $('#deviceId').val();
27549
27550
27551      this.getIP().then(function (ip) {
27552        var isNegativeValue = _this22.isRepricingNegativeValue();
27553        var isZeroValue = _this22.isRepricingZeroValue();
27554        var refundInformation = _this22.getFormRemarkData();
27555
27556        if (isNegativeValue || isZeroValue) {
27557          paymentData = new PaymentNegative(recurring, installments, passengers, merchantAccountId, isZeroValue ? false : hasInsurance, ip, isNegativeValue ? refundInformation : undefined);
27558        } else if (_this22.cartComponent.totalOffDiscount && !_this22.insuranceCheck.is(':checked')) {
27559          paymentData = new PaymentTotalDiscount(passengers, ip, _this22.saleplatform);
27560        } else {
27561          paymentData = new PaymentMalga(token, holderName, recurring, installments, deviceFingerprint, passengers, merchantAccountId, merchantAccount, hasInsurance, ip, _this22.saleplatform, deviceId, cardCvv);
27562        }
27563
27564        var headers = {
27565          Authorization: this.isPaymentWhatsapp ? this.wppToken : SessionStorage.get('jca_token'),
27566          sessionseatlock: SessionStorage.get("sessionseatlock"),
27567          version: _this22.repricingV2 ? 2 : 3,
27568          flow: "malga",
27569          "X-meli-session-id": deviceId,
27570          channel: Utils.getChannelTitle(_this22.isPaymentWhatsapp, _this22.saleplatform)
27571        };
27572
27573        var serviceUrl = _this22.repricingV2 ? 'paymentRemark' : 'confirmSale';
27574
27575        HttpService.post(serviceUrl, paymentData, headers).then(function (data) {
27576          if (data && data.success === false) {
27577            throw {
27578              responseJSON: data
27579            };
27580          }
27581
27582          LoaderService.hide();          
27583
27584          // Analytics
27585          data_layer.page.pageInfo.paymentFlow.paymentFlowChanged = true;
27586            
27587          if (_this22.isPaymentWhatsapp) {
27588            _this22.handleSuccessWpp(false);
27589          } else {
27590            SessionStorage.set("checkout", data.result);
27591            SessionStorage.set("checkout_aux", { installments: installments, method: "CARD" });
27592            SessionStorage.set("cart", _this22.cartService.cart);  
27593              
27594            setTimeout(function () {
27595              $(location).attr("href", $('#checkoutPagePath').val());
27596            }, 300);
27597          }
27598          _this22.buttonSubmit.on("click");
27599          resolve();
27600        }).catch(function (err) {
27601          LoaderService.hide();
27602          if(_this22.isPaymentWhatsapp) {
27603             AlertConfirmation.showAEM('data-js="whatsapp-payment-status-error"', false, true);
27604          } else {           
27605              _this22.eraseInputs();
27606              if (_this22.verifySeatErr(err)) {
27607                AlertConfirmation.show(i18n("error_seat_title"), i18n("error_seat_message"), true);
27608
27609                $('#overlay, [data-js="close-menu"]').on("click", function () {
27610                  $(location).attr("href", $('#homePagePath').val());
27611                });
27612              } else {
27613                var errorMsg = i18n('payment_error');
27614                var errorCode = '';
27615
27616                try {
27617                  var response = err.responseJSON;
27618                  if (response && response.error && response.errorCode) {
27619                    errorMsg = response.error;
27620                    errorCode = response.errorCode;
27621                  } else if (response && response.errors && response.errors.length && response.errors[0].error && response.errors[0].errorCode) {
27622                    errorMsg = response.errors[0].error;
27623                    errorCode = response.errors[0].errorCode;
27624                  }
27625                } catch (e) {}
27626
27627                _this22.checkQttPaymentErr(errorMsg, errorCode);
27628              }
27629              //reject(err);
27630          }
27631        });
27632      });
27633      var getMatchedMessageMalga = function getMatchedMessageMalga(err) {
27634        var errorMsgCode = void 0,
27635          msg = void 0;
27636        var genericError = _this22.confirmSaleMsgs.find(function (msg) {
27637          return msg.errorCode === 0;
27638        }).messageToCostumer;
27639
27640        try {
27641          var errorDetails = err.responseJSON.error;
27642          errorMsgCode = errorDetails.code;
27643
27644          if (!msg && errorMsgCode !== null) {
27645            msg = _this22.confirmSaleMsgs.find(function (msg) {
27646              return msg.errorCode === errorMsgCode;
27647            }).messageToCostumer;
27648          }
27649
27650          if (!msg) return genericError;
27651          LoaderService.hide();
27652          return msg;
27653        } catch (_) {
27654          LoaderService.hide();
27655          return genericError;
27656        }
27657      };
27658    }
27659  }, {
27660    key: 'resolvePaymentCard',
27661    value: function resolvePaymentCard() {
27662      var _this17 = this;
27663
27664      var cardNumber = this.cardNumberEncrypted;
27665      var expiryMont = this.expiryMontEncrypted;
27666      var expiryYear = this.expiryYearEncrypted;
27667      var securityCode = this.securityCodeEncrypted;
27668      var passengers = this.isPaymentWhatsapp ? this.wppPassengers : this.cartService.passengers;
27669      var holderName = $('[data-js="input-name-card"]').val();
27670      var installments = $('[data-js="btn-installment-select"]').val() || $('[data-js="btn-installment"]').data('value');
27671      var deviceFingerprint = $("#device-fingerprint").val(); //Adyen integration
27672      var merchantAccountId = 1;
27673      var recurring = $('#recurring').is(':checked');
27674      var isStoredCard = $('#stored-card').is(':visible');
27675      var token = $('#stored-card').data('token');
27676      var hasInsurance = this.insuranceCheck.is(':checked');
27677      var refundInformation = this.getFormRemarkData();
27678      var paymentData = void 0;
27679      _this17.saleplatform = SessionStorage.get('utm_saleplatform') ? SessionStorage.get('utm_saleplatform') : "SITES-UTP";
27680
27681      if (this.isPaymentWhatsapp) {
27682        _this17.saleplatform = "AariM";
27683      }
27684
27685      LoaderService.show();
27686      this.getIP().then(function (ip) {
27687        var isNegativeValue = _this17.isRepricingNegativeValue();
27688        var isZeroValue = _this17.isRepricingZeroValue();
27689        var hasInsurancew2i = sessionStorage.getItem('insuranceW2iChecked') === 'true';
27690
27691        if (isNegativeValue || isZeroValue) {
27692          var refundInfo = _this17.getFormRemarkData();
27693          paymentData = new PaymentNegative(recurring, installments, passengers, merchantAccountId, isZeroValue ? false : hasInsurance, ip, isNegativeValue ? refundInfo : undefined);
27694        } else if (isStoredCard) {
27695          paymentData = new PaymentToken(securityCode, holderName, recurring, installments, token, deviceFingerprint, passengers, merchantAccountId, hasInsurance, ip, _this17.saleplatform);
27696        } else if (!_this17.repricingV2 && _this17.cartComponent.totalOffDiscount && !_this17.insuranceCheck.is(':checked')) {
27697          paymentData = new PaymentTotalDiscount(passengers, ip, _this17.saleplatform);
27698        } else {
27699          paymentData = new Payment(cardNumber, expiryMont, expiryYear, securityCode, holderName, recurring, installments, deviceFingerprint, passengers, merchantAccountId, hasInsurance, ip, _this17.saleplatform);
27700        }
27701
27702        var headers = _this17.repricingV2 || _this17.isPaymentWhatsapp ? {
27703          'Authorization':  this.isPaymentWhatsapp ? this.wppToken : SessionStorage.get('jca_token'),
27704          'sessionseatlock': SessionStorage.get('sessionseatlock'),
27705          'channel': Utils.getChannelTitle(_this17.isPaymentWhatsapp, _this17.saleplatform)
27706        } : {
27707          'Authorization': '' + SessionStorage.get('jca_token'),
27708          'sessionseatlock': SessionStorage.get('sessionseatlock'),
27709          'version': 2,
27710          'channel': Utils.getChannelTitle(_this17.isPaymentWhatsapp, _this17.saleplatform)
27711        };
27712
27713        if (_this17.repricingV2) {
27714          HttpService.post('paymentRemark', paymentData, headers).then(function (data) {
27715            if (data && data.success === false) {
27716            throw {
27717              responseJSON: data
27718            };
27719          }
27720
27721            LoaderService.hide();
27722            SessionStorage.set('checkout', data.result);
27723            SessionStorage.set('checkout_aux', { installments: installments, method: 'CARD' });
27724            SessionStorage.set('cart', _this17.cartService.cart);
27725
27726            // Analytics
27727            data_layer.page.pageInfo.paymentFlow.paymentFlowChanged = true;
27728            setTimeout(function () {
27729              if ($('#rescheduleCheckoutPathV2') && $('#rescheduleCheckoutPathV2').val()) $(location).attr('href', $('#rescheduleCheckoutPathV2').val());
27730            }, 300);
27731            _this17.buttonSubmit.on('click');
27732
27733          }).catch(function (err) {
27734          LoaderService.hide();
27735          _this17.eraseInputs();
27736          _this17.clearIframeValueAdyen();
27737          if (_this17.verifySeatErr(err)) {
27738            AlertConfirmation.show(i18n("error_seat_title"), i18n("error_seat_message"), true);
27739
27740            $('#overlay, [data-js="close-menu"]').on("click", function () {
27741              $(location).attr("href", $('#homePagePath').val());
27742            });
27743          } else {
27744            var errorMsg = i18n('payment_error');
27745            var errorCode = '';
27746
27747            try {
27748              var response = err.responseJSON;
27749              if (response && response.error && response.errorCode) {
27750                errorMsg = response.error;
27751                errorCode = response.errorCode;
27752              } else if (response && response.errors && response.errors.length && response.errors[0].error && response.errors[0].errorCode) {
27753                errorMsg = response.errors[0].error;
27754                errorCode = response.errors[0].errorCode;
27755              }
27756            } catch (e) {
27757              console.error(e);
27758            }
27759
27760            _this17.checkQttPaymentErr(errorMsg, errorCode);
27761          }
27762        });
27763        } else {
27764          var serviceUrl = _this17.isPaymentWhatsapp ? 'confirmSaleWpp' : 'confirmSale';
27765          HttpService.post(serviceUrl, paymentData, headers).then(function (data) {
27766            LoaderService.hide();
27767            SessionStorage.set('checkout', data.result);
27768            SessionStorage.set('checkout_aux', { installments: installments, method: 'CARD' });
27769
27770
27771            if (_this17.cartService != undefined) {
27772              SessionStorage.set('cart', _this17.cartService.cart);
27773            }
27774
27775            // Analytics
27776            data_layer.page.pageInfo.paymentFlow.paymentFlowChanged = true;
27777            if (_this17.isPaymentWhatsapp) {
27778              _this17.handleSuccessWpp(false);
27779            } else {
27780              setTimeout(function () {
27781                if ($('#checkoutPagePath') && $('#checkoutPagePath').val()) $(location).attr('href', $('#checkoutPagePath').val());
27782              }, 300);
27783            }
27784          }).catch(function (err) {
27785            LoaderService.hide();
27786            _this17.eraseInputs();
27787            _this17.clearIframeValueAdyen();
27788            if (_this17.verifySeatErr(err)) {
27789              AlertConfirmation.show(i18n("error_seat_title"), i18n("error_seat_message"), true);
27790
27791              $('#overlay, [data-js="close-menu"]').on("click", function () {
27792                $(location).attr("href", $('#homePagePath').val());
27793              });
27794            } else {
27795              var errorMsg = 'Erro ao processar pagamento';
27796              var errorCode = '';
27797
27798              try {
27799                var response = err.responseJSON;
27800                if (response && response.error) {
27801                  errorMsg = response.error;
27802                }
27803                if (response && response.errorCode) {
27804                  errorCode = response.errorCode;
27805                }
27806              } catch (e) {
27807                console.error(e);
27808              }
27809
27810              _this17.checkQttPaymentErr(errorMsg, errorCode);
27811            }
27812          });
27813        }
27814      });
27815
27816      var getMatchedMessage = function getMatchedMessage(err) {
27817        var errorMsgCode = void 0,
27818          errorMsgRefusalReason = void 0,
27819          msg = void 0;
27820        var genericError = _this17.confirmSaleMsgs.find(function (msg) {
27821          return msg.errorCode === 0;
27822        }).messageToCostumer;
27823
27824        try {
27825          errorMsgCode = +JSON.parse(err.responseJSON.result).RefusalReasonCode;
27826          errorMsgRefusalReason = '' + JSON.parse(err.responseJSON.result).RefusalReason;
27827
27828          if (errorMsgRefusalReason) {
27829            msg = _this17.confirmSaleMsgs.find(function (msg) {
27830              return msg.refusalReason === errorMsgRefusalReason.trim();
27831            }).messageToCostumer;
27832          } else {
27833            msg = _this17.confirmSaleMsgs.find(function (msg) {
27834              return msg.errorCode === errorMsgCode;
27835            }).messageToCostumer;
27836          }
27837
27838          if (!msg) return genericError;
27839          return msg;
27840        } catch (_) {
27841          errorMsgCode = null;
27842          return genericError;
27843        }
27844      };
27845    }
27846  }, {
27847    key: 'getPaymentMethodPayMee',
27848    value: function getPaymentMethodPayMee(bankName) {
27849      if ($('img[title="' + bankName + '"]').length > 0) {
27850        localStorage.setItem('bank-current-logo', $('img[title="' + bankName + '"]').first().attr('src'));
27851        localStorage.setItem('bank-current-name', bankName);
27852      }
27853      return {
27854        'bradesco': 'BRADESCO_TRANSFER',
27855        'Bradesco': 'BRADESCO_TRANSFER',
27856        'banco_do_brasil': 'BB_TRANSFER',
27857        'Banco do Brasil': 'BB_TRANSFER',
27858        'Banco Do Brasil': 'BB_TRANSFER',
27859        'bs2': 'BS2_TRANSFER',
27860        'Banco bs2': 'BS2_TRANSFER',
27861        'Banco Bs2': 'BS2_TRANSFER',
27862        'BS2': 'BS2_TRANSFER',
27863        'Banco BS2': 'BS2_TRANSFER',
27864        'caixa': 'CEF_TRANSFER',
27865        'Caixa': 'CEF_TRANSFER',
27866        'Caixa Econômica': 'CEF_TRANSFER',
27867        'Caixa Econômica Federal': 'CEF_TRANSFER',
27868        'itau': 'ITAU_TRANSFER_GENERIC',
27869        'itaú': 'ITAU_TRANSFER_GENERIC',
27870        'Itaú': 'ITAU_TRANSFER_GENERIC',
27871        'Banco Itaú': 'ITAU_TRANSFER_GENERIC',
27872        'original': 'ORIGINAL_TRANSFER',
27873        'Original': 'ORIGINAL_TRANSFER',
27874        'Banco Original': 'ORIGINAL_TRANSFER',
27875        'santander': 'SANTANDER_TRANSFER',
27876        'Santander': 'SANTANDER_TRANSFER',
27877        'Banco Santander': 'SANTANDER_TRANSFER',
27878        'inter': 'INTER_TRANSFER'
27879      }[bankName] || 'OUTROS_BANCOS';
27880    }
27881  }, {
27882    key: 'clearIframeValueAdyen',
27883    value: function clearIframeValueAdyen() {
27884      var isClearAdyenIframe = $('[data-js="clear-iframe"]').attr('data-clear').toLowerCase() === 'true';
27885
27886      if (isClearAdyenIframe) {
27887        $('[data-js="iframe-wrapper"]').empty();
27888        $('[data-js="input-doc"]').closest('.field').show();
27889        this.loadAdyenIframe();
27890      }
27891    }
27892  }, {
27893    key: 'resolvePaymentBank',
27894    value: function resolvePaymentBank() {
27895      var _this18 = this;
27896
27897      var branch = this.branch.val();
27898      var account = this.account.val();
27899      var paymentMethod = this.getPaymentMethodPayMee(this.bankName.val());
27900      var document = this.document.val();
27901      var deviceFingerprint = $("#device-fingerprint").val(); //Adyen integration
27902      var passengers = this.cartService.passengers;
27903
27904      var hasInsurance = this.insuranceCheck.is(':checked');
27905
27906      LoaderService.show();
27907      this.getIP().then(function (ip) {
27908        var paymentBank = new PaymentBankTransfer(branch, account, paymentMethod, document, deviceFingerprint, passengers, hasInsurance, ip, _this18.saleplatform);
27909
27910        var channelTitle = _this18.isPaymentWhatsapp ? 'wpp' : 'site';
27911
27912        var headers = {
27913          'Authorization': '' + SessionStorage.get('jca_token'),
27914          'sessionseatlock': SessionStorage.get('sessionseatlock'),
27915          'version': 2,
27916          'channel': Utils.getChannelTitle(_this18.isPaymentWhatsapp, _this18.saleplatform)
27917        };
27918
27919        HttpService.post('paymentBank', paymentBank, headers).then(function (data) {
27920          LoaderService.hide();
27921          SessionStorage.set('checkout', data.result);
27922          SessionStorage.set('cart', _this18.cartService.cart);
27923
27924          // Analytics
27925          data_layer.page.pageInfo.paymentFlow.paymentFlowChanged = true;
27926          setTimeout(function () {
27927            $(location).attr('href', $('#checkoutBankPagePath').val());
27928          }, 300);
27929          _this18.buttonSubmit.on('click');
27930        }).catch(function (err) {
27931          LoaderService.hide();
27932          _this18.enableSubmitButton();
27933          _this18.eraseInputs();
27934          if (_this18.verifyErr(err)) _this18.handleSpecificErr(err); else {
27935            _this18.checkQttPaymentErr();
27936            OverlayService.show();
27937            // send2Analytics(msg)
27938          }
27939        });
27940      });
27941    }
27942  }, {
27943    key: 'resolvePaymentContaGiro',
27944    value: function resolvePaymentContaGiro() {
27945      SessionStorage.set('passengers', this.cartService.passengers);
27946      SessionStorage.set('insuranceCheck', this.insuranceCheck.is(':checked'));
27947      SessionStorage.set('salePlatform', this.saleplatform);
27948      SessionStorage.set('cart', this.cartService.cart);
27949      this.checkisPaymentWallet();
27950      if (this.pinRecentlyVerified) {
27951        this.executeWalletPayment();
27952      } else {
27953        var returnPage = SessionStorage.get('repricingv2') ? $('#reschedulePaymentPagePathV2').val() : $('#paymentPagePath').val();
27954        SessionStorage.set('walletReturnUrl', returnPage);
27955        $(location).attr('href', $('#walletLoginPagePath').val());
27956      }
27957    }
27958  }, {
27959    key: 'executeWalletPayment',
27960    value: function executeWalletPayment() {
27961      var _this28 = this;
27962
27963      var passengers = Array.isArray(this.cartService.passengers) ? this.cartService.passengers : [];
27964      var branch = '0001';
27965      var account = '0001-1';
27966      var documentNumber = this.mainPassenger._documentNumber;
27967      var paymentMethod = 'PIX';
27968      var deviceFingerprint = $("#device-fingerprint").val();
27969      var hasInsurance = this.insuranceCheck.is(':checked');
27970
27971      LoaderService.show();
27972
27973      this.getIP().then(function (ip) {
27974        var paymentData = new PaymentPixWallet(branch, account, documentNumber, paymentMethod, deviceFingerprint, passengers, hasInsurance, ip, _this28.saleplatform);
27975
27976        var headers = {
27977          'Authorization': '' + SessionStorage.get('jca_token'),
27978          'sessionseatlock': SessionStorage.get('sessionseatlock'),
27979          'channel': Utils.getChannelTitle(_this28.isPaymentWhatsapp, _this28.saleplatform)
27980        };
27981
27982        HttpService.post('paymentPixWallet', paymentData, headers).then(function (data) {
27983          if (data.success === false) {
27984            throw {
27985              responseJSON: {
27986                error: data.error || 'Erro ao processar pagamento',
27987                errorCode: data.errorCode || ''
27988              }
27989            };
27990          }
27991
27992          LoaderService.hide();
27993          SessionStorage.set('checkout', data.result);
27994          $(location).attr('href', $('#walletPaymentCheckoutPagePath').val());
27995        }).catch(function (err) {
27996          console.error('Payment error:', err);
27997          LoaderService.hide();
27998
27999          if (_this28.verifySeatErr(err)) {
28000            AlertConfirmation.show(i18n("error_seat_title"), i18n("error_seat_message"), true);
28001
28002            $('#overlay, [data-js="close-menu"]').on("click", function () {
28003              $(location).attr("href", $('#homePagePath').val());
28004            });
28005          } else {
28006            var errorMsg = 'Erro ao processar pagamento';
28007            var errorCode = '';
28008
28009            try {
28010              var response = err.responseJSON;
28011              if (response && response.error) {
28012                errorMsg = response.error;
28013              }
28014              if (response && response.errorCode) {
28015                errorCode = response.errorCode;
28016              }
28017            } catch (e) {
28018              console.error('Error parsing response:', e);
28019            }
28020            _this28.checkQttPaymentErr(errorMsg, errorCode);
28021          }
28022        });
28023      });
28024    }
28025  }, {
28026    key: 'resolvePaymentPix',
28027    value: function resolvePaymentPix() {
28028      var _this19 = this;
28029
28030      var branch = '0001';
28031      var account = '0001-1';
28032      var document = this.mainPassenger._cpf ? this.mainPassenger._cpf : this.mainPassenger._login;
28033      var paymentMethod = 'PIX';
28034      var deviceFingerprint = $("#device-fingerprint").val(); //Adyen integration
28035      var passengers = this.cartService.passengers;
28036      var saleplatform = SessionStorage.get('utm_saleplatform') ? SessionStorage.get('utm_saleplatform') : "SITES-UTP";
28037      var hasInsurance = this.insuranceCheck.is(':checked');
28038
28039      LoaderService.show();
28040      this.getIP().then(function (ip) {
28041        var paymentPix = new PaymentPix(branch, account, document, paymentMethod, deviceFingerprint, passengers, hasInsurance, ip, saleplatform);
28042
28043        var channelTitle = _this19.isPaymentWhatsapp ? 'wpp' : 'site';
28044
28045        var headers = {
28046          'Authorization': '' + SessionStorage.get('jca_token'),
28047          'sessionseatlock': SessionStorage.get('sessionseatlock'),
28048          'version': 2,
28049          'channel': Utils.getChannelTitle(_this19.isPaymentWhatsapp, _this19.saleplatform)
28050        };
28051
28052        var serviceUrl = 'paymentPix';
28053
28054        HttpService.post(serviceUrl, paymentPix, headers).then(function (data) {
28055          if (data.success === false) {
28056            throw {
28057              responseJSON: {
28058                error: data.error || 'Erro ao processar pagamento',
28059                errorCode: data.errorCode || ''
28060              }
28061            };
28062          }
28063          LoaderService.hide();
28064          SessionStorage.set('checkout', data.result);
28065          SessionStorage.set('cart', _this19.cartService.cart);
28066
28067          // Analytics
28068          data_layer.page.pageInfo.paymentFlow.paymentFlowChanged = true;
28069          setTimeout(function () {
28070            $(location).attr('href', (_this19.repricingV2 ? $('#checkoutPixRepricingV2PagePath').val() : $('#checkoutPixPagePath').val()));
28071          }, 300);;
28072          _this19.buttonSubmit.on('click');
28073        }).catch(function (err) {
28074          LoaderService.hide();
28075          _this19.eraseInputs();
28076          _this19.enableSubmitButton();
28077          if (_this19.verifySeatErr(err)) {
28078            AlertConfirmation.show(i18n("error_seat_title"), i18n("error_seat_message"), true);
28079
28080            $('#overlay, [data-js="close-menu"]').on("click", function () {
28081              $(location).attr('href', $('#homePagePath').val());
28082            });
28083          } else {
28084            var errorMsg = 'Erro ao processar pagamento';
28085            var errorCode = '';
28086
28087            try {
28088              var response = err.responseJSON;
28089              if (response && response.error) {
28090                errorMsg = response.error;
28091              }
28092              if (response && response.errorCode) {
28093                errorCode = response.errorCode;
28094              }
28095            } catch (e) {
28096              console.error(e);
28097            }
28098
28099            _this19.checkQttPaymentErr(errorMsg, errorCode);
28100          }
28101        });
28102      });
28103    }
28104  },{
28105    key: 'isMobileDevice',
28106    value: function isMobileDevice() {
28107      var os = Utils.getDeviceOS ? Utils.getDeviceOS() : null;
28108      var isMobileOS = os === 'IOS' || os === 'ANDROID';
28109      return isMobileOS || navigator.maxTouchPoints > 0 && Utils.isMobile();
28110    }
28111  }, {
28112    key: 'resolvePaymentNupay',
28113    value: function resolvePaymentNupay() {
28114      var _this36 = this;
28115
28116      var branch = "0001";
28117      var account = "0001-1";
28118      var document = this.mainPassenger._documentNumber;
28119      var paymentMethod = "NUPAY";
28120      var deviceFingerprint = $("#device-fingerprint").val();
28121      var passengers = this.cartService.passengers;
28122
28123      var hasInsurance = this.insuranceCheck.is(":checked");
28124      var hasInsuranceW2i = false;
28125      var additionalFields = {};
28126
28127      LoaderService.show();
28128      this.getIP().then(function (ip) {
28129        var paymentNupay = new PaymentNupay(additionalFields, branch, account, document, paymentMethod, deviceFingerprint, passengers, hasInsurance, hasInsuranceW2i, ip, _this36.saleplatform);
28130
28131        var headers = {
28132          Authorization: '' + SessionStorage.get("jca_token"),
28133          sessionseatlock: SessionStorage.get("sessionseatlock"),
28134          channel: Utils.getChannelTitle(_this36.isPaymentWhatsapp, _this36.saleplatform)
28135        };
28136
28137        HttpService.post("paymentNupay", paymentNupay, headers).then(function (data) {
28138          LoaderService.hide();
28139
28140          if (data.success === false) {
28141            throw {
28142              responseJSON: {
28143                error: data.error || 'Erro ao processar pagamento',
28144                errorCode: data.errorCode || ''
28145              }
28146            };
28147          }
28148
28149          SessionStorage.set("checkout", data);
28150          SessionStorage.set("checkout_aux", { method: "NUPAY" });
28151          SessionStorage.set("cart", _this36.cartService.cart);
28152          SessionStorage.set("nupayCreatedAt", Date.now());
28153
28154          data_layer.page.pageInfo.paymentFlow.paymentFlowChanged = true;
28155          if (_this36.isMobileDevice()) {
28156            var paymentUrl = data.result && data.result.additionalFields && data.result.additionalFields.nupay && data.result.additionalFields.nupay.paymentUrl;
28157            if (paymentUrl) {
28158              setTimeout(function () {
28159                $(location).attr("href", paymentUrl);
28160              }, 300);
28161            } else {
28162              LoaderService.hide();
28163              AlertConfirmation.show('Pagamento NuPay indisponível', 'Não foi possível obter o link de pagamento NuPay. Por favor, tente novamente.', true);
28164              _this36.eraseInputs();
28165              _this36.enableSubmitButton();
28166            }
28167          } else {
28168            setTimeout(function () {
28169              $(location).attr('href', $('#checkoutNupayPagePath').val())
28170            }, 300);
28171          }
28172          _this36.buttonSubmit.on("click");
28173        }).catch(function (err) {
28174          LoaderService.hide();
28175          _this36.eraseInputs();
28176          _this36.enableSubmitButton();
28177          if (_this36.verifySeatErr(err)) {
28178            AlertConfirmation.show(i18n("error_seat_title"), i18n("error_seat_message"), true);
28179
28180            $('#overlay, [data-js="close-menu"]').on("click", function () {
28181              $(location).attr('href', $('#homePagePath').val());
28182            });
28183          } else {
28184            var errorMsg = 'Erro ao processar pagamento';
28185            var errorCode = '';
28186
28187            try {
28188              var response = err.responseJSON;
28189              if (response && response.error) {
28190                errorMsg = response.error;
28191              }
28192              if (response && response.errorCode) {
28193                errorCode = response.errorCode;
28194              }
28195            } catch (e) {
28196              console.error(e);
28197            }
28198
28199            _this36.checkQttPaymentErr(errorMsg, errorCode);
28200          }
28201        });
28202      });
28203    }
28204  }, {
28205    key: 'resolvePaymentLivelo',
28206    value: function resolvePaymentLivelo() {
28207      var _this20 = this;
28208
28209      var paymentLivelo = '';
28210      var passengers = this.cartService.passengers;
28211      var hasInsuranceW2i = this.insuranceCheck.is(':checked');
28212      var token = $('[data-js="insert-livelo-token"]').val();
28213
28214      LoaderService.show();
28215
28216      if (_this20.typeLivelo == 'mobile') {
28217        paymentLivelo = new PaymentLivelo(passengers, hasInsuranceW2i, token, _this20.typeLivelo);
28218      } else {
28219        paymentLivelo = new PaymentLiveloDevice(passengers, hasInsuranceW2i, token, _this20.typeLivelo, _this20.deviceIdLivelo);
28220      }
28221
28222      var channelTitle = this.isPaymentWhatsapp ? 'wpp' : 'site';
28223
28224      var headers = {
28225        'Authorization': '' + SessionStorage.get('jca_token'),
28226        'sessionseatlock': SessionStorage.get('sessionseatlock'),
28227        'channel': Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform)
28228      };
28229
28230      HttpService.post('paymentLivelo', paymentLivelo, headers).then(function (data) {
28231        LoaderService.hide();
28232        SessionStorage.set('checkout', data.result);
28233        SessionStorage.set('cart', _this20.cartService.cart);
28234
28235        // Analytics
28236        data_layer.page.pageInfo.paymentFlow.paymentFlowChanged = true;
28237        setTimeout(function () {
28238          $(location).attr('href', $('#checkoutLiveloPagePath').val());
28239        }, 300);
28240        _this20.buttonSubmit.on('click');
28241      }).catch(function (err) {
28242        LoaderService.hide();
28243        _this20.eraseInputs();
28244        _this20.enableSubmitButton();
28245        _this20.checkQttPaymentErr();
28246        if (_this20.verifyErr(err)) _this20.handleSpecificErr(err); else {
28247          var errMsg = _this20.getErrMsgBankTransfer();
28248          _this20.checkQttPaymentErr(errMsg);
28249          OverlayService.show();
28250          // send2Analytics(msg)
28251        }
28252      });
28253    }
28254  }, {
28255    key: 'verifyErr',
28256    value: function verifyErr(err) {
28257      try {
28258        var msgError = err.responseJSON && err.responseJSON.result ? JSON.parse(err.responseJSON.result) : {};
28259        var isSpecificError = msgError && msgError.hasOwnProperty('message');
28260        return isSpecificError;
28261      } catch (e) {
28262        return false;
28263      }
28264    }
28265  }, {
28266    key: 'verifyErrMalga',
28267    value: function verifyErrMalga(err) {
28268      try {
28269         var msgError = err.responseJSON.result;
28270
28271         if(msgError.message != undefined) {
28272           var isSpecificError = msgError.message.hasOwnProperty("message");
28273
28274           if (isSpecificError) {
28275             return true;
28276           }
28277         }
28278
28279         return false;
28280      } catch (e) {
28281         return false;
28282      }
28283    }
28284  }, {
28285    key: "verifySeatErr",
28286    value: function verifySeatErr(err) {
28287    if (err && err.responseJSON && err.responseJSON.error && typeof err.responseJSON.error === 'string') {
28288      if (err.responseJSON.error.toLowerCase().includes('number of passengers and seats, incorrect')) return true;
28289    } else if (err && err.responseJSON && err.responseJSON.result && err.responseJSON.result.toLowerCase().includes('sessão expirada')) {
28290      return true;
28291    }
28292
28293    return false;
28294    }
28295  }, {
28296    key: 'handleSpecificErr',
28297    value: function handleSpecificErr(err) {
28298      this.errorPurchasePayment();
28299    }
28300  }, {
28301    key: 'errorPurchasePayment',
28302    value: function errorPurchasePayment() {
28303      OverlayService.show();
28304      var text1 = 'payment_error';
28305      var text2 = 'payment_error_purchase';
28306      var redirect = true;
28307      this.showMsgPaymentError(text1, text2, redirect);
28308    }
28309  }, {
28310    key: 'showMsgPaymentError',
28311    value: function showMsgPaymentError(text1, text2, redirect) {
28312      var title = i18n(text1);
28313      var subtitle = i18n(text2);
28314      AlertConfirmation.show(title, subtitle, redirect);
28315    }
28316  }, {
28317    key: 'checkQttPaymentErr',
28318    value: function checkQttPaymentErr(msg, errorMsgCode) {
28319      OverlayService.show();
28320
28321      this.showMsgPaymentError(msg, errorMsgCode || 'payment_generic_error');
28322
28323      if (errorMsgCode && errorMsgCode.toString().toLowerCase() === '2b0') {
28324        $('[data-js="link-contact-us-confirmation"]').css('display', 'block');
28325      } else {
28326        $('[data-js="link-contact-us-confirmation"]').css('display', 'none');
28327      }
28328    }
28329  }, {
28330    key: 'resolvePayment',
28331    value: function resolvePayment() {
28332      if (this.cartComponent.totalOffDiscount) {
28333        this.resolvePaymentCard();
28334      } else if ($('.card-form-malga').length && !SessionStorage.get('paymentNegative') == true) {
28335        this.resolvePaymentCardMalga();
28336      } else {
28337        this.resolvePaymentCard();
28338      }
28339    }
28340  }, {
28341    key: 'checkPaymentMethod',
28342    value: function checkPaymentMethod() {
28343      var isPaymentBank = $('[data-js="tab-bank"]').hasClass('active') || $('[data-js="tab-bank"]').hasClass('is-selected');
28344      var isPaymentPix = $('[data-js="tab-pix"]').hasClass('active') || $('[data-js="tab-pix"]').hasClass('is-selected');
28345      var isPaymentNupay = $('[data-js="tab-nupay"]').hasClass('is-selected');
28346      var isPaymentLivelo = $('[data-js="tab-livelo"]').hasClass('active');
28347      var isPaymentContaGiro = $('[data-js="tab-conta-giro"]').hasClass('active') || $('[data-js="tab-conta-giro"]').hasClass('is-selected');
28348      var isNegativeValue = this.isRepricingNegativeValue();
28349      var isZeroValue = this.isRepricingZeroValue();
28350
28351      this.disableSubmitButton();
28352
28353      if (this.cartComponent.totalOffDiscount && !this.insuranceCheck.is(':checked') && !this.isPaymentWhatsapp) this.resolvePayment();else if (this.isPaymentWhatsapp) this.resolvePayment();else if (isNegativeValue || isZeroValue) this.resolvePaymentCard();else if (isPaymentBank) this.resolvePaymentBank();else if (isPaymentPix) this.resolvePaymentPix();else if (isPaymentNupay) this.resolvePaymentNupay();else if (isPaymentContaGiro) this.resolvePaymentContaGiro();else if (isPaymentLivelo) this.resolvePaymentLivelo();else this.resolvePayment();
28354    }
28355  }, {
28356      key: 'addPaymentInfoAnalytics',
28357      value: function addPaymentInfoAnalytics( paymentMethod ) {
28358       var _this = this;
28359       var cart = SessionStorage.get('cart');
28360       var value = $('[data-js="price-cart"]').text();
28361       var voucherIsAdded = $('[data-js="discount-code"]').prop('disabled');
28362       var voucher = "";
28363
28364       if (voucherIsAdded)
28365            voucher = $('[data-js="discount-code"]').val().toUpperCase();
28366
28367
28368       var dataLayerView = [];
28369       cart._listOffer.forEach(function (offer) {
28370         var aux = {
28371             item_id: offer._service,
28372             price: offer._price,
28373             item_brand: offer._company._companyName,
28374             item_category: offer._company._origin._label,
28375             item_category2: offer._company._destination._label,
28376             item_category3: offer._company._departureDate,
28377             item_category4: offer._company._arrivingDate,
28378             item_variant: offer._classtype._className,
28379             quantity: cart._listPassengers.length
28380         };
28381         dataLayerView.push(aux);
28382       });
28383
28384       dataLayer.push({ ecommerce: null });
28385       dataLayer.push({ event: "add_payment_info",
28386           ecommerce:{
28387             currency: "BRL",
28388             payment_type: paymentMethod,
28389             coupon: voucher,
28390             value: value,
28391             affiliation: $("#siteName").val(),
28392             items: dataLayerView
28393           }
28394       });
28395      }
28396  }, {
28397    key: 'rejectDiscountPayment',
28398    value: function rejectDiscountPayment(err){
28399      LoaderService.hide();
28400      OverlayService.show();
28401
28402      var errorMsg = i18n("payment_error");
28403      var errorCode = i18n("cupom_error");
28404
28405      try {
28406        var errData = err && err.responseJSON ? err.responseJSON : err;
28407        if (errData && errData.errors && errData.errors.length && errData.errors[0].error && errData.errors[0].errorCode) {
28408          errorMsg = errData.errors[0].error;
28409          errorCode = errData.errors[0].errorCode;
28410        }
28411      } catch (e) {
28412        console.error(e);
28413      }
28414
28415      var redirect = false;
28416      AlertConfirmation.show(errorMsg, errorCode, redirect);
28417    }
28418  }, {
28419    key: 'handleMinTimeBuyTripPayment',
28420    value: function handleMinTimeBuyTripPayment() {
28421      var wppDepartureDate = void 0;
28422      if (this.isPaymentWhatsapp) {
28423        var firstTransactionGoing = this.saleResult.sale.transactions.find(function (transaction) {
28424          return transaction.going === true;
28425        });
28426        wppDepartureDate = firstTransactionGoing.seatResponse.service.departureDate;
28427      }
28428
28429      var minTimeToBuyTrip = $('[data-js="min-time-to-buy-ticket"]').val() ? +$('[data-js="min-time-to-buy-ticket"]').val() : 20;
28430      var hourDepartResearch = new Date().getTime() + minTimeToBuyTrip * 60 * 1000;
28431      var dateTrip = this.isPaymentWhatsapp ? new Date(wppDepartureDate).getTime() : new Date(this.cart._listOffer[0]._company._departureDate).getTime();
28432      var isAfterMinTime = hourDepartResearch < dateTrip;
28433
28434      return isAfterMinTime;
28435    }
28436  }, {
28437    key: 'submitPayment',
28438    value: function submitPayment() {
28439      var _this21 = this;
28440
28441      this.buttonSubmit.off('click').click(function () {
28442        _this21.disableSubmitButton();
28443        if (_this21.handleMinTimeBuyTripPayment()) {
28444          $.when(_this21.validateDiscount()).then(function () {
28445            return _this21.checkPaymentMethod();
28446          }, function (err) {
28447            return _this21.rejectDiscountPayment(err);
28448          });
28449        } else {
28450          SessionService.sessionExpireEvent(true);
28451        }
28452      });
28453    }
28454  }, {
28455    key: 'getIP',
28456    value: function getIP() {
28457      return new Promise(function (resolve, reject) {
28458        $.getJSON('https://api.ipify.org?format=json').then(function (data) {
28459          return resolve(data.ip);
28460        }).catch(function () {
28461          $.getJSON('https://jsonip.com/').then(function (data) {
28462            return resolve(data.ip);
28463          }).catch(function (err) {
28464            return resolve(null);
28465          });
28466        });
28467      });
28468    }
28469  }, {
28470    key: 'eraseInputs',
28471    value: function eraseInputs() {
28472      if (this.shouldEraseInsuranceCheck) this.insuranceCheck.prop('checked', false);
28473
28474      if (this.shouldEraseInputNameCard) this.inputName.val('');
28475
28476      if (this.shouldEraseInputNumberCard) this.inputCardNumber.val('');
28477
28478      if (this.shouldEraseInputSecCode) this.inputSecurity.val('');
28479
28480      if (this.shouldEraseInputExpiration) this.inputExpiration.val('');
28481
28482      if (this.shouldEraseInputCpf) this.inputDoc.val('');
28483
28484      if (this.shouldEraseBtnInstallment) this.btnInstallment.parent().find('.select-items').find('li').first().find('a').click();
28485
28486      if (this.shouldEraseConditionsCheck) this.checkConditions.prop('checked', false);
28487
28488      if (this.checkConditions.is(':checked') && this.isFormValid() || this.checkConditions.is(":checked") && this.isFormValidMalga()) this.enableSubmitButton(); else this.disableSubmitButton();
28489    }
28490  }, {
28491    key: 'validatePaymentForm',
28492    value: function validatePaymentForm() {
28493      var isPaymentFormValid = true;
28494
28495      $('[data-js="card-form"]').find('input:visible, select:visible').each(function (_, el) {
28496        if (!$(el).val()) isPaymentFormValid = false;
28497      });
28498
28499      return isPaymentFormValid;
28500    }
28501  }, {
28502    key: 'validatePaymentFormMalga',
28503    value: function validatePaymentFormMalga() {
28504      var isPaymentFormValid = true;
28505
28506      $("div.card-form-malga").find("input:visible, select:visible").each(function (_, el) {
28507        if (!$(el).val()) isPaymentFormValid = false;
28508      });
28509
28510      return isPaymentFormValid;
28511    }
28512  }, {
28513    key: 'isFormValid',
28514    value: function isFormValid() {
28515      if (!this.isPaymentWhatsapp) {
28516        var isNegativeValue = this.isRepricingNegativeValue();
28517        var isZeroValue = this.isRepricingZeroValue();
28518
28519        if (isZeroValue || isNegativeValue && this.validRemarkForm() || !this.repricingV2 && this.cartComponent.totalOffDiscount) {
28520          return true;
28521        }
28522      }
28523
28524      return this.validatePaymentForm() && $('[data-js="btn-installment-select"]').val() && this.validateIframe();
28525    }
28526  }, {
28527    key: 'isFormValidMalga',
28528    value: function isFormValidMalga() {
28529      var pixActive = $('[data-js="tab-pix"]').hasClass('active') || $('[data-form="pix-wrapper"]').is(':visible');
28530      if (pixActive) return true;
28531
28532      if (this.isUseAdyen && typeof this.isUseAdyen === 'function' && this.isUseAdyen() && !this.isMalgaActive) {
28533        return false;
28534      }
28535
28536      var malgaCardActive = $('.card-form-malga').length && $('.card-form-malga').is(':visible');
28537      if (!malgaCardActive) return false;
28538
28539      if (this.storedCardToken) {
28540        var cvvOk = ($('#securityCode').val() || '').trim().length >= 3;
28541        var installmentOk = !!$('[data-js="btn-installment-select"]').val();
28542        return cvvOk && installmentOk;
28543      }
28544
28545      return this.malgaFieldValidity ? Object.values(this.malgaFieldValidity).every(Boolean) : false;
28546    }
28547  }, {
28548    key: 'renderBankLogo',
28549    value: function renderBankLogo() {
28550      this.handleBankTransfer();
28551    }
28552  }, {
28553    key: 'handleBankTransfer',
28554    value: function handleBankTransfer() {
28555      var _this20 = this;
28556
28557      $('.logo-bank-img').on('click', function (e) {
28558        var typeBank = $('[data-js="bank-select"]')[0];
28559        var title = $(e.currentTarget).attr('title');
28560        _this20.selectCustom.selectDefault(typeBank, title);
28561      });
28562
28563      $('[data-js="bank-select"]').on('change', function () {
28564        var bankSelected = $(this).val().replace(/\_/g, '');
28565        $('.logo-bank-img').removeClass('active');
28566        $('[data-js="' + bankSelected + '"]').addClass('active');
28567      });
28568
28569      $('[data-js="bank-form"] input[required]').on('change focusout', function (e) {
28570        e.stopImmediatePropagation();
28571        var $tip = $(e.target).parent().siblings().find('.tip');
28572
28573        if ($(e.currentTarget).val().length <= 3) {
28574          Utils.addInvalidClass($(e.currentTarget), $('[data-js="bank-fields-required"]').val(), $tip);
28575        } else {
28576          Utils.removeInvalidClass($(e.currentTarget), $tip);
28577        }
28578      });
28579    }
28580  }, {
28581    key: 'handlePaymentCardValid',
28582    value: function handlePaymentCardValid() {
28583      var _this26 = this;
28584
28585      this.checkConditions.on("change", function () {
28586        _this26.checkConditions.is(":checked") && (_this26.isFormValidMalga() || _this26.isFormValid()) ? _this26.enableSubmitButton() : _this26.disableSubmitButton();
28587      });
28588    }
28589  }, {
28590    key: 'fillSelectsBank',
28591    value: function fillSelectsBank() {
28592      var _this21 = this;
28593
28594      var selectBank = $('[data-js="bank-select"]');
28595      $('[data-js="list-logo-bank"]').find('li').each(function (index, element) {
28596        var image = $(element).find('.logo-bank-img');
28597        var option = new Option($(image).attr('title'), $(image).attr('title'));
28598        selectBank.append(option);
28599        _this21.selectCustom.initSingle(selectBank.parent());
28600      });
28601    }
28602  }, {
28603    key: 'validateBtn',
28604    value: function validateBtn() {
28605      var _this23 = this;
28606
28607      this.tabBank.add(this.tabCard).add(this.tabPix).on('click', function () {
28608        var isTabBankActive = _this23.tabBank.hasClass('active');
28609        var isTabPixActive = _this23.tabPix.hasClass('active');
28610
28611        if (isTabBankActive) {
28612          _this23.isFormPaymentBank();
28613        }
28614
28615        if (isTabPixActive) {
28616          _this23.handlePaymentPixValid();
28617        }
28618      });
28619    }
28620  }, {
28621    key: 'handlePaymentPixValid',
28622    value: function handlePaymentPixValid() {
28623      var _this42 = this;
28624
28625      $('[data-js="tab-pix"] input[required], #conditions-check').on('keyup change select', function () {
28626        if ($('[data-js="tab-pix"]').hasClass('active') || $('[data-js="tab-pix"]').hasClass('is-selected')) {
28627          _this42.checkConditions.is(':checked') ? _this42.enableSubmitButton() : _this42.disableSubmitButton();
28628        }
28629      });
28630    }
28631  }, {
28632    key: 'handlePaymentNupayValid',
28633    value: function handlePaymentNupayValid() {
28634      var _this43 = this;
28635
28636      $('#conditions-check').on('change', function () {
28637        if ($('[data-js="tab-nupay"]').hasClass('is-selected')) {
28638          _this43.checkConditions.is(':checked') ? _this43.enableSubmitButton() : _this43.disableSubmitButton();
28639        }
28640      });
28641    }
28642  }, {
28643    key: 'handleWalletPixValid',
28644    value: function handleWalletPixValid() {
28645      var _this35 = this;
28646
28647      $('[data-js="tab-conta-giro"] input[required], #conditions-check').on('keyup change select', function () {
28648        if ($('[data-js="tab-conta-giro"]').hasClass('active')) {
28649          ($('[data-js="pix-check"]').is(':checked') || $('[data-js="balance-check"]').is(':checked')) && _this35.checkConditions.is(':checked') ? _this35.enableSubmitButton() : _this35.disableSubmitButton();
28650        }
28651      });
28652    }
28653  }, {
28654    key: 'isCheckBalanceTrue',
28655    value: function isCheckBalanceTrue() {
28656      $('[data-js="tab-conta-giro"] input[required], #conditions-check').on('keyup change select', function () {
28657        if ($('[data-js="tab-conta-giro"]').hasClass('active')) {
28658          if ($('[data-js="balance-check"]').is(':checked')) {
28659            return true;
28660          } else {
28661            return false;
28662          }
28663        }
28664      });
28665    }
28666  }, {
28667    key: 'isFormPaymentBank',
28668    value: function isFormPaymentBank() {
28669      var _this23 = this;
28670
28671      $('[data-js="bank-form"] input[required], #conditions-check, #bank-select').on('keyup change select', function () {
28672        if ($('[data-js="bank-form"]')[0].checkValidity() && _this23.checkConditions.is(':checked') && $('[data-js="bank-select"]').val() || $('[data-js="bank-select"]').data('value') != null) {
28673          _this23.enableSubmitButton();
28674        }
28675      });
28676    }
28677  }, {
28678    key: 'checkQtdCreditCard',
28679    value: function checkQtdCreditCard() {
28680      var _this24 = this;
28681
28682      var headers = {
28683        'Authorization': '' + SessionStorage.get('jca_token'),
28684        flowPayment: "Adyen"
28685      };
28686
28687      LoaderService.show();
28688      HttpService.get('getCard', headers).then(function (data) {
28689        LoaderService.hide();
28690        _this24.hideSaveCheck(data.result.length);
28691      }).catch(function (err) {
28692        LoaderService.hide();
28693        console.err(err);
28694      });
28695    }
28696  }, {
28697    key: 'checkisPaymentWallet',
28698    value: function checkisPaymentWallet() {
28699      if ($('[data-js="balance-check"]').is(':checked')) {
28700        SessionStorage.set('completementPix', false);
28701      } else {
28702        SessionStorage.set('completementPix', true);
28703      }
28704    }
28705  }, {
28706    key: 'hideSaveCheck',
28707    value: function hideSaveCheck(qtdCards) {
28708      var maxCreditCard = $('[data-js="max-credit-card"]').attr('data-max');
28709
28710      if (qtdCards >= +maxCreditCard) {
28711        $('[data-js="recurring-content"]').hide();
28712      }
28713    }
28714  }, {
28715    key: 'controllerPaymentMethods',
28716    value: function controllerPaymentMethods() {
28717      var showMessageNoBankPixPayment = $('[data-js="message-no-bank-pix-payment-checkbox"]').data('active');
28718      this.listenPaymentMethod(showMessageNoBankPixPayment);
28719
28720      if (!showMessageNoBankPixPayment && !this.isPaymentWhatsapp) {
28721        var noBankTransfer = this.verifyMinHourToBankTransfer();
28722        var noPix = this.verifyMinHourToPix();
28723
28724        if (noBankTransfer) this.removeTabBankTransfer();
28725        if (noPix && !this.cart._listOffer[0]._priceWithDiscountPix) this.removeTabPix();
28726      }
28727    }
28728  }, {
28729    key: 'verifyMinHourToBankTransfer',
28730    value: function verifyMinHourToBankTransfer() {
28731      var minHour = $('[data-js="min-hour-bank-transfer"]').data('hour');
28732      var tripHour = this.cart._listOffer[0]._company._departureDate;
28733      var timeStamp = DateFormatter.getValidDateFormat(tripHour).getTime();
28734      var currentDate = new Date(this.timeExact);
28735      var hourPlusMinHour = currentDate.getHours() + minHour;
28736      var timeDatePlusMinHour = currentDate.setHours(hourPlusMinHour);
28737
28738      if (timeStamp <= timeDatePlusMinHour) return true;
28739
28740      return false;
28741    }
28742  }, {
28743    key: 'verifyMinHourToPix',
28744    value: function verifyMinHourToPix() {
28745      var minMinutes = $('[data-js="min-hour-pix"]').data('min');
28746      var tripHour = this.cart._listOffer[0]._company._departureDate;
28747      var timeStamp = DateFormatter.getValidDateFormat(tripHour).getTime();
28748      var currentDate = new Date(this.timeExact);
28749      var minutesPlusMin = currentDate.getMinutes() + minMinutes;
28750      var timeDatePlusMinMinutes = currentDate.setMinutes(minutesPlusMin);
28751
28752      if (timeStamp <= timeDatePlusMinMinutes) return true;
28753
28754      return false;
28755    }
28756  }, {
28757    key: 'handleBankTransferSelected',
28758    value: function handleBankTransferSelected(showMessageNoBankOrPixPayment) {
28759      var noBankTransfer = this.verifyMinHourToBankTransfer();
28760      var unregisteredCpf = this.mainPassenger._cpf;
28761
28762      if (showMessageNoBankOrPixPayment) {
28763        this.showMessageNoBankOrPixPayment();
28764        this.hideCheckConditions();
28765        if (unregisteredCpf === null || unregisteredCpf === undefined) {
28766          $('[data-js="message-no-cpf-payment"]').removeClass('d-none');
28767          return
28768        } else if (noBankTransfer) {
28769          $('[data-js="message-no-type-payment"]').removeClass('d-none');
28770        } else {
28771          this.showCheckConditions();
28772          this.removeMessageNoBankOrPixPayment();
28773          this.bankForm.trigger('reset');
28774          this.bankForm.fadeIn();
28775        }
28776      } else {
28777        this.showCheckConditions();
28778        this.removeMessageNoBankOrPixPayment();
28779        this.bankForm.trigger('reset');
28780        this.bankForm.fadeIn();
28781      }
28782    }
28783  }, {
28784    key: 'handlePixSelected',
28785    value: function handlePixSelected(showMessageNoBankOrPixPayment) {
28786      var noPix = this.verifyMinHourToPix();
28787      var unregisteredCpf = this.mainPassenger._cpf;
28788
28789      if (showMessageNoBankOrPixPayment) {
28790        this.showMessageNoBankOrPixPayment();
28791        this.hideCheckConditions();
28792        if (unregisteredCpf === null || unregisteredCpf === undefined || unregisteredCpf == "") {
28793          $('[data-js="message-no-cpf-payment"]').removeClass('d-none');
28794          return
28795        } else if (noPix) {
28796          $('[data-js="message-no-type-payment"]').removeClass('d-none');
28797        } else {
28798          this.showCheckConditions();
28799          this.removeMessageNoBankOrPixPayment();
28800          this.pixContent.fadeIn();
28801        }
28802      } else {
28803        this.showCheckConditions();
28804        this.removeMessageNoBankOrPixPayment();
28805        this.pixContent.fadeIn();
28806      }
28807    }
28808  }, {
28809    key: 'handlePixNoCpfSelected',
28810    value: function handlePixNoCpfSelected(pixSelected) {
28811      if (pixSelected && !this.messageCpfController.isCpfValidPix) {
28812        this.showMessageNoCpf(this.messageCpfController.isCpfValidPix);
28813        this.hideCheckConditions();
28814        this.pixContent.addClass('d-none');
28815      } else if (pixSelected && this.messageCpfController.isCpfValidPix) {
28816        this.showCheckConditions();
28817        this.removeMessageNoCpf();
28818        this.pixContent.removeClass('d-none');
28819      }
28820    }
28821  }, {
28822    key: 'handleTransferNoCpfSelected',
28823    value: function handleTransferNoCpfSelected(transferSelected) {
28824      if (transferSelected && !this.messageCpfController.isCpfValidTransfer) {
28825        this.showMessageNoCpf(this.messageCpfController.isCpfValidTransfer);
28826        this.hideCheckConditions();
28827        this.bankForm.addClass('d-none');
28828      } else if (transferSelected && this.messageCpfController.isCpfValidTransfer) {
28829        this.showCheckConditions();
28830        this.removeMessageNoCpf();
28831        this.bankForm.removeClass('d-none');
28832      }
28833    }
28834  }, {
28835   key: 'getCompanyId',
28836   value: function getCompanyId() {
28837     var cart = SessionStorage.get("cart");
28838     var serviceTripId = cart._listOffer[0]._service;
28839
28840     var servicesList = SessionStorage.get("currentResultDep").servicesList;
28841     var serviceTrip = servicesList.find(function (el) {
28842       return el.serviceId == serviceTripId;
28843     });
28844
28845     return serviceTrip.companyId;
28846   }
28847 }, {
28848    key: 'getPaymentAvailability',
28849    value: function getPaymentAvailability() {
28850      var _this29 = this;
28851
28852      // UTPs
28853      var SYSTEM_ID = 90;
28854      var salePlatform = this.saleplatform;
28855      var companyId = Utils.getCompanyId();
28856      var departureDate = SessionStorage.get('cart')._listOffer[0]._company._departureDate;
28857
28858      var headers = {
28859        systemId: SYSTEM_ID,
28860        'Authorization':  this.isPaymentWhatsapp ? this.wppToken : SessionStorage.get('jca_token'),
28861      };
28862
28863      var parameters = {
28864        departureDate: DateFormatter.getDateWithHour(departureDate),
28865        systemId: SYSTEM_ID,
28866        salePlatform: salePlatform,
28867        companyId: this.getCompanyId()
28868      };
28869
28870      var content = 'paymentAvailability?' + $.param(parameters);
28871
28872      LoaderService.show();
28873      HttpService.get(content, headers).then(function (data) {
28874        LoaderService.hide();
28875
28876        if (data.success) {
28877          _this29.applyPaymentAvailability(data.result);
28878        }
28879      }).catch(function (err) {
28880        LoaderService.hide();
28881        console.error(err);
28882      });
28883    }
28884  }, {
28885    key: 'applyPaymentAvailability',
28886    value: function applyPaymentAvailability(availability) {
28887      if (this.isRepricingZeroValue()) {
28888        this.handleCartZeroValue();
28889        return;
28890      }
28891
28892      var allowed = new Set(availability.map(function (a) {
28893        return a.paymentMethod;
28894      }));
28895
28896      if (!allowed.has('PIX')) {
28897        this.tabPix.hide();
28898        this.pixContent.hide();
28899      }
28900
28901      if (!allowed.has('WALLET')) {
28902        this.tabContaGiro.hide();
28903        this.contaGiroForm.hide();
28904        this.createWalletForm.hide();
28905      }
28906
28907      if (!allowed.has('CARTAO')) {
28908        this.tabCard.hide();
28909        this.cardForm.hide();
28910        $('#component-container, .card-form-malga').remove();
28911      }
28912
28913      if (SessionStorage.get('activateContaGiroTab')) {
28914        this.pinRecentlyVerified = !!SessionStorage.get('user_wallet');
28915        SessionStorage.remove('activateContaGiroTab');
28916        this.tabContaGiro.trigger('click');
28917      } else if (!$('.payment-card-wemobi.is-selected:visible').length && !$('.tablinks.active:visible').length) {
28918        $('.payment-card-wemobi:visible').first().click();
28919      }
28920    }
28921  }, {
28922    key: 'getFixedHeaderOffset',
28923    value: function getFixedHeaderOffset() {
28924      var offset = 0;
28925      var nodes = document.querySelectorAll('header, .hero-header-plus, .header-navbar, #header-navbar');
28926
28927      nodes.forEach(function (el) {
28928        var style = window.getComputedStyle(el);
28929        if (style.position !== 'fixed' && style.position !== 'sticky') return;
28930        if (style.display === 'none' || style.visibility === 'hidden') return;
28931
28932        var rect = el.getBoundingClientRect();
28933        if (rect.height <= 0 || rect.height > 140) return;
28934        if (rect.bottom <= 0 || rect.top > 24) return;
28935        offset = Math.max(offset, rect.bottom);
28936      });
28937
28938      return offset;
28939    }
28940  }, {
28941    key: 'scrollToPaymentStep',
28942    value: function scrollToPaymentStep(event, selectors) {
28943      var _this54 = this;
28944
28945      if (!event || !event.originalEvent) return;
28946
28947      var findTarget = function findTarget() {
28948        for (var i = 0; i < selectors.length; i++) {
28949          var nodes = document.querySelectorAll(selectors[i]);
28950          for (var n = 0; n < nodes.length; n++) {
28951            var el = nodes[n];
28952            var style = window.getComputedStyle(el);
28953            if (style.display === 'none' || style.visibility === 'hidden') continue;
28954            if (el.getBoundingClientRect().height < 24) continue;
28955            return el;
28956          }
28957        }
28958        return null;
28959      };
28960
28961      var align = function align(attempt) {
28962        var el = findTarget();
28963        if (!el) {
28964          if (attempt < 10) window.setTimeout(function () {
28965            return align(attempt + 1);
28966          }, 80);
28967          return;
28968        }
28969
28970        var headerOffset = _this54.getFixedHeaderOffset();
28971        var top = window.pageYOffset + el.getBoundingClientRect().top - headerOffset - 12;
28972        var reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
28973
28974        window.scrollTo({
28975          top: Math.max(0, top),
28976          behavior: reduceMotion ? 'auto' : 'smooth'
28977        });
28978      };
28979
28980      window.setTimeout(function () {
28981        return align(0);
28982      }, 80);
28983    }
28984  }, {
28985    key: 'listenPaymentMethod',
28986    value: function listenPaymentMethod() {
28987      var _this48 = this;
28988
28989      var showMessageNoBankOrPixPayment = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
28990
28991      var $inputEnablePaymentMethod = $('[data-js="enabled-payment-method"]');
28992      var autoSelect = $('[data-js="auto-select-payment-method"]').val();
28993      var isCardEnabled = $inputEnablePaymentMethod.data('card');
28994      var isBankEnabled = $inputEnablePaymentMethod.data('bank');
28995      var isPixEnabled = $inputEnablePaymentMethod.data('pix');
28996      var isNupayEnabled = $inputEnablePaymentMethod.data('nupay');
28997      var isLiveloEnabled = $inputEnablePaymentMethod.data('livelo');
28998      var isContaGiroEnabled = $inputEnablePaymentMethod.data('conta-giro');
28999      var tabCard = $('[data-js="tab-card"]');
29000      var tabBank = $('[data-js="tab-bank"]');
29001      var tabPix = $('[data-js="tab-pix"]');
29002      var tabNupay = $('[data-js="tab-nupay"]');
29003      var tabLivelo = $('[data-js="tab-livelo"]');
29004      var tabContaGiro = $('[data-js="tab-conta-giro"]');
29005      var nupayInfo = $('[data-js="nupay-info"]');
29006      var allTabs = tabCard.add(tabBank).add(tabPix).add(tabNupay).add(tabContaGiro);
29007      var termsContent = $('[data-js="terms-content"]');
29008      var paymentFooter = $('.payment-footer');
29009
29010      var clearActiveTabs = function clearActiveTabs() {
29011        allTabs.removeClass('is-selected');
29012        tabCard.removeClass('active');
29013        tabBank.removeClass('active');
29014        tabPix.removeClass('active');
29015        tabContaGiro.removeClass('active');
29016        nupayInfo.addClass('d-none');
29017      };
29018
29019      // total-pix-container só é exibido quando há desconto pix e a aba pix está ativa
29020      var togglePixSummary = function togglePixSummary(isPixTabActive) {
29021        var showPixSummary = _this48.hasPixDiscount && isPixTabActive;
29022        $('[data-js="convenience-fee-container"]').toggleClass('d-none', showPixSummary);
29023        $('[data-js="convenience-fee-pix-container"], [data-js="total-pix-container"]').toggleClass('d-none', !showPixSummary);
29024      };
29025
29026      var triggerCardForm = function triggerCardForm() {
29027        clearActiveTabs();
29028        togglePixSummary(false);
29029        _this48.calculateTotalValueWithCoupon();
29030        _this48.disableSubmitButton();
29031        _this48.resetConditionsCheckbox();
29032        _this48.showCheckConditions();
29033        _this48.removeMessageNoBankOrPixPayment();
29034        _this48.removeMessageNoCpf();
29035        tabCard.addClass('active').addClass('is-selected');
29036        _this48.cardForm.trigger('reset');
29037        _this48.cardForm.fadeIn();
29038        _this48.bankForm.hide();
29039        _this48.pixContent.hide();
29040        _this48.contaGiroForm.hide();
29041        _this48.createWalletForm.hide();
29042        $('[data-js="recurring-content"]').show();
29043        $('.form-container').show();
29044        $('[data-js="bank-form"]').removeClass('active');
29045        _this48.initPaymentColors();
29046        _this48.selectCustom.initSingle(_this48.selInstallments.parent());
29047        _this48.handlePaymentCardValid();
29048        termsContent.show();
29049        paymentFooter.show();
29050
29051        _this48.installmentsQnt = 1;
29052        _this48.syncSummaryThenUpdateCartView(_this48.totalValueWithCoupon);
29053      };
29054
29055      var triggerBankForm = function triggerBankForm() {
29056        clearActiveTabs();
29057        togglePixSummary(false);
29058        _this48.calculateTotalValueWithCoupon();
29059        _this48.disableSubmitButton();
29060        _this48.resetConditionsCheckbox();
29061        tabBank.addClass('active').addClass('is-selected');
29062        $('[data-js="recurring-content"]').hide();
29063        _this48.handleBankTransferSelected(showMessageNoBankOrPixPayment);
29064        _this48.handleTransferNoCpfSelected(isBankEnabled);
29065        _this48.cardForm.hide();
29066        _this48.pixContent.hide();
29067        _this48.contaGiroForm.hide();
29068        _this48.createWalletForm.hide();
29069        $('.form-container').show();
29070        _this48.initPaymentColors();
29071        _this48.removeMessageNoCpf();
29072        _this48.isFormPaymentBank();
29073        _this48.syncSummaryThenUpdateCartView(_this48.totalValueWithCoupon);
29074        $('.interest-amount').remove();
29075        termsContent.show();
29076        paymentFooter.show();
29077
29078        _this48.installmentsQnt = 1;
29079      };
29080
29081      var triggerPix = function triggerPix() {
29082        clearActiveTabs();
29083        togglePixSummary(true);
29084        _this48.calculateTotalValueWithCoupon();
29085        _this48.disableSubmitButton();
29086        _this48.resetConditionsCheckbox();
29087        tabPix.addClass('active').addClass('is-selected');
29088        _this48.handlePixNoCpfSelected(isPixEnabled);
29089        _this48.handlePixSelected(showMessageNoBankOrPixPayment);
29090        _this48.bankForm.hide();
29091        _this48.cardForm.hide();
29092        _this48.contaGiroForm.hide();
29093        _this48.createWalletForm.hide();
29094        $('.form-container').show();
29095        $('[data-js="bank-form"]').removeClass('active');
29096        _this48.initPaymentColors();
29097        $('[data-js="recurring-content"]').hide();
29098        _this48.handlePaymentPixValid();
29099        _this48.syncSummaryThenUpdateCartView(_this48.totalValueWithCoupon);
29100        $('.interest-amount').remove();
29101        _this48.handlePaymentPixValid();
29102        _this48.checkConditions.trigger('change');
29103        termsContent.show();
29104        paymentFooter.show();
29105
29106        _this48.installmentsQnt = 1;
29107      };
29108
29109      var triggerNupay = function triggerNupay() {
29110        clearActiveTabs();
29111        togglePixSummary(false);
29112        _this48.disableSubmitButton();
29113        _this48.resetConditionsCheckbox();
29114        _this48.showCheckConditions();
29115        _this48.removeMessageNoBankOrPixPayment();
29116        _this48.removeMessageNoCpf();
29117        tabNupay.addClass('is-selected');
29118        nupayInfo.removeClass('d-none');
29119        _this48.cardForm.hide();
29120        _this48.bankForm.hide();
29121        _this48.pixContent.hide();
29122        _this48.contaGiroForm.hide();
29123        _this48.createWalletForm.hide();
29124        $('[data-js="recurring-content"]').hide();
29125        $('.form-container').hide();
29126        $('[data-js="bank-form"]').removeClass('active');
29127        _this48.initPaymentColors();
29128        _this48.handlePaymentNupayValid();
29129        termsContent.show();
29130        paymentFooter.show();
29131        _this48.syncSummaryThenUpdateCartView(_this48.totalValueWithCoupon);
29132      };
29133
29134      var triggerLivelo = function triggerLivelo() {
29135        _this48.removeMessageNoBankOrPixPayment();
29136        _this48.disableSubmitButton();
29137        _this48.resetConditionsCheckbox();
29138        tabLivelo.addClass('active');
29139        tabPix.removeClass('active');
29140        tabBank.removeClass('active');
29141        tabCard.removeClass('active');
29142        _this48.liveloForm.show();
29143        _this48.bankForm.hide();
29144        _this48.cardForm.hide();
29145        _this48.pixContent.hide();
29146        _this48.initPaymentColors();
29147        $('[data-js="recurring-content"]').hide();
29148        _this48.getLiveloPoints();
29149        _this48.isFormPaymentLivelo();
29150        _this48.showCheckConditions();
29151      };
29152
29153      var triggerContaGiro = function triggerContaGiro() {
29154        clearActiveTabs();
29155        togglePixSummary(false);
29156        _this48.removeMessageNoBankOrPixPayment();
29157        _this48.removeMessageNoCpf();
29158        _this48.disableSubmitButton();
29159        _this48.resetConditionsCheckbox();
29160        $('[data-js="recurring-content"]').hide();
29161        _this48.showCheckConditions();
29162        _this48.handlePaymentPending();
29163        tabContaGiro.addClass('active').addClass('is-selected');
29164        _this48.initPaymentColors();
29165        _this48.bankForm.hide();
29166        _this48.cardForm.hide();
29167        _this48.pixContent.hide();
29168        $('.form-container').show();
29169        $('[data-js="bank-form"]').removeClass('active');
29170        _this48.handleWalletPixValid();
29171        _this48.isCheckBalanceTrue();
29172        _this48.installmentsQnt = 1;
29173        _this48.syncSummaryThenUpdateCartView(_this48.totalValueWithCoupon);
29174      };
29175
29176      if (isCardEnabled) tabCard.show();
29177
29178      if (isBankEnabled) tabBank.show();
29179
29180      if (isPixEnabled) tabPix.show();
29181
29182      if (isNupayEnabled) { tabNupay.show(); } else { tabNupay.hide(); } 
29183
29184      if (isContaGiroEnabled) tabContaGiro.show();
29185
29186      var isNegativeValue = null;
29187
29188      if (this.cartService != undefined && this.repricingV2) {
29189        isNegativeValue = (Math.sign(this.cartService._cart.balanceTotal) < 0) || this.cartService._cart.balanceTotal === 0;
29190      }
29191
29192      if ((this.isPaymentWhatsapp) || (autoSelect === "false" && (isCardEnabled && !this.cart._listOffer[0]._priceWithDiscountPix || this.repricingV2)) || isNegativeValue) {
29193        triggerCardForm();
29194      } else if (isPixEnabled && autoSelect === "true") {
29195        triggerPix();
29196      } else {
29197        triggerCardForm();
29198      }
29199
29200      tabCard.on('click', function (event) {
29201        triggerCardForm();
29202        _this48.scrollToPaymentStep(event, ['form[data-js="card-form"]']);
29203      });
29204      tabBank.on('click', function (event) {
29205        triggerBankForm();
29206        _this48.scrollToPaymentStep(event, ['[data-js="message-wrapper-no-bank-pix-payment"]', '[data-js="message-wrapper-cpf-invalid"]', '[data-form="bank-form-wrapper"]']);
29207      });
29208      tabPix.on('click', function (event) {
29209        triggerPix();
29210        _this48.scrollToPaymentStep(event, ['.pix-content-container', '[data-js="message-wrapper-no-bank-pix-payment"]', '[data-js="message-wrapper-cpf-invalid"]', '[data-form="pix-wrapper"]']);
29211      });
29212      tabNupay.on('click', function (event) {
29213        triggerNupay();
29214        _this48.scrollToPaymentStep(event, ['[data-js="nupay-info"]']);
29215      });
29216      tabContaGiro.on('click', function (event) {
29217        triggerContaGiro();
29218        _this48.scrollToPaymentStep(event, ['[data-js="createWallet-form"]', '[data-js="contaGiro-form"]', '[data-js="createWallet-wrapper"]', '[data-js="contaGiro-wrapper"]']);
29219      });
29220    }
29221  }, {
29222    key: 'isFormPaymentLivelo',
29223    value: function isFormPaymentLivelo() {
29224      var _this28 = this;
29225
29226      $('[data-js="insert-livelo-token"]').change(function () {
29227        var tokenField = $('[data-js="insert-livelo-token"]').val();
29228
29229        if ($('#conditions-check').is(':checked') && tokenField) {
29230          this.enableSubmitButton();
29231        }
29232      });
29233
29234      $('#conditions-check').on('click', function () {
29235        var tokenField = $('[data-js="insert-livelo-token"]').val();
29236
29237        if ($('#conditions-check').is(':checked') && tokenField) {
29238          _this28.enableSubmitButton();
29239        }
29240      });
29241
29242      $('[data-js="livelo-no-check-token"]').on('click', function () {
29243        $('[data-js="limit-livelo"]').removeClass('active');
29244        $('[data-js="generate-token-livelo"]').removeClass('active');
29245        $('[data-js="modal-overlay"]').removeClass('active');
29246      });
29247
29248      $('[data-js="modal-close-livelo-get-token"]').on('click', function () {
29249        $('[data-js="limit-livelo"]').removeClass('active');
29250        $('[data-js="generate-token-livelo"]').removeClass('active');
29251        $('[data-js="livelo-get-token"]').removeClass('active');
29252        $('[data-js="modal-overlay"]').removeClass('active');
29253      });
29254    }
29255  }, {
29256    key: 'getLiveloPoints',
29257    value: function getLiveloPoints() {
29258      var _this29 = this;
29259
29260      if ($('[data-js="button-apply-discount"]').hasClass("valid")) this.getLiveloPointsWithDiscount(); else {
29261        var body = { "W2iInsurance": this.insuranceCheck.is(':checked') };
29262
29263        var headers = {
29264          'Authorization': '' + SessionStorage.get('jca_token')
29265        };
29266
29267        if (!this.isConsultLiveloAPI) {
29268          HttpService.post('liveloPoints', body, headers).then(function (data) {
29269            var isAvailableLiveloPoints = data.result[0].paymentOptions.available;
29270            _this29.isConsultLiveloAPI = true;
29271            _this29.liveloPoints = data.result[0].paymentOptions.amount ? data.result[0].paymentOptions.amount : 0;
29272
29273            if (!isAvailableLiveloPoints) throw new Error();
29274
29275            _this29.hideLoadingLivelo();
29276            $('[data-js="no-limit-livelo"]').addClass('d-none');
29277            $('[data-js="limit-livelo"]').removeClass('d-none');
29278            $('[data-js="livelo-total-points"]').text(_this29.liveloPoints > 0 ? _this29.liveloPoints + ' pontos Livelo' : '');
29279          }).catch(function () {
29280            _this29.liveloNoPayment = true;
29281            _this29.isConsultLiveloAPI = true;
29282            _this29.hideLoadingLivelo();
29283            $('[data-js="livelo-total-points"]').text(_this29.liveloPoints > 0 ? _this29.liveloPoints + ' pontos Livelo' : '');
29284            $('[data-js="no-limit-livelo"]').removeClass('d-none');
29285            $('[data-js="limit-livelo"]').addClass('d-none');
29286          });
29287        }
29288      }
29289    }
29290  }, {
29291    key: 'getLiveloPointsWithDiscount',
29292    value: function getLiveloPointsWithDiscount() {
29293      var _this30 = this;
29294
29295      this.validateDiscount().then(function () {
29296        var body = { "W2iInsurance": _this30.insuranceCheck.is(':checked') };
29297
29298        var headers = {
29299          'Authorization': '' + SessionStorage.get('jca_token')
29300        };
29301
29302        HttpService.post('liveloPoints', body, headers).then(function (data) {
29303          var isAvailableLiveloPoints = data.result[0].paymentOptions.available;
29304          _this30.isConsultLiveloAPI = true;
29305          _this30.liveloPoints = data.result[0].paymentOptions.amount ? data.result[0].paymentOptions.amount : 0;
29306
29307          if (!isAvailableLiveloPoints) throw new Error();
29308
29309          _this30.hideLoadingLivelo();
29310          $('[data-js="no-limit-livelo"]').addClass('d-none');
29311          $('[data-js="limit-livelo"]').removeClass('d-none');
29312          $('[data-js="livelo-total-points"]').text(_this30.liveloPoints > 0 ? _this30.liveloPoints + ' pontos Livelo' : '');
29313        }).catch(function () {
29314          _this30.liveloNoPayment = true;
29315          _this30.isConsultLiveloAPI = true;
29316          _this30.hideLoadingLivelo();
29317          $('[data-js="livelo-total-points"]').text(_this30.liveloPoints > 0 ? _this30.liveloPoints + ' pontos Livelo' : '');
29318          $('[data-js="no-limit-livelo"]').removeClass('d-none');
29319          $('[data-js="limit-livelo"]').addClass('d-none');
29320        });
29321      });
29322    }
29323  }, {
29324    key: 'createPointsLivelo',
29325    value: function createPointsLivelo() {
29326      var _this6 = this;
29327      this.getNumberLivelo();
29328      var body = { "W2iInsurance": this.insuranceCheck.is(':checked') };
29329
29330      var headers = {
29331        'Authorization': '' + SessionStorage.get('jca_token')
29332      };
29333
29334      HttpService.post('createLiveloPoints', body, headers).then(function (data) {
29335        if (data.result.transactionAuthentication != null && data.result.transactionAuthentication.mobile != null &&
29336          data.result.transactionAuthentication.mobile.length > 0) {
29337          _this6.deviceIdLivelo = data.result.transactionAuthentication.mobile[0].id;
29338        }
29339
29340        if (data.result.transactionAuthentication != null && data.result.transactionAuthentication.phone != null &&
29341          data.result.transactionAuthentication.phone.length > 0) {
29342          _this6.phoneId = data.result.transactionAuthentication.phone[0].id;
29343        }
29344        //<<<<<<<<<<<<<<<<< AEM CUSTOM JS >>>>>>>>>>>>>>>>>>>>>
29345        $('[data-js="limit-livelo"]').removeClass('active');
29346        $('[data-js="livelo-get-token"]').find('.modal-overlay').removeClass('active');
29347        //<<<<<<<<<<<<<<<<< ------------- >>>>>>>>>>>>>>>>>>>>>
29348        $('[data-js="livelo-get-token"]').addClass('active');
29349      }).catch(function (err) {
29350        console.error(err);
29351      });
29352    }
29353  }, {
29354    key: 'handleTriggerGenereteTokenLivelo',
29355    value: function handleTriggerGenereteTokenLivelo() {
29356      var btnGenereteToken = $('[data-js="generate-token-livelo"]');
29357      btnGenereteToken.trigger('click');
29358    }
29359  }, {
29360    key: 'sendLiveloTokenSMS',
29361    value: function sendLiveloTokenSMS() {
29362      var _this8 = this;
29363
29364      var body = { "phoneId": _this8.phoneId };
29365
29366      var headers = {
29367        'Authorization': '' + SessionStorage.get('jca_token'),
29368        'Internal-Validation': 'SUCCESS'
29369      };
29370
29371      HttpService.post('sendLiveloSMS', body, headers).then(function (data) {
29372        $('[data-js="sms-livelo"]').off('change');
29373        $('[data-js="resend-livelo"]').removeClass('d-none');
29374        $('[data-js="insert-token-livelo"]').removeClass('d-none');
29375        $('[data-js="livelo-get-token"]').removeClass('active');
29376        $('[data-js="limit-livelo"]').css('display', 'none');
29377        $('[data-js="generate-token-livelo"]').removeClass('active');
29378        $('[data-js="modal-overlay"]').removeClass('active');
29379      }).catch(function (err) {
29380        $('[data-js="sms-livelo"]').off('change');
29381        $('[data-js="resend-sms-livelo"]').removeClass('d-none');
29382        console.error(err);
29383      });
29384    }
29385  }, {
29386    key: 'getNumberLivelo',
29387    value: function getNumberLivelo() {
29388      var passenger = SessionStorage.get('passenger');
29389      var _areaCode = passenger._areaCode,
29390        _phone = passenger._phone;
29391
29392      var phoneIncripted = _phone.slice(_phone.length - 2);
29393
29394      $('[data-js="phone-to-sms-livelo"]').text('(' + _areaCode + ') *****-**' + phoneIncripted);
29395    }
29396  }, {
29397    key: 'hideLoadingLivelo',
29398    value: function hideLoadingLivelo() {
29399      $('[data-js="loading-livelo"]').hide();
29400    }
29401  }, {
29402    key: 'hideLoadingLivelo',
29403    value: function hideLoadingLivelo() {
29404      $('[data-js="loading-livelo"]').hide();
29405    }
29406  }, {
29407    key: 'removeTabBankTransfer',
29408    value: function removeTabBankTransfer() {
29409      $('[data-js="tab-bank"]').hide();
29410    }
29411  }, {
29412    key: 'removeTabPix',
29413    value: function removeTabPix() {
29414      $('[data-js="tab-pix"]').hide();
29415    }
29416  }, {
29417    key: 'showMessageNoBankOrPixPayment',
29418    value: function showMessageNoBankOrPixPayment() {
29419      var $messageMinHourToBankOrPixPayment = $('[data-js="message-wrapper-no-bank-pix-payment"]');
29420
29421      $messageMinHourToBankOrPixPayment.removeClass('d-none');
29422    }
29423  }, {
29424    key: 'removeMessageNoBankOrPixPayment',
29425    value: function removeMessageNoBankOrPixPayment() {
29426      var $messageMinHourToBankOrPixPayment = $('[data-js="message-wrapper-no-bank-pix-payment"]');
29427
29428      $messageMinHourToBankOrPixPayment.addClass('d-none');
29429    }
29430  }, {
29431    key: 'removeMessageNoCpf',
29432    value: function removeMessageNoCpf() {
29433      var $messageCpfInvalid = $('[data-js="message-wrapper-cpf-invalid"]');
29434
29435      $messageCpfInvalid.addClass('d-none');
29436    }
29437  }, {
29438    key: 'showCheckConditions',
29439    value: function showCheckConditions() {
29440      this.checkConditions.closest('.checkbox-container').show();
29441    }
29442  }, {
29443    key: 'hideCheckConditions',
29444    value: function hideCheckConditions() {
29445      this.checkConditions.closest('.checkbox-container').hide();
29446    }
29447  }, {
29448    key: 'resetConditionsCheckbox',
29449    value: function resetConditionsCheckbox() {
29450      var isChecked = this.checkConditions.is(':checked');
29451
29452      if (isChecked) this.checkConditions.trigger('click');
29453    }
29454  }, {
29455    key: 'handleSetInstallmentsWithInterest',
29456    value: function handleSetInstallmentsWithInterest(data, totalwithDiscount, callback) {
29457      var _this49 = this;
29458
29459      var isSummaryPayload = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
29460
29461
29462      if (isSummaryPayload) {
29463        var total = isSummaryPayload ? data.valueParts.find(function (item) {
29464          return item.code == "Total";
29465        }).value.toFixed(2).replace(".", "") : getTotal();
29466
29467        if (data.valueParts.find(function (item) {
29468          return item.code == "VoucherDiscount";
29469        }).value > 0) {
29470          total = total - data.valueParts.find(function (item) {
29471            return item.code == "VoucherDiscount";
29472          }).value.toFixed(2).replace(".", "");
29473        }
29474
29475        this.selectCustom.eraseSelect(this.selInstallments);
29476        this.selInstallments.val(null);
29477        this.disableSubmitButton();
29478
29479        this.getInstallmentsApi(total).then(function (res) {
29480          var content = [];
29481
29482          _this49.installmentsResult = res.result;
29483          var totalWithInterest = res.result[res.result.length - 1].totalAmountWithInterest;
29484          $('option:gt(0)', _this49.selInstallments).remove();
29485          var numInstallments = _this49.getNumInstallments(totalWithInterest);
29486
29487          for (var i = 1; i <= numInstallments; i++) {
29488            var currValue = _this49.installmentsResult[i - 1].installmentAmount;
29489            var roundedValue = Math.round((currValue + 0.00001) * 100) / 100;
29490            var formatedValue = _this49.installmentsResult[i - 1].interestAmount > 0 ? i + 'x de R$' + roundedValue.toFixed(2).replace('.', ',') + ' - Com Juros' : i + 'x de R$' + roundedValue.toFixed(2).replace('.', ',');
29491
29492            content.push('<li class="installment-value" id="installment-' + i + '" data-value="' + roundedValue + '"> ' + formatedValue + ' </li>');
29493            var option = new Option(formatedValue, i);
29494            _this49.selInstallments.append(option);
29495          }
29496          _this49.selectCustom.initSingle(_this49.selInstallments.parent());
29497
29498          if (typeof callback === 'function') {
29499            callback();
29500          }
29501
29502          _this49.installmentsError = false;
29503
29504          return content;
29505        }).catch(function (err) {
29506          _this49.installmentsError = true;
29507          return _this49.renderInstallments();
29508        });
29509      } else {
29510        this.setInstallmentsWithInterest(null, totalwithDiscount, callback);
29511      }
29512    }
29513  }, {
29514    key: 'handleSetInstallmentsWithInterest',
29515    value: function handleSetInstallmentsWithInterest(data, totalwithDiscount, callback) {
29516      var _this49 = this;
29517
29518      var isSummaryPayload = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
29519
29520
29521      if (isSummaryPayload) {
29522        var total = isSummaryPayload ? data.valueParts.find(function (item) {
29523          return item.code == "Total";
29524        }).value.toFixed(2).replace(".", "") : getTotal();
29525
29526        if (data.valueParts.find(function (item) {
29527          return item.code == "VoucherDiscount";
29528        }).value > 0) {
29529          total = total - data.valueParts.find(function (item) {
29530            return item.code == "VoucherDiscount";
29531          }).value.toFixed(2).replace(".", "");
29532        }
29533
29534        this.selectCustom.eraseSelect(this.selInstallments);
29535        this.selInstallments.val(null);
29536        this.disableSubmitButton();
29537
29538        this.getInstallmentsApi(total).then(function (res) {
29539          var content = [];
29540
29541          _this49.installmentsResult = res.result;
29542          var totalWithInterest = res.result[res.result.length - 1].totalAmountWithInterest;
29543          $('option:gt(0)', _this49.selInstallments).remove();
29544          var numInstallments = _this49.getNumInstallments(totalWithInterest);
29545
29546          for (var i = 1; i <= numInstallments; i++) {
29547            var currValue = _this49.installmentsResult[i - 1].installmentAmount;
29548            var roundedValue = Math.round((currValue + 0.00001) * 100) / 100;
29549            var formatedValue = _this49.installmentsResult[i - 1].interestAmount > 0 ? i + 'x de R$' + roundedValue.toFixed(2).replace('.', ',') + ' - Com Juros' : i + 'x de R$' + roundedValue.toFixed(2).replace('.', ',');
29550
29551            content.push('<li class="installment-value" id="installment-' + i + '" data-value="' + roundedValue + '"> ' + formatedValue + ' </li>');
29552            var option = new Option(formatedValue, i);
29553            _this49.selInstallments.append(option);
29554          }
29555          _this49.selectCustom.initSingle(_this49.selInstallments.parent());
29556
29557          if (typeof callback === 'function') {
29558            callback();
29559          }
29560
29561          _this49.installmentsError = false;
29562
29563          return content;
29564        }).catch(function (err) {
29565          _this49.installmentsError = true;
29566          return _this49.renderInstallments();
29567        });
29568      } else {
29569        this.setInstallmentsWithInterest(null, totalwithDiscount, callback);
29570      }
29571    }
29572  }, {
29573    key: 'renderInstallmentsWithInterest',
29574    value: function renderInstallmentsWithInterest() {
29575      var _this46 = this;
29576
29577      var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
29578      var isSummaryPayload = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
29579
29580      if (this.loadInstallmentsAPI) {
29581        var callApi = true;
29582        $('[data-js="input-name-card"]').click(function (e) {
29583          if (callApi) _this46.handleSetInstallmentsWithInterest(null, function () {
29584            if (!_this46.installmentsError) {
29585              $('[data-js="btn-installment-select"]').change(function (e) {
29586                var numberInstallments = parseInt($(e.target).val());
29587
29588                var installmentObj = _this46.installmentsResult.find(function (installment) {
29589                  return installment.installmentNumber === numberInstallments;
29590                });
29591
29592                if (installmentObj) {
29593                  _this46.priceCart.text(Utils.formatPrice(installmentObj.totalAmountWithInterest));
29594                  $('[data-js="price-in-bottom-cart"]').text('R$ ' + Utils.formatPrice(installmentObj.totalAmountWithInterest));
29595
29596                  if (installmentObj.interestAmount > 0) {
29597                    if ($('.interest-amount')) $('.interest-amount').remove();
29598                    var interestAmount = '<p class="interest-amount"><span class="price">R$ ' + Utils.formatPrice(installmentObj.interestAmount) + ' de juros</span></p>';
29599                    $('.summary-item.with-resume-bottom-cart').append(interestAmount);
29600                  } else {
29601                    $('.interest-amount').remove();
29602                  }
29603                }
29604              });
29605            }
29606          }, isSummaryPayload, null);
29607          callApi = false;
29608        });
29609      }
29610    }
29611  }, {
29612    key: 'setInstallmentsWithInterest',
29613    value: function setInstallmentsWithInterest(data, totalwithDiscount, callback) {
29614      var _this51 = this;
29615
29616      var discountData = SessionStorage.get('discountData');
29617      discountData = discountData ? discountData.result.seats.transactions : null;
29618      var total = 0;
29619      if (data) total = data.result.token.voucherId ? totalwithDiscount : 0;else total = this.isPaymentWhatsapp ? this.totalSalePrice : this.repricingV2 ? this.cartService.balanceTotal : this.convenienceFee ? this.cartService.getTotal(this.convenienceFee) - (discountData ? this.cartService._cart._totalConvenienceFee - this.cartComponent.txPriceTotalConvenienceFee : 0) - Math.round((discountData ? this.cartService.totalDiscount + 0.00001 : 0) * 100) / 100 : this.cartService.total - Math.round((discountData ? this.cartService.totalDiscount + 0.00001 : 0) * 100) / 100;
29620
29621      var numInstallments = this.getNumInstallments(total);
29622
29623      if (this.cartComponent.totalOffDiscount) {
29624        total = this.cartService.cart._insurance.hired ? parseInt(this.cartService.cart._insurance.price.toFixed(2).replace(".", ""), 10) : 0;
29625      } else {
29626        // With the summary enabled, the total (already discounted by the coupon) is retrieved from the endpoint.
29627        var cartSummary = SessionStorage.get("cartSummary");
29628        if (this.useSummary && !data && cartSummary && Array.isArray(cartSummary.valueParts)) {
29629          var totalPart = cartSummary.valueParts.find(function (item) {
29630            return item.code === "Total";
29631          });
29632          total = parseInt((totalPart ? totalPart.value : 0).toFixed(2).replace(".", ""), 10);
29633        } else {
29634          total = parseInt(total.toFixed(2).replace(".", ""), 10);
29635        }
29636      }
29637
29638      this.selectCustom.eraseSelect(this.selInstallments);
29639      this.selInstallments.val(null);
29640      this.disableSubmitButton();
29641
29642      if (total > 0) {
29643        this.getInstallmentsApi(total).then(function (res) {
29644          var content = [];
29645
29646          _this51.installmentsResult = res.result;
29647          var totalWithInterest = res.result[res.result.length - 1].totalAmountWithInterest;
29648          $('option:gt(0)', _this51.selInstallments).remove();
29649          var numInstallments = _this51.getNumInstallments(totalWithInterest);
29650
29651          for (var i = 1; i <= numInstallments; i++) {
29652            var currValue = _this51.installmentsResult[i - 1].installmentAmount;
29653            var roundedValue = Math.round((currValue + 0.00001) * 100) / 100;
29654            var formatedValue = _this51.installmentsResult[i - 1].interestAmount > 0 ? i + 'x de R$' + roundedValue.toFixed(2).replace('.', ',') + ' - Com Juros' : i + 'x de R$' + roundedValue.toFixed(2).replace('.', ',');
29655
29656            content.push('<li class="installment-value" id="installment-' + i + '" data-value="' + roundedValue + '"> ' + formatedValue + ' </li>');
29657            var option = new Option(formatedValue, i);
29658            _this51.selInstallments.append(option);
29659          }
29660          _this51.selectCustom.initSingle(_this51.selInstallments.parent());
29661
29662          if (typeof callback === "function") callback();
29663
29664          _this51.installmentsError = false;
29665          return content;
29666        }).catch(function (err) {
29667          _this51.installmentsError = true;
29668          return _this51.renderInstallments();
29669        });
29670      } else {
29671        this.installmentsError = true;
29672        return this.renderInstallments();
29673      }
29674    }
29675  }, {
29676    key: 'getInstallmentsApi',
29677    value: function getInstallmentsApi(totalCart) {
29678      var headers = {
29679        'Authorization':  this.isPaymentWhatsapp ? this.wppToken : SessionStorage.get('jca_token')
29680      };
29681      var parameters = { Amount: totalCart };
29682
29683      return HttpService.get('installment?' + $.param(parameters), headers);
29684    }
29685  }, {
29686    key: 'handleWhatsappShopping',
29687    value: function handleWhatsappShopping() {
29688      var _this29 = this;
29689
29690      var token = this.whatsParams.get('token');
29691      var sessionSeatLock = this.whatsParams.get('sessionSeatLock');
29692
29693      this.getSaleApi(token, sessionSeatLock).then(function (res) {
29694
29695        // Verifica primeiro se a venda expirou
29696        if (res.result === 'Sale Expired' && res.success === false) {
29697          _this29.handleSuccessWpp(true);
29698          return;
29699        }
29700
29701        // Atualiza o sessionSeatLock
29702        SessionStorage.set(
29703          'sessionseatlock',
29704          res.result.sale.sessionSeatLock
29705        );
29706
29707        var infoData = res.result;
29708        _this29.saleResult = res.result;
29709
29710        var hasReturn = infoData.sale.transactions.some(function (passenger) {
29711          return passenger.going === false;
29712        });
29713
29714        // Informações da ida
29715        _this29.setGoingInformation(infoData, hasReturn);
29716
29717        // Informações da volta
29718        if (hasReturn) {
29719          $('.table-returning').removeClass('d-none');
29720          $('.overview-return').removeClass('d-none');
29721
29722          _this29.setReturnInformation(infoData);
29723        }
29724
29725        // Atualiza os valores do Summary
29726        _this29.getUpdatedPriceSummary();
29727
29728        // Aguarda o Summary terminar antes de montar o parcelamento
29729        if (_this29.useSummary && _this29._summaryPromise) {
29730
29731          return _this29._summaryPromise.then(function () {
29732
29733            return _this29.setInstallmentsWithInterest();
29734
29735          }, function () {
29736
29737            // Mantém o comportamento mesmo se o Summary retornar erro
29738            return _this29.setInstallmentsWithInterest();
29739
29740          });
29741        }
29742
29743        // Caso não utilize Summary
29744        return _this29.setInstallmentsWithInterest();
29745
29746      }).catch(function (err) {
29747
29748        console.log(err);
29749
29750        if (err.status === 504 || err.status === 500 || err.status === 0) {
29751          $('[data-js="alert-overlay"]').remove();
29752        } else if (err.status === 401) {
29753          _this29.handleSuccessWpp(true);
29754        } else {
29755          AlertConfirmation.showAEM(
29756            'data-js="whatsapp-payment-status-error"',
29757            false,
29758            true
29759          );
29760        }
29761
29762      });
29763    }
29764  }, {
29765    key: 'setGoingInformation',
29766    value: function setGoingInformation(infoData, hasReturn) {
29767      var _this32 = this;
29768
29769      var transactions = infoData.sale.transactions;
29770      this.wppPassengers = infoData.sale.passengers;
29771
29772      //setting trip details
29773      var goingTicket = transactions.find(function (passenger) {
29774        return passenger.going === true;
29775      });
29776      var isConnection = goingTicket.isConnection;
29777      var goingConnection = transactions.filter(function (passenger) {
29778        return passenger.going === true && passenger.isConnection === true;
29779      }).pop();
29780
29781      var date = new Date(goingTicket.seatResponse.service.departureDate);
29782      var options = { weekday: 'short', day: 'numeric', month: 'short' };
29783      date = date.toLocaleDateString('pt-BR', options);
29784      var dayWeek = date.replace(/\./g, '');
29785
29786      var departureDate = new Date(goingTicket.seatResponse.service.departureDate);
29787      var hourOptions = { hour: '2-digit', minute: '2-digit' };
29788      var departureTime = departureDate.toLocaleTimeString('pt-BR', hourOptions);
29789
29790      var arrivalDate = new Date(isConnection && goingConnection ? goingConnection.seatResponse.service.arrivalDate : goingTicket.seatResponse.service.arrivalDate);
29791      var arrivalTime = arrivalDate.toLocaleTimeString('pt-BR', hourOptions);
29792
29793      this.dateGoing.text(dayWeek.replace(/^\w/, dayWeek[0].toUpperCase()));
29794      this.origingGoing.text(goingTicket.seatResponse.origin.city);
29795      this.destinationGoing.text(isConnection && goingConnection ? goingConnection.seatResponse.destination.city : goingTicket.seatResponse.destination.city);
29796      this.departureGoing.text(departureTime);
29797      this.arrivalGoing.text(arrivalTime);
29798      this.classGoing.text(goingTicket.seatResponse.service.class);
29799
29800      //setting payment resume info
29801      var passengersQtd = this.wppPassengers.length;
29802      var convenienceFee = this.showConvenienceFee ? transactions.filter(function (transaction) {
29803        return transaction.going === true;
29804      }).reduce(function (total, transaction) {
29805        return total + parseFloat(transaction.seatResponse.service.convenienceFee);
29806      }, 0) : 0;
29807
29808      if (convenienceFee === 0) {
29809        this.convenienceValue.parent().parent().parent().remove();
29810      }
29811
29812      //setting passengers and seats
29813      var passengerSeats = {};
29814
29815      transactions.filter(function (transaction) {
29816        return transaction.going === true;
29817      }
29817).forEach(function (transaction) {
29818        _this32.wppPassengers.filter(function (passenger) {
29819          return passenger.seats.some(function (seat) {
29820            return seat.service === transaction.servico;
29821          });
29822        }).forEach(function (passenger) {
29823          var matchingSeat = passenger.seats.find(function (seat) {
29824            return seat.service === transaction.servico;
29825          });
29826          if (matchingSeat) {
29827            if (!passengerSeats[passenger.name]) {
29828              passengerSeats[passenger.name] = [];
29829            }
29830            if (!passengerSeats[passenger.name].some(function (seat) {
29831              return seat.service === transaction.servico;
29832            })) {
29833              passengerSeats[passenger.name].push(matchingSeat);
29834            }
29835          }
29836        });
29837      });
29838
29839      var goingPassengers = Object.entries(passengerSeats).map(function (_ref) {
29840        var _ref2 = _slicedToArray(_ref, 2),
29841          name = _ref2[0],
29842          seats = _ref2[1];
29843
29844        return {
29845          name: name,
29846          seats: seats.map(function (seat) {
29847            return seat.seat;
29848          })
29849        };
29850      });
29851
29852      goingPassengers.forEach(function (element) {
29853        var passengersGoing = '\n        <li>\n          <div class="container-cart-passenger">\n            <span class="name">' + element.name + '</span>\n            ' + element.seats.map(function (seat) {
29854          return '<span class="square-seat"><p class="icon-seat-number">' + seat + '</p></span>';
29855        }).join('') + '\n          </div>\n        </li>\n      ';
29856        $('[data-js="passengers-going"]').append(passengersGoing);
29857      });
29858
29859      var price = transactions.filter(function (passenger) {
29860        return passenger.going === true;
29861      }).reduce(function (total, passenger) {
29862        return total + parseFloat(passenger.preco.preco);
29863      }, 0);
29864      //var serviceValue = this.showServiceFee ? Utils.calculePercent(price, 20) : 0;
29865
29866      var soma = transactions.filter(function (passenger) {
29867        return passenger.going === true;
29868      }).reduce(function (acumulador, passenger) {
29869        var tarifa = parseFloat(passenger.preco.tarifa);
29870        var taxaEmbarque = parseFloat(passenger.preco.taxaEmbarque);
29871        var pedagio = parseFloat(passenger.preco.pedagio);
29872
29873        return acumulador + tarifa + taxaEmbarque + pedagio;
29874      }, 0);
29875
29876      var roundedValue = Math.round((soma + 0.00001) * 100) / 100;//Math.round((soma - serviceValue + 0.00001) * 100) / 100;
29877      var seatsPrice = roundedValue.toFixed(2).replace('.', ',');
29878
29879      this.totalVoucherValue = transactions.reduce(function (sum, transaction) {
29880        return sum + transaction.voucherValue;
29881      }, 0);
29882
29883      this.totalSalePrice += roundedValue + convenienceFee;// + serviceValue;
29884
29885      if (this.totalVoucherValue > 0 && !hasReturn) {
29886        this.totalSalePrice -= this.totalVoucherValue;
29887        $('[data-js="price-discount"]').text(Utils.formatPrice(this.totalVoucherValue));
29888        $('[data-js="discount"]').show();
29889      }
29890
29891      $('[data-js="subtotal-seats-container"]').addClass('d-none');
29892      $('[data-js="convenience-fee-pix-container"]').addClass('d-none');
29893      $('[data-js="price-in-bottom-cart-pix"]').addClass('d-none');
29894      $('.summary-item').find('.convenienceFee').addClass('d-none');
29895      $('.line-discount-pix').addClass('d-none');
29896      $('[data-js="total-currency"]').removeClass('d-none');
29897
29898      this.passengersNumber.text(passengersQtd + (passengersQtd > 1 ? ' Passageiros' : ' Passageiro'));
29899      this.seatsPrice.text(seatsPrice);
29900      //this.serviceValue.text(Utils.formatPrice(serviceValue));
29901      this.convenienceValue.text(convenienceFee.toFixed(2).replace('.', ','));
29902      this.priceCart.text(Utils.formatPrice(this.totalSalePrice));
29903    }
29904  }, {
29905    key: 'setReturnInformation',
29906    value: function setReturnInformation(infoData) {
29907      var _this33 = this;
29908
29909      var transactions = infoData.sale.transactions;
29910
29911      //setting trip details
29912      var returnTicket = transactions.find(function (passenger) {
29913        return passenger.going === false;
29914      });
29915      var isConnection = returnTicket.isConnection;
29916      var returnConnection = transactions.filter(function (passenger) {
29917        return passenger.going === false && passenger.isConnection === true;
29918      }).pop();
29919
29920      var date = new Date(returnTicket.seatResponse.service.departureDate);
29921      var options = { weekday: 'short', day: 'numeric', month: 'short' };
29922      date = date.toLocaleDateString('pt-BR', options);
29923      var dayWeek = date.replace(/\./g, '');
29924
29925      var departureDate = new Date(returnTicket.seatResponse.service.departureDate);
29926      var hourOptions = { hour: '2-digit', minute: '2-digit' };
29927      var departureTime = departureDate.toLocaleTimeString('pt-BR', hourOptions);
29928
29929      var arrivalDate = new Date(isConnection && returnConnection ? returnConnection.seatResponse.service.arrivalDate : returnTicket.seatResponse.service.arrivalDate);
29930      var arrivalTime = arrivalDate.toLocaleTimeString('pt-BR', hourOptions);
29931
29932      this.dateReturn.text(dayWeek.replace(/^\w/, dayWeek[0].toUpperCase()));
29933      this.origingReturn.text(returnTicket.seatResponse.origin.city);
29934      this.destinationReturn.text(isConnection && returnConnection ? returnConnection.seatResponse.destination.city : returnTicket.seatResponse.destination.city);
29935      this.departureReturn.text(departureTime);
29936      this.arrivalReturn.text(arrivalTime);
29937      this.classReturn.text(returnTicket.seatResponse.service.class);
29938
29939      //setting payment resume info
29940      var passengersQtd = this.wppPassengers.length;
29941      var convenienceFee = this.showConvenienceFee ? transactions.filter(function (transaction) {
29942        return transaction.going === false;
29943      }).reduce(function (total, transaction) {
29944        return total + parseFloat(transaction.seatResponse.service.convenienceFee);
29945      }, 0) : 0;
29946
29947      if (convenienceFee === 0) {
29948        this.convenienceValueReturn.parent().parent().parent().remove();
29949      }
29950
29951      //setting passengers and seats
29952      var passengerSeats = {};
29953
29954      transactions.filter(function (transaction) {
29955        return transaction.going === false;
29956      }
29956).forEach(function (transaction) {
29957        _this33.wppPassengers.filter(function (passenger) {
29958          return passenger.seats.some(function (seat) {
29959            return seat.service === transaction.servico;
29960          });
29961        }).forEach(function (passenger) {
29962          var matchingSeat = passenger.seats.find(function (seat) {
29963            return seat.service === transaction.servico;
29964          });
29965          if (matchingSeat) {
29966            if (!passengerSeats[passenger.name]) {
29967              passengerSeats[passenger.name] = [];
29968            }
29969            if (!passengerSeats[passenger.name].some(function (seat) {
29970              return seat.service === transaction.servico;
29971            })) {
29972              passengerSeats[passenger.name].push(matchingSeat);
29973            }
29974          }
29975        });
29976      });
29977
29978      var returnPassengers = Object.entries(passengerSeats).map(function (_ref3) {
29979        var _ref4 = _slicedToArray(_ref3, 2),
29980          name = _ref4[0],
29981          seats = _ref4[1];
29982
29983        return {
29984          name: name,
29985          seats: seats.map(function (seat) {
29986            return seat.seat;
29987          })
29988        };
29989      });
29990
29991      returnPassengers.forEach(function (element) {
29992        var passengersReturn = '\n        <li>\n          <div class="container-cart-passenger">\n            <span class="name">' + element.name + '</span>\n            ' + element.seats.map(function (seat) {
29993          return '<span class="square-seat"><p class="icon-seat-number">' + seat + '</p></span>';
29994        }).join('') + '\n          </div>\n        </li>\n      ';
29995        $('[data-js="passengers-return"]').append(passengersReturn);
29996      });
29997
29998      var price = transactions.filter(function (passenger) {
29999        return passenger.going === false;
30000      }).reduce(function (total, passenger) {
30001        return total + parseFloat(passenger.preco.preco);
30002      }, 0);
30003      //var serviceValue = this.showServiceFee ? Utils.calculePercent(price, 20) : 0;
30004
30005      var soma = transactions.filter(function (passenger) {
30006        return passenger.going === false;
30007      }).reduce(function (acumulador, passenger) {
30008        var tarifa = parseFloat(passenger.preco.tarifa);
30009        var taxaEmbarque = parseFloat(passenger.preco.taxaEmbarque);
30010        var pedagio = parseFloat(passenger.preco.pedagio);
30011
30012        return acumulador + tarifa + taxaEmbarque + pedagio;
30013      }, 0);
30014
30015      var roundedValue = Math.round((soma + 0.00001) * 100) / 100;//Math.round((soma - serviceValue + 0.00001) * 100) / 100;
30016      var seatsPrice = roundedValue.toFixed(2).replace('.', ',');
30017
30018      this.totalSalePrice += roundedValue + convenienceFee;// + serviceValue;
30019
30020      if (this.totalVoucherValue > 0) {
30021        this.totalSalePrice -= this.totalVoucherValue;
30022        $('[data-js="price-discount"]').text(Utils.formatPrice(this.totalVoucherValue));
30023        $('[data-js="discount"]').show();
30024      }
30025
30026      this.passengersNumberReturn.text(passengersQtd + (passengersQtd > 1 ? ' Passageiros' : ' Passageiro'));
30027      this.seatsPriceReturn.text(seatsPrice);
30028      //this.serviceValueReturn.text(Utils.formatPrice(serviceValue));
30029      this.convenienceValueReturn.text(convenienceFee.toFixed(2).replace('.', ','));
30030      this.priceCart.text(Utils.formatPrice(this.totalSalePrice));
30031    }
30032  }, {
30033    key: 'handleSuccessWpp',
30034    value: function handleSuccessWpp(expiredSession) {
30035      $('.payment-whatsapp-page').remove();
30036      expiredSession ? AlertConfirmation.showAEM('data-js="whatsapp-payment-expired-sale"', false, false, true) : AlertConfirmation.showAEM('data-js="whatsapp-payment-success-alert"', false, false, true);
30037    }
30038  }, {
30039    key: 'getSaleApi',
30040    value: function getSaleApi(token, sessionSeatLock) {
30041      var headers = {
30042        'Authorization': token,
30043        'sessionseatlock': sessionSeatLock
30044      };
30045
30046      return HttpService.get('getSale', headers);
30047    }
30048  }, {
30049    key: 'applyMsgErrorToAlert',
30050    value: function applyMsgErrorToAlert(msg) {
30051      var targetMessage = $('[data-js="return-error-text-target"]');
30052      if ($(targetMessage).find('.cmp-text').length > 0) {
30053        $(targetMessage).find('.cmp-text').text(msg);
30054      } else {
30055        $(targetMessage).html(msg);
30056      }
30057      OverlayService.show();
30058    }
30059  }, {
30060    key: 'applySalesforceMessageToAlert',
30061    value: function applySalesforceMessageToAlert(msg) {
30062      var targetMessage = $('[data-js="salesforce-captured-error-target"]');
30063      if ($(targetMessage).find('.cmp-text').length > 0) {
30064        $(targetMessage).find('.cmp-text').text(msg);
30065      } else {
30066        $(targetMessage).html(msg);
30067      }
30068      OverlayService.show();
30069    }
30070  }], [{
30071    key: 'getInstance',
30072    value: function getInstance($, cartComponentRef) {
30073      var useSummary = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
30074
30075      if (!cartComponentRef) {
30076        return this.instance;
30077      }
30078
30079      if (!this.instance) {
30080        this.instance = new PaymentController($, cartComponentRef, useSummary);
30081      }
30082
30083      return this.instance;
30084    }
30085  }]);
30086
30087  return PaymentController;
30088}();
30089
30090/**
30091 *
30092 * PaymentController
30093 *
30094 * FIM
30095 */
30096'use strict';
30097
30098var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
30099
30100function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30101
30102var PinCodeRecoveryController = function () {
30103  function PinCodeRecoveryController($) {
30104    _classCallCheck(this, PinCodeRecoveryController);
30105
30106    this.emailInput = $('[data-js="input-pin-recovery"]');
30107    this.resetButton = $('[data-js="button-pin-recovery"]');
30108    this.deviceFingerprint = $("#device-fingerprint").val();
30109    this.errorMessageContainer = $('[data-js="pin-code-recovery-error-message"]');
30110    this.errorMessageCodeContainer = $('[data-js="code-verify-email-error-message"]');
30111    this.codeVerifyEmail = $('[data-js="verify-email-container"]');
30112    this.pinCodeRecovery = $('[data-js="pin-code-recovery-section"]');
30113    this.codeInput = $('[data-js="input-code"]');
30114    this.verifyButton = $('[data-js="button-code-verify"]');
30115    this.codeErrorMessageContainer = $('[data-js="code-verify-email-error-message"]');
30116    this.backButton = $('[data-js="login-back"]');
30117    this.emailRecoveryBack = $('[data-js="email-recovery-back"]');
30118    this.resendCodeLink = $('[data-js="resend-verification-code"]');
30119    this.verificationCode = null;
30120    this.init();
30121  }
30122
30123  _createClass(PinCodeRecoveryController, [{
30124    key: 'init',
30125    value: function init() {
30126      var _this = this;
30127
30128      this.emailInput.on('change', function () {
30129        return _this.checkBriteverifyEmail();
30130      });
30131      this.emailInput.on('input', function () {
30132        return _this.toggleResetButton();
30133      });
30134      this.resetButton.on('click', function () {
30135        return _this.resetPin();
30136      });
30137      this.resetButton.prop('disabled', true);
30138
30139      this.codeInput.on('input', function () {
30140        return _this.enableVerifyButton();
30141      });
30142      this.verifyButton.on('click', function () {
30143        return _this.verifyCode();
30144      });
30145      this.verifyButton.prop('disabled', true);
30146
30147      this.backButton.on('click', function () {
30148        return _this.goBackToLogin();
30149      });
30150      this.emailRecoveryBack.on('click', function () {
30151        return _this.goBackToLogin();
30152      });
30153      this.resendCodeLink.on('click', function () {
30154        return _this.resetPin();
30155      });
30156      //Utils.checkWalletGroup();
30157    }
30158  }, {
30159    key: 'goBackToLogin',
30160    value: function goBackToLogin() {
30161      $(location).attr("href", $('#walletLoginPagePath').val());
30162    }
30163  }, {
30164    key: 'goBackToRecovery',
30165    value: function goBackToRecovery() {
30166      this.codeVerifyEmail.addClass('d-none');
30167      this.pinCodeRecovery.removeClass('d-none');
30168    }
30169  }, {
30170    key: 'toggleResetButton',
30171    value: function toggleResetButton() {
30172      var email = this.emailInput.val();
30173      var isValidEmail = this.validateEmail(email);
30174      this.resetButton.prop('disabled', !isValidEmail);
30175    }
30176  }, {
30177    key: 'enableVerifyButton',
30178    value: function enableVerifyButton() {
30179      this.verifyButton.prop('disabled', false);
30180    }
30181  }, {
30182    key: 'validateEmail',
30183    value: function validateEmail(email) {
30184      var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
30185      return emailPattern.test(email);
30186    }
30187  }, {
30188    key: 'resetPin',
30189    value: function resetPin() {
30190      var _this2 = this;
30191
30192      var email = this.emailInput.val();
30193      if (!email) {
30194        this.displayErrorMessage($('[data-js="msg-pin-recovery"]').attr('pin-msg-insert-valid-email'));
30195        return;
30196      }
30197
30198      var payload = this.getResetPinPayload(email);
30199      var headers = this.getAuthHeaders();
30200
30201      LoaderService.show();
30202
30203      HttpService.post("resetPin", payload, headers).then(function (data) {
30204        LoaderService.hide();
30205        Alert.show($('[data-js="msg-pin-recovery"]').attr('pin-msg-send-email-recovery'));
30206        _this2.verificationCode = data.message;
30207        _this2.codeVerifyEmail.removeClass('d-none');
30208        _this2.pinCodeRecovery.addClass('d-none');
30209      }).catch(function (error) {
30210        LoaderService.hide();
30211        _this2.handleErrorMessage(error);
30212      });
30213    }
30214  }, {
30215    key: 'checkBriteverifyEmail',
30216    value: function checkBriteverifyEmail() {
30217      var _this3 = this;
30218
30219      var email = this.emailInput.val();
30220      if (!this.validateEmail(email)) {
30221        this.displayErrorMessage($('[data-js="msg-pin-recovery"]').attr('pin-add-email-valid'));
30222        return;
30223      } else {
30224        this.hideErrorMessage();
30225
30226        var body = { email: email };
30227
30228        HttpService.post("briteEmailValidate", body).then(function (data) {
30229          var emailAttr = data.email;
30230          if (emailAttr.status !== "valid") {
30231            _this3.displayErrorMessage($('[data-js="msg-pin-recovery"]').attr('pin-email-provided-valid'));
30232          }
30233        }).catch(function (err) {
30234          console.log(err);
30235          _this3.displayErrorMessage($('[data-js="msg-pin-recovery"]').attr('pin-error-validate-email'));
30236        });
30237      }
30238    }
30239  }, {
30240    key: 'verifyCode',
30241    value: function verifyCode() {
30242      var _this4 = this;
30243
30244      var enteredCode = this.codeInput.val();
30245      var headers = this.getAuthHeaders();
30246
30247      var payload = {
30248        deviceFingerprint: $("#device-fingerprint").val(),
30249        resetCode: enteredCode
30250      };
30251
30252      LoaderService.show();
30253
30254      HttpService.post('validateCode', payload, headers).then(function (data) {
30255        SessionStorage.set('resetCode', enteredCode);
30256        $(location).attr("href", $('#walletPinPagePath').val());
30257      }).catch(function (error) {
30258        LoaderService.hide();
30259        _this4.handleErrorMessage(error, true);
30260      });
30261    }
30262  }, {
30263    key: 'getResetPinPayload',
30264    value: function getResetPinPayload(email) {
30265      return {
30266        email: email,
30267        deviceFingerPrint: $("#device-fingerprint").val()
30268      };
30269    }
30270  }, {
30271    key: 'getAuthHeaders',
30272    value: function getAuthHeaders() {
30273      var token = this.getToken();
30274      return {
30275        Authorization: token ? token : ''
30276      };
30277    }
30278  }, {
30279    key: 'getToken',
30280    value: function getToken() {
30281      var tokenFromStorage = SessionStorage.get("jca_token");
30282      if (tokenFromStorage) {
30283        return tokenFromStorage;
30284      }
30285
30286      var tokenFromUrl = new URLSearchParams(window.location.search).get('jca_token');
30287      return tokenFromUrl ? tokenFromUrl.replace(/^"|"$/g, '') : null;
30288    }
30289  }, {
30290    key: 'handleErrorMessage',
30291    value: function handleErrorMessage(error) {
30292      var isCodeError = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
30293
30294      var message = void 0;
30295      if (error.responseJSON && error.responseJSON.Message) {
30296        message = error.responseJSON.Message;
30297      } else {
30298        message = isCodeError ? i18n('error_code_verification') : i18n('error_recovery_pin');
30299      }
30300      this.displayErrorMessage(message, isCodeError);
30301    }
30302  }, {
30303    key: 'displayErrorMessage',
30304    value: function displayErrorMessage(message) {
30305      var isCodeError = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
30306
30307      var container = isCodeError ? this.errorMessageCodeContainer : this.errorMessageContainer;
30308      container.find('label.normal').text(message);
30309      container.addClass('d-flex');
30310    }
30311  }, {
30312    key: 'hideErrorMessage',
30313    value: function hideErrorMessage() {
30314      this.errorMessageContainer.removeClass('d-flex');
30315      this.errorMessageContainer.find('label.normal').text('');
30316    }
30317  }, {
30318    key: 'showSuccessMessage',
30319    value: function showSuccessMessage(message) {
30320      this.errorMessageContainer.find('label.normal').text(message);
30321      this.errorMessageContainer.addClass('d-flex');
30322      this.errorMessageContainer.removeClass('error');
30323    }
30324  }]);
30325
30326  return PinCodeRecoveryController;
30327}();
30328'use strict';
30329
30330var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
30331
30332function _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); } }
30333
30334function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30335
30336/**
30337 *
30338 * PromoRoutesController
30339 *
30340 * INICIO
30341 */
30342var PromoRoutesController = function () {
30343  function PromoRoutesController($) {
30344    _classCallCheck(this, PromoRoutesController);
30345
30346    this.origin = $('[data-js="origin"]');
30347    this.destination = $('[data-js="destination"]');
30348    this.select = $('[data-js="input-period-type"]');
30349    this.promoRoutes = $('[datajs="promo-routes"]');
30350    this.routes = [];
30351    this.classCompany = [];
30352    this.dynamicOffers = [];
30353    this.logoMap = {};
30354    this.init();
30355  }
30356
30357  _createClass(PromoRoutesController, [{
30358    key: 'init',
30359    value: function init() {
30360      var _this = this;
30361
30362      if ((!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false')) {
30363        this.loadCompanyData(function () {
30364          _this.getPromoRoutes();
30365          _this.select.on("change", function (event) {
30366            return _this.handleSelectChange(event);
30367          });
30368        });
30369      } else {
30370        this.showGenericRouteOnScreen();
30371      }
30372    }
30373  }, {
30374    key: 'loadCompanyData',
30375    value: function loadCompanyData(callback) {
30376      var _this2 = this;
30377
30378      InternalAPIService.getLogoMap(function (logoMap) {
30379        _this2.logoMap = logoMap;
30380        callback();
30381      });
30382    }
30383  }, {
30384    key: 'handleSelectChange',
30385    value: function handleSelectChange(event) {
30386      var currentSelect = $(event.target);
30387      var promoRoutesContainer = currentSelect.closest('[datajs="promo-routes"]');
30388      this.showRoutesOnScreen(this.routes[0].routes, $(promoRoutesContainer));
30389    }
30390  }, {
30391    key: 'showGenericRouteOnScreen',
30392    value: function showGenericRouteOnScreen() {
30393      var _this3 = this;
30394
30395      var route = {
30396        companyId: 7,
30397        company: "VIACAO COMETA S A",
30398        departureDate: "2025-08-07T16:00:00",
30399        arrivalDate: "2025-08-07T17:30:00",
30400        class: "Executivo",
30401        duration: {
30402          hours: 1,
30403          minutes: 30,
30404          seconds: 0
30405        },
30406        origin: "SAO PAULO (TIETE) - SP",
30407        destination: "CAMPINAS (RODOVIARIA) - SP",
30408        freeSeats: 46,
30409        price: 1.00
30410      };
30411
30412      this.routes = [route];
30413      this.promoRoutes.each(function (_, promoRouteContainer) {
30414        return _this3.showRoutesOnScreen(_this3.routes, $(promoRouteContainer));
30415      });
30416    }
30417  }, {
30418    key: 'getPromoRoutes',
30419    value: function getPromoRoutes() {
30420      var _this4 = this;
30421
30422      var origins = this.origin.map(function (_, el) {
30423        return parseInt($(el).val());
30424      });
30425      var destinations = this.destination.map(function (_, el) {
30426        return parseInt($(el).val());
30427      });
30428      this.getClass();
30429
30430      var promises = origins.map(function (index, origin) {
30431        var destination = destinations[index];
30432        var body = { origin: origin, destination: destination };
30433
30434        return HttpService.post("getDynamicServiceOffer", body).then(function (data) {
30435          if (!data.success) throw new Error();
30436          _this4.handleGetPromoRoutesSuccess(index, origin, destination, data.result);
30437          _this4.dynamicOffers = data.result;
30438          return data.result;
30439        });
30440      });
30441
30442      return Promise.all(promises).catch(function () {
30443        return _this4.promoRoutes.addClass('d-none');
30444      });
30445    }
30446  }, {
30447    key: 'getClass',
30448    value: function getClass() {
30449      var _this5 = this;
30450      var siteName = Utils.getSiteNameForClasses();
30451      var contentClassesUrl = '/content/jca/' + siteName + '/jcr:content.classes.json';
30452
30453      $.ajax({
30454        url: contentClassesUrl,
30455        contentType: 'json',
30456        type: 'GET',
30457        success: function success(data) {
30458          _this5.classCompany = data.result;
30459        },
30460        error: function error(textStatus, errorThrown) {
30461          console.log(textStatus, errorThrown);
30462          callback(errorThrown, null);
30463        }
30464      });
30465    }
30466  }, {
30467    key: 'handleGetPromoRoutesSuccess',
30468    value: function handleGetPromoRoutesSuccess(index, origin, destination, routes) {
30469      var route = [].concat(_toConsumableArray(this.routes), [{
30470        origin: origin.toString(),
30471        destination: destination.toString(),
30472        routes: routes
30473      }]);
30474      this.routes = route;
30475      this.originId = origin;
30476      this.destinationId = destination;
30477      this.showRoutesOnScreen(routes, $(this.promoRoutes[index]));
30478    }
30479  }, {
30480    key: 'sortRoutes',
30481    value: function sortRoutes(routes, select) {
30482      if (!routes) {
30483        var header = select.closest(".offer-header");
30484        var origin = header.find('[data-js="origin"]').val();
30485        var destination = header.find('[data-js="destination"]').val();
30486
30487        var filteredRoute = this.routes.filter(function (route) {
30488          return route.origin === origin;
30489        }).find(function (route) {
30490          return route.destination === destination;
30491        });
30492
30493        routes = filteredRoute ? filteredRoute.routes : [];
30494      }
30495
30496      var currentValue = select.val();
30497      var sortedRoutes = void 0;
30498
30499      switch (currentValue) {
30500        case "date":
30501          sortedRoutes = routes.sort(function (a, b) {
30502            return new Date(a.departureDate).getTime() - new Date(b.departureDate).getTime();
30503          });
30504          break;
30505        case "price":
30506          sortedRoutes = routes.sort(function (a, b) {
30507            return a.price - b.price;
30508          });
30509          break;
30510      }
30511      return sortedRoutes;
30512    }
30513  }, {
30514    key: 'getBestPriceRoutes',
30515    value: function getBestPriceRoutes() {
30516      var sortedRoutes = [].concat(_toConsumableArray(this.routes)).sort(function (a, b) {
30517        return a.price - b.price;
30518      });
30519      var bestPrice = sortedRoutes[0].price;
30520      return bestPrice;
30521    }
30522  }, {
30523    key: 'formatDate',
30524    value: function formatDate(date) {
30525      var dateFormatted = new Date(date);
30526      var day = String(dateFormatted.getDate()).padStart(2, '0');
30527      var month = String(dateFormatted.getMonth() + 1).padStart(2, '0');
30528      var year = dateFormatted.getFullYear();
30529
30530      return '' + day + month + year;
30531    }
30532  }, {
30533    key: 'getRouteUrl',
30534    value: function getRouteUrl(offer) {
30535      var url = $('#searchResultPath').val() + '?';
30536      var searchParams = '';
30537
30538      var params = {
30539        data_ida: this.formatDate(offer.departureDate),
30540        origem_id: this.originId,
30541        destino_id: this.destinationId,
30542        num_psgr: 1,
30543        num_chda: 0,
30544        num_chds: 0,
30545        deep: true
30546      };
30547
30548      for (var key in params) {
30549        if (key.toString() === 'deep') {
30550          searchParams += key + '=' + params[key];
30551        } else {
30552          searchParams += key + '=' + params[key] + '&';
30553        }
30554      }
30555
30556      return url + searchParams;
30557    }
30558  }, {
30559    key: 'formatHour',
30560    value: function formatHour(date) {
30561      var dateFormatted = new Date(date);
30562      return dateFormatted.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
30563    }
30564  }, {
30565    key: 'showRoutesOnScreen',
30566    value: function showRoutesOnScreen(routes, promoRoutesContainer) {
30567      var _this6 = this;
30568
30569      var operatorBy = $('[data-js="operator-by"]').val();
30570      var freeSeat = $('[data-js="free-seat"]').val();
30571      var freeSeats = $('[data-js="free-seats"]').val();
30572      var titleOffer = $('[data-js="title-offer"]').val();
30573
30574      var cardsContainer = promoRoutesContainer.find('.promo-routes-cards');
30575      var template = $("#offer-card-template").html();
30576      var select = promoRoutesContainer.find('[data-js="input-period-type"]');
30577
30578      if (!routes || !routes.length) {
30579        promoRoutesContainer.addClass('d-none');
30580        return;
30581      }
30582
30583      promoRoutesContainer.removeClass('d-none');
30584
30585      var sortedRoutes = this.sortRoutes(routes, select);
30586      var bestPrice = this.getBestPriceRoutes(sortedRoutes);
30587      var defaultImage = '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/offer-card.png';
30588
30589      cardsContainer.empty();
30590
30591      if(sortedRoutes.length > 0) {
30592        promoRoutesContainer.find("[data-js='title-h2']").text(titleOffer.replace("#origem", sortedRoutes[0].origin).replace("#destino", sortedRoutes[0].destination));
30593      }
30594
30595      sortedRoutes.forEach(function (offer, index) {
30596        var cardContent = $("<div class='card-content'></div>");
30597        var card = $(template);
30598        $(card).find(".offer-card-container").removeClass('d-none');
30599        $(card).find(".operator").text(operatorBy + ' '  + offer.company);
30600        $(card).find(".departure-info").find(".time").text(_this6.formatHour(offer.departureDate));
30601        $(card).find(".departure-info").find(".location").text(offer.origin);
30602        $(card).find(".arrival-info").find(".time").text(_this6.formatHour(offer.arrivalDate));
30603        $(card).find(".arrival-info").find(".location").text(offer.destination);
30604        $(card).find(".tripTime").text(offer.duration.hours + 'h ' + offer.duration.minutes + 'min');
30605        $(card).find(".price").text('R$ ' + offer.price.toFixed(2));
30606        $(card).find(".classe").text(offer.class);
30607        $(card).find(".available-seats").text(offer.freeSeats > 1 ? offer.freeSeats + ' ' + freeSeats : offer.freeSeats + ' ' + freeSeat);
30608
30609        $(card).find(".buy-button").attr("href", function () {
30610          if ((!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false' )) {
30611            return _this6.getRouteUrl(offer);
30612          }
30613        });
30614
30615        offer.price === bestPrice && $(card).find(".price-tag").removeClass('d-none');
30616
30617        // Find the matching company logo
30618        var company = _this6.logoMap[offer.company ? offer.company.toUpperCase() : ''];
30619        if (company && !company.companyLogo.includes('undefined')) {
30620          $(card).find(".offer-image").attr("src", company.companyLogo);
30621        } else{
30622          $(card).find(".offer-image").attr("src", defaultImage);
30623        }
30624
30625        cardContent.append(card);
30626        cardsContainer.append(cardContent);
30627      });
30628    }
30629  }]);
30630
30631  return PromoRoutesController;
30632}();
30633/**
30634 *
30635 * PromoRoutesController
30636 *
30637 * FIM
30638 */
30639'use strict';
30640
30641var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
30642
30643function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30644
30645/**
30646 * INICIO
30647 * LOGICA TELA RESULTADO DE BUSCA
30648 *
30649 */
30650
30651var PurchaseInfoModal = function () {
30652  function PurchaseInfoModal($) {
30653    _classCallCheck(this, PurchaseInfoModal);
30654
30655    this.purchaseInfoButton = $('[data-js="shop-info-button"]');
30656    this.purchaseInfoModal = $('[data-js="purchase-info-modal"]');
30657    this.closeButton = $('[data-js="purchase-info-close-button"]');
30658
30659    this.init();
30660  }
30661
30662  _createClass(PurchaseInfoModal, [{
30663    key: 'init',
30664    value: function init() {
30665      this.handleEvents();
30666    }
30667  }, {
30668    key: 'open',
30669    value: function open() {
30670      this.purchaseInfoModal.addClass('active');
30671    }
30672  }, {
30673    key: 'close',
30674    value: function close() {
30675      this.purchaseInfoModal.removeClass('active');
30676    }
30677  }, {
30678    key: 'handleEvents',
30679    value: function handleEvents() {
30680      var _this = this;
30681
30682      this.purchaseInfoButton.on('click', function () {
30683        return _this.open();
30684      });
30685      this.closeButton.on('click', function () {
30686        return _this.close();
30687      });
30688      this.closeButton.on('focusout', function () {
30689        return _this.close();
30690      });
30691    }
30692  }]);
30693
30694  return PurchaseInfoModal;
30695}();
30696'use strict';
30697
30698var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
30699
30700function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30701
30702var PromoCardSectionController = function () {
30703  function PromoCardSectionController($) {
30704    _classCallCheck(this, PromoCardSectionController);
30705    this.init();
30706  }
30707
30708  _createClass(PromoCardSectionController, [{
30709    key: 'init',
30710    value: function init() {
30711      var promoCards = $('.promo-card.aem-GridColumn.aem-GridColumn--default--12 > .promo-card');
30712      if (promoCards.length > 0) {
30713        this.pushViewOfferCarouselEvent();
30714
30715        var self = this;
30716        $('.promo-card-btn').on('click', function () {
30717          var card = $(this).closest('.promo-card');
30718          var visibleCards = promoCards.filter(':visible');
30719          var index = visibleCards.index(card);
30720          self.pushSelectOfferEvent(index);
30721        });
30722      }
30723    }
30724  }, {
30725    key: 'extractState',
30726    value: function extractState(location) {
30727      var match = location ? location.match(/- (\w{2})$/) : null;
30728      return match ? match[1] : null;
30729    }
30730  }, {
30731    key: 'getGeoLocationData',
30732    value: function getGeoLocationData(callback) {
30733      var serviceOrigin = SessionStorage.get('serviceOrigin');
30734      if (!serviceOrigin) {
30735        callback(null);
30736        return;
30737      }
30738
30739      var nearbyLocation = serviceOrigin.nearbyLocations && serviceOrigin.nearbyLocations[0];
30740      if (!nearbyLocation) {
30741        callback({
30742          latitude: null,
30743          longitude: null,
30744          city: null,
30745          region: null,
30746          country: null
30747        });
30748        return;
30749      }
30750
30751      var displayName = nearbyLocation.displayName || null;
30752      var city = displayName ? displayName.split(' - ')[0] : nearbyLocation.name ? nearbyLocation.name : null;
30753      var region = displayName ? this.extractState(displayName) : nearbyLocation.state ? nearbyLocation.state  : null;
30754
30755      Utils.getUserLocation(function (latitude, longitude) {
30756        var geoLocation = {
30757          latitude: latitude || null,
30758          longitude: longitude || null,
30759          city: city,
30760          region: region,
30761          country: 'Brasil'
30762        };
30763        callback(geoLocation);
30764      }, function (error) {
30765        console.error('Erro ao obter geolocalização:', error);
30766        callback({
30767          latitude: null,
30768          longitude: null,
30769          city: null,
30770          region: null,
30771          country: null
30772        });
30773      });
30774    }
30775  }, {
30776    key: 'pushViewOfferCarouselEvent',
30777    value: function pushViewOfferCarouselEvent() {
30778      var offers = [];
30779      var self = this;
30780
30781      $('.promo-card.aem-GridColumn.aem-GridColumn--default--12 > .promo-card').each(function (index) {
30782        var card = $(this);
30783        var departureText = card.find('.promo-card-route .departure p').text().trim() || null;
30784        var arrivalText = card.find('.promo-card-route .arrival p').text().trim() || null;
30785        var offerName = departureText && arrivalText ? departureText + '+' + arrivalText : null;
30786        var offerPriceLarge = card.find('.final-price .price-large span').text().replace(',', '.').trim() || '00';
30787        var offerPriceSmall = card.find('.final-price .price-small span').text().replace(',', '.').trim() || '00';
30788        var offerPrice = parseFloat(offerPriceLarge  + offerPriceSmall);
30789        var offerOriginalPrice = parseFloat(card.find('.price-strike span').text().replace('R$', '').trim().replace(',', '.')) || null;
30790        var offerOperator = card.find('.tag').text().trim() || null;
30791
30792        offers.push({
30793          offer_name: offerName,
30794          offer_id: null,
30795          offer_operator: offerOperator,
30796          departure_city: departureText,
30797          departure_state: self.extractState(departureText),
30798          arrival_city: arrivalText,
30799          arrival_state: self.extractState(arrivalText),
30800          offer_price: offerPrice,
30801          offer_original_price: offerOriginalPrice,
30802          currency: 'BRL',
30803          position: index + 1
30804        });
30805      });
30806
30807      this.getGeoLocationData(function (geoLocation) {
30808        window.dataLayer = window.dataLayer || [];
30809        window.dataLayer.push({
30810          event: "view_offer_carousel",
30811          device: Utils.getDevice(),
30812          sales_origin: $("#siteName").val(),
30813          ecommerce: {
30814            currency: "BRL",
30815            item_list_name: "Carrossel de Ofertas",
30816            offers: offers
30817          },
30818          user_data: Utils.getUserData() || {},
30819          geo_location: geoLocation
30820        });
30821      });
30822    }
30823  }, {
30824    key: 'pushSelectOfferEvent',
30825    value: function pushSelectOfferEvent(index) {
30826      var promoCards = $('.promo-card.aem-GridColumn.aem-GridColumn--default--12 > .promo-card');
30827      var visibleCards = promoCards.filter(':visible');
30828      var card = visibleCards.eq(index);
30829
30830      var departureText = card.find('.promo-card-route .departure p').text().trim() || null;
30831      var arrivalText = card.find('.promo-card-route .arrival p').text().trim() || null;
30832      var offerName = departureText && arrivalText ? departureText + '+' + arrivalText : null;
30833      var offerPriceLarge = card.find('.final-price .price-large span').text().replace(',', '.').trim() || '00';
30834      var offerPriceSmall = card.find('.final-price .price-small span').text().replace(',', '.').trim() || '00';
30835      var offerPrice = parseFloat(offerPriceLarge  + offerPriceSmall);
30836      var offerOriginalPrice = parseFloat(card.find('.price-strike span').text().replace('R$', '').trim().replace(',', '.')) || null;
30837      var offerOperator = card.find('.tag').text().trim() || null;
30838      var self = this;
30839
30840      this.getGeoLocationData(function (geoLocation) {
30841        window.dataLayer = window.dataLayer || [];
30842        window.dataLayer.push({
30843          event: "select_offer",
30844          device: Utils.getDevice(),
30845          sales_origin: $("#siteName").val(),
30846          ecommerce: {
30847            currency: "BRL",
30848            item_list_name: "Carrossel de Ofertas",
30849            offers: [{
30850              offer_name: offerName,
30851              offer_id: null,
30852              offer_operator: offerOperator,
30853              departure_city: departureText,
30854              departure_state: self.extractState(departureText),
30855              arrival_city: arrivalText,
30856              arrival_state: self.extractState(arrivalText),
30857              offer_price: offerPrice,
30858              offer_original_price: offerOriginalPrice,
30859              currency: 'BRL',
30860              position: index + 1
30861            }]
30862          },
30863          user_data: Utils.getUserData() || {},
30864          geo_location: geoLocation
30865        });
30866      });
30867    }
30868  }]);
30869
30870  return PromoCardSectionController;
30871}();
30872'use strict';
30873
30874var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
30875
30876function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30877
30878var PaymentMethod = function () {
30879  function PaymentMethod() {
30880    _classCallCheck(this, PaymentMethod);
30881
30882    this.cardList = $('[data-js="card-list"]');
30883    this.alertRemoveCard = $('[data-js="alert-remove-card"]');
30884    this.closeAlertRemoveCard = $('[data-js="close-alert-remove-card"]');
30885    this.init();
30886  }
30887
30888  _createClass(PaymentMethod, [{
30889    key: 'init',
30890    value: function init() {
30891      this.fetchCards();
30892      this.handleAlert();
30893    }
30894  }, {
30895    key: 'handleAlert',
30896    value: function handleAlert() {
30897      var _this = this;
30898
30899      this.closeAlertRemoveCard.click(function (e) {
30900        _this.alertRemoveCard.fadeOut();
30901      });
30902    }
30903  }, {
30904    key: 'fetchCards',
30905    value: function fetchCards() {
30906      var _this2 = this;
30907
30908      var headersGetCard = {
30909        'Authorization': '' + SessionStorage.get('jca_token'),
30910        'flowPayment': 'Adyen'
30911      };
30912
30913      var headersGetCardMalga = {
30914        'Authorization': '' + SessionStorage.get('jca_token'),
30915        'flowPayment': 'malga'
30916      };
30917
30918      LoaderService.show();
30919
30920      Promise.allSettled([HttpService.get('getCard', headersGetCard), HttpService.get('getCardMalga', headersGetCardMalga)]).then(function (results) {
30921        LoaderService.hide();
30922
30923        var cards = results.flatMap(function (result, index) {
30924          if (result.status === 'fulfilled' && Array.isArray(result.value.result)) {
30925            return result.value.result.map(function (card) {
30926              return {
30927                id: card.id,
30928                token: index === 1 ? card.token : undefined,
30929                holderName: card.holderName,
30930                cardSummary: card.cardSummary,
30931                paymentMethod: card.paymentMethod,
30932                source: index === 0 ? 'normal' : 'malga'
30933              };
30934            });
30935          } else if (result.status === 'rejected') {
30936            console.error('Erro ao obter cart\xF5es ' + (index === 0 ? 'normais' : 'Malga') + ':', result.reason);
30937          }
30938          return [];
30939        });
30940
30941        _this2.addCardToList(cards);
30942        new Modal($);
30943      }).catch(function (err) {
30944        LoaderService.hide();
30945        console.error(err);
30946      });
30947    }
30948  }, {
30949    key: 'addCardToList',
30950    value: function addCardToList(cards) {
30951      var content = [];
30952
30953      cards.forEach(function (card, index) {
30954        //var srcImage = Utils.renderCreditCardImage(card.paymentMethod);
30955        var srcImage = '/etc.clientlibs/wemobi/clientlibs/clientlib-site/resources/images/generic-card-icon.png';
30956        if ($('[data-js="' + card.paymentMethod + '"]').length > 0) srcImage = $('[data-js="' + card.paymentMethod + '"]').first().attr('data-logo-src');
30957
30958        content.push('\n        <li class="row card-details" data-js="card-details-' + index + '" data-source="' + card.source + '">\n          <div class="col-3"><img src="' + srcImage + '" title="Logo ' + card.paymentMethod + '" alt="Logotipo ' + card.paymentMethod + '" /></div>\n          <div class="col-3">\n            <p>' + card.holderName + '</p>\n          </div>\n          <div class="col-3 col-md-3">\n            <p>*****' + card.cardSummary + '</p>\n          </div>\n          <div class="col-3 col-md-3">\n            <div class="d-flex flex-row justify-content-end align-items-center" data-card-number="' + card.cardSummary + '" data-cardid="' + card.id + '" data-token="' + (card.token || '') + '" data-js="remove-card-' + index + '"><em class="jca-ico-trash" data-to-modal="modal-link"  id="icon-delete-credit-card-' + index + '" data-js="delete-credit-card"></em><a data-to-modal="modal-link" data-js="delete-credit-card" href="javascript:void(0)" id="delete-credit-card-' + index + '">Remover</a></div>\n          </div>\n        </li>\n      ');
30959      });
30960
30961      this.cardList.empty().append(content.join(''));
30962      this.handleRemoveCard();
30963    }
30964  }, {
30965    key: 'handleRemoveCard',
30966    value: function handleRemoveCard() {
30967      var _this3 = this;
30968
30969      $('[data-js^="remove-card"]').click(function (e) {
30970        var removeButton = $(e.currentTarget);
30971        var liReferer = removeButton.closest('.card-details').data('js');
30972        var cardNumber = removeButton.data('card-number');
30973        var id = removeButton.data('cardid');
30974        var token = removeButton.data('token');
30975        var source = removeButton.closest('.card-details').data('source');
30976        var removeBtn = $('[data-js="btn-delete-credit-card"]');
30977        $('[data-js="number-card"]').text(cardNumber);
30978        removeBtn.attr('data-cardid', source === 'malga' ? token : id);
30979        removeBtn.attr('data-li-refer', liReferer);
30980        removeBtn.attr('data-source', source);
30981      });
30982
30983      $('[data-js="btn-delete-credit-card"]').on('click', function (e) {
30984        var $el = $(e.currentTarget);
30985        var removeLi = $el.attr('data-li-refer');
30986        var identifier = $el.attr('data-cardid');
30987        var source = $el.attr('data-source');
30988
30989        _this3.removeCard(identifier, removeLi, source);
30990      });
30991
30992      $('[data-js="cancel-delete-credit-card"]').on('click', function () {
30993        $('[data-js="modal-close"]').trigger('click');
30994      });
30995
30996      $('.jca-ico-trash').on('click', function (e) {
30997        $(e.currentTarget).next().click();
30998      });
30999    }
31000  }, {
31001    key: 'removeCard',
31002    value: function removeCard(identifier, el, source) {
31003      var _this4 = this;
31004
31005      this.requestRemoveCard(identifier, source).then(function () {
31006        _this4.removedCard(el);
31007      }).catch(function () {
31008        Alert.show(i18n('remove_card_error'));
31009      });
31010    }
31011  }, {
31012    key: 'requestRemoveCard',
31013    value: function requestRemoveCard(identifier, source) {
31014      var parameters = source === 'malga' ? { cardId: identifier } : { Id: identifier };
31015
31016      var headers = {
31017        'Authorization': 'Bearer ' + SessionStorage.get('jca_token')
31018      };
31019
31020      LoaderService.show();
31021      return new Promise(function (resolve, reject) {
31022        if (source === 'malga') {
31023          return HttpService.delete('removeCardMalga?' + $.param(parameters), {}, headers).then(function (data) {
31024            LoaderService.hide();
31025            resolve(data);
31026          }).catch(function (err) {
31027            LoaderService.hide();
31028            console.error(err);
31029            reject(err);
31030          });
31031        } else {
31032          return HttpService.post('removeCard?' + $.param(parameters), null, headers).then(function (data) {
31033            LoaderService.hide();
31034            resolve(data);
31035          }).catch(function (err) {
31036            LoaderService.hide();
31037            console.error(err);
31038            reject(err);
31039          });
31040        }
31041      });
31042    }
31043  }, {
31044    key: 'removedCard',
31045    value: function removedCard(el) {
31046      $('[data-js="' + el + '"]').remove();
31047      $('[data-js="modal-close"]').trigger('click');
31048      this.alertRemoveCard.fadeIn();
31049    }
31050  }]);
31051
31052  return PaymentMethod;
31053}();
31054'use strict';
31055
31056var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
31057
31058function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
31059
31060var PaymentPending = function () {
31061  function PaymentPending($) {
31062    _classCallCheck(this, PaymentPending);
31063
31064    this.$pixCheck = $('[data-js="pix-check"]');
31065    this.$pixPendingPrice = $('[data-js="pix-pending-price"]');
31066    this.$rectanglePix = $('[data-js="rectangle-pix"]');
31067
31068    this.$balanceCheck = $('[data-js="balance-check"]');
31069    this.$rectangleBalance = $('[data-js="rectangle-balance"]');
31070
31071    this.$buttonFinalBuy = $('[data-js="payment-submit"]');
31072    this.$checkConditions = $('[data-js="conditions-check"]'); // Ensure this is correctly referenced
31073    this.originalButtonText = this.$buttonFinalBuy.text();
31074
31075    this.init();
31076  }
31077
31078  _createClass(PaymentPending, [{
31079    key: 'init',
31080    value: function init() {
31081      var _this = this;
31082
31083      this.handleComponent();
31084      this.$pixCheck.on('change', function () {
31085        return _this.handlePixCheckChange();
31086      });
31087      this.$balanceCheck.on('change', function () {
31088        return _this.handleBalanceCheckChange();
31089      });
31090      this.$checkConditions.on('change', function () {
31091        return _this.updateButtonState();
31092      }); // Add event listener for conditions check
31093      this.updateButtonState(); // Initial check
31094    }
31095  }, {
31096    key: 'handleComponent',
31097    value: function hadleComponent() {
31098      var passenger = SessionStorage.get('passenger');
31099      var nupayPaymentReferenceId = SessionStorage.get('nupayPaymentReferenceId');
31100
31101      if (!passenger && !nupayPaymentReferenceId) {
31102        if ((!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false')) {
31103          $(location).attr('href', $('#homePagePath').val());
31104        }
31105      }
31106
31107      /*if (passenger != null) {
31108        if (!passenger._groups || !passenger._groups.split(',').map(function (group) {
31109          return group.trim();
31110        }).includes('wallet')) {
31111          $('[data-js="tab-conta-giro"]').remove();
31112        }
31113      }*/
31114    }
31115  }, {
31116    key: 'handlePixCheckChange',
31117    value: function handlePixCheckChange() {
31118      if (this.$pixCheck.is(':checked')) {
31119        this.$rectanglePix.addClass('checked-background');
31120        this.$pixPendingPrice.addClass('checked-pix-amount');
31121        this.$buttonFinalBuy.text("Completar a diferença com Pix");
31122      } else {
31123        this.$rectanglePix.removeClass('checked-background');
31124        this.$pixPendingPrice.removeClass('checked-pix-amount');
31125        this.$buttonFinalBuy.text(this.originalButtonText);
31126      }
31127      this.updateButtonState();
31128    }
31129  }, {
31130    key: 'handleBalanceCheckChange',
31131    value: function handleBalanceCheckChange() {
31132      if (this.$balanceCheck.is(':checked')) {
31133        this.$rectangleBalance.addClass('checked-balance-background');
31134      } else {
31135        this.$rectangleBalance.removeClass('checked-balance-background');
31136      }
31137      this.updateButtonState();
31138    }
31139  }, {
31140    key: 'updateButtonState',
31141    value: function updateButtonState() {
31142      if ((this.$pixCheck.is(':checked') || this.$balanceCheck.is(':checked')) && this.$checkConditions.is(':checked')) {
31143        this.$buttonFinalBuy.prop('disabled', false);
31144      } else {
31145        this.$buttonFinalBuy.prop('disabled', true);
31146      }
31147    }
31148  }]);
31149
31150  return PaymentPending;
31151}();
31152'use strict';
31153
31154var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
31155
31156function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
31157
31158var PinCodeController = function () {
31159  function PinCodeController($) {
31160    _classCallCheck(this, PinCodeController);
31161
31162    this.pinInputs = $('[data-js^="pin-input"]');
31163    this.confirmButton = $('[data-js="button-confirm"]');
31164    this.clearButton = $('[data-js="button-clear-pin"]');
31165    this.instructionText = $('.text-container p:first-child');
31166    this.additionalText = $('.text-container p:last-child');
31167    this.pinTitle = $('[data-js="create-pin-title"]');
31168    this.buttonPinConfirm = $('[data-js="button-confirm-pin"]');
31169    this.fromCancelFlow = SessionStorage.get('fromCancelFlow');
31170    this.backToHome = $('[data-js="back-to-home"]');
31171    this.isConfirming = false;
31172    this.firstPin = null;
31173    this.deviceIP = null;
31174    this.isCreateWallet = false;
31175    this.init();
31176  }
31177
31178  _createClass(PinCodeController, [{
31179    key: 'init',
31180    value: function init() {
31181      var _this = this;
31182
31183      //Utils.checkWalletGroup();
31184      this.getIP();
31185      this.setupPinInputs();
31186      this.confirmButton.on('click', function () {
31187        return _this.handleConfirm();
31188      });
31189      this.confirmButton.prop('disabled', true);
31190      this.homeBack();
31191    }
31192  }, {
31193    key: 'homeBack',
31194    value: function homeBack() {
31195      var _this2 = this;
31196
31197      var flowWalletPayment = SessionStorage.get('flowWalletPayment');
31198      this.backToHome.on('click', function () {
31199        if (flowWalletPayment) {
31200          $(location).attr("href", $('#paymentPagePath').val());
31201          return;
31202        }
31203
31204        if (_this2.fromCancelFlow) {
31205          $(location).attr("href", i18n('cancel_trip_wallet_page'));
31206          return;
31207        }
31208
31209        $(location).attr("href", i18n('payment_link_redirect'));
31210      });
31211    }
31212  }, {
31213    key: 'setupPinInputs',
31214    value: function setupPinInputs() {
31215      var _this2 = this;
31216
31217      this.pinInputs.each(function (index, input) {
31218        _this2.setupInput(input, index);
31219      });
31220    }
31221  }, {
31222    key: 'getIP',
31223    value: function getIP() {
31224      var _this3 = this;
31225
31226      return new Promise(function (resolve, reject) {
31227        _this3.fetchIP('https://api.ipify.org?format=json').then(resolve).catch(function () {
31228          return _this3.fetchIP('https://jsonip.com/').then(resolve).catch(reject);
31229        });
31230      });
31231    }
31232  }, {
31233    key: 'fetchIP',
31234    value: function fetchIP(url) {
31235      var _this4 = this;
31236
31237      return $.getJSON(url).then(function (data) {
31238        _this4.deviceIP = data.ip;
31239        return data.ip;
31240      }).catch(function (err) {
31241        console.error('Erro ao obter o IP do dispositivo:', err);
31242        throw err;
31243      });
31244    }
31245  }, {
31246    key: 'setupInput',
31247    value: function setupInput(input, index) {
31248      var _this5 = this;
31249
31250      $(input).on('input', function (event) {
31251        return _this5.handleInput(event, index);
31252      });
31253      $(input).on('focus', function (event) {
31254        return _this5.handleFocus(event);
31255      });
31256    }
31257  }, {
31258    key: 'handleInput',
31259    value: function handleInput(event, index) {
31260      var value = event.target.value;
31261      if (!/^\d$/.test(value)) {
31262        event.target.value = '';
31263        return;
31264      }
31265
31266      if (index < this.pinInputs.length - 1) {
31267        $(this.pinInputs[index + 1]).focus();
31268      }
31269
31270      var allFilled = this.pinInputs.toArray().every(function (input) {
31271        return input.value.length === 1;
31272      });
31273      this.confirmButton.prop('disabled', !allFilled);
31274    }
31275  }, {
31276    key: 'handleFocus',
31277    value: function handleFocus(event) {
31278      event.target.select();
31279    }
31280  }, {
31281    key: 'clearPinInputs',
31282    value: function clearPinInputs() {
31283      this.pinInputs.val('');
31284      $(this.pinInputs[0]).focus();
31285      this.confirmButton.prop('disabled', true);
31286      this.clearButton.hide();
31287    }
31288  }, {
31289    key: 'handleConfirm',
31290    value: function handleConfirm() {
31291      var pin = this.getPinValue();
31292
31293      if (!this.isConfirming) {
31294        this.startPinConfirmation(pin);
31295      } else {
31296        this.confirmPin(pin);
31297      }
31298    }
31299  }, {
31300    key: 'getPinValue',
31301    value: function getPinValue() {
31302      return this.pinInputs.toArray().map(function (input) {
31303        return input.value;
31304      }).join('');
31305    }
31306  }, {
31307    key: 'startPinConfirmation',
31308    value: function startPinConfirmation(pin) {
31309      this.firstPin = pin;
31310      this.isConfirming = true;
31311      this.pinTitle.text('Insira seu PIN Conta Giro novamente');
31312      this.instructionText.text('Por favor, insira seu PIN Conta Giro novamente.');
31313      this.additionalText.hide();
31314      this.clearPinInputs();
31315      this.confirmButton.prop('disabled', true);
31316    }
31317  }, {
31318    key: 'confirmPin',
31319    value: function confirmPin(pin) {
31320      if (pin === this.firstPin) {
31321        var resetCode = SessionStorage.get('resetCode');
31322        if (resetCode) {
31323          this.changePin(pin);
31324        } else {
31325          this.createWallet(pin);
31326        }
31327      } else {
31328        Alert.show('Os PINs não coincidem. Tente novamente.');
31329        this.resetPinEntry();
31330      }
31331    }
31332  }, {
31333    key: 'resetPinEntry',
31334    value: function resetPinEntry() {
31335      this.isConfirming = false;
31336      this.firstPin = null;
31337      this.pinTitle.text('Crie seu PIN Conta Giro');
31338      this.instructionText.text('Escolha um PIN de 6 dígitos: Certifique-se de não escolher números consecutivos repetidos.');
31339      this.additionalText.show().text('Escolha um PIN fácil de lembrar, mas difícil de adivinhar.');
31340      this.clearPinInputs();
31341      this.confirmButton.prop('disabled', true);
31342    }
31343  }, {
31344    key: 'createWallet',
31345    value: function createWallet(userPin) {
31346      var _this6 = this;
31347
31348      var payload = this.getWalletPayload(userPin);
31349      var headers = this.getAuthHeaders();
31350
31351      LoaderService.show();
31352
31353      HttpService.post("createWallet", payload, headers).then(function (data) {
31354        _this6.isCreateWallet = true;
31355        LoaderService.hide();
31356        SessionStorage.set('Wallet', data.result);
31357        _this6.loginWallet(userPin);
31358        ModalConfirmPin.show();
31359        _this6.checkWalletExists();
31360      }).catch(function (error) {
31361        LoaderService.hide();
31362        _this6.handleWalletErrorMessage(error);
31363      });
31364    }
31365  }, {
31366    key: 'getWalletPayload',
31367    value: function getWalletPayload(userPin) {
31368      return {
31369        password: userPin,
31370        deviceFingerPrint: $("#device-fingerprint").val(),
31371        deviceName: this.deviceIP
31372      };
31373    }
31374  }, {
31375    key: 'getAuthHeaders',
31376    value: function getAuthHeaders() {
31377      var token = this.getToken();
31378      return {
31379        Authorization: token ? token : ''
31380      };
31381    }
31382  }, {
31383    key: 'getToken',
31384    value: function getToken() {
31385      var tokenFromStorage = SessionStorage.get("jca_token");
31386      if (tokenFromStorage) {
31387        return tokenFromStorage;
31388      }
31389
31390      var tokenFromUrl = new URLSearchParams(window.location.search).get('jca_token');
31391      return tokenFromUrl ? tokenFromUrl.replace(/^"|"$/g, '') : null;
31392    }
31393  }, {
31394    key: 'loginWallet',
31395    value: function loginWallet(userPin) {
31396      var _this8 = this;
31397
31398      var payload = this.getLoginPayload(userPin);
31399      var headers = this.getAuthHeaders();
31400
31401      LoaderService.show();
31402
31403      HttpService.post("loginWallet", payload, headers).then(function (data) {
31404        LoaderService.hide();
31405        SessionStorage.set('user_wallet', data.result);
31406        _this8.handleModal();
31407      }).catch(function () {
31408        LoaderService.show();
31409        $(location).attr("href", $('#walletLoginPagePath').val());
31410      });
31411    }
31412  }, {
31413    key: 'getLoginPayload',
31414    value: function getLoginPayload(userPin) {
31415      return {
31416        pin: userPin,
31417        deviceFingerPrint: $("#device-fingerprint").val()
31418      };
31419    }
31420  }, {
31421    key: 'handleWalletErrorMessage',
31422    value: function handleWalletErrorMessage(error) {
31423      if (error.responseJSON && error.responseJSON.Message) {
31424        Alert.show(error.responseJSON.Message);
31425      } else {
31426        Alert.show(i18n("wallet_creation_error"));
31427      }
31428    }
31429  }, {
31430    key: 'handleChangePinErrorMessage',
31431    value: function handleChangePinErrorMessage(error) {
31432      if (error.responseJSON && error.responseJSON.Message) {
31433        Alert.show(error.responseJSON.Message);
31434      } else {
31435        Alert.show(i18n("error_change_pin"));
31436      }
31437    }
31438  }, {
31439    key: 'showErrorMessages',
31440    value: function showErrorMessages(error) {
31441      try {
31442        if (error.message) {
31443          Alert.show(error.message);
31444        }
31445        if (error.errors) {
31446          for (var key in error.errors) {
31447            if (error.errors.hasOwnProperty(key)) {
31448              error.errors[key].forEach(function (errMsg) {
31449                Alert.show(errMsg);
31450              });
31451            }
31452          }
31453        }
31454      } catch (e) {
31455        Alert.show(i18n("wallet_creation_error"));
31456      }
31457    }
31458  }, {
31459    key: 'handleModal',
31460    value: function handleModal() {
31461      var _this7 = this;
31462
31463      ModalConfirmPin.show();
31464      $('.modal-overlay').addClass('active');
31465      $('.modal-content[data-js="modal-container-confirm-pin"]').addClass('active');
31466
31467      this.buttonPinConfirm.on('click', function () {
31468        var flowWalletPayment = SessionStorage.get('flowWalletPayment');
31469        if (flowWalletPayment) {
31470          $(location).attr("href", $('#paymentPagePath').val());
31471        } else {
31472          $(location).attr("href", $('#walletHomePagePath').val());
31473        }
31474        if (_this7.fromCancelFlow) {
31475          SessionStorage.remove('fromCancelFlow');
31476          SessionStorage.set('walletCreatedCancel', true);
31477          $(location).attr("href", i18n('cancel_trip_wallet_page'));
31478        }
31479      });
31480    }
31481  }, {
31482    key: 'checkWalletExists',
31483    value: function checkWalletExists() {
31484      var passenger = SessionStorage.get('passenger');
31485
31486      if (passenger && passenger._cpf) {
31487        var cpf = passenger._cpf;
31488
31489        var headers = {
31490          Authorization: '' + SessionStorage.get("jca_token")
31491        };
31492
31493        LoaderService.show();
31494        var content = 'checkWalletExists?cpf=' + cpf;
31495        HttpService.get(content, headers).then(function (data) {
31496          LoaderService.hide();
31497          if (data.success === false) {
31498            SessionStorage.set('walletExists', false);
31499          } else {
31500            SessionStorage.set('walletId', data.result.walletId);
31501            SessionStorage.set('walletExists', true);
31502          }
31503        }).catch(function (err) {
31504          LoaderService.hide();
31505          console.error(err);
31506        });
31507      }
31508    }
31509  }, {
31510    key: 'changePin',
31511    value: function changePin(userPinNew) {
31512      var _this10 = this;
31513
31514      var resetCode = SessionStorage.get('resetCode');
31515      if (!resetCode) {
31516        Alert.show('Código de redefinição não encontrado. Por favor, tente novamente.');
31517        return;
31518      }
31519
31520      var payload = {
31521        deviceFingerprint: $("#device-fingerprint").val(),
31522        resetCode: resetCode,
31523        newPin: userPinNew
31524      };
31525
31526      var headers = this.getAuthHeaders();
31527
31528      LoaderService.show();
31529
31530      HttpService.post("changePin", payload, headers).then(function (data) {
31531        LoaderService.hide();
31532        SessionStorage.remove('resetCode'); // Remove o resetCode do sessionStorage
31533        _this10.handleModal();
31534        SessionStorage.set('user_wallet', data.result);
31535      }).catch(function (error) {
31536        LoaderService.hide();
31537        _this10.handleChangePinErrorMessage(error);
31538      });
31539    }
31540  }]);
31541
31542  return PinCodeController;
31543}();
31544'use strict';
31545
31546var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
31547
31548function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
31549
31550var RouteMap = function () {
31551  function RouteMap($) {
31552    _classCallCheck(this, RouteMap);
31553
31554    this.MOBILE_WIDTH = 768;
31555    var originIconImg = $('[data-js="icon-origin"]').find('img');
31556    var destinationIconImg = $('[data-js="icon-destination"]').find('img');
31557    this.originMapIcon = new ol.style.Style({
31558      image: new ol.style.Icon({
31559        src: originIconImg.attr('src'),
31560        scale: 0.5,
31561        anchor: [0.5, 1]
31562      })
31563    });
31564    this.destinationMapIcon = new ol.style.Style({
31565      image: new ol.style.Icon({
31566        src: destinationIconImg.attr('src'),
31567        scale: 0.5,
31568        anchor: [0.5, 1]
31569      })
31570    });
31571    this.defaultMaxZoom = parseInt($('[data-js="input-default-max-zoom"]').val());
31572    this.routeMapListOffer = $('[data-js="route-map-list-offer"]');
31573    this.routeMapNoResult = $('[data-js="route-map-no-result"]');
31574    $(window).scroll(function () {
31575      var distanceToTop = $(document).scrollTop();
31576      var floating = $('.route-map-results-container');
31577      var floatingHeight = floating.height();
31578      var mapHeight = $('#map').height();
31579      var freeSpace = mapHeight - floatingHeight;
31580      var headerHeight = $('.header-site').height() + 20;
31581      if (freeSpace > 0) {
31582        var newTop = headerHeight + (distanceToTop > freeSpace ? freeSpace : distanceToTop);
31583        if (newTop < 284) newTop = 284;
31584        floating.animate({
31585          top: newTop + "px"
31586        }, {
31587          duration: 400,
31588          queue: false
31589        });
31590      }
31591    });
31592    this.clearSearchBtn = $('[data-js="clear-search"]');
31593    this.lastSelected = {};
31594  }
31595
31596  _createClass(RouteMap, [{
31597    key: 'init',
31598    value: function init() {
31599      var _this = this;
31600
31601      this.requestCoordinates(function () {
31602        _this.selectCompanyFilter = new SelectCustom($);
31603        _this.shouldHideIcons();
31604        _this.initOverlay();
31605        _this.initMap();
31606        _this.locationInput = new LocationInput($, null, null);
31607        _this.locationInput.getAllLocations(function () {
31608          _this.initSearchComponent();
31609          _this.startDefaultValues();
31610          $('body').click(function (e) {
31611            if (!$(e.target).parent().hasClass('ol-viewport')) _this.tooltipCloseIcon.trigger('click');
31612            if (!$(e.target).hasClass('ui-autocomplete-input') && !$(e.target).hasClass('ui-menu-wrapper')) {
31613              if (_this.inputDeparture.data("autocomplete")) _this.inputDeparture.autocomplete('close');
31614              if (_this.inputDestination.data("autocomplete")) _this.inputDestination.autocomplete('close');
31615            }
31616          });
31617        });
31618      });
31619    }
31620  }, {
31621    key: 'initOverlay',
31622    value: function initOverlay() {
31623      var _this2 = this;
31624
31625      var tooltipContainer = $('[data-js="tooltip-container"]');
31626      this.tooltipContent = tooltipContainer.find('.tooltip-description');
31627      this.tooltipCloseIcon = tooltipContainer.find('[data-js="tooltip-close"]');
31628      this.tooltipConfirmIcon = tooltipContainer.find('[data-js="tooltip-confirm"]');
31629      this.overlay = new ol.Overlay({
31630        element: tooltipContainer[0],
31631        autoPan: true,
31632        autoPanAnimation: {
31633          duration: 250
31634        }
31635      });
31636      this.tooltipCloseIcon.click(function () {
31637        _this2.overlay.setPosition(undefined);
31638        _this2.tooltipCloseIcon.blur();
31639        _this2.lastFeature = null;
31640        return false;
31641      });
31642    }
31643  }, {
31644    key: 'shouldHideIcons',
31645    value: function shouldHideIcons() {
31646      var hideTooltipButtons = $('[data-js="hide-tooltip-buttons"]').val().toLowerCase() == 'true';
31647      if (hideTooltipButtons) {
31648        $('.tooltip-icon-container').hide();
31649      }
31650    }
31651  }, {
31652    key: 'getFormattedLocation',
31653    value: function getFormattedLocation(id) {
31654      return this.locationInput.todasLocalidades.filter(function (e) {
31655        return id == e.value;
31656      })[0];
31657    }
31658  }, {
31659    key: 'putAllLocationsOnMap',
31660    value: function putAllLocationsOnMap() {
31661      if (!this.allCoordinates) {
31662        this.allCoordinates = this.getCoordinates(this.locationInput.todasLocalidades);
31663        this.allCoordinates = this.allCoordinates.filter(function (value) {
31664          return value;
31665        });
31666      }
31667      this.showMarkersOnMap(this.allCoordinates, []);
31668    }
31669  }, {
31670    key: 'initMap',
31671    value: function initMap() {
31672      var _this3 = this;
31673
31674      var centerLng = parseFloat($('[data-js="input-default-center-lng"]').val().replace(',', '.'));
31675      var centerLat = parseFloat($('[data-js="input-default-center-lat"]').val().replace(',', '.'));
31676      var defaultZoom = parseInt($('[data-js="input-default-zoom"]').val());
31677      var centerPoint = ol.proj.fromLonLat([centerLng, centerLat]);
31678      this.map = new ol.Map({
31679        interactions: ol.interaction.defaults({
31680          onFocusOnly: true,
31681          pinchRotate: false
31682        }),
31683        target: 'map',
31684        layers: [new ol.layer.Tile({
31685          source: new ol.source.OSM()
31686        })],
31687        view: new ol.View({
31688          center: centerPoint,
31689          zoom: defaultZoom
31690        }),
31691        overlays: [this.overlay]
31692      });
31693      var mouseWheelInt = new ol.interaction.MouseWheelZoom();
31694      this.map.addInteraction(mouseWheelInt);
31695      this.map.on('wheel', function (evt) {
31696        var isShiftPressed = ol.events.condition.shiftKeyOnly(evt);
31697        mouseWheelInt.setActive(isShiftPressed);
31698      });
31699      this.map.on('singleclick', function (evt) {
31700        var feature = _this3.map.forEachFeatureAtPixel(evt.pixel, function (feature) {
31701          return feature;
31702        });
31703        if (feature) {
31704          var lastId = _this3.lastFeature ? _this3.lastFeature.coordinate.id : -1;
31705          if (lastId != feature.coordinate.id) {
31706            _this3.lastFeature = feature;
31707            var val = _this3.getFormattedLocation(feature.coordinate.id);
31708            _this3.tooltipContent.html("<p>" + val.label + "</p>");
31709            _this3.overlay.setPosition(evt.coordinate);
31710            _this3.tooltipConfirmIcon.off('click').click(function () {
31711              _this3.pointClickEvent(feature);
31712            });
31713          }
31714        } else _this3.tooltipCloseIcon.trigger('click');
31715      });
31716      this.map.on('pointermove', function (e) {
31717        var pixel = _this3.map.getEventPixel(e.originalEvent);
31718        var hit = _this3.map.hasFeatureAtPixel(pixel);
31719        _this3.map.getTargetElement().style.cursor = hit ? 'pointer' : '';
31720      });
31721    }
31722  }, {
31723    key: 'pointClickEvent',
31724    value: function pointClickEvent(feature) {
31725      var _this4 = this;
31726
31727      var originInput = this.inputDeparture;
31728      var destinationInput = this.inputDestination;
31729      if (feature.isOrigin) this.forceSelection(originInput, feature.coordinate.id, function () {
31730        _this4._requestAvailableTrips(originInput);
31731      }); else this.forceSelection(destinationInput, feature.coordinate.id, function () {
31732        _this4._requestAvailableTrips(destinationInput);
31733      });
31734      this.tooltipCloseIcon.trigger('click');
31735      if (window.location.search.substring(1).split('&').length > 0) {
31736        var url = window.location.href.replace(window.location.search, '');
31737        history.pushState({
31738          id: 'routemappage'
31739        }, $('head').find('title').text(), url);
31740      }
31741    }
31742  }, {
31743    key: '_fillLocation',
31744    value: function _fillLocation(selectedLocation, value) {
31745      selectedLocation.each(function (index) {
31746        $(this).text(value);
31747      });
31748    }
31749  }, {
31750    key: '_clearInput',
31751    value: function _clearInput(element) {
31752      element.val('');
31753      element.data('value', '');
31754      this.routeMapListOffer.parent().parent().hide();
31755    }
31756  }, {
31757    key: 'requestCoordinates',
31758    value: function requestCoordinates(callback) {
31759      var _this5 = this;
31760      var url = '/content/jca/jcr:content.mappoints.json';
31761      $.getJSON(url).success(function (data, textStatus, jqXHR) {
31762        _this5.locationCoordinates = data.result;
31763        if (callback) callback();
31764      });
31765    }
31766  }, {
31767    key: 'getLocationCoordinate',
31768    value: function getLocationCoordinate(idLocation) {
31769      var result = this.locationCoordinates.filter(function (value) {
31770        return value.id == idLocation;
31771      });
31772      return result[0];
31773    }
31774  }, {
31775    key: 'getCoordinates',
31776    value: function getCoordinates(listDestinations) {
31777      var destinationCoordinates = [];
31778      for (var i = 0; listDestinations != null && i < listDestinations.length; i++) {
31779        var destination = listDestinations[i].value;
31780        var _location = this.getLocationCoordinate(destination);
31781        destinationCoordinates = destinationCoordinates.concat(_location);
31782      }
31783      return destinationCoordinates;
31784    }
31785  }, {
31786    key: '_setVectorLayer',
31787    value: function _setVectorLayer(vectorSource) {
31788      if (!this.vectorLayer) this.vectorLayer = new ol.layer.Vector(); else this.map.removeLayer(this.vectorLayer);
31789      this.vectorLayer.setSource(vectorSource);
31790      this.map.addLayer(this.vectorLayer);
31791    }
31792  }, {
31793    key: 'getLine',
31794    value: function getLine(originPoint, destinationPoint) {
31795      var lineColorHex = $('[data-js="input-line-color"]').val();
31796      var lineWidth = parseInt($('[data-js="input-line-width"]').val());
31797
31798      var line = new ol.Feature({
31799        geometry: new ol.geom.LineString([originPoint, destinationPoint])
31800      });
31801      line.setStyle(new ol.style.Style({
31802        stroke: new ol.style.Stroke({
31803          color: ol.color.asArray(lineColorHex),
31804          width: lineWidth
31805        })
31806      }));
31807      return line;
31808    }
31809  }, {
31810    key: 'putMarkersOnMap',
31811    value: function putMarkersOnMap(mapFeatures, coordinates, isOrigin) {
31812      var sumLongitude = 0;
31813      var sumLatitude = 0;
31814      var icon = isOrigin ? this.originMapIcon : this.destinationMapIcon;
31815      for (var i = 0; i < coordinates.length; i++) {
31816        var coordinate = coordinates[i];
31817        sumLongitude += coordinate.longitude;
31818        sumLatitude += coordinate.latitude;
31819        var point = ol.proj.fromLonLat([coordinate.longitude, coordinate.latitude]);
31820        var marker = new ol.Feature({
31821          geometry: new ol.geom.Point(point)
31822        });
31823        marker.setStyle(icon);
31824        marker.coordinate = coordinate;
31825        marker.isOrigin = isOrigin;
31826        mapFeatures.push(marker);
31827      }
31828      return [sumLongitude, sumLatitude];
31829    }
31830  }, {
31831    key: 'showMarkersOnMap',
31832    value: function showMarkersOnMap(originCoordinates, destinationCoordinates, shouldRevertInputs) {
31833      var mapFeatures = [];
31834      var originSumPoint = [];
31835      var destinationSumPoint = [];
31836      destinationSumPoint = this.putMarkersOnMap(mapFeatures, destinationCoordinates, shouldRevertInputs);
31837      originSumPoint = this.putMarkersOnMap(mapFeatures, originCoordinates, !shouldRevertInputs);
31838      var avgPoint = [(originSumPoint[0] + destinationSumPoint[0]) / destinationCoordinates.length + originCoordinates.length, (originSumPoint[1] + destinationSumPoint[1]) / destinationCoordinates.length + originCoordinates.length];
31839      var centerPoint = ol.proj.fromLonLat(avgPoint);
31840      if (destinationCoordinates.length == 1 && originCoordinates.length == 1) {
31841        var pointA = ol.proj.fromLonLat([destinationCoordinates[0].longitude, destinationCoordinates[0].latitude]);
31842        var pointB = ol.proj.fromLonLat([originCoordinates[0].longitude, originCoordinates[0].latitude]);
31843        mapFeatures.push(this.getLine(pointA, pointB));
31844      }
31845      var vectorSource = new ol.source.Vector({
31846        features: mapFeatures
31847      });
31848      this._setVectorLayer(vectorSource);
31849      this.map.getView().setCenter(centerPoint);
31850      this.map.getView().fit(vectorSource.getExtent(), {
31851        size: this.map.getSize(),
31852        maxZoom: this.defaultMaxZoom
31853      });
31854    }
31855  }, {
31856    key: 'setOriginAndPossibleDestinationsCoordinates',
31857    value: function setOriginAndPossibleDestinationsCoordinates(element) {
31858      this.originCoordinates = [].concat(this.getLocationCoordinate(element.data('value')));
31859      this.originCoordinates = this.originCoordinates.filter(function (value) {
31860        return value;
31861      });
31862      this.listPossibleDestinations = this.getCoordinates(this.locationInput.listDestinations);
31863      this.listPossibleDestinations = this.listPossibleDestinations.filter(function (value) {
31864        return value;
31865      });
31866    }
31867  }, {
31868    key: 'markOriginAndPossibleDestinations',
31869    value: function markOriginAndPossibleDestinations(element, shouldRevertInputs) {
31870      this.setOriginAndPossibleDestinationsCoordinates(element);
31871      if (this.originCoordinates.length > 0) this.showMarkersOnMap(this.originCoordinates, this.listPossibleDestinations, shouldRevertInputs);
31872    }
31873  }, {
31874    key: 'markOnlyOriginAndDestination',
31875    value: function markOnlyOriginAndDestination(element, shouldRevertInputs) {
31876      this.destinationCoordinates = this.listPossibleDestinations.filter(function (value) {
31877        return value.id == element.data('value');
31878      });
31879      this.showMarkersOnMap(this.originCoordinates, this.destinationCoordinates, shouldRevertInputs);
31880    }
31881  }, {
31882    key: 'isDeparture',
31883    value: function isDeparture(input) {
31884      return input.data('js') == this.inputDeparture.data('js');
31885    }
31886  }, {
31887    key: '_fillLocations',
31888    value: function _fillLocations() {
31889      this._fillLocation(this.elSelectedDeparture, !this.inputDeparture.data('value') ? 'Escolha no mapa ou nos campos acima.' : this.inputDeparture.val());
31890      this._fillLocation(this.elSelectedDestination, !this.inputDestination.data('value') ? 'Escolha no mapa ou nos campos acima.' : this.inputDestination.val());
31891    }
31892  }, {
31893    key: 'afterDepartureIsSelected',
31894    value: function afterDepartureIsSelected(element) {
31895      var destination = this.isDeparture(element) ? this.inputDestination : this.inputDeparture;
31896      this._fillLocations();
31897      if (destination.data('value')) {
31898        this.setOriginAndPossibleDestinationsCoordinates(element);
31899        this.markOnlyOriginAndDestination(destination, false);
31900      } else {
31901        this.routeMapListOffer.parent().parent().hide();
31902        this.markOriginAndPossibleDestinations(element, this.locationInput.shouldRevertInputs);
31903      }
31904      this._requestAvailableTrips(element);
31905    }
31906  }, {
31907    key: 'afterDestinationIsSelected',
31908    value: function afterDestinationIsSelected(element) {
31909      this._fillLocations();
31910      this.markOnlyOriginAndDestination(element, this.locationInput.shouldRevertInputs);
31911      this._requestAvailableTrips(element);
31912    }
31913  }, {
31914    key: 'initAutocomplete',
31915    value: function initAutocomplete(originInput, done) {
31916      var _this6 = this;
31917
31918      var autoCompleteWrapper = $('<div id="autocomplete-wrapper" class="ui-autocomplete-wrapper"></div>');
31919      $('body').append(autoCompleteWrapper);
31920      this.locationInput.shouldRevertInputs = !this.isDeparture(originInput);
31921      this.locationInput.initOriginAutocomplete(originInput, function () {
31922        if (done) done();
31923      }, function () {
31924        _this6.afterDepartureIsSelected(originInput);
31925      }, function () {
31926        _this6.afterDestinationIsSelected(_this6.isDeparture(originInput) ? _this6.inputDestination : _this6.inputDeparture);
31927      });
31928    }
31929  }, {
31930    key: 'initSearchComponent',
31931    value: function initSearchComponent() {
31932      var _this7 = this;
31933
31934      var form = $('.input-wrapper-container');
31935      form.disableAutoFill();
31936      this.elSelectedDeparture = $('[data-js="selected-departure"]');
31937      this.elSelectedDestination = $('[data-js="selected-destination"]');
31938      this.inputDeparture = this.locationInput.departure;
31939      this.inputDestination = this.locationInput.destination;
31940      this.inputDeparture.add(this.inputDestination).off('click focus blur').on('click focus', function (e) {
31941        ValidationService.close();
31942        $('#autocomplete-wrapper').addClass('active');
31943        $('.ui-autocomplete').addClass('active');
31944        var element = $(e.currentTarget);
31945        _this7._clearInput(element);
31946        if (_this7.locationInput.shouldRevertInputs === null) {
31947          _this7.initAutocomplete(element, function () {
31948            _this7.locationInput.searchForBlank(element);
31949            $('.ui-autocomplete').addClass('route-map-page');
31950          });
31951        }
31952        _this7.locationInput.searchForBlank(element);
31953        $('.ui-autocomplete').addClass('route-map-page');
31954      });
31955
31956      this.clearSearchBtn.click(function (e) {
31957        _this7._clearInput(_this7.inputDeparture);
31958        _this7._clearInput(_this7.inputDestination);
31959        _this7.elSelectedDeparture.text('Escolha no mapa ou nos campos acima.');
31960        _this7.elSelectedDestination.text('Escolha no mapa ou nos campos acima.');
31961        _this7.map.removeLayer(_this7.vectorLayer);
31962        _this7.locationInput.destroyAutocomplete();
31963        _this7.tooltipCloseIcon.trigger('click');
31964        var shouldShowAllLocations = $('[data-js="shouldShowAllLocations"]').val().toLowerCase().trim() == 'true';
31965        if (shouldShowAllLocations) _this7.putAllLocationsOnMap();
31966      });
31967    }
31968  }, {
31969    key: 'forceSelection',
31970    value: function forceSelection(input, id, callback) {
31971      var _this8 = this;
31972
31973      var selectFunction = function selectFunction() {
31974        var location = _this8.getFormattedLocation(id);
31975        if (location) {
31976          var ui = {
31977            item: {
31978              value: location.value,
31979              label: location.label
31980            }
31981          };
31982
31983          $('#autocomplete-wrapper').removeClass('active');
31984          $('.ui-autocomplete').removeClass('active');
31985
31986          $(input).data("value", ui.item.value);
31987          $(input).val(ui.item.label);
31988          $(input).data("address", ui.item.address);
31989          $(input).removeClass('invalid');
31990          $(input).parent().removeClass('has-invalid-input');
31991
31992          if (ui.item != _this8.lastSelected[input.data('js')]) {
31993            _this8.locationInput.lastSelected[input.data('js')] = ui.item;
31994            $(input).blur();
31995
31996            _this8.locationInput.getDestination(ui.item.value, function () {
31997              if (_this8.isDeparture(input)) _this8.afterDepartureIsSelected(input); else _this8.afterDestinationIsSelected(input);
31998            });
31999          }
32000
32001          $(input).blur();
32002          return false;
32003        } else {
32004          throw new Error("No location found with this id.");
32005        }
32006      };
32007      selectFunction();
32008    }
32009  }, {
32010    key: 'fillDestinationField',
32011    value: function fillDestinationField(destinationId) {
32012      var destinationLocation = this.getFormattedLocation(destinationId);
32013      if (destinationLocation) {
32014        this.inputDestination.data("value", destinationLocation.value);
32015        this.inputDestination.val(destinationLocation.label);
32016        this.elSelectedDestination.text(destinationLocation.label);
32017      } else throw new Error("No location found with this id.");
32018      return destinationLocation;
32019    }
32020  }, {
32021    key: 'startDefaultValues',
32022    value: function startDefaultValues() {
32023      var defaultOriginId = parseInt($("[data-js='input-default-origin']").val());
32024      var defaultDestinationId = parseInt($("[data-js='input-default-destination']").val());
32025      var parameters = this.extractParameters();
32026      if (parameters.origem_id || parameters.destino_id) {
32027        var originId = parameters.origem_id ? parseInt(parameters.origem_id) : null;
32028        var destinationId = parameters.destino_id ? parseInt(parameters.destino_id) : null;
32029        this.setMarkersFromParameters(originId, destinationId);
32030      } else {
32031        var shouldShowAllLocations = $('[data-js="shouldShowAllLocations"]').val().toLowerCase().trim() == 'true';
32032        if (shouldShowAllLocations) this.putAllLocationsOnMap(); else this.setMarkersFromParameters(defaultOriginId, defaultDestinationId);
32033      }
32034    }
32035  }, {
32036    key: 'extractParameters',
32037    value: function extractParameters() {
32038      var parametersList = window.location.search.substring(1).split('&');
32039      var values = {};
32040      for (var i = 0; i < parametersList.length; i++) {
32041        var splitParameter = parametersList[i].split('=');
32042        values[splitParameter[0]] = splitParameter[1];
32043      }
32044      return values;
32045    }
32046  }, {
32047    key: 'setMarkersFromParameters',
32048    value: function setMarkersFromParameters(originId, destinationId) {
32049      var _this9 = this;
32050
32051      try {
32052        if (originId && !destinationId) this.forceSelection(this.inputDeparture, originId);
32053        if (originId && destinationId) {
32054          this.forceSelection(this.inputDeparture, originId, function () {
32055            _this9.fillDestinationField(destinationId);
32056          });
32057        }
32058        if (!originId && destinationId) this.forceSelection(this.inputDestination, destinationId);
32059      } catch (ex) {
32060        console.error(ex.message);
32061      }
32062    }
32063  }, {
32064    key: '_setNextDayRedirectButtonEvent',
32065    value: function _setNextDayRedirectButtonEvent() {
32066      var nextDay = new Date();
32067      nextDay.setDate(nextDay.getDate() + 1);
32068      var day = ('0' + nextDay.getDate()).slice(-2);
32069      var month = ('0' + (nextDay.getMonth() + 1)).slice(-2);
32070      var year = nextDay.getFullYear();
32071      var data = day + month + year;
32072      var deeplink = {
32073        origem_id: this.inputDeparture.data('value'),
32074        destino_id: this.inputDestination.data('value'),
32075        num_psgr: 1,
32076        data_ida: data
32077      };
32078      this.routeMapNoResult.find('.search-next-day').off('click').click(function () {
32079        $(location).attr('href', $('#searchResultPath').val() + '?' + $.param(deeplink));
32080      });
32081    }
32082  }, {
32083    key: '_hideResults',
32084    value: function _hideResults() {
32085      if (this.inputDeparture.data('value') && this.inputDestination.data('value')) this._setNextDayRedirectButtonEvent();
32086      this.routeMapListOffer.hide();
32087      this.routeMapNoResult.show();
32088    }
32089  }, {
32090    key: '_scrollToAfterMap',
32091    value: function _scrollToAfterMap(referenceElement) {
32092      if (Utils.getWindowSize().width <= this.MOBILE_WIDTH && !Utils.isScrolledIntoView(referenceElement)) {
32093        var map = $('#map');
32094        var position = map.offset().top + map.height();
32095        $('html,body').animate({
32096          scrollTop: position / 1.5
32097        }, 500);
32098      }
32099    }
32100  }, {
32101    key: '_requestAvailableTrips',
32102    value: function _requestAvailableTrips(input) {
32103      var _this10 = this;
32104
32105      var otherInput = input.data('js') == 'input-departure' ? this.inputDestination : this.inputDeparture;
32106      if (otherInput.data('value')) {
32107        var origin = this.inputDeparture.data('value');
32108        var destination = this.inputDestination.data('value');
32109        var date = DateFormatter.getNewFormattedDate().slice(0, 10);
32110        APIUtils.getAvailableTrips(origin, destination, date).then(function (data) {
32111          _this10.routeMapListOffer.parent().parent().show();
32112          var listaServico = data.consultaServicos.lsServicos;
32113          listaServico = _this10.filterServiceList(listaServico);
32114          if (listaServico && listaServico.length > 0) {
32115            _this10.getServiceTemplate(listaServico, function (content) {
32116              _this10.routeMapNoResult.hide();
32117              _this10.routeMapListOffer.hide();
32118              _this10.routeMapListOffer.empty();
32119              _this10.routeMapListOffer.append(content);
32120              _this10.routeMapListOffer.show();
32121              _this10._scrollToAfterMap(_this10.routeMapListOffer);
32122            });
32123          } else {
32124            _this10._hideResults();
32125            _this10._scrollToAfterMap(_this10.routeMapNoResult);
32126          }
32127        }).catch(function () {
32128          _this10._hideResults();
32129          _this10._scrollToAfterMap(_this10.routeMapNoResult);
32130        });
32131      }
32132    }
32133  }, {
32134    key: 'getDateObj',
32135    value: function getDateObj(date) {
32136      var dayNumber = date.getDate();
32137      var monthNumber = date.getMonth();
32138      var dayOfTheWeek = DateFormatter.getDaysArray()[date.getDay()];
32139      var month = DateFormatter.getMonthNames()[monthNumber];
32140      dayOfTheWeek = dayOfTheWeek.slice(0, 3);
32141      month = month.slice(0, 3);
32142      var dateObj = {
32143        dayOfTheWeek: Utils.capitalize(dayOfTheWeek),
32144        day: dayNumber,
32145        month: Utils.capitalize(month)
32146      };
32147      return dateObj;
32148    }
32149  }, {
32150    key: 'filterServiceList',
32151    value: function filterServiceList(listService) {
32152      return listService.filter(function (service) {
32153        return DateFormatter.compareWithMinTime(DateFormatter.getNewFormattedDate(), service.saida);
32154      });
32155    }
32156  }, {
32157    key: 'getServiceTemplate',
32158    value: function getServiceTemplate(listService, callback) {
32159      var _this11 = this;
32160
32161      var content = [];
32162      InternalAPIService.getLogoMap(function (mapLogo) {
32163        for (var i = 0; i < listService.length; i++) {
32164          var service = listService[i];
32165          var dataSaidaSemHora = service.saida.split(' ')[0];
32166          var dataChegadaSemHora = service.chegada.split(' ')[0];
32167          var dataSaida = DateFormatter.getValidDateFormat(dataSaidaSemHora);
32168          var dataChegada = DateFormatter.getValidDateFormat(dataChegadaSemHora);
32169          var deeplink = {
32170            data_ida: dataSaidaSemHora.split('-').reverse().join(''),
32171            origem_id: service.origem.id,
32172            destino_id: service.destino.id,
32173            num_psgr: 1
32174          };
32175          var img = mapLogo[service.empresa];
32176          var departure = _this11.getDateObj(dataSaida);
32177          var arriving = _this11.getDateObj(dataChegada);
32178          var conditionImageOrText;
32179          var showCompany;
32180          var siteName = Utils.getSiteNameForClasses();
32181
32182          $.getJSON('/content/jca/' + siteName + '/jcr:content.classes.json').then(function (conditionImageOrText) {
32183            var obj = _this11.getName(conditionImageOrText, service);
32184            showCompany = obj.useName ? '<p class="company-name-text">' + obj.name + '</p>' : '<img class="company-logo" alt="' + obj.img.altText + '" src="' + obj.img.imgLogo + '"> ';
32185
32186            var template = '<li class="single-offer container">\n          <div class="row g-0">\n            <div class="col-3 align-self-center">\n              <div class="company-info-container">' + showCompany + '</div>\n            </div>\n            <div class="col-6 align-self-center">\n              <div class="time-information-container">\n                <div class="availability-container departure-section">\n                  <div class="day">' + departure.dayOfTheWeek + ' ' + departure.day + ' ' + departure.month + '</div>\n                  <div class="time">' + DateFormatter.extractHour(service.saida) + '</div>\n                </div>\n                <div class="separator">------</div>\n                <div class="availability-container arriving-section">\n                <div class="day">' + arriving.dayOfTheWeek + ' ' + arriving.day + ' ' + arriving.month + '</div>\n                <div class="time">' + DateFormatter.extractHour(service.chegada) + '</div>\n                </div>\n              </div>\n            </div>\n            <div class="col-3 align-self-center"><a class="show-more-container" id="show-more-container" href="' + $('#searchResultPath').val() + '?' + $.param(deeplink) + '"><span class="icon"><img src="' + $('[data-js="mapresulticon"]').val() + '" alt="' + $('[data-js="mapresultalttext"]').val() + '"></span>' + $('[data-js="translationviewmore"]').val() + '</a></div>\n          </div>\n        </li>';
32187            content.push(template);
32188          });
32189        }
32190
32191        if (callback) callback(content);
32192      });
32193    }
32194  }]);
32195
32196  return RouteMap;
32197}();
32198'use strict';
32199
32200var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); }
32200 else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
32201
32202var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
32203
32204function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
32205
32206var RepricingController = function () {
32207  function RepricingController($) {
32208    _classCallCheck(this, RepricingController);
32209
32210    this.user = SessionStorage.get('passenger');
32211    this.tripToRepricing = SessionStorage.get('tripToRepricing');
32212    this.remarkingavaibility = SessionStorage.get('remarkingavaibility');
32213    this.remarkingavaibilityFilter = [];
32214    this.linkReturn = $('[data-js="link-return"]');
32215    this.highlightUser = $('[data-js="highlight-user"]');
32216    this.selectAllDepartCheck = $('[data-js="select-all-depart-check"]');
32217    this.selectAllReturnCheck = $('[data-js="select-all-return-check"]');
32218    this.checkConfirmation = $('[data-js="check-confirmation"]');
32219    this.btnOpenConfirm = $('[data-js="btn-open-confirm"]');
32220    this.btnRequireRepricingTrip = $('[data-js="trip-repricing-next"]');
32221    this.btnSubmit = $('[data-js="btn-submit"]');
32222    this.closeConfiration = $('[data-js="close-confirmation"]');
32223    this.cancelGoingText = $('[data-js="cancel-going-text"]');
32224    this.cancelReturnText = $('[data-js="cancel-return-text"]');
32225    this.passGoingList = $('[data-js="passengers-going-list"]');
32226    this.passReturnList = $('[data-js="passengers-return-list"]');
32227    this.confirmContainerOverlay = $('[data-js="cancel-trip-confirmation-overlay"]');
32228    this.confirmContainer = $('[data-js="cancel-trip-confirmation"]');
32229    this.detailsContainer = $('[data-js="cancel-trip-details"]');
32230    this.checkboxGoingTrip = $('[data-js="check-going-trip"]');
32231    this.checkboxReturnTrip = $('[data-js="check-return-trip"]');
32232    this.btnBackTripRepricingSelect = $('[data-js="back-trip-repricing-select"]');
32233    this.btnConfCancelTrip = $('[data-js="trip-cancel-confirm"]');
32234    this.errMsgPassengerStatus = $('[data-js="msg-error-status-cancel"]');
32235    this.errMsgChildCancelTrip = $('[data-js="msg-child-error-cancel"]');
32236    this.isQuantityGoingChecked = true;
32237    this.isQuantityReturnChecked = true;
32238    this.listPassengersToRepricing;
32239    this.usersToRepricing = [];
32240    this.listPassengerRepricingGoing = 0;
32241    this.listPassengerrRepricingReturn = 0;
32242    this.isPassengerAlreadyRepricingGoing;
32243    this.isPassengerAlreadyRepricingReturn;
32244    this.isTripPayedPaymee = false;
32245    this.resumeRepricingTrip = new ResumeRepricingTripController($);
32246    this.breadcrumbRepricing = new BreadcrumbRepricingController($);
32247    this.departure = $('[data-js="input-date-departure"]');
32248    this.return = $('[data-js="input-date-return"]');
32249    this.dateMin = $('[data-js="input-date-departure"]').attr('data-date-min');
32250    this.repricingV2Active = $('[data-js="repricing-v2-active"]').data('active-repricing-v2');
32251    this.departureDateObject = {};
32252    this.returnDateObject = {};
32253    this.listTripToRepricing = [];
32254    this.listBlocked = [];
32255    this.ticketsRemarkingavaibility = [];
32256    this.going = [];
32257    this.goingConnection = [];
32258    this.tripReturn = [];
32259    this.tripReturnConnection = [];
32260    new AlertCreditCard($);
32261    this.init();
32262  }
32263
32264  _createClass(RepricingController, [{
32265    key: 'init',
32266    value: function init() {
32267      if (this.tripToRepricing) {
32268        this.removeCart();
32269        this.handleFreeTickets();
32270        this.displayDetails(this.remarkingavaibilityFilter);
32271        this.displayCannotBeRescheduled(this.listBlocked);
32272        this.loadDatepicker();
32273        this.handleReturn();
32274        this.handleCheckboxes();
32275        this.handleRepricingTrip();
32276        this.setTaxRefund();
32277        this.breadcrumbRepricing.handleBreadCrumbRepricingTrip();
32278        this.handlePassengerStatus();
32279        $('[data-js="image-points-giro-cart"]').hide();
32280      } else {
32281        $(location).attr('href', $('#myAccountPath').val());
32282      }
32283    }
32284  }, {
32285    key: 'removeCart',
32286    value: function removeCart() {
32287      SessionStorage.remove('cart');
32288    }
32289  }, {
32290    key: 'handleFreeTickets',
32291    value: function handleFreeTickets() {
32292      var _this = this;
32293
32294      this.tripToRepricing.forEach(function (elementTrip) {
32295        if (elementTrip) {
32296          elementTrip.forEach(function (elementTripInto) {
32297            _this.listTripToRepricing.push(elementTripInto);
32298          });
32299        }
32300      });
32301
32302      var getIndexOfObject = function getIndexOfObject(arr) {
32303        for (var _len = arguments.length, props = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
32304          props[_key - 1] = arguments[_key];
32305        }
32306
32307        return arr.findIndex(function (el) {
32308          return props.every(function (_ref) {
32309            var _ref2 = _slicedToArray(_ref, 2),
32310              key = _ref2[0],
32311              value = _ref2[1];
32312
32313            return el[key] === value;
32314          });
32315        });
32316      };
32317
32318      this.ticketsRemarkingavaibility = this.getTicketsRemarkingavaibility();
32319      this.ticketsRemarkingavaibility.forEach(function (elementRemark) {
32320        elementRemark.forEach(function (item) {
32321          _this.listTripToRepricing.filter(function (itemfilter) {
32322            if (item.id === itemfilter.id) {
32323              _this.listTripToRepricing.splice(getIndexOfObject(_this.listTripToRepricing, ['id', itemfilter.id]), 1);
32324              return;
32325            }
32326          });
32327        });
32328      });
32329
32330      this.listBlocked = this.listTripToRepricing;
32331    }
32332  }, {
32333    key: 'getTicketsRemarkingavaibility',
32334    value: function getTicketsRemarkingavaibility() {
32335      var _this2 = this;
32336
32337      var listTickets = [];
32338      this.remarkingavaibility.forEach(function (el) {
32339        el.forEach(function (subEl) {
32340          subEl.return.forEach(function (returnEl) {
32341            if (returnEl && returnEl.success && subEl.tickets) {
32342              _this2.remarkingavaibilityFilter.push(el);
32343              listTickets.push(subEl.tickets);
32344            }
32345          });
32346        });
32347      });
32348      return listTickets;
32349    }
32350  }, {
32351    key: 'insertDatepickerMobileStyle',
32352    value: function insertDatepickerMobileStyle() {
32353      var _this3 = this;
32354
32355      if (Utils.getWindowSize().width <= Utils.getWindowSize().breakpoints.LG) {
32356        var labelHeaderDatepicker = $('.input-date-container.active').children('.inner-container').attr('id') === 'input-container-dep' ? 'Data de ida' : 'Data de volta';
32357
32358        var header = $('<div class=\'datepicker-mobile datepicker-header\'>\n          <span data-js="datepicker-back-btn"><em class="jca-ico-angle-left" aria-hidden="true"></em></span>\n          <h4 class=\'header-datepicker\'>\n            ' + labelHeaderDatepicker + '\n          </h4>\n        </div>');
32359        var footer = $('<div class=\'datepicker-mobile datepicker-footer\'>\n          <button class=\'btn-conf-datepicker\'>\n Selecionar \n          </button>\n        </div>\n      ');
32360
32361        setTimeout(function () {
32362          header.prependTo("#ui-datepicker-div");
32363          footer.appendTo("#ui-datepicker-div");
32364          _this3.backToHome();
32365        }, "fast");
32366      } else {
32367        $('.datepicker-mobile').remove();
32368      }
32369    }
32370  }, {
32371    key: 'backToHome',
32372    value: function backToHome() {
32373      var _this4 = this;
32374
32375      if (Utils.getWindowSize().width <= Utils.getWindowSize().breakpoints.LG) {
32376        var isSelectDate = $('.ui-datepicker-current-day');
32377        $('.btn-conf-datepicker').click(function () {
32378          _this4.closeDatepicker();
32379        }).addClass('active');
32380
32381        $(document).on('click', '[data-js="datepicker-back-btn"]', function () {
32382          _this4.closeDatepicker();
32383        });
32384      }
32385    }
32386  }, {
32387    key: 'closeDatepicker',
32388    value: function closeDatepicker() {
32389      this.departure.datepicker("hide");
32390      this.return.datepicker("hide");
32391    }
32392  }, {
32393    key: 'setMonthsDatepicker',
32394    value: function setMonthsDatepicker(mobileNumberOfMonths, deskNumberOfMonths, element) {
32395      var isMobile = Utils.getWindowSize().width <= Utils.getWindowSize().breakpoints.LG;
32396      element.datepicker("option", "numberOfMonths", isMobile ? mobileNumberOfMonths : deskNumberOfMonths);
32397    }
32398  }, {
32399    key: 'closeDatepickerAfterSelect',
32400    value: function closeDatepickerAfterSelect(datepicker) {
32401      if (Utils.getWindowSize().width > Utils.getWindowSize().breakpoints.LG) {
32402        return datepicker.inline = false;
32403      }
32404    }
32405  }, {
32406    key: 'markPrevDate',
32407    value: function markPrevDate() {
32408      var _departureDateObject = this.departureDateObject,
32409        day = _departureDateObject.day,
32410        month = _departureDateObject.month,
32411        year = _departureDateObject.year;
32412
32413
32414      this.datepicker.find('td[data-month="' + month + '"][data-year="' + year + '"]').each(function () {
32415        var td = $(this);
32416        if (td.text().trim() === day.toString()) {
32417          $("a", td).addClass("ui-state-active");
32418        }
32419      });
32420    }
32421  }, {
32422    key: 'markDates',
32423    value: function markDates() {
32424      if (!this.departureDateObject.year || !this.returnDateObject.finalYear) {
32425        return;
32426      }
32427
32428      var _returnDateObject = this.returnDateObject,
32429        finalDay = _returnDateObject.finalDay,
32430        finalMonth = _returnDateObject.finalMonth,
32431        finalYear = _returnDateObject.finalYear;
32432      var _departureDateObject2 = this.departureDateObject,
32433        day = _departureDateObject2.day,
32434        month = _departureDateObject2.month,
32435        year = _departureDateObject2.year;
32436
32437
32438      this.datepicker.find('td[data-month="' + month + '"][data-year="' + year + '"]').each(function () {
32439        var td = $(this);
32440        if (td.text().trim() === day.toString()) {
32441          td.addClass("start-day");
32442          $("a", td).addClass("ui-state-active");
32443        }
32444      });
32445
32446      this.datepicker.find("td:not(.ui-datepicker-unselectable)").each(function () {
32447        var td = $(this);
32448        var tdDay = parseInt(td.text().trim());
32449        var tdMonth = td.data("month");
32450        var tdYear = td.data("year");
32451
32452        if (tdYear < finalYear) {
32453          td.addClass("is-between");
32454        } else if (tdYear === finalYear) {
32455          if (tdMonth == finalMonth) {
32456            if (tdDay < finalDay) {
32457              td.addClass("is-between");
32458            }
32459          } else if (tdMonth < finalMonth) {
32460            td.addClass("is-between");
32461          }
32462        }
32463
32464        if (tdDay === finalDay && tdMonth === finalMonth && tdYear === finalYear) {
32465          td.addClass("end-day");
32466        }
32467      });
32468    }
32469  }, {
32470    key: 'loadDatepicker',
32471    value: function loadDatepicker() {
32472      var _this5 = this;
32473
32474      this.departure.val("");
32475      this.departure.mask('99/99/9999');
32476      this.departure.datepicker({
32477        dateFormat: DateFormatter.getDateFormat(),
32478        minDate: this.dateMin && DateFormatter.getValidDateFormat(this.dateMin) > new Date() ? DateFormatter.getValidDateFormat(this.dateMin) : new Date(),
32479        showAnim: Utils.isMobile() ? '' : 'slideDown',
32480        autoClose: true,
32481        onChangeMonthYear: function onChangeMonthYear() {
32482          _this5.insertDatepickerMobileStyle();
32483          _this5.datepicker = $("#ui-datepicker-div");
32484
32485          setTimeout(function () {
32486            if (!$('.search-results-header').hasClass('active')) {
32487              var pickerWidth = $('#input-container-dep').width();
32488              _this5.datepicker.width(pickerWidth - 20);
32489            }
32490          }, 10);
32491        },
32492        beforeShow: function beforeShow(el, datepicker) {
32493          _this5.datepicker = $("#ui-datepicker-div");
32494          _this5.departure.closest(".input-date-container").addClass("active");
32495          _this5.insertDatepickerMobileStyle();
32496          _this5.setMonthsDatepicker(12, 1, _this5.departure);
32497          _this5.datepicker.addClass("opened");
32498
32499          if (Utils.getWindowSize().width < 951) $("#ui-datepicker-div").animate({ scrollTop: $(_this5).offset().top - 100 }, "fast");
32500
32501          setTimeout(function () {
32502            var left = Utils.getWindowSize().width - datepicker.dpDiv.outerWidth();
32503            var maxLeft = Math.min($(el).parent().offset().left, left);
32504            var dpTop = $(el).offset().top + $(el).outerHeight();
32505
32506            if ($('#change-way-overlay').is(':visible')) {
32507              $('#ui-datepicker-div').appendTo('#change-way-overlay');
32508              datepicker.dpDiv.css({ top: dpTop - 20 - window.scrollY, left: maxLeft });
32509              _this5.datepicker.addClass("on-overlay");
32510            } else {
32511              $("html, body").animate({ scrollTop: $(".search-container").offset().top - 100 }, 500);
32512              datepicker.dpDiv.css({ top: dpTop - 20, left: maxLeft });
32513            }
32514
32515            datepicker.dpDiv.width($(el).parent().width() - 20);
32516          }, 10);
32517        },
32518        onSelect: function onSelect(dateStr, datepicker) {
32519          setTimeout(function () {
32520            if (dateStr !== DateFormatter.parseDateFormat(new Date())) $('.ui-state-hover, .ui-widget-content .ui-state-hover').css('background', 'transparent'); else $('.ui-state-hover, .ui-widget-content .ui-state-hover').css('background', '#0b67b1');
32521          }, "fast");
32522
32523          datepicker.inline = true;
32524          _this5.insertDatepickerMobileStyle();
32525          _this5.closeDatepickerAfterSelect(datepicker);
32526          _this5.departure.data("date", DateFormatter.parseDateApiFormat(dateStr));
32527          _this5.return.datepicker("option", "minDate", dateStr);
32528          _this5.departure.parent().removeClass('has-invalid-input');
32529          _this5.departureDateObject = {
32530            day: parseInt(datepicker.selectedDay),
32531            month: datepicker.selectedMonth,
32532            year: datepicker.selectedYear
32533          };
32534        },
32535        onClose: function onClose(_, datepicker) {
32536          datepicker.inline = false;
32537          _this5.departure.closest(".input-date-container").removeClass("active");
32538          _this5.datepicker.removeClass("opened");
32539          _this5.datepicker.removeClass("header-datepicker");
32540          $('.search-results-header').removeClass('active');
32541          $('body, html').css('overflow-y', 'auto');
32542          _this5.handleNextStepToRepricing();
32543        }
32544      });
32545
32546      this.return.val("");
32547      this.return.mask('99/99/9999');
32548      this.return.datepicker({
32549        dateFormat: DateFormatter.getDateFormat(),
32550        minDate: this.dateMin && DateFormatter.getValidDateFormat(this.dateMin) > new Date() ? DateFormatter.getValidDateFormat(this.dateMin) : new Date(),
32551        showAnim: Utils.isMobile() ? '' : 'slideDown',
32552        onChangeMonthYear: function onChangeMonthYear(el, datepicker) {
32553          _this5.insertDatepickerMobileStyle();
32554          _this5.datepicker = $("#ui-datepicker-div");
32555
32556          setTimeout(function () {
32557            if (!$('.search-results-header').hasClass('active')) {
32558              var pickerWidth = $('#input-container-ret').width();
32559              _this5.datepicker.width(pickerWidth - 20);
32560            }
32561
32562            _this5.markPrevDate();
32563            _this5.markDates();
32564          }, 10);
32565        },
32566        beforeShow: function beforeShow(el, datepicker) {
32567          _this5.datepicker = $("#ui-datepicker-div");
32568          _this5.insertDatepickerMobileStyle();
32569          _this5.return.closest(".input-date-container").addClass("active");
32570          _this5.setMonthsDatepicker(12, 1, _this5.return);
32571          _this5.datepicker.addClass("opened");
32572          _this5.prevDateReturn = _this5.return.val();
32573
32574          if (Utils.getWindowSize().width < 951) $("#ui-datepicker-div").animate({ scrollTop: $(_this5).offset().top - 100 }, "fast");
32575
32576          setTimeout(function () {
32577            var dpDiv = datepicker.dpDiv;
32578
32579            var left = Utils.getWindowSize().width - dpDiv.outerWidth();
32580            var maxLeft = Math.min($(el).parent().offset().left, left);
32581            $('.btn-conf-datepicker').addClass('active');
32582            var dpTop = $(el).offset().top + $(el).outerHeight();
32583            _this5.markPrevDate();
32584
32585            if (_this5.returnDateObject.finalYear) _this5.markDates();
32586
32587            if ($('#change-way-overlay').is(':visible')) {
32588              $('#ui-datepicker-div').appendTo('#change-way-overlay');
32589              _this5.datepicker.addClass("on-overlay");
32590              dpDiv.css({ top: dpTop - 20 - window.scrollY, left: maxLeft });
32591            } else {
32592              $("html, body").animate({ scrollTop: $(".search-container").offset().top - 100 }, 500);
32593              dpDiv.css({ top: dpTop - 20, left: maxLeft });
32594            }
32595
32596            dpDiv.width($(el).parent().width() - 20);
32597          }, 10);
32598        },
32599        onSelect: function onSelect(dateStr, datepicker) {
32600          datepicker.inline = true;
32601          _this5.insertDatepickerMobileStyle();
32602          _this5.return.data("date", DateFormatter.parseDateApiFormat(dateStr));
32603          _this5.closeDatepickerAfterSelect(datepicker);
32604          _this5.returnDateObject = {
32605            finalDay: parseInt(datepicker.selectedDay),
32606            finalMonth: datepicker.selectedMonth,
32607            finalYear: datepicker.selectedYear
32608          };
32609
32610          setTimeout(function () {
32611            _this5.markPrevDate();
32612            _this5.markDates();
32613          });
32614        },
32615        onClose: function onClose(_, datepicker) {
32616          datepicker.inline = false;
32617          _this5.return.closest(".input-date-container").removeClass("active");
32618          _this5.datepicker.removeClass("opened");
32619          _this5.datepicker.removeClass("header-datepicker");
32620          $('.search-results-header').removeClass('active');
32621          $('body, html').css('overflow-y', 'auto');
32622          _this5.handleNextStepToRepricing();
32623        }
32624      });
32625
32626      this.departure.focusout(function (e) {
32627        var input = $(e.currentTarget);
32628        var dateString = input.val().split('/').reverse().join('/');
32629        var date = new Date(dateString);
32630        var today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
32631        if (isNaN(date) || date <= today) date = today;
32632        dateString = DateFormatter.parseDateFormat(date);
32633        if (!input.data("date") || input.data('date') != dateString) {
32634          input.data("date", DateFormatter.parseDateApiFormat(dateString));
32635        }
32636      });
32637
32638      this.return.focusout(function (e) {
32639        var input = $(e.currentTarget);
32640        if (input.val().length > 0) {
32641          var dateString = input.val().split('/').reverse().join('/');
32642          var date = new Date(dateString);
32643          var today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
32644          if (isNaN(date)) {
32645            input.val('');
32646          } else {
32647            if (date < today) date = today; else {
32648              var departureDate = new Date(_this5.departure.data('date').split('-').join('/'));
32649              if (date < departureDate) date = departureDate;
32650            }
32651            dateString = DateFormatter.parseDateFormat(date);
32652            if (!input.data("date") || input.data('date') != dateString) {
32653              input.data("date", DateFormatter.parseDateApiFormat(dateString));
32654              input.val(dateString);
32655            }
32656          }
32657        }
32658      });
32659
32660      $('[data-js="remove-date-return"]').click(function () {
32661        return _this5.removeReturn();
32662      });
32663    }
32664  }, {
32665    key: 'removeReturn',
32666    value: function removeReturn() {
32667      this.return.val("");
32668    }
32669  }, {
32670    key: 'displayCannotBeRescheduled',
32671    value: function displayCannotBeRescheduled(listTicketsBlocked) {
32672      if (this.listBlocked.length > 0) {
32673        var firstElem = listTicketsBlocked[0];
32674        var origin = Utils.capitalize(firstElem.originDescription);
32675        var destination = Utils.capitalize(firstElem.destinationDescription);
32676        var content = "";
32677
32678        $('[data-js="cant-reschedule-summary-origin"]').text(origin);
32679        $('[data-js="cant-reschedule-summary-destination"]').text(destination);
32680
32681        content += "<li class='passenger-item-list-cant-reschedule'>";
32682        listTicketsBlocked.forEach(function (el, i) {
32683          content += '<label>' + el.passengerName + '</label></br>';
32684        });
32685        content += "</li>";
32686
32687        $('[data-js="passenger-list-repricing-cant-reschedule"]').prepend(content);
32688      } else {
32689        $('.trip-cant-reschedule-container').addClass('d-none');
32690        $('.trip-repricing-container-passengers-cant-reschedule').addClass('d-none');
32691      }
32692    }
32693  }, {
32694    key: 'getServerTime',
32695    value: function getServerTime(callback) {
32696      var _this3 = this;
32697
32698      LoaderService.show();
32699      var url = $('#rootPath').val() + '/jcr:content.time.json?cache=1';
32700
32701      // Make an AJAX request to the specified URL
32702      return $.ajax({
32703        url: url,
32704        dataType: 'json',
32705        method: 'GET'
32706      }).then(function (data) {
32707        var time = data.result.time;
32708        var offset = data.result.offset;
32709
32710        time = time.replace("Z", "");
32711        var timezoneOffset = new Date(time).getTimezoneOffset();
32712
32713        // 180 is the difference between brasilia timezone and utc-0 in minutes
32714        time = timezoneOffset > 180 ? time : time + offset;
32715        _this3.timeExact = new Date(time);
32716        LoaderService.hide();
32717        callback(_this3.timeExact);
32718      }).catch(function (error) {
32719        console.error(err.message);
32720        _this3.timeExact = DateFormatter.getValidDateFormat();
32721        LoaderService.hide();
32722        callback(_this3.timeExact);
32723      });
32724    }
32725  }, {
32726    key: 'displayDetails',
32727    value: function displayDetails(listTrip) {
32728      var _this6 = this;
32729
32730      var goingArr = null;
32731      var goingConnectionArr = null;
32732      var returnArr = null;
32733      var returnConnectionArr = null;
32734
32735      listTrip.forEach(function (el) {
32736        if (el[0].going) {
32737          goingArr = el[0].tickets;
32738          _this6.going = goingArr;
32739        }
32740        if (el[0].goingConnection) {
32741          goingConnectionArr = el[0].tickets;
32742          _this6.goingConnection = goingConnectionArr;
32743        }
32744        if (el[0].tripReturn) {
32745          returnArr = el[0].tickets;
32746          _this6.tripReturn = returnArr;
32747        }
32748        if (el[0].tripReturnConnection) {
32749          returnConnectionArr = el[0].tickets;
32750          _this6.tripReturnConnection = returnConnectionArr;
32751        }
32752      });
32753
32754      if (!goingArr && !goingConnectionArr) $('.trip-going-container').addClass('d-none');
32755
32756      if (!returnArr && !returnConnectionArr) $('.trip-return-container').addClass('d-none');
32757
32758      this.appendGoing(goingArr, goingConnectionArr);
32759      this.appendReturn(goingArr, returnArr, returnConnectionArr);
32760    }
32761  }, {
32762    key: 'appendGoing',
32763    value: function appendGoing(goingArr, goingConnectionArr) {
32764      var _this7 = this;
32765
32766      var origin = void 0;
32767      var destination = void 0;
32768      var dateInit = void 0;
32769      var dateDepart = void 0;
32770      var hourDepart = void 0;
32771      var hourArrival = void 0;
32772      var passengers = void 0;
32773      var content = [];
32774      var count = 0;
32775
32776      if (goingArr) {
32777        var mainRegisterCode = goingArr[0].finder;
32778        origin = Utils.capitalize(goingArr[0].originDescription);
32779
32780        destination = Utils.capitalize(goingConnectionArr ? goingConnectionArr[0].destinationDescription : goingArr[0].destinationDescription);
32781
32782        dateInit = goingArr[0].departureDate;
32783        dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(dateInit));
32784        hourDepart = DateFormatter.extractHour(goingArr[0].departureDate);
32785        hourArrival = DateFormatter.extractHour(goingArr[0].arivalDate);
32786
32787        $('[data-js="num-code"]').text(mainRegisterCode);
32788        $('[data-js="going-summary"]').text('IDA - ' + dateDepart);
32789        $('[data-js="going-hour-depart"]').text(hourDepart);
32790        $('[data-js="going-summary-origin"]').text(origin).attr({
32791          'data-serviceId': goingArr[0].service,
32792          'data-id-origin': goingArr[0].originId,
32793          'data-id-destination': goingArr[0].destinationId,
32794          'data-origin-label': goingArr[0].originDescription,
32795          'data-destination-label': goingArr[0].destinationDescription
32796        });
32797        $('[data-js="going-hour-arrival"]').text(hourArrival);
32798        $('[data-js="going-summary-destination"]').text(destination);
32799        $('[data-js="going-summary-date-depart"]').text(DateFormatter.reverseDate(DateFormatter.extractDate(goingArr[0].departureDate)));
32800
32801        passengers = goingArr;
32802        var checkTripPayment = function checkTripPayment(passenger) {
32803          _this7.isTripPayedPaymee = passenger.paymentForm === 'PAYMEE' || passenger.paymentForm === 'PIX' || passenger.paymentForm === 'Pix' || passenger.paymentForm === 'PIX-ITAU';
32804        };
32805
32806        checkTripPayment(passengers);
32807
32808        if (passengers.length > 0) {
32809          $.each(passengers, function (i, el) {
32810            if (el.status || el.typeId === 1) {
32811              content.push('\n              <li class="passenger-item-list">\n                <div class="custom-control custom-checkbox">\n                  <input class="check-confimation custom-control-input check-passenger-trip" id="check-passenger-trip-' + i + '" data-document="' + el.passengerDocument + '" \n                    data-systemnumber-go="' + el.systemNumber + '" data-status="' + el.status + '" data-status-return="" data-type="' + _this7.getTypeNameById(el.typeId) + '" data-price-return="" \n                    data-price="' + (el.typeId === 1 ? 0 : el.amount) + '" data-saleid="' + el.id + '" data-saleid-return="" data-seat="' + el.seat + '" data-seat-return="" type="checkbox" \n                    data-js="check-passenger-trip">\n                  <label class="custom-control-label" for="check-passenger-trip-' + i + '">\n                    ' + el.passengerName + '\n                  </label>\n                </div>\n              </li>\n            ');
32812            } else if (el.status === 'SALE_NON_REFUNDABLE') {
32813              count++;
32814            }
32815          });
32816        } else {
32817          if (passengers.status || passengers.typeId === 1) {
32818            content.push('\n              <li class="passenger-item-list">\n                <div class="custom-control custom-checkbox">\n                  <input class="check-confimation custom-control-input check-passenger-trip" id="check-passenger-trip-' + passengers.id + '" data-document="' + passengers.passengerDocument + '" \n                    data-systemnumber-go="' + passengers.systemNumber + '" data-status="' + passengers.status + '" data-status-return="" data-type="' + this.getTypeNameById(passengers.typeId) + '" data-price-return="" \n                    data-price="' + (passengers.typeId === 1 ? 0 : passengers.amount) + '" data-saleid="' + passengers.id + '" data-saleid-return="" data-seat="' + passengers.seat + '" data-seat-return="" type="checkbox" \n                    data-js="check-passenger-trip">\n                  <label class="custom-control-label" for="check-passenger-trip-' + passengers.id + '">\n                    ' + passengers.passengerName + '\n                  </label>\n                </div>\n              </li>\n            ');
32819          }
32820        }
32821
32822        if (count === passengers.length) {
32823          $('.trip-going').find('.checkbox-all .left').empty();
32824          $('.trip-going').find('.checkbox-all .right').empty();
32825          $('.trip-going').find('.attention').show();
32826        } else {
32827          $('[data-js="passenger-list-repricing"]').prepend(content.join(''));
32828        }
32829
32830        //Going Connection Details
32831        if (goingConnectionArr) {
32832          passengers = goingConnectionArr;
32833
32834          if (passengers.length > 0) {
32835            $.each(passengers, function (i, el) {
32836              if (el.status || el.typeId === 1) {
32837                $('#check-passenger-trip-' + i).attr('data-seat-going-connection', el.seat);
32838                $('#check-passenger-trip-' + i).attr('data-price-going-connection', el.typeId === 1 ? 0 : el.amount);
32839                $('#check-passenger-trip-' + i).attr('data-status-going-connection', el.status);
32840                $('#check-passenger-trip-' + i).attr('data-saleid-going-connection', el.id);
32841                $('#check-passenger-trip-' + i).attr('data-systemnumber-go-connection', el.systemNumber);
32842                $('[data-js="going-summary-origin"]').attr({
32843                  'data-serviceId-conec': el.service,
32844                  'data-id-origin-conec': el.originId,
32845                  'data-id-destination': el.destinationId,
32846                  'data-origin-label-conec': el.originDescription,
32847                  'data-destination-label-conec': el.destinationDescription
32848                });
32849              }
32850            });
32851          } else if (passengers.status || passengers.typeId === 1) {
32852            $('#check-passenger-trip-' + passengers.id).attr('data-seat-going-connection', passengers.seat);
32853            $('#check-passenger-trip-' + passengers.id).attr('data-price-going-connection', passengers.typeId === 1 ? 0 : passengers.amount);
32854            $('#check-passenger-trip-' + passengers.id).attr('data-status-going-connection', passengers.status);
32855            $('#check-passenger-trip-' + passengers.id).attr('data-saleid-going-connection', passengers.id);
32856            $('#check-passenger-trip-' + passengers.id).attr('data-systemnumber-go-connection', passengers.systemNumber);
32857            $('[data-js="going-summary-origin"]').attr({
32858              'data-serviceId-conec': passengers.service,
32859              'data-id-origin-conec': passengers.originId,
32860              'data-id-destination': passengers.destinationId,
32861              'data-origin-label-conec': passengers.originDescription,
32862              'data-destination-label-conec': passengers.destinationDescription
32863            });
32864          }
32865        }
32866      }
32867    }
32868  }, {
32869    key: 'appendReturn',
32870    value: function appendReturn(goingArr, returnArr, returnConnectionArr) {
32871      var _this8 = this;
32872
32873      if (!returnArr || !Array.isArray(returnArr) || !returnArr[0] || !returnArr[0].departureDate) {
32874        $('[data-js="trip-repricing-return"]').hide();
32875        $('[data-js="trip-return"]').hide();
32876        return;
32877      }
32878
32879      var origin = void 0;
32880      var destination = void 0;
32881      var dateDepart = void 0;
32882      var hourDepart = void 0;
32883      var hourArrival = void 0;
32884      var passengers = void 0;
32885      var content = [];
32886      var count = 0;
32887
32888      if (!goingArr && returnArr && returnArr.length > 0) {
32889        var mainRegisterCode = returnArr[0].finder;
32890        origin = Utils.capitalize(returnArr[0].originDescription);
32891
32892        destination = Utils.capitalize(returnConnectionArr ? returnConnectionArr[0].destinationDescription : returnArr[0].destinationDescription);
32893
32894        dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(returnArr[0].departureDate));
32895        hourDepart = DateFormatter.extractHour(returnArr[0].departureDate);
32896        hourArrival = DateFormatter.extractHour(returnArr[0].arivalDate);
32897
32898        $('[data-js="trip-repricing-return"]').show();
32899        $('[data-js="trip-return"]').show();
32900        $('[data-js="num-code"]').text(mainRegisterCode);
32901        $('[data-js="return-summary"]').text('VOLTA - ' + dateDepart);
32902        $('[data-js="return-hour-depart"]').text(hourDepart);
32903        $('[data-js="return-summary-origin"]').text(origin).attr({
32904          'data-serviceId': returnArr[0].service,
32905          'data-id-origin': returnArr[0].originId,
32906          'data-id-destination': returnArr[0].destinationId,
32907          'data-origin-label': returnArr[0].originDescription,
32908          'data-destination-label': returnArr[0].destinationDescription
32909        });
32910        $('[data-js="return-hour-arrival"]').text(hourArrival);
32911        $('[data-js="return-summary-destination"]').text(destination);
32912        $('[data-js="going-summary-date-return"]').text(DateFormatter.reverseDate(DateFormatter.extractDate(returnArr[0].departureDate)));
32913
32914        passengers = returnArr;
32915        if (passengers.length > 0) {
32916          $.each(passengers, function (i, el) {
32917            if (el.status || el.typeId === 1) {
32918              content.push('\n              <li class="passenger-item-list">\n                <div class="custom-control custom-checkbox">\n                  <input class="check-confimation custom-control-input check-passenger-trip" id="check-passenger-trip-' + i + '" \n                    data-document="' + el.passengerDocument + '" data-systemnumber-back="' + el.systemNumber + '" data-status-return="' + el.status + '" \n                    data-type="' + _this8.getTypeNameById(el.typeId) + '" data-price-return="' + (el.typeId === 1 ? 0 : el.amount) + '" data-saleid-return="' + el.id + '" \n                    data-seat-return="' + el.seat + '" type="checkbox" data-js="check-passenger-trip">\n                  <label class="custom-control-label" for="check-passenger-trip-' + i + '">\n                    ' + el.passengerName + '\n                  </label>\n                </div>\n              </li>\n            ');
32919            } else if (el.status === 'SALE_NON_REFUNDABLE') {
32920              count++;
32921            }
32922          });
32923        } else {
32924          if (passengers.status || passengers.typeId === 1) {
32925            content.push('\n              <li class="passenger-item-list">\n                <div class="custom-control custom-checkbox">\n                  <input class="check-confimation custom-control-input check-passenger-trip" id="check-passenger-trip-' + passengers.id + '" \n                    data-document="' + passengers.passengerDocument + '" data-systemnumber-back="' + passengers.systemNumber + '" data-status-return="' + passengers.status + '" \n                    data-type="' + this.getTypeNameById(passengers.typeId) + '" data-price-return="' + (passengers.typeId === 1 ? 0 : passengers.amount) + '" data-saleid-return="' + passengers.id + '" \n                    data-seat-return="' + passengers.seat + '" type="checkbox" data-js="check-passenger-trip">\n                  <label class="custom-control-label" for="check-passenger-trip-' + passengers.id + '">\n                    ' + passengers.passengerName + '\n                  </label>\n                </div>\n              </li>\n            ');
32926          }
32927        }
32928
32929        if (count === passengers.length) {
32930          $('.trip-going').find('.checkbox-all .left').empty();
32931          $('.trip-going').find('.checkbox-all .right').empty();
32932          $('.trip-going').find('.attention').show();
32933        } else {
32934          $('[data-js="passenger-list-repricing"]').prepend(content.join(''));
32935        }
32936
32937        if (returnConnectionArr) {
32938          passengers = returnConnectionArr;
32939
32940          if (passengers.length > 0) {
32941            $.each(passengers, function (i, el) {
32942              if (el.status || el.typeId === 1) {
32943                $('#check-passenger-trip-' + i).attr('data-seat-return-connection', el.seat);
32944                $('#check-passenger-trip-' + i).attr('data-price-return-connection', el.typeId === 1 ? 0 : el.amount);
32945                $('#check-passenger-trip-' + i).attr('data-status-return-connection', el.status);
32946                $('#check-passenger-trip-' + i).attr('data-saleid-return-connection', el.id);
32947                $('#check-passenger-trip-' + i).attr('data-systemnumber-back-connection', el.systemNumber);
32948                $('[data-js="return-summary-origin"]').attr({
32949                  'data-serviceId-conec': el.service,
32950                  'data-id-origin-conec': el.originId,
32951                  'data-id-destination': el.destinationId,
32952                  'data-origin-label-conec': el.originDescription,
32953                  'data-destination-label-conec': el.destinationDescription
32954                });
32955              }
32956            });
32957          } else if (passengers.status || passengers.typeId === 1) {
32958            $('#check-passenger-trip').attr('data-seat-return-connection', passengers.seat);
32959            $('#check-passenger-trip-' + passengers.id).attr('data-price-return-connection', passengers.typeId === 1 ? 0 : passengers.amount);
32960            $('#check-passenger-trip-' + passengers.id).attr('data-status-return-connection', passengers.status);
32961            $('#check-passenger-trip-' + passengers.id).attr('data-saleid-return-connection', passengers.id);
32962            $('#check-passenger-trip-' + passengers.id).attr('data-systemnumber-back-connection', passengers.systemNumber);
32963            $('[data-js="return-summary-origin"]').attr({
32964              'data-serviceId-conec': passengers.service,
32965              'data-id-origin-conec': passengers.originId,
32966              'data-id-destination': passengers.destinationId,
32967              'data-origin-label-conec': passengers.originDescription,
32968              'data-destination-label-conec': passengers.destinationDescription
32969            });
32970          }
32971        }
32972      } else if (goingArr && returnArr && returnArr.length > 0) {
32973
32974        origin = Utils.capitalize(returnArr[0].originDescription);
32975
32976        destination = Utils.capitalize(returnConnectionArr ? returnConnectionArr[0].destinationDescription : returnArr[0].destinationDescription);
32977
32978        dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(returnArr[0].departureDate));
32979        hourDepart = DateFormatter.extractHour(returnArr[0].departureDate);
32980        hourArrival = DateFormatter.extractHour(returnArr[0].arivalDate);
32981
32982        $('[data-js="trip-repricing-return"]').show();
32983        $('[data-js="trip-return"]').show();
32984        $('[data-js="return-summary"]').text('VOLTA - ' + dateDepart);
32985        $('[data-js="return-hour-depart"]').text(hourDepart);
32986        $('[data-js="return-summary-origin"]').text(origin).attr({
32987          'data-serviceId': returnArr[0].service,
32988          'data-id-origin': returnArr[0].originId,
32989          'data-id-destination': returnArr[0].destinationId,
32990          'data-origin-label': returnArr[0].originDescription,
32991          'data-destination-label': returnArr[0].destinationDescription
32992        });
32993        $('[data-js="return-hour-arrival"]').text(hourArrival);
32994        $('[data-js="return-summary-destination"]').text(destination);
32995        $('[data-js="going-summary-date-return"]').text(DateFormatter.reverseDate(DateFormatter.extractDate(returnArr[0].departureDate)));
32996
32997        passengers = returnArr;
32998        if (passengers.length > 0) {
32999          $.each(passengers, function (i, el) {
33000            if (el.status || el.typeId === 1) {
33001              $('#check-passenger-trip-' + i).attr('data-seat-return', el.seat);
33002              $('#check-passenger-trip-' + i).attr('data-price-return', el.typeId === 1 ? 0 : el.amount);
33003              $('#check-passenger-trip-' + i).attr('data-status-return', el.status);
33004              $('#check-passenger-trip-' + i).attr('data-saleid-return', el.id);
33005              $('#check-passenger-trip-' + i).attr('data-saleid-return', el.id);
33006              $('#check-passenger-trip-' + i).attr('data-systemnumber-back', el.systemNumber);
33007            }
33008          });
33009        } else if (passengers.status || passengers.typeId === 1) {
33010          $('#check-passenger-trip-' + passengers.id).attr('data-seat-return', passengers.seat);
33011          $('#check-passenger-trip-' + passengers.id).attr('data-price-return', passengers.typeId === 1 ? 0 : passengers.amount);
33012          $('#check-passenger-trip-' + passengers.id).attr('data-status-return', passengers.status);
33013          $('#check-passenger-trip-' + passengers.id).attr('data-saleid-return', passengers.id);
33014          $('#check-passenger-trip-' + passengers.id).attr('data-saleid-return', passengers.id);
33015          $('#check-passenger-trip-' + passengers.id).attr('data-systemnumber-back', passengers.systemNumber);
33016        }
33017
33018        if (returnConnectionArr) {
33019          passengers = returnConnectionArr;
33020
33021          if (passengers.length > 0) {
33022            $.each(passengers, function (i, el) {
33023              if (el.status || el.typeId === 1) {
33024                $('#check-passenger-trip-' + i).attr('data-seat-return-connection', el.seat);
33025                $('#check-passenger-trip-' + i).attr('data-price-return-connection', el.typeId === 1 ? 0 : el.amount);
33026                $('#check-passenger-trip-' + i).attr('data-status-return-connection', el.status);
33027                $('#check-passenger-trip-' + i).attr('data-saleid-return-connection', el.id);
33028                $('#check-passenger-trip-' + i).attr('data-systemnumber-back-connection', el.systemNumber);
33029                $('[data-js="return-summary-origin"]').attr({
33030                  'data-serviceId-conec': el.service,
33031                  'data-id-origin-conec': el.originId,
33032                  'data-id-destination': el.destinationId,
33033                  'data-origin-label-conec': el.originDescription,
33034                  'data-destination-label-conec': el.destinationDescription
33035                });
33036              }
33037            });
33038          } else if (passengers.status || passengers.typeId === 1) {
33039            $('#check-passenger-trip').attr('data-seat-return-connection', passengers.seat);
33040            $('#check-passenger-trip-' + passengers.id).attr('data-price-return-connection', passengers.typeId === 1 ? 0 : passengers.amount);
33041            $('#check-passenger-trip-' + passengers.id).attr('data-status-return-connection', passengers.status);
33042            $('#check-passenger-trip-' + passengers.id).attr('data-saleid-return-connection', passengers.id);
33043            $('#check-passenger-trip-' + passengers.id).attr('data-systemnumber-back-connection', passengers.systemNumber);
33044            $('[data-js="return-summary-origin"]').attr({
33045              'data-serviceId-conec': passengers.service,
33046              'data-id-origin-conec': passengers.originId,
33047              'data-id-destination': passengers.destinationId,
33048              'data-origin-label-conec': passengers.originDescription,
33049              'data-destination-label-conec': passengers.destinationDescription
33050            });
33051          }
33052        }
33053      }
33054    }
33055  }, {
33056    key: 'getTypeNameById',
33057    value: function getTypeNameById(typeId) {
33058      switch (typeId) {
33059        case 1:
33060          return "CHILD";
33061        case 2:
33062          return "ADULT";
33063        case 5:
33064          return "CHILD_A";
33065      }
33066    }
33067  }, {
33068    key: 'handlePassengerStatusTripToShowInList',
33069    value: function handlePassengerStatusTripToShowInList() {
33070      $('[data-js="check-passenger-trip"]').each(function (_, el) {
33071        if ($(el).data('status') !== 'SALE_APPROVED' && $(el).data('status-return') !== 'SALE_APPROVED' || $(el).data('status') !== 'SALE_RELOCATED' && $(el).data('status-return') !== 'SALE_RELOCATED' || $(el).data('status') !== 'REMARCÁVEL' && $(el).data('status-return') !== 'REMARCÁVEL') {
33072          $(el).closest('.passenger-item-list').remove();
33073        }
33074      });
33075    }
33076  }, {
33077    key: 'handleReturn',
33078    value: function handleReturn() {
33079      this.linkReturn.click(function () {
33080        $(location).attr('href', 'my-account.html');
33081      });
33082    }
33083  }, {
33084    key: 'handleCheckboxes',
33085    value: function handleCheckboxes() {
33086      var _this9 = this;
33087
33088      //Check Quantity
33089      this.handlePassengersQuantity();
33090
33091      var changeReturnOnlyPassengers = function changeReturnOnlyPassengers(disable) {
33092        $('[data-js="check-passenger-trip"]').each(function (_, el) {
33093          if (disable) {
33094            if ($(el).data('status') !== 'SALE_APPROVED' && $(el).data('status') !== 'SALE_RELOCATED' && $(el).data('status') !== 'REMARCÁVEL') {
33095              if ($(el).is(':checked')) $(el).prop('checked', false);
33096              $(el).attr('disabled', true);
33097            } else if (($(el).data('status') === 'SALE_APPROVED' || $(el).data('status') === 'SALE_RELOCATED' || $(el).data('status') === 'REMARCÁVEL') && ($(el).data('status-return') !== 'SALE_APPROVED' || $(el).data('status-return') !== 'SALE_RELOCATED' || $(el).data('status-return') !== 'REMARCÁVEL') && !_this9.checkboxReturnTrip.is(':checked')) {
33098              if ($(el).prop('disabled') === true) $(el).attr('disabled', false);
33099            }
33100          } else {
33101            if (($(el).data('status') !== 'SALE_APPROVED' || $(el).data('status') !== 'SALE_RELOCATED' || $(el).data('status') !== 'REMARCÁVEL') && $(el).prop('disabled') === true) {
33102              $(el).attr('disabled', false);
33103            }
33104          }
33105        });
33106      };
33107
33108      var changeGoingOnlyPassengers = function changeGoingOnlyPassengers(disable) {
33109        $('[data-js="check-passenger-trip"]').each(function (_, el) {
33110          if (disable) {
33111            if ($(el).data('status-return') !== 'SALE_APPROVED' && $(el).data('status-return') !== 'SALE_RELOCATED' && $(el).data('status-return') !== 'REMARCÁVEL') {
33112              if ($(el).is(':checked')) $(el).prop('checked', false);
33113              $(el).attr('disabled', true);
33114            } else if (($(el).data('status-return') === 'SALE_APPROVED' || $(el).data('status-return') === 'SALE_RELOCATED' || $(el).data('status-return') === 'REMARCÁVEL') && ($(el).data('status') !== 'SALE_APPROVED' || $(el).data('status') !== 'SALE_RELOCATED' || $(el).data('status') !== 'REMARCÁVEL') && !_this9.checkboxGoingTrip.is(':checked')) {
33115              if ($(el).prop('disabled') === true) $(el).attr('disabled', false);
33116            }
33117          } else {
33118            if (($(el).data('status-return') !== 'SALE_APPROVED' || $(el).data('status-return') !== 'SALE_RELOCATED' || $(el).data('status-return') !== 'REMARCÁVEL') && $(el).prop('disabled') === true) {
33119              $(el).attr('disabled', false);
33120            }
33121          }
33122        });
33123      };
33124
33125      $('body').find('input[type="checkbox"]').change(function () {
33126        var atLeastOneCancel = false;
33127
33128        $('body').find('.check-passenger').each(function () {
33129          if ($(this).is(':checked')) {
33130            atLeastOneCancel = true;
33131          }
33132        });
33133      });
33134
33135      $('[data-js="input-date-departure"]').on('change', function () {
33136
33137        _this9.handleNextStepToRepricing();
33138      });
33139
33140      this.checkboxGoingTrip.on('change', function (e) {
33141        if ($(e.target).is(':checked')) {
33142          _this9.listPassengerRepricingGoing = 0;
33143          changeReturnOnlyPassengers(true);
33144          _this9.handlePassengerStatusForDep();
33145        } else {
33146          changeReturnOnlyPassengers(false);
33147          _this9.isPassengerAlreadyRepricingGoing = false;
33148        }
33149
33150        _this9.handleNextStepToRepricing();
33151      });
33152
33153      this.checkboxReturnTrip.on('change', function (e) {
33154        if ($(e.target).is(':checked')) {
33155          var $element = $(e.target);
33156          $element.data('status-return') !== 'SALE_APPROVED' || $element.data('status-return') !== 'SALE_RELOCATED' || $element.data('status-return') !== 'REMARCÁVEL' ? (_this9.listPassengerrRepricingReturn++, changeGoingOnlyPassengers(true)) : changeGoingOnlyPassengers(true);
33157        } else {
33158          changeGoingOnlyPassengers(false);
33159          _this9.isPassengerAlreadyRepricingReturn = false;
33160        }
33161
33162        _this9.handleNextStepToRepricing();
33163      });
33164
33165      $('[data-js="check-all-passenger-repricing-trip"]').change(function (e) {
33166        if ($(e.target).is(':checked')) {
33167          $('[data-js="check-passenger-trip"]:not(:checked)').trigger('click');
33168          return;
33169        } else {
33170          $('[data-js="check-passenger-trip"]:checked').trigger('click');
33171        }
33172      });
33173
33174      this.handlePassengerStatus();
33175    }
33176  }, {
33177    key: 'isGoingTripChecked',
33178    value: function isGoingTripChecked() {
33179      return this.checkboxGoingTrip.is(':checked');
33180    }
33181  }, {
33182    key: 'isReturnTripChecked',
33183    value: function isReturnTripChecked() {
33184      return this.checkboxReturnTrip.is(':checked');
33185    }
33186  }, {
33187    key: 'handleNextStepToRepricing',
33188    value: function handleNextStepToRepricing() {
33189      var isPassengerSelected = $('[data-js="check-passenger-trip"]').is(':checked');
33190
33191      if (this.isGoingTripChecked() || this.isReturnTripChecked()) {
33192        if (this.handlePassengerRepricing() && isPassengerSelected && this.hasDateSelected()) {
33193          this.eneableBtnNextStep();
33194        } else {
33195          this.disableBtnNextStep();
33196        }
33197      } else {
33198        this.disableBtnNextStep();
33199        this.hideMsgErrorPassengerAlreadyRepriced();
33200      }
33201    }
33202  }, {
33203    key: 'disablePassengers',
33204    value: function disablePassengers() {
33205      $('[data-js="check-passenger-trip"]').each(function (_, el) {
33206        if ($(el).data('status') !== 'SALE_APPROVED' || $(el).data('status-return') !== 'SALE_APPROVED' || $(el).data('status') !== 'SALE_RELOCATED' || $(el).data('status-return') !== 'SALE_RELOCATED' || $(el).data('status') !== 'REMARCÁVEL' || $(el).data('status-return') !== 'REMARCÁVEL') {
33207          $(el).attr('disabled', true);
33208        }
33209      });
33210    }
33211  }, {
33212    key: 'hasDateSelected',
33213    value: function hasDateSelected() {
33214      var inputDateValid = $('[data-js="input-date-departure"]').val() != '';
33215      var inputDateReturnValid = $('[data-js="input-date-return"]').val() != '';
33216
33217      if (this.isGoingTripChecked() && this.isReturnTripChecked() && !inputDateValid && !inputDateReturnValid) return false;
33218
33219      if (this.isGoingTripChecked() && !inputDateValid) return false;
33220
33221      if (this.isReturnTripChecked() && !inputDateReturnValid) return false;
33222
33223      return true;
33224    }
33225  }, {
33226    key: 'parseDateApiFormat',
33227    value: function parseDateApiFormat(date) {
33228      return date ? date.split("/").reverse().join("-") : '';
33229    }
33230  }, {
33231    key: 'requestDepartureServices',
33232    value: function requestDepartureServices() {
33233      var _this10 = this;
33234
33235      var isSeletecOnlyReturnTrip = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
33236      var isRepricingV2 = arguments[1];
33237
33238      return new Promise(function (resolve, reject) {
33239        var $elOrigin = isSeletecOnlyReturnTrip ? $('[data-js="return-summary-origin"]') : $('[data-js="going-summary-origin"]');
33240        var origin = +$elOrigin.attr('data-id-origin');
33241        var destination = +$elOrigin.attr('data-id-destination');
33242        var date = _this10.parseDateApiFormat(DateFormatter.reverseDate(isSeletecOnlyReturnTrip ? _this10.return.val() : _this10.departure.val()));
33243        var goingArr = null;
33244        var returnArr = null;
33245
33246        _this10.remarkingavaibilityFilter.forEach(function (el) {
33247          if (el[0].going) {
33248            goingArr = el[0].tickets;
33249          }
33250          if (el[0].tripReturn) {
33251            returnArr = el[0].tickets;
33252          }
33253        });
33254
33255        if (isRepricingV2) {
33256          var companyId = isSeletecOnlyReturnTrip ? returnArr[0].companyId : goingArr[0].companyId;
33257
33258          APIUtils.getAvailableTripsRepricing(origin, destination, date, companyId).then(function (data) {
33259            if (data.success) {
33260              SessionStorage.set("currentResultDep", Utils.sortArrayResultsWay(data.result));
33261              resolve();
33262            } else {
33263              var msg = data.result && data.result.result || $('[data-js="error-route-not-found"]').val();
33264              Alert.show(msg);
33265              reject();
33266            }
33267          }).catch(function (error) {
33268            Alert.show(error.message || $('[data-js="error-search-route-fail"]').val());
33269            console.log(error);
33270            reject();
33271          });
33272        } else {
33273          APIUtils.getAvailableTrips(origin, destination, date).then(function (data) {
33274            if (data.success) {
33275              SessionStorage.set("currentResultDep", Utils.sortArrayResultsWay(data.result));
33276              resolve();
33277            } else {
33278              var msg = data.result && data.result.result || typeof data.result === 'string' && data.result || $('[data-js="error-route-not-found"]').val();
33279              Alert.show(msg);
33280              reject();
33281            }
33282          }).catch(function (error) {
33283            Alert.show(error.message || $('[data-js="error-search-route-fail"]').val());
33284            console.log(error);
33285            reject();
33286          });
33287        }
33288      });
33289    }
33290  }, {
33291    key: 'requestReturnServices',
33292    value: function requestReturnServices(isRepricingV2) {
33293      var _this11 = this;
33294
33295      return new Promise(function (resolve, reject) {
33296        var $elOrigin = $('[data-js="return-summary-origin"]');
33297        var origin = +$elOrigin.attr('data-id-origin');
33298        var destination = +$elOrigin.attr('data-id-destination');
33299        var date = _this11.parseDateApiFormat(DateFormatter.reverseDate(_this11.return.val()));
33300
33301        if (isRepricingV2) {
33302          var companyId = _this11.tripReturn[0].companyId;
33303
33304          APIUtils.getAvailableTripsRepricing(origin, destination, date, companyId).then(function (data) {
33305            if (data.success) {
33306              SessionStorage.set('currentResultRet', Utils.sortArrayResultsWay(data.result));
33307              resolve();
33308            } else {
33309              var msg = data.result && data.result.result || $('[data-js="error-route-not-found"]').val();
33310              SessionStorage.set('currentResultRet', {});
33311              Alert.show(msg);
33312              reject();
33313            }
33314          }).catch(function (error) {
33315            SessionStorage.set('currentResultRet', {});
33316            Alert.show(error.message || $('[data-js="error-search-route-fail"]').val());
33317            console.log(error);
33318            reject();
33319          });
33320        } else {
33321          APIUtils.getAvailableTrips(origin, destination, date).then(function (data) {
33322            if (data.success) {
33323              SessionStorage.set('currentResultRet', Utils.sortArrayResultsWay(data.result));
33324              resolve();
33325            } else {
33326              var msg = data.result && data.result.result || typeof data.result === 'string' && data.result || $('[data-js="error-route-not-found"]').val();
33327              SessionStorage.set('currentResultRet', {});
33328              Alert.show(msg);
33329              reject();
33330            }
33331          }).catch(function (error) {
33332            SessionStorage.set('currentResultRet', {});
33333            Alert.show(error.message || $('[data-js="error-search-route-fail"]').val());
33334            console.log(error);
33335            reject();
33336          });
33337        }
33338      });
33339    }
33340  }, {
33341    key: 'setObject',
33342    value: function setObject() {
33343      var _this12 = this;
33344
33345      var isSeletecOnlyReturnTrip = !this.isGoingTripChecked();
33346      var functionsInPromises = [];
33347
33348      this.setFormData(isSeletecOnlyReturnTrip);
33349      this.setPassengers();
33350
33351      functionsInPromises.push(this.requestDepartureServices(isSeletecOnlyReturnTrip, this.repricingV2Active));
33352
33353      if (this.isReturnTripChecked() && !isSeletecOnlyReturnTrip) functionsInPromises.push(this.requestReturnServices(this.repricingV2Active));
33354
33355      Promise.all(functionsInPromises).then(function () {
33356        setTimeout(function () {
33357          _this12.redirectToSearchResult(isSeletecOnlyReturnTrip);
33358        }, 300);
33359      }).catch(function (err) {
33360        console.error(err);
33361      });
33362    }
33363  }, {
33364    key: 'redirectToSearchResult',
33365    value: function redirectToSearchResult() {
33366      var isSeletecOnlyReturnTrip = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
33367
33368      var place = isSeletecOnlyReturnTrip ? $('[data-js="return-summary-origin"]') : $('[data-js="going-summary-origin"]');
33369      var formData = SessionStorage.get('formData');
33370      var submitLocation = void 0;
33371
33372      var submitParams = {};
33373      submitParams.data_ida = isSeletecOnlyReturnTrip ? DateFormatter.reverseDate(this.return.val()) : DateFormatter.reverseDate(this.departure.val());
33374      submitParams.data_volta = this.return.val() && !isSeletecOnlyReturnTrip ? DateFormatter.reverseDate(this.return.val()) : null;
33375      submitParams.origem_id = +place.attr('data-id-origin');
33376      submitParams.destino_id = +place.attr('data-id-destination');
33377      submitParams.num_psgr = formData.passengers[0].quantity;
33378      submitParams.num_chda = formData.passengers[1].quantity;
33379      submitParams.num_chds = formData.passengers[2].quantity;
33380      submitParams.deep = false;
33381
33382      Utils.removeEmptyAttributes(submitParams);
33383      var submitQuerySring = $.param(submitParams);
33384
33385      SessionStorage.set('isSeletecOnlyReturnTrip', isSeletecOnlyReturnTrip);
33386      if (this.repricingV2Active) {
33387        SessionStorage.set("repricingv2", true);
33388        submitLocation = $('#rescheduleSearchResultPathV2').val() + '?' + submitQuerySring;
33389      } else {
33390        submitLocation = $('#rescheduleSearchResultPath').val() + '?' + submitQuerySring;
33391      }
33392
33393      setTimeout(function () {
33394        $(location).attr('href', submitLocation);
33395      }, 300);
33396    }
33397  }, {
33398    key: 'setFormData',
33399    value: function setFormData(isSeletecOnlyReturnTrip) {
33400      var formData = this.getFormObject(isSeletecOnlyReturnTrip);
33401      SessionStorage.set('formData', formData);
33402    }
33403  }, {
33404    key: 'getMinDateDeparture',
33405    value: function getMinDateDeparture() {
33406      return DateFormatter.getNewFormattedDate();
33407    }
33408  }, {
33409    key: 'setPassengers',
33410    value: function setPassengers() {
33411      var passengers = this.getPassengers();
33412
33413      if (this.repricingV2Active) {
33414        var dataToRepricing = this.toJSONDataToRepricing(passengers);
33415
33416        SessionStorage.set('passengersToRepricing', dataToRepricing);
33417      } else {
33418        SessionStorage.set('passengersToRepricing', passengers);
33419      }
33420    }
33421  }, {
33422    key: 'toJSONDataToRepricing',
33423    value: function toJSONDataToRepricing(passengers) {
33424      var _this13 = this;
33425
33426      var passengerArr = [];
33427      var isDepartureConnection = this.goingConnection;
33428      var isReturnConnection = this.tripReturnConnection;
33429      var isSeletecOnlyReturnTrip = !this.isGoingTripChecked();
33430
33431      var getPassengesToRepricing = function getPassengesToRepricing() {
33432        var passengersControlsAttr = _this13.remarkingavaibilityFilter;
33433        var isDeparture = $('[data-js="check-going-trip"]').is(':checked');
33434        var isReturn = $('[data-js="check-return-trip"]').is(':checked');
33435
33436        passengers.forEach(function (el) {
33437          var indexPassenger = el.indexPassenger.replace(/\D/g, '');
33438          var passenger = {
33439            name: el.name,
33440            type: el.type,
33441            document: el.documentNumber
33442
33443            //TODO
33444          }; passengersControlsAttr.forEach(function (element) {
33445            if (isDeparture && element[0].going) {
33446              passenger.controlDeparture = element[0].return[indexPassenger].result;
33447              passenger.systemNumberDeparture = el.systemNumberDeparture;
33448            }
33449
33450            if (isDepartureConnection && element[0].goingConnection) {
33451              passenger.controlDepartureConnection = element[0].return[indexPassenger].result;
33452              passenger.systemNumberDepartureConnection = el.systemNumberDepartureConnection;
33453            }
33454
33455            if (isReturn && element[0].tripReturn) {
33456              passenger.controlReturn = element[0].return[indexPassenger].result;
33457              passenger.systemNumberReturn = el.systemNumberReturn;
33458            }
33459
33460            if (isReturnConnection && element[0].tripReturnConnection) {
33461              passenger.controlReturnConnection = element[0].return[indexPassenger].result;
33462              passenger.systemNumberReturnConnection = el.systemNumberReturnConnection;
33463            }
33464          });
33465
33466          passengerArr.push(passenger);
33467        });
33468
33469        return passengerArr;
33470      };
33471
33472      var isDepartureOnly = !$('[data-js="check-return-trip"]').is(':checked');
33473      // const { finder, departureDate, destinationDescription, originDescription } = (isDepartureOnly? this.going[0] : )
33474
33475      var _ref3 = isSeletecOnlyReturnTrip ? this.tripReturn[0] : this.going[0],
33476        finder = _ref3.finder,
33477        departureDate = _ref3.departureDate,
33478        destinationDescription = _ref3.destinationDescription,
33479        originDescription = _ref3.originDescription;
33480
33481      var dataToRepricing = {
33482        depart: {
33483          departureDate: departureDate,
33484          origin: originDescription,
33485          destination: destinationDescription
33486        },
33487        isDepartureOnly: isDepartureOnly,
33488        finderTrip: finder
33489      };
33490
33491      if (!isDepartureOnly) {
33492        var tripReturn = this.tripReturn[0];
33493
33494        dataToRepricing.return = {
33495          departureDate: tripReturn.departureDate,
33496          origin: destinationDescription,
33497          destination: originDescription
33498        };
33499      }
33500
33501      dataToRepricing.passengers = getPassengesToRepricing();
33502
33503      return dataToRepricing;
33504    }
33505  }, {
33506    key: 'getPassengers',
33507    value: function getPassengers() {
33508      var passengers = [];
33509
33510      $('[data-js="check-passenger-trip"]:checked').each(function (_, el) {
33511        var systemNumberDeparture = $(el).attr('data-systemnumber-go') ? $(el).attr('data-systemnumber-go') : null;
33512        var systemNumberDepartureConnection = $(el).attr('data-systemnumber-go-connection') ? $(el).attr('data-systemnumber-go-connection') : null;
33513        var systemNumberReturn = $(el).attr('data-systemnumber-back') ? $(el).attr('data-systemnumber-back') : null;
33514        var systemNumberReturnConnection = $(el).attr('data-systemnumber-back-connection') ? $(el).attr('data-systemnumber-back-connection') : null;
33515
33516        var passenger = {
33517          name: $(el).next().text().trim(),
33518          type: $(el).attr('data-type'),
33519          documentNumber: $(el).attr('data-document'),
33520          indexPassenger: $(el).attr('id'),
33521          systemNumberDeparture: systemNumberDeparture,
33522          systemNumberDepartureConnection: systemNumberDepartureConnection,
33523          systemNumberReturn: systemNumberReturn,
33524          systemNumberReturnConnection: systemNumberReturnConnection
33525        };
33526
33527        passengers.push(passenger);
33528      });
33529
33530      return passengers;
33531    }
33532  }, {
33533    key: 'getFormObject',
33534    value: function getFormObject(isSeletecOnlyReturnTrip) {
33535      var _this14 = this;
33536
33537      var regexRemoveUF = new RegExp(/\s{1}(\([A-Z]{2}\))/g);
33538
33539      var passengers = function passengers() {
33540        var adult_qtt = 0;
33541        var child_a_qtt = 0;
33542        var child_qtt = 0;
33543
33544        $('[data-js="check-passenger-trip"]:checked').each(function (_, el) {
33545          if (isSeletecOnlyReturnTrip) {
33546
33547            if ($(el).data('statusReturn') == 'SALE_APPROVED' || $(el).data('statusReturn') == 'SALE_RELOCATED' || $(el).data('statusReturn') == 'REMARCÁVEL') {
33548              adult_qtt += $(el).data('type') === 'ADULT' ? 1 : 0;
33549              child_a_qtt += $(el).data('type') === 'CHILD_A' ? 1 : 0;
33550              child_qtt += $(el).data('type') === 'CHILD' ? 1 : 0;
33551            }
33552          } else {
33553
33554            if ($(el).data('status') == 'SALE_APPROVED' || $(el).data('status') == 'SALE_RELOCATED' || $(el).data('status') == 'REMARCÁVEL') {
33555              adult_qtt += $(el).data('type') === 'ADULT' ? 1 : 0;
33556              child_a_qtt += $(el).data('type') === 'CHILD_A' ? 1 : 0;
33557              child_qtt += $(el).data('type') === 'CHILD' ? 1 : 0;
33558            }
33559          }
33560        });
33561
33562        return [{ order: 0, type: "ADULT", quantity: adult_qtt }, { order: 1, type: "CHILD_A", quantity: child_a_qtt }, { order: 3, type: "CHILD", quantity: child_qtt }];
33563      };
33564
33565      var departureTrip = function departureTrip() {
33566        var isSeletecOnlyReturnTrip = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
33567
33568        var place = isSeletecOnlyReturnTrip ? $('[data-js="return-summary-origin"]') : $('[data-js="going-summary-origin"]');
33569
33570        return {
33571          date: isSeletecOnlyReturnTrip ? DateFormatter.reverseDate(_this14.return.val()) : DateFormatter.reverseDate(_this14.departure.val()),
33572          minDate: _this14.getMinDateDeparture(),
33573          origin: {
33574            id: +place.attr('data-id-origin'),
33575            label: place.attr('data-origin-label').replace(regexRemoveUF, ''),
33576            uf: place.attr('data-origin-label').split('-')[1].trim(),
33577            address: null
33578          },
33579          destination: {
33580            id: +place.attr('data-id-destination'),
33581            label: place.attr('data-destination-label-conec') ? place.attr('data-destination-label-conec').replace(regexRemoveUF, '') : place.attr('data-destination-label').replace(regexRemoveUF, ''),
33582            uf: place.attr('data-destination-label-conec') ? place.attr('data-destination-label-conec').split('-')[1].trim() : place.attr('data-destination-label').split('-')[1].trim(),
33583            address: null
33584          }
33585        };
33586      };
33587
33588      var returnTrip = function returnTrip() {
33589        var returnChecked = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
33590
33591        var place = $('[data-js="return-summary-origin"]');
33592
33593        return {
33594          date: returnChecked ? DateFormatter.reverseDate(_this14.return.val()) : null,
33595          minDate: returnChecked ? _this14.getMinDateDeparture() : null,
33596          origin: {
33597            id: returnChecked ? +place.attr('data-id-origin') : null,
33598            label: returnChecked ? place.attr('data-origin-label').replace(regexRemoveUF, '') : null,
33599            uf: returnChecked ? place.attr('data-origin-label').split('-')[1].trim() : null,
33600            address: null
33601          },
33602          destination: {
33603            id: returnChecked ? +place.attr('data-id-destination') : null,
33604            label: returnChecked ? place.attr('data-destination-label-conec') ? place.attr('data-destination-label-conec').replace(regexRemoveUF, '') : place.attr('data-destination-label').replace(regexRemoveUF, '') : null,
33605            uf: returnChecked ? place.attr('data-destination-label-conec') ? place.attr('data-destination-label-conec').split('-')[1].trim() : place.attr('data-destination-label').split('-')[1].trim() : null,
33606            address: null
33607          }
33608        };
33609      };
33610
33611      return {
33612        passengers: passengers(),
33613        departureOnly: this.isGoingTripChecked() && this.isReturnTripChecked() ? false : true,
33614        depart: isSeletecOnlyReturnTrip ? returnTrip(this.isReturnTripChecked()) : departureTrip(isSeletecOnlyReturnTrip),
33615        return: isSeletecOnlyReturnTrip ? returnTrip(false) : returnTrip(this.isReturnTripChecked())
33616      };
33617    }
33618  }, {
33619    key: 'handleRepricingTrip',
33620    value: function handleRepricingTrip() {
33621      var _this15 = this;
33622
33623      this.btnRequireRepricingTrip.click(function () {
33624        var repricingV2IsActive = _this15.repricingV2Active;
33625
33626        _this15.setObject();
33627      });
33628    }
33629  }, {
33630    key: 'handlePassengersQuantity',
33631    value: function handlePassengersQuantity() {
33632      var passengersGoingRequirements = this.getPassengerTypeQttListGoing();
33633      var passengersReturnRequirements = this.getPassengerTypeQttListReturn();
33634
33635      this.sumQuantityGoing(passengersGoingRequirements);
33636      this.sumQuantityReturn(passengersReturnRequirements);
33637    }
33638  }, {
33639    key: 'getSelectedPassengers',
33640    value: function getSelectedPassengers() {
33641      self = this;
33642      self.usersToRepricing = [];
33643      var selectedPassengers = { going: [], return: [] };
33644
33645      $('[data-js="passenger-list-repricing"]').find('.check-passenger-trip').each(function () {
33646        if ($(this).is(':checked') && !selectedPassengers.going.includes($(this).next().text()) && !selectedPassengers.return.includes($(this).next().text())) {
33647          if ($('[data-js="check-going-trip"]').is(':checked')) {
33648            selectedPassengers.going.push({ "name": $(this).next().text().trim(), "seat": $(this).data('seat'), "price": $(this).data('price'), "type": $(this).data('type'), "priceConnection": $(this).data('price-going-connection'), "seatConnection": $(this).data('seat-going-connection') });
33649          }
33650
33651          if ($('[data-js="check-return-trip"]').is(':checked')) {
33652            selectedPassengers.return.push({ "name": $(this).next().text().trim(), "seat": $(this).data('seat-return'), "price": $(this).data('price-return'), "priceConnection": $(this).data('price-return-connection'), "seatConnection": $(this).data('seat-return-connection') });
33653          }
33654        }
33655      });
33656
33657      return selectedPassengers;
33658    }
33659  }, {
33660    key: 'getPassengerTypeQttListGoing',
33661    value: function getPassengerTypeQttListGoing() {
33662      var reg_qtt_going = 0;
33663      var chd_a_qtt_going = 0;
33664      var chd_qtt_going = 0;
33665
33666      $('[data-js="check-passenger-trip"]').each(function (_, el) {
33667        if ($(el).data('status') == 'SALE_APPROVED' || $(el).data('status') == 'SALE_RELOCATED' || $(el).data('status') == 'REMARCÁVEL') {
33668          reg_qtt_going += $(el).data('type') === 'ADULT' ? 1 : 0;
33669          chd_a_qtt_going += $(el).data('type') === 'CHILD_A' ? 1 : 0;
33670          chd_qtt_going += $(el).data('type') === 'CHILD' ? 1 : 0;
33671        }
33672      });
33673
33674      return { reg_qtt_going: reg_qtt_going, chd_a_qtt_going: chd_a_qtt_going, chd_qtt_going: chd_qtt_going };
33675    }
33676  }, {
33677    key: 'getPassengerTypeQttListReturn',
33678    value: function getPassengerTypeQttListReturn() {
33679      var reg_qtt_return = 0;
33680      var chd_a_qtt_return = 0;
33681      var chd_qtt_return = 0;
33682
33683      $('[data-js="check-passenger-trip"]').each(function (_, el) {
33684        if ($(el).data('status-return') == 'SALE_APPROVED' || $(el).data('status-return') == 'SALE_RELOCATED' || $(el).data('status-return') == 'REMARCÁVEL') {
33685          reg_qtt_return += $(el).data('type') === 'ADULT' ? 1 : 0;
33686          chd_a_qtt_return += $(el).data('type') === 'CHILD_A' ? 1 : 0;
33687          chd_qtt_return += $(el).data('type') === 'CHILD' ? 1 : 0;
33688        }
33689      });
33690
33691      return { reg_qtt_return: reg_qtt_return, chd_a_qtt_return: chd_a_qtt_return, chd_qtt_return: chd_qtt_return };
33692    }
33693  }, {
33694    key: 'sumQuantityGoing',
33695    value: function sumQuantityGoing(requirements) {
33696      var _this16 = this;
33697
33698      var reg_qtt_going = requirements.reg_qtt_going,
33699        chd_a_qtt_going = requirements.chd_a_qtt_going,
33700        chd_qtt_going = requirements.chd_qtt_going;
33701
33702
33703      $('[data-js="passenger-list-cancel"]').find('input[type="checkbox"]').change(function (e) {
33704        if ($(e.target).data('status') === 'SALE_APPROVED' || $(e.target).data('status') === 'SALE_RELOCATED' || $(e.target).data('status') === 'REMARCÁVEL') {
33705          var passengerType = $(e.target).data('type');
33706          var isChecked = $(e.target).is(':checked');
33707
33708          switch (passengerType) {
33709            case 'ADULT':
33710              if (isChecked) {
33711                reg_qtt_going--;
33712              } else {
33713                reg_qtt_going++;
33714              }
33715              break;
33716
33717            case 'CHILD_A':
33718              if (isChecked) {
33719                chd_a_qtt_going--;
33720              } else {
33721                chd_a_qtt_going++;
33722              }
33723              break;
33724
33725            case 'CHILD':
33726              if (isChecked) {
33727                chd_qtt_going--;
33728              } else {
33729                chd_qtt_going++;
33730              }
33731              break;
33732          }
33733
33734          if (reg_qtt_going < chd_a_qtt_going || reg_qtt_going < chd_qtt_going) {
33735            _this16.isQuantityGoingChecked = false;
33736          } else {
33737            _this16.isQuantityGoingChecked = true;
33738          }
33739        }
33740      });
33741    }
33742  }, {
33743    key: 'sumQuantityReturn',
33744    value: function sumQuantityReturn(requirements) {
33745      var _this17 = this;
33746
33747      var reg_qtt_return = requirements.reg_qtt_return,
33748        chd_a_qtt_return = requirements.chd_a_qtt_return,
33749        chd_qtt_return = requirements.chd_qtt_return;
33750
33751
33752      $('[data-js="passenger-list-cancel"]').find('input[type="checkbox"]').change(function (e) {
33753        if ($(e.target).data('status-return') === 'SALE_APPROVED' || $(e.target).data('status-return') === 'SALE_RELOCATED' || $(e.target).data('status-return') === 'REMARCÁVEL') {
33754          var passengerType = $(e.target).data('type');
33755          var isChecked = $(e.target).is(':checked');
33756
33757          switch (passengerType) {
33758            case 'ADULT':
33759              if (isChecked) {
33760                reg_qtt_return--;
33761              } else {
33762                reg_qtt_return++;
33763              }
33764              break;
33765
33766            case 'CHILD_A':
33767              if (isChecked) {
33768                chd_a_qtt_return--;
33769              } else {
33770                chd_a_qtt_return++;
33771              }
33772              break;
33773
33774            case 'CHILD':
33775              if (isChecked) {
33776                chd_qtt_return--;
33777              } else {
33778                chd_qtt_return++;
33779              }
33780              break;
33781          }
33782
33783          if (reg_qtt_return < chd_a_qtt_return || reg_qtt_return < chd_qtt_return) {
33784            _this17.isQuantityReturnChecked = false;
33785          } else {
33786            _this17.isQuantityReturnChecked = true;
33787          }
33788        }
33789      });
33790    }
33791  }, {
33792    key: 'eneableBtnNextStep',
33793    value: function eneableBtnNextStep() {
33794      this.btnRequireRepricingTrip.attr('disabled', false);
33795    }
33796  }, {
33797    key: 'disableBtnNextStep',
33798    value: function disableBtnNextStep() {
33799      this.btnRequireRepricingTrip.attr('disabled', true);
33800    }
33801  }, {
33802    key: 'setTaxRefund',
33803    value: function setTaxRefund() {
33804      var taxRefundValue = $('[data-js="tax-refund-attr"]').val();
33805
33806      $('[data-js="tax-refund"]').text(taxRefundValue + '%');
33807    }
33808  }, {
33809    key: 'loadConfirmationPage',
33810    value: function loadConfirmationPage() {
33811      this.listPassengersToRepricing = this.getSelectedPassengers();
33812
33813      var goingArr = null;
33814      var returnArr = null;
33815
33816      this.remarkingavaibilityFilter.forEach(function (el) {
33817        if (el[0].going) {
33818          goingArr = el[0].tickets;
33819        }
33820        if (el[0].tripReturn) {
33821          returnArr = el[0].tickets;
33822        }
33823      });
33824
33825      this.passGoingList.empty();
33826      this.passReturnList.empty();
33827      $('[data-js="passengers-going"]').hide();
33828      $('[data-js="passengers-return"]').hide();
33829      var content = [];
33830
33831      var origin = goingArr[0].originDescription;
33832      var destination = goingArr[0].destinationDescription;
33833      var dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(goingArr[0].departureDate));
33834      var hourDepart = DateFormatter.extractHour(goingArr[0].departureDate);
33835
33836      if (this.listPassengersToRepricing.going.length > 0) {
33837        $('[data-js="passengers-going"]').show();
33838        this.cancelGoingText.text('(' + origin + ' - ' + destination + ') - ' + dateDepart + ' - ' + hourDepart + '');
33839        $.each(this.listPassengersToRepricing.going, function (_, el) {
33840          return content.push('<li class="passenger-name">' + el + '</li>');
33841        });
33842        this.passGoingList.append(content.join(''));
33843      }
33844
33845      if (this.listPassengersToRepricing.return.length > 0) {
33846        origin = returnArr[0].originDescription;
33847        destination = returnArr[0].destinationDescription;
33848        dateDepart = DateFormatter.reverseDate(DateFormatter.extractDate(returnArr[0].departureDate));
33849        hourDepart = DateFormatter.extractHour(returnArr[0].departureDate);
33850        content = [];
33851
33852        $('[data-js="passengers-return"]').show();
33853        this.cancelReturnText.text('(' + origin + ' - ' + destination + ') - ' + dateDepart + ' - ' + hourDepart + '');
33854        $.each(this.listPassengersToRepricing.return, function (_, el) {
33855          return content.push('<li class="passenger-name">' + el + '</li>');
33856        });
33857        this.passReturnList.append(content.join(''));
33858      }
33859    }
33860  }, {
33861    key: 'removeListPassengerResumeTrip',
33862    value: function removeListPassengerResumeTrip() {
33863      $('[data-js="departure-section"]').find('[data-js="trip-details-show-passenger"]').hide();
33864      $('[data-js="return-section"]').find('[data-js="trip-details-show-passenger"]').hide();
33865    }
33866  }, {
33867    key: 'showMsgErrorPassengerAlreadyRepricing',
33868    value: function showMsgErrorPassengerAlreadyRepricing(msgError) {
33869      this.errMsgPassengerStatus.text(msgError).parent().show();
33870    }
33871  }, {
33872    key: 'hideMsgErrorPassengerAlreadyRepriced',
33873    value: function hideMsgErrorPassengerAlreadyRepriced() {
33874      this.errMsgPassengerStatus.parent().hide();
33875    }
33876  }, {
33877    key: 'showChildMsgErrorCancelTrip',
33878    value: function showChildMsgErrorCancelTrip() {
33879      this.errMsgChildCancelTrip.text(i18n('err_msg_cancel')).parent().show();
33880    }
33881  }, {
33882    key: 'handlePassengerStatus',
33883    value: function handlePassengerStatus() {
33884      var _this18 = this;
33885
33886      $('[data-js="check-passenger-trip"]').on('change', function (e) {
33887        var $element = $(e.target);
33888
33889        if ($element.is(':checked')) {
33890          $element.data('status') !== 'SALE_APPROVED' || $element.data('status') !== 'SALE_RELOCATED' || $element.data('status') !== 'REMARCÁVEL' ? _this18.listPassengerRepricingGoing++ : '';
33891          $element.data('status-return') !== 'SALE_APPROVED' || $element.data('status-return') !== 'SALE_RELOCATED' ? _this18.listPassengerrRepricingReturn++ : '';
33892        } else {
33893          $element.data('status') !== 'SALE_APPROVED' || $element.data('status') !== 'SALE_RELOCATED' || $element.data('status') !== 'REMARCÁVEL' ? _this18.listPassengerRepricingGoing-- : '';
33894          $element.data('status-return') !== 'SALE_APPROVED' || $element.data('status-return') !== 'SALE_RELOCATED' ? _this18.listPassengerrRepricingReturn-- : '';
33895        }
33896
33897        if (_this18.checkboxGoingTrip.is(':checked')) {
33898          _this18.checkboxGoingTrip.trigger('change');
33899        }
33900
33901        if (_this18.checkboxReturnTrip.is(':checked')) {
33902          _this18.checkboxReturnTrip.trigger('change');
33903        }
33904      });
33905    }
33906  }, {
33907    key: 'handlePassengerStatusForDep',
33908    value: function handlePassengerStatusForDep() {
33909      this.listPassengerRepricingGoing > 0 ? this.isPassengerAlreadyRepricingGoing = true : this.isPassengerAlreadyRepricingGoing = false;
33910    }
33911  }, {
33912    key: 'handlePassengerStatusForReturn',
33913    value: function handlePassengerStatusForReturn($element) {
33914      if (!this.isPassengerAlreadyRepricingReturn && $element.is(':checked')) {
33915        $element.data('status-return') !== 'SALE_APPROVED' || $element.data('status-return') !== 'SALE_RELOCATED' || $element.data('status-return') !== 'REMARCÁVEL' ? this.listPassengerrRepricingReturn++ : '';
33916      } else {
33917        $element.data('status-return') !== 'SALE_APPROVED' || $element.data('status-return') !== 'SALE_RELOCATED' || $element.data('status-return') !== 'REMARCÁVEL' ? this.listPassengerrRepricingReturn-- : '';
33918      }
33919    }
33920  }, {
33921    key: 'handlePassengerRepricing',
33922    value: function handlePassengerRepricing() {
33923      if (this.isPassengerAlreadyRepricingGoing || this.isPassengerAlreadyRepricingReturn) {
33924        this.showMsgErrorPassengerAlreadyRepricing(i18n('err_msg_passenger_canceled'));
33925        return false;
33926      } else {
33927        this.hideMsgErrorPassengerAlreadyRepriced();
33928        return true;
33929      }
33930    }
33931  }]);
33932
33933  return RepricingController;
33934}();
33935'use strict';
33936
33937var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
33938
33939function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
33940
33941var SearchPageController = function () {
33942  function SearchPageController() {
33943    _classCallCheck(this, SearchPageController);
33944
33945    this.searchInput = $('[data-js="input-search-search"]');
33946    this.btnSearch = $('[data-js="btn-search-search"]');
33947    this.resultSearch = $('[data="search-list-results"]');
33948    this.steppersSearch = $('[data="search-list-steppers"]');
33949    this.qttResultToPage = $('[data-js="qtt-show-items-search"]').val();
33950    this.messageNotResult = $('[data-js="message-not-result-search"]');
33951    this.listSearch = [];
33952    this.listSearchResult = [];
33953
33954    // Components to style in search component
33955    this.colorsToBtnSearch = $('[data-js="btn-search-search-color"]');
33956    this.colorsToSteppersSearch = $('[data-js="stepper-search-color"]');
33957    this.colorsToActiveStepperSearch = $('[data-js="active-stepper-search-color"]');
33958    this.containerSearchResultColor = $('[data-js="container-result-search"]');
33959    this.colorHeaderLabelItemResultSearch = $('[data-js="header-label-item-result-search"]');
33960    this.colorParagraphItemResultSearch = $('[data-js="paragraph-item-result-search"]');
33961    this.colorPathItemResultSearch = $('[data-js="path-item-result-search"]');
33962    this.boldTextParagraphItemResultsSearch = $('[data-js="bold-text-paragraph-item-result-search"]');
33963    this.btnNextPrevStepperSearch = $('[data-js="btn-next-prev-stepper-search"]');
33964    this.srcImageNotResultSearch = $('[data-js="img-not-result-search"]');
33965    this.wordParams = new URLSearchParams(window.location.search);;
33966    this.resultsShow = $('[data-js="quatity-results"]');
33967    this.totalResults = $('[data-js="quantity-total-results"]');
33968    this.init();
33969  }
33970
33971  _createClass(SearchPageController, [{
33972    key: 'init',
33973    value: function init() {
33974      this.initSearchStyle();
33975      this.initFormSearch();
33976      this.listenSearchEvents();
33977    }
33978  }, {
33979    key: 'initFormSearch',
33980    value: function initFormSearch() {
33981      var queryLength = 0;
33982      var queryParam = this.wordParams.get('q');
33983
33984      if (queryParam) {
33985        queryParam = queryParam.trim();
33986        queryLength = queryParam.length;
33987      }
33988
33989      if (queryParam && queryLength > 3 && $('#jca-identifier-page').val() == 'search-page') {
33990        this.btnSearch.prop('disabled', false).addClass('active');
33991        this.messageNotResult.hide();
33992        this.getSearchResults(queryParam);
33993        this.searchInput.val(queryParam);
33994        this.searchInput.trigger('keyup');
33995      }
33996    }
33997  }, {
33998    key: 'initSearchStyle',
33999    value: function initSearchStyle() {
34000      this.btnSearch.css({
34001        'background-color': this.colorsToBtnSearch.attr('data-background'),
34002        'color': this.colorsToBtnSearch.attr('data-color')
34003      });
34004
34005      $('.search-list-steppers li').css({
34006        'background': this.colorsToSteppersSearch.attr('data-background'),
34007        'color': this.colorsToSteppersSearch.attr('data-color'),
34008        'border': '1px solid' + this.colorsToSteppersSearch.data('border')
34009      });
34010
34011      $('.search-list-steppers li.active').css({
34012        'background': this.colorsToActiveStepperSearch.attr('data-background'),
34013        'color': this.colorsToActiveStepperSearch.attr('data-color'),
34014        'border': '1px solid ' + this.colorsToActiveStepperSearch.data('border')
34015      });
34016
34017      $('.search-list-steppers li a').css({
34018        'color': this.colorsToSteppersSearch.attr('data-color')
34019      });
34020
34021      $('.search-list-steppers li.active a').css({
34022        'color': this.colorsToActiveStepperSearch.attr('data-color')
34023      });
34024
34025      $('[data="search-list-results"]').css({
34026        'background': this.containerSearchResultColor.data('background'),
34027        'color': this.containerSearchResultColor.data('color'),
34028        'border': this.containerSearchResultColor.data('border')
34029      });
34030
34031      $('.card-item-result-search p.page-name a').css({
34032        'background': this.colorHeaderLabelItemResultSearch.data('background'),
34033        'color': this.colorHeaderLabelItemResultSearch.data('color')
34034      });
34035
34036      $('.card-item-result-search p.place-word-paragraph a').css({
34037        'backgroud': this.colorParagraphItemResultSearch.data('backgroud'),
34038        'color': this.colorParagraphItemResultSearch.data('color')
34039      });
34040
34041      var test = this.containerSearchResultColor.data('color')
34042      test = this.colorPathItemResultSearch.data('background')
34043      $('.list-path-breadcrumb li a').css({
34044        'background-color': this.colorPathItemResultSearch.data('background'),
34045        'color': this.colorPathItemResultSearch.data('color')
34046      });
34047
34048      $('.card-item-result-search p.place-word-paragraph .bold-word').css({
34049        'background-color': this.boldTextParagraphItemResultsSearch.data('background'),
34050        'color': this.boldTextParagraphItemResultsSearch.data('color')
34051      });
34052
34053      $('.search-btn').css({
34054        'background': this.btnNextPrevStepperSearch.data('background'),
34055        'color': this.btnNextPrevStepperSearch.data('color'),
34056        'border': '1px solid' + this.btnNextPrevStepperSearch.data('border')
34057      });
34058
34059      //$('[data-js="img-not-result"]').attr('src', this.srcImageNotResultSearch.data('src'));
34060    }
34061  }, {
34062    key: 'listenSearchEvents',
34063    value: function listenSearchEvents() {
34064      var _this = this;
34065
34066      this.searchInput.on('keyup', function (e) {
34067        var word = $(e.target).val() ? $(e.target).val().trim() : '';
34068        var wordLength = word.length;
34069
34070        if (wordLength > 3) {
34071          _this.btnSearch.prop('disabled', false).addClass('active');
34072        } else {
34073          _this.btnSearch.prop('disabled', true).removeClass('active');
34074        }
34075      });
34076
34077      $('[data-js="form-search-search"]').on('submit', function (e) {
34078        e.preventDefault();
34079
34080        _this.btnSearch.trigger('click');
34081      });
34082
34083      this.btnSearch.off('click').on('click', function (e) {
34084        e.preventDefault();
34085        var wordSearched = _this.searchInput.val();
34086
34087        try {
34088          var queryParams = new URLSearchParams(window.location.search);
34089          queryParams.set('q', wordSearched);
34090          history.replaceState(null, null, "?" + queryParams.toString());
34091        } catch (error) {
34092          console.log(error);
34093        }
34094
34095        _this.getSearchResults(wordSearched);
34096      });
34097
34098      $('.search-stepper').on('click', function (e) {
34099        e.preventDefault();
34100        var stepperNumberClicked = $(e.target).attr('data-js').replace(/\D/g, '');
34101
34102        _this.showSearch(stepperNumberClicked);
34103        $('[data-js="input-search-search"]').focus();
34104      });
34105
34106      $('[data-js="search-next-btn"]').on('click', function () {
34107        var currentPageIndex = $('.search-list-steppers li.active a.search-stepper').data('js').replace(/\D/g, '');
34108        var currentPage = Math.min(+currentPageIndex + 1, Math.ceil(_this.listSearch.length / _this.qttResultToPage));
34109
34110        _this.showSearch(currentPage);
34111        $('[data-js="input-search-search"]').focus();
34112      });
34113
34114      $('[data-js="search-prev-btn"]').on('click', function () {
34115        var currentPageIndex = $('.search-list-steppers li.active a.search-stepper').data('js').replace(/\D/g, '');
34116        var currentPage = Math.max(currentPageIndex - 1, 1);
34117
34118        _this.showSearch(currentPage);
34119        $('[data-js="input-search-search"]').focus();
34120      });
34121    }
34122  }, {
34123    key: 'getSearchResults',
34124    value: function getSearchResults(wordSearched) {
34125      var _this2 = this;
34126      var serviceUrl = '/content/jca/cometa/jcr:content.search.json?q=';
34127
34128      var siteId = $('#siteName').val();
34129      if (siteId === 'rapidoribeirao') {
34130        serviceUrl = '/content/jca/rapido-ribeirao/jcr:content.search.json?q=';
34131      } else if (siteId === 'catarinense') {
34132        serviceUrl = '/content/jca/catarinense/jcr:content.search.json?q=';
34133      } else if (siteId === '1001') {
34134        serviceUrl = '/content/jca/viacao1001/jcr:content.search.json?q=';
34135      } else if (siteId === 'expressodosul') {
34136        serviceUrl = '/content/jca/expresso-sul/jcr:content.search.json?q=';
34137      } else if (siteId === 'cometa') {
34138        serviceUrl = '/content/jca/cometa/jcr:content.search.json?q=';
34139      } else if (siteId === 'macaense') {
34140        serviceUrl = '/content/jca/macaense/jcr:content.search.json?q=';
34141      }
34142
34143      $.getJSON(serviceUrl + wordSearched).then(function (data) {
34144        LoaderService.hide();
34145        _this2.listSearch = data.items;
34146
34147        if (_this2.listSearch.length) {
34148          _this2.getListSearchResult(wordSearched);
34149        } else {
34150          _this2.showMsgNotResult();
34151        }
34152      }).catch(function (err) {
34153        LoaderService.hide();
34154        console.log(err);
34155      });
34156    }
34157  }, {
34158    key: 'showMsgNotResult',
34159    value: function showMsgNotResult() {
34160      $('.content-search-results, .content-search-steppers').hide();
34161      this.messageNotResult.show();
34162    }
34163  }, {
34164    key: 'getListSearchResult',
34165    value: function getListSearchResult(wordSearched) {
34166      this.messageNotResult.hide();
34167      this.renderlistItemsSearch(this.listSearch, wordSearched);
34168      this.renderSteppersSearch(this.listSearch.length);
34169      $('.content-search-results, .content-search-steppers').show();
34170    }
34171  }, {
34172    key: 'renderlistItemsSearch',
34173    value: function renderlistItemsSearch(listSearchResult, wordSearched) {
34174      var _this3 = this;
34175
34176      this.resultSearch.empty();
34177
34178      listSearchResult.forEach(function (item, i) {
34179        $('[data-js="search-list-results-' + i + '"]').empty();
34180        var itemList = [];
34181
34182        $.each(item.breadcrumb, function (idx, elem) {
34183          itemList.push('\n          <li>\n            <a id="breadcrumb-' + elem.path + '" alt="' + elem.name + '" href="' + elem.path + '" alt="' + elem.name + '">' + elem.name + '</a>\n          </li>\n        ');
34184        });
34185
34186        var regex = new RegExp(wordSearched, 'gi');
34187        var descriptionParagraph = item.teaser.replace(regex, '<span class=\'bold-word\'>' + wordSearched + '</span>');
34188        var pathWordLink = item.anchor ? item.path + '#' + item.anchor : item.path;
34189
34190        var itemsSearch = '\n        <li class="card-item-result-search">\n          <p class="page-name" data-js="place-word-paragrah"><a href="' + pathWordLink + '">' + item.title + '</a></p>\n          <p class="place-word-paragraph"><a href="' + pathWordLink + '" name="' + item.anchor + '">"' + descriptionParagraph + '"</a></p>\n          <ul class="list-path-breadcrumb" data-js="list-path-breadcrumb-' + i + '">\n            ' + itemList.join('') + '\n          </ul>\n        </li>\n      ';
34191
34192        _this3.resultSearch.append(itemsSearch);
34193      });
34194
34195      this.showSearch(1);
34196      this.initSearchStyle();
34197    }
34198  }, {
34199    key: 'renderSteppersSearch',
34200    value: function renderSteppersSearch(listSearchLength) {
34201      var $qttItemsSearch = $('[data-js="qtt-show-items-search"]').val();
34202      var qttSteppers = listSearchLength / $qttItemsSearch;
34203      this.steppersSearch.empty();
34204      qttSteppers = Math.ceil(qttSteppers);
34205
34206      if (qttSteppers > 1) {
34207        for (var i = 1; i <= qttSteppers; i++) {
34208          var itemsSteppers = '\n          <li class="' + (i === 1 ? 'active' : '') + '">\n            <a href="#" class="search-stepper" data-js="stepper-search-' + i + '" alt="' + i + '">' + i + '</a>\n          </li>\n        ';
34209
34210          this.steppersSearch.append(itemsSteppers);
34211        }
34212
34213        var prevBtn = $('<button type="button" class="search-btn search-prev-btn" id="search-prev-btn" data-js="search-prev-btn">' + '<span class="jca-ico-angle-left"></span>' + '</button>');
34214
34215        var nextBtn = $('<button type="button" class="search-btn search-next-btn" id="search-next-btn" data-js="search-next-btn">' + '<span class="jca-ico-angle-right"></span>' + '</button>');
34216
34217        nextBtn.appendTo(this.steppersSearch);
34218        prevBtn.prependTo(this.steppersSearch);
34219      }
34220
34221      this.listenSearchEvents();
34222      this.initSearchStyle();
34223    }
34224  }, {
34225    key: 'showSearch',
34226    value: function showSearch(currentPage) {
34227      var listItems = $('.card-item-result-search');
34228      var firstIndex = Math.max(currentPage - 1, 0) * this.qttResultToPage;
34229      var lastIndex = +firstIndex + (+this.qttResultToPage - 1);
34230
34231      listItems.removeClass('active last');
34232
34233      for (var i = firstIndex; i <= lastIndex; i++) {
34234        listItems.eq(i).addClass('active');
34235      }
34236
34237      this.setQttResults(firstIndex + 1, lastIndex + 1, listItems);
34238      var itemsActive = $('.card-item-result-search.active');
34239
34240      listItems.eq(lastIndex).addClass("last");
34241      $('.search-stepper').parent().removeClass('active');
34242      $('[data-js="stepper-search-' + currentPage + '"]').parent().addClass('active');
34243      this.initSearchStyle();
34244    }
34245  }, {
34246    key: 'setQttResults',
34247    value: function setQttResults(firstIndex, lastIndex, listItems) {
34248      this.resultsShow.text(' ' + firstIndex + ' - ' + (lastIndex > listItems.length ? listItems.length : lastIndex) + ' ');
34249      this.totalResults.text(' ' + listItems.length);
34250    }
34251  }]);
34252
34253  return SearchPageController;
34254}();
34255'use strict';
34256
34257var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
34258
34259function _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); } }
34260
34261function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
34262
34263/**
34264 * INICIO
34265 * LOGICA TELA RESULTADO DE BUSCA
34266 *
34267 */
34268var SearchResult = function () {
34269  function SearchResult($) {
34270    var _this = this;
34271
34272    _classCallCheck(this, SearchResult);
34273
34274    this.formData = SessionStorage.get('formData');
34275    this.nearbyCards = $('[data-js="nearby-cards"]');
34276    this.prevNearbyCard = $('[data-js="prev-nearby-card"]');
34277    this.currNearbyCard = $('[data-js="curr-nearby-card"]');
34278    this.nextNearbyCard = $('[data-js="next-nearby-card"]');
34279    this.labelDeparture = $('[data-js="itinerary-label-departure"]');
34280    this.labelDestination = $('[data-js="itinerary-label-destination"]');
34281    this.tripLabelGo = $('[data-js="trip-label-way-go"]');
34282    this.tripLabelBack = $('[data-js="trip-label-way-back"]');
34283    this.btnClose = $('[data-js="btn-close"]');
34284    this.timeline = $('[data-js="timeline"]');
34285    this.orderByContainer = $('[data-js="order-by-container"]');
34286    this.containerDate = $('[data-js="nearby-dates-container"]');
34287    this.containerFilterOrder = $('#shopping-filter-container');
34288    this.btnPreviousDaysNearby = $('[data-js="btn-prev-days-nearby"]');
34289    this.btnNextDaysNearby = $('[data-js="btn-next-days-nearby"]');
34290    this.hasModalUpsel = $('[data-js="has-modal-upsel"]').attr("is-overlay") == 'true';
34291    this.aemCustomText = ($("#aemMessageNoResult").attr("data-js-content") !== undefined) ? $("#aemMessageNoResult").attr("data-js-content") : i18n('ticket_no_result');
34292    this.requiredLoggedUser = $('[data-js="login-Dependency-Redirect"]').val() == 'true';
34293    this.departureTime = $('[data-js="departure-time"]').val();
34294    this.activateConfirmation = $('[data-js="activate-confirmation"]').attr('value') == 'true';
34295    this.cartComponent = null;
34296    this.loginController = null;
34297    this.listResultRef = null;
34298    this.orderByRef = null;
34299    this.configImagePoints = $('[data-js="config-image-points-giro-comodity"]');
34300    this.configLabelPoints = $('[data-js="config-label-points-giro-comodity"]');
34301    this.configModalPoints = $('[data-js="config-modal-points-text-comodity"]');
34302    this.tripToRepricing = SessionStorage.get('tripToRepricing');
34303    this.tripToRepricingV2 = SessionStorage.get('repricingv2');
34304    this.saleplatform = null;
34305    this.handleCustomPromotion(function () {
34306      return _this.init();
34307    });
34308    this.tripStopRef = new TripStop($);
34309  }
34310
34311  _createClass(SearchResult, [{
34312    key: 'init',
34313    value: function init() {
34314      var _this2 = this;
34315
34316      this.createSessionSeatLock();
34317      this.getServerTime(function () {
34318        _this2.listResultRef = new ListResult($, _this2);
34319        if (!SessionStorage.get('formData')) {
34320          if ($('#homePagePath') && $('#homePagePath').val() && (!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false') && (this.getPromotionParam('deep') == undefined)) {
34321            localStorage.setItem("referrer", $(location).attr('href'));
34322            $(location).attr('href', $('#homePagePath').val());
34323          }
34324        }
34325
34326        if (SessionStorage.get('checkout')) {
34327          SessionStorage.remove('checkout');
34328        }
34329
34330        try {
34331          _this2.cartComponent = new CartComponent($, SessionStorage.get('formData'));
34332          _this2.loginController = new LoginController($, _this2.cartComponent);
34333          _this2.resultFilterRef = new ResultFilter($, _this2, _this2.listResultRef);
34334        } catch (e) {
34335          console.log(e);
34336        }
34337
34338        var amountOffers = _this2.cartComponent.cartService.amountOffers;
34339        _this2.isDeparture = amountOffers === 0 ? true : false;
34340
34341        if (_this2.tripToRepricing || _this2.tripToRepricingV2) {
34342          _this2.nearbyCards.hide();
34343          _this2.containerDate.css('modified-height');
34344          _this2.loadDateRemark(_this2.formData);
34345        } else {
34346          if (_this2.formData instanceof Object && _this2.formData != null) {
34347            if (!_this2.tripToRepricingV2) {
34348              _this2.loadNearbyDates(_this2.formData);
34349              _this2.changeDatePrev(_this2.formData);
34350              _this2.changeDateNext(_this2.formData);
34351              _this2.handleNearbyEvents();
34352            } else {
34353              $('[data-js="nearby-dates-container"]').remove();
34354              _this2.loadItinerary(_this2.formData);
34355            }
34356          }
34357        }
34358
34359        _this2.orderByRef = new OrderBy(_this2.listResultRef);
34360      });
34361      this.clubGiroPoints();
34362    }
34363  }, {
34364    key: 'storeUtmMedium',
34365    value: function storeUtmMedium() {
34366      this.saleplatform = this.getPromotionParam('utm_saleplatform');
34367      if (this.saleplatform) {
34368        this.saleplatform = this.saleplatform.toUpperCase();
34369        SessionStorage.set('utm_saleplatform', this.saleplatform);
34370      }
34371    }
34372  }, {
34373    key: 'getServerTime',
34374    value: function getServerTime(callback) {
34375      var _this3 = this;
34376
34377      LoaderService.show();
34378      HttpService.getAEM('time.json?cache=1').then(function (data) {
34379        var time = data.result.time;
34380        var offset = data.result.offset;
34381
34382        time = time.replace("Z", "");
34383        var timezoneOffset = new Date(time).getTimezoneOffset();
34384
34385        // 180 is the difference between brasilia timezone and utc-0 in minutes
34386        time = timezoneOffset > 180 ? time : time + offset;
34387        _this3.timeExact = new Date(time);
34388        LoaderService.hide();
34389        callback(_this3.timeExact);
34390      }).catch(function () {
34391        console.error(err.message);
34392        _this3.timeExact = DateFormatter.getValidDateFormat();
34393        LoaderService.hide();
34394        callback(_this3.timeExact);
34395      });
34396    }
34397  }, {
34398    key: 'handleCustomPromotion',
34399    value: function handleCustomPromotion(callback) {
34400      var _this4 = this;
34401
34402      var travel = {};
34403      var sURLVariables = window.location.search.substring(1).split('&');
34404
34405      if (sURLVariables[0]) SessionStorage.set('deepLinkParameters', sURLVariables);
34406
34407      var deep = this.getPromotionParam("deep");
34408
34409      var _checkChildrenRequire = this.checkChildrenRequirements(this.getPromotionParam('num_psgr'), this.getPromotionParam('num_chda'), this.getPromotionParam('num_chds')),
34410        passengers = _checkChildrenRequire.passengers,
34411        passengersChda = _checkChildrenRequire.passengersChda,
34412        passengersChds = _checkChildrenRequire.passengersChds;
34413
34414      if (deep === 'false') {
34415        return callback(); // init()
34416      }
34417
34418      this.storeUtmMedium();
34419
34420      var date = this.getPromotionParam('data_ida');
34421      var dateReturn = this.getPromotionParam('data_volta');
34422
34423      var originId = parseInt(this.getPromotionParam('origem_id'));
34424      var destinyId = parseInt(this.getPromotionParam('destino_id'));
34425      var rangeDateIda = parseInt(this.getPromotionParam('range_data_ida'));
34426      var rangeDateVolta = parseInt(this.getPromotionParam('range_data_volta'));
34427
34428      var onlyDeparture = dateReturn || rangeDateVolta ? false : true;
34429
34430      if (date == null && dateReturn == null) {
34431        var cd = new Date();
34432        //date = new Date(cd.getFullYear(), cd.getMonth(), cd.getDate() + rangeDateIda)
34433        date = new Date(cd.getTime() + rangeDateIda * 24 * 60 * 60 * 1000);
34434        dateReturn = new Date(cd.getTime() + rangeDateVolta * 24 * 60 * 60 * 1000);
34435
34436        date = ('0' + date.getDate()).slice(-2).toString() + '-' + ('0' + (1 + date.getMonth())).slice(-2) + '-' + date.getFullYear();
34437        date = date.replace(/[-]/g, '');
34438        if (isNaN(rangeDateVolta)) {
34439          dateReturn = '';
34440          onlyDeparture = true;
34441        } else {
34442          dateReturn = ('0' + dateReturn.getDate()).slice(-2).toString() + '-' + ('0' + (1 + dateReturn.getMonth())).slice(-2) + '-' + dateReturn.getFullYear();
34443          dateReturn = dateReturn.replace(/[-]/g, '');
34444        }
34445      }
34446
34447      date = Utils.parseDateDeepLinkFormat(date);
34448      travel.date = date;
34449      dateReturn = Utils.parseDateDeepLinkFormat(dateReturn);
34450      travel.dateReturn = dateReturn;
34451      travel.originId = originId;
34452      travel.destinyId = destinyId;
34453      travel.onlyDeparture = onlyDeparture;
34454      travel.passengers = passengers;
34455      travel.passengers_chda = passengersChda;
34456      travel.passengers_chds = passengersChds;
34457
34458      LoaderService.show();
34459      HttpService.get('searchOrigin').then(function (data) {
34460        LoaderService.hide();
34461        if (data.success) {
34462          var results = data.result;
34463          travel.originUf = results.find(function (x) {
34464            return x.id == originId;
34465          }).state;
34466          travel.destinyUf = results.find(function (x) {
34467            return x.id == destinyId;
34468          }).state;
34469          travel.origin = results.find(function (x) {
34470            return x.id == originId;
34471          }).city;
34472          travel.destiny = results.find(function (x) {
34473            return x.id == destinyId;
34474          }).city;
34475          travel.originAddress = results.find(function (x) {
34476            return x.id == originId;
34477          }).address;
34478          travel.destinyAddress = results.find(function (x) {
34479            return x.id == destinyId;
34480          }).address;
34481          _this4.formData = _this4.getFormData(travel);
34482          SessionStorage.set("formData", _this4.formData);
34483          SessionStorage.remove("cart");
34484          LoaderService.show();
34485
34486          var loggedUser = SessionStorage.get('passenger');
34487          if (!loggedUser && _this4.requiredLoggedUser) $(location).attr('href', $('#loginPage').val());
34488
34489          var body = {
34490            origin: originId,
34491            destination: destinyId,
34492            departureDate: date,
34493            availability: true
34494          };
34495
34496          var saleplatform = SessionStorage.get('utm_saleplatform');
34497          saleplatform ? body.SalePlatform = this.saleplatform : body.SalePlatform = "SITES-UTP";
34498
34499          var headers = { version: 2 };
34500
34501          HttpService.post('getRoutes', body, headers).then(function (data) {
34502            LoaderService.hide();
34503            loadBreadcrumb();
34504            if (data.success) {
34505              _this4.currentResultDep = data.result;
34506              SessionStorage.set("currentResultDep", Utils.sortArrayResultsWay(_this4.currentResultDep));
34507              callback(); // init()
34508            }
34509
34510            _this4.headerSearch = new SearchComponentForm($);
34511            _this4.headerFilter = new HeaderFilter($, _this4.headerSearch);
34512          }).catch(function () {
34513            SessionStorage.set('currentResultDep', {});
34514            LoaderService.hide();
34515            _this4.containerFilterOrder.hide();
34516            $('[data-js="trip-label-way-back"]').hide();
34517            callback();
34518          });
34519        }
34520      });
34521
34522      var loadBreadcrumb = function loadBreadcrumb() {
34523        var breadcrumb = $('[data-js="breadcrumb"]');
34524        var steps = breadcrumb.children().find('.breadcrumb-section');
34525        var active_step = breadcrumb.children().find('.active');
34526        $(active_step).removeClass('active');
34527        $(steps[0]).addClass('active');
34528      };
34529    }
34530  }, {
34531    key: 'clubGiroPoints',
34532    value: function clubGiroPoints() {
34533      var $changePointsGiroContainer = $('[data-js="points-giro-container-comodity"]');
34534      var $sizeImagePointsGiro = $('[data-js="image-points-giro-comodity"]');
34535      var isVisible = $('[data-js="config-points-giro-container-comodity"]').attr('visible') === 'true';
34536      var $changePointsGiroLabel = $('.points-giro-modal');
34537      var $changePointsGiroModal = $('[data-js="text-modal-points-comodity"]');
34538      $sizeImagePointsGiro.css('height', this.configImagePoints.attr('height'));
34539      $sizeImagePointsGiro.css('width', this.configImagePoints.attr('width'));
34540      $changePointsGiroLabel.css('color', this.configLabelPoints.attr('color'));
34541      $changePointsGiroLabel.css('font-family', this.configLabelPoints.attr('fontFamily'));
34542      $changePointsGiroLabel.css('font-size', this.configLabelPoints.attr('fontSize'));
34543      $changePointsGiroLabel.text(this.configLabelPoints.attr('text'));
34544      $changePointsGiroModal.text(this.configModalPoints.attr('text'));
34545      isVisible ? $changePointsGiroContainer.removeClass('d-none') : $changePointsGiroContainer.addClass('d-none');
34546      this.tripToRepricingV2 ? $changePointsGiroContainer.addClass('d-none') : null;
34547    }
34548  }, {
34549    key: 'checkChildrenRequirements',
34550    value: function checkChildrenRequirements(num_psgr, num_chda, num_chds) {
34551      var maxValue = $('[data-js="select-person"]').data('maxvalue');
34552      var listResults = $('[data-js="list-companies"]');
34553      var passengers = parseInt(num_psgr);
34554      var passengersChda = 0;
34555      var passengersChds = parseInt(num_chds);
34556
34557      if (passengers + passengersChda > maxValue) {
34558        ValidationService.open($('[data-js="translationdeepLink1"]').val());
34559        listResults.remove();
34560      } else {
34561        var sURLVariables = window.location.search.substring(1);
34562
34563        if (passengers < passengersChda) {
34564          ValidationService.open($('[data-js="translationdeepLink2"]').val());
34565          passengersChda = passengers;
34566          sURLVariables = sURLVariables.replace('num_chda=' + num_chda, 'num_chda=' + passengersChda);
34567        }
34568
34569        if (passengers < passengersChds) {
34570          ValidationService.open($('[data-js="translationdeepLink3"]').val());
34571          passengersChds = passengers;
34572          sURLVariables = sURLVariables.replace('num_chds=' + num_chds, 'num_chds=' + passengersChds);
34573        }
34574
34575        var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + "?" + sURLVariables;
34576        window.history.pushState({ path: newurl }, '', newurl);
34577      }
34578
34579      return { passengers: passengers, passengersChda: passengersChda, passengersChds: passengersChds };
34580    }
34581  }, {
34582    key: 'getPromotionParam',
34583    value: function getPromotionParam(sParam) {
34584      var sPageURL = window.location.search.substring(1);
34585      var sURLVariables = sPageURL ? sPageURL.split('&') : SessionStorage.get('deepLinkParameters');
34586      for (var i = 0; i < sURLVariables.length; i++) {
34587        var sParameterName = sURLVariables[i].split("=");
34588        if (sParameterName[0] == sParam) return sParameterName[1];
34589      }
34590    }
34591  }, {
34592    key: 'getFormData',
34593    value: function getFormData(travel) {
34594      return {
34595        "passengers": [{
34596          order: 0,
34597          type: "ADULT",
34598          quantity: parseInt(travel.passengers)
34599        }, {
34600          order: 1,
34601          type: "CHILD_A",
34602          quantity: parseInt(travel.passengers_chda)
34603        }, {
34604          order: 3,
34605          type: "CHILD",
34606          quantity: parseInt(travel.passengers_chds)
34607        }],
34608        "departureOnly": String(travel.onlyDeparture) == "true",
34609        "depart": {
34610          "date": travel.date,
34611          "minDate": DateFormatter.getNewFormattedDate(),
34612          "origin": {
34613            "id": parseInt(travel.originId),
34614            "label": decodeURIComponent(travel.origin),
34615            "uf": travel.originUf,
34616            "address": travel.originAddress
34617          },
34618          "destination": {
34619            "id": parseInt(travel.destinyId),
34620            "label": decodeURIComponent(travel.destiny),
34621            "uf": travel.destinyUf,
34622            "address": travel.destinyAddress
34623          }
34624        },
34625        "return": {
34626          "date": travel.dateReturn,
34627          "minDate": travel.date + "T00:00:00",
34628          "origin": {
34629            "id": parseInt(travel.destinyId),
34630            "label": decodeURIComponent(travel.destiny),
34631            "uf": travel.destinyUf,
34632            "address": travel.destinyAddress
34633          },
34634          "destination": {
34635            "id": parseInt(travel.originId),
34636            "label": decodeURIComponent(travel.origin),
34637            "uf": travel.originUf,
34638            "address": travel.originAddress
34639          }
34640        },
34641        "deep": true
34642      };
34643    }
34644  }, {
34645    key: 'redirect',
34646    value: function redirect() {
34647
34648      if (SessionStorage.get('passenger')) {
34649        $(location).attr('href', $('#resourcePathPassengers').val());
34650      } else {
34651        localStorage.setItem("referrer", $('#resourcePathPassengers').val());
34652        $(location).attr('href', $('#loginPage').val());
34653      }
34654    }
34655  }, {
34656    key: 'buyReturnOffer',
34657    value: function buyReturnOffer(offer) {
34658      this.cartComponent.cartService.addReturnOffer(offer);
34659      SessionStorage.set('cart', this.cartComponent.cartService.cart);
34660
34661      if (this.hasModalUpsel) this.handleBetterOfferToModalUpsel(true);
34662    }
34663  }, {
34664    key: 'buyDepartureOffer',
34665    value: function buyDepartureOffer(offer) {
34666      this.cartComponent.cartService.addDepartOffer(offer);
34667      SessionStorage.set('cart', this.cartComponent.cartService.cart);
34668      if (!this.formData.departureOnly) {
34669        this.cartComponent.initSections(this.formData);
34670        this.cartComponent.initSummaryComponents();
34671        this.cartComponent.updateCartView();
34672        this.isDeparture = false;
34673        this.updateMinDate(offer.company.arrivingDate);
34674        this.listResultRef.orderByComponent.changeWay();
34675      }
34676
34677      if (this.hasModalUpsel) this.handleBetterOfferToModalUpsel();
34678    }
34679  }, {
34680    key: 'resetSlider',
34681    value: function resetSlider() {
34682      var _this5 = this;
34683
34684      new Promise(function () {
34685        _this5.resultFilterRef.resetSlider();
34686      });
34687    }
34688  }, {
34689    key: 'updateMinDate',
34690    value: function updateMinDate(arrivingDate) {
34691      this.formData.return.minDate = arrivingDate;
34692      SessionStorage.set('formData', this.formData);
34693    }
34694  }, {
34695    key: 'requestGetRoutesChangeDays',
34696    value: function requestGetRoutesChangeDays(isRet, formData) {
34697      var _this6 = this;
34698
34699      var origin = isRet ? formData.return.origin.id : formData.depart.origin.id;
34700      var destination = isRet ? formData.return.destination.id : formData.depart.destination.id;
34701      var date = isRet ? formData.return.date : formData.depart.date;
34702
34703      APIUtils.getAvailableTrips(origin, destination, date).then(function (data) {
34704        isRet ? SessionStorage.set('currentResultRet', Utils.sortArrayResultsWay(data.result)) : SessionStorage.set('currentResultDep', Utils.sortArrayResultsWay(data.result));
34705        _this6.loadNearbyDates(_this6.formData);
34706        _this6.resetListResultRef();
34707      }).catch(function (err) {
34708        isRet ? SessionStorage.set('currentResultRet', {}) : SessionStorage.set('currentResultDep', {});
34709        _this6.loadNearbyDates(_this6.formData);
34710        _this6.resetListResultRef();
34711        console.error(err);
34712      });
34713    }
34714  }, {
34715    key: 'requestReturnServices',
34716    value: function requestReturnServices() {
34717      var _this7 = this;
34718
34719      var origin = this.formData.return.origin.id;
34720      var destination = this.formData.return.destination.id;
34721      var date = this.listResultRef.parseDateApiFormat(this.formData.return.date);
34722
34723      APIUtils.getAvailableTrips(origin, destination, date).then(function (data) {
34724        SessionStorage.set('currentResultRet', Utils.sortArrayResultsWay(data.result));
34725        _this7.loadNearbyDates(_this7.formData);
34726        _this7.resetListResultRef();
34727      }).catch(function () {
34728        SessionStorage.set('currentResultRet', {});
34729        _this7.loadNearbyDates(_this7.formData);
34730        _this7.resetListResultRef();
34731      });
34732    }
34733  }, {
34734    key: 'resetListResultRef',
34735    value: function resetListResultRef() {
34736      if (this.listResultRef) {
34737        this.listResultRef.destroy();
34738      }
34739      this.listResultRef = new ListResult($, this);
34740    }
34741  }, {
34742    key: 'buyTicket',
34743    value: function buyTicket(e) {
34744      var _this8 = this;
34745
34746      var self = this;
34747      var offer = e.data.offer;
34748      var searchResultRef = e.data.searchResultRef;
34749      var isReturn = searchResultRef.isReturn();
34750
34751      if (this.activateConfirmation && this.isRangeDeadLine(e.data.offer.company)) {
34752        ModalConfirmDialog.show([i18n('message_modal_confirm_msg_strech_one'), i18n('message_modal_confirm_msg_strech_two')], this.getDerpatureTime(this.getDateTravel(), e.data.offer.company._departureDate, parseInt(this.departureTime))).then(function () {
34753          _this8.proceedToTicketPurchase(offer, searchResultRef, isReturn, self);
34754          ModalConfirmDialog.hide();
34755        }).catch(function () {
34756          ModalConfirmDialog.hide();
34757        });
34758      } else this.proceedToTicketPurchase(offer, searchResultRef, isReturn, self);
34759    }
34760  }, {
34761    key: 'proceedToTicketPurchase',
34762    value: function proceedToTicketPurchase(offer, searchResultRef, isReturn, self) {
34763      var tripToRepricing = SessionStorage.get('tripToRepricing');
34764      this.updateOriginDestination(offer.company, isReturn);
34765
34766      if (isReturn) {
34767        searchResultRef.buyReturnOffer(offer);
34768        this.sendAddToCartAnalytics(offer);
34769
34770        // Analitycs
34771        data_layer.page.pageInfo.paymentFlow.paymentFlowChanged = true;
34772        setTimeout(function () {
34773          if (tripToRepricing) {
34774            self.setPassengerInCart();
34775            $(location).attr('href', $('#seatReservationPathV2').val());
34776          } else {
34777            searchResultRef.redirect();
34778          }
34779        }, 300);
34780      } else {
34781        searchResultRef.buyDepartureOffer(offer);
34782        this.sendAddToCartAnalytics(offer);
34783        if (this.formData.departureOnly) {
34784
34785          // Analitycs
34786          data_layer.page.pageInfo.paymentFlow.paymentFlowChanged = true;
34787          setTimeout(function () {
34788            if (tripToRepricing) {
34789              self.setPassengerInCart();
34790              $(location).attr('href', $('#seatReservationPathV2').val());
34791            } else {
34792              searchResultRef.redirect();
34793            }
34794          }, 300);
34795        } else {
34796          if (tripToRepricing) {
34797            window.location.reload();
34798            this.loadDateRemark(this.formData);
34799          } else searchResultRef.requestReturnServices();
34800        }
34801      }
34802    }
34803  }, {
34804    key: 'setPassengerInCart',
34805    value: function setPassengerInCart() {
34806      var _this9 = this;
34807
34808      var passengersArr = SessionStorage.get('passengersToRepricing');
34809      var arr = [];
34810
34811      passengersArr.passengers.forEach(function (el, idx) {
34812        arr.push(_this9.parseObjPassenger(el));
34813      });
34814
34815      var cartComponentRef = new CartComponent($, SessionStorage.get('formData'));
34816
34817      cartComponentRef.cartService.clearPassengers();
34818      cartComponentRef.cartService.addPassengers(arr);
34819      SessionStorage.set('cart', cartComponentRef.cartService.cart);
34820    }
34821  }, {
34822    key: 'parseObjPassenger',
34823    value: function parseObjPassenger(el) {
34824      var getControlUser = function getControlUser() {
34825        return {
34826          controlDeparture: el.controlDeparture ? el.controlDeparture : null,
34827          controlDepartureConnection: el.controlDepartureConnection ? el.controlDepartureConnection : null,
34828          controlReturn: el.controlReturn ? el.controlReturn : null,
34829          controlReturnConnection: el.controlReturnConnection ? el.controlReturnConnection : null
34830        };
34831      };
34832
34833      var getSystemNumber = function getSystemNumber() {
34834        return {
34835          systemNumberDeparture: el.systemNumberDeparture ? el.systemNumberDeparture : null,
34836          systemNumberDepartureConnection: el.systemNumberDepartureConnection ? el.systemNumberDepartureConnection : null,
34837          systemNumberReturn: el.systemNumberReturn ? el.systemNumberReturn : null,
34838          systemNumberReturnConnection: el.systemNumberReturnConnection ? el.systemNumberReturnConnection : null
34839        };
34840      };
34841
34842      return {
34843        "name": Utils.capitalize(el.name),
34844        "doc": el.document,
34845        "birthDate": null,
34846        "type": el.type,
34847        "cpf": el.document,
34848        "child": null,
34849        "controlRepricing": getControlUser(),
34850        "systemNumberRepricing": getSystemNumber()
34851      };
34852    }
34853  }, {
34854    key: 'handleBetterOfferToModalUpsel',
34855    value: function handleBetterOfferToModalUpsel() {
34856      var isReturn = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
34857
34858      var cart = SessionStorage.get("cart");
34859      var serviceTrip = isReturn ? cart._listOffer[1]._service : cart._listOffer[0]._service;
34860      var serviceTripPossibleBetterOfferClass = +serviceTrip + 1;
34861      var offerToModalUpsel = isReturn ? SessionStorage.get('offerModalUpsel') : {};
34862      var isSameHourCurrentResult = true;
34863      var existBetterOffer = true;
34864
34865      if (isReturn) {
34866        var currentResultReturn = SessionStorage.get("currentResultRet");
34867        var returnServicesList = currentResultReturn.servicesList;
34868        var betterOfferRet = returnServicesList.filter(function (el) {
34869          return el.serviceId == serviceTripPossibleBetterOfferClass;
34870        });
34871        existBetterOffer = betterOfferRet.length > 0;
34872
34873        if (existBetterOffer) {
34874          var hourBetterOfferReturn = betterOfferRet[0].departureDate;
34875          var hourCurrentResult = cart._listOffer[1]._company._departureDate;
34876          isSameHourCurrentResult = hourBetterOfferReturn == hourCurrentResult;
34877        }
34878
34879        offerToModalUpsel.betterOfferReturn = isSameHourCurrentResult ? betterOfferRet : null;
34880        offerToModalUpsel.priceCurrentReturnOffer = isSameHourCurrentResult ? cart._listOffer[1]._price : null;
34881      } else {
34882        var currentResultDeparture = SessionStorage.get("currentResultDep");
34883        var departureServicesList = currentResultDeparture.servicesList;
34884        var betterOfferDep = departureServicesList.filter(function (el) {
34885          return el.serviceId == serviceTripPossibleBetterOfferClass;
34886        });
34887        existBetterOffer = betterOfferDep.length > 0;
34888
34889        if (existBetterOffer) {
34890          var hourBetterOfferDep = betterOfferDep[0].departureDate;
34891          var _hourCurrentResult = cart._listOffer[0]._company._departureDate;
34892          isSameHourCurrentResult = hourBetterOfferDep == _hourCurrentResult;
34893        }
34894
34895        offerToModalUpsel.betterOfferDepart = isSameHourCurrentResult ? betterOfferDep : null;
34896        offerToModalUpsel.priceCurrentDepartOffer = isSameHourCurrentResult ? cart._listOffer[0]._price : null;
34897      }
34898
34899      SessionStorage.set('offerModalUpsel', offerToModalUpsel);
34900    }
34901  }, {
34902    key: 'sendAddToCartAnalytics',
34903    value: function sendAddToCartAnalytics(offer) {
34904      var formData = SessionStorage.get("formData");
34905      var currentResultDep = SessionStorage.get("currentResultDep");
34906      var currentResultRet = SessionStorage.get("currentResultRet");
34907      var departDateInitial = SessionStorage.get("departureDate");
34908      var returnDateInitial = SessionStorage.get("returnDate");
34909      var searchData = Utils.getSearchData(formData, 'add_to_cart');
34910
34911      function optimizeString(str) {
34912          return str.replace(/[\s\-\(\):]+/g, '');
34913      }
34914
34915       var itemName = [
34916          offer._company._origin._label,
34917          offer._company._destination._label
34918       ].join(' + ');
34919
34920       itemName = optimizeString(itemName);
34921
34922       var totalPassengers = formData.passengers[0].quantity + formData.passengers[1].quantity;
34923       var totalValue = offer._price * totalPassengers;
34924
34925       var departureDate = departDateInitial;
34926       if (currentResultDep && currentResultDep.servicesList) {
34927          var depService = currentResultDep.servicesList.find(function(service) {
34928              return service.serviceId === offer._service;
34929          });
34930          if (depService && !departDateInitial) {
34931              departureDate = depService.departureDate;
34932              SessionStorage.set('departureDate', departureDate);
34933          }
34934       }
34935
34936       var returnDate = returnDateInitial;
34937       if (currentResultRet && currentResultRet.servicesList) {
34938         var retService = currentResultRet.servicesList.find(function(service) {
34939             return service.serviceId === offer._service;
34940         });
34941         if (retService) {
34942             returnDate = retService.departureDate;
34943             SessionStorage.set('returnDate', returnDate);
34944         }
34945       }
34946
34947       var items = [{
34948           item_name: itemName,
34949           item_id: offer._service ? offer._service : null,
34950           item_brand: offer._company && offer._company._companyName ? offer._company._companyName : null,
34951           item_variant: offer._classtype && offer._classtype._className ? offer._classtype._className : null,
34952           item_category: $("#siteName").val(),
34953           item_category2: offer._company && offer._company._companyName ? offer._company._companyName : null,
34954           item_category3: offer._company && offer._company._companyName ? offer._company._companyName : null,
34955           benefit: formData.passengers[2].quantity > 0 ? true : false,
34956           departure_date: departureDate,
34957           return_date: returnDate,
34958           price: offer._price ? offer._price : null,
34959           adults_passengers: formData.passengers[0].quantity, // Quantidade de passageiros adultos
34960           infants_passengers: formData.passengers[2].quantity, // Quantidade de passageiros crianças de colo (não pagantes)
34961           children_passengers: formData.passengers[1].quantity, // Quantidade de passageiros crianças (pagantes)
34962           quantity: formData.passengers[0].quantity + formData.passengers[1].quantity,
34963           index: offer._index ? offer._index : null
34964       }];
34965
34966       window.dataLayer = window.dataLayer || [];
34967       window.dataLayer.push({
34968         event: "add_to_cart",
34969         device: Utils.getDevice(),
34970         sale_origin: $("#siteName").val(),
34971          ecommerce: {
34972            currency: "BRL",
34973            value: totalValue,
34974            cart_total: totalValue,
34975            search_data: searchData,
34976		    search_parameters: Utils.getSearchParameters(formData),
34977            items: items,
34978            user_data: Utils.getUserData()
34979          },
34980       });
34981     }
34982  }, {
34983    key: 'isRangeDeadLine',
34984    value: function isRangeDeadLine(company) {
34985      var derpatureHour = new Date(company._departureDate);
34986      var hour = new Date(0, 0, 0, derpatureHour.getHours(), derpatureHour.getMinutes(), 0);
34987
34988      return hour >= this.midnight() && hour <= this.twoInTheMorning() ? true : false;
34989    }
34990  }, {
34991    key: 'midnight',
34992    value: function midnight() {
34993      return new Date(0, 0, 0, 0, 0, 0);
34994    }
34995  }, {
34996    key: 'twoInTheMorning',
34997    value: function twoInTheMorning() {
34998      return new Date(0, 0, 0, 2, 0, 0);
34999    }
35000  }, {
35001    key: 'getDerpatureTime',
35002    value: function getDerpatureTime(date, hour, time) {
35003      var dateDerparture = date.split('-');
35004      var hourDerpature = new Date(hour);
35005      var dateHourDerpature = new Date(dateDerparture[0], dateDerparture[1] - 1, dateDerparture[2], hourDerpature.getHours(), hourDerpature.getMinutes(), 0);
35006
35007      return new Date(dateHourDerpature.getTime() - time / 60 * 60 * 60 * 1000);
35008    }
35009  }, {
35010    key: 'getDateTravel',
35011    value: function getDateTravel() {
35012      return !this.isReturn() ? this.formData.depart.date : this.formData.return.date;
35013    }
35014  }, {
35015    key: 'updateOriginDestination',
35016    value: function updateOriginDestination(company, isReturn) {
35017      var origin = company.origin;
35018      var destination = company.destination;
35019      var originCapitalize = Utils.capitalize(origin.label.split('-')[0]) + ' ';
35020      var destinationCapitalize = Utils.capitalize(destination.label.split('-')[0]) + ' ';
35021
35022      if (isReturn) {
35023        this.formData.return.origin.id = origin.id;
35024        this.formData.return.origin.label = originCapitalize;
35025        this.formData.return.destination.id = destination.id;
35026        this.formData.return.destination.label = destinationCapitalize;
35027      } else {
35028        this.formData.depart.origin.id = origin.id;
35029        this.formData.depart.origin.label = originCapitalize;
35030        this.formData.depart.destination.id = destination.id;
35031        this.formData.depart.destination.label = destinationCapitalize;
35032      }
35033
35034      SessionStorage.set('formData', this.formData);
35035    }
35036  }, {
35037    key: 'setListResultView',
35038    value: function setListResultView(calledByApplyFilter) {
35039      var _this10 = this;
35040
35041      new Promise(function () {
35042        if (_this10.listResultRef) {
35043          _this10.listResultRef.setListResultView(calledByApplyFilter);
35044        }
35045      });
35046    }
35047  }, {
35048    key: 'resetOrderBy',
35049    value: function resetOrderBy() {
35050      var _this9 = this;
35051
35052      new Promise(function () {
35053        if (_this9.listResultRef) _this9.listResultRef.resetOrderBy();
35054      });
35055    }
35056  }, {
35057    key: 'maintainOrdering',
35058    value: function maintainOrdering() {
35059      var _this12 = this;
35060
35061      new Promise(function () {
35062        if (_this12.listResultRef) _this12.listResultRef.maintainOrdering();
35063      });
35064    }
35065  }, {
35066    key: 'loadNearbyDates',
35067    value: function loadNearbyDates(formData) {
35068      var _this10 = this;
35069
35070      var result = {};
35071      if (this.isReturn()) {
35072        result = SessionStorage.get('currentResultRet');
35073      } else {
35074        result = SessionStorage.get('currentResultDep');
35075      }
35076
35077      try {
35078        this.disableNearbyCards();
35079
35080        Promise.all([this.loadNearbyDatesV4(formData), this.loadItinerary(formData), this.setListResultView(), this.resetSlider(), this.resetOrderBy()]).then(function () {
35081          $('html,body').animate({
35082            scrollTop: 0
35083          }, 'slow');
35084          _this10.headerSearch = new SearchComponentForm($);
35085          _this10.headerFilter = new HeaderFilter($, _this10.headerSearch);
35086        });
35087      } catch (ex) {
35088        console.log(ex);
35089      }
35090    }
35091  }, {
35092    key: 'loadDateRemark',
35093    value: function loadDateRemark(formData) {
35094      var _this14 = this;
35095
35096      var result = {};
35097      if (this.isReturn()) {
35098        result = SessionStorage.get('currentResultRet');
35099      } else {
35100        result = SessionStorage.get('currentResultDep');
35101      }
35102
35103      try {
35104        Promise.all([this.loadCurrentDate(formData, result), this.loadItinerary(formData), this.setListResultView(), this.maintainOrdering()]).then(function () {
35105          $('html,body').animate({
35106            scrollTop: 0
35107          }, 'slow');
35108          _this14.headerSearch = new SearchComponentForm($);
35109          _this14.headerFilter = new HeaderFilter($, _this14.headerSearch);
35110        });
35111      } catch (ex) {
35112        console.log(ex);
35113      }
35114    }
35115  }, {
35116    key: 'changeDatePrev',
35117    value: function changeDatePrev(formData) {
35118      var isRet = this.isReturn();
35119      if (this.prevNearbyCard.find('.skeleton').hasClass('active')) {
35120        return;
35121      }
35122
35123      if (isRet) {
35124        var prevDate = this.getPrevDate(formData.return.date);
35125        formData.return.date = prevDate;
35126      } else {
35127        var _prevDate = this.getPrevDate(formData.depart.date);
35128        formData.depart.date = _prevDate;
35129      }
35130
35131      SessionStorage.set("formData", formData);
35132      SessionStorage.remove("filteredResult");
35133      this.requestGetRoutesChangeDays(isRet, formData);
35134    }
35135  }, {
35136    key: 'changeDateNext',
35137    value: function changeDateNext(formData) {
35138      var isRet = this.isReturn();
35139      if (this.nextNearbyCard.find('.skeleton').hasClass('active')) {
35140        return;
35141      }
35142
35143      if (this.isReturn()) {
35144        var nextDate = this.getNextDate(formData.return.date);
35145        formData.return.date = nextDate;
35146      } else {
35147        var _nextDate = this.getNextDate(formData.depart.date);
35148        formData.depart.date = _nextDate;
35149        if (!formData.departureOnly) {
35150          formData.return.date = this.getNewReturnDate(_nextDate);
35151        }
35152      }
35153
35154      SessionStorage.set("formData", formData);
35155      SessionStorage.remove("filteredResult");
35156      this.requestGetRoutesChangeDays(isRet, formData);
35157    }
35158  }, {
35159    key: 'getDesktopDate',
35160    value: function getDesktopDate(date) {
35161      var dayName = this.capitalize(DateFormatter.getDaysArray()[date.getDay()].substr(0, 3));
35162      var month = date.getMonth() + 1;
35163      var day = date.getDate();
35164      var userLang = Utils.getCurrentLang();
35165      switch (userLang) {
35166        case 'en':
35167          return dayName + ' ' + month + '/' + day;
35168        case 'es':
35169          return dayName + ' ' + day + '/' + month;
35170        default:
35171          return dayName + ' ' + day + '/' + month;
35172      }
35173    }
35174  }, {
35175    key: 'capitalize',
35176    value: function capitalize(str) {
35177      return str[0].toUpperCase() + str.slice(1);
35178    }
35179  }, {
35180    key: 'handleMinTimeToBuyTrip',
35181    value: function handleMinTimeToBuyTrip(trip) {
35182      var minTimeToBuyTrip = $('[data-js="min-time-to-buy-ticket"]').val() ? +$('[data-js="min-time-to-buy-ticket"]').val() : 20;
35183      var hourDepartResearch = new Date(this.formData.depart.minDate).getTime() + minTimeToBuyTrip * 60 * 1000;
35184      var dateTrip = new Date(trip.departureDate).getTime();
35185      var isAfterMinTime = hourDepartResearch < dateTrip;
35186
35187      return isAfterMinTime;
35188    }
35189  }, {
35190    key: 'getMinorValueTripVisible',
35191    value: function getMinorValueTripVisible(listTrip) {
35192      var listTripPrice = listTrip.reduce(function (acc, el) {
35193        return acc = [el.price].concat(_toConsumableArray(acc));
35194      }, []);
35195
35196      var minorValue = Math.min.apply(Math, _toConsumableArray(listTripPrice));
35197      return Utils.formatPrice(minorValue);
35198    }
35199  }, {
35200    key: 'filterTripsMinHour',
35201    value: function filterTripsMinHour(listTrip) {
35202      var filteredTrips = [];
35203
35204      for (var i = 0; i < listTrip.length; i++) {
35205        if (this.handleMinTimeToBuyTrip(listTrip[i])) filteredTrips.push(listTrip[i]);
35206      }
35207
35208      filteredTrips.sort(function (a, b) {
35209        return a.price - b.price;
35210      });
35211
35212      return filteredTrips;
35213    }
35214  }, {
35215    key: 'loadCurrentDate',
35216    value: function loadCurrentDate(formData, result) {
35217      var _this13 = this;
35218
35219      new Promise(function () {
35220        _this13.currNearbyCard.fadeOut(200);
35221        var day = _this13.parseDateUTCFormat(_this13.isReturn() ? formData.return.date : formData.depart.date);
35222        _this13.currNearbyCard.find('.skeleton').addClass('active');
35223        _this13.currNearbyCard.attr('disabled', false);
35224
35225        if (!result || !result.servicesList) _this13.currNearbyCard.attr('disabled', true);
35226
35227        _this13.currNearbyCard.children().each(function (_, el) {
35228          var selector = $(el).data('js');
35229          var noResult = !result.servicesList;
35230
35231          switch (selector) {
35232            case 'date':
35233              $(el).text(_this13.getDesktopDate(day));
35234              break;
35235            case 'from':
35236              $(el).text(noResult ? '' : _this13.getFromLabel());
35237              break;
35238            case 'price':
35239              var low_price = _this13.getLowerPrice(result);
35240              $(el).text(noResult ? _this13.aemCustomText : 'R$ ' + low_price);
35241              break;
35242          }
35243        });
35244
35245        _this13.currNearbyCard.fadeIn(200);
35246        _this13.currNearbyCard.find('.skeleton').removeClass('active');
35247      });
35248    }
35249  }, {
35250    key: 'updateNearbyCard',
35251    value: function updateNearbyCard($card, date, listTrips) {
35252      var day = this.parseDateUTCFormat(date);
35253      var hasTrips = listTrips.length > 0;
35254
35255      $card.find('[data-js=\"date\"]').text(this.getDesktopDate(day));
35256      $card.find('[data-js=\"from\"]').text(hasTrips ? this.getFromLabel() : '');
35257      $card.find('[data-js=\"price\"]').text(hasTrips ? 'R$ ' + this.getMinorValueTripVisible(listTrips) : i18n('no_ticket'));
35258
35259      $card.attr('disabled', !hasTrips);
35260      if (!hasTrips) {
35261        $card.addClass('disabled');
35262      } else {
35263        $card.removeClass('disabled');
35264      }
35265
35266      $card.find('.skeleton').removeClass('active');
35267    }
35268  }, {
35269    key: 'loadNearbyDatesV4',
35270    value: function loadNearbyDatesV4(formData) {
35271      var _this18 = this;
35272
35273      var date = this.isReturn() ? formData.return.date : formData.depart.date;
35274      var body = this.getBodyParams(formData, date);
35275      var dayRef = DateFormatter.getValidDateFormat(date);
35276      var sessiondispolock = SessionStorage.get('sessionseatlock');
35277      var headers = { version: 4, sessiondispolock: sessiondispolock };
35278
35279      HttpService.post('getRoutes', body, headers).then(function (data) {
35280        if (!data.success || !Array.isArray(data.result)) return;
35281
35282        var groupedByDate = {};
35283        data.result.forEach(function (trip) {
35284          var dayKey = trip.departureDate.split('T')[0];
35285          if (!groupedByDate[dayKey]) groupedByDate[dayKey] = [];
35286          groupedByDate[dayKey].push(trip);
35287        });
35288
35289        var prevDate = _this18.getPrevDate(date);
35290        var nextDate = _this18.getNextDate(date);
35291
35292        var prevList = groupedByDate[prevDate] || [];
35293        var currList = groupedByDate[date] || [];
35294        var nextList = groupedByDate[nextDate] || [];
35295
35296        _this18.updateNearbyCard(_this18.prevNearbyCard, prevDate, prevList);
35297        _this18.updateNearbyCard(_this18.nextNearbyCard, nextDate, nextList);
35298
35299        if (data.result.length > 0 && currList.length > 0) {
35300          _this18.updateNearbyCard(_this18.currNearbyCard, date, currList);
35301        }
35302
35303        var noResults = data.result.length === 0;
35304        var hasNoPreviousTrips = prevList.length === 0;
35305        var hasNoNextTrips = nextList.length === 0;
35306
35307        _this18.enableNearbyCards(noResults);
35308        _this18.btnPreviousDaysNearby.prop('disabled', hasNoPreviousTrips);
35309        _this18.btnNextDaysNearby.prop('disabled', hasNoNextTrips);
35310
35311        if (hasNoPreviousTrips && currList.length === 0 && hasNoNextTrips) {
35312          _this18.btnPreviousDaysNearby.hide();
35313          _this18.btnNextDaysNearby.hide();
35314        }
35315
35316        $('html,body').animate({ scrollTop: 0 }, 'slow');
35317
35318        _this18.headerSearch = new SearchComponentForm($);
35319        _this18.headerFilter = new HeaderFilter($, _this18.headerSearch);
35320      }).catch(function (err) {
35321        _this18.updateNearbyCard(_this20.prevNearbyCard, null, []);
35322        _this18.updateNearbyCard(_this20.nextNearbyCard, null, []);
35323        _this18.enableNearbyCards(true);
35324
35325        _this18.btnPreviousDaysNearby.hide();
35326        _this18.btnNextDaysNearby.hide();
35327      });
35328    }
35329  }, {
35330    key: 'createSessionSeatLock',
35331    value: function createSessionSeatLock() {
35332      var formData = SessionStorage.get('formData');
35333      var originId = formData.depart.origin.id;
35334      var destinationId = formData.depart.destination.id;
35335      var timestamp = new Date().getTime();
35336      var sessionSeatLock = generateMD5('' + (originId + destinationId + timestamp));
35337      SessionStorage.set('sessionseatlock', sessionSeatLock);
35338    }
35339  }, {
35340    key: 'loadItinerary',
35341    value: function loadItinerary(formData) {
35342      var _this16 = this;
35343
35344      new Promise(function () {
35345        if (formData.depart.origin.label && formData.depart.destination.label) {
35346          if (_this16.isReturn()) {
35347            _this16.tripLabelGo.hide();
35348            _this16.tripLabelBack.show();
35349            _this16.labelDeparture.text(Utils.capitalize(formData.return.origin.label));
35350            _this16.labelDestination.text(Utils.capitalize(formData.return.destination.label));
35351            $('[data-js="arrow-label"]').addClass('active');
35352          } else {
35353            _this16.tripLabelGo.show();
35354            _this16.tripLabelBack.hide();
35355            _this16.labelDeparture.text(Utils.capitalize(formData.depart.origin.label));
35356            _this16.labelDestination.text(Utils.capitalize(formData.depart.destination.label));
35357            $('[data-js="arrow-label"]').removeClass('active');
35358          }
35359        } else {
35360          _this16.timeline.attr('class', 'invisible');
35361        }
35362      });
35363    }
35364  }, {
35365    key: 'getFromLabel',
35366    value: function getFromLabel() {
35367      return 'a partir de';
35368    }
35369  }, {
35370    key: 'getLowerPrice',
35371    value: function getLowerPrice(result) {
35372      if (result.length === 0 || Object.keys(result).length <= 0) return '';
35373
35374      var service = result.servicesList.filter(function (service) {
35375        return service.freeSeats > 0;
35376      }).reduce(function (prev, curr) {
35377        return prev.price < curr.price ? prev : curr;
35378      }, {});
35379
35380      return service.price ? service.price.toFixed(2).toString().replace('.', ',') : '';
35381    }
35382  }, {
35383    key: 'getBodyParams',
35384    value: function getBodyParams(formData, date) {
35385      var body = {};
35386      if (this.isReturn()) {
35387        body = {
35388          origin: formData.return.origin.id,
35389          destination: formData.return.destination.id,
35390          departureDate: date,
35391          availability: true
35392        };
35393      } else {
35394        body = {
35395          origin: formData.depart.origin.id,
35396          destination: formData.depart.destination.id,
35397          departureDate: date,
35398          availability: true
35399        };
35400      }
35401
35402      var saleplatform = SessionStorage.get('utm_saleplatform');
35403      saleplatform ? body.SalePlatform = this.saleplatform : body.SalePlatform = "SITES-UTP";
35404
35405      return body;
35406    }
35407  }, {
35408    key: 'getPrevDate',
35409    value: function getPrevDate(dateDeparture) {
35410      var curr_day = DateFormatter.getValidDateFormat(dateDeparture);
35411      var previous_day = new Date(curr_day.getTime());
35412      previous_day.setDate(curr_day.getDate() - 1);
35413      return previous_day.getFullYear() + '-' + ('0' + (previous_day.getMonth() + 1)).slice(-2) + '-' + ('0' + previous_day.getDate()).slice(-2);
35414    }
35415  }, {
35416    key: 'getNextDate',
35417    value: function getNextDate(dateDeparture) {
35418      var curr_day = DateFormatter.getValidDateFormat(dateDeparture);
35419      var next_day = new Date(curr_day.getTime());
35420      next_day.setDate(curr_day.getDate() + 1);
35421      return next_day.getFullYear() + '-' + ('0' + (next_day.getMonth() + 1)).slice(-2) + '-' + ('0' + next_day.getDate()).slice(-2);
35422    }
35423  }, {
35424    key: 'parseDateUTCFormat',
35425    value: function parseDateUTCFormat(dateStr) {
35426      var date = DateFormatter.getValidDateFormat(dateStr);
35427      return date;
35428    }
35429  }, {
35430    key: 'getNewReturnDate',
35431    value: function getNewReturnDate(newDepartDate) {
35432      var date_return = this.formData.return.date;
35433      if (DateFormatter.getValidDateFormat(newDepartDate) > DateFormatter.getValidDateFormat(date_return)) {
35434        return newDepartDate;
35435      } else {
35436        return date_return;
35437      }
35438    }
35439  }, {
35440    key: 'isReturn',
35441    value: function isReturn() {
35442      var formData = SessionStorage.get('formData');
35443      return formData != null && !formData.departureOnly && this.isDeparture == false;
35444    }
35445  }, {
35446    key: 'showTripStop',
35447    value: function showTripStop() {
35448      this.tripStopRef.show();
35449    }
35450  }, {
35451    key: 'hideTripStop',
35452    value: function hideTripStop() {
35453      this.tripStopRef.hide();
35454    }
35455  }, {
35456    key: 'disableNearbyCards',
35457    value: function disableNearbyCards() {
35458      [this.prevNearbyCard, this.currNearbyCard, this.nextNearbyCard].forEac
35458h(function (card) {
35459        card.find('.skeleton').addClass('active');
35460        card.attr('disabled', true);
35461      });
35462      this.btnPreviousDaysNearby.prop('disabled', true);
35463      this.btnNextDaysNearby.prop('disabled', true);
35464    }
35465  }, {
35466    key: 'enableNearbyCards',
35467    value: function enableNearbyCards() {
35468      var disabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
35469
35470      [this.prevNearbyCard, this.currNearbyCard, this.nextNearbyCard].forEach(function (card) {
35471        card.find('.skeleton').removeClass('active');
35472      });
35473      this.btnPreviousDaysNearby.prop('disabled', disabled);
35474      this.btnNextDaysNearby.prop('disabled', disabled);
35475    }
35476  }, {
35477    key: 'handleNearbyEvents',
35478    value: function handleNearbyEvents() {
35479      var _this17 = this;
35480
35481      this.btnPreviousDaysNearby.add(this.prevNearbyCard).on('click', function () {
35482        _this17.changeDatePrev(_this17.formData);
35483      });
35484
35485      this.btnNextDaysNearby.add(this.nextNearbyCard).on('click', function () {
35486        _this17.changeDateNext(_this17.formData);
35487      });
35488    }
35489  }]);
35490
35491  return SearchResult;
35492}();
35493/** * FIM
35494 * LOGICA TELA RESULTADO DE BUSCA
35495 *
35496 */
35497'use strict';
35498
35499var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
35500
35501function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
35502
35503/**
35504 * INICIO
35505 * LOGICA TELA RESERVA DE ASSENTOS
35506 *
35507 */
35508
35509var SeatReservationRemark = function () {
35510  function SeatReservationRemark($, cartComponentRef) {
35511    var _this = this;
35512
35513    _classCallCheck(this, SeatReservationRemark);
35514
35515    this.formData = SessionStorage.get('formData');
35516    this.cart = SessionStorage.get('cart');
35517    this.isSeletecOnlyReturnTrip = SessionStorage.get('isSeletecOnlyReturnTrip');
35518    this.goingConnection = false;
35519    this.returnConnection = false;
35520
35521    if ((!this.formData || !this.cart) && $('#homePagePath') && $('#homePagePath').val() && (!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false')) {
35522      $(location).attr('href', $('#homePagePath').val());
35523    }
35524
35525    this.$passengerList = $('[data-js="passenger-list"]');
35526    this.$passengerItemTemplate = $('[data-js="passenger-template"]');
35527    this.$passengerSeatTemplate = $('[data-js="passenger-seat-template"]');
35528    this.$tripLabelWay = $('[data-js="trip-label-way"]');
35529    this.$itineraryLabelDeparture = $('[data-js="itinerary-label-departure"]');
35530    this.$itineraryLabelDestination = $('[data-js="itinerary-label-destination"]');
35531    this.$btnProceed = $('[data-js="btn-proceed"]');
35532    this.$originLabel = $('[data-js="summary-label-origin"]');
35533    this.$destinationLabel = $('[data-js="summary-label-destination"]');
35534    this.$errorContainer = $('.seat-error-container');
35535    this.showAlreadyBoughtAlert = $('[data-js="show-already-bought-alert"]').val() ? $('[data-js="show-already-bought-alert"]').val().toLowerCase() == "true" : '';
35536    this.$closeErrorOverlay = $('[data-js="close-overlay-seat-reservation"]');
35537    this.$dateLabel = $('[data-js="departure-date-label"]');
35538    this.$dayLabel = $('[data-js="departure-day-label"]');
35539    this.hour = $('[data-js="hour-departure"]');
35540    this.tripLabelGo = $('[data-js="trip-label-way-go"]');
35541    this.tripLabelBack = $('[data-js="trip-label-way-back"]');
35542    this.tripToRepricingV2 = SessionStorage.get('repricingv2');
35543    this.$closeErrorOverlay.on('click', function () {
35544      _this.closeErrorMessage();
35545    });
35546    this.$closeErrorOverlay.on('focusout', function (e) {
35547      var $target = $(e.relatedTarget);
35548      if ($target.closest('.seat-error-container').length == 0) _this.$closeErrorOverlay.click();
35549    });
35550    this.cartComponent = cartComponentRef;
35551    this.trips = [];
35552    this.busMapSeat = new BusMapSeat($);
35553    this.step = 0;
35554    this.connectionStep = 0;
35555    this.fillArrayTrips();
35556    this.initBtnProceed();
35557    this.scrollFloatingDiv();
35558    this.setWarningAffix();
35559    this.createSessionSeatLock();
35560  }
35561
35562  _createClass(SeatReservationRemark, [{
35563    key: 'createSessionSeatLock',
35564    value: function createSessionSeatLock() {
35565      var formData = SessionStorage.get('formData');
35566      var originId = formData.depart.origin.id;
35567      var destinationId = formData.depart.destination.id;
35568      var timestamp = new Date().getTime();
35569      var sessionSeatLock = generateMD5('' + (originId + destinationId + timestamp));
35570      SessionStorage.set('sessionseatlock', sessionSeatLock);
35571    }
35572  }, {
35573    key: 'initLabel',
35574    value: function initLabel() {
35575      var _this2 = this;
35576
35577      var showGo = function showGo(connectionText) {
35578        _this2.tripLabelGo.show();
35579        if (connectionText) _this2.tripLabelGo.append(connectionText);
35580        _this2.tripLabelBack.hide();
35581        $('[data-js="arrow-label"]').removeClass('active');
35582      };
35583
35584      var showBack = function showBack(connectionText) {
35585        _this2.tripLabelGo.hide();
35586        _this2.tripLabelBack.show();
35587        if (connectionText) _this2.tripLabelBack.append(connectionText);
35588        $('[data-js="arrow-label"]').addClass('active');
35589      };
35590
35591      switch (this.step) {
35592        case 0:
35593          showGo();
35594          break;
35595        case 1:
35596          $('[data-js="trip-label-way-go"]').addClass('hide');
35597          $('[data-js="trip-label-way-go-connection"]').removeClass('hide');
35598          this.goingConnection = true;
35599          break;
35600        case 2:
35601          showBack();
35602          $('[data-js="trip-label-way-go-connection"]').addClass('hide');
35603          break;
35604        case 3:
35605          $('[data-js="trip-label-way-back"]').addClass('hide');
35606          $('[data-js="trip-label-way-back-connection"]').removeClass('hide');
35607          $('[data-js="trip-label-way-back-connection"]').css('display', 'block')
35608          this.returnConnection = true;
35609          break;
35610      }
35611    }
35612  }, {
35613    key: 'listenEvents',
35614    value: function listenEvents() {
35615      $('.reservation-passenger-item').on('click', function () {
35616
35617        if (Utils.isMobile()) {
35618          $('.bus-map-container').addClass('active');
35619          var passengerIndex = $('.reservation-passenger-item.active').find('[data-js="passenger-index"]').text();
35620          var passengerName = $('.reservation-passenger-item.active').find('[data-js="person-name"]').text();
35621
35622          $('[data-js="user-index"]').text(passengerIndex);
35623          $('[data-js="user-name"]').text(passengerName);
35624        }
35625      });
35626
35627      $('[data-js="close-bus-map"]').on('click', function () {
35628        $('.bus-map-container').removeClass('active');
35629      });
35630
35631      $('[data-js="close-button-alert-price-change"]').on('click', function () {
35632        $('.price-change-warning').addClass('d-none');
35633      });
35634    }
35635  }, {
35636    key: 'setWarningAffix',
35637    value: function setWarningAffix() {
35638      $(window).on('scroll', function (event) {
35639        var scrollValue = $(window).scrollTop();
35640        if (scrollValue > 36) {
35641          $('.price-change-warning').addClass('affix');
35642        } else {
35643          $('.price-change-warning').removeClass('affix');
35644        }
35645      });
35646    }
35647  }, {
35648    key: 'isSeatOccuped',
35649    value: function isSeatOccuped(seatNumber, listPassengers) {
35650      for (var i = 0; i < listPassengers.length; i++) {
35651        var seat = void 0;
35652        switch (this.step) {
35653          case 0:
35654            seat = listPassengers[i].seatDeparture.seatNumber;
35655            break;
35656          case 1:
35657            seat = this.connectionStep === 0 ? listPassengers[i].seatDepartureConnection.seatNumber : listPassengers[i].seatDepartureConnection2.seatNumber;
35658            break;
35659          case 2:
35660            seat = listPassengers[i].seatReturn.seatNumber;
35661            break;
35662          case 3:
35663            seat = this.connectionStep === 0 ? listPassengers[i].seatReturnConnection.seatNumber : listPassengers[i].seatReturnConnection2.seatNumber;
35664            break;
35665        }
35666        if (seat === seatNumber) return i;
35667      }
35668      return -1;
35669    }
35670  }, {
35671    key: 'hasFreeSeat',
35672    value: function hasFreeSeat(listPassengers) {
35673      for (var i = 0; i < listPassengers.length; i++) {
35674        var seatNumber = void 0;
35675        switch (this.step) {
35676          case 0:
35677            seatNumber = listPassengers[i].seatDeparture.seatNumber;
35678            break;
35679          case 1:
35680            var seatTypeIDA = this.connectionStep === 0 ? listPassengers[i].seatDepartureC
35680onnection : listPassengers[i].seatDepartureConnection2;
35681
35682            seatNumber = seatTypeIDA.seatNumber;
35683            break;
35684          case 2:
35685            seatNumber = listPassengers[i].seatReturn.seatNumber;
35686            break;
35687          case 3:
35688            var seatTypeVOLTA = this.connectionStep === 0 ? listPassengers[i].seatReturnConnection : listPassengers[i].seatReturnConnection2;
35689
35690            seatNumber = seatTypeVOLTA.seatNumber;
35691            break;
35692        }
35693        if (!seatNumber || seatNumber.length === 0) return true;
35694      }
35695      return false;
35696    }
35697  }, {
35698    key: 'fillArrayTrips',
35699    value: function fillArrayTrips() {
35700      var boughtOffers = this.cart._listOffer;
35701      var formData = this.formData;
35702      var dep = boughtOffers[0];
35703      var depLabel = dep._isDeparture ? "IDA" : "VOLTA";
35704      var retLabel = "VOLTA";
35705      var stopLabel = " - CONEXÃO";
35706
35707      this.trips[0] = new Trip(dep._service, true, dep._company._origin._id, dep._company._origin._label, dep._company._destination._id, dep._company._destination._label, DateFormatter.extractDate(dep._company._arrivingDate), DateFormatter.extractDate(dep._company._departureDate), DateFormatter.extractHour(dep._company._departureDate), DateFormatter.extractHour(dep._company._arrivingDate), depLabel, dep._token);
35708
35709      this.hour.text(DateFormatter.extractHour(dep._company._departureDate));
35710
35711      this.trips[1] = [];
35712
35713      var depConn = dep._connection;
35714
35715      if (depConn) {
35716        if (depConn.secondLeg) {
35717          var c = depConn.secondLeg;
35718          this.trips[0].destinationLabel = c.origin.description;
35719
35720          this.trips[1].push(new Trip(dep._service, true, c.origin.id, c.origin.description, c.destination.id, c.destination.description, c.arrivingDate ? DateFormatter.extractDate(c.arrivingDate) : '', c.departureDate ? DateFormatter.extractDate(c.departureDate) : '', c.departureDate ? DateFormatter.extractHour(c.departureDate) : '', c.arrivingDate ? DateFormatter.extractHour(c.arrivingDate) : '', depLabel + stopLabel, c.token, c.origin.id, c.serviceId, 1));
35721        }
35722
35723        if (depConn.thirdLeg) {
35724          var _c = depConn.thirdLeg;
35725
35726          this.trips[1].push(new Trip(dep._service, true, _c.origin.id, _c.origin.description, _c.destination.id, _c.destination.description, _c.arrivingDate ? DateFormatter.extractDate(_c.arrivingDate) : '', _c.departureDate ? DateFormatter.extractDate(_c.departureDate) : '', _c.departureDate ? DateFormatter.extractHour(_c.departureDate) : '', _c.arrivingDate ? DateFormatter.extractHour(_c.arrivingDate) : '', depLabel + stopLabel, _c.token, _c.origin.id, _c.serviceId, 2));
35727        }
35728      }
35729
35730      if (!formData.departureOnly) {
35731        var ret = boughtOffers[1];
35732        this.trips[2] = new Trip(ret._service, false, ret._company._origin._id, ret._company._origin._label, ret._company._destination._id, ret._company._destination._label, DateFormatter.extractDate(ret._company._arrivingDate), DateFormatter.extractDate(ret._company._departureDate), DateFormatter.extractHour(dep._company._departureDate), DateFormatter.extractHour(dep._company._arrivingDate), retLabel, ret._token);
35733
35734        this.trips[3] = [];
35735
35736        var retConn = ret._connection;
35737
35738        if (retConn) {
35739          if (retConn.secondLeg) {
35740            var _c2 = retConn.secondLeg;
35741            this.trips[2].destinationLabel = _c2.origin.description;
35742
35743            this.trips[3].push(new Trip(ret._service, false, _c2.origin.id, _c2.origin.description, _c2.destination.id, _c2.destination.description, _c2.arrivingDate ? DateFormatter.extractDate(_c2.arrivingDate) : '', _c2.departureDate ? DateFormatter.extractDate(_c2.departureDate) : '', _c2.departureDate ? DateFormatter.extractHour(_c2.departureDate) : '', _c2.arrivingDate ? DateFormatter.extractHour(_c2.arrivingDate) : '', retLabel + stopLabel, _c2.token, _c2.origin.id, _c2.serviceId, 1));
35744          }
35745
35746          if (retConn.thirdLeg) {
35747            var _c3 = retConn.thirdLeg;
35748            this.trips[3].push(new Trip(ret._service, false, _c3.origin.id, _c3.origin.description, _c3.destination.id, _c3.destination.description, _c3.arrivingDate ? DateFormatter.extractDate(_c3.arrivingDate) : '', _c3.departureDate ? DateFormatter.extractDate(_c3.departureDate) : '', _c3.departureDate ? DateFormatter.extractHour(_c3.departureDate) : '', _c3.arrivingDate ? DateFormatter.extractHour(_c3.arrivingDate) : '', retLabel + stopLabel, _c3.token, _c3.origin.id, _c3.serviceId, 2));
35749          }
35750        }
35751      }
35752
35753      this.proceedToNextStep(this.step);
35754    }
35755  }, {
35756    key: 'initBtnProceed',
35757    value: function initBtnProceed() {
35758      var _this3 = this;
35759
35760      this.$btnProceed.off('click').click(function (e) {
35761        return _this3.proceedOnClick(e);
35762      });
35763    }
35764  }, {
35765    key: 'disableBtnProceed',
35766    value: function disableBtnProceed() {
35767      this.$btnProceed.off('click');
35768      this.$btnProceed.attr('disabled', 'disabled');
35769    }
35770  }, {
35771    key: 'closeErrorMessage',
35772    value: function closeErrorMessage() {
35773      $('body').css('overflow-y', 'auto');
35774      OverlayService.hide();
35775      this.$errorContainer.fadeOut();
35776    }
35777  }, {
35778    key: 'showErrorMessage',
35779    value: function showErrorMessage(message, callback) {
35780      AlertConfirmation.showAEM('data-js="alert-protocol-sending-error"');
35781
35782      if (callback) callback();
35783    }
35784  }, {
35785    key: 'proceedToNextStep',
35786    value: function proceedToNextStep(step) {
35787      var _this4 = this;
35788
35789      var isConnectionStep = Array.isArray(this.trips[step]) && this.trips[step] && this.trips[step].length > 0;
35790
35791      if (Array.isArray(this.trips[step]) && this.trips[step].length === 0) {
35792        this.step++;
35793        return this.proceedToNextStep(this.step);
35794      }
35795
35796      var elem = null;
35797
35798      if (isConnectionStep) {
35799        var connections = this.trips[step];
35800        elem = connections[this.connectionStep];
35801
35802        if (!elem) {
35803          this.connectionStep = 0;
35804          this.step++;
35805          return this.proceedToNextStep(this.step);
35806        }
35807      } else {
35808        elem = this.trips[step];
35809      }
35810
35811      if (elem) {
35812        this.$tripLabelWay.text(elem.title);
35813        this.getSeats(elem, function (err, data) {
35814          if (!err) {
35815            var apiResult = data.result;
35816
35817            if (!elem.originLabel || elem.originLabel === "" || elem.originLabel === null || !elem.destinationLabel || elem.destinationLabel === "" || elem.destinationLabel === null) {
35818              elem.originLabel = apiResult.origin.city;
35819              elem.destinationLabel = apiResult.destination.city;
35820            }
35821
35822            if ((!elem._departureDate || elem._departureDate === "" || elem._departureDate === null) && apiResult.date) {
35823              elem._departureDate = apiResult.date;
35824            }
35825
35826            _this4.updateView(data.result.seatMap, elem);
35827            LoaderService.hide();
35828          }
35829        });
35830        return;
35831      }
35832
35833      if (step >= this.trips.length) {
35834        this.cartComponent.cartService.updateStorage();
35835        $(location).attr('href', $('#reschedulePaymentPagePathV2').val());
35836        return;
35837      }
35838
35839      this.step++;
35840      this.proceedToNextStep(this.step);
35841    }
35842  }, {
35843    key: 'getSeats',
35844    value: function getSeats(tripData, done) {
35845      var body = {
35846        token: tripData.token
35847      };
35848
35849      var headers = {
35850        version: 2
35851      };
35852
35853      var saleplatform = SessionStorage.get('utm_saleplatform');
35854      saleplatform ? body.SalePlatform = this.saleplatform : body.SalePlatform = "SITES-UTP";
35855
35856      LoaderService.show();
35857      HttpService.post('getVehicles', body, headers).then(function (data) {
35858        LoaderService.hide();
35859        if (done) done(null, data);
35860      }).catch(function (err) {
35861        Alert.show(i18n('status_error'));
35862        LoaderService.hide();
35863        if (done) done(err);
35864      });
35865    }
35866  }, {
35867    key: 'updateView',
35868    value: function updateView(seatList, trip) {
35869      Utils.scrollTop();
35870      Utils.scrollTop($('.bus-map-seat'));
35871      var validateDepartureDate = DateFormatter.getValidDateFormat(trip._departureDate);
35872      var dayName = DateFormatter.getDaysArray()[validateDepartureDate.getDay()];
35873
35874      var isMobile = Utils.isMobile();
35875      var formatted = isMobile ? DateFormatter.formatDate(trip._departureDate) : DateFormatter.getFullDate(trip._departureDate);
35876
35877      if (!formatted) formatted = '';
35878
35879      this.$dateLabel.text(isMobile ? formatted.slice(0, 5) : formatted.slice(0, 9));
35880      this.$dayLabel.text(dayName.substr(0, 3) + ',');
35881      if (trip._hourDestination && trip._hourDestination !== "") {
35882        this.hour.text(Utils.capitalize(trip._hourDestination));
35883      }
35884
35885      if (this.$originLabel.find('.cmp-text').length > 0) {
35886        this.$originLabel.find('.cmp-text').text(Utils.capitalize(trip.originLabel));
35887      } else {
35888        this.$originLabel.text(Utils.capitalize(trip.originLabel));
35889      }
35890
35891      if (this.$destinationLabel.find('.cmp-text').length > 0) {
35892        this.$destinationLabel.find('.cmp-text').text(Utils.capitalize(trip.destinationLabel));
35893      } else {
35894        this.$destinationLabel.text(Utils.capitalize(trip.destinationLabel));
35895      }
35896      this.hour.text(Utils.capitalize(trip._hourDestination));
35897      this.initPassengerList();
35898      this.initMapBus(seatList);
35899      var listPassengersInfo = this.cartComponent.cartService.passengers;
35900      this.toggleProceedButton(listPassengersInfo);
35901      this.initLabel();
35902    }
35903  }, {
35904    key: 'proceedOnClick',
35905    value: function proceedOnClick(e) {
35906      var _this5 = this;
35907
35908      e.stopImmediatePropagation();
35909      this.cartComponent.cartService.updateStorage();
35910      setTimeout(function () {
35911        $('#floating-div').css('top', '0');
35912        if (_this5.step === 0 && (!_this5.trips[1] || _this5.trips[1].length === 0)) {
35913          _this5.connectionStep = 0;
35914          _this5.step = 2;
35915          return _this5.proceedToNextStep(_this5.step);
35916        }
35917
35918        if (_this5.step === 1 || _this5.step === 3) {
35919          var connections = _this5.trips[_this5.step];
35920
35921          if (connections && connections[_this5.connectionStep + 1]) {
35922            _this5.connectionStep++;
35923            return _this5.proceedToNextStep(_this5.step);
35924          }
35925        }
35926
35927        _this5.connectionStep = 0;
35928        _this5.step++;
35929        _this5.proceedToNextStep(_this5.step);
35930      }, 300);
35931    }
35932  }, {
35933    key: 'initPassengerList',
35934    value: function initPassengerList() {
35935      var _this6 = this;
35936
35937      var listPassengers = this.cartComponent.cartService.passengers;
35938      this.$passengerList.html('');
35939
35940      listPassengers.forEach(function (el, i) {
35941        var seat = void 0;
35942
35943        switch (_this6.step) {
35944          case 0:
35945            seat = el.seatDeparture;
35946            break;
35947          case 1:
35948            seat = el.seatDepartureConnection;
35949            break;
35950          case 2:
35951            seat = el.seatReturn;
35952            break;
35953          case 3:
35954            seat = el.seatReturnConnection;
35955            break;
35956        }
35957
35958        var seatNumber = seat.seatNumber;
35959        var $passenger = _this6.$passengerItemTemplate.clone();
35960
35961        $passenger.attr('index', i);
35962        $passenger.find('[data-js="person-name"]').text(el.name);
35963        $passenger.find('[data-js="passenger-index"]').text('Passageiro ' + (i + 1));
35964        $passenger.find('.reservation-passenger-btn').attr('id', 'reservation-seat-' + i);
35965        var $passengerSeat = _this6.$passengerSeatTemplate.clone();
35966        if (seatNumber) {
35967          $passengerSeat.find('.seat-number').text(seatNumber);
35968          $passengerSeat.show();
35969          $passenger.find('.reservation-passenger-seat').addClass('visible');
35970          $passenger.find('.reservation-label').addClass('selected').text(i18n('seat_selected'));
35971        } else if (!seatNumber && el._type === 'CHILD') {
35972          $passengerSeat.find('.seat-number').text('');
35973          $passengerSeat.show();
35974          $passenger.find('.reservation-label').addClass('selected').text(i18n('seat_child'));
35975          $passenger.find('.reservation-icon img').attr('src', '../../assets/images/child.png');
35976          $passenger.find('.reservation-passenger-seat').hide();
35977        } else {
35978          $passengerSeat.find('.seat-number').text('');
35979          $passengerSeat.hide();
35980        }
35981
35982        $passenger.find('.reservation-passenger-seat').html($passengerSeat);
35983        if (el._type !== 'CHILD') {
35984          $passenger.click({
35985            'seat': seat
35986          }, function (e) {
35987            return _this6.passengerOnClick(e);
35988          });
35989        } else {
35990          $passenger.addClass('disabled');
35991        }
35992
35993        if (i == 0) $passenger.addClass('active');
35994
35995        $passenger.removeClass('invisible');
35996        _this6.$passengerList.append($passenger);
35997      });
35998      this.listenEvents();
35999    }
36000  }, {
36001    key: 'initMapBus',
36002    value: function initMapBus(seatList) {
36003      var _this7 = this;
36004
36005      var listPassengers = this.cartComponent.cartService.passengers;
36006      this.busMapSeat.init(seatList);
36007      var filteredSeatList = seatList.filter(function (s) {
36008        return s.number != '';
36009      });
36010
36011      this.busMapSeat.$mapBus.find('.outer-seat').map(function (i, seatDiv) {
36012        var $seat = $(seatDiv);
36013        var seat = filteredSeatList[i];
36014        var occupedSeat = _this7.isSeatOccuped(seat.number, listPassengers);
36015
36016        if (occupedSeat >= 0) {
36017          _this7.busMapSeat.occupySeat($seat);
36018          if (occupedSeat == 0) _this7.busMapSeat.selectSeat($seat, seat.number);
36019        }
36020
36021        $seat.click({
36022          'seatInfo': seat
36023        }, function (e) {
36024          return _this7.seatOnClick(e);
36025        });
36026
36027        return $seat;
36028      });
36029
36030      var checkBusSize = function reference() {
36031        var _Utils$getWindowSize = Utils.getWindowSize(),
36032          width = _Utils$getWindowSize.width,
36033          breakpoints = _Utils$getWindowSize.breakpoints;
36034
36035        if (width < breakpoints.LGR) {
36036          $('#floating-div').css('position', 'static');
36037        } else if (width >= breakpoints.LGR) {
36038          $('#floating-div').css('position', 'relative');
36039        }
36040        return reference;
36041      }(); //auto-run
36042      $(window).resize(function () {
36043        return checkBusSize();
36044      });
36045    }
36046  }, {
36047    key: 'passengerOnClick',
36048    value: function passengerOnClick(e) {
36049      var seat = e.data.seat || e.data.seatInfo;
36050      var seatNumber = seat.seatNumber;
36051      var $mapBus = this.busMapSeat.$mapBus;
36052      var $passenger = $(e.currentTarget);
36053      var $currentSeat = $mapBus.find('[data-js="seat-' + seatNumber + '"]').find('.inner-seat');
36054      $passenger.siblings().removeClass('active');
36055      $passenger.addClass('active');
36056      var $previouslySelected = $mapBus.find('.selected');
36057      this.busMapSeat.unselectSeat($previouslySelected, seatNumber);
36058      this.busMapSeat.occupySeat($previouslySelected);
36059      this.busMapSeat.occupySeat($currentSeat);
36060      this.busMapSeat.selectSeat($currentSeat, seatNumber);
36061
36062      this.errorOnSeat = false;
36063    }
36064  }, {
36065    key: 'hasPriceChanged',
36066    value: function hasPriceChanged(_, offer, seat) {
36067      if (seat && parseInt(offer.service) == seat.service) {
36068        if (parseFloat(seat.price) > parseFloat(offer.price)) return 1;
36069        if (parseFloat(seat.price) < parseFloat(offer.price)) return 2;
36070      }
36071      return 0;
36072    }
36073  }, {
36074    key: 'isShowAlert',
36075    value: function isShowAlert(el) {
36076      if (!$(el).hasClass('.showedInDeparture') && this.step == 0) {
36077        $(el).addClass('.showedInDeparture');
36078        return true;
36079      }
36080
36081      if (!$(el).hasClass('.showedInReturn') && this.step != 0) {
36082        $(el).addClass('.showedInReturn');
36083        return true;
36084      }
36085    }
36086  }, {
36087    key: 'showAlert',
36088    value: function showAlert(msg) {
36089      var showCartLink = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
36090
36091      var alertPriceWarning = $('.price-change-warning');
36092      var alertPriceWarningMsg = alertPriceWarning.find('[data-js="price-change-msg"]');
36093      var position = alertPriceWarning.offset().top + alertPriceWarning.height();
36094
36095      if (showCartLink) $('.cart-warning').show(); else $('.cart-warning').hide();
36096
36097      if (this.isShowAlert(alertPriceWarning)) {
36098        alertPriceWarningMsg.text(msg);
36099        alertPriceWarning.removeClass('d-none');
36100
36101        $('html,body').animate({
36102          scrollTop: position / 1.8
36103        }, 500);
36104      }
36105    }
36106  }, {
36107    key: 'shouldAlertShowUp',
36108    value: function shouldAlertShowUp(passenger, seat) {
36109      var listOffer = this.cartComponent.cartService.listOffer;
36110      var showAlert = 0;
36111
36112      for (var j = 0; j < listOffer.length && showAlert == 0; j++) {
36113        var offer = listOffer[j];
36114
36115        if (parseInt(offer.service) == seat.service) showAlert = this.hasPriceChanged(passenger, offer, seat);
36116      }
36117
36118      switch (showAlert) {
36119        case 1:
36120          localStorage.alertType = JSON.stringify({
36121            id: showAlert,
36122            desc: 'MORE'
36123          });
36124          this.showAlert($('[data-js="price-change-msg-less"]').val());
36125          break;
36126        case 2:
36127          localStorage.alertType = JSON.stringify({
36128            id: showAlert,
36129            desc: 'LESS'
36130          });
36131          this.showAlert($('[data-js="price-change-msg-student"]').val());
36132          break;
36133        default:
36134          localStorage.alertType = JSON.stringify({
36135            id: 0,
36136            desc: 'NONE'
36137          });
36138          $('.bus-map-container').removeClass('active');
36139      }
36140    }
36141  }, {
36142    key: 'selectNextPassenger',
36143    value: function selectNextPassenger() {
36144      var $selectedPassenger = this.$passengerList.find('.active');
36145      if ($selectedPassenger.next().length > 0) {
36146        $selectedPassenger.next().trigger('click');
36147      }
36148    }
36149  }, {
36150    key: 'cancelSeat',
36151    value: function cancelSeat(passengerSeatInfo, passengerInfo, index) {
36152      var _this8 = this;
36153
36154      var tripData = this.trips[this.step];
36155      var reactivateCheckin = SessionStorage.get('reactivateCheckin');
36156      var passengersToRepricing = SessionStorage.get('passengersToRepricing');
36157      var passengers = passengersToRepricing.passengers;
36158
36159
36160      var getFinderTrip = function getFinderTrip() {
36161        var finderTrip = passengersToRepricing.finderTrip;
36162
36163
36164        return finderTrip;
36165      };
36166
36167      var getControlWay = function getControlWay() {
36168        if (tripData.going) {
36169          if (_this8.isSeletecOnlyReturnTrip) {
36170            if (!_this8.returnConnection) {
36171              return passengers[index].controlReturn;
36172            } else {
36173              return passengers[index].controlReturnConnection;
36174            }
36175          } else if (!_this8.goingConnection) {
36176            return passengers[index].controlDeparture;
36177          } else {
36178            return passengers[index].controlDepartureConnection;
36179          }
36180        } else {
36181          if (!_this8.returnConnection) {
36182            return passengers[index].controlReturn;
36183          } else {
36184            return passengers[index].controlReturnConnection;
36185          }
36186        }
36187      };
36188
36189      var getSystemNumber = function getSystemNumber() {
36190        if (tripData.going) {
36191          if (_this8.isSeletecOnlyReturnTrip) {
36192            if (!_this8.returnConnection) {
36193              return passengers[index].systemNumberReturn;
36194            } else {
36195              return passengers[index].systemNumberReturnConnection;
36196            }
36197          }
36198
36199          if (!_this8.goingConnection) {
36200            return passengers[index].systemNumberDeparture;
36201          } else {
36202            return passengers[index].systemNumberDepartureConnection;
36203          }
36204        } else {
36205          if (!_this8.returnConnection) {
36206            return passengers[index].systemNumberReturn;
36207          } else {
36208            return passengers[index].systemNumberReturnConnection;
36209          }
36210        }
36211      };
36212
36213      var getReactivateCheckin = function getReactivateCheckin() {
36214        var reactivateCheckin = SessionStorage.get('reactivateCheckin');
36215
36216        return reactivateCheckin.reactivateCheckin;
36217      };
36218
36219      var bodyRemarkV2 = {
36220        SeatModel: {
36221          going: tripData.going,
36222          seat: passengerSeatInfo.seatNumber,
36223          token: tripData.token
36224        },
36225        LockSeat: false,
36226        Control: getControlWay(),
36227        Finder: getFinderTrip(),
36228        SystemNumber: +getSystemNumber(),
36229        ReactivateCheckin: getReactivateCheckin(),
36230        SalePlatform: "SITES-UTP"
36231      };
36232
36233      var headers = {
36234        'Authorization': '' + SessionStorage.get('jca_token'),
36235        'sessionseatlock': SessionStorage.get('sessionseatlock'),
36236        'version': 2
36237      };
36238
36239      return HttpService.post('lockSeatRemark', bodyRemarkV2, headers);
36240    }
36241  }, {
36242    key: 'blockSeat',
36243    value: function blockSeat(seatPassenger, passenger, index) {
36244      var _this9 = this;
36245
36246      var tripData = this.trips[this.step];
36247      var passengersToRepricing = SessionStorage.get('passengersToRepricing');
36248      var passengers = passengersToRepricing.passengers;
36249
36250
36251      var getFinderTrip = function getFinderTrip() {
36252        var finderTrip = passengersToRepricing.finderTrip;
36253
36254
36255        return finderTrip;
36256      };
36257
36258      var getControlWay = function getControlWay() {
36259        if (tripData.going) {
36260          if (_this9.isSeletecOnlyReturnTrip) {
36261            if (!_this9.returnConnection) {
36262              return passengers[index].controlReturn;
36263            } else {
36264              return passengers[index].controlReturnConnection;
36265            }
36266          } else if (!_this9.goingConnection) {
36267            return passengers[index].controlDeparture;
36268          } else {
36269            return passengers[index].controlDepartureConnection;
36270          }
36271        } else {
36272          if (!_this9.returnConnection) {
36273            return passengers[index].controlReturn;
36274          } else {
36275            return passengers[index].controlReturnConnection;
36276          }
36277        }
36278      };
36279
36280      var getSystemNumber = function getSystemNumber() {
36281        if (tripData.going) {
36282          if (_this9.isSeletecOnlyReturnTrip) {
36283            if (!_this9.returnConnection) {
36284              return passengers[index].systemNumberReturn;
36285            } else {
36286              return passengers[index].systemNumberReturnConnection;
36287            }
36288          }
36289
36290          if (!_this9.goingConnection) {
36291            return passengers[index].systemNumberDeparture;
36292          } else {
36293            return passengers[index].systemNumberDepartureConnection;
36294          }
36295        } else {
36296          if (!_this9.returnConnection) {
36297            return passengers[index].systemNumberReturn;
36298          } else {
36299            return passengers[index].systemNumberReturnConnection;
36300          }
36301        }
36302      };
36303
36304      var getReactivateCheckin = function getReactivateCheckin() {
36305        var reactivateCheckin = SessionStorage.get('reactivateCheckin');
36306
36307        return reactivateCheckin.reactivateCheckin;
36308      };
36309
36310      var bodyRemarkV2 = {
36311        SeatModel: {
36312          going: tripData.going,
36313          child: passenger.child ? true : false,
36314          seat: seatPassenger,
36315          token: tripData.token
36316        },
36317        LockSeat: true,
36318        Control: getControlWay(),
36319        Finder: getFinderTrip(),
36320        SystemNumber: parseInt(getSystemNumber()),
36321        ReactivateCheckin: getReactivateCheckin(),
36322        SalePlatform: "SITES-UTP"
36323      };
36324
36325      if (passenger.hasDiscount) body.SeatModel.category = 31;
36326
36327      var headers = {
36328        'Authorization': '' + SessionStorage.get('jca_token'),
36329        'sessionseatlock': SessionStorage.get('sessionseatlock'),
36330        'version': 2
36331      };
36332
36333      return HttpService.post('lockSeatRemark', bodyRemarkV2, headers);
36334    }
36335  }, {
36336    key: 'resetSeat',
36337    value: function resetSeat(passengerSeatInfo) {
36338      passengerSeatInfo.transactionId = '';
36339      passengerSeatInfo.seatNumber = '';
36340      passengerSeatInfo.price = 0;
36341      passengerSeatInfo.rate = 0;
36342      passengerSeatInfo.insurance = 0;
36343      passengerSeatInfo.insuranceW2i = 0;
36344      passengerSeatInfo.tax = 0;
36345      passengerSeatInfo.toll = 0;
36346      passengerSeatInfo.other = 0;
36347      passengerSeatInfo.service = '';
36348      passengerSeatInfo.actualAmount = 0;
36349      passengerSeatInfo.balanceAmount = 0;
36350      passengerSeatInfo.newTicketAmount = 0;
36351      return passengerSeatInfo;
36352    }
36353  }, {
36354    key: 'unselectSeat',
36355    value: function unselectSeat($seat, passengerSeatInfo, data) {
36356      var $selectedPassenger = this.$passengerList.find('.active');
36357      var $seatNumber = $selectedPassenger.find('.seat-number');
36358      this.busMapSeat.unselectSeat($seat);
36359
36360      if ($seat.hasClass('occuped')) this.busMapSeat.freeSeat($seat);
36361
36362      $seatNumber.parent().hide();
36363      passengerSeatInfo = this.resetSeat(passengerSeatInfo);
36364      return passengerSeatInfo;
36365    }
36366  }, {
36367    key: 'updateSeat',
36368    value: function updateSeat(number, passengerSeatInfo, data) {
36369      passengerSeatInfo.seatNumber = number;
36370      passengerSeatInfo.transactionId = data.result.transaction;
36371      passengerSeatInfo.price = data.result.price.total;
36372      passengerSeatInfo.rate = data.result.price.tarifa;
36373      passengerSeatInfo.insurance = data.result.price.seguro;
36374      passengerSeatInfo.insuranceW2i = data.result.insurance.value;
36375      passengerSeatInfo.toll = data.result.price.pedagio;
36376      passengerSeatInfo.other = +data.result.price.outros + +data.result.price.taxaEmbarque;
36377      passengerSeatInfo.tax = data.result.price.imposto ? data.result.price.imposto : 0;
36378      passengerSeatInfo.boardingFee = data.result.price.taxaEmbarque;
36379      passengerSeatInfo.service = data.result.service;
36380      passengerSeatInfo.actualAmount = data.result.actualAmount;
36381      passengerSeatInfo.balanceAmount = data.result.balanceAmount;
36382      passengerSeatInfo.newTicketAmount = data.result.newTicketAmount;
36383      passengerSeatInfo.penaltyAmount = data.result.penaltyAmount;
36384      return passengerSeatInfo;
36385    }
36386  }, {
36387    key: 'selectSeat',
36388    value: function selectSeat($seat, numero, passengerSeatInfo, data) {
36389      var $selectedPassenger = this.$passengerList.find('.active');
36390      var $seatNumber = $selectedPassenger.find('.seat-number');
36391      $seatNumber.closest('.reservation-passenger-seat').addClass('visible');
36392      $seatNumber.closest('.content').find('.reservation-label').addClass('selected').text(i18
36392n('seat_selected'));
36393
36394      if (passengerSeatInfo) passengerSeatInfo = this.updateSeat(numero, passengerSeatInfo, data);
36395
36396      this.busMapSeat.occupySeat($seat);
36397      this.busMapSeat.selectSeat($seat, numero);
36398      $($seat).parent().css('outline', 'none');
36399      $seatNumber.text(numero);
36400      $seatNumber.parent().show();
36401      this.selectNextPassenger();
36402
36403      return passengerSeatInfo;
36404    }
36405  }, {
36406    key: 'toggleProceedButton',
36407    value: function toggleProceedButton(listPassengersInfo) {
36408      var passengerNotChild = listPassengersInfo.filter(function (passenger) {
36409        return passenger._type !== 'CHILD';
36410      });
36411
36412      if (this.hasFreeSeat(passengerNotChild)) {
36413        this.disableBtnProceed();
36414      } else {
36415        this.$btnProceed.removeAttr('disabled');
36416        this.initBtnProceed();
36417      }
36418    }
36419  }, {
36420    key: 'getPassengerSeat',
36421    value: function getPassengerSeat(passengerInfo) {
36422      switch (this.step) {
36423        case 0:
36424          return passengerInfo.seatDeparture;
36425        case 1:
36426          return passengerInfo.seatDepartureConnection;
36427        case 2:
36428          return passengerInfo.seatReturn;
36429        case 3:
36430          return passengerInfo.seatReturnConnection;
36431      }
36432    }
36433  }, {
36434    key: 'clickCancelSeat',
36435    value: function clickCancelSeat($seat, passengerSeatInfo, passengerInfo, index) {
36436      var _this10 = this;
36437
36438      LoaderService.show();
36439      return $.when(this.cancelSeat(passengerSeatInfo, passengerInfo, index)).then(function (data) {
36440        if (!data.success) throw new Error();
36441
36442        LoaderService.hide();
36443        _this10.errorOnSeat = false;
36444        passengerSeatInfo = _this10.unselectSeat($seat, passengerSeatInfo, data);
36445      }).catch(function (err) {
36446        LoaderService.hide();
36447        Alert.show(i18n('status_error'));
36448        // send2Analytics(data.cancelamentoPoltrona.erro.descricaoErro)
36449        _this10.errorOnSeat = true;
36450      });
36451    }
36452  }, {
36453    key: 'seatOnClick',
36454    value: function seatOnClick(e) {
36455      var _this11 = this;
36456
36457      var $selectedPassenger = this.$passengerList.find('.active');
36458      var $seat = $(e.currentTarget).find('.inner-seat');
36459      var $selectedSeat = this.busMapSeat.$mapBus.find('.selected');
36460      var listPassengersInfo = this.cartComponent.cartService.passengers;
36461      var index = parseInt($selectedPassenger.attr('index'));
36462      var seatInfo = e.data.seatInfo;
36463      var passengerInfo = listPassengersInfo[index];
36464      var passengerSeatInfo = this.getPassengerSeat(passengerInfo);
36465
36466      if ($selectedPassenger.length === 0) return;
36467
36468      var tripData = void 0;
36469      if (this.step === 1 || this.step === 3) {
36470        tripData = this.trips[this.step][this.connectionStep];
36471      } else {
36472        tripData = this.trips[this.step];
36473      }
36474
36475      var cancelPromise = Promise.resolve();
36476
36477      if ($selectedSeat.html() == $seat.html()) {
36478        this.clickCancelSeat($seat, passengerSeatInfo, passengerInfo, index).then(function () {
36479          _this11.updateCart(listPassengersInfo);
36480        });
36481      } else {
36482
36483        if ($seat.hasClass('occuped')) return;
36484
36485        if ($selectedSeat.length > 0) {
36486          cancelPromise = this.clickCancelSeat($selectedSeat, passengerSeatInfo, passengerInfo, index).then(function () {
36487            _this11.updateCart(listPassengersInfo);
36488          });
36489        }
36490
36491        cancelPromise.then(function () {
36492          LoaderService.show();
36493          _this11.blockSeat(seatInfo.number, passengerInfo, index).then(function (data) {
36494            LoaderService.hide();
36495
36496            if (!data.success) throw new Error();
36497
36498            _this11.errorOnSeat = false;
36499            passengerSeatInfo = _this11.selectSeat($seat, seatInfo.number, passengerSeatInfo, data);
36500            _this11.updateCart(listPassengersInfo);
36501
36502            if (!tripData._hourDestination || !tripData._hourDestination === "") {
36503              tripData._hourDestination = DateFormatter.extractHour(data.result.seatResponse.service.departureDate);
36504              _this11.hour.text(Utils.capitalize(tripData._hourDestination));
36505            }
36506
36507            _this11.shouldAlertShowUp(passengerInfo, passengerSeatInfo);
36508          }).catch(function (err) {
36509            LoaderService.hide();
36510            Alert.show('Este assento está indiponível para marcação. Selecione um novo assento.');
36511            _this11.errorOnSeat = true;
36512            _this11.proceedToNextStep(_this11.step);
36513            return;
36514          });
36515        });
36516      }
36517    }
36518  }, {
36519    key: 'updateCart',
36520    value: function updateCart(listPassengersInfo) {
36521      this.cartComponent.updateCartView();
36522      this.cartComponent.initPassengerList(SessionStorage.get('cart'));
36523      this.toggleProceedButton(listPassengersInfo);
36524    }
36525  }, {
36526    key: 'scrollFloatingDiv',
36527    value: function scrollFloatingDiv() {
36528      $(window).scroll(function () {
36529
36530        var distanceToTop = $(document).scrollTop();
36531        var floating = $('#floating-div');
36532        var floatingHeight = floating.height();
36533        var busMapHeight = $('[data-js="map-bus"]').height();
36534        var busFrontHeight = 0;
36535        var busTotalHeight = busMapHeight + busFrontHeight;
36536        var freeSpace = busTotalHeight - floatingHeight;
36537
36538        if (freeSpace > 0) {
36539          floating.animate({
36540            top: (distanceToTop > freeSpace ? freeSpace : distanceToTop) + "px"
36541          }, {
36542            duration: 400,
36543            queue: false
36544          });
36545        }
36546      });
36547    }
36548  }]);
36549
36550  return SeatReservationRemark;
36551}();
36552/** * FIM
36553 * LOGICA TELA RESERVA DE ASSENTOS
36554 *
36555 */
36556'use strict';
36557
36558
36559var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
36560
36561function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
36562
36563/**
36564 * INICIO
36565 * LOGICA TELA RESERVA DE ASSENTOS
36566 *
36567 */
36568
36569var SeatReservation = function () {
36570  function SeatReservation($) {
36571    var _this = this;
36572
36573    _classCallCheck(this, SeatReservation);
36574
36575    this.formData = SessionStorage.get('formData');
36576    this.cart = SessionStorage.get('cart');
36577
36578    if ((!this.formData || !this.cart) && $('#homePagePath') && $('#homePagePath').val() && (!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false')) {
36579      $(location).attr('href', $('#homePagePath').val());
36580    }
36581
36582    this.$passengerList = $('[data-js="passenger-list"]');
36583    this.$passengerItemTemplate = $('[data-js="passenger-template"]');
36584    this.$passengerSeatTemplate = $('[data-js="passenger-seat-template"]');
36585    this.$tripLabelWay = $('[data-js="trip-label-way"]');
36586    this.$itineraryLabelDeparture = $('[data-js="itinerary-label-departure"]');
36587    this.$itineraryLabelDestination = $('[data-js="itinerary-label-destination"]');
36588    this.$btnProceed = $('[data-js="btn-proceed"]');
36589    this.$originLabel = $('[data-js="summary-label-origin"]');
36590    this.$destinationLabel = $('[data-js="summary-label-destination"]');
36591    this.$errorContainer = $('.seat-error-container');
36592    this.showAlreadyBoughtAlert = $('[data-js="show-already-bought-alert"]').val() ? $('[data-js="show-already-bought-alert"]').val().toLowerCase() == "true" : '';
36593    this.$closeErrorOverlay = $('[data-js="close-overlay-seat-reservation"]');
36594    this.$dateLabel = $('[data-js="departure-date-label"]');
36595    this.$dayLabel = $('[data-js="departure-day-label"]');
36596    this.hour = $('[data-js="hour-departure"]');
36597    this.tripLabelGo = $('[data-js="trip-label-way-go"]');
36598    this.tripLabelBack = $('[data-js="trip-label-way-back"]');
36599    this.modalUpsel = $('[data-js="modal-upsel"]');
36600    this.$closeErrorOverlay.on('click', function () {
36601      _this.closeErrorMessage();
36602    });
36603    this.$closeErrorOverlay.on('focusout', function (e) {
36604      var $target = $(e.relatedTarget);
36605      if ($target.closest('.seat-error-container').length == 0) _this.$closeErrorOverlay.click();
36606    });
36607    this.cartComponent = new CartComponent($, this.formData);
36608    this.trips = [];
36609    this.busMapSeat = new BusMapSeat($);
36610    this.step = 0;
36611    this.connectionStep = 0;
36612    this.saleplatform = SessionStorage.get('utm_saleplatform');
36613    this.fillArrayTrips();
36614    this.initBtnProceed();
36615    this.scrollFloatingDiv();
36616    this.setWarningAffix();
36617    this.bottomResumeCart = $('[data-js="bottom-resume-cart"]');
36618  }
36619
36620  _createClass(SeatReservation, [{
36621    key: 'initLabel',
36622    value: function initLabel() {
36623      var _this2 = this;
36624
36625      var showGo = function showGo(connectionText) {
36626        _this2.tripLabelGo.show();
36627        if (connectionText) _this2.tripLabelGo.append(connectionText);
36628        _this2.tripLabelBack.hide();
36629        $('[data-js="arrow-label"]').removeClass('active');
36630      };
36631
36632      var showBack = function showBack(connectionText) {
36633        _this2.tripLabelGo.hide();
36634        _this2.tripLabelBack.show();
36635        if (connectionText) _this2.tripLabelBack.append(connectionText);
36636        $('[data-js="arrow-label"]').addClass('active');
36637      };
36638
36639      switch (this.step) {
36640        case 0:
36641          showGo();
36642          break;
36643        case 1:
36644          //showGo(' - Conexão');
36645          $('[data-js="trip-label-way-go"]').addClass('hide');
36646          $('[data-js="trip-label-way-go-connection"]').removeClass('hide');
36647          break;
36648        case 2:
36649          showBack();
36650          $('[data-js="trip-label-way-go-connection"]').addClass('hide');
36651          break;
36652        case 3:
36653          //showBack(' - Conexão');
36654          $('[data-js="trip-label-way-back"]').addClass('hide');
36655          $('[data-js="trip-label-way-back-connection"]').removeClass('hide');
36656          $('[data-js="trip-label-way-back-connection"]').css('display', 'block')
36657          break;
36658      }
36659    }
36660  }, {
36661    key: 'listenEvents',
36662    value: function listenEvents() {
36663      $('.reservation-passenger-item').on('click', function () {
36664
36665        if (Utils.isMobile()) {
36666          $('.bus-map-container').addClass('active');
36667          var passengerIndex = $('.reservation-passenger-item.active').find('[data-js="passenger-index"]').text();
36668          var passengerName = $('.reservation-passenger-item.active').find('[data-js="person-name"]').text();
36669
36670          $('[data-js="user-index"]').text(passengerIndex);
36671          $('[data-js="user-name"]').text(passengerName);
36672        }
36673      });
36674
36675      $('[data-js="close-bus-map"]').on('click', function () {
36676        $('.bus-map-container').removeClass('active');
36677      });
36678    }
36679  }, {
36680    key: 'setWarningAffix',
36681    value: function setWarningAffix() {
36682      $(window).on('scroll', function (event) {
36683        var scrollValue = $(window).scrollTop();
36684        if (scrollValue > 36) {
36685          $('.price-change-warning').addClass('affix');
36686        } else {
36687          $('.price-change-warning').removeClass('affix');
36688        }
36689      });
36690    }
36691  }, {
36692    key: 'isSeatOccuped',
36693    value: function isSeatOccuped(seatNumber, listPassengers) {
36694      for (var i = 0; i < listPassengers.length; i++) {
36695        var seat = void 0;
36696        switch (this.step) {
36697          case 0:
36698            seat = listPassengers[i].seatDeparture.seatNumber;
36699            break;
36700          case 1:
36701            seat = this.connectionStep === 0 ? listPassengers[i].seatDepartureConnection.seatNumber : listPassengers[i].seatDepartureConnection2.seatNumber;
36702            break;
36703          case 2:
36704            seat = listPassengers[i].seatReturn.seatNumber;
36705            break;
36706          case 3:
36707            seat = this.connectionStep === 0 ? listPassengers[i].seatReturnConnection.seatNumber : listPassengers[i].seatReturnConnection2.seatNumber;
36708            break;
36709        }
36710        if (seat === seatNumber) return i;
36711      }
36712      return -1;
36713    }
36714  }, {
36715    key: 'hasFreeSeat',
36716    value: function hasFreeSeat(listPassengers) {
36717      for (var i = 0; i < listPassengers.length; i++) {
36718        var seatNumber = void 0;
36719        switch (this.step) {
36720          case 0:
36721            seatNumber = listPassengers[i].seatDeparture.seatNumber;
36722            break;
36723          case 1:
36724            var seatTypeIDA = this.connectionStep === 0 ? listPassengers[i].seatDepartureConnection : listPassengers[i].seatDepartureConnection2;
36725
36726            seatNumber = seatTypeIDA.seatNumber;
36727            break;
36728          case 2:
36729            seatNumber = listPassengers[i].seatReturn.seatNumber;
36730            break;
36731          case 3:
36732            var seatTypeVOLTA = this.connectionStep === 0 ? listPassengers[i].seatReturnConnection : listPassengers[i].seatReturnConnection2;
36733
36734            seatNumber = seatTypeVOLTA.seatNumber;
36735            break;
36736        }
36737        if (!seatNumber || seatNumber.length === 0) return true;
36738      }
36739      return false;
36740    }
36741  }, {
36742    key: 'fillArrayTrips',
36743    value: function fillArrayTrips() {
36744      SessionStorage.remove('popUpData');
36745      var boughtOffers = this.cart._listOffer;
36746      var formData = this.formData;
36747
36748      var dep = boughtOffers[0];
36749      var depLabel = dep._isDeparture ? "IDA" : "VOLTA";
36750      var retLabel = "VOLTA";
36751      var stopLabel = " - CONEXÃO";
36752
36753      this.isReturn = dep._isDeparture ? false : true;
36754
36755      this.trips[0] = new Trip(dep._service, true, dep._company._origin._id, dep._company._origin._label, dep._company._destination._id, dep._company._destination._label, DateFormatter.extractDate(dep._company._arrivingDate), DateFormatter.extractDate(dep._company._departureDate), DateFormatter.extractHour(dep._company._departureDate), DateFormatter.extractHour(dep._company._arrivingDate), depLabel, dep._token);
36756
36757      if (this.hour.find('.cmp-text').length > 0) {
36758        this.hour.find('.cmp-text').text(DateFormatter.extractHour(dep._company._departureDate));
36759      } else {
36760        this.hour.text(DateFormatter.extractHour(dep._company._departureDate));
36761      }
36762
36763      var depConn = dep._connection;
36764
36765      if (depConn) {
36766        if (depConn.secondLeg) {
36767          this.trips[1] = [];
36768          var c = depConn.secondLeg;
36769          this.trips[0].destinationLabel = c.origin.description;
36770
36771          this.trips[1].push(new Trip(dep._service, true, c.origin.id, c.origin.description, c.destination.id, c.destination.description, c.arrivingDate ? DateFormatter.extractDate(c.arrivingDate) : '', c.departureDate ? DateFormatter.extractDate(c.departureDate) : '', c.departureDate ? DateFormatter.extractHour(c.departureDate) : '', c.arrivingDate ? DateFormatter.extractHour(c.arrivingDate) : '', depLabel + stopLabel, c.token, c.origin.id, c.serviceId, 1));
36772        }
36773
36774        if (depConn.thirdLeg) {
36775          var _c = depConn.thirdLeg;
36776          if (_c.departureDate) this.hour.text(DateFormatter.extractHour(_c.departureDate));
36777          this.trips[1].push(new Trip(dep._service, true, _c.origin.id, _c.origin.description, _c.destination.id, _c.destination.description, _c.arrivingDate ? DateFormatter.extractDate(_c.arrivingDate) : '', _c.departureDate ? DateFormatter.extractDate(_c.departureDate) : '', _c.departureDate ? DateFormatter.extractHour(_c.departureDate) : '', _c.arrivingDate ? DateFormatter.extractHour(_c.arrivingDate) : '', depLabel + stopLabel, _c.token, _c.origin.id, _c.serviceId, 2));
36778        }
36779      }
36780
36781      if (!formData.departureOnly && boughtOffers[1]) {
36782        var ret = boughtOffers[1];
36783
36784        this.trips[2] = new Trip(ret._service, false, ret._company._origin._id, ret._company._origin._label, ret._company._destination._id, ret._company._destination._label, DateFormatter.extractDate(ret._company._arrivingDate), DateFormatter.extractDate(ret._company._departureDate), DateFormatter.extractHour(ret._company._departureDate), DateFormatter.extractHour(ret._company._arrivingDate), retLabel, ret._token);
36785
36786        var retConn = ret._connection;
36787
36788        if (retConn) {
36789          if (retConn.secondLeg) {
36790            this.trips[3] = [];
36791            var _c2 = retConn.secondLeg;
36792            this.trips[2].destinationLabel = _c2.origin.description;
36793
36794            this.trips[3].push(new Trip(ret._service, false, _c2.origin.id, _c2.origin.description, _c2.destination.id, _c2.destination.description, _c2.arrivingDate ? DateFormatter.extractDate(_c2.arrivingDate) : '', _c2.departureDate ? DateFormatter.extractDate(_c2.departureDate) : '', _c2.departureDate ? DateFormatter.extractHour(_c2.departureDate) : '', _c2.arrivingDate ? DateFormatter.extractHour(_c2.arrivingDate) : '', retLabel + stopLabel, _c2.token, _c2.origin.id, _c2.serviceId, 1));
36795          }
36796
36797          if (retConn.thirdLeg) {
36798            var _c3 = retConn.thirdLeg;
36799            this.trips[3].push(new Trip(ret._service, false, _c3.origin.id, _c3.origin.description, _c3.destination.id, _c3.destination.description, _c3.arrivingDate ? DateFormatter.extractDate(_c3.arrivingDate) : '', _c3.departureDate ? DateFormatter.extractDate(_c3.departureDate) : '', _c3.departureDate ? DateFormatter.extractHour(_c3.departureDate) : '', _c3.arrivingDate ? DateFormatter.extractHour(_c3.arrivingDate) : '', retLabel + stopLabel, _c3.token, _c3.origin.id, _c3.serviceId, 2));
36800          }
36801        }
36802      }
36803
36804      this.proceedToNextStep(this.step);
36805    }
36806  }, {
36807    key: 'initBtnProceed',
36808    value: function initBtnProceed() {
36809      var _this3 = this;
36810
36811      this.$btnProceed.off('click').click(function (e) {
36812        return _this3.proceedOnClick(e);
36813      });
36814    }
36815  }, {
36816    key: 'disableBtnProceed',
36817    value: function disableBtnProceed() {
36818      this.$btnProceed.off('click');
36819      this.$btnProceed.attr('disabled', 'disabled');
36820    }
36821  }, {
36822    key: 'closeErrorMessage',
36823    value: function closeErrorMessage() {
36824      $('body').css('overflow-y', 'auto');
36825      OverlayService.hide();
36826      this.$errorContainer.fadeOut();
36827    }
36828  }, {
36829    key: 'showErrorMessage',
36830    value: function showErrorMessage(message, callback) {
36831      OverlayService.show();
36832      this.$errorContainer.fadeIn();
36833      this.$errorContainer.find('[data-js="msg-content"]').text(message);
36834      this.$closeErrorOverlay.focus();
36835      this.disableBtnProceed();
36836      $('body').css('overflow-y', 'hidden');
36837
36838      if (callback) callback();
36839    }
36840  }, {
36841    key: 'proceedToNextStep',
36842    value: function proceedToNextStep(step) {
36843      var _this4 = this;
36844
36845      var isConnectionStep = Array.isArray(this.trips[step]) && this.trips[step] && this.trips[step].length > 0;
36846
36847      if (Array.isArray(this.trips[step]) && this.trips[step].length === 0) {
36848        this.step++;
36849        return this.proceedToNextStep(this.step);
36850      }
36851
36852      var elem = null;
36853
36854      if (isConnectionStep) {
36855        var connections = this.trips[step];
36856        elem = connections[this.connectionStep];
36857      } else {
36858        elem = this.trips[step];
36859      }
36860
36861      if (elem) {
36862        this.$tripLabelWay.text(elem.title);
36863
36864        this.getSeats(elem, function (err, data) {
36865          if (!err) {
36866            var apiResult = data.result;
36867
36868            if (!elem.originLabel || elem.originLabel === "" || elem.originLabel === null || !elem.destinationLabel || elem.destinationLabel === "" || elem.destinationLabel === null) {
36869              elem.originLabel = apiResult.origin.city;
36870              elem.destinationLabel = apiResult.destination.city;
36871            }
36872
36873            if ((!elem._departureDate || elem._departureDate === "" || elem._departureDate === null) && apiResult.date) {
36874              elem._departureDate = apiResult.date;
36875            }
36876
36877            _this4.updateView(data.result.seatMap, elem);
36878            LoaderService.hide();
36879          }
36880        });
36881        return;
36882      }
36883
36884      if (isConnectionStep) {
36885        this.connectionStep = 0;
36886        this.step++;
36887        this.proceedToNextStep(this.step);
36888        return;
36889      }
36890
36891      if (step >= this.trips.length) {
36892        this.cartComponent.cartService.updateStorage();
36893        $(location).attr('href', $('#paymentPagePath').val());
36894        return;
36895      }
36896    }
36897  }, {
36898    key: 'getSeats',
36899    value: function getSeats(tripData, done) {
36900      var body = {
36901        token: tripData.token
36902      };
36903
36904      var saleplatform = SessionStorage.get('utm_saleplatform');
36905      saleplatform ? body.SalePlatform = this.saleplatform : body.SalePlatform = "SITES-UTP";
36906
36907      var headers = {
36908        version: 2
36909      };
36910
36911      LoaderService.show();
36912      HttpService.post('getVehicles', body, headers).then(function (data) {
36913        LoaderService.hide();
36914        if (done) done(null, data);
36915      }).catch(function (err) {
36916        Alert.show('Houve algum problema. Tente novamente mais tarde.');
36917
36918        // Analytics - Triggers an event when there is an error on service.
36919        if (typeof _satellite != "undefined") {
36920          _satellite.track('serviceError', {
36921            service: 'getVehicles',
36922            serviceType: 'getVehicles',
36923            statusCode: err.status,
36924            messageError: err.responseJSON,
36925            customMessageError: {
36926              origin: tripData._originLabel,
36927              destination: tripData._destinationLabel,
36928              date: tripData._departureDate,
36929              serviceId: tripData._service
36930            }
36931          });
36932        }
36933
36934        LoaderService.hide();
36935        if (done) done(err);
36936      });
36937    }
36938  }, {
36939    key: 'updateView',
36940    value: function updateView(seatList, trip) {
36941      this.initObservers();
36942      Utils.scrollTop();
36943      Utils.scrollTop($('.bus-map-seat'));
36944      var validateDepartureDate = DateFormatter.getValidDateFormat(trip._departureDate);
36945      var dayName = DateFormatter.getDaysArray()[validateDepartureDate.getDay()];
36946
36947      var isMobile = Utils.isMobile();
36948      var formatted = isMobile ? DateFormatter.formatDate(trip._departureDate) : DateFormatter.getFullDate(trip._departureDate);
36949
36950      if (!formatted) formatted = '';
36951
36952      this.$dateLabel.text(isMobile ? formatted.slice(0, 5) : formatted.slice(0, 9));
36953      this.$dayLabel.text(dayName.substr(0, 3) + ',');
36954      if (trip._hourDestination && trip._hourDestination !== "") {
36955        this.hour.text(Utils.capitalize(trip._hourDestination));
36956      }
36957      if (this.$originLabel.find('.cmp-text').length > 0) {
36958        this.$originLabel.find('.cmp-text').text(Utils.capitalize(trip.originLabel));
36959      } else {
36960        this.$originLabel.text(Utils.capitalize(trip.originLabel));
36961      }
36962
36963      if (this.$destinationLabel.find('.cmp-text').length > 0) {
36964        this.$destinationLabel.find('.cmp-text').text(Utils.capitalize(trip.destinationLabel));
36965      } else {
36966        this.$destinationLabel.text(Utils.capitalize(trip.destinationLabel));
36967      }
36968      this.initPassengerList();
36969      this.initMapBus(seatList);
36970      var listPassengersInfo = this.cartComponent.cartService.passengers;
36971      this.toggleProceedButton(listPassengersInfo);
36972      this.initLabel();
36973    }
36974  }, {
36975    key: 'proceedOnClick',
36976    value: function proceedOnClick(e) {
36977      var _this5 = this;
36978
36979      e.stopImmediatePropagation();
36980      this.cartComponent.cartService.updateStorage();
36981      setTimeout(function () {
36982        $('#floating-div').css('top', '0');
36983
36984        if (_this5.step === 0 && (!_this5.trips[1] || _this5.trips[1].length === 0)) {
36985          _this5.connectionStep = 0;
36986          _this5.step = 2;
36987          return _this5.proceedToNextStep(_this5.step);
36988        }
36989
36990        if (_this5.step === 1 || _this5.step === 3) {
36991          var connections = _this5.trips[_this5.step];
36992
36993          if (connections && connections[_this5.connectionStep + 1]) {
36994            _this5.connectionStep++;
36995            return _this5.proceedToNextStep(_this5.step);
36996          }
36997        }
36998
36999        _this5.connectionStep = 0;
37000        _this5.step++;
37001        _this5.proceedToNextStep(_this5.step);
37002      }, 300);
37003    }
37004  }, {
37005    key: 'initPassengerList',
37006    value: function initPassengerList() {
37007      var _this6 = this;
37008
37009      var listPassengers = this.cartComponent.cartService.passengers;
37010      this.$passengerList.html('');
37011
37012      listPassengers.forEach(function (el, i) {
37013        var seat = void 0;
37014
37015        switch (_this6.step) {
37016          case 0:
37017            seat = el.seatDeparture;
37018            break;
37019          case 1:
37020            seat = _this6.connectionStep === 0 ? el.seatDepartureConnection : el.seatDepartureConnection2;
37021            break;
37022          case 2:
37023            seat = el.seatReturn;
37024            break;
37025          case 3:
37026            seat = _this6.connectionStep === 0 ? el.seatReturnConnection : el.seatReturnConnection2;
37027            break;
37028        }
37029
37030        var seatNumber = seat.seatNumber;
37031        var $passenger = _this6.$passengerItemTemplate.clone();
37032
37033        $passenger.attr('type', el.type)
37034        $passenger.attr('index', i);
37035        $passenger.find('[data-js="person-name"]').text(el.name);
37036        $passenger.find('[data-js="passenger-index"]').text('Passageiro ' + (i + 1));
37037
37038        var $passengerSeat = _this6.$passengerSeatTemplate.clone();
37039        if (seatNumber) {
37040          $passengerSeat.find('.seat-number').text(seatNumber);
37041          $passengerSeat.show();
37042          $passenger.find('.reservation-passenger-seat').addClass('visible');
37043          $passenger.find('.reservation-label').addClass('selected').text(i18n('seat_selected'));
37044        } else if (!seatNumber && el._type === 'CHILD') {
37045          $passengerSeat.find('.seat-number').text('');
37046          $passengerSeat.show();
37047          $passenger.find('.reservation-label').addClass('selected').text(i18n('seat_child'));
37048          $passenger.find('.reservation-icon img').attr('src', '/etc.clientlibs/wemobi/clientlibs/clientlib-site/resources/images/child.png');
37049          $passenger.find('.reservation-passenger-seat').hide();
37050        } else {
37051          $passengerSeat.find('.seat-number').text('');
37052          $passengerSeat.hide();
37053        }
37054
37055        $passenger.find('.reservation-passenger-seat').html($passengerSeat);
37056        if (el._type !== 'CHILD') {
37057          $passenger.click({
37058            'seat': seat
37059          }, function (e) {
37060            return _this6.passengerOnClick(e);
37061          });
37062        } else {
37063          $passenger.addClass('disabled');
37064        }
37065
37066        if (i == 0) $passenger.addClass('active');
37067
37068        $passenger.removeClass('invisible');
37069        _this6.$passengerList.append($passenger);
37070      });
37071      this.listenEvents();
37072    }
37073  }, {
37074    key: 'initMapBus',
37075    value: function initMapBus(seatList) {
37076      var _this7 = this;
37077
37078      var listPassengers = this.cartComponent.cartService.passengers;
37079      this.busMapSeat.init(seatList);
37080      var filteredSeatList = seatList.filter(function (s) {
37081        return s.number != '';
37082      });
37083
37084      this.busMapSeat.$mapBus.find('.outer-seat').map(function (i, seatDiv) {
37085        var $seat = $(seatDiv);
37086        var seat = filteredSeatList[i];
37087        var occupedSeat = _this7.isSeatOccuped(seat.number, listPassengers);
37088
37089        if (occupedSeat >= 0) {
37090          _this7.busMapSeat.occupySeat($seat);
37091          if (occupedSeat == 0) _this7.busMapSeat.selectSeat($seat, seat.number);
37092        }
37093
37094        $seat.click({
37095          'seatInfo': seat
37096        }, function (e) {
37097          return _this7.seatOnClick(e);
37098        });
37099
37100        return $seat;
37101      });
37102
37103      var checkBusSize = function reference() {
37104        var _Utils$getWindowSize = Utils.getWindowSize(),
37105          width = _Utils$getWindowSize.width,
37106          breakpoints = _Utils$getWindowSize.breakpoints;
37107
37108        if (width < breakpoints.LGR) {
37109          $('#floating-div').css('position', 'static');
37110        } else if (width >= breakpoints.LGR) {
37111          $('#floating-div').css('position', 'relative');
37112        }
37113        return reference;
37114      }(); //auto-run
37115      $(window).resize(function () {
37116        return checkBusSize();
37117      });
37118
37119      try {
37120        $('.inner-seat.occupied-seat').each(function (index, element) {
37121          if ($(element).find('.seat-number') && $(element).find('.seat-number').text() != 'X') {
37122            $(element).addClass('selected');
37123          }
37124        });
37125      } catch (error) { console.log(error); }
37126    }
37127  }, {
37128    key: 'passengerOnClick',
37129    value: function passengerOnClick(e) {
37130      var seat = e.data.seat || e.data.seatInfo;
37131      var seatNumber = seat.seatNumber;
37132      var $mapBus = this.busMapSeat.$mapBus;
37133      var $passenger = $(e.currentTarget);
37134      var $currentSeat = $mapBus.find('[data-js="seat-' + seatNumber + '"]').find('.inner-seat');
37135      $passenger.siblings().removeClass('active');
37136      $passenger.addClass('active');
37137      var $previouslySelected = $mapBus.find('.selected');
37138      this.busMapSeat.unselectSeat($previouslySelected, seatNumber);
37139      this.busMapSeat.occupySeat($previouslySelected);
37140      this.busMapSeat.occupySeat($currentSeat);
37141      this.busMapSeat.selectSeat($currentSeat, seatNumber);
37142
37143      this.errorOnSeat = false;
37144    }
37145  }, {
37146    key: 'hasPriceChanged',
37147    value: function hasPriceChanged(_, offer, seat) {
37148      if (seat && parseInt(offer.service) == seat.service) {
37149        if (parseFloat(seat.price) > parseFloat(offer.price)) return 1;
37150        if (parseFloat(seat.price) < parseFloat(offer.price)) return 2;
37151      }
37152      return 0;
37153    }
37154  }, {
37155    key: 'showAlert',
37156    value: function showAlert(msg) {
37157      var showCartLink = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
37158
37159      var alertPriceWarning = $('.price-change-warning');
37160      var alertPriceWarningMsg = alertPriceWarning.find('[data-js="price-change-msg"]');
37161      var position = alertPriceWarning.offset().top + alertPriceWarning.height();
37162
37163      if (showCartLink) $('.cart-warning').show(); else $('.cart-warning').hide();
37164
37165      alertPriceWarningMsg.text(msg);
37166      alertPriceWarning.show();
37167
37168      $('html,body').animate({
37169        scrollTop: position / 1.8
37170      }, 500);
37171    }
37172  }, {
37173    key: 'shouldAlertShowUp',
37174    value: function shouldAlertShowUp(passenger, seat) {
37175      var listOffer = this.cartComponent.cartService.listOffer;
37176      var showAlert = 0;
37177
37178      for (var j = 0; j < listOffer.length && showAlert == 0; j++) {
37179        var offer = listOffer[j];
37180
37181        if (parseInt(offer.service) == seat.service) showAlert = this.hasPriceChanged(passenger, offer, seat);
37182      }
37183
37184      switch (showAlert) {
37185        case 1:
37186          localStorage.alertType = JSON.stringify({
37187            id: showAlert,
37188            desc: 'MORE'
37189          });
37190          this.showAlert($('[data-js="price-change-msg-less"]').val());
37191          break;
37192        case 2:
37193          localStorage.alertType = JSON.stringify({
37194            id: showAlert,
37195            desc: 'LESS'
37196          });
37197          this.showAlert($('[data-js="price-change-msg-student"]').val());
37198          break;
37199        default:
37200          localStorage.alertType = JSON.stringify({
37201            id: 0,
37202            desc: 'NONE'
37203          });
37204          $('.bus-map-container').removeClass('active');
37205      }
37206    }
37207  }, {
37208    key: 'selectNextPassenger',
37209    value: function selectNextPassenger() {
37210      var $selectedPassenger = this.$passengerList.find('.active');
37211      if ($selectedPassenger.next().length > 0) {
37212        $selectedPassenger.next().trigger('click');
37213      }
37214    }
37215  }, {
37216    key: 'cancelSeat',
37217    value: function cancelSeat(passengerSeatInfo) {
37218      var tripData = this.trips[this.step];
37219
37220      var body = {
37221        SeatModel: {
37222          token: tripData.token,
37223          child: false,
37224          going: tripData.going,
37225          category: 1,
37226          seat: passengerSeatInfo.seatNumber
37227        },
37228        LockSeat: false,
37229        SalePlatform: this.saleplatform ? this.saleplatform : "SITES-UTP"
37230      };
37231
37232      var headers = {
37233        'Authorization': '' + SessionStorage.get('jca_token'),
37234        'sessionseatlock': SessionStorage.get('sessionseatlock'),
37235        'version': 2
37236      };
37237
37238      return HttpService.post('lockSeat', body, headers);
37239    }
37240  }, {
37241    key: 'blockSeat',
37242    value: function blockSeat(seatPassenger, passenger) {
37243      var connections = [];
37244      var tripData = null;
37245
37246      if (this.step === 1 || this.step === 3) {
37247        connections = this.trips[this.step];
37248        tripData = connections[this.connectionStep];
37249      } else {
37250        tripData = this.trips[this.step];
37251      }
37252
37253      var body = {
37254        SeatModel: {
37255          token: tripData.token,
37256          child: passenger.child ? true : false,
37257          going: tripData.going,
37258          category: 1,
37259          clientId: '',
37260          seat: seatPassenger
37261        },
37262        LockSeat: true,
37263        SalePlatform: this.saleplatform ? this.saleplatform : "SITES-UTP"
37264      };
37265
37266      if (passenger.hasDiscount) {
37267        body.SeatModel.category = 17;
37268        var allStudentData = SessionStorage.get('allStudentData') || [];
37269        var documentNumber = passenger.documentNumber;
37270        var studentData = allStudentData.find(function (data) {
37271          return data.document === parseInt(documentNumber);
37272        });
37273        if (studentData) {
37274          body.SeatModel.clientId = studentData.clientId;
37275        }
37276      } else {
37277        body.SeatModel.clientId = '';
37278      }
37279
37280      var headers = {
37281        'Authorization': '' + SessionStorage.get('jca_token'),
37282        'sessionseatlock': SessionStorage.get('sessionseatlock'),
37283        'version': 2
37284      };
37285
37286      return HttpService.post('lockSeat', body, headers);
37287    }
37288  }, {
37289    key: 'resetSeat',
37290    value: function resetSeat(passengerSeatInfo) {
37291      passengerSeatInfo.transactionId = '';
37292      passengerSeatInfo.seatNumber = '';
37293      passengerSeatInfo.price = 0;
37294      passengerSeatInfo.rate = 0;
37295      passengerSeatInfo.insurance = 0;
37296      passengerSeatInfo.tax = 0;
37297      passengerSeatInfo.toll = 0;
37298      passengerSeatInfo.other = 0;
37299      passengerSeatInfo.service = '';
37300      return passengerSeatInfo;
37301    }
37302  }, {
37303    key: 'unselectSeat',
37304    value: function unselectSeat($seat, passengerSeatInfo, data) {
37305      var $selectedPassenger = this.$passengerList.find('.active');
37306      var $seatNumber = $selectedPassenger.find('.seat-number');
37307      this.busMapSeat.unselectSeat($seat);
37308
37309      if ($seat.hasClass('occuped')) this.busMapSeat.freeSeat($seat);
37310
37311      // $seatNumber.text(number)
37312      $seatNumber.parent().hide();
37313      passengerSeatInfo = this.resetSeat(passengerSeatInfo);
37314      var listPassengersInfo = this.cartComponent.cartService.passengers;
37315      SessionStorage.set('unselectSeat', 'true');
37316      this.updateCart(listPassengersInfo);
37317      return passengerSeatInfo;
37318    }
37319  }, {
37320    key: 'updateSeat',
37321    value: function updateSeat(number, passengerSeatInfo, data) {
37322      passengerSeatInfo.seatNumber = number;
37323      passengerSeatInfo.transactionId = data.result.transaction;
37324      var seatSummary = this.findSeatSummaryForCartSeat(passengerSeatInfo, data.result.summaryPrice, data.result.service);
37325
37326      if (seatSummary) {
37327        passengerSeatInfo.price = seatSummary.subTotal;
37328        passengerSeatInfo.rate = seatSummary.tarifa;
37329        passengerSeatInfo.tax = 0;
37330        passengerSeatInfo.toll = seatSummary.travelFees;
37331        passengerSeatInfo.other = 0;
37332        passengerSeatInfo.boardingFee = 0;
37333        passengerSeatInfo.convenienceFee = seatSummary.convenienceFee && seatSummary.convenienceFee > 0 ? seatSummary.convenienceFee : data.result.seatResponse.service.convenienceFee;
37334        passengerSeatInfo.commission = seatSummary.commission;
37335        passengerSeatInfo.service = data.result.service;
37336        passengerSeatInfo.insurance = data.result.insurance.value;
37337
37338        this.cartComponent.cartService.cart.subTotal = data.result.summaryPrice.subTotal;
37339        this.cartComponent.cartService.cart.totalPrice = data.result.summaryPrice.total;
37340        this.cartComponent.cartService.cart.totalConvenienceFee = data.result.summaryPrice.convenienceFee;
37341      } else {
37342        passengerSeatInfo.price = data.result.price.total;
37343        passengerSeatInfo.rate = data.result.price.tarifa;
37344        passengerSeatInfo.insurance = data.result.insurance.value;
37345        passengerSeatInfo.toll = data.result.price.pedagio;
37346        passengerSeatInfo.other = data.result.price.outros;
37347        passengerSeatInfo.tax = data.result.price.imposto;
37348        passengerSeatInfo.boardingFee = data.result.price.taxaEmbarque;
37349        passengerSeatInfo.service = data.result.service;
37350        passengerSeatInfo.convenienceFee = data.result.seatResponse.service.convenienceFee;
37351      }
37352
37353      var connections = [];
37354      var tripData = null;
37355
37356      if (this.step === 1 || this.step === 3) {
37357        connections = this.trips[this.step];
37358        tripData = connections[this.connectionStep];
37359      } else {
37360        tripData = this.trips[this.step];
37361      }
37362
37363      passengerSeatInfo.token = tripData.token;
37364
37365      return passengerSeatInfo;
37366    }
37367  }, {
37368    key: 'findSeatSummaryForCartSeat',
37369    value: function findSeatSummaryForCartSeat(passengerSeatInfo, summaryPrice, serviceId) {
37370      if (!summaryPrice || !summaryPrice.services || !Array.isArray(summaryPrice.services)) {
37371        return null;
37372      }
37373
37374      var seatNumber = passengerSeatInfo._seatNumber;
37375      if (!serviceId || !seatNumber) return null;
37376
37377      var serviceSummary = summaryPrice.services.find(function (svc) {
37378        return String(svc.serviceId) === String(serviceId);
37379      });
37380
37381      if (!serviceSummary || !serviceSummary.seats || !Array.isArray(serviceSummary.seats)) {
37382        return null;
37383      }
37384
37385      var seatSummary = serviceSummary.seats.find(function (seat) {
37386        return String(seat.seat) === String(seatNumber);
37387      });
37388
37389      return seatSummary || null;
37390    }
37391  }, {
37392    key: 'selectSeat',
37393    value: function selectSeat($seat, numero, passengerSeatInfo, data) {
37394      var $selectedPassenger = this.$passengerList.find('.active');
37395      var $seatNumber = $selectedPassenger.find('.seat-number');
37396      $seatNumber.closest('.reservation-passenger-seat').addClass('visible');
37397      $seatNumber.closest('.content').find('.reservation-label').addClass('selected').text(i18
37397n('seat_selected'));
37398
37399      if (passengerSeatInfo) passengerSeatInfo = this.updateSeat(numero, passengerSeatInfo, data);
37400
37401      this.busMapSeat.occupySeat($seat);
37402      this.busMapSeat.selectSeat($seat, numero);
37403      $($seat).parent().css('outline', 'none');
37404      $seatNumber.text(numero);
37405      $seatNumber.parent().show();
37406      this.selectNextPassenger();
37407      this.modalUpsel.hide();
37408
37409      return passengerSeatInfo;
37410    }
37411  }, {
37412    key: 'toggleProceedButton',
37413    value: function toggleProceedButton(listPassengersInfo) {
37414      var passengerNotChild = listPassengersInfo.filter(function (passenger) {
37415        return passenger._type !== 'CHILD';
37416      });
37417
37418      if (this.hasFreeSeat(passengerNotChild)) {
37419        this.disableBtnProceed();
37420      } else {
37421        this.$btnProceed.removeAttr('disabled');
37422        this.initBtnProceed();
37423      }
37424    }
37425  }, {
37426    key: 'getPassengerSeat',
37427    value: function getPassengerSeat(passengerInfo) {
37428      switch (this.step) {
37429        case 0:
37430          return passengerInfo.seatDeparture;
37431        case 1:
37432          return this.connectionStep === 0 ? passengerInfo.seatDepartureConnection : passengerInfo.seatDepartureConnection2;
37433        case 2:
37434          return passengerInfo.seatReturn;
37435        case 3:
37436          return this.connectionStep === 0 ? passengerInfo.seatReturnConnection : passengerInfo.seatReturnConnection2;
37437      }
37438    }
37439  }, {
37440    key: 'clickCancelSeat',
37441    value: function clickCancelSeat($seat, passengerSeatInfo) {
37442      var _this8 = this;
37443
37444      LoaderService.show();
37445      return $.when(this.cancelSeat(passengerSeatInfo)).then(function (data) {
37446        LoaderService.hide();
37447
37448        if (!data.success) {
37449          _this8.errorOnSeat = true;
37450          if (Utils.isMobile()) $('[data-js="bus-map-seat-parent"]').hide();
37451          throw new Error();
37452        }
37453
37454        _this8.errorOnSeat = false;
37455        passengerSeatInfo = _this8.unselectSeat($seat, passengerSeatInfo, data);
37456      }).catch(function (err) {
37457        LoaderService.hide();
37458        Alert.show('Houve uma falha na requisição. Tente novamente mais tarde.');
37459        _this8.errorOnSeat = true;
37460      });
37461    }
37462  }, {
37463    key: 'seatOnClick',
37464    value: function seatOnClick(e) {
37465      var _this9 = this;
37466      try {
37467        $('.inner-seat.occupied-seat').each(function (index, element) {
37468          if ($(element).find('.seat-number') && $(element).find('.seat-number').text() != 'X') {
37469            $(element).removeClass('occupied-seat');
37470          }
37471        });
37472      } catch (error) { console.log(error); }
37473
37474      var $selectedPassenger = this.$passengerList.find('.active');
37475      var $seat = $(e.currentTarget).find('.inner-seat');
37476      var $selectedSeat = this.busMapSeat.$mapBus.find('.selected');
37477      var listPassengersInfo = this.cartComponent.cartService.passengers;
37478      var index = parseInt($selectedPassenger.attr('index'));
37479      var seatInfo = e.data.seatInfo;
37480      var passengerInfo = listPassengersInfo[index];
37481      var passengerSeatInfo = this.getPassengerSeat(passengerInfo);
37482      //seatOnClick body starts here
37483
37484      if ($selectedPassenger.length === 0) return;
37485
37486      var tripData = void 0;
37487      if (this.step === 1 || this.step === 3) {
37488        tripData = this.trips[this.step][this.connectionStep];
37489      } else {
37490        tripData = this.trips[this.step];
37491      }
37492
37493      var cancelPromise = Promise.resolve();
37494
37495
37496      if ($selectedSeat.html() == $seat.html()) {
37497        this.clickCancelSeat($seat, passengerSeatInfo).then(function () {
37498          _this9.updateCart(listPassengersInfo);
37499        });
37500      } else {
37501
37502        if ($seat.hasClass('occuped')) return;
37503
37504        if ($selectedSeat.length > 0) {
37505          cancelPromise = this.clickCancelSeat($selectedSeat, passengerSeatInfo).then(function () {
37506            _this9.updateCart(listPassengersInfo);
37507          });
37508        }
37509
37510        cancelPromise.then(function () {
37511          LoaderService.show();
37512          _this9.blockSeat(seatInfo.number, passengerInfo).then(function (data) {
37513            LoaderService.hide();
37514
37515            if (!data.success) {
37516              _this9.errorOnSeat = true;
37517              if (Utils.isMobile()) $('[data-js="bus-map-seat-parent"]').hide();
37518              throw new Error();
37519            }
37520
37521            _this9.errorOnSeat = false;
37522            passengerSeatInfo = _this9.selectSeat($seat, seatInfo.number, passengerSeatInfo, data);
37523            _this9.updateCart(listPassengersInfo);
37524
37525            if (!tripData._hourDestination || !tripData._hourDestination === "") {
37526              tripData._hourDestination = DateFormatter.extractHour(data.result.seatResponse.service.departureDate);
37527              _this9.hour.text(Utils.capitalize(tripData._hourDestination));
37528            }
37529
37530            _this9.shouldAlertShowUp(passengerInfo, passengerSeatInfo);
37531
37532            if (_this9.step == _this9.trips.length - 1)
37533              _this9.shouldAlertShowUp(passengerInfo, passengerSeatInfo);
37534            else
37535              $('.bus-map-container').removeClass('active');
37536
37537          }).catch(function (err) {
37538            LoaderService.hide();
37539            Alert.show('Este assento está indiponível para marcação. Selecione um novo assento.');
37540            // send2Analytics(data.bloqueioPoltrona.erro.descricaoErro)
37541            _this9.errorOnSeat = true;
37542            _this9.proceedToNextStep(_this9.step);
37543            // Analytics - Service Error
37544            _satellite.track('serviceError', {
37545              serviceType: 'transactSeat',
37546              statusCode: err.status,
37547              messageError: err.responseJSON
37548            });
37549            return;
37550          });
37551        });
37552      }
37553    }
37554  }, {
37555    key: 'updateCart',
37556    value: function updateCart(listPassengersInfo) {
37557      this.cartComponent.updateCartView();
37558      this.cartComponent.initPassengerList(SessionStorage.get('cart'));
37559      this.toggleProceedButton(listPassengersInfo);
37560    }
37561  }, {
37562    key: 'scrollFloatingDiv',
37563    value: function scrollFloatingDiv() {
37564      $(window).scroll(function () {
37565
37566        var distanceToTop = $(document).scrollTop();
37567        var floating = $('#floating-div');
37568        var floatingHeight = floating.height();
37569        var busMapHeight = $('[data-js="map-bus"]').height();
37570        var busFrontHeight = 0;
37571        var busTotalHeight = busMapHeight + busFrontHeight;
37572        var freeSpace = busTotalHeight - floatingHeight;
37573
37574        if (freeSpace > 0) {
37575          floating.animate({
37576            top: (distanceToTop > freeSpace ? freeSpace : distanceToTop) + "px"
37577          }, {
37578            duration: 400,
37579            queue: false
37580          });
37581        }
37582      });
37583    }
37584  }, {
37585    key: 'initObservers',
37586    value: function initObservers() {
37587      var _this14 = this;
37588
37589      var observer = new MutationObserver(function () {
37590        var $btnProceed = _this14.$btnProceed.filter(':visible').not(':disabled');
37591
37592        if ($btnProceed.length) {
37593          observer.disconnect();
37594
37595          requestAnimationFrame(function () {
37596            var cartHeight = _this14.bottomResumeCart.filter(':visible').outerHeight() || 0;
37597            var targetScroll = $btnProceed.offset().top - $(window).height() + $btnProceed.outerHeight() + cartHeight + 45;
37598
37599            $("html, body").stop().animate({ scrollTop: targetScroll }, 500);
37600          });
37601        }
37602      });
37603
37604      this.$btnProceed.each(function (_, el) {
37605        observer.observe(el, { attributes: true, attributeFilter: ['disabled'] });
37606      });
37607    }
37608  }]);
37609
37610  return SeatReservation;
37611}();
37612/** * FIM
37613 * LOGICA TELA RESERVA DE ASSENTOS
37614 *
37615 */
37616'use strict';
37617
37618var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
37619
37620function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
37621
37622var AlertCreditCard = function () {
37623  function AlertCreditCard($) {
37624    _classCallCheck(this, AlertCreditCard);
37625
37626    this.closeWarningCard = $('[data-js="close-warning-card"]');
37627    this.emailUser = $('[data-js="user-email"]');
37628    this.passenger = SessionStorage.get('passenger');
37629    this.init();
37630  }
37631
37632  _createClass(AlertCreditCard, [{
37633    key: 'init',
37634    value: function init() {
37635      this.listenEvents();
37636      this.loadEmail();
37637    }
37638  }, {
37639    key: 'listenEvents',
37640    value: function listenEvents() {
37641      this.closeWarningCard.on('click', function () {
37642        $('.container-alert-credit-card').hide();
37643      });
37644
37645      $('[data-js="btn-my-trips"]').on('click', function () {
37646        $(location).attr('href', $('#myAccountPath').val());
37647      });
37648    }
37649  }, {
37650    key: 'loadEmail',
37651    value: function loadEmail() {
37652      var email = this.passenger._email;
37653      var component = $('.container-alert-credit-card:visible');
37654      if (component.length > 0) {
37655        var textContainer = $(component).find('[data-js="user-email"]');
37656        if (textContainer) {
37657          var text = $(textContainer).html();
37658          text = text.replace('${email}', email);
37659          $(textContainer).empty().html(text);
37660        }
37661      }
37662    }
37663  }]);
37664
37665  return AlertCreditCard;
37666}();
37667'use strict';
37668
37669var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
37670
37671function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
37672
37673var AlertNextDay = function () {
37674  function AlertNextDay($) {
37675    _classCallCheck(this, AlertNextDay);
37676
37677    this.currentDate = SessionStorage.get('formData').depart.date;
37678    this.amountCards = (!$("[data-js='amount-of-cards']") || !$("[data-js='amount-of-cards']").val()) ? 6 : parseInt($("[data-js='amount-of-cards']").val());
37679    this.minimumDepartureTime = DateFormatter.getValidDateFormat(this.currentDate + ' ' + $("[data-js='minimum-departure-time']").val());
37680    this.maximumDepartureTimeNextDay = DateFormatter.getValidDateFormat(this.currentDate);
37681    this.maximumDepartureTimeNextDay.setHours(this.minimumDepartureTime.getHours() + 24);
37682    var maxTimeNextDay = (!$("[data-js='maximum-departure-time-next-day']") || !$("[data-js='maximum-departure-time-next-day']").val()) ? '00:00' : $("[data-js='maximum-departure-time-next-day']").val();
37683    this.maximumDepartureTimeNextDay.setHours(parseInt(maxTimeNextDay.split(':')[0]), parseInt(maxTimeNextDay.split(':')[1]), 0);
37684    this.alertNextDayContainer = $('.alert-next-day-container');
37685    this.alertTimeCards = this.alertNextDayContainer.find('.alert-time-cards');
37686    this.alertTimeCards.empty();
37687    this.alertNextDayContainer.find('[data-js="next-day-label"]').text(DateFormatter.parseDateFormat(this.maximumDepartureTimeNextDay));
37688  }
37689
37690  _createClass(AlertNextDay, [{
37691    key: 'init',
37692    value: function init() {
37693      var _this = this;
37694
37695      var currentList = SessionStorage.get('currentResultDep');
37696      $.each(currentList, function (index) {
37697        var company = currentList[index];
37698        if (DateFormatter.compareWithMinTime(_this.minimumDepartureTime, company.saida)) {
37699          _this.initCards();
37700          return false;
37701        }
37702      });
37703      this.toggleContainer();
37704    }
37705  }, {
37706    key: 'initCards',
37707    value: function initCards() {
37708      var _this2 = this;
37709
37710      var nextResult = SessionStorage.get('nextResult');
37711      var validResults = [];
37712
37713      var _loop = function _loop(i) {
37714        if (validResults.filter(function (r) {
37715          return r.saida === nextResult[i].saida;
37716        }).length == 0 && DateFormatter.compareWithMinTime(nextResult[i].saida, _this2.maximumDepartureTimeNextDay)) {
37717          validResults.push(nextResult[i]);
37718        }
37719      };
37720
37721      for (var i = 0;
37721 i < nextResult.length && validResults.length < this.amountCards; i++) {
37722        _loop(i);
37723      }
37724      for (var i = 0; i < validResults.length; i++) {
37725        var chegada = validResults[i].conexao ? validResults[i].conexao.segundoTrechoHoraChegada : validResults[i].chegada;
37726        var alertTripTime = new AlertTripTime(validResults[i].saida, chegada);
37727        this.alertTimeCards.append(alertTripTime.templateString);
37728      }
37729    }
37730  }, {
37731    key: 'toggleContainer',
37732    value: function toggleContainer() {
37733      if (this.alertTimeCards.find('.alert-trip-time-container').length > 0) this.alertNextDayContainer.show(); else this.alertNextDayContainer.hide();
37734    }
37735  }]);
37736
37737  return AlertNextDay;
37738}();
37739'use strict';
37740
37741var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
37742
37743function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
37744
37745var BannerImageController = function () {
37746  function BannerImageController($) {
37747    _classCallCheck(this, BannerImageController);
37748
37749    this.$bannerCarouselItem = $(".banner-image .carousel-item");
37750    this.$bannerConfigDesktop = $('[data-js="banner-config-desktop"]');
37751    this.$bannerConfigMobile = $('[data-js="banner-config-mobile"]');
37752    this.$bannerImage = $('[data-js="banner-image"]');
37753    this.arrowColor = this.$bannerConfigDesktop.attr("arrowColor");
37754
37755    this.init();
37756  }
37757
37758  _createClass(BannerImageController, [{
37759    key: 'init',
37760    value: function init() {
37761      // Evita o Slick rodar antes da imagem principal carregar (reduz reflow pesado)
37762      var firstImg = this.$bannerImage.find('img')[0];
37763      if (firstImg && !firstImg.complete) return;
37764
37765      if (!this.$bannerImage.hasClass("slick-initialized")) {
37766        var desktop = this.$bannerConfigDesktop;
37767        var mobile = this.$bannerConfigMobile;
37768
37769        this.$bannerImage.slick({
37770          autoplay: true,
37771          infinite: true,
37772          waitForAnimation: false, // redução de custo
37773          cssEase: "linear", // redução de custo
37774          dots: this.$bannerCarouselItem.length > 1 && desktop.attr("dots") === "true",
37775          slidesToShow: +desktop.attr("slidesToShow"),
37776          slidesToScroll: +desktop.attr("slidesToScroll"),
37777          speed: +desktop.attr("speed"),
37778          arrows: this.$bannerCarouselItem.length > 1 && desktop.attr("arrows") === "true",
37779          autoplaySpeed: 5000,
37780          responsive: [{
37781            breakpoint: 950,
37782            settings: {
37783              speed: +mobile.attr("speed"),
37784              slidesToShow: +mobile.attr("slidesToShow"),
37785              slidesToScroll: +mobile.attr("slidesToScroll"),
37786              arrows: this.$bannerCarouselItem.length > 1 && mobile.attr("arrows") === "true",
37787              dots: this.$bannerCarouselItem.length > 1 && mobile.attr("dots") === "true"
37788            }
37789          }]
37790        });
37791      }
37792
37793      this.$bannerImage.find(".slick-prev, .slick-next").css("--arrow-color", this.arrowColor);
37794    }
37795  }]);
37796
37797  return BannerImageController;
37798}();
37799
37800'use strict';
37801
37802var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
37803
37804function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
37805
37806var BreadcrumbRepricingController = function () {
37807  function BreadcrumbRepricingController(repricingPhase) {
37808    _classCallCheck(this, BreadcrumbRepricingController);
37809
37810    this.init(repricingPhase);
37811  }
37812
37813  _createClass(BreadcrumbRepricingController, [{
37814    key: 'init',
37815    value: function init(repricingPhase) {
37816      this.handleBreadCrumbRepricingTrip(repricingPhase);
37817    }
37818  }, {
37819    key: 'handleBreadCrumbRepricingTrip',
37820    value: function handleBreadCrumbRepricingTrip() {
37821      var repricingPhase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
37822
37823      var breadcrumb = $('[data-js="breadcrumb-repricing"]');
37824      var breadcrumb_mobile = $('[data-js="breadcrumb-repricing-mobile"]');
37825      var steps = breadcrumb.children().find('.breadcrumb-section');
37826      var stepsArrow = breadcrumb.children().find('.breadcrumb-section .arrow-icon');
37827      var steps_mobile = breadcrumb_mobile.children().find('.breadcrumb-mobile-section a.breadcrumb-mobile-text');
37828      var steps_mobile_section = breadcrumb_mobile.children().find('.breadcrumb-mobile-section');
37829      var steps_mobile_circle = breadcrumb_mobile.children().find('.breadcrumb-mobile-section .breadcrumb-mobile-circle');
37830
37831      if (repricingPhase == 1) {
37832        $(steps_mobile[0]).addClass('active');
37833        $(steps_mobile_section[0]).addClass('active');
37834        $(steps_mobile_circle[0]).addClass('active');
37835        $(steps_mobile_section[1]).removeClass('active');
37836        $(steps_mobile[1]).removeClass('active');
37837        $(steps[0]).addClass('active');
37838        $(steps[1]).removeClass('active');
37839        $(stepsArrow[1]).removeClass('active');
37840      }
37841
37842      if (repricingPhase == 2) {
37843        $(steps_mobile_circle[0]).addClass('previous');
37844        $(steps_mobile_section[0]).removeClass('active');
37845        $(steps_mobile_circle[1]).addClass('active');
37846        $(steps_mobile_section[1]).addClass('active');
37847        $(steps_mobile[0]).removeClass('active');
37848        $(steps_mobile[1]).addClass('active');
37849        $(steps[0]).addClass('active');
37850        $(stepsArrow[0]).addClass('active');
37851        $(steps[1]).addClass('active');
37852        $(stepsArrow[1]).addClass('active');
37853      }
37854
37855      if (repricingPhase == 3) {
37856        $(steps_mobile_circle[0]).addClass('previous');
37857        $(steps_mobile_circle[1]).addClass('previous');
37858        $(steps_mobile_section[1]).removeClass('active');
37859        $(steps_mobile[1]).removeClass('active');
37860        $(steps_mobile_circle[2]).addClass('active');
37861        $(steps_mobile_section[2]).addClass('active');
37862        $(steps_mobile[2]).addClass('active');
37863        $(steps[0]).addClass('active');
37864        $(steps[1]).addClass('active');
37865        $(steps[2]).addClass('active');
37866        $(stepsArrow[0]).addClass('active');
37867        $(stepsArrow[1]).addClass('active');
37868        $(stepsArrow[2]).addClass('active');
37869      }
37870    }
37871  }]);
37872
37873  return BreadcrumbRepricingController;
37874}();
37875'use strict';
37876
37877var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
37878
37879function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
37880
37881var Breadcrumb = function () {
37882  function Breadcrumb($) {
37883    _classCallCheck(this, Breadcrumb);
37884
37885    this.breadcrumbDesktop = $('[data-js="breadcrumb"]');
37886    this.breadcrumbMobile = $('[data-js="breadcrumb-mobile"]');
37887    this.init();
37888  }
37889
37890  _createClass(Breadcrumb, [{
37891    key: 'init',
37892    value: function init() {
37893      this.showBreadcrumb();
37894      this.listenWindowResize();
37895    }
37896  }, {
37897    key: 'showBreadcrumb',
37898    value: function showBreadcrumb() {
37899      if (Utils.getWindowSize().width > 951) {
37900        this.breadcrumbDesktop.show();
37901        this.breadcrumbMobile.hide();
37902      } else {
37903        this.breadcrumbMobile.show();
37904        this.breadcrumbDesktop.hide();
37905      }
37906    }
37907  }, {
37908    key: 'listenWindowResize',
37909    value: function listenWindowResize() {
37910      var _this = this;
37911
37912      $(window).on('resize', function () {
37913        _this.showBreadcrumb();
37914      });
37915    }
37916  }]);
37917
37918  return Breadcrumb;
37919}();
37920'use strict';
37921
37922var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
37923
37924function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
37925
37926var BusPreview = function () {
37927  function BusPreview($, event, offer) {
37928    var elemBusPreviewUpsel = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
37929
37930    _classCallCheck(this, BusPreview);
37931
37932    this.event = event;
37933    this.offer = offer;
37934    this.elemBusPreviewUpsel = elemBusPreviewUpsel;
37935    this.modal = $('[data-js="bus-preview-modal"]');
37936    this.traceOrigin = $('[data-js="trace-orig"]');
37937    this.traceDestination = $('[data-js="trace-dest"]');
37938    this.init();
37939  }
37940
37941  _createClass(BusPreview, [{
37942    key: 'init',
37943    value: function init() {
37944      this.handleEvents(this.event);
37945      this.putInfosIntoModal(this.event, this.offer);
37946    }
37947  }, {
37948    key: 'handleEvents',
37949    value: function handleEvents(event) {
37950      var _this = this;
37951
37952      var offerEl = $(event.target);
37953      var parentEl = offerEl.parent();
37954      var modalEl = document.querySelector('[data-js="bus-preview-modal"]');
37955      this.modalInstance = new bootstrap.Modal(modalEl);
37956      this.modalInstance.show();
37957
37958      modalEl.addEventListener('hidden.bs.modal', function () {
37959        _this.elemBusPreviewUpsel ? $('[data-js="map-bus-modal-upsel"]').empty() : $('[data-js="map-bus"]').empty();
37960
37961        document.querySelectorAll('.modal-backdrop').forEach(function (el) {
37962          return el.remove();
37963        });
37964        document.body.classList.remove('modal-open');
37965
37966        $(parentEl).children()[1].focus();
37967      });
37968
37969      
37970      this.modal.find('.close').on('focusout', function (e) {
37971        var $target = $(e.relatedTarget);
37972
37973        if (!$target.is('#bus-preview-modal') && $target.closest('#bus-preview-modal').length === 0) {
37974          $(e.target).click();
37975          parentEl.focus();
37976        }
37977      });
37978    }
37979  }, {
37980    key: 'putInfosIntoModal',
37981    value: function putInfosIntoModal(event, offer) {
37982      var $target = $(event.target);
37983      var $row = $target.closest('.row');
37984
37985      var isThirdLegRow = $row.hasClass('secondConn');
37986      var isSecondLegRow = $row.hasClass('connection-info');
37987
37988      var connSecond = offer.connection && offer.connection.secondLeg;
37989      var connThird = offer.connection && offer.connection.thirdLeg;
37990
37991      var originLabel = offer._company._origin._label;
37992      var destLabel = offer._company._destination._label;
37993
37994      var tripObj = null;
37995
37996      if (isThirdLegRow && connThird) {
37997        originLabel = connThird.origin.description;
37998        destLabel = connThird.destination.description;
37999
38000        this.traceOrigin.text(Utils.capitalize(originLabel));
38001        this.traceDestination.text(Utils.capitalize(destLabel));
38002
38003        tripObj = this.createTripObj(offer, true, connThird);
38004        this.drawBus(tripObj, true);
38005        return;
38006      }
38007
38008      if (isSecondLegRow && connSecond) {
38009        originLabel = connSecond.origin.description;
38010        destLabel = connSecond.destination.description;
38011
38012        this.traceOrigin.text(Utils.capitalize(originLabel));
38013        this.traceDestination.text(Utils.capitalize(destLabel));
38014
38015        tripObj = this.createTripObj(offer, true);
38016        this.drawBus(tripObj, true);
38017        return;
38018      }
38019
38020      if (connSecond) {
38021        originLabel = offer._company._origin._label;
38022        destLabel = connSecond.origin.description;
38023
38024        this.traceOrigin.text(Utils.capitalize(originLabel));
38025        this.traceDestination.text(Utils.capitalize(destLabel));
38026
38027        tripObj = this.createTripObj(offer);
38028        this.drawBus(tripObj, true);
38029        return;
38030      }
38031
38032      this.traceOrigin.text(Utils.capitalize(originLabel));
38033      this.traceDestination.text(Utils.capitalize(destLabel));
38034
38035      tripObj = this.createTripObj(offer);
38036      this.drawBus(tripObj);
38037
38038      this.modal.find('.outer-seat').attr('tabindex', -1);
38039      this.modal.find('.close').focus();
38040    }
38041  }, {
38042    key: 'createTripObj',
38043    value: function createTripObj(offer) {
38044      var isConnection = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
38045      var conn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
38046
38047      if (isConnection) {
38048        if (conn) {
38049          return new Trip(offer._service, offer._group, conn.origin.id, conn.origin.description, conn.destination.id, conn.destination.description, null, DateFormatter.extractDate(conn.departureDate), null, null, null, conn.token);
38050        }
38051
38052        var secondLeg = offer.connection && offer.connection.secondLeg;
38053
38054        if (secondLeg) {
38055          return new Trip(offer._service, offer._group, secondLeg.origin.id, secondLeg.origin.description, secondLeg.destination.id, secondLeg.destination.description, null, DateFormatter.extractDate(secondLeg.departureDate), null, null, null, secondLeg.token);
38056        }
38057      }
38058
38059      return new Trip(offer._service, offer._group, offer._company._origin._id, offer._company._origin._label, offer._company._destination._id, offer._company._destination._label, null, DateFormatter.extractDate(offer._company._departureDate), null, null, null, offer.token);
38060    }
38061  }, {
38062    key: 'drawBus',
38063    value: function drawBus(tripData) {
38064      var _this = this;
38065
38066      var busBuilder = new BusMapSeat($);
38067
38068      LoaderService.show();
38069      this.fetchBusData(tripData).then(function (data) {
38070        if (data.result) {
38071          var busSeatList = data.result.seatMap;
38072
38073          busBuilder.init(busSeatList, _this.elemBusPreviewUpsel);
38074          _this.handleLargeBusToLargeModal(busSeatList.length);
38075        }
38076
38077        LoaderService.hide();
38078      }).catch(function (err) {
38079        LoaderService.hide();
38080        console.log(err);
38081      });
38082    }
38083  }, {
38084    key: 'handleLargeBusToLargeModal',
38085    value: function handleLargeBusToLargeModal(busLength) {
38086      if (busLength > 65) {
38087        this.modal.find('.modal-dialog').addClass('bus-large');
38088      }
38089    }
38090  }, {
38091    key: 'fetchBusData',
38092    value: function fetchBusData(tripData) {
38093      var body = {
38094        token: tripData.token
38095      };
38096
38097      var saleplatform = SessionStorage.get('utm_saleplatform');
38098      saleplatform ? body.SalePlatform = this.saleplatform : body.SalePlatform = "SITES-UTP";
38099
38100      var headers = {
38101        version: 2
38102      };
38103
38104      return HttpService.post('getVehicles', body, headers);
38105    }
38106  }]);
38107
38108  return BusPreview;
38109}();
38110'use strict';
38111
38112var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
38113
38114function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
38115
38116var CaptchaController = function () {
38117  function CaptchaController() {
38118    _classCallCheck(this, CaptchaController);
38119
38120    this.$captcha = $('[data-js="captcha-component"]');
38121    this.$btnSubmit = $('[data-js="button-login"]');
38122    this.key = $('[data-js="key-captcha"]').data('value');
38123    this.init();
38124  }
38125
38126  _createClass(CaptchaController, [{
38127    key: 'init',
38128    value: function init() {
38129      this.loadCaptchaKey();
38130    }
38131  }, {
38132    key: 'handleCaptcha',
38133    value: function handleCaptcha() {
38134      if (!this.$captcha.hasClass('d-none')) {
38135        if (grecaptcha.getResponse() == "") {
38136          return false;
38137        } else {
38138          return true;
38139        }
38140      }
38141
38142      return true;
38143    }
38144  }, {
38145    key: 'loadCaptchaKey',
38146    value: function loadCaptchaKey() {
38147
38148      this.environment = $('#environmentPayment').val();
38149      this.keyCaptcha = null;
38150      var urlWcmmode = new URL(window.location.href);
38151
38152      if ($('#wcmmodeedit').val() == 'true' || urlWcmmode.searchParams.get("wcmmode") == "disabled") {
38153        this.keyCaptcha = $('#captchaKeyAuthor').val();
38154      } else {
38155        this.keyCaptcha = $('#captchaKeyPublish').val();
38156      }
38157
38158      $('#g-recaptcha').attr('data-sitekey', this.keyCaptcha);
38159    }
38160  }, {
38161    key: 'showCaptcha',
38162    value: function showCaptcha() {
38163      this.$captcha.removeClass('d-none');
38164    }
38165  }, {
38166    key: 'hideCaptcha',
38167    value: function hideCaptcha() {
38168      this.$captcha.addClass('d-none');
38169    }
38170  }]);
38171
38172  return CaptchaController;
38173}();
38174'use strict';
38175
38176var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
38177
38178function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
38179
38180var CardDetailsCheckout = function () {
38181  function CardDetailsCheckout($) {
38182    _classCallCheck(this, CardDetailsCheckout);
38183
38184    this.headerCheckout = $('.header-checkout');
38185    this.bookingFinder = $('.card-finder');
38186    this.checkout = SessionStorage.get('checkout');
38187    this.totalTaxa = 0;
38188    this.totalPrice = 0;
38189    this.totalConvenienceFee = 0;
38190    this.totalDiscount = 0;
38191    this.totalInsurance = 0;
38192
38193    this.init();
38194  }
38195
38196  _createClass(CardDetailsCheckout, [{
38197    key: 'init',
38198    value: function init() {
38199      this.isWalletBack();
38200      this.renderNew();
38201      this.updateValues();
38202      if (this.headerCheckout.length) {
38203        this.headerCheckout[0].style.setProperty("display", "none", "important");
38204      }
38205
38206      if (this.bookingFinder.length) {
38207        this.bookingFinder[0].style.setProperty("display", "none", "important");
38208      }
38209    }
38210  }, {
38211    key: 'isWalletBack',
38212    value: function isWalletBack() {
38213      $('[data-js="btn-back-wallet"]').on('click', function () {
38214        $(location).attr('href', $('#walletButtonConfirm').val());
38215      });
38216    }
38217  }, {
38218    key: 'renderNew',
38219    value: function renderNew() {
38220      var _this = this;
38221
38222      if (!this.checkout || !this.checkout.sales) {
38223        return;
38224      }
38225
38226      this.checkout.sales.forEach(function (sale) {
38227        if (sale.valueParts && Array.isArray(sale.valueParts) && sale.valueParts.length > 0) {
38228          sale.valueParts.forEach(function (part) {
38229            switch (part.code) {
38230              case 'Tax':
38231                _this.totalTaxa += part.value || 0;
38232                break;
38233              case 'Tariff':
38234                _this.totalPrice += part.value || 0;
38235                break;
38236              case 'ConvenienceFee':
38237                _this.totalConvenienceFee += part.value || 0;
38238                break;
38239              case 'Insurance':
38240                _this.totalInsurance += part.value || 0;
38241                break;
38242              case 'Discount':
38243                _this.totalDiscount += part.value || 0;
38244                break;
38245            }
38246          });
38247        }
38248      });
38249    }
38250  }, {
38251    key: 'updateValues',
38252    value: function updateValues() {
38253      this.complementPix = SessionStorage.get('completementPix');
38254
38255      this.repricingV2 = SessionStorage.get('repricingv2');
38256      var valueTotal = this.totalPrice + this.totalConvenienceFee + this.totalDiscount + this.totalTaxa;
38257      var valueWallet = valueTotal - this.checkout.value;
38258
38259      $('[data-js="tariff-wallet"]').text('R$ ' + Utils.formatPrice(this.totalPrice));
38260      $('[data-js="convenience-fee-wallet"]').text('R$ ' + Utils.formatPrice(this.totalConvenienceFee));
38261      $('[data-js="discount-wallet"]').text('R$ ' + Utils.formatPrice(this.totalDiscount));
38262      $('[data-js="tax-wallet"]').text('R$ ' + Utils.formatPrice(this.totalTaxa));
38263      $('[data-js="value-payment-wallet"]').text('R$ ' + Utils.formatPrice(valueWallet));
38264      $('[data-js="value-payment-pix"]').text('R$ ' + Utils.formatPrice(this.checkout.value));
38265
38266      if (this.complementPix && this.complementPix === true) {
38267        $('[data-js="buy-value"]').text('R$ ' + Utils.formatPrice(valueTotal));
38268      }
38269      if (this.repricingV2 && valueWallet > 0) {
38270        $('[data-js="credit-wallet"]').text('-R$ ' + Utils.formatPrice(valueWallet));
38271        $('[data-js="credit-wallet-container"]').removeClass('d-none');
38272      }
38273    }
38274  }]);
38275
38276  return CardDetailsCheckout;
38277}();
38278'use strict';
38279
38280var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
38281
38282var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
38283
38284function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
38285
38286var CheckoutDetailsCard = function () {
38287  function CheckoutDetailsCard(_ref) {
38288    var $parent = _ref.$parent,
38289      trip = _ref.trip,
38290      _ref$index = _ref.index,
38291      index = _ref$index === undefined ? null : _ref$index,
38292      _ref$subindex = _ref.subindex,
38293      subindex = _ref$subindex === undefined ? null : _ref$subindex,
38294      _ref$isNextTripTab = _ref.isNextTripTab,
38295      isNextTripTab = _ref$isNextTripTab === undefined ? true : _ref$isNextTripTab,
38296      isReturn = _ref.isReturn;
38297
38298    _classCallCheck(this, CheckoutDetailsCard);
38299
38300    this.index = index;
38301    this.subindex = subindex;
38302    this.parent = $parent;
38303    this.trip = trip;
38304    this.modal = new Modal($);
38305    this.isNextTripTab = isNextTripTab;
38306    this.ticketLink = $('[data-js="virtual-ticket-link"]').val() ? $('[data-js="virtual-ticket-link"]').val() : 'https://wemobihml.vendasjca.com.br/sale/getticket?';
38307    this.isReturn = isReturn;
38308    this.convenienceFee = $('[data-js="convenience-fee"]').attr('value') == 'true' ? true : false;
38309    this.checkout = SessionStorage.get('checkout');
38310    this.init();
38311  }
38312
38313  _createClass(CheckoutDetailsCard, [{
38314    key: 'init',
38315    value: function init() {
38316      this.loadCardIndexes();
38317      this.loadCardHeader();
38318      this.loadCardBody();
38319      this.loadCardTable();
38320      this.handlePriceDetails();
38321      this.showAddressInCardCheckout();
38322      this.setCompanyName();
38323      this.checkout = SessionStorage.get('checkout');
38324      this.cartComponent = new CartComponent($, this.formData);
38325    }
38326  }, {
38327    key: 'loadCardIndexes',
38328    value: function loadCardIndexes() {
38329      var html = void 0;
38330
38331      //html = this.parent.html().replace(/(${subindex})/g, this.subindex);
38332      //html = html.replace(/(${index})/g, this.index);
38333
38334      // o aem confunde a variavel com o formato ${index} pois cifrão é o usado no HTL,
38335      // por esse motivo no arquivo trip-detail-my-account-v2.htmll substituímos por #INDEX E #SUBINDEX
38336      html = this.parent.html().replace(/(\#SUBINDEX)/g, this.subindex);
38337      html = html.replace(/(\#INDEX)/g, this.index);
38338
38339      this.parent.empty().append(html);
38340    }
38341  }, {
38342    key: 'loadCardHeader',
38343    value: function loadCardHeader() {
38344        Utils.appendAemTextContent(this.parent, 'depart-date', this.getTripData(0));
38345        Utils.appendAemTextContent(this.parent, 'depart-hour', this.getTripData(1));
38346        Utils.appendAemTextContent(this.parent, 'depart-hour-arr', this.getTripData(2));
38347
38348        var collapsedContainer = this.parent.find('.card-checkout').data('inner-collapsed');
38349        if (collapsedContainer) {
38350            this.parent.find('.card-checkout-header').addClass('collapsed');
38351            var collapsible = this.parent.find('.card-checkout-collapsible')[0];
38352				    new bootstrap.Collapse(collapsible, { toggle: false }).hide();
38353        } else {
38354            this.parent.find('.card-checkout-header').removeClass('collapsed');
38355            var _collapsible = this.parent.find('.card-checkout-collapsible')[0];
38356				    new bootstrap.Collapse(_collapsible, { toggle: false }).show();
38357        }
38358
38359        var cardName = this.parent.data('js');
38360        cardName = cardName.replace(/\W\d/gi, '');
38361
38362        switch (cardName) {
38363            case 'detail-depart':
38364                this.parent.find('[data-js="ticket-label"]').text('Ida');
38365                break;
38366            case 'detail-depart-connection':
38367                this.parent.find('[data-js="ticket-label"]').text('Ida - Conexão');
38368                break;
38369            case 'detail-depart-connection2':
38370                this.parent.find('[data-js="ticket-label"]').text('Ida - Conexão');
38371                break;
38372            case 'detail-return':
38373                this.parent.find('[data-js="ticket-label"]').prev().addClass('rotate');
38374                this.parent.find('[data-js="ticket-label"]').text('Volta');
38375                break;
38376            case 'detail-return-connection':
38377                this.parent.find('[data-js="ticket-label"]').prev().addClass('rotate');
38378                this.parent.find('[data-js="ticket-label"]').text('Volta - Conexão');
38379                break;
38380            case 'detail-return-connection2':
38381                this.parent.find('[data-js="ticket-label"]').prev().addClass('rotate');
38382                this.parent.find('[data-js="ticket-label"]').text('Volta - Conexão');
38383                break;
38384        }
38385    }
38386  }, {
38387    key: 'loadCardBody',
38388    value: function loadCardBody() {
38389        var tripArray = Array.isArray(this.trip) ? this.trip : [this.trip];
38390
38391        if (!tripArray.length || !tripArray[0]) {
38392            return;
38393        }
38394
38395        var firstLeg = tripArray[0];
38396        var lastLeg = tripArray[tripArray.length - 1];
38397
38398        var originDescription = firstLeg.originDescription;
38399        var destinationDescription = lastLeg.destinationDescription;
38400        var company = firstLeg.company;
38401
38402        var formData = SessionStorage.get('formData');
38403
38404      if (formData) {
38405        this.setAddressCheckoutCard(formData);
38406        var originAddress = formData.depart.origin.address;
38407        var destinationAddress = formData.depart.destination.address;
38408
38409        Utils.applyAemTextContent(this.parent, 'departureAddress', (!this.isReturn ? originAddress : destinationAddress));
38410        Utils.applyAemTextContent(this.parent, 'destinationAddress', (!this.isReturn ? destinationAddress : originAddress));
38411      }
38412
38413        this.parent.find('[data-js="departureLabel"]').text(Utils.capitalize(originDescription));
38414        this.parent.find('[data-js="destinationLabel"]').text(Utils.capitalize(destinationDescription));
38415        this.parent.find('[data-js="companyName"]').text(company);
38416    }
38417  }, {
38418    key: 'setAddressCheckoutCard',
38419    value: function setAddressCheckoutCard(formData) {
38420      var originAddress = formData.depart.origin.address;
38421      var destinationAddress = formData.depart.destination.address;
38422
38423      Utils.applyAemTextContent(this.parent, 'departureAddress', (!this.isReturn ? originAddress : destinationAddress));
38424      Utils.applyAemTextContent(this.parent, 'destinationAddress', (!this.isReturn ? destinationAddress : originAddress));
38425    }
38426  }, {
38427    key: 'setCompanyName',
38428    value: function setCompanyName() {
38429      var companyName = this.trip[0].company;
38430      Utils.applyAemTextContent(this.parent, 'companyName', companyName);
38431    }
38432  }, {
38433    key: 'loadCardTable',
38434    value: function loadCardTable() {
38435      var _this = this;
38436
38437      var $tableDeparture = this.parent.find('[data-js="checkout-table"]');
38438      $.each(this.trip, function (index, el) {
38439        return _this.addPassenger($tableDeparture.find('tbody'), el, index);
38440      });
38441    }
38442  }, {
38443    key: 'addPassenger',
38444    value: function addPassenger(parent, passenger, index) {
38445      var _this2 = this;
38446
38447      var status = passenger.status;
38448
38449      var seat = passenger.seat;
38450      var statusTrip = status.toUpperCase();
38451      var cart = SessionStorage.get('cart');
38452
38453      var isCanceled = statusTrip === 'SALE_CANCELED' || statusTrip === 'INITIAL_CREATE' || statusTrip === 'REFUND_PENDING' || statusTrip === 'REFUND_PEDING' || statusTrip === 'LATE_REFUND';
38454      var isNextTripTab = this.isNextTripTab;
38455
38456      if (isCanceled) {
38457        passenger.amount = 0;
38458        seat = 'Cancelado';
38459      }
38460
38461      var content = [];
38462
38463      var ticketLinkParameters = {
38464		finder: window.btoa(passenger.finder ?? this.checkout?.result?.finder ?? ''),
38465        id: passenger.id
38466      };
38467
38468      var getPrice = function getPrice(passenger) {
38469        var totalAmount = 0;
38470        var insuranceChecked = sessionStorage.getItem('insuranceChecked') === 'true';
38471
38472        if (passenger.valueParts && Array.isArray(passenger.valueParts) && passenger.valueParts.length > 0) {
38473          totalAmount = passenger.valueParts.reduce(function (total, part) {
38474            return total + (part.value || 0);
38475          }, 0);
38476        } else {
38477          totalAmount = passenger.amount || 0;
38478        }
38479        var optionalInsurance = insuranceChecked ? passenger.optionalInsurance || 0 : 0;
38480
38481        var convenienceFee = _this2.convenienceFee ? passenger.convenienceFee || 0 : 0;
38482        var finalAmount = totalAmount + optionalInsurance + convenienceFee;
38483
38484        return Utils.formatPrice(finalAmount);
38485      };
38486
38487      content.push('\n\t\t\t<tr>\n\t\t\t\t<td class="align-left">\n\t\t\t\t\t<p class="strong"> ' + passenger.passengerName + ' </p>\n\t\t\t\t\t<p class="document hide-desktop">Doc.<span> ' + passenger.passengerDocument + ' </span></p>\n\t\t\t\t</td>\n\t\t\t\t<td class="hide-mobile">\n\t\t\t\t\t<p class="strong"> ' + passenger.passengerDocument + ' </p>\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t\t<p class="strong"> ' + (passenger.typeId === 1 && !isCanceled ? "Sem ocupar" : seat) + ' </p>\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t<p class="strong">\n\t\t\t\t\t' + (passenger.typeId === 1 ? "-" : "R$ " + getPrice(passenger)) + '\n\t\t\t\t</p>\n\t\t\t\t\t<a class="details-price-link ' + (isCanceled ? 'canceled' : '') + '" href="javascript:void(0)" data-bs-toggle="modal" data-bs-target="#price-details-modal" data-bs-collapse-index=' + index + '> Detalhes do pre\xE7o </a>\n\t\t\t\t</td>\n\t\t\t\t<td class="hide-on-mobile ticket-td">\n\t\t\t\t\t<div class="ticket-wrapper">\n\t\t\t\t\t' + (!isCanceled ? passenger.status !== 'SALE_PENDING' && passenger.status !== 'SALE_EXPIRED' && passenger.status !== 'EXCHANGED' && passenger.status !== 'EXCHANGE_PENDING' ? passenger.status !== 'RELOCATED_CANCELED' && passenger.status !== 'CANCELATION_ERROR' ? '<em class="jca-ico-ticket ticketDisponivel"></em><a id="passenger-price-details-' + passenger.finder + '-' + passenger.id + '"  target="_blank" href="' + (this.ticketLink + $.param(ticketLinkParameters)) + '">Dispon\xEDvel</a>' : '<em class="jca-ico-ticket ticketIndisponivel"></em><p class="ticket-canceled">Indisponivel</p>' : '<em class="jca-ico-ticket ticketIndisponivel"></em><p>Pendente</p>' : status == 'INITIAL_CREATE' ? '<p class="ticket-canceled">Indisponivel</p>' : '<em class="jca-ico-ticket ticketIndisponivel"></em><p>Cancelado</p>') + '\n\t\t\t\t\t</div>\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr class="hide-desktop">\n\t\t\t\t<th class="ticket-th" colspan="5">\n\t\t\t\t\t<div class="ticket-wrapper">\n\t\t\t\t\t' + (!isCanceled ? passenger.status !== 'SALE_PENDING' && passenger.status !== 'SALE_EXPIRED' && passenger.status !== 'EXCHANGED' && passenger.status !== 'EXCHANGE_PENDING' ? passenger.status !== 'RELOCATED_CANCELED' && passenger.status !== 'CANCELATION_ERROR' ? '<em class="jca-ico-ticket ticketDisponivel"></em><a id="passenger-return-price-details-' + passenger.finder + '-' + passenger.id + '"  target="_blank" href="' + (this.ticketLink + $.param(ticketLinkParameters)) + '">Dispon\xEDvel</a>' : '<em class="jca-ico-ticket ticketIndisponivel"></em><p class="ticket-canceled">Indisponivel</p>' : '<em class="jca-ico-ticket ticketIndisponivel"></em><p>Pendente</p>' : '<em class="jca-ico-ticket ticketIndisponivel"></em><p>Cancelado</p>') + '\n\t\t\t\t\t</div>\n\t\t\t\t</th>\n\t\t\t</tr>\n\t\t');
38488      parent.append(content.join(''));
38489    }
38490  }, {
38491    key: 'getTripData',
38492    value: function getTripData(index) {
38493        var trip = Array.isArray(this.trip) ? this.trip[0] : this.trip;
38494
38495        var getDesktopDate = function getDesktopDate(date) {
38496            var dateValid = DateFormatter.getValidDateFormat(date);
38497            var dayNumber = dateValid.getDay();
38498
38499            var dayName = Utils.capitalize(DateFormatter.getDaysArray()[dayNumber]);
38500            var month = String(dateValid.getMonth() + 1).padStart(2, '0');
38501            var year = dateValid.getFullYear();
38502            var day = dateValid.getDate();
38503            var userLang = Utils.getCurrentLang();
38504
38505            switch (userLang) {
38506                case 'en':
38507                    return dayName + ', ' + month + '/' + (day > 9 ? day : '0' + day) + '/' + year;
38508                case 'es':
38509                    return dayName + ', ' + (day > 9 ? day : '0' + day) + '/' + month + '/' + year;
38510                default:
38511                    return dayName + ', ' + (day > 9 ? day : '0' + day) + '/' + month + '/' + year;
38512            }
38513        };
38514
38515        switch (index) {
38516            case 0:
38517                return getDesktopDate(trip.departureDate);
38518            case 1:
38519                return DateFormatter.extractHour(trip.departureDate);
38520            case 2:
38521                return DateFormatter.extractHour(trip.arivalDate);
38522            default:
38523                break;
38524        }
38525    }
38526  }, {
38527    key: 'handlePriceDetails',
38528    value: function handlePriceDetails() {
38529      var _this2 = this;
38530
38531      this.parent.find('.details-price-link').on('click', function (e) {
38532        var collapseIndex = $(e.currentTarget).data('collapse-index');
38533        _this2.renderDetailsPassenger(collapseIndex);
38534      });
38535    }
38536  }, {
38537    key: 'renderDetailsPassenger',
38538    value: function renderDetailsPassenger(collapseIndex) {
38539      var _this4 = this;
38540
38541      var contentDetail = [];
38542      var countPassengers = 0;
38543      var cart = SessionStorage.get('cart');
38544      var insuranceChecked = sessionStorage.getItem('insuranceChecked');
38545
38546      var tariff = $('[data-js="modal-price-details-values"]').attr('data-text-tariff') ? $('[data-js="modal-price-details-values"]').attr('data-text-tariff') : 'Tarifa';
38547      var tax = $('[data-js="modal-price-details-values"]').attr('data-text-tax') ? $('[data-js="modal-price-details-values"]').attr('data-text-tax') : 'Taxa';
38548      var totalLabel = $('[data-js="modal-price-details-values"]').attr('data-text-total') ? $('[data-js="modal-price-details-values"]').attr('data-text-total') : 'Total';
38549      var priceDetailsLabel = $('[data-js="modal-price-details-values"]').attr('data-text-price-details') ? $('[data-js="modal-price-details-values"]').attr('data-text-price-details') : 'Detalhes do preço';
38550      var travelInsuranceLabel = $('[data-js="modal-price-details-values"]').attr('data-text-travel-insurance') ? $('[data-js="modal-price-details-values"]').attr('data-text-travel-insurance') : "Seguro Viagem";
38551      var convenienceText = $('[data-js="modal-price-details-values"]').attr('data-text-convenience-fee') ? $('[data-js="modal-price-details-values"]').attr('data-text-convenience-fee') : i18n('convenience_fee');
38552      var conveninenceTextToolip = $('[data-js="modal-price-details-values"]').attr('data-text-msg-faq-convenience-fee') ? $('[data-js="modal-price-details-values"]').attr('data-text-msg-faq-convenience-fee') : i18n('msg_faq_convenience_fee');
38553
38554      var tariffColor = $('[data-js="modal-price-details-values"]').attr('data-text-tariff-color');
38555      var taxColor = $('[data-js="modal-price-details-values"]').attr('data-text-tax-color');
38556      var totalLabelColor = $('[data-js="modal-price-details-values"]').attr('data-text-total-color');
38557      var priceDetailsLabelColor = $('[data-js="modal-price-details-values"]').attr('data-text-price-details-color');
38558      var priceDetailsLabelColorIcon = '-webkit-text-stroke: 1px ' + $('[data-js="modal-price-details-values"]').attr('data-text-price-details-color-icon');
38559      var passengerNameColor = $('[data-js="modal-price-details-values"]').attr('data-text-passenger-name-color');
38560      var lineSeparator = 'border-bottom: 1px solid ' + $('[data-js="modal-price-details-values"]').attr('data-style-line');
38561      var seatNumberColor = 'color:' + $('[data-js="modal-price-details-values"]').attr('data-style-seat-number-color');
38562      var seatNumberBackground = 'background-color:' + $('[data-js="modal-price-details-values"]').attr('data-style-seat-number-background');
38563      var travelInsuranceLabelColor = $('[data-js="modal-price-details-values"]').attr('data-style-travel-insurance-color');
38564
38565
38566      this.trip.forEach(function (el, i) {
38567        var tarifa = 0;
38568        var taxa = 0;
38569        var convenienceFee = 0;
38570        var total = 0;
38571        var discount = 0;
38572        var insurance = 0;
38573        var commissionFee = 0;
38574
38575        if (el.valueParts && el.valueParts.length > 0) {
38576          el.valueParts.forEach(function (part) {
38577            if (part.name === "Tariff") {
38578              tarifa += part.value || 0;
38579            } else if (part.name === "Tax") {
38580              taxa += part.value || 0;
38581            } else if (part.name === "Insurance") {
38582              insurance += part.value || 0;
38583            } else if (part.name === "ConvenienceFee") {
38584              convenienceFee += part.value || 0;
38585            } else if (part.name === "Desconto") {
38586              discount += part.value || 0;
38587            } else if (part.name === "CommissionFee") {
38588              commissionFee += part.value || 0;
38589            }
38590          });
38591          total = tarifa + discount + taxa + convenienceFee + insurance + commissionFee;
38592        } else {
38593          tarifa = el.discountPix ? el.tariff - el.discountPix : el.tariff;
38594          taxa = +el.tollTax + +el.boardingFee + +el.insuranceTax
38595          convenienceFee = el.convenienceFee || 0;
38596          total = el.voucherToken !== "" ? el.amount - taxa : el.tariff;
38597
38598          var _insurance = +el.optionalInsurance ? +el.optionalInsurance || 0 : 0;
38599          total = tarifa + taxa + convenienceFee + _insurance;
38600        }
38601
38602        var isChild = el.typeId === 1;
38603        var isCanceled = el.status === "SALE_CANCELED" || el.status.toUpperCase() === 'REFUND_PEDING' || el.status.toUpperCase() === 'LATE_REFUND';
38604        var isSelectedCollapse = i == collapseIndex;
38605
38606        if (isCanceled) return;
38607
38608        ++countPassengers;
38609        $('[data-js="passenger-count"]').text(countPassengers > 1 ? countPassengers + ' ' + 'Passageiros' : countPassengers + ' ' + 'Passageiros');
38610
38611        contentDetail.push('\n\t\t\t\t<li>\n\t\t\t\t\t<div class="container-cart-passenger">\n\t\t\t\t\t\t<span class="name col-6">' + el.passengerName + '</span>\n\n\t\t\t\t\t\t<span class="square-seat col-2 col-sm-1 ' + (isChild ? 'd-none' : '') + '">\n\t\t\t\t\t\t\t<p class="icon-seat-number">' + el.seat + '</p>\n\t\t\t\t\t\t</span>\n\n\t\t\t\t\t\t<button class="seat-subtitle btn-collapse col-4 col-sm-5" data-bs-collapse="collapse" id="open-collapse-price-' + i + '" data-bs-target="#collapse-price-' + i + '"\n\t\t\t\t\t\t\taria-expanded="true" aria-controls="collapse-price-' + i + '" data-js="collapse-price-' + i + '">\n\t\t\t\t\t\t\t' + priceDetailsLabel + '\n\t\t\t\t\t\t\t<span class="icon-collapse jca-ico-angle-down ' + (isSelectedCollapse ? 'active' : '') + '" data-js="collapse-price-' + i + '" id="open-icon-collapse-price-' + i + '">\t</span>\n\t\t\t\t\t\t</button>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<div class="container-cart-details collapse-container ' + (isSelectedCollapse ? 'active' : '') + '" data-bs-parent="#list-details-price" data-js="collapse-price-' + i + '">\n\t\t\t\t\t\t<div class="container-cart-details-content">\n\t\t\t\t\t\t<p class="title">\n\t\t\t\t\t\t\t<p class="title"><span class="container-cart-details-title">' + tariff + '</span><span class="container-cart-details-result"> R$ ' + (!isChild ? Utils.formatPrice(tarifa) : Utils.formatPrice(0.00)) + '</span></p>\n\t\t\t\t\t\t\t<p class="title"><span class="container-cart-details-title">' + tax + '</span><span class="container-cart-details-result">R$ ' + (!isChild ? Utils.formatPrice(taxa) : Utils.formatPrice(0.00)) + '</span></p>\n\t\t\t\t\t\t</p>\n\t\t\t\t\t\t\t<p class="title ' + (_this4.convenienceFee ? '' : 'd-none') + '">\n                <span class="container-cart-details-title total">\n                  ' + convenienceText + '\n                  <a class="icon jca-ico-info-icon tooltip-btn" href="#">
38611\n                    <span class="tooltiptext">' + conveninenceTextToolip + '</span>\n                  </a>\n                </span>\n                <span class="container-cart-details-result">\n                  R$ ' + (!isChild ? Utils.formatPrice(convenienceFee) : Utils.formatPrice(0.00)) + '\n                </span>\n              </p>\n            ' + (insurance > 0 ? '<p class="title"><span class="container-cart-details-title">' + travelInsuranceLabel + '</span><span class="container-cart-details-result">R$ ' + Utils.formatPrice(insurance) + '</span></p>' : '') + '\n\n\t\t\t\t\t\t\t<p class="title total"><span class="container-cart-details-title total">Total</span><span class="container-cart-details-result">R$ ' + (!isChild ? Utils.formatPrice(total) : Utils.formatPrice(0.00)) + '</span></p>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</li>\n\t\t\t');
38612      });
38613
38614      $('[data-js="list-details-price"]').empty().append(contentDetail.join(''));
38615      new Collapse($);
38616    }
38617  }, {
38618    key: 'showAddressInCardCheckout',
38619    value: function showAddressInCardCheckout() {
38620      var showAddress = $('[data-js="show-address"]').val() == 'true';
38621
38622      if (!showAddress) {
38623        $('[data-js="departureAddress"], [data-js="destinationAddress"]').hide();
38624      }
38625    }
38626  }]);
38627
38628  return CheckoutDetailsCard;
38629}();
38630'use strict';
38631
38632var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
38633
38634function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
38635
38636var DropdownMenu = function () {
38637  function DropdownMenu($, scrollable) {
38638    var _this = this;
38639
38640    _classCallCheck(this, DropdownMenu);
38641
38642    this.selector = $('[data-js="dropdown-header"]');
38643    this.dropdownMenu = $('[data-js="dropdown-list"]');
38644    this.currentTop = 0;
38645    this.selector.click(function (e) {
38646      if ($(e.target).hash && $(e.currentTarget).closest('a').length == 0) e.preventDefault();
38647      if ($(e.target).parent().hasClass('dropdown-header') || $(e.target).parent().hasClass('dropdown-wrapper')) {
38648        _this.expandItem(e.currentTarget);
38649        if (scrollable) _this.scrollToElement(e.currentTarget);
38650      }
38651    });
38652  }
38653
38654  _createClass(DropdownMenu, [{
38655    key: 'expandItem',
38656    value: function expandItem(element) {
38657      var $el = $(element);
38658      var clicked = $el.children('.dropdown-list');
38659      var icon = clicked.parent().find('.arrow-down');
38660      var iconToClose = this.selector.find('.jca-ico-angle-top');
38661      var hiddenTextToChange = this.selector.find('.visuallyHidden');
38662      var hiddenText = $el.find('.visuallyHidden');
38663      if (hiddenText.length > 0 && hiddenText.text() != '') {
38664        if (hiddenText.text() === 'Expandir') {
38665          hiddenTextToChange.text("Expandir");
38666          hiddenText.text("Recolher");
38667        } else hiddenText.text("Expandir");
38668      }
38669      icon.toggleClass('jca-ico-angle-down');
38670      icon.toggleClass('jca-ico-angle-top');
38671      iconToClose.addClass('jca-ico-angle-down');
38672      iconToClose.removeClass('jca-ico-angle-top');
38673      clicked.toggleClass("closed");
38674      this.dropdownMenu.not(clicked).addClass("closed");
38675      $el.toggleClass("active");
38676      this.selector.not(element).removeClass("active");
38677    }
38678  }, {
38679    key: 'scrollToElement',
38680    value: function scrollToElement(element) {
38681      var _Utils$getWindowSize = Utils.getWindowSize(),
38682        width = _Utils$getWindowSize.width,
38683        breakpoints = _Utils$getWindowSize.breakpoints;
38684
38685      var $el = $(element);
38686      var titleClass = $el.find('.title-class') || $el.parent().find('.title-class');
38687      var headerHeight = titleClass ? titleClass.outerHeight() : 0;
38688      headerHeight = width > breakpoints.LG ? headerHeight : 1.5 * headerHeight;
38689      var offset = $el ? $el.offset().top : 0;
38690      self.currentTop = self.currentTop == offset - headerHeight ? 0 : offset - headerHeight;
38691      window.scroll({
38692        top: self.currentTop,
38693        behavior: 'smooth'
38694      });
38695    }
38696  }]);
38697
38698  return DropdownMenu;
38699}();
38700'use strict';
38701
38702var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
38703
38704function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
38705
38706/**
38707 *
38708 * HEADER SEARCH
38709 *
38710 * BEGIN
38711 **/
38712
38713var HeaderSearch = function () {
38714  function HeaderSearch($) {
38715    _classCallCheck(this, HeaderSearch);
38716
38717    this.searchButton = $('[data-js="header-search-button"]');
38718    this.closeButton = $('[data-js="header-search-close-button"]');
38719    this.overlay = $('[data-js="header-search-overlay"]');
38720    this.input = $('[data-js="header-search-input"]');
38721    this.init();
38722  }
38723
38724  _createClass(HeaderSearch, [{
38725    key: 'init',
38726    value: function init() {
38727      this.handleEvents();
38728    }
38729  }, {
38730    key: 'toggleSearch',
38731    value: function toggleSearch() {
38732      this.closeButton.toggleClass('active');
38733      this.searchButton.toggleClass('active');
38734      this.input.toggleClass('active');
38735      this.overlay.toggleClass('active');
38736      if (this.input.is('.active')) {
38737        this.input.trigger('focus');
38738        return;
38739      }
38740
38741      this.input.val('');
38742    }
38743  }, {
38744    key: 'search',
38745    value: function search(text) {
38746      alert('Searching for ' + text + '...');
38747      this.toggleSearch();
38748    }
38749  }, {
38750    key: 'handleSearchButton',
38751    value: function handleSearchButton() {
38752      if (this.input.is('.active') && this.input.val().trim()) {
38753        this.search(this.input.val().trim());
38754        return;
38755      }
38756
38757      this.toggleSearch();
38758    }
38759  }, {
38760    key: 'handleEvents',
38761    value: function handleEvents() {
38762      var _this = this;
38763
38764      this.searchButton.on('click', function () {
38765        return _this.handleSearchButton();
38766      });
38767      this.closeButton.on('click', function () {
38768        return _this.toggleSearch();
38769      });
38770      this.input.on('keyup', function (e) {
38771        var key = e.keyCode || e.which;
38772        if (key === Utils.keyCodes.ENTER) {
38773          _this.search(_this.input.val());
38774        }
38775      });
38776    }
38777  }]);
38778
38779  return HeaderSearch;
38780}();
38781'use strict';
38782
38783var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
38784
38785function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
38786
38787/**
38788 * BEGIN
38789 * Header Filter Class (Deep Link)
38790 *
38791 */
38792
38793var HeaderFilter = function () {
38794  function HeaderFilter($, searchComponent) {
38795    _classCallCheck(this, HeaderFilter);
38796
38797    this.searchComponent = searchComponent;
38798    this.datePickerControl = new DatePickerControl($, searchComponent, null);
38799    this.inputDepart = $('[data-js="input-departure"]:visible');
38800    this.inputDest = $('[data-js="input-destination"]:visible');
38801    this.inputDateDepart = $('[data-js="input-date-departure"]:visible');
38802    this.inputDateRet = $('[data-js="input-date-return"]:visible');
38803
38804    this.init();
38805  }
38806
38807  _createClass(HeaderFilter, [{
38808    key: 'init',
38809    value: function init() {
38810      this.updateServiceDestination();
38811
38812      var formData = SessionStorage.get('formData');
38813
38814      if (formData) {
38815        this.loadFormDataIntoHeaderSearch(formData);
38816        new ShoppingInfo();
38817      }
38818
38819      if ($('main').find("[data-js='search-form']").length <= 0) {
38820        $('.header-passage-form').attr('aria-hidden', 'false');
38821      }
38822    }
38823  }, {
38824    key: 'updateServiceDestination',
38825    value: function updateServiceDestination() {
38826      $('[data-js="input-departure"]:visible').on('click', function () {
38827        SessionStorage.remove('serviceDestination');
38828      });
38829    }
38830  }, {
38831    key: 'loadFormDataIntoHeaderSearch',
38832    value: function loadFormDataIntoHeaderSearch(formData) {
38833      {
38834        //Location
38835        var lastSelectedOrigin = {
38836          value: formData.depart.origin.id,
38837          label: formData.depart.origin.label + ' (' + formData.depart.origin.uf + ')'
38838        };
38839        var lastSelectedDestination = {
38840          value: formData.depart.destination.id,
38841          label: formData.depart.destination.label + ' (' + formData.depart.destination.uf + ')'
38842        };
38843        this.inputDepart.val(lastSelectedOrigin.label);
38844        this.inputDepart.data('value', lastSelectedOrigin.value);
38845        this.inputDest.val(lastSelectedDestination.label);
38846        this.inputDest.data('value', lastSelectedDestination.value);
38847
38848        this.searchComponent.locationInput.lastSelected[this.inputDepart.data('js')] = lastSelectedOrigin;
38849        this.searchComponent.locationInput.lastSelected[this.inputDest.data('js')] = lastSelectedDestination;
38850      }
38851
38852      {
38853        //Dates
38854        this.inputDateDepart.val(DateFormatter.reverseDate(formData.depart.date));
38855        this.inputDateDepart.data('date', formData.depart.date);
38856
38857        if (formData.return.date && formData.return.date.length > 0) {
38858          this.inputDateRet.val(DateFormatter.reverseDate(formData.return.date));
38859          this.inputDateRet.data('date', formData.return.date);
38860        } else {
38861          this.inputDateRet.datepicker("option", "minDate", DateFormatter.reverseDate(formData.depart.date));
38862        }
38863      }
38864
38865      this.searchComponent.currentResultDep = SessionStorage.get('currentResultDep');
38866    }
38867  }]);
38868
38869  return HeaderFilter;
38870}();
38871'use strict';
38872
38873var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
38874
38875function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
38876
38877var InformativeCarousel = function () {
38878  function InformativeCarousel($) {
38879    _classCallCheck(this, InformativeCarousel);
38880
38881    this.slickContainer = $('[data-js="informative-carousel-container"]');
38882
38883    this.init();
38884  }
38885
38886  _createClass(InformativeCarousel, [{
38887    key: 'init',
38888    value: function init() {
38889      this.handleSlick();
38890    }
38891  }, {
38892    key: 'handleSlick',
38893    value: function handleSlick() {
38894      this.slickContainer.each(function () {
38895        var $carousel = $(this);
38896        var $cardsCarousel = $('.informative-item-container', $carousel);
38897        var slidesShow = Math.min(2, $cardsCarousel.length);
38898
38899        this.slickProperties = {
38900          dots: true,
38901          arrows: false,
38902          infinite: true,
38903          adaptiveHeight: true,
38904          slidesToShow: 1,
38905          slidesToScroll: 1,
38906          responsive: [{
38907            breakpoint: 950,
38908            settings: {
38909              slidesToShow: slidesShow,
38910              slidesToScroll: slidesShow,
38911              dots: $cardsCarousel.length > 2
38912            }
38913          }, {
38914            breakpoint: 768,
38915            settings: {
38916              slidesToShow: 1,
38917              slidesToScroll: 1
38918            }
38919          }]
38920        };
38921
38922        $carousel.slick(this.slickProperties);
38923      });
38924    }
38925  }]);
38926
38927  return InformativeCarousel;
38928}();
38929'use strict';
38930
38931var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
38932
38933function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
38934
38935/**
38936 *
38937 * LANGUAGE SELECT
38938 *
38939 * INICIO
38940 *
38941 */
38942var LanguageSelect = function () {
38943  function LanguageSelect($, loginButton) {
38944    _classCallCheck(this, LanguageSelect);
38945
38946    this.languageList = [{
38947      locale: 'pt-br',
38948      icon: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/pt-br.png',
38949      selected: true
38950    }, {
38951      locale: 'es-es',
38952      icon: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/es-es.png'
38953    }, {
38954      locale: 'en-us',
38955      icon: '/etc.clientlibs/jca-v2/clientlibs/clientlib-site/resources/images/en-us.png'
38956    }];
38957
38958    this.langSelect = $('[data-js="lang-select"]');
38959    this.selectedLanguage = $('[data-js="selected-lang"]');
38960    this.langList = $('[data-js="language-list"]');
38961    this.langListOverlay = $('[data-js="language-list-overlay"]');
38962    this.langItems = $('[data-js="lang-item"]');
38963    this.closeButton = $('[data-js="language-close-btn"]');
38964    this.loginButton = loginButton;
38965    this.init($);
38966  }
38967
38968  _createClass(LanguageSelect, [{
38969    key: 'init',
38970    value: function init($) {
38971      var _this = this;
38972
38973      this.handleLanguageList($);
38974      this.langSelect.children().on('focusout', function (e) {
38975        var $target = $(e.relatedTarget);
38976        if ($target.length > 0 && $target.closest('[data-js="lang-select"]').length == 0) _this.closeButton.click();
38977      });
38978    }
38979  }, {
38980    key: 'closeLanguageList',
38981    value: function closeLanguageList() {
38982      this.langList.removeClass('active');
38983      this.langListOverlay.removeClass('active');
38984      this.closeButton.parent().removeClass('active');
38985    }
38986  }, {
38987    key: 'toggleLanguageList',
38988    value: function toggleLanguageList() {
38989      this.langList.toggleClass('active');
38990      this.langItems.first().focus();
38991      this.langListOverlay.toggleClass('active');
38992      this.closeButton.parent().toggleClass('active');
38993    }
38994  }, {
38995    key: 'handleLanguageList',
38996    value: function handleLanguageList($) {
38997      var controller = this;
38998      controller.selectedLanguage.on('click', function () {
38999        return controller.toggleLanguageList();
39000      });
39001      controller.selectedLanguage.on('focus', function () {
39002        controller.closeLanguageList();
39003        if ($('[data-js="header-login-modal-overlay"]').hasClass('active')) controller.loginButton.closeLoginModal();
39004      });
39005      controller.langList.on('click', function () {
39006        return controller.toggleLanguageList();
39007      });
39008      controller.closeButton.on('click', function () {
39009        return controller.closeLanguageList();
39010      });
39011
39012      controller.langItems.on('click', function (event) {
39013        controller.selectLanguage(event, $(this).data('locale'));
39014      });
39015    }
39016  }, {
39017    key: 'selectLanguage',
39018    value: function selectLanguage(event, locale) {
39019      var selectedItem = $(event.currentTarget);
39020      var selectedItemImg = selectedItem.find('img').clone();
39021
39022      selectedItem.parent().prependTo(selectedItem.parent().parent());
39023      this.selectedLanguage.empty().append(selectedItemImg).addClass('selected-lang');
39024    }
39025  }]);
39026
39027  return LanguageSelect;
39028}();
39029'use strict';
39030
39031var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
39032
39033function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
39034
39035var MenuMyData = function () {
39036  function MenuMyData($) {
39037    _classCallCheck(this, MenuMyData);
39038
39039    this.init();
39040  }
39041
39042  _createClass(MenuMyData, [{
39043    key: 'init',
39044    value: function init() {
39045      this.listenLinks();
39046      this.verifyPage();
39047    }
39048  }, {
39049    key: 'listenLinks',
39050    value: function listenLinks() {
39051      $('[data-js="minhas-viagens"]').on('click', function () {
39052        $(location).attr('href', 'my-account.html');
39053      });
39054
39055      $('[data-js="meus-dados"]').on('click', function () {
39056        var isMyDataActive = $(this).hasClass('active');
39057
39058        if (isMyDataActive) {
39059          $('[data-js="edit-data-container"]').addClass('active');
39060          Utils.removeBodyOverFlow();
39061          return;
39062        }
39063
39064        $(location).attr('href', 'edit-data.html');
39065      });
39066
39067      $('[data-js="alterar-senha"]').on('click', function () {
39068        var isUpdatePasswordActive = $(this).hasClass('active');
39069
39070        if (isUpdatePasswordActive) {
39071          $('.update-password-container').addClass('active');
39072          Utils.removeBodyOverFlow();
39073          return;
39074        }
39075
39076        $(location).attr('href', 'update-password.html');
39077      });
39078
39079      $('[data-js="formas-pagamento"]').on('click', function () {
39080        var isPaymentMethodsActive = $(this).hasClass('active');
39081
39082        if (isPaymentMethodsActive) {
39083          $('.payment-methods-container').addClass('active');
39084          Utils.removeBodyOverFlow();
39085          return;
39086        }
39087
39088        $(location).attr('href', 'payment-methods.html');
39089      });
39090
39091      $('[data-js="close-menu"]').on('click', function () {
39092        $(this).closest('.container-menu').removeClass('active');
39093        $('[data-js="message-confir"]').removeClass('active');
39094        $('[data-js="message-confir"]').parent().removeClass('active');
39095        $('.footer-edit-data-container').removeClass('active');
39096        Utils.addBodyOverFlow();
39097      });
39098
39099      $('[data-js="btn-conf"]').on('click', function () {
39100        $(location).attr('href', $('#homePagePath').val());
39101      });
39102
39103      $('[data-js="frequent-passenger"]').on('click', function () {
39104        var isFrequentPassengerActive = $(this).hasClass('active');
39105
39106        if (isFrequentPassengerActive) {
39107          $('.frequent-passenger-container').addClass('active');
39108          Utils.removeBodyOverFlow();
39109          return;
39110        }
39111
39112        $(location).attr('href', 'frequent-passenger.html');
39113      });
39114    }
39115  }, {
39116    key: 'verifyPage',
39117    value: function verifyPage() {
39118      var text = $('.container-menu').data('refer');
39119      $('[data-js ="' + text + '"]').addClass('active');
39120    }
39121  }]);
39122
39123  return MenuMyData;
39124}();
39125'use strict';
39126
39127var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
39128
39129function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
39130
39131var AlertConfirmation = function () {
39132  function AlertConfirmation() {
39133    _classCallCheck(this, AlertConfirmation);
39134  }
39135
39136  _createClass(AlertConfirmation, null, [{
39137    key: 'show',
39138    value: function show(title, subtitle, isError, redirectToHome) {
39139      var alert = isError ? '[data-js="message-confir"]' : '[data-js="alert-generic-success"]';
39140
39141      if ($('.message-confirmation-container').hasClass('active')) {
39142        $('.message-confirmation-container').removeClass('active');
39143        OverlayService.hide();
39144      }
39145
39146      if ($(alert).length > 1) {
39147        var alertVariable = $(alert)[0];
39148        $(alertVariable).parent().addClass('active');
39149        $(alertVariable).addClass('active');
39150      } else {
39151        $(alert).parent().addClass('active');
39152        $(alert).addClass('active');
39153      }
39154
39155      $('.footer-edit-data-container').addClass('active');
39156      $('#wemobi-header').addClass('opened-overlay');
39157
39158      var titleTarget = isError ? $(alert).find('[data-js="message-confir-title"]') : $(alert).find('[data-js="message-confir-title-suc"]');
39159      if (title && title != '' && title != null) {
39160        if (titleTarget.find('.cmp-text').length > 0) {
39161          titleTarget.find('.cmp-text').text(title);
39162        } else {
39163          titleTarget.text(title);
39164        }
39165      } else if (title == '' || title == null) {
39166        $(title).hide();
39167      }
39168
39169      var subtitleTarget = isError ? $(alert).find('[data-js="message-confir-subtitle"]') : $(alert).find('[data-js="message-confir-subtitle-suc"]');
39170      if (subtitle && subtitle != '' && subtitle != null) {
39171        if (subtitleTarget.find('.cmp-text').length > 0) {
39172          subtitleTarget.find('.cmp-text').text(subtitle);
39173        } else {
39174          subtitleTarget.text(subtitle);
39175        }
39176      } else if (subtitle == '' || subtitle == null) {
39177        $(subtitleTarget).hide();
39178      }
39179
39180      if (!Utils.isMobile() && !$('#overlay').hasClass('active') && !$('[data-js="modal-overlay"]').hasClass('active')) {
39181        OverlayService.show();
39182      } else {
39183        $('.header-label-password').add('.update-password-form-wrapper').hide();
39184      }
39185
39186      $('#overlay, [data-js="close-menu"], [data-js="alert-error-close-menu"], [data-js="modal-overlay"]').off('click').on('click', function () {
39187        if (redirectToHome) {
39188          $(location).attr('href', $('#homePagePath').val());
39189        }
39190
39191        $(alert).removeClass('active');
39192        $(alert).parent().removeClass('active');
39193        $('#wemobi-header').removeClass('opened-overlay');
39194        OverlayService.hide();
39195      });
39196    }
39197  }, {
39198    key: 'showMsgWithLink',
39199    value: function showMsgWithLink(_ref) {
39200      var show = _ref.show,
39201        title1 = _ref.title1,
39202        subtitle = _ref.subtitle,
39203        title2 = _ref.title2,
39204        linkText = _ref.linkText,
39205        urlLink = _ref.urlLink;
39206
39207      show ? $('[data-js="message-confir"]').addClass('otherMsg active') : '';
39208      show ? $('.register-wrapper').addClass('removeMargin') : '';
39209      $('[data-js="message-confirmation-box-title"]').text(title1);
39210      $('[data-js="message-confir-title"]').text(title2);
39211      $('[data-js="message-confir-subtitle"]').text(subtitle);
39212      $('[data-js="link-message-confirmation-box"]').text(linkText).attr('href', urlLink ? urlLink : '#');
39213
39214      $('[data-js="message-confir"]').addClass('active')
39215      $('[data-js="message-confir"]').parent().addClass('active');
39216      $('#wemobi-header').addClass('opened-overlay');
39217      $('#overlay, [data-js="close-menu"]').on('click', function () {
39218        $('[data-js="message-confir"]').removeClass('active');
39219        $('[data-js="link-contact-us-confirmation"]').hide();
39220        $('.container-capture').add('.register-wrapper').show();
39221        OverlayService.removeClass('active');
39222      });
39223    }
39224  }, {
39225    key: 'showMsgWithOutOverlay',
39226    value: function showMsgWithOutOverlay(title, subtitle) {
39227      $('[data-js="message-confir"]').addClass('active withoverlay');
39228      $('[data-js="alert-overlay"]').hide();
39229      $('.footer-edit-data-container').addClass('active');
39230      $('[data-js="message-confir-title"]').text(title);
39231      $('[data-js="message-confir-subtitle"]').text(subtitle);
39232    }
39233  }, {
39234    key: 'showAEMCancelTrip',
39235    value: function showAEMCancelTrip(targetAlert) {
39236      var alertDataJs = targetAlert;
39237
39238      $(".confirmation-alert-image-par").find("p").each(function (index) {
39239        if (index == 0) {
39240          $(this).html($('[data-js="msg-response-confirmation-alert"]').data('cancel-msg-confirmation-alert1'));
39241        } else if (index == 1) {
39242          $(this).html($('[data-js="msg-response-confirmation-alert"]').data('cancel-msg-confirmation-alert2'));
39243        }
39244      });
39245
39246      if ($('.message-confirmation-container').hasClass('active')) {
39247        $('.message-confirmation-container').removeClass('active');
39248        OverlayService.hide();
39249      }
39250
39251      $('[' + alertDataJs + ']').parent().addClass('active');
39252      $('[' + alertDataJs + ']').addClass('active');
39253      $('.footer-edit-data-container').addClass('active');
39254      $('#wemobi-header').addClass('opened-overlay');
39255
39256      if (!Utils.isMobile()) {
39257        OverlayService.show();
39258      } else {
39259        $('.header-label-password').add('.update-password-form-wrapper').hide();
39260      }
39261
39262      $('#overlay, [data-js="close-menu"]').off('click').on('click', function () {
39263        $('[' + alertDataJs + ']').removeClass('active');
39264        $('[' + alertDataJs + ']').parent().removeClass('active');
39265        $('#wemobi-header').removeClass('opened-overlay');
39266
39267        if (Utils.isMobile()) {
39268          $('[data-js="edit-data-container"]').removeClass('active');
39269          $('[data-js="update-password-mobile-window"]').removeClass('active');
39270          $('[data-js="btn-conf"]').parent().removeClass('active');
39271          $('[data-js="register-wrapper-container"]').removeClass('updated-successfully');
39272        }
39273
39274        OverlayService.hide();
39275      });
39276    }
39277  }, {
39278    key: 'showAEM',
39279    value: function showAEM(targetAlert, redirectToHome, showOverlay, removeCloseIcon) {
39280      var alertDataJs = targetAlert ? targetAlert : 'data-js="message-confir"';
39281
39282      if ($('.message-confirmation-container').hasClass('active')) {
39283        $('.message-confirmation-container').removeClass('active');
39284        OverlayService.hide();
39285      }
39286
39287      $('[' + alertDataJs + ']').parent().addClass('active');
39288      $('[' + alertDataJs + ']').addClass('active');
39289      $('.footer-edit-data-container').addClass('active');
39290      $('#wemobi-header').addClass('opened-overlay');
39291
39292      if (!Utils.isMobile() || showOverlay) {
39293        OverlayService.show();
39294      } else {
39295        $('.header-label-password').add('.update-password-form-wrapper').hide();
39296      }
39297
39298      $('#overlay, [data-js="close-menu"]').off('click').on('click', function () {
39299        $('[' + alertDataJs + ']').removeClass('active');
39300        $('[' + alertDataJs + ']').parent().removeClass('active');
39301        $('#wemobi-header').removeClass('opened-overlay');
39302
39303        if (Utils.isMobile()) {
39304          $('[data-js="edit-data-container"]').removeClass('active');
39305          $('[data-js="update-password-mobile-window"]').removeClass('active');
39306          $('[data-js="btn-conf"]').parent().removeClass('active');
39307          $('[data-js="register-wrapper-container"]').removeClass('updated-successfully');
39308
39309          setTimeout(function () { $('[data-js="update-password-form-wrapper"]').css('display', 'block'); }, 500);
39310        }
39311
39312        OverlayService.hide();
39313
39314        if (redirectToHome) {
39315          $(location).attr('href', $('#homePagePath').val());
39316        }
39317      });
39318      if (removeCloseIcon) {
39319        $('[data-js="close-menu"]').remove();
39320      }
39321
39322      $('[data-js="close-resend-email-ticket"]').off('click').on('click', function () {
39323        if (Utils.isMobile()) {
39324          $('[data-js="alert-email-resubmit-confirmation"]').removeClass('active');
39325          $('[data-js="alert-email-resubmit-confirmation"]').parent().removeClass('active');
39326        }
39327      });
39328    }
39329  }]);
39330
39331  return AlertConfirmation;
39332}();
39333'use strict';
39334
39335var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
39336
39337function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
39338
39339var ModalCancel = function () {
39340  function ModalCancel() {
39341    _classCallCheck(this, ModalCancel);
39342  }
39343
39344  _createClass(ModalCancel, null, [{
39345    key: 'show',
39346    value: function show() {
39347      var messageElementTitle = '[data-js="modal-container-cancel"]';
39348      var cancelTotalValue = $('[data-js="modal-cancel-total-value"]').val();
39349      var multaCancelamento = $('[data-js="modal-cancel-multa"]').val();
39350
39351      $('.total-info').on('click', function () {
39352        $(messageElementTitle).find(".modal-cancel-message-message-title p").text(cancelTotalValue);
39353        $('[data-js="modal-overlay"]').addClass('active');
39354        $('[data-js="modal-container-cancel"]').addClass('active');
39355      });
39356
39357      $('.cancellation-info').on('click', function () {
39358        $(messageElementTitle).find(".modal-cancel-message-message-title p").text(multaCancelamento);
39359        $('[data-js="modal-overlay"]').addClass('active');
39360        $('[data-js="modal-container-cancel"]').addClass('active');
39361      });
39362    }
39363  }]);
39364
39365  return ModalCancel;
39366}();
39367'use strict';
39368
39369var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
39370
39371function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
39372
39373var ModalConfirmDialog = function () {
39374  function ModalConfirmDialog() {
39375    _classCallCheck(this, ModalConfirmDialog);
39376  }
39377
39378  _createClass(ModalConfirmDialog, null, [{
39379    key: 'show',
39380    value: function show(text, departureDateTime) {
39381      var _this = this;
39382
39383      return new Promise(function (resolve, reject) {
39384        $('[data-js="message-confir"]').addClass('active');
39385        $('.footer-edit-data-container').addClass('active');
39386        $('[data-js="message-confir-subtitle"]').text('' + (text[0] + _this.getHourDerparture(departureDateTime) + text[1] + _this.getDateDerparture(departureDateTime)));
39387
39388        OverlayService.show();
39389
39390        $('[data-js="button-agree"]').on('click', function () {
39391          resolve(true);
39392        });
39393        $('[data-js="button-close"]').on('click', function () {
39394          reject(false);
39395        });
39396        $('[data-js="close-menu"]').on('click', function () {
39397          reject(false);
39398        });
39399      });
39400    }
39401  }, {
39402    key: 'hide',
39403    value: function hide() {
39404      $('[data-js="message-confir"]').removeClass('active');
39405      OverlayService.hide();
39406    }
39407  }, {
39408    key: 'getDateDerparture',
39409    value: function getDateDerparture(data) {
39410      return data.getDate() + '/' + (data.getMonth() + 1) + '/' + data.getFullYear();
39411    }
39412  }, {
39413    key: 'getHourDerparture',
39414    value: function getHourDerparture(hourMinutes) {
39415      return hourMinutes.getHours() + (hourMinutes.getMinutes() < 10 ? ':00' : '' + ':' + hourMinutes.getMinutes());
39416    }
39417  }]);
39418
39419  return ModalConfirmDialog;
39420}();
39421"use strict";
39422
39423var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
39424
39425function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
39426
39427var ModalConfirmPin = function () {
39428  function ModalConfirmPin() {
39429    _classCallCheck(this, ModalConfirmPin);
39430  }
39431
39432  _createClass(ModalConfirmPin, null, [{
39433    key: "show",
39434    value: function show() {
39435      var messageElementMessage = document.querySelector(".pin-configuration-message p");
39436      var textInput = $('[data-js="pin-configuration-message-message"]').val();
39437
39438      messageElementMessage.textContent = textInput;
39439    }
39440  }]);
39441
39442  return ModalConfirmPin;
39443}();
39444'use strict';
39445
39446var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
39447
39448function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
39449
39450var MODAL_NUPAY_CONTENT = {
39451  error: {
39452    subtitle: 'Algo deu errado com o pagamento.',
39453    body1: 'Não conseguimos processar sua transação com o <span class="modal-nupay__brand">NuPay</span>.',
39454    body2: 'Para garantir sua viagem, volte à busca e verifique se a poltrona desejada ainda está disponível.',
39455    primaryBtn: 'Utilizar busca anterior',
39456    primaryAction: 'back',
39457    secondaryBtn: 'Nova busca',
39458    secondaryAction: 'index'
39459  },
39460  cancelled: {
39461    subtitle: 'Pagamento cancelado.',
39462    body1: 'Parece que houve um cancelamento lá no app do Nubank.',
39463    body2: 'Não se preocupe, o valor não foi debitado e sua reserva ainda não foi confirmada.',
39464    primaryBtn: 'Voltar ao início',
39465    primaryAction: 'index',
39466    secondaryBtn: null
39467  },
39468  expired: {
39469    subtitle: 'O tempo de pagamento expirou.',
39470    body1: 'Não conseguimos finalizar seu pagamento a tempo.',
39471    body2: 'Reinicie a compra para verificar a disponibilidade da poltrona.',
39472    primaryBtn: 'Voltar ao início',
39473    primaryAction: 'index',
39474    secondaryBtn: null
39475  }
39476};
39477
39478var ModalNupay = function () {
39479  function ModalNupay() {
39480    _classCallCheck(this, ModalNupay);
39481  }
39482
39483  _createClass(ModalNupay, null, [{
39484    key: 'show',
39485    value: function show(type) {
39486      var content = MODAL_NUPAY_CONTENT[type];
39487      if (!content) return;
39488
39489      $('[data-js="modal-nupay-title"]').text('Ops!');
39490      $('[data-js="modal-nupay-subtitle"]').text(content.subtitle);
39491      $('[data-js="modal-nupay-body-1"]').html(content.body1);
39492      $('[data-js="modal-nupay-body-2"]').text(content.body2);
39493      $('[data-js="modal-nupay-btn-primary"]').text(content.primaryBtn);
39494
39495      var $secondary = $('[data-js="modal-nupay-btn-secondary"]');
39496      if (content.secondaryBtn) {
39497        $secondary.text(content.secondaryBtn).show();
39498      } else {
39499        $secondary.hide();
39500      }
39501
39502      OverlayService.show();
39503      $('[data-js="modal-nupay"]').addClass('active');
39504
39505      $('[data-js="modal-nupay-btn-primary"]').off('click').on('click', function () {
39506        ModalNupay.hide();
39507        if (content.primaryAction === 'back') {
39508          history.back();
39509        } else {
39510          $(location).attr('href', $('#homePagePath').val());
39511        }
39512      });
39513
39514      $('[data-js="modal-nupay-close"]').off('click').on('click', function () {
39515        ModalNupay.hide();
39516        $(location).attr('href', $('#homePagePath').val());
39517      });
39518
39519      if (content.secondaryBtn) {
39520        $secondary.off('click').on('click', function () {
39521          ModalNupay.hide();
39522          $(location).attr('href', $('#homePagePath').val());
39523        });
39524      }
39525
39526      $('#overlay').off('click').on('click', function () {
39527        ModalNupay.hide();
39528        $(location).attr('href', $('#homePagePath').val());
39529      });
39530    }
39531  }, {
39532    key: 'hide',
39533    value: function hide() {
39534      $('[data-js="modal-nupay"]').removeClass('active');
39535      OverlayService.hide();
39536    }
39537  }]);
39538
39539  return ModalNupay;
39540}();
39541"use strict";
39542
39543var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
39544
39545function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
39546
39547var ModalEditableForm = function () {
39548  function ModalEditableForm() {
39549    _classCallCheck(this, ModalEditableForm);
39550  }
39551
39552  _createClass(ModalEditableForm, null, [{
39553    key: "show",
39554    value: function show() {
39555      var messageElementTitle = document.querySelector(".modal-editable-message-message-title h1");
39556      var messageElementMessage = document.querySelector(".modal-editable-message-message-text p");
39557      var titleInput = $('[data-js="modal-editable-message-title"]').val();
39558      var textInput = $('[data-js="modal-editable-message-message"]').val();
39559
39560      messageElementTitle.textContent = titleInput;
39561      messageElementMessage.textContent = textInput;
39562    }
39563  }]);
39564
39565  return ModalEditableForm;
39566}();
39567'use strict';
39568
39569var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
39570
39571function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
39572
39573var ModalStateRefund = function () {
39574  function ModalStateRefund() {
39575    _classCallCheck(this, ModalStateRefund);
39576  }
39577
39578  _createClass(ModalStateRefund, null, [{
39579    key: 'displayRefundModal',
39580    value: function displayRefundModal(state, modalData, modalWallet) {
39581      var modalSelector = '[data-js="refund-message-confir"]';
39582      this.updateModalState(state);
39583      $(modalSelector).addClass('active');
39584      if (modalWallet == 'wallet') {
39585        $('[data-js="session-overlay-container"]').first().show();
39586      } else {
39587        $('[data-js="session-overlay-container"]').show();
39588      }
39589
39590      $('#overlay, [data-js="close-menu"]').off('click').on('click', function () {
39591        $(modalSelector).removeClass('active');
39592        $('[data-js="session-overlay-container"]').hide();
39593      });
39594
39595      if (modalData) {
39596        $(modalSelector).find('[data-js="refund-message-title"]').text(modalData.title);
39597        $(modalSelector).find('[data-js="refund-message-subtitle"]').text(modalData.subtitle);
39598
39599        if (modalData.showLink) {
39600          $(modalSelector).find('.refund-content-message-box').addClass('d-flex');
39601          $(modalSelector).find('[data-js="link-refund-message-box"]').text(modalData.linkText).attr('href', modalData.linkRedirect || '#');
39602          if (!modalData.linkRedirect) {
39603            $(modalSelector).find('[data-js="link-refund-message-box"]').on('click', function () {
39604              $(modalSelector).removeClass('active');
39605              $('[data-js="session-overlay-container"]').hide();
39606            });
39607          }
39608        } else {
39609          $(modalSelector).find('[data-js="link-refund-message-box"]').hide();
39610        }
39611
39612        var btnStateBack = $(modalSelector).find('[data-js="btn-state-back"]');
39613
39614        btnStateBack.off('click').on('click', function () {
39615          if (modalData.linkBackBtn) {
39616            window.location.href = modalData.linkBackBtn;
39617          } else {
39618            $('[data-js="session-overlay-container"]').hide();
39619          }
39620        });
39621      }
39622    }
39623  }, {
39624    key: 'updateModalState',
39625    value: function updateModalState(state) {
39626      var modal = $('.refund-modal-container');
39627      modal.removeClass('processing success error').addClass(state);
39628      var closeMenuElement = $('[data-js="close-menu"]');
39629
39630      var refundButton = modal.find('.refund-btn-action');
39631      var loadingIcon = refundButton.find('.jca-ico-loading');
39632      var buttonText = refundButton.find('.button-text');
39633      var btnStateNext = modal.find('[data-js="btn-state-next"]');
39634
39635      loadingIcon.removeClass('icon-processing icon-success icon-error');
39636      refundButton.removeClass('btn-error btn-success');
39637
39638      switch (state) {
39639        case 'processing':
39640          refundButton.contents().filter(function () {
39641            return this.nodeType === 3;
39642          }).remove();
39643          buttonText.hide();
39644          btnStateNext.removeClass('d-none');
39645          break;
39646        case 'success':
39647          btnStateNext.addClass('d-none');
39648          closeMenuElement.off('click').on('click', function () {
39649            $(location).attr("href", i18n('payment_link_redirect'));
39650          });
39651          break;
39652        case 'error':
39653          buttonText.show();
39654          loadingIcon.hide();
39655          modal.find('[data-js="refund-message-title"]').text('Falha no pagamento');
39656          modal.find('[data-js="refund-message-subtitle"]').text('Informação da falha do pagamento');
39657          buttonText.text('Tentar novamente');
39658          refundButton.addClass('btn-error');
39659          btnStateNext.removeClass('d-none');
39660          btnStateNext.off('click').on('click', function () {
39661            $('[data-js="session-overlay-container"]').hide();
39662          });
39663          break;
39664      }
39665    }
39666  }]);
39667
39668  return ModalStateRefund;
39669}();
39670'use strict';
39671
39672var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
39673
39674function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
39675
39676var SearchModalController = function () {
39677  function SearchModalController() {
39678    _classCallCheck(this, SearchModalController);
39679
39680    this.btnSearchSearchModal = $('[data-js="btn-search-search-modal"]');
39681    this.searchSearchInputModal = $('[data-js="input-search-search-modal"]');
39682
39683    // Components to style in pagination component
39684    this.colorsToBtnSearch = $('[data-js="btn-search-search-color"]');
39685    this.init();
39686  }
39687
39688  _createClass(SearchModalController, [{
39689    key: 'init',
39690    value: function init() {
39691      this.listenEvents();
39692      this.handleSubmit();
39693      this.initStyle();
39694    }
39695  }, {
39696    key: 'initStyle',
39697    value: function initStyle() {
39698      this.btnSearchSearchModal.css({
39699        'background-color': this.colorsToBtnSearch.attr('data-background'),
39700        'color': this.colorsToBtnSearch.attr('data-color')
39701      });
39702    }
39703  }, {
39704    key: 'listenEvents',
39705    value: function listenEvents() {
39706      var _this = this;
39707
39708      this.searchSearchInputModal.on('keyup', function (e) {
39709        var wordLength = $(e.target).val().length;
39710
39711        if (wordLength > 3) {
39712          _this.btnSearchSearchModal.prop('disabled', false).addClass('active');
39713        } else {
39714          _this.btnSearchSearchModal.prop('disabled', true).removeClass('active');
39715        }
39716      });
39717    }
39718  }, {
39719    key: 'handleSubmit',
39720    value: function handleSubmit() {
39721      var _this2 = this;
39722
39723      this.btnSearchSearchModal.on('click', function (e) {
39724        e.preventDefault();
39725        var wordSearched = _this2.searchSearchInputModal.val();
39726        var searchPage = $('[data-js="search-page-path"]').val();
39727        LoaderService.show();
39728        if (searchPage) {
39729          $(location).attr('href', searchPage + '?q=' + wordSearched + '');
39730        } else {
39731          console.log('The path to the search page was not provided.');
39732        }
39733      });
39734    }
39735  }]);
39736
39737  return SearchModalController;
39738}();
39739'use strict';
39740
39741var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
39742
39743function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
39744
39745var Modal = function () {
39746  function Modal($) {
39747    var $link = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
39748
39749    _classCallCheck(this, Modal);
39750
39751    var value = $('[modal-js="modal"]').attr('data-js');
39752    this.modalLink = $link ? $link : $('[data-to-modal="modal-link"]');
39753    this.modalElemt = $('[data-js="' + value + '"]');
39754    this.overlay = $('[data-js="modal-overlay"]');
39755    this.btnCloseOverlay = $('[data-js="modal-close"]');
39756    this.modalContent = $('[data-js="modal-content"]');
39757    this.init();
39758  }
39759
39760  _createClass(Modal, [{
39761    key: 'init',
39762    value: function init() {
39763      this.listenModal();
39764      this.renderModalHeight();
39765    }
39766  }, {
39767    key: 'listenModal',
39768    value: function listenModal() {
39769      var _this = this;
39770
39771      this.modalLink.on('click', function (e) {
39772        var modalName = $(e.target).parent().parent().attr('data-js') ? $(e.target).parent().parent().attr('data-js') : $(e.currentTarget).attr('data-js');
39773        if ($(e.target).hasClass('search-result-offer')) modalName = $(e.target).attr('data-js');
39774        if ($(e.target).hasClass('remove-credit-card-from-stored')) modalName = $(e.target).attr('data-js');
39775        if ($(e.target).hasClass('itinerary-link')) modalName = $(e.target).attr('data-js');
39776        if ($(e.target).hasClass('link-request-data-user')) modalName = $(e.target).attr('data-js');
39777        if ($(e.target).hasClass('jca-ico-search')) modalName = $(e.target).attr('data-js');
39778        if ($(e.target).attr('data-js') && $(e.target).attr('data-js') == 'details-modal-target') modalName = $(e.target).attr('data-js');
39779
39780        if (!modalName && ($(e.target).attr('href') || $(e.target).parent().attr('href'))) {
39781          modalName = $(e.target).attr('href') ? $(e.target).attr('href').replace('#', '') : $(e.target).attr('href');
39782          if (modalName == undefined) {
39783            modalName = $(e.target).parent().attr('href') ? $(e.target).parent().attr('href').replace('#', '') : $(e.target).parent().attr('href');
39784          }
39785          if ($('.modal-content[data-js="' + modalName + '"]').length == 0) return;
39786        }
39787        if (!modalName) return;
39788        var scrollBar = $(window).scrollTop();
39789        $('#wemobi-header').css('z-index', '10');
39790        $('.modal-content[data-js="' + modalName + '"]').css('max-height', $('.modal-content[data-js="' + modalName + '"]').attr('modal-height'));
39791        $('.modal-content[data-js="' + modalName + '"]').addClass('active');
39792        $('body, html').animate({ scrollTop: scrollBar }, 'slow');
39793
39794        _this.showOverlay(modalName);
39795        _this.listenResize();
39796      });
39797
39798      this.btnCloseOverlay.add(this.overlay).on('click', function (e) {
39799        var modalName = $(e.target).closest('.modal-content').attr('data-js');
39800        _this.closeOverlay(modalName);
39801        _this.handleVideoInModal(e);
39802        $('#wemobi-header').removeClass('opened-overlay');
39803      });
39804
39805      $('body, html').on('click', function (e) {
39806        var clickInElement = e.target.closest('.modal-content') || ($(e.target).parent().parent().attr('data-to-modal') == 'modal-link') ||
39807          ($(e.target).parent().parent().parent().attr('data-to-modal') == 'modal-link') || ($(e.target).attr('data-to-modal') == 'modal-link') ? true : false;
39808        if (!clickInElement) {
39809          _this.closeOverlay();
39810          return;
39811        }
39812      });
39813    }
39814  }, {
39815    key: 'handleVideoInModal',
39816    value: function handleVideoInModal(e) {
39817      var isVideoInModal = $(e.target).closest('.modal-content').find('.video-container');
39818      var $video = $(".video-container iframe");
39819
39820      if (!isVideoInModal) return;
39821
39822      var stopVideo = function stopVideo() {
39823        var srcVideo = $video.attr("src");
39824
39825        $video.attr("src", '');
39826        $video.attr("src", srcVideo);
39827      };
39828
39829      stopVideo();
39830    }
39831  }, {
39832    key: 'renderModalHeight',
39833    value: function renderModalHeight() {
39834      var heightContent = this.modalContent.attr('data-content-height');
39835
39836      this.modalContent.css('min-height', heightContent);
39837    }
39838  }, {
39839    key: 'showOverlay',
39840    value: function showOverlay(modalName) {
39841      var overlayElement = $('.modal-content[data-js="' + modalName + '"]').parent().next();
39842      if (!$(overlayElement).hasClass('modal-overlay')) overlayElement = $('[data-js="modal-overlay"]').first();
39843      var isOverlay = $(overlayElement).attr('overlay') == 'true';
39844
39845      if (!isOverlay) {
39846        $('.modal-content').addClass('active-box-shadow');
39847        $('.modal-header').addClass('active');
39848        $('.modal-main').addClass('active');
39849        return;
39850      }
39851
39852      $('#wemobi-header').addClass('opened-overlay');
39853      this.overlay.addClass('active');
39854    }
39855  }, {
39856    key: 'closeOverlay',
39857    value: function closeOverlay(modalName) {
39858      if ($('.modal-content[data-js="' + modalName + '"]').css('display') == 'block') $('.modal-content[data-js="' + modalName + '"]').css('display', '');
39859      if ($('.modal-content.active').css('display') == 'block') $('.modal-content').css('display', '');
39860      $('.modal-content[data-js="' + modalName + '"]').removeClass('active');
39861      $('.modal-content').removeClass('active');
39862      this.overlay.removeClass('active');
39863      $('body, html').css('overflow-y', 'auto');
39864    }
39865  }, {
39866    key: 'listenResize',
39867    value: function listenResize() {
39868      if (Utils.isMobile()) {
39869        $('body, html').css('overflow-y', 'hidden');
39870      }
39871    }
39872  }]);
39873
39874  return Modal;
39875}();
39876'use strict';
39877
39878var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
39879
39880function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
39881
39882var NewRouteFormController = function () {
39883  function NewRouteFormController() {
39884    _classCallCheck(this, NewRouteFormController);
39885
39886    this.form = $('[data-js="new-route-form"]');
39887    this.clientName = $('[data-js="input-client-name"]');
39888    this.newOrigin = $('[data-js="input-new-origin"]');
39889    this.newDestination = $('[data-js="input-new-destination"]');
39890    this.clientEmail = $('[data-js="input-client-email"]');
39891    this.btnSend = $('[data-js="button-send"]');
39892    this.init();
39893  }
39894
39895  _createClass(NewRouteFormController, [{
39896    key: 'init',
39897    value: function init() {
39898      this.handleSubmit();
39899      this.handleForm();
39900    }
39901  }, {
39902    key: 'handleForm',
39903    value: function handleForm() {
39904      var _this = this;
39905
39906      this.form.find('input[required]').keyup(function (e) {
39907        if ($(e.target).hasClass('invalid')) {
39908          $(e.target).removeClass('invalid');
39909        }
39910      });
39911
39912      $('#new-route-modal').on('hidden.bs.modal', function () {
39913        _this.form.find('input[required]').each(function (_, el) {
39914          return $(el).removeClass("invalid");
39915        }).trigger("reset");
39916        $('[data-js="error-msg"]').fadeOut();
39917      });
39918    }
39919  }, {
39920    key: 'handleSubmit',
39921    value: function handleSubmit() {
39922      var _this2 = this;
39923
39924      this.btnSend.click(function () {
39925        if (_this2.isFormValid()) {
39926          $('[data-js="error-msg"]').fadeOut();
39927
39928          var modalEl = document.getElementById('new-route-modal');
39929          var modalInstance = bootstrap.Modal.getInstance(modalEl);
39930          modalInstance.hide();
39931
39932          _this2.submitProtocol();
39933        } else {
39934          _this2.checkInputFields();
39935        }
39936      });
39937    }
39938  }, {
39939    key: 'submitProtocol',
39940    value: function submitProtocol() {
39941      var _this3 = this;
39942
39943      var parameters = {
39944        'encoding': 'UTF-8',
39945        'orgid': '00D1N000002dlIo',
39946        'recordType': '0121N000001DlZt',
39947        'Origin': 'Web',
39948        'Status': 'New',
39949        '00N1N00000FAEW3': 'Novo',
39950        '00N1N00000FAAqo': 'Não',
39951        'name': this.clientName.val(),
39952        'email': this.clientEmail.val(),
39953        'type': $('[data-js="new-route-request-type"]').val(),
39954        'description': 'Origem: ' + this.newOrigin.val() + '; Destino: ' + this.newDestination.val(),
39955        '00N1N00000P8jjs': Utils.getSiteName()
39956      };
39957
39958      LoaderService.show();
39959      HttpService.post('openProtocol', parameters).then(function (data) {
39960        LoaderService.hide();
39961        Utils.scrollTop();
39962        if (data.success) {
39963          AlertConfirmation.show('', i18n('protocol_success'), true, false);
39964        } else {
39965          AlertConfirmation.show('', i18n('protocol_error'), true, false);
39966        }
39967        _this3.form.trigger("reset");
39968      }).catch(function () {
39969        LoaderService.hide();
39970        AlertConfirmation.show('', i18n('protocol_error'), true, false);
39971      });
39972    }
39973  }, {
39974    key: 'checkInputFields',
39975    value: function checkInputFields() {
39976      var allFieldsValid = true;
39977
39978      this.form.find('input[required]').each(function (_, el) {
39979        var value = $(el).val();
39980        if (value.length < +$(el).attr('minLength')) {
39981          $(el).addClass("invalid");
39982          allFieldsValid = false;
39983        } else {
39984          $(el).removeClass("invalid");
39985        }
39986      });
39987
39988      if (!allFieldsValid) $('[data-js="error-msg"]').fadeIn();
39989
39990      return allFieldsValid;
39991    }
39992  }, {
39993    key: 'isFormValid',
39994    value: function isFormValid() {
39995      return $('[data-js="new-route-form"]')[0].checkValidity();
39996    }
39997  }]);
39998
39999  return NewRouteFormController;
40000}();
40001'use strict';
40002
40003var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
40004
40005function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
40006
40007/**
40008 * INÍCIO LÓGICA ORDER BY COMPONENT
40009 */
40010var OrderByComponent = function () {
40011  function OrderByComponent($, listResultRef) {
40012    _classCallCheck(this, OrderByComponent);
40013
40014    this.listResultRef = listResultRef;
40015    this.orderBy = new OrderBy(listResultRef);
40016    this.buttonOrderBy = $('[data-js="button-order-by"]');
40017    this.orderByList = $('[data-js="order-by-list"]');
40018    this.breadcrumb = $('[data-js="breadcrumb"]');
40019    this.departureDateAsc = $('[data-js="departureDateAsc"]');
40020    this.departureDateDesc = $('[data-js="departureDateDesc"]');
40021    this.durationAsc = $('[data-js="durationAsc"]');
40022    this.durationDesc = $('[data-js="durationDesc"]');
40023    this.priceAsc = $('[data-js="priceAsc"]');
40024    this.priceDesc = $('[data-js="priceDesc"]');
40025    this.favPurchaseAsc = $('[data-js="favPurchaseAsc"]');
40026    this.headerSite = $('.header-site');
40027    this.defaultOrder = $('[data-js="order-by-default-select"]').val();
40028    this.currentResult = SessionStorage.get('currentResultDep');
40029    this.init();
40030  }
40031
40032  _createClass(OrderByComponent, [{
40033    key: 'setListToOrder',
40034    value: function setListToOrder(list) {
40035      this.orderBy.listToOrder = list;
40036    }
40037  }, {
40038    key: 'changeWay',
40039    value: function changeWay() {
40040      this.orderByList.find('button').each(function (index) {
40041        var ariaLabel = "";
40042        if (index = 0) {
40043          ariaLabel = $('[data-js="translationreturnearliestfirst"]').val();
40044        } else if (index = 1) {
40045          ariaLabel = $('[data-js="translationreturnlaterfirst"]').val();
40046        } else if (index = 2) {
40047          ariaLabel = $('[data-js="translationreturnmorecheaper"]').val();
40048        } else {
40049          ariaLabel = $('[data-js="translationreturnmoreexpensive"]').val();
40050        }
40051        $(this).attr('aria-label', ariaLabel);
40052      });
40053    }
40054  }, {
40055    key: 'init',
40056    value: function init() {
40057      var self = this;
40058
40059      this.departureDateAsc.click({
40060        "orderByList": self.orderByList,
40061        "orderBy": self.orderBy,
40062        "listResultRef": self.listResultRef,
40063        "sortFunctionName": 'departureDateAsc'
40064      }, self.orderByAction);
40065
40066      this.departureDateDesc.click({
40067        "orderByList": self.orderByList,
40068        "orderBy": self.orderBy,
40069        "listResultRef": self.listResultRef,
40070        "sortFunctionName": 'departureDateDesc'
40071      }, self.orderByAction);
40072
40073      this.durationAsc.click({
40074        "orderByList": self.orderByList,
40075        "orderBy": self.orderBy,
40076        "listResultRef": self.listResultRef,
40077        "sortFunctionName": 'durationAsc'
40078      }, self.orderByAction);
40079
40080      this.durationDesc.click({
40081        "orderByList": self.orderByList,
40082        "orderBy": self.orderBy,
40083        "listResultRef": self.listResultRef,
40084        "sortFunctionName": 'durationDesc'
40085      }, self.orderByAction);
40086
40087      this.priceAsc.click({
40088        "orderByList": self.orderByList,
40089        "orderBy": self.orderBy,
40090        "listResultRef": self.listResultRef,
40091        "sortFunctionName": 'priceAsc'
40092      }, self.orderByAction);
40093
40094      this.priceDesc.click({
40095        "orderByList": self.orderByList,
40096        "orderBy": self.orderBy,
40097        "listResultRef": self.listResultRef,
40098        "sortFunctionName": 'priceDesc'
40099      }, self.orderByAction);
40100
40101      this.favPurchaseAsc.click({
40102        "orderByList": self.orderByList,
40103        "orderBy": self.orderBy,
40104        "listResultRef": self.listResultRef,
40105        "sortFunctionName": 'favPurchaseAsc'
40106      }, self.orderByAction);
40107
40108      var _Utils$getWindowSize = Utils.getWindowSize(),
40109        width = _Utils$getWindowSize.width,
40110        breakpoints = _Utils$getWindowSize.breakpoints;
40111
40112      this.buttonOrderBy.off('click').on('click', function (e) {
40113        if ($('#wemobi-header').hasClass('opened-overlay')) {
40114          $('#wemobi-header').removeClass('opened-overlay')
40115        } else {
40116          $('#wemobi-header').addClass('opened-overlay');
40117        }
40118
40119        if (width >= breakpoints.LG) {
40120          $('[data-js="order-by-window"]').fadeToggle('fast');
40121        } else {
40122          $('[data-js="order-by-window"]').toggleClass('active');
40123        }
40124
40125        $('[data-js="button-order-by"]').find('.arrow-icon').toggleClass('opened');
40126      });
40127      this.setDefaultOrder(this.defaultOrder, self.listResultRef);
40128    }
40129  }, {
40130    key: 'resetOrderBy',
40131    value: function resetOrderBy() {
40132      this.orderByList.children().removeClass('active');
40133      this.orderByList.find('button').removeClass('active');
40134      this.orderByList.find('[data-js="departureDateAsc"]').toggleClass('active');
40135    }
40136  }, {
40137    key: 'maintainOrdering',
40138    value: function maintainOrdering() {
40139      var self = this;
40140
40141      this.setDefaultOrder(this.defaultOrder, self.listResultRef);
40142    }
40143  }, {
40144    key: 'orderByAction',
40145    value: function orderByAction(event) {
40146
40147      if ($(event.target).hasClass('multiple-radios-text')) return;
40148
40149      var selectedItem = $(event.currentTarget).attr('data-js');
40150      var sortFunctionName = event.data.sortFunctionName;
40151      var orderByList = event.data.orderByList;
40152      var orderBy = event.data.orderBy;
40153      var listResultRef = event.data.listResultRef;
40154
40155      if (sortFunctionName != "favPurchaseAsc") {
40156        orderByList.children().removeClass('active');
40157        orderByList.children().find('input').attr('checked', false);
40158        $('[data-js="' + selectedItem + '"]').find('input').attr('checked', true);
40159        $('[data-js="' + selectedItem + '"]').addClass('active');
40160      }
40161
40162      orderBy.sortBy(listResultRef.listRaces, sortFunctionName);
40163      listResultRef.updateListResultView();
40164      listResultRef.setupInfiniteScroll();
40165
40166      //Applying filter
40167      LoaderService.show();
40168      $('body').css('position', 'relative');
40169      setTimeout(function () {
40170        return LoaderService.hide();
40171      }, 300);
40172
40173      var _Utils$getWindowSize = Utils.getWindowSize(),
40174        width = _Utils$getWindowSize.width,
40175        breakpoints = _Utils$getWindowSize.breakpoints;
40176
40177      if (width >= breakpoints.LG) {
40178        $('[data-js="order-by-window"]').fadeToggle('fast');
40179      } else {
40180        $('[data-js="order-by-window"]').toggleClass('active');
40181      }
40182    }
40183  }, {
40184    key: 'setDefaultOrder',
40185    value: function setDefaultOrder(order, listResults) {
40186      var _this = this;
40187
40188      window.addEventListener("getListResults", function () {
40189        LoaderService.show();
40190        $('[data-js="departureDateAsc"]').removeClass('active');
40191        _this.orderByList.children().removeClass('active');
40192
40193        _this.orderByList.children().find('input').attr('checked', false);
40194        $('[data-js="' + order + '"]').find('input').attr('checked', true);
40195        $('[data-js="' + order + '"]').addClass('active');
40196
40197        listResults.isReadyToRender = false;
40198        _this.orderBy.sortBy(listResults.listRaces, order);
40199        listResults.isReadyToRender = true;
40200        listResults.updateListResultView();
40201
40202        $('body').css('position', 'relative');
40203        setTimeout(function () {
40204          return LoaderService.hide();
40205        }, 300);
40206      });
40207    }
40208  }]);
40209
40210  return OrderByComponent;
40211}();
40212
40213/**
40214 * FIM LÓGICA ORDER BY COMPONENT
40215 */
40216
40217'use strict';
40218
40219var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
40220
40221function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
40222
40223/**
40224 * INÍCIO LÓGICA ORDER BY
40225 */
40226var OrderBy = function () {
40227  function OrderBy(listResultRef) {
40228    _classCallCheck(this, OrderBy);
40229
40230    this.listResultRef = listResultRef;
40231  }
40232
40233  _createClass(OrderBy, [{
40234    key: 'sortByDepartureDateAsc',
40235    value: function sortByDepartureDateAsc(a, b) {
40236      var formattedDateA = DateFormatter.getValidDateFormat(a.departureDate);
40237      var formattedDateB = DateFormatter.getValidDateFormat(b.departureDate);
40238      return formattedDateA - formattedDateB;
40239    }
40240  }, {
40241    key: 'sortByDepartureDateDesc',
40242    value: function sortByDepartureDateDesc(a, b) {
40243      var formattedDateA = DateFormatter.getValidDateFormat(a.departureDate);
40244      var formattedDateB = DateFormatter.getValidDateFormat(b.departureDate);
40245      return formattedDateB - formattedDateA;
40246    }
40247  }, {
40248    key: 'sortByDurationAsc',
40249    value: function sortByDurationAsc(a, b) {
40250      var durationA = DateFormatter.getDurationInteger(a.departureDate, a.arrivingDate);
40251      var durationB = DateFormatter.getDurationInteger(b.departureDate, b.arrivingDate);
40252      return durationA - durationB;
40253    }
40254  }, {
40255    key: 'sortByDurationDesc',
40256    value: function sortByDurationDesc(a, b) {
40257      var durationA = DateFormatter.getDurationInteger(a.departureDate, a.arrivingDate);
40258      var durationB = DateFormatter.getDurationInteger(b.departureDate, b.arrivingDate);
40259      return durationB - durationA;
40260    }
40261  }, {
40262    key: 'sortOffersAsc',
40263    value: function sortOffersAsc(company) {
40264      if (company instanceof Company) {
40265        company.listOffer.sort(function (a, b) {
40266          return a.price - b.price;
40267        });
40268      }
40269      return 0;
40270    }
40271  }, {
40272    key: 'sortByPriceAsc',
40273    value: function sortByPriceAsc(a, b) {
40274      var sortOffersAsc = function sortOffersAsc(company) {
40275        if (company instanceof Company) {
40276          company.listOffer.sort(function (a, b) {
40277            return a.price - b.price;
40278          });
40279        }
40280        return 0;
40281      };
40282      sortOffersAsc(a);
40283      sortOffersAsc(b);
40284      return a.listOffer[0].price - b.listOffer[0].price;
40285    }
40286  }, {
40287    key: 'sortByPriceDesc',
40288    value: function sortByPriceDesc(a, b) {
40289      var sortOffersDesc = function sortOffersDesc(company) {
40290        if (company instanceof Company) {
40291          company.listOffer.sort(function (a, b) {
40292            return b.price - a.price;
40293          });
40294        }
40295        return 0;
40296      };
40297      sortOffersDesc(b);
40298      sortOffersDesc(a);
40299      return b.listOffer[0].price - a.listOffer[0].price;
40300    }
40301  }, {
40302    key: 'sortByFavPurchases',
40303    value: function sortByFavPurchases(listRaces) {
40304      // Cookies Favorite Purchases
40305      var favPurchasesRaces = this.requestCookiesFavPurchases();
40306      if (favPurchasesRaces.length > 0) {
40307        //reset
40308        var orderRedRaces = listRaces.sort(this.sortByDepartureDateAsc);
40309        //sort
40310        var favPurchasesRacesInverse = favPurchasesRaces.sort(function (a, b) {
40311          return parseInt(a.occurrences) - parseInt(b.occurrences);
40312        });
40313
40314        var _iteratorNormalCompletion = true;
40315        var _didIteratorError = false;
40316        var _iteratorError = undefined;
40317
40318        try {
40319          var _loop = function _loop() {
40320            var fav = _step.value;
40321
40322            //find item index
40323            itemIndex = orderRedRaces.findIndex(function (item) {
40324              return item.departureDate == fav.date;
40325            });
40326            // move item to first position
40327
40328            if (itemIndex > -1) {
40329              orderRedRaces[itemIndex].favPurchase = true;
40330              orderRedRaces.splice(0, 0, orderRedRaces.splice(itemIndex, 1)[0]);
40331            }
40332          };
40333
40334          for (var _iterator = favPurchasesRacesInverse[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
40335            var itemIndex;
40336
40337            _loop();
40338          }
40339        } catch (err) {
40340          _didIteratorError = true;
40341          _iteratorError = err;
40342        } finally {
40343          try {
40344            if (!_iteratorNormalCompletion && _iterator.return) {
40345              _iterator.return();
40346            }
40347          } finally {
40348            if (_didIteratorError) {
40349              throw _iteratorError;
40350            }
40351          }
40352        }
40353
40354        return orderRedRaces;
40355      } else {
40356        return listRaces;
40357      }
40358    }
40359  }, {
40360    key: 'sortBy',
40361    value: function sortBy(list, key) {
40362      switch (key) {
40363        case 'departureDateAsc':
40364          list.sort(this.sortByDepartureDateAsc);
40365          break;
40366        case 'departureDateDesc':
40367          list.sort(this.sortByDepartureDateDesc);
40368          break;
40369        case 'durationAsc':
40370          list.sort(this.sortByDurationAsc);
40371          break;
40372        case 'durationDesc':
40373          list.sort(this.sortByDurationDesc);
40374          break;
40375        case 'priceAsc':
40376          list.sort(this.sortByPriceAsc);
40377          break;
40378        case 'priceDesc':
40379          list.sort(this.sortByPriceDesc);
40380          break;
40381        case 'favPurchaseAsc':
40382          this.sortByFavPurchases(list);
40383          break;
40384      }
40385    }
40386  }, {
40387    key: 'requestCookiesFavPurchases',
40388    value: function requestCookiesFavPurchases() {
40389      var favPurchases = [];
40390      var cookieName = 'fav_purchases';
40391      var formData = SessionStorage.get('formData');
40392
40393      var cookieArr = Utils.decodeCookie(cookieName) != null ? Utils.decodeCookie(cookieName) : [];
40394
40395      var _iteratorNormalCompletion2 = true;
40396      var _didIteratorError2 = false;
40397      var _iteratorError2 = undefined;
40398
40399      try {
40400        for (var _iterator2 = cookieArr[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
40401          var item = _step2.value;
40402
40403          var isReturn = this.listResultRef.isReturn();
40404          if (isReturn) {
40405            if (formData.return.origin.id == item.origin.id && formData.return.destination.id == item.destination.id) {
40406              var parsedItem = this.parseFavItem(item, formData.return.date);
40407              favPurchases.push(parsedItem);
40408            }
40409          } else {
40410            if (formData.depart.origin.id == item.origin.id && formData.depart.destination.id == item.destination.id) {
40411              var _parsedItem = this.parseFavItem(item, formData.depart.date);
40412              favPurchases.push(_parsedItem);
40413            }
40414          }
40415        }
40416      } catch (err) {
40417        _didIteratorError2 = true;
40418        _iteratorError2 = err;
40419      } finally {
40420        try {
40421          if (!_iteratorNormalCompletion2 && _iterator2.return) {
40422            _iterator2.return();
40423          }
40424        } finally {
40425          if (_didIteratorError2) {
40426            throw _iteratorError2;
40427          }
40428        }
40429      }
40430
40431      return favPurchases;
40432    }
40433  }, {
40434    key: 'parseFavItem',
40435    value: function parseFavItem(item, date) {
40436      item.date = date + ' ' + item.hour;
40437      item.favPurchase = true;
40438      return item;
40439    }
40440  }]);
40441
40442  return OrderBy;
40443}();
40444
40445/**
40446 * FIM LÓGICA ORDER BY
40447 */
40448'use strict';
40449
40450var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
40451
40452function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
40453
40454var UpdatePasswordLink = function () {
40455  function UpdatePasswordLink($) {
40456    _classCallCheck(this, UpdatePasswordLink);
40457
40458    this.newPassword = $('[data-js="input-new-password"]');
40459    this.confirmPassword = $('[data-js="input-confirm-password"]');
40460    this.buttonSumitPassword = $('[data-js="button-save-password"]');
40461    this.errorMessage = $('[data-js="error-message"]');
40462    this.formPassword = $('[data-js="password-form"]');
40463    this.greetingsText = $('[data-js="greetings"]');
40464    this.iconPassword = $('[data-js="show-update-password"]');
40465    this.passenger = SessionStorage.get('passenger');
40466    this.init();
40467  }
40468
40469  _createClass(UpdatePasswordLink, [{
40470    key: 'init',
40471    value: function init() {
40472      this.loadUserData();
40473      this.listenForm();
40474      this.handleFormUpdatePassword();
40475    }
40476  }, {
40477    key: 'loadUserData',
40478    value: function loadUserData() {
40479      //If the page is in edit mode, no action will be taken.
40480      if ($('#wcmmodeedit').val() === 'true') return;
40481
40482      if (!this.passenger) {
40483        $(location).attr('href', $('#loginPage').val());
40484      } else {
40485        var blankText = this.greetingsText.text();
40486        var name = this.passenger._name.trim();
40487        this.greetingsText.text(blankText.replace('#user', Utils.getFirstName(name)));
40488      }
40489    }
40490  }, {
40491    key: 'isPasswordValid',
40492    value: function isPasswordValid() {
40493      var password = this.newPassword.val();
40494      var confPassword = this.confirmPassword.val();
40495      var $tipPassword = this.newPassword.parent().siblings().find('.tip');
40496      var $tipConfPassword = this.confirmPassword.parent().siblings().find('.tip');
40497      var tipMsg = $('[data-js="error-password-alphanumeric"]').val() ? $('[data-js="error-password-alphanumeric"]').val() : i18n('password_alphanumeric_error');
40498
40499      if (password.length > 0) {
40500        if (this.checkPasswordAlphanumeric()) {
40501          if (!(password === confPassword) && confPassword.length > 0) {
40502            this.addInvalidClass(this.newPassword);
40503
40504            if (password.length < 8) {
40505              this.addInvalidClass(this.newPassword, tipMsg, $tipPassword);
40506            } else {
40507              var tipMsgNoMatch = $('[data-js="error-msg-pass-does-not-match"]').val() ? $('[data-js="error-msg-pass-does-not-match"]').val() : i18n('password_no_confirm');
40508              this.addInvalidClass(this.confirmPassword, tipMsgNoMatch, $tipConfPassword);
40509            }
40510            this.disableButtonSubmit();
40511
40512            return false;
40513          } else if (password.length >= 8 && password.length <= 12) {
40514            this.removeInvalidClass(this.newPassword, $tipPassword);
40515            this.removeInvalidClass(this.newPassword);
40516            if (password === confPassword) {
40517              this.removeInvalidClass(this.confirmPassword, $tipConfPassword);
40518              this.enableButtonSubmit();
40519              return true;
40520            }
40521
40522            return false;
40523          } else if (password.length < 8) {
40524            this.addInvalidClass(this.newPassword, tipMsg, $tipPassword);
40525            this.disableButtonSubmit();
40526
40527            return false;
40528          }
40529        } else {
40530          this.addInvalidClass(this.newPassword, tipMsg, $tipPassword);
40531          this.disableButtonSubmit();
40532          return false;
40533        }
40534      }
40535    }
40536  }, {
40537    key: 'checkPasswordAlphanumeric',
40538    value: function checkPasswordAlphanumeric() {
40539      var passwordFormatRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9@$!%*#?&]{8,}$/;
40540
40541      return passwordFormatRegex.test(this.newPassword.val());
40542    }
40543  }, {
40544    key: 'listenForm',
40545    value: function listenForm() {
40546      var _this = this;
40547
40548      this.formPassword.find('input[required]').keyup(function () {
40549        _this.handleFormUpdatePassword();
40550      });
40551
40552      this.iconPassword.on('click', function (e) {
40553        $(e.target).toggleClass('active');
40554        $(e.target).hasClass('active') ? $(e.target).prev().attr('type', 'text') : $(e.target).prev().attr('type', 'password');
40555      });
40556
40557      $('[data-js="close-menu"]').on('click', function () {
40558        $('.header-update-password, .update-password-form-wrapper').show();
40559      });
40560      var dataArray = ['[data-js=input-new-password], [data-js=input-confirm-password]'];
40561      !Utils.quotesBlock(dataArray);
40562    }
40563  }, {
40564    key: 'submitUpdatePassword',
40565    value: function submitUpdatePassword() {
40566      var _this2 = this;
40567
40568      var body = {
40569        "login": this.passenger._login,
40570        "newpassword": this.confirmPassword.val()
40571      };
40572
40573      var headers = {
40574        'Authorization': '' + SessionStorage.get('jca_token'),
40575        'channel': Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform)
40576      };
40577
40578
40579      _this2.disableButtonSubmit();
40580      LoaderService.show();
40581      HttpService.put('changePasswordLink', body, headers).then(function () {
40582        LoaderService.hide();
40583        AlertConfirmation.showAEM('data-js="alert-password-changed"');
40584        _this2.formPassword.trigger("reset");
40585      }).catch(function (err) {
40586        LoaderService.hide();
40587        var customAemErrorMsg = $('[data-js="error-msg-pass-general-error"]').val();
40588        _this2.openValidation(Granite.I18n.get(customAemErrorMsg));
40589
40590        // Analytics - Service Error
40591        _satellite.track('serviceError', {
40592          serviceType: 'changePassword',
40593          statusCode: err.status,
40594          messageError: err.responseJSON.message.toUpperCase()
40595        });
40596      });
40597    }
40598  }, {
40599    key: 'enableButtonSubmit',
40600    value: function enableButtonSubmit() {
40601      $("[data-js='button-save-password']").attr('disabled', false);
40602    }
40603  }, {
40604    key: 'disableButtonSubmit',
40605    value: function disableButtonSubmit() {
40606      $("[data-js='button-save-password']").attr("disabled", true);
40607    }
40608  }, {
40609    key: 'handleFormUpdatePassword',
40610    value: function handleFormUpdatePassword() {
40611      var _this3 = this;
40612
40613      var isPasswordValid = this.isPasswordValid();
40614
40615      if (isPasswordValid) {
40616        this.buttonSumitPassword.click(function (e) {
40617          e.stopImmediatePropagation();
40618          _this3.submitUpdatePassword();
40619        });
40620      }
40621    }
40622  }, {
40623    key: 'isSelectCustom',
40624    value: function isSelectCustom(el) {
40625      return $(el).attr('data-js') === 'input-new-password' || $(el).attr('data-js') === 'input-confirm-password';
40626    }
40627  }, {
40628    key: 'addInvalidClass',
40629    value: function addInvalidClass(el, msg, tip) {
40630      var $links = el.parent().siblings().find('.link');
40631
40632      $(el).addClass("invalid");
40633
40634      if (tip && tip.hasClass('warning')) {
40635        if (msg) tip.text(msg);
40636        tip.fadeIn();
40637        $links.hide();
40638      }
40639    }
40640  }, {
40641    key: 'removeInvalidClass',
40642    value: function removeInvalidClass(el, tip) {
40643      var $links = el.parent().siblings().find('.link');
40644
40645      $(el).removeClass("invalid");
40646      if (tip && tip.hasClass('warning')) {
40647        tip.fadeOut();
40648        $links.show();
40649      }
40650    }
40651  }, {
40652    key: 'openValidation',
40653    value: function openValidation(msg) {
40654      var _this4 = this;
40655
40656      data_layer.page.pageInfo.errorOnSignUp.message = msg; // Analytics
40657
40658      var default_msg = '<p><label class="red">ERRO:</label> ' + msg + ' </p>';
40659      if (msg !== null || msg !== '') {
40660        msg = default_msg;
40661      }
40662
40663      this.errorMessage.empty().append(msg);
40664      this.errorMessage.fadeIn();
40665
40666      data_layer.page.pageInfo.errorOnSignUp.happened = true; // Analytics
40667
40668      this.formPassword.children().find("input").on('focusin', function () {
40669        _this4.errorMessage.fadeOut();
40670      });
40671    }
40672  }, {
40673    key: 'emptyValidation',
40674    value: function emptyValidation() {
40675      var allFieldsValid = true;
40676      var self = this;
40677      this.formRegister.find('input[required]').each(function (idx, el) {
40678        var value = $(el).val() ? $(el).val() : '';
40679        if (self.isEmpty(value)) {
40680          self.addInvalidClass($(el));
40681          allFieldsValid = false;
40682        } else self.removeInvalidClass($(el));
40683      });
40684      if (!allFieldsValid) this.openValidation('Alguns campos estão vazios. Preencha os campos faltantes assinalados em vermelho antes de prosseguir.');
40685      return allFieldsValid;
40686    }
40687  }, {
40688    key: 'showMessage',
40689    value: function showMessage() {
40690      Utils.scrollTop();
40691      Alert.show('Senha editada com sucesso.');
40692    }
40693  }]);
40694
40695  return UpdatePasswordLink;
40696}();
40697'use strict';
40698
40699var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
40700
40701function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
40702
40703var UpdatePassword = function () {
40704  function UpdatePassword($) {
40705    _classCallCheck(this, UpdatePassword);
40706
40707    this.oldPassword = $('[data-js="input-old-password"]');
40708    this.newPassword = $('[data-js="input-new-password"]');
40709    this.confirmPassword = $('[data-js="input-confirm-password"]');
40710    this.buttonSumitPassword = $('[data-js="button-save-password"]');
40711    this.errorMessage = $('[data-js="error-message"]');
40712    this.formPassword = $('[data-js="password-form"]');
40713    this.greetingsText = $('[data-js="greetings"]');
40714    this.iconPassword = $('[data-js="show-update-password"]');
40715    this.passenger = SessionStorage.get('passenger');
40716    this.init();
40717  }
40718
40719  _createClass(UpdatePassword, [{
40720    key: 'init',
40721    value: function init() {
40722      this.loadUserData();
40723      this.listenForm();
40724      this.handleFormUpdatePassword();
40725    }
40726  }, {
40727    key: 'loadUserData',
40728    value: function loadUserData() {
40729
40730      //If the page is in edit mode, no action will be taken.
40731      if ($('#wcmmodeedit').val() === 'true') return;
40732
40733      if (!this.passenger) {
40734        localStorage.setItem("referrer", $(location).attr('href'));
40735        $(location).attr('href', $('#loginPage').val());
40736      } else {
40737        var blankText = this.greetingsText.text();
40738        var name = this.passenger._name.trim();
40739        this.greetingsText.text(blankText.replace('#user', Utils.getFirstName(name)));
40740      }
40741    }
40742  }, {
40743    key: 'isPasswordValid',
40744    value: function isPasswordValid() {
40745      var password = this.newPassword.val();
40746      var confPassword = this.confirmPassword.val();
40747      var $tipPassword = this.newPassword.parent().siblings().find('.tip');
40748      var $tipConfPassword = this.confirmPassword.parent().siblings().find('.tip');
40749      var tipMsg = $('[data-js="error-password-alphanumeric"]').val() ? $('[data-js="error-password-alphanumeric"]').val() : i18n('password_alphanumeric_error');
40750
40751      if (password.length > 0) {
40752        if (this.checkPasswordAlphanumeric()) {
40753          if (!(password === confPassword) && confPassword.length > 0) {
40754            this.addInvalidClass(this.newPassword);
40755
40756            if (password.length < 8) {
40757              this.addInvalidClass(this.newPassword, tipMsg, $tipPassword);
40758            } else {
40759              var tipMsgNoMatch = $('[data-js="error-msg-pass-does-not-match"]').val() ? $('[data-js="error-msg-pass-does-not-match"]').val() : i18n('password_no_confirm');
40760              this.addInvalidClass(this.confirmPassword, tipMsgNoMatch, $tipConfPassword);
40761            }
40762            this.disableButtonSubmit();
40763
40764            return false;
40765          } else if (password.length >= 8 && password.length <= 12) {
40766            this.removeInvalidClass(this.newPassword, $tipPassword);
40767            this.removeInvalidClass(this.newPassword);
40768            if (password === confPassword) {
40769              this.removeInvalidClass(this.confirmPassword, $tipConfPassword);
40770              this.enableButtonSubmit();
40771              return true;
40772            }
40773
40774            return false;
40775          } else if (password.length < 8) {
40776            this.addInvalidClass(this.newPassword, tipMsg, $tipPassword);
40777            this.disableButtonSubmit();
40778
40779            return false;
40780          }
40781        } else {
40782          this.addInvalidClass(this.newPassword, tipMsg, $tipPassword);
40783          this.disableButtonSubmit();
40784          return false;
40785        }
40786      }
40787    }
40788  }, {
40789    key: 'checkPasswordAlphanumeric',
40790    value: function checkPasswordAlphanumeric() {
40791      var passwordFormatRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9@$!%*#?&]{8,}$/;
40792
40793      return passwordFormatRegex.test(this.newPassword.val());
40794    }
40795  }, {
40796    key: 'listenForm',
40797    value: function listenForm() {
40798      var _this = this;
40799
40800      this.formPassword.find('input[required]').keyup(function () {
40801        _this.handleFormUpdatePassword();
40802      });
40803
40804      this.iconPassword.on('click', function (e) {
40805        $(e.target).toggleClass('active');
40806        $(e.target).hasClass('active') ? $(e.target).prev().attr('type', 'text') : $(e.target).prev().attr('type', 'password');
40807      });
40808
40809      $('[data-js="input-old-password"], [data-js="input-new-password"], ' + '[data-js="input-confirm-password"]').on('keyup', function (event) {
40810        var keyCode = event.keyCode || event.which;
40811        if (keyCode === Utils.keyCodes.ENTER) {
40812          _this.buttonSumitPassword.click();
40813        }
40814      });
40815
40816      $('[data-js="close-menu"]').on('click', function () {
40817        $('.header-update-password, .update-password-form-wrapper').show();
40818      });
40819      var dataArray = ['[data-js=input-old-password], [data-js=input-new-password], [data-js=input-confirm-password]'];
40820      !Utils.quotesBlock(dataArray);
40821    }
40822  }, {
40823    key: 'submitUpdatePassword',
40824    value: function submitUpdatePassword() {
40825      var _this2 = this;
40826
40827      var body = {
40828        "Login": this.passenger._login,
40829        "OldPassword": this.oldPassword.val(),
40830        "NewPassword": this.confirmPassword.val()
40831      };
40832
40833      var headers = {
40834        'Authorization': '' + SessionStorage.get('jca_token'),
40835        'channel': Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform)
40836      };
40837
40838
40839      _this2.disableButtonSubmit();
40840      LoaderService.show();
40841      HttpService.put('changePassword', body, headers).then(function () {
40842        LoaderService.hide();
40843        AlertConfirmation.showAEM('data-js="alert-password-changed"');
40844        _this2.formPassword.trigger("reset");
40845      }).catch(function (err) {
40846        LoaderService.hide();
40847        var customAemErrorMsg = $('[data-js="error-msg-pass-general-error"]').val();
40848        _this2.openValidation(Granite.I18n.get(customAemErrorMsg));
40849
40850        // Analytics - Service Error
40851        _satellite.track('serviceError', {
40852          serviceType: 'changePassword',
40853          statusCode: err.status,
40854          messageError: err.responseJSON.message.toUpperCase()
40855        });
40856      });
40857    }
40858  }, {
40859    key: 'enableButtonSubmit',
40860    value: function enableButtonSubmit() {
40861      $("[data-js='button-save-password']").attr('disabled', false);
40862    }
40863  }, {
40864    key: 'disableButtonSubmit',
40865    value: function disableButtonSubmit() {
40866      $("[data-js='button-save-password']").attr("disabled", true);
40867    }
40868  }, {
40869    key: 'handleFormUpdatePassword',
40870    value: function handleFormUpdatePassword() {
40871      var _this3 = this;
40872
40873      var isPasswordValid = this.isPasswordValid();
40874
40875      if (isPasswordValid) {
40876        this.buttonSumitPassword.click(function (e) {
40877          e.stopImmediatePropagation();
40878          _this3.submitUpdatePassword();
40879        });
40880      }
40881    }
40882  }, {
40883    key: 'isSelectCustom',
40884    value: function isSelectCustom(el) {
40885      return $(el).attr('data-js') === 'input-new-password' || $(el).attr('data-js') === 'input-confirm-password';
40886    }
40887  }, {
40888    key: 'addInvalidClass',
40889    value: function addInvalidClass(el, msg, tip) {
40890      var $links = el.parent().siblings().find('.link');
40891
40892      $(el).addClass("invalid");
40893
40894      if (tip && tip.hasClass('warning')) {
40895        if (msg) tip.text(msg);
40896        tip.fadeIn();
40897        $links.hide();
40898      }
40899    }
40900  }, {
40901    key: 'removeInvalidClass',
40902    value: function removeInvalidClass(el, tip) {
40903      var $links = el.parent().siblings().find('.link');
40904
40905      $(el).removeClass("invalid");
40906      if (tip && tip.hasClass('warning')) {
40907        tip.fadeOut();
40908        $links.show();
40909      }
40910    }
40911  }, {
40912    key: 'openValidation',
40913    value: function openValidation(msg) {
40914      var _this4 = this;
40915
40916      var default_msg = '<p><label class="red">ERRO:</label> ' + msg + ' </p>';
40917      if (msg !== null || msg !== '') {
40918        msg = default_msg;
40919      }
40920
40921      this.errorMessage.empty().append(msg);
40922      this.errorMessage.fadeIn();
40923
40924      this.formPassword.children().find("input").on('focusin', function () {
40925        _this4.errorMessage.fadeOut();
40926      });
40927    }
40928  }, {
40929    key: 'emptyValidation',
40930    value: function emptyValidation() {
40931      var allFieldsValid = true;
40932      var self = this;
40933      this.formRegister.find('input[required]').each(function (idx, el) {
40934        var value = $(el).val() ? $(el).val() : '';
40935        if (self.isEmpty(value)) {
40936          self.addInvalidClass($(el));
40937          allFieldsValid = false;
40938        } else self.removeInvalidClass($(el));
40939      });
40940      if (!allFieldsValid) this.openValidation('Alguns campos estão vazios. Preencha os campos faltantes assinalados em vermelho antes de prosseguir.');
40941      return allFieldsValid;
40942    }
40943  }, {
40944    key: 'showMessage',
40945    value: function showMessage() {
40946      Utils.scrollTop();
40947      Alert.show('Senha editada com sucesso.');
40948    }
40949  }]);
40950
40951  return UpdatePassword;
40952}();
40953'use strict';
40954
40955var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
40956
40957function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
40958
40959var PasswordRecoveryOverlay = function () {
40960  function PasswordRecoveryOverlay($) {
40961    _classCallCheck(this, PasswordRecoveryOverlay);
40962
40963    this.savedMsg = $('[data-js="saved-response-msg"]').val();
40964    this.responseMsgSuccess = $('[data-js="result-msg-success"]');
40965    this.responseMsgError = $('[data-js="result-msg-error"]');
40966    this.btnSend = $('[data-js="btn-send"]');
40967    this.inputEmail = $("[data-js='input-email-recovery']");
40968    this.MsgSuccess = $('[data-js="result-msg-success-email"]');
40969    this.init();
40970  }
40971
40972  _createClass(PasswordRecoveryOverlay, [{
40973    key: 'init',
40974    value: function init() {
40975      this.handleForm();
40976      this.handleMasks();
40977      this.handleEvents();
40978      this.btnSend.text($('[data-js="textButtonSend-login-cpm"]').val() || 'Enviar');
40979    }
40980  }, {
40981    key: 'handleEvents',
40982    value: function handleEvents() {
40983      var _this = this;
40984
40985      $('[data-js="btn-close"]').click(function (e) {
40986        return _this.hideOverlay(e);
40987      });
40988
40989      $('.password-recovery-container').children().on('focusout', function (e) {
40990        var $target = $(e.relatedTarget);
40991        if ($target.closest('.password-recovery-container').length == 0 && $target.length > 0) $('[data-js="btn-close"]').click();
40992      });
40993    }
40994  }, {
40995    key: 'handleForm',
40996    value: function handleForm() {
40997      var sentText = $('[data-js="sent-text"]').val() || $('[data-js="textButtonSent"]').val() || $('[data-js="textButtonSent-login-cpm"]').val();
40998      var msgSuccess = 'Enviado com sucesso para o email do usuário ${email}! Você receberá em alguns minutos uma mensagem em seu email cadastrado.&#xa;Caso não tenha mais acesso a este e-mail, contate nossa central de atendimento.';
40999      var msgError = '<span class="error">ERRO: ' + '</span>';
41000
41001      this.btnSend.click({
41002        "msgSuccess": msgSuccess,
41003        "msgError": msgError,
41004        "sentText": sentText,
41005        "maskEmail": this.maskEmail,
41006        'classReference': this
41007      }, this.send);
41008    }
41009  }, {
41010    key: 'handleMasks',
41011    value: function handleMasks() {
41012      var _this2 = this;
41013
41014      var inputEmail = $("[data-js='input-email-recovery']");
41015      var masks = ['000.000.000-009', '00.000.000/0000-00'];
41016
41017      var maskBehavior = function maskBehavior(val) {
41018        return val.replace(/\D/g, '').length <= 11 ? masks[0] : masks[1];
41019      },
41020        cpfCnpjpOptions = {
41021          onKeyPress: function onKeyPress(val, e, field, options) {
41022            field.mask(maskBehavior.apply({}, arguments), options);
41023          }
41024        };
41025
41026      inputEmail.on('keyup keydown click', function (e) {
41027        var keyCode = e.keyCode || e.which;
41028        if (keyCode === Utils.keyCodes.ENTER && _this2.btnSend.is(':disabled')) {
41029          e.preventDefault();
41030        }
41031        var text = _this2.btnSend.text();
41032
41033        if (text === i18n('sending') && e.type === 'keyup') return;
41034
41035        var invalidMask = new RegExp(/[\ !#$%¨&*¹²³£¢¬\(\)\[\]\{\}´`~;:°?*+,|]+/g);
41036        var noInvalidValues = $(e.target).val().replace(invalidMask, '');
41037        $(e.target).val(noInvalidValues);
41038        var matchMasks = new RegExp(/(\.)|(\/)|(\-)/g);
41039        var emailMask = new RegExp(/^([a-zA-Z0-9]+[\_\-\.]{1})*[a-zA-Z0-9]+@[a-zA-Z0-9]*\.[a-zA-Z0-9]+[\.a-zA-Z0-9]*$/g);
41040        var numberMask = new RegExp(/^[0-9]+$/g);
41041        var value = $(e.target).val();
41042        var valueWithoutMask = value.replace(matchMasks, '');
41043        _this2.btnSend.text($('[data-js="textButtonSend-login-cpm"]').val() || 'Enviar');
41044
41045        if (value.length === 0) {
41046          _this2.disableButton();
41047          inputEmail.unmask();
41048          inputEmail.attr("maxLength", "45");
41049          return;
41050        }
41051
41052        if (value.indexOf('@') > -1) {
41053          if (emailMask.test(value)) {
41054            _this2.enableButton();
41055            if (keyCode === Utils.keyCodes.ENTER && e.type === 'keydown') {
41056              e.preventDefault();
41057              _this2.btnSend.click();
41058            }
41059          } else {
41060            _this2.disableButton();
41061          }
41062        } else {
41063          _this2.enableButton();
41064          if (keyCode === Utils.keyCodes.ENTER && e.type === 'keydown') {
41065            e.preventDefault();
41066            _this2.btnSend.click();
41067          }
41068          if (numberMask.test(valueWithoutMask)) {
41069            if (value.length >= 10) {
41070              inputEmail.mask(maskBehavior, cpfCnpjpOptions);
41071            } else {
41072              inputEmail.unmask();
41073              inputEmail.attr("maxLength", "45");
41074            }
41075          }
41076        }
41077      });
41078    }
41079  }, {
41080    key: 'disableButton',
41081    value: function disableButton() {
41082      this.btnSend.attr('disabled', 'disabled');
41083    }
41084  }, {
41085    key: 'enableButton',
41086    value: function enableButton() {
41087      this.btnSend.attr('disabled', false);
41088      this.responseMsgSuccess.fadeOut('fast');
41089      this.responseMsgError.fadeOut('fast');
41090    }
41091  }, {
41092    key: 'showOverlay',
41093    value: function showOverlay() {
41094      var body = $('body');
41095      var breadcrumb = $('[data-js="breadcrumb"]');
41096      var overlayComponent = $('[data-js="bottom-password"]');
41097
41098      var _Utils$getWindowSize = Utils.getWindowSize(),
41099        width = _Utils$getWindowSize.width,
41100        breakpoints = _Utils$getWindowSize.breakpoints;
41101
41102      if (width >= breakpoints.LG) {
41103        if (breadcrumb.is(':visible') && Utils.isScrolledIntoView(breadcrumb)) {
41104          overlayComponent.css('top', 100 + 'px');
41105        } else {
41106          overlayComponent.css('top', 95 + 'px');
41107        }
41108      }
41109
41110      overlayComponent.addClass('bottom-active');
41111
41112      var isLogged = $('div.login-button').find('[data-js="logged-out-section"]').length > 0;
41113      if (!isLogged) {
41114        overlayComponent.addClass('overlay-active');
41115        overlayComponent.removeAttr("style");
41116      }
41117
41118      body.css('overflow-y', 'hidden');
41119      //$('[data-js="btn-send"]').text($('[data-js="textButtonSend-login-cpm"]').val() || 'Enviar');
41120    }
41121  }, {
41122    key: 'hideOverlay',
41123    value: function hideOverlay(e) {
41124      $('body').css('overflow-y', 'auto');
41125      var overlayComponent = $(e.currentTarget).closest("[data-js='bottom-password']");
41126      var inputEmail = overlayComponent.find("[data-js='input-email-recovery']");
41127      var btnSend = overlayComponent.find('[data-js="btn-send"]');
41128
41129      overlayComponent.removeClass('bottom-active overlay-active');
41130
41131      this.responseMsgSuccess.hide();
41132      this.responseMsgError.hide();
41133
41134      $('section.login').css('visibility', 'visible');
41135
41136      inputEmail.removeClass('input-error');
41137      inputEmail.val('');
41138      btnSend.text($('[data-js="textButtonSend-login-cpm"]').val() || 'Enviar');
41139      btnSend.attr('disabled', 'disabled');
41140    }
41141  }, {
41142    key: 'maskEmail',
41143    value: function maskEmail(emailPlain) {
41144      var beforeAt = emailPlain.split('@')[0];
41145      var afterAt = emailPlain.split('@')[1];
41146      var emailMasked = '';
41147      emailMasked += beforeAt.slice(0, 2);
41148
41149      for (var i = 0; i < beforeAt.length - 4; i++) {
41150        emailMasked = emailMasked.concat('*');
41151      } emailMasked = emailMasked.concat(beforeAt.slice(-2)).concat('@').concat(afterAt);
41152
41153      return emailMasked;
41154    }
41155  }, {
41156    key: 'handleEmailCriptograpy',
41157    value: function handleEmailCriptograpy(email) {
41158      var emailCripto = "";
41159      var emailText = email.split("@");
41160
41161      for (var i = 0; i < emailText[0].length; i++) {
41162        if (i >= 2 && i < emailText[0].length - 2) {
41163          emailCripto += "*";
41164        } else {
41165          emailCripto += emailText[0][i];
41166        }
41167      }
41168
41169      return emailCripto + '@' + emailText[1];
41170    }
41171  }, {
41172    key: 'send',
41173    value: function send(event) {
41174      var parent = $(event.currentTarget).closest("[data-js='bottom-password']");
41175      var inputText = parent.find("[data-js='input-email-recovery']").val();
41176      var self = event.data.classReference;
41177      var sentText = event.data.sentText;
41178      var btnSend = $(this);
41179      btnSend.attr('disabled', 'disabled');
41180
41181      var body = self.createRequestObject(inputText);
41182
41183      var isResetPasswordV2 = $('[data-js="active-reset-password-v2"]').val() == "true" ? true : false;
41184
41185      var headers = null;
41186
41187      if (isResetPasswordV2) {
41188        headers = { 'version': 2, 'channel': Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform) };
41189      }
41190
41191      if (body.login.length === 0) return;
41192
41193      btnSend.text('Enviando...');
41194      LoaderService.show();
41195      HttpService.put('resetPassword', body, isResetPasswordV2 ? headers : '').then(function (data) {
41196        LoaderService.hide();
41197        var email = data.email;
41198
41199        var messageEmail = self.handleEmailCriptograpy(email);
41200
41201        if (sentText) {
41202          btnSend.text(sentText);
41203        } else {
41204          btnSend.text('Enviar');
41205        }
41206
41207        self.inputEmail.attr('class', 'email');
41208        self.inputEmail.focus();
41209        self.responseMsgSuccess.fadeIn('fast');
41210        self.MsgSuccess.text(messageEmail)
41211      }).catch(function (err) {
41212        LoaderService.hide();
41213        self.responseMsgError.fadeIn('fast');
41214        btnSend.text($('[data-js="sent-text"]').val() ? $('[data-js="sent-text"]').val() : 'Enviado');
41215
41216        // Analytics - Triggers an event when there is an error on service.
41217        if (typeof _satellite != "undefined") {
41218          _satellite.track('resetPasswordError', { service: 'resetPassword', messageError: err.responseJSON.message.toUpperCase() });
41219
41220          // Analytics - Service Error Event
41221          _satellite.track('serviceError', {
41222            serviceType: 'resetPassword',
41223            statusCode: err.status,
41224            messageError: err.responseJSON.message.toUpperCase()
41225          });
41226        }
41227      });
41228    }
41229  }, {
41230    key: 'createRequestObject',
41231    value: function createRequestObject(login) {
41232      var regex = new RegExp(/^[a-z0-9\.\-\_]+@[a-z0-9]+[-]*[a-z0-9]*\.[a-z]+(\.[a-z]+)?$/gm);
41233      if (regex.test(login.toLowerCase())) {
41234        return {
41235          login: login.toLowerCase()
41236        };
41237      } else {
41238        return {
41239          login: login.replace(/\D/g, '')
41240        };
41241      }
41242    }
41243  }]);
41244
41245  return PasswordRecoveryOverlay;
41246}();
41247'use strict';
41248
41249var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
41250
41251function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
41252
41253var PathOverlay = function () {
41254  function PathOverlay($) {
41255    var _this = this;
41256
41257    _classCallCheck(this, PathOverlay);
41258
41259    this.$container = $('.path-container');
41260    this.$closeButton = $('[data-js="btn-close-path"]');
41261    this.$closeButton.click(function (e) {
41262      return _this.hideOverlay(e);
41263    });
41264    this.$container.children().focusout(function (e) {
41265      var $target = $(e.relatedTarget);
41266      if ($target.length >= 0 && $target.closest('.path-container').length == 0) _this.$closeButton.click();
41267    });
41268  }
41269
41270  _createClass(PathOverlay, [{
41271    key: 'clearTimelineContent',
41272    value: function clearTimelineContent() {
41273      this.$container.find('.timeline').html('');
41274    }
41275  }, {
41276    key: 'showLastIcon',
41277    value: function showLastIcon() {
41278      this.$container.find('.timeline').find('.icon').last().removeClass('hide');
41279    }
41280  }, {
41281    key: 'setTimelineContent',
41282    value: function setTimelineContent(data, origin, destination) {
41283      var listCities = data.itinerarioApp.lsItinerario;
41284      var $listEl = this.$container.find('.timeline');
41285      var $elTemplate = this.$container.find('[data-js="path-template"]');
41286      var originIndex = 0;
41287      var destinationIndex = listCities.length - 1;
41288
41289      for (var i = 0; i < listCities.length; i++) {
41290        if (listCities[i].cidade.toUpperCase() === origin) originIndex = i;
41291        if (listCities[i].cidade.toUpperCase() === destination) destinationIndex = i;
41292      }
41293
41294      for (var _i = originIndex; _i <= destinationIndex; _i++) {
41295        var $city = $elTemplate.clone();
41296        var formattedTime = DateFormatter.formatTimeString(listCities[_i].hora);
41297        var route = listCities[_i].via === undefined ? '' : 'VIA: ' + listCities[_i].via;
41298        var $routeContainer = $city.find('.place-route');
41299        var $routeIconContainer = $city.find('.route-icon');
41300        var routeIconSrc = $routeIconContainer[0].src;
41301
41302        if (route === '') $routeContainer.remove();
41303
41304        if (_i === originIndex || _i === destinationIndex) $routeIconContainer[0].src = routeIconSrc.replace('gray', 'white');
41305
41306        $city.find('.time').text(formattedTime);
41307        $city.find('.place-name').append(listCities[_i].cidade);
41308        $city.find('.place-route').append(route);
41309        $city.attr('data-js', '');
41310        $city.find('.route').text(listCities[_i].via);
41311        $listEl.append($city);
41312        $city.show();
41313      }
41314
41315      $listEl.find('.element').removeClass('active');
41316      $listEl.find('.element').first().addClass('active');
41317      $listEl.find('.element').last().addClass('active');
41318    }
41319  }, {
41320    key: 'showOverlay',
41321    value: function showOverlay(lastElement) {
41322      this.$container.addClass('active');
41323      OverlayService.show("full");
41324      this.$closeButton.first().focus();
41325      this.lastElement = lastElement;
41326    }
41327  }, {
41328    key: 'hideOverlay',
41329    value: function hideOverlay(e) {
41330      this.$container.removeClass('active');
41331      OverlayService.hide();
41332      if (this.lastElement) this.lastElement.focus();
41333    }
41334  }]);
41335
41336  return PathOverlay;
41337}();
41338
41339'use strict';
41340
41341
41342(function ($) {
41343  try {
41344    $('[data-js="btn-close"]').click(function () {
41345      $('[data-js="btn-send"]').text($('[data-js="textButtonSend-login-cpm"]').val() || 'Enviar');
41346      $('[data-js="btn-send"]').attr('was-sent', false);
41347      $("[data-js='response-msg']").text($('[data-js="textareaInformativeText"]').val() || $('[data-js="textareaInformativeText-login-cpm"]').val() || '');
41348    });
41349
41350    if ($('html').attr('lang') != undefined) {
41351      var userLang = $('html').attr('lang').toLowerCase();
41352      var currentLanguage = '/etc.clientlibs/wemobi/clientlibs/clientlib-site/resources/images/' + userLang + '.png';
41353
41354      var img = $('.current-language');
41355      if (img) {
41356        $(img).attr('src', currentLanguage);
41357      }
41358    }
41359  } catch (err) { console.log(err); }
41360})(jQuery);
41361
41362'use strict';
41363
41364var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
41365
41366function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
41367
41368var PaymentInformationLivelo = function () {
41369  function PaymentInformationLivelo($, cartComponentRef) {
41370    _classCallCheck(this, PaymentInformationLivelo);
41371
41372    this.cartComponentRef = cartComponentRef;
41373    this.checkout = SessionStorage.get('checkout');
41374    this.checkoutAux = SessionStorage.get('checkout_aux');
41375    this.cardOperator = $('[data-js="payment-operator"]');
41376    this.authCode = $('[data-js="authorization-code"]');
41377    this.convenienceFeeValue = $('[data-js="convenienceFee-value"]');
41378    this.cardNumber = $('[data-js="number-payment-method"]');
41379    this.paymentMethod = $('[data-js="payment-method"]');
41380    this.installments = $('[data-js="payment-installments"]');
41381    this.datePayment = $('[data-js="payment-date"]');
41382    this.ticketsValue = $('[data-js="value-ticket"]');
41383    this.ticketsTaxs = $('[data-js="services-ticket"]');
41384    this.insuranceValue = $('[data-js="insurance-value"]');
41385    this.tripValue = $('[data-js="trip-value"]');
41386    this.tripValueLivelo = $('[data-js="trip-value-pointsLivelo"]');
41387    this.valueDiscount = $('[data-js="value-descount"]');
41388    this.branch = $('[data-js="my-account-branch"]');
41389    this.account = $('[data-js="my-account-account"]');
41390    this.documentUser = $('[data-js="my-account-document"]');
41391    this.ourBranch = $('[data-js="our-account-branch"]');
41392    this.ourAccount = $('[data-js="our-account-account"]');
41393    this.ourFavored = $('[data-js="our-account-favored"]');
41394    this.buyValue = $('[data-js="buy-value"]');
41395    this.ourBankLogo = $('[data-js="our-account-bank-image"]');
41396    this.bankLogo = $('[data-js="my-account-bank-image"]');
41397    this.maxHour = $('[data-js="bank-transfer-hour"]');
41398    this.checkout = SessionStorage.get('checkout');
41399    this.convenienceFee = $('[data-js="convenience-fee"]').attr('value') == 'true';
41400    this.labelConvenienceFee = $('[data-js="label-convenience-fee"]');
41401    this.init();
41402  }
41403
41404  _createClass(PaymentInformationLivelo, [{
41405    key: 'init',
41406    value: function init() {
41407      this.loadTicketValues(this.checkout);
41408      this.handleConvenienceFee();
41409    }
41410  }, {
41411    key: 'handleConvenienceFee',
41412    value: function handleConvenienceFee() {
41413      if (this.convenienceFee && this.labelConvenienceFee) {
41414        $('.convenience-value').removeClass('d-none');
41415        this.labelConvenienceFee.text(i18n('convenience_fee'));
41416      } else $('.convenience-value').addClass('d-none');
41417    }
41418  }, {
41419    key: 'getTotal',
41420    value: function getTotal(sales) {
41421      var _this = this;
41422
41423      return sales.reduce(function (acc, sale) {
41424        return sale.amount + acc + (_this.convenienceFee ? sale.convenienceFee : 0) + (sale.insurance ? sale.insurance.insuranceValue : 0);
41425      }, 0);
41426    }
41427  }, {
41428    key: 'getTotalConvenienceFee',
41429    value: function getTotalConvenienceFee(sales) {
41430      var total = 0;
41431      sales.forEach(function (sale) {
41432        total += sale.convenienceFee;
41433      });
41434      return total;
41435    }
41436  }, {
41437    key: 'loadTicketValues',
41438    value: function loadTicketValues(checkout) {
41439      var arr = checkout.sales;
41440      var tarifa = 0;
41441      var taxas = 0;
41442      var priceTotal = 0;
41443      var discount = 0;
41444      var insurance = 0;
41445      var convenienceFee = this.getTotalConvenienceFee(arr);
41446
41447      var ticketPassengerValues = arr.reduce(function (acc, elem) {
41448        if (elem.typeId === 1) return acc;
41449
41450        return acc = {
41451          'ticketsPrice': tarifa = tarifa + elem.tariff,
41452          'taxsPrice': taxas = taxas + elem.tax + elem.tollTax + elem.boardingFee + elem.insuranceTax + elem.otherTax,
41453          'convenienceFee': convenienceFee,
41454          'fullPrice': priceTotal = priceTotal + elem.amount,
41455          'discount': discount = discount + elem.voucherValue,
41456          'insurance': insurance += elem.insurance ? elem.insurance.insuranceValue : 0
41457        };
41458      }, {});
41459
41460      var ticketsPrice = Utils.formatPrice(ticketPassengerValues.ticketsPrice);
41461      var taxsPrice = Utils.formatPrice(ticketPassengerValues.taxsPrice);
41462      var discountPrice = Utils.formatPrice(ticketPassengerValues.discount);
41463      var totalPrice = Utils.formatPrice(ticketPassengerValues.fullPrice + ticketPassengerValues.insurance + (this.convenienceFee ? ticketPassengerValues.convenienceFee : 0));
41464      var insurancePrice = Utils.formatPrice(ticketPassengerValues.insurance);
41465      var convenience = this.convenienceFee ? Utils.formatPrice(ticketPassengerValues.convenienceFee) : 0;
41466
41467      this.tripValue.text('R$ ' + totalPrice);
41468      if (this.convenienceFee) this.convenienceFeeValue.text('R$ ' + convenience);
41469      this.tripValueLivelo.text(checkout.payment.transaction.totalPrice.amount + ' Pts');
41470      this.ticketsValue.text('R$ ' + ticketsPrice);
41471      this.valueDiscount.text('R$ ' + discountPrice);
41472      this.ticketsTaxs.text((ticketPassengerValues.taxsPrice ? 'R$ ' + taxsPrice : '-') + ' ');
41473
41474      if (insurancePrice == '0,00') this.insuranceValue.closest('.item-description').remove(); else this.insuranceValue.text('R$ ' + insurancePrice);
41475    }
41476  }]);
41477
41478  return PaymentInformationLivelo;
41479}();
41480'use strict';
41481
41482var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
41483
41484var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
41485
41486function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
41487
41488var PaymentInformation = function () {
41489  function PaymentInformation($, cartComponentRef) {
41490    _classCallCheck(this, PaymentInformation);
41491
41492    this.cartComponentRef = cartComponentRef;
41493    this.checkout = SessionStorage.get('checkout');
41494    this.checkoutAux = SessionStorage.get('checkout_aux');
41495    this.cardOperator = $('[data-js="payment-operator"]');
41496    this.authCode = $('[data-js="authorization-code"]');
41497    this.convenienceFeeValue = $('[data-js="convenienceFee-value"]');
41498    this.cardNumber = $('[data-js="number-payment-method"]');
41499    this.paymentMethod = $('[data-js="payment-method"]');
41500    this.installments = $('[data-js="payment-installments"]');
41501    this.datePayment = $('[data-js="payment-date"]');
41502    this.ticketsValue = $('[data-js="value-ticket"]');
41503    this.ticketsTaxs = $('[data-js="services-ticket"]');
41504    this.insuranceValue = $('[data-js="insurance-value"]');
41505    this.tripValue = $('[data-js="trip-value"]');
41506    this.valueDiscount = $('[data-js="value-descount"]');
41507    this.branch = $('[data-js="my-account-branch"]');
41508    this.account = $('[data-js="my-account-account"]');
41509    this.documentUser = $('[data-js="my-account-document"]');
41510    this.ourBranch = $('[data-js="our-account-branch"]');
41511    this.ourAccount = $('[data-js="our-account-account"]');
41512    this.ourFavored = $('[data-js="our-account-favored"]');
41513    this.buyValue = $('[data-js="buy-value"]');
41514    this.ourBankLogo = $('[data-js="our-account-bank-image"]');
41515    this.bankLogo = $('[data-js="my-account-bank-image"]');
41516    this.maxHour = $('[data-js="bank-transfer-hour"]');
41517    this.checkout = SessionStorage.get('checkout');
41518    this.convenienceFee = $('[data-js="convenience-fee"]').attr('value') == 'true' ? true : false;
41519    this.labelConvenienceFee = $('[data-js="label-convenience-fee"]');
41520    this.repricingV2 = SessionStorage.get('repricingv2');
41521    this.interestValue = $('[data-js="interest-value"]');
41522    this.paymentNegative = SessionStorage.get('paymentNegative');
41523    this.installmentsInfo = undefined;
41524    this.init();
41525  }
41526
41527  _createClass(PaymentInformation, [{
41528    key: 'init',
41529    value: function init() {
41530      if (!this.checkout) return;
41531
41532      if (!this.checkout.sales && this.checkout.result && this.checkout.result.sales) {
41533        this.checkout = this.checkout.result;
41534      }
41535
41536      var isNupay = this.checkoutAux && this.checkoutAux.method === 'NUPAY';
41537
41538      if (isNupay) {
41539        this.loadPaymentNupayInformations();
41540      } else if (this.checkout.payment) {
41541        this.checkout.payment.paymee ? this.loadPaymentBankInformations() : this.loadPaymentCardInformations();
41542        this.sendPurchaseToAnalytics();
41543      } else if (this.checkout.transactionExchangeModels || !this.checkout.payment && !this.checkout.transactionExchangeModels && this.checkout.sales) {
41544        this.loadPaymentInformationDevolution();
41545      } else {
41546        this.loadPaymentCardInformations();
41547      }
41548
41549      this.handleConvenienceFee();
41550    }
41551  }, {
41552    key: 'loadPaymentNupayInformations',
41553    value: function loadPaymentNupayInformations() {
41554      var sales = this.checkout.sales || [];
41555
41556      $('.footer-payment-information-card').hide();
41557
41558      if (sales.length > 0) {
41559        this.loadNupayTicketValues(sales);
41560      }
41561    }
41562  }, {
41563    key: 'loadNupayTicketValues',
41564    value: function loadNupayTicketValues(sales) {
41565      var tariff = 0,
41566          tax = 0,
41567          convFee = 0,
41568          insurance = 0,
41569          discount = 0,
41570          total = 0;
41571
41572      sales.forEach(function (sale) {
41573        if (sale.valueParts) {
41574          sale.valueParts.forEach(function (part) {
41575            switch (part.code) {
41576              case 'Tariff':
41577                tariff += part.value;break;
41578              case 'Tax':
41579                tax += part.value;break;
41580              case 'ConvenienceFee':
41581                convFee += part.value;break;
41582              case 'Insurance':
41583                insurance += part.value;break;
41584              case 'Discount':
41585                discount += Math.abs(part.value);break;
41586            }
41587          });
41588        }
41589      });
41590
41591      total = tariff + tax + convFee + insurance - discount;
41592
41593      this.ticketsValue.text('R$ ' + Utils.formatPrice(tariff));
41594      this.ticketsTaxs.text(tax ? 'R$ ' + Utils.formatPrice(tax) : '-');
41595      this.valueDiscount.text('R$ ' + Utils.formatPrice(discount));
41596      this.tripValue.text('R$ ' + Utils.formatPrice(total));
41597
41598      if (this.convenienceFee && convFee) this.convenienceFeeValue.text('R$ ' + Utils.formatPrice(convFee));
41599
41600      if (insurance > 0) this.insuranceValue.text('R$ ' + Utils.formatPrice(insurance));else this.insuranceValue.closest('.item-description').remove();
41601
41602      this.interestValue.closest('.item-description').remove();
41603    }
41604  }, {
41605    key: 'loadPaymentInformationDevolution',
41606    value: function loadPaymentInformationDevolution() {
41607      $('.footer-payment-information-card').hide();
41608      this.installmentsInfo = this.checkout.installment;
41609      this.loadTicketValues(this.checkout.sales);
41610    }
41611  }, {
41612    key: 'sendPurchaseToAnalytics',
41613    value: function sendPurchaseToAnalytics() {
41614     var _this = this;
41615     var cart = SessionStorage.get('cart');
41616
41617     var voucher = this.checkout.sales[0].voucherToken;
41618
41619      var convenienceFee = this.getTotalConvenienceFee(this.checkout.sales);
41620      var tarifa = 0;
41621      var insurance = 0;
41622      var taxas = 0;
41623      var priceTotal = 0;
41624
41625      var ticketPassengerValues = this.checkout.sales.reduce(function (acc, elem) {
41626          if (elem.typeId === 1) return acc;
41627
41628          return acc = {
41629            'ticketsPrice': tarifa = tarifa + elem.tariff,
41630            'taxsPrice': taxas = taxas + elem.tax + elem.tollTax + elem.boardingFee + elem.insuranceTax + elem.otherTax,
41631            'convenienceFee': convenienceFee,
41632            'fullPrice': priceTotal = priceTotal + elem.voucherToken ? elem.amount + elem.commissionFee : elem.fullPrice,
41633            'insurance': insurance += elem.insurance ? elem.insurance.insuranceValue : 0
41634          };
41635      }, {});
41636
41637      var totalPrice = this.installmentsInfo ?
41638                   Utils.formatPrice(this.installmentsInfo.totalAmountWithInterest) :
41639                   Utils.formatPrice(ticketPassengerValues.ticketsPrice + ticketPassengerValues.insurance + (this.convenienceFee ? ticketPassengerValues.convenienceFee : 0) +
41640                   ticketPassengerValues.taxsPrice);
41641
41642     var dataLayerView = [];
41643     var sales = this.checkout.sales;
41644     cart._listOffer.forEach(function (offer) {
41645       var sale;
41646       for(var i = 0; i < sales.length; i++){
41647         if (sales[i].service == offer._service){
41648           sale=sales[i];
41649           break;
41650         }
41651       }
41652       var aux = {
41653           item_id: offer._service,
41654           price: sale.amount + (sale.insurance ? sale.insurance.insuranceValue : 0),
41655           item_brand: offer._company._companyName,
41656           item_category: offer._company._origin._label,
41657           item_category2: offer._company._destination._label,
41658           item_category3: offer._company._departureDate,
41659           item_category4: offer._company._arrivingDate,
41660           item_variant: offer._classtype._className,
41661           quantity: cart._listPassengers.length
41662       };
41663       dataLayerView.push(aux);
41664     });
41665
41666     dataLayer.push({ ecommerce: null });
41667     dataLayer.push({ event: "purchase_ga4",
41668         ecommerce:{
41669           transaction_id: _this.checkout.sales[0].finder,
41670           currency: "BRL",
41671           revenue: parseFloat(totalPrice.replace(',','.')),
41672           value: totalPrice,
41673           coupon: voucher,
41674           affiliation: $("#siteName").val(),
41675           items: dataLayerView
41676         }
41677     });
41678    }
41679  }, {
41680    key: 'handleConvenienceFee',
41681    value: function handleConvenienceFee() {
41682      if (this.convenienceFee) {
41683        $('[data-js="label-convenience-fee"]').removeClass('d-none');
41684        $('.convenienceFee').removeClass('d-none');
41685      } else $('.convenience-value').addClass('d-none');
41686    }
41687  }, {
41688    key: 'loadPaymentCardInformations',
41689    value: function loadPaymentCardInformations() {
41690      var paymentCardOperator = this.paymentNegative ? this.checkout.payment : this.checkout.payment.result;
41691
41692      var _checkout$sales = _slicedToArray(this.checkout.sales, 1),
41693          sale = _checkout$sales[0];
41694
41695      var _sale$saleTransaction = _slicedToArray(sale.saleTransactions, 1),
41696          date = _sale$saleTransaction[0].date;
41697
41698      var _ref = this.checkout.payment ? paymentCardOperator : this.checkout.resultAdyen.result,
41699          cardOperator = _ref.cardOperator;
41700
41701      var _ref2 = this.checkout.payment ? paymentCardOperator : this.checkout.resultAdyen.result,
41702          authCode = _ref2.authCode;
41703
41704      var _ref3 = this.checkout.payment ? paymentCardOperator : this.checkout.resultAdyen.result,
41705          cardNumber = _ref3.cardNumber;
41706
41707      var installments = this.checkoutAux.installments;
41708      var method = this.checkoutAux.method;
41709
41710
41711      var paymentDate = DateFormatter.extractDate(date);
41712
41713      if (this.cardOperator.find('.cmp-text').length > 0) {
41714        this.cardOperator.find('.cmp-text').text(cardOperator ? cardOperator : '-');
41715      } else {
41716        this.cardOperator.text(cardOperator ? cardOperator : '-');
41717      }
41718
41719      if (this.authCode.find('.cmp-text').length > 0) {
41720        this.authCode.find('.cmp-text').text(authCode);
41721      } else {
41722        this.authCode.text(authCode);
41723      }
41724
41725      if (this.cardNumber.find('.cmp-text').length > 0) {
41726        this.cardNumber.find('.cmp-text').text(cardNumber ? '**** **** **** ' + cardNumber : '-');
41727      } else {
41728        this.cardNumber.text(cardNumber ? '**** **** **** ' + cardNumber : '-');
41729      }
41730
41731      if (this.paymentMethod.find('.cmp-text').length > 0) {
41732        this.paymentMethod.find('.cmp-text').text(method.toUpperCase() === 'CARD' ? 'Cartão de crédito' : 'Transferência bancária');
41733      } else {
41734        this.paymentMethod.text(method.toUpperCase() === 'CARD' ? 'Cartão de crédito' : 'Transferência bancária');
41735      }
41736
41737      if (this.installments.find('.cmp-text').length > 0) {
41738        this.installments.find('.cmp-text').text(installments);
41739      } else {
41740        this.installments.text(installments);
41741      }
41742
41743      if (this.datePayment.find('.cmp-text').length > 0) {
41744        this.datePayment.find('.cmp-text').text(DateFormatter.reverseDate(paymentDate));
41745      } else {
41746        this.datePayment.text(DateFormatter.reverseDate(paymentDate));
41747      }
41748
41749      this.installmentsInfo = this.checkout.installment;
41750      this.loadTicketValues(this.checkout.sales);
41751    }
41752  }, {
41753    key: 'loadPaymentBankInformations',
41754    value: function loadPaymentBankInformations() {
41755
41756      var checkoutPayment = this.checkout.payment.paymee;
41757      var beneficiary_account = checkoutPayment.instructions.beneficiary_account;
41758      var beneficiary_branch = checkoutPayment.instructions.beneficiary_branch;
41759      var beneficiary_name = checkoutPayment.instructions.beneficiary_name;
41760
41761      var bankName = checkoutPayment.instructions.chosen;
41762      var branch = checkoutPayment.shopper.bankDetails.branch;
41763      var account = checkoutPayment.shopper.bankDetails.account;
41764      var number = checkoutPayment.shopper.document.number;
41765
41766      var maxTime = new Date(this.checkout.payment.maxAge);
41767      var tzoffset = new Date().getTimezoneOffset() * 60000;
41768      var localISOTime = new Date(maxTime - tzoffset).toISOString().slice(0, -1);
41769
41770      var maxHour = DateFormatter.extractHour(localISOTime);
41771      var maxDate = DateFormatter.extractDate(localISOTime);
41772
41773      if (this.branch.find('.cmp-text').length > 0) this.branch.find('.cmp-text').text(branch); else this.branch.text(branch);
41774      if (this.account.find('.cmp-text').length > 0) this.account.find('.cmp-text').text(account); else this.account.text(account);
41775      if (this.documentUser.find('.cmp-text').length > 0) this.documentUser.find('.cmp-text').text(number); else this.documentUser.text(number);
41776      if (this.ourBranch.find('.cmp-text').length > 0) this.ourBranch.find('.cmp-text').text(beneficiary_branch); else this.ourBranch.text(beneficiary_branch);
41777      if (this.ourAccount.find('.cmp-text').length > 0) this.ourAccount.find('.cmp-text').text(beneficiary_account); else this.ourAccount.text(beneficiary_account);
41778      if (this.ourFavored.find('.cmp-text').length > 0) this.ourFavored.find('.cmp-text').text(beneficiary_name); else this.ourFavored.text(beneficiary_name);
41779      if (this.buyValue.find('.cmp-text').length > 0) this.buyValue.find('.cmp-text').text('R$ ' + Utils.formatPrice(this.getTotal(this.checkout.sales))); else this.buyValue.text('R$ ' + Utils.formatPrice(this.getTotal(this.checkout.sales)));
41780
41781      if (this.maxHour.find('.cmp-text').length > 0) {
41782        var strTemp = this.maxHour.find('.cmp-text').text();
41783        strTemp = strTemp.replace('${deadline}', ' ' + maxHour + ' de ' + DateFormatter.reverseDate(maxDate))
41784        this.maxHour.find('.cmp-text').text(strTemp);
41785      } else {
41786        this.maxHour.text(' ' + maxHour + ' de ' + DateFormatter.reverseDate(maxDate));
41787      }
41788
41789      var currentBankLogo = localStorage.getItem('bank-current-logo');
41790      if (currentBankLogo && currentBankLogo != null) {
41791        this.bankLogo.attr('src', currentBankLogo);
41792      } else {
41793        this.bankLogo.hide();
41794      }
41795
41796      var currentBankName = localStorage.getItem('bank-current-name');
41797      if (currentBankName && currentBankName != null) {
41798        this.bankLogo.attr('alt', 'alt ' + currentBankName);
41799        this.bankLogo.attr('title', 'title ' + currentBankName);
41800      }
41801    }
41802  }, {
41803    key: 'getTotal',
41804    value: function getTotal(sales) {
41805      var _this = this;
41806
41807      var insuranceChecked = sessionStorage.getItem('insuranceChecked');
41808      return sales.reduce(function (acc, sale) {
41809        return sale.amount + acc + (_this.convenienceFee ? sale.convenienceFee : 0) + (insuranceChecked === 'true' ? sale.optionalInsurance : 0);
41810      }, 0);
41811    }
41812  }, {
41813    key: 'getTotalConvenienceFee',
41814    value: function getTotalConvenienceFee(sales) {
41815      var total = 0;
41816      sales.forEach(function (sale) {
41817        total += sale.convenienceFee;
41818      });
41819      return total;
41820    }
41821  }, {
41822    key: 'loadTicketValues',
41823    value: function loadTicketValues(arr) {
41824      var tarifa = 0;
41825      var taxas = 0;
41826      var priceTotal = 0;
41827      var discount = 0;
41828      var insurance = 0;
41829      var convenienceFee = this.getTotalConvenienceFee(arr);
41830
41831      // Recupera o valor do sessionStorage
41832      var insuranceChecked = sessionStorage.getItem('insuranceChecked');
41833
41834      var ticketPassengerValues = arr.reduce(function (acc, elem) {
41835        if (elem.typeId === 1) return acc;
41836
41837        return acc = {
41838          'ticketsPrice': tarifa = tarifa + elem.tariff,
41839          'taxsPrice': taxas = taxas + elem.tax + elem.tollTax + elem.boardingFee + elem.insuranceTax + elem.otherTax,
41840          'convenienceFee': convenienceFee,
41841          'fullPrice': priceTotal = priceTotal + elem.amount,
41842          'discount': discount = discount + elem.voucherValue,
41843          'insurance': insurance += insuranceChecked === 'true' ? elem.optionalInsurance : 0
41844        };
41845      }, {});
41846
41847      var ticketsPrice = Utils.formatPrice(ticketPassengerValues.ticketsPrice);
41848      var taxsPrice = Utils.formatPrice(ticketPassengerValues.taxsPrice);
41849      var discountPrice = Utils.formatPrice(ticketPassengerValues.discount);
41850      var totalPrice = this.installmentsInfo ? Utils.formatPrice(this.installmentsInfo.totalAmountWithInterest + (ticketPassengerValues.discount && !this.checkout.sales[1] ? ticketPassengerValues.convenienceFee : 0)) : Utils.formatPrice(ticketPassengerValues.fullPrice + ticketPassengerValues.insurance + (this.convenienceFee ? ticketPassengerValues.convenienceFee : 0));
41851      var insurancePrice = Utils.formatPrice(ticketPassengerValues.insurance);
41852      var convenience = this.convenienceFee ? Utils.formatPrice(ticketPassengerValues.convenienceFee) : 0;
41853
41854      if (this.tripValue.find('.cmp-text').length > 0) {
41855        this.tripValue.find('.cmp-text').text('R$ ' + totalPrice);
41856      } else {
41857        this.tripValue.text('R$ ' + totalPrice);
41858      }
41859
41860      if (this.convenienceFee) {
41861        if (this.convenienceFeeValue.find('.cmp-text').length > 0) {
41862          this.convenienceFeeValue.find('.cmp-text').text('R$ ' + convenience);
41863        } else {
41864          this.convenienceFeeValue.text('R$ ' + convenience);
41865        }
41866      }
41867
41868      if (this.ticketsValue.find('.cmp-text').length > 0) {
41869        this.ticketsValue.find('.cmp-text').text('R$ ' + ticketsPrice);
41870      } else {
41871        this.ticketsValue.text('R$ ' + ticketsPrice);
41872      }
41873
41874      if (this.valueDiscount.find('.cmp-text').length > 0) {
41875        this.valueDiscount.find('.cmp-text').text('R$ ' + discountPrice);
41876      } else {
41877        this.valueDiscount.text('R$ ' + discountPrice);
41878      }
41879
41880      if (this.ticketsTaxs.find('.cmp-text').length > 0) {
41881        this.ticketsTaxs.find('.cmp-text').text((ticketPassengerValues.taxsPrice ? 'R$ ' + taxsPrice : '-') + ' ');
41882      } else {
41883        this.ticketsTaxs.text((ticketPassengerValues.taxsPrice ? 'R$ ' + taxsPrice : '-') + ' ');
41884      }
41885
41886      if (insurancePrice == '0,00') {
41887        this.insuranceValue.closest('.item-description').remove();
41888      } else {
41889        if (this.insuranceValue.find('.cmp-text').length > 0) {
41890          this.insuranceValue.find('.cmp-text').text('R$ ' + insurancePrice);
41891        } else {
41892          this.insuranceValue.text('R$ ' + insurancePrice);
41893        }
41894      }
41895      if (this.installmentsInfo == undefined || this.installmentsInfo.interestAmount == 0) {
41896        this.interestValue.closest('.item-description').remove();
41897      } else {
41898        if (this.interestValue.find('.cmp-text').length > 0) {
41899          this.interestValue.find('.cmp-text').text('R$ ' + Utils.formatPrice(this.installmentsInfo.interestAmount));
41900        } else {
41901          this.interestValue.text('R$ ' + Utils.formatPrice(this.installmentsInfo.interestAmount));
41902        }
41903      }
41904
41905      if (this.repricingV2) this.handleRemarkCheckout();
41906    }
41907  }, {
41908    key: 'handleRemarkCheckout',
41909    value: function handleRemarkCheckout() {
41910      var balanceSum = 0;
41911      var penaltySum = 0;
41912      if (this.checkout.transactionExchangeModels) {
41913        balanceSum = this.checkout.transactionExchangeModels.reduce(function (acc, current) {
41914          return acc + current.balanceAmount;
41915        }, 0);
41916
41917        penaltySum = this.checkout.transactionExchangeModels.reduce(function (acc, current) {
41918          return acc + current.penaltyAmount;
41919        }, 0);
41920      }
41921
41922      var amount = this.installmentsInfo ? Utils.formatPrice(this.installmentsInfo.totalAmountWithInterest) : this.checkout.payment && !this.paymentNegative ? this.checkout.payment.result.amount : balanceSum;
41923
41924      var isNegative = Math.sign(amount) < 0;
41925      var totalBalance = 0;
41926
41927      isNegative ? totalBalance = amount : totalBalance = amount / 100;
41928
41929      $('[data-js="penalty-value"]').closest('.item-description-penalty').removeClass('d-none');
41930      $('[data-js="penalty-value"]').text('R$ ' + Utils.formatPrice(penaltySum));
41931
41932      $('[data-js="trip-value-balance"]').closest('.item-description-total-balance').removeClass('d-none');
41933      $('[data-js="trip-value-balance"]').text('R$ ' + Utils.formatPrice(totalBalance));
41934      $('.item-description-total').css({ 'text-decoration': 'line-through' });
41935    }
41936  }]);
41937
41938  return PaymentInformation;
41939}();
41940'use strict';
41941
41942var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
41943
41944function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
41945
41946var PasswordRecoveryWalletController = function () {
41947  function PasswordRecoveryWalletController($) {
41948    _classCallCheck(this, PasswordRecoveryWalletController);
41949
41950    this.emailInput = $('[data-js="input-email-recovery"]');
41951    this.submitButton = $('[data-js="button-password-recovery"]');
41952    this.init();
41953  }
41954
41955  _createClass(PasswordRecoveryWalletController, [{
41956    key: 'init',
41957    value: function init() {
41958      this.setupEventListeners();
41959    }
41960  }, {
41961    key: 'setupEventListeners',
41962    value: function setupEventListeners() {
41963      var _this = this;
41964
41965      this.emailInput.on('input', function () {
41966        var emailValue = _this.emailInput.val().trim();
41967        _this.submitButton.prop('disabled', emailValue === '');
41968      });
41969    }
41970  }]);
41971
41972  return PasswordRecoveryWalletController;
41973}();
41974'use strict';
41975
41976var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
41977
41978function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
41979
41980var PaymentTimer = function () {
41981  function PaymentTimer() {
41982    _classCallCheck(this, PaymentTimer);
41983
41984    this.checkout = SessionStorage.get('checkout');
41985    this.maxAge = new Date(this.checkout.maxAge);
41986    this.timerElement = $('[data-js="payment-timer"]');
41987    this.interval = null;
41988    this.init();
41989  }
41990
41991  _createClass(PaymentTimer, [{
41992    key: 'init',
41993    value: function init() {
41994      this.startCountdown();
41995    }
41996  }, {
41997    key: 'startCountdown',
41998    value: function startCountdown() {
41999      var _this = this;
42000
42001      var currentTime = new Date();
42002      var timeDifference = this.maxAge - currentTime;
42003
42004      if (timeDifference <= 0) {
42005        this.timerElement.text('Tempo esgotado');
42006        return;
42007      }
42008
42009      this.interval = setInterval(function () {
42010        var now = new Date();
42011        var remainingTime = _this.maxAge - now;
42012
42013        if (remainingTime <= 0) {
42014          clearInterval(_this.interval);
42015          _this.timerElement.text('Tempo esgotado');
42016        } else {
42017          var minutes = Math.floor(remainingTime % (1000 * 60 * 60) / (1000 * 60));
42018          var seconds = Math.floor(remainingTime % (1000 * 60) / 1000);
42019
42020          _this.timerElement.text(minutes + 'm ' + seconds + 's');
42021        }
42022      }, 1000);
42023    }
42024  }]);
42025
42026  return PaymentTimer;
42027}();
42028'use strict';
42029
42030var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
42031
42032function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
42033
42034var RegisterBenefitsController = function () {
42035  function RegisterBenefitsController($, callback) {
42036    var _this = this;
42037
42038    _classCallCheck(this, RegisterBenefitsController);
42039
42040    this.formData = SessionStorage.get("formData");
42041    this.formRegister = $('[data-js="register-benefits-form"]');
42042    this.inputName = $('[data-js="input-name"]');
42043    this.inputFatherName = $('[data-js="input-father-name"]');
42044    this.inputMotherName = $('[data-js="input-mother-name"]');
42045    this.inputDocType = $('[data-js="input-doc-type"]');
42046    this.inputCpfNumber = $('[data-js="input-cpf"]');
42047    this.email = $('[data-js="input-email"]');
42048    this.confEmail = $('[data-js="input-email-valid"]');
42049    this.inputRgNumber = $('[data-js="input-rg"]');
42050    this.inputEmissor = $('[data-js="input-emissor"]');
42051    this.inputCourseInit = $('[data-js="input-course-init"]');
42052    this.inputCourseEnd = $('[data-js="input-course-end"]');
42053    this.selectCourseCategory = $('[data-js="input-select-course-type"]');
42054    this.inputDdd = $('[data-js="input-ddd"]');
42055    this.inputPhone = $('[data-js="input-phone"]');
42056    this.inputZipCode = $('[data-js="input-zipcode"]');
42057    this.inputAddress = $('[data-js="input-address"]');
42058    this.inputNumber = $('[data-js="input-number"]');
42059    this.inputNeighborhood = $('[data-js="input-neighborhood"]');
42060    this.inputComplement = $('[data-js="input-complement"]');
42061    this.inputBlock = $('[data-js="input-block"]');
42062    this.inputCity = $('[data-js="input-city"]');
42063    this.inputCountry = $('[data-js="input-country"]');
42064    this.inputSelectState = $('[data-js="input-select-state"]');
42065    this.inputInstitution = $('[data-js="input-institution-name"]');
42066    this.inputInstitutionType = $('[data-js="input-institution-type"]');
42067    this.inputSubject = $('[data-js="input-subject"]');
42068    this.inputMEC = $('[data-js="input-mec-register"]');
42069    this.inputCourseName = $('[data-js="input-course-name"]');
42070    this.btnRegister = $('[data-js="button-register"]');
42071    this.errorMessage = $('[data-js="error-message"]');
42072    this.hasStepsInput = $('[data-js="has-steps"]');
42073    this.cpfInvalid = $('[data-js="msg-input-invalids"]').attr("data-cpf-invalid");
42074    this.emailInvalid = $('[data-js="msg-input-invalids"]').attr("data-email-invalid");
42075    this.documentInvalid = $('[data-js="msg-input-invalids"]').attr("data-doc-invalid");
42076    this.nameInvalid = $('[data-js="msg-input-invalids"]').attr("data-name-invalid");
42077    this.phoneInvalidSize = $('[data-js="msg-input-invalids"]').attr("data-phone-invalid");
42078    this.nameFatherInvalid = $('[data-js="msg-input-invalids"]').attr("data-father-name-invalid");
42079    this.nameMotherInvalid = $('[data-js="msg-input-invalids"]').attr("data-mother-name-invalid");
42080    this.btnFirstStepper = $('[data-js="btn-next-stepper-1"]');
42081    this.btnSecondStepper = $('[data-js="btn-next-stepper-2"]');
42082    this.btnThirdStepper = $('[data-js="btn-next-stepper-3"]');
42083    this.btnFourthStepper = $('[data-js="btn-next-stepper-4"]');
42084    this.isOnlyOneStepInputDesktop = $('[data-js="only-one-step-desktop"]');
42085    this.isOnlyOneStepInputMobile = $('[data-js="only-one-step-mobile"]');
42086    this.emptyFields = i18n("empty_fields");
42087    this.selectCustom = new SelectCustom($);
42088    this.isCPFValid = false;
42089    this.isInputNumberValid = false;
42090    this.emailValid = false;
42091    this.listDomain = [];
42092    this.isRGValid = false;
42093    this.isEmailRegistered = false;
42094    this.companySelect = '';
42095    this.registerSelect = '';
42096    this.clientTypeSelect = '';
42097
42098    new CheckboxController();
42099
42100    this.isFirstStepValid = false;
42101    this.isSecondStepValid = false;
42102    this.isThirdStepValid = false;
42103    this.isFourthStepValid = false;
42104    this.isExclusion = false;
42105
42106    this.init(callback);
42107  }
42108
42109  _createClass(RegisterBenefitsController, [{
42110    key: 'init',
42111    value: function init(callback) {
42112      var _this2 = this;
42113
42114      var passenger = SessionStorage.get('passenger');
42115
42116      if (!passenger) {
42117        if ((!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false')) {
42118          localStorage.setItem("referrer", $(location).attr('href'));
42119          $(location).attr('href', $('#loginPage').val());
42120        }
42121      }
42122
42123      this.getListEmailDomain(function () {
42124        _this2.handleStepsQuantity();
42125        _this2.handleProtocolForm();
42126        _this2.formRegister.disableAutoFill();
42127        _this2.loadMasks();
42128        _this2.enforceMaxLength();
42129        _this2.setEmailAutoComplete(_this2.email, _this2.listDomain.slice(0));
42130        _this2.listenForm();
42131        _this2.submitRegister();
42132        _this2.validationCaracterName();
42133        _this2.showSuccessMsg();
42134        _this2.prefillUserData();
42135        if (callback) callback();
42136      });
42137    }
42138  }, {
42139    key: 'verifySelectedFields',
42140    value: function verifySelectedFields() {
42141      var _this3 = this;
42142
42143      var tipoCliente = '';
42144      var empresa = '';
42145      var tipoCadastro = '';
42146
42147      var titleChooseTypeClient = $('[data-js="title-choose-type"]').val();
42148      var titleChooseAction = $('[data-js="title-choose-action"]').val();
42149      var titleChooseCompany = $('[data-js="title-choose-company"]').val();
42150
42151      var self = this;
42152
42153      $('#student-button').on('click', function () {
42154        $(".vertical-line").animate({ left: "100%" }, 400, function () {
42155          $(".container-stepper-register-type-form-student").removeClass("d-none");
42156          $(".selection-container").addClass("d-none");
42157          $(".title-register p.title").text(titleChooseAction);
42158          $(".student-fields").removeClass("d-none");
42159          $(".student-fields").prop("required", true);
42160          $(".teacher-fields").addClass("d-none");
42161          $(".teacher-fields input").removeAttr("required");
42162        });
42163        tipoCliente = 'Aluno';
42164      });
42165
42166      $('#teacher-button').on('click', function () {
42167        $(".vertical-line").animate({ left: "0%" }, 400, function () {
42168          $(".container-stepper-register-type-form-professor").removeClass("d-none");
42169          $(".selection-container").addClass("d-none");
42170          $(".title-register p.title").text(titleChooseAction);
42171          $(".teacher-fields").removeClass("d-none");
42172          $(".teacher-fields").prop("required", true);
42173          $(".student-fields").addClass("d-none");
42174          $(".student-fields input").removeAttr("required");
42175        });
42176        tipoCliente = 'Professor';
42177      });
42178
42179      $('#inclusao-prof-button').on('click', function () {
42180        $(".container-company").removeClass("d-none");
42181        $(".container-stepper-register-type-form-professor").addClass("d-none");
42182        $(".title-register p.title").text(titleChooseCompany);
42183        $(".register-fields").removeClass("d-none");
42184        $(".register-fields").prop("required", true);
42185        $(".update-fields").addClass("d-none");
42186        $(".update-fields input").removeAttr("required");
42187        $('[data-js="check-first"]').hide();
42188        $('[data-btnregister="first-btn"]').hide();
42189        this.isExclusion = false;
42190        tipoCadastro = 'Inclusão';
42191      });
42192
42193      $('#exclusao-prof-button').on('click', function () {
42194        $(".container-company").removeClass("d-none");
42195        $(".container-stepper-register-type-form-professor").addClass("d-none");
42196        $(".title-register p.title").text(titleChooseCompany);
42197        self.isExclusion = true;
42198        self.hideSteps();
42199        $('[data-js="container-stepper-2"]').removeClass("active");
42200        $('[data-js="container-stepper-3"]').removeClass("active");
42201        $('[data-js="container-stepper-4"]').removeClass("active");
42202        $('[data-js="container-stepper-5"]').removeClass("active");
42203        tipoCadastro = 'Exclusão';
42204      });
42205
42206      $('#renovacao-prof-button').on('click', function () {
42207        $(".container-company").removeClass("d-none");
42208        $(".container-stepper-register-type-form-professor").addClass("d-none");
42209        $(".title-register p.title").text(titleChooseCompany);
42210        $(".update-fields").removeClass("d-none");
42211        $(".update-fields").prop("required", true);
42212        $(".register-fields").addClass("d-none");
42213        $(".register-fields input").removeAttr("required");
42214        $('[data-js="check-first"]').hide();
42215        $('[data-btnregister="first-btn"]').hide();
42216        this.isExclusion = false;
42217        tipoCadastro = 'Renovação';
42218      });
42219
42220      $('#inclusao-student-button').on('click', function () {
42221        $(".container-company").removeClass("d-none");
42222        $(".container-stepper-register-type-form-student").addClass("d-none");
42223        $(".title-register p.title").text(titleChooseCompany);
42224        $(".register-fields").removeClass("d-none");
42225        $(".register-fields").prop("required", true);
42226        $(".update-fields").addClass("d-none");
42227        $(".update-fields input").removeAttr("required");
42228        $('[data-js="check-first"]').hide();
42229        $('[data-btnregister="first-btn"]').hide();
42230        this.isExclusion = false;
42231        tipoCadastro = 'Inclusão';
42232      });
42233
42234      $('#exclusao-student-button').on('click', function () {
42235        $(".container-company").removeClass("d-none");
42236        $(".container-stepper-register-type-form-student").addClass("d-none");
42237        $(".title-register p.title").text(titleChooseCompany);
42238        self.isExclusion = true;
42239        $('[data-js="container-stepper-2"]').removeClass("active");
42240        $('[data-js="container-stepper-3"]').removeClass("active");
42241        $('[data-js="container-stepper-4"]').removeClass("active");
42242        $('[data-js="container-stepper-5"]').removeClass("active");
42243        tipoCadastro = 'Exclusão';
42244      });
42245
42246      $('#renovacao-student-button').on('click', function () {
42247        $(".container-company").removeClass("d-none");
42248        $(".container-stepper-register-type-form-student").addClass("d-none");
42249        $(".title-register p.title").text(titleChooseCompany);
42250        $(".update-fields").removeClass("d-none");
42251        $(".update-fields").prop("required", true);
42252        $(".register-fields").addClass("d-none");
42253        $(".register-fields input").removeAttr("required");
42254        $('[data-js="check-first"]').hide();
42255        $('[data-btnregister="first-btn"]').hide();
42256        tipoCadastro = 'Renovação';
42257      });
42258
42259      var cardButtons = document.querySelectorAll('.container-company .card-button');
42260      cardButtons.forEach(function (button) {
42261        button.addEventListener('click', function () {
42262          var buttonText = button.querySelector('.card-text p').textContent;
42263
42264          switch (buttonText) {
42265            case 'Cometa':
42266              $(".container-stepper-five").show();
42267              $(".title-register p.title").first().addClass("d-none");
42268              $(".title-register p.title").text(titleChooseTypeClient);
42269              $(".container-stepper-register-personal-data").removeClass("d-none");
42270              $(".editable-container").removeClass("d-none");
42271              $(".container-company").addClass("d-none");
42272              empresa = 'Cometa';
42273              self.isExclusion === true ? self.hideSteps() : _this3.btnFirstStepper.parent().removeClass("d-none");
42274              self.isExclusion === true ? self.handleBtnConfirmInFirstStep() : _this3.btnFirstStepper.parent().removeClass("d-none");
42275              self.isExclusion === true ? $('[data-js="check-first"]').show() : '';
42276              $('[data-js="stepper-1"]').addClass("active");
42277              $('[data-js="stepper-1"]').addClass("active");
42278              _this3.resetForm();
42279              var form = document.querySelector('[data-js="register-benefits-form"]');
42280              form.reset();
42281              self.prefillUserData();
42282              break;
42283            case 'Catarinense':
42284              $(".container-stepper-five").show();
42285              $(".title-register p.title").first().addClass("d-none");
42286              $(".title-register p.title").text(titleChooseTypeClient);
42287              $(".container-stepper-register-personal-data").removeClass("d-none");
42288              $(".editable-container").removeClass("d-none");
42289              $(".container-company").addClass("d-none");
42290              empresa = 'Catarinense';
42291              self.isExclusion === true ? self.hideSteps() : _this3.btnFirstStepper.parent().removeClass("d-none");
42292              self.isExclusion === true ? self.handleBtnConfirmInFirstStep() : _this3.btnFirstStepper.parent().removeClass("d-none");
42293              self.isExclusion === true ? $('[data-js="check-first"]').show() : '';
42294              _this3.resetForm();
42295              self.prefillUserData();
42296              break;
42297            case 'Rápido Ribeirão':
42298              $(".container-stepper-five").show();
42299              $(".title-register p.title").first().addClass("d-none");
42300              $(".title-register p.title").text(titleChooseTypeClient);
42301              $(".container-stepper-register-personal-data").removeClass("d-none");
42302              $(".editable-container").removeClass("d-none");
42303              $(".container-company").addClass("d-none");
42304              empresa = 'Rápido Ribeirão';
42305              self.isExclusion === true ? self.hideSteps() : _this3.btnFirstStepper.parent().removeClass("d-none");
42306              self.isExclusion === true ? self.handleBtnConfirmInFirstStep() : _this3.btnFirstStepper.parent().removeClass("d-none");
42307              self.isExclusion === true ? $('[data-js="check-first"]').show() : '';
42308              _this3.resetForm();
42309              self.prefillUserData();
42310              break;
42311          }
42312
42313          if (_this3.hasStepsInput.val() != 'true')
42314            $(".container-stepper-five").hide();
42315
42316          if ($('[data-js="modal-container-editable-form"]').val() != "true")
42317            $(".editable-container").addClass("d-none");
42318
42319          if (empresa && tipoCadastro && tipoCliente) {
42320            $('[data-js="beneficiario-form-value"]').text(tipoCliente);
42321            $('[data-js="modalidade-form-value"]').text(tipoCadastro);
42322            $('[data-js="viacao-form-value"]').text(empresa);
42323
42324            _this3.companySelect = empresa;
42325            _this3.registerSelect = tipoCadastro;
42326            _this3.clientTypeSelect = tipoCliente;
42327
42328            if (_this3.isOnlyOneStepDesktop() && !Utils.isMobile() || _this3.isOnlyOneStepMobile() && Utils.isMobile()) {
42329              $(".container-stepper-register-personal-data").removeClass("d-none");
42330              $('[data-js="container-stepper-2"]').addClass("active");
42331              $('[data-js="container-stepper-3"]').addClass("active");
42332              $('[data-js="container-stepper-4"]').addClass("active");
42333              $('[data-js="container-stepper-5"]').addClass("active");
42334            } else {
42335              $(".container-stepper-register-personal-data").removeClass("d-none");
42336            }
42337          } else {
42338            $(".container-stepper-register-personal-data").addClass("d-none");
42339          }
42340
42341          if (empresa === 'Catarinense' && (tipoCadastro === 'Renovação' || tipoCadastro === 'Inclusão') && tipoCliente === 'Aluno') {
42342            $('[data-js="input-local"]').closest('.g-0').addClass('d-none');
42343            $('[data-js="input-local"]').removeAttr("required");
42344          } else {
42345            $('[data-js="input-local"]').closest('.g-0').removeClass('d-none');
42346            $('[data-js="input-local"]').prop("required", true);
42347          }
42348        });
42349      });
42350    }
42351  }, {
42352    key: 'getListEmailDomain',
42353    value: function getListEmailDomain(callback) {
42354      var _this3 = this;
42355
42356      var url = '/content/jca/jcr:content.domains.json';
42357      $.getJSON(url).done(function (data) {
42358        _this3.listDomain = data.listaDominios;
42359        _this3.listDomain.sort(function (a, b) {
42360          if (a.dominio < b.dominio) return -1;
42361          if (a.dominio > b.dominio) return 1;
42362          return 0;
42363        });
42364        _this3.listDomain = _this3.listDomain.reduce(function (acc, el) {
42365          acc.push({
42366            value: el.dominio.indexOf("@") > -1 ? el.dominio : "@" + el.dominio,
42367            label: el.dominio.indexOf("@") > -1 ? el.dominio : "@" + el.dominio
42368          });
42369          return acc;
42370        }, []);
42371        if (callback) callback();
42372      }).fail(function (textStatus, jqXHR, error) {
42373        console.log(error);
42374        console.log(textStatus);
42375        if (callback) callback();
42376      });
42377    }
42378  }, {
42379    key: 'changeEmailList',
42380    value: function changeEmailList(value, list) {
42381      if (value.trim().length > 0) {
42382        list = list.reduce(function (acc, el) {
42383          var domain = el.value.split("@")[1];
42384          var login = value.indexOf("@") < 0 ? value : value.split("@")[0];
42385          acc.push({
42386            value: login.concat("@").concat(domain),
42387            label: login.concat("@").concat(domain)
42388          });
42389          return acc;
42390        }, []);
42391      }
42392      return list;
42393    }
42394  }, {
42395    key: 'setEmailAutoComplete',
42396    value: function setEmailAutoComplete(input, list) {
42397      var _this4 = this;
42398
42399      list = this.changeEmailList(input.val(), list);
42400      input.keyup(function (event) {
42401        var key = event.which || event.keyCode;
42402        if (Utils.keyIsDigit(key) || key === Utils.keyCodes.BACKSPACE) {
42403          list = _this4.changeEmailList(input.val(), list);
42404          _this4.restartAutoComplete(input, list);
42405          input.autocomplete("search", input.val());
42406        }
42407      });
42408    }
42409  }, {
42410    key: 'setInputOnFocusEvent',
42411    value: function setInputOnFocusEvent(input, list) {
42412      var _this5 = this;
42413
42414      input.off("focus");
42415      input.focus(function () {
42416        _this5.restartAutoComplete(input, list);
42417        input.autocomplete("search", input.val());
42418      });
42419    }
42420  }, {
42421    key: 'restartAutoComplete',
42422    value: function restartAutoComplete(input, list) {
42423      if (input.data("autocomplete")) input.autocomplete("destroy");
42424      input.autocomplete({
42425        minLenght: 0,
42426        source: list,
42427        select: function select(e, ui) {
42428          input.val(ui.item.label);
42429          return false;
42430        }
42431      });
42432      $(".ui-autocomplete").addClass("ui-autocomplete-email");
42433      this.setInputOnFocusEvent(input, list);
42434    }
42435  }, {
42436    key: 'loadMasks',
42437    value: function loadMasks() {
42438      var _this7 = this;
42439
42440      this.inputZipCode.mask("00000-000");
42441      this.inputDdd.mask("(00)");
42442
42443      this.inputCpfNumber.attr("type", "tel").attr("minlength", 14);
42444      this.inputCpfNumber.attr("type", "tel").attr("maxlength", 14);
42445      this.inputCpfNumber.mask("000.000.000-00");
42446
42447      this.inputCpfNumber.on("focusout", function () {
42448        _this7.isDocumentValid();
42449        $("input[required].first-stepper").trigger("keyup");
42450      });
42451
42452      this.email.add(this.confEmail).on('autocompleteclose focusout', function () {
42453        _this7.emailValid = FormFields.checkoutEmail(_this7.email.val(), _this7.email, _this7.emailInvalid);
42454      });
42455
42456      this.inputRgNumber.attr("maxlength", 12);
42457
42458      this.inputPhone.on("input", {
42459        self: this
42460      }, function (e) {
42461        var self = e.data.self;
42462        self.inputPhone.attr("disabled", false);
42463        self.inputDdd.attr("disabled", false);
42464        if ($(e.target).val().length <= 8) {
42465          self.inputPhone.mask("0000-0000");
42466        } else if ($(e.target).val().length > 8) {
42467          self.inputPhone.mask("00000-0000");
42468        }
42469      });
42470
42471      this.inputZipCode.on('focusout', function (e) {
42472        var zipCode = $(e.target).val();
42473        LoaderService.show();
42474        $.getJSON('https://viacep.com.br/ws/' + zipCode + '/json/').then(function (data) {
42475          LoaderService.hide();
42476          if (data.erro) {
42477            _this7.invalidFieldZipCode();
42478            return;
42479          }
42480
42481          _this7.completeInformationClientAddress(data);
42482          _this7.validFieldZipCode();
42483        }).catch(function (err) {
42484          LoaderService.hide();
42485          _this7.invalidFieldZipCode();
42486        });
42487      });
42488
42489      this.inputCourseInit.mask("00/0000");
42490      this.inputCourseEnd.mask("00/0000");
42491    }
42492  }, {
42493    key: 'enforceMaxLength',
42494    value: function enforceMaxLength() {
42495      var excludeFields = ['input-cpf', 'input-ddd', 'input-phone', 'input-email', 'input-course-init', 'input-course-end', 'input-zipcode'];
42496
42497      this.formRegister.find('input[maxlength]').each(function () {
42498        var fieldName = $(this).attr('data-js') || '';
42499        var maxLen = parseInt($(this).attr('maxlength'));
42500
42501        if (!maxLen || excludeFields.indexOf(fieldName) !== -1) return;
42502
42503        var $counter = $('<span class="char-counter">' + '0/' + maxLen + '</span>');
42504        $(this).closest('.input-container').append($counter);
42505
42506        var updateCounter = function () {
42507          var currentLen = $(this).val() ? $(this).val().length : 0;
42508          if (currentLen > maxLen) {
42509            $(this).val($(this).val().substring(0, maxLen));
42510            currentLen = maxLen;
42511          }
42512          $counter.text(currentLen + '/' + maxLen);
42513          if (currentLen >= maxLen) {
42514            $counter.addClass('limit-reached');
42515          } else {
42516            $counter.removeClass('limit-reached');
42517          }
42518        }.bind(this);
42519
42520        $(this).on('input paste keyup', updateCounter);
42521        updateCounter();
42522      });
42523    }
42524  }, {
42525    key: 'validateFieldMaxLength',
42526    value: function validateFieldMaxLength(input, value) {
42527      var maxLength = parseInt(input.attr('maxlength'));
42528      var $tip = input.parent().siblings().find('.tip');
42529
42530      input.val(value || '');
42531
42532      if (maxLength && value && value.length > maxLength) {
42533        this.addInvalidClass(input, 'O valor excede o limite de ' + maxLength + ' caracteres. Por favor, abrevie.', $tip);
42534        return false;
42535      }
42536
42537      this.removeInvalidClass(input, $tip);
42538      return true;
42539    }
42540  }, {
42541    key: 'prefillUserData',
42542    value: function prefillUserData() {
42543      var passenger = SessionStorage.get('passenger');
42544      if (!passenger) return;
42545
42546      var email = passenger._email || passenger.email || '';
42547      var cpf = passenger._cpf || passenger.cpf || '';
42548      var name = passenger._name || passenger.name || '';
42549
42550      if (email) {
42551        this.email.val(email);
42552        this.email.attr('readonly', true);
42553        this.email.addClass('locked-field');
42554      }
42555
42556      if (cpf) {
42557        var rawCpf = cpf.replace(/\D/g, '');
42558        this.inputCpfNumber.unmask();
42559        this.inputCpfNumber.val(rawCpf);
42560        this.inputCpfNumber.mask("000.000.000-00");
42561        this.inputCpfNumber.attr('readonly', true);
42562        this.inputCpfNumber.addClass('locked-field');
42563        this.isCPFValid = true;
42564      }
42565
42566      if (name) {
42567        this.inputName.val(name);
42568      }
42569    }
42570  }, {
42571    key: 'completeInformationClientAddress',
42572    value: function completeInformationClientAddress(data) {
42573      var neighborhood = $('[data-js="input-neighborhood"]');
42574      var city = $('[data-js="input-city"]');
42575      var uf = $('[data-js="input-select-state"]')[0];
42576      var location = $('[data-js="input-address"]');
42577      var stateName = Utils.verifiedState(data.uf);
42578
42579      var isNeighborhoodValid = this.validateFieldMaxLength(neighborhood, data.bairro);
42580      var isCityValid = this.validateFieldMaxLength(city, data.localidade);
42581      var isLocationValid = this.validateFieldMaxLength(location, data.logradouro);
42582
42583      this.selectCustom.selectDefault(uf, stateName);
42584
42585      if (!isNeighborhoodValid || !isCityValid || !isLocationValid) {
42586        this.isSecondStepValid = false;
42587        this.btnSecondStepper.removeClass("active").attr("disabled", true);
42588        $('[data-js="stepper-3"], [data-js="item-border-2"]').removeClass("active");
42589        this.changeRegisterButton();
42590      }
42591    }
42592  }, {
42593    key: 'transitionToNextStep',
42594    value: function transitionToNextStep(nextStepSelector) {
42595      var currentStep = $('.container-stepper-register.active');
42596      var nextStep = $(nextStepSelector);
42597
42598      currentStep.removeClass('active');
42599      currentStep.addClass('d-none');
42600
42601      nextStep.removeClass('d-none');
42602      nextStep.addClass('active');
42603    }
42604  }, {
42605    key: 'modalEditable',
42606    value: function modalEditable() {
42607      var _this8 = this;
42608
42609      if ($('[data-js="modal-container-editable-form"]').val() == "true") {
42610        new Modal($);
42611        ModalEditableForm.show();
42612      }
42613
42614      $('[data-js="modal-btn-editable"]').on('click', function () {
42615        _this8.resetFields();
42616      });
42617
42618      $('[data-js="modal-btn-cancel"]').on('click', function () {
42619        $('[data-js="modal-close"]').click();
42620      });
42621    }
42622  }, {
42623    key: 'listenForm',
42624    value: function listenForm() {
42625      var _this8 = this;
42626
42627      $(".container-stepper-five").hide();
42628
42629      this.verifySelectedFields();
42630
42631      this.modalEditable();
42632
42633      this.editableMessageSucess();
42634
42635      this.inputName.on("input", function () {
42636        _this8.validateNames(_this8.inputName, _this8.nameInvalid);
42637      });
42638
42639      this.inputPhone.on("input", function () {
42640        _this8.validateNumberPhone();
42641      });
42642
42643      this.inputFatherName.on("input", function () {
42644        _this8.validateNames(_this8.inputFatherName, _this8.nameFatherInvalid);
42645      });
42646
42647      this.inputMotherName.on("input", function () {
42648        _this8.validateNames(_this8.inputMotherName, _this8.nameMotherInvalid);
42649      });
42650
42651      this.inputCpfNumber.on("input", function (e) {
42652        var regex = new RegExp(/[!#$%¨&*¹²³ªº£¢¬\(\)\[\]\{\}_´`~;:°?*+,|=§@'"\/\\]+/g);
42653        _this8.inputCpfNumber.val(_this8.inputCpfNumber.val().replace(regex, ""));
42654      });
42655
42656      this.inputCpfNumber.on("input", function () {
42657        _this8.isCPFValid = false;
42658      });
42659
42660      this.email.on("input", function () {
42661        _this8.emailValid = false;
42662      });
42663
42664      this.inputCpfNumber.attr("type", "tel").attr("minlength", 14);
42665      this.inputCpfNumber.mask("000.000.000-00");
42666
42667      this.inputRgNumber.on("focusout", function () {
42668        _this8.isRgValid();
42669        $("input[required].first-stepper").trigger("keyup");
42670      });
42671
42672      this.inputEmissor.on("input", function (e) {
42673        var regex = new RegExp(/^[a-zA-Z0-9.\-/]+$/);
42674        var inputValue = _this8.inputEmissor.val();
42675        var regexTest = regex.test(inputValue);
42676        if (!regexTest) {
42677          var sanitizedValue = inputValue.replace(/[^a-zA-Z0-9.\-/]/g, "");
42678          _this8.inputEmissor.val(sanitizedValue);
42679        }
42680      });
42681
42682      this.inputCourseInit.on("focusout", function () {
42683        _this8.validateCourseDate(_this8.inputCourseInit);
42684        $("input[required].third-stepper").trigger("keyup");
42685      });
42686
42687      this.inputCourseEnd.on("focusout", function () {
42688        _this8.validateCourseDate(_this8.inputCourseEnd);
42689        $("input[required].third-stepper").trigger("keyup");
42690      });
42691
42692      this.formRegister.find("input[required]").keyup(function (e) {
42693        if ($(e.target).hasClass("invalid")) {
42694          $(e.target).removeClass("invalid");
42695        }
42696      });
42697
42698      this.formRegister.find(".select-selected").change(function (e) {
42699        if ($(e.target).hasClass("invalid")) {
42700          $(e.target).removeClass("invalid");
42701        }
42702      });
42703
42704      $(".first-stepper").on("autocompleteclose", function () {
42705        $("input[required].first-stepper").trigger("keyup");
42706      });
42707
42708      $(".second-stepper").on("autocompleteclose", function () {
42709        $("input[required].second-stepper").trigger("keyup");
42710      });
42711
42712      $("input[required].first-stepper").on("keyup", function (event) {
42713        var isEmptyInput = _this8.checkEmptyInput(".first-stepper");
42714
42715        if (isEmptyInput) {
42716          _this8.btnFirstStepper.add(_this8.btnSecondStepper).removeClass("active").attr("disabled", true);
42717          $('[data-js="stepper-2"], [data-js="item-border-1"], [data-js="stepper-3"], [data-js="item-border-2"], [data-js="stepper-4"], [data-js="item-border-3"], [data-js="stepper-5"], [data-js="item-border-4"]').removeClass("active");
42718          _this8.isFirstStepValid = false;
42719          return;
42720        }
42721
42722        var firstStepperValid = _this8.validateFirstStep();
42723
42724        if (firstStepperValid) {
42725          _this8.btnFirstStepper.addClass("active").attr("disabled", false);
42726          $('[data-js="item-border-1"]').addClass("active");
42727          var keyCode = event.keyCode || event.which;
42728          if (keyCode === Utils.keyCodes.ENTER) {
42729            $('[data-js="btn-next-stepper-1"]').click();
42730          }
42731          _this8.isFirstStepValid = true;
42732        } else {
42733          _this8.btnFirstStepper.add(_this8.btnSecondStepper).removeClass("active").attr("disabled", true);
42734          $('[data-js="stepper-2"], [data-js="item-border-1"], [data-js="stepper-3"], [data-js="item-border-2"], [data-js="stepper-4"], [data-js="item-border-3"], [data-js="stepper-5"], [data-js="item-border-4"]').removeClass("active");
42735          _this8.isFirstStepValid = false;
42736        }
42737
42738        _this8.changeRegisterButton();
42739      });
42740
42741      $('.zipcode-field').on("keyup input", function (event) {
42742        var isEmptyInput = false;
42743        var hasExceededMaxLength = false;
42744
42745        _this8.formRegister.find(".zipcode-field").each(function (_, el) {
42746          if (!$(el).val()) {
42747            isEmptyInput = true;
42748          }
42749          var maxLen = parseInt($(el).attr('maxlength'));
42750          if (maxLen && $(el).val() && $(el).val().length > maxLen) {
42751            hasExceededMaxLength = true;
42752          } else if (maxLen && $(el).val() && $(el).val().length <= maxLen) {
42753            var $tip = $(el).parent().siblings().find('.tip');
42754            _this8.removeInvalidClass($(el), $tip);
42755          }
42756        });
42757
42758        if (isEmptyInput || hasExceededMaxLength) {
42759          _this8.btnRegister.removeClass("active").attr("disabled", true);
42760          _this8.btnSecondStepper.removeClass("active").attr("disabled", true);
42761          $('[data-js="stepper-3"], [data-js="item-border-2"]').removeClass("active");
42762          _this8.isSecondStepValid = false;
42763          return;
42764        } else {
42765          _this8.btnSecondStepper.addClass("active").attr("disabled", false);
42766          $('[data-js="item-border-2"]').addClass("active");
42767          var keyCode = event.keyCode || event.which;
42768          if (keyCode === Utils.keyCodes.ENTER) {
42769            $('[data-js="btn-next-stepper-2"]').click();
42770          }
42771          _this8.isSecondStepValid = true;
42772        }
42773
42774        _this8.changeRegisterButton();
42775      });
42776
42777      this.selectCourseCategory.attr("required", "required");
42778
42779      this.selectCourseCategory.on("change", function () {
42780        $("input[required].third-stepper").trigger("keyup");
42781      });
42782
42783      $("input[required].third-stepper").on("keyup", function (event) {
42784        var isEmptyInput = _this8.checkEmptyInput(".third-stepper");
42785        var categoryValue = _this8.selectCourseCategory.val() === null || _this8.selectCourseCategory.val() === undefined ? '' : _this8.selectCourseCategory.val();
42786
42787        if (isEmptyInput || categoryValue === '') {
42788          _this8.btnRegister.removeClass("active").attr("disabled", true);
42789          _this8.btnThirdStepper.removeClass("active").attr("disabled", true);
42790          $('[data-js="stepper-4"], [data-js="item-border-3"],[data-js="stepper-5"], [data-js="item-border-4"]').removeClass("active");
42791          _this8.isThirdStepValid = false;
42792          return;
42793        } else {
42794          _this8.btnThirdStepper.addClass("active").attr("disabled", false);
42795          $('[data-js="item-border-3"]').addClass("active");
42796          var keyCode = event.keyCode || event.which;
42797          if (keyCode === Utils.keyCodes.ENTER) {
42798            $('[data-js="btn-next-stepper-3"]').click();
42799          }
42800          _this8.isThirdStepValid = true;
42801        }
42802
42803        _this8.changeRegisterButton();
42804      });
42805
42806      $("input[required].fourth-stepper").on("focusout", function (event) {
42807        var isEmptyInput = _this8.checkEmptyInput(".fourth-stepper");
42808
42809        if (isEmptyInput) {
42810          _this8.btnRegister.removeClass("active").attr("disabled", true);
42811          _this8.btnFourthStepper.removeClass("active").attr("disabled", true);
42812          $('[data-js="stepper-5"], [data-js="item-border-4"]').removeClass("active");
42813          _this8.isFourthStepValid = false;
42814          return;
42815        } else {
42816          _this8.btnFourthStepper.addClass("active").attr("disabled", false);
42817          $('[data-js="item-border-4"]').addClass("active");
42818          var keyCode = event.keyCode || event.which;
42819          if (keyCode === Utils.keyCodes.ENTER) {
42820            $('[data-js="btn-next-stepper-4"]').click();
42821          }
42822          _this8.isFourthStepValid = true;
42823        }
42824
42825        _this8.changeRegisterButton();
42826      });
42827
42828      $(".btn-next-stepper").on("click", function (e) {
42829        var stepperNumber = $(e.target).closest(".container-stepper-register").data("js").replace(/\D/g, "");
42830
42831        $('[data-js="container-stepper-' + stepperNumber + '"]').removeClass("active");
42832        $('[data-js="stepper-' + stepperNumber + '"]').removeClass("current");
42833        stepperNumber++;
42834        $('[data-js="stepper-' + stepperNumber + '"]').addClass("current").addClass("active");
42835        $('[data-js="container-stepper-' + stepperNumber + '"]').addClass("active");
42836        if (stepperNumber > 1) {
42837          $("input[required].second-stepper").trigger("keyup");
42838          $("input[required].third-stepper").trigger("keyup");
42839        }
42840      });
42841
42842      $(".link-stepper").on("click", function (e) {
42843        if (!$(e.target).hasClass("active")) {
42844          return;
42845        }
42846        $("html, body").animate({ scrollTop: $(window).scrollTop() }, "fast");
42847        var numberStepper = $(e.target).data("js").replace(/\D/g, "");
42848
42849        $(".item-stepper a").removeClass("current");
42850        $(".container-stepper-register").removeClass("active");
42851
42852        $('[data-js="stepper-' + numberStepper + '"]').addClass("current");
42853        $('[data-js="container-stepper-' + numberStepper + '"]').addClass("active");
42854      });
42855
42856      $('[data-js="terms-and-conditions-check"]').on("change", function () {
42857        var termsCheck = $('[data-js="terms-and-conditions-check"]');
42858
42859        if (termsCheck.prop("checked")) {
42860          termsCheck.prop("checked", true);
42861        } else {
42862          termsCheck.prop("checked", false);
42863        }
42864
42865        if (_this8.isFormValid()) {
42866          _this8.btnRegister.prop("disabled", false).addClass("active");
42867        } else {
42868          _this8.btnRegister.prop("disabled", true).removeClass("active");
42869        }
42870      });
42871
42872      if (!$(".link-stepper").hasClass("active") || $(".container-stepper-menu").is(":hidden")) {
42873        $('[data-js="input-name"], [data-js="input-birth"], [data-js="input-doc"], ' + '[data-js="input-email"], [data-js="input-email-valid"], ' + '[data-js="input-pass"], [data-js="input-pass-valid"], ' + '[data-js="input-ddd"], [data-js="input-phone"], [data-js="input-address"], ' + '[data-js="input-number"], [data-js="input-complement"], ' + '[data-js="input-block"], [data-js="input-city"], ' + '[data-js="input-country"], [data-js="input-recommendation-code"], ' + '[data-js="terms-and-conditions-check"], [data-js="newsletter-check"]').on("keyup", function (event) {
42874          var keyCode = event.keyCode || event.which;
42875          if (keyCode === Utils.keyCodes.ENTER && !_this8.btnRegister.is(":disabled")) {
42876            _this8.btnRegister.click();
42877          }
42878        });
42879      }
42880
42881      $('[data-js="select-residence-proof"]').on("change", function () {
42882        if ($('[data-js="select-residence-proof"]').val() === '3') {
42883          $('.residence-proof-type').removeClass('d-none');
42884          $('[data-js="register-file-1"]').prop('required', true);
42885        } else {
42886          $('.residence-proof-type').addClass('d-none');
42887          $('[data-js="register-file-1"]').prop('required', false);
42888        }
42889        _this8.validateAttachments();
42890      });
42891
42892      var _loop = function _loop(i) {
42893        $('[data-js="remove-attachment-' + i + '"]').click(function (e) {
42894          $('[data-js="register-file-' + i + '"]').val(null);
42895          _this8.validateAttachments();
42896          switch (i) {
42897            case 0:
42898              $('[data-js="register-file-label-' + i + '"]').text('Comprovante de residência');
42899              break;
42900            case 1:
42901              $('[data-js="register-file-label-' + i + '"]').text('Declaração do terceiro');
42902              break;
42903            case 2:
42904              $('[data-js="register-file-label-' + i + '"]').text('Documento RG');
42905              break;
42906            case 3:
42907              $('[data-js="register-file-label-' + i + '"]').text('Atestado de Matrícula Ano/Vigente');
42908              break;
42909            case 4:
42910              $('[data-js="register-file-label-' + i + '"]').text('Foto 3x4');
42911              break;
42912            case 5:
42913              $('[data-js="register-file-label-' + i + '"]').text('Diploma');
42914              break;
42915            case 6:
42916              $('[data-js="register-file-label-' + i + '"]').text('Atestado da Instituição que leciona');
42917              break;
42918            default:
42919              $('[data-js="register-file-label-' + i + '"]').text('Anexar arquivo');
42920              break;
42921          }
42922          $(e.currentTarget).addClass('d-none');
42923        });
42924
42925        $('[data-js="register-file-' + i + '"]').change(function (e) {
42926          var target = $(e.currentTarget);
42927          var reader = new FileReader();
42928          var files = target.prop('files');
42929          var file = null;
42930          var maxFileSize = 500000;
42931          $('[data-js="file-size-alert-' + i + '"]').hide();
42932
42933          if (files.length === 0) {
42934            $('[data-js="remove-attachment-' + i + '"]').click();
42935            $('[data-js="file-size-alert-' + i + '"]').fadeIn();
42936            return;
42937          } else {
42938            file = files[0];
42939          }
42940
42941          if (file.size > maxFileSize) {
42942            $('[data-js="remove-attachment-' + i + '"]').click();
42943            $('[data-js="file-size-alert-' + i + '"]').fadeIn();
42944            return;
42945          }
42946
42947          reader.readAsDataURL(file);
42948
42949          reader.onload = function () {
42950            $('[data-js="register-file-label-' + i + '"]').text(file.name);
42951            $('[data-js="remove-attachment-' + i + '"]').removeClass('d-none');
42952          };
42953
42954          reader.onerror = function (error) {
42955            console.log('Error: ', error);
42956          };
42957
42958          _this8.validateAttachments();
42959        });
42960      };
42961
42962      for (var i = 0; i < 7; i++) {
42963        _loop(i);
42964      }
42965
42966      $('.attachment-button').on('keypress', function (e) {
42967        var key = e.which || e.keyCode;
42968
42969        if (key == 13) {
42970          $('#register-file').focus().trigger('click');
42971        }
42972      });
42973    }
42974  }, {
42975    key: 'changeRegisterButton',
42976    value: function changeRegisterButton() {
42977      if (this.isAllStepsValid()) this.btnRegister.removeAttr("disabled").addClass("active"); else this.btnRegister.removeClass("active").attr("disabled", true);
42978    }
42979  }, {
42980    key: 'isAllStepsValid',
42981    value: function isAllStepsValid() {
42982      return this.isFirstStepValid && this.isSecondStepValid && this.isThirdStepValid && this.isFourthStepValid && this.validateAttachments() && $('[data-js="terms-and-conditions-check"]').is(':checked');
42983    }
42984  }, {
42985    key: 'handleProtocolForm',
42986    value: function handleProtocolForm() {
42987      var _this9 = this;
42988
42989      LoaderService.show();
42990      $.getJSON('/content/jca/jcr:content.protocol_fields.json').then(function (data) {
42991        _this9.protocolData = data;
42992        LoaderService.hide();
42993
42994        _this9.getOrigin();
42995      }).catch(function (err) {
42996        console.log(err);
42997        LoaderService.hide();
42998      });
42999    }
43000  }, {
43001    key: 'getOrigin',
43002    value: function getOrigin() {
43003      var _this10 = this;
43004
43005      var localidades = this.protocolData.selects.localidades;
43006
43007
43008      var parsedLocalidades = this.parseToAutoCompleteFormat(localidades);
43009      $('[data-js="input-origin"], [data-js="input-local"]').autocomplete({
43010        messages: {
43011          noResults: this.noResultMessage,
43012          results: function results(amount) {
43013            var singular = _this10.singleResultMessage;
43014            var protip = _this10.protip;
43015            if (amount == 1) return singular + " " + protip; else {
43016              var multipleResultMessage = _this10.multipleResultMessage.replace("#amount", amount);
43017              return multipleResultMessage + " " + protip;
43018            }
43019          }
43020        },
43021        minLength: 0,
43022        source: parsedLocalidades,
43023        select: function select(e, ui) {
43024          $(e.target).data("valid", ui.item.valid);
43025          $(e.target).val(ui.item.label);
43026          $(e.target).removeClass('invalid');
43027          if ($(e.target).data('js') === 'input-origin') _this10.getDestination(localidades, ui.item.label);
43028
43029          return false;
43030        },
43031        focus: function focus(e, ui) {
43032          return false;
43033        }
43034      }).blur(function (e) {
43035        if (!$(e.target).data("valid")) {
43036          _this10.addInvalidClassTripFields($(e.target)[0]);
43037          $(e.target).val('');
43038        }
43039      }).change(function (e) {
43040        var localLabel = void 0;
43041        var targetLabel = $(e.target).val().toUpperCase();
43042        var hasInJson = false;
43043
43044        parsedLocalidades.some(function (local, _) {
43045          localLabel = local.label.toUpperCase();
43046          if (targetLabel === localLabel) {
43047            hasInJson = targetLabel === localLabel;
43048            $(e.target).data("valid", local.valid);
43049            return true;
43050          }
43051        });
43052        if (!hasInJson) $(e.target).data("valid", null);
43053      }).focus(function (e) {
43054        var element = $(e.target);
43055        if (element.data("ui-autocomplete") && element.val().trim().length === 0) element.autocomplete("search", "");
43056      });
43057    }
43058  }, {
43059    key: 'getDestination',
43060    value: function getDestination(localidades, origin) {
43061      var _this11 = this;
43062
43063      var parsedLocalidades = this.parseToAutoCompleteFormat(localidades, origin);
43064      $('[data-js="input-dest"]').autocomplete({
43065        minLength: 0,
43066        source: parsedLocalidades,
43067        messages: {
43068          noResults: this.noResultMessage,
43069          results: function results(amount) {
43070            var singular = _this11.singleResultMessage;
43071            var protip = _this11.protip;
43072            if (amount == 1) return singular + " " + protip; else {
43073              var multipleResultMessage = _this11.multipleResultMessage.replace("#amount", amount);
43074              return multipleResultMessage + " " + protip;
43075            }
43076          }
43077        },
43078        select: function select(e, ui) {
43079          $(e.target).data("valid", ui.item.valid);
43080          $(e.target).val(ui.item.label);
43081          $(e.target).removeClass('invalid');
43082          return false;
43083        },
43084        focus: function focus(e, ui) {
43085          return false;
43086        }
43087      }).blur(function (e) {
43088        if (!$(e.target).data("valid")) {
43089          _this11.addInvalidClassTripFields($(e.target)[0]);
43090          $(e.target).val('');
43091        }
43092      }).change(function (e) {
43093        var localLabel = void 0;
43094        var targetLabel = $(e.target).val().toUpperCase();
43095        var hasInJson = false;
43096        parsedLocalidades.some(function (local, _) {
43097          localLabel = local.label.toUpperCase();
43098          if (targetLabel === localLabel) {
43099            hasInJson = targetLabel === localLabel;
43100            $(e.target).data("valid", local.valid);
43101            return true;
43102          }
43103        });
43104        if (!hasInJson) $(e.target).data("valid", null);
43105      }).focus(function (e) {
43106        var element = $(e.target);
43107        if (element.data("ui-autocomplete") && element.val().trim().length === 0) element.autocomplete("search", "");
43108      });
43109    }
43110  }, {
43111    key: 'addInvalidClassTripFields',
43112    value: function addInvalidClassTripFields(el, showTip) {
43113      if (el.nodeName === "SELECT") $(el).siblings('.select-selected').addClass('invalid'); else if ($(el).attr('required')) {
43114        $(el).addClass("invalid");
43115      }
43116      if (showTip && $(el).next().hasClass("tips")) {
43117        var $tips = $(el).next();
43118        $tips.find('.tip').show();
43119      }
43120    }
43121  }, {
43122    key: 'parseToAutoCompleteFormat',
43123    value: function parseToAutoCompleteFormat(array) {
43124      var origin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
43125
43126      return array.reduce(function (acc, el) {
43127        if (origin === el.value) return acc;
43128
43129        acc.push({
43130          "valid": el.valid,
43131          "label": el.value
43132        });
43133        return acc;
43134      }, []);
43135    }
43136  }, {
43137    key: 'isRgValid',
43138    value: function isRgValid() {
43139      var ignoreAlert = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
43140
43141      var rgNumber = this.inputRgNumber.val().replace(/[.]|[-]|[/]/g, "");
43142      var evaluation = true;
43143      var $tip = this.inputRgNumber.parent().siblings().find(".tip");
43144
43145      evaluation = rgNumber.length >= 4 ? true : false;
43146
43147      if (!evaluation) {
43148        this.isRGValid = false;
43149
43150        this.addInvalidClass(this.inputRgNumber, this.documentInvalid, $tip);
43151      } else {
43152        this.isRGValid = true;
43153        this.removeInvalidClass(this.inputRgNumber, $tip);
43154        $("input[required].first-stepper").trigger("keyup");
43155      }
43156
43157      return evaluation;
43158    }
43159  }, {
43160    key: 'validateNumberPhone',
43161    value: function validateNumberPhone() {
43162      var phoneNumber = $('#input-phone').val();
43163      var phoneNumberLength = phoneNumber.length;
43164      var $tip = this.inputPhone.parent().siblings().find(".tip");
43165
43166      if (phoneNumberLength < 9 || phoneNumberLength > 10) {
43167        this.addInvalidClass($('#input-phone'), this.phoneInvalidSize, $tip);
43168        this.isInputNumberValid = false;
43169      } else {
43170        this.removeInvalidClass($('#input-phone'), $tip);
43171        this.isInputNumberValid = true;
43172      }
43173    }
43174  }, {
43175    key: 'validateCourseDate',
43176    value: function validateCourseDate(field) {
43177      var inputValue = field.val();
43178      var regex = /^\d{2}\/\d{4}$/;
43179      var month = parseInt(inputValue.slice(0, 2));
43180      var year = parseInt(inputValue.slice(3));
43181      var $tip = field.parent().siblings().find(".tip");
43182      var evaluation = true;
43183
43184      evaluation = regex.test(inputValue);
43185
43186      if (!evaluation) {
43187        this.addInvalidClass(field, 'Por favor, preencha com o formato 00/0000.', $tip);
43188      } else if (evaluation && parseInt(month) < 1 || parseInt(month) > 12) {
43189        this.addInvalidClass(field, 'Mês inválido.', $tip);
43190      } else if (evaluation && parseInt(year) === 0) {
43191        this.addInvalidClass(field, 'Ano inválido.', $tip);
43192      } else {
43193        this.removeInvalidClass(field, $tip);
43194
43195        if (field.is(this.inputCourseEnd) && this.inputCourseInit.val()) {
43196          var isEndDateValid = this.validateCourseDateRange();
43197          if (!isEndDateValid) return false;
43198        }
43199
43200        $("input[required].third-stepper").trigger("keyup");
43201      }
43202
43203      return evaluation;
43204    }
43205  }, {
43206    key: 'validateCourseDateRange',
43207    value: function validateCourseDateRange() {
43208      var initValue = this.inputCourseInit.val();
43209      var endValue = this.inputCourseEnd.val();
43210      var regexDate = /^\d{2}\/\d{4}$/;
43211
43212      if (!regexDate.test(initValue) || !regexDate.test(endValue)) return true;
43213
43214      var initMonth = parseInt(initValue.slice(0, 2));
43215      var initYear = parseInt(initValue.slice(3));
43216      var endMonth = parseInt(endValue.slice(0, 2));
43217      var endYear = parseInt(endValue.slice(3));
43218      var $tipEnd = this.inputCourseEnd.parent().siblings().find(".tip");
43219
43220      if (endYear < initYear || endYear === initYear && endMonth < initMonth) {
43221        this.addInvalidClass(this.inputCourseEnd, 'A data de término não pode ser anterior à data de início.', $tipEnd);
43222        return false;
43223      }
43224
43225      this.removeInvalidClass(this.inputCourseEnd, $tipEnd);
43226      return true;
43227    }
43228  }, {
43229    key: 'termAndConditionsChecked',
43230    value: function termAndConditionsChecked() {
43231      var $termsAndConditionsCheckbox = $('[data-js="terms-and-conditions-check"');
43232      var isChecked = $termsAndConditionsCheckbox.attr("required");
43233
43234      if (isChecked) {
43235        return $termsAndConditionsCheckbox.is(":checked");
43236      } else {
43237        return true;
43238      }
43239    }
43240  }, {
43241    key: 'emptyField',
43242    value: function emptyField() {
43243      var allFieldsValid = true;
43244
43245      var self = this;
43246      this.formRegister.find("input[required], select[required]").each(function (idx, el) {
43247        var value = $(el).val() ? $(el).val() : "";
43248        if (self.isEmpty(value)) {
43249          self.addInvalidClass($(el));
43250          allFieldsValid = false;
43251        }
43252      });
43253
43254      return allFieldsValid;
43255    }
43256  }, {
43257    key: 'showSuccessMsg',
43258    value: function showSuccessMsg() {
43259      var formData = SessionStorage.get("formData");
43260
43261      if (formData) {
43262        $('[data-js="stepper-3"]').hide();
43263        $('[data-js="item-border-2"]').hide();
43264        $('[data-js="btn-next-stepper-2"]').hide();
43265        $('[data-js="check-second"]').hide();
43266        $(".list-stepper").addClass("active");
43267      }
43268    }
43269  }, {
43270    key: 'submitRegister',
43271    value: function submitRegister() {
43272      var _this13 = this;
43273
43274      this.btnRegister.click(function () {
43275        if (_this13.isFormValid()) {
43276          LoaderService.show();
43277          _this13.openBenefitsProcess();
43278        } else {
43279          Alert.show(i18n("inputfield_invalid"));
43280        }
43281      });
43282    }
43283  }, {
43284    key: 'handleStepsQuantity',
43285    value: function handleStepsQuantity() {
43286      if (this.isOnlyOneStepDesktop() && !Utils.isMobile()) {
43287        this.handleHasOnlyOneStep();
43288      } else if (this.isOnlyOneStepMobile() && Utils.isMobile()) {
43289        this.handleHasOnlyOneStep();
43290      } else {
43291        if (!this.hasSteps()) {
43292          this.hideSteps();
43293          this.handleBtnConfirmInFirstStep();
43294        } else {
43295          $('[data-btnregister="first-btn"]').hide();
43296          $('[data-js="check-first"]').hide();
43297        }
43298      }
43299    }
43300  }, {
43301    key: 'hideSteps',
43302    value: function hideSteps() {
43303      $('.container-stepper-five').hide();
43304    }
43305  }, {
43306    key: 'hasSteps',
43307    value: function hasSteps() {
43308      return this.hasStepsInput.val() == 'true' ? true : false;
43309    }
43310  }, {
43311    key: 'handleHasOnlyOneStep',
43312    value: function handleHasOnlyOneStep() {
43313      this.handleBtnConfirmInFirstStep();
43314      this.btnFirstStepper.parent().hide();
43315      this.btnSecondStepper.parent().hide();
43316      this.btnThirdStepper.parent().hide();
43317      this.btnFourthStepper.parent().hide();
43318      $(".container-stepper-five").hide();
43319
43320      $('[data-js="check-first"]').add($('[data-btnregister="first-btn"]')).addClass("d-none");
43321
43322      $(".register-container").addClass("is-only-one-step");
43323    }
43324  }, {
43325    key: 'handleBtnConfirmInFirstStep',
43326    value: function handleBtnConfirmInFirstStep() {
43327      this.btnFirstStepper.parent().addClass("d-none");
43328      $('[data-btnregister="first-btn"]').show();
43329    }
43330  }, {
43331    key: 'isOnlyOneStepDesktop',
43332    value: function isOnlyOneStepDesktop() {
43333      return this.isOnlyOneStepInputDesktop.val() == "true" ? true : false;
43334    }
43335  }, {
43336    key: 'isOnlyOneStepMobile',
43337    value: function isOnlyOneStepMobile() {
43338      return this.isOnlyOneStepInputMobile.val() == "true" ? true : false;
43339    }
43340  }, {
43341    key: 'removeScroll',
43342    value: function removeScroll(e) {
43343      if (Utils.getWindowSize() < 951) e.css("overflow", "hidden");
43344    }
43345  }, {
43346    key: 'validationCaracterName',
43347    value: function validationCaracterName() {
43348      var regex = /[^a-zA-Z\u00C0-\u00FF ]+/gi;
43349      this.inputName.on("input", function (e) {
43350        $(this).val($(this).val().replace(regex, ""));
43351      });
43352    }
43353  }, {
43354    key: 'validateNames',
43355    value: function validateNames(input, msg) {
43356      var name = input.val().trim();
43357      var $tip = input.parent().siblings().find(".tip");
43358      var isValidName = name.indexOf(" ") !== -1;
43359
43360      isValidName ? this.removeInvalidClass(input, $tip) : this.addInvalidClass(input, msg, $tip);
43361
43362      return isValidName;
43363    }
43364  }, {
43365    key: 'isDocumentValid',
43366    value: function isDocumentValid() {
43367      var ignoreAlert = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
43368
43369      var documentNumber = this.inputCpfNumber.val().replace(/[.]|[-]|[/]/g, "");
43370      var evaluation = true;
43371      var $tip = this.inputCpfNumber.parent().siblings().find(".tip");
43372
43373      evaluation = Utils.validateCPF(documentNumber);
43374
43375      if (!evaluation) {
43376        this.isCPFValid = false;
43377        this.addInvalidClass(this.inputCpfNumber, this.cpfInvalid, $tip);
43378      } else {
43379        this.removeInvalidClass(this.inputCpfNumber, $tip);
43380        $("input[required].first-stepper").trigger("keyup");
43381        this.isCPFValid = true;
43382      }
43383
43384      return evaluation;
43385    }
43386  }, {
43387    key: 'openValidation',
43388    value: function openValidation(msg) {
43389      var _this15 = this;
43390
43391      data_layer.page.pageInfo.errorOnSignUp.message = msg;
43392
43393      var default_msg = '<p><label class="red">ERRO: </label> ' + msg + " </p>";
43394      if (msg !== null || msg !== "") {
43395        msg = default_msg;
43396      }
43397
43398      this.errorMessage.empty().append(msg);
43399      this.errorMessage.fadeIn();
43400
43401      data_layer.page.pageInfo.errorOnSignUp.happened = true;
43402
43403      this.formRegister.children().find("input, .select-custom").on("focusin", function () {
43404        _this15.errorMessage.fadeOut();
43405      });
43406    }
43407  }, {
43408    key: 'isSelectCustom',
43409    value: function isSelectCustom(el) {
43410      return $(el).attr("data-js") === "input-doc-type" || $(el).attr("data-js") === "input-phone-type";
43411    }
43412  }, {
43413    key: 'isEmpty',
43414    value: function isEmpty(value) {
43415      return value === null || value.trim() === "";
43416    }
43417  }, {
43418    key: 'addInvalidClass',
43419    value: function addInvalidClass(el, msg, tip) {
43420      var $links = el.parent().siblings().find(".link");
43421      if (!this.isSelectCustom(el)) $(el).addClass("invalid"); else $(el).siblings(".select-selected").addClass("invalid");
43422      if (tip && tip.hasClass("warning")) {
43423        if (msg) tip.text(msg);
43424        tip.fadeIn();
43425        $links.hide();
43426      }
43427    }
43428  }, {
43429    key: 'removeInvalidClass',
43430    value: function removeInvalidClass(el, tip) {
43431      var $links = el.parent().siblings().find(".link");
43432      if (!this.isSelectCustom(el)) $(el).removeClass("invalid"); else $(el).siblings(".select-selected").removeClass("invalid");
43433      if (tip && tip.hasClass("warning")) {
43434        tip.fadeOut();
43435        $links.show();
43436      }
43437    }
43438  }, {
43439    key: 'isFormValid',
43440    value: function isFormValid() {
43441      return this.isExclusion ? this.validateFirstStep() : this.emptyValidation() && this.specificValidation() && this.checkAnyInvalid() && this.validateCheckbox() && this.validateAttachments();
43442    }
43443  }, {
43444    key: 'validateCheckbox',
43445    value: function validateCheckbox() {
43446      if (this.termAndConditionsChecked()) {
43447        return true;
43448      } else {
43449        return false;
43450      }
43451    }
43452  }, {
43453    key: 'validateFirstStep',
43454    value: function validateFirstStep() {
43455      return this.isRGValid && this.isInputNumberValid && this.validateNames(this.inputName, this.nameInvalid) && this.validateNames(this.inputFatherName, this.nameFatherInvalid) && this.validateNames(this.inputMotherName, this.nameMotherInvalid);
43456    }
43457  }, {
43458    key: 'checkEmptyInput',
43459    value: function checkEmptyInput(classStepper) {
43460      var empty = false;
43461
43462      this.formRegister.find("input[required]" + classStepper + "").each(function (_, el) {
43463        if (!$(el).val()) {
43464          empty = true;
43465        }
43466      });
43467
43468      return empty;
43469    }
43470  }, {
43471    key: 'specificValidation',
43472    value: function specificValidation() {
43473      var _this16 = this;
43474
43475      var specificValidation = true;
43476      var self = this;
43477      this.formRegister.find("input[required]").each(function (idx, el) {
43478        switch ($(el).attr("data-js")) {
43479          case "input-name":
43480            specificValidation = _this16.validateNames(_this16.inputName, _this16.nameInvalid) && _this16.validateNames(_this16.inputFatherName, _this16.nameFatherInvalid) && _this16.validateNames(_this16.inputMotherName, _this16.nameMotherInvalid);
43481            break;
43482        }
43483        if (!specificValidation) return false; else self.removeInvalidClass($(el));
43484      });
43485      return specificValidation;
43486    }
43487  }, {
43488    key: 'resetFields',
43489    value: function resetFields() {
43490      this.isExclusion = false;
43491      $(".container-stepper-five").hide();
43492      $(".vertical-line").css("left", "");
43493      this.btnFirstStepper.parent().addClass("d-none");
43494      $('[data-btnregister="first-btn"]').hide();
43495      $('[data-js="check-first"]').hide();
43496      $(".title-register p.title").first().removeClass("d-none");
43497      $(".title-register p.title").text($('[data-js="title-choose-type"]').val());
43498      $(".selection-container").removeClass("d-none");
43499      $(".editable-container").addClass('d-none');
43500      $('[data-js="modal-close"]').click();
43501      $('[data-js="stepper-1"]').removeClass("active");
43502      $('[data-js="stepper-2"]').removeClass("active");
43503      $('[data-js="stepper-3"]').removeClass("active");
43504      $('[data-js="stepper-4"]').removeClass("active");
43505      $('[data-js="stepper-5"]').removeClass("active");
43506      $('[data-js="container-stepper-1"]').removeClass("active");
43507      $('[data-js="container-stepper-2"]').removeClass("active");
43508      $('[data-js="container-stepper-3"]').removeClass("active");
43509      $('[data-js="container-stepper-4"]').removeClass("active");
43510      $('[data-js="container-stepper-5"]').removeClass("active");
43511
43512      // Limpar os campos do formulário
43513      $('#register-file-0').val('');
43514      $('#register-file-1').val('');
43515      $('#register-file-2').val('');
43516      $('#register-file-3').val('');
43517      $('#register-file-4').val('');
43518      $('#register-file-5').val('');
43519      $('#register-file-6').val('');
43520
43521      // Remover a classe 'invalid' dos campos
43522      $('.attachment-button').removeClass('no-file-selected');
43523      $('input[type="file"]').removeClass('invalid');
43524
43525      // Remover a mensagem de erro
43526      $('.error-container').empty();
43527
43528      $('[data-js="btn-next-stepper-1"]').prop('disabled', true);
43529      $('[data-js="btn-next-stepper-1"]').removeClass('active');
43530    }
43531  }, {
43532    key: 'emptyValidation',
43533    value: function emptyValidation() {
43534      var allFieldsValid = true;
43535
43536      var self = this;
43537      var attachmentFields = this.formRegister.find("input[type='file'][required]");
43538
43539      attachmentFields.each(function (idx, el) {
43540        var value = $(el).val();
43541        if (!value) {
43542          self.addInvalidClass($(el));
43543          $(el).closest('.attachment-button').addClass('no-file-selected');
43544          allFieldsValid = false;
43545        } else {
43546          self.removeInvalidClass($(el));
43547          $(el).closest('.attachment-button').removeClass('no-file-selected');
43548        }
43549      });
43550
43551      attachmentFields.on('change', function () {
43552        self.emptyValidation();
43553      });
43554
43555      this.formRegister.find("input[required], select[required]").each(function (idx, el) {
43556        var value = $(el).val() ? $(el).val() : "";
43557        if (self.isEmpty(value)) {
43558          self.addInvalidClass($(el));
43559          allFieldsValid = false;
43560        } else {
43561          self.removeInvalidClass($(el));
43562        }
43563      });
43564
43565      if (!allFieldsValid || attachmentFields.length === 0) {
43566        this.openValidation(this.emptyFields);
43567      }
43568
43569      return allFieldsValid && attachmentFields.length > 0;
43570    }
43571  }, {
43572    key: 'validateAttachments',
43573    value: function validateAttachments() {
43574      var file = [];
43575      var totalFields = 4;
43576      for (var i = 0; i < 5; i++) {
43577        if (i === 1) {
43578          if (!$('.residence-proof-type').hasClass('d-none')) {
43579            file.push($('[data-js="register-file-' + i + '"]').prop('files')[0]);
43580            totalFields = 5;
43581          }
43582        }
43583
43584        if (!$('.teacher-fields').hasClass('d-none')) {
43585          totalFields = 6;
43586        }
43587
43588        if (!$('.teacher-fields').hasClass('d-none') && $('.register-fields').hasClass('d-none')) {
43589          totalFields = 4;
43590        } else if (!$('.teacher-fields').hasClass('d-none') && !$('.register-fields').hasClass('d-none')) {
43591          totalFields = 5;
43592        } else if (!$('.student-fields').hasClass('d-none') && $('.register-fields').hasClass('d-none')) {
43593          totalFields = 3;
43594        }
43595
43596        file.push($('[data-js="register-file-' + i + '"]').prop('files')[0]);
43597      }
43598
43599      if (file.length < totalFields) {
43600        return false;
43601      }
43602
43603      return true;
43604    }
43605  }, {
43606    key: 'checkAnyInvalid',
43607    value: function checkAnyInvalid() {
43608      var allFieldsValid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
43609
43610      if (this.formRegister.find("input.invalid[required]").length > 0) {
43611        allFieldsValid = false;
43612      }
43613      return allFieldsValid;
43614    }
43615  }, {
43616    key: 'invalidFieldZipCode',
43617    value: function invalidFieldZipCode() {
43618      var $tip = this.inputZipCode.parent().siblings().find('.tip');
43619      var cepMessage = $('[data-js="postal-code-message"]').val() ? $('[data-js="postal-code-message"]').val() : 'CEP Inválido';
43620    }
43621  }, {
43622    key: 'validFieldZipCode',
43623    value: function validFieldZipCode() {
43624      var $tip = this.inputZipCode.parent().siblings().find('.tip');
43625
43626      this.removeInvalidClass(this.inputZipCode);
43627      this.removeInvalidClass(this.inputZipCode, $tip);
43628    }
43629  }, {
43630    key: 'createAddressObject',
43631    value: function createAddressObject() {
43632      var address = new Address();
43633      address.street = this.inputAddress.val();
43634      address.zipCode = this.inputZipCode.val();
43635      address.complement = this.inputComplement.val();
43636      address.neighborhood = this.inputNeighborhood.val();
43637      address.city = this.inputCity.val();
43638      address.state = this.inputSelectState.val();
43639      address.number = this.inputNumber.val();
43640      return address;
43641    }
43642  }, {
43643    key: 'parseFormAttachmentRequest',
43644    value: function parseFormAttachmentRequest(file, fileBase64) {
43645      return {
43646        title: "Anexo JCA",
43647        PathOnClient: file.name,
43648        ContentLocation: "S",
43649        VersionData: fileBase64
43650      };
43651    }
43652  }, {
43653    key: 'openBenefitsProcess',
43654    value: function openBenefitsProcess() {
43655      var _this18 = this;
43656
43657      var baseUrl = $('#baseUrl').val();
43658      var clientid = $("#clientId").val();
43659      var accessToken = sessionStorage.getItem('access_token');
43660
43661      var createCase = function createCase() {
43662        var case_uri = targetConfig.EXT.endpoints.openProtocol;
43663
43664        var body = _this18.getFormParameters();
43665
43666        return $.ajax({
43667          type: 'POST',
43668          url: '' + (baseUrl + case_uri),
43669          headers: {
43670            'Access-Control-Allow-Origin': '*',
43671            'client_id': clientid,
43672            'access_token': accessToken
43673          },
43674          contentType: 'application/json',
43675          dataType: 'json',
43676          data: JSON.stringify(body)
43677        }).then(function (data) {
43678          return { caseId: data.result.id };
43679        });
43680      };
43681
43682      var getfileAttached = function getfileAttached(_ref2) {
43683        var caseId = _ref2.caseId;
43684
43685        return new Promise(function (resolve, reject) {
43686          var loadedFiles = [];
43687          var targets = [$('[data-js="register-file-0"]'), $('[data-js="register-file-1"]'), $('[data-js="register-file-2"]'), $('[data-js="register-file-3"]'), $('[data-js="register-file-4"]'), $('[data-js="register-file-5"]'), $('[data-js="register-file-6"]')];
43688
43689          var newTargets = targets.filter(function (item) {
43690            return item.val() !== "";
43691          });
43692
43693          newTargets.forEach(function (target, index) {
43694            var reader = new FileReader();
43695            reader.readAsDataURL(target.prop('files')[0]);
43696            var file = target.prop('files')[0];
43697
43698            reader.onload = function () {
43699              var fileBase64 = reader.result.replace(/[data:](\D*)?base64,/g, '');
43700              loadedFiles.push({ file: file, fileBase64: fileBase64, caseId: caseId });
43701              if (index === newTargets.length - 1) {
43702                resolve(loadedFiles);
43703              }
43704            };
43705
43706            reader.onerror = function (error) {
43707              return reject(error);
43708            };
43709          });
43710        });
43711      };
43712
43713      var createContentVersion = function createContentVersion(_ref3) {
43714        var files = [];
43715        var promises = _ref3.map(function (f, index) {
43716          var file = f.file;
43717          var fileBase64 = f.fileBase64;
43718          var caseId = f.caseId;
43719          var content_version_uri = targetConfig.EXT.endpoints.contentVersion;
43720
43721          var body = _this18.parseFormAttachmentRequest(file, fileBase64);
43722
43723          return $.ajax({
43724            type: 'POST',
43725            url: '' + (baseUrl + content_version_uri),
43726            headers: {
43727              'Access-Control-Allow-Origin': '*',
43728              'client_id': clientid,
43729              'access_token': accessToken
43730            },
43731            contentType: 'application/json',
43732            dataType: 'json',
43733            data: JSON.stringify(body)
43734          }).then(function (data) {
43735            files.push({ contentVersionId: data.result.id, caseId: caseId });
43736            if (index === _ref3.length - 1) return Promise.resolve(files);
43737          });
43738        });
43739
43740        return Promise.all(promises);
43741      };
43742
43743      var getContentDocumentId = function getContentDocumentId(_ref4) {
43744        var files = [];
43745        var newRef = _ref4.filter(function (item) {
43746          return item !== undefined;
43747        })[0];
43748        var promises = newRef.map(function (file, index) {
43749          var contentVersionId = file.contentVersionId,
43750            caseId = file.caseId;
43751          var content_version_uri = targetConfig.EXT.endpoints.contentVersion;
43752
43753          return $.ajax({
43754            type: 'GET',
43755            url: '' + (baseUrl + content_version_uri + '/' + contentVersionId),
43756            headers: {
43757              'Access-Control-Allow-Origin': '*',
43758              'client_id': clientid,
43759              'access_token': accessToken
43760            },
43761            contentType: 'application/json',
43762            dataType: 'json'
43763          }).then(function (data) {
43764            var contentDocumentId = data.result.records[0].contentDocumentId;
43765
43766            files.push({ contentDocumentId: contentDocumentId, caseId: caseId });
43767          });
43768        });
43769
43770        return Promise.all(promises).then(function () {
43771          return files;
43772        });
43773      };
43774
43775      var createContentDocumentLink = function createContentDocumentLink(_ref5) {
43776        var newRef = _ref5.filter(function (item) {
43777          return item !== undefined;
43778        });
43779
43780        var promises = newRef.map(function (file, index) {
43781          var contentDocumentId = file.contentDocumentId,
43782            caseId = file.caseId;
43783          var content_link_uri = targetConfig.EXT.endpoints.contentLink;
43784
43785          var body = _this18.parseContentDocumentLink(contentDocumentId, caseId);
43786
43787          return $.ajax({
43788            type: 'POST',
43789            url: '' + (baseUrl + content_link_uri),
43790            headers: {
43791              'Access-Control-Allow-Origin': '*',
43792              'client_id': clientid,
43793              'access_token': accessToken
43794            },
43795            contentType: 'application/json',
43796            dataType: 'json',
43797            data: JSON.stringify(body)
43798          });
43799        });
43800
43801        return Promise.all(promises);
43802      };
43803
43804      var completeChain = function completeChain() {
43805        LoaderService.hide();
43806        _this18.showSuccessForm();
43807        _this18.resetForm();
43808        $('[data-js="protocol-file"]').val(null);
43809        $('[data-js="protocol-file-label"]').text('Anexar um arquivo');
43810        $('[data-js="remove-attachment"]').addClass('d-none');
43811      };
43812
43813      var handleErrors = function handleErrors(err) {
43814        LoaderService.hide();
43815        AlertConfirmation.show('', i18n('protocol_error'), true, false);
43816      };
43817
43818      if (this.registerSelect === 'Exclusão') {
43819        return createCase().then(completeChain).catch(handleErrors);
43820      }
43821
43822      return createCase() // Retorne a chamada do createCase para continuar a cadeia de promissas
43823        .then(getfileAttached).then(createContentVersion).then(getContentDocumentId).then(createContentDocumentLink).then(completeChain).catch(handleErrors);
43824    }
43825  }, {
43826    key: 'parseContentDocumentLink',
43827    value: function parseContentDocumentLink(contentDocumentId, caseId) {
43828      return {
43829        ContentDocumentId: contentDocumentId,
43830        LinkedEntityId: caseId,
43831        Visibility: "AllUsers"
43832      };
43833    }
43834  }, {
43835    key: 'getFormParameters',
43836    value: function getFormParameters() {
43837      var payloadRequest = {
43838        Origin: "Web",
43839        RecordTypeId: $('[data-js="record-type-id"]').val(),
43840        NomeEmpresa: this.companySelect,
43841        Type: "Solicitação",
43842        Motivo: "Desconto Estudante/Professor",
43843        Assunto: this.clientTypeSelect,
43844        SubMotivo: this.registerSelect,
43845        CPF: this.inputCpfNumber.val().replace(/\D/g, ''),
43846        SuppliedName: this.inputName.val(),
43847        SuppliedPhone: '' + (this.inputDdd.val() + this.inputPhone.val().replace(/\D/g, '')),
43848        OrigemViagemWeb: $('[data-js="input-origin"]').val(),
43849        DestinoViagemWeb: $('[data-js="input-dest"]').val(),
43850        LocalFato: $('[data-js="input-local"]').val(),
43851        CompraRealizada: $('[data-js="terms-and-conditions-check"]').is(':checked') ? 'Sim' : 'Não',
43852        SuppliedEmail: $('[data-js="input-email"]').val(),
43853        RG: this.inputRgNumber.val(),
43854        IssuerBody: this.inputEmissor.val(),
43855        DadName: this.inputFatherName.val(),
43856        MomName: this.inputMotherName.val(),
43857        CEP: this.inputZipCode.val().replace(/\D/g, ''),
43858        HomeAddress: this.inputAddress.val(),
43859        HomeNumber: this.inputNumber.val(),
43860        Complement: this.inputComplement.val(),
43861        Neighborhood: this.inputNeighborhood.val(),
43862        City: this.inputCity.val(),
43863        State: this.inputSelectState.val(),
43864        InstitutionName: this.inputInstitution.val(),
43865        TypeInstitution: this.inputInstitutionType.val(),
43866        CoursePeriod: this.inputCourseInit.val() + '/' + this.inputCourseEnd.val(),
43867        CourseCategory: this.selectCourseCategory.next().text(),
43868        CourseName: this.inputCourseName.val(),
43869        SubjectTaught: this.inputSubject.val(),
43870        MECRegistrationNumber: this.inputMEC.val(),
43871        token: SessionStorage.get('jca_token')
43872      };
43873
43874      return payloadRequest;
43875    }
43876  }, {
43877    key: 'editableMessageSucess',
43878    value: function editableMessageSucess() {
43879      var titleElement = document.querySelector('h1.title-sucess-discount');
43880      var messageElement = document.querySelector('p.text-sucess-discount');
43881      var titleInput = $('[data-js="sucess-editable-message-title"]').val();
43882      var textInput = $('[data-js="sucess-editable-message-message"]').val();
43883
43884      titleElement.textContent = titleInput;
43885      messageElement.textContent = textInput;
43886    }
43887  }, {
43888    key: 'showSuccessForm',
43889    value: function showSuccessForm() {
43890      $('[data-js="discount-sucess-message"]').removeClass('d-none');
43891      $(".container-stepper-register-personal-data").addClass("d-none");
43892      $(".editable-container").addClass("d-none");
43893      this.btnFirstStepper.parent().addClass("d-none");
43894      $('[data-btnregister="first-btn"]').hide();
43895      $('[data-js="check-first"]').hide();
43896      $('.container-stepper-five').hide();
43897
43898      $('[data-js="register-benefits-form"]').on('click', function () {
43899
43900        if ($('[data-js="redirect-page-sucess"]').val() != "")
43901          $(location).attr('href', $('[data-js="redirect-page-sucess"]').val());
43902        else
43903          $(location).attr('href', $('#homePagePath').val());
43904      });
43905
43906      this.editableMessageSucess();
43907    }
43908  }, {
43909    key: 'resetForm',
43910    value: function resetForm() {
43911      var _this18 = this;
43912
43913      $('[data-js="stepper-1"]').click();
43914      $('[data-js="stepper-2"]').removeClass('active');
43915      $('[data-js="form-contact-us"]').trigger('reset');
43916      $('[data-js="protocol-form"]').trigger('reset');
43917
43918      $('[data-js="protocol-form"], [data-js="form-contact-us"]').find(".select-custom").each(function (idx, el) {
43919        var select = $(el).children()[0];
43920        _this18.selectCustom.refreshSelect(select);
43921      });
43922
43923      $('input[type=radio]').prop('checked', false);
43924      $('input[type=radio]').siblings().removeClass('strong');
43925      $('[data-js="input-city"]').val('');
43926      $('[data-js="button-search"]').prop('disabled', true);
43927
43928      this.agenciesSearch = [];
43929    }
43930  }]);
43931
43932  return RegisterBenefitsController;
43933}();
43934'use strict';
43935
43936var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
43937
43938function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
43939
43940var RegisterController = function () {
43941  function RegisterController($, loginControllerRef, editData, callback) {
43942    var _this = this;
43943
43944    _classCallCheck(this, RegisterController);
43945
43946    this.formData = SessionStorage.get('formData');
43947    this.formRegister = $('[data-js="register-form"]');
43948    this.inputName = $('[data-js="input-name"]');
43949    this.inputDocType = $('[data-js="input-doc-type"]');
43950    this.inputDocNumber = $('[data-js="input-doc"]');
43951    this.inputBirth = $('[data-js="input-birth"]');
43952    this.inputEmail = $('[data-js="input-email"]');
43953    this.inputEmailValid = $('[data-js="input-email-valid"]');
43954    this.inputPass = $('[data-js="input-pass"]');
43955    this.inputPassValid = $('[data-js="input-pass-valid"]');
43956    this.inputPhoneType = $('[data-js="input-phone-type"]');
43957    this.inputFullPhone = $('[data-js="input-full-phone"]');
43958    this.inputDdd = $('[data-js="input-ddd"]');
43959    this.inputPhone = $('[data-js="input-phone"]');
43960    this.inputZipCode = $('[data-js="input-zipcode"]');
43961    this.inputAddress = $('[data-js="input-address"]');
43962    this.inputNumber = $('[data-js="input-number"]');
43963    this.inputNeighborhood = $('[data-js="input-neighborhood"]');
43964    this.inputComplement = $('[data-js="input-complement"]');
43965    this.inputBlock = $('[data-js="input-block"]');
43966    this.inputCity = $('[data-js="input-city"]');
43967    this.inputCountry = $('[data-js="input-country"]');
43968    this.inputSelectState = $('[data-js="input-select-state"]');
43969    this.btnRegister = $('[data-js="button-register"]');
43970    this.errorMessage = $('[data-js="error-message"]');
43971    this.hasThreeStepsInput = $('[data-js="has-three-steps"]');
43972    this.shouldEvaluate = $('[data-js="validate-document"]').val().trim().toLowerCase() == 'true';
43973    this.shouldShowDocumentAlert = $('[data-js="show-alert-document"]').val().trim().toLowerCase() == 'true';
43974    this.shouldBlockUserOnInvalidDoc = $('[data-js="block-user-invalid-document"]').val().trim().toLowerCase() == 'true';
43975    this.emailDistinct = $('[data-js="msg-input-invalids"]').attr('data-email-distinct');
43976    this.emailInvalid = $('[data-js="msg-input-invalids"]').attr('data-email-invalid');
43977    this.documentInvalid = $('[data-js="msg-input-invalids"]').attr('data-doc-invalid');
43978    this.documentNumberInvalid = $('[data-js="msg-input-invalids"]').attr('data-doc-invalid');
43979    this.documentDocBirthInvalid = $('[data-js="msg-input-invalids"]').attr('data-doc-birth-invalid');
43980    this.birthInvalid = $('[data-js="msg-input-invalids"]').attr('data-birth-invalid');
43981    this.passDistinct = $('[data-js="msg-input-invalids"]').attr('data-pass-distinct');
43982    this.passwordInvalid = $('[data-js="msg-input-invalids"]').attr('data-pass-invalid');
43983
43984    this.inputMsgValid = $('[data-js="msg-input-invalids"]').attr('data-valid-msg');
43985    this.inputMsgInvalid = $('[data-js="msg-input-invalids"]').attr('data-invalid-msg');
43986    this.inputMsgAcceptAll = $('[data-js="msg-input-invalids"]').attr('ddata-accept-msg');
43987    this.inputMsgUnknown = $('[data-js="msg-input-invalids"]').attr('data-unknown-msg');
43988
43989    this.msgPasswordFormatInvalid = $('[data-js="msg-input-invalids"]').attr('data-pass-invalid-format');
43990    this.nameInvalid = $('[data-js="msg-input-invalids"]').attr('data-name-invalid');
43991    this.minCaracteres = i18n('field_min_caracter');
43992    this.btnFirstStepper = $('[data-js="btn-next-stepper-1"]');
43993    this.btnSecondStepper = $('[data-js="btn-next-stepper-2"]');
43994    this.isOnlyOneStepInputDesktop = $('[data-js="only-one-step-desktop"]');
43995    this.isOnlyOneStepInputMobile = $('[data-js="only-one-step-mobile"]');
43996    this.btnRegisterGoogle = $('[data-js="btn-register-google"]');
43997    this.btnRegisterFacebook = $('[data-js="btn-register-facebook"]');
43998    this.btnRegisterApple = $('[data-js="btn-register-apple"]');
43999    this.emptyFields = $('[data-js="msg-input-invalids"]').attr('data-empty-fields') ? $('[data-js="msg-input-invalids"]').attr('data-empty-fields') : i18n('empty_fields');
44000    this.loginControllerRef = loginControllerRef;
44001    this.msgCPFExists = $('[data-js="msg-overlay"]').attr('data-cpf-exists');
44002    this.msgEmailExists = $('[data-js="msg-overlay"]').attr('data-email-exists');
44003    this.msgEmailAndCpfExists = $('[data-js="msg-overlay"]').attr('data-email-and-cpf-exists');
44004    this.msgDefault = $('[data-js="msg-overlay"]').attr('data-status-error');
44005    this.selectCustom = new SelectCustom($);
44006    this.captureScreen = new CapturePhoto($);
44007    this.loginButtonHeader = new LoginButtonHeader($);
44008    this.listDomain = [];
44009    this.isCPFValid = false;
44010    this.isEmailRegistered = false;
44011    this.iconShowPassword = $('[data-js="show-register-password"]');
44012    this.emailPrimaryStatus = null;
44013    this.emailSecondaryStatus = null;
44014    this.invalidEmailStatus = $('[data-js="invalid-email-status"]').attr('value');
44015
44016    new CheckboxController();
44017    if (editData) this.editData = editData;
44018
44019    HttpService.getAEM('time.json?cache=1').then(function (data) {
44020      _this.currentDate = new Date(data.result.time);
44021      _this.init(callback);
44022    }).catch(function () {
44023      _this.currentDate = DateFormatter.getValidDateFormat();
44024      _this.init(callback);
44025    });
44026  }
44027
44028  _createClass(RegisterController, [{
44029    key: 'init',
44030    value: function init(callback) {
44031      var _this2 = this;
44032
44033      this.getListEmailDomain(function () {
44034        _this2.handleStepsQuantity();
44035        if (_this2.formData && _this2.editData == null) $('body').find('.header-site').addClass('search-results-header');
44036
44037        _this2.formRegister.disableAutoFill();
44038        _this2.disableInputs();
44039        _this2.loadMasks();
44040        _this2.listenForm();
44041        _this2.submitRegister();
44042        _this2.handlePassword();
44043        _this2.setEmailAutoComplete(_this2.inputEmail, _this2.listDomain.slice(0));
44044        _this2.setEmailAutoComplete(_this2.inputEmailValid, _this2.listDomain.slice(0));
44045        _this2.setDocumentRequirement();
44046        _this2.preventingCopy();
44047        _this2.validationCaracterName();
44048        _this2.handleSocialRegister();
44049        if (callback) callback();
44050      });
44051    }
44052  }, {
44053    key: 'preventingCopy',
44054    value: function preventingCopy() {
44055      this.inputEmail.add(this.inputEmailValid).on('copy paste cut', function (e) {
44056        e.preventDefault();
44057      });
44058    }
44059  }, {
44060    key: 'setDocumentRequirement',
44061    value: function setDocumentRequirement() {
44062      if (this.shouldBlockUserOnInvalidDoc) {
44063        this.inputDocNumber.attr('required', 'required');
44064      } else {
44065        this.inputDocNumber.removeAttr('required');
44066      }
44067    }
44068  }, {
44069    key: 'handleGiroRequest',
44070    value: function handleGiroRequest() {
44071      var _this3 = this;
44072
44073      if (this.editData) return;
44074
44075      var giroRequestType = $('[data-js="giro-request"]').data('type');
44076
44077      $('[data-js="button-register-utp"]').off('click');
44078      $('[data-js="button-register-giro"]').off('click');
44079
44080      $('[data-js="button-register-utp"]').click(function () {
44081        var passenger = _this3.createPassengerObject();
44082        _this3.sendRegisterData(passenger , false);
44083      });
44084
44085      $('[data-js="button-register-giro"]').click(function () {
44086        var passenger = _this3.createPassengerObject();
44087        _this3.sendRegisterData(passenger, true);
44088      });
44089
44090      switch (giroRequestType) {
44091        case 1:
44092          $('[data-js="clube-giro-banner"]').hide();
44093          $('[data-js="clube-giro-checkbox-container"]').show();
44094          break;
44095        case 2:
44096          $('[data-js="clube-giro-banner"]').show();
44097          $('[data-js="clube-giro-checkbox-container"]').show();
44098          break;
44099        case 3:
44100          $('[data-js="clube-giro-checkbox-container"]').hide();
44101          $('[data-js="clube-giro-banner"]').hide();
44102          this.btnRegister.off('click');
44103
44104          this.btnRegister.on('click', function () {
44105            var cpfCadastradoGiro = SessionStorage.get("giroExistCpf");
44106            if (_this3.isFormValid()) {
44107              if (!cpfCadastradoGiro.exists) {
44108                var modalEl = document.getElementById('clube-giro-modal');
44109                var modalInstance = new bootstrap.Modal(modalEl);
44110                modalInstance.show();
44111              } else {
44112                var _modalEl = document.getElementById('clube-giro-modal');
44113                var _modalInstance = bootstrap.Modal.getInstance(_modalEl);
44114                _modalInstance.hide();
44115                LoaderService.show();
44116                $('[data-js="button-register-utp"]').trigger('click');
44117              }
44118            } else {
44119              Alert.show('Existe algum campo inválido.');
44120            }
44121          });
44122          break;
44123      }
44124    }
44125  }, {
44126    key: 'getListEmailDomain',
44127    value: function getListEmailDomain(callback) {
44128      var _this3 = this;
44129
44130      var url = '/content/jca/jcr:content.domains.json';
44131      $.getJSON(url).done(function (data) {
44132        _this3.listDomain = data.listaDominios;
44133        _this3.listDomain.sort(function (a, b) {
44134          if (a.dominio < b.dominio) return -1;
44135          if (a.dominio > b.dominio) return 1;
44136          return 0;
44137        });
44138        _this3.listDomain = _this3.listDomain.reduce(function (acc, el) {
44139          acc.push({
44140            "value": el.dominio.indexOf('@') > -1 ? el.dominio : '@' + el.dominio,
44141            "label": el.dominio.indexOf('@') > -1 ? el.dominio : '@' + el.dominio
44142          });
44143          return acc;
44144        }, []);
44145        if (callback) callback();
44146      }).fail(function (textStatus, jqXHR, error) {
44147        console.log(error);
44148        console.log(textStatus);
44149        if (callback) callback();
44150      });
44151    }
44152  }, {
44153    key: 'changeEmailList',
44154    value: function changeEmailList(value, list) {
44155      if (value.trim().length > 0) {
44156        list = list.reduce(function (acc, el) {
44157          var domain = el.value.split('@')[1];
44158          var login = value.indexOf('@') < 0 ? value : value.split('@')[0];
44159          acc.push({
44160            "value": login.concat('@').concat(domain),
44161            "label": login.concat('@').concat(domain)
44162          });
44163          return acc;
44164        }, []);
44165      }
44166      return list;
44167    }
44168  }, {
44169    key: 'setEmailAutoComplete',
44170    value: function setEmailAutoComplete(input, list) {
44171      var _this4 = this;
44172
44173      list = this.changeEmailList(input.val(), list);
44174      input.keyup(function (event) {
44175        var key = event.which || event.keyCode;
44176        if (Utils.keyIsDigit(key) || key === Utils.keyCodes.BACKSPACE) {
44177          list = _this4.changeEmailList(input.val(), list);
44178          _this4.restartAutoComplete(input, list);
44179          input.autocomplete("search", input.val());
44180        }
44181      });
44182    }
44183  }, {
44184    key: 'setInputOnFocusEvent',
44185    value: function setInputOnFocusEvent(input, list) {
44186      var _this5 = this;
44187
44188      input.off('focus');
44189      input.focus(function () {
44190        _this5.restartAutoComplete(input, list);
44191        input.autocomplete("search", input.val());
44192      });
44193    }
44194  }, {
44195    key: 'restartAutoComplete',
44196    value: function restartAutoComplete(input, list) {
44197      if (input.data("autocomplete")) input.autocomplete("destroy");
44198      input.autocomplete({
44199        minLenght: 0,
44200        source: list,
44201        select: function select(e, ui) {
44202          input.val(ui.item.label);
44203          return false;
44204        }
44205      });
44206      $('.ui-autocomplete').addClass('ui-autocomplete-email');
44207      this.setInputOnFocusEvent(input, list);
44208    }
44209  }, {
44210    key: 'getAuthHeaders',
44211    value: function getAuthHeaders(accessToken, clientId) {
44212      var headers = {
44213        Authorization: '' + SessionStorage.get("jca_token")
44214      };
44215      if (clientId && accessToken) {
44216        headers.client_id = clientId;
44217        headers.access_token = accessToken;
44218      }
44219      return headers;
44220    }
44221  }, {
44222    key: 'getClientId',
44223    value: function getClientId() {
44224      return $("#clientId").val();
44225    }
44226  }, {
44227    key: 'requestCPFRegistration',
44228    value: function requestCPFRegistration(cpf, callback) {
44229      var _this6 = this;
44230
44231      var $tips = this.inputDocNumber.parent().siblings().find('.tip');
44232      var registeredDoc = void 0;
44233      var clientId = this.getClientId();
44234      var accessToken = sessionStorage.getItem('access_token');
44235
44236      if (this.editData) {
44237        registeredDoc = SessionStorage.get('passenger')._documentNumber;
44238        if (cpf === registeredDoc) {
44239          this.documentTaken = false;
44240          $tips.each(function (_, tip) {
44241            _this6.removeInvalidClass(_this6.inputDocNumber, $(tip));
44242          });
44243        }
44244        if (callback) callback(); else return;
44245      }
44246
44247      if (cpf !== registeredDoc) {
44248        var parameters = { cpf: cpf };
44249
44250        LoaderService.show();
44251        var headers = { 'channel': Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform) };
44252
44253        return HttpService.get('getCPFRegistered?' + $.param(parameters), headers).then(function (data) {
44254          try {
44255            var giroUrl = $("#baseGiroUrl").val() + '/customer/v1/user/existcpf?cpf=' + cpf;
44256            return fetch(giroUrl, {
44257              method: "GET",
44258              headers: _this6.getAuthHeaders(accessToken, clientId)
44259            }).then(function (giroResponse) {
44260              if (!giroResponse.ok) {
44261                throw new Error("Erro HTTP " + giroResponse.status);
44262              }
44263              return giroResponse.json();
44264            }).then(function (giroData) {
44265              SessionStorage.set("giroExistCpf", {
44266                exists: giroData.exists || false
44267              });
44268            }).catch(function (error) {
44269              console.error("Erro ao consultar existcpf do Giro:", error);
44270              SessionStorage.set("giroExistCpf", {
44271                exists: false,
44272                error: true
44273              });
44274            }).finally(function () {
44275              LoaderService.hide();
44276
44277              if (data.exists) {
44278                callback(true);
44279              } else {
44280                callback(false);
44281              }
44282
44283              _this6.handleCheckboxGiro()
44284
44285              $("input[required].first-stepper").trigger("keyup");
44286            });
44287          } catch (error) {
44288            console.error("Erro inesperado:", error);
44289            LoaderService.hide();
44290            callback(false);
44291          }
44292        }).catch(function (err) {
44293          LoaderService.hide();
44294          console.log(err);
44295          callback(false);
44296        });
44297      }
44298    }
44299  }, {
44300    key: 'handleCheckboxGiro',
44301    value: function handleCheckboxGiro() {
44302        var giroExists = SessionStorage.get("giroExistCpf");
44303        var giroRequestType = $('[data-js="giro-request"]').data('type');
44304        if ( !giroExists.exists && ( giroRequestType == 1 || giroRequestType == 2))
44305          $('[data-js="clube-giro-checkbox-container"]').show();
44306        else
44307          $('[data-js="clube-giro-checkbox-container"]').hide();
44308    }
44309  }, {
44310    key: 'requestEmailRegistration',
44311    value: function requestEmailRegistration(email, callback) {
44312      var registeredEmail = '';
44313
44314      if (this.editData) {
44315        registeredEmail = SessionStorage.get('passenger')._email;
44316
44317        if (email.length < 6 || email === registeredEmail) callback(false);
44318      }
44319
44320      if (email !== registeredEmail) {
44321        var parameters = { email: email };
44322
44323        LoaderService.show();
44324        var headers = { 'channel': Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform) };
44325        HttpService.get("getEmailRegistered?" + $.param(parameters), headers).then(function (data) {
44326          LoaderService.hide();
44327
44328          if (data.exists) {
44329            callback(true);
44330          } else {
44331            callback(false);
44332          }
44333        }).catch(function (err) {
44334          LoaderService.hide();
44335          console.log(err);
44336          callback(false);
44337        });
44338      }
44339    }
44340  }, {
44341    key: 'handlePreviousRegister',
44342    value: function handlePreviousRegister() {
44343      var _this7 = this;
44344
44345      var inpDoc = this.inputDocNumber;
44346      var $tip = this.inputDocNumber.parent().siblings().find('.tip');
44347
44348      inpDoc.on('focusout', function (e) {
44349        var $component = $(e.target);
44350        var documento = $component.val().replace(/\D/g, '');
44351
44352        if (documento == '') {
44353          _this7.addInvalidClass(_this7.inputDocNumber, _this7.documentInvalid, $tip);
44354        } else {
44355          _this7.removeInvalidClass(_this7.inputDocNumber, $tip);
44356        }
44357      });
44358    }
44359  }, {
44360    key: 'requestDocumentValidation',
44361    value: function requestDocumentValidation(documento, callback) {
44362      var _this8 = this;
44363
44364      var $tips = this.inputDocNumber.parent().siblings().find('.tip');
44365      var registeredDoc = void 0;
44366      if (this.editData) {
44367        registeredDoc = SessionStorage.get('passenger')._documentNumber;
44368        if (documento === registeredDoc) {
44369          this.documentTaken = false;
44370          $tips.each(function (_, tip) {
44371            _this8.removeInvalidClass(_this8.inputDocNumber, $(tip));
44372          });
44373        }
44374        if (callback) callback(); else return;
44375      }
44376    }
44377  }, {
44378    key: 'handlePassword',
44379    value: function handlePassword() {
44380      var _this9 = this;
44381
44382      if (this.editData) {
44383        this.inputPass.attr('required', false);
44384        this.inputPassValid.attr('required', false);
44385        this.inputDocType.attr('disabled', true);
44386        this.inputDocNumber.attr('disabled', true);
44387        this.inputPass.on('change', function (e) {
44388          if ($(e.target).val().length > 0) {
44389            _this9.inputPassValid.attr('required', true);
44390          } else {
44391            _this9.inputPassValid.attr('required', false).removeClass('invalid');
44392          }
44393        });
44394
44395        this.inputPassValid.on('change', function (e) {
44396          if ($(e.target).val().length > 0) {
44397            _this9.inputPass.attr('required', true);
44398          } else {
44399            _this9.inputPass.attr('required', false).removeClass('invalid');
44400          }
44401        });
44402      }
44403    }
44404  }, {
44405    key: 'disableInputs',
44406    value: function disableInputs() {
44407      var activeIput = $('[data-js="hide-document-type-select"]').val();
44408      this.inputFullPhone.attr("disabled", true);
44409      if (activeIput == 'true') this.inputDocNumber.attr('disabled', false); else this.inputDocNumber.attr('disabled', true);
44410    }
44411  }, {
44412    key: 'loadMasks',
44413    value: function loadMasks() {
44414      var _this11 = this;
44415
44416      this.inputZipCode.mask("00000-000");
44417      this.inputFullPhone.mask("+55 (00) 00000-0000");
44418
44419      this.inputBirth.mask("AB/CD/E000", {
44420        translation: {
44421          A: {
44422            pattern: /[0-3]/
44423          },
44424          B: {
44425            pattern: /[0-9]/
44426          },
44427          C: {
44428            pattern: /[0-1]/
44429          },
44430          D: {
44431            pattern: /[0-9]/
44432          },
44433          E: {
44434            pattern: /[1-2]/
44435          }
44436        },
44437        onKeyPress: function onKeyPress(a, b, c, d) {
44438          if (!a) return;
44439          var m = a.match(/(\d{1})/g);
44440          if (!m) return;
44441          if (parseInt(m[0]) === 3) {
44442            d.translation.B.pattern = /[0-1]/;
44443          } else {
44444            d.translation.B.pattern = /[0-9]/;
44445          }
44446          if (parseInt(m[2]) == 1) {
44447            d.translation.D.pattern = /[0-2]/;
44448          } else {
44449            d.translation.D.pattern = /[0-9]/;
44450          }
44451          var temp_value = c.val();
44452          c.val("");
44453          c.unmask().mask("AB/CD/E000", d);
44454          c.val(temp_value);
44455        }
44456      }).keyup();
44457
44458      this.inputDocType.on("change", {
44459        self: this
44460      }, function (e) {
44461        var self = e.data.self;
44462        self.removeInvalidClass(self.inputDocType);
44463        if (!_this11.editData) self.inputDocNumber.attr("disabled", false);
44464        self.toggleBirthFieldByDocType($(e.target).val());
44465        switch ($(e.target).val()) {
44466          case "1":
44467            self.inputDocNumber.attr("type", "tel").attr("minlength", 14);
44468            self.inputDocNumber.attr("type", "tel").attr("maxlength", 14);
44469            self.inputDocNumber.mask("000.000.000-00");
44470            self.inputDocNumber.attr("placeholder", "CPF");
44471            break;
44472          case "2":
44473            self.inputDocNumber.attr("type", "tel").attr("minlength", 18);
44474            self.inputDocNumber.attr("type", "tel").attr("maxlength", 18);
44475            self.inputDocNumber.mask("00.000.000/0000-00");
44476            self.inputDocNumber.attr("placeholder", "CNPJ");
44477            break;
44478          case "3":
44479            self.inputDocNumber.attr("type", "text").attr("minlength", "");
44480            self.inputDocNumber.attr("type", "text").attr("maxlength", "");
44481            self.inputDocNumber.attr("placeholder", "PASSAPORTE");
44482            self.inputDocNumber.mask("A", {
44483              translation: {
44484                A: {
44485                  pattern: /[A-Za-z0-9]+/,
44486                  recursive: true
44487                }
44488              }
44489            });
44490          default:
44491            break;
44492        }
44493      });
44494
44495      this.inputPhoneType.on("change", { self: this }, function (e) {
44496        var self = e.data.self;
44497        self.removeInvalidClass(self.inputPhoneType);
44498        self.inputFullPhone.attr("disabled", false);
44499      });
44500    }
44501  }, {
44502    key: 'getinformationZipCode',
44503    value: function getinformationZipCode(zipcode) {
44504      var _this11 = this;
44505
44506      LoaderService.show();
44507      $.getJSON('https://viacep.com.br/ws/' + zipcode + '/json/').then(function (data) {
44508        LoaderService.hide();
44509        if (data.erro) {
44510          _this11.invalidFieldZipCode();
44511          return;
44512        }
44513
44514        _this11.completeInformationClientAddress(data);
44515        _this11.validFieldZipCode();
44516      }).catch(function (err) {
44517        LoaderService.hide();
44518        _this11.invalidFieldZipCode();
44519      });
44520    }
44521  }, {
44522    key: 'removeGiroRequest',
44523    value: function removeGiroRequest() {
44524      var _this13 = this;
44525
44526      $('[data-js="clube-giro-checkbox-container"]').hide();
44527      $('[data-js="clube-giro-banner"]').hide();
44528      this.btnRegister.unbind('click');
44529
44530      this.btnRegister.click(function () {
44531        var modalEl = document.getElementById('clube-giro-modal');
44532        var modalInstance = bootstrap.Modal.getInstance(modalEl);
44533        if (modalInstance) modalInstance.hide()
44534        LoaderService.show()
44535        var passenger = _this13.createPassengerObject();
44536        _this13.sendRegisterData(passenger);
44537      });
44538    }
44539  }, {
44540    key: 'completeInformationClientAddress',
44541    value: function completeInformationClientAddress(data) {
44542      var neighborhood = $('[data-js="input-neighborhood"]');
44543      var city = $('[data-js="input-city"]');
44544      var uf = $('[data-js="input-select-state"]')[0];
44545      var location = $('[data-js="input-address"]');
44546      var stateName = Utils.verifiedState(data.uf);
44547
44548      neighborhood.val(data.bairro);
44549      city.val(data.localidade);
44550      location.val(data.logradouro);
44551      this.selectCustom.selectDefault(uf, stateName);
44552    }
44553  }, {
44554    key: 'listenForm',
44555    value: function listenForm() {
44556      var _this14 = this;
44557
44558      this.inputName.on("input", function () {
44559        _this14.validateName();
44560      });
44561
44562      this.inputZipCode.on('focusout', function (e) {
44563        _this14.getinformationZipCode($(e.target).val());
44564      });
44565
44566      this.inputDocType.on('change', function (e) {
44567        $(e.target).val() == 1 ? _this14.handleGiroRequest() : _this14.removeGiroRequest();
44568      });
44569
44570      this.inputPass.on("input", function () {
44571        _this14.isPasswordValid();
44572      });
44573
44574      this.inputPassValid.on("keyup", function () {
44575        _this14.isPasswordValid();
44576      });
44577
44578      this.iconShowPassword.on("click", function (e) {
44579        $(e.target).toggleClass("active");
44580        $(e.target).hasClass("active") ? $(e.target).prev().attr("type", "text") : $(e.target).prev().attr("type", "password");
44581      });
44582
44583      this.formRegister.find("input[required]").keyup(function (e) {
44584        if ($(e.target).hasClass("invalid")) {
44585          $(e.target).removeClass("invalid");
44586        }
44587      });
44588
44589      this.inputFullPhone.on('input', function () {
44590        var value = $(this).val();
44591        if (!value.startsWith('+55')) {
44592          value = value.replace(/^\+*/, '');
44593          $(this).val('+55 ' + value);
44594        }
44595      });
44596
44597      this.inputDocNumber.on("input", function (e) {
44598        var regex = new RegExp(/[!#$%¨&*¹²³ªº£¢¬\(\)\[\]\{\}_´`~;:°?*+,\-|=§@'"\/\\]+/g);
44599        _this14.inputDocNumber.val(_this14.inputDocNumber.val().replace(regex, ""));
44600      });
44601
44602      this.inputDocNumber.on("focusout", function () {
44603        _this14.isDocumentValid();
44604        $("input[required].first-stepper").trigger("keyup");
44605      });
44606
44607      this.inputDocNumber.on("input", function () {
44608        _this14.isCPFValid = false;
44609      });
44610
44611      this.inputBirth.focusout(function () {
44612        var $tip = _this14.inputBirth.parent().siblings().find(".tip");
44613
44614        if (_this14.inputBirth.val().length < 0) {
44615          _this14.addInvalidClass(_this14.inputBirth, _this14.birthInvalid, $tip);
44616        } else {
44617          _this14.removeInvalidClass(_this14.inputBirth, $tip);
44618          _this14.isBirthValid();
44619        }
44620      });
44621
44622      this.formRegister.find(".select-selected").change(function (e) {
44623        if ($(e.target).hasClass("invalid")) {
44624          $(e.target).removeClass("invalid");
44625        }
44626      });
44627
44628      this.inputEmail.on("focusout", function (e) {
44629        e.preventDefault();
44630        var email = _this14.inputEmail.val().toLowerCase();
44631
44632        if (email) {
44633          _this14.checkoutEmail();
44634          $("input[required].first-stepper").trigger("keyup");
44635        }
44636      });
44637
44638      this.inputEmail.on("change", function (e) {
44639        e.preventDefault();
44640        _this14.isEmailRegistered = false;
44641      });
44642
44643      this.inputEmail.on("focusout", function (e) {
44644        if (!Utils.checkChar(e)) e.preventDefault();
44645
44646        $('[data-js="input-email"]').val($('[data-js="input-email"]').val().normalize("NFD").replace(/[\u0300-\u036f]/g, ""));
44647
44648        $('[data-js="input-email"]').val($('[data-js="input-email"]').val().replace(/ /g, ""));
44649      });
44650
44651      this.inputEmailValid.on("change", function (e) {
44652        if (!Utils.checkChar(e)) e.preventDefault();
44653
44654        $('[data-js="input-email-valid"]').val($('[data-js="input-email-valid"]').val().normalize("NFD").replace(/[\u0300-\u036f]/g, ""));
44655        $('[data-js="input-email-valid"]').val($('[data-js="input-email-valid"]').val().replace(/ /g, ""));
44656      });
44657
44658      this.inputEmailValid.add(this.inputEmail).focusout(function (e) {
44659        e.preventDefault();
44660
44661        var email = _this14.inputEmail.val().toLowerCase();
44662        var emailValid = _this14.inputEmailValid.val().toLowerCase();
44663        var $tip = _this14.inputEmailValid.parent().siblings().find(".tip");
44664        if (email !== emailValid && emailValid !== "") {
44665          _this14.addInvalidClass(_this14.inputEmail);
44666          _this14.addInvalidClass(_this14.inputEmailValid, _this14.emailDistinct, $tip);
44667        } else {
44668          _this14.removeInvalidClass(_this14.inputEmail);
44669          _this14.removeInvalidClass(_this14.inputEmailValid, $tip);
44670        }
44671      });
44672
44673      // Setting default select types
44674      var defaultDocTypeValue = $('[data-js="auto-select-document-type"]').val();
44675      if (defaultDocTypeValue) {
44676        var inputDocType = $('[data-js="input-doc-type"]')[0];
44677        this.selectCustom.selectDefault(inputDocType, defaultDocTypeValue);
44678        this.inputDocNumber.attr("disabled", false);
44679        switch (defaultDocTypeValue) {
44680          case "CPF":
44681            this.inputDocNumber.attr("type", "tel").attr("minlength", 14);
44682            this.inputDocNumber.mask("000.000.000-00");
44683            this.inputDocNumber.attr("placeholder", "CPF");
44684            this.handleGiroRequest();
44685            break;
44686          case "CNPJ":
44687            this.inputDocNumber.attr("type", "tel").attr("minlength", 18);
44688            this.inputDocNumber.mask("00.000.000/0000-00");
44689            this.inputDocNumber.attr("placeholder", "CNPJ");
44690            this.toggleBirthFieldByDocType("2");
44691            this.removeGiroRequest();
44692            break;
44693          case "PASSAPORTE":
44694            this.inputDocNumber.attr("type", "tel").attr("minlength", "");
44695            this.inputDocNumber.attr("placeholder", "PASSAPORTE");
44696            this.inputDocNumber.mask("A", {
44697              translation: {
44698                A: {
44699                  pattern: /[A-Za-z0-9]+/,
44700                  recursive: true
44701                }
44702              }
44703            });
44704            this.removeGiroRequest();
44705            break;
44706        }
44707      }
44708
44709      var defaultPhoneTypeValue = $('[data-js="auto-select-phone-type"]').val();
44710      if (defaultPhoneTypeValue) {
44711        var inputPhoneType = $('[data-js="input-phone-type"]')[0];
44712        this.selectCustom.selectDefault(inputPhoneType, defaultPhoneTypeValue);
44713        this.inputFullPhone.attr("disabled", false);
44714      }
44715
44716      var inputsToValidate = [this.inputFullPhone, this.inputName, this.inputDocNumber, this.inputBirth];
44717
44718      inputsToValidate.forEach(function (input) {
44719        input.on("blur", function () {
44720          var isValid = _this14.validateFirstStep();
44721          if (isValid) {
44722            _this14.btnFirstStepper.addClass("active").attr("disabled", false);
44723          } else {
44724            _this14.btnFirstStepper.removeClass("active").attr("disabled", true);
44725          }
44726        });
44727      });
44728
44729      $(".first-stepper").on("autocompleteclose", function () {
44730        $("input[required].first-stepper").trigger("keyup");
44731      });
44732
44733      $(".second-stepper").on("autocompleteclose", function () {
44734        $("input[required].second-stepper").trigger("keyup");
44735      });
44736
44737      $("input[required].first-stepper").on("keyup", function (event) {
44738        var isEmptyInput = _this14.checkEmptyInput(".first-stepper");
44739
44740        if (isEmptyInput) {
44741          _this14.btnFirstStepper.add(_this14.btnSecondStepper).removeClass("active").attr("disabled", true);
44742          $('[data-js="stepper-2"], [data-js="item-border-1"], [data-js="stepper-3"], [data-js="item-border-2"]').removeClass("active");
44743          return;
44744        }
44745
44746        var firstStepperValid = _this14.validateFirstStep();
44747
44748        if (firstStepperValid) {
44749          _this14.btnFirstStepper.addClass("active").attr("disabled", false);
44750          _this14.btnRegister.removeAttr("disabled").addClass("active");
44751          $('[data-js="item-border-1"]').addClass("active");
44752          var keyCode = event.keyCode || event.which;
44753          if (keyCode === Utils.keyCodes.ENTER) {
44754            $('[data-js="btn-next-stepper-1"]').click();
44755          }
44756        } else {
44757          _this14.btnRegister.removeClass("active").attr("disabled", true);
44758          _this14.btnFirstStepper.add(_this14.btnSecondStepper).removeClass("active").attr("disabled", true);
44759          $('[data-js="stepper-2"], [data-js="item-border-1"], [data-js="stepper-3"], [data-js="item-border-2"]').removeClass("active");
44760        }
44761      });
44762
44763      $("input[required].second-stepper").on("keyup", function (event) {
44764        var isEmptyInput = _this14.checkEmptyInput(".second-stepper");
44765
44766        if (isEmptyInput) {
44767          _this14.btnSecondStepper.removeClass("active").attr("disabled", true);
44768          $('[data-js="stepper-3"], [data-js="item-border-2"]').removeClass("active");
44769          return;
44770        } else {
44771          var secondStepperValid = _this14.validateSecondStep();
44772
44773          if (secondStepperValid) {
44774            _this14.btnSecondStepper.addClass("active").attr("disabled", false);
44775            $('[data-js="item-border-2"]').addClass("active");
44776            $('[data-js="terms-and-conditions-check"], [data-js="newsletter-check"]').trigger("change");
44777            var keyCode = event.keyCode || event.which;
44778            if (keyCode === Utils.keyCodes.ENTER) {
44779              $('[data-js="btn-next-stepper-2"]').click();
44780            }
44781          } else {
44782            _this14.btnRegister.removeClass("active").attr("disabled", true);
44783            _this14.btnSecondStepper.removeClass("active").attr("disabled", true);
44784            $('[data-js="stepper-3"], [data-js="item-border-2"]').removeClass("active");
44785          }
44786        }
44787      });
44788
44789      this.btnSecondStepper.on("click", function () {
44790        $('[data-js="terms-and-conditions-check"], [data-js="newsletter-check"]').trigger("change");
44791      });
44792
44793      $(".btn-next-stepper").on("click", function (e) {
44794        var stepperNumber = $(e.target).closest(".container-stepper-register").data("js").replace(/\D/g, "");
44795
44796        $('[data-js="container-stepper-' + stepperNumber + '"]').removeClass("active");
44797        $('[data-js="stepper-' + stepperNumber + '"]').removeClass("current");
44798        stepperNumber++;
44799        $('[data-js="stepper-' + stepperNumber + '"]').addClass("current").addClass("active");
44800        $('[data-js="container-stepper-' + stepperNumber + '"]').addClass("active");
44801        if (stepperNumber > 1) {
44802          $("input[required].second-stepper").trigger("keyup");
44803        }
44804      });
44805
44806      $(".link-stepper").on("click", function (e) {
44807        if (!$(e.target).hasClass("active")) {
44808          return;
44809        }
44810        $("html, body").animate({ scrollTop: $(window).scrollTop() }, "fast");
44811        var numberStepper = $(e.target).data("js").replace(/\D/g, "");
44812
44813        $(".item-stepper a").removeClass("current");
44814        $(".container-stepper-register").removeClass("active");
44815
44816        $('[data-js="stepper-' + numberStepper + '"]').addClass("current");
44817        $('[data-js="container-stepper-' + numberStepper + '"]').addClass("active");
44818      });
44819
44820      $('[data-js="close-register"]').on("click", function () {
44821        var passenger = SessionStorage.get("passenger");
44822
44823        if (!passenger) {
44824          window.history.back();
44825          return;
44826        }
44827
44828        if (_this14.formData) {
44829          $(location).attr('href', $('#searchResultPath').val());
44830        } else {
44831          window.history.back();
44832        }
44833      });
44834
44835      $(".newsletter-check").on("change", function (e) {
44836        var $el = $(e.currentTarget).data("js");
44837        var elementCheck = $('[data-js="' + $el + '"]');
44838
44839        elementCheck.attr("checked", !elementCheck.attr("checked"));
44840      });
44841
44842      $('[data-js="terms-and-conditions-check"]').on("change", function () {
44843        var termsCheck = $('[data-js="terms-and-conditions-check"]');
44844        if (!termsCheck.is(':visible')) {
44845          termsCheck.attr("checked", true);
44846        }
44847        if (_this14.isFormValid()) {
44848          _this14.btnRegister.attr("disabled", false).addClass("active");
44849        } else {
44850          _this14.btnRegister.attr("disabled", true).removeClass("active");
44851        }
44852      });
44853
44854      $('[data-js="newsletter-check"]').on("change", function () {
44855        if (_this14.isFormValid()) {
44856          _this14.btnRegister.attr("disabled", false).addClass("active");
44857        } else {
44858          _this14.btnRegister.attr("disabled", true).removeClass("active");
44859        }
44860      });
44861
44862      if (this.editData || !$(".link-stepper").hasClass("active") || $(".container-stepper-menu").is(":hidden")) {
44863        $('[data-js="input-name"], [data-js="input-birth"], [data-js="input-doc"], ' + '[data-js="input-email"], [data-js="input-email-valid"], ' + '[data-js="input-pass"], [data-js="input-pass-valid"], ' + '[data-js="input-ddd"], [data-js="input-phone"], [data-js="input-address"], ' + '[data-js="input-number"], [data-js="input-complement"], ' + '[data-js="input-block"], [data-js="input-city"], ' + '[data-js="input-country"], [data-js="input-recommendation-code"], ' + '[data-js="terms-and-conditions-check"], [data-js="newsletter-check"]').on("keyup", function (event) {
44864          var keyCode = event.keyCode || event.which;
44865          if (keyCode === Utils.keyCodes.ENTER && !_this14.btnRegister.is(":disabled")) {
44866            _this14.btnRegister.click();
44867          }
44868        });
44869      }
44870      var dataArray = ['[data-js=input-pass] ,[data-js=input-pass-valid]'];
44871      !Utils.quotesBlock(dataArray);
44872    }
44873  }, {
44874    key: 'validateCheckbox',
44875    value: function validateCheckbox() {
44876      if (this.termAndConditionsChecked() && this.newsletterChecked()) {
44877        return true;
44878      } else {
44879        return false;
44880      }
44881    }
44882  }, {
44883    key: 'newsletterChecked',
44884    value: function newsletterChecked() {
44885      var $newsletterCheckbox = $('[data-js="newsletter-check"]');
44886      var isChecked = $newsletterCheckbox.attr('required');
44887
44888      if (isChecked) {
44889        return $newsletterCheckbox.is(':checked');
44890      } else {
44891        return true;
44892      }
44893    }
44894  }, {
44895    key: 'termAndConditionsChecked',
44896    value: function termAndConditionsChecked() {
44897      var $termsAndConditionsCheckbox = $('[data-js="terms-and-conditions-check"');
44898      var isChecked = $termsAndConditionsCheckbox.attr('required');
44899
44900      if (isChecked) {
44901        return $termsAndConditionsCheckbox.is(':checked');
44902      } else {
44903        return true;
44904      }
44905    }
44906  }, {
44907    key: 'emptyField',
44908    value: function emptyField() {
44909      var allFieldsValid = true;
44910
44911      var self = this;
44912      this.formRegister.find('input[required], select[required]').each(function (idx, el) {
44913        var value = $(el).val() ? $(el).val() : '';
44914        if (self.isEmpty(value)) {
44915          self.addInvalidClass($(el));
44916          allFieldsValid = false;
44917        }
44918      });
44919
44920      return allFieldsValid;
44921    }
44922  }, {
44923    key: 'showSuccessMsg',
44924    value: function showSuccessMsg() {
44925      var formData = SessionStorage.get('formData');
44926      $('[data-js="stepper-3"]').hide();
44927      $('[data-js="item-border-2"]').hide();
44928      $('[data-js="btn-next-stepper-2"]').hide();
44929      if (!this.hasThreeSteps()) {
44930        $('[data-js="check-second"]').hide();
44931      };
44932      $(".list-stepper").addClass("active");
44933    }
44934  }, {
44935    key: 'checkoutEmail',
44936    value: function checkoutEmail() {
44937      var _this12 = this;
44938
44939      var $tip = this.inputEmail.parent().siblings().find(".tip");
44940      var email = this.inputEmail.val().toLowerCase();
44941
44942      if (!Utils.validEmail(email)) {
44943        this.addInvalidClass(this.inputEmail, i18n("email_invalid"), $tip);
44944        this.isEmailRegistered = false;
44945        return false;
44946      } else {
44947        this.requestEmailRegistration(email, function (isEmailRegister) {
44948          if (isEmailRegister) {
44949            // Custom AEM Message
44950            var emailExistMessage = $('[data-js="msg-status-return"]').attr('data-status-email-already-registred');
44951
44952            _this12.addInvalidClass(_this12.inputEmail, emailExistMessage, $tip);
44953            _this12.isEmailRegistered = false;
44954            return false;
44955          } else {
44956            _this12.removeInvalidClass(_this12.inputEmail, $tip);
44957            _this12.isEmailRegistered = true;
44958            if (_this12.isActiveBriteVerify()) _this12.checkBriteverifyEmail();
44959            return true;
44960          }
44961        });
44962      }
44963    }
44964  }, {
44965    key: 'isActiveBriteVerify',
44966    value: function isActiveBriteVerify() {
44967      return $('[data-js="briteverify-apply"]').data('value');
44968    }
44969  }, {
44970    key: 'submitRegister',
44971    value: function submitRegister() {
44972      var _this13 = this;
44973
44974      this.btnRegister.click(function () {
44975        if (_this13.isFormValid()) {
44976          var passenger = _this13.createPassengerObject();
44977
44978          _this13.registerPassenger(passenger);
44979        } else {
44980          Alert.show(i18n('inputfield_invalid'));
44981        }
44982      });
44983    }
44984  }, {
44985    key: 'registerPassenger',
44986    value: function registerPassenger(passenger) {
44987      LoaderService.show();
44988      var isUserLogged = SessionStorage.get('passenger');
44989      if (!isUserLogged) {
44990        this.sendRegisterData(passenger);
44991      } else {
44992        this.editData.sendEditData(passenger);
44993      }
44994    }
44995  }, {
44996    key: 'saveUserStorage',
44997    value: function saveUserStorage(data) {
44998      SessionStorage.set("passenger", this.parsePassenger(data));
44999    }
45000  }, {
45001    key: 'handleStepsQuantity',
45002    value: function handleStepsQuantity() {
45003      if (this.isOnlyOneStepDesktop() && !Utils.isMobile()) {
45004        this.handleHasOnlyOneStep();
45005      } else if (this.isOnlyOneStepMobile() && Utils.isMobile()) {
45006        this.handleHasOnlyOneStep();
45007      } else {
45008        if (!this.hasThreeSteps()) {
45009          this.hideThirdStep();
45010          this.handleBtnConfirmInSecondStep();
45011        } else {
45012          $('[data-btnregister="first-btn"]').hide();
45013          $('[data-js="check-first"]').hide();
45014        }
45015      }
45016    }
45017  }, {
45018    key: 'hideThirdStep',
45019    value: function hideThirdStep() {
45020      $('[data-js="item-border-2"], [data-js="stepper-3"]').addClass('d-none');
45021    }
45022  }, {
45023    key: 'hasThreeSteps',
45024    value: function hasThreeSteps() {
45025      return this.hasThreeStepsInput.val() == 'true' ? true : false;
45026    }
45027  }, {
45028    key: 'handleHasOnlyOneStep',
45029    value: function handleHasOnlyOneStep() {
45030      this.handleBtnConfirmInSecondStep();
45031      this.btnFirstStepper.parent().hide();
45032      $(".container-stepper-menu").hide();
45033      $('[data-js="container-stepper-2"]').addClass("active");
45034      $('[data-js="container-stepper-3"]').addClass("active");
45035
45036      if (this.hasThreeSteps())
45037        $('[data-js="check-first"]').add($('[data-btnregister="first-btn"]')).addClass("d-none");
45038
45039      $(".register-container").addClass("is-only-one-step");
45040      this.loginSocialConfigureWithOneStep();
45041    }
45042  }, {
45043    key: 'loginSocialConfigureWithOneStep',
45044    value: function loginSocialConfigureWithOneStep() {
45045      $('.login-social-wrapper').addClass('d-none');
45046      $('.login-social-with-one-step').removeClass('d-none');
45047    }
45048  }, {
45049    key: 'handleBtnConfirmInSecondStep',
45050    value: function handleBtnConfirmInSecondStep() {
45051      this.btnSecondStepper.parent().addClass('d-none');
45052      $('[data-btnregister="first-btn"]').removeClass('d-none');
45053    }
45054  }, {
45055    key: 'isOnlyOneStepDesktop',
45056    value: function isOnlyOneStepDesktop() {
45057      return this.isOnlyOneStepInputDesktop.val() == 'true' ? true : false;
45058    }
45059  }, {
45060    key: 'isOnlyOneStepMobile',
45061    value: function isOnlyOneStepMobile() {
45062      return this.isOnlyOneStepInputMobile.val() == 'true' ? true : false;
45063    }
45064  }, {
45065    key: 'removeScroll',
45066    value: function removeScroll(e) {
45067      if (Utils.getWindowSize() < 951) e.css('overflow', 'hidden');
45068    }
45069  }, {
45070    key: 'verifyRegistrationCampaign',
45071    value: function verifyRegistrationCampaign() {
45072
45073      var utm_campaign = SessionStorage.get('utm_campaign');
45074
45075      return utm_campaign ? utm_campaign : '';
45076    }
45077  }, {
45078    key: 'sendSignUpToAnalytics',
45079    value: function sendSignUpToAnalytics(passengerService, status, error) {
45080      var passenger = passengerService || {};
45081      var errorStatus = (error === null ? null : error.responseJSON.validations[0].message);
45082
45083      if (Object.keys(passenger).length > 0) {
45084        var firstName = passenger.name || null;
45085        var lastName = passenger.familyName || null;
45086        var fullPhone = passenger.areaCode && passenger.phone ? "+55" + passenger.areaCode + passenger.phone : null;
45087        var formData = SessionStorage.get('formData')
45088        var userData = null;
45089
45090        var address = {
45091          street: passenger.addresses[0] ? passenger.addresses[0].street : null,
45092          neighborhood: passenger.addresses[0] ? passenger.addresses[0].neighborhood : null,
45093          city: passenger.addresses[0] ? passenger.addresses[0].city : null,
45094          state: passenger.addresses[0] ? passenger.addresses[0].uf : null,
45095          country: "BR",
45096          zipcode: passenger.addresses[0] ? passenger.addresses[0].zipCode : null
45097        };
45098
45099        var userData = {
45100          user_id: passenger.id || null,
45101          phone: fullPhone || null,
45102          email: passenger.email || null,
45103          birthdate: passenger.birthDate || null,
45104          cpf: passenger.cpf || null,
45105          passport: null,
45106          cnpj: null,
45107          user_status: null,
45108          address: address
45109        };
45110      }
45111
45112      window.dataLayer = window.dataLayer || [];
45113      window.dataLayer.push({
45114        event: "sign_up",
45115        sales_origin: $("#siteName").val(),
45116        device: Utils.getDevice(),
45117        signup_origin: document.referrer.split('?')[0],
45118        status: status,
45119        sign_up_error: errorStatus,
45120        user_data: userData
45121      });
45122
45123    }
45124  }, {
45125    key: 'createPassengerBody',
45126    value: function createPassengerBody(passenger) {
45127      var body = passenger;
45128
45129      if (!this.profileIdToken) return body;
45130
45131      var getFieldSocial = function getFieldSocial(name) {
45132        return {
45133          'google': 'tokenGoogle',
45134          'apple': 'AppleTokenId',
45135          'facebook': 'FacebookTokenId'
45136        }[name];
45137      };
45138
45139      body.socialId = this.profileSocialId;
45140      body.socialType = this.profileSocialType;
45141      body['AppleNonce'] = '';
45142      body['FacebookTokenId'] = '';
45143      body['AppleTokenId'] = '';
45144      body['tokenGoogle'] = '';
45145
45146      var fieldSocial = getFieldSocial(this.profileSocialType);
45147      body[fieldSocial] = this.profileIdToken;
45148
45149      return body;
45150    }
45151  }, {
45152    key: 'sendRegisterData',
45153    value: function sendRegisterData(passenger) {
45154      var _this14 = this;
45155      var registerIntoClubeGiro = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
45156
45157      passenger.registrationCampaign = this.verifyRegistrationCampaign();
45158      var registerContainer = $(".register-wrapper");
45159      var headers = { 'channel': Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform) };
45160
45161      HttpService.post("registerUser", passenger.serviceJSON, headers).then(function (data) {
45162        LoaderService.hide();
45163        _this14.sendSignUpToAnalytics(data, "true", null);
45164        AlertConfirmation.showAEM('data-js="alert-successfully-registered"', true);
45165        $('.register-wrapper').addClass('successfully-registered');
45166        $('.register-wrapper').parent().addClass('successfully-registered');
45167        $('.register-container, .container-stepper-menu').hide();
45168        _this14.loginPassenger(passenger).then(function () {
45169          _this14.saveUserStorage(data);
45170          _this14.removeScroll(registerContainer);
45171
45172          if ($('[data-js="clube-giro-checkbox"]').is(':checked') || registerIntoClubeGiro) {
45173            delete passenger._validated;
45174            _this14.registerPassengerIntoCLubeGiro(passenger);
45175          } else {
45176            setTimeout(function () {
45177            $('.register-container, .container-stepper-menu').hide();
45178            _this14.showSuccessMsg();
45179            }, 300);
45180          }
45181        });
45182        // Analytics - Triggers an event when there is an success registration.
45183        if (typeof _satellite != "undefined") {
45184          _satellite.track('registration');
45185        }
45186      }).catch(function (error) {
45187        console.error(error);
45188        LoaderService.hide();
45189        _this14.sendSignUpToAnalytics({}, "false", error);
45190        _this14.handleErrorMessage(error);
45191
45192        // Analytics - Service Error Event
45193        _satellite.track('serviceError', {
45194          serviceType: 'registerUser',
45195          statusCode: error.status,
45196          messageError: error.responseJSON.validations.length > 0 ? 'INPUT VALIDATION ERROR' : error.responseJSON.message.toUpperCase()
45197        });
45198      });
45199    }
45200  }, {
45201    key: 'registerPassengerIntoCLubeGiro',
45202    value: function registerPassengerIntoCLubeGiro(passenger) {
45203      var _this15 = this;
45204      LoaderService.show();
45205
45206      passenger.registrationCampaign = 'giro-UTP';
45207      var baseGiroUrl = $("#baseGiroUrl").val();
45208
45209      var headersRequest = HttpService.getSessionGiro();
45210      var clientid = $("#clientId").val();
45211      var accessToken = sessionStorage.getItem('access_token');
45212
45213      return $.ajax({
45214        type: "POST",
45215        url: baseGiroUrl + '/customer-integration/v1/users',
45216        data: JSON.stringify(passenger.serviceJSON),
45217        dataType: 'json',
45218        contentType: "application/json",
45219        headers: {
45220          client_id: clientid,
45221          access_token: accessToken,
45222          Authorization: '' + SessionStorage.get("jca_token")
45223        }
45224      }).done(function () {
45225        LoaderService.hide();
45226        $(".register-container, .container-stepper-menu").hide();
45227        _this15.loginPassenger(passenger);
45228      }).fail(function (error) {
45229        LoaderService.hide();
45230        AlertConfirmation.show("", "", true, true);
45231      });
45232    }
45233  }, {
45234    key: 'handleErrorMessage',
45235    value: function handleErrorMessage(error) {
45236      var statusMailCpf = $('[data-js="msg-status-retun"]').attr('data-status-email-cpf-already-registred');
45237      var statusCpf = $('[data-js="msg-status-retun"]').attr('data-status-cpf-already-registred');
45238      var statusCnpj = $('[data-js="msg-status-retun"]').attr('data-status-cnpj-already-registred');
45239      var statusMail = $('[data-js="msg-status-retun"]').attr('data-status-email-already-registred');
45240      var statusGeneric = $('[data-js="msg-status-retun"]').attr('data-status-generic');
45241
45242      statusMailCpf = statusMailCpf ? statusMailCpf : 'CPF e email já cadastrado!';
45243      statusCpf = statusCpf ? statusCpf : 'CPF já cadastrado!';
45244      statusCpf = statusCpf ? statusCpf : 'CNPJ já cadastrado!';
45245      statusMail = statusMail ? statusMail : 'Email já cadastrado!';
45246      statusGeneric = statusGeneric ? statusGeneric : 'Houve um problema. Tente novamente.';
45247
45248      if (error.status != 400) {
45249        Alert.show('Houve uma falha na requisição. Tente novamente mais tarde.');
45250        return;
45251      }
45252
45253      var responseJSON = error.responseJSON;
45254      if (responseJSON && responseJSON.validations === null && responseJSON.value === null) {
45255        Alert.show(responseJSON.message || i18n("brite_unavailable_msg"));
45256        return;
45257      }
45258
45259      try {
45260        var message = error.responseJSON.validations.reduce(function (acc, item) {
45261          return acc += item.message + '</br>';
45262        }, '');
45263
45264        switch (true) {
45265          case message.includes('CPF') && message.includes('Email'):
45266            Alert.show(statusMailCpf);
45267            break;
45268          case message.includes('CPF'):
45269            Alert.show(statusCpf);
45270            break;
45271          case message.includes('Email'):
45272            Alert.show(statusMail);
45273            break;
45274          case message.includes('CNPJ'):
45275            Alert.show('CNPJ já cadastrado!');
45276            break;
45277          default:
45278            Alert.show(statusGeneric);
45279            break;
45280        }
45281      } catch (e) {
45282        Alert.show(statusGeneric);
45283      }
45284    }
45285  }, {
45286    key: 'loginPassenger',
45287    value: function loginPassenger(passenger) {
45288      var _this15 = this;
45289
45290      var body = { login: passenger.login, password: passenger.password };
45291
45292      LoaderService.show();
45293      var headers = { 'channel': Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform) };
45294      return HttpService.post("loginUser", body, headers).then(function (data) {
45295        LoaderService.hide();
45296        SessionStorage.set('jca_token', data.token);
45297        localStorage.setItem("logged", true);
45298        _this15.loginButtonHeader.toggleLoggedSections();
45299      }).catch(function () {
45300        LoaderService.hide();
45301        SessionStorage.remove('passenger');
45302        localStorage.setItem("logged", false);
45303        $(location).attr('href', $('#loginPage').val());
45304      });
45305    }
45306  }, {
45307    key: 'validationCaracterName',
45308    value: function validationCaracterName() {
45309      var regex = /[^a-zA-Z\u00C0-\u00FF ]+/ig;
45310      this.inputName.on("input", function (e) {
45311        $(this).val($(this).val().replace(regex, ""));
45312      });
45313    }
45314  }, {
45315    key: 'validateName',
45316    value: function validateName() {
45317      var name = this.inputName.val().trim();
45318      var $tip = this.inputName.parent().siblings().find('.tip');
45319      var isValidName = name.indexOf(' ') !== -1;
45320
45321      isValidName ? this.removeInvalidClass(this.inputName, $tip) : this.addInvalidClass(this.inputName, this.nameInvalid, $tip);
45322
45323      return isValidName;
45324    }
45325  }, {
45326    key: 'getReferredCode',
45327    value: function getReferredCode() {
45328      var codeRecommendation = $('[data-js="input-recommendation-code"]');
45329      var passenger = SessionStorage.get('passenger');
45330
45331      if (codeRecommendation.length > 0) {
45332        return codeRecommendation.val();
45333      } else {
45334        if (passenger) return passenger._referredCode; else return null;
45335      }
45336    }
45337  }, {
45338    key: 'createPassengerObject',
45339    value: function createPassengerObject() {
45340      var passenger = new Passenger();
45341      var docType = parseInt(this.inputDocType.val());
45342
45343      if (this.inputZipCode.val()) passenger.addresses = [this.createAddressObject()];
45344
45345      var fullPhoneValue = this.inputFullPhone.val();
45346      var phonePattern = /\+55 \((\d{2})\) (\d{5})-(\d{4})/;
45347      var match = fullPhoneValue.match(phonePattern);
45348
45349      if (match) {
45350        passenger.areaCode = match[1];
45351        passenger.phone = match[2] + match[3];
45352      }
45353      passenger.name = Utils.getFirstName(this.inputName.val());
45354      passenger.familyName = Utils.getFamilyName(this.inputName.val());
45355      passenger.login = passenger.cpf;
45356      passenger.password = this.inputPass.val();
45357      passenger.birthDate = docType == 2 ? null : DateFormatter.reverseDate(this.inputBirth.val());
45358      passenger.email = this.inputEmail.val();
45359      passenger.optin = true;
45360      passenger.validated = null;
45361      passenger.phoneType = parseInt(this.inputPhoneType.val());
45362      passenger.image = $('[data-js="capture-photo-cam-photo"]').attr('data-register') == 'true' ? $('[data-js="capture-photo-cam-photo"]').attr('src') : null;
45363      passenger.referredCode = this.getReferredCode();
45364      passenger.emailPrimaryStatus = this.emailPrimaryStatus;
45365      passenger.emailSecondaryStatus = this.emailSecondaryStatus;
45366
45367      if (docType == 1) {
45368        passenger.cpf = this.inputDocNumber.val().replace(/[.]|[-]|[/]/g, '');
45369        passenger.login = passenger.cpf;
45370      } else if (docType == 2) {
45371        passenger.cnpj = this.inputDocNumber.val().replace(/[.]|[-]|[/]/g, '');
45372        passenger.login = passenger.cnpj;
45373      } else if (docType == 3) {
45374        var passportValue = this.inputDocNumber.val().trim().toUpperCase();
45375
45376        passenger.passport = passportValue;
45377        passenger.login = passportValue;
45378      }
45379
45380      return passenger;
45381    }
45382  }, {
45383    key: 'parsePassenger',
45384    value: function parsePassenger(data) {
45385      var addresses = data.addresses.length > 0 ? Utils.parseAddress(data.addresses[0]) : null;
45386      var passenger = new Passenger();
45387      var document = this.handleDocTypePassengerSessionStorageLogin(data);
45388
45389      passenger.name = data.name + " " + data.familyName;
45390      passenger.login = data.cpf;
45391      passenger.image = data.image ? true : false;
45392      passenger.birthDate = data.birthDate != null ? DateFormatter.extractDate(data.birthDate) : null;
45393      passenger.email = data.email;
45394      passenger.cpf = data.cpf;
45395      passenger.cnpj = data.cnpj;
45396      passenger.passport = data.passport;
45397      passenger.documentNumber = document;
45398      passenger.optin = data.optin;
45399      passenger.areaCode = data.areaCode;
45400      passenger.phone = data.phone;
45401      passenger.phoneType = data.phoneType;
45402      passenger.id = data.id;
45403      passenger.referredCode = data.referredCode;
45404      passenger.addresses = addresses;
45405      passenger.validated = data.validated;
45406      return passenger;
45407    }
45408  }, {
45409    key: 'handleDocTypePassengerSessionStorageLogin',
45410    value: function handleDocTypePassengerSessionStorageLogin(data) {
45411      var docType = parseInt(this.inputDocType.val());
45412
45413      if (docType == 1) {
45414        return data.cpf;
45415      } else {
45416        return data.cnpj;
45417      }
45418    }
45419  }, {
45420    key: 'isPasswordValid',
45421    value: function isPasswordValid() {
45422      var password = this.inputPass.val();
45423      var confPassword = this.inputPassValid.val();
45424      var $tipPass = this.inputPass.parent().siblings().find('.tip');
45425      var $tipPassInvalid = this.inputPassValid.parent().siblings().find('.tip');
45426
45427      if (password.length > 0) {
45428        if (this.checkPasswordAlphanumeric()) {
45429
45430          if (!(password === confPassword) && confPassword.length > 0) {
45431            this.addInvalidClass(this.inputPass);
45432            if (password.length < 8) {
45433              this.addInvalidClass(this.inputPass, this.msgPasswordFormatInvalid, $tipPass);
45434            } else {
45435              this.addInvalidClass(this.inputPassValid, this.passDistinct, $tipPassInvalid);
45436            }
45437
45438            return false;
45439          } else if (password.length >= 8 && password.length <= 12) {
45440            this.removeInvalidClass(this.inputPassValid, $tipPassInvalid);
45441            this.removeInvalidClass(this.inputPass, $tipPass);
45442            return true;
45443          } else if (password.length < 8) {
45444            this.addInvalidClass(this.inputPass, this.msgPasswordFormatInvalid, $tipPass);
45445          }
45446        } else {
45447          this.addInvalidClass(this.inputPass, this.msgPasswordFormatInvalid, $tipPass);
45448          return false;
45449        }
45450      }
45451    }
45452  }, {
45453    key: 'checkPasswordAlphanumeric',
45454    value: function checkPasswordAlphanumeric() {
45455      var passwordFormatRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9@$!%*#?&]{8,}$/;
45456
45457      return passwordFormatRegex.test(this.inputPass.val());
45458    }
45459  }, {
45460    key: 'isEmailValid',
45461    value: function isEmailValid() {
45462      var email = this.inputEmail.val().toLowerCase();
45463      var emailValid = this.inputEmailValid.val().toLowerCase();
45464
45465      if (email === emailValid) {
45466        if (!Utils.validEmail(email)) {
45467          this.addInvalidClass(this.inputEmail);
45468          return false;
45469        }
45470        this.removeInvalidClass(this.inputEmailValid);
45471      } else {
45472        this.addInvalidClass(this.inputEmail);
45473        this.addInvalidClass(this.inputEmailValid);
45474        return false;
45475      }
45476      return true;
45477    }
45478  }, {
45479    key: 'checkBriteverifyEmail',
45480    value: function checkBriteverifyEmail() {
45481      var _this16 = this;
45482
45483      var setAttrEmailStatus = function setAttrEmailStatus(emailAttr) {
45484        _this16.emailPrimaryStatus = emailAttr.status;
45485        _this16.emailSecondaryStatus = emailAttr.error_code ? emailAttr.error_code : null;
45486      };
45487
45488      var handleMsgToAppear = function handleMsgToAppear(emailAttr) {
45489        var $tip = _this16.inputEmail.parent().siblings().find('.tip');
45490
45491        switch (emailAttr.status) {
45492          case 'valid':
45493            _this16.addInvalidClass(_this16.inputEmail, _this16.inputMsgValid, $tip);
45494            break;
45495          case 'invalid':
45496            _this16.addInvalidClass(_this16.inputEmail, _this16.inputMsgInvalid, $tip);
45497            break;
45498          case 'accept_all':
45499            _this16.addInvalidClass(_this16.inputEmail, _this16.inputMsgAcceptAll, $tip);
45500            break;
45501          case 'unknown':
45502            _this16.addInvalidClass(_this16.inputEmail, _this16.inputMsgUnknown, $tip);
45503            break;
45504          default:
45505            break;
45506        }
45507      };
45508
45509      var body = {
45510        "email": this.inputEmail.val()
45511      };
45512
45513      HttpService.post('briteEmailValidate', body).then(function (data) {
45514        var emailAttr = data.email;
45515
45516        setAttrEmailStatus(emailAttr);
45517        handleMsgToAppear(emailAttr);
45518      }).catch(function (err) {
45519        var $tip = _this16.getTipFor(_this16.inputEmail);
45520        var message = err.responseJSON && err.responseJSON.message ? err.responseJSON.message : i18n("brite_unavailable_msg");
45521        _this16.addInvalidClass(_this16.inputEmail, message, $tip);
45522      });
45523    }
45524  }, {
45525    key: 'isBirthValid',
45526    value: function isBirthValid() {
45527      var _this20 = this;
45528
45529      if (this.isBirthValidationInProgress) return;
45530
45531      var dateMin = $('[data-js="min-age"]').attr("data-min-age").replace(/\D/g, "");
45532      var birth = DateFormatter.reverseDate(this.inputBirth.val());
45533      var birthToDate = new Date(birth);
45534      var birthToDateAdd = new Date(birthToDate);
45535      var isEditPage = SessionStorage.get('isEditPage');
45536      birthToDateAdd.setDate(birthToDateAdd.getDate() + 1);
45537
45538      var currentDate = new Date();
45539      var year = currentDate.getFullYear();
45540      var $yearMax = this.inputBirth.attr("data-maxyear") ? parseInt(this.inputBirth.attr("data-maxyear"), 10) : year;
45541      var $yearMin = this.inputBirth.attr("data-minyear") ? parseInt(this.inputBirth.attr("data-minyear"), 10) : 1900;
45542      var $tip = this.inputBirth.parent().siblings().find(".tip");
45543
45544      var minBirthDate = new Date();
45545      minBirthDate.setFullYear(minBirthDate.getFullYear() - dateMin);
45546
45547      if (birthToDate.toString() === "Invalid Date" || birthToDateAdd >= currentDate) {
45548        this.addInvalidClass(this.inputBirth, "Data de Nascimento Inválida", $tip);
45549        this.isBirthDateValid = false;
45550        return false;
45551      } else if (birthToDate <= minBirthDate && this.inputBirth.val().length === 10 && birthToDate.getFullYear() >= $yearMin && birthToDate.getFullYear() <= $yearMax) {
45552        !isEditPage && this.validBirthAndCpf(function (isValid, errorMsg) {
45553          if (isValid) {
45554            _this20.removeInvalidClass(_this20.inputBirth, $tip);
45555            _this20.isBirthDateValid = true;
45556          } else {
45557            _this20.addInvalidClass(_this20.inputBirth, errorMsg, $tip);
45558            _this20.isBirthDateValid = false;
45559          }
45560          _this20.updateSubmitButtonState();
45561          _this20.isBirthValidationInProgress = false;
45562        });
45563        return true;
45564      } else {
45565        this.addInvalidClass(this.inputBirth, this.birthInvalid, $tip);
45566        this.isBirthDateValid = false;
45567        return false;
45568      }
45569    }
45570  }, {
45571    key: 'toggleBirthFieldByDocType',
45572    value: function toggleBirthFieldByDocType(docTypeValue) {
45573      var isCnpj = String(docTypeValue) === "2";
45574      var $birthRow = this.inputBirth.closest(".row-custom-gutters");
45575      var $tip = this.inputBirth.parent().siblings().find(".tip");
45576
45577      if (isCnpj) {
45578        this.inputBirth.val("").removeAttr("required");
45579        this.removeInvalidClass(this.inputBirth, $tip);
45580        $birthRow.addClass("d-none");
45581        this.isBirthDateValid = true;
45582      } else {
45583        this.inputBirth.attr("required", "required");
45584        $birthRow.removeClass("d-none");
45585        this.isBirthDateValid = false;
45586      }
45587    }
45588  }, {
45589    key: 'updateSubmitButtonState',
45590    value: function updateSubmitButtonState() {
45591      if (this.isCPFValid && this.isInputNumberValid && this.isBirthDateValid) {
45592        this.btnFirstStepper.addClass("active").attr("disabled", false);
45593      } else {
45594        this.btnFirstStepper.add(this.btnSecondStepper).removeClass("active").attr("disabled", true);
45595        $('[data-js="stepper-2"], [data-js="item-border-1"], [data-js="stepper-3"], [data-js="item-border-2"]').removeClass("active");
45596      }
45597    }
45598  }, {
45599    key: 'passportValidation',
45600    value: function passportValidation() {
45601      var regex = /\W/;
45602      var documento = this.inputDocNumber;
45603      documento.on("keydown", function (e) {
45604        $(this).val($(this).val().replace(regex, ""));
45605      });
45606    }
45607  }, {
45608    key: 'isDocumentValid',
45609    value: function isDocumentValid() {
45610      var _this21 = this;
45611
45612      var documentNumber = this.inputDocNumber.val().replace(/[.]|[-]|[/]/g, "");
45613      var documentType = parseInt(this.inputDocType.val());
45614      var evaluation = true;
45615      var $tip = this.inputDocNumber.parent().siblings().find(".tip");
45616      var isEditPage = SessionStorage.get('isEditPage');
45617
45618      if (documentType === 1) evaluation = Utils.validateCPF(documentNumber);
45619      if (documentType === 2) evaluation = Utils.validateCNPJ(documentNumber);
45620      if (!evaluation) {
45621        this.isCPFValid = false;
45622        this.addInvalidClass(this.inputDocNumber, this.documentInvalid, $tip);
45623      } else {
45624        this.requestCPFRegistration(documentNumber, function (isCPFRegister) {
45625          if (isCPFRegister) {
45626            // Custom AEM message
45627            var cpfExistMessage = $('[data-js="msg-status-return"]').attr('data-cpf-exists');
45628            _this21.addInvalidClass(_this21.inputDocNumber, (cpfExistMessage === "") ? i18n('cpf_exists') : cpfExistMessage, $tip);
45629            _this21.isCPFValid = false;
45630            return false;
45631          } else {
45632            _this21.removeInvalidClass(_this21.inputDocNumber, $tip);
45633            _this21.isCPFValid = true;
45634
45635            if (_this21.inputDocNumber.val() && _this21.inputBirth.val()) {
45636              !isEditPage && _this21.validBirthAndCpf(function (isValid, errorMsg) {
45637                if (isValid) {
45638                  _this21.removeInvalidClass(_this21.inputBirth, _this21.inputBirth.parent().siblings().find(".tip"));
45639                  _this21.isBirthDateValid = true;
45640                } else {
45641                  _this21.addInvalidClass(_this21.inputBirth, errorMsg, _this21.inputBirth.parent().siblings().find(".tip"));
45642                  _this21.isBirthDateValid = false;
45643                }
45644                _this21.updateSubmitButtonState();
45645                _this21.isBirthValidationInProgress = false;
45646              });
45647            } else {
45648              if (_this21.isCPFValid) {
45649                _this21.removeInvalidClass(_this21.inputBirth, _this21.inputBirth.parent().siblings().find(".tip"));
45650              }
45651              _this21.updateSubmitButtonState();
45652            }
45653
45654            return true;
45655          }
45656        });
45657      }
45658
45659      return evaluation;
45660    }
45661  }, {
45662    key: 'openValidation',
45663    value: function openValidation(msg) {
45664      var _this17 = this;
45665      if (msg && !msg.includes('<p>') && !msg.includes('<span>') && !msg.includes('style')) {
45666        msg = '<p><label class="red">ERRO:</label> ' + msg + ' </p>';
45667      }
45668
45669      this.errorMessage.empty().append(msg);
45670      this.errorMessage.fadeIn();
45671
45672      this.formRegister.children().find("input, .select-custom").on('focusin', function () {
45673        _this17.errorMessage.fadeOut();
45674      });
45675    }
45676  }, {
45677    key: 'isSelectCustom',
45678    value: function isSelectCustom(el) {
45679      return $(el).attr('data-js') === 'input-doc-type' || $(el).attr('data-js') === 'input-phone-type';
45680    }
45681  }, {
45682    key: 'isEmpty',
45683    value: function isEmpty(value) {
45684      return value === null || value.trim() === '';
45685    }
45686  }, {
45687    key: 'hasLessThanMin',
45688    value: function hasLessThanMin(value, minlength) {
45689      return value.length < minlength;
45690    }
45691  }, {
45692    key: 'addInvalidClass',
45693    value: function addInvalidClass(el, msg, tip) {
45694      var $links = el.parent().siblings().find('.link');
45695      if (!this.isSelectCustom(el)) $(el).addClass("invalid"); else $(el).siblings('.select-selected').addClass('invalid');
45696      if (tip && tip.hasClass('warning')) {
45697        if (msg) tip.text(msg);
45698        tip.fadeIn();
45699        $links.hide();
45700      }
45701    }
45702  }, {
45703    key: 'removeInvalidClass',
45704    value: function removeInvalidClass(el, tip) {
45705      var $links = el.parent().siblings().find('.link');
45706      if (!this.isSelectCustom(el)) $(el).removeClass("invalid"); else $(el).siblings('.select-selected').removeClass('invalid');
45707      if (tip && tip.hasClass('warning')) {
45708        tip.fadeOut();
45709        $links.show();
45710      }
45711    }
45712  }, {
45713    key: 'isFormValid',
45714    value: function isFormValid() {
45715      return this.emptyValidation() && this.specificValidation() && this.checkAnyInvalid() && this.validateCheckbox();
45716    }
45717  }, {
45718    key: 'checkLockedStatus',
45719    value: function checkLockedStatus() {
45720      if (this.invalidEmailStatus != null) {
45721        var hiddenStatus = this.invalidEmailStatus.toLowerCase().split(',');
45722        if (this.emailPrimaryStatus !== null) return !hiddenStatus.includes(this.emailPrimaryStatus.toLowerCase());
45723      };
45724      return true;
45725    }
45726  }, {
45727    key: 'validateFirstStep',
45728    value: function validateFirstStep() {
45729      return this.isCPFValid && this.validateName() && this.isPhoneValid() && this.isBirthDateValid;
45730    }
45731  }, {
45732    key: 'checkEmptyInput',
45733    value: function checkEmptyInput(classStepper) {
45734      var empty = false;
45735
45736      this.formRegister.find('input[required]' + classStepper + '').each(function (_, el) {
45737        if (!$(el).val()) {
45738          empty = true;
45739        }
45740      });
45741
45742      return empty;
45743    }
45744  }, {
45745    key: 'isPhoneValid',
45746    value: function isPhoneValid() {
45747      var phonePattern = /\+55 \((\d{2})\) \d{5}-\d{4}/;
45748      var phoneValue = this.inputFullPhone.val();
45749      return phonePattern.test(phoneValue);
45750    }
45751  }, {
45752    key: 'validBirthAndCpf',
45753    value: function validBirthAndCpf(callback) {
45754      var _this23 = this;
45755
45756      var docType = parseInt(this.inputDocType.val());
45757
45758      if (docType === 3 || docType === 2) {
45759        callback(true);
45760        return;
45761      }
45762
45763      this.isBirthValidationInProgress = true;
45764      var $tip = this.inputBirth.parent().siblings().find(".tip");
45765
45766      var cpf = this.inputDocNumber.val();
45767      cpf = cpf.replace(/\D/g, "");
45768      var birth = DateFormatter.reverseDate(this.inputBirth.val());
45769
45770      var body = {
45771        cpf: cpf,
45772        birthdate: birth,
45773        cnpj: docType === 2 ? this.inputDocNumber.val() : "",
45774        passport: docType === 3 ? this.inputDocNumber.val() : ""
45775      };
45776
45777      LoaderService.show();
45778      var headers = { 'channel': Utils.getChannelTitle(this.isPaymentWhatsapp, this.saleplatform) };
45779      return HttpService.post("validationCPF", body, headers).then(function (data) {
45780        LoaderService.hide();
45781        if (data.success) {
45782          callback(true);
45783          if (_this23.isCPFValid) {
45784            _this23.removeInvalidClass(_this23.inputDocNumber, _this23.inputDocNumber.parent().siblings().find(".tip"));
45785          }
45786        } else if (!data.success && data.result == "Dados não encontrados.") {
45787          _this23.addInvalidClass(_this23.inputBirth, _this23.documentInvalid, $tip);
45788          _this23.addInvalidClass(_this23.inputDocNumber, " ", _this23.inputDocNumber.parent().siblings().find(".tip"));
45789          callback(false);
45790        } else {
45791          _this23.addInvalidClass(_this23.inputBirth, _this23.documentDocBirthInvalid, $tip);
45792          _this23.addInvalidClass(_this23.inputDocNumber, " ", _this23.inputDocNumber.parent().siblings().find(".tip"));
45793          callback(false);
45794        }
45795      }).catch(function (err) {
45796        LoaderService.hide();
45797        console.log(err);
45798        callback(false);
45799        if (err.status === 500 || err.status === 502 || err.status === 0 || err.status === 504) {
45800          _this23.removeInvalidClass(_this23.inputBirth, $tip);
45801          callback(true);
45802        } else if (err.status === 400) {
45803          callback(true, err.responseJSON.result);
45804        }
45805      });
45806    }
45807  }, {
45808    key: 'validateSecondStep',
45809    value: function validateSecondStep() {
45810      var isValidatedSecondStep = false;
45811      var self = this;
45812
45813      this.formRegister.find("input[required].second-stepper").each(function (_, el) {
45814        switch ($(el).attr("data-js")) {
45815          case "input-pass":
45816            isValidatedSecondStep = self.isPasswordValid();
45817            break;
45818          case "input-email":
45819            isValidatedSecondStep = self.isEmailValid() && self.checkLockedStatus();
45820            break;
45821        }
45822
45823        if (!isValidatedSecondStep) return false;
45824        if (!$(el).val()) {
45825          return false;
45826        }
45827      });
45828
45829      return isValidatedSecondStep;
45830    }
45831  }, {
45832    key: 'specificValidation',
45833    value: function specificValidation() {
45834      var specificValidation = true;
45835      var self = this;
45836      this.formRegister.find("input[required]").each(function (idx, el) {
45837        switch ($(el).attr("data-js")) {
45838          case "input-email":
45839            specificValidation = self.isEmailValid() && self.checkLockedStatus();
45840            break;
45841          case "input-pass":
45842            specificValidation = self.isPasswordValid();
45843            break;
45844          case "input-name":
45845            specificValidation = self.validateName();
45846            break;
45847          case "input-full-phone":
45848            specificValidation = self.isPhoneValid();
45849            break;
45850        }
45851        if (!specificValidation) return false; else self.removeInvalidClass($(el));
45852      });
45853      return specificValidation;
45854    }
45855  }, {
45856    key: 'emptyValidation',
45857    value: function emptyValidation() {
45858      var allFieldsValid = true;
45859
45860      var self = this;
45861      this.formRegister.find('input[required], select[required]').each(function (idx, el) {
45862        var value = $(el).val() ? $(el).val() : '';
45863        if (self.isEmpty(value)) {
45864          self.addInvalidClass($(el));
45865          allFieldsValid = false;
45866        } else self.removeInvalidClass($(el));
45867      });
45868      if (!allFieldsValid)
45869        // this.openValidation('Alguns campos estão vazios. Preencha os campos faltantes assinalados em vermelho antes de prosseguir.')
45870        this.openValidation(this.emptyFields);
45871      return allFieldsValid;
45872    }
45873  }, {
45874    key: 'minLengthValidation',
45875    value: function minLengthValidation() {
45876      var allFieldsValid = true;
45877
45878      var self = this;
45879      this.formRegister.find('input[required]').each(function (idx, el) {
45880        var tips = $(el).parent().siblings('.tips');
45881        var tip = tips.find('[data-js="min-length-validation-msg"]');
45882        var value = $(el).val() ? $(el).val() : '';
45883        var minlength = $(el).attr('minlength') ? parseInt($(el).attr('minlength')) : 0;
45884        if (self.hasLessThanMin(value, minlength)) {
45885          self.addInvalidClass($(el), null, tip);
45886          allFieldsValid = false;
45887        } else self.removeInvalidClass($(el), tip);
45888      });
45889      if (!allFieldsValid)
45890        // this.openValidation('Alguns campos estão com menos caracteres do que o mínimo. Preencha os campos faltantes assinalados em vermelho antes de prosseguir.')
45891        this.openValidation(this.minCaracteres);
45892      return allFieldsValid;
45893    }
45894  }, {
45895    key: 'checkAnyInvalid',
45896    value: function checkAnyInvalid() {
45897      var allFieldsValid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
45898
45899      if (this.formRegister.find('input.invalid[required]').length > 0) {
45900        allFieldsValid = false;
45901        // this.openValidation('Documento e/ou email já cadastrado(s).')
45902      }
45903      return allFieldsValid;
45904    }
45905  }, {
45906    key: 'enableForm',
45907    value: function enableForm() {
45908      this.formRegister.find('input, select, button, .select-selected').each(function () {
45909        if ($(this).attr('data-js') !== 'input-doc-type' && $(this).attr('data-js') !== 'input-doc' && $(this).siblings('select').attr('data-js') !== 'input-doc-type') {
45910          $(this).attr('disabled', false);
45911          if ($(this).hasClass('disabled')) {
45912            $(this).removeClass('disabled');
45913          }
45914        }
45915      });
45916    }
45917  }, {
45918    key: 'disableForm',
45919    value: function disableForm() {
45920      this.formRegister.find('input, select, button, .select-selected').each(function () {
45921        $(this).attr('disabled', true);
45922        if ($(this).hasClass('select-selected')) $(this).addClass('disabled');
45923      });
45924    }
45925  }, {
45926    key: 'loadUserData',
45927    value: function loadUserData(passenger) {
45928      var phone = passenger.phone.replace(/\D/g, "").trim();
45929      var formattedPhone = '+55 (' + passenger.areaCode + ') ' + phone.slice(0, 5) + '-' + phone.slice(5);
45930      var phoneValue = phone;
45931      var phoneSplit = phoneValue ? phoneValue.split(/[(\(|\)|\ )]/) : "";
45932      var docType = void 0;
45933      var inputDocType = $('[data-js="input-doc-type"]')[0];
45934
45935      if (passenger.cpf) {
45936        docType = 'CPF';
45937      } else if (passenger.cnpj) {
45938        docType = 'CNPJ';
45939      } else if (passenger.passport) {
45940        docType = 'PASSAPORTE';
45941      }
45942
45943      if (phoneSplit && phoneSplit.length > 0) phoneSplit = phoneSplit.filter(Boolean);
45944
45945      if (passenger.birthDate) this.inputBirth.val(DateFormatter.reverseDate(passenger.birthDate));
45946
45947      this.selectCustom.selectDefault(inputDocType, docType);
45948      $('[data-js="input-doc-type"]').attr('disabled', true);
45949      this.inputName.val(passenger.name);
45950      this.inputDocNumber.val(passenger.cnpj ? passenger.cnpj : passenger.passport ? passenger.passport : passenger.cpf).trigger('input');
45951      this.inputEmail.val(passenger.email);
45952      this.inputEmailValid.val(passenger.email);
45953      this.inputPhoneType.val(passenger.phoneType).change();
45954      this.inputFullPhone.val(formattedPhone).trigger("input");
45955
45956      if (passenger.addresses) {
45957        var _passenger$addresses = passenger.addresses,
45958          zipCode = _passenger$addresses.zipCode,
45959          street = _passenger$addresses.street,
45960          complement = _passenger$addresses.complement,
45961          neighborhood = _passenger$addresses.neighborhood,
45962          city = _passenger$addresses.city,
45963          state = _passenger$addresses.state,
45964          number = _passenger$addresses.number;
45965
45966
45967        this.inputZipCode.val(zipCode);
45968        this.inputAddress.val(street);
45969        this.inputComplement.val(complement);
45970        this.inputNeighborhood.val(neighborhood);
45971        this.inputCity.val(city);
45972        this.selectCustom.selectDefault(this.inputSelectState, state);
45973        $('#input-select-state option').eq(state + 1).prop('selected', true);
45974        this.inputNumber.val(number);
45975      }
45976    }
45977  }, {
45978    key: 'handleSocialRegister',
45979    value: function handleSocialRegister() {
45980      var _this18 = this;
45981
45982      this.btnRegisterGoogle.click(function () {
45983        return _this18.initSocialRegisterGoogle();
45984      });
45985      this.btnRegisterFacebook.click(function () {
45986        return _this18.initSocialRegisterFacebook();
45987      });
45988      this.btnRegisterApple.click(function () {
45989        localStorage.setItem("referrer-register", $(location).attr('href'));
45990        return _this18.initSocialRegisterApple();
45991      });
45992    }
45993  }, {
45994    key: 'fillFormWithProfileInfo',
45995    value: function fillFormWithProfileInfo() {
45996      this.inputName.val(this.profileName).trigger('input');
45997      this.inputEmail.val(this.profileEmail).trigger('focusout');
45998      this.inputEmailValid.val(this.profileEmail).trigger('focusout');
45999    }
46000  }, {
46001    key: 'saveProfileInfo',
46002    value: function saveProfileInfo(socialType, object) {
46003      switch (socialType) {
46004        case 'google':
46005          var googleIdToken = object.getAuthResponse().id_token;
46006          var profile = object.getBasicProfile();
46007          this.profileName = profile.getName();
46008          this.profileEmail = profile.getEmail();
46009          this.profileSocialId = this.extractSubJwt(googleIdToken);
46010          this.profileSocialType = socialType;
46011          this.profileIdToken = googleIdToken;
46012          break;
46013        case 'facebook':
46014          this.profileName = object.name;
46015          this.profileEmail = object.email;
46016          this.profileSocialId = object.id;
46017          this.profileSocialType = socialType;
46018          this.profileIdToken = object.id_token;
46019          break;
46020        case 'apple':
46021          this.profileName = object.user ? object.user.name.firstName + ' ' + object.user.name.lastName : '';
46022          this.profileEmail = object.user ? object.user.email : '';
46023          this.profileSocialId = this.extractSubJwt(object.authorization.id_token);
46024          this.profileSocialType = socialType;
46025          this.profileIdToken = object.authorization.id_token;
46026          break;
46027      }
46028    }
46029  }, {
46030    key: 'extractSubJwt',
46031    value: function extractSubJwt(token) {
46032      var base64Url = token.split('.')[1];
46033      var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
46034      var jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
46035        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
46036      }).join(''));
46037
46038      var tokenDecode = JSON.parse(jsonPayload);
46039      return tokenDecode.sub;
46040    }
46041  }, {
46042    key: 'initSocialRegisterGoogle',
46043    value: function initSocialRegisterGoogle() {
46044      var _this19 = this;
46045
46046      var initGoogleSignIn = function initGoogleSignIn() {
46047        var onSuccess = function onSuccess(googleUser) {
46048          gapi.auth2.getAuthInstance().signOut();
46049          _this19.saveProfileInfo('google', googleUser);
46050          _this19.fillFormWithProfileInfo();
46051        };
46052
46053        var onFailure = function onFailure(err) {
46054          console.error(err);
46055        };
46056
46057        gapi.auth2.init({ client_id: $('[data-js="google-client-id"]').val() }).then(function (authInstance) {
46058          return authInstance.signIn().then(onSuccess, onFailure);
46059        }).catch(function (err) {
46060          return console.error(err);
46061        });
46062      };
46063
46064      gapi.load('auth2', initGoogleSignIn);
46065    }
46066  }, {
46067    key: 'initSocialRegisterFacebook',
46068    value: function initSocialRegisterFacebook() {
46069      var _this20 = this;
46070
46071      var onSuccess = function onSuccess(facebookUser) {
46072        FB.logout(function (response) {
46073          // FB.logout
46074        });
46075        _this20.saveProfileInfo('facebook', facebookUser);
46076        _this20.fillFormWithProfileInfo();
46077      };
46078
46079      var onFailure = function onFailure(err) {
46080        FB.logout();
46081        console.error(err);
46082      };
46083
46084      FB.init({
46085        appId: $('[data-js="facebook-app-id"]').val(),
46086        autoLogAppEvents: true,
46087        xfbml: true,
46088        version: 'v9.0'
46089      });
46090
46091      FB.login(function (response) {
46092        if (response.status === 'connected') {
46093          FB.api('/me', { fields: 'name, email' }, function (facebookUser) {
46094            facebookUser.id_token = response.authResponse.accessToken;
46095            onSuccess(facebookUser);
46096          });
46097        } else {
46098          onFailure(response);
46099        }
46100      }, {
46101        scope: 'email'
46102      });
46103    }
46104  }, {
46105    key: 'initSocialRegisterApple',
46106    value: function initSocialRegisterApple() {
46107      var _this21 = this;
46108
46109      var nonce = new Date().getTime();
46110
46111      AppleID.auth.init({
46112        clientId: $('[data-js="apple-client-id"]').val(),
46113        scope: "name email",
46114        redirectURI: $('[data-js="apple-redirect-url"]').val() + '?page=register',
46115        nonce: '' + nonce,
46116        usePopup: true
46117      });
46118
46119      var onSuccess = function onSuccess(event) {
46120        _this21.saveProfileInfo('apple', event.detail);
46121        _this21.fillFormWithProfileInfo();
46122      };
46123
46124      var onFailure = function onFailure(event) {
46125        console.error(event);
46126      };
46127
46128      document.addEventListener('AppleIDSignInOnSuccess', onSuccess);
46129      document.addEventListener('AppleIDSignInOnFailure', onFailure);
46130      AppleID.auth.signIn();
46131    }
46132  }, {
46133    key: 'invalidFieldZipCode',
46134    value: function invalidFieldZipCode() {
46135      var $tip = this.inputZipCode.parent().siblings().find('.tip');
46136      var cepMessage = $('[data-js="postal-code-message"]').val() ? $('[data-js="postal-code-message"]').val() : 'CEP Inválido';
46137
46138      this.addInvalidClass(this.inputZipCode);
46139      this.addInvalidClass(this.inputZipCode, cepMessage, $tip);
46140    }
46141  }, {
46142    key: 'validFieldZipCode',
46143    value: function validFieldZipCode() {
46144      var $tip = this.inputZipCode.parent().siblings().find('.tip');
46145
46146      this.removeInvalidClass(this.inputZipCode);
46147      this.removeInvalidClass(this.inputZipCode, $tip);
46148    }
46149  }, {
46150    key: 'createAddressObject',
46151    value: function createAddressObject() {
46152      var address = new Address();
46153      address.street = this.inputAddress.val();
46154      address.zipCode = this.inputZipCode.val();
46155      address.complement = this.inputComplement.val();
46156      address.neighborhood = this.inputNeighborhood.val();
46157      address.city = this.inputCity.val();
46158      address.state = this.inputSelectState.val();
46159      address.number = this.inputNumber.val();
46160      return address;
46161    }
46162  }, {
46163    key: 'profileName',
46164    get: function get() {
46165      return this._profileName;
46166    },
46167    set: function set(profileName) {
46168      this._profileName = profileName;
46169    }
46170  }, {
46171    key: 'profileEmail',
46172    get: function get() {
46173      return this._profileEmail;
46174    },
46175    set: function set(profileEmail) {
46176      this._profileEmail = profileEmail;
46177    }
46178  }, {
46179    key: 'profileIdToken',
46180    get: function get() {
46181      return this._profileIdToken;
46182    },
46183    set: function set(profileIdToken) {
46184      this._profileIdToken = profileIdToken;
46185    }
46186  }, {
46187    key: 'profileSocialType',
46188    get: function get() {
46189      return this._profileSocialType;
46190    },
46191    set: function set(profileSocialType) {
46192      this._profileSocialType = profileSocialType;
46193    }
46194  }, {
46195    key: 'profileSocialId',
46196    get: function get() {
46197      return this._profileSocialId;
46198    },
46199    set: function set(profileSocialId) {
46200      this._profileSocialId = profileSocialId;
46201    }
46202  }]);
46203
46204  return RegisterController;
46205}();
46206'use strict';
46207
46208var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
46209
46210function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
46211
46212/**
46213 *
46214 * Register Wallet Controller
46215 *
46216 * INICIO
46217 */
46218
46219var RegisterWalletController = function () {
46220  function RegisterWalletController($) {
46221    _classCallCheck(this, RegisterWalletController);
46222
46223    this.loginForm = $('[data-js="login-form"]');
46224    this.inputEmail = $('[data-js="input-email"]');
46225    this.inputCPF = $('[data-js="input-doc"]');
46226    this.inputPassword = $('[data-js="input-wallet-password"]');
46227    this.inputPasswordValid = $('[data-js="input-wallet-pass-valid"]');
46228    this.btnShowPassword = $('[data-js="show-password"]');
46229    this.btnShowPasswordConfirm = $('[data-js="show-password-confirm"]');
46230    this.openRequestPassword = $('[data-js="open-request-password"]');
46231    this.passwordRecovery = $('[data-js="password-recovery"]');
46232    this.passwordRecovertBack = $('[data-js="password-recovery-back"]');
46233    this.loginContainer = $('.login-wallet-box');
46234    this.btnRegister = $('[data-js="button-register"]');
46235    this.termsCheckbox = $('[data-js="terms-and-conditions-check"]');
46236    this.passenger = JSON.parse(sessionStorage.getItem('passenger'));
46237    this.init();
46238  }
46239
46240  _createClass(RegisterWalletController, [{
46241    key: 'init',
46242    value: function init() {
46243      var passenger = SessionStorage.get('passenger');
46244
46245      if (!passenger) {
46246        if ((!$('#wcmmodeedit') || $('#wcmmodeedit').val() == '' || $('#wcmmodeedit').val() == 'false')) {
46247          localStorage.setItem("referrer", $(location).attr('href'));
46248          $(location).attr('href', $('#loginPage').val());
46249        }
46250      }
46251
46252      this.handlePasswordRecovery();
46253      this.listenForm();
46254      this.fillForm();
46255    }
46256  }, {
46257    key: 'listenForm',
46258    value: function listenForm() {
46259      var _this = this;
46260
46261      this.inputEmail.on('keyup focusout', function (e) {
46262        return _this.handleEmailInput(e);
46263      });
46264      this.btnShowPassword.on('click', function () {
46265        return _this.togglePasswordVisibility(_this.inputPassword, _this.btnShowPassword);
46266      });
46267      this.btnShowPasswordConfirm.on('click', function () {
46268        return _this.togglePasswordVisibility(_this.inputPasswordValid, _this.btnShowPasswordConfirm);
46269      });
46270      this.inputPassword.on('input', function () {
46271        return _this.handlePasswordInput();
46272      });
46273      this.inputPasswordValid.on('input', function () {
46274        return _this.handlePasswordValidation();
46275      });
46276      this.termsCheckbox.on('change', function () {
46277        return _this.updateBtnRegisterState();
46278      });
46279      this.btnRegister.on('click', function () {
46280        return _this.handleRegisterClick();
46281      });
46282    }
46283  }, {
46284    key: 'handleEmailInput',
46285    value: function handleEmailInput(e) {
46286      this.inputEmail.attr("maxLength", "45");
46287    }
46288  }, {
46289    key: 'togglePasswordVisibility',
46290    value: function togglePasswordVisibility(inputField, toggleButton) {
46291      var isPassword = inputField.attr('type') === 'password';
46292      inputField.attr('type', isPassword ? 'text' : 'password');
46293      toggleButton.toggleClass("active");
46294      inputField.toggleClass("show");
46295    }
46296  }, {
46297    key: 'handlePasswordInput',
46298    value: function handlePasswordInput() {
46299      this.validatePassword(this.inputPassword.val());
46300      this.checkPasswordMatch();
46301      this.updateBtnRegisterState();
46302    }
46303  }, {
46304    key: 'handlePasswordValidation',
46305    value: function handlePasswordValidation() {
46306      this.checkPasswordMatch();
46307      this.updateBtnRegisterState();
46308    }
46309  }, {
46310    key: 'handleRegisterClick',
46311    value: function handleRegisterClick() {
46312      if (this.validateForm()) {
46313        var passenger = this.createPassengerData();
46314        this.registerCLubeGiro(passenger);
46315      }
46316    }
46317  }, {
46318    key: 'validateForm',
46319    value: function validateForm() {
46320      return this.inputPassword.hasClass('valid') && this.inputPasswordValid.hasClass('valid') && this.termsCheckbox.is(':checked');
46321    }
46322  }, {
46323    key: 'handlePasswordRecovery',
46324    value: function handlePasswordRecovery() {
46325      var _this2 = this;
46326
46327      this.openRequestPassword.click(function () {
46328        _this2.passwordRecovery.removeClass('d-none');
46329        _this2.loginContainer.addClass('d-none');
46330      });
46331
46332      this.passwordRecovertBack.on('click', function () {
46333        _this2.passwordRecovery.addClass('d-none');
46334        _this2.loginContainer.removeClass('d-none');
46335      });
46336    }
46337  }, {
46338    key: 'fillForm',
46339    value: function fillForm() {
46340      if (this.passenger) {
46341        if (this.passenger._email) {
46342          this.inputEmail.val(this.passenger._email).attr('disabled', true);
46343        }
46344        if (this.passenger._cpf) {
46345          this.inputCPF.val(this.passenger._cpf).attr('disabled', true);
46346          this.inputCPF.mask('000.000.000-00');
46347        }
46348      }
46349    }
46350  }, {
46351    key: 'validatePassword',
46352    value: function validatePassword(password) {
46353      var passwordCriteria = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d$@$!%*#?&]{8,}$/;
46354      if (passwordCriteria.test(password)) {
46355        this.inputPassword.removeClass('invalid').addClass('valid');
46356      } else {
46357        this.inputPassword.removeClass('valid').addClass('invalid');
46358      }
46359    }
46360  }, {
46361    key: 'checkPasswordMatch',
46362    value: function checkPasswordMatch() {
46363      if (this.inputPassword.val() === this.inputPasswordValid.val()) {
46364        this.inputPasswordValid.removeClass('invalid').addClass('valid');
46365      } else {
46366        this.inputPasswordValid.removeClass('valid').addClass('invalid');
46367      }
46368    }
46369  }, {
46370    key: 'updateBtnRegisterState',
46371    value: function updateBtnRegisterState() {
46372      var isPasswordValid = this.inputPassword.hasClass('valid');
46373      var isPasswordMatch = this.inputPasswordValid.hasClass('valid');
46374      var isTermsChecked = this.termsCheckbox.is(':checked');
46375      if (isPasswordValid && isPasswordMatch && isTermsChecked) {
46376        this.enableBtnRegister();
46377      } else {
46378        this.disableBtnRegister();
46379      }
46380    }
46381  }, {
46382    key: 'enableBtnRegister',
46383    value: function enableBtnRegister() {
46384      this.btnRegister.removeClass('disabled');
46385      this.btnRegister.attr('disabled', false);
46386    }
46387  }, {
46388    key: 'disableBtnRegister',
46389    value: function disableBtnRegister() {
46390      this.btnRegister.addClass('disabled');
46391      this.btnRegister.attr('disabled', true);
46392    }
46393  }, {
46394    key: 'registerCLubeGiro',
46395    value: function registerCLubeGiro(passenger) {
46396      var _this3 = this;
46397
46398      LoaderService.show();
46399
46400      passenger.registrationCampaign = 'giro-UTP';
46401
46402      var headersRequest = HttpService.getSession();
46403
46404      return $.ajax({
46405        type: "POST",
46406        url: $('#baseGiroUrl').val() + '/customer/v1/firebase',
46407        data: JSON.stringify(passenger.serviceJSON),
46408        dataType: 'json',
46409        contentType: "application/json",
46410        headers: headersRequest
46411      }).then(function (response) {
46412        LoaderService.hide();
46413        $(location).attr("href", i18n('register_terms_page'));
46414      }).catch(function (error) {
46415        LoaderService.hide();
46416        _this3.handleErrorMessage(error);
46417      });
46418    }
46419  }, {
46420    key: 'createPassengerData',
46421    value: function createPassengerData() {
46422      if (!this.passenger) {
46423        throw new Error('Dados do passageiro não estão disponíveis.');
46424      }
46425
46426      var _passenger = this.passenger,
46427        _areaCode = _passenger._areaCode,
46428        _phone = _passenger._phone,
46429        _name = _passenger._name,
46430        _birthDate = _passenger._birthDate,
46431        _phoneType = _passenger._phoneType,
46432        _image = _passenger._image,
46433        _addresses = _passenger._addresses;
46434
46435
46436      var passenger = new PassengerGiro();
46437      passenger.addresses = [this.createAddressData(_addresses)];
46438      passenger.areaCode = _areaCode;
46439      passenger.phone = _phone;
46440      passenger.name = _name;
46441      passenger.familyName = Utils.getFamilyName(_name);
46442      passenger.groups = [{ Id: 78 }];
46443      passenger.login = this.removeMask(this.inputCPF.val());
46444      passenger.cpf = this.removeMask(this.inputCPF.val());
46445      passenger.password = this.inputPassword.val();
46446      passenger.birthDate = _birthDate;
46447      passenger.email = this.inputEmail.val();
46448      passenger.optin = true;
46449      passenger.phoneType = _phoneType;
46450
46451      return passenger;
46452    }
46453  }, {
46454    key: 'createAddressData',
46455    value: function createAddressData(addressData) {
46456      if (!addressData) {
46457        throw new Error('Dados do endereço não estão disponíveis.');
46458      }
46459
46460      var _street = addressData._street,
46461        zipCode = addressData.zipCode,
46462        complement = addressData.complement,
46463        city = addressData.city,
46464        state = addressData.state,
46465        number = addressData.number,
46466        neighborhood = addressData.neighborhood;
46467
46468
46469      var address = new Address();
46470      address.street = _street;
46471      address.zipCode = zipCode;
46472      address.complement = complement;
46473      address.city = city;
46474      address.state = state;
46475      address.number = number;
46476      address.neighborhood = neighborhood;
46477
46478      return address;
46479    }
46480  }, {
46481    key: 'removeMask',
46482    value: function removeMask(value) {
46483      return value.replace(/[.\-\/]/g, '');
46484    }
46485  }]);
46486
46487  return RegisterWalletController;
46488}();
46489'use strict';
46490
46491var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
46492
46493function _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); } }
46494
46495function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
46496
46497var ResultFilter = function () {
46498  function ResultFilter($, searchResultRef, listResultRef) {
46499    _classCallCheck(this, ResultFilter);
46500
46501    this.btnFilter = $('[data-js="button-open-filter"]');
46502    this.btnCloseFilter = $('[data-js="button-close-filter"]');
46503    this.modalFilter = $('[data-js="modal-filter"]');
46504    this.btnCleanFilter = $('[data-js="button-clean-filter"]');
46505    this.flatSlider = $('[data-js="flat-slider"]');
46506    this.flatSliderArr = $('[data-js="flat-slider-arrival"]');
46507    this.hourRange = $('[data-js="hour-range"]');
46508    this.companies = $('[data-js="checkbox-companies"]');
46509    this.classes = $('[data-js="checkbox-classes"]');
46510    this.detailsDesk = $('[data-js="checkbox-details-desktop"]');
46511    this.btnApply = $('[data-js="apply-filter"]');
46512    this.searchResultContainer = $('[data-js="search-result"]');
46513    this.filterVal = $('[data-js="alert-validation"]');
46514    this.breadcrumb = $('[data-js="breadcrumb"]');
46515    this.accordionTarget = $('[data-js="accordion-target"]');
46516    this.flatSliderDesk = $('[data-js="flat-slider"]');
46517    this.searchResultRef = searchResultRef;
46518    this.listResultRef = listResultRef;
46519    this.listPriceVisibleInDispo = {};
46520    this.details = [];
46521    this.containerDate = $('[data-js="nearby-dates-container"]');
46522    this.containerFilterOrder = $('#shopping-filter-container');
46523
46524    this.hourRanges = {
46525      departure: $('[data-js="hour-range"][data-referer="departure"]'),
46526      arrival: $('[data-js="hour-range"][data-referer="arrival"]')
46527    };
46528
46529    this.init();
46530  }
46531
46532  _createClass(ResultFilter, [{
46533    key: 'init',
46534    value: function init() {
46535      var _this = this;
46536      this.loadFilter();
46537      this.loadSlider();
46538      this.btnCleanFilter.click(function () {
46539        return _this.cleanFilter();
46540      });
46541      this.applyFilter();
46542      this.handleAccordionEvents();
46543      this.handleCheckboxes();
46544      SessionStorage.remove('filteredResult');
46545    }
46546  }, {
46547    key: 'loadSlider',
46548    value: function loadSlider() {
46549      var _this2 = this;
46550
46551      $('[data-js="flat-slider"]').slider({
46552        orientation: 'horizontal',
46553        min: 0,
46554        max: 24,
46555        range: true,
46556        values: [0, 24],
46557        slide: function slide(e, ui) {
46558          var referer = $(e.target).data('referer');
46559          var text = ui.values[0] + ':00 - ' + ui.values[1] + ':00';
46560          _this2.hourRanges[referer].text(text);
46561        }
46562      });
46563
46564      $('[data-js="flat-slider"]').slider({
46565        orientation: 'horizontal',
46566        min: 0,
46567        max: 24,
46568        range: true,
46569        values: [0, 24],
46570        slide: function slide(e, ui) {
46571          var referer = $(e.target).data('referer');
46572          var text = ui.values[0] + ':00 - ' + ui.values[1] + ':00';
46573          _this2.hourRanges[referer].text(text);
46574        }
46575      });
46576
46577      $('[data-js="flat-slider-arrival"]').slider({
46578        orientation: 'horizontal',
46579        min: 0,
46580        max: 24,
46581        range: true,
46582        values: [0, 24],
46583        slide: function slide(e, ui) {
46584          var referer = $(e.target).data('referer');
46585          var text = ui.values[0] + ':00 - ' + ui.values[1] + ':00';
46586          _this2.hourRanges[referer].text(text);
46587        }
46588      });
46589    }
46590  }, {
46591    key: 'handleAccordionEvents',
46592    value: function handleAccordionEvents() {
46593      this.accordionTarget.on('click', function () {
46594        var $el = $(this);
46595        var $section = $el.parent();
46596        $section.toggleClass('active');
46597      });
46598    }
46599  }, {
46600    key: 'handleCheckboxes',
46601    value: function handleCheckboxes() {
46602      $('input[type=checkbox]').change(function (e) {
46603        var clazz = $(e.target).attr('class').replace(" ", ".");
46604        var checked = $(e.target).is(':checked');
46605        $(document).find('.' + clazz).each(function () {
46606          $(this).prop('checked', checked);
46607        });
46608      });
46609    }
46610  }, {
46611    key: 'getRangeValues',
46612    value: function getRangeValues(departure) {
46613      var flatSlider = $('[data-js="flat-slider"]');
46614      var flatSliderArr = $('[data-js="flat-slider-arrival"]');
46615      if (departure) {
46616        return [('0' + $(flatSlider).slider("values", 0)).slice(-2) + ':00', ('0' + $(flatSlider).slider("values", 1)).slice(-2) + ':00'];
46617      } else {
46618        return [('0' + $(flatSliderArr).slider("values", 0)).slice(-2) + ':00', ('0' + $(flatSliderArr).slider("values", 1)).slice(-2) + ':00'];
46619      }
46620    }
46621  }, {
46622    key: 'loadFilter',
46623    value: function loadFilter() {
46624      var _this3 = this;
46625
46626      this.btnFilter.click(function () {
46627        return _this3.toggleFilter();
46628      });
46629      this.btnCloseFilter.click(function () {
46630        return _this3.closeFilter();
46631      });
46632      var currentResult = {};
46633
46634      if (this.isReturn()) {
46635        currentResult = SessionStorage.get('currentResultRet');
46636      } else {
46637        currentResult = SessionStorage.get('currentResultDep');
46638      }
46639
46640      if (!currentResult || !currentResult.servicesList) return;
46641
46642      var companiesNames = [].concat(_toConsumableArray(new Set(currentResult.servicesList.map(function (res) {
46643        return res.company.toUpperCase();
46644      }))));
46645      var classesNames = [].concat(_toConsumableArray(new Set(currentResult.servicesList.map(function (res) {
46646        return res.class.toUpperCase();
46647      }))));
46648
46649      this.renderCompanies(companiesNames);
46650      this.renderFriendlyClassNames(companiesNames, classesNames);
46651    }
46652  }, {
46653    key: 'renderFriendlyClassNames',
46654    value: function renderFriendlyClassNames(companiesNames, classesNames) {
46655      var _this4 = this;
46656
46657      InternalAPIService.loadInternalAPI(function (_, res) {
46658        var arrayContains = function arrayContains(name, arr) {
46659          return arr.indexOf(name) > -1;
46660        };
46661
46662        var companies = res.result.filter(function (company) {
46663          return arrayContains(company.companyName.toUpperCase(), companiesNames);
46664        });
46665
46666        var classes = companies.reduce(function (comps, company) {
46667          return [].concat(_toConsumableArray(comps), _toConsumableArray(company.classes));
46668        }, []).filter(function (classObj) {
46669          return arrayContains(classObj.className.toUpperCase(), classesNames);
46670        }).map(function (_ref) {
46671          var className = _ref.className,
46672            friendlyName = _ref.friendlyName;
46673          return {
46674            class: className.toUpperCase(),
46675            friendlyName: (friendlyName || className).toUpperCase()
46676          };
46677        });
46678
46679        _this4.renderClasses(classes);
46680      });
46681    }
46682  }, {
46683    key: 'renderDetails',
46684    value: function renderDetails(details) {
46685      var _this5 = this;
46686
46687      var content = [];
46688
46689      details.forEach(function (el, i) {
46690        content.push('<li class="checklist-item">');
46691        content.push('<input data-js="details-checkbox" id="details_check_desk_' + i + '" type="checkbox" checked="checked"/>');
46692        content.push('<label for="details_check_desk_' + i + '">');
46693        content.push('<span class="checkmark" data-js="checkmark"></span>');
46694        content.push('<span class="checklist-item-text">' + _this5.capitalize(el) + '</span>');
46695        content.push('</label>');
46696        content.push('</li>');
46697      });
46698
46699      if (details.size > 0) {
46700        this.detailsDesk.parent().parent().show();
46701        this.detailsDesk.empty().append(content.join(''));
46702      } else {
46703        this.detailsDesk.parent().parent().hide();
46704      }
46705    }
46706  }, {
46707    key: 'renderClasses',
46708    value: function renderClasses(ticketClasses) {
46709      var _this6 = this;
46710
46711      var content = [];
46712      var contentDesk = [];
46713      var friendlyName = void 0;
46714
46715      ticketClasses.forEach(function (ticketClass, i) {
46716        friendlyName = !!ticketClass.friendlyName ? ticketClass.friendlyName : ticketClass.class;
46717        content.push('<li class="checklist-item">');
46718        content.push('<div class="custom-control custom-checkbox">');
46719        content.push('<input class="class_check_' + i + ' custom-control-input" id="class_check_' + i + '" data-js="class-checkbox" type="checkbox"/>');
46720        content.push('<label class="custom-control-label" for="class_check_' + i + '" data-class-name="' + ticketClass.class + '"> ' + _this6.capitalize(friendlyName) + ' </label>');
46721        content.push('</div>');
46722        content.push('</li>');
46723        contentDesk.push('<li class="checklist-item">');
46724        contentDesk.push('<div class="custom-control custom-checkbox">');
46725        contentDesk.push('<input class="class_check_' + i + ' custom-control-input" id="class_check_desk_' + i + '" data-js="class-checkbox" type="checkbox"/>');
46726        contentDesk.push('<label class="custom-control-label" for="class_check_desk_' + i + '" data-class-name="' + ticketClass.class + '"> ' + _this6.capitalize(friendlyName) + ' </label>');
46727        contentDesk.push('</div>');
46728        contentDesk.push('</li>');
46729      });
46730      this.classes.empty().append(content.join(''));
46731      //this.classesDesk.empty().append(contentDesk.join(''));
46732    }
46733  }, {
46734    key: 'renderCompanies',
46735    value: function renderCompanies(companies) {
46736      var _this7 = this;
46737
46738      var content = [];
46739      companies.forEach(function (el, i) {
46740        content.push('<li class="checklist-item">');
46741        content.push('<div class="custom-control custom-checkbox">');
46742        content.push('<input class="company_check_desk_' + i + ' custom-control-input" id="company_check_' + i + '" data-js="company-checkbox"  type="checkbox" checked="checked"/>');
46743        content.push('<label class="custom-control-label" for="company_check_' + i + '"> ' + _this7.capitalize(el) + '</label>');
46744        content.push('</div>');
46745        content.push('</li>');
46746      });
46747
46748      this.companies.empty().append(content.join(''));
46749    }
46750  }, {
46751    key: 'applyFilter',
46752    value: function applyFilter() {
46753      var _this8 = this;
46754
46755      this.btnApply.click(function (e) {
46756        LoaderService.show();
46757        var filteredResult = {},
46758          filteredServices = [];
46759
46760        if (_this8.isReturn()) {
46761          filteredResult = SessionStorage.get('currentResultRet');
46762        } else {
46763          filteredResult = SessionStorage.get('currentResultDep');
46764        }
46765
46766        filteredServices = filteredResult.servicesList;
46767
46768        filteredServices = _this8.filterByClass(filteredServices);
46769        // filteredServices = this.filterByCompany(filteredServices)
46770        filteredServices = _this8.filterByHourDeparture(filteredServices);
46771        filteredServices = _this8.filterByHourArrival(filteredServices);
46772        filteredServices = _this8.filterByDetail(filteredServices);
46773
46774        filteredResult.servicesList = filteredServices;
46775        SessionStorage.set('filteredResult', filteredResult);
46776
46777        if (filteredServices && filteredServices.length !== 0) {
46778          _this8.containerDate.removeClass('not-visible');
46779          $('[data-js="no-result-warning-filter"]').removeClass('active');
46780          if (e.originalEvent && e.originalEvent.isTrusted) {
46781            _this8.searchResultRef.setListResultView(true);
46782            _this8.listResultRef.setupInfiniteScroll();
46783          }
46784          _this8.searchResultRef.setListResultView();
46785          setTimeout(function () {
46786            LoaderService.hide();
46787            _this8.closeFilter();
46788          }, 300);
46789        } else {
46790          $('[data-js="list-companies"]').empty();
46791          $('[data-js="no-result-warning-filter"]').addClass('active');
46792          setTimeout(function () {
46793            return LoaderService.hide();
46794          }, 300);
46795
46796          var _Utils$getWindowSize = Utils.getWindowSize(),
46797            width = _Utils$getWindowSize.width,
46798            breakpoints = _Utils$getWindowSize.breakpoints;
46799
46800          if (width < breakpoints.LG) {
46801            _this8.closeFilter();
46802          }
46803        }
46804      });
46805    }
46806  }, {
46807    key: 'filterByClass',
46808    value: function filterByClass(result) {
46809      var arrayClasses = [];
46810      $('[data-js="class-checkbox"]').each(function (i, el) {
46811        if ($(el).is(':checked')) {
46812          var value = $(el).next().data('class-name').trim();
46813          arrayClasses.push(value.toUpperCase());
46814        }
46815      });
46816
46817      if (arrayClasses.length === 0) {
46818        return result;
46819      } else {
46820        return result.filter(function (service) {
46821          return arrayClasses.includes(service.class);
46822        });
46823      }
46824    }
46825  }, {
46826    key: 'filterByCompany',
46827    value: function filterByCompany(result) {
46828      var arrayCompanies = [];
46829      $('[data-js="company-checkbox"]:checked').each(function (i, el) {
46830        var value = $(el).next().text().trim();
46831        arrayCompanies.push(value.toUpperCase());
46832      });
46833      return result.filter(function (service) {
46834        return arrayCompanies.includes(service.company);
46835      });
46836    }
46837  }, {
46838    key: 'filterByDetail',
46839    value: function filterByDetail(result) {
46840      var arrayDetails = [];
46841      var classDetails = []; // filter by details will be based on classes due to JCA service format
46842
46843      $('[data-js="details-checkbox"]:checked').each(function (i, el) {
46844        var value = $(el).next().text().trim();
46845        arrayDetails.push(value.toUpperCase());
46846      });
46847
46848      this.details.forEach(function (det) {
46849        det.details.forEach(function (d) {
46850          if (arrayDetails.includes(d.classDetailName.toUpperCase())) {
46851            classDetails.push(det.className.toUpperCase());
46852          }
46853        });
46854      });
46855
46856      return classDetails.length > 0 ? result.filter(function (service) {
46857        return [].concat(_toConsumableArray(new Set(classDetails))).includes(service.class);
46858      }) : result;
46859    }
46860  }, {
46861    key: 'filterByHourDeparture',
46862    value: function filterByHourDeparture(result) {
46863      var _this9 = this;
46864
46865      var hourRange = this.getRangeValues(true);
46866      var formData = SessionStorage.get('formData');
46867
46868      if (hourRange[0] != '00:00' || hourRange[1] != '24:00') {
46869        result = result.filter(function (service) {
46870          var departure = DateFormatter.getValidDateFormat(service.departureDate);
46871          var filter_min = void 0,
46872            filter_max = void 0,
46873            date = void 0;
46874
46875          if (_this9.isReturn()) date = formData.return.date; else date = formData.depart.date;
46876
46877          filter_min = DateFormatter.getValidDateFormat(date + 'T' + hourRange[0]);
46878          filter_max = DateFormatter.getValidDateFormat(date + 'T' + hourRange[1]);
46879          return departure >= filter_min && departure <= filter_max;
46880        });
46881      }
46882      return result;
46883    }
46884  }, {
46885    key: 'filterByHourArrival',
46886    value: function filterByHourArrival(result) {
46887      var hourRange = this.getRangeValues(false);
46888      var formData = SessionStorage.get('formData');
46889
46890      if (hourRange[0] != '00:00' || hourRange[1] != '24:00') {
46891        result = result.filter(function (service) {
46892          var arrival = DateFormatter.getValidDateFormat(service.arrivalDate);
46893          var filter_min = void 0,
46894            filter_max = void 0,
46895            date = void 0;
46896
46897          date = arrival.toISOString().split('T')[0];
46898
46899          filter_min = DateFormatter.getValidDateFormat(date + 'T' + hourRange[0]);
46900          filter_max = DateFormatter.getValidDateFormat(date + 'T' + hourRange[1]);
46901          return arrival >= filter_min && arrival <= filter_max;
46902        });
46903      }
46904      return result;
46905    }
46906  }, {
46907    key: 'toggleFilter',
46908    value: function toggleFilter() {
46909      $('#wemobi-header').addClass('opened-overlay');
46910      var body = $('body');
46911
46912      var _Utils$getWindowSize2 = Utils.getWindowSize(),
46913        width = _Utils$getWindowSize2.width,
46914        breakpoints = _Utils$getWindowSize2.breakpoints;
46915
46916      this.modalFilter.toggleClass('active');
46917      
46918      if (this.modalFilter.hasClass('active')) {
46919        this.btnFilter.find('.arrow-icon').addClass('opened');
46920      } else {
46921        this.btnFilter.find('.arrow-icon').removeClass('opened');
46922      }
46923
46924      if (width <= breakpoints.LG && this.modalFilter.hasClass('active')) {
46925        body.css('position', 'fixed');
46926        body.css('width', width);
46927      } else {
46928        body.css('position', 'relative');
46929      }
46930    }
46931  }, {
46932    key: 'closeFilter',
46933    value: function closeFilter() {
46934      $('#wemobi-header').removeClass('opened-overlay');
46935      var body = $('body');
46936
46937      body.css('position', 'relative');
46938      body.css('width', 'auto');
46939      this.modalFilter.removeClass('active');
46940      this.btnFilter.find('.arrow-icon').removeClass('opened');
46941    }
46942  }, {
46943    key: 'resetSlider',
46944    value: function resetSlider() {
46945      var flatSlider = $('[data-js="flat-slider"]');
46946      $(flatSlider).slider("values", [0, 24]);
46947
46948      var flatSliderArr = $('[data-js="flat-slider-arrival"]');
46949      $(flatSliderArr).slider("values", [0, 24]);
46950
46951      $('.accordion-filter.active').removeClass('active');
46952      this.hourRange.text("0:00 - 24:00");
46953      SessionStorage.remove('filteredResult');
46954
46955      $('input[type=checkbox]').each(function () {
46956        if ($(this).is(':checked')) $(this).prop('checked', false);
46957      });
46958
46959      this.btnApply.click();
46960    }
46961  }, {
46962    key: 'cleanFilter',
46963    value: function cleanFilter() {
46964      this.flatSlider.slider("values", [0, 24]);
46965      this.flatSliderArr.slider("values", [0, 24]);
46966      this.hourRange.text("0:00 - 24:00");
46967
46968      $('[data-js="company-checkbox"]').each(function () {
46969        $(this).prop('checked', true);
46970      });
46971
46972      $('[data-js="class-checkbox"]').each(function () {
46973        $(this).prop('checked', false);
46974      });
46975
46976      SessionStorage.remove('filteredResult');
46977    }
46978  }, {
46979    key: 'capitalize',
46980    value: function capitalize(str) {
46981      var strArray = str.split(" ");
46982
46983      for (var i = 0; i < strArray.length; i++) {
46984        strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].slice(1).toLowerCase();
46985      }
46986
46987      return strArray.join(" ");
46988    }
46989  }, {
46990    key: 'isReturn',
46991    value: function isReturn() {
46992      return this.searchResultRef.isReturn();
46993    }
46994  }]);
46995
46996  return ResultFilter;
46997}();
46998'use strict';
46999
47000var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
47001
47002function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
47003
47004/**
47005 * RESULTS SIDE FILTERS
47006 *
47007 * BEGIN
47008 */
47009
47010var ResultsSideFilters = function () {
47011  function ResultsSideFilters($) {
47012    _classCallCheck(this, ResultsSideFilters);
47013
47014    this.accordionTarget = $('[data-js="accordion-target"]');
47015    this.flatSliderDesk = $('[data-js="flat-slider"]');
47016    this.hourRanges = {
47017      departure: $('[data-js="hour-range"][data-referer="departure"]'),
47018      return: $('[data-js="hour-range"][data-referer="return"]')
47019    };
47020    this.init();
47021  }
47022
47023  _createClass(ResultsSideFilters, [{
47024    key: 'init',
47025    value: function init() {
47026      this.handleEvents();
47027      this.loadSlider();
47028    }
47029  }, {
47030    key: 'loadSlider',
47031    value: function loadSlider() {
47032      var _this = this;
47033
47034      this.flatSliderDesk.slider({
47035        orientation: 'horizontal',
47036        min: 0,
47037        max: 24,
47038        range: true,
47039        values: [0, 24],
47040        slide: function slide(e, ui) {
47041          var referer = $(e.target).data('referer');
47042          var text = ui.values[0] + ':00 - ' + ui.values[1] + ':00';
47043          _this.hourRanges[referer].text(text);
47044        }
47045      });
47046    }
47047  }, {
47048    key: 'handleEvents',
47049    value: function handleEvents() {
47050      this.accordionTarget.on('click', function () {
47051        var $el = $(this);
47052        var $section = $el.parent();
47053
47054        $section.toggleClass('active');
47055      });
47056    }
47057  }]);
47058
47059  return ResultsSideFilters;
47060}();
47061'use strict';
47062
47063var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
47064
47065function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
47066
47067/**
47068 * INICIO
47069 * LOGICA ABA PASSAGENS HOTEIS
47070 *
47071 */
47072
47073var CBPFWTabs = function () {
47074  function CBPFWTabs(el, options) {
47075    _classCallCheck(this, CBPFWTabs);
47076
47077    this.options = {
47078      start: 0
47079    };
47080    this.el = el;
47081    this.options = this.extend({}, this.options);
47082    this.extend(this.options, options);
47083    this._init();
47084  }
47085
47086  _createClass(CBPFWTabs, [{
47087    key: 'extend',
47088    value: function extend(a, b) {
47089      for (var key in b) {
47090        if (b.hasOwnProperty(key)) {
47091          a[key] = b[key];
47092        }
47093      }
47094      return a;
47095    }
47096  }, {
47097    key: '_init',
47098    value: function _init() {
47099      // tabs elems
47100      this.tabs = [].slice.call(this.el.querySelectorAll('.buy-menu > ul > li'));
47101      // content items
47102      this.items = [].slice.call(this.el.querySelectorAll('.content-wrap > section'));
47103      // current index
47104      this.current = -1;
47105      // show current content item
47106      this._show();
47107      // init events
47108      this._initEvents();
47109    }
47110  }, {
47111    key: '_initEvents',
47112    value: function _initEvents() {
47113      var self = this;
47114      this.tabs.forEach(function (tab, idx) {
47115        tab.addEventListener('click', function (ev) {
47116          ev.preventDefault();
47117          self._show(idx);
47118        });
47119      });
47120    }
47121  }, {
47122    key: '_show',
47123    value: function _show(idx) {
47124      if (this.current >= 0) {
47125        this.tabs[this.current].className = this.items[this.current].className = '';
47126      }
47127      // change current
47128      this.current = idx != undefined ? idx : this.options.start >= 0 && this.options.start < this.items.length ? this.options.start : 0;
47129      this.tabs[this.current].className = 'tab-current';
47130      this.items[this.current].className = 'content-current';
47131    }
47132  }]);
47133
47134  return CBPFWTabs;
47135}();
47136
47137/**
47138 * FIM
47139 * LOGICA ABA PASSAGENS HOTEIS
47140 *
47141 */
47142'use strict';
47143
47144var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
47145
47146function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
47147
47148/**
47149 * INICIO
47150 * LOGICA DATEPICKER
47151 *
47152 */
47153var DatePickerControl = function () {
47154  function DatePickerControl($, searchComponentRef, personWindowRef) {
47155    _classCallCheck(this, DatePickerControl);
47156
47157    this.departure = $('[data-js="input-date-departure"]:visible');
47158    this.departureDateObject = {};
47159    this.returnDateObject = {};
47160    this.return = $('[data-js="input-date-return"]:visible');
47161    this.overlay = $("#overlay");
47162    this.datepicker = $("#ui-datepicker-div");
47163    this.dateMin = $('[data-js="input-date-departure"]').attr('data-date-min');
47164    this.searchComponentRef = searchComponentRef;
47165    this.personWindowRef = personWindowRef;
47166    this.init();
47167  }
47168
47169  _createClass(DatePickerControl, [{
47170    key: 'init',
47171    value: function init() {
47172      var _this = this;
47173
47174      this.loadDatepicker();
47175      this.checkExternalClick();
47176      this.setDatePickerReadonly();
47177
47178      $(window).on('resize', function () {
47179        _this.setDatePickerReadonly();
47180        if (_this.departure.closest('.input-date-container').hasClass('active')) {
47181          _this.setMonthsDatepicker(12, 1, _this.departure);
47182        } else if (_this.return.closest('.input-date-container').hasClass('active')) {
47183          _this.setMonthsDatepicker(12, 1, _this.return);
47184        }
47185      });
47186    }
47187  }, {
47188    key: 'setDatePickerReadonly',
47189    value: function setDatePickerReadonly() {
47190      var windowSize = Utils.getWindowSize();
47191      if (windowSize.width <= windowSize.breakpoints.LG) {
47192        this.departure.attr('readonly', true);
47193        this.return.attr('readonly', true);
47194      } else {
47195        this.departure.removeAttr('readonly');
47196        this.return.removeAttr('readonly');
47197      }
47198    }
47199  }, {
47200    key: 'checkExternalClick',
47201    value: function checkExternalClick() {
47202      var _this2 = this;
47203
47204      $('body').off("mousedown", $.datepicker._checkExternalClick).click(function (e) {
47205        var container = $("#ui-datepicker-div, .datepicker, .datepicker-mobile");
47206        if (!container.is(e.target) && container.has(e.target).length === 0 && !$(e.target).hasClass("ui-datepicker-prev") && !$(e.target).hasClass("ui-datepicker-next") && !$(e.target).hasClass("input-date") && !$(e.target).is('body')) {
47207          if ($("#ui-datepicker-div").is(":visible")) {
47208            if (Utils.getWindowSize().width > Utils.getWindowSize().breakpoints.LG) _this2.closeDatepicker();
47209          }
47210        }
47211      });
47212    }
47213  }, {
47214    key: 'closeDatepicker',
47215    value: function closeDatepicker() {
47216      this.departure.datepicker("hide");
47217      this.return.datepicker("hide");
47218    }
47219  }, {
47220    key: 'markDates',
47221    value: function markDates() {
47222      if (!this.departureDateObject.year || !this.returnDateObject.finalYear) {
47223        return;
47224      }
47225
47226      var _returnDateObject = this.returnDateObject,
47227        finalDay = _returnDateObject.finalDay,
47228        finalMonth = _returnDateObject.finalMonth,
47229        finalYear = _returnDateObject.finalYear;
47230      var _departureDateObject = this.departureDateObject,
47231        day = _departureDateObject.day,
47232        month = _departureDateObject.month,
47233        year = _departureDateObject.year;
47234
47235
47236      this.datepicker.find('td[data-month="' + month + '"][data-year="' + year + '"]').each(function () {
47237        var td = $(this);
47238        if (td.text().trim() === day.toString()) {
47239          td.addClass("start-day");
47240          $("a", td).addClass("ui-state-active");
47241        }
47242      });
47243
47244      this.datepicker.find("td:not(.ui-datepicker-unselectable)").each(function () {
47245        var td = $(this);
47246        var tdDay = parseInt(td.text().trim());
47247        var tdMonth = td.data("month");
47248        var tdYear = td.data("year");
47249
47250        if (tdYear < finalYear) {
47251          td.addClass("is-between");
47252        } else if (tdYear === finalYear) {
47253          if (tdMonth == finalMonth) {
47254            if (tdDay < finalDay) {
47255              td.addClass("is-between");
47256            }
47257          } else if (tdMonth < finalMonth) {
47258            td.addClass("is-between");
47259          }
47260        }
47261
47262        if (tdDay === finalDay && tdMonth === finalMonth && tdYear === finalYear) {
47263          td.addClass("end-day");
47264        }
47265      });
47266    }
47267  }, {
47268    key: 'markPrevDate',
47269    value: function markPrevDate() {
47270      var _departureDateObject2 = this.departureDateObject,
47271        day = _departureDateObject2.day,
47272        month = _departureDateObject2.month,
47273        year = _departureDateObject2.year;
47274
47275
47276      this.datepicker.find('td[data-month="' + month + '"][data-year="' + year + '"]').each(function () {
47277        var td = $(this);
47278        if (td.text().trim() === day.toString()) {
47279          $("a", td).addClass("ui-state-active");
47280        }
47281      });
47282    }
47283  }, {
47284    key: 'setMonthsDatepicker',
47285    value: function setMonthsDatepicker(mobileNumberOfMonths, deskNumberOfMonths, element) {
47286      var isMobile = Utils.getWindowSize().width <= Utils.getWindowSize().breakpoints.LG;
47287      element.datepicker("option", "numberOfMonths", isMobile ? mobileNumberOfMonths : deskNumberOfMonths);
47288    }
47289  }, {
47290    key: 'backToHome',
47291    value: function backToHome() {
47292      var _this3 = this;
47293
47294      if (Utils.getWindowSize().width <= Utils.getWindowSize().breakpoints.LG) {
47295        var isSelectDate = $('.ui-datepicker-current-day');
47296        $('.btn-conf-datepicker').click(function () {
47297          _this3.closeDatepicker();
47298        }).addClass('active');
47299
47300        $(document).on('click', '[data-js="datepicker-back-btn"]', function () {
47301          _this3.closeDatepicker();
47302        });
47303      }
47304    }
47305  }, {
47306    key: 'insertDatepickerMobileStyle',
47307    value: function insertDatepickerMobileStyle() {
47308      var _this4 = this;
47309
47310      if (Utils.getWindowSize().width <= Utils.getWindowSize().breakpoints.LG) {
47311        var labelHeaderDatepicker = $('.input-date-container.active').children('.inner-container').attr('id') === 'input-container-dep' ? 'Data de ida' : 'Data de volta';
47312
47313        var header = $('<div class=\'datepicker-mobile datepicker-header\'>\n          <span data-js="datepicker-back-btn"><em class="jca-ico-angle-left" aria-hidden="true"></em></span>\n          <h4 class=\'header-datepicker\'>\n            ' + labelHeaderDatepicker + '\n          </h4>\n        </div>');
47314        var footer = $('<div class=\'datepicker-mobile datepicker-footer\'>\n          <button class=\'btn-conf-datepicker\' id=\'btn-conf-datepicker\'>\n Selecionar \n          </button>\n        </div>\n      ');
47315
47316        setTimeout(function () {
47317          header.prependTo("#ui-datepicker-div");
47318          footer.appendTo("#ui-datepicker-div");
47319          _this4.backToHome();
47320        }, "fast");
47321      } else {
47322        $('.datepicker-mobile').remove();
47323      }
47324    }
47325  }, {
47326    key: 'closeDatepickerAfterSelect',
47327    value: function closeDatepickerAfterSelect(datepicker) {
47328      if (Utils.getWindowSize().width > Utils.getWindowSize().breakpoints.LG) {
47329        return datepicker.inline = false;
47330      }
47331    }
47332  }, {
47333    key: 'loadDatepicker',
47334    value: function loadDatepicker() {
47335      var _this5 = this;
47336
47337      this.departure.val("");
47338      this.departure.mask('99/99/9999');
47339      this.departure.datepicker({
47340        dateFormat: DateFormatter.getDateFormat(),
47341        minDate: this.dateMin && DateFormatter.getValidDateFormat(this.dateMin) > new Date() ? DateFormatter.getValidDateFormat(this.dateMin) : new Date(),
47342        showAnim: Utils.isMobile() ? '' : 'slideDown',
47343        autoClose: true,
47344        onChangeMonthYear: function onChangeMonthYear() {
47345          _this5.insertDatepickerMobileStyle();
47346          _this5.datepicker = $("#ui-datepicker-div");
47347
47348          setTimeout(function () {
47349            if (!$('.search-results-header').hasClass('active')) {
47350              var pickerWidth = $('#input-container-ret').width();
47351              _this5.datepicker.width(pickerWidth - 20);
47352            }
47353
47354            _this5.tealeafDatepicker();
47355          }, 10);
47356        },
47357        beforeShow: function beforeShow(el, datepicker) {
47358          _this5.datepicker = $("#ui-datepicker-div");
47359          _this5.departure.closest(".input-date-container").addClass("active");
47360          _this5.insertDatepickerMobileStyle();
47361          _this5.setMonthsDatepicker(12, 1, _this5.departure);
47362          _this5.datepicker.addClass("opened");
47363
47364          if (Utils.getWindowSize().width < 951) $("#ui-datepicker-div").animate({ scrollTop: $(_this5).offset().top - 100 }, "fast");
47365
47366          setTimeout(function () {
47367            var left = Utils.getWindowSize().width - datepicker.dpDiv.outerWidth();
47368            var maxLeft = Math.min($(el).parent().offset().left, left);
47369            var dpTop = $(el).offset().top + $(el).outerHeight();
47370
47371            if ($('#change-way-overlay').is(':visible')) {
47372              $('#ui-datepicker-div').appendTo('#change-way-overlay');
47373              datepicker.dpDiv.css({ top: dpTop - 20 - window.scrollY, left: maxLeft });
47374              _this5.datepicker.addClass("on-overlay");
47375            } else {
47376              $("html, body").animate({ scrollTop: $(".search-container").offset().top - 100 }, 500);
47377              datepicker.dpDiv.css({ top: dpTop - 20, left: maxLeft });
47378            }
47379
47380            datepicker.dpDiv.width($(el).parent().width() - 20);
47381          }, 10);
47382        },
47383        onSelect: function onSelect(dateStr, datepicker) {
47384          setTimeout(function () {
47385            if (dateStr !== DateFormatter.parseDateFormat(new Date())) $('.ui-state-hover, .ui-widget-content .ui-state-hover').css('background', 'transparent'); else $('.ui-state-hover, .ui-widget-content .ui-state-hover').css('background', '#0b67b1');
47386          }, "fast");
47387
47388          datepicker.inline = true;
47389          _this5.insertDatepickerMobileStyle();
47390          _this5.closeDatepickerAfterSelect(datepicker);
47391          _this5.departure.data("date", DateFormatter.parseDateApiFormat(dateStr));
47392          _this5.return.datepicker("option", "minDate", dateStr);
47393          _this5.departure.parent().removeClass('has-invalid-input');
47394          _this5.departureDateObject = {
47395            day: parseInt(datepicker.selectedDay),
47396            month: datepicker.selectedMonth,
47397            year: datepicker.selectedYear
47398          };
47399        },
47400        onClose: function onClose(_, datepicker) {
47401          datepicker.inline = false;
47402          _this5.departure.closest(".input-date-container").removeClass("active");
47403          _this5.datepicker.removeClass("opened");
47404          _this5.datepicker.removeClass("header-datepicker");
47405          $('.search-results-header').removeClass('active');
47406          $('body, html').css('overflow-y', 'auto');
47407        }
47408      });
47409
47410      this.return.val("");
47411      this.return.mask('99/99/9999');
47412      this.return.datepicker({
47413        dateFormat: DateFormatter.getDateFormat(),
47414        minDate: this.dateMin && DateFormatter.getValidDateFormat(this.dateMin) > new Date() ? DateFormatter.getValidDateFormat(this.dateMin) : new Date(),
47415        showAnim: Utils.isMobile() ? '' : 'slideDown',
47416        onChangeMonthYear: function onChangeMonthYear(el, datepicker) {
47417          _this5.insertDatepickerMobileStyle();
47418          _this5.datepicker = $("#ui-datepicker-div");
47419
47420          setTimeout(function () {
47421            if (!$('.search-results-header').hasClass('active')) {
47422              var pickerWidth = $('#input-container-ret').width();
47423              _this5.datepicker.width(pickerWidth - 20);
47424            }
47425
47426            _this5.markPrevDate();
47427            _this5.markDates();
47428            _this5.tealeafDatepicker();
47429          }, 10);
47430        },
47431        beforeShow: function beforeShow(el, datepicker) {
47432          _this5.datepicker = $("#ui-datepicker-div");
47433          _this5.insertDatepickerMobileStyle();
47434          _this5.return.closest(".input-date-container").addClass("active");
47435          _this5.setMonthsDatepicker(12, 1, _this5.return);
47436          _this5.datepicker.addClass("opened");
47437          _this5.prevDateReturn = _this5.return.val();
47438
47439          if (Utils.getWindowSize().width < 951) $("#ui-datepicker-div").animate({ scrollTop: $(_this5).offset().top - 100 }, "fast");
47440
47441          setTimeout(function () {
47442            var dpDiv = datepicker.dpDiv;
47443
47444            var left = Utils.getWindowSize().width - dpDiv.outerWidth();
47445            var maxLeft = Math.min($(el).parent().offset().left, left);
47446            $('.btn-conf-datepicker').addClass('active');
47447            var dpTop = $(el).offset().top + $(el).outerHeight();
47448            _this5.markPrevDate();
47449
47450            if (_this5.returnDateObject.finalYear) _this5.markDates();
47451
47452            if ($('#change-way-overlay').is(':visible')) {
47453              $('#ui-datepicker-div').appendTo('#change-way-overlay');
47454              _this5.datepicker.addClass("on-overlay");
47455              dpDiv.css({ top: dpTop - 20 - window.scrollY, left: maxLeft });
47456            } else {
47457              $("html, body").animate({ scrollTop: $(".search-container").offset().top - 100 }, 500);
47458              dpDiv.css({ top: dpTop - 20, left: maxLeft });
47459            }
47460
47461            dpDiv.width($(el).parent().width() - 20);
47462          }, 10);
47463        },
47464        onSelect: function onSelect(dateStr, datepicker) {
47465          datepicker.inline = true;
47466          _this5.insertDatepickerMobileStyle();
47467          _this5.return.data("date", DateFormatter.parseDateApiFormat(dateStr));
47468          _this5.closeDatepickerAfterSelect(datepicker);
47469          _this5.returnDateObject = {
47470            finalDay: parseInt(datepicker.selectedDay),
47471            finalMonth: datepicker.selectedMonth,
47472            finalYear: datepicker.selectedYear
47473          };
47474
47475          setTimeout(function () {
47476            _this5.markPrevDate();
47477            _this5.markDates();
47478          });
47479        },
47480        onClose: function onClose(_, datepicker) {
47481          datepicker.inline = false;
47482          _this5.return.closest(".input-date-container").removeClass("active");
47483          _this5.datepicker.removeClass("opened");
47484          _this5.datepicker.removeClass("header-datepicker");
47485          $('.search-results-header').removeClass('active');
47486          $('body, html').css('overflow-y', 'auto');
47487        }
47488      });
47489
47490      this.departure.add(this.return).click(function () {
47491        ValidationService.close();
47492        _this5.searchComponentRef.removeInputInvalidClasses();
47493        _this5.tealeafDatepicker();
47494      });
47495
47496      this.departure.focusout(function (e) {
47497        var input = $(e.currentTarget);
47498        var dateString = input.val().split('/').reverse().join('/');
47499        var date = new Date(dateString);
47500        var today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
47501        if (isNaN(date) || date <= today) date = today;
47502        dateString = DateFormatter.parseDateFormat(date);
47503        if (!input.data("date") || input.data('date') != dateString) {
47504          input.data("date", DateFormatter.parseDateApiFormat(dateString));
47505        }
47506      });
47507
47508      this.return.focusout(function (e) {
47509        var input = $(e.currentTarget);
47510        if (input.val().length > 0) {
47511          var dateString = input.val().split('/').reverse().join('/');
47512          var date = new Date(dateString);
47513          var today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate());
47514          if (isNaN(date)) {
47515            input.val('');
47516          } else {
47517            if (date < today) date = today; else {
47518              var departureDate = new Date(_this5.departure.data('date').split('-').join('/'));
47519              if (date < departureDate) date = departureDate;
47520            }
47521            dateString = DateFormatter.parseDateFormat(date);
47522            if (!input.data("date") || input.data('date') != dateString) {
47523              input.data("date", DateFormatter.parseDateApiFormat(dateString));
47524              input.val(dateString);
47525            }
47526          }
47527        }
47528      });
47529
47530      $('[data-js="remove-date-return"]').click(function () {
47531        return _this5.removeReturn();
47532      });
47533    }
47534  }, {
47535    key: 'removeReturn',
47536    value: function removeReturn() {
47537      var formData = SessionStorage.get("formData");
47538      this.searchComponentRef.dateReturn.data("date", "");
47539      this.searchComponentRef.dateReturn.val("");
47540
47541      if (formData) {
47542        formData.return.date = "";
47543        formData.return.minDate = "";
47544      }
47545
47546      this.returnDateObject = {};
47547    }
47548  }, {
47549    key: 'tealeafDatepicker',
47550    value: function tealeafDatepicker() {
47551      $('.ui-state-default').each(function (idx, el) {
47552        var day = $(el).text();
47553        var month = +$(el).parent().attr('data-month') + 1;
47554        var year = $(el).parent().attr('data-year');
47555
47556        $(el).attr('id', 'calendar-' + day + '-' + month + '-' + year).addClass('calendar');
47557      });
47558
47559      $('.ui-datepicker-prev').attr('id', 'prev-datepicker');
47560      $('.ui-datepicker-next').attr('id', 'next-datepicker');
47561    }
47562  }]);
47563
47564  return DatePickerControl;
47565}();
47566
47567/**
47568 * FIM
47569 * LOGICA DATEPICKER
47570 *
47571 */
47572'use strict';
47573
47574var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
47575
47576function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
47577
47578/**
47579 *
47580 * INICIO
47581 * LOGICA INPUT ORIGEM E DESTINO
47582 *
47583 */
47584if ($('[data-js="custom-store-component"]') && $('[data-js="custom-store-component"]').length > 0) {
47585  new SearchComponentDynamic($);
47586};
47587$.widget("custom.catcomplete", $.ui.autocomplete, {
47588  _create: function _create() {
47589    this._super();
47590    this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)", "> :not(.ui-autocomplete-collapse)");
47591  },
47592  _renderMenu: function _renderMenu(ul, items) {
47593    var that = this;
47594
47595    $.each(items, function (_, item) {
47596      that._renderItemData(ul, item);
47597    });
47598  }
47599});
47600
47601var LocationInput = function () {
47602  function LocationInput($, searchComponentRef, shouldRevertInputs) {
47603    var serviceClick = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
47604
47605    _classCallCheck(this, LocationInput);
47606
47607    this.departure = $('[data-js="input-departure"]:visible');
47608    this.destination = $('[data-js="input-destination"]:visible');
47609    this.btnTripWay = $('[data-js="btn-change-way"]');
47610    this.close = $('[data-js="overlay-arrow-left"]:visible');
47611    this.overlay = $('#overlay');
47612    this.label = $('[data-js="label-overlay"]:visible');
47613    this.container = $('[data-js="label-overlay-container"]:visible');
47614    this.dateDeparture = $('[data-js="input-date-departure"]:visible');
47615    this.isPinInInputsLocation = this.departure.attr('data-pin');
47616    this.shouldRevertInputs = shouldRevertInputs ? shouldRevertInputs : null;
47617    this.lastSelected = {};
47618    this.focusOutSet = {};
47619    this.searchComponentRef = searchComponentRef;
47620    this.serviceClick = serviceClick;
47621    this.toggleSearchMode = $('[data-js="toggle-search-mode-aem"]').val() == 'true';
47622    this.test;
47623    this.rankingOrigin = [];
47624    this.rankingDestination = [];
47625    this.nearestOrigin = [];
47626    this.acceptedLocation = false;
47627    this.useUserLocation = false;
47628    this.locationError = false;
47629  }
47630
47631
47632  _createClass(LocationInput, [{
47633    key: "initForSearchComponent",
47634    value: function initForSearchComponent(latitude, longitude) {
47635      this.loadInputs(latitude, longitude);
47636      this.handleCancel();
47637      this.checkLinkClick();
47638      this.listenInputs();
47639      this.updateServiceDestination();
47640    }
47641  }, {
47642    key: "updateServiceDestination",
47643    value: function updateServiceDestination() {
47644      var _this = this;
47645
47646      this.departure.on('click focus', function () {
47647        var saveDestination = SessionStorage.get('serviceDestination');
47648
47649        if (saveDestination) {
47650          SessionStorage.remove('serviceDestination');
47651          _this.destination.catcomplete("option", "source", []);
47652        }
47653      });
47654    }
47655  }, {
47656    key: "filterInputLocationAutocompleteMobile",
47657    value: function filterInputLocationAutocompleteMobile(localeSearched) {
47658      var _this = this;
47659
47660      var $inputDeparture = $('#input-departure');
47661      var $inputDestination = $('#input-destination');
47662
47663      var getElemInputLocation = function getElemInputLocation() {
47664        return _this.isDepartureInputActive() ? $inputDeparture : $inputDestination;
47665      };
47666
47667      var $inputLocation = getElemInputLocation();
47668      $inputLocation.val(localeSearched).trigger('input');
47669      $('.ui-autocomplete').addClass('active');
47670    }
47671  }, {
47672    key: "isDepartureInputActive",
47673    value: function isDepartureInputActive() {
47674      return $('#input-departure').hasClass('active');
47675    }
47676  }, {
47677    key: "listenInputs",
47678    value: function listenInputs() {
47679      var _this2 = this;
47680      $('#input-departure').click(function () {
47681        $('[data-js="header-location"]').text('Origem');
47682      });
47683
47684      $('#input-destination').click(function () {
47685        $('[data-js="header-location"]').text('Destino');
47686      });
47687
47688      $('#input-mobile').on('input', function () {
47689        var localeSearched = $('#input-mobile').val();
47690        _this2.filterInputLocationAutocompleteMobile(localeSearched);
47691      }).on('click focus', function () {
47692        _this2.isDepartureInputActive() ? $('.ui-autocomplete').first().css('display', 'block') : $('.ui-autocomplete').last().css('display', 'block');
47693        ($('.ui-autocomplete').first().length > 0) ? $('.ui-autocomplete').first().css('display', 'none') : $('.ui-autocomplete').first().css('display', 'block');
47694      });
47695    }
47696  }, {
47697    key: "focusInput",
47698    value: function focusInput(element) {
47699      element.parent().addClass('active');
47700    }
47701  }, {
47702    key: "searchForBlank",
47703    value: function searchForBlank(element) {
47704      if (element.data("custom-catcomplete") && element.val().trim().length === 0) element.catcomplete("search", "");
47705    }
47706  }, {
47707    key: "highlightInput",
47708    value: function highlightInput(element) {
47709      if (element.hasClass('invalid')) element.removeClass('invalid');
47710      element.addClass('highlight');
47711    }
47712  }, {
47713    key: "showLabel",
47714    value: function showLabel(element) {
47715      element.val('');
47716      element.addClass('active');
47717      var label_text = this.getLabelText(element.attr('id'));
47718      this.setLabelText(label_text);
47719    }
47720  }, {
47721    key: "loadDestinationAutocomplete",
47722    value: function loadDestinationAutocomplete() {
47723      var departureDataValue = this.lastSelected[this.departure.data('js')];
47724
47725      if (departureDataValue) this.initDestinationAutocomplete(departureDataValue);
47726    }
47727  }, {
47728    key: "loadInputs",
47729    value: function loadInputs(latitude, longitude) {
47730      var _this4 = this;
47731
47732      this.departure.val('');
47733      this.destination.val('');
47734
47735      var onFocus = function onFocus(e) {
47736        var element = $(e.currentTarget);
47737        addAuxiliaryClass(element);
47738        _this4.focusInput(element);
47739        element.val('');
47740        element.data('value', '');
47741        element.data('address', '');
47742        _this4.searchForBlank(element);
47743        _this4.highlightInput(element);
47744        _this4.showLabel(element);
47745
47746        if (_this4.loginButton && $('[data-js="header-login-modal-overlay"]').hasClass('active')) _this4.loginButton.closeLoginModal();
47747      };
47748
47749      this.departure.add(this.destination).off('focus blur click').on('focus click', function (e) {
47750        onFocus(e);
47751        ValidationService.close();
47752        $('#autocomplete-wrapper').addClass('active');
47753        $('.ui-autocomplete').addClass('active');
47754        _this4.searchComponentRef.removeInputInvalidClasses();
47755      });
47756
47757      if (this.toggleSearchMode) {
47758        this.departure.add(this.destination).off('focusout blur').on('focusout blur', function (e) {
47759          if ($('#autocomplete-wrapper').hasClass('active') && $('.ui-autocomplete').hasClass('active')) {
47760            $('#autocomplete-wrapper').removeClass('active');
47761            $('.ui-autocomplete').removeClass('active');
47762          }
47763        });
47764      }
47765
47766      var addAuxiliaryClass = function addAuxiliaryClass(element) {
47767        if ($(window).width() >= 950 && element.parent().parent().hasClass('header-filter')) {
47768          $('.ui-menu').addClass('on-header');
47769          $('.search-results-header').addClass('active');
47770        }
47771        if ($(window).width() < 950 && element.closest('.change-way-overlay').length > 0) {
47772          $('.ui-menu').addClass('on-overlay');
47773          if (_this4.toggleSearchMode) $('#autocomplete-wrapper').addClass('enhanced-change-way-mobile');
47774        }
47775      };
47776
47777      var autoCompleteWrapper = $("<div id=\"autocomplete-wrapper\" class=\"ui-autocomplete-wrapper\"></div>");
47778      $('body').append(autoCompleteWrapper);
47779
47780      this.inputFocusOutEvent(this.departure);
47781      this.inputFocusOutEvent(this.destination);
47782      this.initOriginAutocomplete(this.shouldRevertInputs ? this.destination : this.departure, latitude, longitude, null, null, null);
47783      if (this.toggleSearchMode) {
47784        $('#autocomplete-wrapper').addClass('enhanced-search-mobile');
47785        $('#autocomplete-wrapper').removeClass('normal-search-mobile');
47786        this.addFieldsIntoInputAutoComplete();
47787      } else {
47788        $('#autocomplete-wrapper').addClass('normal-search-mobile');
47789        $('#autocomplete-wrapper').removeClass('enhanced-search-mobile');
47790      }
47791    }
47792  }, {
47793    key: "fillWithNearestOrigin",
47794    value: function fillWithNearestOrigin(nearestList) {
47795      var location = null;
47796
47797      if (nearestList.length === 1) {
47798        // Se houver apenas um elemento, use-o
47799        location = nearestList[0];
47800      } else if (nearestList.length > 1) {
47801        // Filtrar itens que contêm "todos" no label, ignorando maiúsculas e minúsculas
47802        var todosItems = nearestList.filter(function (item) {
47803          return item.label.toLowerCase().includes("todos");
47804        });
47805
47806        // Função para extrair a distância como número
47807        var getDistance = function getDistance(item) {
47808          return parseFloat(item.distance.split(' ')[0]);
47809        };
47810
47811        // Ordenar por distância e pegar o menor
47812        if (todosItems.length > 0) {
47813          location = todosItems.reduce(function (prev, curr) {
47814            return getDistance(prev) < getDistance(curr) ? prev : curr;
47815          });
47816        } else {
47817          location = nearestList.reduce(function (prev, curr) {
47818            return getDistance(prev) < getDistance(curr) ? prev : curr;
47819          });
47820        }
47821      }
47822
47823      // Atualiza os valores de departure com base na localização encontrada
47824      this.departure.val(location ? location.label : '');
47825      this.departure.data('value', location ? location.value : '');
47826      this.departure.data('address', location ? location.address : '');
47827
47828      if (location) {
47829        this.lastSelected[this.departure.data('js')] = location;
47830        this.loadDestinationAutocomplete();
47831      }
47832    }
47833  }, {
47834    key: "addFieldsIntoInputAutoComplete",
47835    value: function addFieldsIntoInputAutoComplete() {
47836      var autoCompleteWrapper = $('#autocomplete-wrapper');
47837      autoCompleteWrapper.find('#header-input-location').remove();
47838      autoCompleteWrapper.find('#footer-input-location').remove();
47839
47840      if (!this.toggleSearchMode) {
47841        var isInputMobileDOM = $('#input-mobile').length > 0;
47842
47843        if (Utils.getWindowSize().width <= Utils.getWindowSize().breakpoints.LG) {
47844          this.addHeader(autoCompleteWrapper);
47845          if (!isInputMobileDOM) this.addInputMobile(autoCompleteWrapper);
47846        }
47847      }
47848
47849      this.addFooter(autoCompleteWrapper);
47850    }
47851  }, {
47852    key: "addFooter",
47853    value: function addFooter(element) {
47854      var redirect = $('[data-js="new-route-form-link"]').data('redirect');
47855      var page = $('[data-js="new-route-form-link"]').data('page');
47856      var formtext = $('[data-js="new-route-form-link"]').data('form-text');
47857      var modal = '#new-route-modal';
47858      if (!formtext) return;
47859
47860      formtext = $(formtext);
47861
47862      $(formtext).find('.form-new-routes-hyperLink').replaceWith(function () {
47863        var linkText = $(formtext).find('.form-new-routes-hyperLink').text();
47864        return (
47865          '<a href="#" class="form-new-route-link form-new-routes-hyperLink" tabindex="-1" data-action="' + (redirect ? page : modal) + '">' + linkText + '</a>'
47866        );
47867      });
47868
47869      var footer = $('<div id="footer-input-location" class="footer-input-location"><div id="new-route-link" class="new-route-link"><p>' + formtext.html() + '</p></div></div>');
47870      element.append(footer);
47871    }
47872  }, {
47873    key: "addHeader",
47874    value: function addHeader(element) {
47875      var _this4 = this;
47876
47877      var header = $("\n      <div id=\"header-input-location\" class=\"header-input-location\">\n        <span id=\"close-input-location\" data-js=\"close-input-location\"><em class=\"jca-ico-angle-left\" aria-hidden=\"true\"></em></span>\n          <h4 class='header-location' data-js=\"header-location\">\n          </h4>\n      </div>\n    ");
47878      element.prepend(header);
47879
47880      $('#close-input-location').add('.header-location').click(function () {
47881        $('#autocomplete-wrapper').removeClass('active');
47882        $('.ui-autocomplete').removeClass('active');
47883        OverlayService.hide();
47884        _this4.container.removeClass('active');
47885        _this4.departure.removeClass('active');
47886        _this4.destination.removeClass('active');
47887        $('#input-mobile').val('');
47888      });
47889    }
47890  }, {
47891    key: "addInputMobile",
47892    value: function addInputMobile(element) {
47893      var input = $("\n      <div class=\"input-location-mobile-content\">\n\t      <label class=\"d-none\" for=\"input-mobile\"> Input </label>\n        <span class=\"input-icon\" aria-hidden=\"true\">\n          <em class=\"jca-ico-pin-map\"></em>\n        </span>\n        <input class=\"input-location-mobile\" type=\"text\" id=\"input-mobile\" data-js=\"input-mobile\" />\n      </div>\n    ");
47894      input.insertAfter(element.find('#header-input-location'));
47895      this.listenInputs();
47896    }
47897  }, {
47898    key: "handleCancel",
47899    value: function handleCancel() {
47900      var _this5 = this;
47901
47902      this.close.off('click').click(function () {
47903        _this5.hideOverlay();
47904      });
47905    }
47906  }, {
47907    key: 'getLabelText',
47908    value: function getLabelText(target_id) {
47909      if (target_id === 'input-departure') {
47910        return 'ORIGEM';
47911      } else {
47912        return 'DESTINO';
47913      }
47914    }
47915  }, {
47916    key: 'setLabelText',
47917    value: function setLabelText(label_text) {
47918      this.label.text(label_text);
47919    }
47920  }, {
47921    key: 'showOverlay',
47922    value: function showOverlay() {
47923      if ($('.change-way-overlay:visible').length === 0) OverlayService.show();
47924      this.container.addClass('active');
47925    }
47926  }, {
47927    key: 'hideOverlay',
47928    value: function hideOverlay() {
47929      this.container.removeClass('active');
47930      this.departure.removeClass('active');
47931      this.destination.removeClass('active');
47932    }
47933  }, {
47934    key: "getSource",
47935    value: function getSource(request, response, localidades, rankingList, nearestList, inputDataJs) {
47936      var _this7 = this;
47937
47938      var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
47939      var matcherWithoutAccent = new RegExp($.ui.autocomplete.escapeRegex(removeAcento(request.term)), "i");
47940      var filterValues = function filterValues(list) {
47941        return $.grep(list, function (value) {
47942          value = value.label || value.value || value;
47943          return matcher.test(value) || matcher.test(removeAcento(value)) || matcherWithoutAccent.test(value);
47944        });
47945      };
47946
47947      if (localidades) {
47948        var filteredAll = request.term ? filterValues(localidades) : filterValues(localidades).slice(0, 5);
47949
47950        if (!this.toggleSearchMode) {
47951          response(filteredAll);
47952        } else {
47953          var filteredRanking = rankingList && rankingList.length > 0 ? filterValues(rankingList) : filteredAll;
47954          var filteredNearest = nearestList && nearestList.length > 0 ? filterValues(nearestList) : filteredRanking;
47955          var result = request.term ? filteredAll : filteredNearest;
47956
47957          var useMyLocationText = $('[data-js="use-my-location-text"]').val();
47958          var useMyLocationErrorText = $('[data-js="use-my-location-error-text"]').val();
47959          var mostSearchedOriginsText = $('[data-js="most-searched-origins-text"]').val();
47960          var mostSearchedDestinationsText = $('[data-js="most-searched-destinations-text"]').val();
47961
47962          if (rankingList && rankingList.length > 0) {
47963            filteredRanking.unshift({ label: inputDataJs === "input-departure" ? mostSearchedOriginsText : mostSearchedDestinationsText, value: "ranking-title", address: '' });
47964          }
47965
47966          if (!this.acceptedLocation && inputDataJs === "input-departure") {
47967            result.unshift({ label: this.locationError ? useMyLocationErrorText : useMyLocationText, value: "use-my-location", address: '' });
47968            this.listCatComplete = result;
47969          }
47970
47971          response(result);
47972        }
47973      }
47974
47975      if (!this.toggleSearchMode) {
47976        if (Utils.getWindowSize().width <= Utils.getWindowSize().breakpoints.LG) {
47977          var $headerMobileAutocomplete = $('[data-js="header-location"]');
47978          var setLabelName = function setLabelName() {
47979            _this7.isDepartureInputActive() ? $headerMobileAutocomplete.text('Origem') : $headerMobileAutocomplete.text('Destino');
47980          };
47981
47982          setLabelName();
47983        }
47984      }
47985    }
47986  }, {
47987    key: "initOriginAutocomplete",
47988    value: function initOriginAutocomplete(input, latitude, longitude, callback, destinationDone, onSelectDestination) {
47989      var _this7 = this;
47990
47991      var originInput = input ? input : this.departure;
47992      this.destroyAutocomplete(input);
47993      var getOriginCallback = function getOriginCallback() {
47994        _this7.initAutocomplete(originInput, _this7.todasLocalidades, _this7.rankingOrigin, _this7.nearestOrigin, function () {
47995          var item = _this7.lastSelected[originInput.data('js')];
47996
47997          // Verifica se o item selecionado é "Usar minha localização"
47998          if (item && item.value === "use-my-location") {
47999            SessionStorage.remove('serviceOrigin');
48000            Utils.getUserLocation(function (latitude, longitude) {
48001              _this7.getAllLocations(function () {
48002                return getOriginCallback();
48003              }, latitude, longitude);
48004            }, function (error) {
48005              if (error instanceof GeolocationPositionError) {
48006                LoaderService.show();
48007
48008                setTimeout(function () {
48009                  _this7.locationError = true;
48010                  originInput.trigger('click');
48011                  LoaderService.hide();
48012                }, 5000);
48013              }
48014            });
48015          } else {
48016            var destinationInput = originInput.data('js') == _this7.departure.data('js') ? _this7.destination : _this7.departure;
48017            _this7.initDestinationAutocomplete(_this7.lastSelected[originInput.data('js')], destinationInput, destinationDone, onSelectDestination);
48018          }
48019        }, function () {
48020          if (callback) callback();
48021        });
48022      };
48023      if (this.todasLocalidades) {
48024        getOriginCallback();
48025      } else {
48026        if (!this.remarkV2) this.getAllLocations(function () {
48027          return getOriginCallback();
48028        }, latitude, longitude);
48029      }
48030    }
48031  }, {
48032    key: "initDestinationAutocomplete",
48033    value: function initDestinationAutocomplete(lastSelected, input, callback, onSelect) {
48034      var _this8 = this;
48035
48036      var destinationInput = input ? input : this.destination;
48037      this.getDestination(lastSelected, function () {
48038        _this8.destroyAutocomplete(destinationInput);
48039        if (_this8.listDestinations) {
48040          var index = _this8.listDestinations.findIndex(function (item) {
48041            return item.value === parseInt(destinationInput.data('value'));
48042          });
48043          if (index < 0) {
48044            destinationInput.data("value", "");
48045            destinationInput.val("");
48046            destinationInput.data("address", "");
48047          } else {
48048            _this8.lastSelected[destinationInput.data('js')] = _this8.listDestinations[index];
48049          }
48050        }
48051        _this8.initAutocomplete(destinationInput, _this8.listDestinations, _this8.rankingDestination, null, function () {
48052          if (onSelect) onSelect();
48053        });
48054        if (callback) {
48055          callback();
48056        }
48057      });
48058    }
48059  }, {
48060    key: 'checkLinkClick',
48061    value: function checkLinkClick() {
48062      $(document).on('mousedown', '#new-route-link', function (e) {
48063        var action = $(e.target).data('action');
48064
48065        if (!action) return;
48066
48067        if (action.includes('#')) {
48068          var modalEl = document.querySelector(action);
48069
48070          var modalInstance = bootstrap.Modal.getInstance(modalEl);
48071          if (!modalInstance) modalInstance = new bootstrap.Modal(modalEl);
48072
48073          modalInstance.toggle();
48074          return;
48075        }
48076
48077        $(location).attr('href', action);
48078      });
48079    }
48080  }, {
48081    key: 'inputFocusOutEvent',
48082    value: function inputFocusOutEvent(input) {
48083      var _this9 = this;
48084
48085      this.focusOutSet[input.data('js')] = true;
48086
48087      input.off('focusout').focusout(function (e) {
48088        e.preventDefault();
48089        var input = $(e.target);
48090
48091        if (!input.data('js') === "input-mobile") {
48092          _this9.hideOverlay();
48093
48094          $('#autocomplete-wrapper').removeClass('active');
48095          $('.ui-autocomplete').removeClass('active');
48096
48097          if (!input.data('value')) {
48098            if (_this9.lastSelected[input.data('js')]) {
48099              input.val(_this9.lastSelected[input.data('js')].label);
48100              input.data('value', _this9.lastSelected[input.data('js')].value);
48101              input.data('address', _this9.lastSelected[input.data('js')].address);
48102            }
48103          }
48104
48105          $('.search-results-header').removeClass('active');
48106          $(e.currentTarget).removeClass('highlight');
48107        }
48108      });
48109    }
48110  }, {
48111    key: "initAutocomplete",
48112    value: function initAutocomplete(input, list, rankingList, nearestList, onSelect, callback) {
48113      var _this11 = this;
48114
48115      var autoCompleteEnabledIcon = $('[data-js="autocomplete-enabled-icon"]').val() === 'true' ? true : false;
48116      var autoCompleteEnabledAddress = $('[data-js="autocomplete-enabled-address"]').val() === 'true' ? true : false;
48117
48118      if (input.length == 0) return;
48119
48120      input.catcomplete({
48121        appendTo: "#autocomplete-wrapper",
48122        minLength: 0,
48123        autoFocus: true,
48124        source: function source(request, response) {
48125          return _this11.getSource(request, response, list, rankingList, nearestList, input.data('js'));
48126        },
48127        change: function change(e, ui) {
48128          var obj = _this11.lastSelected[input.data('js')];
48129          if (ui.item == null && obj != null) {
48130            $(e.target).data("value", obj.value);
48131            $(e.target).val(obj.label);
48132            $(e.target).data("address", obj.address);
48133          }
48134          $('#input-mobile').val('');
48135        },
48136        select: function select(e, ui) {
48137          _this11.hideOverlay();
48138          $('#autocomplete-wrapper').removeClass('active');
48139          $('.ui-autocomplete').removeClass('active');
48140
48141          $(e.target).data("value", ui.item.value);
48142          $(e.target).val(ui.item.label);
48143          $(e.target).data("address", ui.item.address);
48144          $(e.target).removeClass('invalid');
48145          $(e.target).parent().removeClass('has-invalid-input');
48146
48147          if (ui.item.value === 'use-my-location') {
48148            _this11.useUserLocation = true;
48149          }
48150
48151          _this11.lastSelected[input.data('js')] = ui.item;
48152          $(e.target).blur();
48153          if (onSelect) onSelect();
48154
48155          $(e.target).blur();
48156          return false;
48157        },
48158        focus: function focus() {
48159          return false;
48160        },
48161        open: function open() {
48162          _this11.addFieldsIntoInputAutoComplete();
48163          $('#autocomplete-wrapper').removeAttr("style");
48164
48165          if (!_this11.toggleSearchMode) {
48166            if (Utils.getWindowSize().width <= Utils.getWindowSize().breakpoints.LG) {
48167              $('html, body').animate({ scrollTop: 0 }, 'fast');
48168              return;
48169            }
48170          }
48171
48172          var _input$offset = input.offset(),
48173            left = _input$offset.left,
48174            top = _input$offset.top;
48175
48176          top += input.parent().height();
48177
48178          if (_this11.toggleSearchMode) {
48179            if (Utils.getWindowSize().width <= Utils.getWindowSize().breakpoints.LG) {
48180              var width = input.outerWidth();
48181              $('#autocomplete-wrapper').css('width', width);
48182            }
48183          }
48184
48185          if (window.location.href.indexOf($('#homePagePath').val()) != -1) {
48186            top = top - 20;
48187            $('#autocomplete-wrapper').css({ top: top, left: left });
48188            $('#autocomplete-wrapper').css('z-index', '6');
48189          } else {
48190            $('#autocomplete-wrapper').css({ top: top, left: left });
48191            $('#autocomplete-wrapper').css('z-index', '23');
48192          }
48193        },
48194        close: function close() {
48195          $('#footer-input-location').remove();
48196        }
48197      }).data("custom-catcomplete")._renderItem = function (ul, item) {
48198        var itemIcon = _this11.toggleSearchMode ? 'jca-ico-location-city' : 'jca-ico-pin-fill';
48199        var itemDescription = '';
48200
48201        if (item.value === 'use-my-location') {
48202          itemIcon = 'jca-ico-location-target';
48203          var _itemDescription = '';
48204        } else if (item.boardingType && item.boardingType.trim() !== '') {
48205          var normalizedBoardingType = item.boardingType.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, ''); // Remove acentuações
48206
48207          switch (true) {
48208            case normalizedBoardingType.includes('localidade de grupo'):
48209              itemIcon = 'jca-ico-location-city';
48210              itemDescription = $('[data-js="location-group-caption"]').val();
48211              break;
48212            case normalizedBoardingType.includes('terminal rodoviario'):
48213              itemIcon = 'jca-ico-location-bus-station';
48214              itemDescription = $('[data-js="bus-terminal-caption"]').val();
48215              break;
48216            case normalizedBoardingType.includes('ponto externo'):
48217              itemIcon = 'jca-ico-location-boarding';
48218              itemDescription = $('[data-js="external-boarding-point-caption"]').val();
48219              break;
48220            default:
48221              itemIcon = 'jca-ico-location-city';
48222              itemDescription = '';
48223              break;
48224          }
48225        }
48226
48227        if (item.value === 'ranking-title') {
48228          // Renderizar o item 'ranking-title' fora do ui-menu-item
48229          return $('<li class="ui-autocomplete-category">').text(item.label).appendTo(ul);
48230        } else {
48231          if ($('[data-js="caption-on"]').val() !== 'true') {
48232            itemDescription = '';
48233          }
48234
48235          var _normalizedBoardingType = item.boardingType ? item.boardingType.toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '') 
48235: '';
48236
48237          return $("<li class=\"ui-menu-item " + (item.value === 'use-my-location' ? 'use-location-border' : '') + " " + (item.address !== '' ? 'ui-menu-item-fix-position' : '') + "\">").data("value", item.value).append("\n              " + (autoCompleteEnabledIcon ? "<span class=\"input-icon " + (_this11.locationError && item.value === 'use-my-location' ? 'error-location-icon' : '') + "\" aria-hidden=\"true\"> <em class=\"" + itemIcon + "\"></em> </span>" : '') + "\n              <a tabindex=\"-1\" class=\"ui-menu-item-wrapper " + (_this11.locationError && item.value === 'use-my-location' ? 'error-location' : '') + "\" id=\"" + item.label.replace(/ /g, '-') + "\">\n                <p class=\"location-title " + (_this11.locationError && item.value === 'use-my-location' ? 'error-location-title' : '') + " " + (_normalizedBoardingType.includes('localidade de grupo') ? 'location-title-heavy' : '') + "\"> " + item.label + " </p>\n                <p class=\"location-address\">" + itemDescription + "</p>\n                " + (autoCompleteEnabledAddress ? "<p class=\"location-address\"> " + item.address + " </p>" : '') + "\n              </a>\n            ").appendTo(ul);
48238        }
48239      };
48240
48241      if (callback) callback();
48242
48243      if (!this.focusOutSet || !this.focusOutSet[input.data('js')]) this.inputFocusOutEvent(input);
48244
48245      if ((!this.serviceClick || !nearestList) && (!this.useUserLocation || this.useUserLocation && input.data('js') === 'input-destination')) {
48246        input.trigger('focus');
48247      }
48248    }
48249  }, {
48250    key: "destroyAutocomplete",
48251    value: function destroyAutocomplete(input) {
48252      if (input) {
48253        if (input.data('custom-catcomplete')) {
48254          input.catcomplete('destroy');
48255          this.lastSelected[input.data('js')] = {};
48256          this.focusOutSet[input.data('js')] = false;
48257        }
48258      } else {
48259        if (this.departure.data('custom-catcomplete')) {
48260          this.departure.catcomplete("destroy");
48261          this.lastSelected[this.departure.data('js')] = {};
48262          this.focusOutSet[this.departure.data('js')] = false;
48263        }
48264
48265        if (this.destination.data('custom-catcomplete')) {
48266          this.destination.catcomplete("destroy");
48267          this.lastSelected[this.destination.data('js')] = {};
48268          this.focusOutSet[this.destination.data('js')] = false;
48269        }
48270
48271        this.shouldRevertInputs = null;
48272      }
48273    }
48274  }, {
48275    key: "getAllLocations",
48276    value: function getAllLocations(callback, latitude, longitude) {
48277      var _this11 = this;
48278
48279      if ($('#wcmmodeedit').val() == 'true') return;
48280      this.todasLocalidades = {};
48281
48282      var savedOrigin = SessionStorage.get('serviceOrigin');
48283
48284      if (savedOrigin && !this.toggleSearchMode && !savedOrigin.placesList) {
48285        this.todasLocalidades = this.parseToAutoCompleteFormat(savedOrigin);
48286        this.todasLocalidades.sort(function (a, b) {
48287          return a.label.localeCompare(b.label);
48288        });
48289        if (callback) callback();
48290        return;
48291      } else if (savedOrigin && this.toggleSearchMode && savedOrigin.placesList) {
48292        var _savedOrigin$ranking = savedOrigin.ranking,
48293          ranking = _savedOrigin$ranking === undefined ? [] : _savedOrigin$ranking,
48294          _savedOrigin$placesLi = savedOrigin.placesList,
48295          placesList = _savedOrigin$placesLi === undefined ? [] : _savedOrigin$placesLi,
48296          _savedOrigin$nearbyLo = savedOrigin.nearbyLocations,
48297          nearbyLocations = _savedOrigin$nearbyLo === undefined ? [] : _savedOrigin$nearbyLo;
48298
48299        this.nearestOrigin = this.parseToAutoCompleteFormat(nearbyLocations);
48300        this.rankingOrigin = this.parseToAutoCompleteFormat(ranking);
48301        this.todasLocalidades = this.parseToAutoCompleteFormat(placesList);
48302        if (callback) callback();
48303        return;
48304      }
48305
48306      var headers = null;
48307      var params = {};
48308
48309      if (this.toggleSearchMode) {
48310        headers = {
48311          Authorization: "" + SessionStorage.get("jca_token"),
48312          version: "2"
48313        };
48314
48315        params = {
48316          // Definido como 0 por enquanto, pois a localização do usuário ainda não está sendo enviada
48317          userLat: latitude ? latitude : 0,
48318          userLng: longitude ? longitude : 0
48319        };
48320      }
48321
48322      var urlService = this.toggleSearchMode ? "searchOrigin?" + $.param(params) : 'searchOrigin';
48323
48324      setTimeout(function () {
48325        HttpService.get(urlService, headers).then(function (data) {
48326          _this11.saveServiceOrigin(data.result);
48327
48328          if (data.success) {
48329            if (!_this11.toggleSearchMode) {
48330              _this11.todasLocalidades = _this11.parseToAutoCompleteFormat(data.result);
48331              _this11.todasLocalidades.sort(function (a, b) {
48332                return a.label.localeCompare(b.label);
48333              });
48334            } else {
48335              var _data$result = data.result,
48336                _data$result$ranking = _data$result.ranking,
48337                _ranking = _data$result$ranking === undefined ? [] : _data$result$ranking,
48338                _data$result$placesLi = _data$result.placesList,
48339                _placesList = _data$result$placesLi === undefined ? [] : _data$result$placesLi,
48340                _data$result$nearbyLo = _data$result.nearbyLocations,
48341                _nearbyLocations = _data$result$nearbyLo === undefined ? [] : _data$result$nearbyLo;
48342
48343
48344              _this11.nearestOrigin = _this11.parseToAutoCompleteFormat(_nearbyLocations);
48345              _this11.rankingOrigin = _this11.parseToAutoCompleteFormat(_ranking);
48346              _this11.todasLocalidades = _this11.parseToAutoCompleteFormat(_placesList);
48347
48348              if (_this11.nearestOrigin.length > 0) {
48349                _this11.acceptedLocation = true;
48350                _this11.fillWithNearestOrigin(_this11.nearestOrigin);
48351              }
48352            }
48353          }
48354
48355          if (callback) callback();
48356        }).catch(function () {
48357          if (typeof _satellite != "undefined") {
48358            _satellite.track('serviceError', {
48359              serviceType: 'searchOrigin',
48360              statusCode: err.status,
48361              messageError: err.responseJSON.result.toUpperCase()
48362            });
48363          }
48364        });
48365      }, 500);
48366    }
48367  }, {
48368    key: "saveServiceOrigin",
48369    value: function saveServiceOrigin(data) {
48370      SessionStorage.set('serviceOrigin', data);
48371    }
48372  }, {
48373    key: "saveServiceDestination",
48374    value: function saveServiceDestination(data) {
48375      var saveDestination = SessionStorage.get('serviceDestination');
48376
48377      if (!saveDestination) {
48378        SessionStorage.set('serviceDestination', data);
48379      }
48380    }
48381  }, {
48382    key: "getDestination",
48383    value: function getDestination(lastSelected, callback) {
48384      var _this12 = this;
48385
48386      var parameters = { originId: lastSelected.value };
48387
48388      var saveDestination = SessionStorage.get('serviceDestination');
48389
48390      if (saveDestination) {
48391        if (!this.toggleSearchMode && !saveDestination.placesList) {
48392          this.listDestinations = this.parseToAutoCompleteFormat(saveDestination);
48393        } else if (this.toggleSearchMode && saveDestination.placesList) {
48394          var _saveDestination$rank = saveDestination.ranking,
48395            ranking = _saveDestination$rank === undefined ? [] : _saveDestination$rank,
48396            _saveDestination$plac = saveDestination.placesList,
48397            placesList = _saveDestination$plac === undefined ? [] : _saveDestination$plac;
48398
48399          this.rankingDestination = this.parseToAutoCompleteFormat(ranking);
48400          this.listDestinations = this.parseToAutoCompleteFormat(placesList);
48401        }
48402
48403        if (callback) callback();
48404        return;
48405      }
48406
48407      var headers = null;
48408
48409      if (this.toggleSearchMode) {
48410        headers = {
48411          Authorization: "" + SessionStorage.get("jca_token"),
48412          version: "2"
48413        };
48414
48415        parameters.userLat = lastSelected.latitude ? lastSelected.latitude : 0;
48416        parameters.userLng = lastSelected.longitude ? lastSelected.longitude : 0;
48417      }
48418
48419      HttpService.get('searchDestination?' + $.param(parameters), headers).then(function (data) {
48420        _this12.saveServiceDestination(data.result);
48421
48422        if (data.success) {
48423          if (!_this12.toggleSearchMode) {
48424            _this12.listDestinations = _this12.parseToAutoCompleteFormat(data.result);
48425            _this12.listDestinations.sort(function (a, b) {
48426              return a.label.localeCompare(b.label);
48427            });
48428          } else {
48429            var _data$result2 = data.result,
48430              _data$result2$ranking = _data$result2.ranking,
48431              _ranking2 = _data$result2$ranking === undefined ? [] : _data$result2$ranking,
48432              _data$result2$placesL = _data$result2.placesList,
48433              _placesList2 = _data$result2$placesL === undefined ? [] : _data$result2$placesL;
48434
48435            _this12.rankingDestination = _this12.parseToAutoCompleteFormat(_ranking2);
48436            _this12.listDestinations = _this12.parseToAutoCompleteFormat(_placesList2);
48437          }
48438        }
48439
48440        if (callback) callback();
48441      }).catch(function (err) {
48442        Alert.show('Houve uma falha na requisição. Tente novamente mais tarde');
48443
48444        // Analytics - Triggers an event when there is an error on service.
48445        if (typeof _satellite != "undefined") {
48446          _satellite.track('serviceError', {
48447            serviceType: 'searchDestination',
48448            statusCode: err.status,
48449            messageError: err.responseJSON.result.toUpperCase()
48450          });
48451        }
48452      });
48453    }
48454  }, {
48455    key: "parseToAutoCompleteFormat",
48456    value: function parseToAutoCompleteFormat(array) {
48457      return array.reduce(function (acc, el) {
48458        acc.push({
48459          "value": el.id,
48460          "label": (el.city || el.localityOriginName || el.localityDestinationName || el.name) + ' (' + el.state + ')',
48461          "address": el.address ? el.address : '',
48462          "category": Utils.verifiedState(el.state) ? Utils.verifiedState(el.state) : 'Outros',
48463          "latitude": el.latitude,
48464          "longitude": el.longitude,
48465          "distance": el.distance,
48466          "boardingType": el.typeOfBoarding ? el.typeOfBoarding : ""
48467        });
48468        return acc;
48469      }, []);
48470    }
48471  }]);
48472
48473  return LocationInput;
48474}();
48475
48476/**
48477 *
48478 * FIM
48479 * LOGICA INPUT ORIGEM E DESTINO
48480 *
48481 */
48482'use strict';
48483
48484var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
48485
48486function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
48487
48488/**
48489 *
48490 * INICIO
48491 * TELA SELECTIONAR PASSAGEIROS
48492 *
48493 */
48494
48495var PersonQuantityWindow = function () {
48496  function PersonQuantityWindow($, searchComponentRef) {
48497    _classCallCheck(this, PersonQuantityWindow);
48498
48499    this.openWindowButton = $('[data-js="button-open-person-modal"]');
48500    this.cancel = $('[data-js="close-person-quantity"]');
48501    this.submit = $('[data-js="submit-person-quantity"]');
48502    this.childrenValidationMsg = $('[data-js="children-validation-msg"]');
48503
48504    this.passengerMinusOne = $('[data-js="passenger-quantity-minus-one"]');
48505    this.$passengerCurrentValue = $('[data-js="passenger-quantity-value"]');
48506    this.passengerPlusOne = $('[data-js="passenger-quantity-plus-one"]');
48507    this.passengerValidationMsg = $('[data-js="adult-validation-msg"]');
48508
48509    this.childMinusOne = $('[data-js="child-quantity-minus-one"]');
48510    this.$childCurrentValue = $('[data-js="child-quantity-value"]');
48511    this.childPlusOne = $('[data-js="child-quantity-plus-one"]');
48512
48513    this.infantMinusOne = $('[data-js="infant-quantity-minus-one"]');
48514    this.$infantCurrentValue = $('[data-js="infant-quantity-value"]');
48515    this.infantPlusOne = $('[data-js="infant-quantity-plus-one"]');
48516
48517    this.$totalValue = $('[data-js="passenger-current-value"]');
48518    this.maxValue = $('[data-js="select-person"]').data('maxvalue');
48519
48520    {
48521      this.passengerVal = 1;
48522      this.childVal = 0;
48523      this.infantVal = 0;
48524      this.totalVal = 1;
48525    }
48526
48527    this.container = $('[data-js="person-window-container"]');
48528    this.labelContainer = $('[data-js="label-overlay-container"]');
48529    this.label = $('[data-js="label-overlay"]');
48530    this.overlay = $('#overlay');
48531    this.searchButtonPersonWindow = $('[data-js="button-search-person-window"]:last');
48532    this.searchComponentRef = searchComponentRef;
48533    this.active = false;
48534    this.init();
48535  }
48536
48537  _createClass(PersonQuantityWindow, [{
48538    key: 'init',
48539    value: function init() {
48540      this.initPassengersValues();
48541      this.bindOpenWindowClick();
48542      this.handleEvents();
48543      this.checkExternalClick();
48544    }
48545  }, {
48546    key: 'initPassengersValues',
48547    value: function initPassengersValues() {
48548      var formData = SessionStorage.get('formData');
48549
48550      if (formData) {
48551        this.passengerVal = formData.passengers[0].quantity;
48552
48553        this.childVal = formData.passengers[1].quantity;
48554        this.infantVal = formData.passengers[2].quantity;
48555        this.totalVal = Utils.getPassengersQuantity(formData.passengers);
48556
48557        this.$passengerCurrentValue.text(this.passengerVal);
48558        this.$childCurrentValue.text(this.childVal);
48559        this.$infantCurrentValue.text(this.infantVal);
48560        this.$totalValue.text(this.totalVal);
48561
48562        if (this.passengerVal > 1) {
48563          this.passengerMinusOne.removeClass('disabled');
48564        }
48565
48566        if (this.passengerVal + this.childVal == this.maxValue) {
48567          this.passengerPlusOne.addClass('disabled');
48568        }
48569
48570        if (this.infantVal > 0) {
48571          this.infantMinusOne.removeClass('disabled');
48572        }
48573
48574        if (this.infantVal == this.passengerVal) {
48575          this.infantPlusOne.addClass('disabled');
48576        }
48577
48578        if (this.childVal > 0) {
48579          this.childMinusOne.removeClass('disabled');
48580        }
48581
48582        if (this.childVal == this.passengerVal || this.passengerVal + this.childVal == this.maxValue) {
48583          this.childPlusOne.addClass('disabled');
48584        }
48585      }
48586    }
48587  }, {
48588    key: 'bindOpenWindowClick',
48589    value: function bindOpenWindowClick() {
48590      var _this = this;
48591
48592      this.openWindowButton.click(function (e) {
48593        e.stopPropagation();
48594        if (!_this.active) {
48595          _this.openWindow();
48596        } else {
48597          _this.closeWindow();
48598        }
48599      }).focusin(function () {
48600        setTimeout(function () {
48601          return _this.openWindow();
48602        }, 100);
48603      });
48604
48605      $('[data-js="input-date-return"]').focus(function () {
48606        return _this.closeWindow(false);
48607      });
48608      $('[data-js="clear-search"]').focus(function () {
48609        return _this.closeWindow();
48610      });
48611    }
48612  }, {
48613    key: 'incrementQuantity',
48614    value: function incrementQuantity(config) {
48615      var type = config.type;
48616
48617
48618      var passenger_value = this.passengerVal;
48619      var child_value = this.childVal;
48620      var infant_value = this.infantVal;
48621      var sum = this.totalVal;
48622      var max_value = this.maxValue;
48623
48624      switch (type) {
48625        case 'child_a':
48626          if (child_value < passenger_value && sum - infant_value < max_value) {
48627
48628            this.childVal = ++child_value;
48629            this.$childCurrentValue.text(this.childVal);
48630
48631            this.totalVal = passenger_value + child_value + infant_value;
48632            this.$totalValue.text(this.totalVal);
48633
48634            sum = this.totalVal;
48635
48636            if (this.childMinusOne.hasClass('disabled')) {
48637              this.childMinusOne.removeClass('disabled');
48638            }
48639
48640            if (child_value - passenger_value == 0) {
48641              this.childPlusOne.addClass('disabled');
48642            }
48643
48644            if (sum - infant_value == max_value) {
48645              this.childPlusOne.addClass('disabled');
48646              this.passengerPlusOne.addClass('disabled');
48647              this.passengerValidationMsg.fadeIn();
48648            }
48649          } else if (sum - infant_value < max_value) {
48650            this.childrenValidationMsg.fadeIn();
48651          } else if (child_value + passenger_value == max_value) {
48652            if (child_value == passenger_value) this.childrenValidationMsg.fadeIn();
48653            this.passengerValidationMsg.fadeIn();
48654          } else {
48655            this.childrenValidationMsg.fadeIn();
48656          }
48657
48658          break;
48659        case 'child':
48660          if (infant_value < passenger_value) {
48661            this.infantVal = ++infant_value;
48662            this.$infantCurrentValue.text(this.infantVal);
48663
48664            this.totalVal = passenger_value + child_value + infant_value;
48665            this.$totalValue.text(this.totalVal);
48666
48667            sum = this.totalVal;
48668
48669            if (passenger_value == max_value && infant_value == passenger_value) {
48670              this.infantPlusOne.addClass('disabled');
48671            }
48672
48673            if (this.infantMinusOne.hasClass('disabled')) {
48674              this.infantMinusOne.removeClass('disabled');
48675            }
48676
48677            if (infant_value - passenger_value == 0) {
48678              this.infantPlusOne.addClass('disabled');
48679            }
48680          } else {
48681            this.childrenValidationMsg.fadeIn();
48682          }
48683
48684          break;
48685
48686        default:
48687          if (passenger_value < max_value && sum - infant_value < max_value) {
48688            this.childrenValidationMsg.fadeOut();
48689
48690            this.passengerVal = ++passenger_value;
48691            this.$passengerCurrentValue.text(this.passengerVal);
48692
48693            this.totalVal = passenger_value + child_value + infant_value;
48694            this.$totalValue.text(this.totalVal);
48695
48696            sum = this.totalVal;
48697
48698            if (sum - infant_value < max_value) {
48699              this.childPlusOne.removeClass('disabled');
48700              this.infantPlusOne.removeClass('disabled');
48701            }
48702
48703            if (sum - infant_value == max_value) {
48704              this.childPlusOne.addClass('disabled');
48705            }
48706
48707            if (passenger_value > infant_value) {
48708              this.infantPlusOne.removeClass('disabled');
48709            }
48710
48711            if (this.passengerMinusOne.hasClass('disabled')) {
48712              this.passengerMinusOne.removeClass('disabled');
48713            }
48714
48715            if (passenger_value - this.maxValue == 0 || sum - infant_value == max_value) {
48716              this.passengerPlusOne.addClass('disabled');
48717            }
48718          } else {
48719            this.passengerValidationMsg.fadeIn();
48720          }
48721          break;
48722      }
48723    }
48724  }, {
48725    key: 'decrementQuantity',
48726    value: function decrementQuantity(config) {
48727      var type = config.type;
48728
48729
48730      var passenger_value = this.passengerVal;
48731      var child_value = this.childVal;
48732      var infant_value = this.infantVal;
48733      var sum = this.totalVal;
48734      var max_value = this.maxValue;
48735
48736      switch (type) {
48737        case 'child_a':
48738          if (child_value >= 1) {
48739
48740            this.childVal = --child_value;
48741            this.$childCurrentValue.text(this.childVal);
48742
48743            this.totalVal = passenger_value + child_value + infant_value;
48744            this.$totalValue.text(this.totalVal);
48745
48746            sum = this.totalVal;
48747
48748            if (sum - infant_value < max_value) {
48749              this.passengerPlusOne.removeClass('disabled');
48750            }
48751
48752            if (this.childPlusOne.hasClass('disabled')) {
48753              this.childPlusOne.removeClass('disabled');
48754            }
48755
48756            if (child_value == passenger_value) {
48757              this.childPlusOne.addClass('disabled');
48758            }
48759
48760            if (child_value == 0) {
48761              this.childMinusOne.addClass('disabled');
48762              this.childrenValidationMsg.fadeOut();
48763            }
48764
48765            if (child_value < passenger_value) {
48766              this.childrenValidationMsg.fadeOut();
48767            }
48768
48769            if (child_value + passenger_value < max_value) {
48770              this.passengerValidationMsg.fadeOut();
48771            }
48772          }
48773          break;
48774        case 'child':
48775          if (infant_value >= 1) {
48776            this.infantVal = --infant_value;
48777            this.$infantCurrentValue.text(this.infantVal);
48778
48779            this.totalVal = passenger_value + child_value + infant_value;
48780            this.$totalValue.text(this.totalVal);
48781
48782            sum = this.totalVal;
48783
48784            if (this.infantPlusOne.hasClass('disabled')) {
48785              this.infantPlusOne.removeClass('disabled');
48786            }
48787
48788            if (infant_value == 0) {
48789              this.infantMinusOne.addClass('disabled');
48790              this.childrenValidationMsg.fadeOut();
48791            }
48792
48793            if (infant_value < passenger_value) {
48794              this.childrenValidationMsg.fadeOut();
48795            }
48796          } else {
48797            this.passengerValidationMsg.fadeOut();
48798            this.childrenValidationMsg.fadeOut();
48799          }
48800          break;
48801        default:
48802          if (passenger_value > 1) {
48803            this.passengerVal = --passenger_value;
48804            this.$passengerCurrentValue.text(this.passengerVal);
48805
48806            this.totalVal = passenger_value + child_value + infant_value;
48807            this.$totalValue.text(this.totalVal);
48808
48809            sum = this.totalVal;
48810
48811            if (sum - infant_value < max_value) {
48812              this.childPlusOne.removeClass('disabled');
48813              this.infantPlusOne.removeClass('disabled');
48814            }
48815
48816            // handle child
48817            if (child_value > passenger_value) {
48818              this.childMinusOne.click();
48819            }
48820
48821            if (child_value == passenger_value) {
48822              this.childPlusOne.addClass('disabled');
48823            }
48824
48825            // handle infant
48826            if (infant_value > passenger_value) {
48827              this.infantMinusOne.click();
48828              infant_value = parseInt(this.$infantCurrentValue.text());
48829            }
48830
48831            if (infant_value == passenger_value) {
48832              this.infantPlusOne.addClass('disabled');
48833            }
48834
48835            // handle itself
48836            if (this.passengerPlusOne.hasClass('disabled')) {
48837              this.passengerPlusOne.removeClass('disabled');
48838              this.passengerValidationMsg.fadeOut();
48839            }
48840
48841            if (1 - passenger_value == 0) {
48842              this.passengerMinusOne.addClass('disabled');
48843            }
48844
48845            if (max_value > passenger_value) {
48846              this.passengerValidationMsg.fadeOut();
48847            }
48848          }
48849          break;
48850      }
48851    }
48852  }, {
48853    key: 'checkExternalClick',
48854    value: function checkExternalClick() {
48855      var _this2 = this;
48856
48857      var container = $('[data-js="person-window-container"]');
48858      var button = $('[data-js="button-open-person-modal"]');
48859      var buttonGoToPassengers = $('#btn-datectrl-def-pass');
48860
48861      $(document).click(function (e) {
48862        if (!$('body').is(e.target) && !button.is(e.target) && container.has(e.target).length == 0 && !$(buttonGoToPassengers).is(e.target) && _this2.active) {
48863          _this2.closeWindow();
48864        }
48865      });
48866    }
48867  }, {
48868    key: 'handleEvents',
48869    value: function handleEvents() {
48870      var _this3 = this;
48871
48872      this.passengerMinusOne.add(this.childMinusOne).add(this.infantMinusOne).click(function (e) {
48873        var config = {
48874          element: $(e.currentTarget).next(),
48875          minusOne: $(e.currentTarget),
48876          plusOne: $(e.currentTarget).next().next(),
48877          type: $(e.currentTarget).data('type')
48878        };
48879
48880        _this3.decrementQuantity(config);
48881      });
48882
48883      this.passengerPlusOne.add(this.childPlusOne).add(this.infantPlusOne).click(function (e) {
48884        var config = {
48885          element: $(e.currentTarget).prev(),
48886          minusOne: $(e.currentTarget).prev().prev(),
48887          plusOne: $(e.currentTarget),
48888          type: $(e.currentTarget).data('type')
48889        };
48890
48891        _this3.incrementQuantity(config);
48892      });
48893
48894      this.cancel.click(function () {
48895        return _this3.closeWindow();
48896      });
48897    }
48898  }, {
48899    key: 'openWindow',
48900    value: function openWindow() {
48901      this.active = true;
48902      this.container.parent().addClass('active');
48903      this.container.addClass('active');
48904      this.container.find('.content').focus();
48905
48906      if ($('.change-way-overlay:visible').length === 0) OverlayService.show();
48907
48908      this.labelContainer.addClass('person-window');
48909    }
48910  }, {
48911    key: 'closeWindow',
48912    value: function closeWindow() {
48913      var hideOverlay = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
48914
48915      this.active = false;
48916      this.container.parent().removeClass('active');
48917      this.container.removeClass('active');
48918      this.labelContainer.removeClass('person-window');
48919      this.label.removeClass('active');
48920      this.childrenValidationMsg.fadeOut();
48921      if (hideOverlay) {
48922        OverlayService.hide();
48923      }
48924    }
48925  }, {
48926    key: 'resetComponent',
48927    value: function resetComponent() {
48928      this.$totalValue.text('1');
48929      this.totalVal = 1;
48930
48931      this.$passengerCurrentValue.text('1');
48932      this.passengerVal = 1;
48933      this.passengerMinusOne.addClass('disabled');
48934      this.passengerPlusOne.removeClass('disabled');
48935      this.passengerValidationMsg.fadeOut();
48936
48937      this.$childCurrentValue.text('0');
48938      this.childMinusOne.addClass('disabled');
48939      this.childPlusOne.removeClass('disabled');
48940      this.childVal = 0;
48941
48942      this.$infantCurrentValue.text('0');
48943      this.infantMinusOne.addClass('disabled');
48944      this.infantPlusOne.removeClass('disabled');
48945      this.infantVal = 0;
48946    }
48947  }, {
48948    key: 'getQuantityObj',
48949    value: function getQuantityObj(adult, chld, chlds) {
48950      return [{
48951        order: 0,
48952        type: "ADULT",
48953        quantity: adult
48954      }, {
48955        order: 1,
48956        type: "CHILD_A",
48957        quantity: chld
48958      }, {
48959        order: 3,
48960        type: "CHILD",
48961        quantity: chlds
48962      }];
48963    }
48964  }]);
48965
48966  return PersonQuantityWindow;
48967}();
48968
48969/**
48970 *
48971 * FIM
48972 * TELA SELECTIONAR PASSAGEIROS
48973 *
48974 */
48975'use strict';
48976
48977var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
48978
48979function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
48980
48981/**
48982 * INICIO
48983 * LOGICA SEARCH COMPONENT FORM
48984 *
48985 */
48986
48987var SearchComponentForm = function () {
48988  function SearchComponentForm($) {
48989    _classCallCheck(this, SearchComponentForm);
48990
48991    this.btnSwitch = $('[data-js="button-switch"]:visible');
48992    this.departure = $('[data-js="input-departure"]:visible');
48993    this.destination = $('[data-js="input-destination"]:visible');
48994    this.dateDeparture = $('[data-js="input-date-departure"]:visible');
48995    this.dateReturn = $('[data-js="input-date-return"]:visible');
48996    this.passengersTotal = $('[data-js="passenger-current-value"]');
48997    this.passengers = $('[data-js="passenger-quantity-value"]').first();
48998    this.passengersChda = $('[data-js="child-quantity-value"]').first();
48999    this.passengersChds = $('[data-js="infant-quantity-value"]').first();
49000    this.hourSlick = $('[data-js="hour-slick"]:visible');
49001    this.hourSlickContent = $('[data-js="hour-slick-content"]:visible');
49002    this.selectedHour = $('[data-js="hour-selected"]:visible');
49003    this.hourSlickContainer = $('[data-js="hour-slick-container"]:visible');
49004    this.btnSubmit = $('[data-js="button-search"]');
49005    this.personWindow = new PersonQuantityWindow($, this);
49006    this.datePickerControl = new DatePickerControl($, this, this.personWindow);
49007    this.currentResultDep = null;
49008    this.searchForm = $("[data-js='search-form']:visible");
49009    this.searchCookieName = 'WeMobiOriginDestination';
49010    this.searchCookieDaysToExpire = $("[data-js='search-days-to-expire']");
49011    this.clearSearchBtn = $('[data-js="clear-search"]');
49012    this.requiredLoggedUser = $('[data-js="login-Dependency-Redirect"]').val() == 'true';
49013    this.remarkV2 = SessionStorage.get('repricingv2');
49014    this.toggleSearchMode = $('[data-js="toggle-search-mode-aem"]').val() == 'true';
49015    this.init();
49016  }
49017
49018  _createClass(SearchComponentForm, [{
49019    key: 'init',
49020    value: function init() {
49021        this.loadServices();
49022    }
49023  }, {
49024   key: 'loadServices',
49025   value: function loadServices() {
49026     this.initializeLocationInput(true, null, null);
49027     this.handleCommonTasks();
49028   }
49029 }, {
49030    key: 'isHomePage',
49031    value: function isHomePage() {
49032      var currentPath = window.location.href;
49033      return $('#homePagePath').val() && currentPath === $('#homePagePath').val();
49034    }
49035  }, {
49036    key: 'processLocation',
49037    value: async function processLocation() {
49038      await this.checkGeolocationPermission();
49039
49040      var savedOrigin = SessionStorage.get('serviceOrigin');
49041      SessionStorage.remove('serviceDestination');
49042
49043      if (savedOrigin && savedOrigin.nearbyLocations) {
49044        this.handleSavedOrigin(savedOrigin);
49045      } else {
49046        this.getLocation();
49047      }
49048    }
49049  }, {
49050    key: 'checkGeolocationPermission',
49051    value: async function checkGeolocationPermission() {
49052      if (navigator.permissions) {
49053        try {
49054          var permissionStatus = await navigator.permissions.query({ name: 'geolocation' });
49055          permissionStatus.onchange = function () {
49056            if (permissionStatus.state !== "granted") {
49057              SessionStorage.remove('serviceOrigin');
49058              SessionStorage.remove('serviceDestination');
49059            }
49060          };
49061        } catch (error) {
49062          console.error("Erro ao verificar permissão de geolocalização:", error);
49063        }
49064      }
49065    }
49066  }, {
49067    key: 'getLocation',
49068    value: function getLocation() {
49069      var _this2 = this;
49070
49071      Utils.getUserLocation(function (latitude, longitude) {
49072        _this2.initializeLocationInput(true, latitude, longitude);
49073        _this2.handleCommonTasks();
49074      }, function (error) {
49075        _this2.handleLocationError();
49076      });
49077    }
49078  }, {
49079    key: 'handleLocationError',
49080    value: function handleLocationError() {
49081      var _this3 = this;
49082
49083      this.departure.off('click').click(function () {
49084        _this3.handleDepartureClick(false);
49085        _this3.handleCommonTasks();
49086      });
49087    }
49088  }, {
49089    key: 'handleSavedOrigin',
49090    value: function handleSavedOrigin(savedOrigin) {
49091      this.initializeLocationInput(true);
49092      var nearbyLocations = this.locationInput.parseToAutoCompleteFormat(savedOrigin.nearbyLocations);
49093      this.locationInput.fillWithNearestOrigin(nearbyLocations);
49094      this.handleCommonTasks();
49095    }
49096  }, {
49097    key: 'initializeLocationInput',
49098    value: function initializeLocationInput(serviceClick) {
49099      var latitude = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
49100      var longitude = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
49101
49102      this.locationInput = new LocationInput($, this, false, serviceClick);
49103      this.locationInput.initForSearchComponent(latitude, longitude);
49104      if (!this.toggleSearchMode) {
49105        this.inputLocationReadonly();
49106      }
49107      if (!this.remarkV2 && !this.toggleSearchMode) {
49108        this.locationInput.loadDestinationAutocomplete();
49109      }
49110    }
49111  }, {
49112    key: 'handleDepartureClick',
49113    value: function handleDepartureClick(serviceClick) {
49114      SessionStorage.remove('serviceDestination');
49115      this.initializeLocationInput(serviceClick);
49116    }
49117  }, {
49118    key: 'handleCommonTasks',
49119    value: function handleCommonTasks() {
49120      this.handleSubmit();
49121      this.disableAutoFill();
49122      this.handleBtnSwitch();
49123      this.clearSearch();
49124      if (!SessionStorage.get('formData')) {
49125        this.getOriginDestinationCookie();
49126      }
49127    }
49128  }, {
49129    key: 'clearSearch',
49130    value: function clearSearch() {
49131      var _this = this;
49132
49133      this.clearSearchBtn.click(function () {
49134        _this.departure.val('').data('value', null);
49135        _this.destination.val('').data('value', null);
49136        _this.departure.val('').data('address', null);
49137        _this.destination.val('').data('address', null);
49138        _this.dateDeparture.val('').data('date', null);
49139        _this.dateReturn.val('').data('date', null);
49140        _this.personWindow.resetComponent();
49141      });
49142    }
49143  }, {
49144    key: 'inputLocationReadonly',
49145    value: function inputLocationReadonly() {
49146      var _this2 = this;
49147
49148      if (Utils.getWindowSize().width < 950) {
49149        $('[data-js="input-departure"] ,[data-js="input-destination"]').click(function (e) {
49150          _this2.departure.attr('readonly', true);
49151          _this2.destination.attr('readonly', true);
49152        });
49153      } else {
49154        this.departure.attr('readonly', false);
49155        this.destination.attr('readonly', false);
49156      }
49157    }
49158  }, {
49159    key: 'disableAutoFill',
49160    value: function disableAutoFill() {
49161      this.searchForm.disableAutoFill();
49162    }
49163  }, {
49164    key: 'refillForm',
49165    value: function refillForm() {
49166      var formData = SessionStorage.get("formData");
49167      var origin = formData.depart.origin.label + " (" + formData.depart.origin.uf + ")";
49168      var destination = formData.depart.destination.label + " (" + formData.depart.destination.uf + ")";
49169      this.departure.val(origin);
49170      this.destination.val(destination);
49171      this.passengers.text(formData.passengers);
49172      if (formData.depart.date) this.dateDeparture.data("date", formData.depart.date.split("-").reverse().join("-"));
49173      if (formData.return && formData.return.date) this.dateReturn.data("date", formData.return.date.split("-").reverse().join("-"));
49174    }
49175  }, {
49176    key: 'handleBtnSwitch',
49177    value: function handleBtnSwitch() {
49178      var _this3 = this;
49179
49180      this.btnSwitch.off('click');
49181      this.btnSwitch.click(function () {
49182        var departure_label = _this3.departure.val();
49183        var destination_label = _this3.destination.val();
49184        var departure_value = _this3.departure.data("value");
49185        var destination_value = _this3.destination.data("value");
49186
49187        _this3.departure.val(destination_label);
49188        _this3.destination.val(departure_label);
49189        _this3.departure.data("value", destination_value);
49190        _this3.destination.data("value", departure_value);
49191
49192        _this3.locationInput.lastSelected[_this3.departure.data('js')] = {
49193          "value": _this3.departure.data("value"),
49194          "label": _this3.departure.val(),
49195          'address': _this3.departure.data("address")
49196        };
49197        _this3.locationInput.lastSelected[_this3.destination.data('js')] = {
49198          "value": _this3.destination.data("value"),
49199          "label": _this3.destination.val()
49200        };
49201        ValidationService.close();
49202        _this3.removeInputInvalidClasses();
49203      });
49204      this.btnSwitch.keyup(function (e) {
49205        var key = e.keyCode || e.which;
49206        if (key === Utils.keyCodes.TAB) {
49207          _this3.locationInput.hideOverlay();
49208        }
49209      });
49210    }
49211  }, {
49212    key: 'removeInputInvalidClasses',
49213    value: function removeInputInvalidClasses() {
49214      this.searchForm.find("input[required]").each(function () {
49215        $(this).removeClass("invalid").parent().removeClass('has-invalid-input');
49216      });
49217    }
49218  }, {
49219    key: 'isFormValid',
49220    value: function isFormValid() {
49221      var allFieldsValid = true;
49222      this.searchForm.find("input[required]").each(function () {
49223        if ($(this).data("value") == "" || $(this).data("date") == "") {
49224          $(this).addClass("invalid").parent().addClass('has-invalid-input');
49225          allFieldsValid = false;
49226        } else {
49227          $(this).removeClass("invalid").parent().removeClass('has-invalid-input');
49228        }
49229      });
49230
49231      if (allFieldsValid) {
49232        return true;
49233      } else {
49234        ValidationService.open('Preencha os campos marcados para fazer sua busca.');
49235        return false;
49236      }
49237    }
49238  }, {
49239    key: 'parseDateApiFormat',
49240    value: function parseDateApiFormat(date) {
49241      return date ? date.split("/").reverse().join("-") : '';
49242    }
49243  }, {
49244    key: 'clearCart',
49245    value: function clearCart() {
49246      var cart = SessionStorage.get("cart");
49247      if (cart) SessionStorage.remove("cart");
49248    }
49249  }, {
49250    key: 'handleSubmit',
49251    value: function handleSubmit() {
49252      var _this4 = this;
49253
49254      this.btnSubmit.off('click');
49255      this.btnSubmit.on('click', function () {
49256        if (_this4.isFormValid()) {
49257          if (_this4.departure) {
49258            var origin = _this4.departure.data("value");
49259            var destination = _this4.destination.data("value");
49260            var date = _this4.parseDateApiFormat(_this4.dateDeparture.data("date"));
49261            var dataReturn = null;
49262            APIUtils.getAvailableTrips(origin, destination, date).then(function (data) {
49263              dataReturn = data;
49264              if (data) {
49265                _this4.onGetServicosDone(data);
49266                _this4.submitSearch();
49267              } else {
49268                _this4.handleSubmitError(dataReturn, null);
49269              }
49270            }).catch(function (err) {
49271              // send2Analytics(errorObj.erro.descricaoErro)
49272              _this4.handleSubmitError(dataReturn, err);
49273            });
49274          }
49275        }
49276      });
49277    }
49278  }, {
49279    key: 'onGetServicosDone',
49280    value: function onGetServicosDone(data) {
49281      this.currentResultDep = data.result;
49282      SessionStorage.set("currentResultDep", Utils.sortArrayResultsWay(this.currentResultDep));
49283    }
49284  }, {
49285    key: 'sendRouteSearchToAnalytics',
49286    value: function sendRouteSearchToAnalytics(err) {
49287      var formData = SessionStorage.get("formData");
49288
49289      window.dataLayer = window.dataLayer || [];
49290      window.dataLayer.push({
49291        event: "route_search_submit",
49292        device: Utils.getDevice(),
49293        route_search_error: err != undefined ? err : null,
49294        search_data: Utils.getSearchData(formData),
49295        user_data: Utils.getUserData()
49296      });
49297    }
49298  }, {
49299    key: 'redirectToSearchResult',
49300    value: function redirectToSearchResult() {
49301      var formData = this.getFormObject();
49302      SessionStorage.set('formData', formData);
49303      var submitParams = {};
49304      submitParams.data_ida = Utils.parseToDayMonthYearFormat(this.dateDeparture.data('date'));
49305      submitParams.data_volta = Utils.parseToDayMonthYearFormat(this.dateReturn.data('date'));
49306      submitParams.origem_id = this.departure.data('value');
49307      submitParams.destino_id = this.destination.data('value');
49308      submitParams.num_psgr = this.passengers.text();
49309      submitParams.num_chda = this.passengersChda.text();
49310      submitParams.num_chds = this.passengersChds.text();
49311      submitParams.deep = false;
49312
49313      Utils.removeEmptyAttributes(submitParams);
49314      var submitQuerySring = $.param(submitParams);
49315      this.sendRouteSearchToAnalytics();
49316      var submitLocation = $('#searchResultPath').val() + '?' + submitQuerySring;
49317
49318      var loggedUser = SessionStorage.get("passenger");
49319      var checkLogin = $('[data-js="login-Dependency-Redirect"]').val();
49320
49321      setTimeout(function () {
49322        if (checkLogin == 'true') {
49323          if (loggedUser) $(location).attr('href', submitLocation); else $(location).attr('href', $('#loginPage').val());
49324        } else {
49325          $(location).attr('href', submitLocation);
49326        }
49327      }, 300);
49328    }
49329  }, {
49330    key: 'submitSearch',
49331    value: function submitSearch() {
49332      this.clearCart();
49333      this.setOriginDestinationCookie();
49334      this.redirectToSearchResult();
49335    }
49336  }, {
49337    key: 'handleSubmitError',
49338    value: function handleSubmitError(dataReturn, err) {
49339      var formData = this.getFormObject();
49340      SessionStorage.set('formData', formData);
49341
49342      if (formData.depart.destination.id === '') {
49343        this.sendRouteSearchToAnalytics(1);
49344      } else if (formData.depart.origin.id === '') {
49345        this.sendRouteSearchToAnalytics(2);
49346      } else if (formData.depart.date === '') {
49347        this.sendRouteSearchToAnalytics(3);
49348      } else if (dataReturn && !dataReturn.success) {
49349        this.sendRouteSearchToAnalytics(4);
49350      } else if (err != null && err.status != 200) {
49351        this.sendRouteSearchToAnalytics(5);
49352      }
49353
49354      this.currentResultDep = null;
49355      ValidationService.open('Não existe serviço para o trecho e/ou data selecionados.', null, this.btnSubmit);
49356    }
49357  }, {
49358    key: 'getMinDateDeparture',
49359    value: function getMinDateDeparture() {
49360      return DateFormatter.getNewFormattedDate();
49361    }
49362  }, {
49363    key: 'getMinDateReturn',
49364    value: function getMinDateReturn() {
49365      var minDayReturn = this.dateReturn.data("date");
49366      return minDayReturn ? minDayReturn + "T00:00" : "";
49367    }
49368  }, {
49369    key: 'getFormObject',
49370    value: function getFormObject() {
49371      var regexRemoveUF = new RegExp(/\s{1}(\([A-Z]{2}\))/g);
49372      return {
49373        passengers: this.personWindow.getQuantityObj(+this.passengers[0].innerText, +this.passengersChda[0].innerText, +this.passengersChds[0].innerText),
49374        departureOnly: this.dateReturn.data('date') == undefined || this.dateReturn.data('date') === "" ? true : false,
49375        depart: {
49376          date: this.dateDeparture.data('date'),
49377          minDate: this.getMinDateDeparture(),
49378          origin: {
49379            id: this.departure.data('value'),
49380            label: this.departure.val().replace(regexRemoveUF, ''),
49381            uf: this.departure.val().slice(-3, -1),
49382            address: this.departure.data('address')
49383          },
49384          destination: {
49385            id: this.destination.data('value'),
49386            label: this.destination.val().replace(regexRemoveUF, ''),
49387            uf: this.destination.val().slice(-3, -1),
49388            address: this.destination.data('address')
49389          }
49390        },
49391        return: {
49392          date: this.dateReturn.data('date') ? this.dateReturn.data('date') : "",
49393          minDate: this.getMinDateReturn(),
49394          origin: {
49395            id: this.destination.data('value'),
49396            label: this.destination.val().replace(regexRemoveUF, ''),
49397            uf: this.destination.val().slice(-3, -1),
49398            address: this.destination.data('address')
49399          },
49400          destination: {
49401            id: this.departure.data('value'),
49402            label: this.departure.val().replace(regexRemoveUF, ''),
49403            uf: this.departure.val().slice(-3, -1),
49404            address: this.departure.data('address')
49405          }
49406        },
49407        deep: false
49408      };
49409    }
49410  }, {
49411    key: 'setOriginDestinationCookie',
49412    value: function setOriginDestinationCookie() {
49413      var date = DateFormatter.getValidDateFormat();
49414      date.setTime(+date + this.searchCookieDaysToExpire.val() * 86400000);
49415      Utils.setCookie(this.searchCookieName, this.locationInput.lastSelected, date.toGMTString());
49416    }
49417  }, {
49418    key: 'getOriginDestinationCookie',
49419    value: function getOriginDestinationCookie() {
49420      var cookieResultObject = Utils.decodeCookie(this.searchCookieName);
49421
49422      if (cookieResultObject) {
49423        for (var prop in cookieResultObject) {
49424          var obj = cookieResultObject[prop];
49425          $('[data-js=' + prop + ']').val(obj.label);
49426          $('[data-js=' + prop + ']').data('value', obj.value);
49427          $('[data-js=' + prop + ']').data('address', obj.address);
49428        }
49429        this.locationInput.lastSelected = cookieResultObject;
49430      }
49431      return;
49432    }
49433  }]);
49434
49435  return SearchComponentForm;
49436}();
49437
49438/**
49439 * FIM
49440 * LOGICA SEARCH COMPONENT FORM
49441 *
49442 */
49443'use strict';
49444
49445var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
49446
49447function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
49448
49449var ShoppingInfo = function () {
49450  function ShoppingInfo() {
49451    _classCallCheck(this, ShoppingInfo);
49452
49453    this.originName = $('[data-js="origin-info"]');
49454    this.destinationName = $('[data-js="destination-info"]');
49455    this.passengersQuantityInfo = $('[data-js="passengers-quantity-info"]');
49456    this.departureDateInfo = $('[data-js="departure-date-info"]');
49457    this.returnDateInfo = $('[data-js="return-date-info"]');
49458    this.btnTripWay = $('[data-js="btn-change-way"]');
49459    this.locationInput = new LocationInput($, this, false);
49460    this.tripToRepricing = SessionStorage.get('tripToRepricing');
49461    this.remarkV2 = SessionStorage.get('repricingv2');
49462    this.init();
49463  }
49464
49465  _createClass(ShoppingInfo, [{
49466    key: 'init',
49467    value: function init() {
49468      this.fillInfo();
49469      this.handleChangeWay();
49470      if (!this.remarkV2) this.locationInput.loadDestinationAutocomplete();
49471    }
49472  }, {
49473    key: 'fillInfo',
49474    value: function fillInfo() {
49475
49476      $(this.originName).each(function (index, element) {
49477        if ($(element).find('.cmp-text').length > 0) {
49478          $(element).find('.cmp-text').text($('[data-js="input-departure"]').val());
49479        } else {
49480          $(element).text($('[data-js="input-departure"]').val());
49481        }
49482      });
49483
49484      $(this.destinationName).each(function (index, element) {
49485        if ($(element).find('.cmp-text').length > 0) {
49486          $(element).find('.cmp-text').text($('[data-js="input-destination"]').val());
49487        } else {
49488          $(element).text($('[data-js="input-destination"]').val());
49489        }
49490      });
49491
49492      $(this.passengersQuantityInfo).each(function (index, element) {
49493        if ($(element).find('.cmp-text').length > 0) {
49494          $(element).find('.cmp-text').text($('[data-js="passenger-current-value"]').first().text());
49495        } else {
49496          $(element).text($('[data-js="passenger-current-value"]').first().text());
49497        }
49498      });
49499
49500      $(this.departureDateInfo).each(function (index, element) {
49501        if ($(element).find('.cmp-text').length > 0) {
49502          $(element).find('.cmp-text').text($('[data-js="input-date-departure"]').val());
49503        } else {
49504          $(element).text($('[data-js="input-date-departure"]').val());
49505        }
49506      });
49507
49508      if (!$('[data-js="input-date-return"]').val()) {
49509        this.returnDateInfo.closest('.chosen-date').hide();
49510        this.departureDateInfo.closest('.shopping-info-content-date').removeClass('col-10').addClass('col-6');
49511        this.departureDateInfo.closest('.shopping-info-content-date').removeClass('col-sm-8').addClass('col-sm-6');
49512        this.passengersQuantityInfo.closest('.chosen-passengers').removeClass('col-10').addClass('col-6');
49513        this.passengersQuantityInfo.closest('.chosen-passengers').removeClass('.col-sm-4').addClass('col-sm-6');
49514        $('.shopping-info-content-date').addClass('active');
49515        $('.chosen-passengers').addClass('active');
49516        return;
49517      }
49518
49519      $(this.returnDateInfo).each(function (index, element) {
49520        if ($(element).find('.cmp-text').length > 0) {
49521          $(element).find('.cmp-text').text($('[data-js="input-date-return"]').val());
49522        } else {
49523          $(element).text($('[data-js="input-date-return"]').val());
49524        }
49525      });
49526    }
49527  }, {
49528    key: 'handleChangeWay',
49529    value: function handleChangeWay() {
49530      var _this = this;
49531      var body = $("body");
49532      var changeWayOv = $('[data-js="change-way-overlay"]');
49533      var closeChangeWayOv = $('[data-js="close-change-way-overlay"]');
49534
49535      this.btnTripWay.click(function (e) {
49536        if (_this.tripToRepricing) {
49537          $(location).attr('href', $('#rescheduleTripPath').val());
49538        } else {
49539          body.css('overflow-y', 'hidden');
49540          $('#wemobi-header').addClass('opened-overlay');
49541          changeWayOv.addClass('visible');
49542          document.documentElement.classList.add('force-no-scroll');
49543        }
49544      });
49545
49546      closeChangeWayOv.click(function (e) {
49547        $('html').removeClass('disable-scroll');
49548        var personWindowCloseButton = $('[data-js="cancel-person-quantity"]');
49549        personWindowCloseButton.trigger('click');
49550        body.css('overflow-y', 'auto');
49551        $('#wemobi-header').removeClass('opened-overlay');
49552        changeWayOv.removeClass('visible');
49553        document.documentElement.classList.remove('force-no-scroll');
49554      });
49555    }
49556  }]);
49557
49558  return ShoppingInfo;
49559}();
49560'use strict';
49561
49562function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
49563
49564//Ínicio Lógica Slider Main
49565var SliderMain = function SliderMain($) {
49566  _classCallCheck(this, SliderMain);
49567
49568  var carousel = $('[data-js="slider-header"]');
49569  var hiddenInput = $('[data-js="input-timer"]');
49570  var timer = parseInt(hiddenInput.val());
49571  carousel.slick({ dots: true, autoplay: true, autoplaySpeed: timer, infinite: true, prevArrow: fal
49571se, nextArrow: false });
49572};
49573//Fim Lógica Slider Main
49574'use strict';
49575
49576var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
49577
49578function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
49579
49580var TicketLabelDesktop = function () {
49581  function TicketLabelDesktop($) {
49582    _classCallCheck(this, TicketLabelDesktop);
49583
49584    this.btnCollapse = $('[data-js="arrow-collapse"]');
49585    this.ticketDetailsRote = $('[data-js="ticket-details-rote"]');
49586    this.init();
49587  }
49588
49589  _createClass(TicketLabelDesktop, [{
49590    key: 'init',
49591    value: function init() {
49592      this.openDetailsRote();
49593    }
49594  }, {
49595    key: 'openDetailsRote',
49596    value: function openDetailsRote() {
49597      var _this = this;
49598
49599      this.btnCollapse.on('click', function () {
49600        _this.ticketDetailsRote.toggleClass('active');
49601        _this.btnCollapse.toggleClass('active');
49602      });
49603    }
49604  }]);
49605
49606  return TicketLabelDesktop;
49607}();
49608'use strict';
49609
49610var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
49611
49612function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
49613
49614/**
49615 *
49616 * Register TripCancelTermsController
49617 *
49618 * INICIO
49619 */
49620
49621var TripCancelTermsController = function () {
49622  function TripCancelTermsController($) {
49623    _classCallCheck(this, TripCancelTermsController);
49624
49625    this.refuseButton = $('[data-js="terms-refuse-btn"]');
49626    this.acceptButton = $('[data-js="terms-accept-btn"]');
49627    this.termsCheck = $('[data-js="privacy-read-check"]');
49628    this.passenger = SessionStorage.get('passenger');
49629    this.init();
49630  }
49631
49632  _createClass(TripCancelTermsController, [{
49633    key: 'init',
49634    value: function init() {
49635      this.handleButtons();
49636      this.handleCheckbox();
49637    }
49638  }, {
49639    key: 'handleButtons',
49640    value: function handleButtons() {
49641      var _this = this;
49642
49643      this.refuseButton.on('click', function () {
49644        window.history.back();
49645      });
49646
49647      this.acceptButton.on('click', function () {
49648        if (_this.acceptButton.is('[disabled]')) return;
49649        _this.submitTermsAcceptance();
49650      });
49651    }
49652  }, {
49653    key: 'handleCheckbox',
49654    value: function handleCheckbox() {
49655      var _this2 = this;
49656
49657      this.termsCheck.on('change', function () {
49658        if (_this2.termsCheck.is(':checked')) {
49659          _this2.enableButton();
49660        } else {
49661          _this2.disableButton();
49662        }
49663      });
49664    }
49665  }, {
49666    key: 'enableButton',
49667    value: function enableButton() {
49668      this.acceptButton.removeClass('disabled');
49669      this.acceptButton.attr('disabled', false);
49670    }
49671  }, {
49672    key: 'disableButton',
49673    value: function disableButton() {
49674      this.acceptButton.addClass('disabled');
49675      this.acceptButton.attr('disabled', true);
49676    }
49677  }, {
49678    key: 'waitForDeviceId',
49679    value: function waitForDeviceId() {
49680      var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10000;
49681      var interval = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200;
49682
49683      return new Promise(function (resolve, reject) {
49684        var start = Date.now();
49685        var check = function check() {
49686          var id = $('#deviceId').val();
49687          if (id && id.trim() !== '') {
49688            resolve(id);
49689          } else if (Date.now() - start >= timeout) {
49690            reject(new Error('deviceId not available'));
49691          } else {
49692            setTimeout(check, interval);
49693          }
49694        };
49695        check();
49696      });
49697    }
49698  }, {
49699    key: 'submitTermsAcceptance',
49700    value: function submitTermsAcceptance() {
49701      var _this3 = this;
49702
49703      LoaderService.show();
49704
49705      var getDeviceId = function getDeviceId() {
49706        var current = $('#deviceId').val().trim();
49707        return current !== '' ? Promise.resolve($('#deviceId').val()) : _this3.waitForDeviceId();
49708      };
49709
49710      return getDeviceId().then(function (deviceId) {
49711        return _this3.getIP().then(function (userIp) {
49712          return { deviceId: deviceId, userIp: userIp };
49713        });
49714      }).then(function (_ref) {
49715        var deviceId = _ref.deviceId,
49716            userIp = _ref.userIp;
49717
49718        var payload = {
49719          userId: _this3.passenger ? _this3.passenger._id : '',
49720          systemId: 90,
49721          userIp: userIp,
49722          deviceId: deviceId,
49723          terms: [{
49724            title: 'Termo de Aceite Conta Giro',
49725            content: 'Política de Privacidade de Dados\n\nTermos e Condições da Conta Giro\nA Conta Giro valoriza sua privacidade e está comprometida em proteger seus dados pessoais. Esta Política de Privacidade explica como coletamos, usamos, armazenamos e protegemos as informações dos nossos usuários.\n\n1. Informações Coletadas\nColetamos informações pessoais quando você cria uma conta, utiliza nossos serviços ou entra em contato com nosso suporte. As informações podem incluir, mas não se limitam a, nome, endereço de e-mail, número de telefone, informações bancárias e dados de transações.\n\n2. Uso das Informações\nAs informações coletadas são usadas para:\n- Facilitar a gestão de sua conta na Conta Giro;\n- Processar transações financeiras;\n- Melhorar a experiência do usuário no aplicativo;\n- Enviar comunicações relacionadas ao serviço;\n- Cumprir requisitos legais e regulamentares.\n\n3. Compartilhamento de Informações\nNão compartilhamos suas informações pessoais com terceiros, exceto quando necessário para:\n- Processar transações através de nossos parceiros financeiros;\n- Cumprir obrigações legais;\n- Proteger contra fraudes e melhorar a segurança do serviço.',
49726            version: 1,
49727            category: 'giro-account-acceptance'
49728          }]
49729        };
49730
49731        var headers = _this3.getAuthHeaders();
49732        return HttpService.post('termsAcceptance', payload, headers);
49733      }).then(function (res) {
49734        if (res.success) {
49735          $(location).attr('href', i18n('register_wallet_page'));
49736        }
49737      }).catch(function (err) {
49738        console.error(err);
49739      }).finally(function () {
49740        LoaderService.hide();
49741      });
49742    }
49743  }, {
49744    key: 'getAuthHeaders',
49745    value: function getAuthHeaders() {
49746      var token = this.getToken();
49747      return { Authorization: token ? token : '' };
49748    }
49749  }, {
49750    key: 'getToken',
49751    value: function getToken() {
49752      var tokenFromStorage = SessionStorage.get('jca_token');
49753      if (tokenFromStorage) return tokenFromStorage;
49754      var tokenFromUrl = new URLSearchParams(window.location.search).get('jca_token');
49755      return tokenFromUrl ? tokenFromUrl.replace(/^"|"$/g, '') : null;
49756    }
49757  }, {
49758    key: 'getIP',
49759    value: function getIP() {
49760      return new Promise(function (resolve, reject) {
49761        $.getJSON('https://api.ipify.org?format=json').then(function (data) {
49762          return resolve(data.ip);
49763        }).catch(function () {
49764          $.getJSON('https://jsonip.com/').then(function (data) {
49765            return resolve(data.ip);
49766          }).catch(function (err) {
49767            return reject(err);
49768          });
49769        });
49770      });
49771    }
49772  }]);
49773
49774  return TripCancelTermsController;
49775}();
49776
49777/**
49778 *
49779 * Register TripCancelTermsController
49780 *
49781 * FIM
49782 */
49783'use strict';
49784
49785var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
49786
49787function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
49788
49789var TripDetails = function () {
49790  function TripDetails($parent, prefix) {
49791    _classCallCheck(this, TripDetails);
49792
49793    this._prefix = prefix;
49794    this._parent = $parent;
49795    this.cart = SessionStorage.get('cart');
49796
49797    $parent.find('[data-js="trip-details"]').attr('data-js', prefix + '-trip-details');
49798
49799    this.$showMoreDetailsContainer = $parent.find('.show-more-details-container');
49800    this.$tripDetails = $parent.find('[data-js="' + prefix + '-trip-details"]');
49801  }
49802
49803  _createClass(TripDetails, [{
49804    key: 'init',
49805    value: function init() {
49806      this.initListPassengers();
49807    }
49808  }, {
49809    key: 'initListPassengers',
49810    value: function initListPassengers() {
49811      if (this.cart == undefined) return;
49812      var mainPassenger = this.cart._listPassengers[0];
49813
49814      this.$showDetailsLabelArea = this._parent.find('.show-details-label-area');
49815      this.$showDetailsLabelArea.unbind('click');
49816      this.$showDetailsLabelArea.click(this.expandItem);
49817
49818      if (mainPassenger._name && mainPassenger._documentNumber) {
49819        this.$showDetailsLabelArea.show();
49820      }
49821    }
49822  }, {
49823    key: 'initData',
49824    value: function initData() {
49825      this.tripDetailsShowMore = new TripDetailsShowMore(this.$tripDetails, this._prefix);
49826      this.tripDetailsShowMore._offer = this._offer;
49827      this.tripDetailsShowMore._origin = this._origin;
49828      this.tripDetailsShowMore._destination = this._destination;
49829      this.tripDetailsShowMore.initDataForCart();
49830    }
49831  }, {
49832    key: 'expandItem',
49833    value: function expandItem() {
49834      var $parent = $(this).parent();
49835      var $showMoreArea = $parent.find('.trip-details-show-passenger');
49836      var $showMore = $parent.find('[data-js="show-details-label"]');
49837      var $chevron = $showMore.siblings('[data-js="icon-arrow"]');
49838
49839      if (!$showMoreArea.is(':visible')) {
49840        $showMore.text('Ocultar detalhes dos passageiros');
49841        $chevron.removeClass('jca-ico-angle-down');
49842        $chevron.addClass('jca-ico-angle-top');
49843      } else {
49844        $showMore.text('Exibir detalhes dos passageiros');
49845        $chevron.removeClass('jca-ico-angle-top');
49846        $chevron.addClass('jca-ico-angle-down');
49847      }
49848
49849      $showMoreArea.slideToggle();
49850      if ($chevron.hasClass('jca-ico-angle-top')) $parent.find('.icon-close').first().focus();
49851    }
49852  }, {
49853    key: 'origin',
49854    set: function set(origin) {
49855      this._origin = origin;
49856    }
49857  }, {
49858    key: 'destination',
49859    set: function set(destination) {
49860      this._destination = destination;
49861    }
49862  }, {
49863    key: 'offer',
49864    set: function set(offer) {
49865      this._offer = offer;
49866    }
49867  }]);
49868
49869  return TripDetails;
49870}();
49871'use strict';
49872
49873var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
49874
49875function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
49876
49877var Alert = function () {
49878  function Alert() {
49879    _classCallCheck(this, Alert);
49880  }
49881
49882  _createClass(Alert, null, [{
49883    key: 'show',
49884    value: function show(msg) {
49885      var _this = this;
49886
49887      if (msg == null) return;
49888
49889      var body = $('body');
49890      var html = '<div class="alert-overlay" id="alert-overlay" data-js="alert-overlay" tabindex="-1">\n      <article>\n      <header><button class="focusable close-alert-overlay" id="close-alert-overlay" data-js="close-alert-overlay"><em class="jca-ico-close icon"></em></button></header>\n      <main>\n      <p class="main-msg" data-js="main-msg">' + msg + '</p>\n      <button class="btn-back" id="close-alert-overlay" data-js="close-alert-overlay"> Fechar </button>\n      </main>\n      </article>\n      </div>\n    ';
49891
49892      if (body.has("#alert-overlay").length === 0) {
49893        body.append(html);
49894
49895        $('#alert-overlay').fadeIn('fast', function () {
49896          $(this).focus();
49897        });
49898      }
49899
49900      if (body.has("#cookie-warning-container").length > 0 && $("#cookie-warning-container").is(':visible')) {
49901        $('#alert-overlay').find().css('margin-top', 'calc(6vh + 10px)');
49902      }
49903
49904      if (body.has("#header-navbar").length > 0 && !$('#header-navbar').hasClass('header-navbar-fixed')) {
49905        $('#alert-overlay').css('top', '0');
49906      }
49907
49908      $('[data-js="close-alert-overlay"]').on('click focusout', function () {
49909        return _this.hide();
49910      });
49911    }
49912  }, {
49913    key: 'hide',
49914    value: function hide() {
49915      $('#alert-overlay').fadeOut('fast', function () {
49916        $(this).remove();
49917      });
49918    }
49919  }]);
49920
49921  return Alert;
49922}();
49923"use strict";
49924
49925var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
49926
49927function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
49928
49929var AlertTripTime = function () {
49930  function AlertTripTime(departureDate, arrivingDate) {
49931    _classCallCheck(this, AlertTripTime);
49932
49933    this.departureTime = DateFormatter.extractHour(departureDate);
49934    this.arrivingTime = DateFormatter.extractHour(arrivingDate);
49935  }
49936
49937  _createClass(AlertTripTime, [{
49938    key: "templateString",
49939    get: function get() {
49940      return "<div class=\"alert-trip-time-container\">\n        <div class=\"departure-time-container\">Partida:<span class=\"time\" data-js=\"alert-trip-departure-time\">" + this.departureTime + "</span></div>\n        <div class=\"arrival-time-container\">Chegada:<span class=\"time\" data-js=\"alert-trip-arrival-time\">" + this.arrivingTime + "</span></div>\n      </div>";
49941    }
49942  }]);
49943
49944  return AlertTripTime;
49945}();
49946'use strict';
49947
49948var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
49949
49950function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
49951
49952var AnchorController = function () {
49953  function AnchorController() {
49954    _classCallCheck(this, AnchorController);
49955
49956    this.init();
49957  }
49958
49959  _createClass(AnchorController, [{
49960    key: 'init',
49961    value: function init() {
49962      this.showWord();
49963    }
49964  }, {
49965    key: 'showWord',
49966    value: function showWord() {
49967      var currentUrl = window.location.href;
49968      var currentAnchor = currentUrl.split('#');
49969      var $elemId = $('#' + currentAnchor[1] + '');
49970      var collapseContent = $elemId.closest('.collapse');
49971
49972      if (currentAnchor[1]) {
49973        if (collapseContent.length > 0) {
49974          var elem = collapseContent.prev();
49975          elem.trigger('click');
49976        }
49977      }
49978    }
49979  }]);
49980
49981  return AnchorController;
49982}();
49983'use strict';
49984
49985(function ($) {
49986  var title = $('title').first().text();
49987  $('.main-title-container').text(title);
49988})(jQuery);
49989'use strict';
49990
49991var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
49992
49993function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
49994
49995var BottomMobileCart = function () {
49996  function BottomMobileCart($) {
49997    _classCallCheck(this, BottomMobileCart);
49998
49999    this.resumeBottomCart = $('[data-js="has-resume-bottom"]').attr('resume-bottom-cart') == "true";
50000    this.bottomResumeCart = $('[data-js="bottom-resume-cart"]');
50001    this.cartContainer = $('[data-js="cart-container"]');
50002
50003    this.init();
50004  }
50005
50006  _createClass(BottomMobileCart, [{
50007    key: 'init',
50008    value: function init() {
50009      this.loadResumeBottomCart();
50010    }
50011  }, {
50012    key: 'loadResumeBottomCart',
50013    value: function loadResumeBottomCart() {
50014      if (this.resumeBottomCart) {
50015        this.configureCartContainer();
50016        this.handleStyleWithOthersComponents();
50017      } else {
50018        this.bottomResumeCart.addClass('d-none');
50019      }
50020    }
50021  }, {
50022    key: 'configureCartContainer',
50023    value: function configureCartContainer() {
50024      $('.summary-item').addClass('with-resume-bottom-cart');
50025      this.cartContainer.find('.cart-mobile-heder').addClass('d-none');
50026      this.cartContainer.removeClass('cart-details-container');
50027      this.cartContainer.addClass('cart-details-container-bottom-cart');
50028    }
50029  }, {
50030    key: 'handleStyleWithOthersComponents',
50031    value: function handleStyleWithOthersComponents() {
50032      if ($(window).width() <= 950) {
50033        $('.footer').css('padding-bottom', '20px');
50034      }
50035      $('.seat-reservation .card-container .row').css('padding-bottom', '50px');
50036    }
50037  }]);
50038
50039  return BottomMobileCart;
50040}();
50041'use strict';
50042
50043var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
50044
50045function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
50046
50047var BpeMessage = function () {
50048  function BpeMessage($element, originData) {
50049    _classCallCheck(this, BpeMessage);
50050
50051    this.element = $element;
50052    this.data = originData;
50053    this.init();
50054  }
50055
50056  _createClass(BpeMessage, [{
50057    key: 'init',
50058    value: function init() {
50059      var $title = this.element.find('[data-js="bpe-message-title"]');
50060      var $message = this.element.find('[data-js="bpe-message-content"]');
50061
50062      var _getMessageFromServic = this.getMessageFromService(),
50063        title = _getMessageFromServic.title,
50064        msgHtml = _getMessageFromServic.msgHtml;
50065
50066      $title.text(title);
50067      $message.html(msgHtml);
50068    }
50069  }, {
50070    key: 'getMessageFromService',
50071    value: function getMessageFromService() {
50072      var title = void 0,
50073        msgHtml = void 0;
50074      var lang = Utils.getCurrentLang();
50075      var id = this.data.originId;
50076      var uf = this.data.originDescription.slice(this.data.originDescription.length - 2);
50077
50078      LoaderService.show();
50079      HttpService.getAEM('jcaholding_bpe.json?lang=' + lang + '&id=' + id + '&uf=' + uf).then(function (data) {
50080        title = data.result.title;
50081        msgHtml = data.result.message;
50082      }).catch(function (err) {
50083        console.log(err);
50084      }).finally(function () {
50085        LoaderService.hide();
50086        return { title: title, msgHtml: msgHtml };
50087      });
50088    }
50089  }]);
50090
50091  return BpeMessage;
50092}();
50093'use strict';
50094
50095var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
50096
50097function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
50098
50099var BusMapSeat = function () {
50100  function BusMapSeat($) {
50101    _classCallCheck(this, BusMapSeat);
50102
50103    this.$busMapWrapper = $('[data-js="bus-map-wrapper"]');
50104    this.$mapBus = this.$busMapWrapper.find('[data-js="map-bus"]');
50105    this.$seatTemplate = $('[data-js="seat-template"]');
50106    this.$hallTemplate = $('[data-js="inline-hall-template"]');
50107    this.$rowContainerTemplate = $('[data-js="row-container-template"]');
50108    this.seatColor = $('[data-js="seat-color"]').val();
50109    this.seatFontColor = $('[data-js="seat-font-color"]').val();
50110    this.unavailableSeatColor = $('[data-js="unavailable-seat-color"]').val();
50111    this.unavailableSeatFontColor = $('[data-js="unavailable-seat-font-color"]').val();
50112    this.freeSeatColor = $('[data-js="free-seat-color"]').val();
50113    this.selectedSeatFontColor = $('[data-js="selected-seat-font-color"]').val();
50114
50115    this.freeSeatBorderColor;
50116    this.freeSeatBorderSmallRectangule;
50117    // - Block seats
50118    this.seatBlockBorderColor = $('[data-js="block-seat-border-color"]').val();
50119    this.seatBlockBackgroundColor = $('[data-js="block-seat-background-color"]').val();
50120    this.seatBlockFontColor = $('[data-js="block-seat-font-color"]').val();
50121    this.seatBlockSmallRectanguleBorderColor = $('[data-js="block-seat-small-rectangule-border-color"]').val();
50122    this.seatBlockSmallRectanguleBackgroundColor = $('[data-js="block-seat-small-rectangule-background-color"]').val();
50123
50124    // Selected seat
50125    this.seatSelectedBorderColor = $('[data-js="selected-seat-border-color"]').val();
50126    this.seatSelectedBackgroundColor = $('[data-js="selected-seat-background-color"]').val();
50127    this.seatSelectedFontColor = $('[data-js="selected-seat-font-color"]').val();
50128    this.seatSelectedSmallRectanguleBorderColor = $('[data-js="selected-seat-small-rectangule-border-color"]').val();
50129    this.seatSelectedSmallRectanguleBackgroundColor = $('[data-js="selected-seat-small-rectangule-background-color"]').val();
50130    this.initLegendSeatColors();
50131  }
50132
50133  _createClass(BusMapSeat, [{
50134    key: 'initLegendSeatColors',
50135    value: function initLegendSeatColors() {
50136      var legendBlock = $('.seat-legend');
50137      var regularSeat = legendBlock.find('.seat-rectangule').not('.selected').not('.occuped');
50138      var unavailable = legendBlock.find('.seat-rectangule.block');
50139      var selected = legendBlock.find('.seat-rectangule.selected');
50140
50141      regularSeat.css({
50142        'background-color': this.seatColor,
50143        'border': '2px solid' + this.freeSeatBorderColor,
50144        'color': this.freeSeatColor
50145      });
50146
50147      regularSeat.find('.seat-rectangule-small').css({
50148        'background': this.freeSeatColor,
50149        'border': '2px solid' + this.freeSeatBorderSmallRectangule
50150      });
50151
50152      unavailable.css({
50153        'background-color': this.seatBlockBackgroundColor,
50154        'border': '2px solid' + this.seatBlockBorderColor,
50155        'color': this.seatBlockFontColor
50156      });
50157
50158      unavailable.find('.seat-rectangule-small').css({
50159        'background': this.seatBlockSmallRectanguleBackgroundColor,
50160        'border': '2px solid' + this.seatBlockSmallRectanguleBorderColor
50161      });
50162
50163      selected.css({
50164        'background-color': this.seatSelectedBackgroundColor,
50165        'border': '2px solid' + this.seatSelectedBorderColor,
50166        'color': this.seatSelectedFontColor
50167      });
50168
50169      selected.find('.seat-rectangule-small').css({
50170        'background': this.seatSelectedSmallRectanguleBackgroundColor,
50171        'border': '2px solid' + this.seatSelectedSmallRectanguleBorderColor
50172      });
50173    }
50174  }, {
50175    key: 'init',
50176    value: function init(seatList) {
50177      var mapBus = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.$mapBus;
50178
50179      if (!mapBus) mapBus = this.$mapBus;
50180
50181      mapBus.html('');
50182      seatList.sort(function (a, b) {
50183        return a.x - b.x || a.y - b.y;
50184      });
50185      var $row = mapBus.closest('[data-js="bus-map-wrapper"]').siblings('[data-js="row-container-template"]').clone();
50186      $row.attr('data-js', '1');
50187      mapBus.append($row);
50188      for (var i = 0, lastColumn = '0', lastLine = '1'; i < seatList.length; i++) {
50189        this.appendHall($row, seatList[i], lastColumn);
50190        lastColumn = seatList[i].y;
50191        if (parseInt(seatList[i].x) > parseInt(lastLine)) {
50192          lastLine = seatList[i].x;
50193          $row = mapBus.closest('[data-js="bus-map-wrapper"]').siblings('[data-js="row-container-template"]').clone();
50194          $row.attr('data-js', lastLine);
50195          mapBus.append($row);
50196        }
50197        this.appendSeat($row, seatList[i], mapBus);
50198      }
50199    }
50200  }, {
50201    key: 'appendHall',
50202    value: function appendHall($row, seat, lastColumn) {
50203      if (parseInt(seat.y) - parseInt(lastColumn) > 1) {
50204        var $hall = this.$hallTemplate.clone();
50205        $row.append($hall);
50206        $hall.show();
50207      }
50208    }
50209  }, {
50210    key: 'appendSeat',
50211    value: function appendSeat($row, seat, mapBus) {
50212      var $seat = void 0;
50213      if (seat.number) {
50214        $seat = mapBus.closest('[data-js="bus-map-wrapper"]').siblings('[data-js="seat-template"]').clone();
50215        $seat.attr('data-js', 'seat-' + seat.number);
50216        $seat.find('.seat-number').text(seat.number);
50217        $seat.attr('id', 'seat-' + seat.number);
50218        this.restoreSeatColor($seat.find('.inner-seat'));
50219        if (!seat.avaliable) this.occupySeat($seat.find('.inner-seat'));
50220      } else $seat = this.$hallTemplate.clone();
50221
50222      $row.append($seat);
50223      $seat.show();
50224    }
50225  }, {
50226    key: 'restoreSeatColor',
50227    value: function restoreSeatColor($seat, seatnumber) {
50228      if (this.seatColor) {
50229        $seat.find('.seat-rectangule').attr('style', 'background-color: ' + this.seatColor);
50230
50231        $seat.find('.seat-rectangule-small').attr('style', 'background:' + this.freeSeatColor + ';');
50232      }
50233      if (this.seatFontColor) $seat.find('.seat-number').attr('style', 'color: ' + this.seatFontColor + ';');
50234
50235      $seat.find('.jca-ico-seat').attr('style', '');
50236      $seat.find('.seat-number').text(seatnumber);
50237    }
50238  }, {
50239    key: 'occupySeat',
50240    value: function occupySeat($seat, value) {
50241      $seat.addClass('occupied-seat');
50242      $seat.find('.seat-number').text("X").css('color', this.seatBlockFontColor);
50243      $seat.find('.seat-rectangule').css({
50244        'background-color': this.seatBlockBackgroundColor,
50245        'border': '2px solid' + this.seatBlockBorderColor,
50246        'color': this.seatBlockFontColor
50247      });
50248
50249      $seat.find('.seat-rectangule-small').css({
50250        'background': this.seatBlockSmallRectanguleBackgroundColor,
50251        'border': '2px solid' + this.seatBlockSmallRectanguleBorderColor
50252      });
50253
50254      $seat.addClass('occuped');
50255    }
50256  }, {
50257    key: 'freeSeat',
50258    value: function freeSeat($seat) {
50259      $seat.removeClass('occuped');
50260      this.restoreSeatColor($seat);
50261    }
50262  }, {
50263    key: 'selectSeat',
50264    value: function selectSeat($seat, numero) {
50265      $seat.find('.seat-number').closest('.inner-seat').addClass('selected');
50266      $seat.attr('style', '');
50267
50268      if (this.seatSelectedBackgroundColor) {
50269        $seat.find('.seat-rectangule').attr('style', 'background:' + this.seatSelectedBackgroundColor + '; color: white;');
50270      }
50271
50272      if (this.seatSelectedSmallRectanguleBackgroundColor) {
50273        $seat.find('.seat-rectangule-small').attr('style', 'background:' + this.seatSelectedSmallRectanguleBackgroundColor + ';');
50274      }
50275
50276      if (this.seatSelectedFontColor) {
50277        $seat.find('.seat-number').removeClass('block').attr('style', 'color:' + this.seatSelectedFontColor + ';');
50278      }
50279
50280      if (this.seatSelectedFontColor) {
50281        $seat.find('.seat-number').attr('style', 'color: ' + this.seatSelectedFontColor + ' ;');
50282      }
50283
50284      if (Utils.isMobile()) {
50285        $('[data-js="close-bus-map"]').trigger('click');
50286      }
50287
50288      $seat.find('.seat-number').text(numero);
50289      $seat.parent().attr('disabled', false);
50290    }
50291  }, {
50292    key: 'unselectSeat',
50293    value: function unselectSeat($seat, seatnumber) {
50294      $seat.find('.seat-number').closest('.inner-seat').removeClass('selected');
50295      this.restoreSeatColor($seat, seatnumber);
50296    }
50297  }]);
50298
50299  return BusMapSeat;
50300}();
50301'use strict';
50302
50303(function ($) {
50304  $('[data-js=button-logout]').click(function (e) {
50305    SessionStorage.remove('passenger');
50306    SessionStorage.remove('cart')
50307    localStorage.setItem("logged", false);
50308    $(location).attr('href', $('#homePagePath').val());
50309  });
50310})(jQuery);
50311"use strict";
50312
50313var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
50314
50315function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
50316
50317var CartButton = function () {
50318  function CartButton($) {
50319    _classCallCheck(this, CartButton);
50320
50321    var $cartIcon = $("[data-js='cart-button-icon']");
50322    var $cartModal = $('.cart-modal');
50323    $cartModal.find("[data-js='btn-close-cart-details']").attr('data-js', 'btn-close-cart-details-modal');
50324    var $closeButton = $cartModal.find("[data-js='btn-close-cart-details-modal']");
50325    this.overlay = $('[data-js="header-cart-modal-overlay"]');
50326    $cartIcon.click(CartButton.handlerCartIconClick);
50327    $closeButton.off('click');
50328    $closeButton.on('click', CartButton.hideModal);
50329    $('[data-js="header-cart-modal"]').children().focusout(function (e) {
50330      var $target = $(e.relatedTarget);
50331      if ($target.length > 0 && $target.closest('[data-js="header-cart-modal-overlay"]').length == 0 && $target.closest('.cart-details-container').length == 0) $closeButton.click();
50332    });
50333  }
50334
50335  _createClass(CartButton, null, [{
50336    key: "showModal",
50337    value: function showModal(e) {
50338      var body = $("body");
50339      var width = Utils.getWindowSize().width;
50340      var $closeButton = $('.cart-modal').find("[data-js='btn-close-cart-details-modal']").first();
50341      CartButton.scrollPosition = $(window).scrollTop();
50342      $('.cart-modal').addClass('active');
50343      $('[data-js="header-cart-modal-overlay"]').addClass('active');
50344      body.css('width', width);
50345      body.css('position', 'fixed');
50346      body.css('top', -CartButton.scrollPosition);
50347      $closeButton.focus();
50348    }
50349  }, {
50350    key: "hideModal",
50351    value: function hideModal(e) {
50352      var body = $("body");
50353      $('.cart-modal').removeClass('active');
50354      $('[data-js="header-cart-modal-overlay"]').removeClass('active');
50355      body.css('width', '');
50356      body.css('position', '');
50357      body.css('top', '');
50358      $(window).scrollTop(CartButton.scrollPosition);
50359      $("[data-js='cancel-way-confirmation-overlay']").slideUp("fast");
50360    }
50361  }, {
50362    key: "handlerCartIconClick",
50363    value: function handlerCartIconClick(e) {
50364      var isCartModalHidden = $('.cart-modal').is(":hidden");
50365      if (isCartModalHidden) {
50366        CartButton.showModal(e);
50367      } else {
50368        CartButton.hideModal(e);
50369      }
50370    }
50371  }]);
50372
50373  return CartButton;
50374}();
50375
50376(function ($) {
50377  new CartButton($);
50378})(jQuery);
50379'use strict';
50380
50381var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
50382
50383function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
50384
50385var CheckboxController = function () {
50386  function CheckboxController() {
50387    _classCallCheck(this, CheckboxController);
50388
50389    this.checkboxSite = $('[data-js="checkbox-site"]');
50390    this.init();
50391  }
50392
50393  _createClass(CheckboxController, [{
50394    key: 'init',
50395    value: function init() {
50396      this.verifyCheckboxMandatory();
50397    }
50398  }, {
50399    key: 'verifyCheckboxMandatory',
50400    value: function verifyCheckboxMandatory() {
50401      this.checkboxSite.each(function () {
50402        if ($(this).data('mandatory')) {
50403          $(this).find('input').attr('required', true);
50404        }
50405      });
50406    }
50407  }]);
50408
50409  return CheckboxController;
50410}();
50411'use strict';
50412
50413var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
50414
50415function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
50416
50417var Collapse = function () {
50418  function Collapse() {
50419    _classCallCheck(this, Collapse);
50420
50421    this.init();
50422  }
50423
50424  _createClass(Collapse, [{
50425    key: 'init',
50426    value: function init() {
50427      this.collapseAccordion();
50428      this.listenCollapseGeneric();
50429    }
50430  }, {
50431    key: 'listenCollapseGeneric',
50432    value: function listenCollapseGeneric() {
50433      $('[data-bs-collapse="collapse"]').on('click', function (e) {
50434        e.stopImmediatePropagation();
50435        $(e.target).toggleClass('active');
50436
50437        if (!$(e.target).hasClass('.icon-collapse')) $(e.target).find('.icon-collapse').toggleClass('active');
50438
50439        var showContainer = $(e.target).data('js');
50440        var $divCollapse = $('.collapse-container[data-js="' + showContainer + '"]');
50441
50442        if ($divCollapse.hasClass('active')) {
50443          $divCollapse.slideUp('fast', function () {
50444            return $divCollapse.removeClass('active');
50445          });
50446          return;
50447        }
50448
50449        $('.collapse-container[data-js="' + showContainer + '"]').slideToggle('fast');
50450      });
50451    }
50452  }, {
50453    key: 'collapseAccordion',
50454    value: function collapseAccordion() {
50455      $('#accordion').on('shown.bs.collapse', function (e) {
50456        $(e.target).prev().find('.icon').addClass('open');
50457
50458        $('body, html').animate({
50459          scrollTop: $(e.target).prev().offset().top - 80
50460        }, 350);
50461      }).on('hide.bs.collapse', function (e) {
50462        $(e.target).prev().find('.icon').removeClass('open');
50463
50464        $('body, html').animate({
50465          scrollTop: $('.faq-container').offset().top - 80
50466        }, 350);
50467      });
50468    }
50469  }]);
50470
50471  return Collapse;
50472}();
50473"use strict";
50474
50475var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
50476
50477function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
50478
50479var CookieWarning = function () {
50480  function CookieWarning() {
50481    var _this = this;
50482
50483    _classCallCheck(this, CookieWarning);
50484
50485    this.cookieWarningContainer = $('.cookie-warning-container');
50486    this.cookieWarningCloseButton = $("[data-js='cookie-warning-close']");
50487    this.header = $('#header-navbar');
50488    this.contentTextHeader = $('.header-container-text');
50489    this.cookieName = "CookieWarning";
50490    this.ticketStoreContainer = $('.main-content-spaced.ticket-store');
50491    this.init();
50492
50493    $(window).on('resize', function () {
50494      var isDesktop = _this.isDesktop;
50495      _this.checkWindowSize();
50496      var cookieData = Utils.decodeCookie(_this.cookieName);
50497      if (isDesktop != _this.isDesktop && (!cookieData || !cookieData.hasCl
50497ickedClose)) {
50498        _this.hideCookieWarning();
50499        _this.showCookieWarning();
50500      }
50501    });
50502  }
50503
50504  _createClass(CookieWarning, [{
50505    key: "checkWindowSize",
50506    value: function checkWindowSize() {
50507      var windowSizeObject = Utils.getWindowSize();
50508      if (windowSizeObject.width > windowSizeObject.breakpoints.LG) this.isDesktop = true; else this.isDesktop = false;
50509    }
50510  }, {
50511    key: "init",
50512    value: function init() {
50513      var cookieData = Utils.decodeCookie(this.cookieName);
50514      if (!cookieData || !cookieData.hasClickedClose) {
50515        this.setBackgroundColor();
50516        this.setCookieWarningClickEvent();
50517        this.showCookieWarning();
50518      }
50519    }
50520  }, {
50521    key: "isAboveHeader",
50522    value: function isAboveHeader() {
50523      return this.cookieWarningContainer.next().is('header') ||
50524        this.cookieWarningContainer.parent().next().find('header').length > 0 ||
50525        this.cookieWarningContainer.parent().next().next().find('header').length > 0 ||
50526        this.cookieWarningContainer.parent().parent().next().find('header').length > 0;
50527    }
50528  }, {
50529    key: "showCookieWarning",
50530    value: function showCookieWarning() {
50531      this.cookieWarningContainer.show();
50532
50533      if (this.isAboveHeader()) {
50534        if ($(window).width() > 950) {
50535          var paddingTop = parseFloat($('.main-content').css('padding-top'));
50536          var height = parseFloat(this.cookieWarningContainer.css('height'));
50537          $('.header-site').css('top', height + 'px');
50538          $('.main-content').css('padding-top', paddingTop + height + 'px');
50539          $('.chosen-lang').css('top', height + 'px');
50540        }
50541        this.cookieWarningContainer.addClass('is-above-header');
50542        this.header.addClass('active');
50543        this.contentTextHeader.addClass('active');
50544        this.ticketStoreContainer.addClass('active');
50545      }
50546    }
50547  }, {
50548    key: "adjustPasswordOverlay",
50549    value: function adjustPasswordOverlay() {
50550      var headerCurrentTop = parseInt($('.header-site').css('top'));
50551      var overlayComponent = $('[data-js="bottom-password"]');
50552
50553      if (overlayComponent.is(':visible')) {
50554        var top = parseInt(overlayComponent.css('top')) - headerCurrentTop;
50555        overlayComponent.css('top', top);
50556      }
50557    }
50558  }, {
50559    key: "hideCookieWarning",
50560    value: function hideCookieWarning() {
50561      this.cookieWarningContainer.hide();
50562      this.adjustPasswordOverlay();
50563      $('.header-site').css('top', 0);
50564      $('.main-content').css('padding-top', '');
50565      $('.chosen-lang').css('top', 0);
50566      if ($('[data-js="alert-covid"]').length > 0) {
50567        $('#header-navbar').css('margin-top', this.cookieWarningContainer.height() + 'px');
50568      }
50569      this.cookieWarningContainer.removeClass('is-above-header');
50570      this.header.removeClass('active');
50571      this.contentTextHeader.removeClass('active');
50572      this.ticketStoreContainer.removeClass('active');
50573    }
50574  }, {
50575    key: "setBackgroundColor",
50576    value: function setBackgroundColor() {
50577      var backgroundColor = $("[data-js='cookie-warning-background-color']").val();
50578      this.cookieWarningContainer.css('background-color', backgroundColor);
50579    }
50580  }, {
50581    key: "closeEvent",
50582    value: function closeEvent() {
50583      var cookieExpiration = parseInt($("[data-js='cookie-warning-expiration']").val()) * 24;
50584      var cookieDate = DateFormatter.getValidDateFormat();
50585      cookieDate.setHours(cookieDate.getHours() + cookieExpiration);
50586      var cookieData = { "hasClickedClose": true };
50587      Utils.setCookie(this.cookieName, cookieData, cookieDate);
50588      this.hideCookieWarning();
50589    }
50590  }, {
50591    key: "setCookieWarningClickEvent",
50592    value: function setCookieWarningClickEvent() {
50593      var _this2 = this;
50594
50595      this.cookieWarningCloseButton.click(function (e) {
50596        e.preventDefault();
50597        _this2.closeEvent();
50598      });
50599    }
50600  }]);
50601
50602  return CookieWarning;
50603}();
50604"use strict";
50605
50606var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
50607
50608function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
50609
50610var InfoIcon = function () {
50611  function InfoIcon($component, className, $closeIcon) {
50612    var _this = this;
50613
50614    _classCallCheck(this, InfoIcon);
50615
50616    this.icon = $("[data-js='show-info-container']");
50617    this.className = className;
50618    this.$component = $component;
50619    this.$closeIcon = $closeIcon;
50620    this.icon.click(function (e) {
50621      _this.lastSelectedComponent = $(e.currentTarget);
50622      _this.toggle();
50623    });
50624    if ($closeIcon) {
50625      $closeIcon.click(function () {
50626        _this.close();
50627      });
50628    }
50629  }
50630
50631  _createClass(InfoIcon, [{
50632    key: "toggle",
50633    value: function toggle() {
50634      if (this.className) this.$component.toggleClass(this.className); else this.$component.toggle();
50635      if (this.$closeIcon) this.$closeIcon.focus();
50636    }
50637  }, {
50638    key: "close",
50639    value: function close() {
50640      if (this.className) this.$component.removeClass(this.className); else this.$component.hide();
50641      this.lastSelectedComponent.focus();
50642    }
50643  }]);
50644
50645  return InfoIcon;
50646}();
50647'use strict';
50648
50649var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
50650
50651function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
50652
50653var ControllerLoggedAccess = function () {
50654  function ControllerLoggedAccess() {
50655    _classCallCheck(this, ControllerLoggedAccess);
50656
50657    this.tokenJCA = null;
50658    this.init();
50659  }
50660
50661  _createClass(ControllerLoggedAccess, [{
50662    key: 'init',
50663    value: function init() {
50664      var _this = this;
50665
50666      this.getParamsUrl(function () {
50667        _this.loadPassengerInfo();
50668      });
50669    }
50670  }, {
50671    key: 'getParamsUrl',
50672    value: function getParamsUrl(callback) {
50673      this.tokenJCA = Utils.getParamsUrl('jca_token');
50674
50675      if (this.tokenJCA) callback();
50676    }
50677  }, {
50678    key: 'getAttributeDecodedJWTToken',
50679    value: function getAttributeDecodedJWTToken() {
50680      return Utils.decodeJWT(this.tokenJCA);
50681    }
50682  }, {
50683    key: 'loadPassengerInfo',
50684    value: function loadPassengerInfo() {
50685      var attributes = this.getAttributeDecodedJWTToken();
50686
50687      this.passenger = this.parsePassenger(attributes);
50688      SessionStorage.set('passenger', this.passenger);
50689      localStorage.setItem("logged", true);
50690
50691      this.updateURLRemovedToken();
50692    }
50693  }, {
50694    key: 'parsePassenger',
50695    value: function parsePassenger(data) {
50696      var passenger = new Passenger();
50697      passenger.name = String(data.user_Name + ' ' + data.user_FamilyName).trim();
50698      passenger.login = data.user_Login;
50699      passenger.email = data.user_Email;
50700      passenger.image = data.user_Image;
50701      passenger.cpf = data.user_Cpf;
50702      passenger.documentNumber = data.user_Cpf;
50703      passenger.birthDate = DateFormatter.parseDateApiFormatJWT(data.user_BirthDate.split(' ')[0]);
50704      passenger.phone = data.user_Phone;
50705      passenger.areaCode = data.user_AreaCode;
50706      passenger.phoneType = data.user_PhoneType ? data.user_PhoneType.toLowerCase() == 'mobile' ? 1 : 2 : null;
50707      passenger.id = data.user_Id;
50708      passenger.optin = data.user_Optin;
50709      passenger.groups = data.user_Groups;
50710      return passenger;
50711    }
50712  }, {
50713    key: 'updateURLRemovedToken',
50714    value: function updateURLRemovedToken() {
50715      var sPageURL = window.location.href.split('?');
50716      var urlParam = "";
50717      if (sPageURL.length > 1) {
50718        var urlParamArray = sPageURL[1].split('&');
50719        if (urlParamArray.length > 1) {
50720          for (var i = 1; i < urlParamArray.length; i++) {
50721            if (i == 1) {
50722              var urlParamTokenArray = urlParamArray[0].split('=');
50723              if (urlParamTokenArray.length > 1) {
50724                if (urlParamTokenArray[0] == 'token') {
50725                  urlParam += "?" + urlParamArray[0];
50726                } else {
50727                  urlParam += "?" + urlParamArray[i];
50728                }
50729              }
50730            } else {
50731              urlParam += "&" + urlParamArray[i];
50732            }
50733          }
50734        }
50735      }
50736
50737      $(location).attr('href', sPageURL[0] + urlParam);
50738    }
50739  }]);
50740
50741  return ControllerLoggedAccess;
50742}();
50743'use strict';
50744
50745var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
50746
50747function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
50748
50749var InformativeItem = function () {
50750  function InformativeItem($) {
50751    _classCallCheck(this, InformativeItem);
50752
50753    this.informativeTextContainer = $('[data-js="informative-text-container"]');
50754    this.informativeTitle = $('[data-js="informative-title"]');
50755    this.informativeText = $('[data-js="informative-text"]');
50756    this.informativeImage = $('[data-js="informative-image"]');
50757    this.informative = $('[data-js="informative"]');
50758    this.hasBoxShadow = this.informative.attr('has-box-shadow') == 'true' ? true : false;
50759    this.isBanner = this.informative.attr('is-banner') == 'true' ? true : false;
50760
50761    this.init();
50762  }
50763
50764  _createClass(InformativeItem, [{
50765    key: 'init',
50766    value: function init() {
50767      this.handleText();
50768      this.handleImage();
50769      this.handleLink();
50770    }
50771  }, {
50772    key: 'handleLink',
50773    value: function handleLink() {
50774      this.informative.each(function (_, el) {
50775        var isRedirectInSamePage = $(el).attr('redirect-in-same-page') == 'true';
50776        var linkToRedirect = $(el).attr('link-redirect');
50777        var $linkInformative = $(el).closest('[data-js="informative-redirect"]');
50778        if (!linkToRedirect) {
50779          $linkInformative.off('click').css('cursor', 'auto');
50780          return;
50781        }
50782        if (!isRedirectInSamePage) {
50783          $linkInformative.attr({ 'target': '_blank' });
50784          return;
50785        }
50786        $linkInformative.attr({ 'href': linkToRedirect });
50787      });
50788    }
50789  }, {
50790    key: 'handleText',
50791    value: function handleText() {
50792      var titleFontSize = this.informativeTitle.attr('data-font-size');
50793      var textFontSize = this.informativeText.attr('data-font-size');
50794
50795      if (titleFontSize > 0) {
50796        this.informativeTitle.css('font-size', this.setValueToPX(titleFontSize));
50797      }
50798
50799      if (textFontSize > 0) {
50800        this.informativeText.css('font-size', this.setValueToPX(textFontSize));
50801      }
50802    }
50803  }, {
50804    key: 'handleImage',
50805    value: function handleImage() {
50806      var imageMaxWidth = this.informativeImage.attr('data-max-width');
50807      var imageMinHeight = this.informativeImage.attr('data-min-height');
50808
50809      if (this.isBanner) {
50810        this.setupInformativeWithBackground();
50811        if (!imageMaxWidth) {
50812          this.informativeImage.css('max-width', '100%');
50813          this.informativeImage.css('min-width', '100%');
50814        } else {
50815          this.informativeImage.css('max-width', imageMaxWidth);
50816          this.informativeImage.css('min-width', imageMaxWidth);
50817          this.informativeImage.css('max-height', imageMinHeight);
50818          this.informativeImage.css('min-height', imageMinHeight);
50819        }
50820      } else {
50821        this.setMaxWidthAndMinHeight(this.informativeImage, imageMaxWidth);
50822        this.setupInformative();
50823      }
50824    }
50825  }, {
50826    key: 'setupInformative',
50827    value: function setupInformative() {
50828      var maxWidthInformative = this.informative.attr('data-max-width');
50829      var minHeightInformative = this.informative.attr('data-min-height');
50830
50831      this.setMaxWidthAndMinHeight(this.informative, maxWidthInformative, minHeightInformative);
50832
50833      if (this.hasBoxShadow) {
50834        this.informative.addClass('with-box-shadow');
50835      }
50836    }
50837  }, {
50838    key: 'setupInformativeWithBackground',
50839    value: function setupInformativeWithBackground() {
50840      var informativeMaxWidth = this.informative.attr('data-max-width');
50841
50842      this.hideText();
50843      this.informative.addClass('with-background');
50844      this.setMaxWidthAndMinHeight(this.informative, informativeMaxWidth);
50845
50846      if (this.hasBoxShadow) {
50847        this.informativeImage.addClass('with-box-shadow');
50848      }
50849    }
50850  }, {
50851    key: 'setValueToPX',
50852    value: function setValueToPX(value) {
50853      return value + 'px';
50854    }
50855  }, {
50856    key: 'setMaxWidthAndMinHeight',
50857    value: function setMaxWidthAndMinHeight(el) {
50858      var maxWidth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "auto";
50859      var minHeight = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "auto";
50860
50861      $(el).css('max-width', maxWidth);
50862      $(el).css('min-height', minHeight);
50863    }
50864  }, {
50865    key: 'hideText',
50866    value: function hideText() {
50867      this.informativeTextContainer.addClass('d-none');
50868    }
50869  }]);
50870
50871  return InformativeItem;
50872}();
50873'use strict';
50874
50875var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
50876
50877function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
50878
50879/**
50880 *
50881 * LOGIN BUTTON
50882 *
50883 * BEGIN
50884 */
50885
50886var LoginButton = function () {
50887  function LoginButton($) {
50888    _classCallCheck(this, LoginButton);
50889
50890    this.loginButton = $('[data-js="header-login-button"]');
50891    this.closeButton = $('[data-js="header-login-close-button"]');
50892    this.modal = $('[data-js="header-login-modal"]');
50893    this.overlay = $('[data-js="header-login-modal-overlay"]');
50894    this.loginInput = $('[data-js="input-login"]');
50895    this.loggedInSection = $('[data-js="logged-in-section"]');
50896    this.loggedOutSection = $('[data-js="logged-out-section"]');
50897    this.passenger = $('[data-js="user-name"]');
50898    this.loggedButton = $('[data-js="logged-button"]');
50899    this.userMenu = $('[data-js="user-menu"]');
50900    this.userMenuOverlay = $('[data-js="user-menu-overlay"]');
50901    this.logoutButton = $('[data-js="user-menu-logout"]');
50902    this.init();
50903  }
50904
50905  _createClass(LoginButton, [{
50906    key: 'init',
50907    value: function init() {
50908      var _this = this;
50909
50910      this.handleEvents();
50911      this.toggleLoggedSections();
50912      this.closeLoginModal();
50913
50914      $(window).resize(function () {
50915        if (Utils.getWindowSize().width < 950) _this.closeLoginModal();
50916      });
50917    }
50918  }, {
50919    key: 'toggleLoggedSections',
50920    value: function toggleLoggedSections() {
50921      var passenger = SessionStorage.get('passenger');
50922
50923      if (!passenger) {
50924        this.loggedInSection.hide();
50925        this.loggedOutSection.show();
50926        return;
50927      }
50928
50929      this.loggedInSection.show();
50930      $(this.loggedInSection).removeClass('d-none');
50931      this.loggedOutSection.hide();
50932      this.passenger.text(Utils.getFirstName(passenger._name));
50933    }
50934  }, {
50935    key: 'closeLoginModal',
50936    value: function closeLoginModal() {
50937      this.closeButton.removeClass('active');
50938      this.modal.removeClass('active');
50939      this.loginButton.removeClass('active');
50940      this.overlay.removeClass('active');
50941      var body = $("body");
50942      $('[data-js="open-request-password"]').focus();
50943      body.css('width', '');
50944      body.css('position', '');
50945      body.css('top', '');
50946      $(window).scrollTop(this.scrollPosition);
50947    }
50948  }, {
50949    key: 'toggleLoginModal',
50950    value: function toggleLoginModal() {
50951      this.closeButton.toggleClass('active');
50952      this.modal.toggleClass('active');
50953      this.overlay.toggleClass('active');
50954      this.loginButton.toggleClass('active');
50955      var body = $("body");
50956      var width = Utils.getWindowSize().width;
50957      if (this.modal.is('.active')) {
50958        this.scrollPosition = $(window).scrollTop();
50959        body.css('width', width);
50960        body.css('position', 'fixed');
50961        body.css('top', -this.scrollPosition);
50962        this.loginInput.focus();
50963      } else {
50964        body.css('width', '');
50965        body.css('position', '');
50966        body.css('top', '');
50967        $(window).scrollTop(this.scrollPosition);
50968      }
50969    }
50970  }, {
50971    key: 'toggleUserMenu',
50972    value: function toggleUserMenu() {
50973      this.userMenu.toggleClass('active');
50974      this.loggedButton.toggleClass('active');
50975      this.userMenuOverlay.toggleClass('active');
50976    }
50977  }, {
50978    key: 'logout',
50979    value: function logout() {
50980      SessionStorage.remove('passenger');
50981      SessionStorage.remove('cart');
50982      localStorage.setItem("logged", false);
50983      window.location.href = $('#homePagePath').val();
50984    }
50985  }, {
50986    key: 'handleEvents',
50987    value: function handleEvents() {
50988      var _this2 = this;
50989
50990      this.closeButton.on('click', function () {
50991        return _this2.closeLoginModal();
50992      });
50993      this.overlay.on('click', function () {
50994        return _this2.closeLoginModal();
50995      });
50996      this.loginButton.on('click', function () {
50997        return _this2.toggleLoginModal();
50998      });
50999      $('[data-js="logged-out-section"]').children().on('focusout', function (e) {
51000        var $target = $(e.relatedTarget);
51001        if ($target.closest('[data-js="logged-out-section"]').length == 0 && $target.closest('.password-recovery-container').length == 0 && $target.length > 0) {
51002          _this2.closeButton.click();
51003        }
51004      });
51005      this.loggedButton.on('click', function () {
51006        return _this2.toggleUserMenu();
51007      });
51008      this.loggedButton.on('focus', function () {
51009        return CartButton.hideModal();
51010      });
51011      this.userMenuOverlay.on('click', function () {
51012        return _this2.toggleUserMenu();
51013      });
51014      this.userMenu.find('li:last').on('focusout', function () {
51015        return _this2.toggleUserMenu();
51016      });
51017      this.logoutButton.on('click', function () {
51018        return _this2.logout();
51019      });
51020    }
51021  }]);
51022
51023  return LoginButton;
51024}();
51025'use strict';
51026
51027var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
51028
51029function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
51030
51031/**
51032 *
51033 * LOGIN BUTTON
51034 *
51035 * BEGIN
51036 */
51037
51038var LoginButtonHeader = function () {
51039  function LoginButtonHeader($) {
51040    _classCallCheck(this, LoginButtonHeader);
51041
51042    this.loginButton = $('[data-js="header-login-button"]');
51043    this.closeButton = $('[data-js="header-login-close-button"]');
51044    this.modal = $('[data-js="header-login-modal"]');
51045    this.overlay = $('[data-js="header-login-modal-overlay"]');
51046    this.loginInput = $('[data-js="input-login"]');
51047    this.loggedInSection = $('[data-js="logged-in-section"]');
51048    this.loggedOutSection = $('[data-js="logged-out-section"]');
51049    this.passenger = $('[data-js="user-name"]');
51050    this.loggedButton = $('[data-js="logged-button"]');
51051    this.userMenu = $('[data-js="user-menu"]');
51052    this.userMenuOverlay = $('[data-js="user-menu-overlay"]');
51053    this.logoutButton = $('[data-js="user-menu-logout"]');
51054    this.userName = $('[data-js="name-account"]');
51055    new MenuMyData($);
51056    this.init();
51057  }
51058
51059  _createClass(LoginButtonHeader, [{
51060    key: 'init',
51061    value: function init() {
51062      var _this = this;
51063
51064      this.handleEvents();
51065      this.toggleLoggedSections();
51066      this.changeSizeWindow();
51067      this.listenMenu();
51068
51069      $(window).resize(function () {
51070        if (Utils.getWindowSize().width < 950) _this.closeLoginModal();
51071      });
51072    }
51073  }, {
51074    key: 'toggleLoggedSections',
51075    value: function toggleLoggedSections() {
51076      var passenger = SessionStorage.get('passenger');
51077
51078      if (!passenger) {
51079        this.loggedInSection.hide();
51080        this.loggedOutSection.show();
51081        return;
51082      }
51083
51084      this.userName.text(passenger._name);
51085      this.loggedInSection.show();
51086      $(this.loggedInSection).removeClass('d-none');
51087      this.loggedOutSection.hide();
51088      this.passenger.text(Utils.getFirstName(passenger._name));
51089    }
51090  }, {
51091    key: 'closeLoginModal',
51092    value: function closeLoginModal() {
51093      this.closeButton.removeClass('active');
51094      this.modal.removeClass('active');
51095      this.loginButton.removeClass('active');
51096      this.overlay.removeClass('active');
51097      var body = $("body");
51098      $('[data-js="open-request-password"]').focus();
51099      body.css('width', '');
51100      body.css('position', '');
51101      body.css('top', '');
51102      $(window).scrollTop(this.scrollPosition);
51103    }
51104  }, {
51105    key: 'openLoginModal',
51106    value: function openLoginModal() {
51107      this.closeButton.addClass('active');
51108      this.modal.addClass('active');
51109      this.overlay.addClass('active');
51110      this.loginButton.addClass('active');
51111      var body = $("body");
51112      var width = Utils.getWindowSize().width;
51113      if (this.modal.is('.active')) {
51114        this.scrollPosition = $(window).scrollTop();
51115        body.css('width', width);
51116        body.css('position', 'relative');
51117        body.css('top', '0');
51118        body.css('overflow-y', 'hidden');
51119        this.loginInput.focus();
51120      } else {
51121        body.css('width', '');
51122        body.css('position', '');
51123        body.css('top', '');
51124        $(window).scrollTop(this.scrollPosition);
51125      }
51126    }
51127  }, {
51128    key: 'openUserMenu',
51129    value: function openUserMenu() {
51130      this.userMenu.addClass('active');
51131      this.loggedButton.addClass('active');
51132      this.userMenuOverlay.addClass('active');
51133    }
51134  }, {
51135    key: 'closeUserMenu',
51136    value: function closeUserMenu() {
51137      this.userMenu.removeClass('active');
51138      this.loggedButton.removeClass('active');
51139      this.userMenuOverlay.removeClass('active');
51140    }
51141  }, {
51142    key: 'logout',
51143    value: function logout() {
51144      SessionStorage.remove('passenger');
51145      SessionStorage.remove('cart');
51146      window.location.href = $('#homePagePath').val();
51147    }
51148  }, {
51149    key: 'handleEvents',
51150    value: function handleEvents() {
51151      var _this2 = this;
51152
51153      this.closeButton.on('click', function () {
51154        return _this2.closeLoginModal();
51155      });
51156      this.loginButton.on('click', function () {
51157        return _this2.openLoginModal();
51158      });
51159      this.overlay.on('click', function () {
51160        return _this2.closeLoginModal();
51161      });
51162      $('[data-js="logged-out-section"]').children().on('focusout', function (e) {
51163        var $target = $(e.relatedTarget);
51164        if ($target.closest('[data-js="logged-out-section"]').length == 0 && $target.closest('.password-recovery-container').length == 0 && $target.length > 0) {
51165          _this2.closeButton.click();
51166        }
51167      });
51168      this.loggedButton.on('click', function () {
51169        return _this2.openUserMenu();
51170      });
51171      this.loggedButton.on('focus', function () {
51172        return CartButton.hideModal();
51173      });
51174      this.userMenuOverlay.on('click', function () {
51175        return _this2.closeUserMenu();
51176      });
51177      this.userMenu.find('li:last').on('focusout', function () {
51178        return _this2.closeUserMenu();
51179      });
51180      this.logoutButton.on('click', function () {
51181        return _this2.logout();
51182      });
51183    }
51184  }, {
51185    key: 'changeSizeWindow',
51186    value: function changeSizeWindow() {
51187      var _this3 = this;
51188
51189      var width = Utils.getWindowSize().width;
51190
51191      $(window).resize(function () {
51192        if (width < 992) {
51193          $('body').css('overflow-y', 'auto');
51194          _this3.closeLoginModal();
51195        }
51196      });
51197    }
51198  }, {
51199    key: 'listenMenu',
51200    value: function listenMenu() {
51201      $('[data-js="my-perfil"]').on('click', function (e) {
51202        if (Utils.isMobile()) {
51203          $('[data-js="menu-user-mobile"]').addClass('active');
51204          Utils.removeBodyOverFlow();
51205        } else {
51206          $(location).attr('href', 'edit-data.html');
51207        }
51208      });
51209
51210      $('[data-js="close-menu-user"]').on('click', function () {
51211        $('[data-js="menu-user-mobile"]').removeClass('active');
51212        Utils.addBodyOverFlow();
51213      });
51214
51215      $('.submenu-link-item').on('click', function (e) {
51216        if (Utils.isMobile() && $(e.target).attr('data-pagetype') === 'edit-profile-page') {
51217          e.preventDefault();
51218          $('[data-js="menu-user-mobile"]').addClass('active');
51219          Utils.removeBodyOverFlow();
51220        }
51221      });
51222    }
51223  }]);
51224
51225  return LoginButtonHeader;
51226}();
51227'use strict';
51228
51229(function () {
51230  $('[data-js="logo"]').click(function () {
51231    $(location).attr('href', $(this).attr('data-url'));
51232  });
51233})();
51234'use strict';
51235
51236(function ($) {
51237  var mainPassenger = SessionStorage.get('passenger');
51238  var passengerName = $('[data-js="passenger-name"]');
51239  var passengerEmail = $('[data-js="passenger-email"]');
51240  if (mainPassenger) {
51241    passengerName.text(mainPassenger._name.toUpperCase());
51242    passengerEmail.text(mainPassenger._email);
51243  }
51244})(jQuery);
51245'use strict';
51246
51247var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
51248
51249function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
51250
51251var OfferDetailsController = function () {
51252  function OfferDetailsController($) {
51253    _classCallCheck(this, OfferDetailsController);
51254
51255    this.offerTariff = $('[data-js="offer-tariff-detail"]');
51256    this.offerTax = $('[data-js="offer-tax-detail"]');
51257    this.offerTotal = $('[data-js="offer-total-detail"]');
51258    this.offerComission = $('[data-js="offer-comission-detail"]');
51259  }
51260
51261  _createClass(OfferDetailsController, [{
51262    key: 'getOfferWithConnection',
51263    value: function getOfferWithConnection(offer) {
51264      var _this = this;
51265
51266      var offerDetailsConnectionFirstPart = void 0,
51267        offerDetailsConnectionSecondPart = void 0;
51268
51269      var originIdConnectionFirstPart = offer.company.origin.id;
51270      var destinationIdConnectionFirstPart = offer._connection._location._id;
51271      var serviceIdConnectionFirstPart = offer.service;
51272      var departureDateConnectionFirstPart = DateFormatter.extractDate(offer.company._departureDate);
51273
51274      var bodyFirstPart = {
51275        origin: originIdConnectionFirstPart,
51276        destination: destinationIdConnectionFirstPart,
51277        service: serviceIdConnectionFirstPart,
51278        departureDate: departureDateConnectionFirstPart
51279      };
51280
51281      var originIdConnectionSecondPart = offer._connection._location._id;
51282      var destinationIdConnectionSecondPart = offer.company.destination.id;
51283      var serviceIdConnectionSecondPart = offer._connection.service;
51284      var departureDateConnectionSecondPart = DateFormatter.extractDate(offer.company._departureDate);
51285
51286      var bodySecondPart = {
51287        origin: originIdConnectionSecondPart,
51288        destination: destinationIdConnectionSecondPart,
51289        service: serviceIdConnectionSecondPart,
51290        departureDate: departureDateConnectionSecondPart
51291      };
51292
51293      try {
51294        Promise.all([this.getServiceCategory(bodyFirstPart), this.getServiceCategory(bodySecondPart)]).then(function (promiseValues) {
51295          offerDetailsConnectionFirstPart = promiseValues[0];
51296          offerDetailsConnectionSecondPart = promiseValues[1];
51297
51298          _this.loadOfferDetailsWithConnection(offer, offerDetailsConnectionFirstPart, offerDetailsConnectionSecondPart);
51299        }).catch(function (err) {
51300          console.error(err);
51301        });
51302      } catch (ex) {
51303        console.log(ex);
51304      }
51305    }
51306  }, {
51307    key: 'getOffer',
51308    value: function getOffer(offer) {
51309      var _this2 = this;
51310
51311      var originId = offer.company.origin.id;
51312      var destinationId = offer.company.destination.id;
51313      var serviceId = offer.service;
51314      var departureDate = DateFormatter.extractDate(offer.company._departureDate);
51315
51316      var body = {
51317        origin: originId,
51318        destination: destinationId,
51319        service: serviceId,
51320        departureDate: departureDate
51321      };
51322
51323      this.getServiceCategory(body).then(function (offerDetails) {
51324        _this2.loadOfferDetails(offerDetails);
51325      }).catch(function (err) {
51326        console.error(err);
51327      });
51328    }
51329  }, {
51330    key: 'getOfferDetails',
51331    value: function getOfferDetails(offer) {
51332      if (offer._connection._service) {
51333        this.getOfferWithConnection(offer);
51334        return;
51335      }
51336
51337      this.getOffer(offer);
51338    }
51339  }, {
51340    key: 'getServiceCategory',
51341    value: function getServiceCategory(body) {
51342      return new Promise(function (resolve, reject) {
51343        HttpService.post('getServiceCategory', body).then(function (data) {
51344          resolve(data.result);
51345        }).catch(function (err) {
51346          console.error(err);
51347          reject(err);
51348        });
51349      });
51350    }
51351  }, {
51352    key: 'loadOfferDetailsWithConnection',
51353    value: function loadOfferDetailsWithConnection(offer, offerDetailsConnectionFirstPart, offerDetailsConnectionSecondPart) {
51354      var firstPart = this.getOfferDetailsPrices(offerDetailsConnectionFirstPart);
51355      var secondPart = this.getOfferDetailsPrices(offerDetailsConnectionSecondPart);
51356      var fullPrice = offer._price;
51357      var totalTax = firstPart.totalTax + secondPart.totalTax;
51358      var tax = fullPrice - totalTax;
51359
51360      this.offerTariff.text('R$ ' + Utils.formatPrice(tax));
51361      this.offerTax.text('R$ ' + Utils.formatPrice(totalTax));
51362      this.offerTotal.text('R$ ' + Utils.formatPrice(fullPrice));
51363    }
51364  }, {
51365    key: 'loadOfferDetails',
51366    value: function loadOfferDetails(offerDetails) {
51367      var detailsPrice = this.getOfferDetailsPrices(offerDetails);
51368      var tax = detailsPrice.tax;
51369      var totalTax = detailsPrice.totalTax;
51370      var fullPrice = detailsPrice.fullPrice;
51371      /* var isGiroCommission = $('[data-js="giro-comission-details"]').data('value');
51372       var giroCommissionText = $('[data-js="giro-comission-text"]').val();
51373 
51374       if(isGiroCommission) {
51375         var $el = $('[data-js="tootltip-btn-dispo"]')
51376         $el.attr('title', i18n('msg_faq_tax_service'));
51377         $el.tooltip();
51378         this.offerComission.parent().removeClass('d-none');
51379         this.offerComission.text(giroCommissionText);
51380       } */
51381      this.offerTariff.text('R$ ' + Utils.formatPrice(tax));
51382      this.offerTax.text('R$ ' + Utils.formatPrice(totalTax));
51383      this.offerTotal.text('R$ ' + Utils.formatPrice(fullPrice));
51384    }
51385  }, {
51386    key: 'getOfferDetailsPrices',
51387    value: function getOfferDetailsPrices(offerDetails) {
51388      var _offerDetails$ = offerDetails[0],
51389        toll = _offerDetails$.toll,
51390        tax = _offerDetails$.tax,
51391        fullPrice = _offerDetails$.fullPrice,
51392        others = _offerDetails$.others,
51393        insurance = _offerDetails$.insurance,
51394        boardingFee = _offerDetails$.boardingFee;
51395
51396      var totalTax = others + toll + insurance + boardingFee;
51397
51398      return {
51399        tax: tax,
51400        totalTax: totalTax,
51401        fullPrice: fullPrice
51402      };
51403    }
51404  }]);
51405
51406  return OfferDetailsController;
51407}();
51408'use strict';
51409
51410var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
51411
51412function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
51413
51414var RegistrationCampaignController = function () {
51415  function RegistrationCampaignController() {
51416    _classCallCheck(this, RegistrationCampaignController);
51417
51418    this.init();
51419  }
51420
51421  _createClass(RegistrationCampaignController, [{
51422    key: 'init',
51423    value: function init() {
51424      this.getUrl();
51425    }
51426  }, {
51427    key: 'getUrl',
51428    value: function getUrl() {
51429      var utm_campaign = this.getPromotionParam('utm_campaign');
51430
51431      utm_campaign ? SessionStorage.set('utm_campaign', utm_campaign) : '';
51432    }
51433  }, {
51434    key: 'getPromotionParam',
51435    value: function getPromotionParam(sParam) {
51436      var sPageURL = window.location.search.substring(1);
51437
51438      if (sPageURL === "") return;
51439
51440      var sURLVariables = sPageURL ? sPageURL.split('&') : SessionStorage.get('deepLinkParameters');
51441      for (var i = 0; i < sURLVariables.length; i++) {
51442        var sParameterName = sURLVariables[i].split("=");
51443        if (sParameterName[0] == sParam) return sParameterName[1];
51444      }
51445    }
51446  }]);
51447
51448  return RegistrationCampaignController;
51449}();
51450'use strict';
51451
51452var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
51453
51454function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
51455
51456var ResumeCancelTripController = function () {
51457  function ResumeCancelTripController() {
51458    _classCallCheck(this, ResumeCancelTripController);
51459
51460    this.tripToCancel = SessionStorage.get('tripToCancel');
51461    this.totalPriceBottomCart = $('[data-js="price-in-bottom-cart"]');
51462    this.priceCart = $('[data-js="price-cart"]');
51463    this.btnRefund = $('.refund-btn');
51464    this.init();
51465  }
51466
51467  _createClass(ResumeCancelTripController, [{
51468    key: 'init',
51469    value: function init() {
51470      this.loadResumeCancelTrip();
51471    }
51472  }, {
51473    key: 'loadCancelTripDestination',
51474    value: function loadCancelTripDestination(departTrip, departTripConnection) {
51475      var $departureSection = $('[data-js="departure-section"]');
51476      var _departTrip$ = departTrip[0],
51477        originDescription = _departTrip$.originDescription,
51478        departureDate = _departTrip$.departureDate;
51479
51480      var _ref = departTripConnection ? departTripConnection[0] : departTrip[0],
51481        destinationDescription = _ref.destinationDescription,
51482        arivalDate = _ref.arivalDate;
51483
51484      var classTypeDepart = departTrip[0].class;
51485      var totalPassengers = departTrip.length;
51486      var validateDepartureDate = DateFormatter.getValidDateFormat(departureDate);
51487      var operatingCompany = departTrip[0].company;
51488      var operatingCompanyConnection = departTripConnection && departTripConnection.length > 0 ? ' / ' + departTripConnection[0].company : '';
51489
51490      $departureSection.find('[data-js="origin-label"]').text(originDescription);
51491      $departureSection.find('[data-js="destination-label"]').text(destinationDescription);
51492      $departureSection.find('[data-js="departure-day-label"]').text(DateFormatter.getDaysArray()[validateDepartureDate.getDay()]);
51493      $departureSection.find('[data-js="departure-date-label"]').text(Utils.isMobile() ? DateFormatter.formatDate(departureDate).substr(0, 5) : DateFormatter.getFullDate(departureDate).substr(0, 9));
51494      $departureSection.find('[data-js="depart-time-label"]').text(DateFormatter.extractHour(departureDate));
51495      $departureSection.find('[data-js="arriving-time-label"]').text(DateFormatter.extractHour(arivalDate));
51496      $departureSection.find('[data-js="chosen-class"]').text(classTypeDepart);
51497      $departureSection.find('[data-js="operating-company-name"]').text(operatingCompany);
51498      $departureSection.find('[data-js="operating-company-name-connection"]').text(operatingCompanyConnection);
51499      $departureSection.find('[data-js="num-pass-total"]').text(totalPassengers + ' ' + (totalPassengers > 1 ? 'pessoas' : 'pessoa'));
51500      new Collapse($);
51501    }
51502  }, {
51503    key: 'loadCancelTripReturn',
51504    value: function loadCancelTripReturn(returnTrip, returnTripConnection) {
51505      var $returnSection = $('[data-js="return-section"]');
51506      var originDescriptionReturn = returnTrip[0].originDescription;
51507      var destinationDescriptionReturn = returnTripConnection ? returnTripConnection[0].destinationDescription : returnTrip[0].destinationDescription;
51508      var departureDateReturn = returnTrip[0].departureDate;
51509      var arivalDateReturn = returnTripConnection ? returnTripConnection[0].arivalDate : returnTrip[0].arivalDate;
51510      var validateReturnDate = DateFormatter.getValidDateFormat(departureDateReturn);
51511      var classTypeReturn = returnTrip[0].class;
51512      var totalPassengersReturn = returnTrip.length;
51513      var operatingCompany = returnTrip[0].company;
51514      var operatingCompanyConnection = returnTripConnection && returnTripConnection.length > 0 ? ' / ' + returnTripConnection[0].company : '';
51515
51516      $returnSection.find('[data-js="origin-label"]').text(originDescriptionReturn);
51517      $returnSection.find('[data-js="destination-label"]').text(destinationDescriptionReturn);
51518      $returnSection.find('[data-js="return-day-label"]').text(DateFormatter.getDaysArray()[validateReturnDate.getDay()]);
51519      $returnSection.find('[data-js="return-date-label"]').text(Utils.isMobile() ? DateFormatter.formatDate(departureDateReturn).substr(0, 5) : DateFormatter.getFullDate(departureDateReturn).substr(0, 9));
51520      $returnSection.find('[data-js="depart-time-label"]').text(DateFormatter.extractHour(departureDateReturn));
51521      $returnSection.find('[data-js="arriving-time-label"]').text(DateFormatter.extractHour(arivalDateReturn));
51522      $returnSection.find('[data-js="chosen-class"]').text(classTypeReturn);
51523      $returnSection.find('[data-js="operating-company-name"]').text(operatingCompany);
51524      $returnSection.find('[data-js="operating-company-name-connection"]').text(operatingCompanyConnection);
51525      $returnSection.find('[data-js="num-pass-total"]').text(totalPassengersReturn + ' ' + (totalPassengersReturn > 1 ? 'pessoas' : 'pessoa'));
51526      new Collapse($);
51527    }
51528  }, {
51529    key: 'loadResumeCancelTrip',
51530    value: function loadResumeCancelTrip() {
51531      var departTrip = this.tripToCancel[0];
51532      var departTripConnection = this.tripToCancel[1] ? this.tripToCancel[1] : null;
51533      var returnTrip = this.tripToCancel[2];
51534      var returnTripConnection = this.tripToCancel[3] ? this.tripToCancel[3] : null;
51535
51536      this.btnRefund.removeClass('d-none');
51537
51538      this.loadCancelTripDestination(departTrip, departTripConnection);
51539      this.setTotalResumeCancelTrip();
51540      if (returnTrip) {
51541        this.loadCancelTripReturn(returnTrip, returnTripConnection);
51542      } else {
51543        $('[data-js="return-section"]').hide();
51544      }
51545    }
51546  }, {
51547    key: 'setTotalResumeCancelTrip',
51548    value: function setTotalResumeCancelTrip() {
51549      var total = 0;
51550
51551      this.tripToCancel.forEach(function (el, i) {
51552        if (el) {
51553          el.forEach(function (passenger) {
51554
51555            total += passenger.amount;
51556          });
51557        }
51558      });
51559
51560      $('.summary-item').hide();
51561      $('[data-js="discount"]').hide();
51562      this.priceCart.text(Utils.formatPrice(total));
51563      this.totalPriceBottomCart.text("R$ " + Utils.formatPrice(total));
51564    }
51565  }, {
51566    key: 'removePriceResumeCancel',
51567    value: function removePriceResumeCancel() {
51568      $('[data-js="cart-passenger-list"]').empty();
51569      $('[data-js="ticket-departure"]').add('[data-js="ticket-return"]').hide();
51570      $('.summary-item').hide();
51571    }
51572  }, {
51573    key: 'updateResumeCancelTrip',
51574    value: function updateResumeCancelTrip(listPassenger, convenienceFee) {
51575      var itemList = '';
51576      var $departureSectionList = $('[data-js="departure-section"]').find('[data-js="cart-passenger-list"]');
51577      var $returnSectionList = $('[data-js="return-section"]').find('[data-js="cart-passenger-list"]');
51578      var listGoing = listPassenger.going;
51579      var listReturn = listPassenger.return;
51580      var listGoingLength = listGoing.length;
51581      var listReturnLength = listReturn.length;
51582      var totalLiveloPoints = 0;
51583      var totalTicketPriceCancel = 0;
51584      var totalConvenienceFee = 0;
51585      this.removePriceResumeCancel();
51586
51587      if (listGoing.length) {
51588        $('[data-js="departure-section"]').find('[data-js="num-pass-total"]').text(listGoingLength + ' ' + (listGoingLength > 1 ? 'pessoas' : 'pessoa'));
51589
51590        listGoing.forEach(function (el, i) {
51591          itemList = '\n          <li>\n            <div class="container-cart-passenger">
51591\n              <span class="name">' + el.name + '</span>\n                <span class="square-seat">\n                  ' + (el.type != 'CHILD' ? '<p class="icon-seat-number"> ' + el.seat + ' </p>' : '') + '\n                </span>\n              </span>\n            </div>\n          </li>\n\n          ' + (el.seatConnection ? '<li>\n              <div class="container-cart-passenger">\n                <span class="name">' + (el.name + ' - Conexão') + '</span>\n                  <span class="square-seat">\n                    <p class="icon-seat-number"> ' + el.seatConnection + ' </p>\n                  </span>\n                </span>\n              </div>\n            </li>' : '') + '\n        ';
51592
51593          if (el.liveloPoints) {
51594            $('.points-livelo').removeClass('d-none');
51595
51596            totalLiveloPoints += el.liveloPoints + (el.liveloPointsConnection ? el.liveloPointsConnection : 0);
51597          }
51598
51599          totalTicketPriceCancel += +el.price + (el.priceConnection ? +el.priceConnection : 0) + (el.convenienceFee ? el.convenienceFee : 0) + (el.convenienceFeeConnection ? el.convenienceFeeConnection : 0);
51600          totalConvenienceFee += +el.convenienceFee;
51601          $('.cart-passenger-list').removeClass('active');
51602          $departureSectionList.append(itemList);
51603        });
51604      }
51605
51606      if (listReturn.length) {
51607        $('[data-js="return-section"]').find('[data-js="num-pass-total"]').text(listReturnLength + ' ' + (listReturnLength > 1 ? 'pessoas' : 'pessoa'));
51608
51609        listReturn.forEach(function (el, i) {
51610          itemList = '\n          <li>\n            <div class="container-cart-passenger">\n              <span class="name">' + el.name + '</span>\n                <span class="square-seat">\n                  ' + (el.seat ? '<p class="icon-seat-number"> ' + el.seat + ' </p>' : '') + '\n                </span>\n              </span>\n            </div>\n          </li>\n\n          ' + (el.seatConnection ? '<li>\n              <div class="container-cart-passenger">\n                <span class="name">' + (el.name + ' - Conexão') + '</span>\n                  <span class="square-seat">\n                    <p class="icon-seat-number"> ' + el.seatConnection + ' </p>\n                  </span>\n                </span>\n              </div>\n            </li>' : '') + '\n        ';
51611
51612          if (el.liveloPointsReturn) {
51613            $('.points-livelo').removeClass('d-none');
51614
51615            totalLiveloPoints += el.liveloPointsReturn + (el.liveloPointsReturnConnection ? el.liveloPointsReturnConnection : 0);
51616          }
51617
51618          totalTicketPriceCancel += +el.price + (el.priceConnection ? +el.priceConnection : 0) + (el.convenienceFeeReturn ? el.convenienceFeeReturn : 0) + (el.convenienceFeeReturnConnection ? el.convenienceFeeReturnConnection : 0);
51619          totalConvenienceFee += +el.convenienceFeeReturn ? el.convenienceFeeReturn : 0;
51620          $('.cart-passenger-list').removeClass('active');
51621          $returnSectionList.append(itemList);
51622        });
51623      }
51624
51625      $('[data-js="refund-livelo-total"]').text(totalLiveloPoints);
51626      $('[data-js="tax-convenience"]').text('R$ ' + Utils.formatPrice(totalConvenienceFee));
51627    }
51628  }]);
51629
51630  return ResumeCancelTripController;
51631}();
51632'use strict';
51633
51634var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
51635
51636function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
51637
51638var ResumeRepricingTripController = function () {
51639  function ResumeRepricingTripController() {
51640    _classCallCheck(this, ResumeRepricingTripController);
51641
51642    this.tripToRepricing = SessionStorage.get('tripToRepricing');
51643    this.btnRefund = $('[data-js="cart-btn"]');
51644    this.btnRefund.removeClass('cart-btn');
51645    this.btnRefund.addClass('refund-btn');
51646    this.btnRefund.children('span').removeClass('jca-ico-cart');
51647    this.btnRefund.children('span').addClass('jca-ico-refund');
51648
51649    this.init();
51650  }
51651
51652  _createClass(ResumeRepricingTripController, [{
51653    key: 'init',
51654    value: function init() {
51655      this.loadResumeRepricingTrip();
51656      this.updateResumeRepricingTrip(this.tripToRepricing);
51657    }
51658  }, {
51659    key: 'loadRepricingTripDestination',
51660    value: function loadRepricingTripDestination(departTrip, departTripConnection) {
51661      var $departureSection = $('[data-js="departure-section"]');
51662      var _departTrip$ = departTrip[0],
51663        originDescription = _departTrip$.originDescription,
51664        departureDate = _departTrip$.departureDate;
51665
51666      var _ref = departTripConnection && departTripConnection.lenght > 0 ? departTripConnection[0] : departTrip[0],
51667        destinationDescription = _ref.destinationDescription,
51668        arivalDate = _ref.arivalDate;
51669
51670      var classTypeDepart = departTrip[0].class;
51671      var totalPassengers = departTrip.length;
51672      var validateDepartureDate = DateFormatter.getValidDateFormat(departureDate);
51673
51674      $departureSection.find('[data-js="origin-label"]').text(originDescription);
51675      $departureSection.find('[data-js="destination-label"]').text(destinationDescription);
51676      $departureSection.find('[data-js="departure-day-label"]').text(DateFormatter.getDaysArray()[validateDepartureDate.getDay()]);
51677      $departureSection.find('[data-js="departure-date-label"]').text(Utils.isMobile() ? DateFormatter.formatDate(departureDate).substr(0, 5) : DateFormatter.getFullDate(departureDate).substr(0, 9));
51678      $departureSection.find('[data-js="depart-time-label"]').text(DateFormatter.extractHour(departureDate));
51679      $departureSection.find('[data-js="arriving-time-label"]').text(DateFormatter.extractHour(arivalDate));
51680      $departureSection.find('[data-js="chosen-class"]').text(classTypeDepart);
51681      $departureSection.find('[data-js="num-pass-total"]').text(totalPassengers + ' ' + (totalPassengers > 1 ? 'pessoas' : 'pessoa'));
51682      new Collapse($);
51683    }
51684  }, {
51685    key: 'loadRepricingTripReturn',
51686    value: function loadRepricingTripReturn(returnTrip, returnTripConnection) {
51687      var $returnSection = $('[data-js="return-section"]');
51688      var originDescriptionReturn = returnTrip[0].originDescription;
51689      var destinationDescriptionReturn = returnTripConnection && returnTripConnection.lenght > 0 ? returnTripConnection[0].destinationDescription : returnTrip[0].destinationDescription;
51690      var departureDateReturn = returnTrip[0].departureDate;
51691      var arivalDateReturn = returnTripConnection && returnTripConnection.lenght > 0 ? returnTripConnection[0].arivalDate : returnTrip[0].arivalDate;
51692      var validateReturnDate = DateFormatter.getValidDateFormat(departureDateReturn);
51693      var classTypeReturn = returnTrip[0].class;
51694      var totalPassengersReturn = returnTrip.length;
51695
51696      $returnSection.find('[data-js="origin-label"]').text(originDescriptionReturn);
51697      $returnSection.find('[data-js="destination-label"]').text(destinationDescriptionReturn);
51698      $returnSection.find('[data-js="return-day-label"]').text(DateFormatter.getDaysArray()[validateReturnDate.getDay()]);
51699      $returnSection.find('[data-js="return-date-label"]').text(Utils.isMobile() ? DateFormatter.formatDate(departureDateReturn).substr(0, 5) : DateFormatter.getFullDate(departureDateReturn).substr(0, 9));
51700      $returnSection.find('[data-js="depart-time-label"]').text(DateFormatter.extractHour(departureDateReturn));
51701      $returnSection.find('[data-js="arriving-time-label"]').text(DateFormatter.extractHour(arivalDateReturn));
51702      $returnSection.find('[data-js="chosen-class"]').text(classTypeReturn);
51703      $returnSection.find('[data-js="num-pass-total"]').text(totalPassengersReturn + ' ' + (totalPassengersReturn > 1 ? 'pessoas' : 'pessoa'));
51704      new Collapse($);
51705    }
51706  }, {
51707    key: 'loadResumeRepricingTrip',
51708    value: function loadResumeRepricingTrip() {
51709      var departTrip = this.tripToRepricing[0];
51710      var departTripConnection = this.tripToRepricing[1] ? this.tripToRepricing[1] : null;
51711      var returnTrip = this.tripToRepricing[2];
51712      var returnTripConnection = this.tripToRepricing[3] ? this.tripToRepricing[3] : null;
51713
51714      this.btnRefund.removeClass('d-none');
51715      // $('.cart-details-header .title').text('Dados da viagem original');
51716
51717      this.loadRepricingTripDestination(departTrip, departTripConnection);
51718      this.setTotalResumerRepricingTrip();
51719      if (returnTrip && returnTrip.length > 0) {
51720        this.loadRepricingTripReturn(returnTrip, returnTripConnection);
51721      } else {
51722        $('[data-js="return-section"]').hide();
51723      }
51724    }
51725  }, {
51726    key: 'setTotalResumerRepricingTrip',
51727    value: function setTotalResumerRepricingTrip() {
51728      var total = 0;
51729
51730      this.tripToRepricing.forEach(function (el, i) {
51731        if (el) {
51732          el.forEach(function (passenger) {
51733
51734            total += passenger.amount;
51735          });
51736        }
51737      });
51738
51739      $('.summary-item').hide();
51740      $('[data-js="discount"]').hide();
51741      $('[data-js="price-cart"]').text(Utils.formatPrice(total));
51742    }
51743  }, {
51744    key: 'removePriceResumeCancel',
51745    value: function removePriceResumeCancel() {
51746      $('[data-js="cart-passenger-list"]').empty();
51747      $('[data-js="ticket-departure"]').add('[data-js="ticket-return"]').hide();
51748      $('.summary-item').hide();
51749    }
51750  }, {
51751    key: 'updateResumeRepricingTrip',
51752    value: function updateResumeRepricingTrip(listPassenger) {
51753      // $('.cart-details-header .title').text('Resumo');
51754      var itemList = '';
51755      var $departureSectionList = $('[data-js="departure-section"]').find('[data-js="cart-passenger-list"]');
51756      var $returnSectionList = $('[data-js="return-section"]').find('[data-js="cart-passenger-list"]');
51757      var listGoing = listPassenger[0];
51758      var listReturn = listPassenger[2];
51759      var listGoingLength = listGoing.length;
51760      var listReturnLength = listReturn ? listReturn.length : '';
51761      var totalTicketPriceCancel = 0;
51762
51763      if (listGoingLength) {
51764        $('[data-js="departure-section"]').find('[data-js="num-pass-total"]').text(listGoingLength + ' ' + (listGoingLength > 1 ? 'pessoas' : 'pessoa'));
51765
51766        listGoing.forEach(function (el, i) {
51767          itemList = '\n          <li>\n            <div class="container-cart-passenger">
51767\n              <span class="name">' + el.passengerName + '</span>\n                <span class="square-seat">\n                  <p class="icon-seat-number"> ' + el.seat + ' </p>\n                </span>\n              </span>\n            </div>\n          </li>\n\n          ' + (el.seatConnection ? '<li>\n              <div class="container-cart-passenger">\n                <span class="name">' + (el.passengerName + ' - Conexão') + '</span>\n                  <span class="square-seat">\n                    <p class="icon-seat-number"> ' + el.seatConnection + ' </p>\n                  </span>\n                </span>\n              </div>\n            </li>' : '') + '\n        ';
51768
51769          $('.cart-passenger-list').removeClass('active');
51770          $departureSectionList.append(itemList);
51771        });
51772      }
51773
51774      if (listReturnLength) {
51775        $('[data-js="return-section"]').find('[data-js="num-pass-total"]').text(listReturnLength + ' ' + (listReturnLength > 1 ? 'pessoas' : 'pessoa'));
51776
51777        listReturn.forEach(function (el, i) {
51778          itemList = '\n          <li>\n            <div class="container-cart-passenger">\n              <span class="name">' + el.passengerName + '</span>\n                <span class="square-seat">\n                  <p class="icon-seat-number"> ' + el.seat + ' </p>\n                </span>\n              </span>\n            </div>\n          </li>\n\n          ' + (el.seatConnection ? '<li>\n              <div class="container-cart-passenger">\n                <span class="name">' + (el.passengerName + ' - Conexão') + '</span>\n                  <span class="square-seat">\n                    <p class="icon-seat-number"> ' + el.seatConnection + ' </p>\n                  </span>\n                </span>\n              </div>\n            </li>' : '') + '\n        ';
51779
51780          $('.cart-passenger-list').removeClass('active');
51781          $returnSectionList.append(itemList);
51782        });
51783      }
51784
51785      $('[data-js="ticket-departure"]').add('[data-js="ticket-return"]').hide();
51786    }
51787  }]);
51788
51789  return ResumeRepricingTripController;
51790}();
51791'use strict';
51792
51793var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
51794
51795function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
51796
51797var ResumeRepricingRevisionController = function () {
51798  function ResumeRepricingRevisionController() {
51799    _classCallCheck(this, ResumeRepricingRevisionController);
51800
51801    this.cart = SessionStorage.get('cart');
51802    this.passengersToRepricing = SessionStorage.get('passengersToRepricing');
51803    this.init();
51804  }
51805
51806  _createClass(ResumeRepricingRevisionController, [{
51807    key: 'init',
51808    value: function init() {
51809      this.loadResumeRepricingTrip();
51810      this.updateResumeCancelTrip(this.passengersToRepricing);
51811    }
51812  }, {
51813    key: 'loadRepricingTripDestination',
51814    value: function loadRepricingTripDestination(departTrip, departTripConnection) {
51815      var $departureSection = $('[data-js="departure-section"]');
51816      var originDescription = departTrip._company._origin._label;
51817      var departureDate = departTrip._company._departureDate;
51818      var destinationDescription = departTripConnection ? departTripConnection._company._destination._label : departTrip._company._destination._label;
51819      var arivalDate = departTripConnection ? departTripConnection._company._arrivingDate : departTrip._company._arrivingDate;
51820      var classTypeDepart = departTrip._classtype._className;
51821      var totalPassengers = this.getPassengersQtt();
51822      var validateDepartureDate = DateFormatter.getValidDateFormat(departureDate);
51823
51824      $departureSection.find('[data-js="origin-label"]').text(originDescription);
51825      $departureSection.find('[data-js="destination-label"]').text(destinationDescription);
51826      $departureSection.find('[data-js="departure-day-label"]').text(DateFormatter.getDaysArray()[validateDepartureDate.getDay()]);
51827      $departureSection.find('[data-js="departure-date-label"]').text(Utils.isMobile() ? DateFormatter.formatDate(departureDate).substr(0, 5) : DateFormatter.getFullDate(departureDate).substr(0, 9));
51828      $departureSection.find('[data-js="depart-time-label"]').text(DateFormatter.extractHour(departureDate));
51829      $departureSection.find('[data-js="arriving-time-label"]').text(DateFormatter.extractHour(arivalDate));
51830      $departureSection.find('[data-js="chosen-class"]').text(classTypeDepart);
51831      $departureSection.find('[data-js="num-pass-total"]').text(totalPassengers + ' ' + (totalPassengers > 1 ? 'pessoas' : 'pessoa'));
51832      new Collapse($);
51833    }
51834  }, {
51835    key: 'getPassengersQtt',
51836    value: function getPassengersQtt() {
51837      var formData = SessionStorage.get('formData');
51838      var passengersQtt = formData.passengers.reduce(function (acc, el) {
51839        return acc += el.quantity;
51840      }, 0);
51841
51842      return passengersQtt;
51843    }
51844  }, {
51845    key: 'loadRepricingTripReturn',
51846    value: function loadRepricingTripReturn(returnTrip, returnTripConnection) {
51847      var $returnSection = $('[data-js="return-section"]');
51848      var originDescriptionReturn = returnTrip._company._origin._label;
51849      var destinationDescriptionReturn = returnTripConnection ? returnTripConnection._company._destination._label : returnTrip._company._destination._label;
51850      var departureDateReturn = returnTrip._company._departureDate;
51851      var arivalDateReturn = returnTripConnection ? returnTripConnection._company._arrivingDate : returnTrip._company._arrivingDate;
51852      var validateReturnDate = DateFormatter.getValidDateFormat(departureDateReturn);
51853      var classTypeReturn = returnTrip._classtype._className;
51854      var totalPassengersReturn = this.getPassengersQtt();
51855
51856      $returnSection.find('[data-js="origin-label"]').text(originDescriptionReturn);
51857      $returnSection.find('[data-js="destination-label"]').text(destinationDescriptionReturn);
51858      $returnSection.find('[data-js="return-day-label"]').text(DateFormatter.getDaysArray()[validateReturnDate.getDay()]);
51859      $returnSection.find('[data-js="return-date-label"]').text(Utils.isMobile() ? DateFormatter.formatDate(departureDateReturn).substr(0, 5) : DateFormatter.getFullDate(departureDateReturn).substr(0, 9));
51860      $returnSection.find('[data-js="depart-time-label"]').text(DateFormatter.extractHour(departureDateReturn));
51861      $returnSection.find('[data-js="arriving-time-label"]').text(DateFormatter.extractHour(arivalDateReturn));
51862      $returnSection.find('[data-js="chosen-class"]').text(classTypeReturn);
51863      $returnSection.find('[data-js="num-pass-total"]').text(totalPassengersReturn + ' ' + (totalPassengersReturn > 1 ? 'pessoas' : 'pessoa'));
51864      new Collapse($);
51865    }
51866  }, {
51867    key: 'loadResumeRepricingTrip',
51868    value: function loadResumeRepricingTrip() {
51869      var departTrip = this.cart._listOffer[0];
51870      var departTripConnection = this.cart._listOffer[1] ? this.cart._listOffer[1] : null;
51871      var returnTrip = this.cart._listOffer[2];
51872      var returnTripConnection = this.cart._listOffer[3] ? this.cart._listOffer[3] : null;
51873
51874      // $('.cart-details-header .title').text('Dados da viagem original');
51875
51876      this.loadRepricingTripDestination(departTrip, departTripConnection);
51877      $('[data-js="discount"]').closest('.summary-item').remove();
51878
51879      if (returnTrip) {
51880        this.loadRepricingTripReturn(returnTrip, returnTripConnection);
51881      } else {
51882        $('[data-js="return-section"]').hide();
51883      }
51884    }
51885  }, {
51886    key: 'removePriceResumeRepricingRevision',
51887    value: function removePriceResumeRepricingRevision() {
51888      $('[data-js="cart-passenger-list"]').empty();
51889      $('[data-js="ticket-departure"]').add('[data-js="ticket-return"]').hide();
51890      $('.summary-item').hide();
51891    }
51892  }, {
51893    key: 'updateResumeCancelTrip',
51894    value: function updateResumeCancelTrip(listPassenger) {
51895      $('.cart-details-header .title').text('Resumo');
51896      var itemList = '';
51897      var $departureSectionList = $('[data-js="departure-section"]').find('[data-js="cart-passenger-list"]');
51898      var $returnSectionList = $('[data-js="return-section"]').find('[data-js="cart-passenger-list"]');
51899      var listToRepricing = listPassenger;
51900      this.removePriceResumeRepricingRevision();
51901
51902      if (listToRepricing.length) {
51903        $('[data-js="departure-section"]').find('[data-js="num-pass-total"]').text(listToRepricing.length + ' ' + (listToRepricing.length > 1 ? 'pessoas' : 'pessoa'));
51904        $('[data-js="return-section"]').find('[data-js="num-pass-total"]').text(listToRepricing.length + ' ' + (listToRepricing.length > 1 ? 'pessoas' : 'pessoa'));
51905
51906        listToRepricing.forEach(function (el, i) {
51907          itemList = '\n          <li>\n            <div class="container-cart-passenger">\n              <span class="name">' + el.name + '</span>\n            </div>\n          </li>\n        ';
51908
51909          $('.cart-passenger-list').removeClass('active');
51910          $returnSectionList.append(itemList);
51911          $departureSectionList.append(itemList);
51912        });
51913      }
51914    }
51915  }]);
51916
51917  return ResumeRepricingRevisionController;
51918}();
51919'use strict';
51920
51921var SelectCustom = function () {
51922  function SelectCustom($) {
51923    var _this = this;
51924
51925    _classCallCheck(this, SelectCustom);
51926
51927    this.init();
51928    /*if the user clicks anywhere outside the select box,
51929    then close all select boxes:*/
51930    $('body').click(function (e) {
51931      if (!$(e.target).closest('.select-custom').length) _this.closeAllSelect();
51932    });
51933  }
51934
51935  _createClass(SelectCustom, [{
51936    key: 'init',
51937    value: function init() {
51938      var _this2 = this;
51939
51940      /*look for any elements with the class "select-custom":*/
51941      var $selectCustom = $(".select-custom");
51942      $selectCustom.each(function (i, el) {
51943        var $el = $(el);
51944        _this2.initSingle($el);
51945      });
51946    }
51947  }, {
51948    key: 'initSingle',
51949    value: function initSingle($component) {
51950      var _this3 = this;
51951
51952      var pseudoSelector = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'selected';
51953
51954      var $selectCustom = void 0,
51955        selElmnt = void 0,
51956        $selectedItem = void 0,
51957        $selectItem = void 0,
51958        $item = void 0,
51959        $angleIconWrapper = void 0,
51960        $iconAngleDown = void 0;
51961      var self = this;
51962
51963      /*look for any elements with the class "select-custom":*/
51964      $selectCustom = $component;
51965      this.resetSelect($selectCustom);
51966
51967      $selectCustom.attr('tabindex', '0');
51968
51969      selElmnt = $selectCustom.find("select").first();
51970      /*for each element, create $selectedItem new DIV that will act as the selected item:*/
51971      $selectedItem = $('<div></div>');
51972      $selectedItem.attr('class', "select-selected");
51973      $selectedItem.append('<span class="select-text"/>');
51974
51975      $iconAngleDown = $("<em/>").addClass("jca-ico-angle-down");
51976      $angleIconWrapper = $('<span/>').addClass('angle-icon').append($iconAngleDown);
51977      $selectedItem.append($angleIconWrapper);
51978
51979      if (selElmnt.is(':disabled')) {
51980        $selectedItem.addClass('disabled');
51981        selElmnt.parent().attr('tabindex', '-1');
51982      }
51983
51984      /* in protocol it works using "option:disabled"  */
51985      var selectedItemContent = selElmnt.find('option:' + pseudoSelector).text();
51986
51987      $selectedItem.find(".select-text").text(selectedItemContent);
51988      $selectCustom.append($selectedItem);
51989      /*for each element, create $selectedItem new DIV that will contain the option list:*/
51990      $selectItem = $('<ul></ul>');
51991      $selectItem.attr('class', "select-items select-hide");
51992
51993      selElmnt.find('option').each(function (j, el) {
51994        var $el = $(el);
51995        /*for each option in the original select element,
51996        create $selectedItem new DIV that will act as an option item:*/
51997        $item = $('<li><a href="javascript:void(0)"></a></li>');
51998        var itemContent = $el.text();
51999        $item.find('a').text(itemContent).attr('id', itemContent.replace(/ /g, '-'));
52000        $item.find('a').click(self.itemClick);
52001        $item.attr('disabled', $(el).attr('disabled'));
52002
52003        $selectItem.append($item);
52004
52005        /**Item events handling */
52006        $item.keydown(function (e) {
52007          var key = e.which || e.keyCode;
52008          var item = $(e.target);
52009          if (key == Utils.keyCodes.UP || key == Utils.keyCodes.DOWN) e.preventDefault();
52010          if (key == Utils.keyCodes.UP) self.itemFocusPrevious(item);
52011          if (key == Utils.keyCodes.DOWN) self.itemFocusNext(item);
52012        });
52013
52014        $item.focusout(function (e) {
52015          if (!$(e.relatedTarget).is('a') && !$(e.relatedTarget).hasClass('select-selected')) self.closeAllSelect();
52016        });
52017      });
52018
52019      $selectCustom.append($selectItem);
52020
52021      /**Select events handling */
52022      $selectCustom.off('mousedown').on('mousedown', {
52023        'selElmnt': selElmnt,
52024        'selectCustom': self
52025      }, function (e) {
52026        e.preventDefault();
52027        self.selectedItemClick(e);
52028      });
52029
52030      $selectCustom.on('focusout', function (e) {
52031        if (!$(e.relatedTarget).is('a')) self.closeAllSelect();
52032      });
52033
52034      $selectCustom.on('keydown', function (e) {
52035        var key = e.which || e.keyCode;
52036        var el = $(e.target);
52037
52038        if (el.hasClass('select-arrow-active')) {
52039          if (key == Utils.keyCodes.UP || key == Utils.keyCodes.DOWN) e.preventDefault();
52040          if (key == Utils.keyCodes.UP) el.parent().find('a:not([disabled])').last().focus();
52041          if (key == Utils.keyCodes.DOWN) el.parent().find('a:not([disabled])').first().focus();
52042        }
52043
52044        if (key === Utils.keyCodes.ENTER || key === Utils.keyCodes.SPACEBAR) {
52045          var $htmlSelect = $(el.children()[1]);
52046          var $selectedOption = $(el.children()[2]).length > 0 ? $(el.children()[2]) : $(el);
52047
52048          e.data = {
52049            selElmnt: $htmlSelect,
52050            selectCustom: self
52051          };
52052          e.target = $selectedOption;
52053
52054          _this3.selectedItemClick(e);
52055        }
52056      });
52057    }
52058  }, {
52059    key: 'toggleIconDirection',
52060    value: function toggleIconDirection($element, isActive) {
52061      var $icon = $element.find('em');
52062      $icon.toggleClass('jca-ico-angle-down', isActive);
52063      $icon.toggleClass('jca-ico-angle-top', !isActive);
52064    }
52065  }, {
52066    key: 'selectedItemClick',
52067    value: function selectedItemClick(e) {
52068      e.stopImmediatePropagation();
52069      var selElmnt = e.data.selElmnt;
52070      var self = e.data.selectCustom;
52071      var selectedItem = $(e.currentTarget).find('.select-selected');
52072      var isActive = selectedItem.hasClass('select-arrow-active');
52073
52074      if (!selElmnt.is(':disabled') && !$(e.target).is('a') && !$(e.target).is('.select-items')) {
52075        self.closeAllSelect($(e.currentTarget));
52076        selectedItem.next().toggleClass("select-hide");
52077        selectedItem.toggleClass("select-arrow-active");
52078
52079        if (isActive) {
52080          selectedItem.next('.select-items').find('a:not([disabled])').first().focus();
52081        }
52082
52083        this.toggleIconDirection(selectedItem.find(".angle-icon"), isActive);
52084
52085        if (e.type == 'mousedown') {
52086          e.preventDefault();
52087        }
52088      }
52089    }
52090  }, {
52091    key: 'itemFocusNext',
52092    value: function itemFocusNext(item) {
52093      if (item.parent().is(":last-child")) {
52094        var parent = item.parent().parent();
52095        parent.find('li:not([disabled])').first().find('a').focus();
52096      } else {
52097        item.parent().next().find('a').focus();
52098      }
52099    }
52100  }, {
52101    key: 'itemFocusPrevious',
52102    value: function itemFocusPrevious(item) {
52103      var parent = item.parent().parent();
52104      var notDisabledItems = parent.find('li:not([disabled])').find('a');
52105
52106      if (notDisabledItems.first().get(0) == item.get(0)) {
52107        notDisabledItems.last().focus();
52108      } else {
52109        item.parent().prev().find('a').focus();
52110      }
52111    }
52112  }, {
52113    key: 'itemClick',
52114    value: function itemClick(e) {
52115      var y = void 0,
52116        select = void 0,
52117        h = void 0;
52118      var $el = $(e.target);
52119      if (!$el.hasClass('disabled')) {
52120        select = $el.parent().parent().parent().find("select").first();
52121        h = $el.parent().parent().prev();
52122
52123        select.find('option').each(function (i, el) {
52124          var $option = $(el);
52125          if ($option.text() == $el.text()) {
52126            select.val($option.val()).change();
52127            h.find(".select-text").text($el.text());
52128            y = $el.parent().parent().find(".same-as-selected");
52129
52130            y.each(function (k, item) {
52131              $(item).removeAttr('class');
52132            });
52133
52134            $el.attr('class', "same-as-selected");
52135            h.addClass('same-as-selected');
52136            return false;
52137          }
52138        });
52139
52140        h.trigger('mousedown');
52141        select.parent().focus();
52142      }
52143    }
52144  }, {
52145    key: 'resetSelect',
52146    value: function resetSelect(selectCustom) {
52147      var select = selectCustom.find(".select-items.select-hide");
52148      var selected = selectCustom.find(".select-selected");
52149
52150      if (select.length > 0) select.first().remove();
52151
52152      if (selected.length > 0) selected.first().remove();
52153    }
52154  }, {
52155    key: 'refreshSelect',
52156    value: function refreshSelect(select) {
52157      $(select).next().find(".select-text").text($(select).find('option:first').text());
52158    }
52159  }, {
52160    key: 'eraseSelect',
52161    value: function eraseSelect(select) {
52162      var result = $(select).next();
52163      var defaultVal = $(select).find('option:first').text();
52164
52165      $(select).find('option').not(':first').remove();
52166      $(select).next().next().empty().append('<div></div>');
52167      result.text(defaultVal);
52168    }
52169  }, {
52170    key: 'closeAllSelect',
52171    value: function closeAllSelect(selected) {
52172      /*$selectedItem function that will close all select boxes in the document,
52173      except the current select box:*/
52174      var $selectCustom = void 0,
52175        y = void 0;
52176      if (selected) {
52177        $selectCustom = $('.select-custom').not(selected).find(".select-items");
52178        y = $('.select-custom').not(selected).find(".select-selected");
52179      } else {
52180        $selectCustom = $(".select-items");
52181        y = $(".select-selected");
52182      }
52183
52184      if (y.hasClass("select-arrow-active")) this.toggleIconDirection(y, true);
52185
52186      $selectCustom.addClass("select-hide");
52187      y.removeClass("select-arrow-active");
52188    }
52189  }, {
52190    key: 'selectDefault',
52191    value: function selectDefault(element, value) {
52192      var selectSelected = $(element).next();
52193      var options = $(element)[0].options;
52194
52195      var _iteratorNormalCompletion = true;
52196      var _didIteratorError = false;
52197      var _iteratorError = undefined;
52198
52199      try {
52200        for (var _iterator = options[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
52201          var option = _step.value;
52202
52203          if ($(option).text() == value) {
52204            $(element).val($(option).val());
52205            $(selectSelected).find(".select-text").text(value).addClass('same-as-selected');
52206            $(element).change();
52207          }
52208        }
52209      } catch (err) {
52210        _didIteratorError = true;
52211        _iteratorError = err;
52212      } finally {
52213        try {
52214          if (!_iteratorNormalCompletion && _iterator.return) {
52215            _iterator.return();
52216          }
52217        } finally {
52218          if (_didIteratorError) {
52219            throw _iteratorError;
52220          }
52221        }
52222      }
52223    }
52224  }]);
52225
52226  return SelectCustom;
52227}();
52228'use strict';
52229
52230var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
52231
52232function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
52233
52234var TripDetailsActions = function () {
52235  function TripDetailsActions(trip) {
52236    var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
52237    var isNextTripTab = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
52238
52239    _classCallCheck(this, TripDetailsActions);
52240
52241    this.index = index;
52242    this.trip = trip;
52243    this.isNextTripTab = isNextTripTab;
52244    this.btnShowTransferPayment = $('[data-js="trip-details-btn-show-' + this.index + '"]');
52245    this.tripDetailBank = $('.trip-detail-body [data-js="trip-detail-bank-container-' + this.index + '"]');
52246    this.tripDetailPix = $('.trip-detail-body [data-js="trip-detail-pix-container-' + this.index + '"]');
52247    this.tripDetailBankMobile = $('.trip-detail-template .mobile[data-js="trip-detail-bank-container-' + this.index + '"]');
52248    this.tripDetailPixMobile = $('.trip-detail-template .mobile[data-js="trip-detail-pix-container-' + this.index + '"]');
52249    this.tripDetailAction = $('[data-js="trip-detail-actions-container-' + this.index + '"]');
52250    this.branch = $('#accordion-outer-' + this.index + ' [data-js="my-account-branch"]');
52251    this.account = $('#accordion-outer-' + this.index + ' [data-js="my-account-account"]');
52252    this.ourBranch = $('#accordion-outer-' + this.index + ' [data-js="our-account-branch"]');
52253    this.ourAccount = $('#accordion-outer-' + this.index + ' [data-js="our-account-account"]');
52254    this.bankTransferFavoredTo = $('#accordion-outer-' + this.index + ' [data-js="our-account-favored"]');
52255    this.valueTicket = $('#accordion-outer-' + this.index + ' [data-js="buy-value"]');
52256    this.bankLogo = $('#accordion-outer-' + this.index + ' [data-js="my-account-bank-image"]');
52257    this.ourBankLogo = $('#accordion-outer-' + this.index + ' [data-js="our-account-bank-image"]');
52258    this.cpfUser = $('#accordion-outer-' + this.index + ' [data-js="my-account-document"]');
52259    this.pixFavoredTo = $('#accordion-outer-' + this.index + ' [data-js="favored-to"]');
52260    this.pixKey = $('#accordion-outer-' + this.index + ' [data-js="pix-key"]');
52261    this.pixCopyLabel = $('#accordion-outer-' + this.index + ' [data-js="label-copy-key"]');
52262    this.btnCopyPixKey = $('#accordion-outer-' + this.index + ' [data-js="copy-pix-key"]');
52263    this.qrCodePix = $('#accordion-outer-' + this.index + ' [data-js="qrcode-pix"]');
52264    this.pixTotal = $('#accordion-outer-' + this.index + ' [data-js="buy-value"]');
52265    this.btnMobile = $('.trip-detail-template [data-js="open-actions-' + this.index + '"]');
52266    this.summaryStatus = $('[data-js="going-summary-status-' + this.index + '"]');
52267    this.tripAction = $('[data-js="trip-actions-' + this.index + '"]');
52268    this.cpf = this.trip[0].userDocument;
52269    this.value = this.trip[0].amount;
52270    this.init();
52271  }
52272
52273  _createClass(TripDetailsActions, [{
52274    key: 'init',
52275    value: function init() {
52276      this.checkBankTransfer();
52277      this.handleTripDetails();
52278      this.handleOpenActions(this.index);
52279      this.hideResendEmailTrip();
52280      this.hideMoreInfoPaymeePayment();
52281    }
52282  }, {
52283    key: 'showTripTransferPaymentDetail',
52284    value: function showTripTransferPaymentDetail() {
52285      var tripId = this.trip[0].finder;
52286
52287      this.getPaymeePaymentTicket(tripId);
52288    }
52289  }, {
52290    key: 'showBankDetail',
52291    value: function showBankDetail() {
52292      this.tripDetailBank.removeClass('d-none').show();
52293      this.btnShowTransferPayment.hide();
52294    }
52295  }, {
52296    key: 'showPixDetail',
52297    value: function showPixDetail() {
52298      this.tripDetailPix.removeClass('d-none').show();
52299      this.btnShowTransferPayment.hide();
52300    }
52301  }, {
52302    key: 'checkBankTransfer',
52303    value: function checkBankTransfer() {
52304      var isPending = this.trip[0].status == 'SALE_PENDING' || this.trip[0].status == 'EXCHANGE_PENDING';
52305
52306      if (isPending) {
52307        this.btnShowTransferPayment.show();
52308        this.tripDetailAction.hide();
52309        return;
52310      }
52311    }
52312  }, {
52313    key: 'showBtnTripDetail',
52314    value: function showBtnTripDetail() {
52315      this.btnShowBankTransfer.show();
52316      this.tripDetailAction.hide();
52317    }
52318  }, {
52319    key: 'hideResendEmailTrip',
52320    value: function hideResendEmailTrip() {
52321      if (!this.isNextTripTab) {
52322        if (this.trip[0].status == 'SALE_APPROVED' || this.trip[0].status == 'SALE_RELOCATED') {
52323          $('[data-js="resend-receipt-' + this.index + '"]').closest('li').hide();
52324        }
52325      }
52326    }
52327  }, {
52328    key: 'hideMoreInfoPaymeePayment',
52329    value: function hideMoreInfoPaymeePayment() {
52330      if (!this.isNextTripTab) {
52331        if (this.trip[0].status == 'SALE_PENDING' || this.trip[0].status == 'EXCHANGE_PENDING' || this.trip[0].status == 'SALE_EXPIRED' || this.trip[0].status == 'RELOCATED_CANCELED' || this.trip[0].status == 'CANCELATION_ERROR') {
52332          $('[data-js="trip-details-btn-show-' + this.index + '"]').hide();
52333          $('[data-js="resend-receipt-' + this.index + '"]').closest('li').hide();
52334        }
52335
52336        if (this.trip[0].status == 'SALE_PENDING' || this.trip[0].status == 'EXCHANGE_PENDING' || this.trip[0].status == 'SALE_EXPIRED' || this.trip[0].status == 'RELOCATED_CANCELED' || this.trip[0].status == 'CANCELATION_ERROR') {
52337          if (Utils.getWindowSize().width > 951) {
52338            $('[data-js="trip-actions-' + this.index + '"]').hide();
52339          } else {
52340            $('[data-js="cancel-trip-' + this.index + '"]').closest('li').hide();
52341            $('[data-js="resend-receipt-' + this.index + '"]').closest('li').hide();
52342            $('[data-js="link-buy-refund-' + this.index + '"]').closest('li').addClass('d-none');
52343          }
52344        }
52345      }
52346    }
52347  }, {
52348    key: 'getPaymeePaymentTicket',
52349    value: function getPaymeePaymentTicket(finder) {
52350      var _this = this;
52351
52352      var headers = {
52353        'Authorization': '' + SessionStorage.get('jca_token')
52354      };
52355
52356      var parameters = { finder: finder };
52357
52358      LoaderService.show();
52359      HttpService.get('getPaymeePayment?' + $.param(parameters), null, headers)
52360        // $.getJSON('https://run.mocky.io/v3/fb14f880-8893-4e1f-b0ce-9239554e1561')
52361        .then(function (data) {
52362          LoaderService.hide();
52363          if (data.result.pixItauReference || data.result.pixReference) _this.handleTripDetailsPix(data.result); else _this.handleTripDetailsBank(data.result);
52364        }).catch(function (err) {
52365          LoaderService.hide();
52366          console.log(err);
52367        });
52368    }
52369  }, {
52370    key: 'handleTripDetailsPix',
52371    value: function handleTripDetailsPix(trip) {
52372      this.showPixDetail();
52373      this.loadTripDetailsPix(trip);
52374      this.showPixDetailMobile();
52375    }
52376  }, {
52377    key: 'showBankDetailMobile',
52378    value: function showBankDetailMobile() {
52379      if (Utils.getWindowSize().width < 950) this.tripDetailBankMobile.addClass('active');
52380    }
52381  }, {
52382    key: 'showPixDetailMobile',
52383    value: function showPixDetailMobile() {
52384      if (Utils.getWindowSize().width < 950) {
52385        this.tripDetailPixMobile.addClass('active');
52386      }
52387    }
52388  }, {
52389    key: 'loadTripDetailsPix',
52390    value: function loadTripDetailsPix(result) {
52391      var _this2 = this;
52392
52393      var amount = result.amount,
52394        formOfPayment = result.formOfPayment;
52395
52396      var _ref = result.pixReference ? result.pixReference : result.pixItauReference,
52397        qrCodeBase64 = _ref.qrCodeBase64,
52398        qrCode = _ref.qrCode,
52399        favored = _ref.favored,
52400        pixKey = _ref.pixKey,
52401        emailKey = _ref.emailKey;
52402
52403      this.qrCodePix.attr('src', "data:image/png;base64," + qrCodeBase64);
52404      this.pixFavoredTo.text(favored ? favored : formOfPayment);
52405      this.pixTotal.text(Utils.formatPrice(amount));
52406      $('[data-js="pix-key"]').text(qrCode);
52407
52408      this.btnCopyPixKey.on('click', function () {
52409        _this2.copyPixKey(_this2.pixKey[0]);
52410      });
52411    }
52412  }, {
52413    key: 'copyPixKey',
52414    value: function copyPixKey($elem) {
52415      var $temp = $("<input>");
52416      $("body").append($temp);
52417      $temp.val($($elem).text()).select();
52418      document.execCommand("copy");
52419      $temp.remove();
52420    }
52421  }, {
52422    key: 'activateCopyPixKey',
52423    value: function activateCopyPixKey() {
52424      this.btnCopyPixKey.addClass('active');
52425      this.pixCopyLabel.text('Copiado');
52426      this.btnCopyPixKey.attr('data-bs-original-title', 'Chave copiad
52426a');
52427    }
52428  }, {
52429    key: 'handleTripDetailsBank',
52430    value: function handleTripDetailsBank(trip) {
52431      this.showBankDetail();
52432      this.loadTripDetailsBank(trip);
52433      this.showBankDetailMobile();
52434    }
52435  }, {
52436    key: 'loadTripDetailsBank',
52437    value: function loadTripDetailsBank(trip) {
52438      var _trip$paymeeReference = trip.paymeeReference,
52439        beneficiaryBranch = _trip$paymeeReference.beneficiaryBranch,
52440        beneficiaryAccount = _trip$paymeeReference.beneficiaryAccount,
52441        paymentMethod = _trip$paymeeReference.paymentMethod,
52442        branch = _trip$paymeeReference.branch,
52443        account = _trip$paymeeReference.account,
52444        asyncPaymentReference = _trip$paymeeReference.asyncPaymentReference;
52445      var amount = trip.amount;
52446
52447
52448      this.branch.text(branch);
52449      this.account.text(account);
52450      this.ourBranch.text(beneficiaryBranch);
52451      this.ourAccount.text(beneficiaryAccount);
52452      this.cpfUser.text(this.cpf);
52453      this.valueTicket.text('R$ ' + Utils.formatPrice(amount));
52454      this.bankTransferFavoredTo.text(asyncPaymentReference);
52455      var currentBankLogo = $('[data-js="' + paymentMethod + '"]');
52456      if (currentBankLogo.length > 0) {
52457        this.bankLogo.attr('src', $(currentBankLogo).first().attr('data-logo-src'));
52458      } else {
52459        this.bankLogo.hide();
52460      }
52461    }
52462  }, {
52463    key: 'handleTripDetails',
52464    value: function handleTripDetails() {
52465      var _this3 = this;
52466
52467      this.btnShowTransferPayment.on('click', function (e) {
52468        _this3.showTripTransferPaymentDetail();
52469      });
52470    }
52471  }, {
52472    key: 'handleOpenActions',
52473    value: function handleOpenActions() {
52474      var _this4 = this;
52475
52476      this.btnMobile.click(function () {
52477        var isTripActive = _this4.summaryStatus.is('.active, .remarkable, .canceled, .expired');
52478        isTripActive ? _this4.tripAction.addClass('active') : _this4.showTripTransferPaymentDetail();
52479      });
52480
52481      $('[data-js="close-trip-actions"]').click(function () {
52482        return $('[data-js^="trip-actions"]').removeClass('active');
52483      });
52484
52485      $('[data-js="close-trip-detail-bank-menu"]').on('click', function () {
52486        _this4.tripDetailBankMobile.removeClass('active');
52487        _this4.tripDetailPixMobile.removeClass('active');
52488      });
52489
52490      this.btnCopyPixKey.on('click', function () {
52491        _this4.copyPixKey();
52492        _this4.activateCopyPixKey();
52493      });
52494    }
52495  }]);
52496  return TripDetailsActions;
52497}();
52498'use strict';
52499
52500var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
52501
52502function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
52503
52504var TripDetailsShowMore = function () {
52505  function TripDetailsShowMore($parent, prefix) {
52506    var tripDetails = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
52507
52508    _classCallCheck(this, TripDetailsShowMore);
52509
52510    this.prefix = prefix;
52511    this.init($parent);
52512
52513    if (tripDetails) this.initDataForCheckout(tripDetails);
52514  }
52515
52516  _createClass(TripDetailsShowMore, [{
52517    key: 'init',
52518    value: function init($parent) {
52519      $parent.find('[data-js="chosen-class"]').attr('data-js', this.prefix + '-chosen-class');
52520      $parent.find('[data-js="chosen-class-connection"]').attr('data-js', this.prefix + '-chosen-class-connection');
52521      $parent.find('[data-js="origin-circle"]').attr('data-js', this.prefix + '-origin-circle');
52522      $parent.find('[data-js="destination-circle"]').attr('data-js', this.prefix + '-destination-circle');
52523      $parent.find('[data-js="depart-time-label"]').attr('data-js', this.prefix + '-depart-time-label');
52524      $parent.find('[data-js="duration"]').attr('data-js', this.prefix + '-duration');
52525      $parent.find('[data-js="arriving-time-label"]').attr('data-js', this.prefix + '-arriving-time-label');
52526      $parent.find('[data-js="connection"]').attr('data-js', this.prefix + '-connection');
52527      $parent.find('[data-js="origin-label"]').attr('data-js', this.prefix + '-origin-label');
52528      $parent.find('[data-js="destination-label"]').attr('data-js', this.prefix + '-destination-label');
52529      $parent.find('[data-js="connection"]').attr('data-js', this.prefix + '-connection');
52530      $parent.find('[data-js="operating-company-name"]').attr('data-js', this.prefix + '-operating-company-name');
52531      $parent.find('[data-js="operating-company-name-connection"]').attr('data-js', this.prefix + '-operating-company-name-connection');
52532
52533      this.$chosenClass = $parent.find('[data-js="' + this.prefix + '-chosen-class"]');
52534      this.$chosenClassConnection = $parent.find('[data-js="' + this.prefix + '-chosen-class-connection"]');
52535      this.$originCircle = $parent.find('[data-js="' + this.prefix + '-origin-circle"]');
52536      this.$destinationCircle = $parent.find('[data-js="' + this.prefix + '-destination-circle"]');
52537      this.$departTimeLabel = $parent.find('[data-js="' + this.prefix + '-depart-time-label"]');
52538      this.$arrivingTimeLabel = $parent.find('[data-js="' + this.prefix + '-arriving-time-label"]');
52539      this.$duration = $parent.find('[data-js="' + this.prefix + '-duration"]');
52540      this.$connectionIcon = $parent.find('[data-js="' + this.prefix + '-connection"]');
52541      this.$originLabel = $parent.find('[data-js="' + this.prefix + '-origin-label"]');
52542      this.$destinationLabel = $parent.find('[data-js="' + this.prefix + '-destination-label"]');
52543      this.$dateLabel = $('[data-js="' + this.prefix + '-date-label"]');
52544      this.$dayLabel = $('[data-js="' + this.prefix + '-day-label"]');
52545      this.$operatingCompany = $parent.find('[data-js="' + this.prefix + '-operating-company-name"]');
52546      this.$operatingCompanyConnection = $parent.find('[data-js="' + this.prefix + '-operating-company-name-connection"]');
52547    }
52548  }, {
52549    key: 'initDataForCart',
52550    value: function initDataForCart() {
52551      var offer = this._offer;
52552      var origin = this._origin;
52553      var destination = this._destination;
52554
52555      var departureDate = DateFormatter.getValidDateFormat(offer._company.departureDate);
52556      var arrivingDate = DateFormatter.getValidDateFormat(offer._company.arrivingDate);
52557      var departureDurationText = DateFormatter.getDurationLabel(departureDate, arrivingDate);
52558      var dayName = DateFormatter.getDaysArray()[departureDate.getDay()];
52559
52560      var friendlyName = !!offer._classtype.friendlyName ? offer._classtype.friendlyName : offer._classtype.className;
52561
52562      this.$departTimeLabel.text(DateFormatter.formatTimeFromString(offer._company.departureDate));
52563      this.$arrivingTimeLabel.text(DateFormatter.formatTimeFromString(offer._company.arrivingDate));
52564      this.$duration.text(departureDurationText.replace('h', 'h '));
52565      this.$chosenClass.html(friendlyName);
52566      this.$originCircle.text(origin.toUpperCase().substring(0, 3));
52567      this.$destinationCircle.text(destination.toUpperCase().substring(0, 3));
52568      //this.$dateLabel.text(Utils.isMobile() ? DateFormatter.formatDate(offer._company.departureDate).substr(0, 5) : DateFormatter.getFullDate(offer._company.departureDate).substr(0, 9));
52569      //this.$dayLabel.text(dayName.substr(0, 3) + ',');
52570      this.$originLabel.text(origin);
52571      this.$destinationLabel.text(destination);
52572      this.$operatingCompany.text(this._offer._company._companyName);
52573
52574      $(this.$dateLabel).each(function (index, element) {
52575        if ($(element).find('.cmp-text').length > 0) {
52576          $(element).find('.cmp-text').text(Utils.isMobile() ? DateFormatter.formatDate(offer._company.departureDate).substr(0, 5) : DateFormatter.getFullDate(offer._company.departureDate).substr(0, 9));
52577        } else {
52578          $(element).text(Utils.isMobile() ? DateFormatter.formatDate(offer._company.departureDate).substr(0, 5) : DateFormatter.getFullDate(offer._company.departureDate).substr(0, 9));
52579        }
52580      });
52581
52582      $(this.$dayLabel).each(function (index, element) {
52583        if ($(element).find('.cmp-text').length > 0) {
52584          $(element).find('.cmp-text').html(dayName.substr(0, 3) + ', &nbsp;');
52585        } else {
52586          $(element).text(dayName.substr(0, 3) + ',');
52587        }
52588      });
52589
52590      if (offer._connection && offer._connection.service) {
52591        this.$chosenClassConnection.text(" / " + offer._connection._classtype._className);
52592        this.$connectionIcon.show();
52593        this.$operatingCompanyConnection.text(" / " + offer._connection._company);
52594      } else {
52595        this.$chosenClassConnection.text("");
52596        this.$connectionIcon.hide();
52597        this.$operatingCompanyConnection.text("");
52598      }
52599
52600    }
52601  }, {
52602    key: 'initDataForCheckout',
52603    value: function initDataForCheckout(tripDetails) {
52604      var _originLabel = tripDetails._originLabel,
52605        _destinationLabel = tripDetails._destinationLabel,
52606        _arrivingDate = tripDetails._arrivingDate,
52607        _departureDate = tripDetails._departureDate,
52608        _title = tripDetails._title;
52609
52610
52611      var cart = SessionStorage.get('cart');
52612      var offer = cart._listOffer[0];
52613      var friendlyName = !!offer._classtype._friendlyName ? offer._classtype._friendlyName : offer._classtype._className;
52614
52615      var departureDate = DateFormatter.getValidDateFormat(_departureDate);
52616      var arrivingDate = DateFormatter.getValidDateFormat(_arrivingDate);
52617      var departureDurationText = DateFormatter.getDurationLabel(departureDate, arrivingDate);
52618      var date = DateFormatter.getValidDateFormat(_departureDate);
52619      var dayName = DateFormatter.getDaysArray()[date.getDay()];
52620
52621      this.$departTimeLabel.text(DateFormatter.formatTimeFromString(_departureDate));
52622      this.$arrivingTimeLabel.text(DateFormatter.formatTimeFromString(_arrivingDate));
52623      this.$duration.text(departureDurationText.replace('h', 'h '));
52624      this.$originCircle.text(_originLabel.toUpperCase().substring(0, 3));
52625      this.$destinationCircle.text(_destinationLabel.toUpperCase().substring(0, 3));
52626      this.$chosenClass.html(friendlyName);
52627
52628      this.$dateLabel.text(DateFormatter.getFullDate(_departureDate).substr(0, DateFormatter.getFullDate(_departureDate).length - 8));
52629      this.$dayLabel.text(dayName.substr(0, 3) + ',');
52630      this.$originLabel.text(_originLabel);
52631      this.$destinationLabel.text(_destinationLabel);
52632      this.$connectionIcon.hide();
52633    }
52634  }, {
52635    key: 'listenResize',
52636    value: function listenResize() {
52637      var _this = this;
52638
52639      var offer = this._offer;
52640
52641      $(window).on('resize', function () {
52642        if (_this.$dateLabel.find('.cmp-text').length > 0) {
52643          _this.$dateLabel.find('.cmp-text').text(Utils.isMobile() ? DateFormatter.formatDate(offer._company.departureDate).substr(0, 5) : DateFormatter.getFullDate(offer._company.departureDate).substr(0, 9));
52644        } else {
52645          _this.$dateLabel.text(Utils.isMobile() ? DateFormatter.formatDate(offer._company.departureDate).substr(0, 5) : DateFormatter.getFullDate(offer._company.departureDate).substr(0, 9));
52646        }
52647      });
52648    }
52649  }, {
52650    key: 'origin',
52651    set: function set(origin) {
52652      this._origin = origin;
52653    }
52654  }, {
52655    key: 'destination',
52656    set: function set(destination) {
52657      this._destination = destination;
52658    }
52659  }, {
52660    key: 'offer',
52661    set: function set(offer) {
52662      this._offer = offer;
52663    }
52664  }]);
52665
52666  return TripDetailsShowMore;
52667}();
52668'use strict';
52669
52670var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
52671
52672function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
52673
52674var TripStop = function () {
52675  function TripStop($) {
52676    _classCallCheck(this, TripStop);
52677
52678    this.$warningContainer = $('.warning-container');
52679  }
52680
52681  _createClass(TripStop, [{
52682    key: 'hide',
52683    value: function hide() {
52684      this.$warningContainer.removeClass('active');
52685    }
52686  }, {
52687    key: 'show',
52688    value: function show() {
52689      this.$warningContainer.addClass('active');
52690    }
52691  }]);
52692
52693  return TripStop;
52694}(); 'use strict';
52695
52696var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
52697
52698function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
52699
52700var ZipCodeController = function () {
52701  function ZipCodeController($) {
52702    _classCallCheck(this, ZipCodeController);
52703
52704    this.inputZipCode = $('[data-js="input-zipcode"]');
52705    this.inputStreet = $('[data-js="input-street"]');
52706    this.inputNumberAddress = $('[data-js="input-number-addresses"]');
52707    this.inputComplement = $('[data-js="input-complement"]');
52708    this.inputNeighborhood = $('[data-js="input-neighborhood"]');
52709    this.inputCity = $('[data-js="input-city"]');
52710    this.inputState = $('[data-js="input-state"]');
52711    this.inputUf = $('[data-js="input-uf"]');
52712    this.buttonSearchCep = $('[data-js="button-search-cep"]');
52713
52714    this.init();
52715  }
52716
52717  _createClass(ZipCodeController, [{
52718    key: 'init',
52719    value: function init() {
52720      this.loadMask();
52721      this.listenForm();
52722    }
52723  }, {
52724    key: 'listenForm',
52725    value: function listenForm() {
52726      var _this = this;
52727
52728      var regex = /[^a-zA-Z\u00C0-\u00FF ]+/ig;
52729
52730      this.inputZipCode.on('input', function () {
52731        var $tip = _this.inputZipCode.parent().siblings().find('.tip');
52732
52733        if (_this.inputZipCode.val()) {
52734          _this.removeInvalidClass(_this.inputZipCode, $tip);
52735          _this.buttonSearchCep.removeClass('disabled');
52736        } else {
52737          _this.buttonSearchCep.addClass('disabled');
52738        }
52739      });
52740
52741      $(this.inputZipCode).on('keyup', function (event) {
52742        var keyCode = event.keyCode || event.which;
52743        if (keyCode === Utils.keyCodes.ENTER) {
52744          _this.buttonSearchCep.click();
52745        }
52746      });
52747
52748      this.inputStreet.on('input focusout', function () {
52749        var $tip = _this.inputStreet.parent().siblings().find('.tip');
52750
52751        _this.inputStreet.val(_this.inputStreet.val().replace(regex, ""));
52752
52753        if (_this.inputStreet.val() != '') {
52754          _this.removeInvalidClass(_this.inputStreet, $tip);
52755        } else {
52756          _this.addInvalidClass(_this.inputStreet, i18n('street_name_required'), $tip);
52757        }
52758      });
52759
52760      this.inputNumberAddress.on('input focusout', function () {
52761        var $tip = _this.inputNumberAddress.parent().siblings().find('.tip');
52762
52763        _this.inputNumberAddress.val(_this.inputNumberAddress.val().replace(/\D/g, ''));
52764
52765        if (_this.inputNumberAddress.val() != '') {
52766          _this.removeInvalidClass(_this.inputNumberAddress, $tip);
52767        } else {
52768          _this.addInvalidClass(_this.inputNumberAddress, i18n('number_address_invalid'), $tip);
52769        }
52770      });
52771
52772      this.inputState.on('input focusout', function () {
52773        var $tip = _this.inputState.parent().siblings().find('.tip');
52774
52775        _this.inputState.val(_this.inputState.val().replace(regex, ""));
52776
52777        if (_this.inputState.val() != '') {
52778          _this.removeInvalidClass(_this.inputState, $tip);
52779        } else {
52780          _this.addInvalidClass(_this.inputState, i18n('state_name_required'), $tip);
52781        }
52782      });
52783
52784      this.inputNeighborhood.on('input focusout', function () {
52785        var $tip = _this.inputNeighborhood.parent().siblings().find('.tip');
52786
52787        _this.inputNeighborhood.val(_this.inputNeighborhood.val().replace(regex, ""));
52788
52789        if (_this.inputNeighborhood.val() != '') {
52790          _this.removeInvalidClass(_this.inputNeighborhood, $tip);
52791        } else {
52792          _this.addInvalidClass(_this.inputNeighborhood, i18n('neighborhood_name_required'), $tip);
52793        }
52794      });
52795
52796      this.inputCity.on('input focusout', function () {
52797        var $tip = _this.inputCity.parent().siblings().find('.tip');
52798
52799        _this.inputCity.val(_this.inputCity.val().replace(regex, ""));
52800
52801        if (_this.inputCity.val() != '') {
52802          _this.removeInvalidClass(_this.inputCity, $tip);
52803        } else {
52804          _this.addInvalidClass(_this.inputCity, i18n('city_name_required'), $tip);
52805        }
52806      });
52807
52808      this.buttonSearchCep.on('click', function () {
52809        var $tip = _this.inputZipCode.parent().siblings().find('.tip');
52810
52811        if (!_this.buttonSearchCep.hasClass('disabled')) _this.searchCep();
52812      });
52813
52814      this.inputZipCode.on('focusout', function () {
52815        _this.buttonSearchCep.trigger('click');
52816      });
52817    }
52818  }, {
52819    key: 'loadMask',
52820    value: function loadMask() {
52821      this.inputZipCode.mask("99999-999");
52822    }
52823  }, {
52824    key: 'cleanFormCEP',
52825    value: function cleanFormCEP() {
52826      this.inputStreet.val('');
52827      this.inputNumberAddress.val('');
52828      this.inputComplement.val('');
52829      this.inputNeighborhood.val('');
52830      this.inputCity.val('');
52831      this.inputState.val('');
52832    }
52833  }, {
52834    key: 'searchCep',
52835    value: function searchCep() {
52836      var _this2 = this;
52837
52838      var cep = $(this.inputZipCode).val().replace(/\D/g, '');
52839      var $tip = this.inputZipCode.parent().siblings().find('.tip');
52840
52841      if (cep.length == 8) {
52842        LoaderService.show();
52843        $.getJSON("https://viacep.com.br/ws/" + cep + "/json/?callback=?").then(function (cepSearchResult) {
52844          LoaderService.hide();
52845          if (cepSearchResult.uf == 'SP') {
52846            $('.container-cep').removeClass('hide');
52847            $('[data-js="input-street"]').val(cepSearchResult.logradouro);
52848            $('[data-js="input-neighborhood"]').val(cepSearchResult.bairro);
52849            $('[data-js="input-city"]').val(cepSearchResult.localidade);
52850            $('[data-js="input-uf"]').val(cepSearchResult.uf);
52851            $('[data-js="input-state"]').val(Utils.verifiedState(cepSearchResult.uf));
52852            _this2.removeInvalidClass(_this2.inputZipCode, $tip);
52853          } else {
52854            _this2.addInvalidClass(_this2.inputZipCode, i18n('cep_invali
52854d_state'), $tip);
52855            _this2.buttonSearchCep.addClass('disabled');
52856            _this2.cleanFormCEP();
52857          }
52858        }).catch(function () {
52859          LoaderService.hide();
52860          _this2.addInvalidClass(_this2.inputZipCode, i18n('cep_invalid'), $tip);
52861          _this2.buttonSearchCep.addClass('disabled');
52862          _this2.cleanFormCEP();
52863        });
52864      } else {
52865        this.addInvalidClass(this.inputZipCode, i18n('cep_invalid'), $tip);
52866        this.buttonSearchCep.addClass('disabled');
52867        this.cleanFormCEP();
52868      }
52869    }
52870  }, {
52871    key: 'addInvalidClass',
52872    value: function addInvalidClass(el, msg, tip) {
52873      var $links = el.parent().siblings().find('.link');
52874
52875      el.addClass('invalid');
52876
52877      if (tip && tip.hasClass('warning')) {
52878        if (msg) tip.text(msg);
52879        tip.fadeIn();
52880        $links.hide();
52881      }
52882    }
52883  }, {
52884    key: 'removeInvalidClass',
52885    value: function removeInvalidClass(el, tip) {
52886      var $links = el.parent().siblings().find('.link');
52887
52888      el.removeClass('invalid');
52889
52890      if (tip && tip.hasClass('warning')) {
52891        tip.fadeOut();
52892        $links.show();
52893      }
52894    }
52895  }, {
52896    key: 'getAddresses',
52897    value: function getAddresses() {
52898      return {
52899        "city": this.inputCity.val(),
52900        "complement": this.inputComplement.val(),
52901        "neighborhood": this.inputNeighborhood.val(),
52902        "number": this.inputNumberAddress.val(),
52903        "state": this.inputState.val(),
52904        "street": this.inputStreet.val(),
52905        "uf": this.inputUf.val()
52906      };
52907    }
52908  }]);
52909
52910  return ZipCodeController;
52911}();
52912
52913'use strict';
52914
52915var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
52916
52917function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
52918
52919var UserDataRequest = function () {
52920  function UserDataRequest($, type) {
52921    _classCallCheck(this, UserDataRequest);
52922
52923    this.name = $('[data-js="input-name"]');
52924    this.email = $('[data-js="input-email"]');
52925    this.typeDoc = $('[data-js="input-doc-type"]');
52926    this.doc = $('[data-js="input-doc"]');
52927    this.ddd = $('[data-js="input-ddd"]');
52928    this.phone = $('[data-js="input-phone"]');
52929    this.protocolInfo = $('[data-js="request-data-user-protocol-info"]');
52930    this.reason = this.protocolInfo.attr('data-reasonProtocol');
52931    this.typeProtocol = this.protocolInfo.attr('data-typeProtocol');
52932    this.btnRequest = $('[data-js="btn-user-data-request"]');
52933    this.aemRequestUserDescription = $('[data-js="request-user-data-description"]').val();
52934    this.init();
52935  }
52936
52937  _createClass(UserDataRequest, [{
52938    key: 'init',
52939    value: function init() {
52940      this.handleUserDataRequest();
52941    }
52942  }, {
52943    key: 'handleUserDataRequest',
52944    value: function handleUserDataRequest() {
52945      var _this = this;
52946
52947      this.btnRequest.on('click', function () {
52948        _this.submitProtocol();
52949      });
52950    }
52951  }, {
52952    key: 'submitProtocol',
52953    value: function submitProtocol() {
52954      var parameters = {
52955        'encoding': 'UTF-8',
52956        'orgid': '00D1N000002dlIo',
52957        'recordType': '0121N000001DlZt',
52958        'Origin': 'Web',
52959        'Status': 'New',
52960        '00N1N00000FAEW3': 'Novo',
52961        '00N1N00000FAAqo': 'Não',
52962        'name': this.name.val(),
52963        'email': this.email.val(),
52964        'phone': this.ddd.val() + ' ' + this.phone.val().replace(/\D/g, ''),
52965        'cpfoucnpj': this.typeDoc.val(),
52966        'cpf-mask': this.doc.val(),
52967        'type': this.typeProtocol,
52968        '00N1N00000FA8oC': this.reason,
52969        '00N1N00000FA8pt': 'Não',
52970        '00N1N00000P8jjs': Utils.getSiteName(),
52971        'description': this.aemRequestUserDescription,
52972        'token': SessionStorage.get('jca_token')
52973      };
52974
52975      LoaderService.show();
52976      HttpService.post('openProtocol', parameters).then(function (data) {
52977        LoaderService.hide();
52978        Utils.scrollTop();
52979        if (data.success) {
52980          Alert.show(i18n('protocol_success'));
52981          $('[data-js="modal-close"]').trigger('click');
52982        } else {
52983          AlertConfirmation.show('', i18n('protocol_error'), false, false);
52984        }
52985      }).catch(function () {
52986        LoaderService.hide();
52987        AlertConfirmation.show('', i18n('protocol_error'), false, false);
52988      });
52989    }
52990  }]);
52991
52992  return UserDataRequest;
52993}();
52994
52995'use strict';
52996
52997var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
52998
52999function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
53000
53001var SearchTicketClosestService = function () {
53002
53003  function SearchTicketClosestService($, searchComponentRef) {
53004    _classCallCheck(this, SearchTicketClosestService);
53005    this.locationInput = searchComponentRef.locationInput;
53006  }
53007
53008  _createClass(SearchTicketClosestService, [{
53009    key: 'findLocale',
53010    value: function findLocale() {
53011      var _this1 = this;
53012      var cookie = this.getCookie("WeMobiOriginDestination");
53013      var lat;
53014      var lng;
53015      if (!cookie || cookie == null) {
53016        if (navigator.geolocation) {
53017          navigator.geolocation.getCurrentPosition(function (position) {
53018            lat = position.coords.latitude;
53019            lng = position.coords.longitude;
53020            if (lat && lng) {
53021              if ($('#resourcePath')) {
53022                var url = $('#resourcePath').val() + "/jcr:content.closest.json?lat=" + lat + "&lng=" + lng;
53023                _this1.performAjaxRequest(url);
53024              }
53025            }
53026          }, function (error) {
53027            console.log(error);
53028          });
53029        }
53030      }
53031    }
53032  }, {
53033    key: 'performAjaxRequest',
53034    value: function performAjaxRequest(url) {
53035      var _this2 = this;
53036      $.ajax({
53037        url: url,
53038        type: 'GET',
53039        data: {},
53040        dataType: 'json',
53041        success: function (data) {
53042          if (data && data.isSuccess && data.result) {
53043            if (data.result.points && data.result.points.length > 0) {
53044              var point = data.result.points[0];
53045              _this2.locationInput.getDestination(data.result.id);
53046              $('#input-departure').val(data.result.points[0].name + " " + data.result.state);
53047              $('#input-departure').attr('data-value', data.result.id);
53048
53049            } else {
53050              _this2.locationInput.getDestination(data.result.id);
53051              $('#input-departure').val(data.result.name + " " + data.result.state);
53052              $('#input-departure').attr('data-value', data.result.id);
53053            }
53054          }
53055        },
53056        error: function (request, error) {
53057          console.log(error);
53058        }
53059      });
53060    }
53061  }, {
53062    key: 'getCookie',
53063    value: function getCookie() {
53064      var name = "searchOriginDestination";
53065      var cookieArr = document.cookie.split(";");
53066      for (var i = 0; i < cookieArr.length; i++) {
53067        var cookiePair = cookieArr[i].split("=");
53068        if (name == cookiePair[0].trim()) {
53069          return decodeURIComponent(cookiePair[1]);
53070        }
53071      }
53072      return null;
53073    }
53074  }]);
53075
53076  return SearchTicketClosestService;
53077}();
53078
53079/**
53080 * AEM CODE
53081 * JCAUtilsContexthub
53082 * */
53083
53084"use strict";
53085
53086var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
53087
53088function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
53089
53090/**
53091 * MAIN
53092 *
53093 */
53094var JCAUtilsContexthub = function () {
53095  function JCAUtilsContexthub() {
53096    _classCallCheck(this, JCAUtilsContexthub);
53097  }
53098
53099  _createClass(JCAUtilsContexthub, null, [
53100    {
53101      key: "setStoreProperty",
53102      value: function setStoreProperty(storeName, key, value) {
53103        try {
53104          var store = ContextHub.getStore(storeName);
53105          if (store) {
53106            return store.setItem(key, value);
53107          } else {
53108            return null;
53109          }
53110        } catch (error) {
53111          console.log('JCAUtilsContexthub.setStoreProperty ' + error);
53112        }
53113      }
53114    }, {
53115      key: "getStoreProperty",
53116      value: function getStoreProperty(storeName, key) {
53117        try {
53118          var store = ContextHub.getStore(storeName);
53119          if (store) {
53120            return store.getItem(key);
53121          } else {
53122            return null;
53123          }
53124        } catch (error) {
53125          console.log('JCAUtilsContexthub.getStoreProperty ' + error);
53126        }
53127      }
53128    }
53129  ]);
53130
53131  return Utils;
53132}();
53133

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.