"use strict";(function(){window.Skyscanner=window.Skyscanner||{};var n=window.Skyscanner;n.LivePricingClient=function(){function n(t){this._apiService="";this._callbacks=[];this._mostRecentResult=null;t&&(this._registerCallback(n.ON_RESULTS,t.onResults,this),this._registerCallback(n.ON_SERVER_FAILURE,t.onServerFailure,this),this._registerCallback(n.ON_VALIDATION_FAILURE,t.onValidationFailure,this),this._registerCallback(n.ON_BOOKING_DETAILS,t.onBookingDetails,this),this._registerCallback(n.ON_TOKEN_EXPIRE,t.onTokenExpire,this));this.defaults={country:"GB",currency:"GBP",locale:"en-GB",locationSchema:"Iata"}}return n.ON_RESULTS="onResults",n.ON_BOOKING_DETAILS="onBookingDetails",n.ON_SERVER_FAILURE="onServerFailure",n.ON_VALIDATION_FAILURE="onValidationFailure",n.ON_TOKEN_EXPIRE="onTokenExpire",n._FLIGHTS_LIVE_PRICING="/apiservices/pricing/v1.0/",n._MAX_POLLING_ATTEMPTS=22,n.prototype.getFlights=function(t){return this._apiService=n._FLIGHTS_LIVE_PRICING,t=$.extend(this.defaults,t||{}),this._start(t),t},n.prototype.getFlightBookingDetails=function(t,i){var r=this,u=0;$.ajax({type:"PUT",url:t,data:i}).done(function(i,f,e){var o=e.getResponseHeader("Location"),s;o=o.replace("http://","//");s=function(){$.ajax({type:"GET",cache:!1,url:o+t.substring(t.lastIndexOf("?")),dataType:"JSON"}).always(function(t,i,f){switch(f.status){case 200:var e=!0;$.each(t.BookingOptions,function(n,t){$.each(t.BookingItems,function(n,t){t.Status==="Pending"&&(e=!1)})});t=r._inflateResults(t);u++;u<n._MAX_POLLING_ATTEMPTS?(r._callCallback(n.ON_BOOKING_DETAILS,t,e),e||setTimeout(s,1500)):r._callCallback(n.ON_BOOKING_DETAILS,t,!0);break;case 400:r._callCallback(n.ON_VALIDATION_FAILURE,r._composeRejection(f),"polling booking details");break;default:r._callCallback(n.ON_SERVER_FAILURE,r._composeRejection(f),"polling booking details")}})};s()}).fail(function(t){r._callCallback(n.ON_SERVER_FAILURE,r._composeRejection(t),"polling booking details (server may be down)")})},n.prototype._start=function(t){var i=this;this._createSession(t).then(this._pollForResults).progress(function(t){App.Utils.Ui.isSlowDevice()||(t=i._inflateResults(t),i._callCallback(n.ON_RESULTS,t,!1))}).done(function(t){t=i._inflateResults(t);i._callCallback(n.ON_RESULTS,t,!0)}).fail(function(n,t,r){i._callCallback(n,t,r)})},n.prototype._composeRejection=function(n){var t;try{t=JSON.parse(n.responseText||"")}catch(i){t="Could not provide further help"}return n.status===410&&Logger&&App.Services.Session.getToken().done(function(n){Logger("session").error("Session expired: [token: "+n.substr(0,8)+"]")}),{status:n.status,statusText:n.statusText,debugInformation:t}},n.prototype._registerCallback=function(n,t,i){this._callbacks.push({id:n,func:t,context:i})},n.prototype._callCallback=function(){for(var t=arguments[0],r=arguments.length>1?[].slice.call(arguments,1):[],n=0;n<this._callbacks.length;n++)if(this._callbacks[n].id===t&&this._callbacks[n].func)try{this._callbacks[n].func.apply(this._callbacks[n].context,r);return}catch(i){Logger&&Logger("api-service").error("An exception was thrown when calling your "+t+" callback: "+JSON.stringify(JSON.stringify(i&&i.stack)));console.debug("An exception was thrown when calling your "+t+" callback");console.log(i);return}console.debug("An "+t+" event occurred, but no callback is registered to handle it")},n.prototype._createSession=function(t){var i=this,r=$.Deferred();return $.ajax({type:"POST",url:i._apiService,dataType:"JSON",data:t}).done(function(n,u,f){var e=f.getResponseHeader("Location").split("/");r.resolveWith(i,[e[e.length-1],encodeURIComponent(t.apiKey)])}).fail(function(t){t.status===400?r.reject(n.ON_VALIDATION_FAILURE,i._composeRejection(t),"session creation"):r.reject(n.ON_SERVER_FAILURE,i._composeRejection(t),"session creation")}),r.promise()},n.prototype._pollForResults=function(t,i){var u=this,r=$.Deferred(),f=0,o=function(){return f<2?500:f<6?1500:3e3},e=function(){return(f++,f<n._MAX_POLLING_ATTEMPTS)?(setTimeout(h,o()),!0):!1},s=function(n){n.Status==="UpdatesPending"?e()?r.notify(n):r.resolve(n):r.resolve(n)},h=function(){var f={type:"GET",cache:!1,url:u._apiService+t+"?apiKey="+i,dataType:"JSON"};App.Settings.mock_data&&(f.url="/scripts/tempdata/search-result-mock-data.json");$.ajax(f).always(function(t,i,f){switch(f.status){case 200:u._mostRecentResult=t;s(t);break;case 204:case 304:case 500:e()||r.resolve(u._mostRecentResult);break;case 400:r.reject(n.ON_VALIDATION_FAILURE,u._composeRejection(f),"polling for results");break;case 419:r.reject(n.ON_TOKEN_EXPIRE,u._composeRejection(f),"polling for results");break;case 403:case 410:case 429:default:r.reject(n.ON_SERVER_FAILURE,u._composeRejection(f),"polling for results")}})};return e(),r.promise()},n.prototype._inflateResults=function(n){var t=this;return n&&n.Itineraries?{Flights:t._inflateFlightItineraries(n),Query:n.Query}:n&&n.Segments?t._inflateFlightBookingDetails(n):n},n.prototype._inflateFlightItineraries=function(n){var f,r,t,e,i,o,u;return!n||!n.Itineraries?n:(f=[],$.each(n.Agents,function(n,t){f[t.Id]=t}),r=[],$.each(n.Carriers,function(n,t){r[t.Id]=t}),t=[],n.Places&&$.each(n.Places,function(n,i){t[i.Id]=i}),e=[],n.Segments&&App.Utils.RoutesFilter.hasPredefinedCarriers()&&$.each(n.Segments,function(n,t){e[t.Id]=t}),n.places=t,i=[],$.each(n.Legs,function(n,u){$.each(u.Carriers,function(n,t){u.Carriers[n]=r[t]||t});$.each(u.OperatingCarriers,function(n,t){u.OperatingCarriers[n]=r[t]||t});u.DestinationStation=t[u.DestinationStation]||u.DestinationStation;u.OriginStation=t[u.OriginStation]||u.OriginStation;$.each(u.Stops,function(n,i){u.Stops[n]=t[i]||i});i[u.Id]=u}),o=App.Services.OperatingCarriers.isEnabled,t.length&&App.Services.RoutesAndSuppliers.isEnabled&&(App.Services.RoutesAndSuppliers.isCurrentSearchSuite()||(n.Itineraries=[])),u=[],$.each(n.Itineraries,function(n,t){o&&(App.Services.OperatingCarriers.checkIsItinerarySuite({outboundLeg:i[t.OutboundLegId],inboundLeg:i[t.InboundLegId]},e)||u.push(n));$.each(t.PricingOptions,function(n,t){$.each(t.Agents,function(n,i){t.Agents[n]=f[i]||i})});t.OutboundLegId=i[t.OutboundLegId]||t.OutboundLegId;t.InboundLegId=i[t.InboundLegId]||t.InboundLegId}),o&&u.length&&(n.Itineraries=_.filter(n.Itineraries,function(n,t){return!_.contains(u,t)})),n)},n.prototype._inflateFlightBookingDetails=function(n){var t,i;return!n||!n.Segments?n:(t=[],$.each(n.Carriers,function(n,i){t[i.Id]=i}),i=[],$.each(n.Places,function(n,t){i[t.Id]=t}),$.each(n.Segments,function(n,r){r.OriginStation=i[r.OriginStation]||r.OriginStation;r.DestinationStation=i[r.DestinationStation]||r.DestinationStation;r.Carrier=t[r.Carrier]||r.Carrier;r.OperatingCarrier=t[r.OperatingCarrier]||r.OperatingCarrier}),n)},n}()})(),function(n,t){var i=new Backbone.Marionette.Application;i.Settings=t;Skyscanner.LivePricingClient._FLIGHTS_LIVE_PRICING=i.Settings.apiUrl+"apiservices/pricing/v1.0/";i.Router=new(Backbone.Marionette.AppRouter.extend({routes:{":whatever":"defaultNavigate"},defaultNavigate:function(){},isResultsPage:function(){return i.Router.CurrentRoute==="Results"&&!i.Router.is404()},isHomePage:function(){return i.Router.CurrentRoute==="Home"&&!i.Router.is404()},is404:function(){return $("html").hasClass("error404")},onRoute:function(n){var t=$("html"),r=t.attr("class"),i;r&&(i=r.match(/^page-\w+/),i&&t.removeClass(i[0]));t.addClass("page-"+n)}}));Backbone.Marionette.Behaviors.behaviorsLookup=function(){return i.Behaviours};i.Culture={locale:i.Settings.config.locale,locales:i.Settings.config.locales};i.addRegions({header:"#header",errors:"#errors",filters:"#filters",searchAreaContainer:".js-search-area-container",contentArea:Backbone.Marionette.Region.extend({el:"#main-container",attachHtml:function(n){this.$el.hide();this.el.appendChild(n.el);this.$el.show()}}),footer:"#footer",helpTab:".js-help-tab",helpLink:".js-help-link-wrapper"});i.on("before:start",function(){i.GlobalEvents=_.extend({},Backbone.Events);i.Utils.StateStorage.Base.invalidateIfNeeded();i.Utils.DeviceClassAppender.process();i.Utils.BrowserClassAppender.process();i.i18n.loadTranslation()});i.on("start",function(){i.TestMode=i.Utils.Storage.getObject("test-mode");i.Utils.CheckBrowserSupport.check();i.Services.PixelTrackingService.track();i.Services.TrackingServiceInitializer.initialize(i);i.Services.TimeTracker.start();$(document).on("click",function(n){i.GlobalEvents.trigger("global:click",n)});i.Utils.UrlDispatcher.processUrl()&&(i.trigger("appIsReady"),i.SearchArea.start(),i.Home.start(),i.CookieDisclaimer.start(),i.PreviewNotify.start(),i.SearchResult.start(),i.CultureControls.start(),i.HelpFooterLink.start(),Backbone.history&&Backbone.history.start())});i.on("module.ready",function(n){switch(n.name){case"Home":i.Router.CurrentRoute==="Home"&&i.contentArea.show(n.view);break;case"SearchResult":i.Router.CurrentRoute==="Results"&&i.contentArea.show(n.view);break;case"Cookie":$("#skyscanner-white-label body, div#skyscanner-white-label").prepend(n.view.render().$el);break;case"SearchArea":i.searchAreaContainer.show(n.view);break;case"CultureControls":$(".js-culture-container").length&&(i.addRegions({cultureControls:".js-culture-container"}),i.cultureControls.show(n.view));break;case"HelpTab":i.helpTab.show(n.view);break;case"HelpFooterLink":break;default:throw new Error("Module "+n.name+" is not defined");}});n.App=i}(window,window.AppSettings),function(){var n=function(n){this._initialized=!1;this._adRunner=n};n.prototype._initialize=function(){this._initialized||(this._initialized=!0,this._adRunner.run())};n.prototype.start=function(){this._initialize()};typeof Skyscanner.Adverts=="undefined"&&(Skyscanner.Adverts={});Skyscanner.Adverts.AdInitializer=n}.call(this),function(){var n=window.Skyscanner,t=function(){function n(){}return n.prototype.injectScript=function(n,t){var i=document.createElement("script"),r;i.async=!0;i.type="text/javascript";i.src=n;r=document.getElementsByTagName("script")[0];t&&(i.onreadystatechange=i.onload=function(){var n=i.readyState;t.done||n&&!/loaded|complete/.test(n)||(t.done=!0,t())});r.parentNode.insertBefore(i,r)},n}();n.Adverts.GoogleService=t}.call(this),function(){var n=window.Skyscanner,t=function(){function t(n){this.initOptions(n);this.adverts=[]}return t.prototype=new n.Adverts.GoogleService,t.prototype.constructor=t,t.prototype.initScriptLoad=function(){},t.prototype.initOptions=function(n){n=n||{};this.textColour=n.textColour;this.linksColour=n.linksColour;this.bgColour=n.bgColour;this.pageOptions=n.pageOptions||{}},t.prototype.setQuery=function(n){this.pageOptions.query=n},t.prototype.assertAdvertIsValid=function(n){for(var i,r=["position","containerId","numberOfItems"],t=0,u=r.length;t<u;t++)if(i=r[t],!n[i])throw i+" missing";},t.prototype.resetAdverts=function(){this.adverts=[]},t.prototype.addAdvert=function(n){this.assertAdvertIsValid(n);var t=n.position,i={container:n.containerId,position:t,lines:t==="Bottom"?"1":"3",width:t==="Bottom"?"728px":"auto",number:3,fontFamily:"arial",fontSizeTitle:"12",fontSizeDescription:"11",fontSizeDomainLink:"11",colorTitleLink:this.textColour,colorText:this.textColour,colorDomainLink:this.linksColour,colorBackground:this.bgColour,colorBorder:"#dbdcde"};this.adverts.push(i)},t.prototype.renderAdverts=function(){var u=window.google&&window.google.ads&&window.google.ads.search&&window.google.ads.search.Ads,i;if(u){var t=this.adverts.length,n=this.adverts,r=this.pageOptions;for(i=0;i<t;i++)this.showContainer(this.adverts[i]);if(t===1)return new window.google.ads.search.Ads(r,n[0]);if(t===2)return new window.google.ads.search.Ads(r,n[0],n[1]);if(t===3||t===4)return new window.google.ads.search.Ads(r,n[0],n[1],n[2])}return null},t.prototype.showContainer=function(n){document.getElementById(n.container).style.display="block"},t}();n.Adverts.GoogleAdSense=t}.call(this),function(){var n=window.Skyscanner,t=function(){function t(n,t,i){this.adUnit=n||"/24268069/skyscanner.net/flights_funnel/day_view";this.gptadslots=window.gptadslots=[];this.googletag=window.googletag||t||{defineSlot:function(){}};this.googletag.cmd=this.googletag.cmd||[];this.adverts=[];this.init(i);this.adSlotCache={primaryMpu:{dimensions:this.getAdDimensionsForAdvertType("primaryMpu"),pageLocation:"top",afsLocation:"Top"},leftSkyscraper:{dimensions:this.getAdDimensionsForAdvertType("leftSkyscraper"),pageLocation:"left",afsLocation:"Left"},rightSkyscraper:{dimensions:this.getAdDimensionsForAdvertType("rightSkyscraper"),pageLocation:"right",afsLocation:"Right"},bottomAd:{dimensions:this.getAdDimensionsForAdvertType("bottomAd"),pageLocation:"bottom",afsLocation:"Bottom"}}}return t.prototype=new n.Adverts.GoogleService,t.prototype.constructor=t,t.prototype.getAdDimensionsForAdvertType=function(n){if(window.adSlots){var t=_.findWhere(window.adSlots,{advertType:n});if(t&&t.dimensions)return t.dimensions}return null},t.prototype.init=function(n){var t=this,i;n||(n={});this.initOptions(n);i=(document.location.protocol==="https:"?"https://":"http://")+"www.googletagservices.com/tag/js/gpt.js";this.injectScript(n.altUrl||i,function(){t.googletag.cmd.push(function(){t.run()})});this.initGoogleCallModes();this.initPageLevelGoogleTargeting()},t.prototype.initOptions=function(n){n=n||{};this.searchIterations=n.searchIterations||10;this.millisecondsBetweenAdLoadedChecks=n.millisecondsBetweenAdLoadedChecks||200;this.loadingCompleteCallback=n.loadingCompleteCallback||null;this.pageLevelTargeting=n.pageLevelTargeting||{};this.usePageLocation=typeof n.usePageLocation!="undefined"&&n.usePageLocation===!1?!1:!0;this.isSearchPage=n.isSearchPage&&n.isSearchPage===!0||!1},t.prototype.setIsSearchPage=function(n){this.isSearchPage=n},t.prototype.preLoadingComplete=function(n){var f=this.isSearchPage,t,r,u,i;if(f)this.loadingCompleteCallback&&this.loadingCompleteCallback(n);else if(n&&n.emptySlots&&n.emptySlots.length>0)for(t=0,r=n.emptySlots.length;t<r;t++)u=n.emptySlots[t],i=document.getElementById(u.containerId),i&&i.style&&(i.style.display="none")},t.prototype.initGoogleCallModes=function(){var n=this;this.googletag.cmd.push(function(){var t=n.googletag.pubads();t!==null&&(t.enableSingleRequest(),t.enableAsyncRendering(),t.collapseEmptyDivs());n.googletag.enableServices()})},t.prototype.initPageLevelGoogleTargeting=function(){var n=this;this.googletag.cmd.push(function(){var i=n.googletag.pubads(),t,r;if(i!==null)for(t in n.pageLevelTargeting)r=n.pageLevelTargeting[t],i.setTargeting(t,r)})},t.prototype.rememberAdvertForDisplaying=function(n){this.adverts.push(n)},t.prototype.getAdvert=function(n){for(var i,t=0,r=this.adverts.length;t<r;t++)if(i=this.adverts[t],i.containerId===n)return i;return null},t.prototype.cloneAdvert=function(n){return{dimensions:n.dimensions,pageLocation:n.pageLocation,afsLocation:n.afsLocation}},t.prototype.defineSlot=function(n){var r=n.advertType,u=n.containerId,t=this.cloneAdvert(this.adSlotCache[r]),i;return t.containerId=u,this.rememberAdvertForDisplaying(t),i=this,this.googletag.cmd.push(function(){var n=i.adUnit,r;i.usePageLocation&&t.pageLocation&&(n+="/"+t.pageLocation);r=i.googletag.defineSlot(n,t.dimensions,t.containerId).addService(i.googletag.pubads());i.gptadslots.push(r)}),this.googletag},t.prototype.run=function(){if(this.gptadslots&&this.gptadslots.length>0){var n=this.gptadslots[0];n.renderEnded&&typeof n.renderEnded=="function"?(this.setupRenderEndedCallbacks(),this.display()):(this.setUpAdListener(),this.display())}},t.prototype.setUpAdListener=function(){var t=this,n=window.onload;window.onload=function(){n&&n();setTimeout(function(){t.listenForAllAdsLoaded()},500)}},t.prototype.display=function(){for(var n=this,t=0,i=n.adverts.length;t<i;t++)n.googletag.display(n.adverts[t].containerId)},t.prototype.setupRenderEndedCallbacks=function(){for(var n=this,i=this.getResultTemplate(),t=0,r=this.gptadslots.length;t<r;t++)(function(){var e=t,u=n.gptadslots[t],f=u.renderEnded;u.renderEnded=function(){f.call(u);var t=setTimeout(function(){var t=n.onSingleAdRenderEnded(n.adverts[e].containerId),o=n.processAdLoadedResult(t,r,i);u.renderEnded=f;o&&n.preLoadingComplete(i)},5)}})()},t.prototype.onSingleAdRenderEnded=function(n){var t=this.getElement(n),i={advertLoaded:!1,adSlotLocation:n};return t!==null&&this.advertHasRendered(t)&&(i.advertLoaded=!0),i},t.prototype.processAdLoadedResult=function(n,t,i){var r=this.getAdvert(n.adSlotLocation);return n.advertLoaded?i.loaded.push(r):i.emptySlots.push(r),i.allLoaded(t)},t.prototype.getResultTemplate=function(){return{allLoaded:function(n){return this.loaded.length+this.emptySlots.length===n},loaded:[],emptySlots:[]}},t.prototype.listenForAllAdsLoaded=function(){var t,i,n,r,u;if(this.loadingCompleteCallback!==null)for(t=this.getResultTemplate(),i=this,n=0,r=this.adverts.length;n<r;n++)u=this.adverts[n].containerId,this.listenForSingleAdLoaded(u,function(n){var u=i.processAdLoadedResult(n,r,t);return u?i.preLoadingComplete(t):null},0)},t.prototype.getElement=function(n){var t=this.getDOMElement(n);return t===null?null:t},t.prototype.listenForSingleAdLoaded=function(n,t,i){var r,u,f;return(i=i||0,r=this,u=this.getElement(n),i>=this.searchIterations)?t({advertLoaded:!1,adSlotLocation:n}):(f=u!==null?this.getFirstIframe(u.childNodes):null,f===null)?(i++,window.setTimeout(function(){r.listenForSingleAdLoaded(n,t,i)},r.millisecondsBetweenAdLoadedChecks)):this.advertHasRendered(f)?t({advertLoaded:!0,adSlotLocation:n}):(i++,window.setTimeout(function(){r.listenForSingleAdLoaded(n,t,i)},200))},t.prototype.getDOMElement=function(n){return document.getElementById(n)},t.prototype.getFirstIframe=function(n){var t,r,i;if(n===null)return null;for(t=0,r=n.length;t<r;t++)if(i=n[t],i.nodeName.toLowerCase()==="iframe")return i;return null},t.prototype.advertContainerHasBeenHidden=function(n){return n.style.display==="none"},t.prototype.advertHasRendered=function(n){return n===null||n.style===undefined?!1:!this.advertContainerHasBeenHidden(n)},t.prototype.refresh=function(n){var t,i;for(this.setupRenderEndedCallbacks(),t=0;t<this.gptadslots.length;t++){this.gptadslots[t].clearTargeting();for(i in n)this.gptadslots[t].setTargeting(i,n[i])}this.googletag.pubads().refresh()},t}();return n.Adverts.GoogleDfpService=t,t}.call(this),function(){var n=window.Skyscanner,t=function(){function t(n,t){this.adSlots=n||[];this.initOptions(t);this.init()}return t.prototype.setupRequirements=function(){window.gptadslots=[];window.googletag=window.googletag||{};window.googletag.cmd=window.googletag.cmd||[]},t.prototype.init=function(){this.adSlots.sort(function(n,t){return n.priority===t.priority?0:n.priority>t.priority?1:n.priority<t.priority?-1:0});this.setupRequirements()},t.prototype.initOptions=function(n){n=n||{};this.isSearchPage=n.isSearchPage||!1;this.pageLevelTargeting=n.pageLevelTargeting||{};this.adUnit=n.adUnit||"";this.usePageLocation=typeof n.usePageLocation!="undefined"&&n.usePageLocation===!1?!1:!0;this.afsQueryStemReplacementTag="##placename##";this.afsQueryStem=n.queryStem||this.afsQueryStemReplacementTag;this.altGPTUrl=n.altGPTUrl||null},t.prototype.getGAName=function(){var n=window.Skyscanner.ancillary==="airli"&&window.Skyscanner.view_action?window.Skyscanner.view_action:window.Skyscanner.ancillary;return((n||"").match(/dayview/gi)||[]).length?"day-view":((n||"").match(/monthview/gi)||[]).length?"month-view":((n||"").match(/browse/gi)||[]).length?"browse-view":n},t.prototype.run=function(t){var i=0,r=0,u,f;window.afsService=new n.Adverts.GoogleAdSense({textColour:window.google_text_color||"#34363d",linksColour:window.google_links_color||"#29a8bb",bgColour:window.google_bg_color||"#f7fefe",pageOptions:window.google_afs_page_options||{}});u=this;f={searchIterations:10,usePageLocation:this.usePageLocation,isSearchPage:this.isSearchPage,altUrl:this.altGPTUrl,pageLevelTargeting:this.pageLevelTargeting,loadingCompleteCallback:function(f){var e,h;for(window.afsService.resetAdverts(),e=0,i=0,r=f.emptySlots.length;i<r;i++){var s=f.emptySlots[i],o=s.afsLocation,c=o!==null&&o!=="";c&&(window.afsService.addAdvert({position:o,numberOfItems:3,containerId:s.containerId}),e+=1)}t&&window.afsService.setQuery(t());try{h={category:u.getGAName(),action:"AdSenseCall",label:e*3+"",value:undefined,trackOnce:!0};n.Common.GATracking.handleAnalyticsEvents(h)}catch(l){}window.afsService.renderAdverts()}};window.ssDfpAdService=new n.Adverts.GoogleDfpService(this.adUnit,null,f);this.defineAdvertSlots()},t.prototype.defineAdvertSlots=function(){for(var n=0,t=this.adSlots.length;n<t;n++)this.adSlotCanBeFilled(this.adSlots[n])&&window.ssDfpAdService.defineSlot(this.adSlots[n])},t.prototype.adSlotCanBeFilled=function(n){return typeof n.parentContainerId=="undefined"?!0:this.isAdvertSlotVisible(n.parentContainerId)},t.prototype.isAdvertSlotVisible=function(n){return $("#"+n).is(":visible")},t.prototype.refresh=function(n,t){window.ssDfpAdService.setIsSearchPage(!0);window.ssDfpAdService.refresh(n);window.afsService.setQuery(this.afsQueryStem.replace(this.afsQueryStemReplacementTag,t))},t}();return typeof n.Adverts=="undefined"&&(n.Adverts={}),n.Adverts.AdRunner=t,t}.call(this),function(n){n.Logger=function(n){var t,r,i;return n=n||"ssidelog",t=JL.createAjaxAppender("ajaxAppender"),t.setOptions({level:JL.getErrorLevel(),url:App.Settings.baseUrl+"jsnlog",beforeSend:function(t,i){n!=="ssidelog"&&_.each(i.lg,function(n){n.m=JSON.stringify({message:n.m,url:window.location.href})})}}),r=JL.createConsoleAppender("consoleAppender"),i=[r],App.Settings.enableLogging&&i.push(t),JL(n).setOptions({appenders:i})};n.onerror=function(n,t,i,r,u){t.indexOf(window.location.host)!==-1&&Logger().error({message:"window.onerror: "+n,url:window.location.href,file:t,column:r,linenumber:i,stackTrace:u&&u.stack})}}(window);App.module("VentActions",function(n){n.FavoritesBasket={OPEN:"favorites-basket-open",CLOSE:"favorites-basket-close",UPDATE_FLIGHTS:"favorites-basket-update-flights",UPDATE_HOTELS:"favorites-basket-update-hotels",UPDATE_CARHIRE:"favorites-basket-update-carhire",COUNT_HAS_BEEN_CHANGED:"favorites-basket-count-has-been-changed"};n.LowestPrices={OPEN:"lowest-prices-open",CLOSE:"lowest-prices-close"};n.Filters={OPEN:"filters-open",CLOSE:"filters-close",CHANGE:"filters-change",RESET:"filters-reset"};n.Sort={CHANGE:"sort-change"};n.Map={OPEN:"map-open",CLOSE:"map-close",INDICATE_ON_MAP:"indicate-on-map",REMOVE_INDICATE_ON_MAP:"remove-indicate-on-map"};n.Pagination={SET_PAGE:"pagination-set-page"};n.Flights={SEARCH_BEFORE_START:"flights-search-before-start",SEARCH_STARTED:"flights-search-start",SEARCH_FINISHED_SUMMARY:"flights-search-finished-summary",SEARCH_FINISHED:"flights-search-finished",SEARCH_PROGRESS:"flights-search-progress",ItemView:{OPEN_BOOKING_DIALOG:"flights-item-view-open-booking-dialog",CLOSE_BOOKING_DIALOG:"flights-item-view-close-booking-dialog",CONTINUE_BOOKING_DIALOG:"flights-item-view-continue-booking-dialog"}};n.SearchState={READY:"search-state-ready"};n.Results={UPDATE:"results-update"}});App.module("Dictionaries",function(n){n.CabinClasses=[{name:"search.service-class.economy",value:"Economy"},{name:"search.service-class.premium-economy",value:"PremiumEconomy"},{name:"search.service-class.business",value:"Business"},{name:"search.service-class.first",value:"First"}];n.PaxCount=[{name:"0",value:0},{name:"1",value:1},{name:"2",value:2},{name:"3",value:3},{name:"4",value:4},{name:"5",value:5},{name:"6",value:6},{name:"7",value:7},{name:"8",value:8}];n.AgeGroups=[{name:"21",value:"21"},{name:"22",value:"22"},{name:"23",value:"23"},{name:"24",value:"24"},{name:"carhire.search.age-groups.age-25-70",value:"25-70"},{name:"71",value:"71"},{name:"72",value:"72"},{name:"73",value:"73"},{name:"74",value:"74"},{name:"75",value:"75"},{name:"carhire.search.age-groups.76-or-older",value:"76+"}];n.SkyscannerSNAccounts={facebook:"Skyscanner",googleplus:"Skyscanner",twitter:"Skyscanner"};n.SortList=[{name:"search-result.filter-menu.sort-list.price",value:"price"},{name:"search-result.filter-menu.sort-list.journey-duration",value:"journey-duration"}];n.AirlineAlliances=[{name:"Budget Airlines",translatedName:"search-result.filter-menu.airlines-budget",airlines:[1653,842,817,1848,294,1113,1013,174,843,4,1569,967,1028,21,306,1411,912,1172,1481,1240,982,1576,222,193,1146,1708,2055,816,199,843,1028,913,935,1084,1108,1803,343,17,1138,1494,836,1220,1362,1476,196,1969,856,150,1057,895,865,1447,1089,266,1704,916,914,1270,2045,200,1460,1987,144,977,458,1829,969,1008,1025,1009,1050,1062,1842,1298,1950,1093,1077,1078,100,77,264,885,1098,457,1064,129,1272,1716,229,1128,336,1112,1322,979,195,1140,2043,1237,1475,864,124,99,1440,1807,201,1626,244,172,1257,344,1379,1746,1682,171,1131,892,1956,1370,177,1183,1777,1332,291,1304,1737,1327,1528,1297,198,1422,1335,426,1463,1369,1284,385,1426,1269,9,376,1223,1434,1418,1393,282,2034,1961,249,980,1910,890,1001,997,1478,1489,192,417,439,1383,1566,3,1542,1569,1555,1556,1558,2044,82,1090,1688,462,281,1625,1301,1722,1468,1702,1681,194,1706,1337,883,1472,280,1619,130,314,1697,1902,1557,35,1467,1394,467,18,1714,359,1721,197,1953,1705,115,1076,39,1732,176,1767,1764,1762,983,1973,1190,296,418,466,292,1621,1287,1865,230,1864,259,1831,7,942,1914,1909,1929,1281]},{name:"Star Alliance",translatedName:"search-result.filter-menu.airlines-star-alliance",airlines:[1280,819,835,929,1482,1464,1530,1523,854,1710,941,1525,1427,841,1044,898,1375,1368,1707,2040,1713,241,1384,1760,1751,1755,1793]},{name:"Skyteam",translatedName:"search-result.filter-menu.airlines-skyteam",airlines:[1717,850,845,1816,838,858,937,1429,954,1515,988,1121,1329,1324,1317,1413,1718,1663,1854,1414]},{name:"OneWorld",translatedName:"search-result.filter-menu.airlines-one-world",airlines:[834,833,881,952,857,1276,1218,1361,1416,1606,1658,1687,1804,1618,1274,1811]}];n.StopsList=[{name:"search-result.filter-menu.stops-list.any",value:"any",count:-1},{name:"search-result.filter-menu.stops-list.direct",value:"direct",count:0},{name:"search-result.filter-menu.stops-list.one-stop",value:"1stop",count:1},{name:"search-result.filter-menu.stops-list.two-stops",value:"2stops",count:2}];n.LocationSchema="sky";n.LocationSchemas=["sky","iata"];n.ImageLinks={favicon:"http://logos.skyscnr.com/images/airlines/favicon/",OTA:"http://logos.skyscnr.com/images/websites/bar/"};n.SupportedCurrencies=AppSettings.currenciesData.Items;n.SupportedCurrenciesByCode=_.indexBy(n.SupportedCurrencies,"Code");n.SupportedLocales=[{code:"ar-AE",name:"العربية"},{code:"az-AZ",name:"Azərbaycan­ılı"},{code:"bg-BG",name:"Български"},{code:"ca-ES",name:"Català"},{code:"cs-CZ",name:"Čeština"},{code:"da-DK",name:"Dansk"},{code:"de-DE",name:"Deutsch"},{code:"el-GR",name:"Ελληνικά"},{code:"en-GB",name:"English (UK)"},{code:"en-US",name:"English (US)"},{code:"es-ES",name:"Español (ES)"},{code:"es-MX",name:"Español (MX)"},{code:"et-EE",name:"Eesti"},{code:"fi-FI",name:"Suomi"},{code:"fr-FR",name:"Français"},{code:"hr-HR",name:"Hrvatski"},{code:"hu-HU",name:"Magyar"},{code:"id-ID",name:"Bahasa Indonesia"},{code:"it-IT",name:"Italiano"},{code:"ja-JP",name:"日本語"},{code:"ko-KR",name:"한국어"},{code:"lt-LT",name:"Lietuvių"},{code:"lv-LV",name:"Latviešu"},{code:"ms-MY",name:"Bahasa Melayu"},{code:"nb-NO",name:"Norsk, bokmål"},{code:"nl-NL",name:"Nederlands"},{code:"pl-PL",name:"Polski"},{code:"pt-BR",name:"Português (BR)"},{code:"pt-PT",name:"Português (PT)"},{code:"ro-RO",name:"Română"},{code:"ru-RU",name:"Русский"},{code:"sk-SK",name:"Slovenčina"},{code:"sv-SE",name:"Svenska"},{code:"th-TH",name:"ไทย"},{code:"tl-PH",name:"Filipino"},{code:"tr-TR",name:"Türkçe"},{code:"uk-UA",name:"Українська"},{code:"vi-VN",name:"Tiếng Việt"},{code:"zh-CN",name:"简体中文"},{code:"zh-HK",name:"中文(香港特別行政區)"},{code:"zh-SG",name:"中文(新加坡)"},{code:"zh-TW",name:"繁體中文"}];n.AcceptedCountriesForDomesticFlights=["CN","AU","ID","US","CA","FR","UK","CO","IT","BR","ES","JP","TH","PG","DE","RU","TR","NO","IN","GR"];n.Continents=[{id:"E",name:"Europe",inspirational:!0,order:1,countries:["AD","AL","AT","BA","BE","BG","BY","CH","CY","CZ","DE","DK","EE","ES","FI","FO","FR","GG","GI","GR","HR","HU","IE","IT","KO","LI","LT","LU","LV","MC","MD","ME","MK","MT","NL","NO","PL","PT","RO","RS","RU","SE","SI","SJ","SK","SM","UA","UK","VA"]},{id:"Am",name:"Americas",inspirational:!0,order:2,countries:["BL","BM","CA","MX","PM","US","AR","BO","BR","CL","CO","EC","FK","GF","GY","PE","PY","SR","UY","VE","CU"]},{id:"A",name:"Asia",inspirational:!0,order:3,countries:["AF","AM","AZ","BD","BT","CN","GE","ID","IN","IO","JP","KG","KP","KR","KZ","LK","MN","MV","NP","PH","PK","TJ","TH","TM","UZ"]}];n.PopularCountryCodes=[{id:"A",name:"Asia",resource:"inspirational-places.asia",countries:["CN","TH","ID","IN","JP","PH"]},{id:"E",name:"Europe",resource:"inspirational-places.europe",countries:["ES","UK","IT","FR","DE","GR"]},{id:"Am",name:"Americas",resource:"inspirational-places.americas",countries:["US","BR","CA","MX","CU","AR"]}];n.CurrencyCountryMapping={AF:"AFN",AL:"GBP",DZ:"GBP",AS:"USD",AO:"GBP",AI:"GBP",AQ:"GBP",AG:"GBP",AR:"ARS",AM:"GBP",AW:"GBP",AU:"AUD",AT:"EUR",AZ:"GBP",BS:"GBP",BH:"GBP",BD:"BDT",BB:"GBP",BY:"GBP",BE:"EUR",BZ:"GBP",BJ:"XOF",BM:"GBP",BT:"BTN",BO:"BOB",BA:"GBP",BW:"GBP",BR:"BRL",VG:"USD",BN:"GBP",BG:"BGN",BF:"XOF",BI:"GBP",KH:"KHR",CM:"XAF",CA:"CAD",CV:"GBP",BQ:"GBP",KY:"GBP",CF:"XAF",TD:"XAF",CL:"CLP",CN:"CNY",CX:"AUD",CC:"AUD",CO:"COP",KM:"GBP",CG:"XAF",CK:"NZD",CR:"GBP",HR:"HRK",CU:"CUC",CW:"GBP",CY:"EUR",CZ:"CZK",DK:"DKK",DJ:"GBP",DM:"GBP",DO:"GBP",CD:"GBP",TL:"GBP",EC:"USD",EG:"EGP",SV:"USD",GQ:"XAF",ER:"GBP",EE:"EUR",ET:"GBP",FK:"GBP",FO:"DKK",FJ:"FJD",FI:"EUR",FR:"EUR",GF:"EUR",PF:"XPF",GA:"XAF",GM:"GBP",GE:"GBP",DE:"EUR",GH:"GBP",GI:"GBP",GR:"EUR",GL:"DKK",GD:"GBP",GP:"EUR",GU:"USD",GT:"GBP",GG:"GBP",GN:"GBP",GW:"XOF",GY:"GBP",HT:"GBP",HN:"GBP",HK:"HKD",HU:"HUF",IS:"ISK",IN:"INR",ID:"IDR",IR:"GBP",IQ:"GBP",IE:"EUR",IL:"GBP",IT:"EUR",CI:"XOF",JM:"GBP",JP:"JPY",JO:"JOD",KZ:"KZT",KE:"GBP",KI:"AUD",KO:"GBP",KW:"KWD",KG:"KGS",LA:"LAK",LV:"LVL",LB:"GBP",LS:"GBP",LR:"GBP",LY:"GBP",LT:"EUR",LU:"EUR",MO:"MOP",MG:"GBP",MW:"GBP",MY:"MYR",MV:"MVR",ML:"XOF",MT:"EUR",MH:"USD",MQ:"EUR",MR:"GBP",MU:"GBP",YT:"EUR",MX:"MXN",FM:"USD",MD:"GBP",MC:"EUR",MN:"MNT",ME:"EUR",MA:"GBP",MZ:"GBP",MM:"MMK",NA:"GBP",NR:"AUD",NP:"GBP",NL:"EUR",NC:"XPF",NZ:"NZD",NI:"GBP",NE:"XOF",NG:"GBP",NU:"NZD",KP:"KPW",MP:"USD",NO:"NOK",OM:"OMR",PK:"PKR",PW:"USD",PA:"GBP",PG:"PGK",PY:"GBP",PE:"GBP",PH:"PHP",PL:"PLN",PT:"EUR",PR:"USD",QA:"QAR",MK:"GBP",RE:"EUR",RO:"RON",RU:"RUB",RW:"GBP",BL:"GBP",KN:"GBP",LC:"GBP",VC:"GBP",WS:"WST",ST:"GBP",SA:"SAR",SN:"XOF",RS:"GBP",SC:"GBP",SL:"GBP",SG:"SGD",SK:"EUR",SI:"EUR",SB:"GBP",SO:"GBP",ZA:"ZAR",KR:"KRW",SS:"GBP",ES:"EUR",LK:"LKR",SX:"GBP",PM:"EUR",SD:"GBP",SR:"GBP",SZ:"GBP",SE:"SEK",CH:"CHF",SY:"GBP",TW:"TWD",TJ:"TJS",TZ:"GBP",TH:"THB",TG:"XOF",TO:"GBP",TT:"GBP",TN:"GBP",TR:"TRY",TM:"TMT",TC:"USD",TV:"AUD",UG:"GBP",UA:"UAH",AE:"AED",UK:"GBP",US:"USD",UY:"GBP",UZ:"GBP",VU:"VUV",VE:"VEF",VN:"VND",VI:"USD",WF:"XPF",YE:"GBP",ZM:"GBP",ZW:"GBP"}});App.module("Utils",function(n,t){var i="3359018893",r="1424890065",u="/24268069/whitelabels.b2b/",f="pub-6496241184674058";n.Ads={onToggleSidebarsFixed:function(n){this.$body.toggleClass("sidebars-fixed",n)},makeAdsSticky:function(){this.$body=$("html");t.Utils.Ui.on("search-container:toggle-top-fixed",_.bind(this.onToggleSidebarsFixed,this))},placeAdUnits:function(n){if(this.initialized===undefined){this.initialized=!0;this.googleAfsSetup(n);window.adSlots=[{containerId:"ads-left",advertType:"leftSkyscraper",dimensions:[[120,600],[160,600]],priority:1,parentContainerId:"ads-left-container"},{containerId:"ads-right",advertType:"rightSkyscraper",dimensions:[[120,600],[160,600]],priority:2,parentContainerId:"ads-right-container"},{containerId:"ads-top",advertType:"primaryMpu",dimensions:[[300,250],[300,600]],priority:3,parentContainerId:"ads-top-container"},{containerId:"ads-bottom",advertType:"bottomAd",dimensions:[[300,250],[300,250]],priority:3,parentContainerId:"ads-bottom-container"}];var i=typeof Skyscanner.Adverts=="undefined"||typeof Skyscanner.Adverts.GoogleAdSense=="undefined";i||(typeof runnerOptions=="undefined"&&(window.runnerOptions={}),window.runnerOptions.adUnit=u+window.runnerOptions.adUnit,t.Utils.Ui.isFlights()&&(window.runnerOptions.pageLevelTargeting={lang:n.getLocale()?n.getLocale().slice(0,2).toUpperCase():"EN",cc:n.getCabinclass(),adults:n.getAdults(),children:n.getChildren(),isreturn:n.getInbounddate()?!0:!1,idate:n.getInbounddate(),odate:n.getOutbounddate(),oairp:n.getOriginplace(),ocity:n.getOriginplaceCityCode(),octry:n.getOriginCountryCode(),dairp:n.getDestinationplace(),dcity:n.getDestinationCityCode(),dctry:n.getDestinationCountryCode(),b2bpublisher:t.Settings.config.homeUrl.replace("http://","").replace("https://","")}),window.adRunner=new Skyscanner.Adverts.AdRunner(window.adSlots,window.runnerOptions),new Skyscanner.Adverts.AdInitializer(window.adRunner).start())}else _.isFunction(googletag.pubads)&&googletag.pubads().refresh()},googleAfsSetup:function(n){var u;window.runnerOptions={isSearchPage:!0,usePageLocation:!0,adUnit:"flights_funnel"};var v=n.getLocale(),e="",o="",s="";if(t.Utils.Ui.isFlights()){var h=n.getOriginCountryCode(),c=n.getOriginplaceText(),l=n.getDestinationCountryCode(),a=n.getDestinationplaceText();e=[c?c+", ":"",h?h:""].join("");e&&(e=["Flights from ",e].join(""));o=[a?a+", ":"",l?l:""].join("");o&&(o=["Flights to ",o].join(""));s=e+" - "+o}else t.Utils.Ui.isHotels()?s=["Hotels in ",n.getDestinationText(),", ",n.getDestinationCountry()].join(""):t.Utils.Ui.isCarHire()&&(s="Car Hire");u=v.slice(0,2)||"";switch(u.toLowerCase()){case"zh":u="zh_CN";break;case"zw":u="zh_TW";break;case"cz":u="cs";break;case"gr":u="el";break;case"uk":u="ru"}window.google_afs_page_options={query:s,pubId:f,channel:t.Utils.Ui.isCarHire()?r:i,hl:u,linkTarget:"_blank",sellerRatings:!1,siteLinks:!1,titleBold:!0,rolloverLinkUnderline:!0,oe:"utf8",ie:"utf8"}}}});App.module("Utils",function(n){n.FilteredCollection=function(n,t){t=t||{};var i=new n.constructor;i._currentSort={sortColumn:[],sortDirection:[]};i._scrollTo=t.scrollTo;i._sortOptionsPreparation=function(n){var t={};return n.sortDirection&&(t=_.extend(t,{sortDirection:_.map(n.sortDirection.split(","),function(n){return n==="asc"?1:-1})})),n.sortColumn&&(t=_.extend(t,{sortColumn:n.sortColumn.split(",")})),n.alwaysSortAddition&&(t=_.extend(t,{alwaysSortAddition:n.alwaysSortAddition})),t};i.setSort=function(n){n=i._sortOptionsPreparation(n);var t;n.alwaysSortAddition&&(t=i._sortOptionsPreparation(n.alwaysSortAddition),i._currentSort.alwaysSortAddition=_.extend(i._currentSort.alwaysSortAddition||{},t));i._currentSort=_.extend(i._currentSort,{sortColumn:i._currentSort.alwaysSortAddition?i._currentSort.alwaysSortAddition.sortColumn.concat(n.sortColumn):n.sortColumn,sortDirection:i._currentSort.alwaysSortAddition?i._currentSort.alwaysSortAddition.sortDirection.concat(n.sortDirection):n.sortDirection})};i.setSort(t.sort||{});i.comparator=function(n,t){if(!i._currentSort.sortColumn||i._comparatorDisabled)return 0;var r=0;return _.find(i._currentSort.sortColumn,function(u,f){var o=n.get(u),s=t.get(u),e=i._currentSort.sortDirection[f]*(o>s?1:o<s?-1:0);return r===0&&e!==0&&(r=e),e!==0}),r};i.filter=function(t,r,u,f){var e,s,o,h;u=u||i._currentPage||1;i._comparatorDisabled=!1;e=t?n.filter(t).sort(i.comparator):n.models;i._currentCriteria=t;i._currentPaginateBy=r;i.allFiltered=e;this._scrollToModel=null;f&&i._scrollTo&&i._scrollTo.value&&(this._scrollToModel=_.find(n.models,function(n){return n.get(i._scrollTo.property)==i._scrollTo.value}),this._scrollToModel&&(s=_.indexOf(i.allFiltered,this._scrollToModel),u=parseInt(s/i._currentPaginateBy,10)+1));i._currentPage=u;o=[];h=r?_.chain(e).rest((u-1)*r).first(r).value():e;o=h;i.reset(o);i.trigger("onFilterCollection")};i.getScrollToModel=function(){return this._scrollToModel};i.setPage=function(n){n=n||1;i._comparatorDisabled=!1;i._currentPage=n;var t=_.chain(i.allFiltered).rest((n-1)*i._currentPaginateBy).first(i._currentPaginateBy).value();i.reset(t);i.trigger("onSetPageCollection")};i.setPageWhere=function(n){var r=_.indexOf(i.allFiltered,n),t=parseInt(r/i._currentPaginateBy,10)+1;return i._currentPage!==t&&i.setPage(t),t};i.getPage=function(){return i._currentPage||1};i.getNextPages=function(t,r){t=t||1;var u=i._currentPage;return r&&(++t,--u),new n.constructor(i._currentPaginateBy?_.chain(i.allFiltered).rest(u*i._currentPaginateBy).first(i._currentPaginateBy*t).value():i.allFiltered)};i.getAllFiltered=function(){return new n.constructor(i.allFiltered)};i.getCount=function(){return i.allFiltered.length-_.compact(_.pluck(i.allFiltered,"isEmpty")).length};i.getAllCount=function(){return n.length-_.compact(n.pluck("isEmpty")).length};i.freeze=function(){this._frozen=!0};i.unfreeze=function(){this._frozen=!1;this.trigger("reset")};i.isFrozen=function(){return!!this._frozen};i.reset=function(n,t){t=t||{};this.isFrozen()&&(t.silent=!0);Backbone.Collection.prototype.reset.apply(this,[n,t]);this.isFrozen()&&this.trigger("onUpdateFrozenCollection")};n.on("reset",function(){i.filter(i._currentCriteria,i._currentPaginateBy,i._currentPage,!0)});n.on("filter",function(n){n=n||i._currentPage;i.filter(i._currentCriteria,i._currentPaginateBy,n)});return i}});App.module("Utils",function(n){function t(n){this._maxSize=n||-1;this._storage=new i;this._fill=.8}var i=function(){this._items={};this._count=0};i.prototype.get=function(n){return this._items[n]};i.prototype.set=function(n,t){typeof this.get(n)=="undefined"&&this._count++;this._items[n]=t};i.prototype.size=function(){return this._count};i.prototype.remove=function(n){var t=this.get(n);return typeof t!="undefined"&&this._count--,delete this._items[n],t};i.prototype.keys=function(){return _.keys(this._items)};t._item=function(n,t){if(!n)throw new Error("Key cannot be empty");this.key=n;this.value=t;this.created=(new Date).getTime()};t.prototype._clearOld=function(){var t=Math.round(this._maxSize*this._fill),i,n,r;if(this._maxSize<0&&(t=this.size()*this._fill),i=this._storage.keys(),n=_.map(i,_.bind(function(n){return this._storage.get(n)},this)),n.length>t)for(n=_.sortBy(n,function(n,t){return t.created-n.created});n.length>t;)r=n.pop(),this.remove(r.key)};t.prototype.set=function(n,i){var r,u;this._storage.get(n)!==null&&this.remove(n);r=new t._item(n,i);this._storage.set(r.key,r);this._maxSize>0&&this.size()>this._maxSize&&(u=this,setTimeout(function(){u._clearOld.call(u)},0))};t.prototype.clear=function(){var n=this._storage.keys();_.each(n,_.bind(function(n){this.remove(n)},this))};t.prototype.get=function(n){var t=this._storage.get(n);return t?t.value:null};t.prototype.remove=function(n){var t=this._storage.remove(n);return t?t.value:null};t.prototype.size=function(){return this._storage.size()};t.SimpleStorage=i;n.Cache=t});App.module("Utils",function(n,t){n.CheckBrowserSupport={browsers:{msie:8,chrome:1,firefox:12,safari:5,android:4,blackberry:10},redirect:function(){var n="/BrowserNotSupported?locale="+t.Culture.locale;window.location.search&&(n+="&"+window.location.search.slice(1));t.Utils.Location.setHref(n)},isBrowserSupported:function(t){var i=n.CheckBrowserSupport.browsers[t.browser.toLowerCase()],r=_.isUndefined(i)||_.isNumber(i)&&t.version>=i;return(t.os==="blackberry"||t.os==="android")&&(r=t.version>=n.CheckBrowserSupport.browsers[t.os.toLowerCase()]),r},check:function(){var i=t.Utils.Ui.getBrowserInfo();t.Settings.config.isScaffold&&!n.CheckBrowserSupport.isBrowserSupported(i)&&n.CheckBrowserSupport.redirect()}}});App.module("Utils",function(n,t){n.Date={getFriday:function(){var r=moment().add(0,"day"),n=moment().startOf("isoweek").add(4,"days"),u=moment().startOf("isoweek").add(11,"days"),i=n.diff(r),f=i>0&&moment(i).format("D")>2?n:u;return f.format(t.Settings.dateFormat)},today:function(){var n=moment().add(0,"day");return n.format(t.Settings.dateFormat)},addDay:function(n,i){return n._isAMomentObject?n.add(i||1,"day").format(t.Settings.dateFormat):moment(n,t.Settings.dateFormat).add(i||1,"day").format(t.Settings.dateFormat)},getNearestFridayMonday:function(){var n=this.getFriday(),i=moment(n).add(3,"day").format(t.Settings.dateFormat);return{friday:n,monday:i}},getNearestFridaySunday:function(){var n=this.getFriday(),i=moment(n).add(2,"day").format(t.Settings.dateFormat);return{friday:n,sunday:i}},validFormat:function(n){return n===moment(n).format(t.Settings.dateFormat)}}});App.module("Utils",function(n){var t=55,i=266;n.DistanceMinutesConverter={distanceToDriveMinutes:function(n){var t=parseInt(Math.floor(n/i),10);return t?t:1},distanceToWalkMinutes:function(n){var i=parseInt(Math.floor(n/t),10);return i?i:1},walkMinutesToDistance:function(n){return parseInt(Math.floor(n*t),10)},driveMinutesToDistance:function(n){return parseInt(Math.floor(n*i),10)},distanceDescription:function(n,t){var r=this.distanceToWalkMinutes(n),i;return r<30?$.t("hotels.search-result.list.walk-minutes",{count:r,destination:t}):(i=this.distanceToDriveMinutes(n),i<60?$.t("hotels.search-result.list.drive-minutes",{count:i,destination:t}):i<120?$.t("hotels.search-result.list.drive-more-hour",{count:i-60,destination:t}):i===120?$.t("hotels.search-result.list.drive-two-hours",{destination:t}):$.t("hotels.search-result.list.drive-more-two-hours",{destination:t}))}}});App.module("Utils",function(n){n.Favorites={isSameFlightSearch:function(n,t){return n.originplace===t.originplace&&n.destinationplace===t.destinationplace&&n.outbounddate===t.outbounddate&&n.inbounddate===t.inbounddate&&n.cabinclass===t.cabinclass&&n.adults===t.adults&&n.children===t.children&&n.infants===t.infants},isSameHotelSearch:function(n,t){return n.checkin===t.checkin&&n.checkout===t.checkout&&n.destination===t.destination&&n.guests===t.guests&&n.rooms===t.rooms},isSameCarHireSearch:function(n,t){return n.pickupPlace===t.pickupPlace&&n.dropoffPlace===t.dropoffPlace&&n.pickupDate===t.pickupDate&&n.pickupTime===t.pickupTime&&n.dropoffDate===t.dropoffDate&&n.dropoffTime===t.dropoffTime&&n.ageGroup===t.ageGroup&&n.sameDropoffPlace===t.sameDropoffPlace},getRatingClass:function(n){return _.isNumber(n)?n<5?"mark5":n<6?"mark6":n<7?"mark7":n<8?"mark8":n<9?"mark9":n<9.5?"mark95":"":"no-rating"},getHotelDescription:function(n,t,i){return!t&&n.description&&n.description.length>i?n.description.substr(0,i).trim()+"...":n.description},_convertToReadableTimeAgo:function(n,t){var i=t-n,r,u;return i>=0?i>=0&&i<=5?(i===0&&(i=1),$.t("favorites.time.minutes-ago",{value:i})):i<=55?(r=i%5,i=r<=2?i-r:i+(5-r),$.t("favorites.time.minutes-ago",{value:i})):i>55&&i<=1440?(u=parseInt(i/60,10),u===0&&(u=1),$.t("favorites.time.hours-ago",{value:u})):$.t("favorites.time.more-than-day-ago"):!1},addedTimeAgo:function(n){var t=parseInt((new Date).getTime()/6e4,10),i=parseInt(n/6e4,10);return this._convertToReadableTimeAgo(i,t)}}});App.module("Utils",function(n){n.Filters={airportsChecker:function(n){var t=!n||n.length===0||_.every(n,function(n){return n.checked}),i=!_.some(n,function(n){return n.checked});return{allSelected:t,noSelected:i,isSelected:function(r){if(!n||n.length===0||t)return!0;if(n.length&&i)return!1;var u=_.findWhere(n,{code:r.Code||r.code});return u?u.checked:!1}}}}});App.module("Utils",function(n){n.Hash={getObjectHash:function(n){var t=JSON.stringify(n);return this.getStringHash(t)},getStringHash:function(n){var t=0,i,r,u;if(n.length===0)return t;for(i=0,u=n.length;i<u;i++)r=n.charCodeAt(i),t=(t<<5)-t+r|0;return t}}});App.module("i18n",function(n,t,i,r,u){n.loadTranslation=function(){var i=t.Services.Language.getDisplayLanguageSync();n.loadCalendarData(i);n.loadTranslatedResources(i)};n.loadTranslatedResources=function(n){var i={};i[n]={translation:t.Settings.translations};u.i18n.init({lng:n,resStore:i,useDataAttrOptions:!0});u("body").i18n()};n.getCalendarLocale=function(){var n=t.Settings.calendarData?_.keys(t.Settings.calendarData.main):[];return n[0]||"en-GB"};n.loadCalendarData=function(){var r,u,i,f=n.getCalendarLocale();Globalize.load(t.Settings.calendarData);t.Culture.culture=Globalize(f);r=t.Culture.culture.cldr.main("dates").calendars.gregorian;u=r.months.format;i=r.days.format;moment.locale(f,{months:_.filter(u.wide,Boolean),monthsShort:_.filter(u.abbreviated,Boolean),weekdays:_.filter(i.wide,Boolean),weekdaysShort:_.filter(i.abbreviated,Boolean),weekdaysMin:_.filter(i.short,Boolean)})}});App.module("Utils",function(n,t){function i(n){var u,f,i,e,r;return t.Settings.config.isScaffold?t.Utils.Ui.isWidget()?t.Settings.config.searchUrl:t.Settings.config.homeUrl:(u=t.Utils.Ui.isWidget()?t.Settings.redirect:t.Utils.Location.getBaseHref(),f=t.Services.Language.getDisplayLanguageSync(),i=u+f+"/"+n+"/",t.Utils.Ui.isPreview()&&(i+="preview/"),t.Utils.Ui.isWidget()||(e=new t.Utils.Uri(t.Utils.Location.getHref()),r=e.getQueryParam("host"),r&&(i+="?host="+r)),i)}n.WhiteLabelLocation={getFlightsProductPath:function(){var n=t.Services.Feature.get("overridenFlightsProduct"),i=t.Settings.flights_path||"flights";return n||i},getFlightsPageUrl:function(){return i(this.getFlightsProductPath())},getFlightsTabUrl:function(){return t.Settings.config.flightsUrl?t.Settings.config.flightsUrl:n.WhiteLabelLocation.getFlightsPageUrl()},getFlightsSearchPageUrl:function(n,r){var e=this.getFlightsProductPath(),u=new t.Utils.Uri(i(e)),f;return u.setAnchorParams(n),u.setQueryParams(r),f=u.toString(),f.replace("#","#/result")},getFlightsLightRedirectUrl:function(n){var i=_.map(n,function(n,t){return t+"="+n}).join("&");i&&(i="?"+i);var r=t.Utils.Location.getBaseHref(),u=t.Services.Language.getDisplayLanguageSync(),f=t.Services.Feature.get("overridenFlightsProduct");return f?r+u+"/"+f+"/redirect"+i:r+u+"/flights/redirect"+i},getHotelsPageUrl:function(){return i("hotels")},getHotelsSearchPageUrl:function(n){var u=_.map(n,function(n,t){return t+"="+n}).join("&"),r=i(t.Settings.hotels_path?t.Settings.hotels_path:"hotels")+"#/result?"+u;return t.Settings.home_country&&(r+="&home_country="+t.Settings.home_country),r},getCarHirePageUrl:function(){return i("carhire")},getCarHireSearchPageUrl:function(n,r){var u=new t.Utils.Uri(i(t.Settings.carhire_path?t.Settings.carhire_path:"carhire")),f;return t.Settings.home_country&&(r.home_country=t.Settings.home_country),u.setAnchorParams(n),u.setQueryParams(r),f=u.toString(),f.replace("#","#/result")}};n.ShareLocation={getBaseShareUrl:function(n,t,i){var r=_.map(t,function(n,t){return t+"="+n}).join("&");return n.match(/\/$/)&&(n=n.slice(0,-1)),i?n+"/shared/"+i+"?"+r:n+"/shared?"+r},getMainShareUrl:function(n,t){return this.getBaseShareUrl(n,t)},getResultShareUrl:function(n,t){return this.getBaseShareUrl(n,t,"result")},getItineraryShareUrl:function(n,t){return this.getBaseShareUrl(n,t,"itinerary")},getCalendarShareUrl:function(n,t){return this.getBaseShareUrl(n,t,"calendar")}};n.Location={getHref:function(){return window.location.href},getFullPathName:function(){return window.location.origin+window.location.pathname},getPlainPlaceId:function(n){return typeof n!="string"?"":(_.each(t.Dictionaries.LocationSchemas,function(t){n=n.replace("-"+t,"")}),n)},getBaseHref:function(){var n=document.getElementsByTagName("base"),t=null;return n.length>0&&(t=n[0].href),t},setHref:function(n){window.location.href=n},reload:function(n){n?window.location.reload(!0):window.location.reload()},redirect:function(n){window.location.replace(n)},homeRedirect:function(n){if(!t.Utils.Ui.isWidget()){n=n||"";var r=$("base").attr("href"),i=new t.Utils.Uri(r||window.location.href);i.anchor(n);this.redirect(i.toString())}}}}),function(){var n=function(n,t){this.element=n;this.$element=$(n);this.index=t||0;this.init()};n.prototype.init=function(){this.setIndex();this.$element.on("focus.makeEditable",$.proxy(this._onFocus,this)).on("blur",$.proxy(this._onBlur,this))};n.prototype.setIndex=function(n){this.index=n||this.index;this.$element.attr("tabindex",this.index)};n.prototype._onFocus=function(){$(document).on("keydown.makeEditable",$.proxy(this._onKeyDown,this))};n.prototype._onKeyDown=function(n){n.which===13&&this.$element.trigger("click")};n.prototype._onBlur=function(){$(document).off("keydown.makeEditable")};n.prototype.destroy=function(){this.$element.off(".makeEditable").removeAttr("tabindex")};$.fn.makeFocusable=function(t){return this.each(function(){var r=$(this),i=r.data("makeFocusable");i?typeof t=="number"&&i.setIndex(t):r.data("makeFocusable",i=new n(this,t))})}}();App.module("Utils",function(n,t){n.RoutesFilter={getRoutes:function(){return t.Utils.Ui.isWidget()?window.AppConfigSettings.routes:t.Settings.config.routes},hasPredefinedRoutes:function(){return n.RoutesFilter.getRoutes()&&n.RoutesFilter.getRoutes().length},locationsAsDropdown:function(){return(t.Utils.Ui.isWidget()?window.AppConfigSettings.locationsAsDropdown:t.Settings.config.locationsAsDropdown)&&n.RoutesFilter.hasPredefinedRoutes()},isAvailiableOrigin:function(t){return!n.RoutesFilter.hasPredefinedRoutes()||_.contains(n.RoutesFilter.getOrigins(),t)},isAvailiableDestination:function(t,i){return!n.RoutesFilter.hasPredefinedRoutes()||_.contains(n.RoutesFilter.getDestinations(t),i)},getOrigins:function(){return _.pluck(n.RoutesFilter.getRoutes(),"code")},getDestinations:function(t){var r=n.RoutesFilter.getRoutes(),i,u;if(t){if(i=_.findWhere(n.RoutesFilter.getRoutes(),{code:t}),_.isUndefined(i))return[];r=[i]}return u=_.reduce(r,function(n,t){return n.concat(_.pluck(t.destinations,"code"))},[]),_.uniq(u)},hasPredefinedCarriers:function(){return t.Settings.config.carriers&&t.Settings.config.carriers.length}}});App.module("Utils",function(n,t){var r,i;n.Sliders={getDurationToolTip:function(n,t,i){var r=function(n){var t=Math.ceil(n);switch(i){case"hours":t=$.i18n.t("inspirational-places.filters.hours",{count:t});break;default:t=$.i18n.t("inspirational-places.filters.days",{count:t})}return t};return $.Link({target:'-tooltip-<div class="tooltip"><\/div>',getTooltipText:function(n){return r(n[0])+" - "+r(n[1])},getText:r,method:function(n){var t=r(n);$(this).html("<span>"+t+"<\/span>")}})},getLegDurationTooltip:function(n){var t=function(n){var t=Math.round(n/60);return t>1?$.t("search-result.filter-menu.duration-hrs_plural",{hours:t}):$.t("search-result.filter-menu.duration-hrs_singular",{hours:t})};return $.Link({target:'-tooltip-<div class="tooltip"><\/div>',getTooltipText:function(i){return t(n)+" - "+t(i)},getText:t,method:function(n){var i=t(n);$(this).html("<span>"+i+"<\/span>")}})},getTimeToolTip:function(){var n=function(n){return t.Culture.culture.formatDate(new Date(Math.ceil(n)),{time:"short"})};return $.Link({target:'-tooltip-<div class="tooltip"><\/div>',getTooltipText:function(t){return n(t[0])+" - "+n(t[1])},getText:n,method:function(t){$(this).html("<span>"+n(t)+"<\/span>")}})},getCurrencyToolTip:function(n,i,r){var u=function(i){return n?t.Utils.Ui.wrapPrice(Math.ceil(i),n):i},f=function(n){var i=u(n);return t.Services.Feature.check("filters","b")?$.t("search-result.filter-menu.up-to-price",{price:i}):i};return $.Link({target:'-tooltip-<div class="tooltip"><\/div>',getTooltipText:f,getText:u,method:function(t){if(n){var u=(parseInt(i,10)+parseInt(r,10))/2,e=t>u?"right-align":"left-align";$(this).removeClass("right-align left-align");$(this).addClass(e);$(this).html("<span>"+f(t)+"<\/span>")}}})},getToolTips:function(n,t,i,r){switch(n){case"time":return this.getTimeToolTip(i,r);case"duration":return this.getDurationToolTip(i,r);default:return this.getCurrencyToolTip(t,i,r)}}};r=$.fn.noUiSlider;$.fn.noUiSlider=function(n){r.apply(this,arguments);var i=this,u=n.step||(n.range.max-n.range.min)/20,f=function(n,t,r){_.isArray(n)?n[t]=parseFloat(n[t])+r:n=parseFloat(n)+r;i.val(n,!0)},t=n.aria||{};t.getValueText=t.getValueText||function(n){return Math.round(n)};i.find(".noUi-handle").attr({tabindex:0,role:"slider","aria-label":t.label,"aria-orientation":"horizontal","aria-minvalue":t.minvalue||0,"aria-maxvalue":t.maxvalue||100,"aria-valuenow":t.valuenow||100,"aria-valuetext":t.getValueText(t.valuenow||100)}).off("keydown").on("keydown",function(n){var t=i.val(),e=$(n.target),r=e.hasClass("noUi-handle-lower")?0:1;switch(n.which){case 37:f(t,r,-u);break;case 39:f(t,r,u)}});i.on("set",function(){i.find(".noUi-handle").attr({"aria-valuenow":i.val(),"aria-valuetext":t.getValueText(i.val())});i.find(".tooltip").attr({"aria-hidden":!0})});return this};i=$.Link;$.Link=function(n){var t=i.apply(this,arguments);return n&&(t.getTooltipText=n.getTooltipText,t.getText=n.getText),t};$.Link.prototype=i.prototype});App.module("Utils",function(n,t){var i={Android_2x:"android2x",Android_41:"android41",WinPhone_81:"win-phone-81",WinPhone:"win-phone",iPhone:"apple-iphone",iPad:"apple-ipad",iPad7_0_3:"apple-ipad-703"},r={Safari:"safari",Firefox:"firefox",IE9:"ie9",IE8:"ie8"};n.DeviceClassAppender={process:function(){var n=$("html");t.Utils.Ui.isiPad()?(n.addClass(i.iPad),t.Utils.Ui.isiPad7_0_3()&&n.addClass(i.iPad7_0_3)):t.Utils.Ui.isiPhone()?n.addClass(i.iPhone):t.Utils.Ui.is41Android()?n.addClass(i.Android_41):t.Utils.Ui.isWinPhone()?(n.addClass(i.WinPhone),t.Utils.Ui.isWinPhone81()&&n.addClass(i.WinPhone_81)):t.Utils.Ui.is2xAndroid()&&n.addClass(i.Android_2x)}};n.BrowserClassAppender={process:function(){var n=$("html");t.Utils.Ui.isSafari()?n.addClass(r.Safari):t.Utils.Ui.isFirefox()?n.addClass(r.Firefox):t.Utils.Ui.isIE9()?n.addClass(r.IE9):t.Utils.Ui.isIE8()&&n.addClass(r.IE8)}}});App.module("Utils",function(n,t,i,r,u){n.Spin=function(n,t){if(n instanceof u){t=_.extend({lines:17,length:0,width:2,radius:4,corners:0,rotate:90,direction:1,color:"#000",speed:.9,trail:40,shadow:!1,hwaccel:!1,className:"spinner",zIndex:2e9,top:"50%",left:"50%"},t||{});var i=new Spinner(_.extend(t,{color:n.css("color")})).spin();return n.append(i.el),i}}});App.module("Utils",function(n,t){function u(){var n=window.cookieCompliance;return t.Services.Feature.check("functionalCookieExperience")&&n&&n.isFunctional_cookie_experience&&$.isFunction(n.hasConsent)&&!n.hasConsent()?!1:!0}var r=11,i;n.Storage={setObject:function(n,t){if(u())try{return localStorage.setItem(n,JSON.stringify(t)),!0}catch(i){return!1}},setObjectParam:function(n,t,i){if(u())try{var r=this.getObject(n);return r[t]=i,localStorage.setItem(n,JSON.stringify(r)),!0}catch(f){return!1}},deleteObjectParam:function(n,t){try{var i=this.getObject(n);return delete i[t],localStorage.setItem(n,JSON.stringify(i)),!0}catch(r){return!1}},getObject:function(n){try{var t=localStorage.getItem(n);return t&&JSON.parse(t)}catch(i){return null}},deleteObject:function(n){try{return localStorage.getItem(n)?(localStorage.removeItem(n),!0):!1}catch(t){return!1}},clear:function(){try{return localStorage.clear(),!0}catch(n){return!1}}};n.StateStorage={Base:{invalidateIfNeeded:function(){var t="wl-storage-version",i=n.Storage.getObject(t),u;if(i===null)n.Storage.setObject(t,r);else{if(u=parseInt(i,10),u===r)return!0;n.Storage.clear();n.Storage.setObject(t,r)}}},Flights:{get:function(){return t.Utils.Storage.getObject("saved.search")},getPrev:function(){return t.Utils.Storage.getObject("prev.saved.search")},set:function(n){n!==null&&(n=_.pick(n,"outbounddate","inbounddate","originplace","destinationplace","originplaceText","destinationplaceText","cabinclass","adults","children","infants"));t.Utils.Storage.setObject("saved.search",n)},saveStateAsPrev:function(){var i=n.StateStorage.Flights.get();i&&t.Utils.Storage.setObject("prev.saved.search",i)},getFilterSelections:function(){var n=t.Utils.Storage.getObject("filterSelections"),i;return n&&n.lastUpdate&&(i=moment(n.lastUpdate,t.Settings.datetimePricingServiceFormat),moment().diff(i,"months",!0)>1)?(this.clearFilterSelections(),null):n},getFilterDepartTime:function(n){return n&&n["depart.time"]},getFilterReturnTime:function(n){return n&&n["return.time"]},setFilterSelections:function(n){n.lastUpdate=moment().format(t.Settings.datetimePricingServiceFormat);t.Utils.Storage.setObject("filterSelections",n)},clearFilterSelections:function(){t.Utils.Storage.deleteObject("filterSelections")},clearFilterTime:function(){t.Utils.Storage.deleteObjectParam("filterSelections","depart.time");t.Utils.Storage.deleteObjectParam("filterSelections","return.time")},getSorting:function(){return t.Utils.Storage.getObject("flights.sortObj")},setSorting:function(n){n&&t.Utils.Storage.setObject("flights.sortObj",n)}},Hotels:{get:function(){return t.Utils.Storage.getObject("hotels.search.state")},getPrev:function(){return t.Utils.Storage.getObject("hotels.prev.saved.search")},set:function(n){return n!==null&&(n=_.pick(n,"guests","checkin","checkout","rooms","destination","destinationText","destinationCountry","destinationInfo")),t.Utils.Storage.setObject("hotels.search.state",n)},saveStateAsPrev:function(){var i=n.StateStorage.Hotels.get();i&&t.Utils.Storage.setObject("hotels.prev.saved.search",i)},getSorting:function(){return t.Utils.Storage.getObject("hotels.sortObj")},setSorting:function(n){n&&t.Utils.Storage.setObject("hotels.sortObj",n)}},CarHire:{get:function(){return t.Utils.Storage.getObject("carhire.search.state")},getPrev:function(){return t.Utils.Storage.getObject("carhire.prev.saved.search")},set:function(n){return n!==null&&(n=_.pick(n,"pickupDate","dropoffDate","pickupTime","dropoffTime","pickupPlace","pickupPlaceText","dropoffPlace","dropoffPlaceText","ageGroup","sameDropoffPlace")),t.Utils.Storage.setObject("carhire.search.state",n)},saveStateAsPrev:function(){var i=n.StateStorage.CarHire.get();i&&t.Utils.Storage.setObject("carhire.prev.saved.search",i)}}};i={_getStorageName:function(){throw new Error("Class is abstract. The function should be overwritten by child.");},changeFavorite:function(){throw new Error("Class is abstract. The function should be overwritten by child");},fireUpdateBasketEvent:function(){throw new Error("Class is abstract. The function should be overwritten by child");},getFavorites:function(){return t.Utils.Storage.getObject(this._getStorageName())||[]},setFavorites:function(n){t.Utils.Storage.setObject(this._getStorageName(),n)},getByFingerprint:function(n){var i=this.getFavorites(),t=_.findWhere(i,{fingerprint:n});return t?t:null},removeFavorite:function(n){var t=this.getFavorites(),i=t.length;return i&&(t=_.reject(t,function(t){return t.fingerprint===n}),i!==t.length)?(this.setFavorites(t),!0):!1},soldOutFavorite:function(n){for(var t=this.getFavorites(),u=t.length,r=!1,i=0;i<u;i++)if(t[i].fingerprint===n&&t[i].soldOut===!1){t[i].soldOut=!0;r=!0;break}r&&(this.setFavorites(t),this.fireUpdateBasketEvent(!1))},updatePriceIfNeeded:function(n,i){for(var u=this.getFavorites(),o=u.length,r=null,e=-1,f=0;f<o;f++)if(u[f].fingerprint===n){r=u[f];e=f;break}r&&(i=t.Utils.Ui.ceilPrice(i),r.priceWithoutCurrency!==i&&(r.priceWithoutCurrency=i,r.priceWithCurrency=t.Utils.Ui.wrapPrice(i,t.Services.Currency.getCurrentCurrencyInfo()),r.timestamp=(new Date).getTime(),u[e]=r,this.setFavorites(u),this.fireUpdateBasketEvent(!1)))}};n.FavoritesStorage={Flights:_.extend({},i,{_getStorageName:function(){var n=t.Services.Language.getLanguageSync().toLowerCase(),i=t.Services.Currency.getCurrencySync().toLowerCase(),r=t.Services.HomeCity.getHomeCitySync(),u=r.PlaceId.toLowerCase();return["flights.saved.favorites.",n,".",i,".",u].join("")},fireUpdateBasketEvent:function(n){t.vent.trigger(t.VentActions.FavoritesBasket.UPDATE_FLIGHTS,n)},changeFavorite:function(n){var i=this.getFavorites(),u=_.some(i,function(t){return t.fingerprint===n.fingerprint}),r;u&&n.isFavorite&&this.removeFavorite(n.fingerprint)&&this.fireUpdateBasketEvent(!1);u||n.isFavorite||(r={fingerprint:n.fingerprint,legs:[],originplace:n.originplace,originplaceText:n.originPlace.Name,destinationplace:n.destinationplace,destinationplaceText:n.destinationPlace.Name,outbounddate:n.outbounddate,inbounddate:n.inbounddate,cabinclass:n.cabinclass,adults:n.adults,children:n.children,infants:n.infants,priceWithoutCurrency:t.Utils.Ui.ceilPrice(n.priceWithoutCurrency),priceWithCurrency:n.priceWithCurrency,isOneWay:!n.inbounddate,agentName:n.priceOptions.length&&n.priceOptions[0].priceData.agents.length?n.priceOptions[0].priceData.agents[0].name:"",timestamp:(new Date).getTime(),soldOut:!1},_.each(n.legs,function(n){var t={carriers:[],flight:{stops:{text:n.flight.stops.text,length:n.flight.stops.length}},segments:[]};t.agent=_.pick(n.agent,"name","imageUrl");t.flight.duration=_.pick(n.flight.duration,"days","hours","min");_.each(n.carriers,function(n){t.carriers.push({displayCode:n.displayCode})});_.each(n.segments,function(n){t.segments.push({originStation:{Code:n.originStation&&n.originStation.Code||"",Name:n.originStation&&n.originStation.Name||""},departure:{time:n.departure.time},destinationStation:{Code:n.destinationStation&&n.destinationStation.Code||"",Name:n.destinationStation&&n.destinationStation.Name||""},arrival:{time:n.arrival.time,daysShift:n.arrival.daysShift}})});r.legs.push(t)}),i.push(r),this.setFavorites(i),this.fireUpdateBasketEvent(!0))}}),Hotels:_.extend({},i,{_getStorageName:function(){var n=t.Services.Language.getLanguageSync().toLowerCase(),i=t.Services.Currency.getCurrencySync().toLowerCase(),r=t.Services.HomeCity.getHomeCitySync(),u=r.PlaceId.toLowerCase();return["hotels.saved.favorites.",n,".",i,".",u].join("")},fireUpdateBasketEvent:function(n){t.vent.trigger(t.VentActions.FavoritesBasket.UPDATE_HOTELS,n)},changeFavorite:function(n){var i=this.getFavorites(),r=_.find(i,function(t){return t.fingerprint===n.fingerprint});r&&n.favorite&&this.removeFavorite(n.fingerprint)&&this.fireUpdateBasketEvent(!1);r||n.favorite||(i.push(_.extend({},_.pick(n,"name","fingerprint","description","imageUrl","stars","distance","distanceKm","hasPool","hasParking","hasGym","hasWiFi","rating","ratingDesc","ratingClass","agentImageUrl","destination","destinationText","checkin","checkout","guests","rooms","link"),{priceWithCurrency:n.wrappedPrice,priceWithoutCurrency:t.Utils.Ui.ceilPrice(n.priceWithoutCurrency),timestamp:(new Date).getTime(),soldOut:!1})),this.setFavorites(i),this.fireUpdateBasketEvent(!0))}}),CarHire:_.extend({},i,{_getStorageName:function(){var n=t.Services.Language.getLanguageSync().toLowerCase(),i=t.Services.Currency.getCurrencySync().toLowerCase(),r=t.Services.HomeCity.getHomeCitySync(),u=r.PlaceId.toLowerCase();return["carhire.saved.favorites.",n,".",i,".",u].join("")},fireUpdateBasketEvent:function(n){t.vent.trigger(t.VentActions.FavoritesBasket.UPDATE_CARHIRE,n)},changeFavorite:function(n){var i=this.getFavorites(),r=_.find(i,function(t){return t.fingerprint===n.fingerprint}),u;r&&n.favorite&&this.removeFavorite(n.fingerprint)&&this.fireUpdateBasketEvent(!1);r||n.favorite||(u=_.extend(_.pick(n,"vehicle","pickupPlace","dropoffPlace","pickupDate","pickupTime","dropoffDate","dropoffTime","ageGroup","sameDropoffPlace","pickupPlaceText","dropoffPlaceText","seats","air_conditioning","manual","car_class_id","value_add","fingerprint"),{image:{url:n.image.url},webSite:{name:n.webSite.name,image_url:n.webSite.image_url},carClass:{name:n.carClass.name},priceWithoutCurrency:t.Utils.Ui.ceilPrice(n.price_all_days),priceWithCurrency:n.wrappedPrice,timestamp:(new Date).getTime(),soldOut:!1}),i.push(u),this.setFavorites(i),this.fireUpdateBasketEvent(!0))}})}});App.module("Utils",function(n,t,i){var f=null,o=function(n){return n.length===0?!1:n.css("display")!=="none"},e,u,r,s;n.Ui={bodySelector:"#skyscanner-white-label body, div#skyscanner-white-label",Orientation:{LANDSCAPE:"landscape",PORTRAIT:"portrait"},isFlights:_.once(function(){return t.Settings.wlType==="Flights"}),isHotels:_.once(function(){return t.Settings.wlType==="Hotels"}),isCarHire:_.once(function(){return t.Settings.wlType==="CarHire"}),isWidget:function(){return!1},isMobileView:function(){return o($("#mobile-check-container"))},isTabletView:function(){return o($("#tablet-check-container"))},isDesktopView:function(){return!this.isMobileView()&&!this.isTabletView()},getDeviceViewType:function(){return this.isMobileView()?"mobile":this.isTabletView()?"tablet":this.isDesktopView()?"desktop":void 0},isMobileDevice:_.once(function(){if(f===null){var n=!1;(function(t){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|nexus|playbook|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|Kindle|Silk.*Accelerated|Android.*\b(KFTT|KFOTE)\b|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4)))&&(n=!0)})(navigator.userAgent||navigator.vendor||window.opera);f=n}return f}),isPreview:_.once(function(){var i=t.Utils.Location.getHref(),n=i.match(/http.+\/preview/ig);return n?n.length>0:!1}),getAndroidVersion:_.once(function(){var n=navigator.userAgent.match(/Android\s([0-9\.]*)/);return n?n[1]:!1}),isWinPhone81:_.once(function(){var n=navigator.userAgent.match(/(Windows Phone 8\.1).+(iemobile)/ig);return n?n.length>0:!1}),isWinPhone:_.once(function(){var n=navigator.userAgent.match(/(Windows Phone).+(iemobile)/ig);return n?n.length>0:!1}),isiPad:_.once(function(){return navigator.userAgent.match(/iPad/i)!==null}),isiPad7_0_3:_.once(function(){return navigator.userAgent.match(/iPad.+(7_0_3)/i)!==null}),isiPhone:_.once(function(){return navigator.platform.indexOf("iPhone")!==-1||navigator.platform.indexOf("iPod")!==-1}),isAppleDevice:_.once(function(){var t=n.Ui;return t.isiPhone()||t.isiPad()}),isSafari:_.once(function(){var n=navigator.userAgent.toLowerCase();return n.indexOf("safari")!==-1&&n.indexOf("chrome")===-1}),is2xAndroid:_.once(function(){return parseInt(n.Ui.getAndroidVersion(),10)===2}),is41Android:_.once(function(){var t=n.Ui.getAndroidVersion();return t?t.match(/^4\.1\.|^4\.1$/)!==null:!1}),isFirefox:_.once(function(){return n.Ui.isFirefoxFromUserAgent(navigator.userAgent)}),isFirefoxFromUserAgent:function(n){return n.toLowerCase().indexOf("firefox")>-1},isIE8:_.once(function(){return/MSIE 8/i.test(navigator.userAgent)}),isIE9:_.once(function(){return/MSIE 9/i.test(navigator.userAgent)}),isSlowDevice:_.once(function(){var t=n.Ui;return window.ltIE9||(t.isMobileView()||t.isTabletView())&&(t.is2xAndroid()||t.is41Android())}),getBrowserInfo:function(n,t,i){n=n||navigator.userAgent;t=t||navigator.appName;i=i||navigator.appVersion;var f=n.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[],u=n.match(/\bOPR\/(\d+)/),r={browser:null,version:null,os:null};return/trident/i.test(f[1])?(u=/\brv[ :]+(\d+)/g.exec(n)||[],r.browser="MSIE",r.version=u[1]):f[1]==="Chrome"&&u?(r.browser="Opera",r.version=u[1]):(r.browser=f[1]?f[1]:t,r.version=f[2]?f[2]:i,u=n.match(/version\/(\d+)/i),u&&(r.version=u[1])),_.each(["windows","linux","android","ios","blackberry","macintosh"],function(t){n.toLowerCase().indexOf(t)>-1&&(r.os=t)}),u=parseFloat(r.version),r.version=_.isNaN(u)?r.version:u,r},getFilterMenuLeftPosition:function(n,i,r,u){u=_.isUndefined(u)?10:u;var e=t.Utils.Ui.isMobileView()||t.Utils.Ui.isTabletView(),f=i.offset().left+(e?0:-r.offset().left)+i.width()/2-n.width()/2,s=r.width()-f+(e?r.offset().left:0),o=n.width()-s;return f=f-(e?r.offset().left:0)-(o>0?o+u:0),Math.max(u,f)},scrollTo:function(n){t.Utils.Ui.isMobileView()?window.scrollTo(0,n):$("html, body").animate({scrollTop:n},400)},scrollToElement:function(n,i){var r=n.offset().top+i;t.Utils.Ui.scrollTo(r)},scrollToCenter:function(n){var i=n.closest(".js-scrollable-item"),t;if(i.length!==0&&(t=i.closest(".js-scrollable"),t.length!==0)){var u=t.scrollLeft(),f=t.width()/2,e=i.width()/2,o=i.position().left,r=t.css("overflow-x");(r==="auto"||r==="scroll")&&($("body").attr("data-js-scroll",!0),t.scrollLeft(u+o-f+e))}},makeScrollable:function(n){n=n[0];var t=0,i=0;n.addEventListener("touchstart",function(n){t=this.scrollTop+n.touches[0].pageY;i=this.scrollLeft+n.touches[0].pageX},!1);n.addEventListener("touchmove",function(n){(this.scrollTop<this.scrollHeight-this.offsetHeight&&this.scrollTop+n.touches[0].pageY<t-5||this.scrollTop!==0&&this.scrollTop+n.touches[0].pageY>t+5)&&n.preventDefault();(this.scrollLeft<this.scrollWidth-this.offsetWidth&&this.scrollLeft+n.touches[0].pageX<i-5||this.scrollLeft!==0&&this.scrollLeft+n.touches[0].pageX>i+5)&&n.preventDefault();this.scrollTop=t-n.touches[0].pageY;this.scrollLeft=i-n.touches[0].pageX},!1)},inViewPort:function(n){var r=n.offset(),t=r?n.offset().top:0,u=n.height(),i=window.scrollY,f=window.innerHeight;return t>=i&&t+u<=i+f},scrollToBelowViewPortElement:function(n,i){if(n&&n.is(":visible")){i=i||0;var r=n.offset(),e=r?r.top:0,o=n.height(),u=e+o+i,s=window.scrollY,f=window.innerHeight;u>s+f&&t.Utils.Ui.scrollTo(u-f)}},wrapPrice:function(n,i){typeof i=="string"&&(i=t.Dictionaries.SupportedCurrenciesByCode[i]);n=this.transformPrice(n,i.ThousandsSeparator);var r=$.parseJSON(i.SpaceBetweenAmountAndSymbol)?" ":"",u=$.parseJSON(i.SymbolOnLeft),f=u?i.Symbol+r:"",e=u?"":r+i.Symbol;return f+n+e},quoteDateTimeMessage:function(n){return _.isNumber(n)&&n>=0&&n<16?$.t("slider.indicative-pricing-found-"+Math.round(n)+"-days-ago"):""},ceilPrice:function(n){return n=Math.ceil(n*100)/100,parseInt(Math.ceil(Math.abs(n||0)),10)},transformPrice:function(n,t){t=t?t:"";var i=this.ceilPrice(n).toString(),r=i.length>3?i.length%3:0;return(r?i.substr(0,r)+t:"")+i.substr(r).replace(/(\d{3})(?=\d)/g,"$1"+t)},detectOrientation:function(){var n=$(window);return n.outerWidth(!0)>n.outerHeight(!0)?this.Orientation.LANDSCAPE:this.Orientation.PORTRAIT},showLoadError:function(){var n=$.i18n.t("errors-429.limit-exceeded");$("#errors").html('<div class="js-errors container token-error">'+n+"<\/div>")},deactivateValidationErrors:function(n){n.find(".js-context-error.active").removeClass("active").removeClass("main-error")},showValidationErrors:function(n,i,r){var e=this,u=this.isMobileView(),f;_.isObject(i)&&!_.isEmpty(i)&&(f=n.find(".js-context-error.active"),f.length!==0&&this.deactivateValidationErrors(n),setTimeout(_.bind(function(){var h=_.keys(i),f=_.filter(r,function(n){return _.contains(h,n.key)}),s,o;u&&f&&f.length>0&&(s=_.max(f,function(n){return n.weight}),s.mainError=!0);_.each(_.first(f,3),_.bind(function(t){var i=this.find(".js-error-"+t.key);i.addClass("active");i.stop().animate({opacity:1},{duration:1}).animate({opacity:0},{duration:6e3,complete:function(){e.deactivateValidationErrors(n)}});t.isValidationError||i.addClass("only-show");!!t.mainError&&u&&i.addClass("main-error")},n));o=n.find(".js-context-error:visible");o[0]&&!t.Utils.Ui.inViewPort(o)&&t.Utils.Ui.scrollToElement(n.find(".js-context-error:visible"),-10)},this),5))},_currentScrollTop:0,onOpenFullscreenModal:function(){this._currentScrollTop=$(window).scrollTop()},onCloseFullscreenModal:function(){this.scrollTo(this._currentScrollTop,0)},_concatPriceChangeEventLabel:function(n,i){return t.Utils.Ui.wrapPrice(n.obsoletePrice||n.price,i)+"_"+this.wrapPrice(n.price,i)}};_.extend(n.Ui,i.Events);e=n.Ui.detectOrientation();u=n.Ui.getDeviceViewType();$(window).on("resize",function(){var t,i;n.Ui.isMobileDevice()&&(t=n.Ui.detectOrientation(),t!==e&&(e=t,n.Ui.trigger("orientation:change",t)));i=n.Ui.getDeviceViewType();i!==u&&(n.Ui.trigger("breakpoint:change",i,u),u=i)});r=document.body;$(window).on("scroll",function(){r&&r.classList&&(clearTimeout(s),r.classList.contains("disable-hover")||r.classList.add("disable-hover"),s=setTimeout(function(){r.classList.remove("disable-hover")},250))})});App.module("Utils",function(n){function u(n){var t=i.uri_parser,r=t.exec(n||"");return _.object(_.map(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],function(n,t){return[n,r[t]||""]}))}function r(n){return n&&(n=decodeURIComponent(n),n=n.replace(i.pluses," ")),n}function f(n){var f,u,t,r,o,s,e=[];if(typeof n=="undefined"||n===null||n==="")return e;for(n.indexOf("?")===0&&(n=n.substring(1)),f=n.toString().split(i.query_separator),u=0;u<f.length;u++)t=f[u],r=t.indexOf("="),r!==0&&(o=decodeURIComponent(t.substring(0,r)),s=decodeURIComponent(t.substring(r+1)),e.push(r===-1?[t,null]:[o,s]));return e}function t(n){this.uriParts=u(n);this.queryPairs=f(this.uriParts.query)}var i={starts_with_slashes:/^\/+/,ends_with_slashes:/\/+$/,pluses:/\+/g,query_separator:/[&;]/,uri_parser:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/};_.each(["protocol","userInfo","host","port","path","anchor"],function(n){t.prototype[n]=function(t){if(t!==undefined)this.uriParts[n]=t;else return this.uriParts[n]}});t.prototype.getQueryParam=function(n){var t=_.find(this.queryPairs,function(t){return t[0]===n});return t?t[1]:null};t.prototype.getQueryParamsObj=function(){return _.object(this.queryPairs)};t.prototype.getQueryParams=function(n){var t=_.filter(this.queryPairs,function(t){return t[0]===n});return _.map(t,function(n){return n[1]})};t.prototype.getAnchorParams=function(){var f=this.anchor(),n={},r,e,u,t,i;if(f.indexOf("?")<0)return n;if(r=f.split("?"),r.length===2){for(e=r[1],u=e.split("&"),t=0;t<u.length;t++)i=u[t].split("="),n[i[0]]=i.length>1?i[1]:null;return n}return n};t.prototype.setAnchorParams=function(n){var i=this.anchor(),t=_.filter(_.map(n,function(n,t){return t&&n!==undefined?t.toString()+"="+n.toString():null}),function(n){return n!=null}).join("&"),r;i.indexOf("?")<0?t&&this.anchor(i+"?"+t):(r=i.split("?"),t?this.anchor(r[0]+"?"+t):this.anchor(r[0]))};t.prototype.setQueryParams=function(n){_.isObject(n)&&_.each(n,_.bind(function(n,t){this.addQueryParam(t,n,0)},this))};t.prototype.deleteQueryParam=function(n,t){var i,u,f=arguments,e=[];return _.each(this.queryPairs,function(o){i=r(o[0])===r(n);u=o[1]===t;(f.length!==1||i)&&(f.length!==2||i&&u)||e.push(o)}),this.queryPairs=e,this};t.prototype.addQueryParam=function(n,t,i){return arguments.length===3&&i!==-1?(i=Math.min(i,this.queryPairs.length),this.queryPairs.splice(i,0,[n,t])):arguments.length>0&&this.queryPairs.push([n,t]),this};t.prototype.replaceQueryParam=function(n,t,i){var e=-1,u,f;if(arguments.length===3){for(u=0;u<this.queryPairs.length;u++)if(f=this.queryPairs[u],r(f[0])===r(n)&&decodeURIComponent(f[1])===r(i)){e=u;break}this.deleteQueryParam(n,i).addQueryParam(n,t,e)}else{for(u=0;u<this.queryPairs.length;u++)if(f=this.queryPairs[u],r(f[0])===r(n)){e=u;break}this.deleteQueryParam(n);this.addQueryParam(n,t,e)}return this};t.prototype.query=function(){for(var n="",t,i=0;i<this.queryPairs.length;i++)t=this.queryPairs[i],n.length>0&&(n+="&"),t[1]===null?n+=t[0]:(n+=t[0],n+="=",t[1]&&(n+=encodeURIComponent(t[1])));return n.length>0?"?"+n:n};t.prototype.origin=function(){var n=this.scheme();return n==="file://"?n+this.uriParts.authority:(this.userInfo()&&this.host()&&(n+=this.userInfo(),this.userInfo().indexOf("@")!==this.userInfo().length-1&&(n+="@")),this.host()&&(n+=this.host(),this.port()&&(n+=":"+this.port())),n)};t.prototype.scheme=function(){var n="";return this.protocol()&&(n+=this.protocol(),this.protocol().indexOf(":")!==this.protocol().length-1&&(n+=":"),n+="//"),n};t.prototype.toString=function(){var t,n=this.origin();return t=this.path(),i.ends_with_slashes.test(n)||i.starts_with_slashes.test(t)?(n&&n.replace(i.ends_with_slashes,"/"),t=t.replace(i.starts_with_slashes,"/")):n+="/",n+=t,this.query().toString()&&(n+=this.query().toString()),this.anchor()&&(this.anchor().indexOf("#")!==0&&(n+="#"),n+=this.anchor()),n};t.removeBackslashes=function(n){return n.replace(/([^:]\/)\/+/g,"$1")};t.getTrackingParamsFromUrl=function(){if(!window||!window.location||!window.location.search)return{};var n=["utm_medium","utm_campaign","utm_source","associateid","ksh_id","kpid"],t=window.location.search.substr(1),i=_.map(t.split("&"),function(n){var t=n.split("=");return[t[0],t[1]]});return _.object(_.filter(i,function(t){return t[1]&&n.indexOf(t[0])!==-1}))};n.Uri=t});App.module("Utils",function(n,t){n.UrlDispatcher={processUrl:function(){var r=new t.Utils.Uri(t.Utils.Location.getHref()),n=r.getAnchorParams(),i=r.getQueryParamsObj(),h=!i.currency&&!i.market&&!i.home_city&&!i.home_country,u=i.currency,f,e,o,s;return u===null&&(u=n.currency),f=i.market,f===null&&(f=n.market),e=i.home_city,e===null&&(e=n.home_city),o=i.home_country,o===null&&(o=n.home_country),t.Settings.mock_data=i.mock_data==="true"||n.mock_data==="true"?!0:!1,u||f||e||o?(u&&(r.deleteQueryParam("currency"),n.currency=undefined,s=_.values(t.Dictionaries.CurrencyCountryMapping),s.indexOf(u)>=0&&t.Services.Currency.Resolvers.localstorage(u)),f&&(r.deleteQueryParam("market"),n.market=undefined,t.Services.HomeCity.Resolvers.localstorage({PlaceId:f})),e&&(r.deleteQueryParam("home_city"),n.home_city=undefined,t.Services.HomeCity.Resolvers.localstorage({PlaceId:e})),o&&(r.deleteQueryParam("home_country"),n.home_country=undefined,t.Services.Market.Resolvers.localstorage({CountryId:o},"url")),r.setAnchorParams(n),t.Utils.Location.redirect(r.toString()),h&&t.Utils.Location.reload(!0),!1):!0}}});App.module("Services",function(n,t){n.Culture={_cache:{},get:function(n){var i=new $.Deferred,r=t.Settings.baseUrl+"cultureservice/cldr/"+n;return n=n.toLowerCase(),this._cache[n]?i.resolve(this._cache[n]):$.ajax({url:r,dataType:"json"}).done(_.bind(function(t){this._cache[n]=t;i.resolve(this._cache[n])},this)).fail(i.reject),i.promise()}}});App.module("Services",function(n,t,i,r,u){var f={currency:{invoked:!1,resolved:!1,promise:undefined}},s=null,o=null,e={scaffold:function(){var n=new u.Deferred;return t.Settings.config.currency&&t.Settings.config.isScaffold?n.resolve(t.Settings.config.currency):n.reject(),n.promise()},url:function(){var n=new u.Deferred,r=new t.Utils.Uri(t.Utils.Location.getHref()),i=r.getAnchorParams();return i.currency?_.indexOf(_.values(t.Dictionaries.CurrencyCountryMapping),i.currency)!==-1?n.resolve(i.currency):n.reject():n.reject(),n.promise()},localstorage:function(){var n=new u.Deferred,i=t.Utils.Storage.getObject("culture.currency");return i&&t.Dictionaries.SupportedCurrenciesByCode[i]?n.resolve(i):n.reject(),n.promise()},settings:function(){var n=new u.Deferred,i=t.Settings.config.currency;return i?n.resolve(i):n.reject()},market:function(){var n=new u.Deferred;return t.Services.Market.getMarket().done(function(i){_.has(t.Dictionaries.CurrencyCountryMapping,i)?n.resolve(t.Dictionaries.CurrencyCountryMapping[i]):n.reject()}).fail(function(){n.reject()}),n.promise()},defaultFallback:function(){var n=new u.Deferred;return n.resolve(t.Dictionaries.CurrencyCountryMapping.UK)}},h={localstorage:function(n){t.Utils.Storage.setObject("culture.currency",n)}};n.Currency={getCurrency:function(){var n;if(f.currency.invoked&&f.currency.promise!==undefined)return f.currency.promise.promise();n=new u.Deferred;f.currency.invoked=!0;f.currency.promise=n;var t=[e.scaffold,e.url,e.localstorage,e.settings,e.market,e.defaultFallback],i=0,r=function(u){u().then(function(t){s=t;f.currency.resolved=!0;n.resolve(t)},function(){i++;i<t.length?r(t[i]):n.reject()})};return r(t[0]),n.promise()},getCurrencySync:function(){if(!f.currency.resolved)throw new Error("Currency service did not invoked. Using sync function is not allowed.");return s},getCurrentCurrencyInfo:function(){var n=this.getCurrencySync();return o||(o=t.Dictionaries.SupportedCurrenciesByCode[n]),o},getDefaultCurrencyForCountry:function(){var n=new u.Deferred;return e.market().done(function(t){n.resolve(t)}).fail(function(){n.reject()}),n.promise()},setCurrency:function(t){if(typeof n.Currency.Resolvers.onSet=="function")n.Currency.Resolvers.onSet(t)},getAvailableCurrencies:function(){var n=new u.Deferred;return n.resolve(t.Dictionaries.SupportedCurrencies)},getInfoByCurrencyCode:function(n){var i=new u.Deferred;return i.resolve(t.Dictionaries.SupportedCurrenciesByCode[n])},reset:function(){f.currency.resolved=!1;f.currency.invoked=!1;s=null;o=null}};_.extend(n.Currency,i.Events);n.Currency.Resolvers=h;n.Currency.Providers=e});App.module("Services",function(n){function t(){var n=window.AppSettings||window.AppConfigSettings||{};return n.features||{}}n.Feature={check:function(n,i){var r=t();return n?r[n]?i?r[n]===i:r[n]&&r[n]!="off":!1:!1},checkHash:function(n){var t;if(!n||typeof n!="object")return!1;for(t in n)if(!this.check(t,n[t]))return!1;return!0},get:function(n){var i=t();return n?i[n]:i}}});App.module("Services",function(n,t,i,r,u){var f=new t.Utils.Cache(20),e=function(n){var i=[],r=[];_.each(n.Continents,function(n){i=_.union(i,n.Countries)});var u=_.map(i,function(n){return{code:n.Id,name:n.Name,ThumbnailUrl:n.ThumbnailUrl,BannerUrl:n.BannerUrl,cities:_.map(n.Cities,function(n){var t=n.SingleAirportCity&&_.isObject(n.Airports[0]);return _.extend(n,{cityCode:n.Id,name:n.Name,code:t?n.Airports[0].Id:n.Id,fullName:t?n.Airports[0].Name:n.Name,ThumbnailUrl:n.ThumbnailUrl,BannerUrl:n.BannerUrl})})}}),e=o(u),f=[];return _.each(t.Dictionaries.Continents,function(n){var t=_.filter(u,function(t){return _.contains(n.countries,t.code)}),i;r=_.union(r,t);i={id:n.id,name:n.name,order:n.order,countries:t};f.push(i)}),{continents:f,allcountriesProcessed:r,placesLookup:e,rawData:n}},o=function(n){var t={};return _.each(n,function(n){t[n.code]=n;_.each(n.cities,function(n){t[n.Id]=n;_.each(n.Airports,function(n){t[n.Id]=n})})}),t};n.GeoService={getGeoInfo:function(i,r,o,s,h,c){i=_.isUndefined(i)?!0:i;r=_.isUndefined(r)?!0:r;var l=s||new u.Deferred;return h=h||0,u.when(t.Services.Language.getLanguage(),t.Services.Session.getToken(c===!0)).done(function(c,a){var p=o?"&specificcountries="+o.join(";"):"",v=_.template("<%= url %>apiservices/geo/v1.0/"+"?popularcountries=<%= popularcountries %>&popularcities=<%= popularcities %><%= specificcountries %>&languageid=<%= lang %>&apiKey=<%= apiKey %>&includeImages=true",{url:t.Settings.apiUrl,lang:c,popularcountries:i.toString(),popularcities:r.toString(),specificcountries:p,apiKey:encodeURIComponent(a)}),y=f.get(v);if(y!==null)return l.resolve(y);u.get(v).done(function(n){var t=e(n);f.set(v,t);l.resolve(t)}).fail(function(u){if(h>2){Logger("api-service").error(_.template("Can't obtain data from <%= url %>",{url:v}));l.reject();return}switch(u.status){case 419:case 403:n.GeoService.getGeoInfo(i,r,o,l,++h,!0);break;case 429:t.tracking.trackEvent("error","api-service:getGeoInfo","429 Too Many Requests");setTimeout(function(){n.GeoService.getGeoInfo(i,r,o,l,++h)},3e3);break;default:Logger("api-service").error(v+" "+u.status+" Server Error");t.tracking.trackEvent("error","api-service:getGeoInfo",u.status+" Server Error");s.reject(u)}})}).fail(function(){l.reject()}),l.promise()},mapFlightsToHotels:function(i,r){var f=new u.Deferred,e;return!_.isArray(i)&&_.isString(i)&&(i=[i]),_.isArray(i)?(e="/concordance/flights-to-hotels/",u.ajax({url:e,type:"POST",data:i.map(function(n){return"SKY:"+n}).join(","),dataType:"json"}).done(function(n){n=Object.keys(n).reduce(function(t,i){return t[i.substr(4)]=n[i],t},{});_.isObject(n)?f.resolve(n):(Logger("geo-service").error("mapFlightsToHotels error: Returned data format is invalid"),f.reject())}).fail(function(u){u&&(u.status===419||u.status===403)?r<t.Services.Session.MAX_TOKEN_ATTEMPTS?n.GeoService.mapFlightsToHotels(i,++r).done(function(n){f.resolve(n)}).fail(function(n){f.reject(n)}):(Logger("geo-service").fatal("mapFlightsToHotels token error: "+JSON.stringify(u)),f.reject(u)):(Logger("geo-service").fatal("mapFlightsToHotels error: "+JSON.stringify(u)),f.reject(u))})):f.reject(),f.promise()},mapHotelsToFlights:function(i,r){var f=new u.Deferred,e;return!_.isArray(i)&&_.isString(i)&&(i=[i]),_.isArray(i)?(r=r||0,e="/concordance/hotels-to-flights/",u.ajax({url:e,type:"POST",data:i.join(","),dataType:"json"}).done(function(n){n=Object.keys(n).reduce(function(t,i){return t[i]=n[i],t},{});n&&_.isObject(n)?f.resolve(n.results):(Logger("geo-service").error("mapHotelsToFlights error: Returned data format is invalid"),f.reject())}).fail(function(u){u&&(u.status===419||u.status===403)?r<t.Services.Session.MAX_TOKEN_ATTEMPTS?n.GeoService.mapFlightsToHotels(i,++r).done(function(n){f.resolve(n)}).fail(function(n){f.reject(n)}):(Logger("geo-service").fatal("mapHotelsToFlights token error: "+JSON.stringify(u)),f.reject(u)):(Logger("geo-service").fatal("mapHotelsToFlights error: "+JSON.stringify(u)),f.reject(u))})):f.reject(),f.promise()},invalidateCache:function(){f.clear()}}});App.module("Services",function(n,t,i,r,u){var f={localizationService:{invoked:!1,promise:undefined},homeCity:{invoked:!1,resolved:!1,promise:undefined}},s=null,o=function(n,i){var r=new u.Deferred,f;switch(i){case"city-id":u.when(t.Services.Language.getLanguage(),t.Services.Session.getToken()).done(function(i,u){t.Services.PlacesApi.getPlaceById(n,{market:"UK",currency:"GBP",locale:i,token:u}).done(function(n){r.resolve(n)}).fail(function(){r.reject()})}).fail(function(){r.reject()});break;case"user-ip":f="<%= url %>apiservices/autosuggest/v1.0/UK/GBP/"+"<%= locale %>/"+"?query=<%= ip %>-ip"+"&apikey=<%= apiKey %>";u.when(t.Services.Language.getLanguage(),t.Services.Session.getToken()).done(function(i,e){var s=_.template(f,{url:t.Settings.apiUrl,locale:i,ip:n,apiKey:encodeURIComponent(e)}),h=Math.floor((new Date).getTime()/1e3),o=t.Utils.Storage.getObject("skyscanner.home.city.cached.by.ip");o!==null&&h-o.timestamp>3600&&!!o.obj?r.resolve(o.obj):u.get(s).done(function(n){if(n.Places&&n.Places.length>0){var i={obj:n.Places[0],timestamp:Math.floor((new Date).getTime()/1e3)};t.Utils.Storage.setObject("skyscanner.home.city.cached.by.ip",i);r.resolve(n.Places[0])}else r.reject()}).fail(function(){r.reject()})}).fail(function(){r.reject()});break;default:r.reject()}return r.promise()},e={url:function(){var n=new u.Deferred,r=new t.Utils.Uri(t.Utils.Location.getHref()),i=r.getAnchorParams();return i.homecity?o(i.homecity,"city-id").done(function(t){n.resolve(t)}).fail(function(){n.reject()}):n.reject(),n.promise()},checkLockedAirport:function(){var n=new u.Deferred;return t.Settings.config.originplace||n.reject(),t.Services.Feature.check("lockAirport","on")||t.Settings.config.lockAirport?o(t.Settings.config.originplace,"city-id").done(function(t){n.resolve(t)}).fail(function(){n.reject()}):n.reject(),n.promise()},localstorage:function(){var n=new u.Deferred,i=t.Utils.Storage.getObject("culture.homecity");return i?o(i,"city-id").done(function(t){n.resolve(t)}).fail(function(){n.reject()}):n.reject(),n.promise()},settings:function(){var n=new u.Deferred,i=t.Settings.config.city;return i?o(i,"city-id").done(function(t){n.resolve(t)}).fail(function(){Logger("home-city-service").error(_.template("Settings provider. Can't find place with city-id=<%= value %>",{value:i}));n.reject()}):n.reject(),n.promise()},localizationService:function(){if(f.localizationService.invoked&&f.localizationService.promise!==undefined)return f.localizationService.promise.promise();var n=new u.Deferred;return f.localizationService.invoked=!0,f.localizationService.promise=n,t.Services.Session.getUserIp().done(function(t){o(t,"user-ip").done(function(t){n.resolve(t)}).fail(function(){n.reject()})}).fail(function(){Logger("home-city-service").error("Localization service failure. Can't obtain user ip. Have to use default home city as a fallback.");n.reject()}),n.promise()},defaultFallback:function(){var n=new u.Deferred;return n.resolve({PlaceId:"LOND-sky",PlaceName:"London",CountryId:"UK-sky",RegionId:"",CityId:"LOND-sky",CountryName:"United Kingdom"})}},h={localstorage:function(n){n.PlaceId=n.PlaceId.replace("-sky","");t.Utils.Storage.setObject("culture.homecity",n.PlaceId)}};n.HomeCity={getHomeCity:function(){var n;if(f.homeCity.invoked&&f.homeCity.promise!==undefined)return f.homeCity.promise.promise();n=new u.Deferred;f.homeCity.invoked=!0;f.homeCity.promise=n;var i=[e.url,e.checkLockedAirport,e.localstorage,e.settings,e.localizationService,e.defaultFallback],t=0,r=function(u){u().then(function(i){t!==0&&h.localstorage(i);s=i;f.homeCity.resolved=!0;n.resolve(i)},function(){t++;t<i.length?r(i[t]):(Logger("home-city-service").fatal("getHomeCity failure. Something's wrong with providers sequence."),n.reject())})};return r(i[0]),n.promise()},getHomeCitySync:function(){var n="homeCityServiceRestarting";if(f.homeCity.resolved)t.Utils.Storage.deleteObject(n);else if(t.Utils.Storage.getObject(n))throw new Error("HomeCity service did not invoked. Using sync function is not allowed.");else t.Utils.Storage.setObject(n,!0),window.location.reload();return s},getMarket:function(){var t=new u.Deferred;return n.HomeCity.getHomeCity().done(function(n){var i=n.CountryId.replace("-sky","");t.resolve(i)}).fail(function(){Logger("home-city-service").error("getMarket failure");t.reject()}),t.promise()},getMarketSync:function(){var n=this.getHomeCitySync();return n.CountryId.replace("-sky","")},setHomeCity:function(t){if(typeof n.HomeCity.Resolvers.onSet=="function")n.HomeCity.Resolvers.onSet(t)},reset:function(){f.localizationService.invoked=!1;f.homeCity.invoked=!1;f.homeCity.resolved=!1;s=null}};_.extend(n.HomeCity,i.Events);n.HomeCity.Resolvers=h;n.HomeCity.Providers=e});App.module("Services",function(n,t,i,r,u){var o="anywhere",f={getGeoData:{invoked:!1,promise:null},getData:{invoked:!1,promise:null},attributions:{invoked:!1,promise:null}},e;n._getBrowseRoutes=function(i,r,f,e){i=i||new u.Deferred;f=f||0;var o=_.template("<%= url %>apiservices/browseroutes/v1.0/<%= market %>/<%= currency %>/<%= locale %>/<%= homecity %>/<%= country %>/anytime/anytime?apiKey=",{url:t.Settings.apiUrl,currency:r.currency,market:r.market,locale:r.locale,country:r.country,homecity:r.homecity.PlaceId});return t.Services.Session.getToken(e===!0).done(function(e){u.ajax({url:o+encodeURIComponent(e)}).done(function(n){n.currency=r.currency;n.market=r.market;i.resolve(n)}).fail(function(u){if(f>2){Logger("inspirational-service").error("too many failed attemps");i.reject(u);return}switch(u.status){case 419:case 403:n._getBrowseRoutes(i,r,++f,!0);break;case 429:t.tracking.trackEvent("error","inspirational-service:browseroutes","429 Too Many Requests");setTimeout(function(){n._getBrowseRoutes(i,r,++f)},3e3);break;default:Logger("inspirational-service").error(o+" "+u.status+" Server Error");t.tracking.trackEvent("error","inspirational-service:browseroutes",u.status+" Server Error");i.reject(u)}})}).fail(function(){i.reject()}),i.promise()};e=function(){if(f.getData.invoked)return f.getData.promise.promise();var i=new u.Deferred;return f.getData.invoked=!0,f.getData.promise=i,u.when(t.Services.Currency.getCurrency(),t.Services.HomeCity.getHomeCity(),t.Services.Market.getMarket(),t.Services.Language.getLanguage()).done(function(r,f,e,s){t.Utils.Ui.isFlights()?u.when(t.Services.GeoService.getGeoInfo(!1,!0),n._getBrowseRoutes(null,{currency:r,market:e,locale:s,homecity:f,country:o})).done(function(t,u){i.resolve({geo:t,currency:r,market:e,homecity:f,routes:n.InspirationalPlaces._convertToContinentsBase(u,{currency:r,market:e,homecity:f})})}).fail(function(n){i.reject(n)}):u.when(t.Services.GeoService.getGeoInfo(!1,!0)).done(function(n){i.resolve({geo:n,currency:r,market:e,homecity:f,routes:{homecity:f,market:e,currency:r,continents:n.continents}})}).fail(function(n){i.reject(n)})}).fail(function(n){i.reject(n)}),i.promise()};n.getGeoData=function(){if(f.getGeoData.invoked)return f.getGeoData.promise.promise();var n=new u.Deferred;return f.getGeoData.invoked=!0,f.getGeoData.promise=n,u.when(t.Services.Currency.getCurrency(),t.Services.HomeCity.getHomeCity(),t.Services.Market.getMarket(),t.Services.Language.getLanguage()).done(function(i,r,f,e){u.when(t.Services.GeoService.getGeoInfo(!0,!0)).done(function(o){var s=[];_.each(o.allcountriesProcessed,function(n){s=_.union(s,_.pluck(n.cities,"cityCode"))});u.when(t.Services.GeoService.mapFlightsToHotels(s)).done(function(t){_.each(o.continents,function(n){_.each(n.countries,function(n){_.each(n.cities,function(n){var i=t[n.cityCode];i?n.cityId=i:n.failed=!0});n.cities=_.without(n.cities,_.findWhere(n.cities,{failed:!0}))})});var u={routes:{currency:i,homecity:r,market:f,locale:e},geo:o};n.resolve(u)}).fail(function(t){n.reject(t)})}).fail(function(t){n.reject(t)})}).fail(function(t){n.reject(t)}),n.promise()};n.InspirationalPlaces={_convertToCities:function(n,i){var f=_.findWhere(n.citiesGeoInfo.allcountriesProcessed,{code:i}),r,u;return n?(u={},_.each(n.citiesGeoInfo.allcountriesProcessed,function(n){_.each(n.cities,function(n){n.ThumbnailUrl&&(u[n.Id]=n.ThumbnailUrl)})}),r=_.map(n.Quotes,function(i){var e=_.findWhere(n.Places,{PlaceId:i.OutboundLeg.DestinationId}),r;if(!e||(r=_.find(f.cities,function(n){return _.findWhere(n.Airports,{Id:e.SkyscannerCode})}),!r))return null;var o=moment(i.OutboundLeg.DepartureDate,t.Settings.datetimePricingServiceFormat),s=moment(i.InboundLeg.DepartureDate,t.Settings.datetimePricingServiceFormat),c=moment(s).diff(moment(o),"days"),h=r.SingleAirportCity&&_.isObject(r.Airports[0]);return{id:e.PlaceId,code:h?r.Airports[0].Id:r.Id,cityCode:r.Id,name:e.CityName,ThumbnailUrl:u[r.Id],fullName:h?e.Name:e.CityName,countryName:e.CountryName,price:i.MinPrice,unpriced:!i.MinPrice,homecity:n.homecity,wrappedPrice:t.Utils.Ui.wrapPrice(i.MinPrice,n.currency),outboundDepartureDate:o,inboundDepartureDate:s,duration:Math.abs(c)}}),r=_.filter(r,function(n){return n!==null}),r=_.sortBy(r,function(n){return n.price}),r=_.uniq(r,function(n){return n.code})):r=[],r},_convertToContinentsBase:function(n,i){var u=_.sortBy(_.where(t.Dictionaries.Continents,{inspirational:!0}),function(n){return n.order}),r=[];return _.each(u,function(u){var f=[],e;_.each(u.countries,function(r){var o=_.findWhere(n.Places,{SkyscannerCode:r}),s=o?_.where(n.Routes,{DestinationId:o.PlaceId}):[],c=_.every(s,function(n){return n.Price&&n.Price>0}),h,e;if(c&&s.length>0&&(i.market!==r||_.contains(t.Dictionaries.AcceptedCountriesForDomesticFlights,r))){h=_.flatten(_.pluck(s,"QuoteIds"),!0);e=[];_.each(h,function(t){var i=_.findWhere(n.Quotes,{QuoteId:t}),r;i&&(r=_.findWhere(n.Places,{PlaceId:i.OutboundLeg.DestinationId}),i.cityName=r.CityName,i.skyscannerCode=r.SkyscannerCode,i.AirportName=r.Name,e.push(i))});e=_.sortBy(e,function(n){return n.MinPrice});var u=_.first(e),l=_.first(e,3),a=moment(u.InboundLeg.DepartureDate,t.Settings.datetimePricingServiceFormat).diff(moment(u.OutboundLeg.DepartureDate,t.Settings.datetimePricingServiceFormat),"days");f.push({code:r,name:o?o.Name:r,priceCityName:u?u.cityName:"",priceCityCode:u.skyscannerCode,price:u.MinPrice,offers:l,duration:Math.abs(a),dates:{outbound:moment(u.OutboundLeg.DepartureDate,t.Settings.datetimePricingServiceFormat),inbound:moment(u.InboundLeg.DepartureDate,t.Settings.datetimePricingServiceFormat)},wrappedPrice:t.Utils.Ui.wrapPrice(u.MinPrice,i.currency),cities:null})}});e={id:u.id,name:u.name,countries:f,currentMarket:i.market,homecity:i.homecity};r.push(e)}),{homecity:i.homecity,market:i.market,currency:i.currency,continents:r}},getPlaces:function(){var n=new u.Deferred;return e().done(function(t){n.resolve(u.extend(!0,{},t))}).fail(function(t){Logger("inspirational-service").error(t);n.reject(t)}),n.promise()},getPopularPlaces:function(){var t=new u.Deferred;return n.getGeoData().done(function(n){t.resolve(u.extend(!0,{},n))}).fail(function(n){Logger("inspirational-service").error(n);t.reject(n)}),t.promise()},getCities:function(i){var r=new u.Deferred;return u.when(t.Services.Currency.getCurrency(),t.Services.HomeCity.getHomeCity(),t.Services.Market.getMarket(),t.Services.Language.getLanguage()).done(function(f,e,o,s){u.when(n._getBrowseRoutes(null,{currency:f,market:o,locale:s,homecity:e,country:i}),t.Services.GeoService.getGeoInfo(!1,!1,[i])).done(function(t,u){t.homecity=e;t.citiesGeoInfo=u;var f=n.InspirationalPlaces._convertToCities(t,i);r.resolve(f)}).fail(function(n){Logger("inspirational-service").error(n);r.reject(n)})}).fail(function(n){Logger("inspirational-service").error(n);r.reject(n)}),r.promise()},getAttributions:function(){if(f.attributions.invoked)return f.attributions.promise.promise();var n=new u.Deferred;return f.attributions.invoked=!0,f.attributions.promise=n,u.getJSON(t.Settings.baseUrl+"Scripts/tempdata/attribution.json").done(function(t){n.resolve(t)}).fail(function(){Logger("inspirational-service").error("Can't load attributions.json");n.reject()}),n.promise()},invalidate:function(){f={getGeoData:{invoked:!1,promise:null},getData:{invoked:!1,promise:null},attributions:{invoked:!1,promise:null}}}}});App.module("Services",function(n,t){n.Language={getLanguageSync:function(){return t.Settings.config.locale},getDisplayLanguageSync:function(){return t.Settings.config.displayLocale},getLanguage:function(){var n=new $.Deferred;return n.resolve(t.Settings.config.locale)},setLanguage:function(t){if(typeof n.Language.Resolvers.onSet=="function")n.Language.Resolvers.onSet(t.code)}};n.Language.Resolvers={}});App.module("Services",function(n,t,i,r,u){var f={localizationService:{invoked:!1,promise:undefined},market:{invoked:!1,resolved:!1,promise:undefined}},s=null,o=function(n){var i=new u.Deferred;return u.when(t.Services.Language.getLanguage(),t.Services.Session.getToken()).done(function(r,u){t.Services.PlacesApi.getMarketById(n,{market:"UK",currency:"GBP",locale:r,token:u}).done(function(n){i.resolve(n)}).fail(function(){i.reject()})}).fail(function(){i.reject()}),i.promise()},c=function(n){var i=new u.Deferred;return u.when(t.Services.Language.getLanguage(),t.Services.Session.getToken()).done(function(r,u){t.Services.PlacesApi.getMarketById(n,{market:"UK",currency:"GBP",locale:r,token:u}).done(function(n){i.resolve(n)}).fail(function(){i.reject()})}).fail(function(){i.reject()}),i.promise()},e={scaffold:function(){var n=new u.Deferred,i;return t.Settings.config.market&&t.Settings.config.isScaffold?(i={CountryId:t.Settings.config.market+"-sky"},n.resolve(i)):n.reject(),n.promise()},defaultMarket:function(){var n=new u.Deferred,r=t.Settings.config,i=r.defaultMarket,f=r.preventMarketDetection;return i&&f?o(i).done(function(t){n.resolve(t)}).fail(function(){Logger("market-service").error(_.template("DefaultMarket provider. Can't find place with market-id=<%= value %>",{value:i}));n.reject()}):n.reject(),n.promise()},url:function(){var n=new u.Deferred,r=new t.Utils.Uri(t.Utils.Location.getHref()),i=r.getAnchorParams();return i.homemarket?o(i.homemarket).done(function(t){n.resolve(t)}).fail(function(){Logger("market-service").error(_.template("Url provider. Can't find place with market-id=<%= value %>",{value:i.market}));n.reject()}):n.reject(),n.promise()},localstorage:function(){var n=new u.Deferred,i=t.Utils.Storage.getObject("culture.marketFromUrl");return i?(t.Utils.Storage.deleteObject("culture.marketFromUrl"),o(i).done(function(t){n.resolve(t)}).fail(function(){Logger("market-service").error(_.template("Localstorage provider. Can't find place with market-id=<%= value %>",{value:i}));n.reject()})):n.reject(),n.promise()},settings:function(){var n=new u.Deferred,i=t.Settings.config.market;return i?o(i).done(function(t){n.resolve(t)}).fail(function(){Logger("market-service").error(_.template("Settings provider. Can't find place with market-id=<%= value %>",{value:i}));n.reject()}):n.reject(),n.promise()},localizationService:function(){var n=new u.Deferred;return t.Services.HomeCity.getHomeCity().done(function(t){n.resolve(t)}).fail(function(){Logger("market-service").error("getMarket from city failure");n.reject()}),n.promise()},defaultFallback:function(){var n=new u.Deferred,i=t.Settings.config.defaultMarket,r={PlaceId:"LOND-sky",PlaceName:"London",CountryId:"UK-sky",RegionId:"",CityId:"LOND-sky",CountryName:"United Kingdom"};return i?o(i).done(function(t){n.resolve(t)}).fail(function(){Logger("market-service").error(_.template("Default fallback provider. Can't find place with market-id=<%= value %>",{value:i}));n.resolve(r)}):n.resolve(r),n.promise()}},h={localstorage:function(n){n.CountryId=n.CountryId.replace("-sky","");t.Utils.Storage.setObject("culture.marketFromUrl",n.CountryId)}};n.Market={getMarket:function(){var t=new u.Deferred;return n.Market.getMarketFullDetail().done(function(n){var i=n.CountryId.replace("-sky","");i=i==="CE"?"RU":i;t.resolve(i)}).fail(function(){Logger("market-service").error("getMarket failure");t.reject()}),t.promise()},getMarketFullDetail:function(){var n;if(f.market.invoked&&f.market.promise!==undefined)return f.market.promise.promise();n=new u.Deferred;f.market.invoked=!0;f.market.promise=n;var t=[e.scaffold,e.url,e.defaultMarket,e.settings,e.localstorage,e.localizationService,e.defaultFallback],i=0,r=function(u){u().then(function(t){s=t;f.market.resolved=!0;n.resolve(t)},function(){i++;i<t.length?r(t[i]):(Logger("market-service").fatal("getMarket failure. Something's wrong with providers sequence."),n.reject())})};return r(t[0]),n.promise()},getMarketSync:function(){if(!f.market.resolved)throw new Error("Market service did not invoked. Using sync function is not allowed.");return s},setMarket:function(t){if(typeof n.Market.Resolvers.onSet=="function")n.Market.Resolvers.onSet(t)},reset:function(){f.localizationService.invoked=!1;f.market.invoked=!1;f.market.resolved=!1;s=null}};_.extend(n.Market,i.Events);n.Market.Resolvers=h;n.Market.Providers=e});App.module("Services",function(n){n.PixelTrackingService={track:function(){var n=new $.Deferred;return App.Services.Session.getToken().done(function(t){var i=App.Settings.apiUrl+"apiservices/tracking/v1.0/tracking.gif?svc=whitelabelv2&apikey="+encodeURIComponent(t);$.ajax({url:i}).done(function(){Logger("pixel-tracking-service").info("PixelTrackingService success!");n.resolve()})}),n.promise()}}});App.module("Services",function(n,t,i,r,u){function c(n){var i,r,u=n.long_name,t=u.split("(").join(",").split(")").join(",").split(",");return t=_.filter(_.map(t,function(n){return n.trim()}),function(n){return n!==""}),n.geo_type==="Nation"?(i="",r=""):n.geo_type==="Airport"?(t=t.slice(2,t.length),i=t.pop(),t=t.slice(1),r=t.join(", ")+" ("+i+")"):(t=t.slice(2,t.length),i=t.pop(),r=t.join(", ")+" ("+i+")"),{displayName:n.name,geoType:n.geo_type,placeId:n.individual_id,bookable:!0,countryName:i,infoText:r,longitude:n.longitude,latitude:n.latitude}}var f=new t.Utils.Cache(20),o=new t.Utils.Cache(20),h=new t.Utils.Cache(20),l=new t.Utils.Cache(100),s=new t.Utils.Cache(20),e=new Array(10);n.PlacesApi={getAutoSuggestMarkets:function(n){var i=new u.Deferred;return u.when(t.Services.Currency.getCurrency(),"UK",t.Services.Language.getLanguage(),t.Services.Session.getToken()).done(function(r,e,o,s){var h=_.template("<%= url %>apiservices/autosuggest/v1.0/"+"<%= country %>/"+"<%= currency %>/"+"<%= locale %>/"+"?includeAirports=false&includeCities=false&includeCountries=true&query=<%= query %>",{url:t.Settings.apiUrl,country:e,currency:r,locale:o,query:encodeURIComponent(n)}),c=f.get(h),l=_.template("<%= mainUrl %>&apikey=<%= apiKey %>",{mainUrl:h,apiKey:encodeURIComponent(s)});if(c!==null)return i.resolve(c);u.get(l).done(function(n){f.set(h,n);i.resolve(n)}).fail(function(){i.reject()})}).fail(function(){i.reject()}),i.promise()},getAutoSuggestPlaces:function(n){var i=new u.Deferred;return u.when(t.Services.Currency.getCurrency(),t.Services.Market.getMarket(),t.Services.Language.getLanguage(),t.Services.Session.getToken()).done(function(r,e,o,s){var h=_.template("<%= url %>apiservices/autosuggest/v1.0/"+"<%= country %>/"+"<%= currency %>/"+"<%= locale %>/"+"?includeAirports=true&includeCities=true&includeCountries=false&query=<%= query %>",{url:t.Settings.apiUrl,country:e,currency:r,locale:o,query:encodeURIComponent(n)}),c=f.get(h),l=_.template("<%= mainUrl %>&apikey=<%= apiKey %>",{mainUrl:h,apiKey:encodeURIComponent(s)});if(c!==null)return i.resolve(c);u.get(l).done(function(n){var r=t.Services.Feature.get("autosuggestContinentFilter");r?u.when(t.Services.GeoService.getGeoInfo(!1,!1)).done(function(t){var u=_.find(t.rawData.Continents,function(n){return n.Id===r}),e,o,s;u&&u.Countries&&(e=[],o=_.map(u.Countries,function(n){return n.Id.toUpperCase()}),_.each(u.Countries,function(n){e=_.union(e,_.map(n.Cities,function(n){return n.Id.toUpperCase()}))}),s=_.filter(n.Places,function(n){var t=n.CountryId.replace("-sky","").toUpperCase(),i=n.CityId.replace("-sky","").toUpperCase();return _.contains(o,t)||_.contains(e,i)}),n.Places=s);f.set(h,n);i.resolve(n)}):(f.set(h,n),i.resolve(n))}).fail(function(){Logger("api-service").error(_.template("Can't obtain data from <%= url %>",{url:l}));i.reject()})}).fail(function(){i.reject()}),i.promise()},getMarketById:function(n,i){i=i||{};var r=new u.Deferred;return u.when(function(){return i.currency?(new u.Deferred).resolve(i.currency):t.Services.Currency.getCurrency()}(),function(){return i.market?(new u.Deferred).resolve(i.market):t.Services.Market.getMarket()}(),function(){return i.locale?(new u.Deferred).resolve(i.locale):t.Services.Language.getLanguage()}(),function(){return i.token?(new u.Deferred).resolve(i.token):t.Services.Session.getToken()}()).then(function(i,f,e,o){var s=["<%= url %>apiservices/autosuggest/v1.0/<%= country %>/<%= currency %>/","<%= locale %>/?includeAirports=false&includeCities=false&includeCountries=true&id=<%= id %>","&apikey=<%= apiKey %>"],l,c;s[0]=_.template(s[0],{url:t.Settings.apiUrl,country:f,currency:i});s[1]=_.template(s[1],{locale:e,id:n});s[2]=_.template(s[2],{apiKey:encodeURIComponent(o)});l=h.get(s[1]);l!==null?r.resolve(l):(c=s.join(""),u.get(c).done(function(n){n.Places&&n.Places.length>0?(h.set(s[1],n.Places[0]),r.resolve(n.Places[0])):(Logger("api-service").error(_.template("Received unexpected data structure from <%= url %>. Received object: <%= data %>",{url:c,data:JSON.stringify(n)})),r.reject())}).fail(function(){Logger("api-service").error(_.template("Can't obtain data from <%= url %>",{url:c}));r.reject()}))}),r.promise()},getPlaceById:function(n,i){i=i||{};var r=new u.Deferred;return u.when(function(){return i.currency?(new u.Deferred).resolve(i.currency):t.Services.Currency.getCurrency()}(),function(){return i.market?(new u.Deferred).resolve(i.market):t.Services.Market.getMarket()}(),function(){return i.locale?(new u.Deferred).resolve(i.locale):t.Services.Language.getLanguage()}(),function(){return i.token?(new u.Deferred).resolve(i.token):t.Services.Session.getToken()}()).then(function(i,f,e,s){var h=["<%= url %>apiservices/autosuggest/v1.0/<%= country %>/<%= currency %>/","<%= locale %>/?includeAirports=true&includeCities=true&includeCountries=false&id=<%= id %>","&apikey=<%= apiKey %>"],l,c;h[0]=_.template(h[0],{url:t.Settings.apiUrl,country:f,currency:i});h[1]=_.template(h[1],{locale:e,id:n});h[2]=_.template(h[2],{apiKey:encodeURIComponent(s)});l=o.get(h[1]);l!==null?r.resolve(l):(c=h.join(""),u.get(c).done(function(n){n.Places&&n.Places.length>0?(o.set(h[1],n.Places[0]),r.resolve(n.Places[0])):(Logger("api-service").error(_.template("Received unexpected data structure from <%= url %>. Received object: <%= data %>",{url:c,data:JSON.stringify(n)})),r.reject())}).fail(function(){Logger("api-service").error(_.template("Can't obtain data from <%= url %>",{url:c}));r.reject()}))}),r.promise()},getPlacesByIds:function(i){var r=new u.Deferred,f=function(n){r.resolve(n)};return u.when(t.Services.Currency.getCurrency(),t.Services.Market.getMarket(),t.Services.Language.getLanguage(),t.Services.Session.getToken()).done(function(t,r,u,e){var a=i.length,o=0,s={},v,h,c,l;for(s.Places=[],v=(new Date).getTime(),l=0;l<a;l++)n.PlacesApi.getPlaceById(i[l],{currency:t,market:r,locale:u,token:e}).done(function(n){n&&s.Places.push(n);o++;o>=a&&(f(s),h=(new Date).getTime(),c=h-v,console.log("Process data is done. Spent "+c+"ms"))}).fail(function(){o++;o>=a&&(f(s),h=(new Date).getTime(),c=h-v,console.log("Process data is done. Spent "+c+"ms"))})}),r.promise()},getHotelPlaceById:function(n,i){var o=(new Date).getTime(),r=_.findWhere(e,{id:n}),f;if(r&&r.timestamp&&r.deffered){if(o-r.timestamp<300)return r.deffered.promise();r.id=0}return i=i||{},f=new u.Deferred,r={id:n,timestamp:o,deffered:f},e.push(r),e.shift(),u.when(t.Services.Session.getToken(),function(){return i.currency?(new u.Deferred).resolve(i.currency):t.Services.Currency.getCurrency()}(),function(){return i.market?(new u.Deferred).resolve(i.market):t.Services.Market.getMarket()}(),function(){return i.locale?(new u.Deferred).resolve(i.locale):t.Services.Language.getLanguage()}()).then(function(i,r,e,o){var l=n+o,a=s.get(l),h;a!==null?f.resolve(a):(h=_.template("<%= url %>apiservices/hotels/entity/v2/<%= country %>/<%= currency %>/<%= locale %>/<%= id %>?apikey=<%= apiKey %>",{url:t.Settings.apiUrl,country:e,currency:r,locale:o,apiKey:i,id:n}),u.ajax({url:h,dataType:"json"}).done(function(n){if(n&&!_.isEmpty(n)){var t=c(n);s.set(l,t);f.resolve(t)}else f.reject()}).fail(function(){Logger("api-service").error(_.template("Can't obtain data from <%= url %>",{url:h}));f.reject()}))}),f.promise()},invalidateCache:function(){f.clear();o.clear();s.clear();e=new Array(10)}}});App.module("Services",function(n,t,i,r,u){var f={deferred:null,invoked:!1};n.Session={MAX_TOKEN_ATTEMPTS:3,getToken:function(n){if(f.invoked&&n!==!0||f.wait===!0)return f.deferred.promise();f.invoked=!0;f.deferred=new u.Deferred;f.wait=!0;var i=_.template("<%= url %>token",{url:t.Settings.baseUrl});return u.get(i).done(function(n){f.wait=!1;f.value=n.token;f.deferred.resolve(f.value)}).fail(function(n){Logger("session-service").fatal("Request /token returned error: "+JSON.stringify(n));t.Settings.enableLogging=!1;t.Utils.Ui.showLoadError();f.deferred.reject()}),f.deferred.promise()},getUserIp:function(){var n=new u.Deferred;return n.resolve(t.Settings.clientIP),n.promise()},invalidateCache:function(){f.wait=!1;f.invoked=!1;f.deferred=null}}}),function(n){App.module("Services",function(t){function i(){this._agents=[];this._flags={}}function u(){}function r(n){this.options=n||{};this._initializeGAClient()}i.prototype.addTrackingAgent=function(n){if(!n||typeof n.processEvent!="function")throw new Error("agent cannot be null and should have processEvent function");this._agents.push(n)};i.prototype.getAgents=function(){return this._agents};i.prototype.trackEvent=function(n,t,i,r){if(!n||!t)return null;var u={category:n,action:t,label:i,value:r};return _.map(this._agents,function(n){n.processEvent(u)})};i.prototype.trackPageView=function(n){return _.map(this._agents,function(t){t.trackPageView(n)})};i.prototype.setAbTesting=function(n){return _.map(this._agents,function(t){t.setAbTesting&&typeof t.setAbTesting=="function"&&t.setAbTesting(n)})};i.prototype.setFlag=function(n,t){this._flags[n]=t};i.prototype.getFlag=function(n){return this._flags[n]?this._flags[n]:null};i.prototype.decorateUrl=function(n){return ga&&_.isFunction(ga.getAll)&&(this.trackers=this.trackers||ga.getAll()),window.gaplugins&&_.isFunction(window.gaplugins.Linker)&&this.trackers&&(this.linker=this.linker||new window.gaplugins.Linker(this.trackers[0]),n=this.linker.decorate(n)),n};i.prototype.expandDeepLink=function(n,t){var i="&additional_params=marin_tracker_on";return this._expandDeepLink&&["3855438","2363321"].indexOf(t+"")===-1&&n.indexOf(i)===-1?n+i:n};i.prototype.checkSourceCookie=function(){var n=$.cookie("source"),t;if(!n){this._expandDeepLink=!1;return}t=["GOO","MIC","CRIT","FBPD","OBPD","TWPD","YAH"].filter(function(t){return n.indexOf(t)===0});this._expandDeepLink=t.length>0};u.prototype.processEvent=function(n){var t=new Date;console.log(_.template("%c[<%= time %>] Event: <%= event.category %>.<%= event.action %> : <%= event.label %> : <%= event.value %>",{time:t.getHours().toString()+":"+t.getMinutes().toString()+":"+t.getSeconds().toString()+"::"+t.getMilliseconds().toString(),event:n}),"color: blue")};u.prototype.trackPageView=function(n){this.processEvent({category:"pageView",action:n,label:"",value:""})};r.prototype._initializeGAClient=function(){if(n.ga===null||n.ga===undefined)return!1;if(!this.options.accountId)throw new Error("GA tracking agent initialization: GA account id not specified!");if(!this.options.name)throw new Error("GA tracking agent initialization: Agent name not specified!");this.trackerName=this.options.name;n.ga("create",this.options.accountId,this.options)};r.prototype.processEvent=function(t){if(!(n.ga&&t))return!1;n.ga(this.trackerName+".send","event",t.category,t.action,t.label,{eventValue:t.value,dimension1:"2.0"})};r.prototype.trackPageView=function(t){if(!n.ga)return!1;n.ga(this.trackerName+".send","pageview",{page:t,dimension1:"2.0"})};r.prototype.setAbTesting=function(t){n.ga(this.trackerName+".set","dimension2",t)};t.TrackingService=i;t.TrackingService.Agents={Console:u,GoogleAnalytics:r};t.TrackingServiceInitializer={initialize:function(n){var t,i;n.tracking=new n.Services.TrackingService;t=new n.Services.TrackingService.Agents.Console;n.tracking.addTrackingAgent(t);n.Settings.gaId&&(i=new n.Services.TrackingService.Agents.GoogleAnalytics({accountId:n.Settings.gaId,name:"Skyscanner"}),n.tracking.addTrackingAgent(i));n.Services.Feature.check("expandDeepLink","on")&&n.tracking.checkSourceCookie()}}})}(window);App.module("Behaviours",function(n,t,i){n.DropdownKeysControl=i.Marionette.Behavior.extend({_inArrowPressHander:function(n){var i=this.view.$el.find(".js-control-item:visible"),f=i.filter(":focus"),r=i.index(f),u=i.length-1,t=0;r===-1?t=n?0:u:(t=n?r+1:r-1,t=t>u?0:t,t=t<0?u:t);i.get(t)&&i.get(t).focus()},_onKeyDown:function(n){switch(n.keyCode){case 38:case 40:n.preventDefault();this._inArrowPressHander(n.keyCode===40);break;case 27:this.view.close();this.view.focus();break;case 32:n.target.tagName!="INPUT"&&(n.preventDefault(),this.view.$el.find(".js-control-item:focus").trigger("click"))}},_onButtonArrowPress:function(n){if(!this.view.opened){var t=this.view.collection.indexOf(this.view.model),i=this.view.collection.at(n?t+1:t-1);i&&this.view.select(i)}},_onButtonKeyDown:function(n){(n.keyCode===38||n.keyCode===40)&&(n.preventDefault(),this._onButtonArrowPress(n.keyCode===40))},_onViewOpen:function(){$(document).on("keydown."+this.view.cid,_.bind(this._onKeyDown,this))},_onViewClose:function(){$(document).off("keydown."+this.view.cid)},onRender:function(){this.view.ui.toggleContainer.on("keydown."+this.view.cid,_.bind(this._onButtonKeyDown,this));this.view.on("open",_.bind(this._onViewOpen,this));this.view.on("close",_.bind(this._onViewClose,this))},onBeforeDestroy:function(){this.view.ui.toggleContainer.off("keydown."+this.view.cid,_.bind(this._onButtonKeyDown,this))}})});App.module("Behaviours",function(n){n.DropdownExtendedKeysControl=n.DropdownKeysControl.extend({_onButtonArrowPress:function(){this.view.opened||this.view.open()}})});App.module("Behaviours",function(n,t,i){n.DropdownMobileFullscreen=i.Marionette.Behavior.extend({template:"",mobileContainer:null,getHeaderLabel:function(){var n=this.options.getHeaderLabel,t="";return typeof n=="function"&&(t=n.apply(this,[this.view.options.type||""])),t},_beforeRenderDropdown:function(){if(!this.mobileContainer){this.mobileContainer=$(this.template({headerLabel:this.getHeaderLabel()}));this.mobileContainer.on("click",".js-cancel-btn",this._cancelClicked);$(t.Utils.Ui.bodySelector).append(this.mobileContainer);this.view.$childViewContainer=this.mobileContainer.find(".js-dropdown-items-container");this.view.ui.itemsContainerWrapper=this.mobileContainer.find(".js-dropdown-container-wrapper");this.view.ui.itemsContainerWrapper.addClass(this.view.className);this.mobileContainer.i18n();t.Services.Feature.check("filters","b")||this.mobileContainer.addClass("filters-a filters-box")}},_cancelClicked:function(n){n.preventDefault();n.stopImmediatePropagation();this.view.close()},_onTitleChange:function(n){this.mobileContainer.find(".js-modal-header-title").html(n)},_onOpen:function(){this.mobileContainer&&(this.view.isModal=!0,(t.Utils.Ui.isWinPhone()||t.Utils.Ui.is2xAndroid())&&t.Utils.Ui.onOpenFullscreenModal(),$("html").addClass("has-overlay"),this.mobileContainer.addClass("is-active"))},_onClose:function(){this.mobileContainer&&(this.view.isModal=!1,$("html").removeClass("has-overlay"),this.mobileContainer.removeClass("is-active"),(t.Utils.Ui.isWinPhone()||t.Utils.Ui.is2xAndroid())&&t.Utils.Ui.onCloseFullscreenModal())},_init:function(n){var i=this.view.opened;this.view.isDestroyed||(n&&(this.view.triggerMethod("before:dropdown:mobile:fullscreen:init"),i&&this.view.close()),t.Utils.Ui.isMobileView()?this._bindView():(this._unbindView(),this._destroyMobileContainer()),n&&(this.view.render(),i&&this.view.open(),this.view.triggerMethod("after:dropdown:mobile:fullscreen:init")))},_bindView:function(){this.view.on("before:render-dropdown",this._beforeRenderDropdown,this);this.view.on("open",this._onOpen,this);this.view.on("close",this._onClose,this);this.view.on("title:change",this._onTitleChange,this)},_unbindView:function(){this.view.off("before:render-dropdown",this._beforeRenderDropdown,this);this.view.off("open",this._onOpen,this);this.view.off("close",this._onClose,this);this.view.off("title:change",this._onTitleChange,this)},_destroyMobileContainer:function(){this.mobileContainer&&(this.mobileContainer.off().remove(),this.mobileContainer=null)},onBeforeDestroy:function(){this._destroyMobileContainer();this._unbindView()},initialize:function(){this.template=_.template($("#base-dropdown-fullscreen-template").html());_.bindAll(this,"_beforeRenderDropdown","_onOpen","_onClose","_init","_cancelClicked");t.Utils.Ui.on("breakpoint:change",this._init);this._init()}})});App.module("Behaviours",function(n,t){n.DropdownMultilevelKeysControl=t.Behaviours.DropdownExtendedKeysControl.extend({_onDownHandler:function(){var t=this.view.$el.find(".js-dropdown-items-container > .js-dropdown-item"),i,n,r;t.length&&(i=this.view.$el.find(".js-dropdown-item.active"),n=0,i.length&&(n=t.index(i),n++,n===t.length&&(n=0),i.removeClass("active")),i=$(t.get(n)),i.addClass("active"),r=n-3<0?$(t.get(0)):$(t.get(n-3)),this.view.$el.find(".js-dropdown-items-container").scrollTo(r,100))},_onEnterHandler:function(){this.view.$el.find(".js-dropdown-item.active").trigger("click")},_onUpHandler:function(){var t=this.view.$el.find(".js-dropdown-items-container > .js-dropdown-item"),i,n,r;t.length&&(i=this.view.$el.find(".js-dropdown-item.active"),n=0,i.length?(n=t.index(i),n--,n<0&&(n=t.length-1),i.removeClass("active")):n=t.length-1,i=$(t.get(n)),i.addClass("active"),r=n-3>0?$(t.get(n-3)):$(t.get(0)),this.view.$el.find(".js-dropdown-items-container").scrollTo(r,100))}})});App.module("Behaviours",function(n,t,i){n.DropdownSlide=i.Marionette.Behavior.extend({defaults:{itemsShown:10,height:null,enabled:function(){return!0}},ui:{itemsContainerWrapper:".js-dropdown-container-wrapper",itemsContainer:".js-dropdown-items-container"},onOpen:function(){this.options.enabled()&&this.ui.itemsContainer.focus()},onRender:function(){var r;if(this.options.enabled())if(this.options.height)this.ui.itemsContainer.css({"overflow-y":"auto","max-height":this.options.height,"-webkit-overflow-scrolling":"touch","-ms-overflow-style":"scrollbar"});else{this.ui.itemsContainerWrapper.css({visibility:"hidden"});var u=this.$el.find(".js-dropdown-item"),n=u.first(),i=n.length?Math.max(parseInt(n.height()||n.clientHeight,10),25):25;this.options.itemsShown=parseInt(this.options.itemsShown,10);r=i*this.options.itemsShown+.65*i;this.ui.itemsContainerWrapper.css({visibility:"visible"});this.ui.itemsContainer.css({"overflow-y":"auto","max-height":r,"-webkit-overflow-scrolling":"touch"});t.Utils.Ui.is2xAndroid()&&t.Utils.Ui.makeScrollable(this.ui.itemsContainer)}}})});App.module("Behaviours",function(n,t,i){n.DropdownTypeControl=i.Marionette.Behavior.extend({_search:function(n){if(n.length){var t=new RegExp(n,"gi");return this.view.collection.filter(function(i){var r=i.get("name")||i.get("Code");return t.test(r.slice(0,n.length))})}return},_select:function(n){var r=this.view.$el.find(".js-control-item"),t=this._search(n),u,i;t.length&&(r.removeClass("active"),u=t[0].get("name")||t[0].get("Code"),i=r.filter("[data-value="+u+"]"),i.addClass("active"),this.view.$el.find(".js-dropdown-items-container").scrollTo(i,100))},onRender:function(){var n=this;this.view.on("open",function(){var t="",i=null;$(document).on("keypress.type"+n.view.cid,function(r){clearInterval(i);i=setInterval(function(){t="";clearInterval(i)},1e3);t+=String.fromCharCode(r.which);n._select(t)})});this.view.on("close",_.bind(function(){$(document).off("keypress.type"+n.view.cid)},this))}})});App.module("Behaviours",function(n,t,i){n.PlaceSelectorTracking=i.Marionette.Behavior.extend({onTrackChange:function(n){this.trackAutosuggestEvent(n)},trackAutosuggestEvent:function(n){var i=this.view.options.trackingLabel||"autosuggest";t.Services.Language.getLanguage().done(_.bind(function(r){var u=this.getTrackingDetailsString(r,n.placeValue,n.placeId,n.itemIndex);t.tracking.trackEvent("home",i,u)},this))},getTrackingDetailsString:function(n,t,i,r){return r=parseInt(r,10),r=_.isNaN(r)||r<0?"undefined":r,i=i||"undefined",t=t||"undefined",n+"_"+t+"_"+i+"_"+r}})});App.module("Behaviours",function(n,t,i){n.ViewInactiveVeil=i.Marionette.Behavior.extend({globalTriggerName:null,_isRendered:function(){return typeof this.view.ui.containerInactiveVeil!="string"},_isEnable:!1,enable:function(n){n&&this.globalTriggerName!==n||!this._isEnable&&this._isRendered()&&(this.view.ui.containerInactiveVeil.show(),this._isEnable=!0)},disable:function(n){n&&this.globalTriggerName!==n||this._isEnable&&this._isRendered()&&(this.view.ui.containerInactiveVeil.hide(),this._isEnable=!1)},initialize:function(n){this.view.ui.containerInactiveVeil||(this.view.ui.containerInactiveVeil=".js-container-inactive-veil");this.globalTriggerName=n.triggerName;this.view.on("inactive-veil:enable",this.enable,this);this.view.on("inactive-veil:disable",this.disable,this);if(this.globalTriggerName){t.Utils.Ui.on("inactive-veil:enable",this.enable,this);t.Utils.Ui.on("inactive-veil:disable",this.disable,this)}}})});App.module("Behaviours",function(n,t,i){n.ViewUnwrap=i.Marionette.Behavior.extend({onRender:function(){this.view.$el=this.view.$el.children();this.view.$el.unwrap();this.view.setElement(this.view.$el)}})});App.module("SearchResult.Models",function(n){n.DropdownItemModel=Brace.Model.extend({namedAttributes:{value:"string",disabled:"boolean",selected:"boolean",text:"string",data:"object"},defaults:function(){return{value:"",disabled:!1,selected:!1,text:""}}});n.DropdownSliderModel=Brace.Model.extend({namedAttributes:{min:"number",max:"number",step:"number",value:"number",values:"object",label:"string",type:"string",selected:"boolean",ariaLabel:"string",serialization:"object"},defaults:function(){return{min:0,max:100,label:"",type:"",selected:!1,ariaLabel:"",serialization:{getTooltipText:function(n){return n},getText:function(n){return n}}}}});n.DropdownSliderCollection=Brace.Collection.extend({model:n.DropdownSliderModel});n.DropdownCollection=Brace.Collection.extend({model:n.DropdownItemModel});n.DropdownModel=Brace.Model.extend({namedAttributes:{label:"string",icon:"string",resetText:"string",ariaLabel:"string",tabindex:"number",multiselect:"boolean",disabled:"boolean",active:"boolean",selection:"object",options:"object"},defaults:function(){return{label:"",icon:"",resetText:"",ariaLabel:"",tabindex:0,selection:[],options:[],multiselect:!1,disabled:!1,active:!1}}});n.DropdownGroupModel=Brace.Model.extend({namedAttributes:{type:"string",title:"string",selection:"object",options:n.DropdownCollection},defaults:function(){return{type:"",title:"",selection:[],options:[]}}});n.DropdownGroupedCollection=Brace.Collection.extend({model:n.DropdownGroupModel})});App.module("Views",function(n,t,i){n.DatePickerView=i.Marionette.View.extend({settings:{opts:{format:t.Settings.dateFormat.toLowerCase(),clear:"",min:moment().format(t.Settings.dateFormat),max:moment().add(330,"days").format(t.Settings.dateFormat),selectMonths:!0,selectYears:!0,render:!0,klass:{navPrev:"ss-icon-arrow-left ss-icon",navNext:"ss-icon-arrow-right ss-icon",navDisabled:"picker__nav--disabled"}}},ui:{input:"input",cover:".search-date-cover"},events:{"click .search-date-cover, .ss-icon-plus":"open","click .js-button-clear":"clearValue","keydown .search-date-cover, .ss-icon-plus":"_open"},renderDateCover:function(n){var u,f,e;if(n){var i=moment(n,t.Settings.dateFormat),o=moment.months()[i.get("month")],s=moment.monthsShort()[i.get("month")],h=moment.weekdays()[i.format("d")],r=i.format("D");r<10&&(r="0"+r.toString());u="";f="";_.each(moment.months(),function(n){n.length>10&&(u="hide")});f=u==="hide"?f:"hide";e='<span class="offscreen">'+this.ui.cover.attr("data-label")+'<\/span><div class="month"><span class="js-full-month tablet-hide mobile-hide '+u+'">'+o+'<\/span><span class="js-short-month tablet-show-inline mobile-show-inline '+f+'">'+s+'<\/span><\/div><div class="day">'+r+'<\/div><div class="dayofweek">'+h+"<\/div>";this.ui.cover.html(e)}else this.ui.cover.html('<span class="offscreen">'+$.t("aria.search.addreturn")+'<\/span><div class="ss-icon-plus ss-icon"><\/div>')},getButtonsSettings:function(){return{depart:[{key:"today",days:0},{key:"nextday",days:1},{key:"3days",days:3},{key:"5days",days:5},{key:"1week",days:7},{key:"2weeks",days:14}],backreturn:[{key:"sameday",days:0},{key:"nextday",days:1},{key:"3days",days:3},{key:"5days",days:5},{key:"1week",days:7},{key:"2weeks",days:14}]}},addButtons:function(){var n=$(this.options.pickadateContainer());n.find(".picker__footer button.btn-day").off("click");n.find(".picker__footer").empty();var r=this,f=[],u,e=this.getButtonsSettings();this.type==="return"?(f=e.backreturn,u=this.getPointOfReference()):(f=e.depart,u=this.getPointOfReference());_.each(f,_.bind(function(r){var f={},o=new $.Deferred,e=moment(u).add(r.days,"days");f.day=e.get("date");f.day<10&&(f.day="0"+f.day.toString());f.month=moment.monthsShort()[e.get("month")];f.id="depart";f.item=r;f.value=t.Culture.culture.formatDate(e.toDate(),{date:"monthDayAbbr"});f.valueAria=t.Culture.culture.formatDate(e.toDate(),{date:"monthDay"});t.Services.Language.getLanguage().done(function(t){f.biggerFont=t==="ja-JP";var r=i.Marionette.Renderer.render("#date-button-template",f);n.find(".picker__footer").append(r)}).fail(function(){o.reject()})},this));n.find(".picker__footer button.btn-day").on("touchstart click",function(n){var f;n.preventDefault();var e=$(this).data("days"),i=$(this).data("key"),o=moment(u).add(e,"days");r.ui.input.pickadate("picker").set("select",o.format("YYYY-MM-DD"));t.tracking.setFlag(r.type==="depart"?"Datechooser-from":"Datechooser-to",i);f=r.type==="depart"?"Datechooser-from":"Datechooser-to";t.tracking.trackEvent("home",f,i);r.animatedClosing();$(".js-search-form-overlay").removeClass("show");r.close();n.stopPropagation()});n.find(".picker__footer").i18n()},addAccInput:function(){var f=$(this.options.pickadateContainer()),e=f.find(".picker__header"),o=i.Marionette.Renderer.render("#acc-datepicker-template"),t=$(o).i18n(),s=moment(this.picker.get("min")).year(),h=moment(this.picker.get("max")).year(),c,r,u,n;for(c=t.find("[name=acc-days]"),r=t.find("[name=acc-months]"),n=0;n<12;n++)r.append("<option value='"+n+"'>"+moment.months(n)+"<\/option>");for(u=t.find("[name=acc-years]"),n=s;n<=h;n++)u.append("<option value="+n+">"+n+"<\/option>");t.insertAfter(e);t.on("touchstart click",".acc-ok",_.bind(this._validateAccInput,this));t.on("keydown",".acc-input",function(n){(n.keyCode===13||n.keyCode===32)&&n.stopPropagation()})},accOpen:function(){var t=$(this.options.pickadateContainer()),n=this.picker.get()?moment(this.picker.get()):moment(this.getPointOfReference());t.find("[name=acc-days]").val(n.date()).end().find("[name=acc-months]").val(n.month()).end().find("[name=acc-years]").val(n.year()).end().find(".acc-error").empty().end().find(".acc-input:first").focus()},_validateAccDate:function(n){var t=moment(this.picker.get("min").obj),i=moment(this.picker.get("max").obj);return n.isValid()?n.isBefore(t)?"past":n.isAfter(i)?"future":void 0:"invalid"},_validateAccInput:function(){function o(n){return String(n).length===1?"0"+n:n}var n=$(this.options.pickadateContainer()).find(".acc-elements"),t=n.find(".acc-error"),i,r,u,f,e;u=n.find("[name=acc-days]").val();f=parseInt(n.find("[name=acc-months]").val(),10)+1;e=n.find("[name=acc-years]").val();i=e+"-"+o(f)+"-"+o(u);t.empty();n.removeClass("with-dp-errors");r=this._validateAccDate(moment(i));r&&n.closest(".acc-mode").addClass("with-dp-errors");switch(r){case"invalid":t.append("<p role='alert'>"+$.t("aria.search.acc.error.invalid")+"<\/p>");break;case"past":t.append("<p role='alert'>"+$.t("aria.search.acc.error.past")+"<\/p>");break;case"future":t.append("<p role='alert'>"+$.t("aria.search.acc.error.future")+"<\/p>");break;default:this.ui.input.pickadate("picker").set("select",moment(i).format("YYYY-MM-DD"));this.close()}},createCustomHeader:function(){var o=$(this.options.pickadateContainer()),f=this,h=o.find(".picker__header"),c=o.find(".picker__header .picker__select--month"),b=o.find(".picker__header .picker__select--year"),l=moment(this.settings.opts.min),a=moment(this.settings.opts.max),e={month:a.month(),year:a.year()},s={month:l.month(),year:l.year()},n,u,v,y;c.hide();b.hide();var k=function(){var n=_.range(s.year,e.year);return n.push(e.year),n}(),r=[],d=c.find("option");if(_.each(k,function(n){_.each(d,function(i){var u=parseInt($(i).attr("value"),10),f=!1;switch(n){case s.year:u>=s.month&&(f=!0);break;case e.year:u<=e.month&&(f=!0);break;default:f=!0}f&&r.push({month:u,year:n,text:$(i).text(),value:t.Culture.culture.formatDate(new Date(n,u,1),{date:"yearMonth"})})})}),u=this.ui.input.pickadate("picker").get("highlight"),t.Utils.Ui.isMobileDevice()){n=$("<select />");n.html(_.map(r,function(n,i){return _.template('<option data-value="<%= value %>" value="<%= index %>"><%= text %><\/option>',{value:n.month+","+n.year,index:i,text:t.Culture.culture.formatDate(new Date(n.year,n.month,1),{date:"yearMonth"})})}).join(""));v=_.indexOf(r,_.find(r,function(n){return u.year===n.year&&u.month===n.month}));y=n.find("option[value='"+v+"']");y.attr("selected","selected");n.on("change",function(){var i=n.find(":selected"),t=i.data("value");return t=t.split(","),f.picker.set("highlight",[parseInt(t[1],10),parseInt(t[0],10),f.picker.get("highlight").date]),!0})}else{var p=new i.Collection(r),g=p.find(function(n){return n.get("month")===u.month&&n.get("year")===u.year}),w=new t.Views.MonthSelectorView({events:{"click .js-dropdown-toggle":"onToggleClick"},collection:p,model:g});w.on("change",function(n){f.picker.set("highlight",[n.year,n.month,f.picker.get("highlight").date])});n=w.render().$el}h.find(".js-header-month-selector").remove();h.prepend($('<div class="picker__header-month-selector js-header-month-selector"><\/div>').html(n))},getHeaderText:function(n){return"search.datepicker.headers."+n},isOpened:!1,accMode:!1,_open:function(n){(n.keyCode===13||n.keyCode===32)&&this.open(n)},open:function(n){var i,r=$(this.options.pickadateContainer());return n.stopPropagation(),n.preventDefault(),this.accMode=n.shiftKey||n.altKey,this.picker.$root.addClass("active"),r[this.accMode?"addClass":"removeClass"]("acc-mode"),$(".js-datedepart-dialog, .js-datereturn-dialog").removeClass("hide-month-select"),$(".js-datedepart-dialog .picker__header select, .js-datereturn-dialog .picker__header select").removeAttr("disabled"),t.GlobalEvents.trigger("global:click",{target:$(t.Utils.Ui.bodySelector),wltype:"jsclick:datepicker",pickadateContainer:this.options.pickadateContainer()}),this.$el.addClass("selected"),this.trigger("block:form"),i=!t.Utils.Ui.isMobileView(),this.picker.open(i),this.isOpened=!0,this.accMode&&this.accOpen(),!1},close:function(){this.isOpened&&(this.isOpened=!1,$(".js-datedepart-dialog, .js-datereturn-dialog").addClass("hide-month-select"),$(".js-datedepart-dialog .picker__header select, .js-datereturn-dialog .picker__header select").attr("disabled","disabled"),this.picker.$root.removeClass("active"),this.$el.removeClass("selected"),this.trigger("unblock:form"),this.ui.input.blur(),this.ui.cover.focus())},getValue:function(){return this.picker.get()},getSelectObject:function(){return this.picker.get("select")},setValue:function(n){_.isString(n)?this.picker.set("select",n,{format:t.Settings.dateFormat.toLowerCase()}):_.isObject(n)&&this.picker.set("select",n)},setHighlightedDate:function(n){this.picker.set("highlight",n,{format:t.Settings.dateFormat.toLowerCase()})},clearValue:function(n){t.officeData&&(t.officeData.inbounddate="");n.preventDefault();this.model.set("date","");t.tracking.trackEvent("home","TripType","OneWay")},_initPicker:function(n){var i=null;n&&(i=this.picker.get("open")||this.isOpened,this.picker.stop(),this.render());this.ui.input.pickadate(_.extend(this.settings.opts,{firstDay:t.Culture.culture.cldr.supplemental("weekData").daysOfWeek[0].index,monthsFull:moment.months(),monthsShort:moment.monthsShort,weekdaysFull:moment.weekdays(),weekdaysShort:moment.weekdaysShort(),weekdaysMin:moment.weekdaysMin(),labelMonthNext:$.i18n.t("search.datepicker.labels.month-next"),labelMonthPrev:$.i18n.t("search.datepicker.labels.month-prev"),labelMonthSelect:$.i18n.t("search.datepicker.labels.month-select"),labelYearSelect:$.i18n.t("search.datepicker.labels.year-select"),container:this.options.pickadateContainer(),onSet:_.bind(function(){t.tracking.setFlag(this.type==="depart"?"Datechooser-from":"Datechooser-to","Single");var n=this.picker.get();n&&this.model.set("date",n)},this),onOpen:_.bind(function(){$(this.options.pickadateContainer()).find(".picker").show()},this),onRender:_.bind(function(){this.picker&&this.onRender()},this),onClose:_.bind(function(){return this.close(),!1},this)}));this.picker=this.ui.input.pickadate("picker");n&&i&&($(".js-datedepart-dialog, .js-datereturn-dialog").removeClass("hide-month-select"),$(".js-datedepart-dialog .picker__header select, .js-datereturn-dialog .picker__header select").removeAttr("disabled"),this.$el.addClass("selected"),this.trigger("block:form"),this.picker.open(!1),this.isOpened=!0)},animatedClosing:function(){var n=$(this.options.pickadateContainer());n.find(".picker.picker--opened").fadeOut(300,_.bind(function(){this.picker.close(!1);this.close()},this))},initialize:function(n){this.setElement(n.el);this.bindUIElements();this.type=n.type;this.model=new i.Model;this.getPointOfReference=n.getPointOfReference;this.model.on("change:date",_.bind(function(){var n=this.model.get("date");n?(this.ui.input.attr("data-active","true"),this.$el.removeClass("inactive").addClass("active")):(this.ui.input.attr("data-active","false"),this.$el.removeClass("active").addClass("inactive"),this.picker.clear());this.renderDateCover(this.model.get("date"));this.trigger("set",n,this.picker.get("select"))},this));this._initPicker();t.Utils.Ui.on("breakpoint:change",this._initPicker,this);var r=$(this.options.pickadateContainer())},onRender:function(){var n=$(this.options.pickadateContainer()),u,r,i,f;this.createCustomHeader();this.addButtons();this.addAccInput();n.find(".picker__day.picker__day--infocus").on("touchstart click",_.bind(function(n){var i,r;if(n.preventDefault(),i=$(n.target),i.hasClass("picker__day--disabled"))return!1;this.ui.input.pickadate("picker").set("select",moment(i.data("pick")).format("YYYY-MM-DD"));r=this.type==="depart"?"Datechooser-from":"Datechooser-to";t.tracking.trackEvent("home",r,"Single");this.animatedClosing();n.stopPropagation()},this));u=$('<div class="calendar_header" data-i18n="'+this.getHeaderText(this.type)+'"><\/div>');r=$('<button class="btn-close invert" aria-label="'+$.t("aria.common.close")+'"><i class="ss-icon-close ss-icon"><\/i><\/button>');n.find(".picker__header").before(u).before(r);n.find(".picker__header").attr("aria-hidden",!0);r.on("click",_.bind(function(n){n.stopPropagation();n.preventDefault();this.picker&&this.picker.close&&this.animatedClosing()},this));this.$el.find("input").css({"font-size":"16px"});this.$el.i18n();n.i18n();i=this.$el.find("input");f=i.attr("aria-owns");i.removeAttr("aria-owns");i.attr("aria-controls",f)}})});App.module("Views",function(n,t,i,r){n.DialogView=r.ItemView.extend({bodyModalLockClassName:"modal-lock",events:{"click .js-dialog-ok":function(){var n=this.model.get("type");this.trigger("dialog:ok",n);this.triggerMethod("close")},"click .js-dialog-close":function(n){n.preventDefault();this.triggerMethod("close")},"click .js-popup-frame":function(n){$(n.target).hasClass("js-popup-frame")&&this.triggerMethod("close")}},onRender:function(){this.model=new i.Model;this.$el.hide();this.$el.i18n()},onShow:function(){this._focusedElement=$(document.activeElement);this.$el.find(":input").first().focus()},onClose:function(){$(document).unbind("keydown.dialogWindow");$("html").removeClass(this.bodyModalLockClassName);this.$el.hide();this._focusedElement&&this._focusedElement.focus()},onKeypress:function(n){switch(n.keyCode){case 27:this.triggerMethod("close")}}})});App.module("Views",function(n){n.DialogHelpView=n.DialogView.extend({template:"#dialog-help-template",onShow:function(){$("html").addClass(this.bodyModalLockClassName);$(document).bind("keydown.dialogWindow",_.bind(this.onKeypress,this));this.$el.i18n().show()}})});App.module("Views",function(n){n.DialogResetFilterView=n.DialogView.extend({template:"#dialog-reset-filter-template",ui:{prompt:".js-prompt",close:".js-dialog-close",reset:".js-dialog-ok"},onShow:function(t){this.model.set("type",t);this.ui.prompt.attr("data-i18n","dialogs.reset-filter.prompt-"+t);this.ui.prompt.i18n();$("html").addClass(this.bodyModalLockClassName);$(document).bind("keydown.dialogWindow",_.bind(this.onKeypress,this));this.$el.show();n.DialogView.prototype.onShow.apply(this,arguments)}})});App.module("Views",function(n,t,i){n.BaseDropdownItemView=i.Marionette.ItemView.extend({tagName:"li",template:"#base-dropdown-item-template",events:{"click @ui.anchor":"onAnchorClick"},ui:{anchor:".js-dropdown-item"},onAnchorClick:function(n){(n.preventDefault(),this.model.get("disabled"))||(this.model.set("selected",!0),this.trigger("item:select",this.model))},onRender:function(){this.$el.i18n()}});n.BaseDropdownMultiselectItemView=n.BaseDropdownItemView.extend({tagName:"li",template:"#base-dropdown-multiselect-item-template",events:{"change @ui.checkbox":"onCheckboxChange"},ui:{checkbox:".js-dropdown-checkbox"},onCheckboxChange:function(){this.model.get("disabled")||(this.model.set("selected",this.ui.checkbox.is(":checked")),this.trigger("item:check",this.model))}});n.BaseDropdownHeaderView=i.Marionette.ItemView.extend({template:"#base-dropdown-header-template",ui:{toggleName:".js-dropdown-toggle-name"},templateHelpers:{getMultiselectTitle:function(){var n=this.selection||[],t=n.length;return t>0&&t<this.options.length?this.label+" ("+n.length+")":this.label},getSingleselectTitle:function(){var n=this.selection;return n&&n.length>0?_.pluck(n,"text").join(", "):this.label},getTitle:function(){return this.multiselect?this.getMultiselectTitle():this.getSingleselectTitle()}},modelEvents:{change:function(){this.render()}},onRender:function(){this.$el.i18n()}});n.BaseDropdownView=i.Marionette.CompositeView.extend({template:"#base-dropdown-template",childView:n.BaseDropdownItemView,childViewContainer:".js-dropdown-items-container",headerView:n.BaseDropdownHeaderView,opened:!1,ui:{toggleContainer:".js-dropdown-toggle",dropdownContainer:".js-dropdown-container",itemsContainerWrapper:".js-dropdown-container-wrapper"},events:{"click @ui.toggleContainer":"onToggleClick"},childEvents:{"item:select":"_onItemSelected","item:check":"_onItemChecked"},_onItemSelected:function(n,t){this.select(t)},_onItemChecked:function(){this.multiselect()},onToggleClick:function(n){(n.preventDefault(),this.model.get("disabled"))||(t.GlobalEvents.trigger("global:click",n),this.toggle())},select:function(n){this.setValue([n]);this._triggerChangeEvent();this.close();this.focus()},multiselect:function(){this.model.set("selection",this.getSelection(),{silent:!0});this.model.trigger("change");this._triggerChangeEvent()},getSelection:function(){return this.collection.filter(function(n){return n.get("selected")})},getInvertedSelection:function(){return this.collection.filter(function(n){return!n.get("selected")})},_triggerChangeEvent:function(){this.trigger("change",this.getValue())},getValue:function(){return this.model.get("selection")},setValue:function(n){var t=this.getValue();_.each(t,function(n){n.set("selected",!1)});_.each(n,function(n){n.get("selected")||n.set("selected",!0)});this.model.set("selection",n);this.collection.trigger("reset")},onRender:function(){typeof this.headerView=="function"&&(this.headerView=new this.headerView({model:this.model}));this.ui.toggleContainer.html(this.headerView.render().$el);this.$el.i18n()},open:function(){this.opened||(this._bindGlobalClick(),this.ui.toggleContainer.addClass("selected").attr("aria-expanded",!0),this.ui.itemsContainerWrapper.addClass("active"),this.ui.dropdownContainer.addClass("opened"),this.opened=!0,this.trigger("open",this))},focus:function(){this.ui.toggleContainer.focus()},close:function(){this.opened&&(this._unbindGlobalClick(),this.ui.toggleContainer.removeClass("selected").attr("aria-expanded",!1),this.ui.itemsContainerWrapper.removeClass("active"),this.ui.dropdownContainer.removeClass("opened"),this.opened=!1,this.trigger("close",this))},toggle:function(){this.opened?this.close():this.open();this.trigger("toggle",this)},setCollection:function(n){this.collection.reset(n);this.model.set("selection",this.getSelection())},_bindGlobalClick:function(){t.GlobalEvents.on("global:click",_.bind(this._onGlobalClick,this))},_unbindGlobalClick:function(){t.GlobalEvents.off("global:click",_.bind(this._onGlobalClick,this))},_onGlobalClick:function(n){this.$el.is(n.target)||this.$el.has(n.target).length!==0||this.close()},initialize:function(n){this.model=new t.SearchResult.Models.DropdownModel(n.model);this.collection=new t.SearchResult.Models.DropdownCollection(n.collection);this.model.set("selection",this.getSelection());this.model.set("options",this.collection)}})});App.module("Views",function(n,t,i){n.DefaultDropdownItemView=i.Marionette.ItemView.extend({template:"#dropdown-item-template",events:{"click @ui.anchor":"onAnchorClick"},ui:{anchor:".js-dropdown-item"},modelEvents:{},onAnchorClick:function(n){n.preventDefault();this.trigger("item:selected",this.model)},onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.i18n()}});n.DefaultDropdownHeaderView=i.Marionette.ItemView.extend({template:"#dropdown-header-template",ui:{toggleName:".js-dropdown-toggle-name"},modelEvents:{change:function(){this.render()}},onRender:function(){this.$el.i18n()},initialize:function(){}});n.DropdownView=i.Marionette.CompositeView.extend({template:"#dropdown-template",templateHelpers:{tabindex:0,label:"",ariaLabel:""},childView:n.DefaultDropdownItemView,headerView:n.DefaultDropdownHeaderView,childViewContainer:".js-dropdown-items-container",opened:!1,isModal:!1,ui:{headerContainer:".js-header-container",toggleContainer:".js-dropdown-toggle",itemsContainerWrapper:".js-dropdown-container-wrapper"},events:{"click @ui.toggleContainer":"onToggleClick"},childEvents:{"item:selected":function(n,t){this.select(t)}},onToggleClick:function(n){(n.preventDefault(),typeof this.disabled=="boolean"&&this.disabled)||(t.GlobalEvents.trigger("global:click",n),this.toggle())},select:function(n,t){(t=t||!1,n.get("disabled"))||(this.selected&&!_.isEqual(this.selected.attributes,n.attributes)&&(this.selected.set(n.attributes),this.headerView.model.set(n.attributes),t||this.trigger("change",n.attributes)),this.model=n,this.close(),this.focus())},getValue:function(){return this.selected},onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.className&&this.$el.addClass(this.className);typeof this.headerView=="function"&&(this.headerView=new this.headerView({model:this.selected.clone()}));this.ui.headerContainer.html(this.headerView.render().$el);this.onAfterRender&&typeof this.onAfterRender=="function"&&this.onAfterRender()},open:function(){t.GlobalEvents.on("global:update-results",this._adjustPosition,this);this.ui.toggleContainer.addClass("selected").attr("aria-expanded",!0);this.ui.itemsContainerWrapper.css({visibility:"hidden"}).addClass("active");this._adjustPosition();this.ui.itemsContainerWrapper.css("visibility","visible");this.opened=!0;this.trigger("open",this);this.onOpen&&this.onOpen()},focus:function(){this.ui.toggleContainer.focus()},close:function(){t.GlobalEvents.off("global:update-results",this._adjustPosition,this);this.ui.toggleContainer.removeClass("selected").attr("aria-expanded",!1);this.ui.itemsContainerWrapper.removeClass("active");this.opened=!1;this.trigger("close",this);this.onClose&&this.onClose()},toggle:function(){this.opened?this.close():this.open();this.trigger("toggle",this)},_adjustPosition:function(){var n=this.ui.itemsContainerWrapper.css({marginTop:"auto"}).closest(".application"),i=n.offset()||{},r=n.height(),u=this.ui.itemsContainerWrapper.offset(),f=this.ui.itemsContainerWrapper.outerHeight(),t=i.top+r-(u.top+f+10);t<0&&this.ui.itemsContainerWrapper.css("margin-top",t+"px")},_bindGlobalClose:function(){t.GlobalEvents.on("global:click",_.bind(this._onGlobalClick,this))},_onGlobalClick:function(n){this.$el.find(".js-dropdown-toggle").hasClass("selected")&&!this.isModal&&(this.$el.is(n.target)||this.$el.has(n.target).length!==0||(this.close(),this.trigger("toggle",this)))},_bindEvents:function(){this._bindGlobalClose()},onBeforeRenderCollection:function(){this.trigger("before:render-dropdown")},initialize:function(n){n;this.model=n&&n.model?n.model:new i.Model;this.collection=n&&n.collection?n.collection:new i.Collection;this.selected=this.getInitialState&&typeof this.getInitialState=="function"?this.getInitialState().clone():this.model.clone();this.templateHelpers.label=n&&n.label?n.label:"";this.templateHelpers.tabindex=n&&n.tabindex?n.tabindex:0;this.templateHelpers.ariaLabel=n&&n.ariaLabel?n.ariaLabel:"";this._bindEvents();this.onAfterInitialize&&typeof this.onAfterInitialize=="function"&&this.onAfterInitialize()}})});App.module("Views",function(n,t,i){var r=Brace.Model.extend({namedAttributes:{all:"number",filtered:"number",withReset:"boolean",lastResponse:"boolean",showSpinner:"boolean",disableResetButton:"boolean"},defaults:function(){return{all:-1,filtered:-1,withReset:!0,lastResponse:!1,showSpinner:!1,disableResetButton:!1}}});n.FilterCountIndicatorView=i.Marionette.ItemView.extend({template:"#filter-count-indicator-template",events:{"click .js-filtered":"onClickFilteredBtn","focusin .js-filtered":"onFocusFilteredBtn","click .js-filter-reset-btn":"onClickResetBtn"},ui:{indicatorLabel:".js-filter-indicator-label",resetBtn:".js-filter-reset-btn",countSpinner:".js-count-spinner"},isResetBtnVisible:!1,onFocusFilteredBtn:function(){this.onClickFilteredBtn();this.ui.resetBtn.focus()},onClickFilteredBtn:function(n){n&&n.preventDefault();this.model.getWithReset()&&(this.isResetBtnVisible=!0,this.ui.indicatorLabel.animate({marginTop:-this.ui.indicatorLabel.parent().height()},300))},onClickResetBtn:function(n){n.preventDefault();this.model.getWithReset()&&(this.isResetBtnVisible=!1,this.trigger("reset:filter"))},onRender:function(){this.model.getAll()===this.model.getFiltered()&&(this.isResetBtnVisible=!1);this.model.getWithReset()&&this.isResetBtnVisible&&this.ui.indicatorLabel.css("margin-top",-this.ui.indicatorLabel.parent().height());this.ui.countSpinner&&this.ui.countSpinner.length>0&&this.model.getShowSpinner()&&!this.model.getLastResponse()&&t.Utils.Spin(this.ui.countSpinner,{lines:10,length:6,width:2,corners:1,zIndex:10});this.$el.i18n()},update:function(n){this.model.set(n);this.render()},initialize:function(n){this.model=new r({showSpinner:!!n.showSpinner,disableResetButton:!!n.disableResetButton,withReset:!!n.withReset})}})});App.module("Views",function(n,t,i){n.MessageBoxView=i.Marionette.ItemView.extend({model:i.Model,template:"#base-message-box-template",templateHelpers:function(){return{cssClasses:function(){return this.cssClass||"gray"},isMultiLine:function(){return this.messages&&this.messages.length>1?"multiline":""}}},events:{"click .js-btn-close":function(n){n.preventDefault();this.$el.remove();this.trigger("agree")}}})});App.module("Views",function(n,t){n.MonthSelectorView=t.Views.DropdownView.extend({headerView:t.Views.DefaultDropdownHeaderView.extend({template:"#month-selector-template"}),childView:t.Views.DefaultDropdownItemView.extend({template:"#month-selector-item-template",events:{click:function(){return this.trigger("item:selected",this.model),!1}}})})});App.module("Views",function(n,t,i){function r(n){n.onselectstart=function(){return!1};n.style.MozUserSelect="none";n.style.KhtmlUserSelect="none";n.unselectable="on"}n.PlusMinisViewModel=Brace.Model.extend({namedAttributes:{icon:"string",value:"number",maxValue:"number",minValue:"number"},defaultValues:{icon:"",value:0,maxValue:10,minValue:0},increase:function(){var n=this.getValue();n<this.getMaxValue()&&this.setValue(n+1)},decrease:function(){var n=this.getValue();n>this.getMinValue()&&this.setValue(n-1)},set:function(n,t){return n.hasOwnProperty("value")?(n.value>this.getMaxValue()&&(n.value=this.getMaxValue()),n.value<this.getMinValue()&&(n.value=this.getMinValue())):n==="value"&&(t>this.getMaxValue()&&(t=this.getMaxValue()),t<this.getMinValue()&&(t=this.getMinValue())),i.Model.prototype.set.call(this,n,t)},initialize:function(n){this.setValue(n.value)}});n.PlusMinusView=i.Marionette.ItemView.extend({template:"#plus-minus-view-template",buttonsShown:!1,behaviors:{ViewUnwrap:{}},events:{keydown:function(n){switch(n.which){case 40:n.preventDefault();this.model.decrease();break;case 38:n.preventDefault();this.model.increase()}},click:function(){this.buttonsShown?this.hideActionBtns():this.showActionBtns()},"click .js-plus":function(n){n.stopPropagation();this.model.increase()},"click .js-minus":function(n){n.stopPropagation();this.model.decrease()}},modelEvents:{"change:value":function(n){this.ui.countIndicator.html(n.getValue().toString())}},ui:{plusBtn:".js-plus",minusBtn:".js-minus",countIndicator:".js-count-indicator",cover:".plus-minus-selector"},showActionBtns:function(){this.$el.addClass("active");this.buttonsShown=!0},hideActionBtns:function(){this.$el.removeClass("active");this.buttonsShown=!1},onRender:function(){r(this.ui.plusBtn[0]);r(this.ui.minusBtn[0]);this.ui.cover.makeFocusable(1);this.ui.plusBtn.makeFocusable(1);this.ui.minusBtn.makeFocusable(1);t.GlobalEvents.on("global:click",_.bind(function(n){this.$el.is(n.target)||this.$el.has(n.target).length!==0||this.hideActionBtns()},this))},initialize:function(){}})});App.module("Views",function(n,t,i){n.PoweredByView=i.Marionette.ItemView.extend({template:"#powered-by-template",templateHelpers:{showPoweredBy:!t.Services.Feature.check("hidePoweredBy","on"),disablePoweredByLink:t.Services.Feature.check("disablePoweredByLink","on")},model:new i.Model({poweredByUrl:t.Settings.poweredByUrl}),ui:{poweredByLink:"a.js-powered-by"},events:{"click @ui.poweredByLink":"onPoweredByLinkClick"},onPoweredByLinkClick:function(){var n=this.model.get("poweredByUrl"),r=this.options||{},i=this.options.trackingLabel||"Logo_PoweredBy";t.tracking.trackEvent("home",i,n)},onRender:function(){this.$el.i18n()}})});App.module("Views",function(n,t,i,r){var u=30;n.ProgressbarView=r.ItemView.extend({template:"#progressbar-template",templateHelpers:{title:$.i18n.t("search-result.summary.progress-status").replace("__completeTime__",u)},ui:{progressbar:".js-progressbar",progress_bar_title:".progress-bar-title",progress_bar_processed_text:".progress-bar-processed-text"},behaviors:{ViewUnwrap:{}},_getTitle:function(n){return n=n||"",$.i18n.t("search-result."+t.Settings.wlType.toLowerCase()+".progress-status").replace("__completeTime__",n)},_formatProcessed:function(n,t){return n=n||0,t=t||0,["(",n,"/",t,"社&nbsp;完了)"].join("")},onRender:function(){var t=this.model.get("auto"),n=this.model.get("interval");t&&(n=n?n:200,this.interval=setInterval(_.bind(this.autosetPercent,this),n));this.setProgress()},setPercent:function(n){var r=this.model.get("percent")||0,t,i;n=(n||0)>r?n:r;this.model.set("percent",n);t=this.model.get("min");t=t?t:0;i=u;this.templateHelpers.title=i>0?this._getTitle(i):"";this.ui.progress_bar_title.html(this.templateHelpers.title);this.ui.progressbar.css("width",Math.max(n,t)+"%")},setProgress:function(n,t){var i=this._formatProcessed(n,t);this.ui.progress_bar_processed_text.html(i)},autosetPercent:function(){var n=this.model.get("percent"),i=this.model.get("diff"),t=this.model.get("stop");t=t?t:100;i=i?i:5;n=(n?n:0)+i;n>=t&&(n=t,this.stopAutoset());this.setPercent(n)},onDestroy:function(){clearInterval(this.interval)},stopAutoset:function(){clearInterval(this.interval)}})});App.module("Views",function(n,t,i){var r=Brace.Model.extend({namedAttributes:{type:"string",products:["string"]}});n.WhiteLabelSelectorView=i.Marionette.ItemView.extend({template:"#white-label-selector-template",behaviors:{ViewUnwrap:{}},ui:{flightsLink:'[data-tab="flights"]',hotelsLink:'[data-tab="hotels"]',carhireLink:'[data-tab="carhire"]',poweredBy:".js-powered-by-container"},events:{"click @ui.flightsLink":"onFlightsTabClickHandler","click @ui.hotelsLink":"onHotelsTabClickHandler","click @ui.carhireLink":"onCarHireTabClickHandler"},onFlightsTabClickHandler:function(n){return(t.GlobalEvents.trigger("global:click",n),t.tracking.trackEvent("home","Tab_Flights"),$(".js-errors").hide(),t.Utils.Ui.isWidget())?(window.SSWLWidget.loadWidget("flights"),this.destroy(),!1):AppSettings.config.isScaffold?!0:this.model.getType()==="flights"?(t.Router.navigate("/",{trigger:!0}),!1):!0},onHotelsTabClickHandler:function(n){return(t.GlobalEvents.trigger("global:click",n),t.tracking.trackEvent("home","Tab_Hotels"),$(".js-errors").hide(),t.Utils.Ui.isWidget())?(window.SSWLWidget.loadWidget("hotels"),this.destroy(),!1):this.model.getType()==="hotels"?(t.Router.navigate("/",{trigger:!0}),!1):!0},onCarHireTabClickHandler:function(n){return(t.GlobalEvents.trigger("global:click",n),t.tracking.trackEvent("home","Tab_CarHire"),$(".js-errors").hide(),t.Utils.Ui.isWidget())?(window.SSWLWidget.loadWidget("carhire"),this.destroy(),!1):this.model.getType()==="carhire"?(t.Router.navigate("/",{trigger:!0}),!1):!0},updateLinksHref:function(){this.ui.flightsLink.length&&this.ui.flightsLink.attr("href",t.Utils.WhiteLabelLocation.getFlightsTabUrl());this.ui.hotelsLink.length&&this.ui.hotelsLink.attr("href",t.Utils.WhiteLabelLocation.getHotelsPageUrl());this.ui.carhireLink.length&&this.ui.carhireLink.attr("href",t.Utils.WhiteLabelLocation.getCarHirePageUrl())},onRender:function(){t.Utils.Ui.isWidget()||$.when(t.Services.HomeCity.getHomeCity(),t.Services.Currency.getCurrency(),t.Services.Language.getLanguage()).then(_.bind(function(){this.updateLinksHref()},this));var n=new t.Views.PoweredByView({trackingLabel:"Logo_WhiteLabelSelector"});this.ui.poweredBy.html(n.render().$el);this.$el.i18n()},initialize:function(n){this.model=new r({type:n.type,products:n.products})}})});App.module("CookieDisclaimer",function(n,t,i){n.CookieDisclaimerView=i.Marionette.ItemView.extend({template:"#cookie-disclaimer-template",events:{"click .js-ok-button":"onOkButtonClick"},ui:{info:".js-info",submitAgreement:".js-submit-agreement"},behaviors:{ViewUnwrap:{}},onOkButtonClick:function(n){n.preventDefault();$.cookie("disclaimer-agree","true",{expires:365,path:"/"});this.destroy()},onRender:function(){var n=this;$.when(t.Services.Market.getMarket(),t.Services.Language.getLanguage()).done(function(t,i){var u,f,r,e;n.$el.i18n();n.ui.info.i18n({partnerlink:'<a href="'+AppSettings.config.authorityUrl+'">'+AppSettings.config.name+"<\/a>"});u=!0;!AppSettings.config.cookiePolicy||(u=!1);f='<a target="_blank" href="'+_.template(AppSettings.privacyAndPolicyUrl,{market:t,locale:i})+'">Skyscanner<\/a>';r="";u?r=$.i18n.t("home.cookie-disclaimer.submit-agreement-skyscanner-only",{policylink:f}):(e='<a href="'+AppSettings.config.cookiePolicy+'">'+AppSettings.config.name+"<\/a>",r=$.i18n.t("home.cookie-disclaimer.submit-agreement-skyscanner-partner",{partnername:AppSettings.config.name,policylink:f,partnerpolicylink:e}));n.ui.submitAgreement.i18n({placeholder:r})})}})});App.module("CookieDisclaimer",{startWithParent:!1,define:function(n,t){n.CookieDisclaimerCountries=["AT","BE","BG","HR","CY","CZ","DK","EE","FI","FR","DE","GR","HU","IE","IT","LV","LT","LU","MT","NL","PL","PT","RO","SK","SI","ES","SE","UK"];n.agreeWithDisclaimer=function(){return $.cookie("disclaimer-agree")==="true"};n.on("start",function(){n.agreeWithDisclaimer()||t.Services.Feature.check("disableCookieMessage")||t.Services.Market.getMarket().done(function(i){n.CookieDisclaimerCountries.indexOf(i)!==-1&&t.trigger("module.ready",{view:new n.CookieDisclaimerView,name:"Cookie"})})})}});App.module("CultureControls",function(n,t){n.CurrencySelectorView=t.Views.DropdownView.extend({headerView:t.Views.DefaultDropdownHeaderView.extend({template:"#currency-selector-template"}),childView:t.Views.DefaultDropdownItemView.extend({template:"#currency-selector-item-template",templateHelpers:_.extend({},t.Views.DefaultDropdownItemView.prototype.templateHelpers,{isSelected:function(){return typeof this.selected=="boolean"&&this.selected}})}),behaviors:{DropdownSlide:{},DropdownExtendedKeysControl:{},DropdownMobileFullscreen:{getHeaderLabel:function(){return'<span class="modal-title" data-i18n="head.currency"><\/span>'}},DropdownTypeControl:{}}})});App.module("CultureControls",function(n,t){n.LanguageSelectorView=t.Views.DropdownView.extend({headerView:t.Views.DefaultDropdownHeaderView.extend({template:"#languages-selector-template"}),childView:t.Views.DefaultDropdownItemView.extend({template:"#languages-selector-item-template",templateHelpers:{isSelected:function(){return typeof this.selected=="boolean"&&this.selected}}}),behaviors:{DropdownSlide:{},DropdownExtendedKeysControl:{},DropdownMobileFullscreen:{getHeaderLabel:function(){return'<span class="modal-title" data-i18n="head.language"><\/span>'}},DropdownTypeControl:{}}})});App.module("CultureControls",{startWithParent:!1,define:function(n,t,i){n.CultureControlsView=i.Marionette.ItemView.extend({template:"#culture-controls-template",ui:{currency:".js-currency-selector",language:".js-language-selector"},behaviors:{ViewUnwrap:{}},onRender:function(){this.$el.hide();$.when(this._initializeCurrencySelector(),this._initializeLanguageSelector()).then(_.bind(function(n,t){this.ui.currency.html(n.render().$el);this.ui.language.html(t.render().$el);this.$el.show()},this))},_initializeCurrencySelector:function(){var r=new $.Deferred;return $.when(t.Services.Currency.getCurrency(),t.Services.Currency.getAvailableCurrencies()).then(_.bind(function(u,f){var e=function(){var n=new $.Deferred;return t.Services.Currency.getDefaultCurrencyForCountry().done(function(t){var r=new i.Collection(f),u;return t=_.find(r.models,function(n){return n.get("Code")===t}),u=t.clone(),u.set("isDefault",!0),r.add(u),r.comparator=function(n){var t=!1;return n.get("isDefault")&&(t=!0),[!t,n.get("Code")]},r.sort(),n.resolve(r)}),n.promise()};e().done(function(i){var o=i.find(function(n){var t=n.get("Code")===u;return t&&n.set("selected",!0),t}),f=new n.CurrencySelectorView({collection:i,model:o});f.on("change",function(n){t.Services.Currency.getCurrency().done(function(i){i!==n.Code&&(t.tracking.trackEvent("home","CultureSelect","Currency changed to "+n.Code),t.Services.Currency.setCurrency(n.Code))})});f.resetCollection=function(){e().done(function(n){f.collection.reset(n.toJSON())})};r.resolve(f)})},this)),r.promise()},_initializeLanguageSelector:function(){var r=new $.Deferred;return t.Services.Language.getLanguage().done(_.bind(function(u){var f=t.Dictionaries.SupportedLocales,s=t.Culture.locales,h=_.intersection(_.pluck(f,"code"),s),e=new i.Collection(_.sortBy(_.map(h,function(n){return _.find(f,function(t){return t.code===n})}),function(n){return n.code})),c=e.find(function(n){var t=n.get("code")===u;return t&&n.set("selected",!0),t}),o=new n.LanguageSelectorView({collection:e,model:c});o.on("change",function(n){n.code&&t.tracking.trackEvent("home","CultureSelect","Language changed to "+n.code);t.Services.Language.setLanguage(n)});r.resolve(o)},this)),r.promise()}});n.on("start",function(){var i=new n.CultureControlsView;t.trigger("module.ready",{view:i,name:"CultureControls"})})}});App.module("CarHire.Base.Models",function(n){n.CarClassModel=Brace.Model.extend({namedAttributes:{id:"number",name:"string",sort_order:"number"},defaults:function(){return{id:0,name:"",sort_order:0}}})});App.module("CarHire.Base.Models",function(n,t,i,r,u,f){n.FuelPolicyFilterDictionary={fair:"carhire.search-result.filters.fuel-policy.all-fair-fuel-policy",full_to_full:"carhire.search-result.filters.fuel-policy.full-to-full",quarter_to_quarter:"carhire.search-result.filters.fuel-policy.quarter-to-quarter",half_to_half:"carhire.search-result.filters.fuel-policy.half-to-half",half_to_empty:"carhire.search-result.filters.fuel-policy.half-to-empty",quarter_to_empty:"carhire.search-result.filters.fuel-policy.quarter-to-empty",full_to_empty:"carhire.search-result.filters.fuel-policy.full-to-empty",free_full_tank:"carhire.search-result.filters.fuel-policy.free-full-tank"};n.FuelPolicyTooltipDictionary={full_to_full:"carhire.search-result-item.fair-fuel-tooltip-same-amount",quarter_to_quarter:"carhire.search-result-item.fair-fuel-tooltip-same-amount",half_to_half:"carhire.search-result-item.fair-fuel-tooltip-same-amount",full_to_empty:"carhire.search-result-item.fair-fuel-tooltip-full-to-empty",half_to_empty:"carhire.search-result-item.fair-fuel-tooltip-half-to-empty",quarter_to_empty:"carhire.search-result-item.fair-fuel-tooltip-quarter-to-empty",free_full_tank:"carhire.search-result-item.fair-fuel-tooltip-free-full-tank",undefined:"carhire.search-result-item.undefined"};n.CarFuelTypeDictionary=function(){var n=0;return f.object(f.map({petrol:{resourceKey:"petrol",icon:"ss-icon ss-icon-fuel"},diesel:{resourceKey:"diesel",icon:"ss-icon ss-icon-fuel"},lpg:{resourceKey:"lpg",icon:"ss-icon ss-icon-fuel"},electric:{resourceKey:"electric",icon:"ss-icon ss-icon-electric"},hybrid:{resourceKey:"hybrid",icon:"ss-icon ss-icon-electric"},multi_fuel:{resourceKey:"multi_fuel",icon:"ss-icon ss-icon-fuel"}},function(t,i){var r={};return r[i]={},n++,r={id:n,icon:t.icon,resourceKey:"carhire.search-result.filters.fuel-type."+t.resourceKey},[i,r]}))}();n.CarFeaturesDictionary=function(){var n=0;return f.object(f.map({air_conditioning:{resourceKey:"air_conditioning"},"value_add.free_breakdown_assistance":{resourceKey:"free_breakdown_assistance"},"value_add.included_mileage.unlimited":{resourceKey:"included_mileage.unlimited"},"value_add.additional_drivers.paid0":{resourceKey:"free-additional_driver"},"value_add.free_equipments.radio":{resourceKey:"free_equipments.radio"},"value_add.free_equipments.gps":{resourceKey:"free_equipments.gps"},"value_add.free_equipments.roof_rack":{resourceKey:"free_equipments.roof_rack"},"value_add.free_equipments.ski_rack":{resourceKey:"free_equipments.ski_rack"},"value_add.free_equipments.snow_chains":{resourceKey:"free_equipments.snow_chains"},"value_add.free_equipments.snow_tyres":{resourceKey:"free_equipments.snow_tyres"},"value_add.free_equipments.baby_seat":{resourceKey:"free_equipments.baby_seat"},"value_add.free_equipments.child_seat":{resourceKey:"free_equipments.child_seat"},"value_add.free_equipments.booster_seat":{resourceKey:"free_equipments.booster_seat"},"value_add.free_cancellation":{resourceKey:"free_free_cancellation"},"value_add.one_way_surcharge":{resourceKey:"one_way_surcharge"},"value_add.young_driver_surcharge":{resourceKey:"young_driver_surcharge"},"value_add.insurance.theft_protection":{resourceKey:"insurance.theft_protection"},"value_add.insurance.third_party_cover":{resourceKey:"insurance.third_party_cover"},"value_add.insurance.free_collision_waiver":{resourceKey:"insurance.free_collision_waiver"},"value_add.insurance.free_damage_refund":{resourceKey:"insurance.free_damage_refund"}},function(t,i){var r={};return r[i]={},n++,r={id:n,resourceKey:"carhire.search-result-item.additional-features."+t.resourceKey},[i,r]}))}();n.CarLocationItemModel=Brace.Model.extend({namedAttributes:{address:"string",distance_to_search_location_in_km:"number",geo_info:["number"],isValid:"boolean"},defaults:function(){return{address:"",distance_to_search_location_in_km:0,geo_info:[0,0],isValid:!1}},validChecher:function(){this.setIsValid(!f.isEqual(this.getGeo_info(),[0,0]))},initialize:function(){this.validChecher();this.on("change:geo_info",this.validChecher,this)}});n.CarLocationModel=Brace.Model.extend({namedAttributes:{pick_up:n.CarLocationItemModel,drop_off:n.CarLocationItemModel,mapUrls:"object",isValid:"boolean"},defaults:function(){return{mapUrls:{},isValid:!1}},validChecher:function(){var n=this.getPick_up(),t=this.getDrop_off(),i=n?n.getIsValid():!1,r=t?t.getIsValid():!1;this.setIsValid(i||r)},initialize:function(){this.validChecher();this.on("change:pick_up",this.validChecher,this);this.on("change:drop_off",this.validChecher,this)}});n.CarValueAddModel=Brace.Model.extend({namedAttributes:{additional_drivers:"object",free_breakdown_assistance:"boolean",free_cancellation:"boolean",free_equipments:Array,fuel:"object",included_mileage:"object",one_way_surcharge:"boolean",insurance:"object",young_driver_surcharge:"boolean"},defaults:function(){return{additional_drivers:{paid:{currency_id:"",price:-1,original_price:{currency_id:"",price:-1}},free:{min_age:-1,num:-1}},free_breakdown_assistance:!1,free_cancellation:!1,free_equipments:[],fuel:{type:"",fair:!1,policy:""},included_mileage:{unlimited:!1,included:0,unit:""},one_way_surcharge:null,insurance:{free_damage_refund:!1,free_collision_waiver:!1,third_party_cover:!1,theft_protection:!1},young_driver_surcharge:null}}});n.CarModel=f.extend(Brace,f.extend(Brace.Mixins,{createMethodName:function(n,t){for(var r,i=t;(r=i.indexOf("_"))!==-1;)i=i.substr(0,r)+i.charAt(r+1).toUpperCase()+i.substr(r+2);return n+i.charAt(0).toUpperCase()+i.substr(1)}})).Model.extend({namedAttributes:{air_conditioning:"boolean",car_class_id:"number",carClass:n.CarClassModel,deeplink_url:"string",image_id:"number",image:n.ImageModel,location:n.CarLocationModel,mandatory_chauffeur:"boolean",manual:"boolean",price_all_days:"number",wrappedPrice:"string",seats:"number",sipp:"string",value_add:n.CarValueAddModel,vehicle:"string",website_id:"string",webSite:n.WebsiteModel,isEmpty:"boolean",favorite:"boolean",fingerprint:"string",showDetails:"boolean",vendor:n.VendorModel},defaults:function(){return{air_conditioning:!1,car_class_id:0,deeplink_url:"",image_id:0,location:new n.CarLocationModel,mandatory_chauffeur:!1,manual:!0,price_all_days:0,wrappedPrice:"",seats:0,sipp:"",value_add:new n.CarValueAddModel,vehicle:"",website_id:"",carClass:new n.CarClassModel,image:new n.ImageModel,webSite:new n.WebsiteModel,isEmpty:!1,favorite:!1,showDetails:!1,vendor:new n.VendorModel}},takeCarFuelType:function(t){var i=[],r=t||"resourceKey";return f.has(this.getValueAdd().getFuel(),"type")&&this.getValueAdd().getFuel().type!==""&&this.getValueAdd().getFuel().type in n.CarFuelTypeDictionary&&(i=n.CarFuelTypeDictionary[this.getValueAdd().getFuel().type.toLowerCase()][r]),i},takeCarFeatures:function(t){var i=[],r=t||"resourceKey";return this.getAirConditioning()===!0&&i.push(n.CarFeaturesDictionary.air_conditioning[r]),this.getValueAdd().getFree_breakdown_assistance()&&i.push(n.CarFeaturesDictionary["value_add.free_breakdown_assistance"][r]),this.getValueAdd().getFree_cancellation()&&i.push(n.CarFeaturesDictionary["value_add.free_cancellation"][r]),this.getValueAdd().getOne_way_surcharge()&&i.push(n.CarFeaturesDictionary["value_add.one_way_surcharge"][r]),this.getValueAdd().getYoung_driver_surcharge()&&i.push(n.CarFeaturesDictionary["value_add.young_driver_surcharge"][r]),this.getValueAdd().getIncluded_mileage().unlimited&&i.push(n.CarFeaturesDictionary["value_add.included_mileage.unlimited"][r]),f.has(this.getValueAdd().getAdditional_drivers(),"free")&&this.getValueAdd().getAdditional_drivers().free.num>0&&i.push(n.CarFeaturesDictionary["value_add.additional_drivers.paid0"][r]),f.each(this.getValueAdd().getFree_equipments(),function(t){i.push(n.CarFeaturesDictionary["value_add.free_equipments."+t.toLowerCase()][r])}),this.getValueAdd().getInsurance().free_damage_refund&&i.push(n.CarFeaturesDictionary["value_add.insurance.free_damage_refund"][r]),this.getValueAdd().getInsurance().free_collision_waiver&&i.push(n.CarFeaturesDictionary["value_add.insurance.free_collision_waiver"][r]),this.getValueAdd().getInsurance().third_party_cover&&i.push(n.CarFeaturesDictionary["value_add.insurance.third_party_cover"][r]),this.getValueAdd().getInsurance().theft_protection&&i.push(n.CarFeaturesDictionary["value_add.insurance.theft_protection"][r]),i},takeDetailedCarFeaturesList:function(){var t=f.map(this.takeCarFeatures(),function(n){return{name:n,tooltip:""}}),i=this.getValueAdd().getFuel();return i.fair&&t.push({name:"carhire.search-result-item.fair-fuel-title",tooltip:u.i18n.t(n.FuelPolicyTooltipDictionary[i.policy]||"undefined")}),t}})});App.module("CarHire.Base.Models",function(n){n.ImageModel=Brace.Model.extend({namedAttributes:{id:"number",url:"string"},defaults:function(){return{id:0,url:""}}})});App.module("CarHire.Base.Models",function(n){n.VendorModel=Brace.Model.extend({namedAttributes:{id:"string",name:"string",logo_url:"string"},defaults:function(){return{id:"",name:"",logo_url:""}}})});App.module("CarHire.Base.Models",function(n){n.WebsiteModel=Brace.Model.extend({namedAttributes:{id:"string",name:"string",image_url:"string",in_progress:"boolean",optimised_for_mobile:"boolean"},defaults:function(){return{id:"",name:"",image_url:"",in_progress:!1,optimised_for_mobile:!1}}})});App.module("CarHire.SearchResult",function(n,t,i,r){n.CarFeatureModel=Brace.Model.extend({namedAttributes:{name:"string",tooltip:"string"},defaults:function(){return{name:"",tooltip:""}}});n.CarFeatureCollection=Brace.Collection.extend({model:n.CarFeatureModel});n.CarFeatureView=r.ItemView.extend({model:n.CarFeatureModel,template:"#carhire-search-result-list-car-feature-template",tagName:"li"});n.CarFeaturesView=r.CollectionView.extend({tagName:"ul",childView:n.CarFeatureView})});App.module("FavoritesBasket.Models",function(n){n.CarHireItemModel=App.CarHire.Base.Models.CarModel.extend({namedAttributes:{fingerprint:"string",pickupPlace:"string",dropoffPlace:"string",pickupDate:"string",pickupTime:"string",dropoffDate:"string",dropoffTime:"string",ageGroup:"string",sameDropoffPlace:"boolean",pickupPlaceText:"string",dropoffPlaceText:"string",link:"string",priceWithoutCurrency:"number",priceWithCurrency:"string",timestamp:"number",soldOut:"boolean"},defaults:function(){return{pickupPlace:"",dropoffPlace:"",pickupPlaceText:"",dropoffPlaceText:"",link:"",sameDropoffPlace:!0,timestamp:0,soldOut:!1}}})});App.module("FavoritesBasket.Models",function(n){n.CategoryModel=Brace.Model.extend({namedAttributes:{type:"string",name:"string",currentTab:"string",otherTabEmptyMessage:"string",searchState:"object",localStorageState:"function",syncState:"function"},defaults:function(){return{otherTabEmptyMessage:""}}})});App.module("FavoritesBasket.Models",function(n){n.FlightItemModel=Brace.Model.extend({namedAttributes:{legs:Array,fingerprint:"string",originplace:"string",destinationplace:"string",originplaceText:"string",destinationplaceText:"string",outbounddate:"string",inbounddate:"string",cabinclass:"string",adults:"number",children:"number",infants:"number",priceWithCurrency:"string",priceWithoutCurrency:"number",agentName:"string",link:"string",isOneWay:"boolean",isAmPmTimeFormatLocale:"boolean",timestamp:"number",soldOut:"boolean"},defaults:function(){return{destinationplace:"",originplaceText:"",destinationplaceText:"",agentName:"",legs:[],isOneWay:!0,timestamp:0,soldOut:!1}}})});App.module("FavoritesBasket.Models",function(n){n.HotelItemModel=Brace.Model.extend({namedAttributes:{name:"string",fingerprint:"string",description:"string",imageUrl:"string",stars:"number",distance:"string",distanceKm:"string",hasPool:"number",hasParking:"number",hasGym:"number",hasWiFi:"number",rating:"number",ratingDesc:"string",ratingClass:"string",agentImageUrl:"string",destination:"string",destinationText:"string",checkin:"string",checkout:"string",guests:"number",rooms:"number",link:"string",priceWithCurrency:"string",priceWithoutCurrency:"number",timestamp:"number",soldOut:"boolean"},defaults:function(){return{name:"",description:"",imageUrl:"",stars:0,distance:"",distanceKm:"",hasPool:0,hasParking:0,hasGym:0,hasWiFi:0,rating:0,ratingDesc:"",ratingClass:"",agentImageUrl:"",destinationText:"",guests:1,rooms:1,link:"",timestamp:0,soldOut:!1}}})});App.module("FavoritesBasket.Views",function(n,t,i,r,u){n.CarHireItemView=i.Marionette.LayoutView.extend({template:"#favorites-carhire-item-template",className:"carhire-item",events:{"click .js-btn-close":"onRemoveClick","click .js-jump-button":"onJumpButtonClick","click .js-sold-out-button":"onSoldOutButtonClick"},modelEvents:{"change:timestamp":"updateAgeTimestamp"},ui:{fuelTypeLabel:".js-main-features-block-fuel-type-label",fuelTypeIcon:".js-main-features-block-fuel-type-icon",ageTimestamp:".js-age-timestamp"},regions:{featuresList:".js-features-list"},templateHelpers:{longPrice:function(){return this.priceWithCurrency&&this.priceWithCurrency.length>=t.Settings.wrappedPriceLength},getItemSummary:function(){var n=new Date(this.pickupDate+" "+this.pickupTime),i=new Date(this.dropoffDate+" "+this.dropoffTime),r=[u.t("favorites.carhire.pick-up"),"&nbsp;",'<span class="emphasized">',this.pickupPlaceText,"&nbsp;",t.Culture.culture.formatDate(n,{date:"fullAbbr"}),",&nbsp;",t.Culture.culture.formatDate(n,{time:"short"}),"<\/span>"].join(""),f=[u.t("favorites.carhire.drop-off"),"&nbsp;",'<span class="emphasized">',this.dropoffPlaceText?this.dropoffPlaceText:this.pickupPlaceText,"&nbsp;",t.Culture.culture.formatDate(i,{date:"fullAbbr"}),",&nbsp;",t.Culture.culture.formatDate(i,{time:"short"}),"<\/span>"].join(""),e=[u.t("favorites.carhire.age"),"&nbsp;",'<span class="emphasized">',this.ageGroup,"<\/span>"].join("");return[r,f,e].join(", ")}},removeItem:function(){t.Utils.FavoritesStorage.CarHire.removeFavorite(this.model.getFingerprint());this.trigger("item-removed",this.model)},getTrackingEventName:function(){return"Favourite_HeaderDelete_Carhire"},getTrackingDetails:function(){var n=_.template("<%= pickupPlace %>_<%= dropoffPlace %>_<%= priceWithCurrency %>");return n({pickupPlace:this.model.getPickupPlace(),dropoffPlace:this.model.getDropoffPlace(),priceWithCurrency:this.model.getPriceWithCurrency()})},onRemoveClick:function(n){n.preventDefault();this.removeItem()},onSoldOutButtonClick:function(n){n.preventDefault();this.removeItem()},onJumpButtonClick:function(n){n.preventDefault();t.Utils.Favorites.isSameCarHireSearch(this.options.searchState,this.model.toJSON())?this.trigger("jump-to-details",this.model.toJSON()):window.location.href=this.model.getLink()},updateAgeTimestamp:function(){var n=this.model.getTimestamp();n?this.ui.ageTimestamp.text(t.Utils.Favorites.addedTimeAgo(n)):this.ui.ageTimestamp.text("")},onRender:function(){this.updateAgeTimestamp();var n=new t.CarHire.SearchResult.CarFeaturesView({collection:new t.CarHire.SearchResult.CarFeatureCollection(_.map(this.model.takeDetailedCarFeaturesList(),function(n){return{name:n.name,tooltip:n.tooltip}}))});this.model.getValueAdd().getFuel().type&&(this.ui.fuelTypeLabel.html(u.i18n.t(this.model.takeCarFuelType())),this.ui.fuelTypeIcon.addClass(this.model.takeCarFuelType("icon")));this.featuresList.show(n);this.$el.i18n()},_buildLink:function(){var n=_.pick(this.model.toJSON(),"pickupPlace","dropoffPlace","pickupDate","pickupTime","dropoffDate","dropoffTime","ageGroup","sameDropoffPlace");return n.scrollto=this.model.getFingerprint(),t.Utils.WhiteLabelLocation.getCarHireSearchPageUrl(n)},initialize:function(){this.model.set({link:this._buildLink()})}})});App.module("FavoritesBasket.Views",function(n,t,i,r,u){n.FavoritesBasketView=i.Marionette.LayoutView.extend({template:"#favorites-basket-template",templateHelpers:{isFlightsVerticalEnabled:function(){return this.verticals.isFlightsEnabled},isHotelsVerticalEnabled:function(){return this.verticals.isHotelsEnabled},isCarHireVerticalEnabled:function(){return this.verticals.isCarHireEnabled}},ui:{totalPrice:".js-favorites-basket-total-price"},className:"favorites-basket categories-container",regions:{flights:".js-flights",hotels:".js-hotels",carhire:".js-carhire"},childEvents:{"item-removed":"onItemRemoved"},toggle:function(n){this.$el.toggleClass("active",n)},openBasket:function(){this.$el.addClass("active").parent().attr("aria-hidden","false")},closeBasket:function(){this.$el.removeClass("active").parent().attr("aria-hidden","true")},updateTotalPriceIndicator:function(){var n=t.Services.Currency.getCurrentCurrencyInfo(),i=t.Utils.Ui.wrapPrice(this.getTotalPriceBasket(),n);this.ui.totalPrice.html(i)},onRender:function(){var n=this.model.get("verticals");n.isFlightsEnabled&&this.flights.show(this.flightsView);n.isHotelsEnabled&&this.hotels.show(this.hotelsView);n.isCarHireEnabled&&this.carhire.show(this.carhireView);this.updateTotalPriceIndicator()},getItemsCount:function(){return _.reduce(this.views,function(n,t){return n+t.getItemsCount()},0)},getTotalPriceBasket:function(){return _.reduce(this.views,function(n,t){return n+t.getTotalPrice()},0)},updateHotelsBasket:function(n){var i=u(window),r=i.scrollTop(),f=this.$el.is(":visible")?this.$el.outerHeight():0;this.hotelsCollection.reset(t.Utils.FavoritesStorage.Hotels.getFavorites(),{silent:!0});this.hotelsView.render();t.vent.trigger(t.VentActions.FavoritesBasket.COUNT_HAS_BEEN_CHANGED,this.getItemsCount());this.updateTotalPriceIndicator();n&&t.vent.trigger(t.VentActions.FavoritesBasket.OPEN);this.$el.hasClass("active")&&i.scrollTop(r+this.$el.outerHeight()-f)},updateCarHireBasket:function(n){var i=u(window),r=i.scrollTop(),f=this.$el.is(":visible")?this.$el.outerHeight():0;this.carhireCollection.reset(t.Utils.FavoritesStorage.CarHire.getFavorites(),{silent:!0});this.carhireView.render();t.vent.trigger(t.VentActions.FavoritesBasket.COUNT_HAS_BEEN_CHANGED,this.getItemsCount());this.updateTotalPriceIndicator();n&&t.vent.trigger(t.VentActions.FavoritesBasket.OPEN);this.$el.hasClass("active")&&i.scrollTop(r+this.$el.outerHeight()-f)},updateFlightsBasket:function(n){var i=u(window),r=i.scrollTop(),f=this.$el.is(":visible")?this.$el.outerHeight():0;this.flightsCollection.reset(t.Utils.FavoritesStorage.Flights.getFavorites(),{silent:!0});this.flightsView.render();t.vent.trigger(t.VentActions.FavoritesBasket.COUNT_HAS_BEEN_CHANGED,this.getItemsCount());this.updateTotalPriceIndicator();n&&t.vent.trigger(t.VentActions.FavoritesBasket.OPEN);this.$el.hasClass("active")&&i.scrollTop(r+this.$el.outerHeight()-f)},initializeFlights:function(){this.flightsCollection=new Brace.Collection(t.Utils.FavoritesStorage.Flights.getFavorites(),{model:t.FavoritesBasket.Models.FlightItemModel});this.flightsView=new t.FavoritesBasket.Views.CategoryView({model:new t.FavoritesBasket.Models.CategoryModel({type:"flights",name:u.t("breadcrumbs.flights"),currentTab:this.model.get("currentTab"),otherTabEmptyMessage:u.t("favorites.search-for-flights"),localStorageState:t.Flights.SearchState.Base.Provider.localstorage,syncState:t.WLSync.provideFlightsSyncState}),childViewOptions:{searchState:this.model.get("searchState")},collection:this.flightsCollection,childView:t.FavoritesBasket.Views.FlightItemView,itemViewContainer:".js-category-content"});this.flightsView.on("item-removed",function(){this.trigger("changed:favorite");this.updateFlightsBasket()},this);this.flightsView.on("jump-to-details",function(n){this.trigger("jump-to-details",n)},this);return this.listenTo(t.vent,t.VentActions.FavoritesBasket.UPDATE_FLIGHTS,_.bind(this.updateFlightsBasket,this)),this.flightsView},initializeHotels:function(){this.hotelsCollection=new Brace.Collection(t.Utils.FavoritesStorage.Hotels.getFavorites(),{model:t.FavoritesBasket.Models.HotelItemModel});this.hotelsView=new t.FavoritesBasket.Views.CategoryView({model:new t.FavoritesBasket.Models.CategoryModel({type:"hotels",name:u.t("breadcrumbs.hotels"),currentTab:this.model.get("currentTab"),otherTabEmptyMessage:u.t("favorites.search-for-hotels"),localStorageState:t.Hotels.SearchState.Base.Provider.localstorage,syncState:t.WLSync.provideHotelsSyncState}),childViewOptions:{searchState:this.model.get("searchState")},collection:this.hotelsCollection,childView:t.FavoritesBasket.Views.HotelItemView,itemViewContainer:".js-category-content"});this.hotelsView.on("item-removed",function(){this.trigger("changed:favorite");this.updateHotelsBasket()},this);this.hotelsView.on("jump-to-details",function(n){this.trigger("jump-to-details",n)},this);return this.listenTo(t.vent,t.VentActions.FavoritesBasket.UPDATE_HOTELS,_.bind(this.updateHotelsBasket,this)),this.hotelsView},initializeCarHire:function(){this.carhireCollection=new Brace.Collection(t.Utils.FavoritesStorage.CarHire.getFavorites(),{model:t.FavoritesBasket.Models.CarHireItemModel});this.carhireView=new t.FavoritesBasket.Views.CategoryView({model:new t.FavoritesBasket.Models.CategoryModel({type:"carhire",name:u.t("breadcrumbs.carhire"),currentTab:this.model.get("currentTab"),otherTabEmptyMessage:u.t("favorites.search-for-cars"),localStorageState:t.CarHire.SearchState.Base.Provider.localstorage,syncState:t.WLSync.provideCarHireSyncState}),childViewOptions:{searchState:this.model.get("searchState")},collection:this.carhireCollection,childView:t.FavoritesBasket.Views.CarHireItemView,itemViewContainer:".js-category-content"});this.carhireView.on("item-removed",function(){this.trigger("changed:favorite");this.updateCarHireBasket()},this);this.carhireView.on("jump-to-details",function(n){this.trigger("jump-to-details",n)},this);return this.listenTo(t.vent,t.VentActions.FavoritesBasket.UPDATE_CARHIRE,_.bind(this.updateCarHireBasket,this)),this.carhireView},_bindGlobalEvents:function(){this.listenTo(t.vent,t.VentActions.FavoritesBasket.OPEN,_.bind(this.openBasket,this));this.listenTo(t.vent,t.VentActions.FavoritesBasket.CLOSE,_.bind(this.closeBasket,this))},initialize:function(){var i=t.Settings.config.products,n;this.model.set("verticals",{isFlightsEnabled:_.contains(i,"flights"),isHotelsEnabled:_.contains(i,"hotels"),isCarHireEnabled:_.contains(i,"carhire")});this.views=[];n=this.model.get("verticals");n.isFlightsEnabled&&this.views.push(this.initializeFlights());n.isHotelsEnabled&&this.views.push(this.initializeHotels());n.isCarHireEnabled&&this.views.push(this.initializeCarHire());this._bindGlobalEvents()}})});App.module("FavoritesBasket.Views",function(n,t,i,r,u){n.CategoryView=i.Marionette.CompositeView.extend({template:"#favorites-category-template",className:"favorites-category",childEvents:{"item-removed":"onItemRemoved","empty-clicked":"onEmptyClicked","jump-to-details":"onJumpToDetails"},ui:{categoryTitleNum:".js-favorites-category-title-num",searchTitle:".js-title-search"},collectionEvents:{change:"updateCategoryTitleNum"},events:{"click @ui.searchTitle":"onSearchTitleClick"},onSearchTitleClick:function(n){if(n.preventDefault(),this.model.getCurrentTab()===this.model.getType())return!1;var i=this.model.getLocalStorageState(),r=this.model.getSyncState();if(typeof i!="function"||typeof r!="function")return!1;u.when(i(),r()).done(_.bind(function(n,i){var u=_.extend(n,i),r="";switch(this.model.getType()){case"flights":r=t.Utils.WhiteLabelLocation.getFlightsSearchPageUrl(u);break;case"hotels":r=t.Utils.WhiteLabelLocation.getHotelsSearchPageUrl(u);break;case"carhire":r=t.Utils.WhiteLabelLocation.getCarHireSearchPageUrl(u);break;default:Logger("favorites-basket-category-view").error("WL type is not defined")}t.Utils.Location.redirect(r)},this))},updateCategoryTitleNum:function(){var n=this.getItemsCount();n>0?this.ui.searchTitle.hide():this.ui.searchTitle.show();this.ui.categoryTitleNum.text(this.getItemsCount())},onDestroy:function(){this.updateTimeLoop&&(clearInterval(this.updateTimeLoop),this.updateTimeLoop=null)},onRender:function(){this.updateCategoryTitleNum();this.updateTimeLoop||(this.updateTimeLoop=setInterval(_.bind(function(){this.collection.each(function(n){n.trigger("change:timestamp")})},this),6e4));this.$el.i18n()},onItemRemoved:function(n){t.tracking.trackEvent("day-view",n.getTrackingEventName(),this.getTrackingDetails(n));this.trigger("item-removed")},getTrackingDetails:function(n){var t=n.getTrackingDetails(),i=this.collection.indexOf(n.model);return t+"_"+i},onJumpToDetails:function(n,t){this.trigger("jump-to-details",t)},getItemsCount:function(){return this.collection.length},getTotalPrice:function(){return this.collection.filter(function(n){return!n.getSoldOut()}).reduce(function(n,t){var i=t.getPriceWithoutCurrency();return _.isNumber(i)||(i=0),n+i},0)}})});App.module("FavoritesBasket.Views",function(n,t,i,r,u){n.FlightItemView=i.Marionette.CompositeView.extend({template:"#favorites-flight-item-template",className:"flight-item",events:{"click .js-btn-close":"onRemoveClick","click .js-jump-button":"onJumpButtonClick","click .js-sold-out-button":"onSoldOutButtonClick"},modelEvents:{"change:timestamp":"updateAgeTimestamp"},ui:{ageTimestamp:".js-age-timestamp",carrierLogo:".js-carrier-logo"},templateHelpers:{longPrice:function(){return this.priceWithCurrency&&this.priceWithCurrency.length>=t.Settings.wrappedPriceLength},getItemSummary:function(){var r=['<span class="emphasized">',this.originplaceText,"<\/span>"].join(""),f=['<span class="emphasized">',this.destinationplaceText,"<\/span>"].join(""),e=['<span class="emphasized">',t.Culture.culture.formatDate(new Date(this.outbounddate),{date:"fullAbbr"}),"<\/span>"].join(""),n=[],i;return n.push(u.i18n.t("favorites.from-to-on").replace("__fromvar__",r).replace("__tovar__",f).replace("__outboundvar__",e)),this.inbounddate&&(i=['<span class="emphasized">',t.Culture.culture.formatDate(new Date(this.inbounddate),{date:"fullAbbr"}),"<\/span>"].join(""),n.push(u.i18n.t("favorites.returning-on").replace("__inboundvar__",i))),this.adults&&n.push(u.i18n.t("favorites.adults_"+this.adults)),this.children&&n.push(u.i18n.t("favorites.children_"+this.children)),this.infants&&n.push(u.i18n.t("favorites.infants_"+this.infants)),n.join(", ")}},removeItem:function(){t.Utils.FavoritesStorage.Flights.removeFavorite(this.model.getFingerprint());this.trigger("item-removed")},getTrackingEventName:function(){return"Favourite_HeaderDelete_Flight"},getTrackingDetails:function(){var n=_.template("<%= originplace %>_<%= destinationplace %>_<%= priceWithCurrency %>_<%= agentName %>");return n({originplace:this.model.getOriginplace(),destinationplace:this.model.getDestinationplace(),priceWithCurrency:this.model.getPriceWithCurrency(),agentName:this.model.getAgentName()})},onRemoveClick:function(n){n.preventDefault();this.removeItem()},onSoldOutButtonClick:function(n){n.preventDefault();this.removeItem()},onJumpButtonClick:function(n){n.preventDefault();t.Utils.Favorites.isSameFlightSearch(this.options.searchState,this.model.toJSON())?this.trigger("jump-to-details",this.model.toJSON()):window.location.href=this.model.getLink()},onCarrierLogoLoadError:function(n){var t=u(n.target);t.parent().addClass("missing-carrier-logo")},updateAgeTimestamp:function(){var n=this.model.getTimestamp();n?this.ui.ageTimestamp.text(t.Utils.Favorites.addedTimeAgo(n)):this.ui.ageTimestamp.text("")},onRender:function(){this.updateAgeTimestamp();this.$el.i18n();this.ui.carrierLogo.error(_.bind(this.onCarrierLogoLoadError,this))},_buildLink:function(){var n=_.pick(this.model.toJSON(),"originplace","destinationplace","outbounddate","inbounddate","cabinclass","adults","children","infants");return n.itinerary=this.model.getFingerprint(),t.Utils.WhiteLabelLocation.getFlightsSearchPageUrl(n)},initialize:function(){this.model.set({link:this._buildLink()})}})});App.module("FavoritesBasket.Views",function(n,t,i,r,u){n.HotelItemView=i.Marionette.CompositeView.extend({template:"#favorites-hotel-item-template",className:"hotel-item",events:{"click .js-btn-close":"onRemoveClick","click .js-jump-button":"onJumpButtonClick","click .js-sold-out-button":"onSoldOutButtonClick"},modelEvents:{"change:timestamp":"updateAgeTimestamp"},ui:{ageTimestamp:".js-age-timestamp"},templateHelpers:{longPrice:function(){return this.priceWithCurrency&&this.priceWithCurrency.length>=t.Settings.wrappedPriceLength},getItemSummary:function(){var n=['<span class="emphasized">',this.destinationText,"<\/span>"].join(""),i=[u.t("favorites.hotels.check-in"),"&nbsp;",'<span class="emphasized">',t.Culture.culture.formatDate(new Date(this.checkin),{date:"fullAbbr"}),"<\/span>"].join(""),r=[u.t("favorites.hotels.check-out"),"&nbsp;",'<span class="emphasized">',t.Culture.culture.formatDate(new Date(this.checkout),{date:"fullAbbr"}),"<\/span>"].join(""),f=['<span class="emphasized">',this.guests,"<\/span>","&nbsp;",u.t("favorites.hotels.guests")].join(""),e=['<span class="emphasized">',this.rooms,"<\/span>","&nbsp;",u.t("favorites.hotels.rooms")].join("");return[n,i,r,f,e].join(", ")}},removeItem:function(){t.Utils.FavoritesStorage.Hotels.removeFavorite(this.model.getFingerprint());this.trigger("item-removed")},getTrackingEventName:function(){return"Favourite_HeaderDelete_Hotel"},getTrackingDetails:function(){var n=_.template("<%= destination %>_<%= priceWithCurrency %>");return n({destination:this.model.getDestination(),priceWithCurrency:this.model.getPriceWithCurrency()})},onRemoveClick:function(n){n.preventDefault();this.removeItem()},onSoldOutButtonClick:function(n){n.preventDefault();this.removeItem()},onJumpButtonClick:function(n){n.preventDefault();t.Utils.Favorites.isSameHotelSearch(this.options.searchState,this.model.toJSON())?this.trigger("jump-to-details",this.model.toJSON()):window.location.href=this.model.getLink()},updateAgeTimestamp:function(){var n=this.model.getTimestamp();n?this.ui.ageTimestamp.text(t.Utils.Favorites.addedTimeAgo(n)):this.ui.ageTimestamp.text("")},onRender:function(){this.updateAgeTimestamp();this.$el.i18n()},_buildLink:function(){var n=_.pick(this.model.toJSON(),"destination","checkin","checkout","guests","rooms");return n.scrollto=this.model.getFingerprint(),t.Utils.WhiteLabelLocation.getHotelsSearchPageUrl(n)},initialize:function(){this.model.set({ratingClass:t.Utils.Favorites.getRatingClass(this.model.get("rating")),link:this._buildLink()})}})});App.module("HelpFooterLink",{startWithParent:!1,define:function(n,t,i){n.on("start",function(){if(t.Services.Feature.check("helpLinkPopup","on")){var n=$(".ss-footer .ss-help-link"),u=$.t("dialogs.help-filter."+_.sortBy(t.Settings.config.products).join("-")),r=new t.Views.DialogHelpView({model:new i.Model({skyscannerPrompt:$.t("dialogs.help-filter.prompt-skyscanner").replace(/__partner__/g,t.Settings.config.name).replace(/__products__/g,u),continueLabel:"Continue to Skyscanner",customPrompt:$.t("dialogs.help-filter.prompt-custom").replace(/__partner__/g,t.Settings.config.name),skyscannerLink:n.attr("href"),hasCustomLink:!1})});$("body").append(r.render().$el);n.on("click",function(n){n.preventDefault();r.triggerMethod("show")})}t.trigger("module.ready",{name:"HelpFooterLink"})})}});App.module("HelpTab",{startWithParent:!1,define:function(n,t,i){n.HelpTabView=i.Marionette.LayoutView.extend({template:"#help-tab-template",events:{"click @ui.zenboxTab":"onClick"},ui:{zenboxTab:".js-zenbox-tab",dialog:".js-dialog-help"},onRender:function(){this.$el.i18n();t.Settings.config.showSkyscannerHelp&&this.ui.dialog.html(this.dialogView.render().$el);t.helpLink.show(this.helpDescLink)},onClick:function(){return t.Settings.config.showSkyscannerHelp?(t.vent.trigger(t.VentActions.Map.CLOSE),this.dialogView.triggerMethod("show"),!1):(window.open(t.Settings.config.customHelpLink,"_blank"),!1)},buildSkyscannerLink:function(n,i,r){var u="usrplace:"+r+"\ncurrency:"+i+"\nlocale:"+n;return t.Settings.config.skyscannerHelpLink+"&skyCookie="+encodeURIComponent(u)},initialize:function(){if(t.Settings.config.showSkyscannerHelp){var r=!!t.Settings.config.customHelpLink,u=$.t("dialogs.help-filter."+_.sortBy(t.Settings.config.products).join("-"));this.dialogView=new t.Views.DialogHelpView({model:new i.Model({skyscannerPrompt:$.t("dialogs.help-filter.prompt-skyscanner").replace(/__partner__/g,t.Settings.config.name).replace(/__products__/g,u),continueLabel:r?$.t("dialogs.help-filter.help-on").replace(/__products__/g,u):$.t("common.continue"),customPrompt:$.t("dialogs.help-filter.prompt-custom").replace(/__partner__/g,t.Settings.config.name),hasCustomLink:r,skyscannerLink:this.buildSkyscannerLink(this.options.locale,this.options.currency,this.options.market)})})}this.helpDescLink=new n.HelpLinkView;this.helpDescLink.on("click:helpLink",this.onClick,this)}});n.on("start",function(){t.Settings.config.showCustomHelp&&$.when(t.Services.Language.getLanguage(),t.Services.Currency.getCurrency(),t.Services.Market.getMarket()).done(function(i,r,u){var f=new n.HelpTabView({locale:i,currency:r,market:u});t.trigger("module.ready",{name:"HelpTab",view:f})})})}});App.module("HelpTab",function(n,t,i,r){n.HelpLinkView=r.ItemView.extend({template:"#help-link-template",behaviors:{ViewUnwrap:{}},onRender:function(){this.$el.i18n()},events:{click:function(n){n.preventDefault();this.trigger("click:helpLink")}}})});App.module("InspirationalPlaces",function(n,t,i,r){n.FilterView=r.ItemView.extend({template:"#inspirational-places-filter-template",ui:{priceFilter:".js-ins-pl-price-filter",durationFilter:".js-ins-pl-duration-filter"},onDestroy:function(){this.priceFilterView&&this.priceFilterView.destroy()},onRender:function(){var e="change:price",r=this.model.get("priceRange"),u=this.model.get("price"),f,t;if(u&&r&&r[0]!==u){this.ui.priceFilter.show();this.priceFilterView=new n.SliderItemView({model:new i.Model({min:r[0],max:r[1],type:"currency",start:u,title:"inspirational-places.filters.price-title",changeEvent:e,sliderClass:"",connect:"lower",currency:this.model.get("currency")})});this.priceFilterView.on(e,this.onChangePrice,this);this.ui.priceFilter.html(this.priceFilterView.render().$el)}else this.ui.priceFilter.hide();if(f="change:duration",t=this.model.get("duration"),t){this.ui.durationFilter.show();this.durationFilterView=new n.SliderItemView({model:new i.Model({min:t[0],max:t[1],type:"duration",start:t,title:"inspirational-places.filters.duration-title",changeEvent:f,sliderClass:"",connect:!0,format:"days"})});this.durationFilterView.on(f,this.onChangeDuration,this);this.ui.durationFilter.html(this.durationFilterView.render().$el)}else this.ui.durationFilter.hide()},onChangePrice:function(n){n=Math.ceil(n);n!==this.model.get("price")&&(t.Utils.Ui.trigger("inactive-veil:enable","InspirationalPlacesView"),this.model.set("price",n),t.tracking.trackEvent("browse","Browse_Filter_Price",this.model.get("currency")+"_0_"+n))},onChangeDuration:function(n){n=[Math.ceil(n[0]),Math.ceil(n[1])];var i=this.model.get("duration");(n[0]!==i[0]||n[1]!==i[1])&&(t.Utils.Ui.trigger("inactive-veil:enable","InspirationalPlacesView"),this.model.set("duration",n),n.length>0&&t.tracking.trackEvent("browse","Browse_Filter_Duration","Days_"+n[0]+"_"+n[1]))}});n.SliderItemView=r.ItemView.extend({model:i.Model,template:"#slider-item-template",ui:{min:".js-min",max:".js-max",slider:".js-slider"},initialize:function(){var n=this.model.get("titleAddon");this.model.set("titleAddon",n?n:"")},onRender:function(){var n=this,i=t.Utils.Sliders.getToolTips(this.model.get("type"),this.model.get("currency"),this.model.get("min"),this.model.get("max"),this.model.get("format")),r={range:{min:this.model.get("min"),max:this.model.get("max")},start:this.model.get("start"),connect:this.model.get("connect"),serialization:{lower:[i],upper:[i]},aria:{label:$.t(this.model.get("title")),minvalue:this.model.get("min"),maxvalue:this.model.get("max"),valuenow:this.model.get("start"),getValueText:i.getTooltipText}};this.ui.slider.noUiSlider(r);this.ui.slider.on({set:function(){var t=n.ui.slider.val(),i,r;_.isArray(t)&&t.length>1&&(i=t[1]-t[0],r=(n.model.get("max")-n.model.get("min"))/20,i<r?n.$el.find(".tooltip").addClass("bigtooclose"):n.$el.find(".tooltip").removeClass("bigtooclose"));n.$el.find(".active").removeClass("active");n.model.set("start",n.ui.slider.val());n.trigger(n.model.get("changeEvent"),n.ui.slider.val())}});this.$el.i18n()}})});App.module("InspirationalPlaces",function(n,t,i,r){var u,o=function(){if(AppSettings.config.backupImageUrls){var n=_.shuffle([].concat(AppSettings.config.backupImageUrls));return n.pop()}return"http://content.skyscnr.com/80bdf3a17eea79fae3a3e36a424ed9ec/BACKUP-thumbnail.jpg"},e=function(n){var r,f,i;return t.TestMode==="enable-attribution"?{attribution:"http://skyscanner.com/",author:"Skyscanner",title:"Sample attribution",license:"CC BY 2.0",licenseUrl:"https://creativecommons.org/licenses/by/2.0/"}:(r=u.request("attributions"),f=_.indexOf(r.id,n),f===-1)?null:(i=r.attribution[f],i?{attribution:i.url,author:i.author,title:i.title,license:i.license,licenseUrl:i.licenseUrl}:null)},f,s;n.CityView=r.ItemView.extend({tagName:"li",template:"#inspirational-places-city-template",className:"item city",events:{click:"onClick"},ui:{image:".js-image"},modelEvents:{"change:unpriced":"onChangeStatus"},templateHelpers:{getAttributionText:function(){return $.t("image-tooptip.copyright",this.attribution).replace(/"/g,"&quot;")}},trackEvent:function(){var n=t.Utils.Storage.getObject("culture.currency")?t.Utils.Storage.getObject("culture.currency"):0;t.Utils.Ui.isFlights()&&t.tracking.trackEvent("browse","Browse_City",""+this.model.get("code")+"_"+n+this.model.get("price"));(t.Utils.Ui.isHotels()||t.Utils.Ui.isCarHire())&&t.tracking.trackEvent("car-browse","Browse_City",this.model.get("code"))},setTitle:function(n){var r=t.Utils.Date.getNearestFridayMonday(),u=n?moment(r.friday):this.model.get("outboundDepartureDate"),f=n?moment(r.monday):this.model.get("inboundDepartureDate"),e=t.Culture.culture.formatDate(u.toDate(),{date:"long"}),o=t.Culture.culture.formatDate(f.toDate(),{date:"long"}),i=$.t("lowestPrices.labels.depart")+": "+e+"\n";i+=$.t("lowestPrices.labels.return")+": "+o+"\n";i+=n?this._getPriceTooltip($.t("inspirational-places.tooltips.noPrice")):this.model.get("price")===null?"":this.model.get("wrappedPrice");this.$el.attr("title",i)},onChangeStatus:function(){var n=this.model.get("unpriced");this.setTitle(n);this.$el.toggleClass("unpriced",n)},onRender:function(){this.imageLoad();this.onChangeStatus();this.$el.i18n().makeFocusable()},imageLoad:function(){f(this,this.model.get("cityCode"))},_getPriceTooltip:function(n){for(var r=30,t="",i;n.length>0;)n.length<=r?(t+=n,n=""):(i=n.indexOf(" ",r),i===-1?(t+=n,n=""):(t+=n.substring(0,i)+"\n",n=n.substring(i+1)));return t},onClick:function(){this.trackEvent();this.trigger("click:city")},initialize:function(n){this.model.set("attribution",e(this.model.get("cityCode")));n.isFilterDisabled&&this.model.set("unpriced",!0);n.setTitle&&(this.setTitle=n.setTitle)}});f=function(n,t){var i=n.model.get("ThumbnailUrl"),r=o();i||(i=r);i=i.replace("http://","//")+"?resize=190px:140px&quality=90";r=r.replace("http://","//")+"?resize=190px:140px&quality=90";n.ui.image.load(_.bind(function(){n.$el.addClass("loaded")},n)).error(_.bind(function(){n.ui.image.attr("src",r)},n)).attr({src:i,alt:n.model.get("name"),code:t})};s=function(n,t,i){n.ui.image.attr("src",t);n.ui.image.attr("alt",n.model.get("name"));n.ui.image.attr("code",i);n.$el.addClass("loaded")};n.CitiesView=r.CollectionView.extend({tagName:"ul",childView:n.CityView,className:"cities image-carousel-list",childEvents:{"click:city":function(n){this.trigger("click:city",n.model)}},events:{onChangeFilter:"onChangeFilter"},minNumberOfCitiesToBeFiltered:5,onChangeFilter:function(n){var r=this,t=0,i=[];this.collection.filter(function(u){var f=u.get("price"),s=u.get("code"),o=u.get("duration"),h,c,l=f?!0:!_.contains(i,s)&&t<r.minNumberOfCitiesToBeFiltered,a=!_.isNull(n),e=!1;return a?(h=f&&n.price?f<=n.price:!0,c=o&&n.duration?o>=n.duration[0]&&o<=n.duration[1]:!0,e=h&&c&&l):(f||l)&&(e=!0),e&&(t++,i.push(s)),e})},onFilterCollection:function(){var f=$(".js-ins-pl-cities-bg.active .container").width(),e=this.collection.length*t.Settings.imagePlaceWidth,n=$(".js-ins-pl-cities-next,.js-ins-pl-cities-prev"),o=$(".js-ins-pl-cities-next"),i=0,r,u;e>f?(n.show(),o.addClass("active")):(n.hide(),t.Utils.Ui.isDesktopView()&&this.collection.length<5&&(r=this.model.get("countryindex"),u=Math.min(5-this.collection.length,r),i=u*t.Settings.imagePlaceWidth));this.$el.css({"padding-left":i+"px"});this.trigger("checkButtons")},unionWithPopularCities:function(n,t,i){return t=t||[],n&&(_.each(n.cities,function(n){_.extend(n,{code:n.code,cityCode:n.cityCode?n.cityCode:n.code,name:n.name,unpriced:!0,wrappedPrice:"",homecity:i})}),t=_.union(t,n.cities)),_.each(t,function(t){t.countryCode=n.code}),t},initialize:function(n){this.childViewOptions={isFilterDisabled:n.isFilterDisabled};var r=this.collection.toJSON(),u=n.model.get("country"),f=n.model.get("homecity"),e=n.model.get("filter");r=this.unionWithPopularCities(u,r,f);this.collection=new t.Utils.FilteredCollection(new i.Collection(r));this.collection.on("onFilterCollection",this.onFilterCollection,this);this.onChangeFilter(e);this.childViewOptions={setTitle:n.setTitle}},onRender:function(){this.$el.i18n()}});n.CountryView=r.ItemView.extend({tagName:"li",template:"#inspirational-places-country-template",className:"item country",events:{click:"onClick"},ui:{image:".js-image"},modelEvents:{"change:unpriced":"onChangeStatus"},templateHelpers:{getAttributionText:function(){return $.t("image-tooptip.copyright",this.attribution).replace(/"/g,"&quot;")}},setTitle:function(n){var i=this.model.get("dates"),u=t.Utils.Date.getNearestFridayMonday(),f=n||!i?moment(u.friday):i.outbound,e=n||!i?moment(u.monday):i.inbound,o=t.Culture.culture.formatDate(f.toDate(),{date:"long"}),s=t.Culture.culture.formatDate(e.toDate(),{date:"long"}),r=$.t("lowestPrices.labels.depart")+": "+o+"\n";r+=$.t("lowestPrices.labels.return")+": "+s+"\n";r+=n||!i?this._getPriceTooltip($.t("inspirational-places.tooltips.noPrice")):this.model.get("price")===null?"":this.model.get("wrappedPrice");this.$el.attr("title",r)},onChangeStatus:function(){var n=this.model.get("unpriced");this.setTitle(n);this.$el.toggleClass("unpriced",n)},onClick:function(){this.trigger("onClick")},onRender:function(){this.imageLoad();this.onChangeStatus();this.model.get("active")&&this.$el.addClass("active");this.$el.i18n().makeFocusable()},imageLoad:function(){f(this,this.model.get("code"))},_getPriceTooltip:function(n){for(var r=30,t="",i;n.length>0;)n.length<=r?(t+=n,n=""):(i=n.indexOf(" ",r),i===-1?(t+=n,n=""):(t+=n.substring(0,i)+"\n",n=n.substring(i+1)));return t},initialize:function(n){this.model.set("attribution",e(this.model.get("code")));n.setTitle&&(this.setTitle=n.setTitle)}});n.ContinentView=r.CompositeView.extend({tagName:"li",template:"#inspirational-places-continent-template",childViewContainer:".js-ins-pl-countries",childView:n.CountryView,childEvents:{onClick:"onClick"},ui:{progressbar:".js-ins-pl-progressbar",cities:".js-ins-pl-cities",citiesBg:".js-ins-pl-cities-bg",citiesBgContainer:".js-ins-pl-cities-bg .container",navButtons:".js-ins-pl-cities-next,.js-ins-pl-cities-prev",prevButton:".js-ins-pl-cities-prev",nextButton:".js-ins-pl-cities-next",countriesCarouselContainer:".js-ins-pl-countries-carousel-container",countriesContainer:".js-ins-pl-countries-container",countriesNavButtons:".js-ins-pl-countries-next,.js-ins-pl-countries-prev",countriesPrevButton:".js-ins-pl-countries-prev",countriesNextButton:".js-ins-pl-countries-next"},events:{"click .js-ins-pl-cities-next":"onNext","click .js-ins-pl-cities-prev":"onPrev","click .js-ins-pl-countries-next":"onNextCountry","click .js-ins-pl-countries-prev":"onPrevCountry",onChangeFilter:"onChangeFilter"},onChangeFilter:function(n){this.model.set("filter",n);var t=0;this.collection.filter(function(i){var r,u,f,e,o,s,h;return t>=5?(i.get("active")&&i.set("active",!1),!1):(u=i.get("price"),u?(f=i.get("duration"),n===null?(r=!0,i.set("unpriced",!0)):(e=u<=n.price,o=!n.duration||f>=n.duration[0]&&f<=n.duration[1],r=e&&o,s=i.get("cities"),h=i.get("isPopular"),!r&&s&&h?(r=!0,i.set("unpriced",!0)):i.set("unpriced",!1))):(i.set("unpriced",!0),r=!0),r)?(t++,t<=5):(i.get("active")&&i.set("active",!1),!1)})},onNext:function(){this.scrollCities(1)},onPrev:function(){this.scrollCities(-1)},onNextCountry:function(){this.scrollCountries(1)},onPrevCountry:function(){this.scrollCountries(-1)},checkButtons:function(){if(this.ui.cities.jquery){var i=this.ui.citiesBgContainer.width(),r=this.ui.cities.find("ul li").length,n=this.ui.cities.scrollLeft(),u=r*t.Settings.imagePlaceWidth-n;n>=-5&&n<=5?this.ui.prevButton.removeClass("active"):this.ui.prevButton.addClass("active");u-5<=i?this.ui.nextButton.removeClass("active"):this.ui.nextButton.addClass("active")}},checkCountryButtons:function(){if(this.ui.countriesCarouselContainer.jquery){if(t.Utils.Ui.isDesktopView()){this.ui.countriesNavButtons.hide();return}this.ui.countriesNavButtons.show();var i=this.ui.countriesContainer.width(),r=this.ui.countriesContainer.find("ul li").length,n=this.ui.countriesCarouselContainer.scrollLeft(),u=r*t.Settings.imagePlaceWidth-n;n>=-5&&n<=5?this.ui.countriesPrevButton.removeClass("active"):this.ui.countriesPrevButton.addClass("active");u-5<=i?this.ui.countriesNextButton.removeClass("active"):this.ui.countriesNextButton.addClass("active")}},_scrollContainer:function(n,t){var i=null;n.find(".item").each(function(n,r){var u=$(r);if(t>0){if(u.position().left+u.width()>0)return i=u,!1}else if(u.position().left+u.width()/2>0)return i=u,!1});i&&(t>0?i.next().length&&(i=i.next()):i.prev().length&&(i=i.prev()),n.scrollTo(i,200))},scrollCountries:function(n){this._scrollContainer(this.ui.countriesCarouselContainer,n);this.checkCountryButtons()},scrollCities:function(n){this._scrollContainer(this.ui.cities,n);this.checkButtons()},onClick:function(n){var o=t.Utils.Storage.getObject("culture.currency")||0,e=n.model.get("price")||"",i,r,u,f;if(n.$el.hasClass("active")){this.hideCities(n);return}t.Utils.Ui.isFlights()&&t.tracking.trackEvent("browse","Browse_Country",""+n.model.get("code")+"_"+o+e);(t.Utils.Ui.isHotels()||t.Utils.Ui.isCarHire())&&t.tracking.trackEvent("car-browse","Browse_Country",n.model.get("code"));this.ui.navButtons.hide();this.model.collection.trigger("onCountryClick",n,this.model.get("id"));this.citiesView&&this.citiesView.destroy();this.ui.citiesBg.addClass("active");t.Utils.Ui.scrollToBelowViewPortElement(this.ui.citiesBg,50);this.$el.find(this.childViewContainer+" li.active").removeClass("active");this.collection.each(function(n){n.set("active",!1)});n.model.set("active",!0);n.$el.addClass("active");i=n.model.get("code");r=this.model.get("id");this.startProgressbar();u=n._index;f=this;e?t.Services.InspirationalPlaces.getCities(i).done(function(n){f.renderCities(n,r,i,u)}).fail(function(n){f.stopProgressbar();throw new Error(n);}):this.renderCities(null,r,i,u)},startProgressbar:function(){this.progressbarView=new t.Views.ProgressbarView({model:new i.Model({auto:!0,interval:200,diff:2})});var n=this.progressbarView.render().$el;this.ui.citiesBg.addClass("active");this.ui.progressbar.html(n)},stopProgressbar:function(){this.progressbarView&&this.progressbarView.destroy()},onDestroy:function(){this.progressbarView&&(this.progressbarView.stopAutoset(),this.progressbarView.destroy());this.ui.cities.off("scroll");this.ui.countriesCarouselContainer.off("scroll");this.citiesView&&this.citiesView.destroy();t.Utils.Ui.off("breakpoint:change",this.fixScrollBar,this)},hideCities:function(n,t){if(t){if(t===this.model.get("id"))return;this.$el.find(this.childViewContainer+" li.active").removeClass("active")}n&&n.$el.removeClass("active");this.stopProgressbar();this.citiesView&&this.citiesView.destroy();this.ui.citiesBg.removeClass("active")},onCityClick:function(n){this.trigger("click:city",n)},renderCities:function(t,r,u,f){var s=_.clone(this.model.get("filter")),e,o;this.citiesView&&this.citiesView.destroy();e=this.model.get("countries");o=_.findWhere(e,{code:u});this.citiesView=new n.CitiesView({model:new i.Model({continentid:r,countrycode:u,countryindex:f,country:o,homecity:this.model.get("homecity"),filter:s}),collection:new i.Collection(t),isFilterDisabled:this.options.isFilterDisabled,setTitle:this.setCityTitle});this.citiesView.on("checkButtons",this.checkButtons,this);this.citiesView.on("click:city",this.onCityClick,this);this.ui.cities.html(this.citiesView.render().$el);this.stopProgressbar()},onFilterCollection:function(){var t=this.model.get("filter"),n;if(this.citiesView)if(this.citiesView.$el.is(":visible")||(this.$el.find(this.childViewContainer+" li.active").removeClass("active"),this.collection.each(function(n){n.set("active",!1)})),n=this.citiesView.model.get("countrycode"),this.collection.findWhere({code:n}))this.citiesView.onChangeFilter(t);else this.hideCities()},initialize:function(n){var r=n.model.get("countries");if(this.collection=new t.Utils.FilteredCollection(new i.Collection(r)),!this.isFilterDisabled)this.collection.on("onFilterCollection",this.onFilterCollection,this);this.setCityTitle=n.setCityTitle;this.childViewOptions={setTitle:n.setCountryTitle};t.Utils.Ui.on("breakpoint:change",this.fixScrollBar,this);t.Utils.Ui.on("breakpoint:change",this.checkButtons,this);t.Utils.Ui.on("breakpoint:change",this.checkCountryButtons,this)},fixScrollBar:function(){t.Utils.Ui.isMobileDevice()||(t.Utils.Ui.isMobileView()?(this.ui.countriesCarouselContainer.removeClass("scroll-none"),this.ui.cities.removeClass("scroll-none")):(this.ui.countriesCarouselContainer.addClass("scroll-none"),this.ui.cities.addClass("scroll-none")));setTimeout(_.bind(function(){this.ui.countriesCarouselContainer.css("overflow-x","hidden");this.ui.cities.css("overflow-x","hidden");setTimeout(_.bind(function(){this.ui.countriesCarouselContainer.css("overflow-x","auto");this.ui.cities.css("overflow-x","auto")},this),100)},this),100)},onRender:function(){this.ui.cities.on("scroll",_.bind(this.checkButtons,this));this.ui.countriesCarouselContainer.on("scroll",_.bind(this.checkCountryButtons,this));_.defer(_.bind(this.checkCountryButtons,this));this.fixScrollBar()}});n.InspirationalPlacesView=r.CompositeView.extend({template:"#inspirational-places-template",templateHelpers:{getVerticalsSubtitleResourceKey:function(){return t.Utils.Ui.isFlights()?"inspirational-places.header-section.subtitle-flights":t.Utils.Ui.isHotels()?"inspirational-places.header-section.subtitle-hotels":t.Utils.Ui.isCarHire()?"inspirational-places.header-section.subtitle-carhire":void 0}},childViewContainer:".js-ins-pl-continents",childView:n.ContinentView,childEvents:{"click:city":function(n,t){this.trigger("click:city",t)}},ui:{filter:".js-ins-pl-filter",filterWrapper:".js-home-filters-box",inspirationalFilterTitle:".js-inspirational-filter-title",poweredBy:".js-powered-by"},behaviors:{ViewInactiveVeil:{triggerName:"InspirationalPlacesView"}},collectionEvents:{onCountryClick:"onCountryClick"},onDestroy:function(){this.filterView&&this.filterView.destroy()},onRender:function(){var n=this.model.get("summary"),r,u,f;if(!this.options.isFilterDisabled&&n&&(n.duration||n.price)){r={priceRange:n.price,price:n.price?n.price[1]:0,duration:n.duration,currency:n.currency,market:n.market};u=new i.Model(r);r.duration||r.price&&r.priceRange&&r.priceRange[0]!==r.price||this.ui.inspirationalFilterTitle.hide();this.filterView=new t.InspirationalPlaces.FilterView({model:u});this.filterView.model.on("change",this.onChangeFilter,this);this.ui.filter.html(this.filterView.render().$el);this.filterView.model.trigger("change",u)}else{this.onChangeFilter(null);this.ui.filterWrapper.hide()}f=new t.Views.PoweredByView;this.ui.poweredBy.html(f.render().$el);this.$el.i18n();window.scrollTo&&setTimeout(function(){window.scrollTo(0,1);window.scrollTo(0,0)},1)},onChangeFilter:function(n){this.children.call("onChangeFilter",n===null?null:n.toJSON());t.Utils.Ui.trigger("inactive-veil:disable","InspirationalPlacesView")},onCountryClick:function(n,t){this.children.call("hideCities",n,t)},initialize:function(n){u=new i.Wreqr.RequestResponse;u.setHandler("attributions",function(){return n.attributions});this.childViewOptions={summary:n.model.get("summary"),isFilterDisabled:n.isFilterDisabled,setCountryTitle:n.setCountryTitle,setCityTitle:n.setCityTitle};this.$el.removeClass("inactive")}})});App.module("ImageBanner",function(n){var t=Brace.Model.extend({namedAttributes:{id:"string",name:"string",departureDate:null||undefined||!1}}),i=Brace.Model.extend({namedAttributes:{id:"string",name:"string",countryId:"string",countryName:"string",departureDate:null||undefined||!1}});n.ImageBannerModel=Brace.Model.extend({namedAttributes:{image:"object",url:"string",origin:t,destination:i,attribution:"object",name:"string",cityId:"string",cityNumber:"string",countryId:"string",countryName:"string",price:null||undefined||!1,quoteDateTime:"string",quoteAgeInMinutes:null||undefined||!1,wrappedPrice:"string",withoutPrice:"boolean","static":"boolean",bannerUrl:"string",bannerPlaceCode:"string"},namedEvents:["select"],defaults:function(){return{image:null,url:"",origin:{},destination:{},attribution:null,name:"",cityId:"",cityNumber:"",countryId:"",countryName:"",price:null,quoteDateTime:"",quoteAgeInMinutes:null,wrappedPrice:"",withoutPrice:!1,"static":!1}}});n.ImageBannersCollection=Brace.Collection.extend({model:n.ImageBannerModel})});App.module("ImageBanner",function(n){function i(n){var i,r,t;AppSettings.config.backupBannerUrls&&(i=_.shuffle([].concat(AppSettings.config.backupBannerUrls)),r=/\bbackup_[0-9]+/i,n.bannerUrl=i.pop(),t=r.exec(n.bannerUrl),n.bannerPlaceCode=t&&t.length>0?t[0]:"BACKUP")}function t(){var n=new $.Deferred;return $.when(App.Services.InspirationalPlaces.getPlaces()).done(function(t){n.resolve(t.geo.placesLookup)}).fail(function(){n.reject()}),n.promise()}n.addBanners=function(n,t,r){return _.each(t,function(t){var u=null,o=null,e=r[t.cityId],s=e?e:r[t.countryId],f;t.cityId&&e&&(u=e.BannerUrl,u&&(u=u.replace("http://","//")),o=t.cityId);!u&&s&&(u=s.BannerUrl,u&&(u=u.replace("http://","//")),o=t.countryId);u?(t.bannerUrl=u,u&&(u=u.replace("http://","//")),t.bannerPlaceCode=o):i(t);t.bannerUrl&&(t.bannerUrl=t.bannerUrl+"?resize=2000px:530px&quality=90",t.bannerUrl&&(t.bannerUrl=t.bannerUrl.replace("http://","//")));t.bannerPlaceCode&&(f=n.attribution[t.bannerPlaceCode],f&&(t.attribution={attribution:f.url,author:f.author,title:f.title,license:f.license,licenseUrl:f.licenseUrl}))}),t};n.getBannerForCity=function(i){var r=$.Deferred();return $.when(App.Services.InspirationalPlaces.getAttributions(),t()).done(function(t,u){var f=$.Deferred().done(function(i){r.resolve(n.addBanners(t,[i],u)[0])}).fail(function(){var f={cityId:"BACKUP",name:i.CityName,countryId:"BACKUP",countryName:i.CountryName};r.resolve(n.addBanners(t,[f],u)[0])});App.Utils.Ui.isFlights()&&f.resolve({cityId:i.CityId,name:i.CityName,countryId:i.CountryId,countryName:i.CountryName});App.Utils.Ui.isHotels()&&App.Services.GeoService.mapHotelsToFlights(i.CityId).done(function(n){n&&n[0]&&n[0].to?App.Services.PlacesApi.getPlaceById(n[0].to).done(function(n){f.resolve({cityId:n.CityId.replace("-"+App.Dictionaries.LocationSchema,""),name:i.CityName,countryId:n.CountryId.replace("-"+App.Dictionaries.LocationSchema,""),countryName:i.CountryName})}).fail(function(){f.reject()}):f.reject()}).fail(function(){f.reject()});App.Utils.Ui.isCarHire()&&App.Services.GeoService.mapHotelsToFlights(i.CityId).done(function(n){n&&n[0]&&n[0].to?App.Services.PlacesApi.getPlaceById(n[0].to).done(function(n){f.resolve({cityId:n.CityId.replace("-"+App.Dictionaries.LocationSchema,""),name:i.CityName,countryId:n.CountryId.replace("-"+App.Dictionaries.LocationSchema,""),countryName:i.CountryName})}).fail(function(){f.reject()}):f.reject()}).fail(function(){f.reject()})}),r.promise()};n.getBannerForCode=function(n){var i=new $.Deferred;return t().done(function(t){var r=t[n];i.resolve(r?r.BannerUrl:null)}).reject(function(){i.resolve(null)}),i.promise()};n.getBanners=function(){var i=[],r=new $.Deferred;return App.Utils.Ui.isFlights()&&(App.Services.OperatingCarriers.isEnabled||App.Services.RoutesAndSuppliers.isEnabled)?r.resolve([]):($.when(App.Services.InspirationalPlaces.getPlaces(),App.Services.InspirationalPlaces.getAttributions(),t()).done(function(t,u,f){var h=t.routes.continents,o=t.geo,c=t.routes.homecity,a=t.routes.currency,v=[_.shuffle([[2,9],[2,9],[1,7]]),[[2,9],[2,9],[1,7]]],e=v[_.random(0,1)],s,l;_.each(h,function(n,t){var i=[];if(App.Utils.Ui.isFlights()&&(i=_.sortBy(n.countries,function(n){return n.price}),i=_.first(_.shuffle(_.first(i,e[t][1])),e[t][0]),_.each(i,function(n){var i=_.findWhere(o.continents[t].countries,{code:n.code}),r;i&&(r=_.flatten(_.map(i.cities,function(n){return n.Airports})),_.each(n.offers,function(n){var t=_.findWhere(r,{Id:n.skyscannerCode});t&&(n.CityId=t.CityId,n.AirportName=t.Name)}))})),i.length<e[t][0]){var r=_.property("countries")(_.findWhere(App.Dictionaries.PopularCountryCodes,{id:o.continents[t].id})),u=_.filter(o.continents[t].countries,function(n){return _.indexOf(r,n.code)!==-1}),f=_.first(_.shuffle(u),e[t][0]-i.length);_.each(f,function(n){var t=[],r=_.first(_.shuffle(n.cities),2);_.each(r,function(n){_.each(_.first(n.Airports,1),function(i){t.push({AirportName:i.Name,CityId:i.CityId,cityName:n.Name,skyscannerCode:i.Id})})});i.push({code:n.code,name:n.name,price:null,offers:t})})}n.countries=i});s=App.Utils.Date.getNearestFridayMonday();_.each(h,function(n){_.each(n.countries,function(n){if(n&&n.offers&&n.offers.length>0){var t=n.offers[_.random(0,n.offers.length-1)];i.push({cityId:t.CityId,countryId:n.code,name:t.cityName,countryName:n.name,price:t.MinPrice?t.MinPrice:null,quoteDateTime:t.QuoteDateTime,wrappedPrice:t.MinPrice?App.Utils.Ui.wrapPrice(t.MinPrice,a):"",bannerUrl:t.bannerUrl,origin:{id:c.PlaceId,name:c.PlaceName,departureDate:t.OutboundLeg?moment(t.OutboundLeg.DepartureDate,App.Settings.dateFormat):moment(s.friday)},destination:{id:t.skyscannerCode,name:t.AirportName,countryId:n.code,countryName:n.name,departureDate:t.InboundLeg?moment(t.InboundLeg.DepartureDate,App.Settings.dateFormat):moment(s.monday)}})}})});i=_.sortBy(i,function(n){return parseInt(n.price,10)});i=n.addBanners(u,i,f);App.Utils.Ui.isFlights()?r.resolve(i):(l=_.pluck(i,"cityId"),App.Services.GeoService.mapFlightsToHotels(l).done(function(n){_.each(i,function(t){t.cityNumber=n[t.cityId]});r.resolve(i)}))}).fail(function(){r.reject()}),r.promise())}});App.module("ImageBanner",function(n,t,i,r,u){var f=!1,e=!0;n.ImageBannerItemView=i.Marionette.ItemView.extend({template:"#image-banner-item-template",templateHelpers:{getAttributionText:function(){return u.t("image-tooptip.copyright",this.attribution).replace(/"/g,"&quot;")},getQuoteDateTime:function(){var n=null;return this.quoteDateTime&&this.quoteDateTime.length>0&&(n=moment().diff(moment(this.quoteDateTime),"days")),t.Utils.Ui.quoteDateTimeMessage(n)}},ui:{imageContainer:".js-image-container"},events:{"click .js-banner-info span":function(){this.model.getStatic()!==!0&&(t.tracking.trackEvent("day-view","Carousel_Selection",this.model.getCityId()),this.model.triggerSelect(this.model))}},onRender:function(){var n;this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.hide();this.ui.imageContainer.html(this.model.getImage());this.$el.attr("data-city-id",this.model.getCityId());n=this.model.getDestination();n&&this.$el.attr("data-city-code",n.getId());this.$el.i18n()},initialize:function(){}});n.ImageBannerView=i.Marionette.View.extend({el:".js-banner-image",events:{'click .js-arrow[data-arrow-type="left"]':function(){f||(this.prev(),t.tracking.trackEvent("day-view","Carousel_Left","Clicked on carousel left arrow."))},'click .js-arrow[data-arrow-type="right"]':function(){f||(this.next(),t.tracking.trackEvent("day-view","Carousel_Right","Clicked on carousel right arrow."))}},ui:{arrowsContainer:".js-banner-arrows-container"},imageCounter:0,_onResetCollection:function(){var n=0;this.static=this.collection.length===1;this.collection.each(_.bind(function(t){t.on("select",this.onSelect,this);var i=u("<img />").attr("src",t.getBannerUrl()).load(_.bind(function(){n++;t.setImage(i);this.collection.length===1?(this.initAppendImage(t),this.last().done(_.bind(this.removePrevSlides,this)),this.ui.arrowsContainer.fadeOut(500)):n===this.collection.length&&(this.showShareButtons(),this.initAppendImages(),this.next().done(_.bind(this.removePrevSlides,this)),this.ui.arrowsContainer.fadeIn(500))},this))},this))},swapSlides:function(n,t){var i=new u.Deferred;return f=!0,t.css({display:"block","z-index":2,opacity:0}).animate({opacity:1},500,function(){return n&&(n.hide(),e&&(n.remove(),e=!1)),t.css("z-index",1),f=!1,i.resolve()}),i.promise()},showShareButtons:function(){var n=u("#js-main-sharing");n.show();n.find(".js-share-button").show()},displayBanners:function(n){_.isArray(n)||(n=[n]);this.collection.reset(n)},getCurrentCityCode:function(){var n=this.$el.find(".js-banner-item:visible");return n.length>0?n.attr("data-city-id"):""},next:function(){var n=this.$el.find(".js-banner-item:visible"),t;return n.length===0&&(n=this.$el.find(".js-default-banner-item")),t=n.next(".js-banner-item"),t.length===0&&(t=this.$el.find(".js-banner-item:first")),this.swapSlides(n,t)},prev:function(){var t=this.$el.find(".js-banner-item:visible"),n=t.prev(".js-banner-item");return n.length===0&&(n=this.$el.find(".js-banner-item:last")),this.swapSlides(t,n)},last:function(){var n=this.$el.find(".js-banner-item:visible"),t=this.$el.find(".js-banner-item:last");return this.swapSlides(n,t)},removePrevSlides:function(){var n=this.$el.find(".js-banner-item:visible");n.prevAll(".js-banner-item").remove()},initAppendImage:function(n){this.appendImage(n);this.imageCounter++},initAppendImages:function(){this.collection.each(_.bind(function(n){this.appendImage(n)},this))},appendImage:function(i){var u=!t.Utils.Ui.isFlights()||this.static,r;i.setWithoutPrice(u);i.setStatic(this.static);r=new n.ImageBannerItemView({model:i});this.$el.append(r.render().$el)},onSelect:function(n){this.trigger("select",n)},lazyLoadImage:function(n,t,i){i=i||0;t=t||new u.Deferred;i++;n.on("select",this.onSelect,this);var r=u("<img />").attr("src",n.getBannerUrl()).load(_.bind(function(){n.setImage(r);this.initAppendImage(n);this.imageCounter===1&&this.next();i===this.collection.length&&(this.showShareButtons(),this.ui.arrowsContainer.fadeIn(500));t.resolve()},this));return setTimeout(_.bind(function(){i<this.collection.length?this.lazyLoadImage(this.collection.at(i),t,i):t.reject()},this),500),t.promise()},render:function(){var n=this.collection.at(0);n&&this.lazyLoadImage(n)},initialize:function(){this.setElement(this.el);this.bindUIElements();this.collection.on("reset",this._onResetCollection,this);this.listenTo(t.vent,t.VentActions.Flights.SEARCH_FINISHED_SUMMARY,_.bind(function(n){this.collection.length===1&&n&&n.cheapest&&n.cheapest.price&&this.showShareButtons()},this))}})});App.module("ImageBanner",{startWithParent:!1,define:function(n,t){var i=!1;n.Views={imageBannerView:null};n.isStarted=function(){return i};n.onImageBannerClick=function(t){n.trigger("select",t)};n.initializeCustomBanner=function(){var n=new Image;n.onload=function(){if(this.width&&this.height){var n=this.width/this.height,i=t.Settings.bannerDimensions.width/t.Settings.bannerDimensions.height;n>i?$(this).attr("height",t.Settings.bannerDimensions.height).removeAttr("width"):$(this).attr("width",t.Settings.bannerDimensions.width).removeAttr("height")}};n.src=t.Settings.config.customBanner;$(".js-banner-image-container").append(n).addClass("custom-banner")};n.restartModule=function(){t.Settings.config.showImageBanner&&n.getBanners().done(function(t){n.Views.imageBannerView.displayBanners(t)})};n.showCityBanner=function(i){if(t.Settings.config.showImageBanner){if(!n.Views.imageBannerView){n.Views.imageBannerView=new n.ImageBannerView({collection:new n.ImageBannersCollection});n.Views.imageBannerView.off("select").on("select",n.onImageBannerClick);n.Views.imageBannerView.render()}n.getBannerForCity(i).done(function(t){n.Views.imageBannerView.displayBanners(t)})}};n.getCurrentCityCode=function(){return n.Views.imageBannerView?n.Views.imageBannerView.getCurrentCityCode():""};n.on("start",function(r){if(t.Settings.config.showImageBanner&&!n.isStarted()&&(!t.Utils.Ui.isMobileDevice()||!t.Utils.Ui.isMobileView())){if(t.Settings.config.customBanner){n.initializeCustomBanner();return}r=_.extend({city:null},r||{});r.city?(i=!0,n.showCityBanner(r.city)):n.getBanners().done(function(t){i=!0;n.Views.imageBannerView=new n.ImageBannerView({collection:new n.ImageBannersCollection(t)});n.Views.imageBannerView.off("select").on("select",n.onImageBannerClick);n.Views.imageBannerView.render()})}});n.on("stop",function(){i=!1;n.Views.imageBannerView&&(n.Views.imageBannerView.remove(),n.Views.imageBannerView=null)})}});App.module("PreviewNotify",function(n,t,i){n.PreviewNotifyView=i.Marionette.ItemView.extend({template:"#preview-notify-template",onRender:function(){this.$el.i18n()}})});App.module("PreviewNotify",{startWithParent:!1,define:function(n,t){n.isNeedToRender=function(){return t.Settings.preview};n.on("start",function(){n.isNeedToRender()&&$(t.Utils.Ui.bodySelector).prepend((new n.PreviewNotifyView).render().$el)})}});App.module("WLSync",function(n,t){function i(n){$.cookie("wl-sync",JSON.stringify(n),{path:"/"})}function r(){var n=$.cookie("wl-sync");return n?JSON.parse(n):null}n.Modes={flights:"flights",hotels:"hotels",carhire:"carhire"};n.updateFlightsStatus=function(){i({flights:!0,hotels:!1,carhire:!1,mode:n.Modes.flights})};n.updateHotelsStatus=function(){i({flights:!1,hotels:!0,carhire:!1,mode:n.Modes.hotels})};n.updateCarHireStatus=function(){i({flights:!1,hotels:!1,carhire:!0,mode:n.Modes.carhire})};n.provideFlightsSyncState=function(){var f=new $.Deferred,o,u,e;if(r()===null)return f.resolve({});if(o=r(),o.flights)f.resolve({});else{o.flights=!0;i(o);switch(o.mode){case n.Modes.hotels:u=t.Utils.StateStorage.Hotels.getPrev();u===null?f.resolve({}):(e={outbounddate:u.checkin,inbounddate:u.checkout,adults:u.guests,children:0,infants:0},u.destination?t.Services.GeoService.mapHotelsToFlights(u.destination).done(function(n){n&&_.isObject(n[0])&&_.isString(n[0].to)&&(e.destinationplace=n[0].to);f.resolve(e)}).fail(function(){f.resolve(e)}):f.resolve(e));break;case n.Modes.carhire:u=t.Utils.StateStorage.CarHire.getPrev();u===null?f.resolve({}):(e={},e.outbounddate=u.pickupDate,e.inbounddate=u.dropoffDate,u.pickupPlace?$.when(t.Services.GeoService.mapHotelsToFlights(u.pickupPlace)).done(function(n){n&&_.isObject(n[0])&&_.isString(n[0].to)&&(e.destinationplace=n[0].to);f.resolve(e)}).fail(function(){f.resolve(e)}):f.resolve(e));break;default:f.resolve({})}}return f.promise()};n.provideHotelsSyncState=function(){var e=new $.Deferred,o,u,f;if(r()===null)return e.resolve({});if(o=r(),o.hotels)e.resolve({});else{o.hotels=!0;i(o);switch(o.mode){case n.Modes.flights:u=t.Utils.StateStorage.Flights.getPrev();u!==null?(f={},f.checkin=u.outbounddate,f.checkout=u.outbounddate===u.inbounddate||u.inbounddate===""?t.Utils.Date.addDay(u.outbounddate,1):u.inbounddate||t.Utils.Date.addDay(u.outbounddate,2),_.isNumber(u.adults)&&_.isNumber(u.children)&&(f.guests=u.adults+u.children,f.rooms=parseInt(Math.ceil(u.adults/2),10)||1),u.destinationplace?t.Services.GeoService.mapFlightsToHotels(u.destinationplace).done(function(n){n&&_.isObject(n[0])&&_.isString(n[0].to)&&(f.destination=n[0].to);e.resolve(f)}).fail(function(){e.resolve(f)}):e.resolve(f)):e.resolve({});break;case n.Modes.carhire:u=t.Utils.StateStorage.CarHire.getPrev();u!==null?(f={},f.checkin=u.pickupDate,f.checkout=u.dropoffDate,f.destination=u.pickupPlace,f.destinationText=u.pickupPlaceText,e.resolve(f)):e.resolve({});e.resolve({});break;default:e.resolve({})}}return e.promise()};n.provideCarHireSyncState=function(){var e=new $.Deferred,o,f,u;if(r()===null)return e.resolve({});if(o=r(),o.carhire)e.resolve({});else{o.carhire=!0;i(o);switch(o.mode){case n.Modes.flights:f=t.Utils.StateStorage.Flights.getPrev();f!==null?(u={},f.outbounddate===f.inbounddate?(u.pickupDate=f.outbounddate,u.dropoffDate=t.Utils.Date.addDay(f.outbounddate,1)):(u.pickupDate=f.outbounddate,u.dropoffDate=f.inbounddate||t.Utils.Date.addDay(f.outbounddate,1)),f.destinationplace?t.Services.GeoService.mapFlightsToHotels(f.destinationplace).done(function(n){n&&_.isObject(n[0])&&_.isString(n[0].to)&&(u.pickupPlace=n[0].to,u.dropoffPlace=n[0].to,u.sameDropoffPlace=!0);e.resolve(u)}).fail(function(){e.resolve(u)}):e.resolve(u)):e.resolve({});break;case n.Modes.hotels:f=t.Utils.StateStorage.Hotels.getPrev();f!==null?(u={},u.pickupDate=f.checkin,u.dropoffDate=f.checkout,f.destination?(u.pickupPlace=f.destination,u.dropoffPlace=f.destination,u.sameDropoffPlace=!0,e.resolve(u)):e.resolve(u)):e.resolve({});break;default:e.resolve({})}}return e.promise()}});App.module("CarHire.SearchState.Base",function(n,t){n.Provider={localstorage:function(){var n=new $.Deferred,i=t.Utils.StateStorage.CarHire.get();return i?n.resolve(_.pick(i,"pickupDate","dropoffDate","pickupPlace","dropoffPlace","pickupPlaceText","dropoffPlaceText","pickupTime","dropoffTime","ageGroup","sameDropoffPlace")):n.resolve({}),n.promise()}};n.Resolver={url:function(n){var r,i;return n=_.pick(n,"pickupPlace","dropoffPlace","pickupDate","dropoffDate","pickupTime","dropoffTime","ageGroup","sameDropoffPlace"),r=new t.Utils.Uri(t.Utils.Location.getHref()),r.setAnchorParams(n),i=r.anchor(),i=i.split("?"),i[1]}}});App.module("Flights.SearchState.Base",function(n,t){n.Provider={localstorage:function(){var i=new $.Deferred,n=t.Utils.StateStorage.Flights.get();return n?(n=_.pick(n,"outbounddate","inbounddate","originplace","destinationplace","originplaceText","destinationplaceText","cabinclass","adults","children","infants"),i.resolve(n)):i.resolve({}),i.promise()}};n.Resolver={url:function(n){var r,i;return n=_.pick(n,"originplace","destinationplace","outbounddate","inbounddate","cabinclass","adults","children","infants"),r=new t.Utils.Uri(t.Utils.Location.getHref()),r.setAnchorParams(n),i=r.anchor(),i=i.split("?"),i[1]}}});App.module("Hotels.SearchState.Base",function(n,t){n.Provider={localstorage:function(){var n=new $.Deferred,i=t.Utils.StateStorage.Hotels.get();return i?n.resolve(_.pick(i,"guests","checkin","checkout","rooms","destination","destinationText","destinationCountry","destinationInfo")):n.resolve({}),n.promise()}};n.Resolver={url:function(n){var r,i;return n=_.pick(n,"destination","checkin","checkout","guests","rooms"),r=new t.Utils.Uri(t.Utils.Location.getHref()),r.setAnchorParams(n),i=r.anchor(),i=i.split("?"),i[1]}}});App.module("SearchArea",{startWithParent:!1,define:function(n,t,i){n.SearchAreaView=i.Marionette.LayoutView.extend({template:"#search-area-template",behaviors:{ViewUnwrap:{}},ui:{searchFormRegion:".js-search-form-region"},onRender:function(){var n=t[t.Settings.wlType],r=new n.Models.SearchStateModel({}),u={};this.addRegion("searchForm",i.Marionette.Region.extend({el:this.ui.searchFormRegion,attachHtml:function(n){this.$el.hide();this.el.appendChild(n.el);this.$el.show()}}));n.SearchForm.on("ready",_.bind(function(n){this.searchForm.show(n)},this));n.SearchForm.start({errors:u,model:r});n.SearchState.provide().done(_.bind(function(n,i){_.extend(u,i);r.set(n);t.vent.trigger(t.VentActions.SearchState.READY)},this))}});n.on("start",function(){var i=new n.SearchAreaView;t.trigger("module.ready",{name:"SearchArea",view:i})});n.on("stop",function(){})}});App.module("SearchResult.Filters",function(n,t){n.FilterDropdownHeaderBase=t.Views.BaseDropdownHeaderView.extend({template:"#filter-dropdown-header-template"});n.FilterDropdownItemBase=t.Views.BaseDropdownItemView.extend({template:"#filter-dropdown-item-template"});n.FilterDropdownMultiselectItemBase=t.Views.BaseDropdownMultiselectItemView.extend({ui:_.extend({},t.Views.BaseDropdownMultiselectItemView.prototype.ui,{onlyButton:".js-only-button"}),events:_.extend({},t.Views.BaseDropdownMultiselectItemView.prototype.events,{"click @ui.onlyButton":"_onOnlyButtonClick"}),_onOnlyButtonClick:function(n){(n.preventDefault(),n.stopPropagation(),this.model.get("disabled"))||(this.model.set("selected",!0),this.trigger("item:only",this.model),this.trigger("item:select",this.model))}});n.FilterDropdownBase=t.Views.BaseDropdownView.extend({template:"#filter-dropdown-template",templateHelpers:_.extend({},t.Views.BaseDropdownView.prototype.templateHelpers,{isFilterApplied:function(){return this.multiselect?this.selection.length<this.options:this.selection.length>0}}),headerView:n.FilterDropdownHeaderBase,ui:_.extend({},t.Views.BaseDropdownView.prototype.ui,{resetButton:".js-reset-button"}),events:_.extend({},t.Views.BaseDropdownView.prototype.events,{"click @ui.resetButton":"_onResetButtonClick"}),modelEvents:{change:"onModelChange"},childView:n.FilterDropdownItemBase,behaviors:{DropdownExtendedKeysControl:{}},onBeforeRenderCollection:function(){this.trigger("before:render-dropdown")},onModelChange:function(){var n=this.isFilterApplied();this.ui.resetButton.toggleClass("selected",!n);this.ui.toggleContainer.toggleClass("active",n)},_resetSelection:function(){var n=this.model.get("multiselect");this.collection.forEach(function(t){t.set("selected",n)});this.collection.trigger("reset");this.model.set("selection",n?this.collection.models:[])},reset:function(){this.isFilterApplied()&&(this._resetSelection(),this._triggerChangeEvent())},_bindGlobalClick:function(){if(!t.Utils.Ui.isMobileView())t.GlobalEvents.on("global:click",_.bind(this._onGlobalClick,this))},_unbindGlobalClick:function(){t.Utils.Ui.isMobileView()||t.GlobalEvents.off("global:click",_.bind(this._onGlobalClick,this))},_onResetButtonClick:function(){this.reset();this.close();this.focus()},isFilterApplied:function(){return this.model.get("multiselect")?this.getValue().length<this.model.get("options").length:this.getValue().length>0}})});App.module("SearchResult.Filters",function(n,t,i){n.FilterDropdownGroupOption=t.SearchResult.Filters.FilterDropdownMultiselectItemBase.extend({});n.FilterDropdownGroup=i.Marionette.CompositeView.extend({template:"#filter-dropdown-group-template",tagName:"li",childView:n.FilterDropdownGroupOption,childViewContainer:".js-group-options",childEvents:{"item:select":"onItemSelect","item:check":"onItemCheck"},onItemSelect:function(n,t){this.collection.forEach(function(n){n.set("selected",n===t)});this.trigger("selection:change");this.render()},onItemCheck:function(n,t){this.trigger("item:check",t)},initialize:function(){this.collection=this.model.get("options")}});n.FilterDropdownGrouped=t.SearchResult.Filters.FilterDropdownBase.extend({childView:n.FilterDropdownGroup,childEvents:_.extend({},t.SearchResult.Filters.FilterDropdownBase.prototype.childEvents,{"selection:change":"_onGroupSelectionChange"}),_resetSelection:function(){var n=[],t=this.model.get("multiselect");this.collection.forEach(function(i){i.get("options").forEach(function(i){i.set("selected",t);t&&n.push(i)})});this.collection.trigger("reset");this.model.set("selection",n)},_onGroupSelectionChange:function(){this.model.set("selection",this.getSelection());this._triggerChangeEvent()},getSelection:function(){var n=[];return this.collection.each(function(t){var i=_.filter(t.get("options").models,function(n){return n.get("selected")});n.push.apply(n,i)}),n},getInvertedSelection:function(){var n=[];return this.collection.each(function(t){var i=_.filter(t.get("options").models,function(n){return!n.get("selected")});n.push.apply(n,i)}),n},setValue:function(n){var t=[];this.collection.forEach(function(i){_.each(i.get("options").models,function(i){n.indexOf(i)>-1?(i.set("selected",!0),t.push(i)):i.set("selected",!1)})});this.model.set("selection",t);this.collection.trigger("reset")},_getFlattenedOptions:function(n){var t=[];return _.each(n,function(n){t.push.apply(t,n.options)}),t},setCollection:function(n){t.SearchResult.Filters.FilterDropdownBase.prototype.setCollection.apply(this,arguments);this.model.set("options",this._getFlattenedOptions(n))},initialize:function(n){this.model=new t.SearchResult.Models.DropdownModel(n.model);this.collection=new t.SearchResult.Models.DropdownGroupedCollection(n.collection);this.model.set("selection",[])}})});App.module("SearchResult.Filters",function(n,t,i){n.FilterDropdownSliderItem=i.Marionette.ItemView.extend({tagName:"li",template:"#filter-dropdown-slider-item-template",templateHelpers:{getText:function(){return this.serialization.getTooltipText(this.values||this.value)}},ui:{slider:".js-slider",value:".js-value"},modelEvents:{"reset:default":"reset"},_initSlider:function(){var n=this._getSliderOptions();this.ui.slider.noUiSlider(n);this.ui.slider.on({slide:_.bind(this._onSliderMove,this),set:_.bind(this._onSliderChange,this)});this._updateModel()},_getSliderOptions:function(){var n=this.model.get("min"),t=this.model.get("max"),r=this.model.get("values"),i=this._getSliderStart(),u=this.model.get("step"),f=this.model.get("serialization");return{range:{min:n,max:t},step:u,start:i,connect:!!r||"lower",serialization:this._getSliderSerialization(),aria:{label:this.model.get("ariaLabel"),minvalue:n,maxvalue:t,valuenow:i,getValueText:f.getTooltipText}}},_getSliderStart:function(){var i=this.model.get("value"),n=this.model.get("values"),r=this.model.get("min"),t=this.model.get("max");return this._isSingleControl()?Math.min(i||0,t):[Math.max(n[0]||0,r),Math.min(n[1]||0,t)]},_getSliderSerialization:function(){var n=this.model.get("serialization");if(n instanceof $.Link)return{lower:[n],upper:[n]}},_isSingleControl:function(){return!this.model.get("values")},_getDefaultValue:function(){return this.model.get("max")},_getDefaultValues:function(){return[this.model.get("min"),this.model.get("max")]},_updateModel:function(){var n=this.ui.slider.val();this._isSingleControl()?(this.model.set("value",parseInt(n)),this.model.set("selected",this._isValueChanged())):(this.model.set("values",n),this.model.set("selected",this._areValuesChanged()))},_updateLabel:function(){var n=this.model.get("serialization"),t=this.model.get("values")||this.model.get("value");this.ui.value.text(n.getTooltipText(t))},_onSliderChange:function(){this._updateModel();this._updateLabel();this.trigger("item:check",this.model)},_onSliderMove:function(){this._updateModel();this._updateLabel()},_isValueChanged:function(){var n=this.model.get("value");return parseInt(n,10)!==parseInt(this.model.get("max"),10)},_areValuesChanged:function(){var n=this.model.get("values");return parseInt(n[0],10)!==parseInt(this.model.get("min"),10)||parseInt(n[1],10)!==parseInt(this.model.get("max"),10)},_destroySlider:function(){this.ui.slider.off();this.ui.slider[0]&&typeof this.ui.slider[0].destroy=="function"&&this.ui.slider[0].destroy()},reset:function(){this._isSingleControl()?this.model.set("value",this._getDefaultValue()):this.model.set("values",this._getDefaultValues());this.model.set("selected",!1);this._destroySlider();this._initSlider()},onDestroy:function(){this._destroySlider()},onRender:function(){this._initSlider()}});n.FilterDropdownSliderHeader=t.SearchResult.Filters.FilterDropdownHeaderBase.extend({templateHelpers:_.extend({},t.SearchResult.Filters.FilterDropdownHeaderBase.prototype.templateHelpers,{getTitle:function(){if(this.selection.length>0){var n=_.map(this.options,function(n){return n.serialization.getTooltipText(n.values||n.value)});return n.join("<br>")}return this.label}})});n.FilterDropdownSlider=t.SearchResult.Filters.FilterDropdownBase.extend({childView:n.FilterDropdownSliderItem,headerView:n.FilterDropdownSliderHeader,_triggerChangeEvent:function(){this.trigger("change",this._getChanges())},_getChanges:function(){var t=this.getValue()||[],n={};return _.each(t,function(t,i){n[t.get("type")||i]=t.get("values")||t.get("value")}),n},_resetSelection:function(){this.collection.forEach(function(n){n.trigger("reset:default")});this.model.set("selection",[])},initialize:function(n){this.model=new t.SearchResult.Models.DropdownModel(n.model);this.collection=new t.SearchResult.Models.DropdownSliderCollection(n.collection);this.model.set("selection",[]);this.model.set("options",this.collection)}})});App.module("BrowserNotSupported",function(n,t,i,r){n.BrowserNotSupportedView=r.ItemView.extend({template:"#browser-not-supported-template",onRender:function(){this.$el.i18n()},onShow:function(){}})});App.module("Errors",function(n,t,i,r){n.Error404View=r.ItemView.extend({template:"#errors-template",onRender:function(){this.$el.i18n()}})});App.module("Errors",function(n,t){n.is404=function(){return $("html").hasClass("error404")};n.on("start",function(){if(n.is404()){var i=new n.Error404View;t.errors.show(i)}})});App.module("Services",function(n){var t=new App.Utils.Cache(100),r=function(n){return n.weight+" "+n.unit},i=Backbone.Model.extend({defaults:{carrierMatrix:[],carrierData:{}},setCarrierBaggageDataModel:function(n){var i,t;if(this.attributes.carrierMatrix.length===0&&this.attributes.carrierMatrix.push(["Carrier","Cabin Baggage","1st Checked Bag","2nd Checked Bag","3rd Checked Bag"]),i=n.get("carrierCode"),!this.attributes.carrierData.hasOwnProperty(i)){this.attributes.carrierData[i]=[n];var r=[i,n.get("cabinBaggage").get("bagItems")[0].getMatrixCell()],u=n.get("checkedBaggage"),f=u.get("bagItems");for(t=0;t<3;t++)!u.isEmpty()&&f[t]instanceof BaggageItemModel?r.push(f[t].getMatrixCell()):r.push("N/A");this.set("carrierMatrix",this.get("carrierMatrix").push(r))}},getDisplayMatrix:function(){return this.get("carrierMatrix")}});n.BaggageFees={_apiUrl:"/baggage-details",_apiVersion:"1",_consumer:"whitelabel",_matrix:null,_detailsTemplate:null,itineraryBaggageKey:"baggageDetails",baggageTypes:["checked","cabin"],processLegs:function(n,t){for(var f=[],r,u,o,i=0,e=n.length;i<e;i++)r=n[i],o=t.get("legs")[i],r.leg=i===0?"outbound":"inbound",u?_.isEqual(r.passenger_types,u.passenger_types)?u.leg="both":f.push(r):f.push(r),u=r;return f},processItineraries:function(n,i){var r=this,u=[],f={},e;n.each(function(n,i){var e=t.get(n.get("fingerprint"));e===null?(f[n.get("fingerprint")]=i,u.push(n)):n.set(r.itineraryBaggageKey,e)});e=this._buildRequest(u);e.done(function(u){$.ajax({type:"POST",url:r._apiUrl,data:JSON.stringify(u),contentType:"application/json",dataType:"json"}).done(function(u){var e=App.Dictionaries&&App.Dictionaries.Carriers||{};_.each(u.journeys,function(i){var u=[],o;_.each(i.baggage_travels,function(n){var t;_.each(n.cabin,function(n){t=_.where(e,{Code:n.carrier});t=t.length?t[0]:{};n.carrier={code:n.carrier,url:t.ImageUrl,name:t.Name}});t=_.where(e,{Code:n.checked.carrier});t=t.length?t[0]:{};n.checked.carrier={code:n.checked.carrier,url:t.ImageUrl,name:t.Name};u.push(n)});o=i.journey_id;t.set(o,u);n.at(f[o]).set(r.itineraryBaggageKey,u)});i.call(this,n)}).fail(function(){})})},fillMatrix:function(n){this._matrix===null&&(this._matrix=new i);this._matrix.setCarrierBaggageDataModel(n)},getDisplayMatrix:function(){return this._matrix instanceof i?this._matrix.getDisplayMatrix():null},_buildRequest:function(n){var i=this,t=new $.Deferred;return $.when(App.Services.Language.getLanguage(),App.Services.Market.getMarket(),App.Services.Currency.getCurrency()).done(_.bind(function(r,u,f){var e={version:i._apiVersion,consumer:i._consumer,sale_details:{user_market:u,user_currency:f,sale_date:moment().format("YYYY-MM-DD")},params:{show_summary:!1,show_text:!1,show_all_checked_items:!1,compressed_allowance:!1},passengers:[],journeys:[]};e.passengers=["adults"];e.journeys=_.map(n,function(n){var t=n.attributes,i=t.cabinclass.value.split(/(?=[A-Z])/).join("_").toLowerCase(),r=_.unique(_.flatten(_.map(t.legs,function(n){return _.map(n.carriers,function(n){return n.code})})));return{journey_id:t.fingerprint,journey_type:App.Utils.StateStorage.Flights.get().inbounddate?"RoundTrip":"OneWay",legs:_.map(t.legs,function(n,t){return{leg_id:""+t,cabin_class:i,origin:n.firstStation.code,destination:n.lastStation.code,date:App.Utils.StateStorage.Flights.get().inbounddate,flights:_.map(n.segments,function(n,r){return{flight_id:t+"-"+r,origin:n.originStation.Code,destination:n.destinationStation.Code,departure_datetime:n.departure.datetime,arrival_datetime:n.arrival.datetime,marketing_carrier:n.carrier.Code,operating_carrier:n.operatingCarrier?n.operatingCarrier.Code:n.carrier.Code,cabin_class:i}})}})}});t.resolve(e)})).fail(function(){t.reject()}),t.promise()},invalidate:function(){t.clear()},renderDetails:function(n,t){var i;this._detailsTemplate||(this._detailsTemplate=_.template($("#baggage-details-table").html()));this._carrierTemplate||(this._carrierTemplate=_.template($("#baggage-details-carrier").html()));this._bagsTemplate||(this._bagsTemplate=_.template($("#baggage-details-bags").html()));i=this._detailsTemplate({carrierTemplate:this._carrierTemplate,bagsTemplate:this._bagsTemplate,baggageDetails:t});n.html(i).addClass("rendered").i18n()}}});App.module("Services",function(n,t){t.Services.Market.Resolvers.onSet=function(n){n.CountryId=n.CountryId.replace("-"+t.Dictionaries.LocationSchema,"");t.Services.Market.Resolvers.localstorage(n,"user_select");var i=new t.Utils.Uri(t.Utils.Location.getHref()),r=i.getAnchorParams();_.has(r,"destination")&&Backbone.history.stop();t.Utils.Location.reload()};t.Services.HomeCity.Resolvers.onSet=function(n){var r,i,u;n.PlaceId=n.PlaceId.replace("-"+t.Dictionaries.LocationSchema,"");t.Services.HomeCity.Resolvers.localstorage(n);t.Flights.SearchForm.trigger("change:originPlace",n);r=new t.Utils.Uri(t.Utils.Location.getHref());i=r.getAnchorParams();_.has(i,"destinationplace")&&i.destinationplace===n.PlaceId||_.has(i,"originplace")&&(u=t.Flights.SearchForm.getCurrentStateForUrlParams(),i=_.extend({},i,u,{originplace:n.PlaceId}),_.has(i,"homecity")&&(i.homecity=n.PlaceId),r.setAnchorParams(i),Backbone.history.stop(),t.Utils.Location.setHref(r.toString()));t.Utils.Location.reload()};t.Services.Language.Resolvers.onSet=function(n){var i=new t.Utils.Uri(t.Utils.Location.getHref()),r=i.getAnchorParams(),f,u;_.has(r,"originplace")&&(f=t.Flights.SearchForm.getCurrentStateForUrlParams(),r=_.extend({},r,f),i.setAnchorParams(r));u=i.path().toLowerCase();u=u.replace(/\/\w{2}-\w{2}/i,"/"+n);i.path(u);t.Utils.Location.setHref(i.toString())};t.Services.Currency.Resolvers.onSet=function(n){var r,i,u;t.Services.Currency.Resolvers.localstorage(n);r=new t.Utils.Uri(t.Utils.Location.getHref());i=r.getAnchorParams();_.has(i,"originplace")&&(u=t.Flights.SearchForm.getCurrentStateForUrlParams(),i=_.extend({},i,u),r.setAnchorParams(i),_.has(i,"currency")&&(i.currency=n),r.setAnchorParams(i),Backbone.history.stop(),t.Utils.Location.setHref(r.toString()));t.Utils.Location.reload()}});App.module("Services",function(n,t){function i(n){if(n){if(moment(n).isSame(moment(),"day")){var i=moment.utc();return i.format(t.Settings.dateFormat)}return n}}n.Flights={getFlights:function(r,u){r.outbounddate=i(r.outbounddate);r.inbounddate=i(r.inbounddate);var f=new $.Deferred;return u=u||0,t.Services.Session.getToken().done(function(i){r.apiKey=i;n.Flights.skyscannerLivePricing("getFlights",r).progress(function(n){t.Utils.Ui.isSlowDevice()||f.notify(n)}).done(function(n){f.resolve(n)}).fail(function(i){if(i.status===419||i.status===403)u<t.Services.Session.MAX_TOKEN_ATTEMPTS?(u++,t.Services.Session.getToken(!0).done(function(){n.Flights.getFlights(r,u).progress(function(n){f.notify(n)}).done(function(n){f.resolve(n)}).fail(function(n){f.reject(n)})})):(Logger("flights-service").fatal("getFlights token error: "+JSON.stringify(i)),f.reject(i));else{if(i.status!==404&&i.status!==429){var e={response:i,request:r};Logger("flights-service").fatal("getFlights fatal error:"+JSON.stringify(e))}switch(i.status){case 400:t.tracking.trackEvent("error","flights-service:getFlights","400 Bad Request");break;case 429:Logger("flights-service").error("getFlights error:"+JSON.stringify(e));t.tracking.trackEvent("error","flights-service:getFlights","429 Too Many Requests");break;case 500:t.tracking.trackEvent("error","flights-service:getFlights","500 Server Error")}f.reject(i)}})}).fail(function(n){f.reject(n)}),f.promise()},getFlightBookingDetails:function(i,r,u){var f=new $.Deferred;return u=u||0,t.Services.Session.getToken().done(function(e){var o=t.Utils.Uri.removeBackslashes(i+"?apikey="+encodeURIComponent(e));n.Flights.skyscannerLivePricing("getFlightBookingDetails",o,r).progress(function(n){f.notify(n)}).done(function(n){f.resolve(n)}).fail(function(e){if(e.status===419||e.status===403)u<t.Services.Session.MAX_TOKEN_ATTEMPTS?(u++,t.Services.Session.getToken(!0).done(function(){n.Flights.getFlightBookingDetails(i,r,u).done(function(n){f.resolve(n)}).fail(function(n){f.reject(n)})})):(Logger("flights-service").fatal("getFlightBookingDetails token error: "+JSON.stringify(e)),f.reject(e));else{e.status!==404&&Logger("flights-service").fatal("getFlightBookingDetails error: "+JSON.stringify(e));switch(e.status){case 400:t.tracking.trackEvent("error","flights-service:getFlightBookingDetails","400 Bad Request");break;case 429:t.tracking.trackEvent("error","flights-service:getFlightBookingDetails","429 Too Many Requests");break;case 500:t.tracking.trackEvent("error","flights-service:getFlightBookingDetails","500 Server Error")}f.reject(e)}})}).fail(function(n){f.reject(n)}),f.promise()},skyscannerLivePricing:function(n,t,i){var f=this,r=$.Deferred(),u="",e,o;return n==="getFlights"&&(u=this.getRequestHash(t)),e={onResults:function(n){n||r.reject(n);n.Flights.Status!=="UpdatesComplete"?r.notify(f.inflateResponse(n,u)):r.resolve(f.inflateResponse(n,u))},onServerFailure:function(n){r.reject(n)},onValidationFailure:function(n){r.reject(n)},onBookingDetails:function(n,t){t?r.resolve(n):r.notify(n)},onTokenExpire:function(n){r.reject(n)}},o=new Skyscanner.LivePricingClient(e),o[n](t,i),r.promise()},getItineraryFingerPrint:function(n,t){var i="",r=[n.OutboundLegId];return n.InboundLegId&&r.push(n.InboundLegId),_.each(r,function(n){i+=n.departureTime.toString();_.each(n.FlightNumbers,function(t){var r=_.findWhere(n.Carriers,{Id:t.CarrierId});r&&(i+=r.Code+t.FlightNumber)})}),i=i+"-"+t},inflateResponse:function(n,i){var f,e,r,o,u;return!n||!n.Flights||n.Flights.Itineraries.length===0?n:(n.oneway=!n.Flights.Query.InboundDate,n.Flights.SegmentsById=_.indexBy(n.Flights.Segments,"Id"),n.Flights.PlacesById=_.indexBy(n.Flights.Places,"Id"),f=this,n.Flights.Itineraries=_.filter(n.Flights.Itineraries,function(n){return n.PricingOptions&&n.PricingOptions.length>0}),t.Services.Feature.check("topItineraryLabels","on")&&(e=_.map(n.Flights.Itineraries,function(n){return n.PricingOptions[0].Price}),r=_.sortBy(e),r=_.uniq(r,!0).slice(0,3),o=_.map(n.Flights.Itineraries,function(n){var t=n.OutboundLegId.Duration;return n.InboundLegId&&(t+=n.InboundLegId.Duration),t}),u=_.sortBy(o),u=_.uniq(u,!0).slice(0,3)),_.each(n.Flights.Itineraries,function(e){var o,h,v,c,y,s,l,a;if(e.maxStops=Math.max(e.OutboundLegId.Stops.length,e.InboundLegId?e.InboundLegId.Stops.length:0),e.maxStops>=4){e.removed=!0;return}e.price=e.PricingOptions[0].Price;e.bookingDetailsLinkBody=e.BookingDetailsLink.Body;e.duration=e.OutboundLegId.Duration+(e.InboundLegId?e.InboundLegId.Duration:0);e.airlines=_.map(_.union(e.OutboundLegId.Carriers,e.InboundLegId?e.InboundLegId.Carriers:[]),function(n){return n.Id});o=[];o.push(e.OutboundLegId.OriginStation.Code);o.push(e.OutboundLegId.DestinationStation.Code);n.oneway||(o.push(e.InboundLegId.OriginStation.Code),o.push(e.InboundLegId.DestinationStation.Code));e.mainAirports=_.uniq(o);h=function(t){var i=[];return t?(_.each(t.Stops,function(r){r?i.push(r.Code):_.each(t.SegmentIds,function(t){var f=n.Flights.SegmentsById[t].OriginStation,o=n.Flights.SegmentsById[t].OriginStation,r=n.Flights.PlacesById[f],u=n.Flights.PlacesById[o];r&&e.mainAirports.indexOf(r)===-1&&i.push(r.Code);u&&e.mainAirports.indexOf(u)===-1&&i.push(u.Code)})}),i):i};e.airports=_.union(h(e.OutboundLegId),h(e.InboundLegId));e.InboundLegId&&(e.InboundLegId.departureTime=parseInt(moment(e.InboundLegId.Departure,t.Settings.datetimePricingServiceFormat).format(t.Settings.timePricingServiceFormat).replace(/:/,"")));e.OutboundLegId&&(e.OutboundLegId.departureTime=parseInt(moment(e.OutboundLegId.Departure,t.Settings.datetimePricingServiceFormat).format(t.Settings.timePricingServiceFormat).replace(/:/,"")));v=f.getConnectingAirports(e.OutboundLegId,n);c=[];e.InboundLegId&&(c=_.union(f.getConnectingAirports(e.InboundLegId,n)));y=_.union(v,c);e.connectingAirports=_.uniq(y);e.fingerprint=f.getItineraryFingerPrint(e,i);r&&u&&(s=[],l=r.indexOf(e.price),l>=0&&s.push("cheapest"+(l+1)),a=u.indexOf(e.duration),a>=0&&s.push("shortest"+(a+1)),e.topItineraryLabels=s)}),n.Flights.Itineraries=_.reject(n.Flights.Itineraries,function(n){return n.removed}),t.Dictionaries.Carriers=n.Flights.Carriers.concat([]),t.Dictionaries.Places=n.Flights.Places,this._updateImageURL(t.Dictionaries.Carriers,t.Dictionaries.ImageLinks.favicon),n)},getConnectingAirports:function(n,t){var i=[];return _.each(n.SegmentIds,function(n){var r=t.Flights.SegmentsById[n],u,f;r&&(u=t.Flights.places[r.OriginStation],f=t.Flights.places[r.DestinationStation],u&&f&&(i.push(u.Code),i.push(f.Code)))}),i},getFilteredItineraries:function(n,i,r){var a,v,y,l,p,tt,u,w,b,k,d,g;if(!n||!n.Flights||n.Flights.Itineraries.length===0)return[];var s=n.Flights.Itineraries,u,nt=!1,f=function(){return nt||s.length>0?s:n.Flights.Itineraries},e=function(n){s=n;nt=!0},h=i.departTimeRange||i.times&&i.times.outbound,c=i.returnTimeRange||i.times&&i.times.inbound,o;if(i.airports&&(a=i.airports,o=_.findWhere(a,{checked:!1}),o&&(l=[],_.each(a,function(n){n.checked&&l.push(n.code)}),u=[],v=[],_.each(r.mainAirports,function(n){v.push(n.code)}),_.each(f(),function(n){var t=_.intersection(v,n.mainAirports);_.intersection(l,t).length===t.length&&u.push(n)}),e(u))),i.connectingAirports&&(o=_.findWhere(i.connectingAirports,{checked:!1}),o&&(y=[],_.each(i.connectingAirports,function(n){n.checked&&y.push(n.code)}),u=[],_.each(f(),function(n){_.intersection(y,n.airports).length===n.airports.length&&(n.airports.length!==0||n.maxStops===0)&&u.push(n)}),e(u))),i.airportsv2&&i.airportsv2.not&&(l=i.airportsv2.not,u=[],_.each(f(),function(n){var t=_.union(n.mainAirports,n.airports),i=_.intersection(t,l);i.length===0&&u.push(n)}),e(u)),i.stops&&i.stops!=="any"&&(u=[],p=_.findWhere(t.Dictionaries.StopsList,{value:i.stops}),_.each(f(),function(n){n.OutboundLegId.Stops&&n.OutboundLegId.Stops.length<=p.count&&(!n.InboundLegId||n.InboundLegId.Stops&&n.InboundLegId.Stops.length<=p.count)&&u.push(n)}),e(u)),i.airlines&&(o=_.findWhere(i.airlines,{checked:!1}),o)){if(u=[],i.airlines.length===0)return[];tt=_.map(_.filter(i.airlines,function(n){return n.checked}),function(n){return n.code});_.each(f(),function(n){_.intersection(tt,n.airlines).length===n.airlines.length&&u.push(n)});e(u)}return i.airlinesv2&&i.airlinesv2.not&&(u=[],_.each(f(),function(n){var t=_.intersection(i.airlinesv2.not,n.airlines);t.length===0&&u.push(n)}),e(u)),i.priceMax&&(u=[],_.each(f(),function(n){n.price<=i.priceMax&&u.push(n)}),e(u)),i.duration&&(u=[],_.each(f(),function(n){(n.OutboundLegId.Duration<=i.duration.outbound||i.duration.outboundMax)&&(i.duration.inbound&&n.InboundLegId?(n.InboundLegId.Duration<=i.duration.inbound||i.duration.inboundMax)&&u.push(n):u.push(n))}),e(u)),h&&(u=[],w=h[0]?parseInt(moment(parseFloat(h[0])).format(t.Settings.timePricingServiceFormat).replace(/:/,"")):null,b=h[1]?parseInt(moment(parseFloat(h[1])).format(t.Settings.timePricingServiceFormat).replace(/:/,"")):null,_.each(f(),function(n){(!b||n.OutboundLegId.departureTime<=b)&&(!w||n.OutboundLegId.departureTime>=w)&&u.push(n)}),e(u)),c&&(u=[],k=c[0]?parseInt(moment(parseFloat(c[0])).format(t.Settings.timePricingServiceFormat).replace(/:/,"")):null,d=c[1]?parseInt(moment(parseFloat(c[1])).format(t.Settings.timePricingServiceFormat).replace(/:/,"")):null,_.each(f(),function(n){(!n.InboundLegId||(!d||n.InboundLegId.departureTime<=d)&&(!k||n.InboundLegId.departureTime>=k))&&u.push(n)}),e(u)),i.sort&&(g=i.sort.type==="price",s=_.chain(f()).sortBy(function(n){return g?n.duration:n.price}).sortBy(function(n){return g?n.price:n.duration}).value()),s},separateTime:function(n,t){var i="000"+n,r=i.substr(i.length-t);return r.substr(0,2)+":"+r.substr(2)},getSliderRangeInfo:function(n,t,i){var r,u,f;if(!n)return{};var l=this.separateTime(n.timeBoundary.outboundTime.min.OutboundLegId.departureTime,4),a=this.separateTime(n.timeBoundary.outboundTime.max.OutboundLegId.departureTime,4),v=n.timeBoundary.inboundTime.min!==null?this.separateTime(n.timeBoundary.inboundTime.min.InboundLegId.departureTime,4):"",y=n.timeBoundary.inboundTime.max!==null?this.separateTime(n.timeBoundary.inboundTime.max.InboundLegId.departureTime,4):"",e=moment("2014-06-20 "+l).valueOf(),o=moment("2014-06-20 "+a).valueOf(),s=moment("2014-06-20 "+v).valueOf(),h=moment("2014-06-20 "+y).valueOf(),c=Math.ceil(n.dearest.price);return t&&typeof t.priceMax!="undefined"&&(c=t.priceMax),r=[e,o],t&&typeof t.departTimeRange!="undefined"&&t.departTimeRange.length===2&&(r[0]=t.departTimeRange[0]?t.departTimeRange[0]:r[0],r[1]=t.departTimeRange[1]?t.departTimeRange[1]:r[1]),t&&t.times&&t.times.outbound&&(r=t.times.outbound),u=[s,h],t&&typeof t.returnTimeRange!="undefined"&&t.returnTimeRange.length===2&&(u[0]=t.returnTimeRange[0]?t.returnTimeRange[0]:u[0],u[1]=t.returnTimeRange[1]?t.returnTimeRange[1]:u[1]),t&&t.times&&t.times.inbound&&(u=t.times.inbound),f={priceMax:c,departTimeRange:r,returnTimeRange:u},i||(f=_.extend(f,{minOutBoundTime:e,maxOutBoundTime:o,minInBoundTime:s,maxInBoundTime:h})),f},getPageForIndex:function(n,t){return Math.max(1,Math.ceil((1+n)/t))},getSummaryModel:function(n,i){var ft=this,et=t.Services.Currency.getCurrentCurrencyInfo(),r=n.Flights.Itineraries,f,o,b,y,s,h,k,ut,a,e;if(r.length===0)return null;f=n.Flights&&n.Flights.Carriers?_.map(n.Flights.Carriers,function(n){var i=-1,f=!1,u;return t.Utils.Ui.isSlowDevice()||(u=_.filter(r,function(t){var i=_.pluck(t.OutboundLegId.Carriers,"Id"),r=t.InboundLegId?_.pluck(t.InboundLegId.Carriers,"Id"):[];return _.contains(i,n.Id)&&(t.InboundLegId?_.contains(r,n.Id):!0)}),i=_.min(u,function(n){return n.price}),i=i?Math.ceil(i.price):"",f=_.find(u,function(n){return n.airlines!=null&&n.airlines.length===1})!=null),{id:n.Id,name:n.Name,displayCode:n.DisplayCode,value:n.Code,minPrice:isNaN(i)?-1:i,filterable:f,checked:!0}}):[];t.Utils.Ui.isSlowDevice()||(f=_.reject(f,function(n){return n.minPrice===""}));f=_.sortBy(f,function(n){return n.name.toLowerCase()});var w=n.Flights&&n.Flights.Places?_.clone(_.where(n.Flights.Places,{Type:"Airport"})):[],u=[],g=[{stops:0,number:0},{stops:1,number:0},{stops:2,number:0},{stops:3,number:0}];_.each(r,function(t){u.push(t.OutboundLegId.OriginStation.Code);u.push(t.OutboundLegId.DestinationStation.Code);n.oneway||(u.push(t.InboundLegId.OriginStation.Code),u.push(t.InboundLegId.DestinationStation.Code));g[t.maxStops].number++});u=_.uniq(u);var v=parseInt(n.Flights.Query.OriginPlace),nt=parseInt(n.Flights.Query.DestinationPlace),ot=_.filter(n.Flights.Places,function(t){return parseInt(t.Id,10)===parseInt(n.Flights.Query.OriginPlace,10)||parseInt(t.Id,10)===parseInt(n.Flights.Query.DestinationPlace,10)});u=_.map(u,function(n){var t=_.findWhere(w,{Code:n});return _.extend(t,{isBoundary:t.ParentId===v||t.ParentId===nt||t.Id===v||t.Id===nt,isOrigin:t.ParentId===v||t.Id===v,checked:!0})});o=_.clone(u);b=_.countBy(u,function(n){return n.isOrigin?"origin":"destination"});u=_.filter(u,function(n){return b.origin>1&&n.isOrigin||b.destination>1&&!n.isOrigin});y=[];_.each(ot,function(n){var t=_.sortBy(_.where(u,{ParentId:n.Id}),function(n){return n.Name.toLowerCase()});y=_.union(y,t)});u=_.pluck(y,"Code");o=_.pluck(o,"Code");u=_.map(u,function(n){return{code:n,checked:!0}});t.Utils.Ui.isSlowDevice()||_.each(u,function(n){var t=_.filter(r,function(t){return _.contains(t.mainAirports,n.code)});n.minPrice=Math.ceil(_.min(t,function(n){return n.price}).price)});var st=_.filter(w,function(n){return!_.contains(o,n.Code)}),ht=_.map(st,function(n){var i=-1,u;return t.Utils.Ui.isSlowDevice()||(u=_.filter(r,function(t){return _.contains(t.connectingAirports,n.Code)}),i=Math.ceil(_.min(u,function(n){return n.price}).price)),{code:n.Code,checked:!0,name:n.Name,minPrice:i}}),tt=_.min(r,function(n){return n.price});_.each(r,function(n){var t=n.OutboundLegId.Duration;n.InboundLegId&&(t+=n.InboundLegId.Duration);n.calculatedDuration=t});s=_.min(r,function(n){return n.OutboundLegId.departureTime});s=_.extend(s,{time:s.OutboundLegId.departureTime});h=_.max(r,function(n){return n.OutboundLegId.departureTime});h=_.extend(h,{time:h.OutboundLegId.departureTime});k=!1;_.each(r,function(n){n.OutboundLegId.departureTime>="1200"&&n.OutboundLegId.departureTime<="1800"&&(k=!0)});var ct=_.min(r,function(n){return n.OutboundLegId.Duration}).OutboundLegId.Duration,lt=_.max(r,function(n){return n.OutboundLegId.Duration}).OutboundLegId.Duration,it=null,d=null,c=null,l=null,rt=!1;n.oneway||(it=_.min(r,function(n){return n.InboundLegId.Duration}).InboundLegId.Duration,d=_.max(r,function(n){return n.InboundLegId.Duration}).InboundLegId.Duration,c=_.min(r,function(n){return n.InboundLegId.departureTime}),c=_.extend(c,{time:c.InboundLegId.departureTime}),l=_.max(r,function(n){return n.InboundLegId.departureTime}),l=_.extend(l,{time:l.InboundLegId.departureTime}),_.each(r,function(n){n.InboundLegId.departureTime>="1200"&&n.InboundLegId.departureTime<="1800"&&(rt=!0)}));ut=_.filter(r,function(n,t){return n.page=ft.getPageForIndex(t,i),n.price===tt.price});a=_.min(ut,function(n){return n.calculatedDuration});a&&(a.price=Math.ceil(a.price));e=_.filter(r,function(n){return n.OutboundLegId.Stops.length===0&&(!n.InboundLegId||n.InboundLegId.Stops.length===0)});e=e&&e.length>0?_.min(e,function(n){return n.price}):null;var at=_.max(r,function(n){return n.price}),vt=_.min(r,function(n){return n.calculatedDuration}),yt=_.filter(r,function(n){return n.calculatedDuration===vt.calculatedDuration}),p=_.min(yt,function(n){return n.price});return p&&(p.price=Math.ceil(p.price)),{flightsNumber:r.length,currency:et,cheapest:tt,cheapestShortest:a,cheapestDirect:e,dearest:at,shortestCheapest:p,paginateBy:i,timeBoundary:{inboundTime:{min:c,max:l,afternoon:rt},outboundTime:{min:s,max:h,afternoon:k}},airlines:f,outbound:{maxDuration:lt,minDuration:ct},inbound:d?{maxDuration:d,minDuration:it}:null,allAirports:w,mainAirports:u,boundaryAirports:o,stopsDistribution:g,ca:ht}},wrapLeg:function(n,i){var r=[],c=moment(n.Arrival,t.Settings.datetimePricingServiceFormat),l=moment(n.Departure,t.Settings.datetimePricingServiceFormat),h;this._updateImageURL(n.Carriers,t.Dictionaries.ImageLinks.favicon);this._updateImageURL(n.OperatingCarriers,t.Dictionaries.ImageLinks.favicon);var y=[],p=[],w=!1,u=_.map(n.SegmentIds,function(r,u){var f=i.Flights.SegmentsById[r],d=_.findWhere(n.Carriers,{Id:f.Carrier}),g=_.findWhere(n.OperatingCarriers,{Id:f.OperatingCarrier}),c=moment.duration(f.Duration,"minutes"),e={id:f.Id,originStation:_.findWhere(i.Flights.Places,{Id:f.OriginStation}),destinationStation:_.findWhere(i.Flights.Places,{Id:f.DestinationStation}),carrier:d,operatingCarrier:g,flightNumber:f.FlightNumber,duration:{days:c.days(),hrs:c.hours(),mins:c.minutes()}},h,o;if(f.DepartureDateTime&&(h=moment(f.DepartureDateTime,t.Settings.datetimePricingServiceFormat),e=_.extend(e,{departure:{datetime:f.DepartureDateTime,datetimeMoment:h,date:t.Culture.culture.formatDate(h.toDate(),{date:"fullAbbr"}),dateMobile:t.Culture.culture.formatDate(h.toDate(),{date:"monthDayAbbr"}),time:t.Culture.culture.formatDate(h.toDate(),{time:"short"})}})),f.ArrivalDateTime&&(o=moment(f.ArrivalDateTime,t.Settings.datetimePricingServiceFormat),e=_.extend(e,{arrival:{datetime:f.ArrivalDateTime,datetimeMoment:o,date:t.Culture.culture.formatDate(o.toDate(),{date:"fullAbbr"}),dateMobile:t.Culture.culture.formatDate(o.toDate(),{date:"monthDayAbbr"}),time:t.Culture.culture.formatDate(o.toDate(),{time:"short"})}}),u<n.SegmentIds.length-1)){var a=i.Flights.SegmentsById[n.SegmentIds[u+1]],nt=_.findWhere(i.Flights.Places,{Id:a.OriginStation}),tt=moment(a.DepartureDateTime,t.Settings.datetimePricingServiceFormat),v=tt.diff(o,"minutes"),l=moment.duration(v,"minutes"),s=_.uniq([e.destinationStation,nt]),b=v>180,k=!1;s.length>1&&_.every(s,function(n){return n&&n.Name})&&(y.push(s),k=!0);b&&(_.every(s,function(n){return n&&n.Name})?p.push(s):w=!0);e=_.extend(e,{stopAirports:s,longLayover:b,transferBetweenAirports:k,stopDuration:{hrs:l.hours()+parseInt(l.days(),10)*24+(parseInt(l.minutes(),10)>0?1:0)}})}return e}),a=u[0];_.each(u,function(n){if(a.departure){var t=a.departure.datetimeMoment?a.departure.datetimeMoment.startOf("day"):!1;n.departure&&_.extend(n.departure,{daysShift:!n.departure.datetimeMoment||!t?0:n.departure.datetimeMoment.startOf("day").diff(t,"days")});n.arrival&&_.extend(n.arrival,{daysShift:!n.arrival.datetimeMoment||!t?0:n.arrival.datetimeMoment.startOf("day").diff(t,"days")})}});r.push({code:n.OriginStation.Code,id:n.OriginStation.Id,name:n.OriginStation.Name,datetime:l,time:l.format(t.Settings.timePricingServiceFormat),date:l.format(t.Settings.datePricingServiceFormat)});r.push({code:n.DestinationStation.Code,id:n.DestinationStation.Id,name:n.DestinationStation.Name,datetime:c,time:c.format(t.Settings.timePricingServiceFormat),date:c.format(t.Settings.datePricingServiceFormat)});var v=moment.duration({minutes:n.Duration}),e=n.OperatingCarriers[0]||{},b=_.map(n.Carriers,function(n){return{id:n.Id,code:n.Code,name:n.Name,imageUrl:n.ImageUrl,displayCode:n.DisplayCode}}),tt=_.map(n.OperatingCarriers,function(n){return{id:n.Id,code:n.Code,name:n.Name,imageUrl:n.ImageUrl}}),k=_.difference(_.map(n.OperatingCarriers,function(n){return n.Id}),_.map(n.Carriers,function(n){return n.Id})),o=_.map(_.filter(n.OperatingCarriers,function(n){return _.contains(k,n.Id)}),function(n){return{id:n.Id,code:n.Code,name:n.Name,imageUrl:n.ImageUrl}}),it=_.map(n.FlightNumbers,function(n){var i={number:n.FlightNumber},t=_.find(tt,function(t){return n.CarrierId===t.id});return t&&(i=_.extend(i,{carrier:{id:t.id,name:t.name,code:t.code,imageUrl:t.imageUrl,showOperatedBy:_.contains(k,t.id)}})),i}),s=_.map(_.filter(n.Stops,function(n){return n.Code}),function(n){return n.Code?n.Code:"..."}).join(", ");s!==""&&(s="("+s+")");var d=r[r.length-1].datetime.startOf("day").diff(r[0].datetime.startOf("day"),"days"),g=n.Directionality==="Outbound",rt={imageUrl:n.Carriers[0].ImageUrl,name:n.Carriers[0].Name,id:n.Carriers[0].Id},ut=r[r.length-1],f={multipleAirlines:b.length>1,arrival:d!==0,operatedByCarriers:o.length>1,operatedByOne:o.length===1,transferBetweenAirports:y,longLayovers:p,hasUnknownLongLayovers:w},nt=g?$.t("search-result.details.messages-depart"):$.t("search-result.details.messages-return");return u.length&&u[0].departure&&(nt+=" "+u[0].departure.date),h=[],o.length>0&&_.each(u,function(n){h.push($.i18n.t("search-result.details.codeshare-message-short",{carrier:n.operatingCarrier?n.operatingCarrier.Name:n.carrier?n.carrier.Name:"---",flight:n.carrier?n.carrier.Code+n.flightNumber:n.flightNumber}))}),{messages:f,stations:r,firstStation:r[0],lastStation:ut,segments:u,agent:rt,flight:{stops:{length:n.Stops.length,context:n.Stops.length===0?"flightinfozero":"",text:s},duration:{min:v.minutes(),hours:v.hours(),days:v.days()}},operatedBy:{id:e.Id,code:e.Code,name:e.Name,imageUrl:e.ImageUrl},flightNumbers:it,carriers:b,isDepart:g,daysShift:d,carriersDiff:o,longLayovers:{show:f.longLayovers.length>0||f.hasUnknownLongLayovers,airports:_.pluck(_.flatten(_.filter(f.longLayovers,function(n){return n.length===1}),!0),"Name").join(", "),hasUnknownLongLayovers:f.hasUnknownLongLayovers},mobileHeader:nt,codeshare:h.length>1?h.join(", ")+".":""}},getList:function(n,i){var u=this,r=n.get("response"),e=n.get("filteredItineraries");if(!r||!r.Flights||r.Flights.Itineraries.length===0||!e||e.length===0)return[];var l=n.get("page"),o=AppSettings.paginateBy,f=t.Services.Currency.getCurrentCurrencyInfo(),s=l*o-o,a=e.slice(s,s+o),v=_.pluck(t.Utils.FavoritesStorage.Flights.getFavorites(),"fingerprint"),h=u.isGroupPrice(i),c=[];return _.each(a,function(e,o){var s=_.clone(e),w=Math.ceil(s.price),b,a,k;_.each(s.PricingOptions,function(n){u._updateImageURL(n.Agents,t.Dictionaries.ImageLinks.OTA)});var y=s.PricingOptions[0].Agents[0],g={imageUrl:y.ImageUrl,name:y.Name,id:y.Id,type:y.Type,isMultibooking:s.PricingOptions[0].Agents.length>1},l=[];if(l.push(u.wrapLeg(s.OutboundLegId,r)),s.InboundLegId&&l.push(u.wrapLeg(s.InboundLegId,r)),l.length>1){var p=[l[0].segments.length,l[1].segments.length],nt=_.min(p),tt=_.max(p),it=nt+"_"+tt;l[p[0]===nt?0:1].directionClass=it+"_f";l[p[0]===tt?0:1].directionClass=it+"_s"}b=[];s.topItineraryLabels&&s.topItineraryLabels.length!==0&&(b=s.topItineraryLabels.slice());a=[];_.each(s.PricingOptions[0].Agents,function(n){a.push({id:n.Id,name:n.Name,imageUrl:n.ImageUrl})});_.each(l,function(n){_.extend(n.messages,{nonGuaranted:l.length===1&&a.length>1||l.length>1&&a.length>2,multibooking:!n.isDepart&&l.length===2&&a.length===2&&l[0].segments.length===1&&l[1].segments.length===1,diffDepart:!n.isDepart&&l[0].stations[l[0].stations.length-1].code!==n.stations[0].code,diffArrive:!n.isDepart&&l[0].stations[0].code!==n.lastStation.code})});k={};_.each(l,function(n){_.each(n.carriers,function(n){k[n.id]=n.displayCode})});_.each(l,function(n){var u="",i=n.isDepart?"outbound":"inbound",t="",f,r;n.messages.nonGuaranted?t=$.i18n.t("search-result.details.non-protected-flight-message-"+i,{}):!n.isDepart&&g.isMultibooking&&a.length<=2?t=$.i18n.t("search-result.details.multi-booking-message-"+i):n.messages.transferBetweenAirports&&n.messages.transferBetweenAirports.length>0?(t=[],_.each(n.messages.transferBetweenAirports,function(n){var r=_.pluck(n,"Name"),u;r&&(u=$.i18n.t("search-result.details.transfer-between-airports-message-"+i,{airport1:r[0],airport2:r[1]}),t.push(u))})):!n.isDepart&&n.messages.diffDepart?t=$.i18n.t("search-result.details.diff-airports-message-departs"):!n.isDepart&&n.messages.diffArrive?t=$.i18n.t("search-result.details.diff-airports-message-arrives"):!n.longLayovers.hasUnknownLongLayovers&&n.longLayovers.show&&n.longLayovers.airports?(u=!n.longLayovers.hasUnknownLongLayovers&&n.longLayovers.airports?"search-result.details.long-layover-message-":"search-result.details.long-layover-unknown-message-",t=$.i18n.t(u+i,{airports:n.longLayovers.airports})):n.messages.arrival?t=$.i18n.t("search-result.details.arrival-message-"+i,{date:n.lastStation.date}):n.messages.operatedByOne?(f=_.filter(n.segments,function(t){return t.operatingCarrier&&t.operatingCarrier.Id===n.carriersDiff[0].id}),r=f.length,r=Math.min(3,Math.max(1,r)),t=$.i18n.t("search-result.details.operated-by-one-"+r+"-"+i,{carrier:n.carriersDiff[0].name})):n.messages.operatedByCarriers&&(t=$.i18n.t("search-result.details.operated-by-carriers-"+i,{}));_.extend(n,{info:t})});var ut=_.some(l,function(n){return n.info}),rt={price:{amount:w,currency:f},agents:a,uri:s.BookingDetailsLink.Uri,body:s.BookingDetailsLink.Body,method:s.BookingDetailsLink.Method,deepLink:s.PricingOptions[0].DeeplinkUrl,displayCodes:k},d=_.map(s.PricingOptions,function(n){var u=t.Utils.Ui.wrapPrice(Math.ceil(n.Price),f),i=[],r;return _.each(n.Agents,function(n){i.push({id:n.Id,name:n.Name,imageUrl:n.ImageUrl})}),r=_.extend(_.clone(rt),{price:{amount:Math.ceil(n.Price),currency:f},agents:i}),{name:n.Agents[0].Name,price:u,priceData:r,deepLink:n.DeeplinkUrl,quoteAgeInMinutes:n.QuoteAgeInMinutes}}),ft=_.contains(v,s.fingerprint),et=Math.min(d.length,h?3:4),ot=t.Utils.Ui.wrapPrice(w,f),st={index:o,priceWithoutCurrency:w,priceWithCurrency:ot,priceData:rt,agent:g,agents:a,legs:l,topItineraryLabels:b,topPriceOptions:d.slice(1,et),priceOptions:d,baggageDetails:null,cabinclass:_.findWhere(t.Dictionaries.CabinClasses,{value:i.cabinclass}),bookingDetailsLinkBody:s.BookingDetailsLink.Body,isFavorite:ft,fingerprint:s.fingerprint,readInfo:ut,showDetails:_.contains(n.get("detailsOpenedItems"),s.fingerprint)?" details":"",isGroupPrice:h};c.push(st)}),c},isGroupPrice:function(n){return n.adults!==1||n.children||n.infants},getRequestHash:function(n){return t.Utils.Hash.getObjectHash(_.pick(n,"originplace","destinationplace","outbounddate","inbounddate","cabinclass","adults","children","infants"))},_updateImageURL:function(n,t){_.each(n,function(n){var i=n.ImageUrl;i&&(n.ImageUrl=t+i.substring(i.lastIndexOf("/")+1),n.ImageUrl=n.ImageUrl.replace("http://","//"))})}}});App.module("Services",function(n,t){var i=t.Settings.config.carriers,r=i&&!!i.length,u={getFirstSegment:function(n,t){return t[_.first(n.SegmentIds)].OperatingCarrier},getOtherSegments:function(n,t){var i=[],r=_.rest(_.initial(n.SegmentIds));return _.each(r,function(n){var r=t[n].OperatingCarrier;r&&i.push(r)}),i},getLastSegment:function(n,t){return t[_.last(n.SegmentIds)].OperatingCarrier},checkLeg:function(n,t,i){if(!n)return!1;var u=n.Directionality?n.Directionality==="Outbound":!1,r=t.id||-1,f=t.originSegment||!1,e=t.otherSegment||!1,o=t.destinationSegment||!1,s,h=[],c,l,a,v;return!f&&!e&&!o?!1:(f&&(s=u?this.getFirstSegment(n,i):this.getLastSegment(n,i),l=r===s),e&&(h=this.getOtherSegments(n,i),a=_.contains(h,r)),o&&(c=u?this.getLastSegment(n,i):this.getFirstSegment(n,i),v=r===c),_.some([l,a,v]))}};n.OperatingCarriers={isEnabled:r,checkIsItinerarySuite:function(n,t){if(!r)return null;var o=n.outboundLeg,f=n.inboundLeg,e=[];return _.each(i,function(n){var i=u.checkLeg(o,n,t),r=f?u.checkLeg(f,n,t):!0;e.push(i&&r)}),_.some(e)}}});App.module("Services",function(n,t){var i=t.Settings.config.routes,r=i&&!!i.length,u={getOrigin:function(){return t.Flights.SearchForm.getCurrentStateForUrlParams().originplace},getDestination:function(){return t.Flights.SearchForm.getCurrentStateForUrlParams().destinationplace}},f=function(){var t=_.findWhere(i,{code:u.getOrigin()}),n;return t?(n=_.findWhere(t.destinations,{code:u.getDestination()}),!n)?!1:n.suppliers:!1};n.RoutesAndSuppliers={isEnabled:r,isCurrentSearchSuite:function(){return r?!!f():!0},getSelectedAgentsSync:function(){if(!r)return null;var n=f();return!n||!n.length?null:n.join(",")}}});App.module("Services",function(n,t){function c(){o=moment().utc();e=0;h=!1}function l(){e+=1}function a(){f=moment().utc();s=moment.duration(f.diff(o));h=!0;t.tracking.trackEvent("day-view","ResultsReady",s.as("seconds")+"_"+e+"_"+f.format("DD/MM/YY_HH:ss"))}var i=t.VentActions.Flights,r=t.vent,o,f,s,e=0,h=!0,u=!1;n.TimeTracker={start:function(){if(!u){r.on(i.SEARCH_STARTED,c);r.on(i.SEARCH_PROGRESS,l);r.on(i.SEARCH_FINISHED,a);u=!0}},stop:function(){u&&(r.off(i.SEARCH_STARTED,c),r.off(i.SEARCH_PROGRESS,l),r.off(i.SEARCH_FINISHED,a),u=!1)},isTracking:function(){return u},getTimers:function(){return{start:o,end:f,duration:s,polls:e,idle:h}}}});App.module("Models",function(n,t,i){n.BookingDialogModel=i.Model.extend({defaults:function(){return{messageHeader:"",messageContent:"",hasProgress:!1,price:"",priceObsolete:"",agencyName:"",continueLink:"",showClose:!0,multiPart:!1,segments:[],total:"",priceComment:"",isMore:!0}}})});App.module("Flights.Models",function(n){var t=["Economy","PremiumEconomy","Business","First"];n.SearchStateModel=Brace.Model.extend({namedAttributes:{originplace:"string",originplaceText:"string",destinationplace:"string",destinationplaceText:"string",outbounddate:"string",inbounddate:"string",country:"string",currency:"string",locale:"string",locationSchema:"string",adults:"number",children:"number",infants:"number",cabinclass:"string",shared:"boolean",originCityCode:"string",originCountryCode:"string",originCountryName:"string",originplaceCityCode:"string",destinationCityCode:"string",destinationCountryCode:"string",destinationCountryName:"string",itinerary:"string",groupPricing:"boolean",includeAgents:"string",isOutlookAddin:"boolean"},defaults:function(){return{originplace:"",originplaceText:"",destinationplace:"",destinationplaceText:"",outbounddate:"",inbounddate:"",country:"",currency:"",locale:"",locationSchema:"",adults:0,children:0,infants:0,cabinclass:"",groupPricing:!0}},validate:function(){var t=new $.Deferred,i=n.SearchStateModel.validate(this.toJSON());return _.isEmpty(i)?t.resolve(this):t.reject(i),t.promise()}});n.SearchStateModel.validate=function(i){var r={},f;(i.originplace===""||i.destinationplace==="")&&(r[n.SearchStateModel.ValidationErrors.EMPTY_PLACE.key]=$.i18n.t(n.SearchStateModel.ValidationErrors.EMPTY_PLACE.message));i.originplace!==""&&i.originplace===i.destinationplace&&(r[n.SearchStateModel.ValidationErrors.SAME_PLACE.key]=$.i18n.t(n.SearchStateModel.ValidationErrors.SAME_PLACE.message));i.adults=parseInt(i.adults,10)||1;i.children=parseInt(i.children,10)||0;i.infants=parseInt(i.infants,10)||0;i.adults<1&&(i.adults=1);i.adults+i.children>9&&(r[n.SearchStateModel.ValidationErrors.MAX_8_PASSENGERS.key]=$.i18n.t(n.SearchStateModel.ValidationErrors.MAX_8_PASSENGERS.message));i.adults<i.infants&&(i.infants=i.adults,r[n.SearchStateModel.ValidationErrors.TOO_MANY_INFANTS.key]=$.i18n.t(n.SearchStateModel.ValidationErrors.TOO_MANY_INFANTS.message));f=_.some(_.map(t,function(n){return n===i.cabinclass}));f||(i.cabinclass=_.first(t));var u=!1,e=!1,o=App.Utils.Date.today();return(!_.isString(i.outbounddate)||_.isEmpty(i.outbounddate)||!App.Utils.Date.validFormat(i.outbounddate)||i.outbounddate<o)&&(u=!0),_.isEmpty(i.inbounddate)||(!_.isString(i.inbounddate)||!App.Utils.Date.validFormat(i.inbounddate)||i.inbounddate<o||u===!1&&i.inbounddate<i.outbounddate)&&(e=!0),u&&(i.outbounddate=App.Utils.Date.getFriday(),(u||!_.isEmpty(i.inbounddate))&&(i.inbounddate=""),r[n.SearchStateModel.ValidationErrors.INCORRECT_DATES.key]=$.i18n.t(n.SearchStateModel.ValidationErrors.INCORRECT_DATES.message)),e&&(i.inbounddate="",r[n.SearchStateModel.ValidationErrors.INCORRECT_DATES.key]=$.i18n.t(n.SearchStateModel.ValidationErrors.INCORRECT_DATES.message)),r};n.SearchStateModel.ValidationErrors={EMPTY_PLACE:{key:"empty_place",message:"search.errors.select-origin-and-destination",isValidationError:!0,weight:900},SAME_PLACE:{key:"same_place",message:"search.errors.same-places",isValidationError:!0,weight:800},MAX_8_PASSENGERS:{key:"max_8_passengers",message:"search.errors.max-9-passengers",isValidationError:!1,weight:700},TOO_MANY_INFANTS:{key:"too_many_infants",message:"search.errors.number-of-infants-higher-number-of-adults",isValidationError:!1,weight:300},INCORRECT_DATES:{key:"incorrect_dates",message:"search.errors.incorrect-dates",isValidationError:!0,weight:200}}});App.module("Addthis",function(n,t,i,r){var u=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){var t=Math.random()*16|0,i=n=="x"?t:t&3|8;return i.toString(16)})};n.AddthisToolboxView=r.ItemView.extend({template:"#addthis-toolbox-template",className:"addthis_toolbox addthis_20x20_style",ui:{buttonCompact:".addthis_button_compact"},initialize:function(){},hideHover:function(){this.ui.buttonCompact.trigger("mouseout")},onRender:function(){var i="",o;i=t.Utils.Ui.isFlights()?t.Utils.WhiteLabelLocation.getFlightsPageUrl():t.Utils.Ui.isHotels()?t.Utils.WhiteLabelLocation.getHotelsPageUrl():t.Utils.WhiteLabelLocation.getCarHirePageUrl();var s=new t.Utils.Uri(t.Utils.Location.getHref()),e=s.getAnchorParams(),h=this.model.get("allSocial"),r=this.model.get("params"),n=this.model.get("options"),f=this.model.get("shareRouter");e&&(r=_.extend({},e,r));o=this.$el.find("a");o.each(function(){var e=_.extend({},r),o=$(this),l=o.hasClass("js-twitter")||o.hasClass("js-more"),b=o.hasClass("js-facebook"),k=o.hasClass("js-googleplus"),v=o.hasClass("js-calendar"),g=l?"twitter":b?"facebook":k?"googleplus":"",y=t.Dictionaries.SkyscannerSNAccounts[g],a,s,w,c;if(y=y?" @"+y:"",a=t.Settings.config[l?"twitterAccount":b?"facebookAccount":k?"googleAccount":""],a=a?" @"+a:"",_.extend(n,{partner:a,skyscanner:y}),s=h,w=o.data("utm-source"),w&&(e=_.extend({},e,{"utm-source":w})),n.price&&(e=_.extend({},e,{price:n.price})),n.destination&&(e=_.extend({},e,{destinationText:n.destination})),l||v||(e=_.extend({},e,{freshguid:u()})),v&&(n.origin&&(e=_.extend({},e,{originText:n.origin})),n.outboundDate&&(e=_.extend({},e,{outboundDate:n.outboundDate})),n.outboundTime&&(e=_.extend({},e,{outboundTime:n.outboundTime})),n.inboundDate&&(e=_.extend({},e,{inboundDate:n.inboundDate})),n.inboundTime&&(e=_.extend({},e,{inboundTime:n.inboundTime})),n.outboundDuration&&(e=_.extend({},e,{outboundDuration:n.outboundDuration})),n.inboundDuration&&(e=_.extend({},e,{inboundDuration:n.inboundDuration}))),c="",v?c=t.Utils.ShareLocation.getCalendarShareUrl(i,e):f==="itinerary"?c=t.Utils.ShareLocation.getItineraryShareUrl(i,e):f==="result"?c=t.Utils.ShareLocation.getResultShareUrl(i,e):f==="main"&&(c=t.Utils.ShareLocation.getMainShareUrl(i,e)),v){n.origin?(o.attr("href",c),o.show()):o.hide();return}o.attr("addthis:url",c);s.image&&!l&&o.attr("addthis:image",s.image);var p=s.title.needTranslation?$.i18n.t(s.title.key,n):s.title.key,d=s.description.needTranslation?$.i18n.t(s.description.key,n):s.description.key,nt=s.message.needTranslation?$.i18n.t(s.message.key,n):s.message.key;p=l&&s.message?nt:p;p&&o.attr("addthis:title",p);d&&o.attr("addthis:description",d)});this.$el.i18n()}})});App.module("Sharing",function(n,t,i,r){n.MainSharingView=r.ItemView.extend({template:"#main-sharing-template",className:"home-sharing-box",ui:{sharingToolbox:".js-sharing-toolbox",loading:".js-share-spinner"},events:{"click .js-share-button":"onToggleShareBox",blockShareButtons:"onBlockShareButtons",resetShareButtons:"onResetShareButtons"},hideHover:function(){this.addthisToolboxView&&this.addthisToolboxView.hideHover()},onBlockShareButtons:function(){this.ui.sharingToolbox.css("opacity","0.5")},onResetShareButtons:function(n){this.options=n;this.ui.sharingToolbox.css("opacity","1")},onToggleShareBox:function(n){parseInt(this.ui.sharingToolbox.css("opacity"),10)!==1||this.$el.hasClass("waiting")||this.$el.hasClass("active")||(n.stopPropagation(),n.preventDefault(),t.tracking.trackEvent("home","Share_Page"),t.GlobalEvents.trigger("global:click",{target:$(t.Utils.Ui.bodySelector)}),this.renderAll(this.options))},onGlobalClick:function(){this.ui.sharingToolbox.animate({opacity:0},{duration:300,complete:_.bind(function(){this.$el.removeClass("active");this.ui.sharingToolbox.css("opacity",1)},this)})},onDestroy:function(){this.addthisToolboxView&&this.addthisToolboxView.destroy()},renderAll:function(n){if(t.Mode!=="TEST"){this.addthisToolboxView&&this.addthisToolboxView.destroy();var r=t.Router.isResultsPage(),u=r?"search-result":"home-page",o="",s="",f="",e={};if(r)if(n)o=n.destinationPlace?n.destinationPlace.Name:"",s=t.Utils.Ui.wrapPrice(n.price?n.price:"-",n.currency),n.destinationCityCode&&_.extend(e,{destinationCityCode:n.destinationCityCode});else return;else t.ImageBanner.isStarted()&&(f=t.ImageBanner.getCurrentCityCode()),_.extend(e,{destinationCityCode:f});this.addthisToolboxView=new t.Addthis.AddthisToolboxView({model:new i.Model({allSocial:{title:{key:r?"sharing."+u+".title":$("<div/>").html(t.Settings.config.title).text(),needTranslation:r},description:{key:"sharing."+u+".description",needTranslation:!0},message:{key:"sharing."+u+".message-twitter",needTranslation:!0}},options:{sitename:t.Settings.config.name,destination:o,destinationCityCode:f,price:s},shareRouter:r?"result":"main",params:_.extend(e,{utm_campaign:r?"search_results_share":"homepage_share"})})});this.ui.sharingToolbox.html(this.addthisToolboxView.render().$el);t.Utils.AddThis.isReady()||t.Utils.Spin(this.ui.loading);this.$el.addClass("waiting");t.Utils.AddThis.onAddThisReady(_.bind(function(n){if(this.$el.removeClass("waiting"),this.ui.loading.empty(),n){this.$el.addClass("active");window.addthis.toolbox(this.ui.sharingToolbox.get(0));t.GlobalEvents.once("global:click",_.bind(this.onGlobalClick,this))}},this))}}})});App.module("Paginator",function(n,t,i,r){n.PaginatorView=r.ItemView.extend({model:i.Model,template:"#paginator-template",events:{"click .js-number":"onNumberClick","click .js-decrease":"onDecreaseClick","click .js-increase":"onIncreaseClick"},modelEvents:{"change:page":"onPageChanged","change:itemsCount":"onItemsCountChanged"},onBeforeRender:function(n){var t=Math.max(1,Math.ceil((0+n.model.get("itemsCount"))/n.model.get("paginateBy"))),i=[],r=[],u=1,f,e;t>1&&(f=Math.max(n.model.get("aroundCount"),1),u=Math.max(1,Math.min(t,n.model.get("page"))),r[0]=this.getNumbers(1,2),r[1]=this.getNumbers(Math.max(1,u-f),Math.min(u+f,f*2+1)),r[2]=this.getNumbers(t-1,2),e=_.filter(_.unique(_.flatten(r)),function(n){return n<=t&&n>0}),_.each(e,function(n,t){i[i.length]=n;e[t+1]-n==2&&(i[i.length]=n+1)}));_.extend(n.model.attributes,{range:i,maxpage:t,page:u})},onRender:function(){this.$el.i18n()},hidePagination:function(){this.$el.hide()},showPagination:function(){this.$el.show()},onItemsCountChanged:function(){var n=this.model.get("page")?this.model.get("page"):1;this.model.set("page",n);this.model.hasChanged("page")||this.render()},onPageChanged:function(){this.render()},onNumberClick:function(n){var t=$(n.target).text();return(n.preventDefault(),t==this.model.get("page"))?!1:(this.triggerEvent(t,!0),!1)},onDecreaseClick:function(n){return(n&&n.preventDefault(),1===this.model.get("page"))?!1:(this.triggerEvent(Math.max(1,this.model.get("page")-1),!0),!1)},onIncreaseClick:function(n){return(n&&n.preventDefault(),this.model.get("maxpage")===this.model.get("page"))?!1:(this.triggerEvent(Math.min(this.model.get("maxpage"),this.model.get("page")+1),!0),!1)},triggerEvent:function(n){t.Utils.Ui.trigger("inactive-veil:enable","SearchResultListView");t.vent.trigger(t.VentActions.Pagination.SET_PAGE,n,!0)},getNumbers:function(n,t){var i=[];if(!n||!t)return i;while(t--)i[t]=n+t;return i}})});App.module("Dialog",function(n,t,i,r){n.PopupDialogButtonView=r.ItemView.extend({tagName:function(){return{button:"button",link:"a"}[this.model.get("type")]},events:{click:"onClick"},template:_.template("<%- text %>"),onClick:function(){this.trigger("make:action")},initialize:function(){},onRender:function(){this.model.get("action")==="close"&&this.$el.addClass(this.model.get("type")==="link"?"js-dialog-link":"js-dialog-close");this.model.get("type")==="link"&&(this.$el.attr("href",this.model.get("href")),this.$el.attr("target",this.model.get("target")),this.$el.addClass("button"));var n=this.model.get("color");n=n?n:"cyan";this.$el.addClass("btn-"+n)}});n.PopupDialogView=r.CompositeView.extend({template:"#popup-dialog-template",bodyModalLockClassName:"modal-lock",childViewContainer:".js-buttons-box",ui:{details:".js-details"},triggers:{"click .js-dialog-close":"close"},events:{"click .js-popup-frame":"onOutsideClick"},childView:n.PopupDialogButtonView,childEvents:{"make:action":"onChildAction"},onOutsideClick:function(n){$(n.target).hasClass("js-popup-frame")&&this.onClose()},onChildAction:function(n){n.model.get("action")==="close"&&this.onClose()},initialize:function(n){this.model.set("buttonsCount",n.collection.models.length);var t=n.model.get("details");n.model.set("showDetails",Boolean(t))},onRender:function(){var n=$("html"),t;n.on("keyup.popupDialog",_.bind(this.onKeyup,this));n.addClass(this.bodyModalLockClassName);n.on("scroll.popupDialog",function(n){return n.preventDefault(),!1});t=this.model.get("details");t&&this.ui.details.html(t);this._focusedElement=$(document.activeElement);this.$el.find(":input").first().focus()},onKeyup:function(n){_.contains(["27"],n.keyCode.toString())&&this.onClose()},onClose:function(){this.$el.hide();var n=$("html");n.removeClass(this.bodyModalLockClassName);n.off("scroll.popupDialog");n.off("keyup.popupDialog");this._focusedElement&&this._focusedElement.focus();setTimeout(_.bind(function(){this.destroy()},this),1)}})});App.module("Home",function(n,t){n.onImageBannerClick=function(n){if(t.ImageBanner.isStarted()){var r=n.getOrigin(),i=n.getDestination();t.Flights.SearchForm.trigger("change:originPlace",{PlaceId:r.getId(),PlaceName:r.getName()});t.Flights.SearchForm.trigger("change:destinationPlace",{PlaceId:i.getId(),PlaceName:i.getName(),CountryCode:i.getCountryId(),CountryName:i.getCountryName()});t.Flights.SearchForm.trigger("change:cabinclass","Economy");t.Flights.SearchForm.trigger("change:date",r.getDepartureDate(),i.getDepartureDate());t.Flights.SearchForm.search()}};n.HomeController=Backbone.Marionette.Controller.extend({home:function(){if(_.isUndefined(t.contentArea.currentView)||t.contentArea.currentView.destroy(),t.Router.CurrentRoute="Home",!t.Router.is404())return new n.HomeLayoutView}});n.HomeLayoutView=Backbone.Marionette.LayoutView.extend({template:"#home-layout-template",regions:{inspiration:".js-home-inspiration-panel"},views:{},onBeforeDestroy:function(){t.InspirationalPlaces.off("ready");t.InspirationalPlaces.stop()},onRender:function(){this.inspiration.show(this.views.inspirationalView)},_bindEvents:function(){t.InspirationalPlaces.on("ready",_.bind(function(n){this.views.inspirationalView=n;this._triggerReady()},this))},_triggerReady:function(){t.trigger("module.ready",{name:"Home",view:this})},initialize:function(){t.tracking.trackPageView("/homeview/"+t.Settings.config.locale+"/flights/");this._bindEvents();t.InspirationalPlaces.start();t.Flights.SearchForm.trigger("hide:shortLabel");t.ImageBanner.isStarted()?t.ImageBanner.restartModule():t.ImageBanner.start();t.ImageBanner.off("select").on("select",n.onImageBannerClick)}});n.on("start",function(){t.Router.processAppRoutes(new n.HomeController,{"":"home",".:whatever":"home"})})});App.module("Flights.SearchState",function(n,t){var i=function(n,i,r,u,f){var e,o;f=f||function(n){return n};e=n[r];e&&(u&&(o=f(e),i[u].setAsync(o)),t.officeData[r]=e)},r=function(n){var i=n.id,r=n.text,u=new $.Deferred,f={PlaceId:"",PlaceName:"",CityId:"",CountryId:"",CountryName:""},e;return i&&i.split("-")[0].length>4&&(r=i,i=null),e=i?t.Services.PlacesApi.getPlaceById(i):r?t.Services.PlacesApi.getAutoSuggestPlaces(r).then(function(n){return n.Places.length===0?(new $.Deferred).reject(new Error("no suggestion found for "+r)):n.Places[0]}):u.resolve(f),e.done(function(n){u.resolve({PlaceId:n.PlaceId,PlaceName:n.PlaceName,CityId:t.Utils.Location.getPlainPlaceId(n.CityId),CountryId:t.Utils.Location.getPlainPlaceId(n.CountryId),CountryName:n.CountryName?n.CountryName:""})}).fail(function(){u.resolve(f)}),u.promise()};n.Provider={settings:function(){var n=new $.Deferred;return $.when(t.Services.HomeCity.getHomeCity(),t.Services.Market.getMarket(),t.Services.Currency.getCurrency(),t.Services.Language.getLanguage()).done(function(i,r,u,f){var e;return e=t.Settings.config.originplace?{PlaceId:t.Settings.config.originplace,PlaceName:""}:{PlaceId:i.PlaceId,PlaceName:i.PlaceName},n.resolve({originplaceText:e.PlaceName||"",originplace:e.PlaceId||"",destinationplaceText:"",destinationplace:t.Settings.config.destinationplace||"",outbounddate:t.Utils.Date.getFriday(),inbounddate:"",country:r,currency:u,locale:f,locationSchema:t.Dictionaries.LocationSchema,adults:1,children:0,infants:0,cabinclass:"Economy"})}).fail(function(){n.reject()}),n.promise()},sync:function(){return t.WLSync.provideFlightsSyncState()},url:function(){var r=new $.Deferred,u=new t.Utils.Uri(t.Utils.Location.getHref()),n=u.getAnchorParams(),i=n.location_schema;return n=_.pick(n,"outbounddate","inbounddate","originplace","destinationplace","cabinclass","adults","children","infants","itinerary","shared"),_.isEmpty(n)||_.has(n,"inbounddate")||(n.inbounddate=""),n.adults&&(n.adults=parseInt(n.adults,10)),n.children&&(n.children=parseInt(n.children,10)),n.infants&&(n.infants=parseInt(n.infants,10)),n.shared&&(n.shared=n.shared==="true"||n.shared===!0),i&&n.originplace.indexOf("-")===-1&&(n.originplace+="-"+i),i&&n.destinationplace.indexOf("-")===-1&&(n.destinationplace+="-"+i),r.resolve(n)},outlookAddin:function(){var i=new $.Deferred,n;return n=t.officeData?t.officeData:{},n.isOutlookAddin=!!t.officeData,i.resolve(n)},place:function(n){var u=new $.Deferred,f,i;return t.Utils.RoutesFilter.isAvailiableOrigin(n.originplace)||(n.originplace=""),t.Utils.RoutesFilter.isAvailiableDestination(n.originplace,n.destinationplace)||(n.destinationplace=""),f={id:n.originplace},i={},i[n.isOutlookAddin?"text":"id"]=n.isOutlookAddin?n.destinationplaceText:n.destinationplace,delete n.isOutlookAddin,$.when(r(f),r(i)).done(_.bind(function(i,r){n.originplace=t.Utils.Location.getPlainPlaceId(i.PlaceId);n.originplaceText=i.PlaceName;n.originplaceCityCode=i.CityId;n.originCountryCode=i.CountryId;n.originCountryName=i.CountryName;n.destinationplace=t.Utils.Location.getPlainPlaceId(r.PlaceId);n.destinationCityCode=r.CityId;n.destinationplaceText=r.PlaceName;n.destinationCountryCode=r.CountryId;n.destinationCountryName=r.CountryName;u.resolve(n)},this)),u.promise()}};n.Resolver={localstorage:function(n){var i=n.originplace!==n.destinationplace;n.destinationplace=i?n.destinationplace:"";n.destinationplaceText=i?n.destinationplaceText:"";t.Utils.StateStorage.Flights.set(n)},outlookAddin:function(n){if(window.Office){var t=Office.context.mailbox.item;i(n,t,"destinationplace");i(n,t,"destinationplaceText","location");i(n,t,"outbounddate","start",function(n){return new Date(n)});i(n,t,"inbounddate","end",function(n){return new Date(n)})}}};n.provide=function(){var i=new $.Deferred;return $.when(n.Provider.settings(),t.Flights.SearchState.Base.Provider.localstorage(),n.Provider.sync(),n.Provider.url(),n.Provider.outlookAddin()).done(function(n,r,u,f,e){var o=_.extend({},n,r,u,f,e),s=t.Flights.Models.SearchStateModel.validate(o),h=t.Settings.config.originplace,l=t.Settings.config.destinationplace,c=t.Services.Feature.check("lockAirport","on")||t.Settings.config.lockAirport;c&&h&&o.destinationplace!==h&&(o.originplace=h,o.originplaceText="");i.notify(o,s);t.Flights.SearchState.Provider.place(o).done(function(n){s=t.Flights.Models.SearchStateModel.validate(n);_.isEmpty(u)&&_.isEmpty(f)?(delete s[t.Flights.Models.SearchStateModel.ValidationErrors.INCORRECT_DATES.key],delete s[t.Flights.Models.SearchStateModel.ValidationErrors.EMPTY_PLACE.key],delete s[t.Flights.Models.SearchStateModel.ValidationErrors.SAME_PLACE.key]):_.isEmpty(u)||(t.Flights.SearchState.Resolver.localstorage(u),t.Flights.SearchState.Resolver.outlookAddin(u));i.resolve(n,s)})}).fail(function(){i.reject("Cannot resolve search state")}),i.promise()}});App.module("Flights.SearchForm",function(n,t){n.CabinClassDropdownView=t.Views.DropdownView.extend({headerView:t.Views.DefaultDropdownHeaderView.extend({template:"#cabinclass-dropdown-header-template"}),childView:t.Views.DefaultDropdownItemView.extend({template:"#cabinclass-dropdown-list-item-template"}),behaviors:{DropdownKeysControl:{}}})});App.module("Flights.SearchForm",function(n,t,i,r){n.DateFormView=r.View.extend({_bindEvents:function(){this.departView.on("set",_.bind(function(n,i){var r=this.returnView.getValue(),u=this.returnView.getSelectObject();r!==""&&n!==""&&i.pick>u.pick?(r=n,this.returnView.setValue(i),this.model.set({outbounddate:n,inbounddate:r})):this.model.set({outbounddate:n});r===""&&this.returnView.setHighlightedDate(t.Utils.Date.addDay(n));this.trigger("change",this.model.attributes)},this));this.returnView.on("set",_.bind(function(n,i){this.model.get("inbounddate")===""&&t.tracking.trackEvent("home","TripType","Return");var r=this.departView.getValue(),u=this.departView.getSelectObject();r!==""&&n!==""&&u.pick>i.pick?(r=n,this.departView.setValue(i),this.model.set({outbounddate:r,inbounddate:n})):this.model.set({inbounddate:n});n===""&&this.returnView.setHighlightedDate(t.Utils.Date.addDay(r));this.trigger("change",this.model.attributes)},this));this.model.get("outbounddate")&&this.departView.setValue(this.model.get("outbounddate"));this.model.get("inbounddate")&&this.returnView.setValue(this.model.get("inbounddate"))},_initializeViews:function(){var n=this;this.departView=new t.Views.DatePickerView({el:".js-search-date-depart",pickadateContainer:function(){return t.Utils.Ui.isMobileView()&&!t.Utils.Ui.isWidget()?".js-datedepart-dialog":".js-search-date-depart"},type:"depart",getPointOfReference:function(){return t.Utils.Date.today()}});this.departView.model.on("change:buttonTitle",function(t){n.trigger("setButtonTitle",t.get("buttonTitle"))});this.departView.on("block:form",this.onBlockForm,this);this.departView.on("unblock:form",this.onUnblockForm,this);this.returnView=new t.Views.DatePickerView({el:".js-search-date-return",pickadateContainer:function(){return t.Utils.Ui.isMobileView()&&!t.Utils.Ui.isWidget()?".js-datereturn-dialog":".js-search-date-return"},type:"return",getPointOfReference:_.bind(function(){return this.departView.getValue()||t.Utils.Date.today()},this)});this.returnView.model.on("change:buttonTitle",function(t){n.trigger("setButtonTitle",t.get("buttonTitle"))});this.returnView.on("block:form",this.onBlockForm,this);this.returnView.on("unblock:form",this.onUnblockForm,this)},onBlockForm:function(){this.trigger("block:form")},onUnblockForm:function(){this.trigger("unblock:form")},close:function(){this.departView.picker.close(!1);this.returnView.picker.close(!1)},initialize:function(n){this.model=new i.Model;this.model.set("inbounddate",n.inbounddate);this.model.set("outbounddate",n.outbounddate);this._initializeViews();this._bindEvents()}})});App.module("Flights.SearchForm",function(n,t){n.PaxDropdownView=t.Views.DropdownView.extend({headerView:t.Views.DefaultDropdownHeaderView.extend({template:"#pax-dropdown-header-template"}),childView:t.Views.DefaultDropdownItemView.extend({template:"#pax-dropdown-list-item-template"}),behaviors:{DropdownKeysControl:{}}})});App.module("Flights.SearchForm",function(n,t,i){n.PeopleSelectorView=i.Marionette.View.extend({views:{adultsView:null,childrenView:null,infantsView:null},ui:{adultsViewContainer:".js-people-selector__adults",childrenViewContainer:".js-people-selector__children",infantsViewContainer:".js-people-selector__infants"},_initializeAdultsView:function(){var r=new i.Collection(_.without(t.Dictionaries.PaxCount,_.findWhere(t.Dictionaries.PaxCount,{value:0}))),u=r.find(_.bind(function(n){return n.get("value")===this.model.get("adults")},this))||r.first();u.set("icon","ss-icon-adult");this.views.adultsView=new n.PaxDropdownView({model:u,collection:r,tabindex:1,ariaLabel:$.t("aria.search.pax-adults")});this.ui.adultsViewContainer.html(this.views.adultsView.render().$el);this.model.on("change:adults",_.bind(function(n){n.get("adults")!==this.views.adultsView.model.get("value")&&(t.tracking.trackEvent("home","PaxChoice","Adult_"+n.get("adults")),this.views.adultsView.select(r.find(function(t){return t.get("value")===n.get("adults")})))},this));this.views.adultsView.on("change",_.bind(function(n){this.model.set("adults",n.value)},this))},_initializeChildrenView:function(){var r=new i.Collection(t.Dictionaries.PaxCount),u=r.find(_.bind(function(n){return n.get("value")===this.model.get("children")},this))||r.first();u.set("icon","ss-icon-child");this.views.childrenView=new n.PaxDropdownView({model:u,collection:r,tabindex:1,ariaLabel:$.t("aria.search.pax-children")});this.ui.childrenViewContainer.html(this.views.childrenView.render().$el);this.model.on("change:children",_.bind(function(n){n.get("children")!==this.views.childrenView.model.get("value")&&(t.tracking.trackEvent("home","PaxChoice","Child_"+n.get("children")),this.views.childrenView.select(r.find(function(t){return t.get("value")===n.get("children")})))},this));this.views.childrenView.on("change",_.bind(function(n){this.model.set("children",n.value)},this))},_initializeInfantsView:function(){var r=new i.Collection(t.Dictionaries.PaxCount),u=r.find(_.bind(function(n){return n.get("value")===this.model.get("infants")},this))||r.first();u.set("icon","ss-icon-infant");this.views.infantsView=new n.PaxDropdownView({model:u,collection:r,tabindex:1,ariaLabel:$.t("aria.search.pax-infants")});this.ui.infantsViewContainer.html(this.views.infantsView.render().$el);this.model.on("change:infants",_.bind(function(n){n.get("infants")!==this.views.infantsView.model.get("value")&&(t.tracking.trackEvent("home","PaxChoice","Infant_"+n.get("infants")),this.views.infantsView.select(r.find(function(t){return t.get("value")===n.get("infants")})))},this));this.views.infantsView.on("change",_.bind(function(n){this.model.set("infants",n.value)},this))},initialize:function(n){this.setElement(n.el);this.bindUIElements();this.model=new i.Model({adults:1,children:0,infants:0});this.model.set(n.provider());this._initializeAdultsView();this._initializeChildrenView();this._initializeInfantsView();this.model.on("change",function(t){n.resolver(t.attributes)});this.on("update",_.bind(function(){this.model.set(n.provider())},this))}})});App.module("Flights.SearchForm",function(n,t,i,r){var u=function(n){return n?n.replace("-"+t.Dictionaries.LocationSchema,""):n},f=function(n){return n?(n=t.Utils.Location.getPlainPlaceId(n),n.length>3?$.i18n.t("search.place.any-airport"):n):n};n.PlaceModel=i.Model.extend({defaults:function(){return{PlaceName:"",PlaceId:"",CityId:"",CountryId:"",CountryName:"",ShowPlaceId:"",Active:!1,HasParent:!1}},initialize:function(){this.set("PlaceId",u(this.get("PlaceId")));this.set("CityId",u(this.get("CityId")));this.set("CountryId",u(this.get("CountryId")));this.set("ShowPlaceId",f(this.get("PlaceId")))}});n.PlacesCollection=i.Collection.extend({model:n.PlaceModel});n.PlaceItemView=r.ItemView.extend({tagName:"li",className:"dropdown-item",template:"#autocomplete-place-item-template",events:{mousedown:function(n){return n.stopImmediatePropagation(),this._select(n),!1},click:function(n){return n.stopImmediatePropagation(),this._select(n),!1}},modelEvents:{select:"_select","change:Active":"_onActiveChange"},_onActiveChange:function(){this.model.get("Active")===!0?this.$el.addClass("active"):this.$el.removeClass("active")},_select:function(){this.trigger("item:select",{PlaceName:this.model.get("PlaceName"),PlaceId:this.model.get("PlaceId"),CityId:this.model.get("CityId"),CountryId:this.model.get("CountryId"),CountryName:this.model.get("CountryName"),ShowPlaceId:this.model.get("ShowPlaceId")})},onRender:function(){this.model.get("HasParent")===!0&&this.$el.addClass("indent")},initialize:function(){}});n.PlaceListView=r.CompositeView.extend({template:"#autocomplete-place-template",childView:n.PlaceItemView,childViewContainer:"ul",ui:{input:"input",placeId:".js-placeid",list:".js-dropdown-items",loading:".js-loading",notFound:".js-not-found",cover:".js-autocomplete-place-cover"},behaviors:{ViewUnwrap:{},PlaceSelectorTracking:{}},events:{"input @ui.input":"onInput","textchange @ui.input":"onInput","blur @ui.input":"onInputBlur","focus @ui.input":"onInputFocus","keydown @ui.input":"onInputKeydown","keyup @ui.input":"onInputKeyup","mousedown @ui.notFound":"onNotFoundClick","click @ui.cover":"onCoverClick","mousedown @ui.cover":"onCoverMousedown","focus @ui.cover":"onCoverMousedown","mouseup @ui.input":function(n){n.preventDefault();this._globalClickPropagation(n)},click:function(n){this.ui.input.focus();this._globalClickPropagation(n)}},onFocusOut:function(){setTimeout(_.bind(function(){this.ui.input.blur()},this),500)},_globalClickPropagation:function(n){t.GlobalEvents.trigger("global:click",n)},childEvents:{"item:select":"onItemSelect"},getValue:function(){return{PlaceName:this.model.get("PlaceName"),PlaceId:this.model.get("PlaceId"),CityId:this.model.get("CityId")}},setValue:function(n){this.select(u(n.PlaceId),n.PlaceName,f(n.PlaceId),u(n.CityId),"","")},showPlaces:function(n){var t=_.pluck(_.filter(n,function(n){return n.CityId===n.PlaceId}),"PlaceId");_.each(n,function(n){n.HasParent=_.contains(t,n.CityId)&&n.CityId!==n.PlaceId});this.collection.reset(n);this.moveCursor(1);this.toggleLoading(!1);this.ui.list.addClass("active")},hideDropdown:function(n){this.trigger("hide:dropdown");var i=t.Utils.Ui.isMobileView()?t.Utils.Ui.isFirefox()?500:300:1;setTimeout(_.bind(function(){this.collection.reset();n||this.ui.notFound.hide();this.toggleLoading(!1);this.ui.list.removeClass("active")},this),i)},onCoverMousedown:function(n){(n.preventDefault(),n.stopImmediatePropagation(),this._globalClickPropagation(n),this._disabled)||(this.$el.addClass("active"),this.ui.input.trigger("focus"))},onCoverClick:function(n){(n.preventDefault(),n.stopImmediatePropagation(),this._globalClickPropagation(n),this._disabled)||(this.$el.addClass("active"),this.ui.input.trigger("focus"))},onNotFoundClick:function(){return this.ui.input.val("").focus(),this.hideDropdown(),this.ui.notFound.hide(),!1},onItemSelect:function(n,t){return this.select(t.PlaceId,t.PlaceName,t.ShowPlaceId,t.CityId,t.CountryId,t.CountryName),!0},select:function(n,t,i,r,u,f){var e,o,s;return this.blurTimeout&&(clearTimeout(this.blurTimeout),delete this.blurTimeout),this.model.get("PlaceId")!==n&&this.model.get("PlaceId")!==""&&(e=this.ui.input.val(),o=this.collection.indexOf(_.find(this.collection.models,function(t){return t.get("PlaceId")===n})),this.triggerMethod("TrackChange",{placeValue:e,placeId:n,itemIndex:o})),this.model.set({PlaceName:t,PlaceId:n,CityId:r,CountryId:u,CountryName:f}),s=t?t+" <span class='place-selector__cover-id'>("+i+")<span>":this.options.placeholder,this.ui.cover.html(s).addClass("populated"),this.ui.input.val(t),this.ui.input.data("prev",t),this.trackEvent=!1,this.hideDropdown(),!0},onInputBlur:function(){this.trigger("blur:input");var n=t.Utils.Ui.isMobileView()?t.Utils.Ui.isFirefox()?600:400:this._asDropdown?300:100;this.blurTimeout=setTimeout(_.bind(function(){if(this._scrolling){this._scrolling=!1;this.ui.input.focus();return}if(this.$el.removeClass("active"),this.hasBeenChanged){if(this.ui.input.val()==="")this.setDefault();else{var n=this.getSelectedModel();n?this.select(n.get("PlaceId"),n.get("PlaceName"),n.get("ShowPlaceId"),n.get("CityId"),n.get("CountryId"),n.get("CountryName")):(this.trackEvent&&(this.triggerMethod("TrackChange",{placeValue:this.ui.input.val()}),this.trackEvent=!1),this.setDefault())}this.hasBeenChanged=!1}this.$el.parent().removeClass("active")},this),n)},setDefault:function(){this.ui.input.val(this.model.get("PlaceName"));this.hideDropdown()},clear:function(){this.model.set({PlaceId:"",PlaceName:"",CityId:""});this.ui.input.val("");this.ui.cover.html(this.options.placeholder).removeClass("populated");this.hideDropdown()},onEnter:function(){var n=this.getSelectedModel();return n?(n.trigger("select"),n.set("Active",!1)):this.setDefault(),this.hideDropdown(),!0},getSelectedModel:function(){if(this.collection.length>0){var n=_.find(this.collection.models,function(n){return n.get("Active")===!0});return n?n:null}return null},moveCursor:function(n){var r,i,t;return this.collection.length>0&&(r=this.getSelectedModel(),i=null,r?(r.set("Active",!1),t=this.collection.indexOf(r),t=t===0&&n<0?this.collection.length-1:t===this.collection.length-1&&n===1?0:t+n,i=this.collection.at(t),i.set("Active",!0)):(i=this.collection.models[0],i.set("Active",!0))),!1},onInputKeydown:function(n){if(_.contains(["13","27","38","40"],n.keyCode.toString())){n.preventDefault();n.stopPropagation();switch(n.keyCode){case 13:return this.onEnter();case 27:return this.setDefault();case 38:return this.moveCursor(-1);case 40:return this.moveCursor(1)}}return n.keyCode===8&&(this.hasBeenChanged=!0),n.keyCode===9&&(this.hasBeenChanged=!0),this.ui.input.data("prev",this.ui.input.val()),!0},onChangeSelection:function(){this.$el.addClass("active");this.$el.parent().addClass("active");setTimeout(_.bind(function(){this.ui.input.select()},this),200)},onInputFocus:function(){if(!this._disabled){this.trigger("focus:input");this.$el.addClass("active");this.ui.input.get(0).setSelectionRange?this.ui.input.get(0).setSelectionRange(0,9999):this.ui.input.select();this.selectedInput=!0;this.ui.loading.hasClass("js-spin-activated")===!1&&(this.spinner=t.Utils.Spin(this.ui.loading),this.ui.loading.addClass("js-spin-activated"));this.$el.parent().addClass("active");var n=this.trimQuery(this.ui.input.val());!n.length&&this.model.get("locationsAsDropdown")&&this.onInput()}},onInputKeyup:function(n){if(!_.contains(["13","27","38","40"],n.keyCode.toString())&&(this.ui.input.data("prev",this.ui.input.val()),(t.Utils.Ui.isWidget()&&t.Utils.Ui.isIE8()||this.model.get("locationsAsDropdown")&&(t.Utils.Ui.isIE9()||t.Utils.Ui.isIE8()))&&this.onInput(),window.ltIE9))this.onInput(!0)},trimQuery:function(n){var t=n.replace(/^[\s\uFEFF\xA0]+/g,"");return t.replace(/[\s\uFEFF\xA0]+$/g," ")},onInput:function(){if(this.trigger("change:input"),this.timer&&clearTimeout(this.timer),this.ui.input.data("dropdown-open")!==1){this.selectedInput&&(t.Utils.Ui.isMobileView()||t.Utils.Ui.isTabletView())&&(this.ui.input.val(this.ui.input.val().charAt(0)),this.selectedInput=!1);this.trackEvent=!0;this.hasBeenChanged=!0;var n=this.trimQuery(this.ui.input.val());return n.length<2&&!this.model.get("locationsAsDropdown")?(this.hideDropdown(),!1):(this.toggleLoading(!0),this.timer&&clearTimeout(this.timer),this.timer=setTimeout(_.bind(function(){var i=++this.lastRequestId;this.model.get("locationsAsDropdown")&&!n.length?t.Services.PlacesApi.getPlacesByIds(this.getPredefinedAvailablePlaces()).done(_.bind(function(n){if(i===this.lastRequestId){this._asDropdown=!0;this.onGetPlaces(n)}},this)):t.Services.PlacesApi.getAutoSuggestPlaces(n).done(_.bind(function(t){var f,r,e;if(i===this.lastRequestId&&(this._asDropdown=!1,f=this.trimQuery(this.ui.input.val()),f.trim()===n.trim())){if(r=this.getPredefinedAvailablePlaces(),r){e=_.filter(t.Places,function(n){return _.contains(r,u(n.PlaceId))});this.onGetPlaces({Places:e});return}this.onGetPlaces(t)}},this))},this),100),!1)}},onGetPlaces:function(n){n.Places.length>0?(this.ui.notFound.hide(),this.showPlaces(n.Places)):(this.hideDropdown(!0),this.ui.notFound.show())},getPredefinedAvailablePlaces:function(){if(t.Utils.RoutesFilter.hasPredefinedRoutes()){if(this.options.type==="origin")return t.Utils.RoutesFilter.getOrigins();if(this.options.type==="destination"){var n=this.options.originplaceView&&this.options.originplaceView.getValue().PlaceId;return t.Utils.RoutesFilter.getDestinations(u(n))}}return null},toggleLoading:function(n){n?this.ui.loading.show():this.ui.loading.hide()},disable:function(){this._disabled=!0;this.$el.addClass("locked");this.$el.removeClass("active");this.ui.cover.removeAttr("tabindex")},enable:function(){this._disabled=!1;this.$el.removeClass("locked");this.ui.cover.attr("tabindex","1")},onRender:function(){if(this.ui.input.data("dropdown-open",1),this.$el.i18n(),setTimeout(_.bind(function(){this.ui.input.data("dropdown-open",0)},this),10),this.model.get("PlaceId")!==""&&this.select(this.model.get("PlaceId"),this.model.get("PlaceName"),f(this.model.get("PlaceId")),this.model.get("CityId"),this.model.get("CountryId"),this.model.get("CountryName")),!t.Utils.Ui.isMobileView())this.ui.list.on("scroll",_.bind(function(){this._scrolling=!0;setTimeout(_.bind(function(){this._scrolling=!1},this),500)},this))},onGlobalClick:function(n){if(n&&n.target){var i=$(n.target);i.parents(".js-place-selector").length||(this.hasBeenChanged=!0,!t.Utils.Ui.isFirefox()&&t.Utils.Ui.isMobileView()&&this.onInputBlur())}return!1},initialize:function(){this.model=new i.Model({PlaceName:"",PlaceId:"",CityId:"",CountryId:"",CountryName:"",locationsAsDropdown:t.Utils.RoutesFilter.locationsAsDropdown()});this.collection=new n.PlacesCollection;this.hasBeenChanged=!1;this.lastRequestId=0;this.options.placeholder=this.options.placeholder||$.i18n.t("search.place.placeholder");this.templateHelpers=this.templateHelpers||{};this.templateHelpers.placeholder=this.options.placeholder;t.GlobalEvents.on("global:click",this.onGlobalClick,this)}})});App.module("Flights.SearchForm",function(n,t,i){var r=Brace.Model.extend({namedAttributes:{errors:"object"}});n.SearchFormErrorView=i.Marionette.ItemView.extend({template:"#search-form-error-template",ui:{message:".js-search-form-error-message"},events:{click:function(){return this.hide(),!1}},behaviors:{ViewUnwrap:{}},hide:function(){this.$el.hide()},show:function(){this.$el.show()},initialize:function(n){this.model=new r({errors:n.errors});this.model.on("change:errors",this.render,this)}})});App.module("Flights.SearchForm",function(n,t,i,r){n.SearchFormView=r.ItemView.extend({model:t.Flights.Models.SearchStateModel,template:"#search-form-template",templateHelpers:{isLongTitles:function(){return t.Utils.Ui.isWidget()&&(t.Culture.culture.name==="tl-PH"||t.Culture.culture.name==="ru-RU")||t.Culture.locale==="tl-PH"||t.Culture.locale==="ru-RU"},showSwap:function(){return!t.Utils.RoutesFilter.hasPredefinedRoutes()}},ui:{peopleSelector:".js-people-selector",cabinClassSelector:".js-cabin-class-selector",originPlaceSelector:".js-originplace",destinationPlaceSelector:".js-destinationplace",whiteLabelSelector:".js-white-label-selector",error:".js-search-form-error",infoPanel:".js-search-info",shortLabel:".js-short-label",search:"#search",switchPlaces:".js-switch-places",searchButton:".js-search-button",poweredBy:".js-powered-by-container"},events:{"click .js-switch-places":"swapPlaces","click @ui.searchButton":"onSearchButtonClick","keydown @ui.searchButton":"onSearchButtonKeyDown","click .js-search-overlay":"onOverlayClick"},modelEvents:{change:"_updateSearchLink"},behaviors:{ViewUnwrap:{}},_initializePlacesSelector:function(){this.listenTo(t.vent,t.VentActions.SearchState.READY,_.bind(this._setLockState,this));this.originplaceView=new n.PlaceListView({type:"origin",trackingLabel:"Auto_Departure",placeholder:$.i18n.t("search.place.origin.placeholder")});this.destinationplaceView=new n.PlaceListView({type:"destination",trackingLabel:"Auto_Arrival",originplaceView:this.originplaceView,placeholder:$.i18n.t("search.place.destination.placeholder")});this.originplaceView.model.on("change",_.bind(function(n){this.model.set({originplaceText:n.get("PlaceName"),originplace:n.get("PlaceId"),originCityCode:n.get("CityId"),originCountryCode:n.get("CountryId"),originCountryName:n.get("CountryName")});this.checkDestinations()},this));this.model.on("change:originplace",_.bind(function(n){n.get("originplace")!==this.originplaceView.model.get("PlaceId")&&(this.originplaceView.setValue({PlaceId:n.get("originplace"),PlaceName:n.get("originplaceText"),CityId:n.get("originCityCode"),CountryId:n.get("originCountryCode"),CountryName:n.get("originCountryName")}),this.checkDestinations())},this));this.ui.originPlaceSelector.html(this.originplaceView.render().$el);this.destinationplaceView.model.on("change",_.bind(function(n){this.model.set({destinationplaceText:n.get("PlaceName"),destinationplace:n.get("PlaceId"),destinationCityCode:n.get("CityId"),destinationCountryCode:n.get("CountryId"),destinationCountryName:n.get("CountryName")})},this));this.model.on("change:destinationplace",_.bind(function(n){n.get("destinationplace")!==this.destinationplaceView.model.get("PlaceId")&&this.destinationplaceView.setValue({PlaceId:this.model.get("destinationplace"),PlaceName:this.model.get("destinationplaceText"),CityId:this.model.get("destinationCityCode"),CountryId:this.model.get("destinationCountryCode"),CountryName:this.model.get("destinationCountryName")})},this));this.ui.destinationPlaceSelector.html(this.destinationplaceView.render().$el);this.model.get("originplace")&&this.originplaceView.setValue({PlaceId:this.model.get("originplace"),PlaceName:this.model.get("originplaceText"),CityId:this.model.get("originCityCode"),CountryId:this.model.get("originCountryCode"),CountryName:this.model.get("originCountryName")});this.model.get("destinationplace")&&this.destinationplaceView.setValue({PlaceId:this.model.get("destinationplace"),PlaceName:this.model.get("destinationplaceText"),CityId:this.model.get("destinationCityCode"),CountryId:this.model.get("destinationCountryCode"),CountryName:this.model.get("destinationCountryName")});this.originplaceView.on("change:focus",_.bind(function(){this.destinationplaceView.triggerMethod("change:selection")},this));this.destinationplaceView.on("change:focus",_.bind(function(){this.originplaceView.triggerMethod("change:selection")},this))},_canLockAirport:function(){return t.Services.Feature.check("lockAirport","on")?!0:t.Settings.config.lockAirport},_shouldLockAirport:function(n){var i=t.Settings.config.originplace;return this._sameAirports()?!1:n&&n===i},_sameAirports:function(){return this.model.get("originplace")===this.model.get("destinationplace")},_setLockState:function(){this._canLockAirport()&&(this._shouldLockAirport(this.originplaceView.getValue().PlaceId)?this.originplaceView.disable():this.originplaceView.enable(),this._shouldLockAirport(this.destinationplaceView.getValue().PlaceId)?this.destinationplaceView.disable():this.destinationplaceView.enable())},checkDestinations:function(){if(t.Utils.RoutesFilter.hasPredefinedRoutes()){var n=t.Utils.RoutesFilter.getDestinations(this.model.get("originplace"));_.contains(n,this.model.get("destinationplace"))||this.destinationplaceView.clear()}},swapPlaces:function(n){var i=this.originplaceView.getValue(),r=this.destinationplaceView.getValue();if(n.preventDefault(),this._sameAirports())return!1;this.ui.switchPlaces.toggleClass("rotate");t.tracking.trackEvent("home","Auto_DepartureArrival_Switch");this.originplaceView.setValue(r);this.destinationplaceView.setValue(i);this._setLockState()},_initializeCabinClassSelector:function(){var f=this.model.get("cabinclass"),u=new i.Collection(t.Dictionaries.CabinClasses),e=u.find(function(n){return n.get("value")===f})||u.first(),r=new n.CabinClassDropdownView({model:e,collection:u,tabindex:1,ariaLabel:$.t("aria.search.cabinclass")});this.cabinClassSelector=r;r.on("change",_.bind(function(n){this.model.set("cabinclass",n.value);t.tracking.trackEvent("home","CabinClassChoice",n.value)},this));this.model.on("change:cabinclass",_.bind(function(n){n.get("cabinclass")!==r.model.get("value")&&r.select(u.find(function(t){return t.get("value")===n.get("cabinclass")}))},this));this.ui.cabinClassSelector.html(r.render().$el)},_initializePeopleSelector:function(){var t=new n.PeopleSelectorView({el:this.ui.peopleSelector,provider:_.bind(function(){return{adults:parseInt(this.model.get("adults"),10),children:parseInt(this.model.get("children"),10),infants:parseInt(this.model.get("infants"),10)}},this),resolver:_.bind(function(n){this.model.set({adults:n.adults,children:n.children,infants:n.infants})},this)});this.peopleSelector=t;this.model.on("change:adults",function(){t.trigger("update")});this.model.on("change:children",function(){t.trigger("update")});this.model.on("change:infants",function(){t.trigger("update")})},blockShareButtons:function(){this.mainSharingView&&(this.mainSharingView.hideHover(),this.mainSharingView.$el.hide())},resetShareButtons:function(n){if(this.mainSharingView){this.mainSharingView.$el.show();_.extend(n,{destinationCityCode:this.model.get("destinationCityCode")});this.mainSharingView.onResetShareButtons(n)}},onDestroy:function(){this.mainSharingView&&this.mainSharingView.destroy();this.peopleSelector&&this.peopleSelector.destroy();this.cabinClassSelector&&this.cabinClassSelector.destroy();this.originplaceView&&this.originplaceView.destroy();this.destinationplaceView&&this.destinationplaceView.destroy();this.whiteLabelSelectorView&&this.whiteLabelSelectorView.destroy();t.Utils.Ui.off("orientation:change",this.onOrientationChange,this)},renderMainSharing:function(n){this.mainSharingView&&this.mainSharingView.destroy();this.mainSharingView=new t.Sharing.MainSharingView(n);$("#js-main-sharing").html(this.mainSharingView.render().$el);this.mainSharingView.onResetShareButtons(n)},onDomRefresh:function(n){var t=this.model.get("country");t!=="CN"&&this.renderMainSharing(n)},onChangeDate:function(n,i){n&&this.model.set("outbounddate",n.format(t.Settings.dateFormat));i&&this.model.set("inbounddate",i.format(t.Settings.dateFormat))},onSearchButtonKeyDown:function(n){n.which===32&&(n.preventDefault(),this.ui.searchButton.click())},onSearchButtonClick:function(n){var r=this.model.toJSON(),i=t.Flights.Models.SearchStateModel.validate(r);_.isEmpty(i)?(t.Utils.Ui.deactivateValidationErrors(this.$el),t.Utils.Ui.isWidget()||(n.preventDefault(),this.ui.searchButton.blur(),this.trigger("search",this.model))):(n.preventDefault(),this._showErrors(i))},_updateSearchLink:function(){var n=t.Utils.WhiteLabelLocation.getFlightsSearchPageUrl(_.pick(this.model.toJSON(),"originplace","destinationplace","outbounddate","inbounddate","cabinclass","adults","children","infants"));this.ui.searchButton.attr("href",n)},_showErrors:function(n){this.$el.is(":visible")&&_.isObject(n)&&!_.isEmpty(n)&&(t.Utils.Ui.showValidationErrors(this.$el,n,t.Flights.Models.SearchStateModel.ValidationErrors),n.too_many_infants&&this.model.set("infants",this.model.get("adults")))},_initializeDateSelectors:function(){var t=this;setTimeout(function(){var i=new n.DateFormView({inbounddate:t.model.get("inbounddate"),outbounddate:t.model.get("outbounddate")});t.dateFormView=i;i.on("change",function(n){t.model.set({outbounddate:n.outbounddate,inbounddate:n.inbounddate})});i.on("setButtonTitle",function(n){t.model.set("dateButton",n)});i.on("block:form",t.onBlockForm,t);i.on("unblock:form",t.onUnblockForm,t);t.model.on("change:outbounddate",_.bind(function(n){var t=i.departView.getValue();n.get("outbounddate")!==t&&i.departView.setValue(n.get("outbounddate"))},t));t.model.on("change:inbounddate",_.bind(function(n){var t=i.returnView.getValue();n.get("inbounddate")!==t&&i.returnView.setValue(n.get("inbounddate"))},t))},10)},_initializeWhiteLabelSelector:function(n){this.whiteLabelSelectorView=new t.Views.WhiteLabelSelectorView({type:"flights",products:n});this.ui.whiteLabelSelector.html(this.whiteLabelSelectorView.render().$el)},_initializeShortLabel:function(){this.searchShortLabelView=new n.ShortLabelView({el:this.ui.shortLabel,model:new i.Model({flight:{}})});this.searchShortLabelView.on("show",_.bind(function(){this.ui.search.addClass("mobile-hide")},this));this.searchShortLabelView.on("hide",_.bind(function(){this.ui.search.removeClass("mobile-hide");this.originplaceView.triggerMethod("focus:out");this.destinationplaceView.triggerMethod("focus:out")},this))},_initializePoweredByButton:function(){var n=new t.Views.PoweredByView({trackingLabel:"Logo_SearchPanel"});this.ui.poweredBy.html(n.render().$el)},onRender:function(){this.$el.i18n();this._initializeDateSelectors();this._initializePlacesSelector();this._initializeCabinClassSelector();this._initializePeopleSelector();this._initializeShortLabel();this._initializePoweredByButton();t.Settings.config.products&&t.Settings.config.products.length>0&&this._initializeWhiteLabelSelector(t.Settings.config.products);this._showErrors(this.options.errors);this.setScrollingTransformations()},onOrientationChange:function(){t.Utils.Ui.showValidationErrors(this.$el,this.options.errors,t.Flights.Models.SearchStateModel.ValidationErrors)},onBlockForm:function(){$(".js-search-form-overlay").addClass("show")},onUnblockForm:function(){$(".js-search-form-overlay").removeClass("show")},onHideShortlabel:function(){this.searchShortLabelView.hide()},onShowShortlabel:function(){this.searchShortLabelView.show(_.pick(this.model.toJSON(),"originplace","destinationplace","originplaceText","destinationplaceText","inbounddate","outbounddate"))},onShowErrors:function(n){this._showErrors(n)},setScrollingTransformations:function(){if(!t.Utils.Ui.isWidget()){this.$window=$(window);this.$window.off("resize.searchForm").on("resize.searchForm",_.bind(this.onWindowResize,this));this.onWindowResize();this.$window.off("scroll.searchForm").on("scroll.searchForm",_.bind(this.onWindowScroll,this))}},onWindowScroll:function(){var n=this.getSearchBannerContainer(),i=n.hasClass("top-fixed");if(n.length!==0)if(!this._isMobile&&t.Router.isResultsPage()){var r=this.$window.scrollTop(),f=t.Settings.config.showImageBanner?85:48,u=n.offset().top+n.outerHeight()-f;!i&&r>=u&&(this.cabinClassSelector&&this.cabinClassSelector.close(),this.dateFormView&&this.dateFormView.close(),this.originplaceView&&this.originplaceView.onInputBlur(),this.destinationplaceView&&this.destinationplaceView.onInputBlur(),n.addClass("top-fixed"),t.Utils.Ui.trigger("search-container:toggle-top-fixed",!0));i&&r<u&&(n.removeClass("top-fixed"),t.Utils.Ui.trigger("search-container:toggle-top-fixed",!1))}else i&&(n.removeClass("top-fixed"),t.Utils.Ui.trigger("search-container:toggle-top-fixed",!1))},getSearchBannerContainer:function(){return this.$container&&this.$container.length!==0||(this.$container=$(".js-search-container-fluid")),this.$container},onWindowResize:function(){this._isMobile=t.Utils.Ui.isMobileView();this.onWindowScroll()},onOverlayClick:function(){var n=t.Settings.config.showImageBanner?-280:-210;$.scrollTo(this.getSearchBannerContainer(),{duration:"500",over:"1",offset:{top:n}})},initialize:function(){t.Utils.Ui.on("orientation:change",this.onOrientationChange,this)}})});App.module("Flights.SearchForm",function(n,t,i,r){n.ShortLabelView=r.ItemView.extend({template:"#search-short-label-template",ui:{departCover:".js-label-depart-cover",returnCover:".js-label-return-cover",separator:".js-date-separator"},events:{click:function(){this.hide()}},wrapDate:function(n){var i={},u="",f="",e="",r="";return n&&(i=moment(n,t.Settings.dateFormat),u=i.get("year"),f=moment.monthsShort()[i.get("month")],e=moment.weekdaysShort()[i.format("d")],r=i.format("D"),r<10&&(r="0"+r.toString())),_.extend(i,{year:u,month:f,day:r,dayOfWeek:e}),i},show:function(n){n=_.extend(n,{formatted:{outbounddate:this.wrapDate(n.outbounddate),inbounddate:this.wrapDate(n.inbounddate)}});this.model.set("flight",n);this.render();this.$el.removeClass("mobile-hide").addClass("mobile-show");this.trigger("show")},hide:function(){this.$el.removeClass("mobile-show").addClass("mobile-hide");this.trigger("hide")},onRender:function(){this.model.get("flight").inbounddate||(this.ui.separator.hide(),this.ui.returnCover.hide());var n=null,i=this;_.each(["outbounddate","inbounddate"],function(r){var f;n=r==="outbounddate"?moment(i.model.get("flight").outbounddate,t.Settings.dateFormat):moment(i.model.get("flight").inbounddate,t.Settings.dateFormat);var e=n.get("year"),o=moment.monthsShort()[n.get("month")],s=moment.weekdaysShort()[n.format("d")],u=n.format("D");u<10&&(u="0"+u.toString());f="<span>"+s+" <strong> "+u+" "+o+"<\/strong> "+e+"<\/span>";r==="outbounddate"?i.ui.departCover.html(f):i.ui.returnCover.html(f)});this.$el.i18n()}})});App.module("Flights.SearchForm",{startWithParent:!1,define:function(n,t){var i={updateState:function(n,t){n.model.set(_.pick(t.toJSON(),"originplace","destinationplace","originplaceText","destinationplaceText","originCityCode","originCountryName","originCountryCode","destinationCityCode","destinationCountryCode","destinationCountryName","outbounddate","inbounddate","cabinclass","adults","children","infants"))},"change:date":function(n,t,i){n.triggerMethod("change:date",t,i)},blockShareButtons:function(n){n.blockShareButtons()},resetShareButtons:function(n,t){n.resetShareButtons(t)},"change:originPlace":function(n,t){n.model.set({originplace:t.PlaceId,originplaceText:t.PlaceName})},"change:destinationPlace":function(n,t){n.model.set({destinationplace:t.PlaceId,destinationplaceText:t.PlaceName,destinationCountryCode:t.CountryCode,destinationCountryName:t.CountryName})},"change:cabinclass":function(n,t){n.model.set({cabinclass:t})},"clear:itinerary":function(n){n.model.set({itinerary:null})},"show:shortLabel":function(n){n.triggerMethod("show:shortlabel")},"hide:shortLabel":function(n){n.triggerMethod("hide:shortlabel")},"show:errors":function(n,t){n.triggerMethod("show:errors",t)}},r;n.search=function(i){i||(i=n.getCurrentStateForUrlParams());var r=t.Flights.SearchState.Base.Resolver.url(i);t.vent.trigger(t.VentActions.Flights.SEARCH_BEFORE_START,i);t.Router.is404()?t.Utils.Location.homeRedirect("#/result?"+r):t.Router.navigate("#/result?"+r,{trigger:!0})};r=function(r,u){var f=new n.SearchFormView({model:r,errors:u});t.Flights.SearchForm.trigger("change:cabinclass","Economy");f.model.on("change",function(n){t.Flights.SearchState.Resolver.outlookAddin(n.toJSON());t.Flights.SearchState.Resolver.localstorage(n.toJSON())});f.on("search",function(){f.blockShareButtons&&f.blockShareButtons();var i=f.model.toJSON(),r=i.originplace?i.originplace:"",u=i.destinationplace?i.destinationplace:"",e=r+"_"+u+"_PAX_"+i.adults+";"+i.children+";"+i.infants;t.tracking.trackEvent("home","SearchClick",e);t.Flights.SearchState.Resolver.outlookAddin(i);t.Flights.SearchState.Resolver.localstorage(i);n.search(i)});n.getCurrentStateForUrlParams=function(){var n=f.model.toJSON();return _.pick(n,"originplace","destinationplace","outbounddate","inbounddate","cabinclass","adults","children","infants")};_.each(i,function(t,i){n.on(i,function(){return Array.prototype.unshift.call(arguments,f),t.apply(null,arguments)})});n.trigger("ready",f)};n.on("start",function(n){r(n.model,n.errors)});n.on("stop",function(){_.each(i,function(t,i){n.off(i)})})}});App.module("Utils",function(n,t){var i,r=!1,u=!1;n.AddThis={onAddThisReady:function(n){if(i&&i(!1),r){n(!0);return}i=n;u||(u=!0,$.ajax({url:"//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-53fd8f4d611a5927",dataType:"script",success:function(){window.addthis&&window.addthis.addEventListener("addthis.menu.share",function(n){if(n.type==="addthis.menu.share"){var i=typeof n=="object"&&n.data&&n.data.service||"";t.tracking.trackEvent("day-view","Share_Intent",i)}});r=!0;i&&(i(!0),i=null)},error:function(){t.tracking.trackEvent("error","addthis_LoadFailed","Error getting script for addthis toolbox")}}))},isReady:function(){return r}}});App.module("SearchResult.Utils",function(n,t){var i=11;n.BookingHandler={processBooking:function(n,r){var e=n.priceOptions,h=Math.floor((new Date).getTime()/6e4),c=h-r,l=e.quoteAgeInMinutes+c;if(l<=i)this.openBookingDeeplink(e.deepLink,n);else{var u=e.priceData,o=u.body,f=n.searchParams,s=!t.Services.Flights.isGroupPrice(f);s||(o+="&adults="+f.adults+"&children="+f.children+"&infants="+f.infants);t.Services.Currency.getCurrency().done(_.bind(function(t){this.openLightRedirectPage({body:o,uri:u.uri,price:u.price.amount,isSinglePassenger:s,agentId:u.agents[0].id,agent:u.agents[0].name,currency:t,itineraryIndex:n.itineraryIndex,priceIndex:n.priceIndex})},this))}},openBookingDeeplink:function(n,i){var r=i.searchParams,u=r.originplace?r.originplace:"",f=r.destinationplace?r.destinationplace:"",e=u+"_"+f+"_PAX_"+r.adults+";"+r.children+";"+r.infants;t.tracking.trackEvent("day-view","BookClick","Flights_liveprice_"+i.itineraryIndex+"_"+i.priceIndex+"_"+e);window.open(t.tracking.decorateUrl(n),"_blank")},openLightRedirectPage:function(n){_.each(n,function(t,i){n[i]=encodeURIComponent(t)});window.open(t.Utils.WhiteLabelLocation.getFlightsLightRedirectUrl(n),"_blank")}}});App.module("SearchResult.Utils",function(n,t){var r=new t.Utils.Cache,i;n.BrowseCache={getData:function(n,t){return n.inbounddate?this.getTwoWaysData(n,t):this.getOneWayData(n,t)},getOneWayData:function(n,u){var w=moment.utc(n.outbounddate,t.Settings.dateFormat),l=this.getRangeBounds(w,this._getRange(!0,u),!0),f={outboundStart:l.begin,outboundFinish:l.end},o=$.Deferred(),a=[],s=this,e={outbounds:[],currency:{}},h=this._buildRequestParams(n);i=moment.weekdaysMin();for(var c=f.outboundStart.clone().set("date",1),b=f.outboundFinish.clone().set("date",1),v=function(n){var i=new $.Deferred;return t.Services.Session.getToken().done(function(u){$.ajax({type:"GET",url:AppSettings.apiUrl+"apiservices/browsegrid/v1.0/"+n+"?apiKey="+encodeURIComponent(u),dataType:"JSON"}).always(function(u,o,c){var l=(u!=null?u.status:void 0)!=null?u:c;switch(l.status){case 200:var a=l.responseJSON.Dates,y=moment(a[0][0].DateString,t.Settings.dateFormat),p=y.format(t.Settings.monthFormat),w=s._buildCacheKey(h,p);r.set(w,{cachedData:l.responseJSON});s._processingOneWayResponse(l.responseJSON,e,f.outboundStart,f.outboundFinish);i.resolve(l.responseJSON);break;case 204:case 304:i.reject();break;case 403:case 419:t.Services.Session.getToken(!0).done(function(){v(n).done(function(n){i.resolve(n)}).fail(function(){i.reject()})}).fail(function(n){i.reject(n)});break;case 400:t.tracking.trackEvent("error","browseCache:lowestPrices","400 Bad Request");i.reject();break;case 429:t.tracking.trackEvent("error","browseCache:lowestPrices","429 Too Many Requests");i.reject(u);break;case 500:t.tracking.trackEvent("error","browseCache:lowestPrices","500 Server Error");i.reject();break;default:i.reject()}})}).fail(function(n){i.reject(n)}),i.promise()};c<=b;){var y=c.format(t.Settings.monthFormat),k=this._buildCacheKey(h,y),p=r.get(k),d=p?p:v(h+y);a.push(d);c.add(1,"months")}return $.when.apply($,a).done(function(){_.each(arguments,function(n){n&&!_.isUndefined(n.cachedData)&&s._processingOneWayResponse(n.cachedData,e,f.outboundStart,f.outboundFinish)});e.outbounds=_.sortBy(e.outbounds,function(n){return n.date});o.resolve(e)}).fail(function(n){o.reject(n)}),o.promise()},getTwoWaysData:function(n,u,f){var o=moment(n.outbounddate,t.Settings.dateFormat),s=moment(n.inbounddate,t.Settings.dateFormat),c,e,y,a,h,p,d,b;_.isUndefined(f)&&(f={outbound:o,inbound:s});c={outBound:f.outbound?this.getRangeBounds(f.outbound,this._getRange(!1,u)):null,inBound:f.inbound?this.getRangeBounds(f.inbound,this._getRange(!1,u)):null};e={};e.outBound=c.outBound?{begin:c.outBound.begin.clone(),end:c.outBound.end.clone()}:null;e.inBound=c.inBound?{begin:c.inBound.begin.clone(),end:c.inBound.end.clone()}:null;e.outBound&&e.outBound.end>s&&(e.inRefl={begin:e.outBound.begin>s?e.outBound.begin.clone():s.clone().add(1,"days"),end:e.outBound.end.clone()},e.outBound.end=s);e.inBound&&e.inBound.begin<o&&(e.outRefl={begin:e.inBound.begin.clone(),end:e.inBound.end<o?e.inBound.end.clone():o.clone().subtract(1,"days")},e.inBound.begin=o);var w=$.Deferred(),k=[],v=this,l={outbounds:[],inbounds:[],currency:{}};if(i=moment.weekdaysMin(),y=this._buildRequestParams(n),a=[],e.outBound)for(h=e.outBound.begin.clone().set("date",1),p=e.outBound.end.clone().set("date",1);h<=p;)a.push({outbound:h.format(t.Settings.monthFormat),inbound:s.format(t.Settings.monthFormat)}),h.add(1,"months");if(e.inBound)for(h=e.inBound.begin.clone().set("date",1),p=e.inBound.end.clone().set("date",1);h<=p;)d={outbound:o.format(t.Settings.monthFormat),inbound:h.format(t.Settings.monthFormat)},this._pusnMonthsNotExist(d,a),h.add(1,"months");return this._updateMonthsListRefl(e.outRefl,a),this._updateMonthsListRefl(e.inRefl,a),b=function(n){var i=new $.Deferred;return t.Services.Session.getToken().done(function(u){$.ajax({type:"GET",url:AppSettings.apiUrl+"apiservices/browsegrid/v1.0/"+n+"?apiKey="+encodeURIComponent(u),dataType:"JSON"}).always(function(u,f,h){var c=(u!=null?u.status:void 0)!=null?u:h;switch(c.status){case 200:var a=c.responseJSON.Dates,p=moment(a[0][1].DateString,t.Settings.dateFormat),w=moment(a[1][0].DateString,t.Settings.dateFormat),k=p.format(t.Settings.monthFormat),d=w.format(t.Settings.monthFormat),g=v._buildCacheKey(y,k,d);r.set(g,{cachedData:c.responseJSON});v._processTwoWaysResponse(c.responseJSON,l,e,o,s);i.resolve(c.responseJSON);break;case 204:case 304:i.reject();break;case 403:case 419:t.Services.Session.getToken(!0).done(function(){b(n).done(function(n){i.resolve(n)}).fail(function(){i.reject()})}).fail(function(n){i.reject(n)});break;case 400:t.tracking.trackEvent("error","browseCache:lowestPrices","400 Bad Request");i.reject();break;case 429:t.tracking.trackEvent("error","browseCache:lowestPrices","429 Too Many Requests");i.reject(c);break;case 500:t.tracking.trackEvent("error","browseCache:lowestPrices","500 Server Error");i.reject();break;default:i.reject()}})}).fail(function(n){i.reject(n)}),i.promise()},_.each(a,function(n){var i=v._buildCacheKey(y,n.outbound,n.inbound),t=r.get(i),u=t?t:b(y+n.outbound+"/"+n.inbound);k.push(u)}),$.when.apply($,k).done(function(){_.each(arguments,function(n){n&&!_.isUndefined(n.cachedData)&&v._processTwoWaysResponse(n.cachedData,l,e,o,s)});e.outBound&&(l.outbounds=_.sortBy(l.outbounds,function(n){return n.date}));e.inBound&&(l.inbounds=_.sortBy(l.inbounds,function(n){return n.date}));w.resolve(l)}).fail(function(n){w.reject(n)}),w.promise()},_updateMonthsListRefl:function(n,i){var r,u,f;if(n)for(r=n.begin.clone().set("date",1),u=n.end.clone().set("date",1);r<=u;)f={outbound:r.format(t.Settings.monthFormat),inbound:r.format(t.Settings.monthFormat)},this._pusnMonthsNotExist(f,i),r.add(1,"months")},_pusnMonthsNotExist:function(n,t){var i=_.isUndefined(_.find(t,function(t){return t.outbound==n.outbound&&t.inbound==n.inbound}));i&&t.push(n)},_processingOneWayResponse:function(n,r,u,f){var e=n.Dates,s=moment.utc(e[0][0].DateString,t.Settings.dateFormat),c=moment.utc(e[0][e[0].length-1].DateString,t.Settings.dateFormat),o;if(u<=c&&f>=s){var l=u>s?u.get("date"):1,h=u>s?u.get("day"):s.get("day"),a=f<c?f.get("date"):c.get("date");for(o=l-1;o<a;o++)r.outbounds.push({date:e[0][o].DateString,day:i[h],price:e[1][o]==null?null:e[1][o].MinPrice,timestamp:moment(e[0][o].DateString,t.Settings.dateFormat),timestampRefl:null}),h=h==6?0:++h}n.Currencies&&(r.currency=n.Currencies[0])},_processTwoWaysResponse:function(n,r,u,f,e){var s=n.Dates,c={outBound:{begin:moment(s[0][1].DateString,t.Settings.dateFormat),end:moment(s[0][s[0].length-1].DateString,t.Settings.dateFormat)},inBound:{begin:moment(s[1][0].DateString,t.Settings.dateFormat),end:moment(s[s.length-1][0].DateString,t.Settings.dateFormat)}},w=f.clone().set("date",1),b=e.clone().set("date",1),h,o,l,a,y,p,v;if(u.outBound&&!c.inBound.begin.diff(b)&&this._boundsInMonth(u.outBound,c.outBound))for(h=this._getLimits(u.outBound,c.outBound),y=s[e.get("date")],o=h.startNumber;o<=h.endNumber;o++)r.outbounds.push({date:s[0][o].DateString,day:i[h.day],price:y[o]==null?null:y[o].MinPrice,timestamp:moment(s[0][o].DateString,t.Settings.dateFormat),timestampRefl:null}),this._incrementDay(h);if(u.inBound&&!c.outBound.begin.diff(w)&&this._boundsInMonth(u.inBound,c.inBound))for(h=this._getLimits(u.inBound,c.inBound),p=f.get("date"),o=h.startNumber;o<=h.endNumber;o++)r.inbounds.push({date:s[o][0].DateString,day:i[h.day],price:s[o][p]==null?null:s[o][p].MinPrice,timestamp:moment(s[o][0].DateString,t.Settings.dateFormat),timestampRefl:null}),this._incrementDay(h);if(u.outRefl&&!c.outBound.begin.diff(c.inBound.begin)&&this._boundsInMonth(u.outRefl,c.outBound))for(h=this._getLimits(u.outRefl,c.outBound),o=h.startNumber;o<=h.endNumber;o++){for(l=o,v=s[l],a=v[l];!a&&l>1;)a=v[--l];a||(l=o);r.inbounds.push({date:v[0].DateString,day:i[h.day],price:a==null?0:a.MinPrice,timestamp:moment(v[0].DateString,t.Settings.dateFormat),timestampRefl:moment(s[0][l].DateString,t.Settings.dateFormat)});this._incrementDay(h)}if(u.inRefl&&!c.outBound.begin.diff(c.inBound.begin)&&this._boundsInMonth(u.inRefl,c.inBound))for(h=this._getLimits(u.inRefl,c.inBound),o=h.startNumber;o<=h.endNumber;o++){for(l=o,a=s[l][o];!a&&l<c.inBound.end.get("date");)a=s[++l][o];a||(l=o);r.outbounds.push({date:s[0][o].DateString,day:i[h.day],price:a==null?null:a.MinPrice,timestamp:moment(s[0][o].DateString,t.Settings.dateFormat),timestampRefl:moment(s[l][0].DateString,t.Settings.dateFormat)});this._incrementDay(h)}n.Currencies&&(r.currency=n.Currencies[0])},_boundsInMonth:function(n,t){return n.begin<=t.end&&n.end>=t.begin},_getLimits:function(n,t){var i=n.begin>t.begin?n.begin:t.begin,r=i.get("date"),u=i.get("day"),f=n.end<t.end?n.end.get("date"):t.end.get("date");return{startNumber:r,endNumber:f,day:u}},_incrementDay:function(n){n.day=n.day==6?0:++n.day},_fillPrice:function(n,r,u){for(var f=r.clone();f<=u;)n.push({date:f.format(t.Settings.dateFormat),day:i[f.get("day")],price:null,timestamp:f.clone()}),f.add(1,"days")},_buildRequestParams:function(n){return n.country+"/"+n.currency+"/"+n.locale+"/"+n.originplace+"/"+n.destinationplace+"/"},_buildCacheKey:function(n,t,i){return"browsegrid/"+n+t+(i?"/"+i:"")},getRangeBounds:function(n,t,i){var r=n.clone().subtract(t,"days"),u=n.clone().add(t,"days"),f=this.getAvailiableDates(i),e,o;return r<f.begin&&(e=f.begin.diff(r,"days"),r.add(e,"days"),u.add(e,"days")),u>f.end&&(o=u.diff(f.end,"days"),r.subtract(o,"days"),u.subtract(o,"days")),{begin:r,end:u}},getAvailiableDates:function(n){var i=moment().format(t.Settings.dateFormat),r=n?moment.utc(i):moment(i),u=r.clone().add(1,"year");return{begin:r,end:u}},getMaxPrice:function(n){var t=_.filter(n,function(n){return n!=null});if(t.length==0)return 0;var i=_.max(t),r=this._getMedianPrice(t),u=Math.min(2*r,i);return this.getSmoothedPrice(u)},getSmoothedPrice:function(){for(var n=Math.max.apply(null,arguments),t=1;n>=20;)n/=10,t*=10;return Math.ceil(n)*t},getNormalizedData:function(n,t,i){var r=[];return _.each(n,function(n){n.percent=t?n.price*100/t:0;n.selected=!n.timestamp.diff(i,"days");n.number=n.timestamp.get("date");r.push(n)}),r},getMonthsList:function(n){for(var o,r=n[Math.floor(n.length/2)].timestamp.clone(),s=moment.monthsShort(),u=moment(),i=moment({year:u.get("year"),month:u.get("month")}),h=moment({year:r.get("year"),month:r.get("month")}),f=[],e=0;e<12;e++)o=i.get("month"),f.push({name:s[o],selected:!i.diff(h),date:i.format(t.Settings.monthFormat)}),i.add(1,"months");return f},_getMedianPrice:function(n){var t=_.sortBy(n),i=Math.floor(n.length/2);return t.length%2?t[i]:(t[i-1]+t[i])/2},_getRange:function(n,i){if(t.Utils.Ui.isMobileView()){var r=Math.floor(i/t.Settings.lowestPrices.pixelsPerDayForScrolling);return Math.floor((r-1)/2)}return n?t.Settings.lowestPrices.oneWayRange:t.Settings.lowestPrices.twoWayRange}}});App.module("SearchResult.Filters",function(n,t){n.AggregationDropdownView=Backbone.Marionette.CompositeView.extend({template:"#dropdown-template",templateHelpers:{tabindex:0,label:"",ariaLabel:""},className:"class-name-aggregation",headerView:Backbone.Marionette.ItemView.extend({template:function(n){return _.template(['<span data-i18n="search-result.filter-menu.more-header"><\/span>','<% if (typeof value !== "undefined" && value) { %>','<b class="ss-icon ss-icon-triangle-down active"><\/b> <b class="ss-icon ss-icon-triangle-up"><\/b>',"<% } else { %>",'<b class="ss-icon ss-icon-triangle-down"><\/b> <b class="ss-icon ss-icon-triangle-up"><\/b>',"<% } %>"].join(""),n)},onRender:function(){this.$el.i18n()}}),getChildView:function(n){return n.get("view")},behaviors:{DropdownExtendedKeysControl:{},DropdownMobileFullscreen:{getHeaderLabel:function(){return'<span class="modal-title" data-i18n="search-result.filter-menu.more-header"><\/span>'}}},childViewContainer:".js-dropdown-items-container",opened:!1,ui:{toggleContainer:".js-dropdown-toggle",itemsContainerWrapper:".js-dropdown-container-wrapper"},events:{"click @ui.toggleContainer":"onToggleClick"},childEvents:{change:function(n,t){this.trigger("change",t)},hide:function(){this.$el.addClass("inactive");this.disabled=!0},show:function(){this.$el.removeClass("inactive");this.disabled=!1}},onToggleClick:function(n){return n.preventDefault(),this.disabled||(t.GlobalEvents.trigger("global:click",n),this.toggle()),!1},onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.className&&this.$el.addClass(this.className);typeof this.headerView=="function"&&(this.headerView=new this.headerView({model:new Backbone.Model({value:""})}));this.ui.toggleContainer.html(this.headerView.render().$el);this.onAfterRender&&typeof this.onAfterRender=="function"&&this.onAfterRender()},open:function(){t.GlobalEvents.on("global:update-results",this._adjustPosition,this);this.ui.toggleContainer.addClass("selected");this.ui.itemsContainerWrapper.css({visibility:"hidden",marginTop:"auto"}).addClass("active");this._adjustPosition();this.ui.itemsContainerWrapper.css("visibility","visible");this.opened=!0;this.trigger("open",this);this.onOpen&&this.onOpen()},close:function(){t.GlobalEvents.off("global:update-results",this._adjustPosition,this);this.ui.toggleContainer.removeClass("selected");this.ui.itemsContainerWrapper.removeClass("active");this.opened=!1;this.trigger("close",this);this.onClose&&this.onClose()},toggle:function(){this.opened?this.close():this.open();this.trigger("toggle",this)},focus:function(){this.ui.toggleContainer.focus()},_adjustPosition:function(){var n=this.ui.itemsContainerWrapper.closest(".application"),i=n.offset()||{},r=n.height(),u=this.ui.itemsContainerWrapper.offset(),f=this.ui.itemsContainerWrapper.outerHeight(),t=i.top+r-(u.top+f+10);t<0&&this.ui.itemsContainerWrapper.css("margin-top",t+"px")},_bindEvents:function(){t.GlobalEvents.on("global:click",_.bind(function(n){!this.$el.find(".js-dropdown-toggle").hasClass("selected")||t.Utils.Ui.isMobileView()&&this.opened||this.$el.is(n.target)||this.$el.has(n.target).length!==0||(this.close(),this.trigger("toggle",this))},this))},onOpen:function(){var u=$(".js-filter-menu-list"),n=this.$el.find(".js-dropdown-container-wrapper"),i=n.closest(".dropdown"),r;(t.Utils.Ui.isMobileView()||t.Utils.Ui.isTabletView())&&t.Utils.Ui.scrollToCenter(i);t.Utils.Ui.isMobileDevice()&&t.Utils.Ui.isMobileView()||(r=t.Utils.Ui.getFilterMenuLeftPosition(n,i,u),n.css("left",r))},onBeforeRenderCollection:function(){this.trigger("before:render-dropdown")},onChangeSummary:function(n){_.each(this.children._views,function(t){t.triggerMethod("change:summary",n)})},reset:function(n){_.each(this.children._views,function(t){t.reset(n)})},savedCollections:[],onBeforeDropdownMobileFullscreenInit:function(){this.savedCollections=[];_.each(this.children._views,function(n){this.savedCollections.push(n.collection.toJSON())},this)},onAfterDropdownMobileFullscreenInit:function(){var n=0;_.each(this.children._views,function(t){t.collection.reset(this.savedCollections[n]);t._updateHeaderView&&typeof t._updateHeaderView=="function"&&t._updateHeaderView();n++},this)},setDisabled:function(){this.disabled&&this.$el.addClass("inactive")},onDestroy:function(){t.Utils.Ui.off("breakpoint:change",this.setDisabled,this)},initialize:function(n){this.collection.each(function(n){var i=n.get("view");n.set("view",i.extend({template:"#aggregated-dropdown-template",behaviors:{DropdownSlide:{height:310,enabled:function(){return!(t.Utils.Ui.isMobileDevice()&&t.Utils.Ui.isMobileView())}}}}))});this.model=n&&n.model?n.model:new Backbone.Model;this.templateHelpers.label=n&&n.label?n.label:"";this.templateHelpers.tabindex=n&&n.tabindex?n.tabindex:0;this.templateHelpers.ariaLabel=n&&n.ariaLabel?n.ariaLabel:"";t.Utils.Ui.on("breakpoint:change",this.setDisabled,this);this._bindEvents()}})});App.module("SearchResult.Filters",function(n,t,i){var r=i.Marionette.ItemView.extend({template:"#any-airlines-dropdown-item-template",templateHelpers:{isSelected:function(){return typeof this.selected=="boolean"&&this.selected}},ui:{anchor:".js-dropdown-item"},onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.i18n()},modelEvents:{"change:selected":function(n){n.get("selected")?this.ui.anchor.addClass("selected").attr("aria-checked",!0):this.ui.anchor.removeClass("selected").attr("aria-checked",!1)}},events:{"click @ui.anchor":function(n){return n.preventDefault(),this.model.set("selected",!this.model.get("selected")),this.trigger("item:selected",{type:this.model.get("type")}),!1}}}),u=i.Marionette.CompositeView.extend({template:"#alliances-collection-view-template",childViewContainer:".js-alliances-container",childView:i.Marionette.ItemView.extend({template:"#airlines-dropdown-item-alliance-template",templateHelpers:{isSelected:function(){return typeof this.selected=="boolean"&&this.selected}},onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.i18n();this.model.get("disabled")?this.$el.hide():this.$el.show()},modelEvents:{"change:selected":function(n){n.get("selected")?this.ui.anchor.addClass("selected").attr("aria-checked",!0):this.ui.anchor.removeClass("selected").attr("aria-checked",!1)},"change:disabled":function(n){n.get("disabled")?this.$el.hide():this.$el.show()}},ui:{anchor:".js-dropdown-item"},events:{"click @ui.anchor":function(n){return n.preventDefault(),this.model.set("selected",!this.model.get("selected")),this.trigger("item:selected",this.model),!1}}}),childEvents:{"item:selected":function(n,t){this.trigger("item:selected",{type:this.model.get("type"),alliance:t})}},onBeforeRenderCollection:function(){this.collection.each(function(n){var t=n.get("translatedName");t?n.set("translatedName",$.i18n.t(t)):n.set("translatedName",n.get("name"))})},onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.i18n()},initialize:function(){this.collection=this.model.get("alliances")}}),f=i.Marionette.CompositeView.extend({template:"#airlines-collection-view-template",childViewContainer:".js-airlines-container",childView:i.Marionette.ItemView.extend({template:"#airlines-dropdown-item-airline-template",templateHelpers:{isMobileTabletView:function(){return t.Utils.Ui.isMobileView()||t.Utils.Ui.isTabletView()}},onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.i18n()},ui:{checkbox:"input"},modelEvents:{"change:checked":function(n){_.defer(_.bind(function(){this.ui.checkbox.prop("checked",n.get("checked"))},this))}},events:{click:function(){return this.model.set("checked",!this.model.get("checked")),this.trigger("item:selected",this.model),!1},"click .js-only-btn":function(){return this.model.set("checked",!0),this.trigger("item:only",this.model),!1}}}),childEvents:{"item:selected":function(){this.trigger("item:selected",{type:this.model.get("type")})},"item:only":function(n,t){this.collection.each(function(n){t.get("code")!==n.get("code")&&n.set("checked",!1)});this.trigger("item:selected",{type:this.model.get("type")})}},onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.i18n()},initialize:function(){this.collection=this.model.get("airlines")}});n.AirlinesDropdownView=t.Views.DropdownView.extend({className:"class-name-airlines",headerView:t.Views.DefaultDropdownHeaderView.extend({template:"#airlines-dropdown-header-template"}),behaviors:{DropdownExtendedKeysControl:{},DropdownMobileFullscreen:{getHeaderLabel:function(){return'<span class="modal-title" data-i18n="search-result.filter-menu.airlines"><\/span>'}},DropdownSlide:{height:405,enabled:function(){return!(t.Utils.Ui.isMobileDevice()&&t.Utils.Ui.isMobileView())}}},getChildView:function(n){switch(n.get("type")){case"any":return r;case"alliance":return u;case"airline":return f;default:throw"not supported";}},_getAlliancesCollection:function(){return this.collection.at(1).get("alliances")},_getAirlinesCollection:function(){return this.collection.at(2).get("airlines")},_getAnyModel:function(){return this.collection.at(0)},_updateHeaderView:function(){var t,u=this._getAirlinesCollection(),n=u.where({checked:!0}),f,i,r;n.length===u.length?t="":(f=this._getAlliancesCollection(),i=_.map(n,function(n){return n.get("code")}),i.length===0?t="(0)":(r="",f.each(function(n){var t=n.get("existedAirlines"),u=_.intersection(t,i);if(u.length===t.length&&u.length===i.length)return r=n.get("name"),!1}),t=r?r:n.length>0&&n.length<=3?_.map(n,function(n){return n.get("displayCode")}).join(", "):"("+n.length+")"));this.headerView.model.set({value:t})},select:function(n){var o=n.type,u=this._getAnyModel(),e=this._getAlliancesCollection(),i=this._getAirlinesCollection(),f,s,r,c,l;if(o==="any")f=u.get("selected"),e.each(function(n){n.set("selected",!1)}),i.each(function(n){n.set("checked",f)}),f&&t.tracking.trackEvent("day-view","SecondaryFilter","Airlines_Any");else if(o==="alliance"){s=n.alliance;f=s.get("selected");var a=s.get("existedAirlines"),h=e.where({selected:!0}),v=u.get("selected");v&&f&&(u.set("selected",!1),i.each(function(n){n.set("checked",!1)}));i.each(function(n){_.indexOf(a,n.get("code"))!==-1&&n.set("checked",f)});h.length===1?t.tracking.trackEvent("day-view","SecondaryFilter","Airlines_"+h[0].get("name")):h.length>1&&t.tracking.trackEvent("day-view","SecondaryFilter","Airlines_ManyAlliances")}else o==="airline"&&(r=i.where({checked:!0}),r.length===i.length?(e.each(function(n){n.set("selected",!1)}),u.set("selected",!0)):r.length===0?(e.each(function(n){n.set("selected",!1)}),u.set("selected",!1)):(u.set("selected",!1),c=_.map(r,function(n){return n.get("code")}),l=i.pluck("code"),e.each(function(n){var t=n.get("existedAirlines"),i=_.intersection(t,c),r=_.intersection(t,l);n.set("selected",i.length===r.length)})),r.length===1?t.tracking.trackEvent("day-view","SecondaryFilter","Airlines_"+r[0].get("displayCode")):r.length>1&&t.tracking.trackEvent("day-view","SecondaryFilter","Airlines_Many"));this.trigger("change",{airlines:i.toJSON()});this._updateHeaderView()},onChangeSummary:function(n){var s=n.get("summary"),r=n.get("filter"),h=this._getAnyModel(),u=this._getAlliancesCollection(),c=this._getAirlinesCollection(),i,f,e,o;if(!r||!r.airlines||r.airlines.length===0){this.$el.hide();return}s&&(u.length===0&&u.reset(_.toArray(t.Dictionaries.AirlineAlliances)),i=r.airlines,_.sortBy(i,function(n){return n.name}),f=0,_.each(i,function(n){var i=n.minPrice;n.wrappedMinPrice=i>0?t.Utils.Ui.wrapPrice(i,s.currency):"";n.checked&&f++}),e=_.pluck(i,"code"),o=_.chain(i).filter(function(n){return n.checked}).pluck("code").value(),u.each(function(n){var i=n.get("airlines"),t=_.intersection(e,i),r;n.set("existedAirlines",t);t.length===0?n.set("disabled",!0):(n.set("disabled",!1),e.length>o.length&&(r=_.intersection(i,o),n.set("selected",r.length===t.length)))}),c.reset(i),f===i.length?h.set("selected",!0):h.set("selected",!1),this._updateHeaderView(),this.$el.show(),this.isAlreadyShown=!0)},isAlreadyShown:!1,reset:function(){var n=this._getAnyModel();n.set("selected",!0);this.select({type:"any"})},onOpen:function(){var u=$(".js-filter-menu-list"),n=this.$el.find(".js-dropdown-container-wrapper"),i=n.closest(".dropdown"),r;(t.Utils.Ui.isMobileView()||t.Utils.Ui.isTabletView())&&t.Utils.Ui.scrollToCenter(i);t.Utils.Ui.isMobileDevice()&&t.Utils.Ui.isMobileView()||(r=t.Utils.Ui.getFilterMenuLeftPosition(n,i,u),n.css("left",r))},onAfterInitialize:function(){this.collection=new i.Collection([{type:"any"},{type:"alliance",alliances:new i.Collection},{type:"airline",airlines:new i.Collection}])},onAfterRender:function(){this.isAlreadyShown&&this.$el.show()}})});App.module("SearchResult.Filters",function(n,t,i){var u=i.Marionette.ItemView.extend({template:"#airports-dropdown-list-item-template",onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.i18n()},ui:{checkbox:"input"},modelEvents:{"change:checked":function(n){_.defer(_.bind(function(){this.ui.checkbox.prop("checked",n.get("checked"))},this))}},events:{click:function(){return this.model.set("checked",!this.model.get("checked")),this.trigger("item:checked"),!1}}}),r=i.Marionette.CompositeView.extend({template:"#airports-dropdown-list-collection-item-template",childView:u,childViewContainer:".js-airports-container",childEvents:{"item:checked":function(){this.trigger("item:selected",this.model)}},onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.i18n();this.hideIfEmpty()},hideIfEmpty:function(){this.collection.length===0?this.$el.hide():this.$el.show()},onBeforeRenderCollection:function(){this.hideIfEmpty()},initialize:function(){this.collection=this.model.get("airports");switch(this.model.get("type")){case"origin":this.model.set("name",$.i18n.t("search-result.filter-menu.airports-origin-airports"));break;case"destination":this.model.set("name",$.i18n.t("search-result.filter-menu.airports-destination-airports"));break;default:throw"not supported";}}}),f=i.Marionette.ItemView.extend({template:"#airports-dropdown-any-item-template",templateHelpers:{isSelected:function(){return typeof this.selected=="boolean"&&this.selected}},ui:{anchor:".js-dropdown-item"},onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.i18n()},modelEvents:{"change:selected":function(n){n.get("selected")?this.ui.anchor.addClass("selected").attr("aria-selected",!0):this.ui.anchor.removeClass("selected").attr("aria-selected",!1)}},events:{"click @ui.anchor":function(n){return n.preventDefault(),this.model.set("selected",!this.model.get("selected")),this.trigger("item:selected",this.model),!1}}});n.AirportsDropdownView=t.Views.DropdownView.extend({className:"class-name-airports",headerView:t.Views.DefaultDropdownHeaderView.extend({template:function(n){return _.template(['<span data-i18n="search-result.filter-menu.airports"><\/span>','<% if (typeof value !== "undefined" && value) { %>',': <span class="dropdown-toggle-value"><%= value %><\/span>','<b class="ss-icon ss-icon-triangle-down active"><\/b>  <b class="ss-icon ss-icon-triangle-up"><\/b>',"<% } else { %>",': <span class="dropdown-toggle-value" data-i18n="search-result.filter-menu.airports-header-any"><\/span>','<b class="ss-icon ss-icon-triangle-down"><\/b>  <b class="ss-icon ss-icon-triangle-up"><\/b>',"<% } %>"].join(""),n)},onRender:function(){this.$el.i18n()}}),getChildView:function(n){switch(n.get("type")){case"any":return f;case"origin":return r;case"destination":return r;default:throw"not supported";}},behaviors:{DropdownExtendedKeysControl:{},DropdownMobileFullscreen:{getHeaderLabel:function(){return'<span class="modal-title" data-i18n="search-result.filter-menu.airports"><\/span>'}},DropdownSlide:{height:360,enabled:function(){return!(t.Utils.Ui.isMobileDevice()&&t.Utils.Ui.isMobileView())}}},select:function(n){var u=this.collection.at(1).get("airports"),f=this.collection.at(2).get("airports"),e=[u,f],t=[],i=0,r;n.get("type")==="any"?(r=n.get("selected"),_.each(e,function(n){n.each(function(n){r&&i++;n.set("checked",r);t.push({code:n.get("Code"),checked:r})})})):(n.get("type")==="origin"||n.get("type")==="destination")&&(_.each(e,function(n){n.each(function(n){var r=n.get("checked");r&&i++;t.push({code:n.get("Code"),checked:r})})}),i===u.length+f.length?this.collection.at(0).set("selected",!0):this.collection.at(0).set("selected",!1));t.length&&(this._updateHeaderView(t,i),this._trackGAEvents(t,i),this.trigger("change",{airports:t}))},splitAirports:function(n){var t=[],i=[];return _.each(n,function(n){n.isOrigin===!0?t.push(n):i.push(n)}),{origin:t,destination:i}},_updateHeaderView:function(n,t){var r,i=_.filter(n,function(n){return n.checked});r=t===n.length?"":i.length>0&&i.length<=3?_.map(i,function(n){return n.code}).join(", "):"("+i.length+")";this.headerView.model.set({value:r})},_trackGAEvents:function(n,i){if(i===1){var r=_.findWhere(n,{checked:!0});t.tracking.trackEvent("day-view","SecondaryFilter","Airports_"+r.code)}else i>1&&t.tracking.trackEvent("day-view","SecondaryFilter","Airports_Many")},reset:function(n){this.onChangeSummary(n,!0)},onChangeSummary:function(n,i){var u=n.get("summary"),r,c,e;if(u&&u.mainAirports&&u.allAirports&&(r=_.filter(u.allAirports,function(n){return n.minPrice}),r=_.sortBy(r,function(n){return n.Name}),_.each(r,function(n){n.wrappedMinPrice=n.minPrice>0?t.Utils.Ui.wrapPrice(n.minPrice,u.currency):"";n.checked=!0;n.name=n.Name?n.Name:"";n.code=n.code?n.code:n.Code}),r.length!==0)){var o=this.collection.at(1).get("airports"),s=this.collection.at(2).get("airports"),h=this.collection.at(0),f=0,l=n.get("filter").airports;i?f=r.length:(c=t.Utils.Filters.airportsChecker(l),_.each(r,function(n){var t=o.findWhere({name:n.name})||s.findWhere({name:n.name});n.checked=t?t.get("checked"):c.isSelected(n);n.checked&&f++}));e=this.splitAirports(r);o.reset(e.origin);s.reset(e.destination);f===r.length?h.set("selected",!0):h.set("selected",!1);this._updateHeaderView(r,f);this.$el.show();this.isAlreadyShown=!0;return}this.$el.hide()},isAlreadyShown:!1,onOpen:function(){var u=$(".js-filter-menu-list"),n=this.$el.find(".js-dropdown-container-wrapper"),i=n.closest(".dropdown"),r;(t.Utils.Ui.isMobileView()||t.Utils.Ui.isTabletView())&&t.Utils.Ui.scrollToCenter(i);t.Utils.Ui.isMobileDevice()&&t.Utils.Ui.isMobileView()||(r=t.Utils.Ui.getFilterMenuLeftPosition(n,i,u),n.css("left",r))},onAfterInitialize:function(){this.collection=new i.Collection([{type:"any"},{type:"origin",airports:new i.Collection},{type:"destination",airports:new i.Collection}])},onAfterRender:function(){this.isAlreadyShown&&this.$el.show()}})});App.module("SearchResult.Filters",function(n,t,i){var r=i.Marionette.ItemView.extend({template:"#airports-dropdown-list-item-template",onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.i18n()},ui:{checkbox:"input"},modelEvents:{"change:checked":function(n){_.defer(_.bind(function(){this.ui.checkbox.prop("checked",n.get("checked"))},this))}},events:{click:function(){return this.model.set("checked",!this.model.get("checked")),this.trigger("item:checked"),!1}}}),u=i.Marionette.CompositeView.extend({template:"#connecting-airports-dropdown-list-collection-item-template",childView:r,childViewContainer:".js-airports-container",childEvents:{"item:checked":function(){this.trigger("item:selected",this.model)}},onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.i18n()},initialize:function(){this.collection=this.model.get("airports")}}),f=i.Marionette.ItemView.extend({template:"#airports-dropdown-any-item-template",templateHelpers:{isSelected:function(){return typeof this.selected=="boolean"&&this.selected}},ui:{anchor:".js-dropdown-item"},onRender:function(){this.$el=this.$el.children();this.$el.unwrap();this.setElement(this.$el);this.$el.i18n()},modelEvents:{"change:selected":function(n){n.get("selected")?this.ui.anchor.addClass("selected"):this.ui.anchor.removeClass("selected")}},events:{click:function(){return this.model.set("selected",!this.model.get("selected")),this.trigger("item:selected",this.model),!1}}});n.ConnectingAirportsFilterView=t.Views.DropdownView.extend({className:"class-name-connecting-airports",headerView:t.Views.DefaultDropdownHeaderView.extend({template:function(n){return _.template(['<span data-i18n="search-result.filter-menu.connecting-airports"><\/span>','<% if (typeof value !== "undefined" && value) { %>',': <span class="dropdown-toggle-value"><%= value %><\/span>','<b class="ss-icon ss-icon-triangle-down active"><\/b>  <b class="ss-icon ss-icon-triangle-up"><\/b>',"<% } else { %>",': <span class="dropdown-toggle-value" data-i18n="search-result.filter-menu.connecting-airports-header-any"><\/span>','<b class="ss-icon ss-icon-triangle-down"><\/b>  <b class="ss-icon ss-icon-triangle-up"><\/b>',"<% } %>"].join(""),n)},onRender:function(){this.$el.i18n()}}),getChildView:function(n){switch(n.get("type")){case"any":return f;case"airports":return u;default:throw"not supported";}},behaviors:{DropdownExtendedKeysControl:{},DropdownSlide:{height:360,enabled:function(){return!(t.Utils.Ui.isMobileDevice()&&t.Utils.Ui.isMobileView())}}},select:function(n){var r=this.collection.at(1).get("airports"),f=this.collection.at(0),t=[],i=0,u;n.get("type")==="any"?(u=n.get("selected"),r.each(function(n){n.set("checked",u);t.push({code:n.get("code"),checked:n.get("checked")})}),i=u?t.length:0):n.get("type")==="airports"&&(r.each(function(n){var r=n.get("checked");r&&i++;t.push({code:n.get("code"),checked:r})}),i===r.length?f.set("selected",!0):f.set("selected",!1));t.length&&(this._updateHeaderView(t,i),this._trackGAEvents(t,i),this.trigger("change",{connectingAirports:t}))},_updateHeaderView:function(n,t){var u,r=n||this.collection.at(1).get("airports").toJSON(),f=t||_.countBy(r,function(n){return n.checked})["true"],i=_.filter(r,function(n){return n.checked});u=f===r.length?"":i.length>0&&i.length<=3?_.map(i,function(n){return n.code}).join(", "):"("+i.length+")";this.headerView.model.set({value:u})},_trackGAEvents:function(n,i){if(i===1){var r=_.findWhere(n,{checked:!0});t.tracking.trackEvent("day-view","SecondaryFilter","ConnectingAirports_"+r.code)}else i>1&&t.tracking.trackEvent("day-view","SecondaryFilter","ConnectingAirports_Many")},reset:function(n){this.onChangeSummary(n,!0)},onChangeSummary:function(n,i){var u=n.get("summary"),h=n.get("filter"),r,s;if(u&&u.boundaryAirports&&u.mainAirports&&u.allAirports&&(r=_.clone(h.connectingAirports),r=_.sortBy(r,function(n){return n.name}),_.each(r,function(n){n.wrappedMinPrice=n.minPrice>0?t.Utils.Ui.wrapPrice(n.minPrice,u.currency):""}),r.length>1)){var e=this.collection.at(1).get("airports"),o=this.collection.at(0),f=0,c=n.get("filter").connectingAirports;i?f=r.length:(s=t.Utils.Filters.airportsChecker(c),_.each(r,function(n){var t=e.findWhere({name:n.name});n.checked=t?t.get("checked"):s.isSelected(n);n.checked&&f++}));e.reset(r);f===r.length?o.set("selected",!0):o.set("selected",!1);this._updateHeaderView(r,f);this.$el.show();return}this.$el.hide()},onOpen:function(){var u=$(".js-filter-menu-list"),n=this.$el.find(".js-dropdown-container-wrapper"),i=n.closest(".dropdown"),r;(t.Utils.Ui.isMobileView()||t.Utils.Ui.isTabletView())&&t.Utils.Ui.scrollToCenter(i);t.Utils.Ui.isMobileDevice()&&t.Utils.Ui.isMobileView()||(r=t.Utils.Ui.getFilterMenuLeftPosition(n,i,u),n.css("left",r))},onAfterInitialize:function(){this.collection=new i.Collection([{type:"any"},{type:"airports",airports:new i.Collection}])}})});App.module("SearchResult.Filters",function(n,t){var i=function(n){var t=n>1?"search-result.filter-menu.duration-hrs_plural":"search-result.filter-menu.duration-hrs_singular";return $.i18n.t(t).replace("__hours__",n.toString())};n.DurationDropdownView=t.Views.DropdownView.extend({className:"class-name-duration",headerView:t.Views.DefaultDropdownHeaderView.extend({template:"#duration-dropdown-header-template"}),childView:t.Views.DefaultDropdownItemView.extend({template:"#duration-dropdown-list-item-template",getTime:function(n){return parseInt(n/6e5,10)},getHoursTranslation:i,onRender:function(){var n,t,u,i,f,r;if(this.$el=this.$el.children(),this.$el.unwrap(),this.setElement(this.$el),n=this.model.get("outbound"),t=this.model.get("inbound"),n){u=$.Link({target:'-tooltip-<div class="tooltip"><\/div>',method:_.bind(function(n){var t=this.getTime(n);this.$el.find(".js-outbound .js-max-duration").text(this.getHoursTranslation(t))},this)});i=this.$el.find(".js-outbound .js-slider");i.noUiSlider({range:{min:n.min,max:n.max},start:n.start,connect:n.connect,serialization:{lower:[u]},aria:{label:$.t("aria.filter-menu.duration-outbound"),orientation:"horizontal",minvalue:n.min,maxvalue:n.max,valuenow:n.start,getValueText:_.bind(function(n){var t=this.getTime(n);return this.getHoursTranslation(t)},this)}});i.on({set:_.bind(function(){n.start=parseInt(i.val(),10);this.model.set("outbound",n);this.trigger("change",this.model)},this)});i.find(".noUi-handle").addClass("js-control-item")}if(t){f=$.Link({target:'-tooltip-<div class="tooltip"><\/div>',method:_.bind(function(n){var t=parseInt(n/6e5,10);this.$el.find(".js-inbound .js-max-duration").text(this.getHoursTranslation(t))},this)});r=this.$el.find(".js-inbound .js-slider");r.noUiSlider({range:{min:t.min,max:t.max},start:t.start,connect:t.connect,serialization:{lower:[f]},aria:{label:$.t("aria.filter-menu.duration-inbound"),orientation:"horizontal",minvalue:t.min,maxvalue:t.max,valuenow:t.start,getValueText:_.bind(function(n){var t=this.getTime(n);return this.getHoursTranslation(t)},this)}});r.on({set:_.bind(function(){t.start=parseInt(r.val(),10);this.model.set("inbound",t);this.trigger("change",this.model)},this)});r.find(".noUi-handle").addClass("js-control-item")}this.$el.find(".js-duration-points").i18n();this.$el.i18n()}}),onOpen:function(){var u=$(".js-filter-menu-list"),n=this.ui.itemsContainerWrapper,i=n.closest(".js-scrollable-item"),r;(t.Utils.Ui.isMobileView()||t.Utils.Ui.isTabletView())&&t.Utils.Ui.scrollToCenter(i);r=t.Utils.Ui.getFilterMenuLeftPosition(n,i,u);n.css("left",r)},childEvents:{change:function(n){this.onChangeDuration(n.model)}},_updateHeaderView:function(){var n=this.model.get("duration"),i,t,r,u;n&&(i=$.i18n.t("search-result.filter-menu.duration-header-any"),t=i,n.outbound.start!==n.outbound.max&&(t="< "+this.getHoursTranslation(parseInt(n.outbound.start/6e5,10))),r=t,n.inbound&&(u="< "+this.getHoursTranslation(parseInt(n.inbound.start/6e5,10)),n.inbound.start===n.inbound.max&&(u=i),r=t===i&&t===u?"":t+"; "+u),r===i&&(r=""),this.headerView.model.set({value:r}))},onChangeDuration:function(n){var r=n.get("outbound"),i=n.get("inbound"),u;this.trigger("change",{duration:{outbound:parseInt(r.start/1e4,10),inbound:i?parseInt(i.start/1e4,10):null,outboundMax:r.start===r.max,inboundMax:i?i.start===i.max:!1}});this.model.set({duration:{outbound:r,inbound:i}});this._updateHeaderView();u="TripDuration_"+parseInt(r.min/6e5,10)+"_"+parseInt(r.start/6e5,10);i&&(u+="_"+parseInt(i.min/6e5,10)+"_"+parseInt(i.start/6e5,10));t.tracking.trackEvent("day-view","SecondaryFilter",u)},reset:function(n){this.$el.removeClass("active");this.onChangeSummary(n);this.headerView.model.set({value:""})},select:function(){},checkDuration:function(n){var t=!0;return n?!n.inbound&&n.outbound&&n.outbound.minDuration===n.outbound.maxDuration?t=!1:n.inbound&&n.inbound.minDuration===n.inbound.maxDuration&&n.outbound&&n.outbound.minDuration===n.outbound.maxDuration&&(t=!1):t=!1,t},onChangeSummary:function(n){var t=n.get("summary"),f=this.checkDuration(t),u,i,r;f?this.trigger("show"):this.trigger("hide");u=n.get("filter");t&&t.outbound&&(i=t.outbound.maxDuration,r=t.inbound?t.inbound.maxDuration:null,u&&u.duration&&(u.duration.outboundMax||(i=u.duration.outbound,i=i<t.outbound.minDuration?t.outbound.minDuration:i,i=i>t.outbound.maxDuration?t.outbound.maxDuration:i),t.inbound&&u.duration.inbound&&!u.duration.inboundMax&&(r=u.duration.inbound,r=r<t.inbound.minDuration?t.inbound.minDuration:r,r=r>t.inbound.maxDuration?t.inbound.maxDuration:r)),this.collection.reset([{outbound:{min:parseInt(t.outbound.minDuration*1e4,10),max:parseInt(t.outbound.maxDuration*1e4,10),start:parseInt(i,10)*1e4,minTitle:this.getHoursTranslation(parseInt(t.outbound.minDuration/60,10)),maxTitle:this.getHoursTranslation(parseInt(t.outbound.maxDuration/60,10)),connect:"lower"},inbound:t.inbound?{min:parseInt(t.inbound.minDuration*1e4,10),max:parseInt(t.inbound.maxDuration*1e4,10),start:parseInt(r,10)*1e4,minTitle:this.getHoursTranslation(parseInt(t.inbound.minDuration/60,10)),maxTitle:this.getHoursTranslation(parseInt(t.inbound.maxDuration/60,10)),connect:"lower"}:null}]))},getHoursTranslation:i,getInitialState:function(){return this.model.set({value:""}),this.model},initialize:function(n){n&&n.model||(this.model=new Backbone.Model);this.templateHelpers.tabindex=n&&n.tabindex?n.tabindex:this.templateHelpers.tabindex;this.templateHelpers.ariaLabel=n&&n.ariaLabel?n.ariaLabel:this.templateHelpers.ariaLabel;this.collection=new Backbone.Collection;this.selected=this.getInitialState&&typeof this.getInitialState=="function"?this.getInitialState().clone():this.model.clone();this._bindEvents();this.onAfterInitialize&&typeof this.onAfterInitialize=="function"&&this.onAfterInitialize()}})});App.module("SearchResult.Filters",function(n,t,i){n.SortFilterView=i.Marionette.ItemView.extend({className:"dropdown class-name-sort",template:function(n){return _.template(['<a href="#" class="dropdown-toggle js-dropdown-toggle">','<span data-i18n="search-result.filter-menu.sort"><\/span>',': <span class="dropdown-toggle-value" data-i18n="<%= name %>"><\/span>',"<\/a>"].join(""),n)},events:{"click .js-dropdown-toggle":"onClickHandler"},ui:{toggleContainer:".js-dropdown-toggle"},_trackGAEvent:function(n){switch(n){case"price":t.tracking.trackEvent("day-view","SecondaryFilter","PriceSort");break;case"journey-duration":t.tracking.trackEvent("day-view","SecondaryFilter","TripDurationSort")}},setValue:function(n){this.model=n;this.render();this._trackGAEvent(n.get("value"));this.trigger("change",{sort:{type:n.get("value")}})},onClickHandler:function(n){n.preventDefault();t.GlobalEvents.trigger("global:click",n);var i=this.collection.indexOf(this.model);return i++,i>=this.collection.length&&(i=0),this.setValue(this.collection.at(i)),this.ui.toggleContainer.focus(),(t.Utils.Ui.isMobileView()||t.Utils.Ui.isTabletView())&&t.Utils.Ui.scrollToCenter(this.$el),!1},onRender:function(){this.$el.i18n()},reset:function(){},initialize:function(n){this.collection=new i.Collection(t.Dictionaries.SortList);this.model=this.collection.findWhere({value:n.type})}})});App.module("SearchResult.Filters",function(n,t){n.StopsDropdownView=t.Views.DropdownView.extend({className:"class-name-stops",headerView:t.Views.DefaultDropdownHeaderView.extend({template:function(n){return _.template(['<span data-i18n="search-result.filter-menu.stops"><\/span>',"<% if (name && count !== -1) { %>",': <span class="dropdown-toggle-value" data-i18n="<%= name %>"><\/span>','<b class="ss-icon-triangle-down ss-icon active"><\/b>  <b class="ss-icon-triangle-up ss-icon active"><\/b>',"<% } else { %>",': <span class="dropdown-toggle-value" data-i18n="search-result.filter-menu.stops-header-any"><\/span>','<b class="ss-icon-triangle-down ss-icon"><\/b>  <b class="ss-icon-triangle-up ss-icon"><\/b>',"<% } %>"].join(""),n)},onRender:function(){this.model.get("name")&&this.model.get("count")!==-1?this.$el.parents(".js-dropdown-toggle").first().addClass("active"):this.$el.parents(".js-dropdown-toggle").first().removeClass("active");this.$el.i18n()}}),childView:t.Views.DefaultDropdownItemView.extend({template:function(n){return _.template(["<li>","<a href role=\"menuitem\" aria-checked=\"<%= isSelected() %>\" class=\"dropdown-item js-dropdown-item js-control-item<%- isSelected() ? ' selected': '' %><%- isDisabled() ? ' disabled': '' %>\">",'<i class="ss-icon-tick ss-icon"><\/i><span data-value="<%= value %>" data-i18n="<%= name %>"><\/span>',"<\/a>","<\/li>"].join(""),n)},templateHelpers:{isSelected:function(){return typeof this.selected=="boolean"&&this.selected},isDisabled:function(){return typeof this.disabled=="boolean"&&this.disabled}},modelEvents:_.extend(t.Views.DefaultDropdownItemView.prototype.modelEvents,{"change:selected":function(n){n.get("selected")===!1?this.ui.anchor.removeClass("selected").attr("aria-checked",!1):this.ui.anchor.addClass("selected").attr("aria-checked",!0)},"change:disabled":function(n){n.get("disabled")===!1?(this.ui.anchor.removeClass("disabled"),this.ui.anchor.addClass("js-control-item")):(this.ui.anchor.addClass("disabled"),this.ui.anchor.removeClass("js-control-item"))}})}),behaviors:{DropdownExtendedKeysControl:{},DropdownMobileFullscreen:{getHeaderLabel:function(){return'<span class="modal-title" data-i18n="search-result.filter-menu.stops"><\/span>'}}},select:function(n){n.get("disabled")||(n.get("active")&&n.set("active",!1),this.selected&&this.selected.get("count")!==n.get("count")&&(this.collection.each(function(n){n.set("selected",!1)}),n.set("selected",!0),this.selected.set(n.toJSON()),this.headerView.model.set(n.toJSON()),this.trigger("change",{stops:n.get("value")}),this._trackGAEvent(n.get("value"))),this.close(),this.focus())},onChangeSummary:function(n){var t=n.get("summary"),i=n.get("filter"),r=this;this.collection.each(_.bind(function(n){n.get("count")>-1&&t&&t.stopsDistribution&&t.stopsDistribution.length>0&&n.set("disabled",t.stopsDistribution[n.get("count")].number===0);var u=i&&i.stops&&n.get("value")===i.stops;n.set("selected",u);u&&(r.selected=n.clone());n.get("selected")===!0&&this.headerView.model.set(n.toJSON())},this))},reset:function(n){this.$el.removeClass("active");this.onChangeSummary(n)},getInitialState:function(){return this.collection.find(_.bind(function(n){return n.get("value")===this.model.get("filter")},this))},onOpen:function(){var u=$(".js-filter-menu-list"),n=this.$el.find(".js-dropdown-container-wrapper"),i=n.closest(".dropdown"),r;(t.Utils.Ui.isMobileView()||t.Utils.Ui.isTabletView())&&t.Utils.Ui.scrollToCenter(i);t.Utils.Ui.isMobileDevice()&&t.Utils.Ui.isMobileView()||(r=t.Utils.Ui.getFilterMenuLeftPosition(n,i,u),n.css("left",r))},_trackGAEvent:function(n){var i="";switch(n){case"direct":i="Stops_Direct";break;case"1stop":i="Stops_1Stop";break;case"2stops":i="Stops_2Stops";break;default:return}t.tracking.trackEvent("day-view","SecondaryFilter",i)}})});App.module("SearchResult.Filters",function(n,t,i){n.AirlinesFilterOption=t.SearchResult.Filters.FilterDropdownMultiselectItemBase.extend({template:"#airlines-filter-option",templateHelpers:{getWrappedPrice:function(){var n=t.Services.Currency.getCurrencySync();return this.data.minPrice>0?t.Utils.Ui.wrapPrice(this.data.minPrice,n):""}}});n.AlliancesFilterOptions=i.Marionette.CollectionView.extend({childView:t.SearchResult.Filters.FilterDropdownItemBase,childEvents:{"item:select":"onSelectionChange"},onSelectionChange:function(n,t){this.collection.forEach(function(n){n!==t&&n.set("selected",!1)});this.collection.trigger("reset");this.trigger("item:check",t)}});n.AirlinesFilterView=t.SearchResult.Filters.FilterDropdownBase.extend({childView:n.AirlinesFilterOption,childEvents:_.extend({},t.SearchResult.Filters.FilterDropdownBase.prototype.childEvents,{"item:only":"onOnlyButtonClick"}),alliancesView:n.AlliancesFilterOptions,multiselect:function(){t.SearchResult.Filters.FilterDropdownBase.prototype.multiselect.apply(this,arguments);var n=this._getInvertedValue();n.not=n.not||[];t.tracking.trackEvent("day-view","Filter_Airlines",n.not.join("_")||"any")},onOnlyButtonClick:function(n,i){t.tracking.trackEvent("day-view","Filter_Airlines_Only",i.get("value"))},_triggerChangeEvent:function(){var n=this._getInvertedValue();this._updateAlliancesCollection();this.trigger("change",{airlinesv2:n})},_getInvertedValue:function(){var n={};return this.getValue()&&(n.not=_.map(this.getInvertedSelection(),function(n){return parseInt(n.get("value"),10)})),n},_onSummaryUpdate:function(n){var t=n.get("summary"),i=n.get("filter")||{};t&&(this.setCollection(this._getAirlinesCollection(t,i.airlinesv2)),this.setAlliancesCollection(),this._updateAlliancesCollection())},_initAlliancesView:function(){if(typeof this.alliancesView=="function"){this.alliancesView=new this.alliancesView({collection:new t.SearchResult.Models.DropdownCollection});this.ui.resetButton.after(this.alliancesView.render().$el);this.alliancesView.on("item:check",this._onAllianceSelected,this)}},setAlliancesCollection:function(){this.alliancesView.collection.reset(this._getAlliances(t.Dictionaries.AirlineAlliances));this.model.set("selection",this.getSelection())},_getAlliances:function(n){var r=this.collection,t=this.getValue(),i=[];return _.each(n,function(n){var u=[],f;r.forEach(function(t){n.airlines.indexOf(parseInt(t.get("value"),10))>-1&&u.push(t)});f=_.intersection(t,u);u.length>0&&i.push({value:n.name,text:$.t(n.translatedName),selected:f.length===t.length&&t.length===u.length,data:u})}),i.length>1?i:[]},_onAllianceSelected:function(n){var r=n.get("data"),i;_.each(r,function(n){n.set("selected",!0)});this.setValue(r);i=this._getInvertedValue();i.not=i.not||[];t.tracking.trackEvent("day-view","Filter_Airlines",i.not.join("_")||"any");this._triggerChangeEvent()},_getAirlinesCollection:function(n,t){var i=[];return _.each(n.airlines,_.bind(function(n){if(n.filterable&&n.minPrice){var r=this._getAirlineModel(n);r.selected=!t||!t.not||t.not.indexOf(n.id)===-1;i.push(r)}},this)),i},_getAirlineModel:function(n){return{data:n,selected:!0,value:n.id.toString(),text:n.name}},_updateAlliancesCollection:function(){var n=this.getValue();this.alliancesView.collection.forEach(function(t){var i=t.get("data"),r=_.intersection(n,i);t.set("selected",r.length===n.length&&n.length===i.length)});this.alliancesView.collection.trigger("reset")},onRender:function(){t.SearchResult.Filters.FilterDropdownBase.prototype.onRender.apply(this,arguments);this._initAlliancesView()},initialize:function(){var n={model:{label:$.t("search-result.filter-menu.airlines"),icon:"ss-icon-flights",multiselect:!0,resetText:$.t("search-result.filter-menu.airlines-header-any")}};t.SearchResult.Filters.FilterDropdownBase.prototype.initialize.apply(this,[n]);this.on("change:summary",_.bind(this._onSummaryUpdate,this))}})});App.module("SearchResult.Filters",function(n,t){n.AirportsFilterGroupItemView=t.SearchResult.Filters.FilterDropdownGroupOption.extend({template:"#airports-filter-dropdown-option-template",templateHelpers:{getWrappedPrice:function(){var n=t.Services.Currency.getCurrencySync();return this.data.minPrice?t.Utils.Ui.wrapPrice(this.data.minPrice,n):""}}});n.AirportsFilterGroupView=t.SearchResult.Filters.FilterDropdownGroup.extend({childView:n.AirportsFilterGroupItemView});n.AirportsFilterView=t.SearchResult.Filters.FilterDropdownGrouped.extend({childView:n.AirportsFilterGroupView,_onSummaryUpdate:function(n){var r=n.get("summary"),u=n.get("filter")||{},t,i=[];r&&(t=this._getAirportsCollection(r,u.airportsv2),t.origin.length>1&&i.push({title:$.t("search-result.filter-menu.airports-origin-airports"),type:"origin",options:t.origin}),t.destination.length>1&&i.push({title:$.t("search-result.filter-menu.airports-destination-airports"),type:"destination",options:t.destination}),t.connecting.length>1&&i.push({title:$.t("search-result.filter-menu.connecting-airports"),type:"connecting",options:t.connecting}),this.setCollection(i))},_getAirportsCollection:function(n,t){var r=n.allAirports,u=_.indexBy(n.ca,"code"),i={origin:[],destination:[],connecting:[]};return r=_.sortBy(r,function(n){return n.Name})||[],_.each(r,_.bind(function(n){var r=this._getAirportModel(n,t);u[n.Code]?(r.data.minPrice=u[n.Code].minPrice,i.connecting.push(r)):n.isOrigin?i.origin.push(r):i.destination.push(r)},this)),i},_getAirportModel:function(n,t){return{data:n,selected:!t||!t.not||t.not.indexOf(n.Code)===-1,value:n.Code,text:n.Name}},_triggerChangeEvent:function(){var n=this._getInvertedValue();this.trigger("change",{airportsv2:n})},multiselect:function(){t.SearchResult.Filters.FilterDropdownSlider.prototype.multiselect.apply(this,arguments);var n=this._getInvertedValue();n.not=n.not||[];t.tracking.trackEvent("day-view","Filter_Airports",n.not.join("_")||"any")},_getInvertedValue:function(){var n={};return this.getValue()&&(n.not=_.map(this.getInvertedSelection(),function(n){return n.get("value")})),n},initialize:function(){var n={model:{label:$.t("search-result.filter-menu.airports"),icon:"ss-icon-airport",multiselect:!0,resetText:$.t("search-result.filter-menu.airports-any")}};t.SearchResult.Filters.FilterDropdownGrouped.prototype.initialize.apply(this,[n]);this.on("change:summary",_.bind(this._onSummaryUpdate,this))}})});App.module("SearchResult.Filters",function(n,t){n.DurationFilterView=t.SearchResult.Filters.FilterDropdownSlider.extend({_onSummaryUpdate:function(n){var r=n.get("summary"),u=n.get("filter"),f,i,e=[];r&&(f=r.outbound.minDuration,i=r.outbound.maxDuration,e=[],e.push({max:i,min:f,type:"outbound",label:$.t("search-result.filter-menu.duration-outbound"),value:u&&u.duration&&u.duration.outbound||i,ariaLabel:$.t("search-result.filter-menu.duration-outbound"),serialization:t.Utils.Sliders.getLegDurationTooltip(f,i)}),r.inbound&&(f=r.inbound.minDuration,i=r.inbound.maxDuration,e.push({max:i,min:f,type:"inbound",label:$.t("search-result.filter-menu.duration-inbound"),value:u&&u.duration&&u.duration.inbound||i,ariaLabel:$.t("search-result.filter-menu.duration-inbound"),serialization:t.Utils.Sliders.getLegDurationTooltip(f,i)})),this.setCollection(e))},_triggerChangeEvent:function(){var n=this._getChanges();this.trigger("change",{duration:n.outbound?n:null})},multiselect:function(){t.SearchResult.Filters.FilterDropdownSlider.prototype.multiselect.apply(this,arguments);var n=this._getChanges(),i=n.outbound||"any",r=n.inbound||"any";t.tracking.trackEvent("day-view","Filter_Duration",i+"_"+r)},initialize:function(){var n={model:{label:$.t("search-result.filter-menu.duration"),icon:"ss-icon-duration"}};t.SearchResult.Filters.FilterDropdownSlider.prototype.initialize.apply(this,[n]);this.on("change:summary",_.bind(this._onSummaryUpdate,this))}})});App.module("SearchResult.Filters",function(n,t,i){n.MobileFilterMenuSubheader=i.Marionette.ItemView.extend({template:"#mobile-filter-subheader-template",ui:{resultsCountIndicator:".js-results-count",resetButton:".js-reset-button"},events:{"click @ui.resetButton":"_onResetClick"},_onResetClick:function(){this.trigger("reset:click")},onSummaryChanged:function(){this.countIndicator.update(this.model)},onRender:function(){this.countIndicator||(this.countIndicator=new t.SearchResult.Views.FlightsCountIndicatorView({el:this.ui.resultsCountIndicator,disableResetButton:!0,showSpinner:!0}))},initialize:function(n){this.model=n.model}});n.MobileFilterMenu=i.Marionette.ItemView.extend({template:"#base-dropdown-fullscreen-template",_title:"",ui:{modal:".js-modal",backButton:".js-back-btn",closeButton:".js-cancel-btn",subheader:".js-modal-subheader",headerTitle:".js-modal-header-title",itemsContainerWrapper:".js-dropdown-container-wrapper"},onSummaryChanged:function(n){var t=n.get("summary");this.fsview.triggerMethod("summary:changed",n);this.subheaderView.triggerMethod("summary:changed")},onChangeFilter:function(){this.subheaderView.triggerMethod("summary:changed")},onRender:function(){this.trigger("before:render-dropdown");this.fsview=new t.SearchResult.Filters.FilterMenuView({model:new i.Model({filter:this.model.get("filter")})});this.fsview.on("changeFilterEvent",this._onFilterMenuChanged,this);this.fsview.on("filter:open",this._onFilterOpen,this);this.fsview.on("filter:close",this._onFilterClose,this);this.ui.itemsContainerWrapper.html(this.fsview.render().$el);this.subheaderView=new n.MobileFilterMenuSubheader({model:this.model});this.subheaderView.on("reset:click",this._onResetClick,this);this.ui.subheader.html(this.subheaderView.render().$el);this.$el.i18n();this.ui.modal.addClass("filters-b");this.ui.backButton.on("click",_.bind(this._onBackClick,this));this.ui.closeButton.on("click",_.bind(this._onCloseClick,this))},onDestroy:function(){(this.close(),this.subheaderView.destroy(),this.ui.backButton.off(),this.ui.closeButton.off(),this.fsview)&&(this.fsview.off(),this.fsview.destroy())},_onResetClick:function(){this._openedFilter&&this._openedFilter.close();this.trigger("reset:filter",this.model);this.fsview.triggerMethod("reset:filters",this.model)},_onFilterOpen:function(n){var t=n.model.get("label");this.ui.itemsContainerWrapper.addClass("filter-opened");this.ui.headerTitle.text(t);this._openedFilter=n},_onFilterClose:function(){var n=this._title;this.ui.itemsContainerWrapper.removeClass("filter-opened");this.ui.headerTitle.text(n);this._openedFilter=null},_onFilterMenuChanged:function(n){this.trigger("changeFilterEvent",n)},_onBackClick:function(){this._openedFilter?this._openedFilter.close():this.close()},_onCloseClick:function(){this.close()},open:function(){this.ui.modal.appendTo(t.Utils.Ui.bodySelector).show();$("html").addClass("has-overlay")},close:function(){this._openedFilter&&this._openedFilter.close();this.ui.modal.detach().hide();$("html").removeClass("has-overlay")},initialize:function(n){this.model=n&&n.model||new i.model({});this._title=$.t("hotels.search-result.filters.subtitle");this.model.set("headerLabel",this._title);i.Marionette.ItemView.prototype.initialize()}})});App.module("SearchResult.Filters",function(n,t){n.PriceFilterView=t.SearchResult.Filters.FilterDropdownSlider.extend({_onSummaryUpdate:function(n){var i=n.get("summary"),f=n.get("filter"),r,u,e;i&&i.dearest&&i.cheapest&&(r=i.dearest.price,u=i.cheapest.price,e=i.currency,this.setCollection([{max:r,min:u,type:"priceMax",value:f&&f.priceMax||i.dearest.price,ariaLabel:$.t("sliders.price.title"),serialization:t.Utils.Sliders.getCurrencyToolTip(e,r,u)}]))},_triggerChangeEvent:function(){var n=this._getChanges();this.trigger("change",n)},multiselect:function(){t.SearchResult.Filters.FilterDropdownSlider.prototype.multiselect.apply(this,arguments);var n=this._getChanges();t.tracking.trackEvent("day-view","Filter_Price",n.priceMax||"any")},initialize:function(){var n={model:{label:$.t("search-result.filter-menu.price"),icon:"ss-icon-currency"}};t.SearchResult.Filters.FilterDropdownSlider.prototype.initialize.apply(this,[n]);this.on("change:summary",_.bind(this._onSummaryUpdate,this))}})});App.module("SearchResult.Filters",function(n,t){n.StopsFilterView=t.SearchResult.Filters.FilterDropdownBase.extend({_triggerChangeEvent:function(){var n=this.getSerializedValue();this.trigger("change",{stops:n})},select:function(){t.SearchResult.Filters.FilterDropdownBase.prototype.select.apply(this,arguments);var n=this.getSerializedValue();t.tracking.trackEvent("day-view","Filter_Stops",n)},getSerializedValue:function(){var n=this.getValue(),t=n&&n[0];return t?t.get("value"):"any"},_onResetButtonClick:function(){t.tracking.trackEvent("day-view","Filter_Stops","any");t.SearchResult.Filters.FilterDropdownBase.prototype._onResetButtonClick.apply(this,arguments)},initialize:function(n){var i,r;i=_.filter(t.Dictionaries.StopsList,function(n){return n.value!=="any"});r={model:{label:$.t("search-result.filter-menu.stops"),icon:"ss-icon-stops",resetText:$.t("search-result.filter-menu.stops-list.any")},collection:_.map(i,function(t){return{value:t.value,text:$.t(t.name),selected:t.value===n.stops}})};t.SearchResult.Filters.FilterDropdownBase.prototype.initialize.apply(this,[r])}})});App.module("SearchResult.Filters",function(n,t){n.TimesFilterView=t.SearchResult.Filters.FilterDropdownSlider.extend({_onSummaryUpdate:function(n){var e=n.get("summary"),u=n.get("filter"),f,r,i,o=[],s=9e5;e&&(f=t.Services.Flights.getSliderRangeInfo(e,u),r=f.minOutBoundTime,i=f.maxOutBoundTime,i=r===i?i+36e5:i,o.push({max:i,min:r,step:s,type:"outbound",label:$.t("sliders.depart"),values:u&&u.times&&u.times.outbound||[r,i],ariaLabel:$.t("sliders.depart"),serialization:t.Utils.Sliders.getTimeToolTip(r,i)}),e.inbound&&(r=f.minInBoundTime,i=f.maxInBoundTime,i=r===i?i+36e5:i,o.push({max:i,min:r,step:s,type:"inbound",label:$.t("sliders.return"),values:u&&u.times&&u.times.inbound||[r,i],ariaLabel:$.t("sliders.return"),serialization:t.Utils.Sliders.getTimeToolTip(r,i)})),this.setCollection(o))},_triggerChangeEvent:function(){var n=this._getChanges();this.trigger("change",{times:n})},multiselect:function(){t.SearchResult.Filters.FilterDropdownSlider.prototype.multiselect.apply(this,arguments);var r=this._getChanges(),n=[],i=[];_.each(r.outbound,function(i){n.push(t.Culture.culture.formatDate(new Date(Math.ceil(i)),{time:"short"}))});_.each(r.inbound,function(n){i.push(t.Culture.culture.formatDate(new Date(Math.ceil(n)),{time:"short"}))});n=n.join("-")||"any";i=i.join("-")||"any";t.tracking.trackEvent("day-view","Filter_Times",n+"_"+i)},initialize:function(){var n={model:{label:$.t("search-result.filter-menu.times"),icon:"ss-icon-time"}};t.SearchResult.Filters.FilterDropdownSlider.prototype.initialize.apply(this,[n]);this.on("change:summary",_.bind(this._onSummaryUpdate,this))}})});App.module("SearchResult.Filters",function(n,t,i,r){n.FilterMenuView=r.CompositeView.extend({template:"#list-filter-menu-template",ui:{stopsDropDown:".js-stops-wrapper",airportsDropDown:".js-airports-wrapper",airlinesDropDown:".js-airlines-wrapper",connectingAirportsDropDown:".js-connecting-airports-wrapper",tripDurationDropDowm:".js-trip-duration-wrapper",sortDropDown:".js-sort-wrapper",aggregationDropDown:".js-aggregation-wrapper",priceDropdown:".js-price-wrapper",timesDropdown:".js-times-wrapper",filterMenuList:".js-filter-menu-list",filterWrapper:".js-itinerary-list-filter-menu"},initialize:function(){this.$el.hide()},onSummaryChanged:function(n){var t=n.get("summary");t&&t.flightsNumber>0?this.$el.show():this.$el.hide();_.each(this.viewsArray,function(t){t.triggerMethod("change:summary",n)})},onResetFilters:function(n){this._resetting=!0;_.each(this.viewsArray,function(t){t.reset&&t.reset(n)});this._resetting=!1;t.vent.trigger(t.VentActions.Filters.RESET)},_initializeStopsFilter:function(){var r=this.model.get("filter"),n=new t.SearchResult.Filters.StopsDropdownView({model:new i.Model({type:"stops",filter:r&&r.stops||"any"}),collection:new i.Collection(t.Dictionaries.StopsList)});this.ui.stopsDropDown.html(n.render().$el);n.on("change",this.onFilterChanged,this);n.on("open",this.onFilterOpen,this);n.on("close",this.onFilterClose,this);return n},_initializeAirlinesFilter:function(){var n=new t.SearchResult.Filters.AirlinesDropdownView;this.ui.airlinesDropDown.html(n.render().$el);n.on("change",this.onFilterChanged,this);n.on("open",this.onFilterOpen,this);n.on("close",this.onFilterClose,this);return n},_initializeAirportsFilterView:function(){var n=new t.SearchResult.Filters.AirportsDropdownView;this.ui.airportsDropDown.html(n.render().$el);n.on("change",this.onFilterChanged,this);n.on("open",this.onFilterOpen,this);n.on("close",this.onFilterClose,this);return n},_initializeConnectionAirportsFilter:function(){var n=new t.SearchResult.Filters.ConnectingAirportsFilterView;this.ui.connectingAirportsDropDown.html(n.render().$el);n.on("change",this.onFilterChanged,this);n.on("open",this.onFilterOpen,this);n.on("close",this.onFilterClose,this);return n},_initializeTripDurationFilter:function(){var n=new t.SearchResult.Filters.DurationDropdownView;this.ui.tripDurationDropDowm.html(n.render().$el);n.on("change",this.onFilterChanged,this);n.on("open",this.onFilterOpen,this);n.on("close",this.onFilterClose,this);return n},_initializeAggregatedFilter:function(){var r=new i.Collection([{view:t.SearchResult.Filters.DurationDropdownView},{view:t.SearchResult.Filters.ConnectingAirportsFilterView}]),n=new t.SearchResult.Filters.AggregationDropdownView({collection:r});this.ui.aggregationDropDown.html(n.render().$el);n.on("open",this.onFilterOpen,this);n.on("close",this.onFilterClose,this);n.on("change",this.onFilterChanged,this);return n},_initializeSortFilter:function(){var i=this.model.get("filter").sort,n=new t.SearchResult.Filters.SortFilterView({type:i?i.type:"price"});this.ui.sortDropDown.html(n.render().$el);n.on("change",function(n){this.ui.filterWrapper.removeClass("focused");this.onFilterChanged(n);this.onSetPage(n)},this);return n},_initStopsFilter:function(){var n,i=this.model.get("filter");n=new t.SearchResult.Filters.StopsFilterView(i);n.on("change",this.onFilterChanged,this);n.on("open",this.onFilterOpen,this);n.on("close",this.onFilterClose,this);return this.ui.stopsDropDown.html(n.render().$el),n},_initAirlinesFilter:function(){var n=new t.SearchResult.Filters.AirlinesFilterView;n.on("change",this.onFilterChanged,this);n.on("open",this.onFilterOpen,this);n.on("close",this.onFilterClose,this);return this.ui.airlinesDropDown.html(n.render().$el),n},_initAirportsFilter:function(){var i=this.model.get("filter"),n=new t.SearchResult.Filters.AirportsFilterView;n.on("change",this.onFilterChanged,this);n.on("open",this.onFilterOpen,this);n.on("close",this.onFilterClose,this);return this.ui.airportsDropDown.html(n.render().$el),n},_initDurationFilter:function(){var n=new t.SearchResult.Filters.DurationFilterView;n.on("change",this.onFilterChanged,this);n.on("open",this.onFilterOpen,this);n.on("close",this.onFilterClose,this);return this.ui.tripDurationDropDowm.html(n.render().$el),n},_initPriceFilter:function(){var n=new t.SearchResult.Filters.PriceFilterView;n.on("change",this.onFilterChanged,this);n.on("open",this.onFilterOpen,this);n.on("close",this.onFilterClose,this);return this.ui.priceDropdown.html(n.render().$el),n},_initTimesFilter:function(){var n=new t.SearchResult.Filters.TimesFilterView;n.on("change",this.onFilterChanged,this);n.on("open",this.onFilterOpen,this);n.on("close",this.onFilterClose,this);return this.ui.timesDropdown.html(n.render().$el),n},onRender:function(){this.viewsArray=[];t.Services.Feature.check("filters","b")?(this.viewsArray.push(this._initStopsFilter()),this.viewsArray.push(this._initAirlinesFilter()),this.viewsArray.push(this._initAirportsFilter()),this.viewsArray.push(this._initDurationFilter()),this.viewsArray.push(this._initPriceFilter()),this.viewsArray.push(this._initTimesFilter())):this._initOldFilters();t.Utils.Ui.is2xAndroid()&&t.Utils.Ui.makeScrollable(this.ui.filterMenuList);this.ui.filterMenuList.on("scroll",_.bind(this.onScrollFilterMenuList,this))},_initOldFilters:function(){this.viewsArray.push(this._initializeStopsFilter());this.viewsArray.push(this._initializeAirlinesFilter());this.viewsArray.push(this._initializeSortFilter());this.viewsArray.push(this._initializeAirportsFilterView());this.viewsArray.push(this._initializeAggregatedFilter())},onScrollFilterMenuList:function(){var i,n,r;t.Utils.Ui.is41Android()&&this.ui.filterWrapper.hasClass("focused")||(i=$(t.Utils.Ui.bodySelector),n=i.attr("data-js-scroll"),n!=="ignore")&&(r=n?$.parseJSON(n):n,r||(this.ui.filterWrapper.removeClass("focused"),_.each(this.viewsArray,function(n){n.close?n.close():(n.$el.removeClass("selected"),n.list&&n.list.currentView.$el.hide())})),i.attr("data-js-scroll",!1))},onSetPage:function(n){t.Utils.Ui.trigger("inactive-veil:enable","SearchResultListView");this.trigger("setFirstPageEvent",n)},onFilterChanged:function(n){t.Utils.Ui.trigger("inactive-veil:enable","SearchResultListView");this._resetting||t.vent.trigger(t.VentActions.Filters.CHANGE);this.trigger("changeFilterEvent",n)},onFilterOpen:function(n){t.Utils.Ui.isMobileDevice()||t.Utils.Ui.isMobileView()||this.ui.filterWrapper.addClass("focused");this.trigger("filter:open",n)},onFilterClose:function(n){t.Utils.Ui.isMobileDevice()||t.Utils.Ui.isMobileView()||this.ui.filterWrapper.removeClass("focused");this.trigger("filter:close",n)}})});App.module("LowestPrices",function(n,t,i,r){var u={single:"single",outbound:"outbound",inbound:"inbound",empty:"empty"},f=new i.Wreqr.EventAggregator,e={UPDATE_CHART:"lowest-prices-update-chart"};n.LowestPricesView=r.LayoutView.extend({template:"#lowest-prices-template",regions:{departPricesAxis:".js-depart-prices-axis",departChart:".js-depart-chart",returnPricesAxis:".js-return-prices-axis",returnChart:".js-return-chart"},ui:{content:".js-lowest-prices-content",error:".js-lowest-prices-error",departChart:".js-depart-chart",returnChart:".js-return-chart"},className:"chart-container-main",events:{"click .js-btn-close":function(n){n.preventDefault();t.vent.trigger(t.VentActions.LowestPrices.CLOSE)}},initialize:function(){var n=this.model.get("searchParams");this.listenTo(t.vent,t.VentActions.LowestPrices.OPEN,_.bind(function(){this.openCharts()},this));this.listenTo(t.vent,t.VentActions.LowestPrices.CLOSE,_.bind(this.closeCharts,this));this.listenTo(f,e.UPDATE_CHART,_.bind(this.onChartUpdate,this));this._outboundMiddleDate=moment(n.outbounddate,t.Settings.dateFormat);this._inboundMiddleDate=moment(n.inbounddate,t.Settings.dateFormat);this._isMobileView=t.Utils.Ui.isMobileView();$(window).on("resize.lowestPrices",_.bind(this._updateColumnsCount,this))},onChangeBrowseCacheData:function(n){n.inbounds?this._renderTwoWaysCharts(n):this._renderOneWayChart(n)},onRender:function(){var r=this.model.get("searchParams"),f,e,o,s;this._departDt=moment(r.outbounddate,t.Settings.dateFormat);f=this.model.get("originplaceText");e=this.model.get("destinationplaceText");this._returnDt=r.inbounddate?moment(r.inbounddate,t.Settings.dateFormat):null;o=new n.LowestPricesChartView({model:new i.Model({direction:$.t("lowestPrices.labels.depart"),date:this._departDt,dateOther:this._returnDt,place:f,type:r.inbounddate?u.outbound:u.single,months:[],bars:[]})});this.departChart.show(o);r.inbounddate?(s=new n.LowestPricesChartView({model:new i.Model({direction:$.t("lowestPrices.labels.return"),date:this._returnDt,dateOther:this._departDt,place:e,type:u.inbound,months:[],bars:[]})}),this.returnChart.show(s)):this.$el.addClass("one-way")},onChartUpdate:function(n){var i=this,f=this.model.get("searchParams"),r;n.type===u.single?(n.date&&(this._outboundMiddleDate=n.date),f.outbounddate=this._outboundMiddleDate.format(t.Settings.dateFormat),this.trackChartUpdate(n.type===u.single,n.type===u.outbound),t.SearchResult.Utils.BrowseCache.getOneWayData(f,this.getChartsWidth()).done(_.bind(i._renderOneWayChart,i)).fail(_.bind(i._onLowestPricesRequestError,i))):(n.type===u.outbound?(r={outbound:n.date},this._outboundMiddleDate=n.date):n.type===u.inbound?(r={inbound:n.date},this._inboundMiddleDate=n.date):n.type===u.empty&&(r={outbound:this._outboundMiddleDate,inbound:this._inboundMiddleDate}),this.trackChartUpdate(n.type===u.single,n.type===u.outbound),r&&t.SearchResult.Utils.BrowseCache.getTwoWaysData(f,this.getChartsWidth(),r).done(_.bind(i._renderTwoWaysCharts,i)).fail(_.bind(i._onLowestPricesRequestError,i)))},trackChartUpdate:function(n,i){var u=n?"MonthDepart":i?"MonthDepart":"MonthReturn",r="Depart_"+this._outboundMiddleDate.format("YYYYMM");!n&&this._inboundMiddleDate&&(r+="_Return_"+this._inboundMiddleDate.format("YYYYMM"));t.tracking.trackEvent("day-view","LowestPrice_"+u,r)},getChartsWidth:function(){return this.ui.departChart.find(".chart-content").width()-1},showError:function(n){var t=n===429?$.i18n.t("errors-429.limit-exceeded"):$.i18n.t("errors.message");this.ui.content.hide();this.ui.error.find(".js-error-text").empty().text(t).end();this.ui.error.show()},onDestroy:function(){$(window).off("resize.lowestPrices")},_updateColumnsCount:function(){var n=t.Utils.Ui.isMobileView(),i,r;if(n||n!==this._isMobileView){this._isMobileView=n;i=this.model.get("searchParams");r={type:i.inbounddate?u.empty:u.single};this.onChartUpdate(r)}},_getCurrency:function(n){return t.Dictionaries.SupportedCurrenciesByCode[n]},_renderOneWayChart:function(n){this.ui.error.hide();this.ui.content.show();var i=t.SearchResult.Utils.BrowseCache.getMaxPrice(_.pluck(n.outbounds,"price"));this.departChart.currentView.renderChart(n,i);this._renderPriceAxis(i,this._getCurrency(n.currency.Code))},_renderTwoWaysCharts:function(n){this.ui.error.hide();this.ui.content.show();var r=n.outbounds.length?_.pluck(n.outbounds,"price"):this.departChart.currentView.getPrices(),u=n.inbounds.length?_.pluck(n.inbounds,"price"):this.returnChart.currentView.getPrices(),i=t.SearchResult.Utils.BrowseCache.getMaxPrice(r.concat(u));this.departChart.currentView.renderChart(n,i);this.returnChart.currentView.renderChart(n,i);this._renderPriceAxis(i,this._getCurrency(n.currency.Code))},_renderPriceAxis:function(r,u){var f=new i.Collection([{price:t.Utils.Ui.wrapPrice(0,u),bottom:!0},{price:t.Utils.Ui.wrapPrice(r/2,u)},{price:t.Utils.Ui.wrapPrice(r,u),top:!0}]);this.departPricesAxis.show(new n.LowestPricesPricesCollectionView({collection:f}));_.isUndefined(this.model.get("searchParams").inbounddate)||this.returnPricesAxis.show(new n.LowestPricesPricesCollectionView({collection:f}));this.$el.find("li.selected a").first().focus()},_onLowestPricesRequestError:function(){Logger().error("error on getting grid of prices results")},openCharts:function(){this.$el.parent().addClass("active").attr("aria-hidden","false");this._updateColumnsCount()},closeCharts:function(){this.$el.parent().removeClass("active").attr("aria-hidden","true")}});n.LowestPricesChartView=r.LayoutView.extend({template:"#lowest-prices-chart-template",regions:{bars:".js-chart-bars"},events:{"click .js-months-list li a":"onMonthClick","click .js-scroll-left":"onScrollLeftClick","click .js-scroll-right":"onScrollRightClick"},ui:{scrollLeft:".js-scroll-left",scrollRight:".js-scroll-right"},initialize:function(){this.model.set("titleDate",this.model.get("date").format(t.Settings.dateFormatMonthDateDay))},onRender:function(){var r=this.model.get("bars"),f=new n.LowestPricesChartBarsCollectionView({collection:new i.Collection(r),currency:this.model.get("currency"),dateOther:this.model.get("dateOther"),isDepart:this._isDepart()}),e,u;f.on("onBarClicked",this.onBarClicked,this);this.bars.show(f);e=this;this.$el.swipe({swipe:_.bind(this.onSwipe,e)});r.length&&(u=t.SearchResult.Utils.BrowseCache.getAvailiableDates(),this.ui.scrollLeft.toggleClass("inactive",!_.first(r).timestamp.diff(u.begin)),this.ui.scrollRight.toggleClass("inactive",!_.last(r).timestamp.diff(u.end)))},_getCurrency:function(n){return t.Dictionaries.SupportedCurrenciesByCode[n]},renderChart:function(n,i){var u=this._isDepart()?n.outbounds:n.inbounds,r,f;u&&u.length?(r=t.SearchResult.Utils.BrowseCache.getNormalizedData(u,i,this.model.get("date")),this.model.set({bars:r,months:t.SearchResult.Utils.BrowseCache.getMonthsList(r),maxPrice:i,currency:this._getCurrency(n.currency.Code)}),this.render()):this._maxPrice!==i&&(f=this.model.get("bars"),r=t.SearchResult.Utils.BrowseCache.getNormalizedData(f,i,this.model.get("date")),this.model.set({bars:r}),this.render());this._maxPrice=i},getPrices:function(){return _.pluck(this.model.get("bars"),"price")},onMonthClick:function(n){var r=$(n.currentTarget),i=moment(r.data("date"),t.Settings.monthFormat),u=moment({year:i.get("year"),month:i.get("month"),day:t.Settings.lowestPrices.middleMonthDay});n.preventDefault();f.trigger(e.UPDATE_CHART,{date:u,type:this.model.get("type")})},onBarClicked:function(n){var i=this._isDepart(),f=i?this.model.get("date"):this.model.get("dateOther"),u=i?this.model.get("dateOther"):this.model.get("date"),r="Depart_"+f.format("YYYYMMDD");u!=null&&(r+="_Return_"+u.format("YYYYMMDD"));r+="_Price_"+n.model.get("price");t.tracking.trackEvent("day-view","LowestPrice_DateSelect",r);t.Flights.SearchForm.trigger("change:date",i?n.model.get("timestamp"):n.model.get("timestampRefl"),i?n.model.get("timestampRefl"):n.model.get("timestamp"));t.Flights.SearchForm.search()},onScrollLeftClick:function(n){n.preventDefault();f.trigger(e.UPDATE_CHART,{date:this._getMiddleDate().clone().subtract(t.Settings.lowestPrices.scrollOffset,"days"),type:this.model.get("type")})},onScrollRightClick:function(n){n.preventDefault();f.trigger(e.UPDATE_CHART,{date:this._getMiddleDate().clone().add(t.Settings.lowestPrices.scrollOffset,"days"),type:this.model.get("type")})},onSwipe:function(n,i,r){var u=Math.round(r/t.Settings.lowestPrices.pixelsPerDayForScrolling);u*=i==="left"?1:-1;f.trigger(e.UPDATE_CHART,{date:this._getMiddleDate().clone().add(u,"days"),type:this.model.get("type")})},_getMiddleDate:function(){var n=this.bars.currentView.collection,t=Math.floor(n.length/2);return n.at(t).get("timestamp")},_isDepart:function(){return this.model.get("type")!==u.inbound}});n.LowestPricesChartBarView=r.ItemView.extend({template:"#lowest-prices-chart-bar-template",tagName:"li",initialize:function(n){n.model.get("percent")>100?n.model.set({percent:100,overrides:!0}):n.model.set("overrides",!1)},onRender:function(n){var o;n.model.get("selected")&&this.$el.addClass("selected");n.model.get("price")||this.$el.addClass("search");n.model.get("overrides")&&n.$el.addClass("overrides");n.model.get("timestampRefl")&&n.$el.addClass("nodata");this.$el.data("date",n.model.get("date"));var f=n.model.get("timestamp"),i=n.model.get("timestampRefl"),r=this.getOption("dateOther"),e=this.getOption("isDepart"),s=e?f:i?i:r,u=$.t("lowestPrices.labels.depart")+": "+s.format(t.Settings.tooltipFormat)+"\n";r&&(o=e?i?i:r:f,u+=$.t("lowestPrices.labels.return")+": "+o.format(t.Settings.tooltipFormat)+"\n");u+=n.model.get("price")===null?this._getNoDataTooltip():t.Utils.Ui.wrapPrice(n.model.get("price"),this.getOption("currency"));this.$el.attr("title",u)},events:{"click .js-start-new-search":"onItemClick"},onItemClick:function(n){n.preventDefault();this.trigger("clicked",this)},_getNoDataTooltip:function(){return _.isUndefined(this._noDataTooltip)&&(this._noDataTooltip=this._getPriceTooltip($.t("lowestPrices.tooltips.noPrice"))),this._noDataTooltip},_getPriceTooltip:function(n){for(var r=30,t="",i;n.length>0;)n.length<=r?(t+=n,n=""):(i=n.indexOf(" ",r),i===-1?(t+=n,n=""):(t+=n.substring(0,i)+"\n",n=n.substring(i+1)));return t}});n.LowestPricesChartBarsCollectionView=r.CollectionView.extend({tagName:"ul",childView:n.LowestPricesChartBarView,collection:i.Collection,className:"chart-content",childEvents:{clicked:"onItemClicked"},onItemClicked:function(n){this.trigger("onBarClicked",n)},initialize:function(n){this.childViewOptions={currency:n.currency,isDepart:n.isDepart,dateOther:n.dateOther}}});n.LowestPricesPriceItemView=r.ItemView.extend({model:i.Model,template:"#lowest-prices-price-item-template",tagName:"div",className:"cost",onRender:function(n){n.model.get("bottom")?n.$el.addClass("btm"):n.model.get("top")?n.$el.addClass("top"):n.$el.addClass("mid")}});n.LowestPricesPricesCollectionView=r.CollectionView.extend({tagName:"div",childView:n.LowestPricesPriceItemView,collection:i.Collection})});App.module("SearchResult.Views",function(n,t,i,r){n.BookingDialogView=r.LayoutView.extend({model:i.Model,template:"#booking-dialog-multipart-template",bodyModalLockClassName:"modal-lock",events:{"click .js-dialog-close":"onDialogCloseClick","click .js-dialog-continue":"onContinueClick","click .js-dialog-book":"onBookClick","mouseenter .js-multipart-item":"onItemHover","mouseleave .js-multipart-item":"onItemLeave"},regions:{progress:".js-dialog-progress"},ui:{dialog:".booking-dialog",continueButton:".js-dialog-continue",items:".js-agent-container"},initialize:function(n){this.options=_.extend({},n);t.GlobalEvents.on("global:click",this.closeDialog,this)},onItemHover:function(n){this.ui.items.addClass("inactive");$(n.currentTarget).removeClass("inactive")},onItemLeave:function(){this.ui.items.removeClass("inactive")},closeDialog:function(n){this.isDestroyed||n&&(this.ui.dialog.length&&$.contains(this.ui.dialog[0],n.target)||$(n.target).closest(".js-raise-booking, .js-prices-warning a").length)||(this.$el.find(".multi-part").length>0&&t.tracking.trackEvent("day-view","Multipart_Close"),t.vent.trigger(t.VentActions.Flights.ItemView.CLOSE_BOOKING_DIALOG),this.destroy())},onRender:function(){if(this.model.get("hasProgress")){var n=new t.Views.ProgressbarView({model:new i.Model({min:10})});this.progress.show(n);n.setPercent()}this.$el.i18n();$("html").addClass(this.bodyModalLockClassName);$(window).on("scroll.bookingDialog",function(n){return n.preventDefault(),!1});this.ui.dialog.show()},onDialogCloseClick:function(n){n.preventDefault();this.closeDialog()},onContinueClick:function(){this.trigger("continueEvent");t.vent.trigger(t.VentActions.Flights.ItemView.CONTINUE_BOOKING_DIALOG,this.model.get("continueLink"))},onBookClick:function(n){var i=$(n.target).data("book-link"),r=$(n.target).data("book-index"),u=this.model.attributes.itineraryIndex;t.tracking.trackEvent("day-view","BookClick","Flights_Multipart_"+u+"_"+r);window.open(t.tracking.decorateUrl(i),"_blank")},onDestroy:function(){t.GlobalEvents.unbind("global:click",this.closeDialog,this);$("html").removeClass(this.bodyModalLockClassName);$(window).off("scroll.bookingDialog")},setPercent:function(n){this.progress.currentView&&this.progress.currentView.setPercent(n)}})});App.module("SearchResult.Errors",function(n,t,i,r){n.ErrorItemView=r.ItemView.extend({model:i.Model,tagName:"li",template:"#error-item-template",onRender:function(){this.$el.i18n()}});n.ErrorListView=r.CollectionView.extend({childView:n.ErrorItemView,collection:i.Collection,tagName:"ul",onRender:function(){this.$el.i18n()}})});App.module("SearchResult.Views",function(n,t,i,r){n.SearchResultItineraryItemView=r.ItemView.extend({template:"#search-result-itinerary-item-template",templateHelpers:{enableFavorites:!t.Services.Feature.check("disableFavorites","on"),getItemClasses:function(){var n=[];return this.isFavorite&&n.push("favorite"),this.legs.length===1&&n.push("single"),t.Services.Feature.check("bookButton","b")&&n.push("b-tests"),n.push(this.showDetails),n.join(" ")},longPrice:function(){return this.priceWithCurrency&&this.priceWithCurrency.length>=t.Settings.wrappedPriceLength},isLongWaitLabelIsLong:function(){return t.Culture.locale==="hu-HU"||t.Culture.locale==="tl-PH"},getItemSummary:function(){return $.i18n.t("aria.results.heading")+" "+(this.index+1)+", "+this.priceWithCurrency},formatLabel:function(n){var t=n.match(/^cheapest(\d)$/),i;return t?(i=t.pop(),["最安",i,"位"].join("")):(t=n.match(/^shortest(\d)$/),t)?(i=t.pop(),["最短",i,"位"].join("")):""},getItineraryLabel:function(n){var i=_.template('<li class="<%= className %>"><%= labelName %><\/li>'),t={};return t.className=/^cheapest/.test(n)?"label-cheapest":/^shortest/.test(n)?"label-shortest":"",t.labelName=this.formatLabel(n),i(t)}},events:{"click .js-details-toggle":"onDetailsButtonClick","click .js-more-btn":"onMoreButtonClick","click .js-before-bying":"toggleReadBeforeBooking","click .js-baggage-info":"toggleBaggageInfo","mousedown .js-details-toggle":"onFocusableMousedown","mousedown .js-before-bying":"onFocusableMousedown","click .js-raise-booking":"openBookingDialog","click @ui.favoriteIcon":"addToFavorites","mousedown @ui.favoriteIcon":"onFocusableMousedown","click .js-extra-fees-warning a":"openExtraFeesWarningPage","click .js-unfreeze-message":"onUnfreeze","click .js-outbound-header":"onLegHeaderClick","click .js-inbound-header":"onLegHeaderClick","click @ui.shareButton":"onToggleShareBox","mousedown @ui.shareButton":"onFocusableMousedown","click .js-codeshare":"onToggleCodeshare"},ui:{detailsButton:".js-details-toggle",detailsPanel:".js-details",beforeBuying:".js-before-bying",item:".js-item",outboundHeader:".js-outbound-header",inboundHeader:".js-inbound-header",sharingToolboxWrapper:".js-sharing-toolbox-wrapper",sharingToolbox:".js-sharing-toolbox",codeshare:".js-codeshare",favoriteIcon:".js-favorite",shareButton:".js-share-button",shareLoading:".js-share-spinner",baggageDetailsButton:".js-baggage-info",baggageDetailsPanel:".js-baggage-panel",labels:".js-labels",carrierLogo:".js-carrier-logo"},modelEvents:{"change:isFavorite":"onFavoriteChange","change:isFocused":"onFocusChange"},onFocusableMousedown:function(n){var t=$(n.target);t=t.is("a")?t:t.closest("a");t.css("outline","none").one("blur",function(){$(this).css("outline","")})},onToggleShareBox:function(n){if(n.preventDefault(),this.ui.sharingToolboxWrapper.is(":visible")||this.ui.shareButton.hasClass("waiting"))this.ui.shareButton.attr("aria-expanded",!1);else{n.stopPropagation();t.Utils.AddThis.isReady()||t.Utils.Spin(this.ui.shareLoading);this.ui.shareButton.addClass("waiting");t.Utils.AddThis.onAddThisReady(_.bind(function(n){if(!this.isDestroyed&&(this.ui.shareButton.removeClass("waiting").attr("aria-expanded",!0),this.ui.shareLoading.empty(),n)){this.model.get("addThisToolboxCreated")||(window.addthis.toolbox(this.ui.sharingToolbox.get(0)),this.model.set("addThisToolboxCreated",!0));this.ui.sharingToolboxWrapper.addClass("active");t.GlobalEvents.trigger("global:click",{target:$(t.Utils.Ui.bodySelector)});t.GlobalEvents.once("global:click",_.bind(this.onGlobalClick,this))}},this))}},onGlobalClick:function(){this.isDestroyed||this.ui.sharingToolboxWrapper.animate({opacity:0},{duration:300,complete:_.bind(function(){this.ui.sharingToolboxWrapper.removeClass("active");this.ui.sharingToolboxWrapper.css("opacity",1)},this)})},onLegHeaderClick:function(n){$(n.currentTarget).toggleClass("active")},onToggleCodeshare:function(){this.ui.codeshare.toggleClass("active")},addToFavorites:function(){return this.trigger("addToFavorites"),!1},onFavoriteChange:function(n,t){this.ui.item.toggleClass("favorite",t);this.ui.favoriteIcon.attr({title:t?$.t("search-result.remove-from-favourites"):$.t("search-result.add-to-favourites"),"aria-checked":t})},onFocusChange:function(){this.toggleDetails({openAnyway:!0});this.scrollToElement()},onDetailsButtonClick:function(n){n.preventDefault();var i=this.ui.detailsPanel.hasClass("expanded")?"FlightDetails_Close":"FlightDetails_Open";t.tracking.trackEvent("day-view",i,this.model.get("index"));this.toggleDetails()},onMoreButtonClick:function(n){n.preventDefault();this.toggleDetails()},onCarrierLogoLoadError:function(n){var t=$(n.target);t.parent().addClass("missing-carrier-logo")},toggleDetails:function(n,t){return this.trigger("onItemClick",t),!1},toggleReadBeforeBooking:function(n,t){return this.trigger("onReadBeforeBookingClick",t),!1},toggleBaggageInfo:function(n,i){var r=this.ui.baggageDetailsPanel.hasClass("expanded")?"BaggageDetails_Close":"BaggageDetails_Open";return t.tracking.trackEvent("day-view",r,this.model.get("index")),this.trigger("onBaggageInfo",i),!1},scrollToElement:function(){t.Utils.Ui.scrollToElement(this.ui.item,t.Utils.Ui.isMobileView()?-50:-100)},onUnfreeze:function(n,t){this.trigger("unfreeze",t)},openBookingDialog:function(n,t){n.preventDefault();n.stopPropagation();var i=$(n.currentTarget);t=t>=0?t:parseInt(i.attr("data-index"));t=isNaN(t)?-1:t;this.trigger("openBookingDialog",n,t)},openExtraFeesWarningPage:function(){window.open(AppSettings.airlinesFeesUrl,"_blank")},onRender:function(){this.$el.i18n();this.$el.attr("id",this.cid);this.ui.carrierLogo.error(_.bind(this.onCarrierLogoLoadError,this))},_getDurationForSharing:function(n){return(n.days>0?n.days+"D":"")+(n.hours>0?n.hours+"H":"")+(n.min>0?n.min+"M":"")},onDomRefresh:function(){var d=this.model.get("country"),n,f,a,v,y,p,w,b,s,h,k;if(d!=="CN"){var e=this.model.get("destinationPlace"),g=this.model.get("originPlace"),c=this.model.get("legs"),r=c[0],u=c[1],o={origin:g.Name,destination:e.Name,sitename:t.Settings.config.name,price:this.model.get("priceWithCurrency")},l={};e.cityCode&&_.extend(l,{destinationCityCode:e.cityCode});r&&r.segments&&r.segments.length>0&&(n=r.segments[0],f=r.segments[r.segments.length-1],n.departure&&(a=n.departure.date?n.departure.date:"-",v=n.departure.time?n.departure.time:"-",y=r.flight.duration?r.flight.duration:"-"),f.arrival&&(s=f.arrival.date?f.arrival.date:"",h=f.arrival.time?f.arrival.time:""),_.extend(o,{outboundDate:a,outboundTime:v,outboundDuration:this._getDurationForSharing(y),date:s,time:h}));u&&u.segments&&u.segments.length>0&&(n=u.segments[0],p=n.departure.date?n.departure.date:"-",w=n.departure.time?n.departure.time:"-",b=u.flight.duration?u.flight.duration:"-",_.extend(o,{inboundDate:p,inboundTime:w,inboundDuration:this._getDurationForSharing(b)}));k=new t.Addthis.AddthisToolboxView({model:new i.Model({allSocial:{title:{key:"sharing.itinerary.title",needTranslation:!0},description:{key:"sharing.itinerary.description",needTranslation:!0},message:{key:"sharing.itinerary.message-twitter",needTranslation:!0}},options:o,params:_.extend(l,{utm_campaign:"itinerary_share",arrivalDate:s,arrivalTime:h,itinerary:this.model.get("fingerprint")}),shareRouter:"itinerary"})});this.ui.sharingToolbox.html(k.render().$el)}}});n.SearchResultItineraryListView=r.CompositeView.extend({model:i.Model,template:"#search-result-itinerary-list-template",collection:i.Collection,childViewContainer:".js-itinerary-list-container",childView:n.SearchResultItineraryItemView,collectionEvents:{"change reset":"onCollectionChange"},childEvents:{onItemClick:"onItemClick",onReadBeforeBookingClick:"onReadBeforeBookingClick",onBaggageInfo:"onBaggageInfo",openBookingDialog:"openBookingDialog",addToFavorites:"addToFavorites",unfreeze:"onUnfreeze"},events:{"click .js-all-results-link":"onResetFilters"},ui:{loading:".js-itinerary-list-loading",empty:".js-itinerary-list-empty",filterEmpty:".js-itinerary-list-filter-empty",itineraryContainer:".js-itinerary-list-container",departDateSuggestion:".js-depart-date-suggestion",returnDateSuggestion:".js-return-date-suggestion"},modelEvents:{"change:response":"updateList","change:page":"onChangePage","change:filteredItineraries":"onFilteredItinerariesChanged"},behaviors:{ViewInactiveVeil:{triggerName:"SearchResultListView"}},childViewOptions:function(n){return n.set({country:this.model.get("country"),destinationPlace:this.model.get("destinationPlace"),originPlace:this.model.get("originPlace")}),{}},onFilteredItinerariesChanged:function(){this.$el.removeClass("frozen");var n=this.model.get("page")?this.model.get("page"):1;this.model.set({page:n},{silent:!0});this.updateList()},onFreeze:function(){this.$el.addClass("frozen")},onUnfreeze:function(n,t){this.onItemClick(n,t);this.$el.removeClass("frozen");this.trigger("unfreeze")},onRender:function(){this.hideFilterEmptyError();this.hideEmptyError();this.ui.departDateSuggestion.on("click",".js-date-suggestion-link",this.onSuggestionLinkClick.bind(this));this.ui.returnDateSuggestion.on("click",".js-date-suggestion-link",this.onSuggestionLinkClick.bind(this))},showEmptyError:function(){$(".js-summary-prices").hide();this.ui.empty.show();this.enableDateSuggestion(t.Utils.StateStorage.Flights.get());t.tracking.trackEvent("day-view","NoResults_Select")},hideEmptyError:function(){$(".js-summary-prices").show();this.ui.empty.hide()},showFilterEmptyError:function(){this.ui.filterEmpty.show();this.enableDateSuggestion(t.Utils.StateStorage.Flights.get());t.tracking.trackEvent("day-view","NoResults_Filter")},hideFilterEmptyError:function(){this.ui.filterEmpty.hide()},enableDateSuggestion:function(n){n.inbounddate?this.ui.returnDateSuggestion.show():this.ui.returnDateSuggestion.hide();this.$el.find(".search-no-results__suggestion-link--inbound").text(t.Culture.culture.formatDate(moment(n.inbounddate).toDate(),{time:"short"}));this.$el.find(".search-no-results__suggestion-link--outbound").text(t.Culture.culture.formatDate(moment(n.outbounddate).toDate(),{time:"short"}))},onRenderCollection:function(){this._scrollToItems()},_scrollToItems:function(){this.options.scrolled||t.Services.Feature.check("filters","b")||this.ui.itineraryContainer.find(".js-item").length&&(this.options.scrolled=!0,t.Utils.Ui.scrollToElement(this.ui.itineraryContainer,t.Utils.Ui.isMobileView()?-50:-100))},onCollectionChange:function(){var n=this.model.get("response");n&&(n.Flights.Status==="UpdatesComplete"&&(n.Flights.Itineraries.length===0?(this.showEmptyError(),this.hideFilterEmptyError()):this.hideEmptyError()),n.Flights.Itineraries.length&&(this.collection.length===0?this.showFilterEmptyError():this.hideFilterEmptyError()))},onChangePage:function(){this.model.set("detailsOpenedItems",[]);this.updateList()},updateList:function(){var u=this,i=t.Services,n,r;this.model.get("filteredItineraries")&&(n=i.Flights.getList(this.model,this.options.searchParams),r=this.collection.length===0&&n.length>0,this.collection.reset(n),t.Flights.renderedResults=n,i.Feature.check("baggageDetails","on")&&i.BaggageFees.processItineraries(this.collection,function(n){u.collection.reset(n.toJSON())}),r&&this.trigger("load:firstResults"),this.trigger("remove:inactiveLayout"),this.trigger("inactive-veil:disable"),t.GlobalEvents.trigger("global:update-results"),t.vent.trigger(t.VentActions.Results.UPDATE))},addToFavorites:function(n){t.Utils.FavoritesStorage.Flights.changeFavorite(_.extend(n.model.toJSON(),this.options.searchParams));this.updateFavorites();n.model.get("isFavorite")?t.tracking.trackEvent("day-view","Favourite_Flight_Add",this.getTrackingDetails(n.model)):t.tracking.trackEvent("day-view","Favourite_Flight_Delete",this.getTrackingDetails(n.model))},getTrackingDetails:function(n){var t=_.template("<%= originplace %>_<%= destinationplace %>_<%= priceWithCurrency %>_<%= agentName %>_<%= position %>");return t({originplace:n.get("originPlace")?n.get("originPlace").Code:"undefined",destinationplace:n.get("destinationPlace")?n.get("destinationPlace").Code:"undefined",priceWithCurrency:n.get("priceWithCurrency"),agentName:n.get("agent")?n.get("agent").name:"undefined",position:this.collection.indexOf(n)})},updateFavorites:function(){var n=t.Utils.FavoritesStorage.Flights.getFavorites();_.each(this.collection.models,function(t){var i=t.get("fingerprint");t.set("isFavorite",_.some(n,function(n){return n.fingerprint===i}))})},onItemClick:function(n,t){var f=n.$el.find(".js-item"),r=n.model.get("fingerprint"),i=this.model.get("detailsOpenedItems"),u;t&&t.openAnyway||!n.ui.detailsPanel.hasClass("expanded")?(u=parseInt(n.model.get("index"))+parseInt(this.model.get("paginateBy"))*parseInt(this.model.get("page")-1),this._showDetails(n),i=i||[],i.push(r)):(this._hideDetails(n),i=_.without(i,r));this.model.set("detailsOpenedItems",i)},onReadBeforeBookingClick:function(n){var r=t.Utils.StateStorage.Flights.get(),i,u;r&&t.tracking.trackEvent("day-view","ReadBeforeBuyingClick",r.originplace+"_"+r.destinationplace);i=n.$el.find(".js-read-before-booking");u=n.$el.find(".js-item");i.is(":visible")?(i.hide(),n.ui.beforeBuying.attr("aria-expanded",!1)):(i.show(),this._showDetails(n),n.ui.beforeBuying.attr("aria-expanded",!0))},onBaggageInfo:function(n){var i=n.ui.baggageDetailsPanel,r=i.is(":visible");r||i.hasClass("rendered")||t.Services.BaggageFees.renderDetails(i,n.model.get("baggageDetails"));this._togglePanel(n,"baggageDetails")},onResetFilters:function(){t.tracking.trackEvent("day-view","NoResults_Select","Reset");this.trigger("reset:filter")},onSuggestionLinkClick:function(n){var r=$(n.currentTarget),u=t.Utils.StateStorage.Flights.get(),f=moment(u.outbounddate),e=moment(u.inbounddate),i=parseInt(r.attr("data-days")),o=r.attr("data-type");isNaN(i)||(t.tracking.trackEvent("day-view","NoResults_Select",i<0?"Previous":"Next"),o==="depart"?t.Flights.SearchForm.trigger("change:date",moment(f).add(i,"days")):t.Flights.SearchForm.trigger("change:date",moment(f),moment(e).add(i,"days")),t.Flights.SearchForm.search())},openBookingDialog:function(n,i,r){var f=$(i.currentTarget),u,v,y,p;r=r>=0?r:parseInt(f.attr("data-index"));r=isNaN(r)?-1:r;var o=r,s,e=[],h=parseInt(this.model.get("page"),10)-1,c=h===0?"":h,l=t.Services.Feature,a=t.tracking;f.hasClass("agency")?(s=f.data("id"),a.trackEvent("day-view","AltProviderClick",s+"_"+r)):(e.push("Flights_"+c+n.model.get("index")+"_"+r),l.check("bookButton")&&e.push("v="+l.get("bookButton")),a.trackEvent("day-view","SelectFlight",e.join(";")));u=n.model.get("priceOptions")[o];u.deepLink&&(v=t.Utils.Uri.getTrackingParamsFromUrl(),y=_.map(v,function(n,t){return encodeURIComponent("&"+t+"="+n)}),u.deepLink=u.deepLink+y.join(""));t.Services.Feature.check("expandDeepLink","on")&&u&&u.deepLink&&(u.deepLink=t.tracking.expandDeepLink(u.deepLink,u.priceData.agents[0].id));u&&(t.vent.trigger(t.VentActions.Flights.ItemView.OPEN_BOOKING_DIALOG,u,c.toString()+n.model.get("index"),o),n.model.get("agents").length>1&&(p=n.$el.find(".js-item"),p.hasClass("details")||this._showDetails(n)))},_showDetails:function(n){var r=n.$el,i,t,u,f;this._showPanel(n,"details");i=r.find(".js-outbound-header");t=r.find(".js-inbound-header");t&&t.length>0&&(u=i.first().height(),f=t.first().height(),u<f?i.addClass("minimal"):t.addClass("minimal"));this.trigger("click:details")},_hideDetails:function(n){this._hidePanel(n,"details");this.trigger("click:details")},_showPanel:function(n,t){var r=n.ui[t+"Button"],u=n.ui[t+"Panel"],i=n.model.get("openedPanel");i&&i!==t&&this._hidePanel(n,i);r.attr("aria-expanded",!0).addClass("expanded");u.addClass("expanded");n.ui.item.addClass("focused").addClass("panel-"+t+"-open");n.model.set("openedPanel",t)},_hidePanel:function(n,t){var i=n.ui[t+"Button"],r=n.ui[t+"Panel"];i.attr("aria-expanded",!1).removeClass("expanded");r.removeClass("expanded");n.ui.item.removeClass("focused").removeClass("panel-"+t+"-open");n.model.set("openedPanel",null)},_togglePanel:function(n,t){var i=n.ui[t+"Panel"];this[i.hasClass("expanded")?"_hidePanel":"_showPanel"].call(this,n,t);this.trigger("click:baggage")},initialize:function(){}})});App.module("SearchResult.Views",function(n,t,i,r){n.FlightsCountIndicatorView=t.Views.FilterCountIndicatorView.extend({update:function(n){var r=n.get("summary"),u=n.get("filteredItineraries"),e=u?u.length:-1,i=n.get("response"),f;r&&(f={all:r.flightsNumber,filtered:e,lastResponse:!i||!i.Flights||i.Flights.Status!=="UpdatesPending"},t.Views.FilterCountIndicatorView.prototype.update.apply(this,[f]))},templateHelpers:{allLabel:function(){var n=this.all>1?"search-result.summary.flights_plural":"search-result.summary.flights_singular";return $.i18n.t(n).replace("__flightsCount__",'<span class="num">'+this.all.toString()+"<\/span>")},filteredLabel:function(){return $.i18n.t("search-result.summary.flights-indicator-filtered-label").replace("__filteredNumber__",'<span class="num">'+this.filtered.toString()+"<\/span>").replace("__flightsNumber__",'<span class="num">'+this.all.toString()+"<\/span>")}}});n.SearchResultSummaryIconsView=r.ItemView.extend({template:"#search-result-summary-icons-template",templateHelpers:{enableFavorites:!t.Services.Feature.check("disableFavorites","on")},ui:{flightsNumber:".js-flights-count-wrapper",resetFiltersButton:".js-reset-filters-plate",lowestPricesLink:".js-lowest-prices-link",filtersButton:".js-filters-plate",poweredBy:".js-powered-by",favoritesPlate:".js-favorites-plate",favoritesPlateItemsNumber:".js-favorites-plate-items-num",infoIcons:".js-info-icons"},events:{"click @ui.resetFiltersButton":"onResetFiltersButtonClick","click @ui.lowestPricesLink":"clickOnLowestPrices","click @ui.favoritesPlate":"onFavoritesPlateClick","click @ui.filtersButton":"onFiltersPlateClick"},modelEvents:{"change:favoritesBasketItemsCount":"updateFavouriteBasketItemsCount"},views:{flightsIndicator:null},disable:function(){this.options.disabled=!0;this.$el.addClass("buttons-disabled")},enable:function(){this.options.disabled=!1;this.$el.removeClass("buttons-disabled")},updateFavouriteBasketItemsCount:function(){var n=this.model.get("favoritesBasketItemsCount");this.templateHelpers.enableFavorites&&(n>0?this.ui.favoritesPlateItemsNumber.text(n).show():this.ui.favoritesPlateItemsNumber.hide())},onRender:function(){if(this.views={},this.ui.infoIcons.addClass("no-result"),t.Utils.Ui.isSlowDevice()&&this.ui.lowestPricesLink.hide(),this.options.disabled&&this.disable(),t.Services.Feature.check("filters","b")){this.mobileFilterView=new t.SearchResult.Filters.MobileFilterMenu({model:this.model});this.mobileFilterView.on("changeFilterEvent",this.onMobileFilterChange,this);this.mobileFilterView.on("reset:filter",_.bind(function(){this.trigger("reset:filter")},this));this.mobileFilterView.render()}this.updateFavouriteBasketItemsCount();this.$el.i18n()},isNoResult:!0,onMobileFilterChange:function(n){this.trigger("changeFilterEvent",n)},onChangeSummary:function(n){var t=n.get("summary");t&&(this.renderFlightsCounter(),this.ui.resetFiltersButton.attr("disabled",!0),this.ui.filtersButton.attr("disabled",t.flightsNumber<1),this.ui.infoIcons.removeClass("no-result"),this.mobileFilterView&&this.mobileFilterView.triggerMethod("summary:changed",n),this.isNoResult=!1)},onChangeFilter:function(n){var t=n.get("summary"),i=n.get("filteredItineraries"),u=i?i.length:-1,r=!1;t&&(this.renderFlightsCounter(),r=this.isFilteringApplied(u,t.flightsNumber),this.ui.resetFiltersButton.attr("disabled",!r),this.ui.infoIcons.removeClass("no-result"),this.isNoResult=!1,this.mobileFilterView&&this.mobileFilterView.triggerMethod("change:filter",n))},isFilteringApplied:function(n,t){return n>=0&&t>n},renderFlightsCounter:function(){if(!this.views.flightsIndicator){this.views.flightsIndicator=new n.FlightsCountIndicatorView({el:this.ui.flightsNumber,withReset:!t.Services.Feature.check("filtersResetButton","b"),disableResetButton:t.Services.Feature.check("filtersResetButton","b"),showSpinner:t.Services.Feature.check("filtersResetButton","b")});this.views.flightsIndicator.on("reset:filter",_.bind(function(){this.trigger("reset:filter")},this))}this.views.flightsIndicator.update(this.model)},checkActiveArrow:function(){this.ui.lowestPricesLink.removeClass("first");this.ui.favoritesPlate.removeClass("first");this.ui.lowestPricesLink.hasClass("active")?this.ui.lowestPricesLink.addClass("first"):this.ui.favoritesPlate.hasClass("active")&&this.ui.favoritesPlate.addClass("first")},onResetFiltersButtonClick:function(){this.ui.resetFiltersButton.attr("disabled")||(t.tracking.trackEvent("day-view","Filter_Reset"),this.trigger("reset:filter"))},clickOnLowestPrices:function(n){return(n.preventDefault(),this.options.disabled||this.isNoResult)?!1:(t.tracking.trackEvent("day-view","LowestPrice_Header",this.getLowestPriceClickTrackingInfo()),this.ui.lowestPricesLink.hasClass("active")?t.vent.trigger(t.VentActions.LowestPrices.CLOSE):t.vent.trigger(t.VentActions.LowestPrices.OPEN),!1)},getLowestPriceClickTrackingInfo:function(){var n=t.Utils.StateStorage.Flights.get(),r,i;return n?(r="Depart_"+moment(n.outbounddate).format("YYYYMM"),i="",n.inbounddate&&(i="_Return_"+moment(n.inbounddate).format("YYYYMM")),r+i):""},onFiltersPlateClick:function(){this.mobileFilterView&&this.mobileFilterView.open()},onFavoritesPlateClick:function(n){n.preventDefault();t.tracking.trackEvent("day-view","Favourite_Header");this.ui.favoritesPlate.hasClass("active")?(this.ui.favoritesPlate.attr("aria-expanded","false"),t.vent.trigger(t.VentActions.FavoritesBasket.CLOSE)):(this.ui.favoritesPlate.attr("aria-expanded","true"),t.vent.trigger(t.VentActions.FavoritesBasket.OPEN))},onOpenLowestPrices:function(){this.ui.lowestPricesLink.hasClass("active")||(this.ui.lowestPricesLink.addClass("active").attr("aria-expanded","true"),this.checkActiveArrow(),t.vent.trigger(t.VentActions.FavoritesBasket.CLOSE))},onCloseLowestPrices:function(){this.ui.lowestPricesLink.hasClass("active")&&(this.ui.lowestPricesLink.removeClass("active").attr("aria-expanded","false").focus(),this.checkActiveArrow())},onOpenFavoritesBasket:function(){this.ui.favoritesPlate.hasClass("active")||(this.ui.favoritesPlate.addClass("active"),this.checkActiveArrow(),t.vent.trigger(t.VentActions.LowestPrices.CLOSE))},onCloseFavoritesBasket:function(){this.ui.favoritesPlate.hasClass("active")&&(this.ui.favoritesPlate.removeClass("active"),this.checkActiveArrow())},initialize:function(n){this.model=n.model;this.listenTo(t.vent,t.VentActions.FavoritesBasket.OPEN,_.bind(this.onOpenFavoritesBasket,this));this.listenTo(t.vent,t.VentActions.FavoritesBasket.CLOSE,_.bind(this.onCloseFavoritesBasket,this));this.listenTo(t.vent,t.VentActions.FavoritesBasket.COUNT_HAS_BEEN_CHANGED,_.bind(function(n){this.model.set("favoritesBasketItemsCount",parseInt(n,10))},this));this.listenTo(t.vent,t.VentActions.LowestPrices.OPEN,_.bind(this.onOpenLowestPrices,this));this.listenTo(t.vent,t.VentActions.LowestPrices.CLOSE,_.bind(this.onCloseLowestPrices,this))}})});App.module("SearchResult.Views",function(n,t,i,r){n.SearchResultSummaryPricesView=r.ItemView.extend({model:i.Model,template:"#search-result-summary-prices-template",inactiveClassName:"inactive",events:{"click .js-cheapest":"onClickCheapest","click .js-shortest":"onClickShortest"},ui:{dialogResetFilter:".js-dialog-reset-filter",container:".js-summary-prices-container",cheapest:".js-cheapest",cheapestPrice:".js-cheapest-price",cheapestStops:".js-cheapest-stops",cheapestDuration:".js-cheapest-duration",shortest:".js-shortest",shortestPrice:".js-shortest-price",shortestStops:".js-shortest-stops",shortestDuration:".js-shortest-duration"},initialize:function(n){this.model=new i.Model(n);this.dialogResetFilter=new t.Views.DialogResetFilterView;this.dialogResetFilter.on("dialog:ok",this.onDialogResetFilterOk,this)},onRender:function(){this.ui.dialogResetFilter.html(this.dialogResetFilter.render().$el);this.ui.cheapest.hide();this.ui.shortest.hide();this.$el.hide();this.$el.i18n();t.Utils.Ui.is2xAndroid()&&t.Utils.Ui.makeScrollable(this.ui.container)},onDialogResetFilterOk:function(n){this.trigger("reset:filter");var t=this,u=0,i=0,r=null,f=null;switch(n){case"cheapest":u=0;f=window.setInterval(function(){++u!=5&&t.ui.cheapest.hasClass(this.inactiveClassName)||(window.clearInterval(f),t.onClickCheapest())},200);break;case"shortest":i=0;r=window.setInterval(function(){++i!=5&&t.ui.shortest.hasClass(this.inactiveClassName)||(window.clearInterval(r),t.onClickShortest())},200);break;case"favorite":i=0;r=window.setInterval(function(){t.trigger("reset:to:favorite");++i==5&&window.clearInterval(r)},200)}},onChangeSummary:function(n){this.$el.show();var i=n.get("summary");i&&(i.cheapestShortest&&i.currency&&(this.model.set({cheapest:{link:i.cheapestShortest.BookingDetailsLink.Body}}),this.ui.cheapestPrice.text(t.Utils.Ui.wrapPrice(i.cheapestShortest.price,i.currency)),this.model.set("cheapestShortest",i.cheapestShortest.price),this.ui.cheapestStops.attr("data-i18n","search-result."+i.cheapestShortest.maxStops+"stops"),this.ui.cheapestDuration.text(this._formatDurationText(i.cheapestShortest.duration)),this.ui.cheapest.show()),i.shortestCheapest&&i.currency&&(this.model.set({shortest:{link:i.shortestCheapest.BookingDetailsLink.Body}}),this.ui.shortestPrice.text(t.Utils.Ui.wrapPrice(i.shortestCheapest.price,i.currency)),this.model.set("shortestCheapest",i.shortestCheapest.price),this.ui.shortestStops.attr("data-i18n","search-result."+i.shortestCheapest.maxStops+"stops"),this.ui.shortestDuration.text(this._formatDurationText(i.shortestCheapest.duration)),this.ui.shortest.show()),this.$el.i18n(),this.$el.show())},_formatDurationText:function(n){var t=Math.floor(n/60),i=n-t*60,r=_.template("(<%= hours %> <%= minutes %>)"),u=t===1?"search-result.filter-menu.duration-hrs_singular":"search-result.filter-menu.duration-hrs_plural";return r({hours:$.t(u,{hours:t}),minutes:i})},checkIfItemVisibile:function(n,t){return!!n&&!!n.bookingDetailsLinkBody&&Math.round(n.price)<=t.price&&n.bookingDetailsLinkBody===t.link},onChangeVisibility:function(n){var t={cheapest:{link:this.model.get("cheapest").link,price:this.model.get("cheapestShortest")},shortest:{link:this.model.get("shortest").link,price:this.model.get("shortestCheapest")}};!!n&&this.checkIfItemVisibile(n.cheapest,t.cheapest)?this.ui.cheapest.removeClass(this.inactiveClassName):this.ui.cheapest.addClass(this.inactiveClassName);!!n&&this.checkIfItemVisibile(n.shortest,t.shortest)?this.ui.shortest.removeClass(this.inactiveClassName):this.ui.shortest.addClass(this.inactiveClassName)},onClickCheapest:function(n){if(n&&n.preventDefault(),t.tracking.trackEvent("day-view","Sort_Cheapest"),t.Services.Feature.check("sortingTabs","b"))this.ui.cheapest.addClass("active"),this.ui.shortest.removeClass("active"),this.trigger("sort",{sort:{type:"price"}});else{if(this.ui.cheapest.hasClass(this.inactiveClassName))return this.dialogResetFilter.triggerMethod("show","cheapest"),!1;var i=this.model.get("cheapest").link;this.trigger("select:bestOffer",i)}t.vent.trigger(t.VentActions.Sort.CHANGE)},onClickShortest:function(n){if(n&&n.preventDefault(),t.tracking.trackEvent("day-view","Sort_Duration"),t.Services.Feature.check("sortingTabs","b"))this.ui.shortest.addClass("active"),this.ui.cheapest.removeClass("active"),this.trigger("sort",{sort:{type:"journey-duration"}});else{if(this.ui.shortest.hasClass(this.inactiveClassName))return this.dialogResetFilter.triggerMethod("show","shortest"),!1;var i=this.model.get("shortest").link;this.trigger("select:bestOffer",i)}t.vent.trigger(t.VentActions.Sort.CHANGE)},onFavoriteTriggeredOut:function(){this.dialogResetFilter.triggerMethod("show","favorite")}})});App.module("SearchResult.Views",function(n,t,i,r){n.SearchResultView=r.LayoutView.extend({itemView:null,itemViewContainer:null,model:i.Model,collection:i.Collection,template:"#search-result-template",ui:{messageBox:".js-message-box",resultsContainer:".js-results-container"},behaviors:{ViewUnwrap:{}},regions:{summaryIcons:".js-summary-icons",summaryPrices:".js-summary-prices",list:".js-itinerary-list",listMessages:".js-itinerary-list-messages",sliders:".js-itinerary-list-sliders",filterMenu:".js-itinerary-list-filter-menu-wrapper",favoritesBasket:".js-favorites-basket",lowestPrices:".js-lowest-prices",paginator:".js-paginator",errors:".js-errors"},modelEvents:{"change:response":"onResponseChanged","change:errors":"onErrorsChanged","change:filter":"onFilterChanged","change:filteredItineraries":"onFilteredItinerariesChanged","change:summary":"onSummaryChanged"},initialize:function(n){var e,o;$('<div class="js-booking-dialog" />').appendTo(t.Utils.Ui.bodySelector);this.addRegions({dialog:new i.Marionette.Region({el:".js-booking-dialog"})});t.Flights.SearchForm.trigger("blockShareButtons");this.searchParams=n.searchParams;this.searchTime=Math.floor((new Date).getTime()/6e4);this.additionalSearchParams=n.additionalSearchParams;this.listenTo(t.vent,t.VentActions.Pagination.SET_PAGE,_.bind(this.setPage,this));this.listenTo(t.vent,t.VentActions.Flights.ItemView.OPEN_BOOKING_DIALOG,_.bind(this.openBookingDialog,this));this.listenTo(t.vent,t.VentActions.Flights.ItemView.CLOSE_BOOKING_DIALOG,_.bind(this.closeBookingDialog,this));this.listenTo(t.vent,t.VentActions.Flights.ItemView.CONTINUE_BOOKING_DIALOG,_.bind(this.goToAgency,this));this.$searchWrapper=$(".search-wrapper-container");this._bookingValidationInProgress=!1;var r=this.model.get("filter"),u=t.Utils.StateStorage.Flights,f=u.getFilterSelections();(!r||f)&&(r||(r=this.setDefaultFiltersValues()),f&&(e=u.getPrev(),o=this._keepMenuFilters(e),o?(_.extend(r,f.menu),e.outbounddate===this.searchParams.outbounddate&&e.inbounddate===this.searchParams.inbounddate?(r.departTimeRange=r.departTimeRange||u.getFilterDepartTime(f),r.returnTimeRange=r.returnTimeRange||u.getFilterReturnTime(f)):u.clearFilterTime()):u.clearFilterSelections()),this.model.set({filter:r},{silent:!0}));u.saveStateAsPrev();this.model.set("lowestPricesAreDisplayed",this._lowestPricesAreDisplayed())},setDefaultFiltersValues:function(){var n={sortColumn:"price",sortDirection:"asc"},i=this.model.get("filter"),u=t.Services.Feature,r;return i&&i.sort&&i.sort.type?(n.sortColumn=i.sort.type,n.sortDirection="asc"):(r=t.Utils.StateStorage.Flights.getSorting(),r?n=r:u.check("defaultSortByDuration")&&(n.sortColumn="journey-duration")),{sort:{type:n.sortColumn,order:n.sortDirection},stops:u.check("filters","b")?"":"any",airlines:[],airports:[],connectingAirports:[],duration:null}},onSummaryChanged:function(){var r=this.model.get("frozen"),i,n;this.summaryPrices&&this.summaryPrices.currentView&&this.summaryPrices.currentView.triggerMethod("change:summary",this.model);this.summaryIcons&&this.summaryIcons.currentView&&this.summaryIcons.currentView.triggerMethod("change:summary",this.model);i=this.model.get("summary");i&&this.ui.messageBox.show();this.filterMenu&&this.filterMenu.currentView&&this.filterMenu.currentView.triggerMethod("summary:changed",this.model);this.sliders&&this.sliders.currentView&&this.sliders.currentView.triggerMethod("change:summary",this.model,this.searchParams);n=this.model.get("response");n&&n.Flights&&(r||this.onFilterChanged(),this.resetShareButton(n,i),this.model.trigger("change:filter"),this.changeProgressbar(),n.Flights.Status==="UpdatesComplete"&&(this.summaryIcons.currentView.enable(),this.sliders&&this.sliders.currentView&&this.sliders.currentView.enable(),this.paginator.currentView.showPagination(),this.trigger("progressbar:destroy"),t.vent.trigger(t.VentActions.Flights.SEARCH_FINISHED_SUMMARY,i),this.model.set("isDone",!0),t.SearchResult.ItineraryToOpen&&this._soldOutOrUpdateIfNeeded(t.SearchResult.ItineraryToOpen),this._scrollToItinerary()))},resetShareButton:function(n,i){var r,u;i&&i.cheapestShortest&&i.cheapestShortest.price&&(r=_.findWhere(n.Flights.Places,{Id:parseInt(n.Flights.Query.DestinationPlace)}),r.Type!=="City"&&r.ParentId&&(r=_.findWhere(n.Flights.Places,{Id:r.ParentId})),u={destinationPlace:r,price:i.cheapestShortest?i.cheapestShortest.price:null,currency:i.currency},t.Flights.SearchForm.trigger("resetShareButtons",u))},checkBestOffers:function(){var n=this.model.get("summary"),u=this.model.get("frozen"),r;if(n){var i=u?this.model.get("frozenItineraries"):this.model.get("filteredItineraries"),t={},f=n.cheapestShortest?_.findWhere(i,{bookingDetailsLinkBody:n.cheapestShortest.bookingDetailsLinkBody}):!1;t=_.extend(t,{cheapest:f});r=n.shortestCheapest?_.findWhere(i,{bookingDetailsLinkBody:n.shortestCheapest.bookingDetailsLinkBody}):!1;t=_.extend(t,{shortest:r});this.summaryPrices&&this.summaryPrices.currentView&&this.summaryPrices.currentView.triggerMethod("change:visibility",t)}},onFilterChanged:function(){var r=this.model.get("response"),i=this.model.get("filter"),n=this.model.get("summary"),u=i?t.Services.Flights.getFilteredItineraries(r,i,n):r&&r.Flights?r.Flights.Itineraries:[],f=!1;if(n){var e={price:0,duration:0,BookingDetailsLink:{Body:""}},o=_(u).sortBy("price")[0]||e,s=_(u).sortBy("duration")[0]||e,h=n.cheapestShortest.price===o.price,c=n.shortestCheapest.duration===s.duration;f=!(h&&c);n.cheapestShortest=o;n.shortestCheapest=s}this.model.set({filteredItineraries:u},{silent:!0});this.model.trigger("change:filteredItineraries",u);f&&this.model.trigger("change:summary",n);i&&i.sort&&t.Utils.StateStorage.Flights.setSorting({sortColumn:i.sort.type,sortDirection:"asc"})},onFilteredItinerariesChanged:function(){var u=this.model.get("frozen"),n=this.model.get("response"),r,t,i;this.checkBestOffers();r=this.model.get("filteredItineraries");this.summaryIcons&&this.summaryIcons.currentView&&this.summaryIcons.currentView.triggerMethod("change:filter",this.model);u?this.list.currentView.triggerMethod("freeze"):(t={},i={},n.Flights&&n.Flights.Itineraries&&n.Flights.Itineraries.length>0&&(t=_.findWhere(n.Flights.Places,{Id:parseInt(n.Flights.Query.DestinationPlace)}),t.Type!=="City"&&t.ParentId&&(t=_.findWhere(n.Flights.Places,{Id:t.ParentId})),_.extend(t,{cityCode:this.additionalSearchParams.destinationCityCode}),i=_.findWhere(n.Flights.Places,{Id:parseInt(n.Flights.Query.OriginPlace)}),i.Type!=="City"&&i.ParentId&&(i=_.findWhere(n.Flights.Places,{Id:i.ParentId}))),this.list.currentView.model.set({country:this.searchParams.country,destinationPlace:t,originPlace:i,response:n,filteredItineraries:r},{silent:!0}),this.list.currentView.model.trigger("change:filteredItineraries"));this.paginator.currentView.model.set({itemsCount:r.length});parseInt(this.paginator.currentView.model.get("maxpage"))<parseInt(this.list.currentView.model.get("page"))&&this.list.currentView.model.set("page",this.paginator.currentView.model.get("maxpage"))},recalculateFilters:function(n,i,r){var u,f,l,e,a,o;n=n?n:this.model.get("summary");u=this.model.get("filter");(!u||r)&&(u=this.setDefaultFiltersValues());var s=u.airports,h=u.connectingAirports,c=u.airlines;n&&(f=_.map(n.mainAirports,function(t){return _.findWhere(n.allAirports,{Code:t.code})}),_.each(f,function(t){var r=_.findWhere(s,{code:t.Code}),i;t.checked=r?r.checked:t.checked;i=_.findWhere(n.mainAirports,{code:t.Code});i&&(t.minPrice=i.minPrice)}),l=t.Utils.Filters.airportsChecker(s),u=_.extend(u,{airports:_.map(f,function(n){return{code:n.Code,checked:l.isSelected(n),name:n.Name,minPrice:n.minPrice}})}),e=n.ca,_.each(e,function(n){var t=_.findWhere(h,{code:n.code});n.checked=t?t.checked:n.checked}),a=t.Utils.Filters.airportsChecker(h),u=_.extend(u,{connectingAirports:_.map(e,function(n){return{code:n.code,checked:a.isSelected(n),name:n.name,minPrice:n.minPrice}})}),o=[],_.each(n.airlines,function(n){var t=_.findWhere(c,{code:n.id}),i;_.findWhere(c,{checked:!1})&&!t&&(n.checked=!1);i=t?t.checked:n.checked;n.minPrice&&n.filterable&&o.push({code:n.id,checked:i,id:n.id,name:n.name,minPrice:n.minPrice,displayCode:n.displayCode,filterable:n.filterable})}),u=_.extend(u,{airlines:o}),this.updateCachedFilter({airports:u.airports,connectingAirports:u.connectingAirports,airlines:u.airlines}),this.model.set("filter",u,{silent:!0}),i&&this.model.trigger("change:filter"))},onResponseChanged:function(){var r,i,n;this.ui.resultsContainer.show();r=this.model.get("response");i=t.Services.Flights.getSummaryModel(r,t.Settings.paginateBy);this.recalculateFilters(i);this.model.set("summary",i);n=this.model.get("response").Flights;n&&n.Itineraries.length===0&&n.Status==="UpdatesComplete"&&(this.list.currentView.model.set("response",this.model.get("response")),this.trigger("progressbar:destroy"),this.onFilterChanged());n.Status==="UpdatesComplete"&&t.vent.trigger(t.VentActions.Flights.SEARCH_FINISHED,i);this.filterMenu.currentView.triggerMethod("show")},changeProgressbar:function(){var n=this.model.get("response"),t=n.Flights.Agents.length,i=_.filter(n.Flights.Agents,function(n){return n.Status==="UpdatesComplete"}),r=t===0?0:100*i.length/t;n.Flights.Status!=="UpdatesComplete"&&(this.trigger("progressbar:setPercent",r),this.trigger("progressbar:setProgress",i.length,t))},onErrorsChanged:function(){if(this.errors.currentView)this.errors.currentView.collection.reset(this.model.get("errors"));else{var n=new t.SearchResult.Errors.ErrorListView({collection:new i.Collection(this.model.get("errors"))});this.errors.show(n)}},onSliderChanged:function(n){var u;this.model.set("frozen",!1);var r=n.model.get("start"),f=n.model.get("code"),i=_.clone(this.model.get("filter"));i||(i={});u=!1;switch(f){case"max.price":u=i.priceMax!==r;i=_.extend(i,{priceMax:r});break;case"depart.time":u=!i.departTimeRange||!i.departTimeRange.length||i.departTimeRange[0]!==r[0]||i.departTimeRange[1]!==r[1];i=_.extend(i,{departTimeRange:r});break;case"return.time":u=!i.returnTimeRange||!i.returnTimeRange.length||i.returnTimeRange[0]!==r[0]||i.returnTimeRange[1]!==r[1];i=_.extend(i,{returnTimeRange:r})}u&&t.Utils.Ui.trigger("inactive-veil:enable","SearchResultListView");this.model.set("filter",i);this.setFirstPage(1);this.list.currentView.$el.find(".js-itinerary-list-container").addClass("filtered-animate")},showSliders:function(n){this.slidersView=new t.SearchResult.Slider.SliderListView({model:new i.Model,collection:new i.Collection(n.get("sliders")),disabled:t.Utils.Ui.isSlowDevice()});this.slidersView.on("onSliderChanged",this.onSliderChanged,this);this.sliders.show(this.slidersView)},showFilters:function(){var i=[moment("2014-06-20 00:00").valueOf(),moment("2014-06-20 12:00").valueOf()],r=[moment("2014-06-20 12:00").valueOf(),moment("2014-06-20 18:00").valueOf()],u=[moment("2014-06-20 18:00").valueOf(),moment("2014-06-20 23:59").valueOf()],f=[{title:"sliders.morning",range:i,active:!0},{title:"sliders.afternoon",range:r,active:!0},{title:"sliders.evening",range:u,active:!0}],e=[{title:"sliders.morning",range:i,active:!0},{title:"sliders.afternoon",range:r,active:!0},{title:"sliders.evening",range:u,active:!0}],o=this.searchParams,n=[{code:"max.price",sliderClass:"price",title:"sliders.price.title",min:0,max:0,start:0,connect:"lower",type:"currency",currency:null,orderButton:!0},{code:"depart.time",sliderClass:"depart-time",title:"sliders.depart",min:moment("2014-06-20 00:00").valueOf(),max:moment("2014-06-20 23:59").valueOf(),titleAddon:"",start:[moment("2014-06-20 00:00").valueOf(),moment("2014-06-20 23:59").valueOf()],connect:!0,type:"time",buttons:f}];o.inbounddate&&(n[n.length]={code:"return.time",sliderClass:"return-time",title:"sliders.return",min:moment("2014-06-20 00:00").valueOf(),max:moment("2014-06-20 23:59").valueOf(),titleAddon:"",start:[moment("2014-06-20 00:00").valueOf(),moment("2014-06-20 23:59").valueOf()],connect:!0,type:"time",buttons:e});this.model.set("sliders",n);t.Services.Feature.check("filters","b")||this.showSliders(this.model)},onChangeBrowseCacheData:function(){var n=this.model.get("browseCacheData");this.lowestPrices&&this.lowestPrices.currentView&&this.lowestPrices.currentView.triggerMethod("change:browseCacheData",n);this.summaryPrices&&this.summaryPrices.currentView&&this.summaryPrices.currentView.triggerMethod("change:browseCacheData",n)},showBrowseCacheErrorMessage:function(n){this.lowestPrices&&this.lowestPrices.currentView&&this.lowestPrices.currentView.showError(n)},requestBrowseCacheData:function(){if(this._lowestPricesAreDisplayed()){var n=this,i=this.lowestPrices&&this.lowestPrices.currentView?this.lowestPrices.currentView.getChartsWidth():{departWidth:null,returnWidth:null};t.SearchResult.Utils.BrowseCache.getData(this.searchParams,i).done(_.bind(function(n){this.model.set("browseCacheData",n,{silent:!0});this.triggerMethod("change:browseCacheData")},this)).fail(function(t){t&&t.status&&n.showBrowseCacheErrorMessage(t.status)})}},initializeMessageBox:function(){t.MessageBox.on("module.ready",_.bind(function(n){n.model.get("messages").length>0&&this.ui.messageBox.append(n.render().$el)},this));t.vent.on(t.VentActions.Flights.SEARCH_FINISHED_SUMMARY,function(n){t.MessageBox.start(n)})},lowestPricesInit:function(){if(!t.Utils.Ui.isSlowDevice()&&!this.lowestPrices.currentView&&this.model.get("lowestPricesAreDisplayed")){var n=new t.LowestPrices.LowestPricesView({model:new i.Model({originplaceText:this.additionalSearchParams.originplaceText,destinationplaceText:this.additionalSearchParams.destinationplaceText,searchParams:_.clone(this.searchParams)}),containerSelector:this.lowestPrices.el});this.lowestPrices.show(n)}},favoritesBasketInit:function(){if(!this.favoritesBasketView){this.favoritesBasketView=new t.FavoritesBasket.Views.FavoritesBasketView({model:new i.Model({currentTab:"flights",searchState:this.searchParams})});this.favoritesBasketView.on("changed:favorite",function(){this.list.currentView&&this.list.currentView.updateFavorites.apply(this.list.currentView)},this);this.favoritesBasketView.on("jump-to-details",function(n){this._scrollToItinerary(n.fingerprint)},this);this.favoritesBasket.show(this.favoritesBasketView);this.model.set("favoritesBasketItemsCount",this.favoritesBasketView.getItemsCount())}},filterMenuInit:function(){this.fsview=new t.SearchResult.Filters.FilterMenuView({model:new i.Model({filter:this.model.get("filter")})});this.fsview.on("changeFilterEvent",this.onFilterMenuChanged,this);this.fsview.on("setFirstPageEvent",this.setFirstPage,this);this.filterMenu.show(this.fsview)},setFirstPage:function(){this.setPage(1)},onClickDetails:function(){var n=this.model.get("response");if(!n||!n.Flights)return!1;n.Flights.Status!=="UpdatesComplete"&&(this.model.set("frozen",!0),this.model.set("frozenItineraries",this.model.get("filteredItineraries")))},onUnfreeze:function(){this.model.set("frozen",!1);this.onFilteredItinerariesChanged();this.setFirstPage();t.Utils.Ui.scrollToElement(this.$el)},summaryIconsInit:function(){var n=new t.SearchResult.Views.SearchResultSummaryIconsView({disabled:t.Utils.Ui.isSlowDevice(),model:this.model});n.on("reset:filter",this.onResetFilters,this);n.on("changeFilterEvent",this.onFilterMenuChanged,this);this.summaryIcons.show(n)},onRender:function(){var r=this,f=this.searchParams,n=new t.SearchResult.Views.SearchResultItineraryListView({model:new i.Model,collection:new i.Collection([]),searchParams:f,additionalParams:this.additionalSearchParams}),u,e,o;n.on("load:firstResults",this.onFirstResultsLoad,this);n.on("reset:filter",this.onResetFilters,this);n.on("click:details",this.onClickDetails,this);n.on("click:baggage",this.onClickDetails,this);n.on("unfreeze",this.onUnfreeze,this);n.on("remove:inactiveLayout",this.removeInactiveLayout,this);this.list.show(n);this.lowestPricesInit();this.filterMenuInit();t.Services.Feature.check("disableFavorites","on")||this.favoritesBasketInit();this.summaryIconsInit();this.showFilters();u=new t.SearchResult.Views.SearchResultSummaryPricesView({sort:this.model.get("filter").sort});u.on("select:bestOffer",this.onSelectBestOffer,this);u.on("reset:filter",this.onResetFilters,this);u.on("reset:to:favorite",function(){this._favoriteOnFilterReset&&(this._findAndOpenByFingerprint(this._favoriteOnFilterReset),this._favoriteOnFilterReset=null)},this);u.on("sort",this.onFilterMenuChanged,this);this.summaryPrices.show(u);e=new t.Paginator.PaginatorView({model:new i.Model({paginateBy:AppSettings.paginateBy,aroundCount:1,gap:"...",page:1,itemsCount:0})});this.paginator.show(e);this.initializeMessageBox();n.model.set("paginateBy",r.paginator.currentView.model.get("paginateBy"),{silent:!0});setTimeout(function(){r.showShortLabel()},300);o=function(n){t.Services.Flights.getFlights(n).progress(function(n){r.model.set("response",n);t.vent.trigger(t.VentActions.Flights.SEARCH_PROGRESS,n)}).done(function(n){r.model.set("response",n)}).fail(function(n){r.showErrorMessage(n)});t.vent.trigger(t.VentActions.Flights.SEARCH_STARTED,n)};setTimeout(function(){r.requestBrowseCacheData();o(f)},this.getTimeout(10));this.$el.i18n()},showErrorMessage:function(n){if(n){var t;switch(n.status){case 429:t=$.i18n.t("errors-429.limit-exceeded");break;case 400:t=$.i18n.t("errors-400.bad-request");break;default:t=$.i18n.t("errors.message");Logger("flights-view").error("errorText: "+t+"|userAgent: "+navigator.userAgent+"|urlParams: "+JSON.stringify(this.searchParams))}n.message=t;this.trigger("progressbar:destroy");this.model.set("errors",null,{silent:!0});this.model.set("errors",n)}},showShortLabel:function(){t.Utils.Ui.isMobileView()&&t.Flights.SearchForm.trigger("show:shortLabel")},onFirstResultsLoad:function(){this.trigger("load:firstResults")},onResetFilters:function(){this.model.set("frozen",!1);var n=this.model.get("summary");this.recalculateFilters(n,!0,!0);t.Utils.StateStorage.Flights.clearFilterSelections();this.filterMenu&&this.filterMenu.currentView&&!t.Utils.Ui.isMobileView()&&this.filterMenu.currentView.triggerMethod("reset:filters",this.model);this.sliders&&this.sliders.currentView&&this.sliders.currentView.triggerMethod("reset:filters",this.model)},onFilterMenuChanged:function(n){this.updateCachedFilter(n);this.model.set("frozen",!1);Logger().debug("--> onFilterMenuChanged --> frozen is false");var i=this.model.toJSON().filter;i=_.extend(i,n);this.setFirstPage(1);(t.Utils.Ui.isIE9()||t.Utils.Ui.isIE8())&&this.list.currentView.$el.find(".js-itinerary-list-container").fadeOut(300);this.list.currentView.$el.find(".js-itinerary-list-container").addClass("filtered-animate");this.model.set({filter:i});this.model.trigger("change:filter")},removeInactiveLayout:function(){var n=t.Utils.Ui.isMobileView()?600:300;(t.Utils.Ui.isIE9()||t.Utils.Ui.isIE8())&&this.list.currentView.$el.find(".js-itinerary-list-container").fadeIn(n);window.clearTimeout(this._resultsFilterAnimationTimeout);this._resultsFilterAnimationTimeout=window.setTimeout(_.bind(function(){this.list.currentView.$el.find(".js-itinerary-list-container").removeClass("filtered-animate")},this),n)},updateCachedFilter:function(n){var r=_.pick(n,"duration","stops","priceMax","airports","airportsv2","connectingAirports","airlines","airlinesv2","sort","times"),i;_.keys(r).length&&(i=t.Utils.StateStorage.Flights.getFilterSelections()||{},i.menu=i.menu||{},_.extend(i.menu,n),t.Utils.StateStorage.Flights.setFilterSelections(i))},onDestroy:function(){window.clearTimeout(this._resultsFilterAnimationTimeout);this._resultsFilterAnimationTimeout=null},getCurrentPageNumber:function(){return this.list.currentView.model.set("page")},setPage:function(n,i){var u=this.model.get("frozen"),r=0;u&&(this.model.set("frozen",!1),this.onFilteredItinerariesChanged());this.list.currentView.model.set("page",n);this.paginator.currentView.model.set("page",n);i&&this.filterMenu&&(this.$searchWrapper.parent().hasClass("top-fixed")&&(r=-(this.$searchWrapper.height()+10)),t.Utils.Ui.scrollToElement(this.filterMenu.currentView.$el,r))},getTimeout:function(n){var i=n,u=moment().format(t.Settings.datetimeFormat),r=this.searchParams;return r&&r.timestamp>u&&(Logger().debug("actualSearch.timestamp > curTimestamp"),i=1e4),i},_processMultiPartBooking:function(n,i,r){var o=n.body,s=n.price,h=n.agents,l=n.uri,f=this.searchParams,e=!t.Services.Flights.isGroupPrice(f),c,u;e||(o+="&adults="+f.adults+"&children="+f.children+"&infants="+f.infants);c=new t.SearchResult.Views.BookingDialogView({model:new t.Models.BookingDialogModel({messageHeader:$.i18n.t("booking.checking.header"),hasProgress:!0,price:e?t.Utils.Ui.wrapPrice(s.amount,s.currency):"",agencyName:h.length>1?"":h[0].name,itineraryIndex:i})});this.dialog.show(c);this._bookingValidationInProgress=!0;u=this;t.tracking.trackEvent("day-view","Multipart_Loading");t.Services.Flights.getFlightBookingDetails(l,o).progress(function(t){if(u._bookingValidationInProgress){if(Logger().debug("booking check is continuing"),u.dialog.currentView.model.get("hasProgress")){var o=0,s=0;_.each(t.BookingOptions,function(n,t){_.each(t.BookingItems,function(n,t){s+=t.Status!=="Pending"?1:0;o++})});u.dialog.currentView.setPercent(100*s/o)}u._multibookingRespProcessing(t,n,f,e,!1,i,r)}}).done(function(o){if(u._bookingValidationInProgress){u.dialog.currentView.model.get("hasProgress")&&u.dialog.currentView.setPercent(100);t.Services.Feature.check("expandDeepLink","on")&&_.each(o.BookingOptions[0].BookingItems,function(n){n.Deeplink=t.tracking.expandDeepLink(n.Deeplink,n.AgentID)});Logger().debug("booking check finished");u._multibookingRespProcessing(o,n,f,e,!0,i,r)||Logger().debug("actual info unaccessible");var s={obsoletePrice:n.price.amount,price:Math.round(o.BookingOptions[0].BookingItems.reduce(function(n,t){return n+t.Price},0))};t.tracking.trackEvent("day-view","PriceStatus",t.Utils.Ui._concatPriceChangeEventLabel(s,n.price.currency));t.tracking.trackEvent("day-view","Multipart_Dialog")}}).fail(function(n){t.tracking.trackEvent("day-view","Multipart_Dialog_Failed","Error_"+n.status);n.status===410?(Logger().debug("-------error 410 -------"),t.Flights.SearchForm.search(u.searchParams)):n.status===500&&Logger().debug("-------error 500 -------");u.showErrorDialog()})},openBookingDialog:function(n,i,r){var u=n.priceData.agents.length;u===1?t.SearchResult.Utils.BookingHandler.processBooking({priceOptions:n,searchParams:this.searchParams,itineraryIndex:parseInt(i,10),priceIndex:parseInt(r,10)},this.searchTime):u>1?this._processMultiPartBooking(n.priceData,i,r):Logger("search-result-view").error("Price agent is not defined")},closeBookingDialog:function(){this.dialog.reset();this._bookingValidationInProgress=!1},goToAgency:function(n){window.open(n,"_blank");this.dialog.reset();this._bookingValidationInProgress=!1},_scrollToItinerary:function(n){var i=n||t.SearchResult.ItineraryToOpen;i&&setTimeout(_.bind(function(){this._findAndOpenByFingerprint(i);t.SearchResult.ItineraryToOpen=null;t.Flights.SearchForm.trigger("clear:itinerary")},this),100)},_multibookingRespProcessing:function(n,i,r,u,f,e,o){var l=i.agents,a=i.price,h=!1,c,b,k,s,y,p,w,g;if(l.length===1)return!0;if(l.length>1)if(c={},_.each(l,function(n){c[n.id.toString()]={name:n.name,imageUrl:n.imageUrl}}),b=_.every(n.BookingOptions[0].BookingItems,function(n){return!_.isUndefined(c[n.AgentID])}),b)if(k=_.pluck(n.BookingOptions[0].BookingItems,"Status"),s=this._getMultiPartBookingStatus(k),s==="Current"||s==="Estimated"){var nt=this,tt=s==="Estimated",d=[],v=0;_.each(n.BookingOptions[0].BookingItems,function(r){var u=_.clone(c[r.AgentID]);u.price=t.Utils.Ui.wrapPrice(r.Price,a.currency);u.deeplink=r.Deeplink;u.number=++v>9?v:"0"+v;u.segments=[];_.each(r.SegmentIds,function(r){var f=nt._getById(n.Segments,r),e=moment(f.DepartureDateTime,t.Settings.datetimePricingServiceFormat),o=moment.monthsShort()[e.get("month")],s=e.get("date")+" "+o+" "+e.get("year");u.segments.push({departure:s,origin:f.OriginStation.Code,destination:f.DestinationStation.Code,flightNumber:f.FlightNumber,carrierCode:_.isUndefined(i.displayCodes[f.Carrier.Id])?f.Carrier.Code:i.displayCodes[f.Carrier.Id]})});d.push(u)});y=_.reduce(n.BookingOptions[0].BookingItems,function(n,t){return n+t.Price},0);p="";u&&(p=tt?$.i18n.t("booking.estimated.header"):Math.ceil(y)>Math.ceil(a.amount)?$.i18n.t("booking.changed.header"):$.i18n.t("booking.live.header"));w=new t.SearchResult.Views.BookingDialogView({model:new t.Models.BookingDialogModel({messageHeader:$.i18n.t("booking.multipart.header"),messageContent:$.i18n.t("booking.multipart.content"),multiPart:!0,agents:d,total:t.Utils.Ui.wrapPrice(y,a.currency),priceComment:p,itineraryIndex:e})});this._trackBookEvent(w,e,o,r);this.dialog.show(w);this._bookingValidationInProgress=!1;h=!0}else(s==="NotAvailable"||s==="Failed")&&(g=_.reduce(n.BookingOptions[0].BookingItems,function(n,t){return n||t.Deeplink},""),this._showNotAvailableDialog(i,r,g,e,o),h=!0);else Logger().debug("Information about all agents hasn't been gotten");return!h&&f&&this.showErrorDialog(),h},_trackBookEvent:function(n,i,r,u){var f=u.originplace?u.originplace:"",e=u.destinationplace?u.destinationplace:"",o=f+"_"+e+"_PAX_"+u.adults+";"+u.children+";"+u.infants;n.on("continueEvent",function(){t.tracking.trackEvent("day-view","BookClick","Flights_"+i+"_"+r+"_"+o)})},_getMultiPartBookingStatus:function(n){var t=function(t){return _.any(n,function(n){return n===t})};return t("Failed")?"Failed":t("NotAvailable")?"NotAvailable":t("Pending")?"Pending":t("Estimated")?"Estimated":"Current"},_getById:function(n,t){return _.find(n,function(n){return n.Id===t})},_showNotAvailableDialog:function(n,i,r,u,f){var e=n.price,s=n.agents,o=new t.SearchResult.Views.BookingDialogView({model:new t.Models.BookingDialogModel({messageHeader:$.i18n.t("booking.unavailable.header"),messageContent:$.i18n.t("booking.unavailable.content"),priceObsolete:t.Utils.Ui.wrapPrice(e.amount,e.currency),agencyName:s[0].name,continueLink:r||n.deepLink||"",itineraryIndex:u})});this._trackBookEvent(o,u,f,i);this.dialog.show(o);this._bookingValidationInProgress=!1},showErrorDialog:function(){var n=new t.SearchResult.Views.BookingDialogView({model:new t.Models.BookingDialogModel({messageHeader:$.i18n.t("booking.errorGettingData.header"),messageContent:$.i18n.t("errors-429.limit-exceeded")})});this.dialog.show(n);this._bookingValidationInProgress=!1},onSelectBestOffer:function(n){var i=this.model.get("filteredItineraries"),u=_.findWhere(i,{bookingDetailsLinkBody:n}),f=_.indexOf(i,u),r=t.Services.Flights.getPageForIndex(f,t.Settings.paginateBy);this.getCurrentPageNumber()!==r&&this.setPage(r);this.list.currentView.collection.findWhere({bookingDetailsLinkBody:n}).set("isFocused",!0)},_soldOutOrUpdateIfNeeded:function(n){var u=this.model.get("response").Flights.Itineraries,r=_.findWhere(u,{fingerprint:n}),i=t.Utils.FavoritesStorage.Flights.getByFingerprint(n);i&&!i.soldOut&&t.Utils.Favorites.isSameFlightSearch(this.searchParams,i)&&(r?t.Utils.FavoritesStorage.Flights.updatePriceIfNeeded(n,r.price):t.Utils.FavoritesStorage.Flights.soldOutFavorite(n))},_findAndOpenByFingerprint:function(n){var u=this.model.get("response").Flights.Itineraries,i=_.find(u,function(t){return t.fingerprint===n}),r;if(this._favoriteOnFilterReset=null,i)if(r=_.some(this.model.get("filteredItineraries"),function(t){return t.fingerprint===n}),r)this.onSelectBestOffer(i.bookingDetailsLinkBody);else this._favoriteOnFilterReset=n,this.summaryPrices.currentView.onFavoriteTriggeredOut();else this.model.set("errors",[{message:$.i18n.t("sharing.itinerary.not-found")}]),t.Utils.Ui.scrollToElement(this.errors.$el,-100)},_triggerWidgetData:function(n,t){this.summaryPrices&&this.summaryPrices.currentView&&n&&n.price&&n.deepLink&&this.summaryPrices.currentView.triggerMethod("change:"+t,n,this.model)},_lowestPricesAreDisplayed:function(){return this.searchParams.cabinclass==="Economy"&&!t.Services.Flights.isGroupPrice(this.searchParams)&&!t.Utils.RoutesFilter.hasPredefinedRoutes()&&!t.Utils.RoutesFilter.hasPredefinedCarriers()},_keepMenuFilters:function(n){return n&&this.searchParams.adults===n.adults&&this.searchParams.children===n.children&&this.searchParams.infants===n.infants&&this.searchParams.cabinclass===n.cabinclass&&this.searchParams.originplace===n.originplace&&this.searchParams.destinationplace===n.destinationplace}})});App.module("SearchResult.Slider",function(n,t,i,r){n.SliderItemButtonView=r.ItemView.extend({model:i.Model,template:"#slider-item-button-template",className:"js-slider-button",events:{click:"onClick"},initialize:function(){this.model.get("active")||this.$el.addClass("inactive");var n=this.model.get("showStart");this.model.set("showStart",n?n:!1)},onClick:function(){this.$el.hasClass("inactive")||this.trigger("onButtonClick",this)}});n.SliderItemButtonCollectionView=r.CollectionView.extend({model:i.Model,childView:n.SliderItemButtonView,collection:i.Collection,childEvents:{onButtonClick:"onButtonClick"},onButtonClick:function(n){this.trigger("onButtonClick",n)}});n.SliderItemView=r.LayoutView.extend({model:i.Model,template:"#slider-item-template",tagName:"li",ui:{min:".js-min",max:".js-max",slider:".js-slider"},regions:{buttons:".js-buttons"},modelEvents:{change:"modelChanged"},onButtonClick:function(n){var i=n.$el.hasClass("active")?!0:!1,t;this.$el.find(".active").removeClass("active");i?this.resetSliderPoints():(n.$el.addClass("active"),t=n.model.get("range"),this.model.get("type")==="currency"&&(t=t.substr(1)),this.model.set("start",t),this.model.trigger("change"))},initialize:function(){var t=this.model.get("titleAddon"),n;this.model.set("titleAddon",t?t:"");n=this.model.get("buttons");this.model.set("buttons",n?n:[])},onRender:function(){var r=this,f=t.Utils.Sliders.getToolTips(this.model.get("type"),this.model.get("currency"),this.model.get("min"),this.model.get("max")),e,u;this.ui.slider.noUiSlider({range:{min:this.model.get("min"),max:this.model.get("max")},start:this.model.get("start"),connect:this.model.get("connect"),serialization:{lower:[f],upper:[f]}});this.ui.slider.on({set:function(){var n=r.ui.slider.val(),t,i;_.isArray(n)&&n.length>1&&(t=n[1]-n[0],i=(r.model.get("max")-r.model.get("min"))/100*4.3,t<i?r.$el.find(".tooltip").addClass("tooclose"):r.$el.find(".tooltip").removeClass("tooclose"));r.$el.find(".active").removeClass("active");r.model.set("start",null,{silent:!0});r.model.set("start",r.ui.slider.val())}});e=this.model.get("buttons");this.$el.addClass("slider-item-box");this.model.get("type")==="currency"&&this.$el.addClass("currency-slider");u=new n.SliderItemButtonCollectionView({collection:new i.Collection(e)});u.on("onButtonClick",this.onButtonClick,this);this.buttons.show(u);this.$el.i18n()},modelChanged:function(){var n=this.model.get("start");n&&(this.model.get("type")==="currency"&&(n=Math.ceil(n),this.model.attributes.start=n),this.ui.slider.val(n),this.trigger("onSliderChanged"))},resetSliderPoints:function(){this.model.set("start",[this.model.get("min"),this.model.get("max")]);this.ui.slider.val(this.model.get("start"))}});n.SliderListView=r.CompositeView.extend({template:"#slider-list-template",childView:n.SliderItemView,childViewContainer:".js-sliders",collection:i.Collection,childEvents:{onSliderChanged:"onSliderChanged"},ui:{sliders:".js-sliders"},disable:function(){this.options.disabled=!0;this.$el.addClass("buttons-disabled")},enable:function(){this.options.disabled=!1;this.$el.removeClass("buttons-disabled")},onSliderChanged:function(n){var i,o,f,s,r,u,e;n.model.get("type")==="currency"?(f=this.model.get("filter").sliders[0].currency.Code,i=this.model.get("filter").sliders[0].min,f&&i&&n.model.get("start")&&t.tracking.trackEvent("day-view","PriceFilter",f+"_"+i+"_"+n.model.get("start"))):(i=t.Culture.culture.formatDate(new Date(Math.ceil(n.model.get("start")[0])),{time:"short"}),i=t.Culture.culture.formatDate(new Date(Math.ceil(n.model.get("start")[1])),{time:"short"}),i&&o&&(s=n.model.get("code")==="depart.time"?"DepartTimeFilter":"ReturnTimeFilter",t.tracking.trackEvent("day-view",s,"Hours_"+i.replace(":","")+"_"+o.replace(":",""))),r=_.find(this.model.get("filter").sliders,function(t){return t.code===n.model.get("code")}),u=[],u.push(_.isUndefined(r)||r.min!==n.model.get("start")[0]?n.model.get("start")[0]:null),u.push(_.isUndefined(r)||r.max!==n.model.get("start")[1]?n.model.get("start")[1]:null),e=t.Utils.StateStorage.Flights.getFilterSelections()||{},e[n.model.get("code")]=u,t.Utils.StateStorage.Flights.setFilterSelections(e));this.trigger("onSliderChanged",n)},onRender:function(){this.options.disabled&&this.disable();this.$el.addClass("sliders-count-"+this.collection.length);this.$el.hide()},onResetFilters:function(n){var u=_.clone(n.get("summary")),f=_.clone(n.get("filter")),e=this.model.get("filter");if(u){var r=t.Services.Flights.getSliderRangeInfo(u,f,!0),o=this,s=e.sliders,i;_.each(s,function(n){switch(n.code){case"max.price":i=r.priceMax;break;case"depart.time":i=r.departTimeRange;break;case"return.time":i=r.returnTimeRange;break;default:throw"Slider does not exist";}o.$el.find(".js-slider-"+n.sliderClass).val(i)})}},separateTime:function(n,t){var i="000"+n,r=i.substr(i.length-t);return r.substr(0,2)+":"+r.substr(2)},onChangeSummary:function(n,i){var f=_.clone(n.get("summary")),w=_.clone(n.get("filter")),l=i,c,y,u;if(f){var r=t.Services.Flights.getSliderRangeInfo(f,w),e={priceMax:r.priceMax,departTimeRange:r.departTimeRange,returnTimeRange:r.returnTimeRange},o=[moment("2014-06-20 00:00").valueOf(),moment("2014-06-20 12:00").valueOf()],s=[moment("2014-06-20 12:00").valueOf(),moment("2014-06-20 18:00").valueOf()],h=[moment("2014-06-20 18:00").valueOf(),moment("2014-06-20 23:59").valueOf()],a=[{title:"sliders.morning",range:o,active:r.minOutBoundTime<=o[1],selected:r.departTimeRange[1]===o[1]},{title:"sliders.afternoon",range:s,active:f.timeBoundary.outboundTime.afternoon,selected:r.departTimeRange[0]===s[0]&&r.departTimeRange[1]===s[1]},{title:"sliders.evening",range:h,active:r.maxOutBoundTime>=h[0],selected:r.departTimeRange[0]===h[0]}],v=[{title:"sliders.morning",range:o,active:r.minInBoundTime<=o[1],selected:r.returnTimeRange[1]===o[1]},{title:"sliders.afternoon",range:s,active:f.timeBoundary.inboundTime.afternoon,selected:r.returnTimeRange[0]===s[0]&&r.returnTimeRange[1]===s[1]},{title:"sliders.evening",range:h,active:r.maxInBoundTime>=h[0],selected:r.returnTimeRange[0]===h[0]}],b=f.cheapest.price===f.dearest.price,p=r.minOutBoundTime===r.maxOutBoundTime;p&&(++r.maxOutBoundTime,++e.departTimeRange[1]);c=[{code:"max.price",sliderClass:"price",title:"sliders.price.title",min:f.cheapest.price,max:f.dearest.price,isDisabled:b,start:e.priceMax,connect:"lower",type:"currency",currency:f.currency,orderButton:!0},{code:"depart.time",sliderClass:"depart-time",title:"sliders.depart",min:r.minOutBoundTime,max:r.maxOutBoundTime,isDisabled:p,titleAddon:moment(l.outbounddate,t.Settings.dateFormat).format(t.Settings.dateFormatMonthDateDay),start:e.departTimeRange,connect:!0,type:"time",buttons:a}];l.inbounddate&&(y=r.minInBoundTime===r.maxInBoundTime,y&&(++r.maxInBoundTime,++e.returnTimeRange[1]),c[c.length]={code:"return.time",sliderClass:"return-time",title:"sliders.return",min:r.minInBoundTime,max:r.maxInBoundTime,isDisabled:y,titleAddon:moment(l.inbounddate,t.Settings.dateFormat).format(t.Settings.dateFormatMonthDateDay),start:e.returnTimeRange,connect:!0,type:"time",buttons:v});u=this;_.each(c,function(n){var r=t.Utils.Sliders.getToolTips(n.type,n.currency,n.min,n.max),i=u.$el.find(".js-slider-"+n.sliderClass),f;i.closest("li").toggleClass("disabled",n.isDisabled);i.noUiSlider({range:{min:n.min,max:n.max},start:n.start,connect:n.connect,aria:{label:$.t(n.title),minvalue:n.min,maxvalue:n.max,valuenow:n.start,getValueText:r.getTooltipText},serialization:{lower:[r],upper:[r]}},!0);n.isDisabled?i.attr("disabled","disabled"):i.removeAttr("disabled");n.type==="time"&&(f=i.next().find(".js-slider-button"),_.each(f,function(t,i){n.code==="depart.time"?(a[i].active?u.$el.find(t).removeClass("inactive"):u.$el.find(t).addClass("inactive"),a[i].selected?u.$el.find(t).addClass("active"):u.$el.find(t).removeClass("active")):(v[i].active?u.$el.find(t).removeClass("inactive"):u.$el.find(t).addClass("inactive"),v[i].selected?u.$el.find(t).addClass("active"):u.$el.find(t).removeClass("active"))}))});e=_.extend(e,{sliders:c});this.model.set("filter",e);this.$el.show()}}})});App.module("SearchResult",{startWithParent:!1,define:function(n,t,i){n.ResultsLayout=i.Marionette.LayoutView.extend({template:"#results-layout-template",ui:{poweredBy:".js-powered-by",resultsLayout:".js-results-layout"},regions:{progressBar:".js-results-progress-panel",main:".js-results-main-panel"},views:{},onRender:function(){this.progressBar.show(this.views.progressBarView);this.main.show(this.views.resultsView);this.views.progressBarView.setPercent();var n=new t.Views.PoweredByView({trackingLabel:"Logo_SearchResults"});this.ui.poweredBy.html(n.render().$el)},onLoadInitialResults:function(){t.Utils.Ui.scrollTo(this.ui.resultsLayout.offset().top-85)},onProgressBarDestroy:function(){this.views.progressBarView&&this.views.progressBarView.destroy()},onProgressBarSetPercent:function(n){this.views.progressBarView&&this.views.progressBarView.setPercent(n)},onProgressBarSetProgress:function(n,t){this.views.progressBarView&&this.views.progressBarView.setProgress(n,t)},_initializeProgressBar:function(){var n=new i.Model({min:10});t.SearchResult.ItineraryToOpen&&n.set({title:$.t("favorites.checking-flights")});this.views.progressBarView=new t.Views.ProgressbarView({model:n})},initialize:function(){$.when(t.Services.Language.getLanguage(),t.Services.Market.getMarket(),t.Services.Currency.getCurrency()).then(_.bind(function(n,r,u){var f=_.omit(this.model.attributes,"destinationplaceText","originplaceText","itinerary"),e;f=_.extend({},f,{locale:n,country:r,currency:u});t.Services.RoutesAndSuppliers.isEnabled&&(f.includeAgents=t.Services.RoutesAndSuppliers.getSelectedAgentsSync());e={destinationplaceText:this.model.get("destinationplaceText"),originplaceText:this.model.get("originplaceText"),destinationCityCode:this.model.get("destinationCityCode")};t.SearchResult.ItineraryToOpen=this.model.get("itinerary");this.views.resultsView=new t.SearchResult.Views.SearchResultView({model:new i.Model,collection:new i.Collection,searchParams:f,additionalSearchParams:e});this._initializeProgressBar();this.views.resultsView.on("progressbar:destroy",this.onProgressBarDestroy,this);this.views.resultsView.on("progressbar:setPercent",this.onProgressBarSetPercent,this);this.views.resultsView.on("progressbar:setProgress",this.onProgressBarSetProgress,this);if(t.Services.Feature.check("autoScrollToResults","on"))this.views.resultsView.on("load:firstResults",this.onLoadInitialResults,this);t.trigger("module.ready",{name:"SearchResult",view:this})},this))}});n.ResultsController=i.Marionette.Controller.extend({results:function(){(t.Router.CurrentRoute="Results",t.Router.is404())||(t.HelpTab.start(),t.Flights.SearchState.provide().done(function(i,r){var u;t.tracking.trackPageView("/dayview/"+i.locale+"/flights/"+i.originplaceCityCode+"/"+i.destinationCityCode);u=new t.Flights.Models.SearchStateModel(i);t.GoogleRemarketingTag.send(u);_.isEmpty(r)?(u=new t.Flights.Models.SearchStateModel(i),u.validate().done(function(i){t.WLSync.updateFlightsStatus();t.Flights.SearchForm.trigger("updateState",i);new n.ResultsLayout({model:i});t.ImageBanner.isStarted()?t.ImageBanner.showCityBanner({CityId:i.get("destinationCityCode"),CityName:i.get("destinationplaceText"),CountryId:i.get("destinationCountryCode"),CountryName:i.get("destinationCountryName")}):t.ImageBanner.start({city:{CityId:i.get("destinationCityCode"),CityName:i.get("destinationplaceText"),CountryId:i.get("destinationCountryCode"),CountryName:i.get("destinationCountryName")}});t.Settings.enableAds&&t.Utils.Ads.placeAdUnits(i);t.Utils.Ads.makeAdsSticky()}).fail(function(){t.Router.navigate("/",{trigger:!0});t.Flights.SearchForm.showForm()})):(t.Router.navigate("/",{trigger:!0}),t.Flights.SearchForm.trigger("updateState",u),t.Flights.SearchForm.trigger("show:errors",r))}),n.showLowestPrices=!1)}});n.addInitializer(function(){t.Router.processAppRoutes(new n.ResultsController,{result:"results"})})}});App.module("InspirationalPlaces",{startWithParent:!1,define:function(n,t,i,r,u){n.processContinentsForInspirational=function(n,i,r){return _.each(i,function(i){var f=i.countries,l,s,h,a,v;f=_.sortBy(f,function(n){return n.price});f=_.first(f,5);var c=_.findWhere(r,{id:i.id}),e=c.countries,o=_.findWhere(t.Dictionaries.PopularCountryCodes,{id:i.id});o&&(e=_.compact(_.map(o.countries,function(n){return _.findWhere(e,{code:n})})));_.each(e,function(n){_.extend(n,{code:n.code,name:n.name,wrappedPrice:"",isPopular:!0})});l=_.filter(e,function(i){return!_.findWhere(f,{code:i.code})&&(n.market!==i.code||_.contains(t.Dictionaries.AcceptedCountriesForDomesticFlights,i.code))});_.each(f,function(n){var t=_.findWhere(c.countries,{code:n.code}),i;t&&t.cities&&_.extend(n,{cities:t.cities,ThumbnailUrl:t.ThumbnailUrl});i=_.findWhere(e,{code:n.code});i&&_.extend(n,{isPopular:!0})});f=_.union(f,l);s=_.max(f,function(n){return n.price});s=s?s.price:0;h=_.min(f,function(n){return n.price});h=h?h.price:0;a=f.length>0?_.min(f,function(n){return n.duration}).duration:null;v=f.length>0?_.max(f,function(n){return n.duration}).duration:null;_.extend(i,{countries:f,maxPrice:s,minPrice:h,minDuration:a,maxDuration:v,displayName:o&&o.resource?u.t(o.resource):i.name})}),i};n.getSummary=function(n,t){var u=_.without(_.pluck(t,"minDuration"),null),f=_.without(_.pluck(t,"maxDuration"),null),r=[u.length>0?_.min(u,function(n){return n}):0,f.length>0?_.max(f,function(n){return n}):0],i=[_.min(t,function(n){return n.minPrice}).minPrice,_.max(t,function(n){return n.maxPrice}).maxPrice];return{currency:n.currency,market:n.market,price:i[0]&&i[1]&&i[0]>0&&i[1]>0?i:null,duration:r[0]<r[1]?r:null}};n.convertData=function(t){var i=t.routes.continents,u=t.geo.continents,r;return i=n.processContinentsForInspirational(t.routes,i,u),r=n.getSummary(t.routes,i),_.extend(t.routes,{continents:i,summary:r}),t.routes};n.initializeInspirationalPlaces=function(r){var u=n.convertData(r);t.Services.InspirationalPlaces.getAttributions().done(function(f){var o=function(n){var i=n.get("homecity"),f=n.get("code"),r=n.get("unpriced"),e=n.get("fullName"),o=n.get("countryName"),s=n.get("countryCode"),u=t.Utils.Date.getNearestFridayMonday(),h=r?moment(u.friday):n.get("outboundDepartureDate"),c=r?moment(u.monday):n.get("inboundDepartureDate");t.Flights.SearchForm.trigger("change:originPlace",{PlaceId:i.PlaceId,PlaceName:i.PlaceName});t.Flights.SearchForm.trigger("change:destinationPlace",{PlaceId:f,PlaceName:e,CountryName:o,CountryCode:s});t.Flights.SearchForm.trigger("change:cabinclass","Economy");t.Flights.SearchForm.trigger("change:date",h,c);t.Flights.SearchForm.search();t.vent.trigger(t.VentActions.SearchState.READY)},e=new n.InspirationalPlacesView({model:new i.Model({summary:u.summary,homecity:r.routes.homecity.PlaceName,tooltipsTitle:"inspirational-places.tooltips.title",title:"inspirational-places.title",titleDescription:"inspirational-places.description"}),collection:new i.Collection(u.continents),attributions:f,isInspirationalPlaces:!0});e.on("click:city",o,this);n.trigger("ready",e)})};n.on("start",_.bind(function(){t.Settings.config.showInspirationalPanel&&(t.Utils.Ui.is2xAndroid()||t.Utils.Ui.isFlights()&&(t.Services.OperatingCarriers.isEnabled||t.Services.RoutesAndSuppliers.isEnabled)||t.Services.InspirationalPlaces.getPlaces().done(_.bind(n.initializeInspirationalPlaces,this)))},this))}});App.module("MessageBox",{startWithParent:!1,initialize:function(n,t,i){this.cookieName="message-box-version";this.messageVersion=t.Settings.messageBoxVersion;this.checkPromotedPrice=i.checkPromotedPrice;this.checkMessage=i.checkMessage;this.formatPromotedPriceChange=i.formatPromotedPriceChange},checkMessage:function(){var n,t=this.messageVersion,i=this.cookieName;return t===""?($.removeCookie(i,{path:"/"}),!1):(n=$.cookie(i),!n||parseInt(n,10)<parseInt(t,10))?!0:!1},checkPromotedPrice:function(n){var u=new App.Utils.Uri(App.Utils.Location.getHref()),t=u.getQueryParamsObj(),i=u.getAnchorParams(),r=t.promotedPrice||i.promotedPrice,e=t.promotedCurrency||i.promotedCurrency,o=t.promotedProvider||i.promotedProvider,f=n.cheapest.price;return r?f>Number(r)?f-Number(r):!1:!1},formatPromotedPriceChange:function(n,t){return"<em class='price-change'>"+App.Utils.Ui.wrapPrice(n,t)+"<\/em>"},define:function(n,t,i,r,u){n.on("start",function(r){var o=n.checkMessage(),s=r?n.checkPromotedPrice(r):null,f=[],e;o&&f.push(u.t("message-box.text"));s&&f.push(u.t("promotedPrice").replace("__amount__",this.formatPromotedPriceChange(s,r.currency)));e=new t.Views.MessageBoxView({model:new i.Model({messages:f})});e.on("agree",_.bind(function(){o&&u.cookie(this.cookieName,this.messageVersion,{expires:365,path:"/"})},this));n.trigger("module.ready",e)})}});App.module("GoogleRemarketingTag",function(n,t){n.send=function(n){t.Services.Feature.check("googleRemarketingTag")&&$.isFunction(window.google_trackConversion)&&window.google_trackConversion({google_conversion_id:925383803,google_custom_params:{flight_originid:n.attributes.originplace,flight_destid:n.attributes.destinationplace,flight_startdate:n.attributes.outbounddate,flight_enddate:n.attributes.inbounddate,flight_pagetype:"cart",flight_totalvalue:null,flight_appname:AppSettings.config.shortApiKey},google_remarketing_only:!0})}})