/* Minification failed. Returning unminified contents.
(5218,49-69): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: nearbySearchErrorMsg
 */
/*global jQuery*/
(function ($) {
	'use strict';
	$.widget('ua.farewheel', {
		// Default options.
		options: {
			scrollAnim: 'swing',
			duration: 100,
			hideScrollClass: 'noScroll',
			leftLimitClass: 'maxLeft',
			rightLimitClass: 'maxRight',
			itemSelector: '.fare-wheel-item',
			searchedItemSelector: '.search-day',
			clipContainerSelector: '.fare-wheel',
			scrollContainerSelector: '.fare-wheel-scroll-container',
			scrollTriggerSelector: '.fare-wheel-scroll',
			scrollIncrement: 1, //set to 0 to scroll one "page" at a time
			beforeScroll: null,
			scroll: null,
			beforeSelectDay: null,
			selectDay: null
		},
		maxScrollLeft: 0,
		itemCount: 0,
		visibleItemCount: 0,
		itemWidth: 0,
		items: null,
		widgetWidth: 0,
		searchDayIndex: 0,
		clipContainerWidth: 0,
		clipContainer: null,
		scrollContainer: null,
		scrollTriggers: null,
		scrollAmount: 0,
		_checkScrollLimits: function (widget, isPreventTab) {
			var element = widget.element,
				options = widget.options,
				clipContainer = widget.clipContainer,
				scrollLeft = clipContainer.scrollLeft();
			element.removeClass(options.leftLimitClass).removeClass(options.rightLimitClass);
			if (scrollLeft <= 0) {
				element.addClass(options.leftLimitClass);
			}
			if (scrollLeft >= widget.maxScrollLeft) {
				element.addClass(options.rightLimitClass);
			}
			if (!isPreventTab) {
				widget._setFirstTabIndex();
			}
		},
		_scroll: function (event) {
			var widget = this,
				scrollAmount = widget.scrollAmount,
				target = $(event.currentTarget);
			if (event && widget._trigger('beforeScroll', event) === false) {
				return;
			}
			if (target.hasClass('left')) {
				scrollAmount = scrollAmount * -1;
			}
			widget._scrollTo('+=' + scrollAmount, event);
		},
		_scrollTo: function (position, event, isPreventTab) {
			var widget = this,
				options = widget.options;
			this.clipContainer.animate({ scrollLeft: position }, options.duration, options.scrollAnim, function () { widget._checkScrollLimits(widget, isPreventTab); widget._trigger('scroll', event); });
		},
		_selectDay: function (event) {
			if (event && this._trigger('beforeSelectDay', event) === false) {
				return;
			}
			this._trigger('selectDay', event);
		},
		_getFirstVisibleItemIndex: function () {
			var scrollAmmount = this.clipContainer.scrollLeft(),
				itemNo = null;
			if (this.itemWidth !== 0){
				itemNo = scrollAmmount / this.itemWidth;
			}
			return Math.round(itemNo);
		},
		_getLastVisibleItemIndex: function () {
			var scrollAmmount = this.clipContainer.scrollLeft(),
				itemNo = null;
			if (this.itemWidth !== 0){
				itemNo = (scrollAmmount / this.itemWidth) + (this.visibleItemCount - 1);
			}
			return itemNo;
		},
		_setFirstTabIndex: function () {
			var itemIndex = this._getFirstVisibleItemIndex(),
				item,
				options = this.options;
			if (itemIndex !== null) {
				this.items.attr("tabIndex", -1);
				item = this.items.eq(itemIndex);
				if (item.hasClass(options.searchedItemSelector)) {
					item = item.next(options.itemSelector);
				}
				item.attr("tabIndex", 0);
			}
		},
		_centerSearchedDay: function () {
			var offset, widget = this,
				options = widget.options,
				clipContainer = widget.clipContainer,
				sce = clipContainer.get(0);
			this.maxScrollLeft = sce.scrollWidth - sce.clientWidth;
			this.clipContainerWidth = clipContainer.width();
			this.visibleItemCount = this.clipContainerWidth / this.itemWidth;
			if (options.scrollIncrement > 0){
				this.scrollAmount = options.scrollIncrement * this.itemWidth;
			}
			else {
				this.scrollAmount = this.visibleItemCount * this.itemWidth;
			}
			offset = widget.itemWidth * (widget.searchDayIndex - (widget.visibleItemCount - 1) / 2);
			clipContainer.scrollLeft(offset);
			if (widget.visibleItemCount >= widget.itemCount) {
				widget.element.addClass(options.hideScrollClass);
			}
		},
		_keydown: function (event) {
			if (event.altKey || event.ctrlKey) {
				return;
			}

			var tempVisibleItemIndex, keyCode = $.ui.keyCode,
				length = this.items.length,
				currentIndex = this.items.index(event.target),
				toFocus = false,
				toFocusIndex = -1,
				toScrollTo = null,
				scrollAdjust = this.itemWidth,
				searchedItemSelector = this.options.searchedItemSelector;

			switch (event.keyCode) {
				case keyCode.RIGHT:
				case keyCode.DOWN:
					toFocusIndex = (currentIndex + 1) % length;
					toFocus = this.items[toFocusIndex];
					if ($(toFocus).is(searchedItemSelector)) {
						toFocusIndex = (currentIndex + 2) % length;
						toFocus = this.items[toFocusIndex];
					}
					tempVisibleItemIndex = this._getLastVisibleItemIndex();
					if (toFocusIndex > tempVisibleItemIndex) {
						toScrollTo = "+=" + (this.scrollAmount + scrollAdjust * (toFocusIndex - tempVisibleItemIndex - 1));
					}
					else if (toFocusIndex < this._getFirstVisibleItemIndex()) {
						toScrollTo = 0;
					}
					break;
				case keyCode.LEFT:
				case keyCode.UP:
					toFocusIndex = (currentIndex - 1 + length) % length;
					toFocus = this.items[toFocusIndex];
					if ($(toFocus).is(searchedItemSelector)) {
						toFocusIndex = (currentIndex - 2 + length) % length;
						toFocus = this.items[toFocusIndex];
						scrollAdjust = this.itemWidth;
					}
					tempVisibleItemIndex = this._getFirstVisibleItemIndex();
					if (toFocusIndex < tempVisibleItemIndex) {
						toScrollTo = "-=" + (this.scrollAmount + scrollAdjust * (tempVisibleItemIndex - toFocusIndex - 1));
					}
					else if (toFocusIndex > this._getLastVisibleItemIndex()) {
						toScrollTo = this.maxScrollLeft;
					}
					break;
				case keyCode.SPACE:
				case keyCode.ENTER:
					this._selectDay(event);
					break;
				case keyCode.HOME:
					toScrollTo = 0;
					toFocus = this.items[0];
					if ($(toFocus).is(searchedItemSelector)) {
						toFocus = this.items[0];
					}
					break;
				case keyCode.END:
					toScrollTo = this.maxScrollLeft;
					toFocus = this.items[length - 1];
					if ($(toFocus).is(searchedItemSelector)) {
						toFocus = this.items[length - 2];
					}
					break;
			}

			if (toFocus) {
				if(toScrollTo !== null){
					this._scrollTo(toScrollTo, event, true);
				}
				$(event.target).attr("tabIndex", -1);
				$(toFocus).attr("tabIndex", 0);
				toFocus.focus();
				event.preventDefault();
			}
		},
		_setupEvents: function () {
			var elements = this.items.add(this.scrollTriggers);
			this._off(elements);
			this._on(this.items, { keydown: "_keydown" });
			this._on(this.scrollTriggers, { click: "_scroll" });
			this._on(this.items, { click: "_selectDay" });
			this._focusable(this.items);
			this._hoverable(elements);
		},
		_create: function () {
			var self = this,
				options = self.options,
				element = this.element;
			self.clipContainer = element.find(options.clipContainerSelector);
			self.scrollContainer = element.find(options.scrollContainerSelector);
			self.scrollTriggers = element.find(options.scrollTriggerSelector);
			self.items = self.clipContainer.find(options.itemSelector);
			self.itemCount = self.items.length;
			self.itemWidth = self.items.not(options.searchedItemSelector).outerWidth(true);
			if (self.itemWidth === null || self.itemWidth === 0) {
				element.hide();
				return;
			}
			self.scrollContainer.width(self.itemCount * self.itemWidth);
			self.searchDayIndex = self.items.filter(options.searchedItemSelector).index();
			self._centerSearchedDay();
			self._checkScrollLimits(self);
			self._setupEvents();
		},
		_destroy: function () {
		}
	});
}(jQuery));;
/*global jQuery, UA, Handlebars, _, History */

(function ($) {
    'use strict';
    var previousValue, lastDestination,
        safeSessionStorage = UA.Utilities.safeSessionStorage;

    function fsrTip() {
        return {
            name: "",
            priority: 0,
            maximumOccurs: 0,
            defaultLevel: 0,
            level: 0,
            level1Possible: false,
            level2Possible: false,
            level3Possible: false,
            inserted: false,
            position: "",
            rowIndex: 0,
            indexChanged: false,
            primaryClassChanged: false,
            secondaryClassChanged: false,
            firstRowClassChanged: false,
            data: null,

            getPoint: function () {
                switch (this.level) {
                    case 1:
                        return 6;
                        break;
                    case 2:
                        return 3;
                        break;
                    case 3:
                        return 2;
                        break;
                    default:
                        return 0;
                        break;
                }
            },

            getMinimumPoint: function () {
                if (this.level3Possible) {
                    return 2;
                } else if (this.level2Possible) {
                    return 3;
                } else if (this.level1Possible) {
                    return 6;
                } else {
                    0;
                }
            },

            getMinimumLevel: function () {
                if (this.level3Possible) {
                    return 3;
                } else if (this.level2Possible) {
                    return 2;
                } else if (this.level1Possible) {
                    return 1;
                } else {
                    0;
                }
            },

            getPrimaryClass: function () {
                switch (this.level) {
                    case 1:
                        return "fl-search-segment-level-1";
                        break;
                    case 2:
                        return "fl-search-segment-level-2";
                        break;
                    case 3:
                        return "fl-search-segment-level-3";
                        break;
                    default:
                        return "";
                        break;
                }
            },

            getSecondaryClass: function () {
                switch (this.level) {
                    case 1:
                        return "";
                        break;
                    case 2:
                        switch (this.position) {
                            case "l":
                                return "fl-search-segment-level-2-l";
                                break;
                            case "r":
                                return "fl-search-segment-level-2-r";
                                break;
                            default:
                                return ""
                                break;
                        }
                        break;
                    case 3:
                        switch (this.position) {
                            case "l":
                                return "fl-search-segment-level-3-l";
                                break;
                            case "c":
                                return "fl-search-segment-level-3-c";
                                break;
                            case "r":
                                return "fl-search-segment-level-3-r";
                                break;
                            default:
                                return ""
                                break;
                        }
                        break;
                    default:
                        return "";
                        break;
                }
            },

            getFirstRowClass: function () {
                switch (this.rowIndex) {
                    case 1:
                        return "fl-search-segment-firstrow fl-search-segment-row-" + this.rowIndex;
                        break;
                    default:
                        return "fl-search-segment-row-" + this.rowIndex;
                        break;
                }
            },

            removeLevelClasses: function () {
                $("#hello").removeClass(function (index, className) {
                    return (className.match(/(^|\s)fl-search-segment-level-\S+/g) || []).join(' ');
                });
            }
        }
    }

    var fsrTipsClass = (function () {
        var nearbyErrorMinimumLevel = parseInt($("#hdnNearbyErrorMinimumLevel").val());
        var nearbyErrorDefaultLevel = parseInt($("#hdnNearbyErrorDefaultLevel").val());
        var oNearbyError = new fsrTip();
        oNearbyError.name = "nearbyError";
        oNearbyError.priority = parseInt($("#hdnNearbyErrorPriority").val());
        oNearbyError.maximumOccurs = parseInt($("#hdnNearbyErrorMaximumOccurs").val());
        oNearbyError.defaultLevel = nearbyErrorDefaultLevel;
        oNearbyError.level = nearbyErrorDefaultLevel;
        oNearbyError.level1Possible = nearbyErrorMinimumLevel >= 1 ? true : false;
        oNearbyError.level2Possible = nearbyErrorMinimumLevel >= 2 ? true : false;
        oNearbyError.level3Possible = nearbyErrorMinimumLevel >= 3 ? true : false;
        oNearbyError.inserted = false;
        oNearbyError.position = "";
        oNearbyError.indexChanged = false;
        oNearbyError.primaryClassChanged = false;
        oNearbyError.secondaryClassChanged = false;
        oNearbyError.onlyFsr1 = $("#hdnNearbyErrorOnlyFsr1").val() === "true" ? true : false;
        oNearbyError.includeMulticity = $("#hdnNearbyErrorIncludeMulticity").val() === "true" ? true : false;
        oNearbyError.buttonLike = $("#hdnNearbyErrorButtonLike").val() === "true" ? true : false;
        oNearbyError.data = null;

        var nearbyMinimumLevel = parseInt($("#hdnNearbyMinimumLevel").val());
        var nearbyDefaultLevel = parseInt($("#hdnNearbyDefaultLevel").val());
        var oNearby = new fsrTip();
        oNearby.name = "nearby";
        oNearby.priority = parseInt($("#hdnNearbyPriority").val());
        oNearby.maximumOccurs = parseInt($("#hdnNearbyMaximumOccurs").val());
        oNearby.defaultLevel = nearbyDefaultLevel;
        oNearby.level = nearbyDefaultLevel;
        oNearby.level1Possible = nearbyMinimumLevel >= 1 ? true : false;
        oNearby.level2Possible = nearbyMinimumLevel >= 2 ? true : false;
        oNearby.level3Possible = nearbyMinimumLevel >= 3 ? true : false;
        oNearby.inserted = false;
        oNearby.position = "";
        oNearby.indexChanged = false;
        oNearby.primaryClassChanged = false;
        oNearby.secondaryClassChanged = false;
        oNearby.onlyFsr1 = $("#hdnNearbyOnlyFsr1").val() === "true" ? true : false;
        oNearby.includeMulticity = $("#hdnNearbyIncludeMulticity").val() === "true" ? true : false;
        oNearby.buttonLike = $("#hdnNearbyButtonLike").val() === "true" ? true : false;
        oNearby.data = null;

        var nearbyCitiesMinimumLevel = parseInt($("#hdnNearbyCitiesMinimumLevel").val());
        var nearbyCitiesDefaultLevel = parseInt($("#hdnNearbyCitiesDefaultLevel").val());
        var oNearbyCity = new fsrTip();
        oNearbyCity.name = "nearbyCity";
        oNearbyCity.priority = parseInt($("#hdnNearbyCitiesPriority").val());
        oNearbyCity.maximumOccurs = parseInt($("#hdnNearbyCitiesMaximumOccurs").val());
        oNearbyCity.defaultLevel = nearbyCitiesDefaultLevel;
        oNearbyCity.level = nearbyCitiesDefaultLevel;
        oNearbyCity.level1Possible = nearbyCitiesMinimumLevel >= 1 ? true : false;
        oNearbyCity.level2Possible = nearbyCitiesMinimumLevel >= 2 ? true : false;
        oNearbyCity.level3Possible = nearbyCitiesMinimumLevel >= 3 ? true : false;
        oNearbyCity.inserted = false;
        oNearbyCity.position = "l";
        oNearbyCity.indexChanged = false;
        oNearbyCity.primaryClassChanged = false;
        oNearbyCity.secondaryClassChanged = false;
        oNearbyCity.onlyFsr1 = $("#hdnNearbyCitiesOnlyFsr1").val() === "true" ? true : false;
        oNearbyCity.includeMulticity = $("#hdnNearbyCitiesIncludeMulticity").val() === "true" ? true : false;
        oNearbyCity.buttonLike = $("#hdnNearbyCitiesButtonLike").val() === "true" ? true : false;
        oNearbyCity.data = null;

        var nonstopMsgMinimumLevel = parseInt($("#hdnNonstopSuggestionMinimumLevel").val());
        var nonstopMsgDefaultLevel = parseInt($("#hdnNonstopSuggestionDefaultLevel").val());
        var oNonstopMsg = new fsrTip();
        oNonstopMsg.name = "nonstopMsg";
        oNonstopMsg.priority = parseInt($("#hdnNonstopSuggestionPriority").val());
        oNonstopMsg.maximumOccurs = parseInt($("#hdnNonstopSuggestionMaximumOccurs").val());
        oNonstopMsg.defaultLevel = nonstopMsgDefaultLevel;
        oNonstopMsg.level = nonstopMsgDefaultLevel;
        oNonstopMsg.level1Possible = nonstopMsgMinimumLevel >= 1 ? true : false;
        oNonstopMsg.level2Possible = nonstopMsgMinimumLevel >= 2 ? true : false;
        oNonstopMsg.level3Possible = nonstopMsgMinimumLevel >= 3 ? true : false;
        oNonstopMsg.inserted = false;
        oNonstopMsg.position = "l";
        oNonstopMsg.indexChanged = false;
        oNonstopMsg.primaryClassChanged = false;
        oNonstopMsg.secondaryClassChanged = false;
        oNonstopMsg.onlyFsr1 = $("#hdnNonstopSuggestionOnlyFsr1").val() === "true" ? true : false;
        oNonstopMsg.includeMulticity = $("#hdnNonstopSuggestionIncludeMulticity").val() === "true" ? true : false;
        oNonstopMsg.buttonLike = $("#hdnNonstopSuggestionButtonLike").val() === "true" ? true : false;
        oNonstopMsg.data = null;

        var betterOfferMinimumLevel = parseInt($("#hdnBetterOffersMinimumLevel").val());
        var betterOfferDefaultLevel = parseInt($("#hdnBetterOffersDefaultLevel").val());
        var oBetterOffer = new fsrTip();
        oBetterOffer.name = "betterOffer";
        oBetterOffer.priority = parseInt($("#hdnBetterOffersPriority").val());
        oBetterOffer.maximumOccurs = parseInt($("#hdnBetterOffersMaximumOccurs").val());
        oBetterOffer.defaultLevel = betterOfferDefaultLevel;
        oBetterOffer.level = betterOfferDefaultLevel;
        oBetterOffer.level1Possible = betterOfferMinimumLevel >= 1 ? true : false;
        oBetterOffer.level2Possible = betterOfferMinimumLevel >= 2 ? true : false;
        oBetterOffer.level3Possible = betterOfferMinimumLevel >= 3 ? true : false;
        oBetterOffer.inserted = false;
        oBetterOffer.position = "l";
        oBetterOffer.indexChanged = false;
        oBetterOffer.primaryClassChanged = false;
        oBetterOffer.secondaryClassChanged = false;
        oBetterOffer.onlyFsr1 = $("#hdnBetterOffersOnlyFsr1").val() === "true" ? true : false;
        oBetterOffer.includeMulticity = $("#hdnBetterOffersIncludeMulticity").val() === "true" ? true : false;
        oBetterOffer.buttonLike = $("#hdnBetterOffersButtonLike").val() === "true" ? true : false;
        oBetterOffer.data = null;

        var defaultFsrTips = {
            nearbyError: oNearbyError,
            nearby: oNearby,
            nearbyCity: oNearbyCity,
            nonstopMsg: oNonstopMsg,
            betterOffer: oBetterOffer
        };

        var ordereds = [];
        var allItems = [];

        return {
            maximumRows: parseInt($("#hdnFsrTipsMaximumRows").val()),
            maximumTips: parseInt($("#hdnFsrTipsMaximumTips").val()),
            fsrTips: null,

            init: function () {
                this.fsrTips = [];
            },

            arrange: function () {
                if (ordereds == null || ordereds.length == 0) {
                    return;
                }

                var i;
                var j;
                var k;
                var l;
                var fsrTipsTemp1 = [];
                $.extend(true, fsrTipsTemp1, ordereds);

                var lenTemp1 = fsrTipsTemp1.length;
                for (i = 0; i < lenTemp1 - 1; ++i) {
                    for (j = i + 1; j < lenTemp1; ++j) {
                        if (fsrTipsTemp1[i].priority > fsrTipsTemp1[j].priority) {
                            var temp = fsrTipsTemp1[i];
                            fsrTipsTemp1[i] = fsrTipsTemp1[j];
                            fsrTipsTemp1[j] = temp;
                        }
                    }
                }

                var lenTemp2;
                var fsrTipsTemp2 = [];
                while (fsrTipsTemp1.length > 0) {
                    lenTemp2 = fsrTipsTemp2.push(fsrTipsTemp1.shift());

                    i = 0;
                    while (fsrTipsTemp1.length > 0) {
                        if (fsrTipsTemp2[lenTemp2 - 1].name == fsrTipsTemp1[i].name) {
                            var deletedItems = fsrTipsTemp1.splice(i, 1);
                            if (deletedItems != null && deletedItems.length > 0) {
                                fsrTipsTemp2.push(deletedItems[0]);
                            }
                        } else {
                            i++;
                        }
                        if (i == fsrTipsTemp1.length) {
                            break;
                        }
                    };
                };

                var points = 0;
                var group1s = 0;
                var group2s = 0;
                var group3s = 0;
                lenTemp2 = fsrTipsTemp2.length;
                for (i = 0; i < lenTemp2; ++i) {
                    if (fsrTipsTemp2[i].level3Possible) {
                        fsrTipsTemp2[i].level = 3;
                        group3s++;
                        points += 2;
                    } else if (fsrTipsTemp2[i].level2Possible) {
                        fsrTipsTemp2[i].level = 2;
                        group2s++;
                        points += 3;
                    } else if (fsrTipsTemp2[i].level1Possible) {
                        fsrTipsTemp2[i].level = 1;
                        group1s++;
                        points += 6;
                    }
                }

                var rows = group1s + Math.floor(group2s / 2) + Math.floor(group3s / 3);
                if (group2s % 2 + group3s % 3 > 0) {
                    rows++;
                    if (group2s % 2 + group3s % 3 > 2) {
                        rows++;
                    }
                }

                var remind3s = group3s % 3;
                var remind2s = group2s % 2;

                var bPerfect = false;
                if (remind3s == 1 && remind2s == 0) {
                    if (group3s == 1) {
                        for (i = 0; i < lenTemp2; ++i) {
                            if (fsrTipsTemp2[i].level == 3) {
                                fsrTipsTemp2[i].level = 1;
                                bPerfect = true;
                                break;
                            }
                        }
                    } else {
                        var sameName3s = [];
                        for (i = 0; i < lenTemp2; ++i) {
                            var indivalName = "";
                            var indivalName3s = [];
                            if (fsrTipsTemp2[i].level == 3) {
                                indivalName = fsrTipsTemp2[i].name;
                                indivalName3s.push(i);

                                for (j = i + 1; j < lenTemp2; ++j) {
                                    if (fsrTipsTemp2[i].name == fsrTipsTemp2[j].name) {
                                        indivalName3s.push(j);
                                    } else {
                                        i = j - 1;
                                        break;
                                    }
                                }

                                if (indivalName3s.length > 0) {
                                    sameName3s.push({ name: indivalName, occurs: indivalName3s });
                                }
                            }
                        }

                        var sameName2s = [];
                        for (i = 0; i < lenTemp2; ++i) {
                            var indivalName = "";
                            var indivalName2s = [];
                            if (fsrTipsTemp2[i].level == 2) {
                                indivalName = fsrTipsTemp2[i].name;
                                indivalName2s.push(i);
                            }
                            for (j = i + 1; j < lenTemp2; ++j) {
                                if (fsrTipsTemp2[i].name == fsrTipsTemp2[j].name) {
                                    indivalName2s.push(j);
                                } else {
                                    i = j - 1;
                                    break;
                                }
                            }

                            if (indivalName2s.length > 0) {
                                sameName2s.push({ name: indivalName, occurs: indivalName2s });
                            }
                        }

                        var lenSame3s = sameName3s.length;
                        for (i = 0; i < lenSame3s; ++i) {
                            if (sameName3s[i].occurs.length === 3) {
                                for (j = 0; j < lenSame3s; ++j) {
                                    if (j != i && sameName3s[j].occurs.length == 1) {
                                        fsrTipsTemp2[sameName3s[i].occurs[0]].level = 2;
                                        fsrTipsTemp2[sameName3s[i].occurs[1]].level = 2;
                                        fsrTipsTemp2[sameName3s[i].occurs[2]].level = 2;
                                        fsrTipsTemp2[sameName3s[j].occurs[0]].level = 2;
                                        bPerfect = true;
                                        break;
                                    }
                                }
                            }
                        }

                        if (!bPerfect) {
                            var lenSame2s = sameName2s.length;
                            for (i = 0; i < lenSame2s; ++i) {
                                if (sameName2s[i].occurs.length === 2) {
                                    fsrTipsTemp2[sameName2s[i].occurs[0]].level = 1;
                                    break;
                                }
                            }
                            for (i = 0; i < lenSame3s; ++i) {
                                if (sameName3s[i].occurs.length === 1) {
                                    fsrTipsTemp2[sameName3s[i].occurs[0]].level = 2;
                                    bPerfect = true;
                                    break;
                                }
                            }
                        }

                        if (!bPerfect) {
                            for (i = 0; i < lenSame3s; ++i) {
                                if (sameName3s[i].occurs.length === 2) {
                                    for (j = 0; j < lenSame3s; ++j) {
                                        if (j != i && sameName3s[j].occurs.length == 2) {
                                            fsrTipsTemp2[sameName3s[i].occurs[0]].level = 2;
                                            fsrTipsTemp2[sameName3s[i].occurs[1]].level = 2;
                                            fsrTipsTemp2[sameName3s[j].occurs[0]].level = 2;
                                            fsrTipsTemp2[sameName3s[j].occurs[1]].level = 2;
                                            bPerfect = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        if (!bPerfect) {
                            for (i = 0; i < lenSame3s; ++i) {
                                if (sameName3s[i].occurs.length === 2) {
                                    for (j = 0; j < lenSame3s; ++j) {
                                        if (j != i && sameName3s[j].occurs.length == 1) {
                                            for (k = 0; k < lenSame3s; ++k) {
                                                if (k != i && k != j && sameName3s[k].occurs.length == 1) {
                                                    fsrTipsTemp2[sameName3s[i].occurs[0]].level = 2;
                                                    fsrTipsTemp2[sameName3s[i].occurs[1]].level = 2;
                                                    fsrTipsTemp2[sameName3s[j].occurs[0]].level = 2;
                                                    fsrTipsTemp2[sameName3s[k].occurs[0]].level = 2;
                                                    bPerfect = true;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (!bPerfect) {
                            for (i = 0; i < lenSame3s; ++i) {
                                if (sameName3s[i].occurs.length === 1) {
                                    for (j = 0; j < lenSame3s; ++j) {
                                        if (j != i && sameName3s[j].occurs.length == 1) {
                                            for (k = 0; k < lenSame3s; ++k) {
                                                if (k != i && k != j && sameName3s[k].occurs.length == 1) {
                                                    for (l = 0; l < lenSame3s; ++l) {
                                                        if (l != i && l != j && l != k && sameName3s[l].occurs.length == 1) {
                                                            fsrTipsTemp2[sameName3s[i].occurs[0]].level = 2;
                                                            fsrTipsTemp2[sameName3s[j].occurs[0]].level = 2;
                                                            fsrTipsTemp2[sameName3s[k].occurs[0]].level = 2;
                                                            fsrTipsTemp2[sameName3s[l].occurs[0]].level = 2;
                                                            bPerfect = true;
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else if (remind3s == 0 && remind2s == 1) {
                    if (group2s == 1) {
                        for (i = 0; i < lenTemp2; ++i) {
                            if (fsrTipsTemp2[i].level == 2) {
                                fsrTipsTemp2[i].level = 1;
                                bPerfect = true;
                                break;
                            }
                        }
                    } else {
                        var sameName2s = [];
                        for (i = 0; i < lenTemp2; ++i) {
                            var indivalName = "";
                            var indivalName2s = [];
                            if (fsrTipsTemp2[i].level == 2) {
                                indivalName = fsrTipsTemp2[i].name;
                                indivalName2s.push(i);

                                for (j = i + 1; j < lenTemp2; ++j) {
                                    if (fsrTipsTemp2[i].name == fsrTipsTemp2[j].name) {
                                        indivalName2s.push(j);
                                    } else {
                                        i = j - 1;
                                        break;
                                    }
                                }

                                if (indivalName2s.length > 0) {
                                    sameName2s.push({ name: indivalName, occurs: indivalName2s });
                                }
                            }
                        }

                        var lenSame2s = sameName2s.length;
                        for (i = 0; i < lenSame2s; ++i) {
                            if (sameName2s[i].occurs.length === 1) {
                                fsrTipsTemp2[sameName2s[i].occurs[0]].level = 1;
                                bPerfect = true;
                                break;
                            }
                        }
                    }
                } else if (remind3s == 1 && remind2s == 1) {
                    if (group3s == 1) {
                        for (i = 0; i < lenTemp2; ++i) {
                            if (fsrTipsTemp2[i].level == 3) {
                                fsrTipsTemp2[i].level = 2;
                                bPerfect = true;
                                break;
                            }
                        }
                    } else {
                        var sameName3s = [];
                        for (i = 0; i < lenTemp2; ++i) {
                            var indivalName = "";
                            var indivalName3s = [];
                            if (fsrTipsTemp2[i].level == 3) {
                                indivalName = fsrTipsTemp2[i].name;
                                indivalName3s.push(i);

                                for (j = i + 1; j < lenTemp2; ++j) {
                                    if (fsrTipsTemp2[i].name == fsrTipsTemp2[j].name) {
                                        indivalName3s.push(j);
                                    } else {
                                        i = j - 1;
                                        break;
                                    }
                                }

                                if (indivalName3s.length > 0) {
                                    sameName3s.push({ name: indivalName, occurs: indivalName3s });
                                }
                            }
                        }

                        var lenSame3s = sameName3s.length;
                        for (i = 0; i < lenSame3s; ++i) {
                            if (sameName3s[i].occurs.length === 1) {
                                fsrTipsTemp2[sameName3s[i].occurs[0]].level = 2;
                                bPerfect = true;
                                break;
                            }
                        }
                    }
                } else if (remind3s == 2 && remind2s == 0) {
                    if (group3s == 2) {
                        for (i = 0; i < lenTemp2; ++i) {
                            if (fsrTipsTemp2[i].level == 3) {
                                fsrTipsTemp2[i].level = 2;
                                break;
                            }
                        }

                        for (j = i + 1; j < lenTemp2; ++j) {
                            if (fsrTipsTemp2[j].level == 3) {
                                fsrTipsTemp2[j].level = 2;
                                bPerfect = true
                                break;
                            }
                        }
                    } else {
                        var sameName3s = [];
                        for (i = 0; i < lenTemp2; ++i) {
                            var indivalName = "";
                            var indivalName3s = [];
                            if (fsrTipsTemp2[i].level == 3) {
                                indivalName = fsrTipsTemp2[i].name;
                                indivalName3s.push(i);

                                for (j = i + 1; j < lenTemp2; ++j) {
                                    if (fsrTipsTemp2[i].name == fsrTipsTemp2[j].name) {
                                        indivalName3s.push(j);
                                    } else {
                                        i = j - 1;
                                        break;
                                    }
                                }

                                if (indivalName3s.length > 0) {
                                    sameName3s.push({ name: indivalName, occurs: indivalName3s });
                                }
                            }
                        }

                        var lenSame3s = sameName3s.length;
                        for (i = 0; i < lenSame3s; ++i) {
                            if (sameName3s[i].occurs.length === 2) {
                                fsrTipsTemp2[sameName3s[i].occurs[0]].level = 2;
                                fsrTipsTemp2[sameName3s[i].occurs[1]].level = 2;
                                bPerfect = true;
                                break;
                            }
                        }
                        if (!bPerfect) {
                            for (i = 0; i < lenSame3s; ++i) {
                                if (sameName3s[i].occurs.length === 1) {
                                    fsrTipsTemp2[sameName3s[i].occurs[0]].level = 2;
                                    break;
                                }
                            }
                            for (j = i + 1; j < lenSame3s; ++j) {
                                if (sameName3s[j].occurs.length === 1) {
                                    fsrTipsTemp2[sameName3s[j].occurs[0]].level = 2;
                                    bPerfect = true;
                                    break;
                                }
                            }
                        }
                    }
                } else if (remind3s == 2 && remind2s == 1) {
                    var sameName3s = [];
                    for (i = 0; i < lenTemp2; ++i) {
                        var indivalName = "";
                        var indivalName3s = [];
                        if (fsrTipsTemp2[i].level == 3) {
                            indivalName = fsrTipsTemp2[i].name;
                            indivalName3s.push(i);

                            for (j = i + 1; j < lenTemp2; ++j) {
                                if (fsrTipsTemp2[i].name == fsrTipsTemp2[j].name) {
                                    indivalName3s.push(j);
                                } else {
                                    i = j - 1;
                                    break;
                                }
                            }

                            if (indivalName3s.length > 0) {
                                sameName3s.push({ name: indivalName, occurs: indivalName3s });
                            }
                        }
                    }

                    var sameName2s = [];
                    for (i = 0; i < lenTemp2; ++i) {
                        var indivalName = "";
                        var indivalName2s = [];
                        if (fsrTipsTemp2[i].level == 2) {
                            indivalName = fsrTipsTemp2[i].name;
                            indivalName2s.push(i);

                            for (j = i + 1; j < lenTemp2; ++j) {
                                if (fsrTipsTemp2[i].name == fsrTipsTemp2[j].name) {
                                    indivalName2s.push(j);
                                } else {
                                    i = j - 1;
                                    break;
                                }
                            }

                            if (indivalName2s.length > 0) {
                                sameName2s.push({ name: indivalName, occurs: indivalName2s });
                            }
                        }
                    }

                    var lenSame2s = sameName2s.length;
                    for (i = 0; i < lenSame2s; ++i) {
                        if (sameName2s[i].occurs.length === 1) {
                            fsrTipsTemp2[sameName2s[i].occurs[0]].level = 1;
                            break;
                        }
                    }
                    var lenSame3s = sameName3s.length;
                    for (i = 0; i < lenSame3s; ++i) {
                        if (sameName3s[i].occurs.length === 2) {
                            fsrTipsTemp2[sameName3s[i].occurs[0]].level = 2;
                            fsrTipsTemp2[sameName3s[i].occurs[1]].level = 2;
                            bPerfect = true;
                            break;
                        }
                    }

                    if (!bPerfect) {
                        for (i = 0; i < lenSame3s; ++i) {
                            if (sameName3s[i].occurs.length === 1) {
                                fsrTipsTemp2[sameName3s[i].occurs[0]].level = 2;
                                break;
                            }
                        }
                        for (j = i + 1; j < lenSame3s; ++j) {
                            if (sameName3s[j].occurs.length === 1) {
                                fsrTipsTemp2[sameName3s[j].occurs[0]].level = 2;
                                bPerfect = true;
                                break;
                            }
                        }
                    }
                }

                for (i = lenTemp2 - 1; i >= 0; --i) {
                    if (fsrTipsTemp2[i].level == 1 && fsrTipsTemp2[i].level2Possible) {
                        break;
                    }
                }

                if (i > 0) {
                    for (j = 0; j < i; ++j) {
                        if (fsrTipsTemp2[j].level == 2 && fsrTipsTemp2[j].level1Possible && fsrTipsTemp2[j].defaultLevel == 1 && fsrTipsTemp2[j].name != fsrTipsTemp2[j + 1].name) {
                            fsrTipsTemp2[j].level = 1;
                            fsrTipsTemp2[i].level = 2;
                            break;
                        }
                    }
                }

                var positions = [];
                for (i = 0; i < lenTemp2; ++i) {
                    positions[i] = i;
                }

                var total2s = 0;
                var firstI2 = 0;
                var secondI2 = 0;
                for (i = 0; i < lenTemp2; ++i) {
                    if (fsrTipsTemp2[i].level == 2) {
                        if (total2s % 2 == 0) {
                            firstI2 = i;
                        } else {
                            secondI2 = i;
                        }
                        total2s++;

                        if (total2s % 2 == 0) {
                            if (secondI2 - firstI2 > 1) {
                                var tempDeletedItem = fsrTipsTemp2.splice(secondI2, 1);
                                fsrTipsTemp2.splice(firstI2 + 1, 0, tempDeletedItem[0]);
                                var tempDeletedPosition = positions.splice(secondI2, 1);
                                positions.splice(firstI2 + 1, 0, tempDeletedPosition[0]);
                            }
                        }
                    }
                }

                var total3s = 0;
                var firstI3 = 0;
                var secondI3 = 0;
                var thirdI3 = 0;
                for (i = 0; i < lenTemp2; ++i) {
                    if (fsrTipsTemp2[i].level == 3) {
                        if (total3s % 3 == 0) {
                            firstI3 = i;
                        } else if (total3s % 3 == 1) {
                            secondI3 = i;
                        } else {
                            thirdI3 = i;
                        }
                        total3s++;

                        if (total3s % 3 == 0) {
                            if (secondI3 - firstI3 > 1) {
                                var tempDeletedItem = fsrTipsTemp2.splice(secondI3, 1);
                                fsrTipsTemp2.splice(firstI3 + 1, 0, tempDeletedItem[0]);
                                var tempDeletedPosition = positions.splice(secondI3, 1);
                                positions.splice(firstI3 + 1, 0, tempDeletedPosition[0]);
                            }

                            if (thirdI3 - firstI3 > 2) {
                                var tempDeletedItem = fsrTipsTemp2.splice(thirdI3, 1);
                                fsrTipsTemp2.splice(firstI3 + 2, 0, tempDeletedItem[0]);
                                var tempDeletedPosition = positions.splice(thirdI3, 1);
                                positions.splice(firstI3 + 2, 0, tempDeletedPosition[0]);
                            }
                        }
                    }
                }

                var rowPoints = 0;
                var rowIndex = 0;
                var previousRowIndex = 1;
                lenTemp2 = fsrTipsTemp2.length;
                for (i = 0; i < lenTemp2; ++i) {
                    rowIndex = Math.ceil((rowPoints + fsrTipsTemp2[i].getPoint()) / 6);
                    fsrTipsTemp2[i].rowIndex = rowIndex;

                    if (previousRowIndex == rowIndex) {
                        if (i == 0) {
                            if (fsrTipsTemp2[i].level == 1) {
                                fsrTipsTemp2[i].position = "c";
                            } else if (fsrTipsTemp2[i].level == 2) {
                                fsrTipsTemp2[i].position = "l";
                            } else {
                                fsrTipsTemp2[i].position = "l";
                            }
                        } else {
                            if (fsrTipsTemp2[i].level == 2) {
                                fsrTipsTemp2[i].position = "r";
                            } else if (fsrTipsTemp2[i].level == 3) {
                                if (rowPoints < 3) {
                                    fsrTipsTemp2[i].position = "c";
                                } else {
                                    fsrTipsTemp2[i].position = "r";
                                }
                            }
                        }
                    } else {
                        if (fsrTipsTemp2[i].level == 1) {
                            fsrTipsTemp2[i].position = "c";
                        } else if (fsrTipsTemp2[i].level == 2) {
                            if (rowPoints % 6 < 3) {
                                fsrTipsTemp2[i].position = "l";
                            } else {
                                fsrTipsTemp2[i].position = "r";
                            }
                        } else if (fsrTipsTemp2[i].level == 3) {
                            if (rowPoints % 6 < 2) {
                                fsrTipsTemp2[i].position = "l";
                            } else if (rowPoints % 6 < 4) {
                                fsrTipsTemp2[i].position = "c";
                            } else {
                                fsrTipsTemp2[i].position = "r";
                            }
                        }
                    }

                    rowPoints += fsrTipsTemp2[i].getPoint();
                    previousRowIndex == rowIndex;
                }

                this.fsrTips = [];
                this.fsrTips.length = 0;
                $.extend(true, this.fsrTips, fsrTipsTemp2);

                ordereds = [];
                ordereds.length = 0;
                var smallest = 0;
                while (smallest < lenTemp2) {
                    for (i = 0; i < lenTemp2; ++i) {
                        if (positions[i] == smallest) {
                            ordereds.push(fsrTipsTemp2[i]);
                            ++smallest;
                        }
                    }
                }
            },

            clear: function () {
                ordereds = [];
                ordereds.length = 0;
                allItems = [];
                allItems.length = 0;
                this.fsrTips = [];
                this.fsrTips.length = 0;
            },

            remove: function (elemName) {
                if (allItems != null) {
                    var len = allItems.length;
                    var i;
                    for (i = len - 1; i >= 0; --i) {
                        if (allItems[i].hasOwnProperty(elemName)) {
                            break;
                        }
                    }

                    if (i >= 0) {
                        var j;
                        for (j = i; j < len - 1; ++j) {
                            allItems[j] = allItems[j + 1];
                        }
                        allItems[len - 1] = null;
                        allItems.length = len - 1;
                    }
                }

                if (ordereds != null) {
                    var len = ordereds.length;
                    var i;
                    for (i = len - 1; i >= 0; --i) {
                        if (ordereds[i].hasOwnProperty(elemName)) {
                            break;
                        }
                    }

                    if (i >= 0) {
                        var j;
                        for (j = i; j < len - 1; ++j) {
                            ordereds[j] = ordereds[j + 1];
                        }
                        ordereds[len - 1] = null;
                        ordereds.length = len - 1;

                        this.arrange();

                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            },

            removeAll: function (elemName) {
                if (allItems != null) {
                    var bFound = false;
                    var len = 0;
                    do {
                        len = allItems.length;
                        if (len > 0) {
                            var i;
                            for (i = len - 1; i >= 0; --i) {
                                if (allItems[i].hasOwnProperty(elemName)) {
                                    bFound = true;
                                    break;
                                }
                            }

                            if (i >= 0) {
                                var j;
                                for (j = i; j < len - 1; ++j) {
                                    allItems[j] = allItems[j + 1];
                                }
                                allItems[len - 1] = null;
                                allItems.length = len - 1;
                            } else {
                                break;
                            }
                        }
                    } while (len > 0);
                }

                if (ordereds != null) {
                    var bFound = false;
                    var len = 0;
                    do {
                        len = ordereds.length;
                        if (len > 0) {
                            var i;
                            for (i = len - 1; i >= 0; --i) {
                                if (ordereds[i].hasOwnProperty(elemName)) {
                                    bFound = true;
                                    break;
                                }
                            }

                            if (i >= 0) {
                                var j;
                                for (j = i; j < len - 1; ++j) {
                                    ordereds[j] = ordereds[j + 1];
                                }
                                ordereds[len - 1] = null;
                                ordereds.length = len - 1;
                            } else {
                                break;
                            }
                        }
                    } while (len > 0);

                    if (bFound) {
                        this.arrange();
                    }

                    return bFound;
                } else {
                    return false;
                }
            },

            insert: function (elemName, data) {
                if (!defaultFsrTips.hasOwnProperty(elemName)) {
                    return null;
                }

                var insertedsMinimumPoint = 0;
                var inserteds = 0;
                var occurs = 0;
                var firstOccur = 0;
                var lastLevel = -1;
                var possibleLevel = 0;
                var maximumOccurs = 0;
                var minimumPoint = 0;
                var minimumLevel = 0;
                var defaultPriority = 0;
                var group1s = 0;
                var group2s = 0;
                var group3s = 0;
                var i;
                var j;
                var len = allItems.length;
                var defaultItem = defaultFsrTips[elemName];

                if (defaultFsrTips.hasOwnProperty(elemName)) {
                    maximumOccurs = defaultItem.maximumOccurs;
                    minimumPoint = defaultItem.getMinimumPoint();
                    minimumLevel = defaultItem.getMinimumLevel();
                    defaultPriority = defaultItem.priority;
                } else {
                    return null;
                }

                var newItem = new fsrTip();
                newItem.name = defaultItem.name;
                newItem.priority = defaultItem.priority;
                newItem.maximumOccurs = defaultItem.maximumOccurs;
                newItem.defaultLevel = defaultItem.defaultLevel;
                newItem.level = defaultItem.getMinimumLevel();
                newItem.level1Possible = defaultItem.level1Possible;
                newItem.level2Possible = defaultItem.level2Possible;
                newItem.level3Possible = defaultItem.level3Possible;
                newItem.inserted = true;
                newItem.position = "l";
                newItem.indexChanged = false;
                newItem.primaryClassChanged = false;
                newItem.secondaryClassChanged = false;
                newItem.onlyFsr1 = defaultItem.onlyFsr1;
                newItem.includeMulticity = defaultItem.includeMulticity;
                newItem.buttonLike = defaultItem.buttonLike;
                newItem.data = data;

                for (i = len - 1; i >= 0; --i) {
                    inserteds++;
                    insertedsMinimumPoint += allItems[i].getMinimumPoint();
                    if (allItems[i].getMinimumLevel() === 1) {
                        group1s++;
                    } else if (allItems[i].getMinimumLevel() === 2) {
                        group2s++;
                    } else if (allItems[i].getMinimumLevel() === 3) {
                        group3s++;
                    }

                    if (allItems[i].priority <= defaultPriority) {
                        if (lastLevel == -1) {
                            lastLevel = i;
                        }
                    }

                    if (allItems[i].name == elemName) {
                        occurs++;
                        firstOccur = i;
                    }
                }

                if (occurs >= maximumOccurs) {
                    return null;
                } else if (occurs > 0) {
                    if (firstOccur + occurs >= len) {
                        allItems.push(newItem);
                    } else {
                        allItems.splice(firstOccur + occurs - 1, 0, newItem);
                    }
                } else {
                    if (lastLevel == -1) {
                        allItems.unshift(newItem);
                    } else if (lastLevel == len - 1) {
                        allItems.push(newItem);
                    } else {
                        allItems.splice(lastLevel + 1, 0, newItem);
                    }
                }

                var tempAllItems = [];
                $.extend(true, tempAllItems, allItems);

                var tempFsrTips = [];
                len = tempAllItems.length;
                inserteds = 0;
                for (i = 0; i < len; ++i) {
                    var len1 = tempFsrTips.length;
                    if (len1 >= this.maximumTips) {
                        break;
                    }

                    group1s = 0;
                    group2s = 0;
                    group3s = 0;
                    insertedsMinimumPoint = 0;
                    for (j = 0; j < len1; ++j) {
                        insertedsMinimumPoint += tempFsrTips[j].getMinimumPoint();
                        var tempMinimumLevel = tempFsrTips[j].getMinimumLevel();
                        if (tempMinimumLevel === 1) {
                            group1s++;
                        } else if (tempMinimumLevel === 2) {
                            group2s++;
                        } else if (tempMinimumLevel === 3) {
                            group3s++;
                        }
                    }

                    var tempInsertedsMinimumPoint = insertedsMinimumPoint + tempAllItems[i].getMinimumPoint();
                    var tempGroup1s = group1s;
                    var tempGroup2s = group2s;
                    var tempGroup3s = group3s;
                    var allItemMinimumLevel = tempAllItems[i].getMinimumLevel();
                    if (allItemMinimumLevel == 1) {
                        ++tempGroup1s;
                    } else if (allItemMinimumLevel == 2) {
                        ++tempGroup2s;
                    } else {
                        ++tempGroup3s;
                    }

                    if (tempInsertedsMinimumPoint <= this.maximumRows * 6) {
                        var rows = tempGroup1s + Math.floor(tempGroup2s / 2) + Math.floor(tempGroup3s / 3);
                        if ((tempGroup2s % 2) / 2 + (tempGroup3s % 3) / 3 > 1) {
                            rows++;
                            rows++;
                        } else if ((tempGroup2s % 2) / 2 + (tempGroup3s % 3) / 3 > 0) {
                            rows++;
                        }

                        if (rows <= this.maximumRows) {
                            tempFsrTips.push(tempAllItems[i])
                        } else {
                            if (this.maximumRows * 6 - insertedsMinimumPoint < 2) {
                                break;
                            }
                        }
                    } else {
                        if (this.maximumRows * 6 - insertedsMinimumPoint < 2) {
                            break;
                        } else {
                            continue;
                        }
                    }
                }

                if (tempFsrTips.length > 0) {
                    ordereds = [];
                    ordereds.length = 0;
                    $.extend(true, ordereds, tempFsrTips);

                    this.arrange();

                    return newItem;
                } else {
                    return null;
                }
            }
        };
    })();

    function log() {
        return UA.Utilities.log.apply(this, arguments); //ignore jslint - used in apply call
    }
    UA.Utilities.namespace('UA.Booking.FlightSearch');

    UA.Booking.FlightSearch = (function () {
        var FILTERS_ACTION_NONE = 0;
        var FILTERS_ACTION_USED = 1;
        var FILTERS_ACTION_GUI_APPLIED = 2;
        var FILTERS_ACTION_CLEAR_CLICK = 4;
        //var dcmPopulated = false;
        var triggeredStateChange = false;
        var isInitialload = true;
        var existtripIndex = -1;
        var isDatePickerErrorOpened = false;
        var scCurrentCabinIndex = -1;
        var scColumnClick = false;
        var scOptVal = null;
        var showFsrTips = false;
        var fsrTipsPhase2 = false; 
        var fsrTipsShowNearbyError = false;
        var fsrTipsShowNearby = false;
        var fsrTipsShowNearbyCities = false;
        var fsrTipsShowNonstopSuggestion = false;
        var fsrTipsShowBetterOffers = false;
        var filterActionClick = false;
        var IsSignModalClosed = false;
        var IsServiceCallCompleted = false;
        var IsPageContentRead = false;

        function extractCity(airport, airportDecoded) {
            var airportPieces = [];
            if (airportDecoded) {
                airportPieces = airportDecoded.split(',');
                if (airportPieces.length > 0) {
                    return airportPieces[0];
                } else {
                    return airport;
                }
            } else {
                return airport;
            }
        }

        function formatDate(dt) {
            var dte = new Date(dt);
            return UA.Utilities.formatting.formatShortDate(dte);
        }

        function formatAMPM(date) {
            var a, strTime, countries12Hour, hours, minutes, ampm;
            if ($('#hdnIsSignedIn').val() === "True") {
                a = $('#hdnPreferredTime').val() == "H:mm" ? -1 : 1;
            } else {
                countries12Hour = ["Micronesia | English", "Guam | English", "Panama | English", "Puerto Rico | English", "India | English", "Northern Mariana Islands | English", "Azerbaijan | English", "Canada | English", "United States | English"];
                a = jQuery.inArray(document.getElementById('current-lang').value, countries12Hour);
            }

            if (a >= 0) {
                hours = date.getHours();
                minutes = date.getMinutes();
                ampm = hours >= 12 ? 'pm' : 'am';
                hours = hours % 12;
                hours = hours || 12;
                minutes = minutes < 10 ? '0' + minutes : minutes;
                strTime = hours + ':' + minutes + ' ' + ampm;
            }
            else {
                hours = date.getHours();
                minutes = date.getMinutes();
                hours = hours || 12;
                minutes = minutes < 10 ? '0' + minutes : minutes;
                strTime = hours + ':' + minutes;
            }
            return strTime;
        }

        function formatDateNoWeekDay(dt) {
            var dte = new Date(dt);
            return UA.Utilities.formatting.formatShortDateNoWeekDay(dte);
        }
        function formatShortDate(dt) {
            var dte = new Date(dt);
            return UA.Utilities.formatting.formatDateCustom("mm/dd/yy", dte);
        }

        function logErrors(errors) {
            if (errors) {
                $.each(errors, function (index, value) {
                    log(value);
                });
                UA.UI.logCustomErrors(errors);
            }
        }

        function handleRestartSearchClick(event) {
            if (!($(event.currentTarget).data('restart-search') === 'refresh')) {
                UA.Booking.FlightSearch.currentResults.appliedSearch.more = true;
            }
            UA.Booking.FlightSearch.currentResults.appliedSearch.CartId = '';
            var form = $(UA.Utilities.assembleForm(UA.Booking.FlightSearch.currentResults.appliedSearch));
            $('body').append(form);
            form.submit();
        }

        function displayErrorDialog(errors, cartId) {
            if (errors) {
                $('#FlightResultsError').find('li')[0].innerHTML = errors[0];
                $('#FlightResultsError').show();
            }
            if (cartId !== 'undefined') {
                $('#CartId').val(cartId);
            }
        }

        function parseTime(dt) {
            if (!dt) {
                return '';
            }
            if (dt.length === 0) {
                return '';
            }
            var time = dt.split(' ');
            return time[1];
        }

        function splitHoursMinutes(value) {
            return UA.Utilities.formatting.formatSplitHoursMinutes(value);
        }

        function combineConnectionsWithFlights(flights) {
            var flightNumbers = [];
            _.forEach(flights, function (f) {
                flightNumbers.push(f.FlightNumber);
                if (f.Connections && f.Connections.length > 0) {
                    _.forEach(f.Connections, function (c) {
                        flightNumbers.push(c.FlightNumber);
                    });
                }
            });
            return flightNumbers;
        }

        function registerHelpers() {

            Handlebars.registerHelper({
                minutesToHour: function (min) {
                    var hours = Math.floor(min / 60),
                        minutes = min % 60;
                    if (hours === 0) {
                        return minutes + 'm';
                    }
                    if (minutes === 0) {
                        return hours + "h";
                    }
                    return hours + "h" + ' ' + minutes + 'm';
                },
                monthYear: function () {
                    var date = new Date();
                    return date.getMonthName(true) + ' ' + date.getFullYear();
                },
                departureMonthYear: function (year, month) {
                    if (year && month)
                    {
                        var date = new Date(year, month - 1);
                        return date.getMonthName(true) + ' ' + date.getFullYear();
                    }
                    return "--";                    
                },
                oneBase: function (index) {
                    return ++index;
                },
                debug: function (optionalValue) {
                    log("\nCurrent Context");
                    log("====================");
                    log(this);

                    if (optionalValue) {
                        log("\nValue");
                        log("====================");
                        log(optionalValue);
                    }
                },
                compareTwo: function (v1, operator, v2, operator2, v4, options) {
                    return ((v1 != v2) && (previousValue != v4)) ? options.fn(this) : options.inverse(this);
                },
                checkIsLastDestination: function (value, options) {
                    return value != lastDestination ? options.fn(this) : options.inverse(this);
                },
                compare: function (v1, operator, v2, options) {
                    switch (operator) {
                        case '==':
                            return (v1 == v2) ? options.fn(this) : options.inverse(this); //ignore jslint - operator specific
                        case '===':
                            return (v1 === v2) ? options.fn(this) : options.inverse(this);
                        case '!=':
                            return (v1 != v2) ? options.fn(this) : options.inverse(this); //ignore jslint - operator specific
                        case '<':
                            return (v1 < v2) ? options.fn(this) : options.inverse(this);
                        case '<=':
                            return (v1 <= v2) ? options.fn(this) : options.inverse(this);
                        case '>':
                            return (v1 > v2) ? options.fn(this) : options.inverse(this);
                        case '>=':
                            return (v1 >= v2) ? options.fn(this) : options.inverse(this);
                        case '&&':
                            return (v1 && v2) ? options.fn(this) : options.inverse(this);
                        case '||':
                            return (v1 || v2) ? options.fn(this) : options.inverse(this);
                        default:
                            return options.inverse(this);
                    }
                },
                CompareWithTodayDate: function (year, month, dateValue, today, options) {
                    var today = new Date(today);
                    today.setHours(0, 0, 0, 0);
                    var calDate = UA.Utilities.formatting.parseDate('yy-m-d', year + '-' + month + '-' + dateValue);
                    return (calDate >= today) ? options.fn(this) : options.inverse(this);
                },
                CompareBeyond337Days: function (year, month, dateValue, today, options) {
                    var today = new Date(today);
                    today.addDays(337);
                    var calDate = UA.Utilities.formatting.parseDate('yy-m-d', year + '-' + month + '-' + dateValue);
                    return (today >= calDate) ? options.fn(this) : options.inverse(this);
                },
                savePrevious: function (value, connections) {
                    previousValue = value;
                    if (connections) {
                        var connObject = connections[connections.length - 1];
                        if (connObject != null)
                            lastDestination = connections[connections.length - 1].Destination;
                    }
                },
                contains: function (v1, v2, options) {
                    if (typeof v1 === 'string') {
                        return v1 && v2 ? (v1.indexOf(v2) > -1) ? options.fn(this) : options.inverse(this) : "";
                    }
                    return v1 && v2 ? ($.inArray(v2, v1) > -1) ? options.fn(this) : options.inverse(this) : "";
                },
                isContainsString: function (str1, str2, options) {
                    if (typeof str1 === 'string' && typeof str2 === 'string' && str1 && str2) {
                        str1 = str1.toLowerCase();
                        str2 = str2.toLowerCase();
                        return (str1.indexOf(str2) > -1) ? options.fn(this) : options.inverse(this);
                    }
                    return options.inverse(this);
                },
                toIdAttribute: function (str) {
                    if (typeof str === 'string') {
                        return UA.Utilities.escapeAttributeValue(str.toLowerCase().replace(/\s/g, '-'));
                    }
                    return "";
                },
                toLowerCase: function (str) {
                    if (typeof str === 'string') {
                        return str.toLowerCase();
                    }
                    return "";
                },
                parseTime: function (dt) {
                    return parseTime(dt);
                },
                formatDate: function (year, month, day) {
                    var date = new Date(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10), 12, 0, 0, 0),
                        dateString = date.toDateString();
                    return (dateString.substring(4, 7) + ". " + dateString.substring(8));
                },
                formatFirstLetter: function (dayOfWeek) {
                    return dayOfWeek.substr(0, 1);
                },
                formatThreeLetter: function (dayOfWeek) {
                    return dayOfWeek.substr(0, 3);
                },
                formatLongDate: function (year, month, day) {
                    var date = new Date(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10));
                    return (UA.Utilities.formatting.formatLongDate(date));
                },
                formatLongDateAlt: function (date) {
                    if (typeof date === 'string') {
                        date = Date.parseExact(date, 'MM/dd/yyyy');
                    }
                    return (UA.Utilities.formatting.formatLongDate(date));
                },
                formatLongMonth: function (dateString) {
                    var date = UA.Utilities.formatting.tryParseDate(dateString);
                    if (date) {
                        return Date.CultureInfo.monthNames[date.getMonth()];
                    }
                    return null;
                },
                formatShortMonth: function (month) {
                    return Date.CultureInfo.abbreviatedMonthNames[month];
                },
                formatShortMonthOneBasedNumbering: function (month) {
                    return Date.CultureInfo.abbreviatedMonthNames[month - 1];
                },
                fareSizeClass: function (value) {
                    if (value && value >= 7) {
                        return "large-currency";
                    }
                    return "";
                },
                isExpertMode: function (value, options) {
                    if (UA.Booking.FlightSearch.currentResults.IsExpertMode) {
                        return options.fn(this);
                    }
                    return options.inverse(this);
                },
                isAdRow: function (rowNumber, totalFlights, options) {
                    var adRowNumber = 0,
                        flightCountThreshold = 4;
                    if (totalFlights > flightCountThreshold) {
                        adRowNumber = 3;
                    } else if (totalFlights === flightCountThreshold) {
                        adRowNumber = 2;
                    } else if (totalFlights < flightCountThreshold) {
                        adRowNumber = totalFlights - 1;
                    }

                    if (rowNumber === adRowNumber) {
                        return options.fn(this);
                    }
                    return options.inverse(this);
                },
                fareWheelSizeClass: function (value) {
                    if (value >= 8) {
                        return "large-currency";
                    }
                    if (value > 6) {
                        return "medium-currency";
                    }
                    return "";
                },
                sorterDisplay: function (context, options) {
                    var sorterData = Handlebars.createFrame(options.data || {});

                    if (!options.hash['appliedSearch']) {
                        return options.fn(context);
                    }

                    sorterData.priceActive = false;

                    switch (options.hash['appliedSearch'].SortType) {
                        case 'departure_early':
                            sorterData.departureActive = true;
                            sorterData.sortDirection = "ascending";
                            break;
                        case 'departure_late':
                            sorterData.departureActive = true;
                            sorterData.sortDirection = "descending";
                            break;
                        case 'arrival_early':
                            sorterData.arrivalActive = true;
                            sorterData.sortDirection = "ascending";
                            break;
                        case 'arrival_late':
                            sorterData.arrivalActive = true;
                            sorterData.sortDirection = "descending";
                            break;
                        case 'stops_low':
                            sorterData.stopsActive = true;
                            sorterData.sortDirection = "ascending";
                            break;
                        case 'stops_high':
                            sorterData.stopsActive = true;
                            sorterData.sortDirection = "descending";
                            break;
                        case 'duration_fastest':
                            sorterData.durationActive = true;
                            sorterData.sortDirection = "ascending";
                            break;
                        case 'duration_longest':
                            sorterData.durationActive = true;
                            sorterData.sortDirection = "descending";
                            break;
                        case 'price_low':
                            sorterData.priceActive = UA.Booking.FlightSearch.currentResults.appliedSearch.SearchFilters != undefined &&
                                UA.Booking.FlightSearch.currentResults.appliedSearch.SearchFilters.RealFareFamily != undefined &&
                                UA.Booking.FlightSearch.currentResults.appliedSearch.SearchFilters.RealFareFamily === options.hash['productType'];
                            sorterData.sortDirection = "ascending";
                            sorterData.isSortedFare = UA.Booking.FlightSearch.currentResults.SearchFilters.FareFamily === context.FareFamily;
                            break;
                        case 'price_high':
                            sorterData.priceActive = UA.Booking.FlightSearch.currentResults.appliedSearch.SearchFilters != undefined &&
                                UA.Booking.FlightSearch.currentResults.appliedSearch.SearchFilters.RealFareFamily != undefined &&
                                UA.Booking.FlightSearch.currentResults.appliedSearch.SearchFilters.RealFareFamily === options.hash['productType'];
                            sorterData.sortDirection = "descending";
                            sorterData.isSortedFare = UA.Booking.FlightSearch.currentResults.SearchFilters.FareFamily === context.FareFamily;
                            break;

                        default:
                            break;
                    }

                    return options.fn(context, {
                        data: sorterData
                    });
                },
                isRequireEditSearch: function (selFlightIndex, TripIndex, options) {
                    if (selFlightIndex == (TripIndex - 1)) {
                        return options.fn(this);
                    }
                    return options.inverse(this);
                },
                formatWarning: function (description) {
                    if (!description) {
                        return "";
                    }
                    if (typeof description === "string" && description.indexOf("_") > -1) {
                        description = description.replace(/_/g, ' ').toLowerCase();
                    }
                    return description;
                },
                ifVisibleWarnings: function (context, options) {

                    var visibleWarnings = _.filter(context, function (warning) {
                        return !warning.Hidden;
                    });

                    if (visibleWarnings.length) {
                        return options.fn(this);
                    }
                    return options.inverse(this);
                },
                airportDescription: function (description) {
                    if (!description) {
                        return "";
                    }
                    if (_.indexOf(description, "/") > -1) {
                        description = description.replace("/", " / ");
                    }
                    if (_.isString(description) && _.indexOf(description, "(") > -1) {
                        return description.substr(0, _.indexOf(description, "("));
                    }
                    return description;
                },
                amenitiesExist: function (context, options) {

                    var amenitiesExist = _.filter(context, function (amenity) {
                        return amenity.Key != "Other";
                    });

                    if (amenitiesExist.length) {
                        return options.fn(this);
                    }
                    return options.inverse(this);
                },
                hasLmxData: function (context, options) {

                    if (options.data.root.IsLmxIncluded == false) {
                        return options.inverse(this);
                    }

                    var lmxExists = _.filter(context, function (product) {
                        return product.LmxLoyaltyTiers && product.LmxLoyaltyTiers !== null;
                    });

                    if (lmxExists.length) {
                        return options.fn(this);
                    }
                    return options.inverse(this);
                },
                isLmxAccrualCapped: function (context, options) {

                    var capExists = _.filter(context, function (tier) {

                        var quoteCapExists = _.filter(tier.LmxQuotes, function (quote) {
                            return quote.IsCapped;
                        });
                        return quoteCapExists.length;
                    });

                    if (capExists.length) {
                        return options.fn(this);
                    }
                    return options.inverse(this);
                },
                trimAirportCity: function (airport) {
                    var city = (airport != null ? airport.substring(0, airport.indexOf('(')) : "");
                    return city;
                },
                trimAirportName: function (airport) {
                    var name = (airport != null ? airport.substring(airport.indexOf('(') + 1, airport.indexOf(')')) : "");
                    return name;
                },
                formatShortDay: function (date) {
                    return UA.Utilities.formatting.formatDay(UA.Utilities.formatting.tryParseDate(date));
                },
                formatDayMonth: function (date) {
                    return UA.Utilities.formatting.formatShortDateNoWeekDay(UA.Utilities.formatting.tryParseDate(date));
                },
                formatShortDateNoYear: function (date){
                    return UA.Utilities.formatting.formatShortDateNoYear(UA.Utilities.formatting.tryParseDate(date));
                },
                getConsolidateMessage: function (connections) {
                    if (connections) {
                        var consolidateChaseBenefitMessage = '';
                        for (var i = 0; i < connections.length; i++) {
                            if (connections[i].ChaseBenefitMessage && connections[i].ChaseBenefitMessage.trim() != '') {
                                consolidateChaseBenefitMessage = connections[i].ChaseBenefitMessage;
                                break;
                            }
                        }
                        return consolidateChaseBenefitMessage;
                    } else {
                        return '';
                    }
                },
                setSelectValue: function (value, options) {
                    var select = document.createElement('select');
                    select.innerHTML = options.fn(this);
                    select.value = value;
                    if (select.children[select.selectedIndex]) {
                        select.children[select.selectedIndex].setAttribute('selected', 'selected');
                    } else {
                        if (select.children[0]) {
                            select.children[0].setAttribute('selected', 'selected');
                        }
                    }
                    return select.innerHTML;
                },
                getRecommendedFlightMessage: function (hashCode) {
                    var message = '';
                    _.forEach(UA.Booking.FlightSearch.recommendedFlights, function (hash) {
                        if (hash.hash == hashCode) {
                            message = hash.message;
                        }
                    });
                    return message;
                },
                ifCond: function (v1, v2, options) {
                    console.log(v1);
                    console.log(v2);
                    if (v1 && v2 && v1.toLowerCase() === v2.toLowerCase()) {
                        return options.fn(this);
                    }
                    return options.inverse(this);
                },
                splitcount: function (value) {
                    if (value) {
                        return value.split(',').length;
                    }
                    return 0;
                },
                isallairportexist: function (v1, v2, options) {
                    if (v2) {
                        var airportlist = v2.split(',');
                        var isallexist = true;
                        v1.forEach(function (airport) {
                            if ($.inArray(airport.Code, airportlist) < 0) {
                                isallexist = false;
                            }
                        });
                        if (isallexist)
                            return options.fn(this);
                        else
                            return options.inverse(this);
                    }
                    return options.inverse(this);
                },
                ifProductAvailable: function (isAvailableOnly, upgradeOptions, options) {
                    var upgOpt = getUpgradeOption(isAvailableOnly, upgradeOptions);
                    if (upgOpt) {
                        return options.fn(this);
                    }
                    else {
                        return options.inverse(this);
                    }
                },
                selectUpgradeOption: function (isAvailableOnly, upgradeOptions, options) {

                    var upgOpt = getUpgradeOption(isAvailableOnly, upgradeOptions);
                    if (upgOpt) {
                        return options.fn(upgOpt);
                    }
                    else {
                        return options.inverse(this);
                    }
                },
                selectSegmentMapping: function (segmentMappings, origin, destination, options) {
                    if (segmentMappings && segmentMappings.length > 0) {
                        if (segmentMappings.length == 1) {
                            return options.fn(segmentMappings[0]);
                        }
                        else {
                            var segmentMapping = _.find(segmentMappings, function (segment) { return segment.Origin === origin && segment.Destination === destination });
                            if (segmentMapping) {
                                return options.fn(segmentMapping);
                            }
                            return options.inverse(this);
                        }
                    }
                    return options.inverse(this);
                },
                selectAvailableLmxProduct: function (Products, options) {
                    if (Products != null && Products.length > 0) {
                        for (var i = 0; i < Products.length; i++) {
                            if (Products[i] != null && Products[i].LmxLoyaltyTiers != null) {
                                if (Products[i].LmxLoyaltyTiers[0].LmxQuotes.length > 0) {
                                    return options.fn(Products[i]);
                                    break;
                                }
                            }
                        }
                    }
                    return options.inverse(this);
                },
                Is2019Flight: function (DepartDateTime, options) {
                    if (typeof DepartDateTime === "string" && DepartDateTime.indexOf("2019") > -1) {
                        return options.fn(this);
                    }
                    return options.inverse(this);
                },
                filterMessages: function (messages, options) {
                    if (messages && messages.length > 0) {
                        return options.fn(UA.Booking.FlightSearch.prioritizeMessages(messages));
                    }
                    return options.inverse(this);
                },
            });
        }

        function getUpgradeOption(isAvailableOnly, upgradeOptions) {
            var upgOpt = null;
            if (isAvailableOnly) {
                upgOpt = _.find(upgradeOptions, function (upgrade) {
                    return upgrade.UpgradeType == "UGC" && _.some(upgrade.SegmentMapping, function (segment) {
                        return segment.UpgradeStatus != null && segment.UpgradeStatus.toUpperCase() == "AVAILABLE";
                    });
                });
                if(!upgOpt){
                    upgOpt = _.find(upgradeOptions, function (upgrade) {
                        return upgrade.UpgradeType == "CUG" && _.some(upgrade.SegmentMapping, function (segment) {
                            return segment.UpgradeStatus != null && segment.UpgradeStatus.toUpperCase() == "CONFIRMABLE";
                        });
                    });
                }
            }
            else
            {
                upgOpt = _.find(upgradeOptions, function (upgrade) {
                    return upgrade.UpgradeType == "UGC";
                });
                if (!upgOpt) {
                    upgOpt = _.find(upgradeOptions, function (upgrade) {
                        return upgrade.UpgradeType == "MUA";
                    });
                }
            }
            return upgOpt;
        }

        function getAwardCalendarFillerData(awardCalendarType) {

            var isMonthly = awardCalendarType === 1 || (typeof awardCalendarType === 'string' && awardCalendarType.toLowerCase() === "monthly");
            var fakeCalendarData = { "loading": true, "Months": [{ "Month": 11, "NextSelectDate": "01/01/2017", "PreviousSelectDate": "01/01/2017", "ShowNextMonthIndicator": true, "ShowPreviousMonthIndicator": true, "Weeks": [] }], "IsWeeklyCalendarView": !isMonthly, "IsMonthlyCalendarView": isMonthly, "CalendarRangeStart": "Jan 1, 2017", "CalendarRangeEnd": "Jan 7, 2017", "CalendarRangeDesc": "" }
            var fakeCalendarDay = { "DateValue": "--", "SearchedDay": false, "Products": [{ "Prices": [{ "AmountFormat": "--" }, { "AmountFormat": "$--" }] }], "Month": 1, "Year": 2017, "DayOfWeekFormat": "Weekday" }
            var fakeCalendarWeek = { "Days": [] }

            for (var d = 0; d < 7; d++) {
                fakeCalendarWeek.Days.push(fakeCalendarDay);
            }

            if (isMonthly) {
                for (var w = 0; w < 5; w++) {
                    fakeCalendarData.Months[0].Weeks.push(fakeCalendarWeek);
                }
            } else {
                fakeCalendarData.Months[0].Weeks.push(fakeCalendarWeek);
            }

            return fakeCalendarData;
        }

        function setTopFiltersMinPricesNonStopAndStops(_this, response, filteredFlights) {
            filteredFlights.SearchFilters.StopAmountTop = response.SearchFilters ? response.SearchFilters.StopFormattedAmountAward : "";
            filteredFlights.SearchFilters.NonStopAmountTop = response.SearchFilters ? response.SearchFilters.NonStopFormattedAmountAward : "";
        }

        return {
            currentResults: {},
            recommendedFlightsResults: {},
            selectedFlights: [],
            selectedFlightsProduct: [],
            recommendedFlights: [],
            filteredRecommendedFlights: [],
            lineLoaderState: "",
            shopBookingDetailsError: {},
            setElements: function () {
                this.elements = {};
                this.elements.container = $("#fl-results-wrapper");
                this.elements.currentTripIndex = $("#hdnCurrentTripIndex");
                this.elements.calendarContainer = $("#fl-calendar-wrap");
                this.elements.resultsContainer = $("#fl-results");
                this.elements.resetNotificationContainer = $("#fl-bestresult-notification");
                this.elements.fullPageLoader = $('#fl-results-loader-full');
                if (showFsrTips) {
                    if (fsrTipsPhase2) {
                        this.elements.resultsHeaderFsrTips = $('#fl-search-header-fsrtips');
                    } else {
                        this.elements.resultsHeaderSegmentNonstopSuggestion = $('#fl-search-header-segment-nonstopsuggestion');
                        this.elements.resultsHeaderSegmentNearbyCities = $('#fl-search-header-segment-nearbycities');
                        this.elements.resultsHeaderSegmentBetterOffers = $('#fl-search-header-segment-betteroffers');
                    }
                }
                this.elements.resultsHeaderSegmentContainer = $('#fl-search-header-segment-placeholder');
                this.elements.resultsStopNonStopLoader = $('.loader-section-fsr');
                this.elements.resultsStopNonStopLoaderText = $('.loader-section-text');
                this.elements.resultsHeaderSegmentFareDisclaimerContainer = $('#fl-search-header-segment-fare-disclaimer-placeholder');
                this.elements.resultsHeaderContainer = $('#fl-search-header-placeholder');
                this.elements.selectedFlightContainer = $('#fl-selected-segment-wrap');
                this.elements.newSearchContainer = $('#fl-new-search-wrap');
                this.elements.filterSortContainer = $('#fl-filter-sort-wrap');
                this.elements.searchCountFlagContainer = $('#fl-searchcount-wrap');
                this.elements.searchCountVisuallyHiddenFlagContainer = $('#fl-searchcount-container-visuallyhidden');
                this.elements.resultsFooter = $('#fl-results-footer');
                this.elements.filterConnectionId = 'filter-checkbox-connections';
                this.elements.filterOriginId = 'filter-checkbox-origin';
                this.elements.filterDestinationId = 'filter-checkbox-destination';
                this.elements.filterAmenitiesId = 'filter-checkbox-amenities';
                this.elements.filterAdvisoriesId = 'filter-checkbox-advisories';
                this.elements.sorterContainerId = '#fl-result-sorters';
                this.elements.fareMatrixCalendarSection = '#fare-matrix-section';
                this.elements.tabbedFareWheelSection = $('#tabbed-fare-wheel-section');
                this.elements.lineLoaderSection = $('#line-loader-section');
                this.elements.farematrixlineLoaderSection = $('#fare-matrix-lineloader-section');
                this.elements.awardLineLoaderSection = $('#fare-award-lineloader-section');
                this.elements.plusMinusThreeDayLinkSection = $('#plus-minue-three-days-section');
                this.elements.singleColumnFSRLowFareSection = $('#singlecolumnfsr-lowestfare-section');
                this.elements.lineLoaderMessageSection = $('#line-loader-content');
                this.elements.awardLineLoaderMessageSection = $('#award-line-loader-content');
                this.elements.noFlightMesssageSection = $('#fl-no-flight-search');
                
            },
            init: function () {
                showFsrTips = $("#hdnShowFsrTips").length > 0 && $("#hdnShowFsrTips").val() === "true";
                fsrTipsPhase2 = $("#hdnShowFsrTipsPhase2").length > 0 && $("#hdnShowFsrTipsPhase2").val() === "true";
                fsrTipsShowNearbyError = $("#hdnShowNearbyError").length > 0 && $("#hdnShowNearbyError").val() === "true";
                fsrTipsShowNearby = $("#hdnShowNearby").length > 0 && $("#hdnShowNearby").val() === "true";
                fsrTipsShowNearbyCities = $("#hdnShowNearbyCities").length > 0 && $("#hdnShowNearbyCities").val() === "true";
                fsrTipsShowNonstopSuggestion = $("#hdnShowNonstopSuggestion").length > 0 && $("#hdnShowNonstopSuggestion").val() === "true";
                fsrTipsShowBetterOffers = $("#hdnShowBetterOffers").length > 0 && $("#hdnShowBetterOffers").val() === "true";
                this.fsrTipsData = fsrTipsClass;
                this.fsrTipsData.init();
                //set initial search values
                $("#hdnCurrentTripIndex").val("1");
                this.clearAllFiltersAction = FILTERS_ACTION_NONE;
                this.setFilterFromTrip(this.currentResults.appliedSearch.SearchFilters, 0);

                //cache elements
                this.setElements();
                this.setFilterMode();

                //compile handlebars templates
                this.compileTemplates();

                this.showFullPageLoader();

                //get results view type
                this.currentResults.IsListView = this.fetchResultViewType();
                this.elements.resultsContainer.toggleClass('flight-block-style-list', this.currentResults.IsListView);


                //extend jQuery UI to allow external lists
                $.widget("ui.tabs", $.ui.tabs, {
                    _getList: function () {
                        var list = null;
                        if (this.options.tabList) {
                            list = this.options.tabList;
                        }
                        return list || this._super();
                    }
                });

                this.bindEvents();

                if (History && History.pushState) {
                    var state = History.getState(),
                        searchState = state.data;
                    if (!searchState.currentTripIndex || searchState.currentTripIndex === 1) {
                        $("#hdnCurrentTripIndex").val("1");
                        this.pushOrLoadResults(1, true);
                    } else {
                        $("#hdnCurrentTripIndex").val(searchState.currentTripIndex);
                        //searchState.currentResults.appliedSearch.Revise = true;
                        this.clearAndLoadResult(searchState);
                    }
                } else {
                    $("#hdnCurrentTripIndex").val("1");
                    this.loadFlightResults(this.currentResults.appliedSearch);
                }

                //register handlebars helpers
                registerHelpers();

                if (showFsrTips) {
                    if (fsrTipsPhase2) {
                        this.elements.resultsHeaderFsrTips.empty();
                    }
                }

                if ($("#ecd-notice-id").length > 0 && $("#ecd-notice-id").val() == "true") {
                    this.renderEditSearchOnly();
                    $("#fl-new-search-wrap").show();
                }

                if ($('#hdnIsEmployeeTwentyPath').val() != "True" && $('#hdnAward').val() == "True" && $('#hdnIsSignedIn').val() === "False") {
                    //setTimeout(function () { UA.Common.Header.showLoginModal(); }, 9000);
                    UA.Common.Header.showLoginModal();
                }
                this.initNewModalDialog();
            },
            initNewModalDialog: function () {
                var _this = this;

                //Sort Flights by dialog
                var sortposition = $('.sort-flight-content').offset();
                $('.sort-flight-content').on('keypress click', function (){
                    $.modal.close();
                    $("#sortflightsby").modal({
                        minWidth: 224,
                        fixed: false,
                        autoPosition: false,
                        persist: true,
                        containerCss: {
                            top: sortposition.top,
                            left: sortposition.left,
                            boxShadow: 'none'
                        },
                        overlayCss: {
                            backgroundImage: 'none'
                        },
                        closeHTML: '',
                        escClose: true,
                        overlayClose: true,
                        onShow: function (dialog) {
                            $(dialog.container).find('.dropdown-close').focus();
                        }
                    });
                    $('#sortflightsby').on('keypress click', 'input', function () {
                        $('.selectedtext-sortflights').text($(this).data("value"));
                        $('.sort-flight-content .sort-selected-text').text($(this).data("value"));
                        $.modal.close();
                        var data = { fareType: _this.currentResults.appliedSearch.SearchFilters.FareFamily };
                        _this.currentResults.appliedSearch.SortType = $(this).val();
                        $('#SortType').val(_this.currentResults.appliedSearch.SortType);
                        _this.setSorterState($(this).val(), data);

                        $("#fl-results-pager-container").trigger('search.sort.changed');
                        $('#sortflightsby').find("input[type='checkbox']:checked").prop("checked", false)
                        $('#sortflightsby').find("input[type='checkbox'][value='" + _this.currentResults.appliedSearch.SortType + "']").prop("checked", true);
                    });
                });
                $('.selectedtext-sortflights').on('keypress click',function (e) {
                    $.modal.close();
                });

                //Stops dialog
                var stopposition = $('.filter-stop-content').offset();
                $('.filter-stop-content').on('keypress click', function () {
                    $.modal.close();
                    $("#stops").modal({
                        minWidth: 164,
                        fixed: false,
                        autoPosition: false,
                        persist: true,
                        containerCss: {
                            top: stopposition.top,
                            left: stopposition.left,
                            boxShadow: 'none'
                        },
                        overlayCss: {
                            backgroundImage: 'none'
                        },
                        closeHTML: '',
                        escClose: true,
                        overlayClose: true,
                        onShow: function (dialog) {
                            $(dialog.container).find('.dropdown-close').focus();
                            var checkedOption = $(dialog.container).find("input[type='checkbox']:checked");
                            if (checkedOption.length == 2) {
                                $(dialog.container).find("input[type='checkbox']:checked").prop("checked", false)
                                $(dialog.container).find("input[type='checkbox'][name='allflights']").prop("checked", true);
                            }
                        }
                    });
                    $('#stops').on('keypress click', 'input', function (e) {
                        _this.handleNewTopStopsFilterClick(e);
                        $('.selectedtext-stops').text($(this).val());
                        $('.filter-stop-content .stop-selected-text').text($(this).val());
                        $.modal.close();
                    });
                });
                $('.selectedtext-stops').on('keypress click', function (e) {
                    $.modal.close();
                });

                //Connecting Airports dialog
                var airportposition = $('.filter-airport-content').offset();
                $('.filter-airport-content').on('keypress click', function () {
                    $.modal.close();
                    $("#connectingairpots").modal({
                        fixed: false,
                        autoPosition: false,
                        persist: true,
                        containerCss: {
                            top: airportposition.top,
                            left: airportposition.left,
                            boxShadow: 'none'
                        },
                        overlayCss: {
                            backgroundImage: 'none'
                        },
                        closeHTML: '',
                        escClose: true,
                        overlayClose: true,
                        onShow: function (dialog) {
                            $(dialog.container).find('.dropdown-close').focus();
                            var allcheckBox = $(dialog.container).find("input[type='checkbox']");
                            var checkedOption = $(dialog.container).find("input[type='checkbox']:checked");
                            if (allcheckBox.length != checkedOption.length) {
                                $('.allairporttoggle').prop('checked', false);
                            }
                        },
                        onClose: function () {
                            _this.handleFilterApply();
                        }
                    });
                    $('#connectingairpots').on('keypress click', 'input', function () {
                        updateConnectingAirports();
                    });
                    $('#airporttogglespan').on('keypress click', function (e) {
                        if ($('.allairporttoggle').prop("checked")) {
                            $('#connectingairpots .dropdownv3 input[type="checkbox"]').prop('checked', false);
                        }
                        else {
                            $('#connectingairpots .dropdownv3 input[type="checkbox"]').prop('checked', true);
                        }
                        updateConnectingAirports();
                    });
                    $('.allairporttoggle').on('keypress click',function (e) {
                        if ($(e.currentTarget).prop("checked")) {
                            $('#connectingairpots .dropdownv3 input[type="checkbox"]').prop('checked', true);
                        }
                        else {
                            $('#connectingairpots .dropdownv3 input[type="checkbox"]').prop('checked', false);
                        }
                        updateConnectingAirports();
                    });
                    $('.filter-only-v3, .filter-me-only-v3').on('keypress click', function (e) {
                        e.preventDefault();
                        var onlyEle = $(e.currentTarget);
                        $('#connectingairpots .dropdownv3 input[type="checkbox"]').prop('checked', false);
                        $('.allairporttoggle').prop('checked', false);
                        var toBeClickId = onlyEle.data('only-for');
                        $('#connectingairpots .dropdownv3 input[type="checkbox"][id=' + toBeClickId + ']').prop('checked', true);
                        updateConnectingAirports();
                    });
                });
                function updateConnectingAirports() {
                    var selectedCheckboxes = $('#connectingairpots .dropdownv3 input[type="checkbox"]:checked').length;
                    var totalCheckboxes = $('#connectingairpots .dropdownv3 input[type="checkbox"]').length;
                    if (totalCheckboxes == selectedCheckboxes) {
                        $('.selectedtext-connectingairports').text($('#allAirportsSelectedText').val());
                        $('.filter-airport-content .airports-selected-text').text($('#allAirportsSelectedText').val());
                        $('.allairporttoggle').prop('checked', true);
                    }
                    else {
                        $('.selectedtext-connectingairports').text(selectedCheckboxes + " " + $('#selectedAirportsText').val());
                        $('.filter-airport-content .airports-selected-text').text(selectedCheckboxes + " " + $('#selectedAirportsText').val());
                        $('.allairporttoggle').prop('checked', false);
                    }
                }
                $('.selectedtext-connectingairports').on('keypress click', function (e) {
                    e.preventDefault();
                    $.modal.update();
                    $.modal.close();
                    _this.handleFilterApply();                   
                });
            },
            compileTemplates: function () {
                var handlebarsOptions = {
                    data: true,
                    knownHelpers: {
                        'minutesToHour': true,
                        'monthYear': true,
                        'oneBase': true,
                        'debug': true,
                        'compare': true,
                        'compareTwo': true,
                        'CompareWithTodayDate': true,
                        'CompareBeyond337Days': true,
                        'savePrevious': true,
                        'checkIsLastDestination': true,
                        'contains': true,
                        'toIdAttribute': true,
                        'toLowerCase': true,
                        'parseTime': true,
                        'formatLongDate': true,
                        'formatLongDateAlt': true,
                        'formatDate': true,
                        'formatLongMonth': true,
                        'formatShortMonth': true,
                        'formatShortMonthOneBasedNumbering': true,
                        'fareSizeClass': true,
                        'isExpertMode': true,
                        'isAdRow': true,
                        'fareWheelSizeClass': true,
                        'formatWarning': true,
                        'ifVisibleWarnings': true,
                        'airportDescription': true,
                        'amenitiesExist': true,
                        'hasLmxData': true,
                        'isLmxAccrualCapped': true,
                        'sorterDisplay': true,
                        'isRequireEditSearch': true,
                        'trimAirportCity': true,
                        'trimAirportName': true,
                        'formatShortDay': true,
                        'formatDayMonth': true,
                        'getConsolidateMessage': true,
                        'setSelectValue': true,
                        'formatFirstLetter': true,
                        'getRecommendedFlightMessage': true,
                        'formatThreeLetter': true,
                        'ifCond': true,
                        'isContainsString': true,
                        'formatShortDateNoYear': true,
                        'splitcount': true,
                        'isallairportexist': true,
                        'selectUpgradeOption': true,
                        'ifProductAvailable': true,
                        'selectAvailableLmxProduct': true,
                        'selectSegmentMapping': true,
                        'filterMessages': true,
                        'Is2019Flight': true,
                        'departureMonthYear': true
                    },
                    knownHelpersOnly: true
                };
                this.templates = {};
                this.templates.tripDetails = Handlebars.compile($("#template-flight-detail").html(), handlebarsOptions);
                this.templates.flightResults = Handlebars.compile($("#template-flight-results").html(), handlebarsOptions);
                if ($("#template-flight-results-version-4").length > 0) {
                    this.templates.flightResultsV4 = Handlebars.compile($("#template-flight-results-version-4").html(), handlebarsOptions);
                }
                if ($("#template-flight-results-version-2").length > 0) {
                    this.templates.flightResultsV2 = Handlebars.compile($("#template-flight-results-version-2").html(), handlebarsOptions);
                }
                if ($("#template-economy-upsell").length > 0) {
                    this.templates.economyUpsell = Handlebars.compile($("#template-economy-upsell").html(), handlebarsOptions);
                }
                this.templates.recommendedFlightResults = Handlebars.compile($("#template-recommendedflight-results").html(), handlebarsOptions);
                if ($("#template-recommendedflight-results-version-2").length > 0) {
                    this.templates.recommendedFlightResultsV2 = Handlebars.compile($("#template-recommendedflight-results-version-2").html(), handlebarsOptions);
                }
                if ($("#template-recommendedflight-results-version-4").length > 0) {
                    this.templates.recommendedFlightResultsV4 = Handlebars.compile($("#template-recommendedflight-results-version-4").html(), handlebarsOptions);
                }
                this.templates.flightResultEmpty = Handlebars.compile($("#template-search-empty-result").html(), handlebarsOptions);
                this.templates.flightResultReset = Handlebars.compile($("#template-search-reset-result").html(), handlebarsOptions);
                this.templates.flightResultSearch = Handlebars.compile($("#template-search-reset-search").html(), handlebarsOptions);
                if (fsrTipsPhase2) {
                    this.templates.flightResultsFsrTips = Handlebars.compile($("#template-flight-fsrTips").html(), handlebarsOptions);
                    this.templates.flightResultsSegmentNearbyError = Handlebars.compile($("#template-flight-segment-nearbyerror").html(), handlebarsOptions);
                    this.templates.flightResultsSegmentNearby = Handlebars.compile($("#template-flight-segment-nearby").html(), handlebarsOptions);
                }
                this.templates.flightResultsSegmentNonstopSuggestion = Handlebars.compile($("#template-flight-segment-nonstopsuggestion").html(), handlebarsOptions);
                this.templates.flightResultsSegmentNearbyCities = Handlebars.compile($("#template-flight-segment-nearbycities").html(), handlebarsOptions);
                this.templates.flightResultsSegmentBetterOffers = Handlebars.compile($("#template-flight-segment-betteroffers").html(), handlebarsOptions);
                this.templates.flightResultsSegmentHeader = Handlebars.compile($("#template-flight-segment-results-header").html(), handlebarsOptions);
                this.templates.flightResultsSegmentHeaderFareDisclaimer = Handlebars.compile($("#template-flight-segment-fare-disclaimer").html(), handlebarsOptions);
                if ($("#template-upgrade-options").length > 0) {
                    this.templates.pprUpgradeRadioButton = Handlebars.compile($("#template-upgrade-options").html(), handlebarsOptions);
                }
                this.templates.flightResultsHeader = Handlebars.compile($("#template-flight-results-header").html(), handlebarsOptions);
                if ($("#template-flight-results-header-version-2").length > 0) {
                    this.templates.flightResultsHeaderV2 = Handlebars.compile($("#template-flight-results-header-version-2").html(), handlebarsOptions);
                }
                if (this.showTopFilters || this.showTopFiltersAward) {
                    this.templates.filterSearchFilters = Handlebars.compile($("#template-filter-search-result").html(), handlebarsOptions);
                }
                if (this.searchFilterMode === 'footerondemand' || this.searchFilterMode === 'footer' || this.showTopFilters || this.showTopFiltersAward) {
                    this.templates.searchFilters = Handlebars.compile($("#template-search-filters").html(), handlebarsOptions);
                }
                this.templates.searchFilterSummary = Handlebars.compile($("#template-search-filters-summary").html(), handlebarsOptions);
                this.templates.searchAmenitiesResults = Handlebars.compile($("#template-search-segment-amenities").html(), handlebarsOptions);
                this.templates.searchFarelockResults = Handlebars.compile($("#template-search-farelock-icon").html(), handlebarsOptions);
                this.templates.searchUpgradeAvailResults = Handlebars.compile($("#template-search-upgrade-avail-icon").html(), handlebarsOptions);
                this.templates.searchFilterAmenities = Handlebars.compile($("#template-search-filters-amenities").html(), handlebarsOptions);
                this.templates.flightResultAwardReset = Handlebars.compile($("#template-search-award-reset-result").html(), handlebarsOptions);
                this.templates.flightResultSeasonalAwardReset = Handlebars.compile($("#template-search-award-seasonal-reset-result").html(), handlebarsOptions);
                this.templates.confirmElfFare = Handlebars.compile($('#template-confirm-elf-fare-modal').html(), handlebarsOptions);
                this.templates.confirmWithRestrictionFare = Handlebars.compile($('#template-confirm-with-restriction-fare-modal').html(), handlebarsOptions);
                if ($('#template-fsr-shopsearchcount-modal').length > 0) {
                    this.templates.shopSearchCount = Handlebars.compile($('#template-fsr-shopsearchcount-modal').html(), handlebarsOptions);
                }
                if ($('#template-fsr-shopsearchcount-modal-hidden').length > 0) {
                    this.templates.shopSearchCountHidden = Handlebars.compile($('#template-fsr-shopsearchcount-modal-hidden').html(), handlebarsOptions);
                }
                this.templates.fareComparisonTemplate = Handlebars.compile($('#template-fare-comparison-modal').html(), handlebarsOptions);
                if ($('#template-confirm-ibe-fare-modal').length > 0) {
                    this.templates.confirmIbeFare = Handlebars.compile($('#template-confirm-ibe-fare-modal').html(), handlebarsOptions);
                }
                this.templates.uppdoubleupgrade = Handlebars.compile($('#template-upp-double-upgrade-modal').html(), handlebarsOptions);
                var editFlightSearch = $('#editFlightSearch').val() == 'True' ? true : false;
                if (editFlightSearch && this.currentResults != null && this.currentResults.appliedSearch.searchTypeMain != null && this.currentResults.appliedSearch.searchTypeMain.toLowerCase() != "multicity") {
                    this.templates.searchFiltersEdit = Handlebars.compile($("#template-search-filters-Edit").html(), handlebarsOptions);
                }
                if ($("#template-fare-calendar").length > 0) {
                    this.templates.fareCalendar = Handlebars.compile($("#template-fare-calendar").html(), handlebarsOptions);
                    this.templates.fareCalendarTooltip = Handlebars.compile($("#template-fare-calendar-tooltip").html(), handlebarsOptions);
                }
                if ($("#template-availability-calendar").length > 0) {
                    this.templates.awardCalendar = Handlebars.compile($("#template-availability-calendar").html(), handlebarsOptions);
                }
                if ($("#template-farewheel").length > 0) {
                    this.templates.farewheel = Handlebars.compile($('#template-farewheel').html(), handlebarsOptions);
                }
                if ($('#template-tabbed-farewheel').length > 0) {
                    this.templates.tabbedFareWheel = Handlebars.compile($('#template-tabbed-farewheel').html(), handlebarsOptions);
                }
                if ($('#template-fsr-line-loader').length > 0) {
                    this.templates.lineLoader = Handlebars.compile($('#template-fsr-line-loader').html(), handlebarsOptions);
                }
                if ($('#template-plus-minus-threedayslink').length > 0) {
                    this.templates.plusMinusThreeDaysLink = Handlebars.compile($('#template-plus-minus-threedayslink').html());
                }
                if ($('#singlecolumnfsr-lowfare').length > 0) {
                    this.templates.singleColumnFSRLowestFare = Handlebars.compile($('#singlecolumnfsr-lowfare').html());
                }
                this.templates.selectedFlight = Handlebars.compile($("#template-selected-flight").html(), handlebarsOptions);
                if ($("#template-advisories-tooltip").length > 0) {
                    this.templates.advisoriesTooltip = Handlebars.compile($("#template-advisories-tooltip").html(), handlebarsOptions);
                }
                this.templates.onTimePerformance = Handlebars.compile($("#template-on-time-performance").html(), handlebarsOptions);
                this.templates.mixedCabinTooltip = Handlebars.compile($("#template-mixed-cabin-tooltip").html(), handlebarsOptions);
                if ($("#template-mixed-upgrade-tooltip").length > 0) {
                    this.templates.mixedUpgradeTooltip = Handlebars.compile($("#template-mixed-upgrade-tooltip").html(), handlebarsOptions);
                }

                if ($("#template-mixed-upgrade-tooltip-v3").length > 0) {
                    this.templates.upgradeTooltipV3 = Handlebars.compile($("#template-mixed-upgrade-tooltip-v3").html(), handlebarsOptions);
                }

                if ($("#template-lmx-accrual-tooltip").length > 0) {
                    this.templates.lmxAccrualTooltip = Handlebars.compile($("#template-lmx-accrual-tooltip").html(), handlebarsOptions);
                }

                if ($('#template-fsr-no-flight-message').length > 0) {
                    this.templates.noFlightFoundMessage = Handlebars.compile($('#template-fsr-no-flight-message').html(), handlebarsOptions);
                }

                this.templates.message = Handlebars.compile($("#template-message").html(), handlebarsOptions);
                this.templates.messageV3 = Handlebars.compile($("#template-message-version-3").html(), handlebarsOptions);
                this.templates.flightConnectionTooltip = Handlebars.compile($("#template-flight-connection-tooltip").html(), handlebarsOptions);
                if ($('#template-fare-matrix-calendar').length > 0) {
                    this.templates.fareMatrixCalendar = Handlebars.compile($("#template-fare-matrix-calendar").html(), handlebarsOptions);
                }
            },
            setFilterMode: function () {
                this.searchFilterMode = 'footerondemand'; //bottomfilters is true even with switch for showBottomFilters is off. SHD
                if (this.currentResults.appliedSearch.isReshopPath && this.currentResults.appliedSearch.awardTravel) {
                    this.searchFilterMode = 'footerondemand';
                    this.showTopFilters = false;
                    this.showTopFiltersAward = false;
                    this.hideOnlyNonstopAward = false;
                    this.showBottomFilters = false;
                    return;
                }
                var showFilteronClick = ($('#showFilteronClick').val() === "True" ? true : false),
                    showBottomFilters = ($('#showBottomFilters').val() === "True" ? true : false),
                    showTopFilters = ($('#showTopFilters').val() === "True" ? true : false),
                    showTopFiltersAward = ($('#showTopFiltersAward').val() === "True" ? true : false),
                    hideOnlyNonstopAward = ($('#hideOnlyNonstopAward').val() === "True" ? true : false);


                this.showTopFilters = showTopFilters;
                this.showTopFiltersAward = showTopFiltersAward;
                this.hideOnlyNonstopAward = hideOnlyNonstopAward;
                this.showBottomFilters = showBottomFilters;
                if (showBottomFilters) {

                    if (showFilteronClick && typeof this.searchFilterMode === "undefined") {
                        this.searchFilterMode = 'footerondemand';
                    } else {
                        this.searchFilterMode = 'footer';
                    }
                }

            },
            showAirportChangeBlock: function (flightNo) {
                $('#airportChangeLessInfoLnk' + flightNo).addClass('showAirportChange');
                $('#airportChangeDetailsBlock' + flightNo).removeClass('hideAirportChange');
                $('#airportChangeMoreInfoLnk' + flightNo).addClass('hideAirportChange');
            },
            hideAirportChangeBlock: function (flightNo) {
                $('#airportChangeDetailsBlock' + flightNo).addClass('hideAirportChange');
                $('#airportChangeLessInfoLnk' + flightNo).removeClass('showAirportChange');
                $('#airportChangeMoreInfoLnk' + flightNo).removeClass('hideAirportChange');
            },
            clearAndLoadResult: function (searchState) {
                if (searchState.currentResults.appliedSearch.Revise && !searchState.currentResults.appliedSearch.IsAwardCalendarEnabled) {
                    this.elements.calendarContainer.empty();
                }
                if (showFsrTips) {
                    if (fsrTipsPhase2) {
                        this.emptyFsrTips();
                    } else {
                        this.elements.resultsHeaderSegmentNearbyCities.empty();
                        this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
                        this.elements.resultsHeaderSegmentBetterOffers.empty();
                    }
                }
                this.elements.resultsHeaderSegmentContainer.empty();
                $('#upgrade-option-placeholder').empty();
                this.elements.resultsHeaderSegmentFareDisclaimerContainer.empty();
                this.elements.resultsHeaderContainer.empty();
                this.elements.resultsContainer.empty();
                this.elements.filterSortContainer.empty();
                this.elements.resetNotificationContainer.empty();
                this.elements.noFlightMesssageSection.empty();
                this.resetTabbedFWHeader();

                this.elements.currentTripIndex.val(searchState.currentTripIndex);

                this.currentResults.appliedSearch = searchState.currentResults.appliedSearch;

                if (searchState.appliedSearch) {
                    this.loadFlightResults(searchState.appliedSearch);
                } else {
                    this.loadFlightResults(searchState.currentResults.appliedSearch);
                }
            },

            clearAllFiltersTop: function (e) {
                this.clearAllFilters(e, true);
            },

            clearAllFiltersBottom: function (e) {
                this.clearAllFilters(e, false);
            },

            clearAllFilters: function (e, fromTop) {
                e.preventDefault();

                filterActionClick = true;
                $(".bottom-clear-all-filters").prop("disabled", true);
                var $currentElement = $(e.currentTarget);
                var $targetLoader = $currentElement.parent();
                //$targetLoader.loader();

                var moduleInfo;
                if (fromTop === true) {
                    moduleInfo = "{\"action\": \"Clear all filters\", \"desc\": \"Top link\"}";
                } else {
                    moduleInfo = "{\"action\": \"Clear all filters\", \"desc\": \"Bottom link\"}";
                }
                $currentElement.removeAttr("data-module-info").attr("data-module-info", moduleInfo);
                $currentElement.data("module-info", JSON.parse(moduleInfo));
                UA.UI.processModule($currentElement);
                
                var _this = this;
                var tripIdx = _this.getTripIndex();
                var request = _this.fetchClearAllFilters(tripIdx);
                $.when(request).done(function () {
                    _this.currentResults.appliedSearch.Trips[tripIdx].ClearAllFilters = true;
                    if (_this.currentResults.appliedSearch.Cached != null &&
                        _this.currentResults.appliedSearch.Cached.Trips != null &&
                        _this.currentResults.appliedSearch.Cached.length > tripIdx) {
                        _this.currentResults.appliedSearch.Cached.Trips[tripIdx].ClearAllFilters = true;
                    }
                    _this.clearAllFiltersAction &= FILTERS_ACTION_USED;
                    _this.currentResults.GuiFiltersApplied = false;
                    $(".bottom-clear-all-filters").addClass("visiblehidden");
                    if (fromTop) {
                        _this.resetFilter();
                    } else {
                        _this.resetFilter($targetLoader);
                    }

                    if (_this.showTopFiltersAward === true && _this.currentResults.appliedSearch.flexibleAward === false) {
                        var isAwardCalendarNonstop = false;
                        if (_this.currentResults.SearchFilters &&
                            !_this.currentResults.SearchFilters.HideNoneStop &&
                            _this.currentResults.SearchFilters.HideOneStop &&
                            _this.currentResults.SearchFilters.HideTwoPlusStop) {
                            isAwardCalendarNonstop = true;
                        }
                        _this.handleAwardCalendarNonstopFilterChangeFunc(isAwardCalendarNonstop);
                    }
                });
            },

            pushOrLoadResults: function (currentTripIndex, replace, search) {
                if (this.getTripIndex() > 0 && !this.isFareWheelClick) {
                    this.currentResults.appliedSearch.SortType = this.currentResults.SortType;
                }
                if (History && History.pushState) {
                    var url, urlquery, params, state = History.getState();

                    var appliedSearch = _.omit(this.currentResults.appliedSearch, 'AppliedSearch');
                    appliedSearch = _.omit(appliedSearch, 'SearchFilters');
                    appliedSearch = _.omit(appliedSearch, 'PosCountryList');

                    var current = {
                        appliedSearch: appliedSearch
                    };

                    var searchState = {
                        _index: History.getCurrentIndex(),
                        currentTripIndex: currentTripIndex,
                        currentResults: current,
                        totalTrips: parseInt($("#hdnTotalTrips").val(), 10)
                    };

                    var isUsingHash = History.emulated.pushState;

                    if (isUsingHash) {
                        urlquery = "?" + window.location.hash.substring(1);
                    } else {
                        urlquery = state.url;
                    }

                    params = UA.Utilities.getQueryStringValues(urlquery);
                    var idx = params.idx;
                    params.idx = searchState.currentTripIndex;
                    url = "?" + decodeURIComponent($.param(params));

                    triggeredStateChange = false;
                    if (replace) {
                        if (search) {
                            searchState.appliedSearch = search;
                            if (current.appliedSearch.awardTravel == true) {
                                searchState.appliedSearch.nonStopOnly = current.appliedSearch.nonStopOnly;
                                searchState.appliedSearch.calendarStops = current.appliedSearch.calendarStops;
                            }
                        }
                        if (idx == searchState.currentTripIndex) {
                            var self = this;
                            self.loadFlightResults(searchState.appliedSearch ? searchState.appliedSearch : searchState.currentResults.appliedSearch);
                        } else {
                            History.replaceState(searchState, document.title, url);
                        }
                    } else {
                        History.pushState(searchState, document.title, url);
                    }
                } else {
                    this.loadFlightResults(this.currentResults.appliedSearch);
                }
            },
            renderFareWheel: function (data) {
                //if (!data) return; //CSI-1303 SHD
                data = data || this.currentResults;
                var data1 = {};
                $.extend(true, data1, data);
                if (data1.SearchType == null || data1.SearchType === "") {
                    if (data1.appliedSearch == null) {
                        if (this.currentResults != null) {
                            if (this.currentResults.SearchType == null || this.currentResults.SearchType === "") {
                                if (this.currentResults.appliedSearch != null) {
                                    data1.SearchType = this.currentResults.appliedSearch.searchTypeMain;
                                }
                            } else {
                                data1.SearchType = this.currentResults.SearchType;
                            }
                        }
                    } else {
                        data1.SearchType = data1.appliedSearch.searchTypeMain;
                    }
                }

                if (data1.SearchType === "rt") {
                    data1.SearchType = "roundTrip";
                } else if (data1.SearchType === "mc") {
                    data1.SearchType = "multiCity";
                } else if (data1.SearchType === "ow") {
                    data1.SearchType = "oneWay";
                }
                //To deleted below two line in future.
                //var fareWheelContainer = $('#farewheel-placeholder');
                //fareWheelContainer.html(this.templates.farewheel(data1));
                if (this.templates.tabbedFareWheel != null) {
                    if (data1.FareWheel && data1.FareWheel.GridRowItems && data1.FareWheel.GridRowItems.length > 0) {
                        this.elements.tabbedFareWheelSection.html(this.templates.tabbedFareWheel(data1));
                        this.hideLineLoader();
                        //$('#tabbed-fare-wheel-section').css('display', 'block');
                    }
                    else {
                        //$('#tabbed-fare-wheel-section').css('display', 'none');
                        this.elements.tabbedFareWheelSection.html(this.templates.tabbedFareWheel(data1));
                        if (data1.Errors.length > 0)
                            this.resetTabbedFWHeader();
                        else
                            this.showLineLoader();
                    }
                }
                if (showFsrTips) {
                    if (fsrTipsPhase2) {
                        if (fsrTipsShowBetterOffers) {
                            this.showBetterOffers(data1);
                        }
                    } else {
                        if ($('#hdnBetterOffersOnlyFsr1').val() === "true") {
                            if (data1.Trips != null && data1.Trips.length > 0 && data1.Trips[0].Index === 1) {
                                this.elements.resultsHeaderSegmentBetterOffers.html(this.templates.flightResultsSegmentBetterOffers(data1));
                            }
                        } else {
                            this.elements.resultsHeaderSegmentBetterOffers.html(this.templates.flightResultsSegmentBetterOffers(data1));
                        }
                    }
                }
                //UA.UI.processModule(fareWheelContainer);
            },
            renderAvailabilityCalendar: function (data) {
                data = data || this.currentResults;
                data.Calendar.Months[0].OriginDecoded = data.Trips[0].OriginDecoded;
                data.Calendar.Months[0].DestinationDecoded = data.Trips[0].DestinationDecoded;
                if (data.SelectedTrips.length == 1) {
                    if (data.Trips[0].Destination === data.SelectedTrips[0].Origin) {
                        data.Calendar.isReturn = true;
                    }
                }
                this.elements.calendarContainer.html(this.templates.awardCalendar(data.Calendar));
                if (data.IsAward && data.HideNonStopOnly) {
                    $('#award-nonstop-calendar-chkbox').hide();
                }
                UA.UI.reInit(this.elements.calendarContainer);
            },
            renderFareCalendar: function (data) {
                this.clearLineLoaderSection();
                data = data || this.currentResults;
                var _today, _searchDate;
                if (data.Calendar != null && data.Calendar.Months != null && data.Calendar.Months.length > 0) {
                    data.Calendar.Months[0].OriginDecoded = data.Trips[0].OriginDecoded;
                    data.Calendar.Months[0].DestinationDecoded = data.Trips[0].DestinationDecoded;
                    this.elements.calendarContainer.html(this.templates.fareCalendar(data.Calendar));
                } else {
                    this.elements.calendarContainer.html("");
                }
                this.initTravelersStepper();
                this.initAirportAutocomplete();
                UA.UI.reInit(this.elements.calendarContainer);

                _today = Date.today();
                _searchDate = UA.Utilities.formatting.tryParseDate(this.currentResults.appliedSearch.flexMonth);
                $("[id^=FlexMonth]").val(_searchDate > _today ? data.appliedSearch.flexMonth : UA.Utilities.formatting.formatShortDateNoWeekDay(_today));
                $('.OriginCal').typeahead('val', this.currentResults.appliedSearch.Trips[0].Origin).change();
                $('.DestinationCal').typeahead('val', this.currentResults.appliedSearch.Trips[0].Destination).change();
                $('#tripLength2').val(data.appliedSearch.tripLength);
                $('[id^=TripLength]').val(data.appliedSearch.tripLength);
                $('#sptripLength').text(data.appliedSearch.tripLength);

                UA.Booking.EditSearch.init();
            },
            MakeFSRResultsAccessible: function () {
                setTimeout(function () { $('#fl-results').attr('aria-live', 'assertive'); }, 0);
            },
            ShowLoginModalForAward: function () {
                if ($('#hdnAward').val() == "True" && $('#hdnIsSignedIn').val() === "False") {
                    UA.Common.Header.showLoginModal();
                }
            },
            renderFlightResults: function (data) {
                var newResults;
                data = data || this.currentResults;
                $('#award-nonstop-calendar-chkbox').show();
                if (isInitialload && data.Trips[0].CurrentFlightCount === 0) {
                    existtripIndex = this.getTripIndex();
                    this.elements.resultsContainer.empty();
                    if (data.IsAward && !data.IsAwardNonStopDisabled) {
                        if (data.IsAwardCalendarSeasonal) {
                            $(this.templates.flightResultSeasonalAwardReset()).appendTo(this.elements.resetNotificationContainer.empty()).show();
                        } else {
                            $(this.templates.flightResultEmpty(data)).appendTo(this.elements.resultsContainer.empty()).show();
                        }
                        $('#award-nonstop-calendar-chkbox').hide();
                    }
                        //else if (this.currentResults.SearchFilters.nonStop == false) { } //bug 693817 
                    else {
                        $(this.templates.flightResultEmpty(data)).appendTo(this.elements.resultsContainer.empty()).show();
                    }
                } else if (!isInitialload && data.Trips[0].CurrentFlightCount === 0) {
                    if (data.IsAward && data.HideNonStopOnly && this.currentResults.appliedSearch.SearchFilters.twoPlusStop) {
                        $('#award-nonstop-calendar-chkbox').hide();
                    }
                    //else if (this.currentResults.SearchFilters.nonStop == false) { } //bug 693817 
                    if (this.currentResults.appliedSearch.CalendarOnly == false) {
                        $(this.templates.flightResultEmpty(data)).appendTo(this.elements.resultsContainer.empty()).show();
                    }
                } else {
                    if (this.showTopFilters !== true && this.showTopFiltersAward !== true) {
                        this.PopuplateEmptyResultMessage(data);
                    }
                    if (data.IsAward && data.HideNonStopOnly) {
                        $('#award-nonstop-calendar-chkbox').hide();
                        var isNonStopSelected = this.currentResults.appliedSearch.Trips[this.getTripIndex()].nonStopOnly;
                        if (existtripIndex != this.getTripIndex() && isNonStopSelected && !data.IsAwardNonStopDisabled) {
                            if (data.IsAwardCalendarSeasonal) {
                                $(this.templates.flightResultSeasonalAwardReset()).appendTo(this.elements.resetNotificationContainer.empty()).show();
                            } else {
                                $(this.templates.flightResultAwardReset()).appendTo(this.elements.resultsContainer.empty()).show();
                            }
                        }
                    }

                    var data1 = {};
                    $.extend(true, data1, data);
                    if (data1.SearchType == null || data1.SearchType === "") {
                        if (data1.appliedSearch == null) {
                            if (this.currentResults != null) {
                                if (this.currentResults.SearchType == null || this.currentResults.SearchType === "") {
                                    if (this.currentResults.appliedSearch != null) {
                                        data1.SearchType = this.currentResults.appliedSearch.searchTypeMain;
                                    }
                                } else {
                                    data1.SearchType = this.currentResults.SearchType;
                                }
                            }
                        } else {
                            data1.SearchType = data1.appliedSearch.searchTypeMain;
                        }
                    }

                    if (data1.SearchType === "rt") {
                        data1.SearchType = "roundTrip";
                    } else if (data1.SearchType === "mc") {
                        data1.SearchType = "multiCity";
                    } else if (data1.SearchType === "ow") {
                        data1.SearchType = "oneWay";
                    }

                    var minBookingCount = $('#hdnMinBookingCount').val();
                    var maxBookingCount = $('#hdnMaxBookingCount').val();
                    if (!isNaN(minBookingCount) && !isNaN(maxBookingCount)) {
                        data1.MinBookingCount = minBookingCount;
                        data1.MaxBookingCount = maxBookingCount;
                    }
                    else {
                        data1.MinBookingCount = 1;
                        data1.MaxBookingCount = 6;
                    }

                    if (data1.GuiFiltersApplied === true) {
                        $(".bottom-clear-all-filters").removeClass("visiblehidden");
                    } else {
                        $(".bottom-clear-all-filters").addClass("visiblehidden");
                    }
                    if ($('#hdnLowestRevenueBannerOption2').val() == "True") {
                        data1.LowestRevenueBannerOption2 = true;
                        data1.LowestRevenueBannerOption2Index = $('#hdnLowestRevenueBannerOption2Index').val();
                    }
                    newResults = $(this.getFlightResultsHTML(data1)).appendTo(this.elements.resultsContainer.empty());
                    if (this.currentResults.lowestRevenueResponse && (this.currentResults.SelectedTrips == null || (this.currentResults.SelectedTrips && this.currentResults.SelectedTrips.length == 0))) {
                        this.lowestRevenueTemplateBind(this.currentResults.lowestRevenueResponse);
                    }
                    UA.UI.processModule(newResults);
                    UA.UI.Tooltip.init();
                    if (this.IsFlightRecommendationEnabledWithVOne()) {
                        this.recommendedFlightsResults = data1;
                        this.UpdateFlightsForRecommendationVOne(this.filteredRecommendedFlights);
                    }
                    this.initFlightBlock();
                    isInitialload = false;
                    existtripIndex = this.getTripIndex();
                }
            },            

            renderShopSearchCount: function (data) {
                var _this = this;
                $.when(this.fetchShopSearchCount(data))
                   .done(function (response) {
                       if (response != null) {
                           _this.elements.searchCountFlagContainer.empty();
                           _this.elements.searchCountVisuallyHiddenFlagContainer.empty();
                           if (response.data != null && response.status == "success") {
                               if (response.data.SearchCount > $('#hdnMaxShopSearchCount').val() && $('#hdnAward').val() != "True") {
                                   _this.elements.searchCountFlagContainer.html(_this.templates.shopSearchCount(response.data));
                                   _this.elements.searchCountVisuallyHiddenFlagContainer.html(_this.templates.shopSearchCountHidden(response.data));
                                   $('#fl-searchcount-container').trigger('inview');
                                   _this.initStickyElements();
                               }
                           }
                       }
                   });
            },

            renderFlightResultsFooter: function () {
                this.elements.resultsFooter.show();
            },
            renderFlightResultsHeader: function (data) {
                data = data || this.currentResults;

                var data1 = {};
                $.extend(true, data1, data);
                if (data1.SearchType == null || data1.SearchType === "") {
                    if (data1.appliedSearch == null) {
                        if (this.currentResults != null) {
                            if (this.currentResults.SearchType == null || this.currentResults.SearchType === "") {
                                if (this.currentResults.appliedSearch != null) {
                                    data1.SearchType = this.currentResults.appliedSearch.searchTypeMain;
                                }
                            } else {
                                data1.SearchType = this.currentResults.SearchType;
                            }
                        }
                    } else {
                        data1.SearchType = data1.appliedSearch.searchTypeMain;
                    }
                }

                if (data1.appliedSearch == null) {
                    data1.appliedSearch = this.currentResults.appliedSearch;
                }

                if (data1.SearchType === "rt") {
                    data1.SearchType = "roundTrip";
                } else if (data1.SearchType === "mc") {
                    data1.SearchType = "multiCity";
                } else if (data1.SearchType === "ow") {
                    data1.SearchType = "oneWay";
                }

                if (data1.SearchFilters != null && (data1.SearchFilters.HideNoneStop === true || (data1.SearchFilters.HideOneStop === true && data1.SearchFilters.HideTwoPlusStop === true))) {
                    data1.useTableRow = false;
                } else if (!(data1.GuiFiltersApplied === true)) {
                    data1.useTableRow = false;
                } else if (data1.IsAward) {
                    if ($("#hndShowFareCompareAward").val() === "true") {
                        if ($("#hdnShortLanguage").val() === "true") {
                            data1.useTableRow = false;
                        } else {
                            data1.useTableRow = true;
                        }
                    } else {
                        data1.useTableRow = false;
                    }
                } else {
                    if ($("#hdnLongLanguage").val() === "true") {
                        data1.useTableRow = true;
                    } else {
                        data1.useTableRow = false;
                    }
                }

                this.elements.lineLoaderMessageSection.hide();
                if (data1.GuiFiltersApplied === true) {
                    $(".bottom-clear-all-filters").removeClass("visiblehidden");
                } else {
                    $(".bottom-clear-all-filters").addClass("visiblehidden");
                }
                
                this.elements.resultsHeaderSegmentContainer.removeClass("fare-selecting");
                this.elements.resultsHeaderSegmentContainer.html(this.templates.flightResultsSegmentHeader(data1));
                this.renderResultHeader(data1);
                if (this.templates.plusMinusThreeDaysLink != null) {
                    this.elements.plusMinusThreeDayLinkSection.html(this.templates.plusMinusThreeDaysLink(data1));
                }
                if (this.templates.singleColumnFSRLowestFare != null && this.isSingleColumnDesignActive())  {
                    this.elements.singleColumnFSRLowFareSection.html(this.templates.singleColumnFSRLowestFare(data1));
                }
                if (!this.isFilterClick) {
                    this.elements.resultsHeaderContainer.html(this.getFlightResultsHeaderHTML(data1));                    
                }
                this.isFilterClick = false;
                //$("#ddSortType").find('ul.dropdownFSR > li').has('a#' + data1.appliedSearch.SortType).click();
                //resetting the upper filter checkbox value based on  current flight count===0
                if (data1.Trips != null && data1.Trips[0].CurrentFlightCount === 0) {
                    $('#newfilter_nonStop').prop('checked', false);
                    $('#newfilter_stop').prop('checked', false);
                } else if (!isInitialload && data1.Trips != null && data1.Trips[0].CurrentFlightCount > 0) {
                    var CurrentResultWithStop = false;
                    $.each(data.Trips[0].Flights, function (index, val) {
                        if (val.StopsandConnections > 0) {
                            CurrentResultWithStop = true;
                            return false;
                        }
                    });
                    if (CurrentResultWithStop) {
                        //this.currentResults.SearchFilters.OneStop == true;
                        //this.currentResults.SearchFilters.twoPlusStop == true;
                        $('#newfilter_stop').prop('checked', true);
                        //e.preventDefault();
                    } else {
                        //this.currentResults.SearchFilters.OneStop == false;
                        //this.currentResults.SearchFilters.twoPlusStop == false;
                        $('#newfilter_stop').prop('checked', false);
                        //e.preventDefault();
                    }

                }

                if (this.currentResults.appliedSearch.SortType !== null && this.getTripIndex() > 0) {
                    $('#SortType').val(this.currentResults.appliedSearch.SortType);
                }
                if (this.currentResults.appliedSearch.UpgradeType !== null) {
                    $('#UpgradeType').val(this.currentResults.appliedSearch.UpgradeType);
                }

                if (this.currentResults.appliedSearch.awardTravel) {
                    if ($('#editFlightSearch').val() != "True") {
                        $('#fl-new-search-wrap').hide();
                    }
                }
                this.initNewSearchToggle();
                var editFlightSearch = $('#editFlightSearch').val() == 'True' ? true : false;
                if (!editFlightSearch) {
                    if (this.currentResults.appliedSearch.flexibleAward) {
                        $('.btn-show-new-search').click();
                    }
                    else if ($('.fl-new-search-wrap').css('display') == 'block' && !$('.btn-show-new-search').hasClass('toggler-active')) {
                        $('.btn-show-new-search').click();
                    }
                } else {
                    UA.Booking.EditSearch.removeValidationOnInitial(this.currentResults);
                    UA.Booking.EditSearch.initDepartReturnDate(this.currentResults);
                }

                this.initAirportName();
                this.initTravelersStepper();
                UA.Booking.EditSearch.init();
                $('.dropdown-upgrade-type-trigger').dropdown({
                    modal: false,
                    allowFocus: true
                });
                
                if (!$("#ddSortType").hasClass("dd-init-complete")) {
                    UA.Common.SortDropdown.init($("#ddSortType"), $.proxy(this.handleSortDropdownChangeEvent, this));
                    $("#ddSortType").addClass("dd-init-complete");
                }
                $(document).click(function () { $('.wrapper-dropdown-1').removeClass('active'); });

                $("#ddSortType li:last").keypress(function (event) {
                    if (event.keyCode == 9 || event.which == 9) {
                        $('.wrapper-dropdown-1').removeClass('active');
                    }
                });
                this.initNewModalDialog();


               

                if (!this.currentResults.appliedSearch.awardTravel) {
                    UA.Common.SortDropdown.setValue(this.currentResults.appliedSearch.SortType);
                }

                if (this.currentResults.appliedSearch.UpgradeType && this.currentResults.appliedSearch.UpgradeType.toUpperCase() == 'POINTS') {
                    $('#SortType').val(this.currentResults.appliedSearch.SortType);
                    var sortByText = $('#SortType').find('option:selected').text();
                    if (this.currentResults.appliedSearch.SortType != null && (this.currentResults.appliedSearch.SortType == 'price_low' || this.currentResults.appliedSearch.SortType == 'price_high')) {
                        $('.selectedtext-sortflights').text($('#dropdownCustomText').val());
                        $('.sort-flight-content .sort-selected-text').text($('#dropdownCustomText').val());
                    }
                    else {
                        $('.selectedtext-sortflights').text(sortByText);
                        $('.sort-flight-content .sort-selected-text').text(sortByText);
                    }
                }
            },
            renderEditSearchOnly: function (data) {
                data = data || this.currentResults;

                var data1 = {};
                $.extend(true, data1, data);
                if (data1.SearchType == null || data1.SearchType === "") {
                    if (data1.appliedSearch == null) {
                        if (this.currentResults != null) {
                            if (this.currentResults.SearchType == null || this.currentResults.SearchType === "") {
                                if (this.currentResults.appliedSearch != null) {
                                    data1.SearchType = this.currentResults.appliedSearch.searchTypeMain;
                                }
                            } else {
                                data1.SearchType = this.currentResults.SearchType;
                            }
                        }
                    } else {
                        data1.SearchType = data1.appliedSearch.searchTypeMain;
                    }
                }

                if (data1.appliedSearch == null) {
                    data1.appliedSearch = this.currentResults.appliedSearch;
                }

                if (data1.SearchType === "rt") {
                    data1.SearchType = "roundTrip";
                } else if (data1.SearchType === "mc") {
                    data1.SearchType = "multiCity";
                } else if (data1.SearchType === "ow") {
                    data1.SearchType = "oneWay";
                }
                if (!data1.IsAward) {
                    data1.IsAward = $('.fl-results-award').length > 0 ? true : false;
                }

                if (data1.SearchFilters != null && (data1.SearchFilters.HideNoneStop === true || (data1.SearchFilters.HideOneStop === true && data1.SearchFilters.HideTwoPlusStop === true))) {
                   data1.useTableRow = false;
                } else if (!(data1.GuiFiltersApplied === true)) {
                    data1.useTableRow = false;
                } else if (data1.IsAward) {
                    if ($("#hndShowFareCompareAward").val() === "true") {
                        if ($("#hdnShortLanguage").val() === "true") {
                            data1.useTableRow = false;
                        } else {
                            data1.useTableRow = true;
                        }
                    } else {
                        data1.useTableRow = false;
                    }
                } else {
                    if ($("#hdnLongLanguage").val() === "true") {
                        data1.useTableRow = true;
                    } else {
                        data1.useTableRow = false;
                    }
                }

                this.elements.lineLoaderMessageSection.hide();
                if (data1.GuiFiltersApplied === true) {
                    $(".bottom-clear-all-filters").removeClass("visiblehidden");
                } else {
                    $(".bottom-clear-all-filters").addClass("visiblehidden");
                }
                this.elements.resultsHeaderSegmentContainer.removeClass("fare-selecting");
                this.renderResultHeader(data1);
                this.elements.resultsHeaderSegmentContainer.html(this.templates.flightResultsSegmentHeader(data1));
                this.elements.resultsHeaderContainer.html(this.getFlightResultsHeaderHTML(data1));
                $("#fl-search-header-placeholder").addClass("visiblehidden");
                $('#fl-search-header-placeholder').hide();
                this.initNewSearchToggle();
                this.initAirportName();
                this.initTravelersStepper();
                UA.Booking.EditSearch.init();
                var editFlightSearch = $('#editFlightSearch').val() == 'True' ? true : false;
                if (!editFlightSearch)
                    $('.btn-show-new-search').click();

                $('.fare-disclaimer').hide();
                this.initNewModalDialog();
            },
            renderResultHeader: function (data) {
                this.elements.resultsHeaderSegmentFareDisclaimerContainer.html(this.templates.flightResultsSegmentHeaderFareDisclaimer(data));
                if ($("#upgrade-option-placeholder").length > 0) {
                    $('#upgrade-option-placeholder').html(this.templates.pprUpgradeRadioButton(data));
                }
            },
            renderFlightDetails: function (flightBlock, data) {

                var detailsElement = flightBlock.find(".flight-details"),
                    segments,
                    segmentDetailHeight;

                detailsElement.html(this.getFlightDetailsHTML(data));
                detailsElement.data('isRendered', true);
                detailsElement.trigger('focus');

                segments = detailsElement.find('.segment');
                $.each(segments, function (i, segment) {
                    segmentDetailHeight = $(segment).find('.segment-details-left').outerHeight();
                    $(segment).find('.product-details td').css('height', segmentDetailHeight - 20);
                });

                UA.UI.processModule(detailsElement);

            },
            renderFlightDetailsVersion3: function (detailContainer, data) {
                detailContainer.html(this.templates.tripDetails(data));
                detailContainer.data('loaded', true);
            },
            renderEconomyUpsell: function (data, economyPlusPanel, currentColumn) {
                var spinnerContainer;
                
                //if (economyPlusPanel.data('isRendered')) {
                //    economyPlusPanel.addClass('active');
                //    return;
                //}
                var tData = data;
                if (tData == null) {
                    tData = {};
                    tData.noData = true;
                }
                tData.currentColumnDescription = currentColumn;
                economyPlusPanel.html(this.templates.economyUpsell(tData));
                spinnerContainer = economyPlusPanel.find('.economy-select-spinner-container');

                if (data === null) {
                    spinnerContainer.loader({ top: "32px" });
                    $('.economy-plus-select-button').hide();
                    $('.economy-select-button').hide();
                } else {
                    //spinnerContainer.loader({ top: "32px", left: "-158px" });
                    if (spinnerContainer.data("ua-loader")) {
                        spinnerContainer.loader('destroy');
                    }
                    //economyPlusPanel.data('isRendered', true);
                }
                
                economyPlusPanel.addClass('active');
                this.initPremiumEconomyNotAvaliableToolTip();
            },
            renderSeatDetailsVersion3: function (seatDetailContainer, params) {
                if (!seatDetailContainer.data('ua-seatmap')) {
                    seatDetailContainer.seatmap({
                        data: params,
                        segments: {
                            enabled: true
                        },
                        seatGrid: {
                            url: this.elements.container.data('seatmapurl')
                        },
                        planeDetails: {
                            enabled: false
                        },
                        afterDisplay: $.proxy(this.initStickyElements, this),
                    });
                }
                seatDetailContainer.data('loaded', true);
            },
            fetchEconomyPlusFare: function (params) {
                //ajax service call here.. return request
                var serviceUrl = this.elements.container.data('geteconomoyplussinglefsr');
                
                if (this.economyPlusFareRequest && this.economyPlusFareRequest.readyState !== 4) {
                        this.economyPlusFareRequest.abort();
                    }
                
                this.economyPlusFareRequest = $.ajax({
                        type: "POST",
                        url: serviceUrl,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify(params)
                    });
            
                return this.economyPlusFareRequest;
            },
            loadEconomyPlusFare: function (economyPlusPanel, selectedProduct, flightHash, currentColumn) {
                var request,
                    //data = { ECONOMY_PRICE: "na", SELECTED_PRODUCT: selectedProduct, FLIGHT_HASH: flightHash, ORIGIN_DECODE: this.currentResults.Trips[0].Origin, DESTINATION_CODE: this.currentResults.Trips[0].Destination },
                    _this = this;
                
                //if (economyPlusPanel.data('isRendered')) {
                //    return;
                //}
                $.when(this.fetchEconomyPlusFare({
                           CartId: $('#CartId').val(),
                           FlightHash: flightHash,
                           ProductId: selectedProduct[0].ProductId
                })).done(function (response) {
                    if (response != null && response.data != null) {
                        var tripIndex = _this.getTripIndex();
                        response.data.SelectedProduct = selectedProduct;
                        response.data.FlightHash = flightHash;
                        response.data.Origin = _this.currentResults.Trips[tripIndex].Origin;
                        response.data.Destination = _this.currentResults.Trips[tripIndex].Destination;
                        _this.renderEconomyUpsell(response.data, economyPlusPanel, currentColumn);
                    }
                    else {
                        var data = {};
                        data.Errors = [];
                        data.Errors.push('EconomyPlus Fare response is null');
                        _this.renderEconomyUpsell(data, economyPlusPanel, currentColumn);
                        console.log("EconomyPlus Fare response is null.");
                    }
                });
                
                //temporary timer to work through ui
                //setTimeout(function () { if ($(economyPlusPanel).hasClass('active')) { _this.renderEconomyUpsell(data, economyPlusPanel); }}, 3000, data, economyPlusPanel, _this);
                //will handle request here later.
            },
            handleCloseEconomyUpsell: function (e) {
                this.collapseEconomyUpsellPanels();
                $(".fare-select-sc-button.button-disable").removeClass('button-disable');
                $(".fare-select-button.button-disable").removeClass('button-disable');
            },

            handleCloseShopSearchCount: function (e) {
                $('.fl-searchcount-container').addClass('invisibilityCloak');
            },
            
            collapseDetailsAndSeatMapTabs: function () {
                $('.ui-tabs-active').each(function () {
                    var flightBlock = $(this).closest('.flight-block'),
                    flightBlockDetails = flightBlock.find('.flight-block-details-container');
                    flightBlockDetails.tabs({ active: false, collapsible: true });
                });
            },
            collapseEconomyUpsellPanels: function () {
                $('.economy-select-section.active').removeClass('active');
            },
            collapseAllTabsAndPanels: function () {
                this.collapseDetailsAndSeatMapTabs();
                this.collapseEconomyUpsellPanels();
                
            },
            initPremiumEconomyNotAvaliableToolTip: function () {
                UA.UI.Tooltip.init($('.tool-tip-pre-econ'), {
                    content: {
                        text: function (event, api) {
                            return $(this).next('.tip-pre-econ').clone();
                        }
                    }
                });
            },
            renderSearchFilters: function (data, refresh, showFilterContent) {
                if (this.currentResults && this.currentResults.Trips && this.currentResults.Trips.length > 0 && this.currentResults.Trips[0].Flights && this.currentResults.Trips[0].Flights.length > 0) {
                    ;
                } else {
                    if (this.currentResults && this.currentResults.appliedSearch && this.currentResults.appliedSearch.flexibleAward === true) {
                        return;
                    }
                }

                var $filterSummaryContainer;
                if (typeof showFilterContent === "undefined" || showFilterContent === null) {
                    showFilterContent = true;
                }
                if (showFilterContent) {
                    var selectedLabel = $("#select-fare-family option:selected").text();
                    if (!this.currentResults.appliedSearch.SearchFilters.FareFamilyDescription) {
                        selectedLabel = _.where(this.currentResults.Trips[0].Columns, {
                            Selected: true
                        });
                        if (selectedLabel && selectedLabel.length > 0) {
                            selectedLabel = selectedLabel[0].ColumnName + " " + selectedLabel[0].Description;
                        } else {
                            selectedLabel = this.currentResults.appliedSearch.SearchFilters.FareFamily;
                        }
                    }
                    data.SearchFilters.FareFamilyDescription = selectedLabel;

                    var minPrice = data.SearchFilters.MinPrices[this.currentResults.appliedSearch.SearchFilters.FareFamily];
                    var maxPrice = data.SearchFilters.MaxPrices[this.currentResults.appliedSearch.SearchFilters.FareFamily];

                    if (minPrice === maxPrice) {
                        data.SearchFilters.HidePrice = true;
                    }

                    data.SearchFilters.nonStop = this.currentResults.appliedSearch.SearchFilters.nonStop;
                    data.SearchFilters.oneStop = this.currentResults.appliedSearch.SearchFilters.oneStop;
                    data.SearchFilters.twoPlusStop = this.currentResults.appliedSearch.SearchFilters.twoPlusStop;
                    data.SearchFilters.nonStopOnly = this.currentResults.appliedSearch.SearchFilters.nonStopOnly;
                    data.SearchFilters.calendarStops = this.currentResults.appliedSearch.SearchFilters.calendarStops;

                    if (!data.SearchFilters.NonStopMinPricesByColumn[this.currentResults.appliedSearch.SearchFilters.FareFamily] ||
                        data.SearchFilters.NonStopMinPricesByColumn[this.currentResults.appliedSearch.SearchFilters.FareFamily] <= 0) {
                        data.SearchFilters.NonStopFormattedAmount = "N/A";
                    }
                    if (!data.SearchFilters.OneStopMinPricesByColumn[this.currentResults.appliedSearch.SearchFilters.FareFamily] ||
                        data.SearchFilters.OneStopMinPricesByColumn[this.currentResults.appliedSearch.SearchFilters.FareFamily] <= 0) {
                        data.SearchFilters.OneStopFormattedAmount = "N/A";
                    }
                    if (!data.SearchFilters.TwoPlusMinPricesByColumn[this.currentResults.appliedSearch.SearchFilters.FareFamily] ||
                        data.SearchFilters.TwoPlusMinPricesByColumn[this.currentResults.appliedSearch.SearchFilters.FareFamily] <= 0) {
                        data.SearchFilters.TwoPlusStopFormattedAmount = "N/A";
                    }

                    data.SearchFilters.CurrentFlightCount = data.Trips[0].CurrentFlightCount;
                    data.SearchFilters.TotalFlightCount = data.Trips[0].TotalFlightCount;

                    data.SearchFilters.ShowClearFilters = true;
                    if (data.SearchFilters.TotalFlightCount > 0 && data.SearchFilters.CurrentFlightCount === data.SearchFilters.TotalFlightCount && !this.currentResults.appliedSearch.SearchFilters.FilterApplied) {
                        data.SearchFilters.ShowClearFilters = false;
                    } else {
                        this.currentResults.appliedSearch.SearchFilters.FilterApplied = true;
                        $('#clear-filters').show();
                    }
                }

                if (refresh) {
                    var data1 = {};
                    $.extend(true, data1, data);
                    if (data1 != null) {
                        if (this.currentResults != null) {
                            data1.SearchType = this.currentResults.SearchType;
                            if (data1.SearchType == null || data1.SearchType === "") {
                                if (this.currentResults.appliedSearch != null) {
                                    data1.SearchType = this.currentResults.appliedSearch.searchTypeMain;
                                }
                            }
                        }

                        if (data1.SearchType === "rt") {
                            data1.SearchType = "roundTrip";
                        } else if (data1.SearchType === "mc") {
                            data1.SearchType = "multiCity";
                        } else if (data1.SearchType === "ow") {
                            data1.SearchType = "oneWay";
                        }
                    }

                    if (data1.Trips && data1.Trips.length > 0 && data1.Trips[0].Flights.length > 0) {
                        data1.SearchFilters.HideExperienceSection = false;
                    }
                    this.elements.filterSortContainer.html(this.templates.searchFilters(data1));
                    if (!this.currentResults.SearchFilters.HideAirportSection) {
                        if ($("#filter-checkbox-connections input:checkbox:checked").length == 0) {
                            $('#filter_oneStop').prop('checked', false);
                            this.currentResults.appliedSearch.SearchFilters.oneStop = false;
                            if (this.currentResults.SearchFilters.HideTwoPlusStop == false) {
                                $('#filter_twoPlusStop').prop('checked', false)
                                this.currentResults.appliedSearch.SearchFilters.twoPlusStop = false;
                            }
                        }
                    }
                    UA.UI.processModule(this.elements.filterSortContainer);
                    $('.trip-count-shown').text(data.SearchFilters.CurrentFlightCount);
                    if (showFilterContent) {
                        if (this.searchFilterMode === 'footerondemand') {
                            this.elements.filterSortContainer.find('[data-toggle=""]').each(function () {
                                $(this).attr('data-toggle', 'toggler');
                            });
                        }
                        UA.UI.Toggler.init();
                        this.initFilterSelections(data);
                    }
                } else if (showFilterContent) {
                    $filterSummaryContainer = $('.fl-results-summary');
                    $filterSummaryContainer.html(this.templates.searchFilterSummary(data));
                    UA.UI.Uniform.update('.fl-filter-container');

                    $('#filter-nonStop-lowest-fare').html(data.SearchFilters.NonStopFormattedAmount);
                    $('#filter-oneStop-lowest-fare').html(data.SearchFilters.OneStopFormattedAmount);
                    $('#filter-twoPlusStop-lowest-fare').html(data.SearchFilters.TwoPlusStopFormattedAmount);

                    _.forEach(data.SearchFilters.AirportsDestinationList, function (destination) {
                        $('#filter-destination-' + destination.Code + '-lowest-fare').html(destination.AmountFormatted);
                    });

                    _.forEach(data.SearchFilters.AirportsOriginList, function (origin) {
                        $('#filter-origin-' + origin.Code + '-lowest-fare').html(origin.AmountFormatted);
                    });
                }
                if (showFilterContent) {
                    if (data.SearchFilters.Warnings.length < 1 && data.SearchFilters.Amenities.length < 2 && data.SearchFilters.CarriersPreference.length < 2 && data.SearchFilters.AircraftList.length < 2) {
                        $(".filter-section-experience").hide();
                    }
                }
                $('#fl-filter-container').trigger('inview');
                this.initStickyElements();
            },
            renderSelectedFlight: function (selectedFlightIndex) {

                var $selectedFlight;
                $selectedFlight = $(this.templates.selectedFlight(this.selectedFlights[selectedFlightIndex]));
                $selectedFlight.appendTo(this.elements.selectedFlightContainer).hide().fadeIn(500);
                this.initFlightBlock(this.elements.selectedFlightContainer.find('.flight-block'));
                this.initTravelersStepper();
                this.initNewSearchToggle();
                UA.UI.processModule($selectedFlight);

            },
            handleFlightBlockTabsBeforeActivate: function (e, ui) {
                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    e.preventDefault();
                    return;
                }

                var tab = ui.newTab.length ? ui.newTab : ui.oldTab,
                    $parentblock = tab.closest('.flight-block');

                $parentblock.toggleClass('flight-block-expanded', ui.newTab.length != 0);

            },
            handleFlightBlockTabsActivate: function (e, ui) {
                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    e.preventDefault();
                    return;
                }

                if (!ui.newTab.length) {
                    this.initStickyElements();
                    $(ui.oldTab.context).css('height', 'auto');
                    return;
                }
                var tabFunc = ui.newTab.data('tab');

                if (!this.isSingleColumnDesignActive()) {
                    $(ui.newTab.context).css('height', ui.newPanel.offset().top - ui.newTab.offset().top - 20);
                }

                if (tabFunc == 'details') {
                    this.handleDetailsTabActivate(e, ui);
                } else if (tabFunc == 'seatmap') {
                    this.handleSeatmapTabActivate(e, ui);
                } 
                this.initStickyElements();
            },
            handleSeatmapTabActivate: function (e, ui) {
                var $target = ui.newTab,
                params = $target.data('seat-select'),
                seatDiv = $target.closest(".flight-block").find(".seatmap-details");
                var isReactViewOnlySeatMapEnabled = $('#hdnReactViewOnlySeatMap').val().toLowerCase() == "true";

                if (isReactViewOnlySeatMapEnabled && params && params.Flights) {
                    if (seatDiv.length > 0) {
                        var iframe = $(seatDiv[0]).find('iframe').length;
                        if (iframe === 0) {
                            $(seatDiv[0]).parent().loader();
                            $(seatDiv[0]).html(this.renderSeatMapIframe(params));
                        }
                    }
                } else {
                    if (!seatDiv.data('ua-seatmap')) {
                        seatDiv.seatmap({
                            data: params,
                            segments: {
                                enabled: true
                            },
                            seatGrid: {
                                url: this.elements.container.data('seatmapurl')
                            },
                            planeDetails: {
                                enabled: true
                            },
                            afterDisplay: $.proxy(this.initStickyElements, this)
                        });
                    }
                }
            },
            renderSeatMapIframe: function (params) {
                return $(
                    "<iframe id='"+ params.Flights.ValidateData +
                    "' src='"+ params.Flights.SeatMapUrl +
                    "' data-segments='" + JSON.stringify(params.Flights.SeatMapItems) +
                    "' style='width: 100%; height: 20px; border: 0;' target='_parent' scrolling='no'/>"
                ).load(function (e) {
                    $(e.target).closest('.flight-block-details-container').loader('destroy');
                });
            },
            handleDetailsTabActivate: function (e, ui) {

                var flightBlock = ui.newTab.closest('.flight-block'),
                    detailsElement = flightBlock.find(".flight-details"),
                    activeFlight,
                    _this = this,
                    lmxRequest,
                    detailsRendered = detailsElement.data('isRendered'),
                    lmxRendered = detailsElement.data('isLmxRendered'),
                    tripIndex;


                if (!detailsRendered || !lmxRendered) {

                    if (detailsRendered && lmxRendered) {
                        return;
                    }

                    if (typeof flightBlock.data('selected-flight-index') === 'undefined') {
                        activeFlight = this.getFlightByHash(flightBlock.data('flight-hash'));
                    } else {
                        activeFlight = this.getSelectedFlightByHash(flightBlock.data('flight-hash'));
                        tripIndex = flightBlock.data('selected-flight-index') + 1; //make index 1 based, ugh
                    }

                    activeFlight.IsAward = this.currentResults.IsAward;
                    this.renderFlightDetails(flightBlock, activeFlight);

                    if (!activeFlight.LmxLoaded && !this.currentResults.IsAward) {
                        lmxRequest = this.loadLmxData(flightBlock.data('flight-hash'), tripIndex);

                        $.when(lmxRequest)
                            .done(function () {
                                _this.renderFlightDetails(flightBlock, activeFlight);
                                UA.UI.Tooltip.init(null, null, null, detailsElement);
                                detailsElement.data('isLmxRendered', true);
                            })
                            .fail(function () {
                                detailsElement.data('isLmxRendered', false);
                            });

                    }

                }
            },
            initFlightBlock: function (flightBlock) {
                if (this.getFSRVersion() != "3") {
                    if (flightBlock == null || flightBlock.length === 0) {
                        if ($('.flight-block').length > 0) {
                            if ($('.flight-block').find('.flight-block-fares-container.use-roundtrippricing').length > 0) {
                                this.initFlightBlockRevenue(flightBlock);
                            } else {
                                this.initFlightBlockOld(flightBlock);
                            }
                        }
                    } else {
                        if ($(flightBlock).find('.flight-block-fares-container.use-roundtrippricing').length > 0) {
                            this.initFlightBlockRevenue(flightBlock);
                        } else {
                            this.initFlightBlockOld(flightBlock);
                        }
                    }
                }

            },
            initFlightBlockOld: function (flightBlock) {
                var self = this;
                $.each(flightBlock || $('.flight-block'), function (x, i) {
                    var $i = $(i);
                    UA.UI.Tabs.init($i.find('.flight-block-details-container'), {
                        tabList: $i.find('.flight-block-tab-list'),
                        collapsible: true,
                        active: false,
                        beforeActivate: $.proxy(self.handleFlightBlockTabsBeforeActivate, self),
                        activate: $.proxy(self.handleFlightBlockTabsActivate, self)
                    });

                    if (($('#hdnShowFareSelectButton').val() === 'True')) {
                        var pricePointWrapMargin = 0,
                            mixedCabin = $i.find(".fare-cabin-mixed"),
                            mixedCabinUpgrade = $i.find(".fare-cabin-mixed-upgrade"),
                            fareoption = $i.find('.flight-block-fares-container .fare-option'),
                            discountedFare = $i.find(".pp-discounted-fare"),
                            corporateMixedRate = $i.find(".corporate-rates-mixed-cabin"),
                            corporateRate = $i.find(".corporate-rates"),
                            IsAward = ($('.fl-results-award').length > 0 ? true : false),
                            fareOptionPricePointWrap = fareoption.find(".price-point-wrap");
                        if (IsAward) {
                            pricePointWrapMargin = 12;
                        } else
                            pricePointWrapMargin = 20;

                        if ((corporateRate.length > 0 && !corporateMixedRate.length > 0) || (discountedFare.length > 0 && !(mixedCabinUpgrade.length > 0 || mixedCabin.length > 0))) {
                            pricePointWrapMargin = 10;
                        }
                        var pricePointPaddingTop = 0;
                        if (corporateRate.length > 0 || corporateMixedRate.length > 0 || discountedFare.length > 0) {
                            var fareTopSpacing = 10;
                            var corporateRateHeight = (corporateRate.length > 0) ? corporateRate.height() : corporateMixedRate.height();
                            var paddingHeight = (discountedFare.length > 0) ? discountedFare.height() : corporateRateHeight;
                            $i.find('.price-point-revised').css("padding-top", paddingHeight + fareTopSpacing);
                            pricePointPaddingTop = parseInt($i.find('.price-point-revised').css("padding-top"));
                            if ($i.find('.fare-not-available').length > 0) {
                                $i.find('.fare-not-available').css("padding-top", pricePointPaddingTop);
                            }
                        }
                        if ($i.find(".fare-option-icon").length > 0) {
                            pricePointWrapMargin = parseInt($i.find(".fare-option-icon").css("top")) + $i.find(".fare-option-icon").height();
                        }
                        if ((mixedCabin.length > 0 || mixedCabinUpgrade.length > 0)) {
                            var mixedHeight = Math.max(mixedCabin.outerHeight(), mixedCabinUpgrade.outerHeight());
                            if (!IsAward) {
                                pricePointWrapMargin -= 6;
                            }
                            pricePointWrapMargin += mixedHeight;
                        }
                        fareOptionPricePointWrap.css("margin-top", pricePointWrapMargin);
                        var additionalPadding = 0;
                        if ((UA.Booking.FlightSearch.IsFlightRecommendationEnabledWithVTwo() || UA.Booking.FlightSearch.IsFlightRecommendationEnabledWithVOne())
                            && $i.find('.date-duration').length > 0 && $i.find('flight-recommendation-block').css("display") != "none" > 0) {
                            additionalPadding = 14;
                        }
                        $i.find('.flight-block-summary-container').css("padding-top", pricePointWrapMargin + pricePointPaddingTop + additionalPadding);
                        var oFareOptionEconomy = $i.find('.fare-option-economy');
                        if (oFareOptionEconomy.length > 0) {
                            var hContainer = $i.find('.flight-block-fares-container').height();
                            var hOutColumn = oFareOptionEconomy.outerHeight(true);
                            if (hContainer > hOutColumn) {
                                oFareOptionEconomy.css("padding-bottom", 0).height(hContainer);
                            }
                        }
                        $i.find('.flight-block-fares-container').find(".fare-option-revised").css("vertical-align", "top");
                        $i.find('.flight-block-fares-container').find(".fare-not-available").css("vertical-align", "middle");
                        $i.find('.fare-not-available').find(".price-point-wrap").css("margin-top", "initial");

                    } else {
                        if (UA.AppData.Data.Session.LangCode.toLowerCase() == "es" || UA.AppData.Data.Session.LangCode.toLowerCase() == "de-de" || UA.AppData.Data.Session.LangCode.toLowerCase() == "pt") {
                            var fareoptionHeight = $i.find('.flight-block-fares-container .fare-option').height() + $i.find(".pp-from-total, .pp-discounted-fare, .pp-remaining-seats, .pp-sub-label").height();
                            var height = Math.max($i.height(), fareoptionHeight);
                            $i.find('.flight-block-fares-container .fare-option').css('height', 'auto').css('height', height);
                        } else {
                            $i.find('.flight-block-fares-container .fare-option').css('height', 'auto').css('height', $i.find('.flight-block-summary-container').outerHeight());
                        }
                    }
                });

                self.elements.resultsContainer.find('.flight-block:odd').addClass('flight-block-odd');

                UA.UI.Tooltip.init();

                if (!this.currentResults.IsAward) {
                    if (this.currentResults.IsListView) {
                        $('.flight-mixed-iternary-list').show();
                        $('.flight-mixed-iternary-expanded').hide();
                    } else {
                        $('.flight-mixed-iternary-list').hide();
                        $('.flight-mixed-iternary-expanded').show();
                    }
                } else {
                    $('.flight-mixed-iternary-list').hide();
                    $('.flight-mixed-iternary-expanded').hide();
                }
                if (this.currentResults.IsListView) {
                    $('.flight-chasebenefit-listview').show();
                    $('.flight-chasebenefit-expanded').hide();
                } else {
                    $('.flight-chasebenefit-listview').hide();
                    $('.flight-chasebenefit-expanded').show();
                }
            },
            initFlightBlockRevenue: function (flightBlock) {
                var self = this;
                $.each(flightBlock || $('.flight-block'), function (x, i) {
                    var $i = $(i);
                    UA.UI.Tabs.init($i.find('.flight-block-details-container'), {
                        tabList: $i.find('.flight-block-tab-list'),
                        collapsible: true,
                        active: false,
                        beforeActivate: $.proxy(self.handleFlightBlockTabsBeforeActivate, self),
                        activate: $.proxy(self.handleFlightBlockTabsActivate, self)
                    });

                    if (($('#hdnShowFareSelectButton').val() === 'True')) {
                        if (self.isRemoveSelectDesignActive()) {
                            var pricepointwraptopMaxheight = Math.max.apply(null, $i.find('.price-point-wrap-top').map(function () {
                                return $(this).outerHeight();
                            }).get());
                            $i.find('.price-point-wrap-top').css('min-height', pricepointwraptopMaxheight);
                            var pricepointwrapmiddleMaxheight = Math.max.apply(null, $i.find('.price-point-middle').map(function () {
                                return $(this).outerHeight();
                            }).get());
                            $i.find('.fare-not-available-middle').css('min-height', pricepointwrapmiddleMaxheight);
                        }
                        var oldLeftPaddingTop = parseFloat($i.find('.flight-block-summary-container').css("padding-top"));
                        var minLeft = 19 + oldLeftPaddingTop;
                        var oldRightMarginTop = parseFloat($i.find('.price-point-wrap.use-roundtrippricing').css("margin-top"));
                        var minRight = 10 + oldRightMarginTop;
                        var hMaxWrapper = 0;
                        var hRecommendation = 0;
                        var hDuration = 0;
                        var hSummary = 0;
                        var hMinPricePoit = 0;
                        var isTripMultiCity = UA.Booking.FlightSearch.currentResults.SearchType && ["mc", "multicity"].indexOf(UA.Booking.FlightSearch.currentResults.SearchType.toLowerCase()) !== -1;
                        if (UA.Booking.FlightSearch.IsFlightRecommendationEnabledWithVTwo() || UA.Booking.FlightSearch.IsFlightRecommendationEnabledWithVOne() || isTripMultiCity) {
                            var recommendation = $i.find('.flight-recommendation-block');
                            if (recommendation.length > 0 &&
                                recommendation.css("display") != "none") {
                                hRecommendation = recommendation.outerHeight(true);
                            }
                        }
                        var duration = $i.find('.date-duration');
                        if (duration.length > 0) {
                            hDuration = duration.outerHeight();
                        }

                        var summary = $i.find('.lof-summary.flight-summary');
                        if (summary.length > 0) {
                            hSummary = summary.outerHeight();
                        }

                        if (hRecommendation > 0) {
                            if (hDuration > 0) {
                                minLeft = hSummary / 2 + hRecommendation + (oldLeftPaddingTop - 3);
                            } else {
                                minLeft = hSummary / 2 + hRecommendation - (oldLeftPaddingTop - 10);
                            }
                        } else {
                            if (hDuration > 0) {
                                minLeft = hSummary / 2 + oldLeftPaddingTop;
                            }
                        }

                        var buttonTops = $i.find('.price-point-wrap-top.use-roundtrippricing');
                        if (buttonTops.length > 0) {
                            $.each(buttonTops, function (idx, elem) {
                                var pricePoint = $(elem).parent().children('.price-point');
                                if (pricePoint.length > 0) {
                                    var hPricePoit = pricePoint.height();
                                    if (hMinPricePoit === 0) {
                                        hMinPricePoit = hPricePoit;
                                    }
                                    else if (hMinPricePoit > hPricePoit) {
                                        hMinPricePoit = hPricePoit;
                                    }
                                }
                            });

                            $.each(buttonTops, function (idx, elem) {
                                var pricePoint = $(elem).parent().children('.price-point');
                                if (pricePoint.length > 0) {
                                    var hWrapTop = $(elem).outerHeight();
                                    var possibleMinRight = hMinPricePoit / 2 + (hWrapTop > 0 ? 3 : 0) + hWrapTop + parseFloat($(elem).parent().css('margin-top'));
                                    if (possibleMinRight > minRight) {
                                        minRight = possibleMinRight;
                                        hMaxWrapper = $(elem).outerHeight();
                                    }
                                }
                            });
                        }

                        var minHeight = (minRight > minLeft) ? minRight : minLeft;

                        var theWrappers = $i.find('.price-point-wrap.use-roundtrippricing');
                        $.each(theWrappers, function (idx, elem) {
                            var hWrap = $(elem).outerHeight();
                            var theWrapperTop = $(elem).children('.price-point-wrap-top.use-roundtrippricing');
                            var oldTop = parseFloat($(elem).css('margin-top'));
                            if (theWrapperTop.length > 0) {
                                var pricePoint = $(elem).children('.price-point');
                                if (pricePoint.length > 0) {
                                    var hWrapTop = theWrapperTop.outerHeight();
                                    var possibleTop = minHeight - hMinPricePoit / 2 - (hWrapTop > 0 ? 3 : 0) - hWrapTop;
                                    if (oldTop !== possibleTop) {
                                        $(elem).css('margin-top', possibleTop);
                                    }
                                } else {
                                    if (oldTop !== minHeight - hMinPricePoit / 2) {
                                        $(elem).css('margin-top', minHeight - hMinPricePoit / 2);
                                    }
                                }
                            } else {
                                if (oldTop !== minHeight - hMinPricePoit / 2) {
                                    $(elem).css('margin-top', minHeight - hMinPricePoit / 2);
                                }
                            }
                        });

                        $i.find('.flight-block-summary-container').css("padding-top", minHeight - hSummary / 2);
                        $i.find('.flight-block-fares-container').find(".fare-option-revised").css("vertical-align", "top");
                        $i.find('.flight-block-fares-container').find(".fare-not-available").css("vertical-align", "middle");
                        $i.find('.fare-not-available').find(".price-point-wrap").css("margin-top", "initial");

                        var oFareOptionEconomy = $i.find('.fare-option-economy');
                        if (oFareOptionEconomy.length > 0) {
                            var hContainer = $i.find('.flight-block-fares-container').height();
                            var hOutColumn = oFareOptionEconomy.outerHeight(true);
                            if (hContainer > hOutColumn) {
                                oFareOptionEconomy.height(hContainer);
                            }
                        }                        
                    } else {
                        if (UA.AppData.Data.Session.LangCode.toLowerCase() == 'es' || UA.AppData.Data.Session.LangCode.toLowerCase() == 'de-de' || UA.AppData.Data.Session.LangCode.toLowerCase() == 'pt') {
                            var fareoptionHeight = $i.find('.flight-block-fares-container .fare-option').height() + $i.find('.pp-from-total, .pp-discounted-fare, .pp-remaining-seats, .pp-sub-label').height();
                            var height = Math.max($i.height(), fareoptionHeight);
                            $i.find('.flight-block-fares-container .fare-option').css('height', 'auto').css('height', height);
                        } else {
                            $i.find('.flight-block-fares-container .fare-option').css('height', 'auto').css('height', $i.find('.flight-block-summary-container').outerHeight());
                        }
                    }
                });

                self.elements.resultsContainer.find('.flight-block:odd').addClass('flight-block-odd');

                UA.UI.Tooltip.init();

                if (!this.currentResults.IsAward) {
                    if (this.currentResults.IsListView) {
                        $('.flight-mixed-iternary-list').show();
                        $('.flight-mixed-iternary-expanded').hide();
                    } else {
                        $('.flight-mixed-iternary-list').hide();
                        $('.flight-mixed-iternary-expanded').show();
                    }
                } else {
                    $('.flight-mixed-iternary-list').hide();
                    $('.flight-mixed-iternary-expanded').hide();
                }
                if (this.currentResults.IsListView) {
                    $('.flight-chasebenefit-listview').show();
                    $('.flight-chasebenefit-expanded').hide();
                } else {
                    $('.flight-chasebenefit-listview').hide();
                    $('.flight-chasebenefit-expanded').show();
                }
            },
            handleFootnoteClick: function()
            {
                $('.footmark').each(function () {
                    var dfootnote = $(this).attr('href');
                    var footmarkID = $(this).attr('id');
                    $(this).click(function (e) {
                        $(dfootnote).focus();
                        $(dfootnote + '> .goback').css('display', 'inline-flex');
                        $(dfootnote + '> .goback').attr('href', '#' + footmarkID);
                        $(dfootnote + '> .goback').animate({ left: 0 },
                           "slow",
                           function () {
                               $(dfootnote + '> .goback').focus();
                           });
                        $(dfootnote + '> .goback').click(function (e) {
                            $(this).css('display', 'none');
                        });
                    });
                });
            },
            showAdvancedCompareModal: function () {
                var usedSearchType;
                if (this.currentResults.SearchType === "rt") { usedSearchType = "roundTrip"; }
                else if (this.currentResults.SearchType === "mc") { usedSearchType = "multiCity"; }
                else if (this.currentResults.SearchType === "ow") { usedSearchType = "oneWay"; }
                else { usedSearchType = this.currentResults.SearchType; }

                var _this = this,
					modalExists = $('#fare-compare-modal').length ? true : false;

                $(modalExists ? '#fare-compare-modal' : '<div />').modal({
                    overlayClose: true,
                    onOpen: function (dialog) {
                        if (modalExists) {
                            dialog.overlay.show();
                            dialog.container.show();
                            dialog.data.show();
                        }
                        else {

                            dialog.container.addClass('modal-loading bundle-compare-ajax');
                            $.modal.setPosition();
                            dialog.overlay.show();
                            dialog.container.show();
                            dialog.container.loader();

                            var bcContentRequest = _this.fetchFareCompareContents(dialog);

                            $.when(bcContentRequest)
								.done(function (response) {
								    if (response != null) {
								        if (response.data != null && response.data.Columns != null) {
								            if (response.data.Columns.length > 0) {
								                _.forEach(response.data.Columns, function (column) {
								                    if (column.ProductType == "ECO-BASIC") {
								                        var bagFee = (column.BagFee != null) ? UA.Utilities.formatting.formatMoney(column.BagFee, column.Currency, 0) : '';
								                        column.FareContentDescription = column.FareContentDescription.replace('{0}', bagFee);
								                    }
								                });
								            }
								            var obj = {
								                isAward: _this.currentResults.IsAward,
								                searchType: usedSearchType,
								                Columns: response.data.Columns,
                                                UpgradeType: (_this.currentResults.appliedSearch != null && _this.currentResults.appliedSearch.UpgradeType != null) ? _this.currentResults.appliedSearch.UpgradeType.toUpperCase() : ''
								            }
								            dialog.data.html(_this.templates.fareComparisonTemplate(obj));
								            dialog.container.loader('destroy');
								            dialog.container.removeClass('modal-loading');
								            $.modal.update();
								            dialog.data.show();
								        }
								    }
								})
								.fail(function (response) {
								    dialog.container.loader('destroy');
								    $.modal.close();
								});
                        }
                    }
                });
            },
            handleFareCompareClick: function (e) {
                e.preventDefault();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    return;
                }

                if (this.currentResults.appliedSearch.awardTravel && this.showTopFiltersAward) {
                    this.showAwardFareCompareModal();
                } else {
                    if ($("#hdnNewBELite").val() == 'True') {
                        this.showAdvancedCompareModal();
                    }
                    else
                    {
                        this.showFareCompareModal();
                    }
                }
            },

            showFareCompareModal: function () {
                $('#fare-compare-modal').modal();
            },

            showAwardFareCompareModal: function () {
                $('#awardfare-compare-modal').modal();
            },

            initNewSearchToggle: function () {
                var _this = this;
                var editFlightSearch = $('#editFlightSearch').val() == 'True' ? true : false;
                if (!editFlightSearch) {
                    $('.btn-show-new-search').toggler({
                        targetSelector: '#fl-new-search-wrap',
                        animate: false,
                        triggerSelector: '.toggle-new-search',
                        onBeforeShow: function () {
                            $(this).parents('section').before($('#fl-new-search-wrap'));
                        },
                        onShow: function () {
                            if (_this.elements.resultsHeaderContainer.hasClass('stuck')) {
                                UA.Utilities.scrollTo($('#fl-new-search-wrap'), 300);
                            }
                            $(this).addClass('invisible');
                        },
                        onHide: function () {
                            $(this).removeClass('invisible');
                        }
                    });
                } else {
                    $('.btn-show-new-search').click(function () {
                        var advancesearch = $('#flightSearch [name="multiple"]').click();
                    });
                }
            },
            initAirportName: function () {
                if ($("#OriginFullName").val() != "") {
                    $("#Origin").val($("#OriginFullName").val());
                }
                if ($("#DestinationFullName").val() != "") {
                    $("#Destination").val($("#DestinationFullName").val());
                }
                if (this.currentResults.appliedSearch.searchTypeMain.toLowerCase() == 'multicity' && $('#editFlightSearch').val() == "True") {
                    for (var i = 0; i < this.currentResults.appliedSearch.Trips.length; i++) {

                        if ($('#OriginFullName_' + i).val() != "") {
                            $('#TripsForEditSearch_' + i + '__Origin').val($('#OriginFullName_' + i).val());
                        }
                        if ($('#DestinationFullName_' + i).val() != "") {
                            $('#TripsForEditSearch_' + i + '__Destination').val($('#DestinationFullName_' + i).val());
                        }
                    }
                }
            },
            initDepartReturnDate: function () {
                if (this.currentResults != null && this.currentResults.appliedSearch != null) {
                    if (this.currentResults.appliedSearch.searchTypeMain.toLowerCase() != 'multicity') {
                        if ($('#editFlightSearch').val() == 'True' && this.currentResults.appliedSearch.flexMonth != null) {
                            $("#DepartDate").val(this.currentResults.appliedSearch.flexMonth);
                        } else {
                            $("#DepartDate").val(this.currentResults.appliedSearch.DepartDate);
                        }
                    } else {
                        if (this.currentResults.appliedSearch.Trips != null) {
                            for (var i = 0; i < this.currentResults.appliedSearch.Trips.length; i++) {
                                $("#TripsForEditSearch_" + i + "__DepartDate").val(this.currentResults.appliedSearch.Trips[i].DepartDate);
                                $("#TripsForEditSearch_" + i + "__Origin").val(this.currentResults.appliedSearch.Trips[i].OriginFullName);
                                $("#TripsForEditSearch_" + i + "__Destination").val(this.currentResults.appliedSearch.Trips[i].DestinationFullName);
                            }
                        }
                    }
                }
            },
            removeValidationOnInitial: function () {
                $('.materialDesign').find('.field-validation-error').closest('.materialDesign').find('.element-label').css('visibility', 'hidden');
                $('.materialDesignBlock').find('.input-validation-error').closest('.materialDesign').find('.element-label').css('visibility', 'hidden');
                $('.materialDesign').find('.field-validation-error').addClass('field-validation-valid');
                $('.materialDesign').find('.field-validation-valid').removeClass('field-validation-error').html('');
                $('.materialDesignBlock').find('.input-validation-error').removeClass('input-validation-error');
            },
            initTravelersStepper: function () {
                var lofTravelersStepper = $('#lof-travelers-selector'),
                    calTravelersStepper = $('#calendar-travelers-selector');

                if (!calTravelersStepper.data('ua-travelerStepper')) {
                    calTravelersStepper.travelerStepper();
                }

                var maxTravelers = $('#hdnMaxAllowedTravelersCount').val();
                if (!lofTravelersStepper.data('ua-travelerStepper')) {
                    lofTravelersStepper.travelerStepper({
                        dropdownOptions: {
                            modal: false
                        },
                        setTriggerText: false,
                        totalMaxValue: maxTravelers == null || maxTravelers == 'undefined' ? 7 : maxTravelers - 1
                    });
                }
            },
            initAirportAutocomplete: function () {
                UA.UI.Autocomplete.applyAirportAutocomplete($('input[data-autocomplete-airport]'));
            },
            fetchAwardCalendar: function (params) {
                var serviceUrl = this.elements.container.data('awardcalendarurl'),
                    _this = this;

                if (_this.awardCalendarRequest && _this.awardCalendarRequest.readyState !== 4) {
                    _this.awardCalendarRequest.abort();
                }

                _this.awardCalendarRequest = $.ajax({
                    type: "POST",
                    url: serviceUrl,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(params)
                });

                return _this.awardCalendarRequest;

            },
            loadAwardCalendar: function (searchParams) {
                var _this = this, request;

                request = _this.fetchAwardCalendar(searchParams);

                _this.renderAwardCalendar(getAwardCalendarFillerData(searchParams.AwardCalendarType));
                setTimeout(function () {
                    _this.awardCalenderShowLineLoader(); //Award Calender Loader
                }, 50);
                $.when(request).done(function (response) {
                    if (response.data !== null && response.data.Calendar !== null) {
                        _this.awardCalendarResults = response.data.Calendar;
                       // _this.awardCalendarResults.cabinTypeSelection = _this.currentResults.appliedSearch.cabinSelection != null ? _this.currentResults.appliedSearch.cabinSelection.toLowerCase() : "economy";
                        // Bug 1336683                        
						_this.awardCalendarResults.cabinTypeSelection = searchParams.cabinSelection != null ? searchParams.cabinSelection.toLowerCase() : "economy"; //updated cabin selection is inserted                         
					   _this.awardCalendarResults.isCabinTypeChange = true;
                        _this.renderAwardCalendar(_this.prepareCalendarData(_this.awardCalendarResults));
                        if (_this.currentResults && _this.currentResults.SearchFilters && _this.currentResults.SearchFilters.HideNoneStop) {
                            $('#award-nonstop-calendar-chkbox').hide();
                        }
                        if (searchParams.isChangeWeek) { if ($('.cal-select-day').first().length > 0) { $('.cal-select-day').first().focus(); } }
                    } else {
                        _this.renderAwardCalendar({
                            error: true
                        });
                    }
                }).then(function () {
                    _this.awardCalenderClearLineLoader(); //Award Calender Loader
                    //_this.ShowLoginModalForAward();
                    IsServiceCallCompleted = true;
                    _this.readPageContentOnPageLoad();
                });
            },
            displayAwardCalendarLowestFare: function () {
                var searchedDateIsLowest = $('.date-searched.date-lowest-fare').attr('data-cal-date');
                if (typeof searchedDateIsLowest !== "undefined") {
                    $('.date-lowest-fare').each(function () {
                        if ($(this).attr('data-cal-date') !== searchedDateIsLowest) {
                            if ($('#ngrpFinetuning').val() == 'True') {
                                $(this).removeClass("date-serach-lowest-fare");
                            }
                            else {
                                $(this).addClass("reset-lowest-fare'");
                                $(this).find('.sub-text').hide();
                            }
                        }
                        else {
                            if ($('#ngrpFinetuning').val() == 'True') {
                                $(this).addClass("date-serach-lowest-fare");
                            }
                            $(this).removeClass('reset-lowest-fare');
                            $(this).find('.sub-text').show();
                        }
                    });
                }
                else {
                    $('.date-lowest-fare').each(function () {
                        if ($(this).attr('data-cal-date') !== searchedDateIsLowest) {
                            if ($('#ngrpFinetuning').val() == 'True') {
                                $(this).removeClass("date-serach-lowest-fare");
                            }
                            $(this).removeClass('reset-lowest-fare');
                            $(this).find('.sub-text').show();
                        }
                    });
                }
            },
            renderAwardCalendar: function (calendarData) {
                calendarData = calendarData || this.awardCalendarResults;
                this.elements.calendarContainer.html(this.templates.awardCalendar(calendarData));
                this.displayAwardCalendarLowestFare();
                UA.UI.reInit(this.elements.calendarContainer);
            },
            prepareCalendarData: function (unpreparedCalendarData) {

                if (unpreparedCalendarData.loading) {
                    return unpreparedCalendarData;
                }

                var preparedCalendarData = _.cloneDeep(unpreparedCalendarData);
                preparedCalendarData = this.filterAwardCalendarDataByCabintype(preparedCalendarData);
                for (var i = 0; i < preparedCalendarData.Months[0].Weeks.length; i++) {
                    for (var j = 0; j < preparedCalendarData.Months[0].Weeks[i].Days.length; j++) {
                        if (preparedCalendarData.Months[0].Weeks[i].Days[j].Products.length==0 && unpreparedCalendarData.Months[0].Weeks[i].Days[j].Products.length>0) 
                        {
                            preparedCalendarData.Months[0].Weeks[i].Days[j].Products = unpreparedCalendarData.Months[0].Weeks[i].Days[j].Products;
                        }
                    }
                }
                preparedCalendarData.transition = !unpreparedCalendarData.isCabinTypeChange;
                preparedCalendarData.isWeeklyCalendarView = false;
                preparedCalendarData.isMonthlyCalendarView = true;

                return preparedCalendarData;
            },
            filterAwardCalendarDataByCabintype: function (calendarData) {
                if (!calendarData.cabinTypeSelection) {
                    return calendarData;
                }

                _.forEach(calendarData.Months, function (month, i) {
                    _.forEach(month.Weeks, function (week, x) {
                        _.forEach(week.Days, function (day, y) {
                            day.Products = _.filter(day.Products, function (p) {
                                return p.CabinType.toLowerCase() === calendarData.cabinTypeSelection.toLowerCase();
                            });
                        });
                    });
                });

                return calendarData;
            },
            showAwardCalendarLoader: function () {
                if (this.showTopFiltersAward) {
                    //this.awardShowLineLoader();
                    var calendarLoader = $("#fl-award-calendar-loader"),
                        spinnerEl = calendarLoader.find('.spinner-container');

                    if (!spinnerEl.data('ua-loader')) {
                        spinnerEl.loader({
                            zIndex: 9999
                        });
                    }
                    calendarLoader.show();
                } else {
                    var calendarLoader = $("#fl-award-calendar-loader"),
                        spinnerEl = calendarLoader.find('.spinner-container');

                    if (!spinnerEl.data('ua-loader')) {
                        spinnerEl.loader({
                            zIndex: 9999
                        });
                    }
                    calendarLoader.show();
                }
            },
            awardShowLineLoader: function () {
                var data = {};
                this.lineLoaderState = "loading";
                data.loadingState = this.lineLoaderState;
                this.elements.awardLineLoaderSection.html(this.templates.lineLoader(data));
                this.lineLoaderAnimation('.load', '.bar');
              },
            awardClearLineLoader: function () {
                this.lineLoaderState = "";
                this.elements.awardLineLoaderSection.empty();
            },
            fetchFareWheel: function (params) {

                var serviceUrl = this.elements.container.data('farewheelurl');

                if (this.fareWheelRequest && this.fareWheelRequest.readyState !== 4) {
                    this.fareWheelRequest.abort();
                }

                if (!(params.isReshopPath && !params.awardTravel))
                {
                    this.fareWheelRequest = $.ajax({
                        type: "POST",
                        url: serviceUrl,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify(params)
                    });
                }
                return this.fareWheelRequest;

            },
            fetchNonStopDate: function (params) {

                var serviceUrl = this.elements.container.data('nonstopdateurl');

                if (this.nonStopDateRequest && this.nonStopDateRequest.readyState !== 4) {
                    this.nonStopDateRequest.abort();
                }

                this.nonStopDateRequest = $.ajax({
                    type: "POST",
                    url: serviceUrl,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(params),
                    async: true,
                    cache: false
                });
                return this.nonStopDateRequest;
            },
            fetchNearbyCities: function (searchInput) {
                var serviceUrl = this.elements.container.data('nearbycitiesurl');
                var params = {
                    SearchType: UA.Booking.FlightSearch.currentResults.SearchType,
                    Origin: UA.Booking.FlightSearch.currentResults.Trips[0].Origin,
                    Destination: UA.Booking.FlightSearch.currentResults.Trips[0].Destination,
                    DepartDate: searchInput.Trips[0].DepartDate,
                    ReturnDate: UA.Booking.FlightSearch.currentResults.SearchType === "roundTrip" ? searchInput.Trips[1].DepartDate : ""
                };

                if (this.nearbyCitiesRequest && this.nearbyCitiesRequest.readyState !== 4) {
                    this.nearbyCitiesRequest.abort();
                }

                this.nearbyCitiesRequest = $.ajax({
                    type: "POST",
                    url: serviceUrl,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(params),
                    async: true,
                    cache: false
                });
                return this.nearbyCitiesRequest;
            },
            fetchFareMatrix: function (params) {
                var serviceUrl = this.elements.container.data('farematrixurl');

                if (this.fareMatrixRequest && this.fareMatrixRequest.readyState !== 4) {
                    this.fareMatrixRequest.abort();
                }

                this.fareMatrixRequest = $.ajax({
                    type: "POST",
                    url: serviceUrl,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(params)
                });

                return this.fareMatrixRequest;
            },
            fetchFlightResults: function (params) {
                var serviceUrl = this.elements.container.data('resultsurl');

                if (this.request && this.request.readyState !== 4) {
                    //this.request.abort();
                }
                
                var confirmationID = $('#hdnConfirmationID').val();
                this.request = $.ajax({
                    type: "POST",
                    url: serviceUrl,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify({ searchInput: params, pnr: confirmationID })
                });

                return this.request;

            },

            getLowestRevenueFare: function (params) {
                var serviceUrl = this.elements.container.data('lowestrevenuefareurl');

                if (this.lowestRevenueRequest && this.lowestRevenueRequest.readyState !== 4) {
                    this.lowestRevenueRequest.abort();
                }

                this.lowestRevenueRequest = $.ajax({
                    type: "POST",
                    url: serviceUrl,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(params)
                });

                return this.lowestRevenueRequest;
            },

            fetchClearAllFilters: function (tripIndex) {
                var serviceUrl = this.elements.container.data('filtersurl');
                var cachedSearchInput = UA.Booking.FlightSearch.currentResults.appliedSearch.Cached;
                this.filtersRequest = $.ajax({
                    type: "POST",
                    cache: false,
                    url: serviceUrl,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify({ tripIndex: tripIndex, cachedSearchInput: cachedSearchInput})
                });

                return this.filtersRequest;
            },

            getRecommendedFlightRequest: function (cartID, tripIndex) {
                var serviceUrl = this.elements.container.data('getrecommendedflights');

                if (this.flightRecommendationRequest && this.flightRecommendationRequest.readyState !== 4) {
                    this.flightRecommendationRequest.abort();
                }

                this.flightRecommendationRequest = $.ajax({
                    type: "POST",
                    url: serviceUrl,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify({
                        cartId: cartID,
                        tripIndex: tripIndex
                    })
                });

                return this.flightRecommendationRequest;
            },
            fetchNextFlightResults: function (params) {
                var serviceUrl = this.elements.container.data('resultsurl');

                if (this.request && this.request.readyState !== 4) {
                    this.request.abort();
                }

                this.request = $.ajax({
                    type: "POST",
                    url: serviceUrl,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(params),
                    async: false
                });

                return this.request;

            },
            loadFlightResults: function (searchInput) {
                var request, _this = this;
                scCurrentCabinIndex = -1;
                searchInput = _.omit(searchInput, 'AppliedSearch');
                searchInput = _.omit(searchInput, 'SearchFilters');
                searchInput = _.omit(searchInput, 'PosCountryList');

                if ($("#hdnManageReviseTrip").val() == 'True' && searchInput.Revise == true) {
                    this.ResetReviseStatus(searchInput);
                }
                var stopnonstopfeature = ($('#StopNonStop').val() == "True" ? true : false) && !searchInput.CalendarOnly && !($('#hdnAward').val() == "True" ? true : false);
                if (stopnonstopfeature) {
                    var trpindex = _this.getTripIndex();
                    if (searchInput.Revise && trpindex == 0) {
                        trpindex = searchInput.CurrentTripIndex;
                    } else {
                        searchInput.CurrentTripIndex = trpindex;
                    }
                    //605465- EQA:Booking 2.0: Flight results are not displayed when we Change date in Fare wheel after clicking "Revise" Link in Shopping Cart. 
                    var param = null;
                    try {
                        param = UA.Utilities.readCookie("SearchInput");
                    }
                    catch (exception) {
                        param = null;
                    }
                    if (searchInput.Trips == null && param != null) {

                        searchInput.Trips = param.Trips;
                    }
                    if (searchInput.Trips != null && searchInput.Trips && searchInput.Trips.length > trpindex && searchInput.Trips[trpindex].NonStopMarket) {
                        searchInput = _this.prepareSearchInput(searchInput, trpindex);
                    }
                }
                if (this.currentResults.appliedSearch.StartFlightRecommendation) {
                    searchInput.StartFlightRecommendation = this.currentResults.appliedSearch.StartFlightRecommendation;
                }
                if (this.currentResults.appliedSearch.FareWheelOrCalendarCall) {
                    searchInput.FareWheelOrCalendarCall = this.currentResults.appliedSearch.FareWheelOrCalendarCall;
                }
                //WI:667632 D2 Booking_Award travel_GovernmentPath_Flight search results: Per Ruby there should be no award option for government path (Update button)	
                var govtPathValue = {
                    MilitaryOrGovernmentPersonnelStateCode: searchInput.MilitaryOrGovernmentPersonnelStateCode,
                    MilitaryTravelType: searchInput.MilitaryTravelType,
                    GovType: searchInput.GovType,
                    isGovtPath: ((searchInput.MilitaryOrGovernmentPersonnelStateCode == undefined || searchInput.MilitaryOrGovernmentPersonnelStateCode == null || searchInput.MilitaryOrGovernmentPersonnelStateCode == '') ? false : true) || ((searchInput.MilitaryTravelType == undefined || searchInput.MilitaryTravelType == null || searchInput.MilitaryTravelType == '') ? false : true)
                };
                UA.Utilities.safeSessionStorage.setItem("GovtPath", JSON.stringify(govtPathValue));

                this.showPageLoader();

                this.showContentMessage();

                if (searchInput.Matrix3day) {
                    _this.handleFareMatrixLinkClick(window.event);
                    UA.UI.Uniform.init();
                    _this.initStickyElements();
                    return;
                }
                request = this.fetchFlightResults(searchInput);
                this.elements.resultsFooter.hide();
                if (!searchInput.IsParallelFareWheelCallEnabled || (searchInput.CellIdSelected != null && searchInput.CellIdSelected != '')) {
                    _this.loadFlightResultsWithFareWheelSquentialCall(searchInput, request);
                } else {
                    _this.loadFlightResultsWithFareWheelParallelCall(searchInput, request);
                }
                this.resetSettings();
            },
            ResetReviseStatus: function (searchInput) {
                //1504269:Clear the Revise flag once it is used for selected revise trip.
                //RevisingSearch flag to be sent as true only for the selected revise trip. It should be false for all the upcoming shopselect trip calls.                
                var currentTripidx = this.getTripIndex();
                if (currentTripidx == 0) {
                    currentTripidx = searchInput.CurrentTripIndex;
                }
                
                if (currentTripidx != searchInput.SelectedReviseTripIndex) {
                    searchInput.Revise = false;
                }                
            },
            RedirectToAdvanceSearch: function (error) {
                //clear page and show loading indicator
                this.abortCurrentRequests();
                $('#FlightResultsError, #fl-notices').hide();
                this.elements.calendarContainer.empty();
                if (showFsrTips) {
                    if (fsrTipsPhase2) {
                        this.emptyFsrTips();
                    } else {
                        this.elements.resultsHeaderSegmentNearbyCities.empty();
                        this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
                        this.elements.resultsHeaderSegmentBetterOffers.empty();
                    }
                }
                this.elements.resultsHeaderSegmentContainer.empty();
                this.elements.resultsHeaderSegmentFareDisclaimerContainer.empty();
                this.elements.resultsHeaderContainer.empty();
                this.elements.resultsContainer.empty();
                this.elements.filterSortContainer.empty();
                this.elements.newSearchContainer.empty();
                this.elements.resultsFooter.empty();
                this.elements.selectedFlightContainer.empty();
                this.elements.resetNotificationContainer.empty();
                this.resetTabbedFWHeader();
                $('.cart-container').empty();
                this.showPageLoader();
                window.location.href = this.elements.container.data('advancedsearch').concat("?cid=", this.currentResults.appliedSearch.CartId, "&error=", error);
            },
            loadFlightResultsWithFareWheelSquentialCall: function (searchInputNonStop, request) {
                var i, _this = this;
                _this.globalFWResponse = null;//CSI1303 SHD/Butrenkuu
                searchInputNonStop = _.omit(searchInputNonStop, 'AppliedSearch');
                searchInputNonStop = _.omit(searchInputNonStop, 'SearchFilters');
                searchInputNonStop = _.omit(searchInputNonStop, 'PosCountryList');

                var isReshopPath = this.currentResults.appliedSearch.isReshopPath;
                if (isReshopPath) {
                    this.showPageLoader(true);
                }
                else {
                    this.showPageLoader();
                }
                this.elements.resultsFooter.hide();
                this.elements.noFlightMesssageSection.empty();
                var isNonStopsEmpty = false;
                if (showFsrTips && !fsrTipsPhase2 && fsrTipsShowNonstopSuggestion) {
                    this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
                }

                //if (!searchInput.IsParallelFareWheelCallEnabled || (searchInput.CellIdSelected != null && searchInput.CellIdSelected != '')) {
                //    var fareWheelInput = searchInput;
                //    if (searchInput.CartId != _this.currentResults.appliedSearch.CartId) {
                //        fareWheelInput = $.extend(true, {}, searchInput);
                //        fareWheelInput.CartId = _this.currentResults.appliedSearch.CartId;
                //    }
                //    _this.loadFareWheel(fareWheelInput);
                //}                
                var fareWheelRequest
                var fareWheelSearchInput = {};
                $.extend(true, fareWheelSearchInput, searchInputNonStop);
                if (fareWheelSearchInput!=null && fareWheelSearchInput.CurrentTripIndex!=null)
                fareWheelSearchInput.Trips[fareWheelSearchInput.CurrentTripIndex].StopCount = 0;
                if (!this.currentResults.appliedSearch.awardTravel && (searchInputNonStop.CellIdSelected == null || searchInputNonStop.CellIdSelected == '' || $('#FWParallelCallOnFSR2').val() == "True")) {                    
                    fareWheelRequest = _this.fetchFareWheel(fareWheelSearchInput);
                }

                var tripindx = searchInputNonStop.CurrentTripIndex;
                var stopnonstopfeature = (($('#StopNonStop').val() == "True" ? true : false) && searchInputNonStop.Trips && searchInputNonStop.Trips.length > tripindx &&
                    searchInputNonStop.Trips[tripindx].NonStopMarket && !this.currentResults.appliedSearch.awardTravel && !searchInputNonStop.CalendarOnly);
                var requestForStopFlights = {};
                var searchInput = {};
                if (stopnonstopfeature) {
                    $.extend(true, searchInput, searchInputNonStop);
                    if (searchInputNonStop != null && searchInputNonStop.CurrentTripIndex != null)
                    searchInput.Trips[searchInputNonStop.CurrentTripIndex].StopCount = 2;
                    searchInput.StartFlightRecommendation = false;
                    if ($('#FSRParallelCall').val() == "True") {
                        requestForStopFlights = _this.fetchFlightResults(searchInput);
                    }
                }

                $.when(request).done(function (response) {
                    scCurrentCabinIndex = -1;
                    _this.removeCabinsforSingleColumnDesign(response);
                    _this.buildFlightResults(searchInputNonStop, response, null, fareWheelRequest);
                    if (_this.showTopFilters || _this.showTopFiltersAward) {
                        //$("#filter-search-result").hide();
                    }
                    _this.displayWarningMessages(response);
                    if ($('#editFlightSearch').val() === "True") {
                        var totalTrips = parseInt($("#hdnTotalTrips").val(), 10),
                            currentTripIndex = parseInt(_this.elements.currentTripIndex.val(), 10);
                        if (currentTripIndex <= totalTrips) {
                            _this.RenderFSRCart(response, currentTripIndex);
                        }
                    }
                }).then(
                    function (response) {
                        _this.removeCabinsforSingleColumnDesign(response);
                        _this.ShopMainErrorCheck(response);
                        if (stopnonstopfeature) {
                            var nononstopresultserror = true;
                            if (response.status !== "success") {
                                for (i = 0; i < response.data.Errors.length; i += 1) {
                                    if ((response.data.Errors[i].MajorCode === "FA" && response.data.Errors[i].MinorCode === "131") ||
                                        (response.data.Errors[i].MinorCode === "10038" && response.data.Errors[i].MinorDescription == "Service Error – No results found")) {
                                        nononstopresultserror = true;
                                        isNonStopsEmpty = true;
                                        break;
                                    } else nononstopresultserror = false;
                                }
                            }
                            if (nononstopresultserror) {
                                var timeout = 0,
                                    hasnonstop = false;
                                searchInput.Trips[tripindx].HasNonStopFlights = false;
                                var trip = searchInput.Trips[tripindx];
                                if (response.status == "success" && response.data.Trips && response.data.Trips.length > 0 && response.data.Trips[0].TotalFlightCount > 0) {
                                    searchInput.Trips[tripindx].HasNonStopFlights = hasnonstop = true;
                                    timeout = 500;
                                    searchInput.LowestNonStopEconomyFare = response.data.Trips[0].LowestEconomyFare;
                                }
                                if (searchInput.Trips[tripindx].HasNonStopFlights) {
                                    _this.OnSuccessBuildFlightResults(response, searchInput, fareWheelRequest);
                                    if (!isReshopPath)
                                    {
                                        _this.ProcessRecommendedFlights();
                                    }                                   
                                }
                                setTimeout(function () {
                                    var noflightError = false,
                                        errormsg, stopspecificsearch = (!hasnonstop && !trip.nonStop && (trip.oneStop || trip.twoPlusStop));
                                    if (stopspecificsearch) {
                                        _this.elements.resultsContainer.empty();
                                    }
                                    if (trip.oneStop || trip.twoPlusStop || (!trip.nonStop && !trip.oneStop && !trip.twoPlusStop)) {
                                        _this.showStopsLoader();
                                        if (showFsrTips) {
                                            if (fsrTipsPhase2) {
                                                var bRemoved1 = _this.fsrTipsData.removeAll("nearbyCity");
                                                var bRemoved2 = _this.fsrTipsData.removeAll("betterOffer");
                                                if (bRemoved1 || bRemoved2) {
                                                    this.drawFsrTips();
                                                }
                                            } else {
                                                _this.elements.resultsHeaderSegmentNearbyCities.empty();
                                                _this.elements.resultsHeaderSegmentBetterOffers.empty();
                                            }
                                        }
                                    }
                                    if (response.data.CartId != null) {
                                        searchInput.CartId = response.data.CartId;
                                    }
                                    searchInput.HideFarewheel = false;
                                    if (_this.selectedFlights[tripindx] == null) {
                                        //request = _this.fetchFlightResults(searchInput);
                                        if ($('#FSRParallelCall').val() != "True") {
                                            requestForStopFlights = _this.fetchFlightResults(searchInput);
                                        }
                                        if (!isNonStopsEmpty) {
                                            UA.Utilities.addLinearLoader($('.loader-section-fsr'));
                                            $('.loader-section-text').show();
                                        }
                                        $.when(requestForStopFlights).done(function (response) {
                                            scCurrentCabinIndex = -1;
                                            _this.removeCabinsforSingleColumnDesign(response);
                                            if (_this.selectedFlights[tripindx] == null && response.status == "success") {
                                                _this.buildFlightResults(searchInput, response, null, fareWheelRequest);
                                                //_this.ProcessRecommendedFlights();
                                                if (showFsrTips && fsrTipsShowNonstopSuggestion) {
                                                    _this.showNonStopSuggestMessage(searchInputNonStop);
                                                }
                                            } else if (response.status != "success") {
                                                for (i = 0; i < response.data.Errors.length; i += 1) {
                                                    if ((response.data.Errors[i].MajorCode === "FA" && response.data.Errors[i].MinorCode === "131") ||
                                                        (response.data.Errors[i].MinorCode === "10038" && response.data.Errors[i].MinorDescription == "Service Error – No results found")) {
                                                        noflightError = true;
                                                        errormsg = response.data.Errors[i].Message;
                                                        break;
                                                    }
                                                }
                                                if (!noflightError) {
                                                    $(_this.templates.flightResultSearch()).appendTo(_this.elements.resetNotificationContainer.empty()).show();
                                                }
                                                if (_this.elements.calendarContainer !== null && response.data.Calendar !== null) {
                                                    if (_this.currentResults.appliedSearch.flexible) {
                                                        _this.renderFareCalendar();
                                                    } else {
                                                        $('#fl-calendar-wrap').removeClass('flexible-calendar');
                                                        _this.renderAvailabilityCalendar();
                                                        _this.clearLineLoaderSection();
                                                    }
                                                } else if (!searchInput.IsParallelFareWheelCallEnabled || (searchInput.CellIdSelected != null && searchInput.CellIdSelected != '')) {
                                                    var fareWheelInput = searchInput;
                                                    if (searchInput.CartId != _this.currentResults.appliedSearch.CartId) {
                                                        fareWheelInput = $.extend(true, {}, searchInput);
                                                        fareWheelInput.CartId = _this.currentResults.appliedSearch.CartId;
                                                    }
                                                    if (fareWheelRequest) {
                                                        $.when(fareWheelRequest).done(function (fareWheelResponse) {
                                                            _this.buildFareWheel(fareWheelResponse);
                                                        });
                                                    } else {
                                                        _this.loadFareWheel(fareWheelSearchInput);
                                                    }
                                                }
                                                //_this.ProcessRecommendedFlights();
                                                if (showFsrTips && fsrTipsShowNonstopSuggestion) {
                                                    _this.showNonStopSuggestMessage(searchInputNonStop);
                                                }
                                            }
                                        }).then(
                                            function (response) {
                                                _this.removeCabinsforSingleColumnDesign(response);
                                                if (_this.selectedFlights[tripindx] == null && response.status == "success") {
                                                    if (_this.showTopFilters || _this.showTopFiltersAward) {
                                                        //if (_this.currentResults.SearchFilters && !_this.currentResults.SearchFilters.HideAirportSection && _this.currentResults.SearchFilters.AirportsStopList.length > 0) {
                                                        //    $("#filter-search-result").show();
                                                        //} else {
                                                        //    $("#filter-search-result").hide();
                                                        //}
                                                    }
                                                    _this.OnSuccessBuildFlightResults(response, searchInput, fareWheelRequest);
                                                    return response;
                                                } else if (response.status != "success") {
                                                    if (!noflightError) {
                                                        $(_this.templates.flightResultSearch()).appendTo(_this.elements.resetNotificationContainer.empty()).show();
                                                    } else if (noflightError && stopspecificsearch) {
                                                        $(_this.templates.flightResultEmpty(response.data)).appendTo(_this.elements.resultsContainer.empty()).show();
                                                    } else if (isNonStopsEmpty && noflightError) {
                                                        _this.OnSuccessBuildFlightResults(response, searchInput, fareWheelRequest);
                                                    }
                                                }
                                            }
                                        ).always(function () {
                                                UA.Utilities.removeLinearLoader($('.loader-section-fsr'));
                                                $('.loader-section-text').hide();
                                                _this.hidePageLoader();
                                                // _this.MakeFSRResultsAccessible();
                                            });
                                    } else {
                                        _this.hidePageLoader();
                                        //_this.MakeFSRResultsAccessible();
                                    }
                                }, timeout);
                            } else {
                                _this.OnSuccessBuildFlightResults(response, searchInput, fareWheelRequest);
                            }
                        } else {
                            //if (_this.showTopFilters || _this.showTopFiltersAward) {
                            //    setTimeout(function () {
                            //        if (_this.currentResults && _this.currentResults.SearchFilters && !_this.currentResults.SearchFilters.HideAirportSection && _this.currentResults.SearchFilters.AirportsStopList.length > 0) {
                            //            $("#filter-search-result").show();
                            //        }
                            //        else { $("#filter-search-result").hide(); }
                            //    }, 10);
                            //}
                            _this.OnSuccessBuildFlightResults(response, searchInputNonStop, fareWheelRequest);
                            if (!isReshopPath)
                            {
                                _this.ProcessRecommendedFlights();
                            }                            
                            if (showFsrTips && fsrTipsShowNonstopSuggestion) {
                                _this.showNonStopSuggestMessage(searchInputNonStop);
                            }
                        }
                        return response;
                    },
                    function (response) {
                        return $.Deferred().reject(response);
                    }
                    ).always(function (response) {
                        if (!isNonStopsEmpty) {
                            _this.hidePageLoader();
                            UA.UI.Uniform.init();
                            _this.initStickyElements();
                            if (!isInitialload) {
                                _this.MakeFSRResultsAccessible();
                            }
                        }
                        _this.currentResults.appliedSearch.StartFlightRecommendation = false;
                        _this.renderShopSearchCount(response.data);                        
                    });
            },
            ShopMainErrorCheck: function (response) {
                if (response && response.data && response.data.Errors && _.some(response.data.Errors, function (error) { return error.MinorCode == "10080" })) {
                    this.RedirectToAdvanceSearch("pet");
                    return true;
                }
                return false;
            },
            OnSuccessBuildFlightResults: function (response, searchInput, fareWheelRequest) {
                var noResults, i, _this = this;
                var isSearchNearBy;
                var nearbySearchErrorMsg;
                var isAgencyError = false;
                if (response != null && response.data != null && response.data.Errors != null && response.data.Errors.length > 0) {
                    for (i = 0; i < response.data.Errors.length; i += 1) {
                        if (response.data.Errors[i] && response.data.Errors[i].Message == "AgencyServiceErrorProcessing") {
                            isAgencyError = true;
                        }
                    }
                }
                var noSeats;
                if (response.status !== "success" && response.data.Errors != null && isAgencyError) {
                    $('#AgencyPNRFlightResultsError').show();
                }
                else if (response.status !== "success" && !isAgencyError) {
                    $('#AgencyPNRFlightResultsError').hide();
                    if (response.data.Errors != null) {
                        noResults = false;
                        isSearchNearBy = false;
                        for (i = 0; i < response.data.Errors.length; i += 1) {
                            if ($("#hdnNoFlightSeasionalStation").val() == 'True') {
                                if ((response.data.Errors[i].MajorCode === "FA" && response.data.Errors[i].MinorCode === "136") ||
                                (response.data.Errors[i].MajorCode === "FA" && response.data.Errors[i].MinorCode === "137") ||
                                    (response.data.Errors[i].MajorCode === "FA" && response.data.Errors[i].MinorCode === "131")) {
                                    isSearchNearBy = true;
                                    $("#seasionalStationMsg").html(response.data.Errors[i].Message);
                                }
                            }
                            else {
                                if (response.data.Errors[i].MajorCode === "FA" && response.data.Errors[i].MinorCode === "131") {
                                    isSearchNearBy = true;
                                    if (showFsrTips && fsrTipsShowNearbyError) {
                                        nearbySearchErrorMsg = response.data.Errors[i].Message;
                                    } else {
                                        $("#nearbysearcherrormsg").html(response.data.Errors[i].Message);
                                    }
                                }
                            }
                            if (response.data.Errors[i].MajorCode === "FA" && response.data.Errors[i].MinorCode === "9") {
                                noSeats = true;
                            }
                            if (response.data.Errors[i].MinorCode === "10061")
                            {
                                if (response.data.Errors[i].Message != null)
                                {
                                    $('#SeniorandInfant').show();
                                }
                                noResults = true;
                            }
                            if (response.data.Errors[i].MinorCode === "10038") {
                                if (response.data.Errors[i].Message != null) {
                                    if (_this.currentResults.appliedSearch.awardTravel) {
                                        $('#FlightResultsError')[0].innerHTML = response.data.Errors[i].Message;
                                    }
                                    else if ($('#FlightResultsError').find('li').length > 0 && $('#FlightResultsError').find('li')[0] != null && !isSearchNearBy) {
                                        $('#FlightResultsError').find('li')[0].innerHTML = response.data.Errors[i].Message;
                                    }
                                }
                                noResults = true;
                            }
                            if (response.data.Errors[i].MinorCode === "10036") {
                                if (response.data.Errors[i].Message != null) {
                                    $('#FlightResultsError').show();
                                }
                                noResults = true;
                            }
                            if (response.data.Errors[i].MinorCode === "10051") {
                                if (response.data.Errors[i].Message != null) {
                                    $('#FlightResultsError').show();
                                }
                                noResults = true;
                            }
                        }
                        if (!isSearchNearBy) {
                            if ($('#hdnNoFlightSeasionalStation').val() == 'True') {
                                $('#seasionalStationError').hide();
                            }
                            else {
                                if (showFsrTips && fsrTipsPhase2 && fsrTipsShowNearbyError) {
                                    var bRemoved = _this.fsrTipsData.removeAll("nearbyError");
                                    if (bRemoved) {
                                        this.drawFsrTips();
                                    }
                                } else {
                                    $('#gridNearByError').hide();
                                }
                            }
                            $('#FlightResultsError').show();
                            for (i = 0; i < response.data.Errors.length; i += 1)
                            {
                                if (response.data.Errors[i].MinorCode === "10061")
                                {
                                    if (response.data.Errors[i].Message != null)
                                    {
                                        $('#FlightResultsError').hide();
                                    }
                                }
                            }
                        }
                    }
                    if (noResults) {
                        var cboMiles;
                        var cboMiles2;
                        if (_this.currentResults && _this.currentResults.Trips && _this.currentResults.Trips.length > 0) {
                            if (_this.currentResults.Trips[0].OriginTriggeredAirport === true) {
                                cboMiles = "100";
                            } else {
                                cboMiles = "";
                            }
                            if (_this.currentResults.Trips[0].DestinationTriggeredAirport === true) {
                                cboMiles2 = "100";
                            } else {
                                cboMiles2 = "";
                            }
                            if (cboMiles === "" && cboMiles2 === "") {
                                cboMiles = "100";
                                cboMiles2 = "100";
                            }
                        } else {
                            cboMiles = "100";
                            cboMiles2 = "100";
                        }
                        if (this.templates.noFlightFoundMessage) {
                            var noFlightTempData = [];
                            noFlightTempData.isSearchNearBy = isSearchNearBy;
                            noFlightTempData.CboMiles = cboMiles;
                            noFlightTempData.CboMiles2 = cboMiles2;
                            noFlightTempData.titleVariantOne = isSearchNearBy || (this.currentResults.appliedSearch && this.currentResults.appliedSearch.searchTypeMain && this.currentResults.appliedSearch.searchTypeMain.toLowerCase() != "multicity");
                            this.elements.noFlightMesssageSection.html(this.templates.noFlightFoundMessage(noFlightTempData));
                        }

                        if (isSearchNearBy) {
                            $('#pos-notice').css('display', 'none');
                            if ($('#hdnNoFlightSeasionalStation').val() == 'True') {
                                $('#seasionalStationError').show();
                            }
                            else {
                                if (showFsrTips && fsrTipsPhase2 && fsrTipsShowNearbyError) {
                                    _this.showNearbyError({
                                        IsSearchNearBy: isSearchNearBy,
                                        NearbyErrorMsg: nearbySearchErrorMsg,
                                        CboMiles: cboMiles,
                                        CboMiles2: cboMiles2
                                    });

                                } else {
                                    $('#gridNearByError').show();
                                    _this.hideLineLoader();
                                }
                            }
                            $('#FlightResultsError, #fl-notices').hide();
                            setTimeout(function () { $('#fl-notices').attr('aria-live', 'assertive'); }, 0);
                            _this.renderFlightResultsHeader(response.data);
                            $('.fl-farewheel-disclaimer-container').hide();
                            var farewheelresp;
                            var farewheelhasPrice = false;
                            if (_this.currentResults.appliedSearch.Trips.length > 0) {
                                _this.currentResults.appliedSearch.Trips[0].OriginTriggeredAirport = false;
                                _this.currentResults.appliedSearch.Trips[0].DestinationTriggeredAirport = false;
                            }
                            if (!fareWheelRequest) {
                                fareWheelRequest = _this.fetchFareWheel(searchInput);
                            }
                            $.when(fareWheelRequest).done(function (response) {
                                farewheelresp = response;
                            }).then(function () {
                                if (farewheelresp != undefined && farewheelresp != null) {
                                    if (farewheelresp.data != null && farewheelresp.data.FareWheel != null) {
                                        _.forEach(farewheelresp.data.FareWheel.GridRowItems, function (row, i) {
                                            if (row != null && row.PricingItem != null) {
                                                if (row.PricingItem.Amount > 0) {
                                                    return farewheelhasPrice = true;
                                                }
                                            }
                                        });
                                    }
                                }

                                if (farewheelhasPrice) {
                                    _this.buildFareWheel(farewheelresp);
                                    $('.fl-farewheel-disclaimer-container').show();
                                } else {
                                    $(".fl-result-list-header, #fl-results").hide();
                                }
                            });
                        } else {
                            $('#pos-notice').css('display', 'none');
                                $('#FlightResultsError').show();
                            for (i = 0; i < response.data.Errors.length; i += 1)
                            {
                                if (response.data.Errors[i].MinorCode === "10061")
                                {
                                    if (response.data.Errors[i].Message != null)
                                    {
                                        $('#FlightResultsError').hide();
                                    }
                                }
                            }
                            if ($('#hdnNoFlightSeasionalStation').val() == 'True') {
                                $('#seasionalStationError').hide();
                            }
                            else {
                                if (showFsrTips && fsrTipsPhase2 && fsrTipsShowNearbyError) {
                                    var bRemoved = _this.fsrTipsData.removeAll("nearbyError");
                                    if (bRemoved) {
                                        this.drawFsrTips();
                                    }
                                } else {
                                    $('#gridNearByError').hide();
                                }
                            }
                            var hideLineLoader = $('#hideLineLoader').val() === 'True' ? true : false;
                            if (hideLineLoader && (response.data.Trips == null && noSeats)) {
                                _this.hideLineLoader();
                            }
                            _this.renderFlightResultsHeader(response.data);

                            if ($('.fl-new-search-wrap').css('display') !== 'block') {
                                $('.fl-new-search-wrap').show();
                            }

                            $("#fl-search-header-placeholder").addClass("visiblehidden");
                            $('.fare-disclaimer, .btn-hide-new-search, #fl-search-header-placeholder, #fl-results').hide();
                            if (response.data.FareWheel) {
                                _this.renderFareWheel(response.data);
                            }
                        }
                    } else {
                        logErrors(response.errors);
                        displayErrorDialog(response.errors, response.CartId);
                    }
                    if (this.templates.noFlightFoundMessage) {
                        $('#FlightResultsError').hide();
                    }
                } else {
                    if ($('#hdnNoFlightSeasionalStation').val() == 'True') {
                        $('#seasionalStationError').hide();
                    }
                    else {
                        if (showFsrTips && fsrTipsPhase2 && fsrTipsShowNearbyError) {
                            var bRemoved = _this.fsrTipsData.removeAll("nearbyError");
                            if (bRemoved) {
                                this.drawFsrTips();
                            }
                        } else {
                            $('#gridNearByError').hide();
                        }
                    }
                    _this.currentResults.appliedSearch.InitialShop = false;
                    if (_this.currentResults.appliedSearch.Trips.length > _this.getTripIndex() && !response.data.IsAward && _this.currentResults.SearchType.toLowerCase() != "mc") {
                        _this.currentResults.appliedSearch.Trips[_this.getTripIndex()].OriginTriggeredAirport = response.data.Trips[0].OriginTriggeredAirport;
                        _this.currentResults.appliedSearch.Trips[_this.getTripIndex()].DestinationTriggeredAirport = response.data.Trips[0].DestinationTriggeredAirport;
                    }

                    if (response.data.Trips[0].TotalFlightCount > 0) {
                        $("#fl-search-header-placeholder").removeClass("visiblehidden");
                        $('.fare-disclaimer, .btn-hide-new-search, #fl-search-header-placeholder, #fl-results,#fl-notices, .fl-farewheel-disclaimer-container').show();
                        setTimeout(function () { $('#fl-notices').attr('aria-live', 'assertive'); }, 0);
                    }
                    $('#AgencyPNRFlightResultsError').hide();
                }
                if ($('#editFlightSearch').val() === "True") {
                    var searchNbyAirportBtn = $('#searchByNearbyAirport');
                    if (searchNbyAirportBtn.length > 0) {
                        var searchNbyAirportBtnIH = searchNbyAirportBtn.innerHeight();
                        var searchNbyAirportBtnSH = searchNbyAirportBtn[0].scrollHeight;
                        if (searchNbyAirportBtnSH > searchNbyAirportBtnIH) {
                            searchNbyAirportBtn.css('height', '60px');
                            searchNbyAirportBtn.css('margin-right', '5px');
                        }
                    }
                }
            },
            openEditSearchHeightSet: function () {
                var editSearchMarginTop = parseInt($('.materialEditSearchSection').css('margin-top'));
                var editSearchMarginBottom = parseInt($('.materialEditSearchSection').css('margin-top'));
                var cartHeight = $('.cart-container').outerHeight();
                var cartFinalHeight = cartHeight - editSearchMarginBottom - editSearchMarginTop;
                $('.materialEditSearchSection').css('min-height', cartFinalHeight);
            },
            loadFlightResultsWithFareWheelParallelCall: function (searchInput, request) {
                var i, _this = this;

                searchInput = _.omit(searchInput, 'AppliedSearch');
                searchInput = _.omit(searchInput, 'SearchFilters');
                searchInput = _.omit(searchInput, 'PosCountryList');

                this.showPageLoader();
                this.elements.resultsFooter.hide();

                var fareWheelResponse = "";
                var fareWheelRequest = this.fetchFareWheel(searchInput);
                $.when(fareWheelRequest).done(function (response) {
                    fareWheelResponse = response;
                });

                $.when(request).done(function (response) {
                    _this.removeCabinsforSingleColumnDesign(response);
                    _this.buildFlightResults(searchInput, response, fareWheelResponse);
                    //if (_this.showTopFilters || _this.showTopFiltersAward || _this.currentResults.appliedSearch.isReshopPath) {
                    //    $('#filter-search-result').hide();
                    //}
                    _this.displayWarningMessages(response);
                    if ($('#editFlightSearch').val() === "True") {
                        var totalTrips = parseInt($("#hdnTotalTrips").val(), 10),
                            currentTripIndex = parseInt(_this.elements.currentTripIndex.val(), 10);
                        if (currentTripIndex <= totalTrips) {
                            _this.RenderFSRCart(response, currentTripIndex);
                        }
                    }
                })
                    .then(
                    function (response) {
                        _this.removeCabinsforSingleColumnDesign(response);
                        var noResults;
                        var isSearchNearBy;
                        if (response.status !== "success") {
                            if (response.data.Errors != null) {
                                noResults = false;
                                isSearchNearBy = false;
                                for (i = 0; i < response.data.Errors.length; i += 1) {
                                    if ($("#hdnNoFlightSeasionalStation").val() == 'True') {
                                        if ((response.data.Errors[i].MajorCode === "FA" && response.data.Errors[i].MinorCode === "136") ||
                                        (response.data.Errors[i].MajorCode === "FA" && response.data.Errors[i].MinorCode === "137") ||
                                            (response.data.Errors[i].MajorCode === "FA" && response.data.Errors[i].MinorCode === "131")) {
                                            isSearchNearBy = true;
                                            $("#seasionalStationMsg").html(response.data.Errors[i].Message);
                                        }
                                    }
                                    else {
                                        if (response.data.Errors[i].MajorCode === "FA" && response.data.Errors[i].MinorCode === "131") {
                                            isSearchNearBy = true;
                                            if (showFsrTips && fsrTipsShowNearbyError) {
                                                nearbySearchErrorMsg = response.data.Errors[i].Message;
                                            } else {
                                                $("#nearbysearcherrormsg").html(response.data.Errors[i].Message);
                                            }
                                        }
                                    }
                                    if (response.data.Errors[i].MinorCode === "10038") {
                                        if (response.data.Errors[i].Message != null) {
                                            if (_this.currentResults.appliedSearch.awardTravel) {
                                                $('#FlightResultsError')[0].innerHTML = response.data.Errors[i].Message;
                                            }
                                            else if ($('#FlightResultsError').find('li').length > 0 && $('#FlightResultsError').find('li')[0] != null && !isSearchNearBy) {
                                                $('#FlightResultsError').find('li')[0].innerHTML = response.data.Errors[i].Message;
                                            }
                                        }
                                        noResults = true;
                                    }
                                }
                                if (!isSearchNearBy) {
                                    if ($('#hdnNoFlightSeasionalStation').val() == 'True') {
                                        $('#seasionalStationError').hide();
                                    } else {
                                        if (showFsrTips && fsrTipsPhase2 && fsrTipsShowNearbyError) {
                                            var bRemoved = _this.fsrTipsData.removeAll("nearbyError");
                                            if (bRemoved) {
                                                this.drawFsrTips();
                                            }
                                        } else {
                                            $('#gridNearByError').hide();
                                        }
                                    }
                                    $('#FlightResultsError').show();
                                }
                            }
                            if (noResults) {
                                if (isSearchNearBy) {
                                    $('#pos-notice').css('display', 'none');
                                    if ($('#hdnNoFlightSeasionalStation').val() == 'True') {
                                        $('#seasionalStationError').show();
                                    }
                                    else {
                                        if (showFsrTips && fsrTipsPhase2 && fsrTipsShowNearbyError) {
                                            var cboMiles;
                                            var cboMiles2;
                                            if (_this.currentResults && _this.currentResults.Trips && _this.currentResults.Trips.length > 0) {
                                                if (_this.currentResults.Trips[0].OriginTriggeredAirport === true) {
                                                    cboMiles = "100";
                                                } else {
                                                    cboMiles = "";
                                                }
                                                if (_this.currentResults.Trips[0].DestinationTriggeredAirport === true) {
                                                    cboMiles2 = "100";
                                                } else {
                                                    cboMiles2 = "";
                                                }
                                                if (cboMiles === "" && cboMiles2 === "") {
                                                    cboMiles = "100";
                                                    cboMiles2 = "100";
                                                }
                                            } else {
                                                cboMiles = "100";
                                                cboMiles2 = "100";
                                            }
                                            _this.showNearbyError({
                                                IsSearchNearBy: isSearchNearBy,
                                                NearbyErrorMsg: nearbySearchErrorMsg,
                                                CboMiles: cboMiles,
                                                CboMiles2: cboMiles2
                                            });
                                        } else {
                                            $('#gridNearByError').show();
                                            _this.hideLineLoader();
                                        }
                                    }
                                    $('#FlightResultsError, #fl-notices').hide();
                                    _this.renderFlightResultsHeader(response.data);
                                    $('.fl-farewheel-disclaimer-container').hide();
                                    var farewheelresp;
                                    var fareWheelRequest = _this.fetchFareWheel(searchInput);
                                    var farewheelhasPrice = false;
                                    if (_this.currentResults.appliedSearch.Trips.length > 0) {
                                        _this.currentResults.appliedSearch.Trips[0].OriginTriggeredAirport = false;
                                        _this.currentResults.appliedSearch.Trips[0].DestinationTriggeredAirport = false;
                                    }
                                    $.when(fareWheelRequest).done(function (response) {
                                        farewheelresp = response;
                                    }).then(function () {
                                        if (farewheelresp != undefined && farewheelresp != null) {
                                            if (farewheelresp.data != null && farewheelresp.data.FareWheel != null) {
                                                _.forEach(farewheelresp.data.FareWheel.GridRowItems, function (row, i) {
                                                    if (row != null && row.PricingItem != null) {
                                                        if (row.PricingItem.Amount > 0) {
                                                            return farewheelhasPrice = true;
                                                        }
                                                    }
                                                });
                                            }
                                        }

                                        if (farewheelhasPrice) {
                                            //scenario 1B if farewheel has price then render farewheel
                                            _this.buildFareWheel(farewheelresp);
                                            $('.fl-farewheel-disclaimer-container').show();
                                        } else {
                                            $(".fl-result-list-header").hide();
                                        }
                                    });
                                } else {
                                    // WI 161182 - D2 Booking: Change POS: Incorrect  informational message is displayed for "product check fail" scenario on FSR pages.
                                    if (typeof searchredirectto != "undefined" && searchredirectto) {
                                        window.location.href = searchredirectto;
                                        $('#pos-notice').css('display', 'none');
                                    } else {
                                        $('#FlightResultsError').show();
                                        if ($('#hdnNoFlightSeasionalStation').val() == 'True') {
                                            $('#seasionalStationError').hide();
                                        }
                                        else {
                                            if (showFsrTips && fsrTipsPhase2 && fsrTipsShowNearbyError) {
                                                var bRemoved = _this.fsrTipsData.removeAll("nearbyError");
                                                if (bRemoved) {
                                                    this.drawFsrTips();
                                                }
                                            } else {
                                                $('#gridNearByError').hide();
                                            }
                                        }
                                        _this.renderFlightResultsHeader(response.data);
                                        var editFlightSearch = $('#editFlightSearch').val() == 'True' ? true : false;
                                        if (!editFlightSearch) {
                                            if ($('.fl-new-search-wrap').css('display') !== 'block') {
                                                $('.btn-show-new-search').click();
                                            }
                                        }

                                        $("#fl-search-header-placeholder").addClass("visiblehidden");
                                        $('.fare-disclaimer, .btn-hide-new-search, #fl-search-header-placeholder, #fl-results').hide();
                                        if (response.data.FareWheel) {
                                            _this.renderFareWheel(response.data);
                                        }
                                    }
                                }
                            } else {
                                logErrors(response.errors);
                                displayErrorDialog(response.errors, response.CartId);
                            }
                        } else {
                            if ($('#hdnNoFlightSeasionalStation').val() == 'True') {
                                $('#seasionalStationError').hide();
                            }
                            else {
                                if (showFsrTips && fsrTipsPhase2 && fsrTipsShowNearbyError) {
                                    var bRemoved = _this.fsrTipsData.removeAll("nearbyError");
                                    if (bRemoved) {
                                        this.drawFsrTips();
                                    }
                                } else {
                                    $('#gridNearByError').hide();
                                }
                            }
                            _this.currentResults.appliedSearch.InitialShop = false;
                            if (_this.currentResults.appliedSearch.Trips.length > _this.getTripIndex() && !response.data.IsAward && _this.currentResults.SearchType.toLowerCase() != "mc") {
                                _this.currentResults.appliedSearch.Trips[_this.getTripIndex()].OriginTriggeredAirport = response.data.Trips[0].OriginTriggeredAirport;
                                _this.currentResults.appliedSearch.Trips[_this.getTripIndex()].DestinationTriggeredAirport = response.data.Trips[0].DestinationTriggeredAirport;
                            }
                            if (response.data.Trips[0].TotalFlightCount > 0) {
                                $("#fl-search-header-placeholder").removeClass("visiblehidden");
                                $('.fare-disclaimer, .btn-hide-new-search, #fl-search-header-placeholder, #fl-results,#fl-notices, .fl-farewheel-disclaimer-container').show();
                                setTimeout(function () { $('#fl-notices').attr('aria-live', 'assertive'); }, 0);
                            }
                        }
                        return response;
                    },
                    function (response) {

                        return $.Deferred().reject(response);

                    }
                    ).always(function (response) {

                        _this.hidePageLoader();

                        UA.UI.Uniform.init();

                        _this.initStickyElements();
                        //_this.MakeFSRResultsAccessible();
                        _this.renderShopSearchCount(response.data);
                    });
            },
            mergeStopNonStop: function (response) {
                var _this = this;
                var trpIndex = _this.getTripIndex(),
                    addproducts = [],
                    ecdoffer = false,
                    productindex = 0;
                if (_this.currentResults && _this.currentResults.Trips && _this.currentResults.Trips.length > 0 && response.data.Trips && response.data.Trips.length > 0) {
                    _this.currentResults.Messages = _this.mergeMessages(_this.currentResults.Messages, response.data.Messages);
                    _this.mergeFlags(_this.currentResults, response.data);
                    if (_this.currentResults.Trips[0].Columns.length < response.data.Trips[0].Columns.length) {
                        _this.currentResults.SearchFilters.FareFamily = response.data.SearchFilters.FareFamily;

                        if (_this.currentResults.appliedSearch.offerCode != null && $('#PromotionalCabin').val() == "True") { //Bug 829639 fix
                            ecdoffer = true;
                        }
                        _.forEach(response.data.Trips[0].Columns, function (column) {
                            var isproductavaialble = false;
                            var extprodindx = 0;
                            _.forEach(_this.currentResults.Trips[0].Columns, function (rescolumn) {
                                if (ecdoffer) {
                                    if (rescolumn.FareFamily == column.FareFamily && !isproductavaialble) {
                                        isproductavaialble = true;
                                    }
                                }
                                else {
                                    if (rescolumn.FareFamily == column.FareFamily && !isproductavaialble) {
                                        isproductavaialble = true;
                                    }
                                }
                                extprodindx++;
                            });
                            if (!isproductavaialble) {
                                addproducts.push({
                                    index: productindex,
                                    producttype: column.FareFamily, productsubtype: column.ProductSubtype,
                                    farefamily: column.FareFamily
                                });
                            }
                            productindex++;
                        });
                        _.forEach(addproducts, function (prod) {
                            var products = {};
                            _.forEach(_this.currentResults.Trips[0].Flights, function (flight) {
                                products = {
                                    BestMatchSortOrder: flight.Products[0].BestMatchSortOrder,
                                    ProductType: prod.producttype,
                                    ProductSubtype: prod.productsubtype,
                                    FareFamily: prod.farefamily
                                };
                                flight.Products.splice(prod.index, 0, products);
                            });
                        });
                        $.extend(_this.currentResults.Trips[0].Columns, response.data.Trips[0].Columns);
                    } else if (_this.currentResults.Trips[0].Columns.length > response.data.Trips[0].Columns.length) {
                        _.forEach(_this.currentResults.Trips[0].Columns, function (column) {
                            var isproductavaialble = false;
                            var extprodindx = 0;
                            _.forEach(response.data.Trips[0].Columns, function (rescolumn) {
                                if (rescolumn.FareFamily == column.FareFamily && !isproductavaialble) {
                                    isproductavaialble = true;
                                    column.Description = rescolumn.Description;
                                }
                                extprodindx++;
                            });
                            if (!isproductavaialble) {
                                addproducts.push({
                                    index: productindex,
                                    producttype: column.FareFamily, productsubtype: column.ProductSubtype,
                                    farefamily: column.FareFamily
                                });
                            }
                            productindex++;
                        });
                        _.forEach(addproducts, function (prod) {
                            var products = {};
                            _.forEach(response.data.Trips[0].Flights, function (flight) {
                                products = {
                                    BestMatchSortOrder: flight.Products[0].BestMatchSortOrder,
                                    ProductType: prod.producttype,
                                    ProductSubtype: prod.productsubtype,
                                    FareFamily: prod.farefamily
                                };
                                flight.Products.splice(prod.index, 0, products);
                                _.forEach(flight.Connections, function (conn) {
                                    conn.Products.splice(prod.index, 0, products);
                                });
                            });
                        });
                    } else {
                        _.forEach(_this.currentResults.Trips[0].Columns, function (column) {
                            var isproductavaialble = false;
                            _.forEach(response.data.Trips[0].Columns, function (rescolumn) {
                                if (rescolumn.FareFamily == column.FareFamily && !isproductavaialble) {
                                    isproductavaialble = true;
                                    column.Description = rescolumn.Description;
                                }
                            });
                        });
                    }
                    $.merge(_this.currentResults.Trips[0].Flights, response.data.Trips[0].Flights);
                    _this.currentResults.Trips[0].CurrentFlightCount = _this.currentResults.Trips[0].Flights.length;
                    if (response.data.Trips[0].LowestEconomyFare > 0) _this.currentResults.Trips[0].LowestEconomyFare = response.data.Trips[0].LowestEconomyFare;
                    $.merge(_this.currentResults.SearchFilters.AirportsDestinationList, response.data.SearchFilters.AirportsDestinationList);
                    $.merge(_this.currentResults.SearchFilters.AirportsOriginList, response.data.SearchFilters.AirportsOriginList);
                    $.merge(_this.currentResults.SearchFilters.CabinOptions, response.data.SearchFilters.CabinOptions);
                    $.merge(_this.currentResults.SearchFilters.EquipmentList, response.data.SearchFilters.EquipmentList);
                    $.merge(_this.currentResults.SearchFilters.OneStopAirports, response.data.SearchFilters.OneStopAirports);
                    $.merge(_this.currentResults.SearchFilters.TwoPlusStopAirports, response.data.SearchFilters.TwoPlusStopAirports);
                    _this.currentResults.SearchFilters.EquipmentCodes += (',' + response.data.SearchFilters.EquipmentCodes);
                    _this.currentResults.SearchFilters.EquipmentTypes += (',' + response.data.SearchFilters.EquipmentTypes);
                    var oldHideColumnPrices = $.extend({}, _this.currentResults.SearchFilters.HideColumnPrices);
                    _.forEach(_this.currentResults.Trips[0].Columns, function (column) {
                        if (_this.currentResults.SearchFilters.HideColumnPrices[column.FareFamily] && !response.data.SearchFilters.HideColumnPrices[column.FareFamily]) {
                            _this.currentResults.SearchFilters.HideColumnPrices[column.FareFamily] = false;
                        }

                        if (oldHideColumnPrices && oldHideColumnPrices[column.FareFamily] && _this.currentResults.appliedSearch.cabinSelection === column.FareFamily) {
                            if (_this.currentResults.SearchFilters.HideColumnPrices[column.FareFamily] == false && oldHideColumnPrices[column.FareFamily] == true) {
                                _this.currentResults.SearchFilters.FareFamily = column.FareFamily;
                            }
                        }
                    });
                    _.forEach(_this.currentResults.Trips[0].Columns, function (column) {
                        if (_this.currentResults.SearchFilters.MaxPrices[column.FareFamily] < response.data.SearchFilters.MaxPrices[column.FareFamily]) {
                            _this.currentResults.SearchFilters.MaxPrices[column.FareFamily] = response.data.SearchFilters.MaxPrices[column.FareFamily];
                        }
                        if (_this.currentResults.SearchFilters.MinPrices[column.FareFamily] > response.data.SearchFilters.MinPrices[column.FareFamily]) {
                            _this.currentResults.SearchFilters.MinPrices[column.FareFamily] = response.data.SearchFilters.MinPrices[column.FareFamily];
                        }
                    });
                    if (response.data.SearchFilters.PriceMax > _this.currentResults.SearchFilters.PriceMax) {
                        _this.currentResults.SearchFilters.PriceMax = response.data.SearchFilters.PriceMax;
                    }
                    if (response.data.SearchFilters.PriceMin < _this.currentResults.SearchFilters.PriceMin) {
                        _this.currentResults.SearchFilters.PriceMin = response.data.SearchFilters.PriceMin;
                        _this.currentResults.SearchFilters.PriceMinFormatted = response.data.SearchFilters.PriceMinFormatted;
                    }
                    _this.currentResults.SearchFilters.AirportsStop = response.data.SearchFilters.AirportsStop;
                    _this.currentResults.SearchFilters.AirportsStopList = response.data.SearchFilters.AirportsStopList;
                    _this.currentResults.SearchFilters.HideAirportSection = response.data.SearchFilters.HideAirportSection;
                    _this.currentResults.SearchFilters.HideExperienceSection = response.data.SearchFilters.HideExperienceSection;
                    if (!response.data.SearchFilters.HideOneStop) {
                        _this.currentResults.SearchFilters.HideOneStop = response.data.SearchFilters.HideOneStop;
                        _this.currentResults.SearchFilters.OneStopMinPricesByColumn = response.data.SearchFilters.OneStopMinPricesByColumn;
                    }
                    if (!response.data.SearchFilters.HideTwoPlusStop) {
                        _this.currentResults.SearchFilters.HideTwoPlusStop = response.data.SearchFilters.HideTwoPlusStop;
                        _this.currentResults.SearchFilters.TwoPlusMinPricesByColumn = response.data.SearchFilters.TwoPlusMinPricesByColumn;
                    }
                    if (response.data.SearchFilters.SingleCabinExist) _this.currentResults.SearchFilters.SingleCabinExist = response.data.SearchFilters.SingleCabinExist;
                    if (response.data.SearchFilters.MultiCabinExist) _this.currentResults.SearchFilters.MultiCabinExist = response.data.SearchFilters.MultiCabinExist;
                    if (response.data.SearchFilters.TurboPropExist) _this.currentResults.SearchFilters.TurboPropExist = response.data.SearchFilters.TurboPropExist;
                    if (response.data.SearchFilters.CarrierDefault) _this.currentResults.SearchFilters.CarrierDefault = response.data.SearchFilters.CarrierDefault;
                    if (response.data.SearchFilters.CarrierExpress) _this.currentResults.SearchFilters.CarrierExpress = response.data.SearchFilters.CarrierExpress;
                    if (response.data.SearchFilters.CarrierStar) _this.currentResults.SearchFilters.CarrierStar = response.data.SearchFilters.CarrierStar;
                    if (response.data.SearchFilters.DreamLinerExist) _this.currentResults.SearchFilters.DreamLinerExist = response.data.SearchFilters.DreamLinerExist;
                    if (response.data.SearchFilters.CarrierPartners) _this.currentResults.SearchFilters.CarrierPartners = response.data.SearchFilters.CarrierPartners;
                    if (_this.currentResults.SearchFilters.DurationMin > response.data.SearchFilters.DurationMin) _this.currentResults.SearchFilters.DurationMin = response.data.SearchFilters.DurationMin;
                    if (_this.currentResults.SearchFilters.DurationMax < response.data.SearchFilters.DurationMax) _this.currentResults.SearchFilters.DurationMax = response.data.SearchFilters.DurationMax;
                    _this.currentResults.SearchFilters.TimeDepartMaxPreferred = response.data.SearchFilters.TimeDepartMaxPreferred;
                    _this.currentResults.SearchFilters.TimeDepartMinPreferred = response.data.SearchFilters.TimeDepartMinPreferred;
                    _this.currentResults.SearchFilters.TimeArrivalMaxPreferred = response.data.SearchFilters.TimeArrivalMaxPreferred;
                    _this.currentResults.SearchFilters.TimeArrivalMinPreferred = response.data.SearchFilters.TimeArrivalMinPreferred;
                    if (!response.data.SearchFilters.HideLayover) {
                        _this.currentResults.SearchFilters.HideLayover = false;
                        _this.currentResults.SearchFilters.LayoverMax = response.data.SearchFilters.LayoverMax;
                    }
                    $.extend(_this.currentResults.SearchFilters.Warnings, response.data.SearchFilters.Warnings);
                    if (new Date(_this.currentResults.SearchFilters.TimeArrivalMax) < new Date(response.data.SearchFilters.TimeArrivalMax)) _this.currentResults.SearchFilters.TimeArrivalMax = response.data.SearchFilters.TimeArrivalMax;
                    if (new Date(_this.currentResults.SearchFilters.TimeArrivalMin) > new Date(response.data.SearchFilters.TimeArrivalMin)) _this.currentResults.SearchFilters.TimeArrivalMin = response.data.SearchFilters.TimeArrivalMin;
                    if (new Date(_this.currentResults.SearchFilters.TimeDepartMax) < new Date(response.data.SearchFilters.TimeDepartMax)) _this.currentResults.SearchFilters.TimeDepartMax = response.data.SearchFilters.TimeDepartMax;
                    if (new Date(_this.currentResults.SearchFilters.TimeDepartMin) > new Date(response.data.SearchFilters.TimeDepartMin)) _this.currentResults.SearchFilters.TimeDepartMin = response.data.SearchFilters.TimeDepartMin;
                    if (this.currentResults.SearchFilters.StopFormattedAmountAward == null || this.currentResults.SearchFilters.StopFormattedAmountAward === "") {
                        this.currentResults.SearchFilters.StopFormattedAmountAward = response.data.SearchFilters.StopFormattedAmountAward;
                    }
                }
            },
            mergeMessages: function (MessagesList1, MessagesList2) {
                var _this = this;

                _.forEach(MessagesList2, function (Message) {
                    if ((MessagesList1 == null || MessagesList1.length == 0 || (_.findIndex(MessagesList1, { 'Code': Message.Code}) == -1)) && _this.OrTypeCode(Message.Code)) {
                        MessagesList1.push(Message);
                    }
                });

                _.forEach(MessagesList1, function (Message) {
                    if ((MessagesList2 == null || MessagesList2.length == 0 || (_.findIndex(MessagesList2, { 'Code': Message.Code }) == -1)) && _this.AndTypeCode(Message.Code)) {
                        MessagesList1 = MessagesList1.filter(function (msg) { return msg.Code != Message.Code; });
                    }
                });
                return MessagesList1;
            },
            mergeFlags: function (Result1, Result2) {
                Result1.Trips[0].IsPartialFlightCovered = Result1.Trips[0].IsPartialFlightCovered || Result2.Trips[0].IsPartialFlightCovered;
            },
            OrTypeCode: function (code){
                return ["PEBTD", "NEPUAT"].includes(code);
            },
            AndTypeCode: function (code){
                return ["NUEF", "NEPYFU"].includes(code);
            },
            compareFareFamilies: function (fareFamilies1, fareFamilies2) {
                // this function is only written for comparing fareFamilies as additional check for comparing columns while merging non-stop and stop results.
                // according to Esteban from CSL, to compare fareFamilies, first element should be enough as CSL always keep them in same order.
                if (fareFamilies1 && fareFamilies2 && fareFamilies1.length > 0 && fareFamilies2.length > 0) {
                    return fareFamilies1[0] === fareFamilies2[0];
                }
                return true;
            },
            prepareSearchInput: function (searchInput, trpindex) {
                var _this = this;
                var trpindx = trpindex;
                searchInput.Trips[trpindx].StopCount = 1;
                var tripsAllStopsChecked = JSON.parse(UA.Utilities.safeSessionStorage.getItem("tripsAllStopsChecked"));
                if (tripsAllStopsChecked == null) tripsAllStopsChecked = [];
                if (!searchInput.Revise) {
                    var present = tripsAllStopsChecked.filter(function (stops) {
                        return stops.tripindx == trpindx
                    });
                    if (present.length == 0) {
                        tripsAllStopsChecked.push({
                            tripindx: trpindx,
                            nonstop: searchInput.Trips[trpindx].nonStop,
                            onestop: searchInput.Trips[trpindx].oneStop,
                            twoPlusStop: searchInput.Trips[trpindx].twoPlusStop
                        });
                    }
                }
                if (tripsAllStopsChecked != null && tripsAllStopsChecked.length > trpindx) {
                    searchInput.Trips[trpindx].nonStop = tripsAllStopsChecked[trpindx].nonstop;
                    searchInput.Trips[trpindx].oneStop = tripsAllStopsChecked[trpindx].onestop;
                    searchInput.Trips[trpindx].twoPlusStop = tripsAllStopsChecked[trpindx].twoPlusStop;
                }
                UA.Utilities.safeSessionStorage.setItem("tripsAllStopsChecked", JSON.stringify(tripsAllStopsChecked));
                searchInput.HideFarewheel = true;
                return searchInput;
            },
            RenderFSRCart: function (request, currTripIndex) {
                var isUpgradeType = (this.currentResults.appliedSearch.UpgradeType !== null) ? true : false;
                if (currTripIndex === 1 && !isUpgradeType) {
                    $('#fsrcartcontainer').html('');
                    return;
                }
                var serviceUrl = this.elements.container.data('carturl');
                var _this = this,
                    getFSRCartInfo;
                var loaderEl = $('.cart-placeholder');
                //loaderEl.loader();
                getFSRCartInfo = $.ajax({
                    cache: false,
                    url: serviceUrl,
                    type: 'post',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({
                        cartId: $('#CartId').val(),
                        isRevised: request.data.IsRevised,
                        searchType: request.data.SearchType,
                        tripIndex: currTripIndex,
                        hotFix: _this.currentResults.appliedSearch.awardTravel,
                        isAwardTravel: _this.currentResults.appliedSearch.awardTravel,
                        isUpgradeType: isUpgradeType
                    }),
                    traditional: true
                });

                $.when(getFSRCartInfo)
                    .done(function (response) {
                        $('#fsrcartcontainer').html(response);
                        $('.cart-section-prices').hide();
                        $('.cart-section-total').hide();
                        $('.cart-section-remainingseats').hide();
                        //$('.cart-change-trip').text($("#hdnFSRCartChangeText").val());
                        $('#edit-search-modal').html('');
                        $('.cart-container #edit-search').hide();
                        if (loaderEl.data('ua-loader')) {
                            loaderEl.loader('destroy');
                        } else { }
                        if ($('#editFlightSearch').val() === "True") {
                            _this.openEditSearchHeightSet();
                        }
                    })
                    .fail(function (jqXHR, status) {
                        if (loaderEl.data('ua-loader')) {
                            loaderEl.loader('destroy');
                        }
                    });
            },
            prioritizeMessages: function (messages) {
                var result = {
                    messages: [],
                };
                if (messages && messages.length > 0) {
                    var messagePriorityList = ["NUEF", "PEBTD", "NEPYFU", "NEPUAT"];
                    result.messages = _.filter(messages, function (msg) {
                        return !_.find(messagePriorityList, function (item) { return item == msg.Code; });
                    }) || [];
                    _.forEach(messagePriorityList, function (code) {
                        var message = _.find(messages, function (msg) { return msg.Code == code; });
                        if (message) {
                            result.messages.push(message)
                            return false;
                        }
                    });
                }
                return result;
            },
            buildFlightResults: function (searchInput, response, fareWheelResponse, fareWheelRequest) {
                var i, selectedTrip, flight, desc, selectedcellid, select, request, _this = this,
                    pageredisplay = {},
                    selectedObj = {},
                    trpIndex = _this.getTripIndex();
                //this.recommendedFlights = [];
                _this.currentResults.SearchFilters = _.omit(_this.currentResults.SearchFilters, 'TimeDepartMaxPreferred');
                _this.currentResults.SearchFilters = _.omit(_this.currentResults.SearchFilters, 'TimeDepartMinPreferred');
                var stopnonstopfeature = ($('#StopNonStop').val() == "True" ? true : false) && !($('#hdnAward').val() == "True" ? true : false);

                if (stopnonstopfeature && searchInput != null && searchInput.Trips && searchInput.Trips.length > trpIndex && searchInput.Trips[trpIndex].StopCount == 2 && searchInput.Trips[trpIndex].HasNonStopFlights) {
                    _this.currentResults.CartId = response.data.CartId;
                    _this.mergeStopNonStop(response);
                } else {
                    $.extend(_this.currentResults, response.data);
                    //_this.currentResults.appliedSearch = response.data;
                }               
                _this.addHasConfPPRUpgrade(_this.currentResults);
                if (_this.currentResults.appliedSearch.IsAwardCalendarEnabled) {
                    _this.currentResults.appliedSearch.cabinSelection = (_this.currentResults.appliedSearch.cabinSelection !== null && (_this.currentResults.appliedSearch.cabinSelection.toLowerCase() == "business" || _this.currentResults.appliedSearch.cabinSelection.toLowerCase() == "first")) ? "businessfirst" : _this.currentResults.appliedSearch.cabinSelection;

                    var isAwardCalendarNonstop = false;
                    if (_this.currentResults.Calendar !== null) {
                        isAwardCalendarNonstop = _this.currentResults.Calendar.NonStopOnly;
                    } else {
                        if (_this.currentResults.SearchFilters) {
                            if (_this.currentResults.NonStopOnly) {
                                if (!_this.currentResults.SearchFilters.HideNoneStop) {
                                    isAwardCalendarNonstop = true;
                                } else {
                                    if (!_this.currentResults.SearchFilters.HideOneStop || !_this.currentResults.SearchFilters.HideTwoPlusStop) {
                                        isAwardCalendarNonstop = true;
                                    }
                                }
                            } else {
                                var currentTripIndex = _this.currentResults.Trips[0].Index - 1;
                                if (currentTripIndex >= 0) {
                                    if (!_this.currentResults.SearchFilters.HideNoneStop) {
                                        if (_this.currentResults.SearchFilters.HideOneStop && _this.currentResults.SearchFilters.HideTwoPlusStop) {
                                            if (_this.currentResults.appliedSearch && _this.currentResults.appliedSearch.Trips) {
                                                if (_this.currentResults.appliedSearch.Trips[currentTripIndex].nonStop) {
                                                    isAwardCalendarNonstop = true;
                                                } else if (!_this.currentResults.appliedSearch.Trips[currentTripIndex].oneStop && !_this.currentResults.appliedSearch.Trips[currentTripIndex].twoPlusStop) {
                                                    isAwardCalendarNonstop = true;
                                                }
                                            }
                                        } else if (_this.currentResults.SearchFilters.HideOneStop) {
                                            if (_this.currentResults.appliedSearch.Trips[currentTripIndex].nonStop && !_this.currentResults.appliedSearch.Trips[currentTripIndex].twoPlusStop) {
                                                isAwardCalendarNonstop = true;
                                            }
                                        } else if (_this.currentResults.SearchFilters.HideTwoPlusStop) {
                                            if (_this.currentResults.appliedSearch.Trips[currentTripIndex].nonStop && !_this.currentResults.appliedSearch.Trips[currentTripIndex].oneStop) {
                                                isAwardCalendarNonstop = true;
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            isAwardCalendarNonstop = _this.currentResults.NonStopOnly;
                        }
                    }

                    _this.currentResults.appliedSearch.IsAwardCalendarNonstop = isAwardCalendarNonstop;
                    _this.currentResults.appliedSearch.isChangeWeek = false;
                }
                if (_this.currentResults.appliedSearch.IsAwardCalendarEnabled && _this.currentResults.appliedSearch.awardTravel && !_this.currentResults.appliedSearch.flexibleAward && response.data.SelectedTrips && response.data.SelectedTrips.length > 0) {
                    for (var i = 0; i < response.data.SelectedTrips.length; i++) {
                        var tripidx = response.data.SelectedTrips[i].Index - 1;
                        _this.currentResults.appliedSearch.Trips[tripidx].BBXSession = response.data.SelectedTrips[i].BBXSession;
                        _this.currentResults.appliedSearch.Trips[tripidx].BBXSolutionSetId = response.data.SelectedTrips[i].SolutionSetId;
                        _this.currentResults.appliedSearch.Trips[tripidx].BBXCellIdSelected = response.data.SelectedTrips[i].CellIdSelected;
                        _this.currentResults.appliedSearch.Trips[tripidx].SelectedFlights = response.data.SelectedTrips[i].Flights;
                        if (_this.currentResults.appliedSearch.isReshopPath) { _this.currentResults.appliedSearch.OriginalReservation = response.data.OriginalReservation; }
                    }
                }
                $('#CartId').val(_this.currentResults.CartId);

                if ((_this.currentResults && _this.currentResults.Trips && _this.currentResults.Trips.length > 0)) {

                    if (_this.currentResults.appliedSearch.isReshopPath && _this.currentResults.appliedSearch.awardTravel) {
                        var currentTripIndex = _this.currentResults.Trips[0].Index;
                        var availableMiles = _this.currentResults.appliedSearch.AccountBalance;
                        if (currentTripIndex > 0) {
                            if (!_this.currentResults.appliedSearch.OriginalMilesTripWise)
                                _this.currentResults.appliedSearch.OriginalMilesTripWise = [];
                            if (_this.currentResults.Trips[0].OriginalMileage) {
                                var NoofTravelers = 0;
                                if (_this.currentResults.NoOfTravelers)
                                    NoofTravelers = _this.currentResults.NoOfTravelers;
                                if (NoofTravelers > 0)
                                    availableMiles = availableMiles + (parseInt(_this.currentResults.Trips[0].OriginalMileage) * NoofTravelers);
                                else
                                    availableMiles = availableMiles + (parseInt(_this.currentResults.Trips[0].OriginalMileage));
                            }
                            _this.currentResults.appliedSearch.OriginalMilesTripWise[currentTripIndex - 1] = _this.currentResults.Trips[0].OriginalMileageTotal;
                            if (availableMiles) {
                                _this.currentResults.appliedSearch.AvailableMileageBalance = availableMiles;
                                $('#Available-MileageBalance').text(availableMiles);
                            } else
                                _this.currentResults.appliedSearch.AvailableMileageBalance = 0;
                        }
                    }
                    _this.currentResults.appliedSearch.CartId = _this.currentResults.CartId;
                    $('#hdnBBXId').val(_this.currentResults.LastResultId);
                    $('#change-language-pos').data("cartid", _this.currentResults.CartId);
                    $('#SolutionSetId').val(_this.currentResults.Trips[0].SolutionSetId);

                    if (_this.currentResults.Trips) {
                        pageredisplay = {
                            CartId: _this.currentResults.CartId,
                            SolutionSetId: _this.currentResults.Trips[0].SolutionSetId,
                            CellIdSelected: _this.currentResults.Trips[0].CellIdSelected
                        };
                    }

                    $('#aHeaderSignIn').data("page-redisplay", pageredisplay);

                    _this.elements.currentTripIndex.val(_this.currentResults.Trips[0].Index);

                }

                if (_this.elements.calendarContainer !== null && _this.currentResults.Calendar !== null && (!searchInput.HideFarewheel || searchInput.HideFarewheel === null)) {
                    if (_this.currentResults.appliedSearch.flexible) {
                        _this.renderFareCalendar();
                        setTimeout(function () {
                            window.setTimeout(function () {
                                $('.logo').focusWithoutScrolling();
                            }, 1);
                            window.setTimeout(function () {
                                $('.head-adjunct').focusWithoutScrolling();
                            }, 100);
                            window.setTimeout(function () {
                                $('#main-content').focusWithoutScrolling();
                            }, 300);
                            window.setTimeout(function () {
                                $('footer').focusWithoutScrolling();
                            }, 400);
                            window.setTimeout(function () {
                                $('.logo').focusWithoutScrolling();
                            }, 500);
                        }, 1000);
                    } else {
                        $('#fl-calendar-wrap').removeClass('flexible-calendar');
                        if (_this.currentResults.appliedSearch.IsPromo || _this.currentResults.appliedSearch.flexibleAward || !_this.currentResults.appliedSearch.IsAwardCalendarEnabled) {
                            _this.renderAvailabilityCalendar();
                        }
                        if (_this.currentResults.Trips[0].Index == 1) {
                            _this.renderEditSearchOnly();
                        }
                    }
                } else {
                    $('#fl-calendar-wrap').removeClass('flexible-calendar');
                }

                //render page level notices
                if (_this.currentResults.appliedSearch.UpgradeType != null && _this.currentResults.appliedSearch.UpgradeType.toUpperCase() == "POINTS")
                {
                    $('#fl-notices2').html(_this.templates.messageV3(_this.currentResults));
                }
                else
                {
                    $('#fl-notices2').html(_this.templates.message(_this.currentResults));
                }
                $('#fl-notices2 .notification-block p').addClass('noticeFSR');
                //CSI-7654 - Accessibility 2.0: FSR - screenreader does NOT announce the Learn more link correctly when using the NVDA Keys
                if ($('div.notification-block p a')) {
                    if (!$('div.notification-block p').find('.anchorseperator').length) {
                        $('div.notification-block p a').before('<span class="visuallyhidden anchorseperator" style="overflow: visible;"></span>');
                    }
                }
                if (showFsrTips && fsrTipsPhase2) {
                    if (fsrTipsShowNearby) {
                        if (_this.currentResults.Trips && _this.currentResults.Trips[0]) {
                            if (_this.currentResults.Trips[0].OriginTriggeredAirport === true &&
                                _this.currentResults.Trips[0].DestinationTriggeredAirport === true) {
                                _this.showNearby({
                                    IsSearchNearBy: true,
                                    Both: true,
                                    AirportCode: _this.currentResults.Trips[0].Origin,
                                    AirportCity: _this.currentResults.Trips[0].OriginDecoded,
                                    AirportCode2: _this.currentResults.Trips[0].Destination,
                                    AirportCity2: _this.currentResults.Trips[0].DestinationDecoded,
                                    CboMiles: "100",
                                    CboMiles2: "100"
                                });
                            } else if (_this.currentResults.Trips[0].OriginTriggeredAirport === true) {
                                _this.showNearby({
                                    IsSearchNearBy: true,
                                    Both: false,
                                    AirportCode: _this.currentResults.Trips[0].Origin,
                                    AirportCity: _this.currentResults.Trips[0].OriginDecoded,
                                    AirportCode2: null,
                                    AirportCity2: null,
                                    CboMiles: "100",
                                    CboMiles2: ""
                                });
                            } else if (_this.currentResults.Trips[0].DestinationTriggeredAirport === true) {
                                _this.showNearby({
                                    IsSearchNearBy: true,
                                    Both: false,
                                    AirportCode: _this.currentResults.Trips[0].Destination,
                                    AirportCity: _this.currentResults.Trips[0].DestinationDecoded,
                                    AirportCode2: null,
                                    AirportCity2: null,
                                    CboMiles: "",
                                    CboMiles2: "100"
                                });
                            }
                        }
                    } else if (fsrTipsShowNearbyCities) {
                        if (_this.currentResults.Trips && _this.currentResults.Trips[0]) {
                            if (_this.currentResults.Trips[0].DestinationTriggeredAirport === true) {
                                _this.showNearbyCities(searchInput);
                            }
                        }
                    }
                }
                if ($('#editFlightSearch').val() == 'True' && _this.currentResults.appliedSearch.flexible) {
                    this.initAirportName();
                    var tripDepartdate = UA.Utilities.formatting.tryParseDate(this.currentResults.appliedSearch.flexMonth);
                    if (tripDepartdate == null) {
                        tripDepartdate = new Date(_this.currentResults.appliedSearch.DepartDate);
                        $("input[name='FlexMonth2']").val(formatDateNoWeekDay(tripDepartdate));
                    }
                    $('#DepartDate').val(formatDateNoWeekDay(tripDepartdate));
                    if (_this.currentResults.appliedSearch.searchTypeMain.toLowerCase() == 'roundtrip') {
                        tripDepartdate.setDate(tripDepartdate.getDate() + parseInt(_this.currentResults.appliedSearch.tripLength));
                        $('#ReturnDateForEditSearch').val(formatDateNoWeekDay(tripDepartdate));
                    }

                }
                if (_this.currentResults.Trips !== null && _this.currentResults.Trips.length > 0 && _this.currentResults.Trips[0].Flights !== null && _this.currentResults.Trips[0].Flights.length > 0 && _this.elements.resultsContainer !== null) {

                    if (_this.currentResults.Trips[0].LowestEconomyFare > 0 && !($('#hdnAward').val() == "True" ? true : false)) {
                        _.forEach(_this.currentResults.Trips[0].Flights, function (flight, i) {
                            _.forEach(flight.Products, function (prod, i) {
                                if ((prod.ProductType === "ECONOMY" || prod.ProductType === "ECONOMY-FLEXIBLE") && (prod.ProductSubtype === "BASE" || prod.ProductSubtype === "CORPDISC")) {
                                    if (prod.Prices != null && prod.Prices.length > 0 && prod.Prices[0].Amount == _this.currentResults.Trips[0].LowestEconomyFare) {
                                        prod.isLowestFare = true;
                                    } else {
                                        prod.isLowestFare = false;
                                    }
                                }
                            });
                        });
                    }
                    //render header
                    if ($('#showTopFilters').val() == "False" || $('#showTopFiltersAward').val() == "False") {
                        _this.renderFlightResultsHeader();
                    }

                    //render fare wheel
                    if (response.data.FareWheel && this.lineLoaderState != "loading") {
                        _this.renderFareWheel();
                    }

                    //render selected flights
                    if (_this.currentResults.SelectedTrips !== null && _this.currentResults.SelectedTrips.length > 0) {

                        for (i = $('.fl-selected-segment-wrap .segments').length; i < _this.currentResults.SelectedTrips.length; i += 1) {
                            if (_this.selectedFlights[i] == null) {
                                selectedTrip = _this.currentResults.SelectedTrips[i];
                                flight = selectedTrip.Flights[0];
                                if (flight.Products != null) {
                                    desc = flight.Products.length > 0 ? flight.Products[0].ColumnDesc : '';
                                    if (flight.Products.length > 0) {
                                        _.forEach(flight.Products, function (product, i) {
                                            if (flight.Products[i].ProductId != null) {
                                                selectedcellid = flight.Products[i].ProductId;
                                            }
                                        });
                                    }
                                }
                                select = {
                                    CartId: _this.currentResults.CartId,
                                    CellIdSelected: selectedcellid,
                                    SolutionSetId: flight.SolutionSetId
                                };

                                selectedObj = {
                                    Flights: [selectedTrip.Flights[0]],
                                    FareDescription: desc,
                                    TripIndex: selectedTrip.Index,
                                    SearchType: _this.currentResults.SearchType,
                                    Origin: selectedTrip.OriginDecoded,
                                    Destination: selectedTrip.DestinationDecoded,
                                    DepartDate: selectedTrip.DepartDateFormat,
                                    DepartDateShort: selectedTrip.DepartDateShort,
                                    SelectedFlightIndex: i,
                                    IsSelectedFlight: true,
                                    appliedSearch: _this.currentResults.appliedSearch,
                                    PreviousCellIdSelected: '',
                                    PreviousSolutionSetId: ''
                                };

                                if (i > 0) {
                                    selectedObj.PreviousCellIdSelected = _this.currentResults.SelectedTrips[_this.currentResults.SelectedTrips.length - 1].Flights[0].Products != null ?
                                        _this.currentResults.SelectedTrips[_this.currentResults.SelectedTrips.length - 1].Flights[0].Products[0].ProductId : '';
                                    selectedObj.PreviousSolutionSetId = _this.currentResults.SelectedTrips[_this.currentResults.SelectedTrips.length - 1].Flights[0].SolutionSetId;
                                }

                                _this.selectedFlights[i] = $.extend({}, selectedObj, select);
                                _this.renderSelectedFlight(i);
                            }
                        }
                    }

                    var savedRealFareFamily;
                    if (UA.Booking.FlightSearch.currentResults.appliedSearch.SearchFilters != undefined) {
                        savedRealFareFamily = _this.currentResults.appliedSearch.SearchFilters.RealFareFamily;
                    }
                    _this.currentResults.appliedSearch.SearchFilters = {};
                    if (savedRealFareFamily != undefined) {
                        _this.currentResults.appliedSearch.SearchFilters.SortFareFamily = savedRealFareFamily;
                    }
                    if (trpIndex > 0) {
                        //_this.currentResults.appliedSearch.SortType = _this.currentResults.SortType;
                        _this.currentResults.appliedSearch.SearchFilters.PriceMin = null;
                        _this.currentResults.appliedSearch.SearchFilters.PriceMax = null;
                    }

                    _this.currentResults.appliedSearch.SearchFilters.FilterApplied = false;

                    if (_this.currentResults.UseClearAllFilters === true) {
                        _this.clearAllFiltersAction = FILTERS_ACTION_USED;
                        if (_this.currentResults.GuiFiltersApplied === true) {
                            _this.clearAllFiltersAction |= FILTERS_ACTION_GUI_APPLIED;
                            _this.clearAllFiltersAction |= FILTERS_ACTION_CLEAR_CLICK;
                        }
                    } else {
                        _this.clearAllFiltersAction = FILTERS_ACTION_NONE;
                    }

                    _this.currentResults.SearchFilters.AircraftList = [];
                    if (_this.currentResults.SearchFilters.SingleCabinExist) {
                        _this.currentResults.SearchFilters.AircraftList.push('SingleCabinExist');
                    }
                    if (_this.currentResults.SearchFilters.MultiCabinExist) {
                        _this.currentResults.SearchFilters.AircraftList.push('MultiCabinExist');
                    }
                    if (_this.currentResults.SearchFilters.TurboPropExist) {
                        _this.currentResults.SearchFilters.AircraftList.push('TurboPropExist');
                    }

                    _this.currentResults.SearchFilters.CarriersPreference = [];
                    if (_this.currentResults.SearchFilters.CarrierDefault) {
                        _this.currentResults.SearchFilters.CarriersPreference.push('CarrierDefault');
                    }
                    if (_this.currentResults.SearchFilters.CarrierExpress) {
                        _this.currentResults.SearchFilters.CarriersPreference.push('CarrierExpress');
                    }
                    if (_this.currentResults.SearchFilters.CarrierStar) {
                        _this.currentResults.SearchFilters.CarriersPreference.push('CarrierStar');
                    }
                    if (_this.currentResults.SearchFilters.CarrierPartners) {
                        _this.currentResults.SearchFilters.CarriersPreference.push('CarrierPartners');
                    }

                    _this.currentResults.appliedSearch.SearchFilters.AirportsStop = "";
                    var hidden = [];
                    if (_this.currentResults.SearchFilters.AirportsStopList && _this.currentResults.SearchFilters.AirportsStopList.length > 0) {
                        var stops = [];
                        var activeStops = _.where(_this.currentResults.SearchFilters.AirportsStopList, {
                            'Active': true
                        });
                        stops = _.map(activeStops, function (s) {
                            return s.Code;
                        });

                        if (stops.length > 0) {
                            _this.currentResults.appliedSearch.SearchFilters.AirportsStop = stops.join();
                        }
                    }
                    if (_this.currentResults.SearchFilters.AirportsDestinationList && _this.currentResults.SearchFilters.AirportsDestinationList.length > 0) {
                        var destinationCodes = [];
                        var activeDestination = _.where(_this.currentResults.SearchFilters.AirportsDestinationList, {
                            'Active': true
                        });
                        destinationCodes = _.map(activeDestination, function (s) {
                            return s.Code;
                        });

                        if (destinationCodes.length > 0) {
                            _this.currentResults.appliedSearch.SearchFilters.AirportsDestination = destinationCodes.join();
                        }
                    }
                    if (_this.currentResults.SearchFilters.AirportsOriginList && _this.currentResults.SearchFilters.AirportsOriginList.length > 0) {
                        var departCodes = [];
                        var activeOrigin = _.where(_this.currentResults.SearchFilters.AirportsOriginList, {
                            'Active': true
                        });
                        departCodes = _.map(activeOrigin, function (s) {
                            return s.Code;
                        });

                        if (departCodes.length > 0) {
                            _this.currentResults.appliedSearch.SearchFilters.AirportsOrigin = departCodes.join();
                        }
                    }

                    var columns = _.map(_this.currentResults.Trips[0].Columns, function (column) {
                        return column.FareFamily;
                    });
                    var currentSelection = _this.currentResults.SearchFilters.FareFamily;
                    if ((currentSelection === "FIRST" || currentSelection === "businessFirst") && $.inArray("BUSINESS", columns) > -1) {
                        currentSelection = "BUSINESS";
                    }
                    if (!currentSelection) {
                        currentSelection = columns[0];
                    }
                    if (_this.currentResults.SearchFilters.HideColumnPrices[currentSelection]) {
                        var availCol = _.filter(_this.currentResults.Trips[0].Columns, function (column) {
                            return column.ProductType != currentSelection && !_this.currentResults.SearchFilters.HideColumnPrices[column.ProductType];
                        });
                        if (availCol && availCol.length > 0) {
                            _this.currentResults.SearchFilters.FareFamily = availCol[0].ProductType;
                            columns = _.map(availCol, function (column) {
                                return column.ProductType;
                            });
                        } else {
                            columns = _.toArray(columns).slice(0, 1);
                        }
                        currentSelection = columns[0];
                    }
                    var filterFamilies = _.filter(_this.currentResults.SearchFilters.FareFamilyFilters, function (fareFamily) {
                        return _.contains(columns, fareFamily.FareFamily) && !_this.currentResults.SearchFilters.HideColumnPrices[fareFamily.FareFamily];
                    });
                    if (!_this.currentResults.SearchFilters.MinPrices[currentSelection]) {
                        for (var i = 0; i < _this.currentResults.Trips[0].Columns.length; i++) {
                            if (String(currentSelection).trim().toLowerCase() == String(_this.currentResults.Trips[0].Columns[i].ColumnName).trim().toLowerCase()) {
                                currentSelection = _this.currentResults.Trips[0].Columns[i].ProductType;
                                break;
                            }
                        }
                        if (!_this.currentResults.SearchFilters.MinPrices[currentSelection]) {
                            //currentSelection = columns[0];
                            var cols = $.grep(columns, function (c) {
                                return c == currentSelection;
                            });
                            currentSelection = cols.length > 0 ? cols[0] : columns[0];
                        }
                    }

                    _this.currentResults.SearchFilters.FareFamily = currentSelection;
                    _this.currentResults.SearchFilters.FareFamilyFilters = [];

                    var isSelected;
                    if (currentSelection === "ECONOMY-PROMOTION") {
                        isSelected = 0;
                    } else {
                        isSelected = _this.currentResults.Trips[0].Columns.filter(function (p) {
                            return p.ProductType == "ECO-BASIC";
                        }).length;
                    }
                    _.forEach(_this.currentResults.Trips[0].Columns, function (column) {

                        column.Selected = ((isSelected == 0 && column.ProductType === _this.currentResults.SearchFilters.FareFamily) ||
                            (isSelected > 0 && column.ProductType === "ECO-BASIC"));

                        if (_this.currentResults.SearchFilters.HideColumnPrices[column.ProductType]) {
                            column.IsProductsAvailable = false;
                        } else {
                            column.IsProductsAvailable = true;
                            _this.currentResults.SearchFilters.FareFamilyFilters.push({
                                ProductType: column.ProductType,
                                FareFamily: column.FareFamily
                            });
                        }
                    });
                    
                    if (_this.currentResults.SearchFilters.MinPrices) {
                        _this.currentResults.appliedSearch.SearchFilters.PriceMin = _this.currentResults.SearchFilters.MinPrices[currentSelection];
                    }
                    if (_this.currentResults.SearchFilters.MaxPrices) {
                        _this.currentResults.appliedSearch.SearchFilters.PriceMax = _this.currentResults.SearchFilters.MaxPrices[currentSelection];
                    }
                    _this.currentResults.appliedSearch.SearchFilters.TimeDepartMax = _this.currentResults.SearchFilters.TimeDepartMax;
                    if (_this.currentResults.SearchFilters.TimeDepartMaxPreferred) {
                        _this.currentResults.appliedSearch.SearchFilters.TimeDepartMax = _this.currentResults.SearchFilters.TimeDepartMaxPreferred;
                    }
                    _this.currentResults.appliedSearch.SearchFilters.TimeDepartMin = _this.currentResults.SearchFilters.TimeDepartMin;
                    if (_this.currentResults.SearchFilters.TimeDepartMinPreferred) {
                        _this.currentResults.appliedSearch.SearchFilters.TimeDepartMin = _this.currentResults.SearchFilters.TimeDepartMinPreferred;
                    }
                    _this.currentResults.appliedSearch.SearchFilters.TimeArrivalMax = _this.currentResults.SearchFilters.TimeArrivalMax;
                    if (_this.currentResults.SearchFilters.TimeArrivalMaxPreferred) {
                        _this.currentResults.appliedSearch.SearchFilters.TimeArrivalMax = _this.currentResults.SearchFilters.TimeArrivalMaxPreferred;
                    }
                    _this.currentResults.appliedSearch.SearchFilters.TimeArrivalMin = _this.currentResults.SearchFilters.TimeArrivalMin;
                    if (_this.currentResults.SearchFilters.TimeArrivalMinPreferred) {
                        _this.currentResults.appliedSearch.SearchFilters.TimeArrivalMin = _this.currentResults.SearchFilters.TimeArrivalMinPreferred;
                    }
                    _this.currentResults.appliedSearch.SearchFilters.Warnings = _this.currentResults.SearchFilters.Warnings;
                    _this.currentResults.appliedSearch.SearchFilters.AircraftList = _this.currentResults.SearchFilters.AircraftList;
                    _this.currentResults.appliedSearch.SearchFilters.CarriersPreference = _this.currentResults.SearchFilters.CarriersPreference;
                    if (_this.currentResults.SearchFilters.CarrierPreferred) {
                        _this.currentResults.appliedSearch.SearchFilters.CarriersPreference = _this.currentResults.SearchFilters.CarrierPreferred;
                    }

                    _this.currentResults.Trips[0].TotalFlightCount = _this.currentResults.Trips[0].Flights.length;

                    //apply filter setting from AFS ex: non stop, one stop, two plus stops. 
                    _this.setFilterFromTrip(_this.currentResults.appliedSearch.SearchFilters, trpIndex + 1, _this.currentResults.SearchFilters);

                    if (_this.currentResults.SearchFilters.IsUnaccompaniedMinor) {
                        var trip = _this.currentResults.appliedSearch.Trips[trpIndex];
                        trip.nonStop = true;
                        trip.oneStop = false;
                        trip.twoPlusStop = false;
                        _this.setFilterFromTrip(_this.currentResults.appliedSearch.SearchFilters, trpIndex + 1);
                    }
                    //282751 apply filter setting from non stop, one stop, two plus stops.

                    //bug-712887 - EQA : Prod - 1 Stop flights are not displayed in FSR page when 'Nonstop' checkbox unchecked in AFS page
                    _this.currentResults.SearchFilters.StopCountMin = _this.currentResults.appliedSearch.SearchFilters.StopCountMin;
                    _this.currentResults.SearchFilters.StopCountMax = _this.currentResults.appliedSearch.SearchFilters.StopCountMax;

                    _this.loadSearchFilterResults(_this.currentResults.appliedSearch.SearchFilters, _this.currentResults.appliedSearch.SearchFilters); //CSI1226-Priya
                    _this.setRenderHold(true);

                    if (_this.currentResults.SearchFilters.StopCountMin > 0 && _this.currentResults.appliedSearch.nonStopOnly) {
                        _this.currentResults.appliedSearch.SearchFilters.AirportsStop = _this.currentResults.SearchFilters.AirportsStop;
                    }
                    if (_this.clearAllFiltersAction !== FILTERS_ACTION_NONE &&
                        (_this.clearAllFiltersAction & (FILTERS_ACTION_USED | FILTERS_ACTION_GUI_APPLIED)) !== (FILTERS_ACTION_USED | FILTERS_ACTION_GUI_APPLIED)) {

                        var data1 = {};
                        $.extend(true, data1, _this.currentResults);
                        if (data1 != null) {
                            if (_this.currentResults != null) {
                                data1.SearchType = _this.currentResults.SearchType;
                                if (data1.SearchType == null || data1.SearchType === "") {
                                    if (_this.currentResults.appliedSearch != null) {
                                        data1.SearchType = _this.currentResults.appliedSearch.searchTypeMain;
                                    }
                                }
                            }

                            if (data1.SearchType === "rt") {
                                data1.SearchType = "roundTrip";
                            } else if (data1.SearchType === "mc") {
                                data1.SearchType = "multiCity";
                            } else if (data1.SearchType === "ow") {
                                data1.SearchType = "oneWay";
                            }
                        }

                        if (data1.Trips && data1.Trips.length > 0 && data1.Trips[0].Flights.length > 0) {
                            data1.SearchFilters.HideExperienceSection = false;
                        }
                        _this.elements.filterSortContainer.html(_this.templates.searchFilters(data1));

                        _this.resetFilterFields(true);
                    }
                    if ($('#hdnAward').val() === "True" && $('#hdnNGRP').val() === "True") {
                        if (_this.showTopFiltersAward === true) {
                            _this.loadFilterResults(_this.currentResults.appliedSearch, true);
                        } else {
                            _this.loadFilterResults(_this.currentResults.appliedSearch, true, false);
                        }
                    } else {
                        _this.loadFilterResults(_this.currentResults.appliedSearch, true);
                    }
                    setTimeout(function () {
                        if (!searchInput.HideFarewheel || searchInput.HideFarewheel === null) {
                            if (!searchInput.IsParallelFareWheelCallEnabled || (searchInput.CellIdSelected != null && searchInput.CellIdSelected != '')) {
                                var fareWheelInput = searchInput;
                                if (searchInput.CartId != _this.currentResults.appliedSearch.CartId) {
                                    fareWheelInput = $.extend(true, {}, searchInput);
                                    fareWheelInput.CartId = _this.currentResults.appliedSearch.CartId;
                                }
                                if (fareWheelRequest) {
                                    $.when(fareWheelRequest).done(function (fareWheelResponse) {
                                        _this.buildFareWheel(fareWheelResponse);
                                    });
                                } else {
                                    _this.loadFareWheel(fareWheelInput);
                                }

                            } else {
                                if (_this.currentResults.ShowFareWheel &&
                                    fareWheelResponse && fareWheelResponse != null &&
                                    fareWheelResponse.data != null && fareWheelResponse.data.FareWheel) {
                                    _this.buildFareWheel(fareWheelResponse);
                                }
                            }
                        }
                    }, 100);
                    setTimeout(function () {
                        _this.loadFlightAmenities();
                    }, 200);
                    setTimeout(function () {
                        _this.loadFlightAux();
                    }, 400);

                    if (searchInput.awardTravel &&
                        ($("#hdnLowestRevenueBannerOption1").val() === "True" || $("#hdnLowestRevenueBannerOption2").val() === "True") &&
                        (searchInput.CellIdSelected == null || searchInput.CellIdSelected == "")) {

                        setTimeout(function () {
                            if ($("#hdnLowestRevenueBannerOption1").val() === "False")
                            {
                                $('#dvLowestRevenueOption1').empty()
                            }

                            //Get fare wheel - lowest revenue request
                            var lowestRevenueRequest = _this.getLowestRevenueFare(searchInput);
                            $.when(lowestRevenueRequest).done(function (lowestRevenueResponse) {
                                _this.currentResults.lowestRevenueResponse = lowestRevenueResponse;
                                _this.lowestRevenueTemplateBind(lowestRevenueResponse);
                            }).fail(function () {
                                    $('#lowest-revenue-banner-placeholder').html("");
                             });
                        }, 50);
                    }

                    if (_this.currentResults.appliedSearch.IsAwardCalendarEnabled && _this.currentResults.appliedSearch.awardTravel && !_this.currentResults.appliedSearch.flexibleAward) {
                        if (_this.currentResults.appliedSearch.SkipAwardCalendar !== true) {
                            setTimeout(function () {
                                _this.loadAwardCalendar(_this.currentResults.appliedSearch);
                            }, 200);
                        } else {
                            _this.currentResults.appliedSearch.IsAwardCalendarNonstop = _this.oldIsAwardCalendarNonstop;
                    }
                    }

                    $('#FlightResultsError').hide();
                        //Defect #109064

                    if (UA.Utilities.formatting.parseDate("yy-m-d", _this.currentResults.Trips[0].DepartDate) <= new Date() && _this.currentResults.BillingAddressCountryDescription != "") {
                        $('#FlightResultsErrorfor24hrs').show();
                        $('#billingAddressCountryDesc').text(_this.currentResults.BillingAddressCountryDescription);
                    } else {
                        $('#FlightResultsErrorfor24hrs').hide();
                    }

                        //Defect #109064
                    }
                    else {
                    if (_this.currentResults.appliedSearch.IsAwardCalendarEnabled && _this.currentResults.appliedSearch.awardTravel && !_this.currentResults.appliedSearch.flexibleAward && this.currentResults.appliedSearch.SkipAwardCalendar !== true) {
                        setTimeout(function () {
                            _this.loadAwardCalendar(_this.currentResults.appliedSearch);
                        }, 200);
                    }
                }
                //ToDo: to delete below lines in future.
                //INIT VALUES
                //$('.fare-wheel-container').farewheel({
                //    selectDay: function (event) {
                //        //select day code
                //        _this.handleFareWheelChange(event);
                //    }
                //});
                $('#pos-notice').css('display', 'block');

                // Directly calling to RTI Page without showing FSR page.
                if (UA && UA.ReShop) {
                    var CanceltotalTrips = parseInt($("#hdnTotalTrips").val(), 10)
                    if (CanceltotalTrips == 0) {

                        if (this.currentResults !== null && this.currentResults !== 'undefined') {
                            var RTICancelCartID, RTICancelSolutionSetId, RTICancelProductId;
                            RTICancelProductId = null;

                            RTICancelCartID = this.currentResults.CartId;
                            if (this.currentResults.Trips !== null && this.currentResults.Trips.length > 0 && this.currentResults.Trips[0].Flights !== null && this.currentResults.Trips[0].Flights.length > 0) {
                                RTICancelSolutionSetId = this.currentResults.Trips[0].Flights[0].SolutionSetId;
                                if (this.currentResults.Trips[0].Flights[0].Products !== null && this.currentResults.Trips[0].Flights[0].Products.length > 0) {
                                    _.forEach(this.currentResults.Trips[0].Flights[0].Products, function (RTICancelProduct) {
                                        if (RTICancelProduct !== null && RTICancelProduct !== 'undefined' && RTICancelProduct.ProductId !== null && RTICancelProduct.ProductId !== 'undefined' && RTICancelProductId === null
                                            && RTICancelProduct.ProductSubtype !== null && RTICancelProduct.ProductSubtype !== 'NonExistingProductPlaceHolder')
                                            RTICancelProductId = RTICancelProduct.ProductId;
                                    });
                                }
                            }
                            this.NavigateToRTIPage(true, RTICancelCartID, RTICancelSolutionSetId, RTICancelProductId);
                        }
                    }
                }
            },
            lowestRevenueTemplateBind: function (response){
                if (response && response.IsCheapest) {
                    $('#lowest-revenue-banner-placeholder').html(response.Content);
                    this.awardRevenueAnalytics($('#lowest-revenue-banner-placeholder'), response.LowestAmount);
                }
                else {
                    $('#lowest-revenue-banner-placeholder').html("");
                }
            },
            loadSearchFilterResults: function (reqsearchInput, respStopcount) {
                if (!reqsearchInput.nonStop && !reqsearchInput.oneStop && !reqsearchInput.twoPlusStop) {
                    reqsearchInput.nonStop = true;
                    reqsearchInput.oneStop = true;
                    reqsearchInput.twoPlusStop = true;
                }
                ////282751 - selected the non stop flight based on the stopcountMin
                if (reqsearchInput.nonStop && respStopcount.StopCountMin == 0 && !reqsearchInput.oneStop && !reqsearchInput.twoPlusStop) {
                    reqsearchInput.nonStop = true;
                    reqsearchInput.oneStop = false;
                    reqsearchInput.twoPlusStop = false;
                }
                //nonstop unchecked, 1stop checked, 2plusstop checked, but the market only has nonstop flights and no onestop or twostop flights
                if (!reqsearchInput.nonStop && respStopcount.StopCountMin == 0 && reqsearchInput.oneStop && reqsearchInput.twoPlusStop) {
                    reqsearchInput.nonStop = true;
                    reqsearchInput.oneStop = false;
                    reqsearchInput.twoPlusStop = false;
                }
                //only non stop is checked and one stop and twoplus stops are unchecked but the flight results contains only flights with onestop and twoplus stops.
                if (reqsearchInput.nonStop && !reqsearchInput.oneStop && respStopcount.StopCountMin >= 1 && !reqsearchInput.twoPlusStop) {
                    reqsearchInput.nonStop = false;
                    reqsearchInput.oneStop = true;
                    reqsearchInput.twoPlusStop = true;
                }
                ////282751 - selected the one stop flight based on the stopcountMin
                if (!reqsearchInput.nonStop && respStopcount.StopCountMax > 0 && reqsearchInput.oneStop && !reqsearchInput.twoPlusStop) {
                    reqsearchInput.nonStop = false;
                    reqsearchInput.oneStop = true;
                    reqsearchInput.twoPlusStop = false;
                }
                //nonstop checked,onestop not checked, twoplusstop checked, but the market only has 1stop flights and no NonStop or 2stop flights
                if (reqsearchInput.nonStop && respStopcount.StopCountMax == 1 && !reqsearchInput.oneStop && reqsearchInput.twoPlusStop) {
                    reqsearchInput.nonStop = false;
                    reqsearchInput.oneStop = true;
                    reqsearchInput.twoPlusStop = false;
                }
                //nonstop unchecked, onestop unchecked, twoplusstop checked, but the market only has onestop flights and nonstop flights but no 2 stop flights.
                if (!reqsearchInput.nonStop && !reqsearchInput.oneStop && respStopcount.StopCountMax <= 1 && reqsearchInput.twoPlusStop) {
                    reqsearchInput.nonStop = true;
                    reqsearchInput.oneStop = true;
                    reqsearchInput.twoPlusStop = false;
                }

                ////282751 - selected the twoPlusStop flight based on the stopcountMin
                if (!reqsearchInput.nonStop && !reqsearchInput.oneStop && reqsearchInput.twoPlusStop && respStopcount.StopCountMax > 1) {
                    reqsearchInput.nonStop = false;
                    reqsearchInput.oneStop = false;
                    reqsearchInput.twoPlusStop = true;
                }
            },
            addHasConfPPRUpgrade: function (response) {
                if (response.Trips && response.Trips.length > 0) {
                    _.forEach(response.Trips, function (trip) {
                        if (trip.Flights && trip.Flights.length > 0) {
                            _.forEach(trip.Flights, function (flt) {
                                if (flt.Products && flt.Products.length > 0) {
                                    _.forEach(flt.Products, function (prod) {
                                        if (prod.UpgradeOptions && prod.UpgradeOptions.length > 0) {
                                            _.forEach(prod.UpgradeOptions, function (options) {
                                                if (options != null && options.SegmentMapping != null && options.SegmentMapping.length > 0 && _.some(options.SegmentMapping, function (segment) { return segment.UpgradeStatus != null && segment.UpgradeStatus.toUpperCase() == "CONFIRMABLE";})) {
                                                    response.Trips[0].HasConfPPRUpgrade = true;
                                                }
                                            });
                                        }
                                    });
                                }
                            });
                        }
                    });
                }
            },
            loadCalendarResults: function (searchInput) {
                var _this = this,
                    request = this.fetchFlightResults(searchInput);

                $.when(request).done(function (response) {
                    if ((response.data && response.data.Trips && response.data.Trips.length > 0)) {
                        _this.currentResults.Calendar = response.data.Calendar;
                    }

                    if (_this.elements.calendarContainer !== null && response.data.Calendar !== null) {
                        if (_this.currentResults.appliedSearch.flexible) {
                            _this.renderFareCalendar(_this.currentResults);
                        } else {
                            _this.renderAvailabilityCalendar(_this.currentResults);
                        }
                    }
                })
                    .then(
                    function (response) {

                        if (response.status !== "success") {
                            logErrors(response.errors);
                            displayErrorDialog(response.errors, response.CartId);
                        } else {
                            _this.currentResults.appliedSearch.InitialShop = false;
                        }
                        return response;
                    },
                    function (response) {

                        return $.Deferred().reject(response);

                    }
                    ).always(function (data) {

                        _this.hidePageLoader();

                        UA.UI.Uniform.init();

                        if (_this.spinner_button !== null) {
                            try {
                                _this.spinner_button.loader('destroy');
                            } catch (ex) {
                                ;
                            }

                            try {
                                if (_this.currentResults.appliedSearch.flexible) {
                                    $(".fc-price-calendar-container.calendar-loader > .fc-calendar").attr("tabindex", "0");
                                    $(".fc-price-calendar-container.calendar-loader > .fc-calendar").focus();

                                    setTimeout(function () {
                                        $(".fc-price-calendar-container.calendar-loader > .fc-calendar").removeAttr("tabindex");
                                    }, 300);
                                }
                            } catch (ex) {
                                ;
                            }
                        }
                    });
                return request;
            },
            fetchLmxData: function (flightHashList, tripIndex, metrics) {
                var serviceUrl = this.elements.container.data('lmxurl'),
                    request = $.ajax({
                        type: "POST",
                        url: serviceUrl,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify({
                            cartId: this.currentResults.appliedSearch.CartId,
                            hashList: flightHashList,
                            tripIndex: tripIndex,
                            metrics: metrics
                        })
                    });

                return request;

            },
            loadLmxData: function (flightHashList, tripIndex, metrics) {

                var _this = this,
                    request,
                    flight,
                    isSelectedFlight = typeof tripIndex !== 'undefined';

                request = this.fetchLmxData(flightHashList, tripIndex, metrics);


                //map lmx data back to current results or to selected results

                $.when(request).done(function (response) {

                    _this.removeLmxProductsforSingleColumnDesign(response);

                    if (response.data) {
                        _.forEach(response.data, function (responseFlight) {
                            flight = isSelectedFlight ? _this.getSelectedFlightByHash(responseFlight.Hash) : _this.getFlightByHash(responseFlight.Hash)
                            try {
                                if (responseFlight.Products.length < flight.Products.length) {
                                    var isproductavaialble = false, productindex = 0;
                                    _.forEach(flight.Products, function (prod) {
                                        isproductavaialble = false;
                                        _.forEach(responseFlight.Products, function (lmxprod) {
                                            if (lmxprod.ProductType == prod.ProductType && lmxprod.ProductSubtype == prod.ProductSubtype && !isproductavaialble) {
                                                isproductavaialble = true;
                                            }
                                        });
                                        if (!isproductavaialble) {
                                            var products = {};
                                            products = {
                                                ProductType: prod.producttype, ProductSubtype: "NonExistingProductPlaceholder"
                                            }
                                            responseFlight.Products.splice(productindex, 0, products);
                                        }
                                        productindex++;
                                    });
                                }

                                _.forEach(flight.Products, function (product, i) {
                                    if (product.ProductSubtype != "NonExistingProductPlaceholder") {
                                        product.LmxLoyaltyTiers = isSelectedFlight ? responseFlight.Products[0].LmxLoyaltyTiers : responseFlight.Products[i].LmxLoyaltyTiers;
                                        flight.LmxLoaded = true;
                                    }
                                });
                            }
                            catch (lmxerror) { }
                        });
                    }
                });


                return request;
            },
            loadFlightAmenities: function () {
                var _this = this,
                    currentResults = _this.currentResults,
                    param = {
                        CartId: currentResults.CartId,
                        FlightNumbers: combineConnectionsWithFlights(currentResults.Trips[0].Flights)
                    },
                    serviceUrl = this.elements.container.data('amenitiesurl'),
                    request = $.ajax({
                        type: "POST",
                        url: serviceUrl,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify(param)
                    });


                $.when(request).done(function (response) {
                    if (response.data) {
                        var hasAmenities = false,
                            flightPair,
                            flightExists,
                            parentAmenities,
                            parentOffered = {},
                            connAmenities,
                            connOffered,
                            other = {
                                "Description": null,
                                "IsOffered": true,
                                "Key": "Other"
                            },
                            allowedAmenities = ['WiFi', 'InseatPower', 'DirecTV'],
                            available = [];

                        _.forEach(_this.currentResults.Trips[0].Flights, function (flight) {

                            //populate each parent flight's amenities
                            parentAmenities = response.data[flight.FlightNumber];
                            parentOffered = {};
                            if (parentAmenities) {
                                _.forEach(parentAmenities, function (parentAmenity) {
                                    if (parentAmenity.IsOffered && _.contains(allowedAmenities, parentAmenity.Key)) {
                                        hasAmenities = true;
                                        if (!_.contains(available, parentAmenity.Key)) {
                                            available.push(parentAmenity.Key);
                                        }
                                        parentOffered[parentAmenity.Key] = parentAmenity;
                                    }
                                });
                            }

                            if (!flightPair) {
                                flightPair = {};
                            }
                            var stopnonstopfeature = (($('#StopNonStop').val() == "True" ? true : false) && _this.currentResults.appliedSearch != null && !_this.currentResults.appliedSearch.awardTravel);
                            if (stopnonstopfeature) {
                                if (flight.Amenities == null) {
                                    flight.Amenities = parentOffered;
                                }
                            } else {
                                flight.Amenities = parentOffered;
                            }

                            flightExists = _.contains(_.keys(flightPair), flight.FlightNumber);

                            if (!flightExists) {
                                if (!_.isEmpty(parentOffered)) {
                                    var segIndicator = $('#fl-results').find('.lof-segment-summary .segment[data-flight-number=' + flight.FlightNumber + ']')
                                        .find('.segment-indicators-list');
                                    if (parentOffered.hasOwnProperty('WiFi')) {
                                        if (segIndicator.find('i').hasClass('icon-wifi') === false)
                                            segIndicator.prepend(_this.templates.searchAmenitiesResults(parentOffered));
                                    } else
                                        segIndicator.prepend(_this.templates.searchAmenitiesResults(parentOffered));
                                } else {
                                    if (!_.contains(available, other.Key) && _.contains(allowedAmenities, other.Key)) {
                                        available.push(other.Key);
                                    }

                                    flight.Amenities.Other = _.clone(other);
                                }

                                flightPair[flight.FlightNumber] = {
                                    Amenities: flight.Amenities
                                };
                            } else {
                                flight.Amenities = flightPair[flight.FlightNumber].Amenities;
                            }

                            //populate each flight's connections amenities
                            if (flight.Connections && flight.Connections.length > 0) {
                                _.forEach(flight.Connections, function (conn) {
                                    connAmenities = response.data[conn.FlightNumber];
                                    connOffered = {};
                                    if (connAmenities) {
                                        _.forEach(connAmenities, function (connAmenity) {
                                            if (connAmenity.IsOffered && _.contains(allowedAmenities, connAmenity.Key)) {
                                                hasAmenities = true;
                                                if (!_.contains(available, connAmenity.Key)) {
                                                    available.push(connAmenity.Key);
                                                }
                                                connOffered[connAmenity.Key] = connAmenity;
                                            }
                                        });
                                    }

                                    if (!flightPair) {
                                        flightPair = {};
                                    }

                                    conn.Amenities = connOffered;
                                    flightExists = _.contains(_.keys(flightPair), conn.FlightNumber);

                                    if (!flightExists) {

                                        if (!_.isEmpty(connOffered)) {
                                            $('#fl-results').find('.lof-segment-summary .segment[data-flight-number=' + conn.FlightNumber + ']')
                                                .find('.segment-indicators-list')
                                                .prepend(_this.templates.searchAmenitiesResults(connOffered));
                                        } else {
                                            if (!_.contains(available, other.Key) && _.contains(allowedAmenities, other.Key)) {
                                                available.push(other.Key);
                                            }
                                            conn.Amenities.Other = _.clone(other);
                                        }

                                        flightPair[conn.FlightNumber] = {
                                            Amenities: conn.Amenities
                                        };
                                    } else {
                                        conn.Amenities = flightPair[conn.FlightNumber].Amenities;
                                    }
                                });
                            }
                        });

                        if (!hasAmenities) {
                            if (_this.currentResults.SearchFilters.Warnings.length < 1 && _this.currentResults.SearchFilters.CarriersPreference.length < 2 && _this.currentResults.SearchFilters.AircraftList.length < 2) {
                                $(".filter-section-experience").hide();
                            }
                            return;
                        }

                        var avialableAmenities = _.intersection(allowedAmenities, available);
                        $.extend(_this.currentResults.SearchFilters.Amenities, avialableAmenities);
                        if ($('#filter-checkbox-amenities').length > 0) {
                            $('#filter-checkbox-amenities').html('');
                        }
                        _this.currentResults.appliedSearch.SearchFilters.Amenities = [];

                        if (_this.currentResults.SearchFilters.Warnings.length < 1 && avialableAmenities.length < 2 && _this.currentResults.SearchFilters.CarriersPreference.length < 2 && _this.currentResults.SearchFilters.AircraftList.length < 2) {
                            $(".filter-section-experience").hide();
                        }

                        $('#experience-content .filter-content-spacer').prepend(_this.templates.searchFilterAmenities(currentResults));

                        UA.UI.reInit($('#filter-checkbox-amenities'));
                        UA.UI.Toggler.init();

                        $('#fl-results-pager-container').trigger('search.auxillary.updated', ['Amenities', flightPair]);
                    }
                })
                    .then(
                    function (response) {
                        if (response.errors) {
                            logErrors(response.errors);
                        }
                        return response;
                    },
                    function (response) {

                        return $.Deferred().reject(response);

                    });
                return request;
            },
            loadFlightAux: function () {
                var _this = this,
                    currentResults = _this.currentResults,
                    param = {
                        CartId: currentResults.CartId,
                        TravelerCount: currentResults.NoOfTravelers,
                        isReshopPath: currentResults.appliedSearch.isReshopPath
                    },
                    serviceUrl = this.elements.container.data('indicatorsurl'),
                    request = $.ajax({
                        type: "POST",
                        url: serviceUrl,
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify(param)
                    });

                $.when(request).done(function (response) {
                    if (response.data) {
                        var flightPair;
                        var auxData = response.data;
                        var isAuxilliaryUpgradeEligible = false;
                        var isComplimentaryUpgrade = false;

                        _.forEach(_this.currentResults.Trips[0].Flights, function (flight) {
                            var aux = auxData[flight.Hash];
                            var $farelockIcon;

                            if (aux) {
                                isAuxilliaryUpgradeEligible = false;
                                if (flight.Connections && flight.Connections.length > 0) {
                                    _.forEach(flight.Connections, function (connection) {
                                        if (aux.ConnectionsPair != null) {
                                            var connectAux = aux.ConnectionsPair[connection.FlightNumber];
                                            if (connectAux) {
                                                _.forEach(connection.Products, function (productConnections) {
                                                    _.forEach(connectAux.AuxiliaryProducts, function (auxilliaryConnection) {
                                                        if (productConnections && productConnections.ProductType == auxilliaryConnection.ProductType) {
                                                            productConnections.ComplimentaryUpgrade = auxilliaryConnection.ComplimentaryUpgradeInfo;
                                                            if (productConnections && productConnections.ComplimentaryUpgrade && productConnections.ComplimentaryUpgrade.Eligible && !productConnections.ComplimentaryUpgrade.Waitlisted) {
                                                                isComplimentaryUpgrade = true;
                                                            }
                                                        }
                                                    });
                                                });
                                                connectAux.Auxilliary = true;
                                                connection.UpgradeEligible = connectAux.UpgradeEligible;
                                            }
                                        }
                                    });
                                }

                                _.forEach(flight.Products, function (product) {
                                    _.forEach(aux.AuxiliaryProducts, function (auxilliary) {
                                        if (product.ProductType === auxilliary.ProductType) {
                                            product.ComplimentaryUpgrade = auxilliary.ComplimentaryUpgradeInfo;
                                            product.ComplimentaryEligible = auxilliary.ComplimentaryEligible;
                                            if (product.ComplimentaryUpgrade && product.ComplimentaryUpgrade.Eligible && !product.ComplimentaryUpgrade.Waitlisted) {
                                                isAuxilliaryUpgradeEligible = true;
                                            }
                                            auxilliary.BookingCode = product.BookingCode;
                                            var $auxilliary = $('.flight-block[data-flight-hash="' + flight.Hash + '"]', $('#fl-results')).find('#product_' + auxilliary.ProductType + '_' + _.escapeRegExp(flight.Hash) + ' .fare-option-icon');
                                            if ($auxilliary.length > 0) {
                                                $auxilliary.remove();
                                            }
                                            $('.flight-block[data-flight-hash="' + flight.Hash + '"]', $('#fl-results')).find('#product_' + auxilliary.ProductType + '_' + _.escapeRegExp(flight.Hash) + ' .sr_product_wrapper').prepend(_this.templates.searchUpgradeAvailResults(auxilliary));
                                        }
                                    });
                                });

                                var auxillaryEligible = {
                                    FarelockEligible: aux.FarelockEligible,
                                    UpgradeEligible: isAuxilliaryUpgradeEligible
                                };

                                $farelockIcon = $('.flight-block[data-flight-hash="' + flight.Hash + '"]').find('.flight-connection-container .farelock-icon');
                                if ($farelockIcon.length > 0) {
                                    $farelockIcon.remove();
                                }
                                $('.flight-block[data-flight-hash="' + flight.Hash + '"]', $('#fl-results')).find('.flight-connection-container').prepend(_this.templates.searchFarelockResults(auxillaryEligible));

                                flight.Auxilliary = auxillaryEligible;
                            }

                            if (!flightPair) {
                                flightPair = {};
                            }

                            flightPair[flight.Hash] = flight;
                        });
                        $('#fl-results-pager-container').trigger('search.auxillary.updated', ['auxillary', flightPair]);
                    }
                })
                    .then(
                    function (response) {
                        _.forEach(_this.currentResults.Trips[0].Flights, function (flight) {
                            if (flight.Connections && flight.Connections.length > 0) {
                                _.forEach(flight.Connections, function (connection) {

                                    //if thru-flight - check to see if a stop has been treated as a connection
                                    if (flight.FlightNumber == connection.FlightNumber) {

                                        //set auxilliary properties
                                        if (flight.Auxilliary != null && connection.Auxilliary == null) {
                                            connection.Auxilliary = flight.Auxilliary;
                                        }

                                        //set Upgrade attributes from parent flight to stop that is treated as connection
                                        for (var z = 0; z < flight.Products.length; z++) {

                                            //set complimentary upgrades
                                            if (flight.Products[z].ComplimentaryUpgrade != null) {
                                                if (connection.Products[z] != null && (connection.Products[z].ComplimentaryUpgrade == null || !connection.Products[z].ComplimentaryUpgrade.length > 0)) {
                                                    connection.Products[z].ComplimentaryUpgrade = flight.Products[z].ComplimentaryUpgrade;
                                                }
                                            }

                                            //set complimentary eligible property
                                            if (flight.Products[z].ComplimentaryEligible != null) {
                                                if (connection.Products[z] != null && connection.Products[z].ComplimentaryEligible == null) {
                                                    connection.Products[z].ComplimentaryEligible = flight.Products[z].ComplimentaryEligible;
                                                }
                                            }

                                        }

                                    }
                                });
                            }
                        });

                        return response;
                    }
                    )
                    .then(
                    function (response) {
                        if (response.errors) {
                            logErrors(response.errors);
                        }
                        return response;
                    },
                    function (response) {

                        return $.Deferred().reject(response);

                    });
                return request;
            },
            loadFareWheel: function (params) {

                if (params.awardTravel) {
                    return;
                }

                if (params.flexible) {
                    return;
                }

                var request, _this = this;

                request = this.fetchFareWheel(params);
                $.when(request).done(function (response) {
                    _this.buildFareWheel(response);
                });
            },
            showNearbyError: function (nearbyError) {
                var bInserted = this.fsrTipsData.insert("nearbyError", nearbyError);
                if (bInserted) {
                    this.drawFsrTips();

                    var $element = $("#fl-search-header-nearbyerror");
                    if ($element.length > 0) {
                        var $parentElement = $element.parent();
                        var moduleInfo = "{\"action\": \"No results shown\", \"desc\": \"No flights match your search criteria\"}";
                        $parentElement.removeAttr("data-module-info").attr("data-module-info", moduleInfo);
                        $parentElement.data("module-info", JSON.parse(moduleInfo));
                        UA.UI.processModule($parentElement);
                    }
                }
            },
            showNearby: function (nearby) {
                var bInserted = this.fsrTipsData.insert("nearby", nearby);
                if (bInserted) {
                    this.drawFsrTips();

                    var $element = $("#fl-search-header-nearby");
                    if ($element.length > 0) {
                        var $parentElement = $element.parent();
                        var moduleInfo = "{\"action\": \"Nearby airport shown\", \"desc\": \"Nearby airport\"}";
                        $parentElement.removeAttr("data-module-info").attr("data-module-info", moduleInfo);
                        $parentElement.data("module-info", JSON.parse(moduleInfo));
                        UA.UI.processModule($parentElement);
                    }
                }
            },
            showBetterOffers: function (searchResponse) {
                if (searchResponse.appliedSearch && searchResponse.appliedSearch.flexible === true) {
                    return;
                }

                if (showFsrTips && fsrTipsPhase2 && fsrTipsShowBetterOffers) {
                    if (searchResponse.IsAward === false && searchResponse.Trips && searchResponse.BetterOffers && searchResponse.BetterOffers.Better) {
                        var bInsert = false;
                        if ($('#hdnBetterOffersOnlyFsr1').val() === "true") {
                            if (searchResponse.Trips != null && searchResponse.Trips.length > 0 && searchResponse.Trips[0].Index === 1) {
                                bInsert = true;
                            }
                        } else {
                            bInsert = true;
                        }
                        if (bInsert) {
                            var data = {
                                SearchType: searchResponse.SearchType,
                                SearchIndex: searchResponse.Trips[0].Index,
                                BetterOffers: searchResponse.BetterOffers
                            };
                            var bInserted = this.fsrTipsData.insert("betterOffer", data);
                            if (bInserted) {
                                this.drawFsrTips();

                                var $element = $("#fl-search-header-betteroffers");
                                if ($element.length > 0) {
                                    var $parentElement = $element.parent();
                                    var moduleInfo = "{\"action\": \"Suggest date cheaper fare shown\", \"desc\": \"Cheaper fare available on other day\"}";
                                    $parentElement.removeAttr("data-module-info").attr("data-module-info", moduleInfo);
                                    $parentElement.data("module-info", JSON.parse(moduleInfo));
                                    UA.UI.processModule($parentElement);
                                }
                            }
                        }
                    }
                };
            },
            showNonStopSuggestMessage: function (searchInput) {
                var _this = this;
                if (fsrTipsPhase2 && fsrTipsShowNonstopSuggestion) {
                    var bRemoved = _this.fsrTipsData.removeAll("nonstopMsg");
                    if (bRemoved) {
                        _this.drawFsrTips();
                    }
                } else {
                    _this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
                }

                if (!UA.Booking.FlightSearch.currentResults ||
                    !UA.Booking.FlightSearch.currentResults.Trips ||
                    !UA.Booking.FlightSearch.currentResults.Trips[0].Flights) {
                    return;
                }

                var isNonStop = false;
                var len = UA.Booking.FlightSearch.currentResults.Trips[0].Flights.length;
                var i;
                for (i = 0; i < len; ++i) {
                    if (UA.Booking.FlightSearch.currentResults.Trips[0].Flights[i].StopsandConnections === 0) {
                        isNonStop = true;
                        break;
                    }
                }
                if (isNonStop) {
                    return;
                } else if (searchInput.awardTravel === true) {
                    return;
                } else if (searchInput.flexible === true) {
                    return;
                }

                searchInput.Trips[0].OriginDecoded = UA.Booking.FlightSearch.currentResults.Trips[0].OriginDecoded;
                if (UA.Booking.FlightSearch.currentResults.SearchType === "roundTrip") {
                    searchInput.Trips[1].DestinationDecoded = UA.Booking.FlightSearch.currentResults.Trips[0].DestinationDecoded;
                }
                var fareWheelRequest = _this.fetchNonStopDate(searchInput);
                $.when(fareWheelRequest).done(function (response) {
                    if (response.data && response.data.Exist) {
                        response.data.Origin = UA.Booking.FlightSearch.currentResults.Trips[0].Origin;
                        response.data.OriginDescription = extractCity(UA.Booking.FlightSearch.currentResults.Trips[0].Origin, UA.Booking.FlightSearch.currentResults.Trips[0].OriginDecoded);
                        response.data.Destination = UA.Booking.FlightSearch.currentResults.Trips[0].Destination;
                        response.data.DestinationDescription = extractCity(UA.Booking.FlightSearch.currentResults.Trips[0].Destination, UA.Booking.FlightSearch.currentResults.Trips[0].DestinationDecoded);
                        if (fsrTipsPhase2) {
                            if (fsrTipsShowNonstopSuggestion) {
                                var bInserted = _this.fsrTipsData.insert("nonstopMsg", response.data);
                                if (bInserted) {
                                    _this.drawFsrTips();

                                    var $element = $("#fl-search-header-nonstopsuggestion");
                                    if ($element.length > 0) {
                                        var $parentElement = $element.parent();
                                        var moduleInfo = "{\"action\": \"Suggest non stop shown\", \"desc\": \"Nonstop options\"}";
                                        $parentElement.removeAttr("data-module-info").attr("data-module-info", moduleInfo);
                                        $parentElement.data("module-info", JSON.parse(moduleInfo));
                                        UA.UI.processModule($parentElement);
                                    }
                                }
                            }
                        } else {
                            _this.elements.resultsHeaderSegmentNonstopSuggestion.html(_this.templates.flightResultsSegmentNonstopSuggestion(response.data));
                        }
                    }
                });
            },
            showNearbyCities: function (searchInput) {
                if (showFsrTips) {
                    if (fsrTipsPhase2) {
                        if (fsrTipsShowNearbyCities) {
                            var _this = this;
                            var bRemoved = _this.fsrTipsData.removeAll("nearbyCity");
                            if (bRemoved) {
                                this.drawFsrTips();
                            }

                            if (!UA.Booking.FlightSearch.currentResults ||
                                !UA.Booking.FlightSearch.currentResults.Trips ||
                                !UA.Booking.FlightSearch.currentResults.Trips[0].Flights ||
                                UA.Booking.FlightSearch.currentResults.Trips[0].Flights.length === 0 ||
                                UA.Booking.FlightSearch.currentResults.SearchType === "multiCity") {
                                return;
                            }

                            var nearbyCitiesRequest = _this.fetchNearbyCities(searchInput);
                            $.when(nearbyCitiesRequest).done(function (response) {
                                var nearbyCities = response.data
                                if (nearbyCities && nearbyCities.Exist && UA.Booking.FlightSearch.currentResults.IsAward === false && UA.Booking.FlightSearch.currentResults.Trips && UA.Booking.FlightSearch.currentResults.Trips[0].Index === 1) {
                                    nearbyCities.Origin.CityNameShort = extractCity(UA.Booking.FlightSearch.currentResults.Trips[0].Origin, UA.Booking.FlightSearch.currentResults.Trips[0].OriginDecoded);
                                    var len = nearbyCities.Destinations.length;
                                    var i;
                                    for (i = 0; i < len; ++i) {
                                        var nearbyCity = {
                                            SearchType: UA.Booking.FlightSearch.currentResults.SearchType,
                                            Origin: nearbyCities.Origin,
                                            Destination: nearbyCities.Destinations[i],
                                            DepartDay: nearbyCities.DepartDay,
                                            ReturnDay: nearbyCities.ReturnDay,
                                            PricingItem: nearbyCities.PricingItem
                                        };
                                        var bInserted = _this.fsrTipsData.insert("nearbyCity", nearbyCity);
                                        if (bInserted) {
                                            _this.drawFsrTips();

                                            var $element = $(".fl-search-nearbycities");
                                            if ($element.length > 0) {
                                                var $parentElement = $element.parent();
                                                var moduleInfo = "{\"action\": \"Nearby airport shown\", \"desc\": \"Nearby airport\"}";
                                                $parentElement.removeAttr("data-module-info").attr("data-module-info", moduleInfo);
                                                $parentElement.data("module-info", JSON.parse(moduleInfo));
                                                UA.UI.processModule($parentElement);
                                            }
                                        }
                                    }
                                }
                            });
                        }
                    } else {
                        if (fsrTipsShowNearbyCities) {
                            var _this = this;
                            _this.elements.resultsHeaderSegmentNearbyCities.empty();

                            if (!UA.Booking.FlightSearch.currentResults ||
                                !UA.Booking.FlightSearch.currentResults.Trips ||
                                !UA.Booking.FlightSearch.currentResults.Trips[0].Flights ||
                                UA.Booking.FlightSearch.currentResults.Trips[0].Flights.length === 0 ||
                                UA.Booking.FlightSearch.currentResults.SearchType === "multiCity") {
                                return;
                            }

                            var nearbyCitiesRequest = this.fetchNearbyCities(searchInput);
                            $.when(nearbyCitiesRequest).done(function (response) {
                                if (response.data) {
                                    response.data.Origin.CityNameShort = extractCity(UA.Booking.FlightSearch.currentResults.Trips[0].Origin, UA.Booking.FlightSearch.currentResults.Trips[0].OriginDecoded);
                                    var data1 = {
                                        SearchType: UA.Booking.FlightSearch.currentResults.SearchType,
                                        IsAward: UA.Booking.FlightSearch.currentResults.IsAward,
                                        Trips: UA.Booking.FlightSearch.currentResults.Trips,
                                        NearbyCities: response.data
                                    };
                                    _this.elements.resultsHeaderSegmentNearbyCities.html(_this.templates.flightResultsSegmentNearbyCities(data1));
                                }
                            });
                        }
                    }
                }
            },
            drawFsrTips: function () {
                var _this = this;
                if (_this.fsrTipsData && _this.fsrTipsData.fsrTips && _this.fsrTipsData.fsrTips.length > 0) {
                    var fsrTipsHtml = "";
                    $.each(_this.fsrTipsData.fsrTips, function (idx, elem) {
                        elem.data.FsrTip = {
                            Level: elem.level,
                            PrimaryClass: elem.getPrimaryClass(),
                            SecondaryClass: elem.getSecondaryClass(),
                            FirstRowClass: elem.getFirstRowClass(),
                            onlyFsr1: elem.onlyFsr1,
                            includeMulticity: elem.includeMulticity,
                            buttonLike: elem.buttonLike
                        };
                        if (elem.name == "nearbyError") {
                            fsrTipsHtml += _this.templates.flightResultsSegmentNearbyError(elem.data);
                            _this.hideLineLoader();
                        } else if (elem.name == "nearby") {
                            fsrTipsHtml += _this.templates.flightResultsSegmentNearby(elem.data);
                        } else if (elem.name == "nearbyCity") {
                            fsrTipsHtml += _this.templates.flightResultsSegmentNearbyCities(elem.data);
                        } else if (elem.name == "nonstopMsg") {
                            fsrTipsHtml += _this.templates.flightResultsSegmentNonstopSuggestion(elem.data);
                        } else if (elem.name == "betterOffer") {
                            fsrTipsHtml += _this.templates.flightResultsSegmentBetterOffers(elem.data);
                        }                        
                    });
                    _this.elements.resultsHeaderFsrTips.html(fsrTipsHtml);
                    if (fsrTipsHtml === "") {
                        if ($("#fl-search-header-fsrtips").hasClass("fl-search-header-fsrtips-empty") === false) {
                            $("#fl-search-header-fsrtips").addClass("fl-search-header-fsrtips-empty");
                        }
                    } else {
                        var i;
                        for (i = 1; i <= _this.fsrTipsData.maximumRows; ++i) {
                            var objSameRowTips = $(".fl-search-segment-row-" + i);
                            if (objSameRowTips.length > 0) {
                                if (objSameRowTips.hasClass("fl-search-segment-level-1")) {
                                    continue;
                                }

                                var maxHeight = 0;
                                $.each(objSameRowTips, function (idx, elem) {
                                    var height = $(elem).children(".fl-search-header-segment-table").height();
                                    if (height > maxHeight) {
                                        maxHeight = height;
                                    }
                                });

                                $.each(objSameRowTips, function (idx, elem) {
                                    var height = $(elem).children(".fl-search-header-segment-table").height();
                                    if (height < maxHeight) {
                                        var oldBottom = $(elem).children(".fl-search-header-segment-table").css("padding-bottom");
                                        var oldBottomNum = parseFloat(oldBottom);
                                        var oldBottomUnit = oldBottom.replace(oldBottomNum, "");
                                        $(elem).children(".fl-search-header-segment-table").css("padding-bottom", (oldBottomNum + maxHeight - height) + oldBottomUnit);
                                    }
                                });
                            }
                        }

                        $("#fl-search-header-fsrtips").removeClass("fl-search-header-fsrtips-empty");
                    }
                } else {
                    _this.elements.resultsHeaderFsrTips.empty();
                    if ($("#fl-search-header-fsrtips").hasClass("fl-search-header-fsrtips-empty") === false) {
                        $("#fl-search-header-fsrtips").addClass("fl-search-header-fsrtips-empty");
                    }
                }
            },
            emptyFsrTips: function () {
                this.elements.resultsHeaderFsrTips.empty();
                if ($("#fl-search-header-fsrtips").hasClass("fl-search-header-fsrtips-empty") === false) {
                    $("#fl-search-header-fsrtips").addClass("fl-search-header-fsrtips-empty");
                }
                this.fsrTipsData.clear();
            },
            buildFareWheel: function (response) {
                if (!response)//CSI1303 SHD,Burehkuu
                    return;
                var _this = this;
                _this.globalFWResponse = response;
                if (response.data && response.data.FareWheel && response.data.ShowFareWheel && _this.currentResults.Trips && _this.currentResults.Trips.length > 0) {
                    _this.renderFareWheel(response.data);
                    $('href.logo').focus();
                    $('.fare-wheel-container').farewheel({
                        selectDay: function (event) {
                            _this.handleFareWheelChange(event);
                        }
                    });
                } else {
                    $('#farewheel-placeholder').hide();                    
                    $('.fl-farewheel-disclaimer-container').addClass('no-farewheel');
                    if (_this.currentResults.Trips && _this.currentResults.Trips.length > 0) {
                        this.hideLineLoader();
                    }
                }
            },
            initStickyElements: function () {

                $('.fl-result-list-sticky-header').stickyheader({
                    offsetPartner: this.elements.resultsContainer
                });
                this.elements.filterSortContainer.find('.sticky').stickyheader();
                this.elements.searchCountFlagContainer.find('.sticky').stickyheader();
                if ($('.fsr-header')[0]) {
                    stickybits('#fl-search-header-placeholder', { useStickyClasses: true });
                }
            },
            initSliders: function (filterOpts) {
                if (!filterOpts) {
                    return;
                }
                var durationMin, durationMax, durationStart, durationEnd,
                    layoverMin, layoverMax, layoverStart, layoverEnd,
                    timeDepartMin, timeDepartMax, timeDepartStart, timeDepartEnd,
                    timeArrivalMin, timeArrivalMax, timeArrivalStart, timeArrivalEnd,
                    sliderPriceElement = $('#slide-price'),
                    sliderDurationElement = $('#slide-duration'),
                    sliderDepartElement = $('#slide-depart-time'),
                    sliderArriveElement = $('#slide-arrival-time'),
                    sliderLayoverElement = $('#slide-layover-time'),
                    self = this,
                    priceMin = Math.floor((filterOpts.MinPrices && filterOpts.MinPrices[self.currentResults.appliedSearch.SearchFilters.FareFamily]) ? filterOpts.MinPrices[self.currentResults.appliedSearch.SearchFilters.FareFamily] : filterOpts.PriceMin),
                    priceMax = Math.ceil((filterOpts.MaxPrices && filterOpts.MaxPrices[self.currentResults.appliedSearch.SearchFilters.FareFamily]) ? filterOpts.MaxPrices[self.currentResults.appliedSearch.SearchFilters.FareFamily] : filterOpts.PriceMax),
                    priceStart = priceMin,
                    priceEnd = priceMax,
                    priceCurrencyCode = filterOpts.CurrencyCode,
                    timeFilterStep = 60000,
                    timeFilterStepModifier = 60,
                    timeFilterTitleModifierMultiple = 1 / timeFilterStep,
                    timeFormatValues = function (values) {
                        var dateA = new Date(values[0]),
                            dateB = new Date(values[1]);
                        return [(dateA.toString("ddd. ") + formatAMPM(dateA)),
                        ((new Date(timeDepartStart).toString('ddd') === new Date(timeDepartEnd).toString('ddd')) ?
                            formatAMPM(dateB) :
                            dateB.toString("ddd. ") + formatAMPM(dateB))
                        ];
                    },
                    timespanFilterStep = 15,
                    timespanFilterStepModifier = 4,
                    timespanFormatValues = function (values) {
                        return [splitHoursMinutes(values[0]), splitHoursMinutes(values[1])];
                    },
                    tripIndex = this.getTripIndex(),
                    sliderOptions = {};

                //Setup for price slider
                //make sure there is a currency code.  try to get it from the SearchFilters if not present
                if (!priceCurrencyCode) {
                    //if nothing from filterOpts or SearchFilters then use the session currency code
                    priceCurrencyCode = self.currentResults.appliedSearch.SearchFilters.Currency || UA.AppData.Data.Session.Currency;
                }
                if (sliderPriceElement.length > 0) {
                    if (self.currentResults.appliedSearch.SearchFilters) {
                        if (self.currentResults.appliedSearch.SearchFilters.PriceMin) {
                            priceStart = Math.floor(self.currentResults.appliedSearch.SearchFilters.PriceMin);
                        }
                        if (self.currentResults.appliedSearch.SearchFilters.PriceMax) {
                            priceEnd = Math.ceil(self.currentResults.appliedSearch.SearchFilters.PriceMax);
                        }
                        self.currentResults.appliedSearch.SearchFilters.HidePrice = priceMin === priceMax;
                    }
                    sliderOptions.sliderPrice = {
                        element: sliderPriceElement,
                        startElement: $('#priceStartVal'),
                        endElement: $('#priceEndVal'),
                        min: priceMin,
                        max: priceMax,
                        start: priceStart,
                        end: priceEnd,
                        stepAmount: 1,
                        stepModifierMultiple: 100,
                        setFilterSetting: function (vals) {
                            self.currentResults.appliedSearch.SearchFilters.PriceMin = vals[0];
                            self.currentResults.appliedSearch.SearchFilters.PriceMax = vals[1];
                        },
                        formatValues: function (values) {
                            return [UA.Utilities.formatting.formatMoney(values[0], priceCurrencyCode, 0), UA.Utilities.formatting.formatMoney(values[1], priceCurrencyCode, 0)];
                        },
                        lowerHandleTitle: 'You\'re on a filter for price range. Use the left/right arrows to modify ticket minimum price by ${0}. Use CTRL+left/right arrows to change by ${1}',
                        upperHandleTitle: 'You\'re on a filter for price range. Use the left/right arrows to modify ticket maximum price by ${0}. Use CTRL+left/right arrows to change by ${1}'
                    };
                }

                //Setup for duration slider
                if (sliderDurationElement.length > 0) {
                    durationMin = (15 * Math.floor(filterOpts.DurationMin / 15));
                    durationMax = (15 * Math.ceil(filterOpts.DurationMax / 15));
                    durationStart = durationMin;
                    durationEnd = durationMax;
                    if (self.currentResults.appliedSearch.SearchFilters) {
                        if (self.currentResults.appliedSearch.SearchFilters.DurationMin) {
                            durationStart = Math.floor(self.currentResults.appliedSearch.SearchFilters.DurationMin);
                        }
                        if (self.currentResults.appliedSearch.SearchFilters.DurationMax) {
                            durationEnd = Math.ceil(self.currentResults.appliedSearch.SearchFilters.DurationMax);
                        }
                    }
                    sliderOptions.sliderDuration = {
                        element: sliderDurationElement,
                        startElement: $('#durationStartVal'),
                        endElement: $('#durationEndVal'),
                        min: durationMin,
                        max: durationMax,
                        start: durationStart,
                        end: durationEnd,
                        stepAmount: timespanFilterStep,
                        stepModifierMultiple: timespanFilterStepModifier,
                        setFilterSetting: function (vals) {
                            self.currentResults.appliedSearch.SearchFilters.DurationMin = vals[0];
                            self.currentResults.appliedSearch.SearchFilters.DurationMax = vals[1];
                        },
                        formatValues: timespanFormatValues,
                        lowerHandleTitle: 'You\'re on a filter for trip duration. Use the left/right arrows to modify minimum travel time by {0} minutes. Use CTRL+left/right arrows to change by {1} minutes',
                        upperHandleTitle: 'You\'re on a filter for trip duration. Use the left/right arrows to modify maximum travel time by {0} minutes. Use CTRL+left/right arrows to change by {1} minutes'
                    };
                }

                //Setup for depart time slider
                if (sliderDepartElement.length > 0) {
                    timeDepartMin = self.parseDateTime(filterOpts.TimeDepartMin).getTime();
                    timeDepartMax = self.parseDateTime(filterOpts.TimeDepartMax).getTime();
                    timeDepartStart = timeDepartMin;
                    timeDepartEnd = timeDepartMax;
                    if (self.currentResults.appliedSearch.SearchFilters) {
                        if (self.currentResults.appliedSearch.SearchFilters.TimeDepartMin) {
                            timeDepartStart = self.parseDateTime(self.currentResults.appliedSearch.SearchFilters.TimeDepartMin).getTime();
                        }
                        if (self.currentResults.appliedSearch.SearchFilters.TimeDepartMax) {
                            timeDepartEnd = self.parseDateTime(self.currentResults.appliedSearch.SearchFilters.TimeDepartMax).getTime();
                        }
                    }
                    sliderOptions.sliderDepart = {
                        element: sliderDepartElement,
                        startElement: $('#departStartVal'),
                        endElement: $('#departEndVal'),
                        min: timeDepartMin,
                        max: timeDepartMax,
                        start: timeDepartStart,
                        end: timeDepartEnd,
                        stepAmount: timeFilterStep,
                        stepModifierMultiple: timeFilterStepModifier,
                        titleModifierMultiple: timeFilterTitleModifierMultiple,
                        setFilterSetting: function (vals) {
                            var dateA = new Date(parseInt(vals[0], 10)),
                                dateB = new Date(parseInt(vals[1], 10));
                            self.currentResults.appliedSearch.SearchFilters.TimeDepartMin = dateA.toString("MM/dd/yyyy HH:mm");
                            self.currentResults.appliedSearch.SearchFilters.TimeDepartMax = dateB.toString("MM/dd/yyyy HH:mm");
                            self.currentResults.appliedSearch.Trips[tripIndex].PreferredTime = '';
                        },
                        formatValues: timeFormatValues,
                        lowerHandleTitle: 'You\'re on a filter for departure time. Use the left/right arrows to modify earliest time by {0} minute. Use CTRL+left/right arrows to change by {1} minutes.',
                        upperHandleTitle: 'You\'re on a filter for departure time. Use the left/right arrows to modify latest time by {0} minute. Use CTRL+left/right arrows to change by {1} minutes.'
                    };
                }

                //Setup for arrival time slider
                if (sliderArriveElement.length > 0) {
                    timeArrivalMin = self.parseDateTime(filterOpts.TimeArrivalMin).getTime();
                    timeArrivalMax = self.parseDateTime(filterOpts.TimeArrivalMax).getTime();
                    timeArrivalStart = timeArrivalMin;
                    timeArrivalEnd = timeArrivalMax;
                    if (self.currentResults.appliedSearch.SearchFilters) {
                        if (self.currentResults.appliedSearch.SearchFilters.TimeArrivalMin) {
                            timeArrivalStart = self.parseDateTime(self.currentResults.appliedSearch.SearchFilters.TimeArrivalMin).getTime();
                        }
                        if (self.currentResults.appliedSearch.SearchFilters.TimeArrivalMax) {
                            timeArrivalEnd = self.parseDateTime(self.currentResults.appliedSearch.SearchFilters.TimeArrivalMax).getTime();
                        }
                    }
                    sliderOptions.sliderArrive = {
                        element: sliderArriveElement,
                        startElement: $('#arriveStartVal'),
                        endElement: $('#arriveEndVal'),
                        min: timeArrivalMin,
                        max: timeArrivalMax,
                        start: timeArrivalStart,
                        end: timeArrivalEnd,
                        stepAmount: timeFilterStep,
                        stepModifierMultiple: timeFilterStepModifier,
                        titleModifierMultiple: timeFilterTitleModifierMultiple,
                        setFilterSetting: function (vals) {
                            var dateA = new Date(parseInt(vals[0], 10)),
                                dateB = new Date(parseInt(vals[1], 10));
                            self.currentResults.appliedSearch.SearchFilters.TimeArrivalMin = dateA.toString("MM/dd/yyyy HH:mm");
                            self.currentResults.appliedSearch.SearchFilters.TimeArrivalMax = dateB.toString("MM/dd/yyyy HH:mm");
                            self.currentResults.appliedSearch.Trips[tripIndex].PreferredTime = '';
                        },
                        formatValues: timeFormatValues,
                        lowerHandleTitle: 'You\'re on a filter for arrival time. Use the left/right arrows to modify earliest time by {0} minute. Use CTRL+left/right arrows to change by {1} minutes.',
                        upperHandleTitle: 'You\'re on a filter for arrival time. Use the left/right arrows to modify earliest time by {0} minute. Use CTRL+left/right arrows to change by {1} minutes.'
                    };
                }

                //Setup for layover slider
                if (sliderLayoverElement.length > 0) {
                    layoverMin = (15 * Math.floor(filterOpts.LayoverMin / 15));
                    layoverMax = (15 * Math.ceil(filterOpts.LayoverMax / 15));
                    layoverStart = layoverMin;
                    layoverEnd = layoverMax;
                    if (self.currentResults.appliedSearch.SearchFilters) {
                        if (self.currentResults.appliedSearch.SearchFilters.LayoverMin) {
                            layoverStart = Math.floor(self.currentResults.appliedSearch.SearchFilters.LayoverMin);
                        }
                        if (self.currentResults.appliedSearch.SearchFilters.LayoverMax) {
                            layoverEnd = Math.ceil(self.currentResults.appliedSearch.SearchFilters.LayoverMax);
                        }
                    }
                    sliderOptions.sliderLayover = {
                        element: sliderLayoverElement,
                        startElement: $('#layoverStartVal'),
                        endElement: $('#layoverEndVal'),
                        min: layoverMin,
                        max: layoverMax,
                        start: layoverStart,
                        end: layoverEnd,
                        stepAmount: timespanFilterStep,
                        stepModifierMultiple: timespanFilterStepModifier,
                        setFilterSetting: function (vals) {
                            self.currentResults.appliedSearch.SearchFilters.LayoverMin = vals[0];
                            self.currentResults.appliedSearch.SearchFilters.LayoverMax = vals[1];
                        },
                        formatValues: timespanFormatValues,
                        lowerHandleTitle: 'You\'re on a filter for connection time. Use the left/right arrows to modify minimum connection time by {0} minute. Use CTRL+left/right arrows to change by {1} minutes',
                        upperHandleTitle: 'You\'re on a filter for connection time. Use the left/right arrows to modify maximum connection time by {0} minute. Use CTRL+left/right arrows to change by {1} minutes'
                    };
                }

                //apply slider settings
                _.each(sliderOptions, function (sliderSettings, key) {

                    //Set up labels
                    var titleModifierMultiple = sliderSettings.titleModifierMultiple || 1,
                        valuesFormatted = sliderSettings.formatValues([sliderSettings.start, sliderSettings.end]),
                        stepAmount = sliderSettings.stepAmount * titleModifierMultiple,
                        ctlStepAmount = stepAmount * sliderSettings.stepModifierMultiple,
                        lowerHandleTitle = sliderSettings.lowerHandleTitle.format(stepAmount, ctlStepAmount),
                        upperHandleTitle = sliderSettings.upperHandleTitle.format(stepAmount, ctlStepAmount);
                    sliderSettings.startElement.text(valuesFormatted[0]);
                    sliderSettings.endElement.text(valuesFormatted[1]);

                    //initialize Slider
                    sliderSettings.element.noUiSlider({
                        range: {
                            'min': [sliderSettings.min],
                            'max': [sliderSettings.max]
                        },
                        start: [sliderSettings.start, sliderSettings.end],
                        connect: true,
                        margin: 1,
                        step: sliderSettings.stepAmount,
                        behaviour: 'extend-tap'
                    });

                    // initial values to enable tabbing to slider handles
                    sliderSettings.lowerHandle = sliderSettings.element.find('.noUi-handle-lower');
                    sliderSettings.upperHandle = sliderSettings.element.find('.noUi-handle-upper');
                    sliderSettings.lowerHandle.attr({
                        'tabindex': 0,
                        'role': 'slider',
                        'aria-valuemin': valuesFormatted[0],
                        'aria-valuemax': valuesFormatted[1],
                        'aria-valuetext': valuesFormatted[0],
                        'aria-valuenow': sliderSettings.start,
                        'title': lowerHandleTitle
                    });
                    sliderSettings.upperHandle.attr({
                        'tabindex': 0,
                        'role': 'slider',
                        'aria-valuemin': valuesFormatted[0],
                        'aria-valuemax': valuesFormatted[1],
                        'aria-valuetext': valuesFormatted[1],
                        'aria-valuenow': sliderSettings.end,
                        'title': upperHandleTitle
                    });

                    //utility fucntion for setting values in slider event
                    function setSliderVals(sliderSettings, vals) {
                        var valsFormatted = sliderSettings.formatValues(vals);
                        sliderSettings.startElement.text(valsFormatted[0]);
                        sliderSettings.endElement.text(valsFormatted[1]);
                        sliderSettings.lowerHandle.attr({
                            'aria-valuetext': valsFormatted[0],
                            'aria-valuenow': vals[0]
                        });
                        sliderSettings.upperHandle.attr({
                            'aria-valuetext': valsFormatted[1],
                            'aria-valuenow': vals[1]
                        });
                        sliderSettings.setFilterSetting(vals);
                    }

                    //add slider events
                    sliderSettings.element.on({
                        slide: function () {
                            var sliderVals = $(this).val(),
                                a = parseInt(sliderVals[0], 10),
                                b = parseInt(sliderVals[1], 10);
                            setSliderVals(sliderSettings, [a, b]);
                        },
                        keydown: function (e) {
                            var $this,
                                $target,
                                isLowerHandle,
                                sliderVals,
                                a,
                                b,
                                step = sliderSettings.stepAmount,
                                    keyCode = e.which;
                            if (e.ctrlKey || e.metaKey) {
                                step *= sliderSettings.stepModifierMultiple;
                            }
                            if (keyCode === 37 || keyCode === 39) {
                                e.preventDefault();
                                e.stopPropagation();
                                $this = $(this);
                                sliderVals = $this.val();
                                a = parseInt(sliderVals[0], 10);
                                b = parseInt(sliderVals[1], 10);
                                $target = $(e.target);
                                isLowerHandle = $target.hasClass('noUi-handle-lower');
                                if (keyCode === 39) { // right arrow
                                    if (isLowerHandle) {
                                        a += step;
                                    } else {
                                        b += step;
                                    }
                                } else if (keyCode === 37) { // left arrow
                                    if (isLowerHandle) {
                                        a -= step;
                                    } else {
                                        b -= step;
                                    }
                                }
                                if (a <= b && a >= sliderSettings.min && b <= sliderSettings.max) {
                                    setSliderVals(sliderSettings, [a, b]);
                                    $this.val([a, b]);
                                    $this.trigger('set');
                                }
                            }
                        },
                        set: $.proxy(self.handleFilterSliderSet, self)
                    });
                });
            },
            generateUUID: function () {
                var d = new Date().getTime();
                var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                    var r = (d + Math.random() * 16) % 16 | 0;
                    d = Math.floor(d / 16);
                    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
                });
                return uuid;
            },
            handleStateChange: function () {
                var _this = this,
                    historyBack, state = History.getState(),
                    searchState = state.data,
                    prevState = History.getStateByIndex(History.getCurrentIndex() - 1);

                triggeredStateChange = true;

                if (state.internal) {
                    if (prevState.data.currentResults) {
                        historyBack = true;
                        searchState = prevState.data;
                    } else {
                        window.location.replace(document.URL);
                        return;
                    }
                } else {
                    if (searchState.currentTripIndex < prevState.data.currentTripIndex) {
                        historyBack = true;
                    }
                }

                if (historyBack) {
                    this.elements.selectedFlightContainer.empty();
                    this.selectedFlights = [];
                    this.showLineLoader(true);
                    if (searchState.currentTripIndex !== 1) {
                        //searchState.currentResults.appliedSearch.Revise = true;
                    } else {
                        searchState.currentResults.appliedSearch.CartId = $('#CartId').val();
                    }
                }
                this.clearAndLoadResult(searchState);
            },
            handleFilterSliderSet: function () {
                if (!this.loadFilterResultsDebounced) {
                    this.loadFilterResultsDebounced = _.debounce(this.loadFilterResults, 250);
                }
                this.loadFilterResultsDebounced(this.currentResults.appliedSearch);
                $("#fl-bestresult-notification").empty();
            },
            initFilterSelections: function (response) {
                var _this = this;
                $('#SortType').prop('selectedIndex', 0);
                if (this.currentResults.appliedSearch.SortType) {
                    $('#SortType').val(this.currentResults.appliedSearch.SortType);
                }

                if (this.currentResults.appliedSearch.SearchFilters.CarriersPreference && this.currentResults.appliedSearch.SearchFilters.CarriersPreference.length > 0) {
                    $('#filt-airlines-opt-cont input:checkbox').each(function () {
                        if (_.contains(_this.currentResults.appliedSearch.SearchFilters.CarriersPreference, $(this).val())) {
                            $(this).prop('checked', true);
                        } else {
                            $(this).prop('checked', false);
                        }
                    });
                }

                this.initSliders(response.SearchFilters);
                UA.UI.reInit(this.elements.filterSortContainer);
            },
            handleFareFocus: function (e) {
                var isFocused = e.type == 'focusin';
                $(e.currentTarget).parent('.fare-option').toggleClass('fare-option-focused', isFocused);
            },

            handleUpgradeUPPFareSelect: function (e) {                
                e.preventDefault();
                var btnEl = $(e.currentTarget),
                    fareData = btnEl.data('fare-data'),
                    fareDescription = btnEl.data('fare-description'),
                    flightHash = btnEl.data('flight-hash'),
                    flightData = this.getFlightByHash(flightHash);
                if (fareData.AdditionalUpgradeIds)
                {
                    var currentSelectedPriceId = $('#hdnAdditionalUpgradeId').val();
                    if (currentSelectedPriceId) {
                        $('#hdnAdditionalUpgradeId').val(currentSelectedPriceId.concat(',', fareData.AdditionalUpgradeIds));
                    }
                    else {
                        $('#hdnAdditionalUpgradeId').val(fareData.AdditionalUpgradeIds);
                    }
                }                    
                $.modal.close();

                this.handleFareSelected(fareDescription, flightHash, flightData, fareData);
            },

            handleConfirmFare: function (e) {
                e.preventDefault();
                var btnEl = $(e.currentTarget),
                    fareData = btnEl.data('fare-data'),
                    flightData = this.getFlightByHash(fareData.flightHash);

                if (fareData.isElf) {
                    $.modal.close();
                }

                if (fareData.ProductCode != null && (fareData.ProductCode == 'LGT' || (fareData.IsIBEType == 'true') || fareData.ProductCode == '')) {
                    $.modal.close();
                }

                // this.handleFareSelected(fareData.fareDescription, fareData.flightHash, flightData, fareData, fareData.isElf);
                this.handleFareSelected(fareData.fareDescription, fareData.flightHash, flightData, fareData);

            },
            handleSingleColumnSelect: function(e) {
                var fareEl, selectedProduct;
                fareEl = ($('#hdnShowFareSelectButton').val() === 'True') ? $(e.currentTarget).closest('.fare-option-revised') : $(e.currentTarget);
                this.currentResults.appliedSearch.SkipAwardCalendar = false;
                var flightHash = fareEl.parents('.flight-block').data('flight-hash'),
                    flightData = this.getFlightByHash(flightHash),
                    select = fareEl.data('flight-select'),
                    selectedProductId = select.CellIdSelected,
                    _this = this;
                
                selectedProduct = _.filter(flightData.Products, function (product) {
                    return product.ProductId == selectedProductId;
                });

                if (_this.isSingleColumnDesignActive() && flightData && flightData.Products && flightData.Products.length > 0
                    && $.inArray(selectedProduct[0].ProductType, this.columnsWithUpsell()) != -1) {
                    var economyUpsellPanels, currentEconomyUpsellPanel;

                    currentEconomyUpsellPanel = $(e.currentTarget).closest('.flight-block').find('.economy-select-section');

                    this.collapseAllTabsAndPanels();

                    $(".fare-select-sc-button").removeClass('button-disable');
                    
                    $(e.currentTarget).addClass('button-disable');
                    this.renderEconomyUpsell(null, currentEconomyUpsellPanel, selectedProduct[0].ProductTypeDescription);
                    this.loadEconomyPlusFare(currentEconomyUpsellPanel, selectedProduct, flightHash, selectedProduct[0].ProductTypeDescription);

                } else {
                    this.handleFareSelection(e);
                }
            },
            handleUpSell: function (e) {
                var fareEl, selectedProduct;
                fareEl = ($('#hdnShowFareSelectButton').val() === 'True') ? $(e.currentTarget).closest('.fare-option-revised') : $(e.currentTarget);
                this.currentResults.appliedSearch.SkipAwardCalendar = false;
                var flightHash = fareEl.parents('.flight-block').data('flight-hash'),
                    flightData = this.getFlightByHash(flightHash),
                    select = fareEl.data('flight-select'),
                    selectedProductId = select.CellIdSelected,
                    _this = this;

                selectedProduct = _.filter(flightData.Products, function (product) {
                    return product.ProductId == selectedProductId;
                });

                if (flightData && flightData.Products && flightData.Products.length > 0
                    && $.inArray(selectedProduct[0].ProductType, this.columnsWithUpsell()) != -1) {
                    var economyUpsellPanels, currentEconomyUpsellPanel;

                    currentEconomyUpsellPanel = $(e.currentTarget).closest('.flight-block').find('.economy-select-section');

                    this.collapseAllTabsAndPanels();

                    $(".fare-select-button").removeClass('button-disable');

                    $(e.currentTarget).addClass('button-disable');
                    this.upSellFlightElement = $(e.currentTarget).closest('.fare-option-revised');
                    this.renderEconomyUpsell(null, currentEconomyUpsellPanel, selectedProduct[0].ProductTypeDescription);
                    this.loadEconomyPlusFare(currentEconomyUpsellPanel, selectedProduct, flightHash, selectedProduct[0].ProductTypeDescription);

                } else {
                    this.handleFareSelection(e, true);
                }
            },

            handleFareSelection: function (e, dontCallUpsell) {
                this.emptyComponents();
                var _this = this;
                this.currentResults.appliedSearch.ShowAvailableOnlyUpgrades = false;
                _this.abortCurrentRequests();
                $("#lowest-revenue-banner-placeholder").empty();

                if (e && !dontCallUpsell && e.currentTarget.classList.contains("fare-select-button") && this.isUpSellActive()) {
                    this.handleUpSell(e);
                    return;
                }
                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    e.preventDefault();
                    return;
                }
                //UA.Utilities.safeSessionStorage.setItem("SortBy", JSON.stringify(UA.Common.SortDropdown.getValue()));
                this.elements.resultsHeaderSegmentContainer.addClass("fare-selecting");

                var fareEl;
                if ((e.currentTarget).className == "economy-select-button" || (e.currentTarget).className == "economy-plus-select-button price") {
                    var flightBlock = $(e.currentTarget).closest('.flight-block');                    
                    fareEl = flightBlock.find('.fare-option-revised');
                    if (this.isUpSellActive() && this.upSellFlightElement) {
                        fareEl = this.upSellFlightElement;
                    }
                } else {
                    fareEl = ($('#hdnShowFareSelectButton').val() === 'True') ? $(e.currentTarget).closest('.fare-option-revised') : $(e.currentTarget);
                }

                $('#hdnAdditionalUpgradeId').val("");
                
                this.currentResults.appliedSearch.SkipAwardCalendar = false;
                var flightHash = fareEl.parents('.flight-block').data('flight-hash'),
                    flightData = this.getFlightByHash(flightHash),
                    select = fareEl.data('flight-select'),
                    selectedProductId = select.CellIdSelected,
                    fareDescription = fareEl.data('column-description'),
                    currentTripIndex = parseInt(this.elements.currentTripIndex.val(), 10),
                    _this = this;
                if (fareEl.find('.fsr-flt-plus-points').length > 0) {
                    $('#hdnAdditionalUpgradeId').val(fareEl.find('.fsr-flt-plus-points').data('upgradeprice-id'))
                }
                else if (fareEl.data('upgrade-price-id')) {
                    $('#hdnAdditionalUpgradeId').val(fareEl.data('upgrade-price-id'))
                }
                var showallresults = _this.getShowAllResultsCookie();
                var tripindex = _this.getTripIndex();
                var selectedflightcount = fareEl.parents('.flight-block').data('trip-index');
                if (showallresults) {
                    var tripsShowAllResults = JSON.parse(UA.Utilities.safeSessionStorage.getItem("tripsShowAllResults"));
                    var pagesize = parseInt($('#AllflightfeaturePageSize').val()) || 35;
                    if (tripsShowAllResults != null && tripsShowAllResults.length > tripindex && selectedflightcount > pagesize) {
                        tripsShowAllResults[tripindex].flightscrollpos = flightHash;
                    } else {
                        tripsShowAllResults[tripindex].flightscrollpos = '';
                    }
                    UA.Utilities.safeSessionStorage.setItem("tripsShowAllResults", JSON.stringify(tripsShowAllResults));
                }
                var selectedProducts = _.filter(flightData.Products, function (product) {
                    return product.ProductId === selectedProductId;
                });

                if ($(e.currentTarget).data('productcode') && $(e.currentTarget).data('productcode') != '' && selectedProducts != null && selectedProducts.length > 0) {
                    $('#hdnSelectedEPlusProductCode').val($(e.currentTarget).data('productcode'));
                    $('#hdnSelectedEPlusBundleId').val($(e.currentTarget).data('bundleid'));
                    $('#hdnSelectedEPlusFlightHash').val(flightHash);
                    $('#hdnSelectedEPlusProductId').val(selectedProducts[0].ProductId);
                }

                var usedSearchType;
                if (this.currentResults.SearchType === "rt") { usedSearchType = "roundTrip"; }
                else if (this.currentResults.SearchType === "mc") { usedSearchType = "multiCity"; }
                else if (this.currentResults.SearchType === "ow") { usedSearchType = "oneWay"; }
                else { usedSearchType = this.currentResults.SearchType; }
                var selectedAdditionalUpgrade = null;
                if (selectedProducts[0].AdditionalUpgrades && selectedProducts[0].AdditionalUpgrades.length > 0)
                    selectedAdditionalUpgrade = selectedProducts[0];
                if (!selectedAdditionalUpgrade && flightData.Connections)
                {
                    _.each(flightData.Connections, function (connection) {
                        _.each(connection.Products, function (product) {
                            if (product.FareFamily === selectedProducts[0].FareFamily)
                            {
                                if (!selectedAdditionalUpgrade && product.AdditionalUpgrades && product.AdditionalUpgrades.length > 0)
                                    selectedAdditionalUpgrade = product;
                            }

                        });
                    });
                }
                if (!selectedProducts[0].IsElf || currentTripIndex > 1) {
                    if ((selectedProducts[0].ProductCode != null
                                && (selectedProducts[0].ProductCode == 'LGT'))
                                && ($("#hdnNewBELite").val() == 'True') && currentTripIndex == 1) {

                        $("#confirm-with-restriction-fare-modal-placeholder").modal({
                            overlayClose: true,
                            onOpen: function (dialog) {
                                dialog.container.addClass('modal-loading bundle-compare-ajax');
                                $.modal.setPosition();
                                dialog.overlay.show();
                                dialog.container.show();
                                dialog.container.loader();

                                var bcContentRequest = _this.fetchBasicEconomyFare(dialog, flightHash);
                                $.when(bcContentRequest)
                                    .done(function (response) {
                                        var products = _this.findWithRestrictionUpgradeProduct(flightData.Products);
                                        var firstChargeBagFee = {
                                            selectedProduct: selectedProducts[0],
                                            upgradeProduct: products,
                                            flightHash: flightHash,
                                            flightData: flightData,
                                            fareDescription: fareDescription,
                                            solutionSetId: select.SolutionSetId,
                                            cartId: select.CartId,
                                            columnData: (products != null) ? [_this.currentResults.Trips[0].Columns[0], _this.currentResults.Trips[0].Columns[products.Index - 1]] : [_this.currentResults.Trips[0].Columns[0], _this.currentResults.Trips[0].Columns[1]],
                                            hasMultipleElfEligibleTravelers: _this.getElfEligibleTravelerCount() > 1,
                                            isAward: _this.currentResults.IsAward,
                                            searchType: usedSearchType,
                                            BELiteBagFee: response.data.BELiteFirstChkBagFee != null ? UA.Utilities.formatting.formatMoney(response.data.BELiteFirstChkBagFee, response.data.BELiteBagFeeCurrency, 0): null,
                                            EconomyBagFee: response.data.EconomyFirstChkBagFee != null ? UA.Utilities.formatting.formatMoney(response.data.EconomyFirstChkBagFee, response.data.EconomyBagFeeCurrency, 0) : null,
                                        }
                                        dialog.data.html(_this.templates.confirmWithRestrictionFare(firstChargeBagFee)).show();
                                        dialog.container.loader('destroy');
                                        dialog.container.removeClass('modal-loading');
                                        $.modal.update();
                                        _this.handleFootnoteClick();

                                        dialog.data.show();
                                    })
                            .fail(function (response) {
                                dialog.container.loader('destroy');
                                $.modal.close();
                            });
                            }
                        });
                    }
                    else if ((selectedProducts[0].ProductType == 'ECO-BASIC' && !selectedProducts[0].IsElf  && (selectedProducts[0].ProductCode))
                        && ($("#hdnNewBELite").val() == 'True') && currentTripIndex == 1) {
                        var serviceUrl = this.elements.container.data('beliteurl');
                        $.ajax({
                            type: "POST",
                            url: serviceUrl,
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            data: JSON.stringify({
                                cartId: this.currentResults.appliedSearch.CartId,
                                flightHash: flightHash,
                                productCode: selectedProducts[0].ProductCode,
                            }),
                            success: function (response) {
                                if (response != null) {
                                    if (response.data != null) {
                                        var products = _this.findWithRestrictionUpgradeProduct(flightData.Products);
                                        var firstChargeBagFee = {
                                            selectedProduct: selectedProducts[0],
                                            upgradeProduct: products,
                                            flightHash: flightHash,
                                            flightData: flightData,
                                            fareDescription: fareDescription,
                                            solutionSetId: select.SolutionSetId,
                                            cartId: select.CartId,
                                            columnData: (products != null) ? [_this.currentResults.Trips[0].Columns[0], _this.currentResults.Trips[0].Columns[1]] : [_this.currentResults.Trips[0].Columns[0], _this.currentResults.Trips[0].Columns[1]],
                                            hasMultipleElfEligibleTravelers: _this.getElfEligibleTravelerCount() > 1,
                                            isAward: _this.currentResults.IsAward,
                                            searchType: usedSearchType,
                                            BELiteBagFee: response.data.BELiteFirstChkBagFee != null ? UA.Utilities.formatting.formatMoney(response.data.BELiteFirstChkBagFee, response.data.BELiteBagFeeCurrency, 0) : null,
                                            EconomyBagFee: response.data.EconomyFirstChkBagFee != null ? UA.Utilities.formatting.formatMoney(response.data.EconomyFirstChkBagFee, response.data.EconomyBagFeeCurrency, 0) : null,
                                            isChangeFeeWaived: _this.isChangeFeeWaived(),
                                            isBEChangeFeePolicyActiveFlag: _this.isBEChangeFeePolicyActive(),
                                            beModelData: response.data.BEModelContent,
                                            productCode: selectedProducts[0].ProductCode,
                                            IsIBEType: true,
                                        }
                                        if (_this.templates.confirmIbeFare != null) {
                                            $("#confirm-ibe-fare-modal-placeholder").modal({
                                                onOpen: function (dialog) {
                                                    dialog.overlay.show();
                                                    dialog.container.show();
                                                    dialog.data.html(_this.templates.confirmIbeFare(firstChargeBagFee)).show();
                                                    UA.UI.reInit($(dialog.container));
                                                    $.modal.update();
                                                    _this.handleFootnoteClick();
                                                }
                                            });
                                        }
                                        else {
                                            _this.handleFareSelected(fareDescription, flightHash, flightData, select);
                                        }
                                    }
                                }
                            }
                        });
                    }
                    else if ((selectedProducts[0].FareFamily == "ECONOMY-UPGRADEABLE-MUA" || selectedProducts[0].FareFamily == "ECONOMY-UPGRADEABLE-GPU" || selectedProducts[0].FareFamily == "ECONOMY-UPGRADEABLE-RPU")
                        && selectedAdditionalUpgrade && $('#hdnUPPDoubleUpgradeEnabled').val() == "True"
                        && this.isSelectedProductWaitlisted(selectedProducts[0])) {
                        var uppData = selectedAdditionalUpgrade.AdditionalUpgrades[0];
                        uppData.CellIdSelected = select.CellIdSelected,
                        uppData.flightHash = flightHash;
                        uppData.fareDescription = fareDescription;
                        uppData.solutionSetId = select.SolutionSetId;
                        uppData.cartId = select.CartId;
                        uppData.Origin = this.currentResults.Trips[0].Origin;
                        uppData.Destination = this.currentResults.Trips[0].Destination;
                        uppData.IsMixedUpgrade = selectedProducts[0].IsMixedUpgrade;

                        if (uppData.IsWaitList)
                        {
                            uppData.ModelTitle = $('#hdnUPPDoubleUpgradeWaitlistTitle').val().format(selectedAdditionalUpgrade.DescriptionWaitlist);
                        }
                        else {
                            uppData.ModelTitle = $('#hdnUPPDoubleUpgradeAvailableTitle').val().format(selectedAdditionalUpgrade.DescriptionWaitlist);
                        }
                        if (selectedProducts[0].IsMixedUpgrade && selectedProducts[0].FlightDetails && selectedProducts[0].FlightDetails.length > 1) {
                            selectedProducts[0].FlightDetails = _.filter(selectedProducts[0].FlightDetails, function (flights) {
                                return flights.UpgradeEligible == true;
                            });

                            if (selectedProducts[0].FlightDetails && selectedProducts[0].FlightDetails.length > 0) {
                                uppData.Origin = selectedProducts[0].FlightDetails[0].Origin;
                                uppData.Destination = selectedProducts[0].FlightDetails[0].Destination;
                            }
                        }

                        $("#upp-double-upgrade-modal-placeholder").modal({
                            onOpen: function (dialog) {
                                dialog.overlay.show();
                                dialog.container.show();
                                dialog.data.html(_this.templates.uppdoubleupgrade(uppData)).show();
                                UA.UI.reInit($(dialog.container));
                                $.modal.update();
                            }
                        });
                    }
                    else {
                        // this.handleFareSelected(fareDescription, flightHash, flightData, select, selectedProducts[0].IsElf);
                        this.handleFareSelected(fareDescription, flightHash, flightData, select);
                    }
                }
                else {
                    var obj = {
                        selectedProduct: selectedProducts[0],
                        upgradeProduct: this.findElfUpgradeProduct(flightData.Products),
                        flightHash: flightHash,
                        flightData: flightData,
                        fareDescription: fareDescription,
                        solutionSetId: select.SolutionSetId,
                        cartId: select.CartId,
                        columnData: [this.currentResults.Trips[0].Columns[0], this.currentResults.Trips[0].Columns[1]],
                        hasMultipleElfEligibleTravelers: this.getElfEligibleTravelerCount() > 1,
                        SSAforBEActive: ($('#hdnIsSellingSeatAssignmentForBEActive').val() === "True"), //does not check for and BE because flight has not been selected yet
                        isAward: this.currentResults.IsAward,
                        searchType: usedSearchType,
                        isChangeFeeWaived: _this.isChangeFeeWaived(),
                        isBEChangeFeePolicyActiveFlag: _this.isBEChangeFeePolicyActive(),
                    };

                    $("#confirm-elf-fare-modal-placeholder").modal({
                        onOpen: function (dialog) {
                            dialog.overlay.show();
                            dialog.container.show();
                            //dialog.container.loader();
                            dialog.data.html(_this.templates.confirmElfFare(obj)).show();
                            UA.UI.reInit($(dialog.container));
                            $.modal.update();
                        }
                    });

                    $('.goback').click(function () {
                        var footmarkID = $(this).data('val');
                        $(this).css('display', 'none');
                        $('#' + footmarkID).focus();
                    });
                    $('.linkfoot').click(function () {
                        $('.footnotes .goback').css('display', 'none');
                        var dfootnote = $(this).data('val');
                        var footmarkID = $(this).attr('id');
                        $('#' + dfootnote + '> .goback').css('display', 'block');
                        $('#' + dfootnote + '> .goback').data('val', footmarkID);
                        $('#' + dfootnote).focus();
                    });
                    $('.linkfoot').focus(function () {
                        $(this).prev().find('a').css('outline', '2px dotted #003057');
                    });
                    $('.linkfoot').blur(function () {
                        $(this).prev().find('a').css('outline', 'none');
                    });
                }
            },
            isChangeFeeWaived: function () {
                var isChangeFeeWaiverActive = $('#hdnIsChangeFeeWaiverActive').val();
                if (isChangeFeeWaiverActive && isChangeFeeWaiverActive === "True") {
                    return true;
                }
                return false;
            },
            isBEChangeFeePolicyActive: function () {
                return ($('#hdnIsBEChangeFeePolicyActive').val() === "True");
            },
            emptyComponents: function () {
                    UA.Utilities.removeLinearLoader(this.elements.resultsStopNonStopLoader);
                    this.elements.resultsStopNonStopLoaderText.hide();
            },

            isSelectedProductWaitlisted: function (products) {
                var enableUPPModal = false;

                if (products.UpgradeInfo && products.UpgradeInfo.Waitlisted)
                    enableUPPModal = true;
                else {
                    var upgradeWaitlisted = _.filter(products.FlightDetails, function (flights) {
                        return (flights.UpgradeEligible == true && flights.UpgradeDescription == "Upgrade waitlist");
                    });
                    if (products.IsMixedUpgrade && upgradeWaitlisted && upgradeWaitlisted.length > 0)
                        enableUPPModal = true;
                }
                return enableUPPModal;
            },

            getElfEligibleTravelerCount: function () {
                return this.currentResults.appliedSearch.numberOfTravelers - this.currentResults.appliedSearch.numOfLapInfants;
            },
            findElfUpgradeProduct: function (products) {
                return _.chain(products)
                    .filter(function (product) {
                        return product.CabinType === "Coach"
                    })
                    .filter(function (product) {
                        return !product.IsElf
                    })
                    .find(function (product) {
                        return product.Prices.length
                    })
                    .value();
            },
            fetchFareCompareContents: function (dialog) {
                var serviceUrl = this.elements.container.data('getfarecomparecontenturl');
                var request = $.ajax({
                    url: serviceUrl + "?cartid=" + this.currentResults.appliedSearch.CartId,
                    type: "GET",
                    contentType: "application/json; charset=utf-8",
                    traditional: true,
                    cache: false
                });
                return request;
            },
            fetchShopSearchCount: function (data) {
                var serviceUrl = this.elements.container.data('getsearchcounturl');
                if (data && data.Trips && data.Trips.length > 0 && data.Trips[0].Origin && data.Trips[0].Destination) {
                    var request = $.ajax({
                        url: serviceUrl + "?Origin=" + data.Trips[0].Origin + "&Destination=" + data.Trips[0].Destination
                                        + "&DepartureDate=" + data.Trips[0].DepartDate,
                        type: "GET",
                        contentType: "application/json; charset=utf-8",
                        traditional: true,
                        cache: false
                    });
                    return request;
                }
            },
            fetchBasicEconomyFare: function (dialog, flightHash) {
                var serviceUrl = this.elements.container.data('beliteurl');
                var request = $.ajax({
                    type: "POST",
                    url: serviceUrl,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify({
                        cartId: this.currentResults.appliedSearch.CartId,
                        flightHash: flightHash
                    }),
                    traditional: true,
                    cache: false
                })
                return request;
            },
            findWithRestrictionUpgradeProduct: function (products) {
                return _.chain(products)
                    .filter(function (product) {
                        return product.CabinType === "Coach"
                    })
                    .filter(function (product) {
                        return !(product.ProductCode != null && (product.ProductCode == 'LGT' || (product.IBEType)))
                    })
                    .find(function (product) {
                        return product.Prices.length
                    })
                    .value();
            },
            // handleFareSelected: function (fareDescription, flightHash, flightData, select, selectProdsIsElf) {
            handleFareSelected: function (fareDescription, flightHash, flightData, select) {
                var _this = this;

                var totalTrips = parseInt($("#hdnTotalTrips").val(), 10),
                    currentTripIndex = parseInt(this.elements.currentTripIndex.val(), 10),
                    selectedFlight;

                if (!select || select.CartId === '' || select.CellIdSelected === '') {
                    return;
                }
                safeSessionStorage.setItem("SolutionSetId" + (currentTripIndex + 1), select.SolutionSetId);
                safeSessionStorage.setItem("CellIdSelected" + (currentTripIndex + 1), select.CellIdSelected);
                if (showFsrTips && fsrTipsShowNonstopSuggestion && !fsrTipsPhase2) {
                    this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
                }
                this.currentResults.appliedSearch.SelectedUpgradePrices = $('#hdnAdditionalUpgradeId').val();
                if (this.currentResults.appliedSearch.SelectedUpgradePrices) {
                    this.currentResults.appliedSearch.SelectedUpgradePrices = this.currentResults.appliedSearch.SelectedUpgradePrices.split(',');
                }
                if (currentTripIndex < totalTrips) {

                    //clear results, calendar, header
                    this.elements.calendarContainer.empty();
                    if (showFsrTips) {
                        if (fsrTipsPhase2) {
                            this.emptyFsrTips();
                        } else {
                            this.elements.resultsHeaderSegmentNearbyCities.empty();
                            this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
                            this.elements.resultsHeaderSegmentBetterOffers.empty();
                        }
                    }
                    this.elements.resultsHeaderSegmentContainer.empty();
                    this.elements.resultsHeaderSegmentFareDisclaimerContainer.empty();
                    this.elements.resultsHeaderContainer.empty();
                    this.elements.resultsContainer.empty();
                    this.elements.filterSortContainer.empty();
                    this.resetTabbedFWHeader();
                    if ($('#editFlightSearch').val() != "True") {
                        this.elements.newSearchContainer.hide();
                    }
                    this.elements.resetNotificationContainer.empty();

                    //reset toggle
                    var editFlightSearch = $('#editFlightSearch').val() == 'True' ? true : false;
                    var isMultiCity = this.currentResults.SearchType.toLowerCase() == "multicity" ? true : false;
                    if (!editFlightSearch) {
                        $('.btn-show-new-search').toggler('hideContent');
                    }
                    else if (isMultiCity) {
                        if (UA.Booking.EditSearch) {
                            UA.Booking.EditSearch.resetLofs();
                        }
                    }

                    select.UpgradeType = this.currentResults.SelectableUpgradesOriginal;
                    select.SearchFilters = this.currentResults.appliedSearch.SearchFilters;
                    select.awardTravel = this.currentResults.appliedSearch.awardTravel;
                    select.FlexibleDaysBefore = this.currentResults.appliedSearch.FlexibleDaysBefore;
                    select.FlexibleDaysAfter = this.currentResults.appliedSearch.FlexibleDaysAfter;
                    select.SortType = this.currentResults.appliedSearch.SortType;
                
                    
                    selectedFlight = {
                        Flights: [flightData],                        
                        FareDescription: fareDescription,
                        TripIndex: currentTripIndex,
                        SearchType: this.currentResults.SearchType,
                        Origin: this.currentResults.Trips[0].OriginDecoded,
                        Destination: this.currentResults.Trips[0].DestinationDecoded,
                        DepartDate: this.currentResults.Trips[0].DepartDateFormat,
                        DepartDateShort: this.currentResults.Trips[0].DepartDateShort,
                        SelectedFlightIndex: currentTripIndex - 1,
                        FlightHash: flightHash,
                        IsSelectedFlight: true,
                        appliedSearch: this.currentResults.appliedSearch,                        
                        PreviousCellIdSelected: '',
                        PreviousSolutionSetId: ''
                    };                    
                    selectedFlight.Flights[0].Products = _.filter(selectedFlight.Flights[0].Products, function (product) {
                        return product.ProductId == select.CellIdSelected;
                    });
                    this.selectedFlightsProduct[currentTripIndex - 1] = selectedFlight.Flights[0].Products[0];
                    _.forEach(selectedFlight.Flights[0].Connections, function (conn, index) {
                        selectedFlight.Flights[0].Connections[index].Products = _.filter(selectedFlight.Flights[0].Connections[index].Products, function (product) {
                            return product.ProductId == select.CellIdSelected;
                        });
                    });

                    if (selectedFlight.Flights[0].Products && selectedFlight.Flights[0].Products.length > 0) {
                        selectedFlight.FareDescription = selectedFlight.Flights[0].Products[0].ProductTypeDescription;
                    }

                    $.extend(selectedFlight, select);                    
                    $.extend(this.currentResults.appliedSearch, select);
                    if (this.selectedFlights.length > 0) {
                        selectedFlight.PreviousCellIdSelected = this.selectedFlights[this.selectedFlights.length - 1].CellIdSelected;
                        selectedFlight.PreviousSolutionSetId = this.selectedFlights[this.selectedFlights.length - 1].SolutionSetId;
                    }                    
                    this.currentResults.appliedSearch.CalendarOnly = false;
                    this.currentResults.appliedSearch.CalendarDateChange = '';
                    this.selectedFlights[currentTripIndex - 1] = selectedFlight;

                    this.elements.currentTripIndex.val(currentTripIndex + 1);
                    this.setFilterFromTrip(select.SearchFilters, currentTripIndex + 1);

                    //show selected flight at top
                    this.renderSelectedFlight(currentTripIndex - 1);
                    this.showLineLoader(true);
                    $(window).scrollTop(0);

                    this.pushOrLoadResults(currentTripIndex + 1);
                } else {
                    var isReshopPath = false;
                    isReshopPath = this.currentResults.appliedSearch.isReshopPath;
                    var RTICartId, RTISolutionSetId, RTICellIdSelected;
                    RTICartId = select.CartId;
                    RTISolutionSetId = select.SolutionSetId;
                    RTICellIdSelected = select.CellIdSelected;
                    this.selectedFlightsProduct[currentTripIndex - 1] = _.filter(flightData.Products, function (product) {
                        return product.ProductId == select.CellIdSelected;
                    })[0];
                    this.selectedFlights[currentTripIndex - 1] = select;
                    if (!_this.currentResults.appliedSearch.awardTravel) {
                        this.clearFSRResults();
                    }
                    this.showLineLoader(true);
                    var _this = this;
                    select.EPlusProductCode = $('#hdnSelectedEPlusProductCode').val();
                    select.EPlusBundleId = $('#hdnSelectedEPlusBundleId').val();
                    select.EPlusFlightHash = $('#hdnSelectedEPlusFlightHash').val();
                    select.EPlusProductId = $('#hdnSelectedEPlusProductId').val();
                    select.SelectedUpgradePrices = $('#hdnAdditionalUpgradeId').val();
                    if (select.SelectedUpgradePrices) {
                        select.SelectedUpgradePrices = select.SelectedUpgradePrices.split(',');
                    }
                    var shopSelectRequest = this.fetchFlightResults(select);
                    $.when(shopSelectRequest)
                        .done(function (response) {
                            if (!_this.ShopMainErrorCheck(response)) {
                                _this.NavigateToRTIPage(isReshopPath, RTICartId, RTISolutionSetId, RTICellIdSelected);
                            }
                        });
                    // Maxymiser calling logic
                    //var _this = this;
                    //if ((selectProdsIsElf == undefined || selectProdsIsElf.toString() == "false") && (!isReshopPath)) {
                    //    // If select button is not Basic Economy then async call to generate a generation response in Maxymiser
                    //    $.ajax({
                    //        type: 'GET',
                    //        url: 'FlightShopping/gencall',
                    //        success: function (data) {
                    //            if (data == "variant1")
                    //                _this.NavigateToTIPage(RTICartId, RTISolutionSetId, RTICellIdSelected);
                    //            else
                    //                _this.NavigateToRTIPage(isReshopPath, RTICartId, RTISolutionSetId, RTICellIdSelected);
                    //        },
                    //        error: function (err) {
                    //            _this.NavigateToRTIPage(isReshopPath, RTICartId, RTISolutionSetId, RTICellIdSelected);
                    //        }
                    //    });
                    //}
                    //else {
                    //    this.NavigateToRTIPage(isReshopPath, RTICartId, RTISolutionSetId, RTICellIdSelected);
                    //}
                }
            },
            // Method to transfer to Traveler Info page
            //NavigateToTIPage(paramCartId, paramSolutionSetId, paramCellIdSelected) {
            //    var placeholder = $('#divTmp'),
            //        postHtml;
            //    var serviceUrl = this.elements.container.data('travelerinfourl');
            //    // Clear page and show loading indicator
            //    this.elements.calendarContainer.empty();
            //    this.elements.resultsHeaderSegmentNearbyCities.empty();
            //    this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
            //    this.elements.resultsHeaderSegmentBetterOffers.empty();
            //    this.elements.resultsHeaderSegmentContainer.empty();
            //    this.elements.resultsHeaderContainer.empty();
            //    this.elements.resultsContainer.empty();
            //    this.elements.filterSortContainer.empty();
            //    this.elements.newSearchContainer.empty();
            //    this.elements.resultsFooter.empty();
            //    this.elements.selectedFlightContainer.empty();
            //    this.elements.resetNotificationContainer.empty()
            //    $('.cart-container').empty();
            //    this.showPageLoader();

            //    // Create hidden form and submit
            //    postHtml = "<form id='travInfoForm' action =" + serviceUrl + " method='post'> \n" +
            //        " <input id='CartId' name='CartID' type='hidden' value='" + paramCartId + "'> \n" +
            //        " <input id='SolutionSetId' name='SolutionSetId' type='hidden' value='" + paramSolutionSetId + "'> \n" +
            //        " <input id='CellIdSelected' name='CellIdSelected' type='hidden' value='" + paramCellIdSelected + "'> \n" +

            //        " <input class='hdn-selected-product' type='hidden' value='' id='BundlesSelected[0].ProductId' name='BundlesSelected[0].ProductId'> \n" +
            //        " <input class='hdn-selected-product' type='hidden' value='' id='BundlesSelected[0].SolutionSetId' name='BundlesSelected[0].SolutionSetId'> \n" +
            //        " <input class='hdn-selected-product' type='hidden' value='' id='BundlesSelected[0].SubProductCode' name='BundlesSelected[0].SubProductCode'> \n" +
            //        " <input class='hdn-selected-product' type='hidden' value='' id='BundlesSelected[0].ProductCode' name='BundlesSelected[0].ProductCode'> \n" +

            //        " <input type='hidden' name='hasCutOffWarning' value='False'> \n" +
            //        " <input type='hidden' name='hasCutOffError' value='False'> \n" +
            //        " <input type='hidden' name='ReviewFlightBtnContinue' value='ReviewFlightContinue'> \n" +
            //        " <input type='hidden' name='IsElf' value='False'> \n" +
            //        " </form>";

            //    placeholder.html(postHtml);

            //    $('#travInfoForm').submit();
            //},
            NavigateToRTIPage: function (paramisReshopPath, paramCartId, paramSolutionSetId, paramCellIdSelected) { 
                var reviewFlightURL = this.elements.container.data('reviewurl');
                var reviewUpgradeURL = this.elements.container.data('reviewupgradeurl');

                if (!paramisReshopPath && this.currentResults.appliedSearch.UpgradeType != null &&
                    this.currentResults.appliedSearch.UpgradeType.toUpperCase() == 'POINTS' && this.IsUpgradeExist()) {
                    this.NavigateToNextPage(paramisReshopPath, paramCartId, paramSolutionSetId, paramCellIdSelected, reviewUpgradeURL);
                }
                else {
                    this.NavigateToNextPage(paramisReshopPath, paramCartId, paramSolutionSetId, paramCellIdSelected, reviewFlightURL);
                }
            },
            IsUpgradeExist: function(){
                var isUpgradeExist = _.some(this.selectedFlightsProduct, function (product) {
                    if (product)
                        return product.ProductType.toUpperCase().indexOf("UPGRADE") !== -1 ? true : false;
                    else
                        return false;
                });
                if (!isUpgradeExist && this.currentResults.SelectedTrips != null && this.currentResults.SelectedTrips.length > 0)
                    isUpgradeExist = _.some(this.currentResults.SelectedTrips, function (trip) {
                        if (trip != null && trip.Flights != null && trip.Flights.length == 1) {
                            return _.some(trip.Flights[0].Products, function (product) {
                                return (product.ProductSubtype != "NonExistingProductPlaceholder" && (product.ProductType.toUpperCase().indexOf("UPGRADE") !== -1 ? true : false));
                            });
                        }
                    });
                return isUpgradeExist
            },
            NavigateToNextPage: function (paramisReshopPath, paramCartId, paramSolutionSetId, paramCellIdSelected, serviceUrl) {
                if (UA && UA.ReShop && UA.ReShop.Login) {
                    UA.ReShop.Login.handleSignInModalPopUp();
                }
                //set hiddend field in result view
                if ($('#hdnIsSignedIn').val() === "False" && ($('#hdnAward').val() === "True" || $('#hdnUpgrade').val() === "True")) {
                    if (paramisReshopPath) {

                        if (paramCartId === null || paramCartId === 'undefined' || paramCartId === '' || paramCellIdSelected === null || paramCellIdSelected === 'undefined' || paramCellIdSelected === '') {
                            //go to Reshop Advance page
                            var advanceSearchPageUrl = $('#hdnreshopadvancesearchUrl').val();
                            //create hidden form and submit
                            var placeholder = $('#divTmp'),
                                postHtml;
                            postHtml = '<form id="ReshopAdvanceSearchForm" method="post" action="' + advanceSearchPageUrl + '"> \n' +
                                '</form>';
                            placeholder.html(postHtml);
                            $('#ReshopAdvanceSearchForm').submit();
                            return;
                        }
                        this.showFullPageLoader();
                        setTimeout(function () {
                            var _this = UA.Booking.FlightSearch;
                            var IsLogInRequiredVal = _this.IsLogInRequired({
                                CellIdSelected: paramCellIdSelected,
                                SolutionSetId: paramSolutionSetId,
                                CartId: paramCartId,
                                IncludeLmx: _this.currentResults.appliedSearch.IncludeLmx,
                                AwardTravel: _this.currentResults.appliedSearch.awardTravel
                            });
                            _this.hidePageLoader();
                            if (IsLogInRequiredVal) {
                                //go to RTI page
                                _this.postToReviewTrip({
                                    postUrl: serviceUrl,
                                    cellIdSelected: paramCellIdSelected,
                                    solutionSetId: paramSolutionSetId,
                                    cartId: paramCartId,
                                    ePlusProductCode: $('#hdnSelectedEPlusProductCode').val(),
                                    ePlusBundleId: $('#hdnSelectedEPlusBundleId').val(),
                                    ePlusFlightHash: $('#hdnSelectedEPlusFlightHash').val(),
                                    ePlusProductId: $('#hdnSelectedEPlusProductId').val(),
                                    additionalUpgradeIds: $('#hdnAdditionalUpgradeId').val()
                                });
                            } else {
                                $("#selectCartId").val(paramCartId);
                                $("#selectSolutionSetId").val(paramSolutionSetId);
                                $("#selectCellIdSelected").val(paramCellIdSelected);
                                $('#includeLmx').val(_this.currentResults.appliedSearch.IncludeLmx);
                                _this.showLoginModal();
                                this.hideLineLoader();
                            }
                        }, 0);
                    } else {
                        $("#selectCartId").val(paramCartId);
                        $("#selectSolutionSetId").val(paramSolutionSetId);
                        $("#selectCellIdSelected").val(paramCellIdSelected);
                        $('#includeLmx').val(this.currentResults.appliedSearch.IncludeLmx);
                        this.showLoginModal();
                        this.hideLineLoader();
                    }
                } else {
                    //go to RTI page
                    this.postToReviewTrip({
                        postUrl: serviceUrl,
                        cellIdSelected: paramCellIdSelected,
                        solutionSetId: paramSolutionSetId,
                        cartId: paramCartId,
                        ePlusProductCode: $('#hdnSelectedEPlusProductCode').val(),
                        ePlusBundleId: $('#hdnSelectedEPlusBundleId').val(),
                        ePlusFlightHash: $('#hdnSelectedEPlusFlightHash').val(),
                        ePlusProductId: $('#hdnSelectedEPlusProductId').val(),
                        additionalUpgradeIds: $('#hdnAdditionalUpgradeId').val()
                    });
                }
            },

            handleUpgradeFareSelection: function (e) {
                //try {

                var flightBlock = $(e.currentTarget).closest('.flight-block');
                //var fareEl = flightBlock.find('.fare-option-revised');
                var flightHash = flightBlock.data('flight-hash');
                var flightData = this.getFlightByHash(flightHash);
                //var select = flightData.data('flight-select');
                var paramisReshopPath, paramCartId, paramSolutionSetId, paramCellIdSelected;

                this.NavigateToRivewUpgrade(paramisReshopPath, paramCartId, paramSolutionSetId, paramCellIdSelected);
                //} catch (e) {
    
                //}
            },

            IsShopbookingDetailsSuccess: function (paramCartId, paramSolutionSetId, paramCellIdSelected) {
                var _this = this;
                var IsSuccess = false;
               
                var CartId = paramCartId;
                var SolutionSetId = paramSolutionSetId;
                var CellIdSelected = paramCellIdSelected;
               
                var IncludeLmx = this.currentResults.appliedSearch.IncludeLmx;
                var AwardTravel = this.currentResults.appliedSearch.awardTravel;
                var CorporateBooking = this.currentResults.appliedSearch.corporateBooking;
                //var EPlusProductCode = $('#hdnSelectedEPlusBundleId').val();
                //var EPlusBundleId = $('#hdnSelectedEPlusBundleId').val();
                //var EPlusFlightHash = $('#hdnSelectedEPlusFlightHash').val();
                //var EPlusProductId = $('#hdnSelectedEPlusProductId').val();
                //var SelectedUpgradePrices = $('#hdnAdditionalUpgradeId').val();
                var serviceUrl = $('#hdnshopbookingdetailsonlastfsr').val();
               
                var params = { "CellIdSelected": CellIdSelected, "SolutionSetId": SolutionSetId, "CartId": CartId, "AwardTravel": AwardTravel, "CorporateBooking": CorporateBooking };

                var Request = $.ajax({
                    type: "POST",
                    url: serviceUrl, //UA.Utilities.url('/Booking/FlightShopping/ShopBookingDetailsOnLastFSR'),
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    data: JSON.stringify(params)
                });

                $.when(Request).done(function (response) {
                    if (response != null) {
                        if (response.Status == "success") {
                            IsSuccess = true;
                            _this.shopBookingDetailsError = response.Error;
                        }
                    }
                });
                return IsSuccess;
            },

            IsLogInRequired: function (params) {
                var IsLogInRequiredVal = false;
                var serviceUrl = $('#hdnevenexchangecheckurl').val();
                if (this.evenExchangeCheckRequest && this.evenExchangeCheckRequest.readyState !== 4) {
                    this.evenExchangeCheckRequest.abort();
                }

                this.evenExchangeCheckRequest = $.ajax({
                    type: "POST",
                    url: serviceUrl,
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    dataType: "json",
                    data: JSON.stringify(params)
                });

                $.when(this.evenExchangeCheckRequest).done(function (response) {
                    if (response != null) {
                        if (response.data != null) {
                            IsLogInRequiredVal = response.data;
                        }
                    }
                });
                return IsLogInRequiredVal;
            },
            showContentMessage: function () {

                try {
                    var trpIndex = this.getTripIndex();
                    var DepartDate = this.currentResults.appliedSearch.Trips[trpIndex].DepartDate;
                    var currentTripDepartdate = UA.Utilities.formatting.tryParseDate(DepartDate);

                    if (currentTripDepartdate.getFullYear() === 2019) {
                        $("#fsr-2019").show();
                        $("#fsr-2020").hide();
                    }
                    else {
                        $("#fsr-2019").hide();
                        $("#fsr-2020").show();
                    }

                } catch (e) {

                }
            },
            showFullPageLoader: function () {

                this.showPageLoader(true);

            },
            showPageLoader: function (isFullPage) {
                if (!isFullPage) {
                    this.showLineLoader();
                }
                else if (this.currentResults.appliedSearch.isReshopPath && isFullPage) {
                    this.lineLoaderAnimation('.load', '.bar');
                }
                else {
                    //This code will be called only when Page is loaded (isFullPage == true). In all other user cases it is handled above in IF
                    var pageLoader = this.elements.fullPageLoader,
                    spinnerEl = pageLoader.find('.spinner-container'),
                    messageKey = (this.selectedFlights[0] && this.selectedFlights[0].isElf ? 'wifi' : 'eplus').toLowerCase();

                    if (!spinnerEl.data('ua-loader')) {
                        spinnerEl.loader({
                            zIndex: 9999
                        });
                    }

                    pageLoader.find('.loading-content-msg').removeClass('active');
                    pageLoader.find('.msg-' + messageKey).addClass('active');

                    pageLoader.show();
                }
            },
            showLineLoader: function (isLoadWithMessage) {
                if (this.templates && this.templates.lineLoader && (this.lineLoaderState == "" || this.lineLoaderState == "loaded")) {
                    var data = {};
                    this.lineLoaderState = "loading";
                    data.loadingState = this.lineLoaderState;
                    if (this.currentResults.appliedSearch.awardTravel) {
                        // showLineLoader existing code will just prepare line loader and Accessibility Markup
                        //if it is award then it will process markup witch is replica of this.elements.partialPageLoader markup
                        //and it will do same as how we use to process inside showPageLoader pageLoader == this.elements.lineLoaderMessageSection
                        $("#flight-result-elements").addClass("loading");
                        isLoadWithMessage = true;
                        var pageLoader = this.elements.awardLineLoaderMessageSection,
                        messageKey = (this.selectedFlights[0] && this.selectedFlights[0].isElf ? 'wifi' : 'eplus').toLowerCase();
                        if (pageLoader) {
                            pageLoader.find('.loading-content-msg').removeClass('active');
                            pageLoader.find('.msg-' + messageKey).addClass('active');
                        }
                    }
                    data.loadWithMessage = isLoadWithMessage;
                    this.elements.lineLoaderSection.html(this.templates.lineLoader(data));
                    this.lineLoaderAnimation('.load', '.bar');
                }
                if (isLoadWithMessage) {
                    if (this.currentResults.appliedSearch.awardTravel) {
                        this.elements.awardLineLoaderMessageSection.parent().show();
                    }
                    else {
                        this.elements.lineLoaderMessageSection.show();
                    }
                }
            },
            hideLineLoader: function () {
                if (this.templates && this.templates.lineLoader && (this.lineLoaderState == "" || this.lineLoaderState == "loading")) {
                    var data = {};
                    this.lineLoaderState = "loaded";
                    data.loadingState = this.lineLoaderState;
                    this.elements.lineLoaderSection.html(this.templates.lineLoader(data));
                }
                if (this.currentResults.appliedSearch.awardTravel) {
                    $("#flight-result-elements").removeClass("loading");
                    this.elements.awardLineLoaderMessageSection.parent().hide();
                }
                else {
                    this.elements.lineLoaderMessageSection.hide();
                }
            },
            clearLineLoaderSection: function () {
                this.lineLoaderState = "";
                this.elements.lineLoaderSection.empty();
            },
            farematrixshowLineLoader: function () {
                var data = [];
                this.lineLoaderState = "loading";
                data.loadingState = this.lineLoaderState;
                this.elements.farematrixlineLoaderSection.html(this.templates.lineLoader(data));
                this.lineLoaderAnimation('.load', '.bar');
              },
            farematrixclearLineLoader: function () {
                this.lineLoaderState = "";
                this.elements.farematrixlineLoaderSection.empty();
            },
            //Award Calender Loader
            awardCalenderShowLineLoader: function () {
                var data = [];
                this.lineLoaderState = "loading";
                data.loadingState = this.lineLoaderState;
                data.AwardCalender = true;
                $("#award-lineloader-section").html(this.templates.lineLoader(data));
                this.lineLoaderAnimation('#fl-award-calendar-loader', '.bar');
            },
            awardCalenderClearLineLoader: function () {
                this.lineLoaderState = "";
                $("#award-lineloader-section").empty();
            },
            showFareMatrixLineLoader: function () {
                try {
                    var _this = this;

                    var fakeFareMatrixLoadData = { "loading": true }

                    if (_this.currentResults && _this.currentResults.Trips != null && _this.currentResults.Trips.length > 0 && _this.currentResults.Trips[0].OriginDecoded && _this.currentResults.Trips[0].DestinationDecoded) {
                        fakeFareMatrixLoadData = { "loading": true, "Trips": [{ "OriginDecoded": _this.currentResults.Trips[0].OriginDecoded, "DestinationDecoded": _this.currentResults.Trips[0].DestinationDecoded }] }
                    } else if (_this.currentResults && _this.currentResults.appliedSearch && _this.currentResults.appliedSearch.Trips != null && _this.currentResults.appliedSearch.Trips.length > 0 &&
                        _this.currentResults.appliedSearch.Trips[0].Origin && _this.currentResults.appliedSearch.Trips[0].Destination) {
                        fakeFareMatrixLoadData = { "loading": true, "Trips": [{ "OriginDecoded": _this.currentResults.appliedSearch.Trips[0].Origin, "DestinationDecoded": _this.currentResults.appliedSearch.Trips[0].Destination }] }
                    }
                    $('#fare-matrix-section').html(_this.templates.fareMatrixCalendar(fakeFareMatrixLoadData));
                    this.lineLoaderAnimation('.load', '.bar');

                } catch (e) {

                }
            },
            hideFareMatrixClearLineLoader: function () {
                    var fareMatrixLineLoaderSeaction = $('#fare-matrix-lineloader-section');

                    if (fareMatrixLineLoaderSeaction) {
                        fareMatrixLineLoaderSeaction.html("");
                    }
            },
            resetTabbedFWHeader: function () {
                this.elements.tabbedFareWheelSection.empty();
                this.clearLineLoaderSection();
                this.elements.plusMinusThreeDayLinkSection.empty();
                this.elements.singleColumnFSRLowFareSection.empty();
            },
            lineLoaderAnimation: function (container, bar) {
                //this function will be converted into plugin and will be placed at global level.
                var _this = this;
                $(bar).animate({ left: $(container).width() }, 1000, function () {
                    $(bar).css("left", -($(bar).width()) + "px");
                    _this.lineLoaderAnimation(container, bar);
                });
            },
            showFilterLoader: function () {
                $(".newfilters_nonstopdiv").addClass("visuallyhidden");
                $(".newfilters_stopdiv").addClass("visuallyhidden");
                var FilterLoader = $(".newfilters"),
                   spinnerEl = FilterLoader.find('.spinner-container');

                if (!spinnerEl.data('ua-loader')) {
                    spinnerEl.loader({
                        zIndex: 9999
                    });
                }
                FilterLoader.show();
            },
            showStopsLoader: function () {
                var pageLoader = $("#fl-stopsresults-loader-partial"),
                    spinnerEl = pageLoader.find('.spinner-container');

                if (!spinnerEl.data('ua-loader')) {
                    spinnerEl.loader({
                        zIndex: 9999
                    });
                }
                pageLoader.find('.loading-message').show();
                pageLoader.show();
            },
            hidePageLoader: function (clearRenderHold) {

                if (!this.renderHold || clearRenderHold) {
                    $('.fl-results-loader').hide();
                    this.setRenderHold(false);
                }

                var _this = this;
                if (this.currentResults.appliedSearch.awardTravel) {
                    setTimeout(function () {
                        _this.hideLineLoader();
                    }, 600);
                }
            },
            setRenderHold: function (value) {
                this.renderHold = value;
            },
            handleFareWheelChange: function (e) {
                e.preventDefault();
                this.elements.tabbedFareWheelSection.empty();
                var newSelectDay = $(e.currentTarget),
                    selectDay = newSelectDay.data('select-day');

                if (!selectDay) {
                    return;
                }
                if (showFsrTips) {
                    if (fsrTipsPhase2) {
                        this.emptyFsrTips();
                    } else {
                        this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
                        this.elements.resultsHeaderSegmentNearbyCities.empty();
                        this.elements.resultsHeaderSegmentBetterOffers.empty();
                    }
                }

                $('.fare-wheel-item').removeClass('search-day');
                newSelectDay.addClass('search-day');

                var isMultiCity = this.currentResults.SearchType.toLowerCase() == "multicity" ? true : false;
                if ($('#editFlightSearch').val() == 'True' && isMultiCity) {
                    if (UA.Booking.EditSearch) {
                        UA.Booking.EditSearch.resetLofs();
                    }
                }
                this.changeSelectDayFW(selectDay, newSelectDay.data('select-id'));
                $("html, body").animate({
                    scrollTop: 0
                });
            },
            handleUpgradeTypeChange: function (e) {

                var upgradeType = $('[name="UpgradeTypeSelection"]:checked').val();
                this.changeUpgradeType(upgradeType);
                $('.dropdown-upgrade-type-trigger').dropdown('destroy');
            },
            changeUpgradeType: function (upgradeType) {
                var searchInput = {};
                this.showPageLoader();
                this.currentResults.appliedSearch.UpgradeType = upgradeType;
                searchInput = this.currentResults.appliedSearch;
                searchInput.InitialShop = true;
                if (this.selectedFlights !== null && this.selectedFlights.length > 0) {
                    searchInput = this.selectedFlights[this.selectedFlights.length - 1];
                    searchInput.UpgradeType = upgradeType;
                }
                //151525
                if (this.currentResults.appliedSearch !== null) {
                    searchInput.Trips = this.currentResults.appliedSearch.Trips;
                    searchInput.CellIdSelected = this.currentResults.appliedSearch.CellIdSelected;
                }
                //129940
                searchInput.SelectableUpgradesOriginal = this.currentResults.SelectableUpgradesOriginal;
                if (searchInput.appliedSearch) {
                    searchInput.appliedSearch.SelectableUpgradesOriginal = this.currentResults.SelectableUpgradesOriginal;
                }

                var isMultiCity = this.currentResults.SearchType.toLowerCase() == "multicity" ? true : false;
                if ($('#editFlightSearch').val() == 'True' && isMultiCity) {
                    if (UA.Booking.EditSearch) {
                        UA.Booking.EditSearch.resetLofs();
                    }
                }
                //151525
                this.loadFlightResults(searchInput);
            },
            handleUpdateTravelersClick: function (e) {
                e.preventDefault();

                var travelerData = {},
                    originalTravelerData = {},
                    numOfAdults = parseInt($('#lofNumOfAdults').val(), 10),
                    numOfSeniors = parseInt($('#lofNumOfSeniors').val(), 10),
                    numOfChildren01 = parseInt($('#lofNumOfChildren01').val(), 10),
                    numOfChildren02 = parseInt($('#lofNumOfChildren02').val(), 10),
                    numOfChildren03 = parseInt($('#lofNumOfChildren03').val(), 10),
                    numOfChildren04 = parseInt($('#lofNumOfChildren04').val(), 10),
                    numOfInfants = parseInt($('#lofNumOfInfants').val(), 10),
                    numOfLapInfants = parseInt($('#lofNumOfLapInfants').val(), 10);

                originalTravelerData = {
                    numOfAdults: parseInt(this.currentResults.appliedSearch.numOfAdults, 10),
                    numOfChildren01: parseInt(this.currentResults.appliedSearch.numOfChildren01, 10),
                    numOfChildren02: parseInt(this.currentResults.appliedSearch.numOfChildren02, 10),
                    numOfChildren03: parseInt(this.currentResults.appliedSearch.numOfChildren03, 10),
                    numOfInfants: parseInt(this.currentResults.appliedSearch.numOfInfants, 10),
                    numOfLapInfants: parseInt(this.currentResults.appliedSearch.numOfLapInfants, 10),
                    numOfSeniors: parseInt(this.currentResults.appliedSearch.numOfSeniors, 10),
                    numOfTravelers: parseInt(this.currentResults.appliedSearch.numberOfTravelers, 10)
                };

                travelerData = {
                    numOfAdults: numOfAdults,
                    numOfChildren01: numOfChildren01,
                    numOfChildren02: numOfChildren02,
                    numOfChildren03: numOfChildren03,
                    numOfChildren04: numOfChildren04,
                    numOfInfants: numOfInfants,
                    numOfLapInfants: numOfLapInfants,
                    numOfSeniors: numOfSeniors
                };

                travelerData.numberOfTravelers = this.getTravelerTotal(travelerData);

                if (!_.isEqual(originalTravelerData, travelerData)) {
                    this.changeTravelers(travelerData);
                }

                return;
            },
            changeTravelers: function (travelerData) {
                this.showPageLoader();

                this.currentResults.appliedSearch.numOfAdults = travelerData.numOfAdults;
                this.currentResults.appliedSearch.numOfChildren01 = travelerData.numOfChildren01;
                this.currentResults.appliedSearch.numOfChildren02 = travelerData.numOfChildren02;
                this.currentResults.appliedSearch.numOfChildren03 = travelerData.numOfChildren03;
                this.currentResults.appliedSearch.numOfChildren04 = travelerData.numOfChildren04;
                this.currentResults.appliedSearch.numOfInfants = travelerData.numOfInfants;
                this.currentResults.appliedSearch.numOfLapInfants = travelerData.numOfLapInfants;
                this.currentResults.appliedSearch.numOfSeniors = travelerData.numOfSeniors;
                this.currentResults.appliedSearch.numberOfTravelers = travelerData.numberOfTravelers;


                this.currentResults.appliedSearch.InitialShop = true;
                this.currentResults.appliedSearch.CartId = '';
                this.currentResults.appliedSearch.CellIdSelected = '';
                this.currentResults.appliedSearch.SolutionSetId = '';
                this.currentResults.appliedSearch.cabinSelection = '';
                this.currentResults.appliedSearch.EditSearch = false;

                //clear results, calendar, header
                this.elements.calendarContainer.empty();
                if (showFsrTips) {
                    if (fsrTipsPhase2) {
                        this.emptyFsrTips();
                    } else {
                        this.elements.resultsHeaderSegmentNearbyCities.empty();
                        this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
                        this.elements.resultsHeaderSegmentBetterOffers.empty();
                    }
                }
                this.elements.resultsHeaderSegmentContainer.empty();
                this.elements.resultsHeaderSegmentFareDisclaimerContainer.empty();
                this.elements.resultsHeaderContainer.empty();
                this.elements.resultsContainer.empty();
                this.elements.filterSortContainer.empty();
                this.elements.selectedFlightContainer.empty();
                this.elements.resetNotificationContainer.empty();

                UA.Booking.EditSearch.changeTravelers(travelerData);
                var trpIndex = this.getTripIndex();

                if (travelerData.numOfAdults > 0 || travelerData.numOfSeniors > 0 && this.currentResults.SearchFilters.IsUnaccompaniedMinor) {
                    var trip = this.currentResults.appliedSearch.Trips[trpIndex];
                    trip.nonStop = true;
                    trip.oneStop = true;
                    trip.twoPlusStop = true;
                }

                if (travelerData.numOfAdults == 0 && (travelerData.numOfLapInfants > 0 || travelerData.numOfInfants > 0) && travelerData.numOfSeniors == 0) {
                    $('#flightSearch').submit();
                } else if (travelerData.numberOfTravelers == 0) {
                    $('#flightSearch').submit();
                } else if (travelerData.numOfAdults == 0 && travelerData.numOfSeniors == 0 && (travelerData.numOfChildren02 > 0 || travelerData.numOfChildren03 > 0 || travelerData.numOfChildren04 > 0) && this.currentResults.appliedSearch != null && this.currentResults.appliedSearch.travelwPet > 0) {
                    var formChildren = $("#flightSearch");
                    formChildren.append("<input type='hidden' name='NumberOfPets' id='NumberOfPets' value='" + this.currentResults.appliedSearch.NumberOfPets + "' />");
                    formChildren.append("<input type='hidden' name='TravelwPet' id='TravelwPet' value='1' />");
                    $('#flightSearch').submit();
                } else if ((travelerData.numOfAdults == 0 && travelerData.numOfSeniors == 0 && (travelerData.numOfChildren03 > 0 || travelerData.numOfChildren02 > 0)) && this.currentResults.appliedSearch != null && this.currentResults.appliedSearch.IsUnAccompaniedMinor !== true) {
                    $('#flightSearch').submit();
                } else {
                    this.loadFlightResults(this.currentResults.appliedSearch);
                }
            },
            getTravelerTotal: function (travelersObj) {
                var total = 0,
                prop;
                for (prop in travelersObj) {
                    if (travelersObj.hasOwnProperty(prop)) {
                        total += travelersObj[prop];
                    }
                }
                return total;
            },
            changeSelectDayFW: function (day, id) {

                var currentTripIndex, previousTripIndex, selectedFlt, item, tag,
                    search = {};
                this.currentResults.appliedSearch.CalendarDateChange = '';
                this.currentResults.appliedSearch.FareWheelOrCalendarCall = true;
                // checking whether or not startFlightrecommendation should be called
                if ($('#hdnFlightRecommendationActive').val() == 'True' && this.currentResults.appliedSearch.searchTypeMain && this.currentResults.appliedSearch.searchTypeMain.toLowerCase() != "multicity") {
                    this.currentResults.appliedSearch.StartFlightRecommendation = true;
                }
                //this.currentResults.appliedSearch.CartId = '';
                this.currentResults.appliedSearch.EditSearch = false;

                //Bug 549009 - Defaulting FareWheel to user's cabin type selection
                var param = null;
                try {
                    param = UA.Utilities.readCookie("SearchInput");
                }
                catch (exception) {
                    param = null;
                }
                if (param != null) 
                {
                    //Bug 783161 -  Business/First Unrestricted fares are not displayed on FSR page when user changes search date from farewheel
                    if (this.currentResults.appliedSearch.cabinSelection == "FIRST-FLEXIBLE" || this.currentResults.appliedSearch.cabinSelection == "ECONOMY-FLEXIBLE" || this.currentResults.appliedSearch.cabinSelection == "FIRST-UNRESTRICTED" || this.currentResults.appliedSearch.cabinSelection == "ECONOMY-UNRESTRICTED")
                    {
                        this.currentResults.appliedSearch.cabinSelection = this.currentResults.appliedSearch.cabinSelection;
                    }
                    else
                        this.currentResults.appliedSearch.cabinSelection = param.cabinType == "businessFirst" ? "FIRST" : "ECONOMY";
                }
                this.currentResults.appliedSearch.SortType = 'price_low';                
                //this.currentResults.SortType = 'price_low';
                var trpIndex = this.getTripIndex();
                this.currentResults.appliedSearch.Trips[trpIndex].nonStop = true;
                this.currentResults.appliedSearch.Trips[trpIndex].oneStop = true;
                this.currentResults.appliedSearch.Trips[trpIndex].twoPlusStop = true;
                this.currentResults.appliedSearch.Trips[trpIndex].nonStopOnly = false;

                if (this.selectedFlights.length > 0) {
                    search.flexible = false;
                    search.CalendarDateChange = day;
                    currentTripIndex = parseInt($("#hdnCurrentTripIndex").val(), 10);
                    previousTripIndex = currentTripIndex - 1;
                    selectedFlt = this.selectedFlights[previousTripIndex - 1];
                    search.CartId = $('#CartId').val();
                    if (this.globalFWResponse != null && this.globalFWResponse.data != null && this.globalFWResponse.data.LastSolutionSetId != null){
                        search.SolutionSetId = this.globalFWResponse.data.LastSolutionSetId; //selectedFlt.SolutionSetId;
                    } else {
                        search.SolutionSetId = null;
                    }
                    search.CellIdSelected = id; //selectedFlt.CellIdSelected;
                    search.CalendarOnly = false;
                    search.CabinType = this.currentResults.appliedSearch.cabinType;
                    if (this.currentResults.appliedSearch.Revise == true)
                        search.Revise = this.currentResults.appliedSearch.Revise;
                    item = this.currentResults.appliedSearch.Trips[currentTripIndex - 1];
                    tag = '#cartTrip_' + (currentTripIndex);
                    $(tag).find('.cart-trip-name').find('strong').text(item.Origin + ' - ' + item.Destination + ' ' + formatDate(search.CalendarDateChange));
                    var stopnonstopfeature = $('#StopNonStop').val() == "True" ? true : false;
                    if (stopnonstopfeature && this.currentResults.SearchType != null && this.currentResults.SearchType.toLowerCase() != "multicity") {
                        search.Trips = this.currentResults.appliedSearch.Trips;
                    } else {
                        search.Trips = null;
                    }

                    if (!(this.currentResults.SearchType == "mc" || this.currentResults.SearchType == "multiCity")) {

                        item.DepartDate = day;
                        var itemLength = this.currentResults.appliedSearch.Trips.length;
                        if (currentTripIndex === 1) {

                            $('#DepartDate').val(formatDateNoWeekDay(item.DepartDate));
                        } else if (currentTripIndex === itemLength) {
                            $('#ReturnDate').val(formatDateNoWeekDay(item.DepartDate));
                            if ($('#editFlightSearch').val() == 'True') {
                                $('#ReturnDateForEditSearch').val(formatDateNoWeekDay(item.DepartDate));
                            }
                        }
                    } else {
                        if ($('#editFlightSearch').val() == 'True') {
                            item.DepartDate = day;
                            $("#TripsForEditSearch_" + (currentTripIndex - 1) + "__DepartDate").val(formatDateNoWeekDay(item.DepartDate));
                        }
                    }

                    if ($('#ReviseLinkDepartDate').val() == "True") {
                        safeSessionStorage.setItem("SolutionSetId" + currentTripIndex, search.SolutionSetId);
                        safeSessionStorage.setItem("CellIdSelected" + currentTripIndex, search.CellIdSelected);
                    }
                    this.isFareWheelClick = true;
                    this.pushOrLoadResults(currentTripIndex, true, search);
                    this.isFareWheelClick = false;
                } else {

                    this.currentResults.appliedSearch.flexible = false;
                    //this.currentResults.appliedSearch.CartId = '';
                    this.currentResults.appliedSearch.Trips[0].DepartDate = day;
                    item = this.currentResults.appliedSearch.Trips[0];

                    this.currentResults.appliedSearch.InitialShop = true;

                    if (!(this.currentResults.SearchType == "mc" || this.currentResults.SearchType == "multiCity")) {
                        item.DepartDate = day;
                        $.each(this.currentResults.appliedSearch.Trips, function (index, item) {
                            var departDate, tag;
                            if (index === 0) {

                                $('#DepartDate').val(formatDateNoWeekDay(item.DepartDate));
                            } else {
                                if (isFinite(new Date(item.DepartDate))) {
                                    $('#ReturnDate').val(formatDateNoWeekDay(item.DepartDate));
                                } else {
                                    $('#ReturnDate').val(item.DepartDate);
                                }
                                if ($('#editFlightSearch').val() == 'True') {
                                    if (isFinite(new Date(item.DepartDate))) {
                                        $('#ReturnDateForEditSearch').val(formatDateNoWeekDay(item.DepartDate));
                                    } else {
                                        $('#ReturnDateForEditSearch').val(item.DepartDate);
                                    }
                                }
                            }
                        });
                    } else {
                        if ($('#editFlightSearch').val() == 'True') {
                            item.DepartDate = day;
                            $.each(this.currentResults.appliedSearch.Trips, function (index, item) {
                                if (index === 0) {
                                    $("#TripsForEditSearch_" + index + "__DepartDate").val(formatDateNoWeekDay(item.DepartDate));
                                }
                            });
                        }
                    }

                    tag = '#cartTrip_1';
                    $(tag).find('.cart-trip-name').find('strong').text(item.Origin + ' - ' + item.Destination + ' ' + formatDate(item.DepartDate));

                    this.pushOrLoadResults(1, true);
                }
            },
            checkIfReshopApiIscalled: function (trips, currentTripIndex) {
                var isReshopApiCalled = false;
                var isBookingPath = true;
                if (UA && UA.ReShop && UA.ReShop.Login) {
                    isBookingPath = false;
                }
                if (isBookingPath == true) {
                    isReshopApiCalled = true;
                } else {
                    $.each(trips, function (index, item) {
                        if (index < (currentTripIndex - 1)) {
                            if (item.ChangeType == 0 || item.ChangeType == 1) {
                                isReshopApiCalled = true;
                            }
                        }
                    });
                }
                return isReshopApiCalled;
            },
            clearAwardBanner: function () {
                this.currentResults.lowestRevenueResponse = null;
                $('#lowest-revenue-banner-placeholder').html("");
            },
            changeSelectDay: function (day) {
                var currentTripIndex, previousTripIndex, selectedFlt, item, tag,
                    search = {};
                this.clearAwardBanner();
                if (this.currentResults && this.currentResults.appliedSearch) {
                    this.oldIsAwardCalendarNonstop = this.currentResults.appliedSearch.IsAwardCalendarNonstop;
                }
                this.currentResults.appliedSearch.CalendarDateChange = '';
                this.currentResults.appliedSearch.FareWheelOrCalendarCall = false;
                if ($('#hdnFlightRecommendationActive').val() == 'True' && this.currentResults.appliedSearch.searchTypeMain && this.currentResults.appliedSearch.searchTypeMain.toLowerCase() != "multicity") {
                    this.currentResults.appliedSearch.StartFlightRecommendation = true;
                }
                //this.currentResults.appliedSearch.CartId = '';
                this.currentResults.appliedSearch.EditSearch = false;
                this.currentResults.appliedSearch.SkipAwardCalendar = true;
                search.awardTravel = this.currentResults.appliedSearch.awardTravel;
                if ($('#filter-onlynonstop').is(':checked')) {
                    this.currentResults.appliedSearch.nonStopOnly = 1;
                    this.currentResults.appliedSearch.calendarStops = 0;
                } else {
                    this.currentResults.appliedSearch.nonStopOnly = 0;
                    this.currentResults.appliedSearch.calendarStops = 4;
                }
                var isReshopApiCalled = this.checkIfReshopApiIscalled(this.currentResults.appliedSearch.Trips, parseInt($("#hdnCurrentTripIndex").val(), 10));
                var isMultiCity = (this.currentResults.SearchType ? this.currentResults.SearchType.toLowerCase() : this.currentResults.appliedSearch.searchTypeMain.toLowerCase()) == "multicity" ? true : false;
                var totalTrips = this.currentResults.appliedSearch.Trips;

                if (isReshopApiCalled && this.selectedFlights.length > 0) {
                    if ($('#editFlightSearch').val() == 'True' && isMultiCity) {
                        if (UA.Booking.EditSearch) {
                            UA.Booking.EditSearch.resetLofs();
                        }
                    }

                    search.flexible = false;
                    search.CalendarDateChange = day;
                    currentTripIndex = parseInt($("#hdnCurrentTripIndex").val(), 10);
                    previousTripIndex = currentTripIndex - 1;
                    selectedFlt = this.selectedFlights[previousTripIndex - 1];
                    search.CartId = $('#CartId').val();
                    search.SolutionSetId = selectedFlt.SolutionSetId;
                    search.CellIdSelected = selectedFlt.CellIdSelected;
                    search.CalendarOnly = false;
                    item = this.currentResults.appliedSearch.Trips[currentTripIndex - 1];
                    item.DepartDate = day;
                    $('#ReturnDate').val(formatDateNoWeekDay(item.DepartDate));
                    if ($('#editFlightSearch').val() == 'True') {
                        $('#ReturnDateForEditSearch').val(formatDateNoWeekDay(item.DepartDate));
                        if (isMultiCity) {
                            $("#TripsForEditSearch_" + (currentTripIndex - 1) + "__DepartDate").val(formatDateNoWeekDay(item.DepartDate));
                        }
                    }
                    tag = '#cartTrip_' + (currentTripIndex);
                    $(tag).find('.cart-trip-name').find('strong').text(item.Origin + ' - ' + item.Destination + ' ' + formatDate(search.CalendarDateChange));
                    search.Trips = null;

                    this.pushOrLoadResults(currentTripIndex, true, search);
                } else {

                    if (this.currentResults.appliedSearch.flexible) {

                        this.currentResults.appliedSearch.SortType = 'price_low';
                        this.currentResults.SortType = 'price_low';
                        this.currentResults.appliedSearch.CalendarDateChange = day;
                        this.currentResults.appliedSearch.SolutionSetId = $('#SolutionSetId').val();
                        this.currentResults.appliedSearch.CartId = $('#CartId').val();
                        this.currentResults.appliedSearch.flexible = false;
                        this.elements.calendarContainer.empty();
                        $('#fl-calendar-wrap').removeClass('flexible-calendar');
                    }

                    search.tripLength = this.currentResults.appliedSearch.tripLength;
                    search.multicityTripLength = this.currentResults.appliedSearch.MultiCityTripLength;
                    var count = 1;
                    var isReshopPath = false;
                    var isFlexibleAward = this.currentResults.appliedSearch.flexibleAward;
                    var isFlexible = this.currentResults.appliedSearch.CalendarOnly;
                    var isAwardTravel = this.currentResults.appliedSearch.awardTravel;
                    var isSearchFromFareMatrix = this.currentResults.appliedSearch.fareMatrix;
                    if (isAwardTravel) {
                        var param = null;
                        try {
                            param = UA.Utilities.readCookie("SearchInput");
                        }
                        catch (exception) {
                            param = null;
                        }
                        if (param != null) this.currentResults.appliedSearch.cabinSelection = param.awardCabinType == "awardBusinessFirst" ? "BUSINESS" : param.awardCabinType == "awardFirst" ? "FIRST" : "ECONOMY";
                    }
                    if (UA && UA.ReShop && UA.ReShop.Login) {
                        isReshopPath = true;
                    }

                    //insert return date for valid search for promotion calendar availibility 517842 SHD
                    if (totalTrips.length == 2 && !isReshopPath && !isFlexible && !isFlexibleAward && !isAwardTravel && !isSearchFromFareMatrix) {
                        var newDepartDate = new Date(UA.Utilities.formatting.tryParseDate(day));
                        var currentReturnDate = new Date(UA.Utilities.formatting.tryParseDate(this.currentResults.appliedSearch.Trips[1].DepartDate));
                        if (newDepartDate > currentReturnDate) {
                            var newReturnDate = UA.Utilities.formatting.addDays(newDepartDate, search.tripLength);
                            this.currentResults.appliedSearch.Trips[1].DepartDate = formatDateNoWeekDay(newReturnDate);
                            $('#ReturnDateForEditSearch').val(formatDateNoWeekDay(newReturnDate));
                        }
                    }

                    if ($('#editFlightSearch').val() == 'True' && isMultiCity) {
                        if (UA.Booking.EditSearch) {
                            UA.Booking.EditSearch.resetLofs();
                        }
                    }


                    $.each(this.currentResults.appliedSearch.Trips, function (index, item) {
                        var departDate, tag;
                        if (isReshopPath) {
                            if ((item.ChangeType === 0 || item.ChangeType === 1) && count == 1) {
                                item.DepartDate = day;
                                $('#DepartDate').val(formatDateNoWeekDay(item.DepartDate));
                                count++;
                            }
                        } else {
                            if (index === 0) {
                                item.DepartDate = day;
                                $('#DepartDate').val(formatDateNoWeekDay(item.DepartDate));
                                if ($('#editFlightSearch').val() == 'True' && isMultiCity) {
                                    $("#TripsForEditSearch_" + index + "__DepartDate").val(formatDateNoWeekDay(item.DepartDate));
                                }
                            } else if (isFlexibleAward || isFlexible || isAwardTravel) {
                                departDate = new Date(day);
                                if (isMultiCity) {
                                    departDate.setDate(departDate.getDate() + search.multicityTripLength[index - 1]);
                                } else {
                                    departDate.setDate(departDate.getDate() + search.tripLength);
                                }

                                day = formatShortDate(departDate);
                                item.DepartDate = day;
                                if (isFinite(new Date(item.DepartDate))) {
                                    $('#ReturnDate').val(formatDateNoWeekDay(item.DepartDate));
                                } else {
                                    $('#ReturnDate').val(item.DepartDate);
                                }
                                if ($('#editFlightSearch').val() == 'True') {
                                    if (isFinite(new Date(item.DepartDate))) {
                                        $('#ReturnDateForEditSearch').val(formatDateNoWeekDay(item.DepartDate));
                                    } else {
                                        $('#ReturnDateForEditSearch').val(item.DepartDate);
                                    }
                                    if (isMultiCity) {
                                        if (isFinite(new Date(item.DepartDate))) {
                                            $("#TripsForEditSearch_" + index + "__DepartDate").val(formatDateNoWeekDay(item.DepartDate));
                                        } else {
                                            $("#TripsForEditSearch_" + index + "__DepartDate").val(item.DepartDate);
                                        }
                                    }
                                }
                            }
                        }
                        tag = '#cartTrip_' + (index + 1);
                        $(tag).find('.cart-trip-name').find('strong').text(item.Origin + ' - ' + item.Destination + ' ' + formatDate(item.DepartDate));

                    });
                    this.elements.filterSortContainer.empty();
                    this.currentResults.appliedSearch.CalendarOnly = false;
                    if (!isAwardTravel) {
                        this.resetTabbedFWHeader();
                        this.showLineLoader(true);
                    }
                    this.pushOrLoadResults(1, true);
                }
            },
            getFlightByHash: function (hash) {
                return _.filter(this.currentResults.Trips[0].Flights, function (flight) {
                    return flight.Hash == hash;
                })[0];
            },
            getSelectedFlightByHash: function (hash) {
                return _.filter(this.selectedFlights, function (flight) {
                    return flight.Flights[0].Hash == hash;
                })[0].Flights[0];
            },
            handleUpgradeWaitlistTooltip: function (e) {
                e.stopPropagation();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    e.preventDefault();
                    return;
                }

                UA.UI.Tooltip.init($(e.currentTarget), {
                    overwrite: false,
                    content: {
                        text: $('#tooltip-fare-upgrade-waitlist').clone()
                    },
                    show: {
                        event: e.type,
                        ready: true
                    }
                }, 'close-delegated', null, false, e);

            },
            handleUpgradeAvailableTooltip: function (e) {
                e.stopPropagation();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    e.preventDefault();
                    return;
                }

                UA.UI.Tooltip.init($(e.currentTarget), {
                    overwrite: false,
                    content: {
                        text: $('#tooltip-fare-upgrade-available').clone()
                    },
                    show: {
                        event: e.type,
                        ready: true
                    }
                }, 'close-delegated', null, false, e);

            },
            handleUpgradeEligibleTooltip: function (e) {
                e.stopPropagation();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    e.preventDefault();
                    return;
                }

                var target = $(e.currentTarget);
                UA.UI.Tooltip.init(target, {
                    overwrite: false,
                    content: {
                        text: target.hasClass('booking-code-m') ? $('#tooltip-fare-upgrade-1k-eligible').clone() : $('#tooltip-fare-upgrade-eligible').clone()
                    },
                    show: {
                        event: e.type,
                        ready: true
                    }
                }, 'close-delegated', null, false, e);

            },
            handleUpgradeNotEligibleTooltip: function (e) {
                e.stopPropagation();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    e.preventDefault();
                    return;
                }

                UA.UI.Tooltip.init($(e.currentTarget), {
                    overwrite: false,
                    content: {
                        text: $('#tooltip-fare-upgrade-not-eligible').clone()
                    },
                    show: {
                        event: e.type,
                        ready: true
                    }
                }, 'close-delegated', null, false, e);

            },
            handleFareLockTooltip: function (e) {
                e.preventDefault();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    return;
                }

                UA.UI.Tooltip.init($(e.currentTarget), {
                    content: {
                        text: $('#tooltip-fare-lock-info').clone()
                    },
                    show: {
                        event: e.type,
                        ready: true
                    }
                }, 'default-delegated', null, false, e);

            },
            handleLmxIneligibleTooltip: function (e) {
                e.preventDefault();

                UA.UI.Tooltip.init($(e.currentTarget), {
                    content: {
                        text: true
                    },
                    style: {
                        classes: "tip-united lmx-ineligible-tooltip-content"
                    },
                    show: {
                        event: e.type,
                        ready: true
                    }
                }, 'default-delegated', null, false, e);

            },
            handleOnTimePerfTooltip: function (e) {
                var _this = this;
                e.preventDefault();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    return;
                }

                UA.UI.Tooltip.init($(e.currentTarget), {
                    suppress: false,
                    content: {
                        text: '',
                    },
                    position: {
                        at: 'top center',
                        my: 'bottom center',
                        adjust: {
                            method: 'shift flip'
                        },
                        effect: false
                    },
                    show: {
                        event: e.type,
                        ready: true
                    },
                    events: {
                        show: function (event, api) {

                            // Collect the relevant flight data.
                            var target = $(event.originalEvent.target),
                                postData = [],
                                fullPath = location.pathname.toLowerCase(),
                                serviceUrl = _this.elements.container.data('performanceurl'),
                                flightBlock = target.parents('.flight-block'),
                                isSelectedFlight = typeof flightBlock.data('selected-flight-index') !== 'undefined',
                                hash = flightBlock.data('flight-hash'),
                                    dataset;

                            dataset = !isSelectedFlight ? _this.getFlightByHash(hash) : _this.getSelectedFlightByHash(hash);

                            postData.push({
                                flightNumber: dataset.FlightNumber,
                                origin: dataset.Origin,
                                destination: dataset.Destination,
                                departureDateTime: dataset.DepartDateTime,
                                marketingCarrier: dataset.MarketingCarrier
                            });

                            if (dataset.Connections) {
                                _.each(dataset.Connections, function (flight) {
                                    postData.push({
                                        flightNumber: flight.FlightNumber,
                                        origin: flight.Origin,
                                        destination: flight.Destination,
                                        departureDateTime: flight.DepartDateTime,
                                        marketingCarrier: flight.MarketingCarrier
                                    });
                                });
                            }

                            api.set('content.text', $('<div class="tooltip-loading-container"/>').loader({
                                preset: 'tooltip'
                            }));

                            $.ajax({
                                url: serviceUrl,
                                type: 'POST',
                                cache: true,
                                contentType: "application/json",
                                dataType: 'json',
                                data: JSON.stringify(postData)

                            })
                                .then(
                                function (response) {
                                    var renderedContent = _this.templates.onTimePerformance(response.data);
                                    api.set('content.text', renderedContent);
                                },
                                function (xhr, status, error) {
                                    api.set('content.text', status + ': ' + error);
                                }
                                    );
                        }
                    }
                }, 'close-delegated', null, false, e);

            },
            handleFlightConnectionTooltip: function (e) {
                e.preventDefault();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    return;
                }

                var _this = this;
                UA.UI.Tooltip.init($(e.currentTarget), {
                    content: {
                        text: ''
                    },
                    show: {
                        event: e.type,
                        ready: true
                    },
                    position: {
                        at: 'top center',
                        my: 'bottom center',
                        target: 'event',
                        effect: false
                    },
                    events: {
                        show: function (event, api) {
                            var target = $(event.originalEvent.target),
                                flightBlock = target.parents('.flight-block'),
                                isSelectedFlight = typeof flightBlock.data('selected-flight-index') !== 'undefined',
                                hash = flightBlock.data('flight-hash'),
                                dataset = !isSelectedFlight ? _this.getFlightByHash(hash) : _this.getSelectedFlightByHash(hash);

                            api.set('content.text', _this.templates.flightConnectionTooltip(dataset));
                        }
                    }
                }, 'default-delegated', null, false, e);
            },
            handleAdvisoriesTooltip: function (e) {
                e.preventDefault();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    return;
                }

                var _this = this;
                UA.UI.Tooltip.init($(e.currentTarget), {
                    content: {
                        text: ''
                    },
                    show: {
                        event: e.type,
                        ready: true
                    },
                    position: {
                        target: 'event',
                        effect: false
                    },
                    events: {
                        show: function (event, api) {
                            var target = $(event.originalEvent.target),
                                flightBlock = target.parents('.flight-block'),
                                isSelectedFlight = typeof flightBlock.data('selected-flight-index') !== 'undefined',
                                hash = flightBlock.data('flight-hash'),
                                dataset = !isSelectedFlight ? _this.getFlightByHash(hash) : _this.getSelectedFlightByHash(hash),
                                connectionIndex = target.parents('.segment').data('connection-index'),
                                data = typeof connectionIndex !== 'undefined' ? dataset.Connections[connectionIndex] : dataset;

                            api.set('content.text', _this.templates.advisoriesTooltip(data));
                        }
                    }
                }, 'default-delegated', null, false, e);
            },
            handleMixedCabinTooltip: function (e) {
                var _this = this;
                e.preventDefault();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    return;
                }

                UA.UI.Tooltip.init($(e.currentTarget), {
                    overwrite: false,
                    content: {
                        text: ''
                    },
                    hide: {
                        delay: 20
                    },
                    position: {
                        target: $(e.currentTarget)
                    },
                    show: {
                        event: e.type,
                        ready: true
                    },
                    events: {
                        show: function (event, api) {
                            var target = $(e.currentTarget),
                                flightBlock = target.parents('.flight-block'),
                                isSelectedFlight = typeof flightBlock.data('selected-flight-index') !== 'undefined',
                                hash = flightBlock.data('flight-hash'),
                                dataset = !isSelectedFlight ? _this.getFlightByHash(hash) : _this.getSelectedFlightByHash(hash),
                                connectionIndex = target.parents('.segment').data('connection-index'),
                                data = typeof connectionIndex !== 'undefined' ? dataset.Connections[connectionIndex] : dataset,
                                prodIndex = target.data('product-index');

                            api.set('content.text', _this.templates.mixedCabinTooltip(data.Products[prodIndex]));
                        }
                    }
                }, 'default-delegated', null, false, e);

            },

            handleUpgradeTooltipV3: function (e) {

                var _this = this;
                e.preventDefault();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    return;
                }

                UA.UI.Tooltip.init($(e.currentTarget), {
                    overwrite: false,
                    content: {
                        text: ''
                    },
                    hide: {
                        delay: 20
                    },
                    position: {
                        target: $(e.currentTarget)
                    },
                    show: {
                        event: e.type,
                        ready: true
                    },
                    events: {
                        show: function (event, api) {
                            var target = $(e.originalEvent.target),
                                flightBlock = target.parents('.flight-block'),
                                isSelectedFlight = typeof flightBlock.data('selected-flight-index') !== 'undefined',
                                hash = flightBlock.data('flight-hash'),
                                dataset = !isSelectedFlight ? _this.getFlightByHash(hash) : _this.getSelectedFlightByHash(hash),
                                connectionIndex = target.parents('.connection-details').data('connection-index'),
                                data = typeof connectionIndex !== 'undefined' ? dataset.Connections[connectionIndex] : dataset,
                                prodIndex = target.data('product-index');
                                var product = $.extend(true, {}, data.Products[prodIndex]);
                                product.ShowAvailableOnlyUpgrades = _this.currentResults.appliedSearch.ShowAvailableOnlyUpgrades;
                                product.IsLOF = target.data("lof");
                                product.Origin = data.Origin;
                                product.Destination = data.Destination;
                                api.set('content.text', _this.templates.upgradeTooltipV3(product));
                        }
                    }
                }, 'default-delegated', null, false, e);

            },
            handleMixedUpgradeTooltip: function (e) {

                var _this = this;
                e.preventDefault();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    return;
                }

                UA.UI.Tooltip.init($(e.currentTarget), {
                    overwrite: false,
                    content: {
                        text: ''
                    },
                    hide: {
                        delay: 20
                    },
                    position: {
                        target: $(e.currentTarget)
                    },
                    show: {
                        event: e.type,
                        ready: true
                    },
                    events: {
                        show: function (event, api) {
                            var target = $(e.currentTarget),
                                flightBlock = target.parents('.flight-block'),
                                isSelectedFlight = typeof flightBlock.data('selected-flight-index') !== 'undefined',
                                hash = flightBlock.data('flight-hash'),
                                dataset = !isSelectedFlight ? _this.getFlightByHash(hash) : _this.getSelectedFlightByHash(hash),
                                connectionIndex = target.parents('.segment').data('connection-index'),
                                data = typeof connectionIndex !== 'undefined' ? dataset.Connections[connectionIndex] : dataset,
                                prodIndex = target.data('product-index');

                            api.set('content.text', _this.templates.mixedUpgradeTooltip(data.Products[prodIndex]));
                        }
                    }
                }, 'default-delegated', null, false, e);

            },
            handleFareCalendarTooltip: function (e) {
                e.preventDefault();
                var _this = this;
                UA.UI.Tooltip.init($(e.currentTarget), {
                    overwrite: false,
                    content: {
                        text: ''
                    },
                    hide: {
                        delay: 0
                    },
                    show: {
                        event: e.type,
                        ready: true
                    },
                    position: {
                        at: 'top center',
                        my: 'bottom center',
                        target: $(e.currentTarget)
                    },
                    events: {
                        show: function (event, api) {
                            var target = $(e.currentTarget),
                                isRoundTrip = _this.currentResults.SearchType === 'rt',
                                departDate = new Date(target.data('cal-date')), //#218100  
                                returnDate = null,
                                    data = {};

                            if (isRoundTrip) {
                                returnDate = new Date(departDate);
                                returnDate.setDate(returnDate.getDate() + _this.currentResults.appliedSearch.tripLength);
                                returnDate = UA.Utilities.formatting.formatShortDate(returnDate);
                            }

                            departDate = UA.Utilities.formatting.formatShortDate(departDate);

                            data = {
                                isRoundTrip: isRoundTrip,
                                returnDate: returnDate,
                                departDate: departDate
                            };
                            api.set('content.text', _this.templates.fareCalendarTooltip(data));
                            if (target.length > 0 && target.hasClass("donotdescribe")) {
                                target.removeAttr("aria-describedby");
                            }
                        }
                    }
                }, 'default-delegated', null, false, e);

            },
            handleLmxAccrualTooltip: function (e) {
                e.preventDefault();
                var _this = this;

                UA.UI.Tooltip.init($(e.currentTarget), {
                    content: {
                        text: ''
                    },
                    show: {
                        event: e.type,
                    },
                    position: {
                        at: 'top center',
                        my: 'bottom center',
                        adjust: {
                            method: 'shift flip'
                        },
                        effect: false
                    },
                    events: {
                        show: function (event, api) {
                            var target = $(event.originalEvent.target),
                                flightBlock = target.parents('.flight-block'),
                                isSelectedFlight = typeof flightBlock.data('selected-flight-index') !== 'undefined',
                                hash = flightBlock.data('flight-hash'),
                                dataset = !isSelectedFlight ? _this.getFlightByHash(hash) : _this.getSelectedFlightByHash(hash),
                                prodIndex = target.data('product-index');

                            api.set('content.text', _this.templates.lmxAccrualTooltip(dataset.Products[prodIndex]));
                        }
                    }
                }, 'close-delegated', null, false, e);

            },
            handleAwardCalendarRetryClick: function (e) {
                e.preventDefault();
                this.loadAwardCalendar(this.currentResults.appliedSearch);
            },
            handleAwardCalendarViewClick: function (e) {
                e.preventDefault();
                var el = $(e.currentTarget);

                if (el.hasClass('calendar-loading')) {
                    return;
                }

                var requestedCalendarType = el.data('calendar-type');

                this.currentResults.appliedSearch.AwardCalendarType = requestedCalendarType;
                this.currentResults.appliedSearch.isChangeWeek = true;
                this.loadAwardCalendar(this.currentResults.appliedSearch);
            },
            handleCalendarCabinTypeChange: function (e) {
                var el = $(e.currentTarget),
                    requestedCabinType = el.val();

                this.awardCalendarResults.cabinTypeSelection = requestedCabinType;
                this.awardCalendarResults.isCabinTypeChange = true;
                this.awardCalendarResults.isChangeWeek = true;
                this.renderAwardCalendar(this.prepareCalendarData(this.awardCalendarResults));
                if (this.currentResults && this.currentResults.SearchFilters && this.currentResults.SearchFilters.HideNoneStop) {
                    $('#award-nonstop-calendar-chkbox').hide();
                }
            },
            handleAwardCalendarNonstopFilterChange: function (e) {
                e.preventDefault();
                var el = $(e.currentTarget),
                    isAwardCalendarNonstop = el.is(':checked');
                this.handleAwardCalendarNonstopFilterChangeFunc(isAwardCalendarNonstop);
            },
            handleAwardCalendarNonstopFilterChangeFunc: function (isAwardCalendarNonstop) {
                if (this.showTopFiltersAward === true && this.currentResults.appliedSearch.IsAwardCalendarNonstop === isAwardCalendarNonstop) {
                    return;
                }
                this.currentResults.appliedSearch.cabinSelection = $("#calendar-cabintype-dropdown").val();
                this.currentResults.appliedSearch.CurrentTripIndex = this.getTripIndex();
                this.currentResults.appliedSearch.IsAwardCalendarNonstop = isAwardCalendarNonstop;
                this.currentResults.appliedSearch.isChangeWeek = true;
                this.loadAwardCalendar(this.currentResults.appliedSearch);
            },
            handleAwardChangeRangeClick: function (e) {
                e.preventDefault();
                var el = $(e.currentTarget);
                if (el.hasClass("calendar-loading")) {
                    return;
                }

                var updatedSearchParams = _.cloneDeep(this.currentResults.appliedSearch),
                    newCalendarRangeStartDate = el.data('cal-date');
                var tripindex = this.getTripIndex();
                updatedSearchParams.Trips[tripindex].DepartDate = newCalendarRangeStartDate;
				// Bug :1336683 
                var cabinSelection = $("#calendar-cabintype-dropdown").val();  //getting the selected cabin type from the dropdown
                updatedSearchParams.cabinSelection = cabinSelection;          // updating the cabinselection.
                if (tripindex == 0) {
                    _.forEach(updatedSearchParams.Trips, function (trip, index) {
                        if (index > 0) {
                            var newdepartdate = new Date(newCalendarRangeStartDate);
                            trip.DepartDate = newCalendarRangeStartDate = newdepartdate.addDays(7);
                        }
                    });
                }
                updatedSearchParams.isChangeWeek = true;
                this.loadAwardCalendar(updatedSearchParams);

            },
            stepCalendar: function (e) {
                e.preventDefault();
                var _d, el = $(e.currentTarget),
                    calDate = el.data('cal-date'),
                    calRequestData = {};

                if (!calDate) {

                    el.find('option:selected').each(function () {

                        calDate = this.value;
                    });
                }

                var today = new Date();
                var _calDate = new Date(calDate);
                var isCurrentMonth = _calDate < today && (today.getMonth() + 1) == (_calDate.getMonth() + 1);
                if (isCurrentMonth) {
                    calDate = (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear();
                }

                calRequestData = $.extend(true, {}, this.currentResults.appliedSearch);
                calRequestData.flexMonth = calDate;
                calRequestData.flexMonth2 = calDate;
                this.currentResults.appliedSearch.flexMonth = formatDateNoWeekDay(calDate);
                this.currentResults.appliedSearch.flexMonth2 = formatDateNoWeekDay(calDate);
                calRequestData.Trips[0].DepartDate = calRequestData.flexMonth;

                if (calRequestData.Trips[1]) {
                    _d = new Date(calRequestData.flexMonth);
                    _d.setDate(_d.getDate() + calRequestData.tripLength);
                    calRequestData.Trips[1].DepartDate = (_d.getMonth() + 1) + "/" + _d.getDate().toString() + "/" + _d.getFullYear().toString();
                }

                var isReshopApiCalled = this.checkIfReshopApiIscalled(this.currentResults.appliedSearch.Trips, parseInt($("#hdnCurrentTripIndex").val(), 10));
                if (isReshopApiCalled && this.selectedFlights.length > 0) {
                    var currentTripIndex = parseInt($("#hdnCurrentTripIndex").val(), 10);
                    var previousTripIndex = currentTripIndex - 1;
                    var selectedFlt = this.selectedFlights[previousTripIndex - 1];
                    calRequestData.SolutionSetId = selectedFlt.SolutionSetId;

                } else {
                    calRequestData.SolutionSetId = $('#SolutionSetId').val();
                }
                //198129 - Current month fails to display when selected in Availability Calendar
                if (isCurrentMonth) {
                    calRequestData.flexMonth = null;
                    calRequestData.flexMonth2 = null;
                }
                calRequestData.CalendarDateChange = calDate;
                calRequestData.CartId = $('#CartId').val();
                calRequestData.CalendarOnly = true;
                if ($('#filter-onlynonstop').is(':checked')) {
                    calRequestData.nonStopOnly = 1;
                    calRequestData.calendarStops = 0;
                    this.currentResults.appliedSearch.nonStopOnly = 1;
                    this.currentResults.appliedSearch.calendarStops = 0;
                } else {
                    calRequestData.nonStopOnly = 0;
                    calRequestData.calendarStops = 4;
                    this.currentResults.appliedSearch.nonStopOnly = 0;
                    this.currentResults.appliedSearch.calendarStops = 4;
                }
                var pageLoader = $("#calendar-results-loader-partial");
                if (pageLoader.length > 0) {
                    try {
                        this.spinner_button = $("#calendar-results-loader-partial").loader();
                    } catch (err) {
                        ;
                    }
                } else {
                    this.spinner_button = $('.calendar-loader').loader();
                }
                this.loadCalendarResults(calRequestData);

            },
            onlyNonStop: function (e) {

                //e.preventDefault();
                var calRequestData = {};
                calRequestData = $.extend(true, {}, this.currentResults.appliedSearch);

                if ($('#filter-onlynonstop').is(':checked')) {
                    calRequestData.nonStopOnly = 1;
                    calRequestData.calendarStops = 0;
                    if (this.currentResults && this.currentResults.Trips && this.currentResults.Trips.length > 0 && this.currentResults.Trips[0].Flights && this.currentResults.Trips[0].Flights.length > 0) {
                        ;
                    } else {
                        this.currentResults.appliedSearch.CalendarOnly = true;
                        this.currentResults.appliedSearch.nonStopOnly = 1;
                        this.currentResults.appliedSearch.calendarStops = 0;
                    }
                } else {
                    calRequestData.nonStopOnly = 0;
                    calRequestData.calendarStops = 4;
                    if (this.currentResults && this.currentResults.Trips && this.currentResults.Trips.length > 0 && this.currentResults.Trips[0].Flights && this.currentResults.Trips[0].Flights.length > 0) {
                        ;
                    } else {
                        this.currentResults.appliedSearch.nonStopOnly = 0;
                        this.currentResults.appliedSearch.calendarStops = 4;
                    }
                }
                calRequestData.CartId = $('#CartId').val();
                calRequestData.SolutionSetId = $('#SolutionSetId').val();
                calRequestData.CalendarOnly = true;

                this.spinner_button = $('.calendar-loader').loader();
                this.loadCalendarResults(calRequestData);
            },
            modifyFareCalendar: function (e) {
                e.preventDefault();
                var _selectedDateMonth2;
                var _selectedDate = $('#FlexMonth2').val(),
                    _today = Date.today();

                this.currentResults.appliedSearch.flexMonth = (UA.Utilities.formatting.tryParseDate(_selectedDate) < _today) ? formatDate(_today) : _selectedDate;
                if (this.currentResults.appliedSearch.flexible) {
                    var tripDepartdate = UA.Utilities.formatting.tryParseDate(_selectedDate);
                    if (tripDepartdate == null) {
                        tripDepartdate = new Date(this.currentResults.appliedSearch.DepartDate);
                        _selectedDateMonth2 = formatDateNoWeekDay(tripDepartdate);
                    } else {
                        _selectedDateMonth2 = _selectedDate;
                    }
                } else {
                    _selectedDateMonth2 = _selectedDate;
                }
                this.currentResults.appliedSearch.flexMonth2 = (UA.Utilities.formatting.tryParseDate(_selectedDateMonth2) < _today) ? formatDate(_today) : _selectedDateMonth2;
                this.currentResults.appliedSearch.cabinSelection = $('#cabinType2 option:selected').val();
                this.currentResults.appliedSearch.tripLength = parseInt($('#tripLength2 option:selected').val(), 10);
                if (this.currentResults.appliedSearch.IsPromo && this.currentResults.appliedSearch.offerCode != null && this.currentResults.appliedSearch.offerCode.length >0) {
                    $('#OfferCode').val(this.currentResults.appliedSearch.offerCode);
                }
                $("input[name='FlexMonth']").val(this.currentResults.appliedSearch.flexMonth);
                $("input[name='FlexMonth2']").val(this.currentResults.appliedSearch.flexMonth2);
                $('#cabinTypeCal').val(this.currentResults.appliedSearch.cabinSelection).prop('selected', true);
                $('#TripLength').val(this.currentResults.appliedSearch.tripLength).prop('selected', true);
                this.modifyFareCalendarSearch(e);
                return;
            },
            modifyFareCalendarSearch: function (e) {
                e.preventDefault();

                this.spinner_button = $('.calendar-loader').loader();
                $('#frm-search-options').submit();
                return;

            },
            handleEditCalendarSearchClick: function (e) {
                e.preventDefault();
                $(".fc-options-summary, .edit-calendar-search").addClass('hidden');
                $(".fc-options-edit, .close-calendar-search").removeClass('hidden');
                UA.UI.Uniform.init();
            },
            handleCloseCalendarSearchClick: function (e) {
                e.preventDefault();
                $(".fc-options-summary, .edit-calendar-search").removeClass('hidden');
                $(".fc-options-edit, .close-calendar-search").addClass('hidden');
            },
            getTripIndex: function () {
                var tripIndex = parseInt(this.elements.currentTripIndex.val(), 10);
                tripIndex = tripIndex - 1;
                if (tripIndex < 0) {
                    tripIndex = 0;
                }

                return tripIndex;
            },
            addHoursMinutesToDate: function (dateString, hours, minutes) {
                var date = new Date(dateString);
                date.setHours(hours);
                date.setMinutes(minutes);
                return date;
            },
            PopuplateEmptyResultMessage: function (data) {
                try {
                    var tripindexcurrent = this.getTripIndex();

                    //Display or do not Display message based on Preferred time available flights
                    if (data.appliedSearch.Trips[tripindexcurrent].PreferredTime !== undefined && data.appliedSearch.Trips[tripindexcurrent].PreferredTime !== null) {
                        var preferredtime = $.trim(data.appliedSearch.Trips[tripindexcurrent].PreferredTime);
                        if (preferredtime) {
                            var departdate = data.appliedSearch.Trips[tripindexcurrent].DepartDate;
                            var timeDepartMin = this.parseDateTime(data.SearchFilters.TimeDepartMin).getTime();
                            var timeDepartMax = this.parseDateTime(data.SearchFilters.TimeDepartMax).getTime();
                            var preferredtimemin, preferredtimemax;
                            switch (preferredtime) {
                                case 'MorningEarly':

                                    preferredtimemin = this.addHoursMinutesToDate(departdate, '00', '00').getTime();
                                    preferredtimemax = this.addHoursMinutesToDate(departdate, '07', '59').getTime();
                                    break;
                                case 'Morning':

                                    preferredtimemin = this.addHoursMinutesToDate(departdate, '08', '00').getTime();
                                    preferredtimemax = this.addHoursMinutesToDate(departdate, '10', '59').getTime();
                                    break;
                                case 'Noon':

                                    preferredtimemin = this.addHoursMinutesToDate(departdate, '11', '00').getTime();
                                    preferredtimemax = this.addHoursMinutesToDate(departdate, '13', '59').getTime();
                                    break;
                                case 'AfterNoon':

                                    preferredtimemin = this.addHoursMinutesToDate(departdate, '14', '00').getTime();
                                    preferredtimemax = this.addHoursMinutesToDate(departdate, '16', '59').getTime();
                                    break;
                                case 'Evening':

                                    preferredtimemin = this.addHoursMinutesToDate(departdate, '17', '00').getTime();
                                    preferredtimemax = this.addHoursMinutesToDate(departdate, '20', '59').getTime();
                                    break;
                                case 'Midnight':

                                    preferredtimemin = this.addHoursMinutesToDate(departdate, '21', '00').getTime();
                                    preferredtimemax = this.addHoursMinutesToDate(departdate, '23', '59').getTime();
                                    break;
                                default:
                                    var time = parseInt(preferredtime.substr(0, preferredtime.length - 5), 10);
                                    if (preferredtime.indexOf('AM') > 0) {
                                        preferredtimemin = this.addHoursMinutesToDate(departdate, time - 1, '01').getTime();
                                        preferredtimemax = this.addHoursMinutesToDate(departdate, time + 1, '59').getTime();
                                    }
                                    if (preferredtime.indexOf('PM') > 0) {
                                        preferredtimemin = this.addHoursMinutesToDate(departdate, time + 11, '01').getTime();
                                        preferredtimemax = this.addHoursMinutesToDate(departdate, time + 12, '59').getTime();
                                    }
                            }
                            if (preferredtimemin !== undefined && preferredtimemax !== undefined) {
                                if ((timeDepartMin < preferredtimemin && timeDepartMax < preferredtimemin) || (timeDepartMin > preferredtimemax && timeDepartMax > preferredtimemax)) {
                                    $(this.templates.flightResultReset()).appendTo(this.elements.resetNotificationContainer.empty()).show();
                                }
                            }
                        }
                    }

                    //Display or do not Display message based on availability of NONSTOP only and onestop or twostop Only flights
                    var NonStop = data.appliedSearch.Trips[tripindexcurrent].nonStop;
                    var NonStopOnly = data.appliedSearch.Trips[tripindexcurrent].nonStopOnly;
                    var OneStop = data.appliedSearch.Trips[tripindexcurrent].oneStop;
                    var TwoStopPlus = data.appliedSearch.Trips[tripindexcurrent].twoPlusStop;
                    var airportstops = parseInt(data.SearchFilters.AirportsStopList.length, 10);
                    var NonStopHidden = data.SearchFilters.HideNoneStop;
                    var OneStopHidden = data.SearchFilters.HideOneStop;
                    var TwoStopHidden = data.SearchFilters.HideTwoPlusStop;
                    var NoStopSelectionmade = false;
                    var AllStopOptionsChecked = false;
                    if (!NonStop && !NonStopOnly && !OneStop && !TwoStopPlus) {
                        NoStopSelectionmade = true;
                    }
                    if (NonStop && OneStop && TwoStopPlus) {
                        AllStopOptionsChecked = true;
                    }

                    if (!AllStopOptionsChecked) {
                        if (!NoStopSelectionmade) {
                            if (!OneStop && !TwoStopPlus) {
                                //nonstop unchecked, 1stop checked, 2plusstop checked, but the market only has nonstop flights and no onestop or twostop flights
                                //Example DEN-HLN
                                if (!NonStop && !NonStopHidden) {
                                    $(this.templates.flightResultReset()).appendTo(this.elements.resetNotificationContainer.empty()).show();
                                }
                                //Display the message if only non stop is checked and one stop and twoplus stops are unchecked but the flight results contains only flights with onestop and twoplus stops.
                                //Example SEA-MIA or BOS-MSP
                                if (NonStopOnly && NonStopHidden) {
                                    $(this.templates.flightResultReset()).appendTo(this.elements.resetNotificationContainer.empty()).show();
                                }
                            }

                            if (!NonStopOnly) {
                                //nonstop checked,onestop not checked, twoplusstop checked, but the market only has 1stop flights and no NonStop or 2stop flights
                                //Example market BHM-MSY
                                if (!OneStop && !TwoStopPlus && NonStopHidden && TwoStopHidden) {
                                    $(this.templates.flightResultReset()).appendTo(this.elements.resetNotificationContainer.empty()).show();
                                }
                                //nonstop unchecked, onestop unchecked, twoplusstop checked, but the market only has onestop flights and nonstop flights but no 2 stop flights.
                                //Example market BUF-FAT
                                if (TwoStopPlus && !OneStop && TwoStopHidden) {
                                    $(this.templates.flightResultReset()).appendTo(this.elements.resetNotificationContainer.empty()).show();
                                }

                                if (TwoStopPlus && OneStop && !NonStopHidden) {
                                    $(this.templates.flightResultReset()).appendTo(this.elements.resetNotificationContainer.empty()).show();
                                }
                            } else {
                                //Display the message if only non stop is checked and one stop and twoplus stops are unchecked but the flight results contains only flights with onestop and twoplus stops.
                                //Example SEA-MIA or BOS-MSP
                                if (NonStopHidden && NonStop) {
                                    $(this.templates.flightResultReset()).appendTo(this.elements.resetNotificationContainer.empty()).show();
                                }
                            }
                        }
                    }
                } catch (error) { }

            },
            handleFareFamilySelect: function (e) {
                var target = $(e.currentTarget),
                    fareFamily = target.val(),
                    _this = this;
                var selectElId = target.attr('id');
                var selectedFamilyDescription = $("#" + selectElId + " option:selected").text();
                this.currentResults.appliedSearch.cabinSelection = fareFamily;
                this.currentResults.appliedSearch.SearchFilters.FareFamily = fareFamily;
                this.currentResults.appliedSearch.SearchFilters.FareFamilyDescription = selectedFamilyDescription;
                this.currentResults.appliedSearch.SearchFilters.SortFareFamily = fareFamily;
                _.forEach(this.currentResults.Trips[0].Columns, function (column) {
                    column.Selected = column.ProductType == fareFamily;
                });

                this.currentResults.appliedSearch.SearchFilters.PriceMin = this.currentResults.SearchFilters.MinPrices[fareFamily];
                this.currentResults.appliedSearch.SearchFilters.PriceMax = this.currentResults.SearchFilters.MaxPrices[fareFamily];


                if (selectElId == 'select-fare-family') {
                    this.loadFilterResults(this.currentResults.appliedSearch, true);
                } else if (this.showTopFilters || this.showTopFiltersAward) {
                    this.loadFilterResults(this.currentResults.appliedSearch, null, null, true);
                } else if (this.searchFilterMode === 'footerondemand' || this.searchFilterMode === 'footer') {
                    this.loadFilterResults(this.currentResults.appliedSearch, true);
                }
                target.val(fareFamily);
                UA.UI.reInit(target);

                UA.UI.Uniform.update('#' + selectElId);

            },
            handleOnlyFilterClick: function (e) {
                e.preventDefault();

                var target = $(e.currentTarget),
                    checkGroup = $(target).parents('.filter-group');

                checkGroup.find('input').prop('checked', false);

                $('#' + target.data('only-for')).prop('checked', true);

                //var tempNonStop = $('#filter_nonStop').is(':checked');

                //$('#newfilter_nonStop').prop('checked', tempNonStop);
                //this.currentResults.appliedSearch.SearchFilters.nonStop = tempNonStop;

                //$('#newfilter_stop').prop('checked', ($('#filter_oneStop').is(':checked') || $('#filter_twoPlusStop').is(':checked')));
                //this.currentResults.appliedSearch.SearchFilters.oneStop = $('#filter_oneStop').is(':checked');
                //this.currentResults.appliedSearch.SearchFilters.twoPlusStop = ($('#filter_twoPlusStop').is(':checked'));
                //this.currentResults.appliedSearch.SearchFilters.filterOnlyClick = false;
                //bottom and top only search filter (gsp
                if ($(target).attr("id") == "hrefNonStop") {
                    $('#filter_nonStop').prop('checked', true);
                    $('#filter_oneStop').prop('checked', false);
                    $('#filter_twoPlusStop').prop('checked', false);
                    $('#newfilter_nonStop').prop('checked', true);
                    this.currentResults.appliedSearch.SearchFilters.nonStop = true;
                    this.currentResults.appliedSearch.SearchFilters.oneStop = false;
                    this.currentResults.appliedSearch.SearchFilters.twoPlusStop = false;
                    this.currentResults.appliedSearch.SearchFilters.filterOnlyClick = 'nonStop';
                }
                else if ($(target).attr("id") == "hrefOneStop") {
                    $('#filter_nonStop').prop('checked', false);
                    $('#filter_oneStop').prop('checked', true);
                    $('#filter_twoPlusStop').prop('checked', false);
                    $('#newfilter_nonStop').prop('checked', false);
                    $('#newfilter_stop').prop('checked', true);
                    $('#' + this.elements.filterConnectionId + ' input:checkbox, .filter-connection-list' + ' input:checkbox').prop('checked', true);//SHD turn on all airports
                    this.currentResults.appliedSearch.SearchFilters.nonStop = false;
                    this.currentResults.appliedSearch.SearchFilters.oneStop = true;
                    this.currentResults.appliedSearch.SearchFilters.twoPlusStop = false;
                    this.currentResults.appliedSearch.SearchFilters.stop = true;
                    this.currentResults.appliedSearch.SearchFilters.filterOnlyClick = 'oneStop';
                }
                else if ($(target).attr("id") == "hreftwoPlusStop") {
                    $('#filter_nonStop').prop('checked', false);
                    $('#filter_oneStop').prop('checked', false);
                    $('#filter_twoPlusStop').prop('checked', true);
                    $('#newfilter_nonStop').prop('checked', false);
                    $('#newfilter_stop').prop('checked', true);
                    $('#' + this.elements.filterConnectionId + ' input:checkbox, .filter-connection-list' + ' input:checkbox').prop('checked', true);//SHD turn on all airports
                    this.currentResults.appliedSearch.SearchFilters.nonStop = false;
                    this.currentResults.appliedSearch.SearchFilters.oneStop = false;
                    this.currentResults.appliedSearch.SearchFilters.twoPlusStop = true;
                    this.currentResults.appliedSearch.SearchFilters.stop = true;
                    this.currentResults.appliedSearch.SearchFilters.filterOnlyClick = 'twoPlusStop';
                }
                else {
                    this.currentResults.appliedSearch.SearchFilters.filterOnlyClick = 'airportOnly';

                    //$('#filter_nonStop').prop('checked', true);
                    //$('#filter_oneStop').prop('checked', true);
                    //$('#filter_twoPlusStop').prop('checked', true);
                    //$('#newfilter_nonStop').prop('checked', true);
                    //$('#newfilter_stop').prop('checked', true);

                    //this.currentResults.appliedSearch.SearchFilters.nonStop = true;
                    //this.currentResults.appliedSearch.SearchFilters.oneStop = true;
                    //this.currentResults.appliedSearch.SearchFilters.twoPlusStop = true;
                    //this.currentResults.appliedSearch.SearchFilters.stop = true;


                    if ($('#' + target.data('only-for')).is(":checked")) {//move focus back on parent checkbox after click on only SHD
                        $('#filter_oneStop').prop('checked', true);
                        $('#filter_twoPlusStop').prop('checked', true);
                        $('#newfilter_stop').prop('checked', true);

                        this.currentResults.appliedSearch.SearchFilters.oneStop = true;
                        this.currentResults.appliedSearch.SearchFilters.twoPlusStop = true;
                        this.currentResults.appliedSearch.SearchFilters.stop = true;

                        var strDataOnlyFor = target.data('only-for');
                        if (strDataOnlyFor.indexOf('filter-destination') != -1) {    //top airport only click, dont handleCheckBoxFilterClick
                            setTimeout(function () {
                                $('#' + target.data('only-for')).focus();
                            }, 10);
                            return;
                        }
                    }


                }

                UA.UI.reInit(checkGroup);
                this.handleCheckBoxFilterClick(this.currentResults.appliedSearch);
            },
            handleClearFilters: function (e) {
                e.preventDefault();

                this.resetFilter();
                $("#fl-bestresult-notification").hide();

                if (this.showTopFiltersAward === true && this.currentResults.appliedSearch.flexibleAward === false) {
                    var isAwardCalendarNonstop = false;
                    if (this.currentResults.SearchFilters && !this.currentResults.SearchFilters.HideNoneStop && this.currentResults.SearchFilters.HideOneStop && this.currentResults.SearchFilters.HideTwoPlusStop) {
                        isAwardCalendarNonstop = true;
                    }
                    this.handleAwardCalendarNonstopFilterChangeFunc(isAwardCalendarNonstop);
                }
            },

            resetFilterFields: function (notInitialized) {
                var tripIndex, trip, _this = this;
                var airportsStop, originList, destinationList, warningList, equipCodes, optCarriers, aircraftList, selectedFareFamily;
                var selectedFamilyDescription, selectedSort;

                airportsStop = $.map($('#' + this.elements.filterConnectionId + ' input:checkbox'), function (ev, i) {
                    return $(ev).val();
                });
                originList = $.map($('#' + this.elements.filterOriginId + ' input:checkbox'), function (ev, i) {
                    return $(ev).val();
                });
                destinationList = $.map($('#' + this.elements.filterDestinationId + ' input:checkbox'), function (ev, i) {
                    return $(ev).val();
                });
                warningList = $.map($('#' + this.elements.filterAdvisoriesId + ' input:checkbox'), function (ev, i) {
                    return $(ev).val();
                });
                equipCodes = $.map($('#filt-equipment-type-cont input:checkbox'), function (ev, i) {
                    return $(ev).val();
                });
                optCarriers = $.map($('#filt-airlines-opt-cont input:checkbox'), function (ev, i) {
                    return $(ev).val();
                });
                aircraftList = $.map($('#filter-checkbox-aircraft input:checkbox'), function (ev, i) {
                    return $(ev).val();
                });
                this.currentResults.appliedSearch.SearchFilters.EquipmentCodes = equipCodes.join();
                this.currentResults.appliedSearch.SearchFilters.AirportsStop = airportsStop.join();
                this.currentResults.appliedSearch.SearchFilters.AirportsDestination = destinationList.join();
                this.currentResults.appliedSearch.SearchFilters.AirportsOrigin = originList.join();
                //this.currentResults.appliedSearch.hiddenUnpreferredConn = "";
                selectedFareFamily = $('#select-fare-family').val();
                selectedFamilyDescription = $("#select-fare-family option:selected").text();
                if (typeof selectedFareFamily === 'undefined') {
                    var selectedFareFamilyObj = this.currentResults.Trips[0].Columns.filter(function (p) {
                        return p.FareFamily === _this.currentResults.appliedSearch.SearchFilters.FareFamily;
                    });
                    if (selectedFareFamilyObj !== null && typeof selectedFareFamilyObj !== 'undefined' && selectedFareFamilyObj.length >0) {
                        selectedFareFamily = this.currentResults.appliedSearch.SearchFilters.FareFamily;
                        if (selectedFareFamilyObj != null && selectedFareFamilyObj.length > 0) {
                            selectedFamilyDescription = selectedFareFamilyObj[0].ColumnName;
                        }
                    }
                }

                if (notInitialized !== true) {
                    this.currentResults.SearchFilters.PriceFilterActive = $('.filter-section-price-schedule').toggler('isActive');
                    this.currentResults.SearchFilters.AirportFilterActive = $('.filter-section-airport-route').toggler('isActive');
                    this.currentResults.SearchFilters.ExperienceFilterActive = $('.filter-section-experience').toggler('isActive');
                }

                if (this.showTopFilters || this.showTopFiltersAward) {

                    if (this.currentResults.SearchFilters.AirportsStopList && this.currentResults.SearchFilters.AirportsStopList.length > 0) {
                        var stops = [];
                        stops = _.map(this.currentResults.SearchFilters.AirportsStopList, function (s) {
                            return s.Code;
                        });
                        if (stops.length > 0) {
                            this.currentResults.appliedSearch.SearchFilters.AirportsStop = stops.join();
                        }
                    }
                    if (this.currentResults.SearchFilters.AirportsDestinationList && this.currentResults.SearchFilters.AirportsDestinationList.length > 0) {
                        var destinationCodes = [];
                        var activeDestination = _.where(this.currentResults.SearchFilters.AirportsDestinationList, {
                            'Active': true
                        });
                        destinationCodes = _.map(activeDestination, function (s) {
                            return s.Code;
                        });

                        if (destinationCodes.length > 0) {
                            this.currentResults.appliedSearch.SearchFilters.AirportsDestination = destinationCodes.join();
                        }
                    }
                    if (this.currentResults.SearchFilters.AirportsOriginList && this.currentResults.SearchFilters.AirportsOriginList.length > 0) {
                        var departCodes = [];
                        var activeOrigin = _.where(this.currentResults.SearchFilters.AirportsOriginList, {
                            'Active': true
                        });
                        departCodes = _.map(activeOrigin, function (s) {
                            return s.Code;
                        });

                        if (departCodes.length > 0) {
                            this.currentResults.appliedSearch.SearchFilters.AirportsOrigin = departCodes.join();
                        }
                    }
                    selectedFareFamilyObj = this.currentResults.Trips[0].Columns.filter(function (p) {
                        return p.FareFamily === _this.currentResults.appliedSearch.SearchFilters.FareFamily;
                    });
                    if (selectedFareFamilyObj !== null && typeof selectedFareFamilyObj !== 'undefined' && selectedFareFamilyObj.length > 0) {
                        selectedFareFamily = this.currentResults.appliedSearch.SearchFilters.FareFamily;
                        if (selectedFareFamilyObj != null && selectedFareFamilyObj.length > 0) {
                            selectedFamilyDescription = selectedFareFamilyObj[0].ColumnName;
                        }
                    }
                }
                //selectedSort = $('#SortType').val();
                //this.currentResults.appliedSearch.SortType = selectedSort;
                this.currentResults.appliedSearch.SearchFilters.FareFamily = selectedFareFamily;
                this.currentResults.appliedSearch.SearchFilters.FareFamilyDescription = selectedFamilyDescription;
                this.currentResults.appliedSearch.SearchFilters.Warnings = warningList;
                this.currentResults.appliedSearch.SearchFilters.AircraftList = aircraftList;
                this.currentResults.appliedSearch.SearchFilters.CarriersPreference = optCarriers;
                _.forEach(this.currentResults.Trips[0].Columns, function (column) {
                    column.Selected = column.ProductType == selectedFareFamily;
                });
                this.currentResults.appliedSearch.SearchFilters.Amenities = [];

                this.currentResults.appliedSearch.SearchFilters.PriceMin = this.currentResults.SearchFilters.MinPrices[selectedFareFamily];
                this.currentResults.appliedSearch.SearchFilters.PriceMax = this.currentResults.SearchFilters.MaxPrices[selectedFareFamily];

                this.currentResults.appliedSearch.SearchFilters.TimeDepartMax = this.currentResults.SearchFilters.TimeDepartMax;
                this.currentResults.appliedSearch.SearchFilters.TimeDepartMin = this.currentResults.SearchFilters.TimeDepartMin;
                this.currentResults.appliedSearch.SearchFilters.TimeArrivalMax = this.currentResults.SearchFilters.TimeArrivalMax;
                this.currentResults.appliedSearch.SearchFilters.TimeArrivalMin = this.currentResults.SearchFilters.TimeArrivalMin;

                this.currentResults.appliedSearch.SearchFilters.DurationMax = (15 * Math.ceil(this.currentResults.SearchFilters.DurationMax / 15));
                this.currentResults.appliedSearch.SearchFilters.DurationMin = (15 * Math.floor(this.currentResults.SearchFilters.DurationMin / 15));
                this.currentResults.appliedSearch.SearchFilters.LayoverMax = (15 * Math.ceil(this.currentResults.SearchFilters.LayoverMax / 15));
                this.currentResults.appliedSearch.SearchFilters.LayoverMin = (15 * Math.floor(this.currentResults.SearchFilters.LayoverMin / 15));

                tripIndex = this.getTripIndex();
                trip = this.currentResults.appliedSearch.Trips[tripIndex];
                trip.nonStop = true;
                trip.oneStop = true;
                trip.twoPlusStop = true;
                this.setFilterFromTrip(this.currentResults.appliedSearch.SearchFilters, tripIndex + 1);

                //<!-- CARRIER PREFERENCE -->
                this.currentResults.appliedSearch.SearchFilters.CarrierDefault = true;
                this.currentResults.appliedSearch.SearchFilters.CarrierExpress = true;
                this.currentResults.appliedSearch.SearchFilters.CarrierStar = true;
                this.currentResults.appliedSearch.SearchFilters.CarrierPartners = true;

                //this.currentResults.appliedSearch.SearchFilters.AirportFilterActive = true;
                this.currentResults.appliedSearch.SearchFilters.SingleCabinExist = true;
                this.currentResults.appliedSearch.SearchFilters.MultiCabinExist = true;
                this.currentResults.appliedSearch.SearchFilters.TurboPropExist = true;

                _.forEach(this.currentResults.SearchFilters.AirportsStopList, function (stop) {
                    stop.active = true;
                });
            },

            resetFilter: function (targetLoader) {
                this.resetFilterFields();
                this.loadFilterResults(this.currentResults.appliedSearch, true, null, null, false, targetLoader);
            },
            handleNewTopStopsFilterClick: function (e) {
                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    e.preventDefault();
                    return;
                }

                filterActionClick = true;

                var target = $(e.currentTarget),
                    targetName = target.attr('name'),
                    nonStop = targetName == "allflights" ? true : targetName == "nonstop" ? true : false,
                    oneStop = false, twoPlusStop = false, tripIndex, trip;                

                if (!(this.currentResults.SearchFilters && this.currentResults.SearchFilters.HideOneStop)) {
                    oneStop = targetName == "allflights" ? true : targetName == "stop" ? true : false;
                }
                if (!(this.currentResults.SearchFilters && this.currentResults.SearchFilters.HideTwoPlusStop)) {
                    twoPlusStop = targetName == "allflights" ? true : targetName == "stop" ? true : false;
                }

                tripIndex = this.getTripIndex();
                trip = this.currentResults.appliedSearch.Trips[tripIndex];
                trip.nonStop = nonStop;
                trip.oneStop = oneStop;
                trip.twoPlusStop = twoPlusStop;
                this.setFilterFromTrip(this.currentResults.appliedSearch.SearchFilters, tripIndex + 1);
                this.isFilterClick = true;
                this.loadFilterResults(this.currentResults.appliedSearch);

            },
            handleUpgradesFilterClick: function (e) {
                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    e.preventDefault();
                    return;
                }

                filterActionClick = true;

                var target = $(e.currentTarget);

                if (target.attr('id') == "showonlyoptions")
                {
                    this.currentResults.appliedSearch.ShowAvailableOnlyUpgrades = true;
                }
                else
                {
                    this.currentResults.appliedSearch.ShowAvailableOnlyUpgrades = false;
                }


                //var tripIndex = this.getTripIndex();
                //trip = this.currentResults.appliedSearch.Trips[tripIndex];
                //trip.nonStop = nonStop;
                //trip.oneStop = oneStop;
                //trip.twoPlusStop = twoPlusStop;
                //this.setFilterFromTrip(this.currentResults.appliedSearch.SearchFilters, tripIndex + 1);
                //this.isFilterClick = true;
                this.loadFilterResults(this.currentResults.appliedSearch);

            },
            handleTopStopsFilterClick: function (e) {
                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    e.preventDefault();
                    return;
                }

                filterActionClick = true;

                var target = $(e.currentTarget),
                    nonStop = $('#newfilter_nonStop').is(':checked'),
                    oneStop = false, twoPlusStop = false, tripIndex, trip;

                //$(e.currentTarget).parent().children("label").loader();

                if (!(this.currentResults.SearchFilters && this.currentResults.SearchFilters.HideOneStop)) {
                    oneStop = $('#newfilter_stop').is(':checked');
                }
                if (!(this.currentResults.SearchFilters && this.currentResults.SearchFilters.HideTwoPlusStop)) {
                    twoPlusStop = $('#newfilter_stop').is(':checked');
                }

                if (this.showTopFiltersAward === true && this.currentResults.appliedSearch.flexibleAward === false) {
                    var isAwardCalendarNonstop = false;
                    if (this.currentResults.SearchFilters) {
                        if (this.currentResults.SearchFilters.HideNoneStop) {
                            if (this.currentResults.SearchFilters.HideOneStop && this.currentResults.SearchFilters.HideTwoPlusStop) {
                                ;
                            } else {
                                if ($('#newfilter_stop').is(':checked')) {
                                    ;
                                } else {
                                    isAwardCalendarNonstop = true;
                                }
                            }
                        } else {
                            if (this.currentResults.SearchFilters.HideOneStop && this.currentResults.SearchFilters.HideTwoPlusStop) {
                                if ($('#newfilter_nonStop').is(':checked')) {
                                    isAwardCalendarNonstop = true;
                                } else {
                                    isAwardCalendarNonstop = false;
                                }
                            } else {
                                if ($('#newfilter_nonStop').is(':checked')) {
                                    if ($('#newfilter_stop').is(':checked')) {
                                        ;
                                    } else {
                                        isAwardCalendarNonstop = true;
                                    }
                                } else {
                                    ;
                                }
                            }
                        }
                    } else {
                        ;
                    }

                    this.handleAwardCalendarNonstopFilterChangeFunc(isAwardCalendarNonstop);
                }

                if ((this.showTopFilters || this.showTopFiltersAward) && (this.searchFilterMode === 'footerondemand' || this.searchFilterMode === 'footer') && target.is('#newfilter_nonStop')) {
                    $('#filter_nonStop').prop('checked', nonStop); //align footer to top filter checkbox
                }
                if (target.is('#newfilter_stop') && target.is(':checked')) {
                    $('#' + this.elements.filterConnectionId + ' input:checkbox').prop('checked', true);
                    UA.UI.reInit($('#' + this.elements.filterConnectionId));
                }
                if (target.is('#newfilter_stop') && !target.is(':checked')) {
                    $('input:checkbox[id^="filter-connection"]').prop('checked', false);
                }
                var airportsStop = $.map($('#' + this.elements.filterConnectionId + ' input:checkbox:checked'), function (ev, i) {
                    return $(ev).val();
                }),
                originList = $.map($('#' + this.elements.filterOriginId + ' input:checkbox:checked'), function (ev, i) {
                    return $(ev).val();
                }),
                amenitiesList = $.map($('#' + this.elements.filterAmenitiesId + ' input:checkbox:checked'), function (ev, i) {
                    return $(ev).val();
                }),
                destinationList = $.map($('#' + this.elements.filterDestinationId + ' input:checkbox:checked'), function (ev, i) {
                    return $(ev).val();
                }),
                warningList = $.map($('#' + this.elements.filterAdvisoriesId + ' input:checkbox:checked'), function (ev, i) {
                    return $(ev).val();
                }),
                equipCodes = $.map($('#filt-equipment-type-cont input:checkbox:checked'), function (ev, i) {
                    return $(ev).val();
                }),
                optCarriers = $.map($('#filt-airlines-opt-cont input:checkbox:checked'), function (ev, i) {
                    return $(ev).val();
                }),
                aircraftList = $.map($('#filter-checkbox-aircraft input:checkbox:checked'), function (ev, i) {
                    return $(ev).val();
                });

                this.currentResults.appliedSearch.SearchFilters.Amenities = amenitiesList;
                this.currentResults.appliedSearch.SearchFilters.EquipmentCodes = equipCodes.join();
                this.currentResults.appliedSearch.SearchFilters.AirportsStop = airportsStop.join();
                this.currentResults.appliedSearch.SearchFilters.AirportsDestination = destinationList.join();
                this.currentResults.appliedSearch.SearchFilters.AirportsOrigin = originList.join();
                this.currentResults.appliedSearch.SearchFilters.Warnings = warningList;
                this.currentResults.appliedSearch.SearchFilters.AircraftList = aircraftList;
                this.currentResults.appliedSearch.SearchFilters.CarriersPreference = optCarriers;
                //Setting up the Airport Origin and Destinations
                if (this.currentResults.appliedSearch.SearchFilters.AirportsDestination.length == 0 && this.currentResults.SearchFilters.AirportsDestinationList && this.currentResults.SearchFilters.AirportsDestinationList.length > 0) {
                    var destinationCodes = [];
                    var activeDestination = _.where(this.currentResults.SearchFilters.AirportsDestinationList, {
                        'Active': true
                    });
                    destinationCodes = _.map(activeDestination, function (s) {
                        return s.Code;
                    });

                    if (destinationCodes.length > 0) {
                        this.currentResults.appliedSearch.SearchFilters.AirportsDestination = destinationCodes.join();
                    }
                }
                if (this.currentResults.appliedSearch.SearchFilters.AirportsOrigin.length == 0 && this.currentResults.SearchFilters.AirportsOriginList && this.currentResults.SearchFilters.AirportsOriginList.length > 0) {
                    var departCodes = [];
                    var activeOrigin = _.where(this.currentResults.SearchFilters.AirportsOriginList, {
                        'Active': true
                    });
                    departCodes = _.map(activeOrigin, function (s) {
                        return s.Code;
                    });

                    if (departCodes.length > 0) {
                        this.currentResults.appliedSearch.SearchFilters.AirportsOrigin = departCodes.join();
                    }
                }

                tripIndex = this.getTripIndex();
                trip = this.currentResults.appliedSearch.Trips[tripIndex];
                trip.nonStop = nonStop;
                trip.oneStop = oneStop;
                trip.twoPlusStop = twoPlusStop;
                this.setFilterFromTrip(this.currentResults.appliedSearch.SearchFilters, tripIndex + 1);
                //<!-- CARRIER PREFERENCE -->
                if ($('#filter-airline-united').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.CarrierDefault = $('#filter-airline-united').is(':checked');
                }

                if ($('#filter-airline-united-express').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.CarrierExpress = $('#filter-airline-united-express').is(':checked');
                }

                if ($('#filter-airline-star-alliance').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.CarrierStar = $('#filter-airline-star-alliance').is(':checked');
                }

                if ($('#filter-airline-partner').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.CarrierPartners = $('#filter-airline-partner').is(':checked');
                }
                //Setting CARRIER PREFERENCE
                //if (this.currentResults.appliedSearch.SearchFilters.CarriersPreference.length == 0) {
                //    if (this.currentResults.SearchFilters.CarrierDefault) {
                //        this.currentResults.appliedSearch.SearchFilters.CarriersPreference.push('CarrierDefault');
                //    }
                //    if (this.currentResults.SearchFilters.CarrierExpress) {
                //        this.currentResults.appliedSearch.SearchFilters.CarriersPreference.push('CarrierExpress');
                //    }
                //    if (this.currentResults.SearchFilters.CarrierStar) {
                //        this.currentResults.appliedSearch.SearchFilters.CarriersPreference.push('CarrierStar');
                //    }
                //    if (this.currentResults.SearchFilters.CarrierPartners) {
                //        this.currentResults.appliedSearch.SearchFilters.CarriersPreference.push('CarrierPartners');
                //    }
                //    this.currentResults.appliedSearch.SearchFilters.CarriersPreference = _.uniq(this.currentResults.appliedSearch.SearchFilters.CarriersPreference);
                //}

                /*if ($('#airport-route-content').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.AirportFilterActive = $('#airport-route-content').is(':visible');
                }*/

                if ($('#filter-aircraft-single-cabin').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.SingleCabinExist = true;
                }

                if ($('#filter-aircraft-multi-cabin').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.MultiCabinExist = true;
                }

                if ($('#filter-aircraft-turbo-prop').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.TurboPropExist = true;
                }

                if (this.searchFilterMode === 'footerondemand') {
                    this.currentResults.appliedSearch.SearchFilters.FilterApplied = true;
                }
                this.isFilterClick = true;
                this.loadFilterResults(this.currentResults.appliedSearch);

                if ($("#newfilter_stop").is(':checked')) {//update bottom filters based on top filters for stops only RRM

                    if ($('#filter_oneStop').length) {
                        $('#filter_oneStop').prop('checked', true);
                    }
                    if ($('#filter_twoPlusStop').length) {
                        $('#filter_twoPlusStop').prop('checked', true);
                    }
                } else {
                    if ($('#filter_oneStop').length) {
                        $('#filter_oneStop').prop('checked', false);
                    }
                    if ($('#filter_twoPlusStop').length) {
                        $('#filter_twoPlusStop').prop('checked', false);
                    }
                }

            },
            handleCheckBoxFilterClick: function (e) {
                var target = $(e.currentTarget);
                //if (this.showTopFilters) { 
                //    if (((target.is('#filter_oneStop') || target.is('#filter_twoPlusStop'))
                //        && target.is(':checked')
                //        && $('#' + this.elements.filterConnectionId + ' input:checkbox:checked').length == 0) 
                //        || (this.currentResults.appliedSearch.SearchFilters.filterOnlyClick == 'oneStop'
                //        || this.currentResults.appliedSearch.SearchFilters.filterOnlyClick == 'twoPlusStop')) {
                //        $('#' + this.elements.filterConnectionId + ' input:checkbox').prop('checked', true);
                //        $('#filter-checkbox-connections input:checkbox').prop('checked', true);//
                //        UA.UI.reInit($('#' + this.elements.filterConnectionId));
                //        //return;
                //    }
                //    //return;

                //    if (typeof this.currentResults.appliedSearch.SearchFilters.filterOnlyClick == 'undefined') {
                //        this.currentResults.appliedSearch.SearchFilters.filterOnlyClick = false;
                //    }
                //    if (($('#' + this.elements.filterConnectionId + ' input:checkbox').length == 0)
                //        && (this.currentResults.appliedSearch.SearchFilters.filterOnlyClick == 'airportOnly')
                //        && (this.currentResults.appliedSearch.SearchFilters.oneStop == true || this.currentResults.appliedSearch.SearchFilters.twoPlusStop == true)) {
                //        $('#' + this.elements.filterConnectionId + ' input:checkbox').prop('checked', true);
                //        $('#filter-checkbox-connections input:checkbox').prop('checked', true);
                //    }

                //}
                var i, nonStop = $('#filter_nonStop').is(':checked'),
                    oneStop = $('#filter_oneStop').is(':checked'),
                    twoPlusStop = $('#filter_twoPlusStop').is(':checked'),
                    airportsToAvoid, onestopcount, twostopcount, tripIndex, trip, _this = this;

                if ($('#' + this.elements.filterConnectionId + ' input:checkbox:checked').length == 1 && (oneStop == false && twoPlusStop == false)) {

                    _this.currentResults.appliedSearch.SearchFilters.oneStop = true;
                    _this.currentResults.appliedSearch.SearchFilters.twoPlusStop = true;
                    $('#filter_oneStop').prop('checked', true);
                    $('#filter_twoPlusStop').prop('checked', true);
                    $('#newfilter_stop').prop('checked', true);
                    oneStop = true;
                    twoPlusStop = true;
                }

                if (this.currentResults.SearchFilters.OneStopAirports != null && this.currentResults.SearchFilters.TwoPlusStopAirports != null) {

                    onestopcount = this.currentResults.SearchFilters.OneStopAirports.length;
                    twostopcount = this.currentResults.SearchFilters.TwoPlusStopAirports.length;
                    if (target.is('#filter_oneStop') && this.currentResults.SearchFilters.HideOneStop == false && !oneStop) {
                        for (var i = 0; i < onestopcount; i++) {
                            $('#filter-connection-' + this.currentResults.SearchFilters.OneStopAirports[i]).prop('checked', false);
                        }
                        for (var i = 0; i < twostopcount; i++) {
                            $('#filter-connection-' + this.currentResults.SearchFilters.TwoPlusStopAirports[i]).prop('checked', true);
                        }
                        _this.currentResults.appliedSearch.SearchFilters.oneStop = false;
                    }
                    else if (target.is('#filter_oneStop') && this.currentResults.SearchFilters.HideOneStop == false && oneStop) {
                        for (var i = 0; i < onestopcount; i++) {
                            $('#filter-connection-' + this.currentResults.SearchFilters.OneStopAirports[i]).prop('checked', true);
                        }
                        _this.currentResults.appliedSearch.SearchFilters.oneStop = true;
                    }

                    if (target.is('#filter_twoPlusStop') && this.currentResults.SearchFilters.HideTwoPlusStop == false && !twoPlusStop) {
                        for (var i = 0; i < twostopcount; i++) {
                            $('#filter-connection-' + this.currentResults.SearchFilters.TwoPlusStopAirports[i]).prop('checked', false);
                        }
                        for (var i = 0; i < onestopcount; i++) {
                            $('#filter-connection-' + this.currentResults.SearchFilters.OneStopAirports[i]).prop('checked', true);
                        }
                        _this.currentResults.appliedSearch.SearchFilters.twoPlusStop = false;
                    }
                    else if (target.is('#filter_twoPlusStop') && this.currentResults.SearchFilters.HideTwoPlusStop == false && twoPlusStop) {
                        for (var i = 0; i < twostopcount; i++) {
                            $('#filter-connection-' + this.currentResults.SearchFilters.TwoPlusStopAirports[i]).prop('checked', true);
                        }
                        _this.currentResults.appliedSearch.SearchFilters.twoPlusStop = true;
                    }
                }
                if ((this.currentResults.SearchFilters.HideNoneStop == false && (oneStop == false && this.currentResults.SearchFilters.HideTwoPlusStop == true) || oneStop == false && twoPlusStop == false)) {
                    $('#filter-checkbox-connections').find('input[type=checkbox]:checked').removeAttr('checked');
                }

                $('#filter-checkbox-connections input[type=checkbox]').change(function () {
                    if ($("#filter-checkbox-connections input:checkbox:checked").length == 0) {
                        $('#filter_oneStop').prop('checked', false);
                        $('#filter_twoPlusStop').prop('checked', false);
                        $('#newfilter_stop').prop('checked', false);
                        _this.currentResults.appliedSearch.SearchFilters.oneStop = false; //fottom airports uncheck last airport unchecks top withstop checkbox SHD
                        _this.currentResults.appliedSearch.SearchFilters.twoPlusStop = false;
                    }

                    //718372 - EQA Production: 2+ stops filter is checked when there are no flights displayed on FSR page
                    if ($("#filter-checkbox-connections input:checkbox:checked").length == 1) {
                        $('#filter_twoPlusStop').prop('checked', false);
                        _this.currentResults.appliedSearch.SearchFilters.twoPlusStop = false;
                    }
                    if ($("#filter-checkbox-connections input:checkbox:checked").length >= 2) {
                        $('#filter_oneStop').prop('checked', true);
                        $('#filter_twoPlusStop').prop('checked', true);
                        //$('#newfilter_stop').prop('checked', true);
                        _this.currentResults.appliedSearch.SearchFilters.oneStop = true;
                        _this.currentResults.appliedSearch.SearchFilters.twoPlusStop = true;
                    }

                });
                //Bottom [X]one stop [X] two stop, update top filters

                //Bottom [ ]one stop [X] two stop, update top filters
                //Bottom [X]one stop [ ] two stop, update top filters
                //Bottom [ ]one stop [ ] two stop, update top filters
                //Bottom [X]one stop [X] two stop, update top filters

                //Bottom [X] nonstop, update top filter
                //Bottom [ ] nonstop, update top filter



                //multi-directional checkbox fixes SHD
                //if (this.showTopFilters && (this.searchFilterMode === 'footerondemand' || this.searchFilterMode === 'footer') && target.is('#filter_nonStop')) {
                //    $('#newfilter_nonStop').prop('checked', nonStop);
                //}
                //if (this.showTopFilters && !(target.is('#filter_oneStop') || target.is('#filter_twoPlusStop') || target.is('#filter_nonStop'))) {
                //    nonStop = $('#newfilter_nonStop').is(':checked');
                //    if ($('#newfilter_stop').is(':checked')) {
                //        if (this.currentResults.SearchFilters.HideOneStop == false && target.is('#filter_oneStop')) {
                //            $('#filter_oneStop').prop('checked', true);
                //            oneStop = true;
                //        }
                //        if (this.currentResults.SearchFilters.HideTwoPlusStop == false && target.is('#filter_twoPlusStop')) {
                //            $('#filter_twoPlusStop').prop('checked', true);
                //            twoPlusStop = true;
                //        }
                //    }
                //    else
                //    {
                //        oneStop = twoPlusStop = false;
                //        $('#filter_oneStop').prop('checked', false);
                //        $('#filter_twoPlusStop').prop('checked', false);
                //    }
                //}
                //else
                //{
                //    $('#newfilter_nonStop').prop('checked', nonStop); //these set the state of new filters checkboxes based on bottom filters
                //    if (!_this.currentResults.SearchFilters.HideOneStop) {
                //        $('#newfilter_stop').prop('checked', oneStop);
                //    }
                //    if (!_this.currentResults.SearchFilters.HideTwoPlusStop) {
                //        $('#newfilter_stop').prop('checked', twoPlusStop);
                //    }
                //}

                if ((target.is('#filter_oneStop') || target.is('#filter_twoPlusStop')) && target.is(':checked') && $('#' + this.elements.filterConnectionId + ' input:checkbox:checked').length == 0) {
                    $('#' + this.elements.filterConnectionId + ' input:checkbox').prop('checked', true);
                    UA.UI.reInit($('#' + this.elements.filterConnectionId));
                }

                if ((target.is('#filter-onlynonstop')) && target.is(':checked')) {
                    $('#' + this.elements.filterConnectionId + ' input:checkbox').prop('checked', true);
                    UA.UI.reInit($('#' + this.elements.filterConnectionId));
                }
                var airportsStop = $.map($('#' + this.elements.filterConnectionId + ' input:checkbox:checked'), function (ev, i) {
                    return $(ev).val();
                }),
                    originList = $.map($('#' + this.elements.filterOriginId + ' input:checkbox:checked'), function (ev, i) {
                        return $(ev).val();
                    }),
                    amenitiesList = $.map($('#' + this.elements.filterAmenitiesId + ' input:checkbox:checked'), function (ev, i) {
                        return $(ev).val();
                    }),
                    destinationList = $.map($('#' + this.elements.filterDestinationId + ' input:checkbox:checked'), function (ev, i) {
                        return $(ev).val();
                    }),
                    warningList = $.map($('#' + this.elements.filterAdvisoriesId + ' input:checkbox:checked'), function (ev, i) {
                        return $(ev).val();
                    }),
                    equipCodes = $.map($('#filt-equipment-type-cont input:checkbox:checked'), function (ev, i) {
                        return $(ev).val();
                    }),
                    optCarriers = $.map($('#filt-airlines-opt-cont input:checkbox:checked'), function (ev, i) {
                        return $(ev).val();
                    }),
                    aircraftList = $.map($('#filter-checkbox-aircraft input:checkbox:checked'), function (ev, i) {
                        return $(ev).val();
                    });

                if (this.currentResults && this.currentResults.Trips && this.currentResults.Trips.length > 0 && this.currentResults.Trips[0].Flights && this.currentResults.Trips[0].Flights.length > 0) {
                    ;
                } else {
                    if (this.currentResults.appliedSearch.SearchFilters == null && this.currentResults && this.currentResults.SearchFilters) {
                        this.currentResults.appliedSearch.SearchFilters = this.currentResults.SearchFilters;
                    }
                }

                this.currentResults.appliedSearch.SearchFilters.Amenities = amenitiesList;
                this.currentResults.appliedSearch.SearchFilters.EquipmentCodes = equipCodes.join();
                this.currentResults.appliedSearch.SearchFilters.AirportsStop = airportsStop.join();
                this.currentResults.appliedSearch.SearchFilters.AirportsDestination = destinationList.join();
                this.currentResults.appliedSearch.SearchFilters.AirportsOrigin = originList.join();
                this.currentResults.appliedSearch.SearchFilters.Warnings = warningList;
                this.currentResults.appliedSearch.SearchFilters.AircraftList = aircraftList;
                this.currentResults.appliedSearch.SearchFilters.CarriersPreference = optCarriers;
                tripIndex = this.getTripIndex();
                trip = this.currentResults.appliedSearch.Trips[tripIndex];
                trip.nonStop = nonStop;
                if (_this.currentResults.SearchFilters.HideOneStop) {
                    oneStop = false;
                }
                trip.oneStop = oneStop;
                if (_this.currentResults.SearchFilters.HideTwoPlusStop) {
                    twoPlusStop = false;
                }
                trip.twoPlusStop = twoPlusStop;
                this.currentResults.appliedSearch.SearchFilters.twoPlusStop = twoPlusStop;
                this.setFilterFromTrip(this.currentResults.appliedSearch.SearchFilters, tripIndex + 1);

                    //<!-- CARRIER PREFERENCE -->
                if ($('#filter-airline-united').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.CarrierDefault = $('#filter-airline-united').is(':checked');
                }

                if ($('#filter-airline-united-express').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.CarrierExpress = $('#filter-airline-united-express').is(':checked');
                }

                if ($('#filter-airline-star-alliance').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.CarrierStar = $('#filter-airline-star-alliance').is(':checked');
                }

                if ($('#filter-airline-partner').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.CarrierPartners = $('#filter-airline-partner').is(':checked');
                }

                    /*if ($('#airport-route-content').is(':checked')) {
                        this.currentResults.appliedSearch.SearchFilters.AirportFilterActive = $('#airport-route-content').is(':visible');
                    }*/

                if ($('#filter-aircraft-single-cabin').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.SingleCabinExist = true;
                }

                if ($('#filter-aircraft-multi-cabin').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.MultiCabinExist = true;
                }

                if ($('#filter-aircraft-turbo-prop').is(':checked')) {
                    this.currentResults.appliedSearch.SearchFilters.TurboPropExist = true;
                }

                if (this.searchFilterMode === 'footerondemand') {
                    this.currentResults.appliedSearch.SearchFilters.FilterApplied = true;
                }
                if (this.currentResults && this.currentResults.Trips && this.currentResults.Trips.length > 0 && this.currentResults.Trips[0].Flights && this.currentResults.Trips[0].Flights.length > 0) {
                    this.loadFilterResults(this.currentResults.appliedSearch);
                } else {
                    this.loadFilterResults(this.currentResults.appliedSearch, false, false, true);
                }
                $("#fl-bestresult-notification").empty();
            },
            setFilterFromTrip: function (reqSearchFilters, tripIndex, respSearchFilters) {
                //var tripIndex = parseInt(this.elements.currentTripIndex.val(), 10);
                //adjust to zero based
                tripIndex = tripIndex - 1;
                if (tripIndex < 0) {
                    tripIndex = 0;
                }

                var trip = this.currentResults.appliedSearch.Trips[tripIndex];
                var NonStopOnly = trip.nonStopOnly;
                //Make sure we check to see if Stops are available for selection
                if ($.isEmptyObject(respSearchFilters) === false) {
                    respSearchFilters.nonStop = trip.nonStop;
                    respSearchFilters.oneStop = trip.oneStop;
                    respSearchFilters.twoPlusStop = trip.twoPlusStop;
                    respSearchFilters.nonStopOnly = trip.nonStopOnly;
                    if (reqSearchFilters.FareFamily == null) {
                        reqSearchFilters.FareFamily = respSearchFilters.FareFamily;
                    }
                }

                reqSearchFilters.ClearAllFilters = trip.ClearAllFilters;
                reqSearchFilters.nonStop = trip.nonStop;
                reqSearchFilters.oneStop = trip.oneStop;
                reqSearchFilters.twoPlusStop = trip.twoPlusStop;
                this.currentResults.appliedSearch.nonStopOnly = 0;
                this.currentResults.appliedSearch.calendarStops = 4;
                //Non-stops [X]  1 stop [ ], 2+ stops [ ]
                if (reqSearchFilters.nonStop === true && reqSearchFilters.oneStop === false && reqSearchFilters.twoPlusStop === false) {
                    reqSearchFilters.StopCountMin = 0;
                    reqSearchFilters.StopCountMax = 0;
                    this.currentResults.appliedSearch.nonStopOnly = 1;
                    this.currentResults.appliedSearch.calendarStops = 0;
                }
                //Non-stops [ ], 1 stop [X], 2+ stops [ ]
                if (reqSearchFilters.nonStop === false && reqSearchFilters.oneStop === true && reqSearchFilters.twoPlusStop === false) {
                    reqSearchFilters.StopCountMin = 1;
                    reqSearchFilters.StopCountMax = 1;
                }
                //Non-stops [ ], 1 stop [ ], 2+ stops [X]
                if (reqSearchFilters.nonStop === false && reqSearchFilters.oneStop === false && reqSearchFilters.twoPlusStop === true) {
                    reqSearchFilters.StopCountMin = 2;
                }
                //Non-stops [X], 1 stop [X], 2+ stops [ ]
                if (reqSearchFilters.nonStop === true && reqSearchFilters.oneStop === true && reqSearchFilters.twoPlusStop === false) {
                    reqSearchFilters.StopCountMin = 0;
                    reqSearchFilters.StopCountMax = 1;
                }
                //Non-stops [ ], 1 stop [X], 2+ stops [X]
                if (reqSearchFilters.nonStop === false && reqSearchFilters.oneStop === true && reqSearchFilters.twoPlusStop === true) {
                    reqSearchFilters.StopCountMin = 1;
                }
                //Non-stops [x], 1 stop [], 2+ stops [X]
                if (reqSearchFilters.nonStop === true && reqSearchFilters.oneStop === false && reqSearchFilters.twoPlusStop === true) {
                    reqSearchFilters.StopCountExcl = 1;
                }

                if (($('#filter-onlynonstop').is(':checked') || $('#notstoponlyv2').is(':checked')) || NonStopOnly == true) {
                    this.currentResults.appliedSearch.nonStopOnly = 1;
                    this.currentResults.appliedSearch.calendarStops = 0;
                } else {
                    this.currentResults.appliedSearch.nonStopOnly = 0;
                    this.currentResults.appliedSearch.calendarStops = 4;
                }
            },
            signIn: function (e) {
                var button, signInData, load,
                    self = this,
                    tag = $('#divRequireSignIn'),
                    authUrl = tag.data('authurl'),
                    reviewUrl = tag.data('reviewurl'),
                    form = $(e.currentTarget),
                    isReshopPath = false;

                if (form === null || !form.valid()) {
                    return false;
                }

                button = $(form).find('#btnSignIn').loader({
                    preset: 'btnTile'
                });

                signInData = {
                    MpNumber: $('#MpNumber').val(),
                    Password: $('#Password').val(),
                    RememberMe: $('#RememberMe').is(':checked'),
                    DbEnvironment: $('input:radio[name=DbEnvironment]:checked').val(),
                    AllowEnrollment: true,
                    AllowRememberMe: true,
                    ShowTileAd: false,
                    ShowSignInHeader: true,
                    IsSignInRequired: true
                };

                if ((UA && UA.ReShop && UA.ReShop.Login) && UA.ReShop.Login.handleSignIn(signInData, form, tag) == false) {
                    return false;
                }
                if (UA && UA.ReShop && UA.ReShop.Login) {
                    UA.ReShop.Login.LogoutExistingInvalidUser();
                    isReshopPath = true;
                }

                load = $.ajax({
                    url: authUrl,
                    type: "POST",
                    data: signInData,
                    dataType: 'html'
                });
                load.success(function (signInResponseData) {
                    button.loader('destroy');

                    var result,
                        actionUrl = reviewUrl,
                        hdnIsSignedIn = $(signInResponseData).find('#hdnIsSignedIn'),
                        hdnIsEmployeeSignedIn = $(signInResponseData).find('#hdnIsEmployeeSignedIn'),
                        hdnUpdatedUrl = $($(signInResponseData).find('#hdnIsRedirect')).val(),
                        selectorForm = '#flightSearch',
                        hdnIsUpdates = $(signInResponseData).find('#hdnIsUpdates');

                    if (hdnIsSignedIn !== null && hdnIsSignedIn.val() === "True") {
                        $('.account-tool').loader({
                            preset: 'smallRight'
                        });

                        if (!isReshopPath && hdnUpdatedUrl && hdnUpdatedUrl.length >= 1 && hdnUpdatedUrl !== "") {
                            var travelerFormAction = $(selectorForm).attr("action");
                            var posUpdatedUrl = hdnUpdatedUrl.substr(0, hdnUpdatedUrl.indexOf('book-a-flight'));
                            var travelerInfoUrl = travelerFormAction.replace(travelerFormAction.substr(0, travelerFormAction.indexOf('book-a-flight')), '');
                            if (posUpdatedUrl !== "") {
                                actionUrl = posUpdatedUrl + travelerInfoUrl;
                                $(selectorForm).attr("action", actionUrl);
                            }
                        }

                        self.postToReviewTrip({
                            postUrl: actionUrl,
                            cellIdSelected: $("#selectCellIdSelected").val(),
                            solutionSetId: $("#selectSolutionSetId").val(),
                            cartId: $("#selectCartId").val(),
                            additionalUpgradeIds: $("#hdnAdditionalUpgradeId").val()
                        });

                    } else if (hdnIsEmployeeSignedIn && hdnIsEmployeeSignedIn.val() === "True") {
                        $.modal.close();
                    } else {
                        if (hdnIsUpdates && hdnIsUpdates.val() === "True") {
                            var headerSignInTag = $('#aHeaderSignIn');
                            UA.Utilities.loadScriptCallback(headerSignInTag.data('updates-bundle-href'), function () {
                                UA.Common.AcctUpdates.processStart(signInResponseData, true, true);
                            });
                            //UA.Common.AcctUpdates.processStart(signInResponseData, true, true);
                        } else {
                            result = $('#divSignInModal');
                            result.fadeOut(50, function () {

                                jQuery(result)
                                    .empty()
                                    .append(signInResponseData)
                                    .find('#frm-login')
                                    .submit($.proxy(self.signIn, self));

                                UA.UI.reInit(result);
                                result.fadeIn(100, function () {
                                    UA.UI.Tooltip.showValidation(null, result);
                                });
                            });
                        }
                    }
                });
                load.error(function () {
                    form.find('#Password').val('').change();
                    button.loader('destroy');
                });

                return false;
            },
            postToReviewTrip: function (params) {
                var placeholder = $('#divTmp'),
                    postHtml;

                //clear page and show loading indicator
                this.elements.calendarContainer.empty();
                if (showFsrTips) {
                    if (fsrTipsPhase2) {
                        this.emptyFsrTips();
                    } else {
                        this.elements.resultsHeaderSegmentNearbyCities.empty();
                        this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
                        this.elements.resultsHeaderSegmentBetterOffers.empty();
                    }
                }
                this.elements.resultsHeaderSegmentContainer.empty();
                this.elements.resultsHeaderSegmentFareDisclaimerContainer.empty();
                this.elements.resultsHeaderContainer.empty();
                this.elements.resultsContainer.empty();
                this.elements.filterSortContainer.empty();
                this.elements.newSearchContainer.empty();
                this.elements.resultsFooter.empty();
                this.elements.selectedFlightContainer.empty();
                this.elements.resetNotificationContainer.empty();
                this.resetTabbedFWHeader();
                $('.cart-container').empty();
                this.clearFSRResults();
                this.showPageLoader();

                var isReshopPath = this.currentResults.appliedSearch.isReshopPath;
                
                var relocateRti;
                if (this.isRelocateRtiDesignActive()) {
                    relocateRti = true;
                    var flightLen = this.selectedFlights.length;
                    for (var i = 0; i < flightLen - 1; ++i) {
                        var flight = this.selectedFlights[i];
                        if (flight.isElf === "true" ||
                            flight.IsIBEType === "true") {
                            relocateRti = false;
                            break;
                        }
                    }

                    if (relocateRti && flightLen > 0) {
                        var lastFlight = this.selectedFlights[flightLen - 1];
                        if (lastFlight.isElf === "true" ||
                            flight.IsIBEType === "true") {
                            relocateRti = false;
                        } else if (lastFlight.isElf === undefined && lastFlight.ProductCode == undefined) {
                            if (this.currentResults.Trips[0].SolutionSetId === params.solutionSetId) {
                                var columnLen = this.currentResults.Trips[0].Columns.length;
                                for (var j = 0; j < columnLen; ++j) {
                                    var column = this.currentResults.Trips[0].Columns[j];
                                    if (column.Selected === true) {
                                        if (column.FareFamilies === "ECO-BASIC") {
                                            relocateRti = false;
                                        }
                                        break;
                                    }
                                }
                            }
                        }
                    }
                } else {
                    relocateRti = false;
                }
                var skipCartEmptyValidation = false;
                if (!isReshopPath) {
                    this.IsShopbookingDetailsSuccess(params.cartId, params.solutionSetId, params.cellIdSelected);
                }
                else {
                    var totalTrips = parseInt($("#hdnTotalTrips").val(), 10);
                    if (totalTrips == 0 && this.currentResults !== null && this.currentResults !== 'undefined') {
                        skipCartEmptyValidation = true;
                    }
                }
                //create hidden form and submit
                // If condtion is to Skip RTI Page for Maxymiser Test Path                
                if ($('#hdnSkipRTIMaxymiserTestPath').val() == "true" && !isReshopPath) {
                    postHtml = '<form id="travelerInfoForm" method="post" action="' + $('#fl-results-wrapper').data('travelerinfourl') + '"> \n' +
                        ' <input type="hidden" name="CellIdSelected" value="' + params.cellIdSelected + '" /> \n' +
                        ' <input type="hidden" name="SolutionSetId" value="' + params.solutionSetId + '" /> \n' +
                        ' <input type="hidden" name="CartId" value="' + params.cartId + '" /> \n' +
                        ' <input type="hidden" name="IncludeLmx" value="' + this.currentResults.appliedSearch.IncludeLmx + '" /> \n' +
                        ' <input type="hidden" name="AwardTravel" value="' + this.currentResults.appliedSearch.awardTravel + '" /> \n' +
                        ' <input type="hidden" name="CorporateBooking" value="' + this.currentResults.appliedSearch.CorporateBooking + '" /> \n' +
                        ' <input type="hidden" name="EPlusProductCode" value="' + params.ePlusProductCode + '" /> \n' +
                        ' <input type="hidden" name="EPlusBundleId" value="' + params.ePlusBundleId + '" /> \n' +
                        ' <input type="hidden" name="EPlusFlightHash" value="' + params.ePlusFlightHash + '" /> \n' +
                        ' <input type="hidden" name="EPlusProductId" value="' + params.ePlusProductId + '" /> \n' +
                        ' <input type="hidden" name="RelocateRti" value="' + relocateRti + '" /> \n' +
                        '</form>';

                    placeholder.html(postHtml);

                    $('#travelerInfoForm').submit();
                } else {
                    var errorHtml = '';
                    if (!_.isEmpty(this.shopBookingDetailsError)) {
                        errorHtml = ' <input type="hidden" name="emaj" value="' + this.shopBookingDetailsError.MajorCode + '" /> \n' +
                            ' <input type="hidden" name="emin" value="' + this.shopBookingDetailsError.MinorCode + '" /> \n';
                    }
                    postHtml = '<form id="reviewFlightForm" method="post" action="' + params.postUrl + '"> \n' +
                        ' <input type="hidden" name="CellIdSelected" value="' + params.cellIdSelected + '" /> \n' +
                        ' <input type="hidden" name="SolutionSetId" value="' + params.solutionSetId + '" /> \n' +
                        ' <input type="hidden" name="CartId" value="' + params.cartId + '" /> \n' +
                        ' <input type="hidden" name="ConfirmationID" value="' + $('#hdnConfirmationID').val() + '" /> \n' +
                        ' <input type="hidden" name="IncludeLmx" value="' + this.currentResults.appliedSearch.IncludeLmx + '" /> \n' +
                        ' <input type="hidden" name="AwardTravel" value="' + this.currentResults.appliedSearch.awardTravel + '" /> \n' +
                        ' <input type="hidden" name="CorporateBooking" value="' + this.currentResults.appliedSearch.corporateBooking + '" /> \n' +
                        ' <input type="hidden" name="EPlusProductCode" value="' + params.ePlusProductCode + '" /> \n' +
                        ' <input type="hidden" name="EPlusBundleId" value="' + params.ePlusBundleId + '" /> \n' +
                        ' <input type="hidden" name="EPlusFlightHash" value="' + params.ePlusFlightHash + '" /> \n' +
                        ' <input type="hidden" name="EPlusProductId" value="' + params.ePlusProductId + '" /> \n' +
                        ' <input type="hidden" name="SelectedUpgradePrices" value="' + params.additionalUpgradeIds + '" /> \n' +
                        ' <input type="hidden" name="RelocateRti" value="' + relocateRti + '" /> \n' +
                        ' <input type="hidden" name="SkipCartEmptyValidation" value="' + skipCartEmptyValidation + '" /> \n' + errorHtml +
                        '</form>';

                    placeholder.html(postHtml);

                    $('#reviewFlightForm').submit();
                }

            },
            showLoginModal: function (e) {
                var self = this,
                    tag = $('#divRequireSignIn'),
                    authFormUrl = tag.data('modalurl'),
                    signInData = {
                        AllowEnrollment: true,
                        AllowRememberMe: true,
                        ShowTileAd: false,
                        ShowSignInHeader: true
                    };
                if (UA && UA.ReShop && UA.ReShop.Login) {
                    var queryParams = window.location.href;
                    signInData.IsAwardTravel = _.contains(queryParams, 'awd');
                    signInData.ShowReShopHeader = true;
                }

                $("<div id='divSignInModal' class='modal-sign-in-content' />").modal({
                    minWidth: 360,
                    minHeight: 350,
                    containerClass: 'modal-sign-in modal-tile',
                    onOpen: function (dialog) {
                        var simplemodalInstance = this;
                        dialog.overlay.fadeIn(100);
                        dialog.container.fadeIn(100, function () {
                            var load, container = $(this);
                            container.loader();
                            load = $.ajax({
                                url: authFormUrl,
                                type: "POST",
                                data: signInData,
                                dataType: 'html'
                            });
                            load.success(function (signInViewHtml) {
                                container.loader('destroy');
                                dialog.data.append(signInViewHtml)
                                    .find('#frm-login')
                                    .submit($.proxy(self.signIn, self))
                                    .end()
                                    .fadeIn(100);
                                UA.UI.reInit(container);
                                simplemodalInstance.setLabel(true);
                            });
                            load.error(function () {
                                container.loader('destroy');
                                $.modal.close();
                            });
                        });
                    }
                });
                return false;
            },
            changeTrip: function (e) {
                e.preventDefault();

                var url = $(e.currentTarget).data('href'),
                    data = $(e.currentTarget).data('trip');
                data.CartId = $("#CartId").val();
                var postHtml = '<form style="display:none;" id="cartupdate" method="post" action="' + url + '"> \n' +
                    ' <input type="hidden" name="BbxSessionId" value="' + data.BbxSessionId + '" /> \n' +
                    ' <input type="hidden" name="SolutionSetId" value="' + data.SolutionSetId + '" /> \n' +
                    ' <input type="hidden" name="CartId" value="' + data.CartId + '" /> \n' +
                    ' <input type="hidden" name="ProductId" value="' + data.ProductId + '" /> \n' +
                    ' <input type="hidden" name="TripIndex" value="' + data.TripIndex + '" /> \n' +
                    '</form>';

                jQuery('<div/>')
                    .append(postHtml)
                    .appendTo('body')
                    .find('#cartupdate')
                    .submit();

            },
            handleBackToTopClick: function (e) {
                e.preventDefault();
                $("html, body").animate({
                    scrollTop: 0
                });
            },
            handleReviseFlightClick: function (e) {
                e.preventDefault();
                var target = $(e.currentTarget),
                    flightData = target.data('trip');

                this.elements.currentTripIndex.val(flightData.TripIndex);

                //immediately remove selected and following flights from page
                var segment = target.parents('.segments').add(target.parents('.segments').nextAll('.segments'));
                segment.remove();

                //immediately remove selected and following flights from selectedFlights obj
                var index = target.parents('.flight-block-selected-flight').data('selected-flight-index');
                this.selectedFlights = this.selectedFlights.slice(0, index);

                //clear results, calendar, header
                this.elements.calendarContainer.empty();
                if (showFsrTips) {
                    if (fsrTipsPhase2) {
                        this.emptyFsrTips();
                    } else {
                        this.elements.resultsHeaderSegmentNearbyCities.empty();
                        this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
                        this.elements.resultsHeaderSegmentBetterOffers.empty();
                    }
                }
                this.elements.resultsHeaderSegmentContainer.empty();
                this.elements.resultsHeaderSegmentFareDisclaimerContainer.empty();
                this.elements.resultsHeaderContainer.empty();
                this.elements.resultsContainer.empty();
                this.elements.filterSortContainer.empty();
                this.elements.resetNotificationContainer.empty();

                flightData.SelectableUpgradesOriginal = this.currentResults.SelectableUpgradesOriginal;

                //clear data if tripindex = 1
                if (flightData.TripIndex == 1) {
                    this.currentResults.appliedSearch.CartId = '';
                    this.currentResults.appliedSearch.SolutionSetId = '';
                    this.currentResults.appliedSearch.CellIdSelected = '';
                    this.loadFlightResults(this.currentResults.appliedSearch);
                } else {
                    this.loadFlightResults(flightData);
                }
            },
            handleResultViewTypeChange: function (e) {
                if (this.getFSRVersion() != "3") {
                    var option = $(e.currentTarget);
                option.attr('id') == 'resultViewTypeList' ? this.setListView() : this.setExpandedView();
                }
            },
            setListView: function () {
                this.storeResultViewType('list');
                this.currentResults.IsListView = true;
                this.elements.resultsContainer.addClass('flight-block-style-list');
                $(this.elements.sorterContainerId).addClass('sorter-style-list');

                this.initFlightBlock();
                $('.list-view-tip').removeClass('hidden');
            },
            setExpandedView: function () {
                this.storeResultViewType('expanded');
                this.currentResults.IsListView = false;
                this.elements.resultsContainer.removeClass('flight-block-style-list');
                $(this.elements.sorterContainerId).removeClass('sorter-style-list');
                this.initFlightBlock();
                $('.list-view-tip').addClass('hidden');
            },
            storeResultViewType: function (type) {
                safeSessionStorage.setItem('resultExpandedViewState', type === 'list' ? 0 : 1)
            },
            fetchResultViewType: function () {
                return !parseInt(safeSessionStorage.getItem('resultExpandedViewState'), 10);
            },
            handleSortChange: function (e, data) {
                var target = $(e.currentTarget),
                    sortType = target.val(),
                    sorter;

                this.currentResults.appliedSearch.SortType = sortType;
                if (data && data.fareType) {
                    this.currentResults.appliedSearch.SearchFilters.SortFareFamily = data.fareType;
                }

                sorter = this.setSorterState(sortType, data);

                $("#fl-results-pager-container").trigger('search.sort.changed');
            },
            handleSorterClick: function (e) {
                e.preventDefault();

                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                    return;
                }

                var sorter = $(e.currentTarget),
                    sorterSelect = $('#SortType'),
                    data;

                //go back to best matches if shift click
                if (e.shiftKey) {
                    sorter.removeClass('active ascending descending');
                    sorterSelect.val('bestmatches').change();
                    return;
                }
                data = {
                    sorter: sorter,
                    fareType: sorter.data('product-type')
                }

                if (sorter.hasClass('descending') || !sorter.hasClass('active')) {
                    sorterSelect.val(sorter.data('sort-ascending')).trigger('change', data);
                } else {
                    sorterSelect.val(sorter.data('sort-descending')).trigger('change', data);
                }

                if(!this.currentResults.appliedSearch.awardTravel)
                    UA.Common.SortDropdown.setValue($('#SortType').val());

                if (this.currentResults.appliedSearch.UpgradeType && this.currentResults.appliedSearch.UpgradeType.toUpperCase() == 'POINTS') {
                    $('#SortType').val(this.currentResults.appliedSearch.SortType);
                    if (this.currentResults.appliedSearch.SortType != null && (this.currentResults.appliedSearch.SortType == 'price_low' || this.currentResults.appliedSearch.SortType == 'price_high')) {
                         $('.selectedtext-sortflights').text($('#dropdownCustomText').val());
                         $('.sort-flight-content .sort-selected-text').text($('#dropdownCustomText').val());
                    }
                    else {
                        var sortByText = $('#SortType').find('option:selected').text();
                        $('.selectedtext-sortflights').text(sortByText);
                        $('.sort-flight-content .sort-selected-text').text(sortByText);
                    }
                }

            },
            setSorterState: function (sortType, data) {

                var sorter, isActive, sortDirection, sorterTrigger;

                $('#announceDepartSort').text("");
                $('#announceArriveSort').text("");
                $('#announceStopSort').text("");
                $('#announceDurationSort').text("");
                $("[id*=announcePriceSort]").text("");
                switch (sortType) {
                    case 'bestmatches':
                        return;
                    case 'departure_early':
                        sortDirection = 'ascending';
                        sorter = $('.sorter-depart');
                        $('#announceDepartSort').text("sorted ascending");
                        break;
                    case 'departure_afternoon':
                        sortDirection = 'ascending';
                        sorter = $('.sorter-depart');
                        $('#announceDepartSort').text("sorted afternoon");
                        break;
                    case 'departure_evening':
                        sortDirection = 'ascending';
                        sorter = $('.sorter-depart');
                        $('#announceDepartSort').text("sorted evening");
                        break;
                    case 'departure_late':
                        sortDirection = 'descending';
                        sorter = $('.sorter-depart');
                        $('#announceDepartSort').text("sorted descending");
                        break;
                    case 'departure_afternoon':
                        sortDirection = 'descending';
                        sorter = $('.sorter-depart');
                        $('#announceDepartSort').text("sorted descending");
                        break;
                    case 'arrival_early':
                        sortDirection = 'ascending';
                        sorter = $('.sorter-arrive');
                        $('#announceArriveSort').text("sorted ascending");
                        break;
                    case 'arrival_late':
                        sortDirection = 'descending';
                        sorter = $('.sorter-arrive');
                        $('#announceArriveSort').text("sorted descending");
                        break;
                    case 'stops_low':
                        sortDirection = 'ascending';
                        sorter = $('.sorter-stops');
                        $('#announceStopSort').text("sorted ascending");
                        break;
                    case 'stops_high':
                        sortDirection = 'descending';
                        sorter = $('.sorter-stops');
                        $('#announceStopSort').text("sorted descending");
                        break;
                    case 'duration_fastest':
                        sortDirection = 'ascending';
                        sorter = $('.sorter-duration');
                        $('#announceDurationSort').text("sorted ascending");
                        break;
                    case 'duration_longest':
                        sortDirection = 'descending';
                        sorter = $('.sorter-duration');
                        $('#announceDurationSort').text("sorted descending");
                        break;
                    case 'price_low':
                        sortDirection = 'ascending';
                        sorter = $('.sorter-price-' + data.fareType);
                        $('#announcePriceSort-' + data.fareType).text("sorted ascending");
                        break;
                    case 'price_high':
                        sortDirection = 'descending';
                        sorter = $('.sorter-price-' + data.fareType);
                        $('#announcePriceSort-' + data.fareType).text("sorted descending");
                        break;
                }

                isActive = sorter.hasClass('active');

                sorterTrigger = sorter.find('.sorter-trigger');


                //remove all active sorters
                if (!isActive) {
                    $('.sorter').removeClass('active ascending descending').attr('aria-sort', 'none');
                    sorter.addClass('active');
                }

                if (sortDirection == 'ascending') {
                    sorter.addClass('ascending').removeClass('descending');
                } else {
                    sorter.addClass('descending').removeClass('ascending');
                }


                return sorter;
            },
            handleElfFareRestrictionAgreeChange: function (e) {

                var el = $(e.currentTarget);
                $('#btn-select-elf-fare').prop('disabled', el.prop('checked') === false);

            },
            handleWithElfFareRestrictionAgreeChange: function (e) {

                var el = $(e.currentTarget);
                $('#btn-select-restriction-fare').prop('disabled', el.prop('checked') === false);


            },
            bindEvents: function () {

                var self = this,
                    $document = $(document);

                History.Adapter.bind(window, 'statechange', $.proxy(this.handleStateChange, this));
                //History.Adapter.bind(window, 'popstate', $.proxy(this.handleStateChange, this));

                $document.on('change', '[name="resultViewType"]', $.proxy(this.handleResultViewTypeChange, this));

                /**********************EXPAND CALENDAR SEARCH***********************************************************************************/
                $document.on('click', '.close-calendar-search', this.handleCloseCalendarSearchClick);

                /**********************COLLAPSE CALENDAR SEARCH*********************************************************************************/
                $document.on('click', '.edit-calendar-search', this.handleEditCalendarSearchClick);

                /**********************ADVISORIES ICON TOOLTIP************************************************************************/
                $document.on('mouseenter click', '.segment-advisories', $.proxy(this.handleAdvisoriesTooltip, this));

                /**********************MIXED CABIN ICON TOOLTIP************************************************************************/
                $document.on('mouseenter click', '.fare-cabin-mixed', $.proxy(this.handleMixedCabinTooltip, this));

                /**********************MIXED UPGRADE ICON TOOLTIP************************************************************************/
                $document.on('mouseenter click', '.fare-cabin-mixed-upgrade', $.proxy(this.handleMixedUpgradeTooltip, this));

                $document.on('mouseenter click', '.ppr-upgrade-tooltip', $.proxy(this.handleUpgradeTooltipV3, this));

                /**********************FARELOCK ICON TOOLTIP************************************************************************/
                $document.on('mouseenter click', '.farelock-icon', $.proxy(this.handleFareLockTooltip, this));

                /**********************UPGRADE ELIGIBLE TOOLTIP************************************************************************/
                $document.on('mouseenter click', '.upgrade-eligible', $.proxy(this.handleUpgradeEligibleTooltip, this));

                /**********************UPGRADE NOT-ELIGIBLE TOOLTIP************************************************************************/
                $document.on('mouseenter click', '.upgrade-not-eligible', $.proxy(this.handleUpgradeNotEligibleTooltip, this));

                /**********************UPGRADE AVAILALBLE TOOLTIP************************************************************************/
                $document.on('mouseenter click', '.upgrade-available', $.proxy(this.handleUpgradeAvailableTooltip, this));

                /**********************UPGRADE WAITLIST TOOLTIP************************************************************************/
                $document.on('mouseenter click', '.upgrade-waitlist', $.proxy(this.handleUpgradeWaitlistTooltip, this));

                /**********************ON TIME PERFORMANCE TOOLTIP************************************************************************/
                $document.on('click', '.otp-tooltip-trigger', $.proxy(this.handleOnTimePerfTooltip, this));

                /**********************LMX INELIGIBLE TOOLTIP************************************************************************/
                $document.on('mouseenter click', '.lmx-ineligible-tooltip-icon', $.proxy(this.handleLmxIneligibleTooltip, this));

                /**********************LMX ACCRUAL TOOLTIP************************************************************************/
                $document.on('click', '.lmx-accrual-tooltip-trigger', $.proxy(this.handleLmxAccrualTooltip, this));

                /**********************FARE CALENDAR TOOLTIP************************************************************************/
                $document.on('mouseover focus', '.fc-calendar .cal-select-day', $.proxy(this.handleFareCalendarTooltip, this));

                /**********************FLIGHT CONNECTION TOOLTIP************************************************************************/
                $document.on('click', '.flight-connection-tooltip-trigger', $.proxy(this.handleFlightConnectionTooltip, this));

                /**********************CHANGE SORT BY****************************************************************************************/
                $document.on('change', '#SortType', $.proxy(this.handleSortChange, this));

                /**********************SORTER CLICK****************************************************************************************/
                $document.on('click', '.sorter', $.proxy(this.handleSorterClick, this));

                /**********************CHANGE UPGRADE TYPE***********************************************************************************/
                $document.on('click', '#btn-change-upgrade-type', $.proxy(this.handleUpgradeTypeChange, this));

                /**********************CHANGE TRIP LINK CLICK***********************************************************************************/
                $(document).on('click', '.cart-change-trip', $.proxy(this.changeTrip, this));

                /**********************TILE PRICE SELECTION**********************************************************************************/
                if ($('#hdnShowFareSelectButton').val() === 'True') {
                    $document.on('click', ".fare-select-button", $.proxy(this.handleFareSelection, this));
                    $document.on('click', ".price-point-middle", $.proxy(this.handleFareSelection, this));
                    $document.on('click', ".fare-select-sc-button", $.proxy(this.handleSingleColumnSelect, this));
                    $document.on('click', ".economy-select-button", $.proxy(this.handleFareSelection, this));
                    $document.on('click', ".economy-plus-select-button", $.proxy(this.handleFareSelection, this));                    
                    $document.on('click', ".economy-upsell-close", $.proxy(this.handleCloseEconomyUpsell, this));
                    $document.on('click', ".shopsearch-count-close", $.proxy(this.handleCloseShopSearchCount, this));
                } else {
                    $document.on('click', ".fare-option", $.proxy(this.handleFareSelection, this));

                    $document.on('focusin focusout', ".fare-select", $.proxy(this.handleFareFocus, this));
                }
                $document.on('click', '.fl-clear-all-filters > section > .btn-clear-all-filters', $.proxy(this.clearAllFiltersTop, this));
                $document.on('click', '.clear-filter-for-v3', $.proxy(this.clearAllFiltersTop, this));
                $document.on('click', '.bottom-clear-all-filters > .btn-clear-all-filters', $.proxy(this.clearAllFiltersBottom, this));

                /***************************AWARD CALENDAR CABIN TYPE DROPDOWN*************************************************/
                $document.on("change", "#calendar-cabintype-dropdown", $.proxy(this.handleCalendarCabinTypeChange, this));

                /***************************AWARD CALENDAR WEEKLY/MONTHLY VIEW TOGGLE*************************************************/
                $document.on("click", ".calendar-view-toggle", $.proxy(this.handleAwardCalendarViewClick, this));
                $document.on("click", ".calendar-view-toggle-ngrp", $.proxy(this.handleAwardCalendarViewClick, this));

                /***************************AWARD CALENDAR RETRY LOAD*************************************************/
                $document.on("click", ".reload-award-calendar", $.proxy(this.handleAwardCalendarRetryClick, this));

                /***************************AWARD CALENDAR - ONLY NONSTOP FILTER*************************************************/
                $document.on("click", "#award-calendar-filter-nonstop", $.proxy(this.handleAwardCalendarNonstopFilterChange, this));

                /***************************AWARD CALENDAR CHANGE RANGE*************************************************/
                $document.on("click", ".calendar-range-control", $.proxy(this.handleAwardChangeRangeClick, this));


                /***************************AVAILABILITY CALENDAR PREVIOUS/NEXT MONTH SELECTIONS**************************************/
                $document.on("click", ".move-month-next, .move-month-prev", $.proxy(this.stepCalendar, this));

                /***************************AVAILABILITY CALENDAR DROPDOWN SELECTIONS*************************************************/
                $document.on("change", "#calender-dropdown", $.proxy(this.stepCalendar, this));

                /***************************AVAILABILITY CALENDAR ONLY NON STOP AVAILABILITY******************************************/
                $document.on("click", "#filter-onlynonstop", $.proxy(this.onlyNonStop, this));

                /***************************AVAILABILITY CALENDER - UPDATE BASED ON THE DATE FOR LOWEST PRICE*************************/
                $document.on('click', '#btn-modify-fare', $.proxy(this.modifyFareCalendar, this));

                /***************************FARE CALENDAR - UPDATE BASED ON THE DATE FOR LOWEST PRICE*********************************/
                $document.on('click', '#btn-edit-cal-search-options', $.proxy(this.modifyFareCalendarSearch, this));




                /**********************BACK TO TOP LINK CLICK**************************************************************************************/
                $document.on('click', 'a[href="#top"]', $.proxy(this.handleBackToTopClick, this));

                /**********************UPDATE TRAVELERS CLICK**************************************************************************************/
                $document.on('click', '#btn-update-travelers', $.proxy(this.handleUpdateTravelersClick, this));

                /********************** RESTART SEARCH CLICK**************************************************************************************/
                $document.on('click', '[data-restart-search]', $.proxy(handleRestartSearchClick, this));

                /********************** SHOW FARE COMPARISON MODAL **************************************************************************************/
                $document.on('click', '#show-fare-compare-modal', $.proxy(this.handleFareCompareClick, this));

                /********************** CONFIRM ELF MODAL **************************************************************************************/
                $document.on('change', '#elf-fare-agree', $.proxy(this.handleElfFareRestrictionAgreeChange, this));
                $document.on('change', '#elf-restriction-fare-agree', $.proxy(this.handleWithElfFareRestrictionAgreeChange, this));
                $document.on('click', '.btn-confirm-elf-or-standard', $.proxy(this.handleConfirmFare, this));

                /********************** PREMIUM ECONOMY MODAL **************************************************************************************/
                $document.on('click', ".upgrade-upp-select-button", $.proxy(this.handleUpgradeUPPFareSelect, this));
                $document.on('click', ".upgrade-upp-no-button", $.proxy(this.handleUpgradeUPPFareSelect, this));

                /********************** REINIT STICKY ELEMENTS AFTER RESIZE **************************************************************************************/
                $document.on('toggleronshow ', $.proxy(this.initStickyElements, this));
                $document.on('toggleronhide ', $.proxy(this.initStickyElements, this));

                /********************** REVISE FLIGHT CLICK **************************************************************************************/
                $document.on('click', '.revise-flight', $.proxy(this.handleReviseFlightClick, this));

                //***************************CALENDAR DAY MONTH SELECTIONS*************************************************
                $document.on("click", ".cal-select-day", function () {
                    if (!$(this).data("cal-date")) {
                        return;
                    } else if ($(this).hasClass("calendar-loading")) {
                        return;
                    }
                    $(this).trigger('mouseleave');
                    var day = $(this).data("cal-date");

                    $('.date-searched').removeClass('date-searched');
                    $(this).addClass('date-searched');
                    self.displayAwardCalendarLowestFare();

                    if (self.CheckDepartDate(day)) {
                        self.changeSelectDay(day);
                    }
                });

                /**********************AIRPORT LOOKUP EVENTS**************************************************************************************/
                $document.on('click', '.airport-autocomplete .full-airport-list', function (e) {
                    e.preventDefault();
                    UA.Common.AirportLookup.init({
                        target: self.currentAutocompleteField
                    });
                });

                $document.on('click', '.tt-suggestion a', function (e) {
                    e.preventDefault();
                });


                $document.on('click', '.fare-cabin', function (e) {
                    e.stopPropagation();
                });

                $document.on('inview', '#fl-filter-container', function (event, isInView, visiblePartX, visiblePartY) {
                    var filterEl = $('#fl-filter-sort-wrap');
                    if (isInView) {
                        // element is now visible in the viewport
                        if (visiblePartY == 'top') {
                            filterEl.addClass('sticky stuck');
                        } else {
                            filterEl.removeClass('sticky stuck');
                        }
                    } else {
                        filterEl.addClass('sticky stuck');
                    }
                });

                $(window).scroll(function () {
                    var scrollLeft = $(window).scrollLeft();
                    self.elements.filterSortContainer.css('left', scrollLeft == 0 ? 'auto' : '-' + $(window).scrollLeft() + 'px');
                });

                $document.on('inview', '#fl-searchcount-container', function (event, isInView, visiblePartX, visiblePartY) {
                    var filterEl = $('#fl-searchcount-wrap');
                    if (isInView) {
                        // element is now visible in the viewport
                        //if (visiblePartY == 'top') {
                            //filterEl.addClass('sticky stuck');
                        //} else {
                            filterEl.removeClass('sticky stuck');
                        //}
                    } else {
                        filterEl.addClass('sticky stuck');
                    }
                });

                $(window).scroll(function () {
                    var scrollLeft = $(window).scrollLeft();
                    self.elements.filterSortContainer.css('left', scrollLeft == 0 ? 'auto' : '-' + $(window).scrollLeft() + 'px');
                });

                $document.on('click', '#searchByNearbyAirport', function (e) {
                    var formChildren = $("#flightSearch");
                    if (self != "undefined" && self != null && self.currentResults != "undefined" && self.currentResults != null && self.currentResults.appliedSearch != "undefined" &&
                        self.currentResults.appliedSearch != null && self.currentResults.appliedSearch.Trips != "undefined" && self.currentResults.appliedSearch.Trips.length > 0) {
                        if (self.currentResults.appliedSearch.Trips[0].OriginTriggeredAirport) {
                            formChildren.append("<input type='hidden' name='CboMiles' id='CboMiles' value='100' />");
                        }
                        if (self.currentResults.appliedSearch.Trips[0].DestinationTriggeredAirport) {
                            formChildren.append("<input type='hidden' name='CboMiles2' id='CboMiles' value='100' />");
                        }
                        if (!self.currentResults.appliedSearch.Trips[0].DestinationTriggeredAirport && !self.currentResults.appliedSearch.Trips[0].OriginTriggeredAirport) {
                            formChildren.append("<input type='hidden' name='CboMiles' id='CboMiles' value='100' />");
                            formChildren.append("<input type='hidden' name='CboMiles2' id='CboMiles2' value='100' />");
                        }
                    } else {
                        formChildren.append("<input type='hidden' name='CboMiles' id='CboMiles' value='100' />");
                        formChildren.append("<input type='hidden' name='CboMiles2' id='CboMiles2' value='100' />");
                    }
                    $('#flightSearch').submit();
                });
                $document.on('click', '#searchFutureTravel', function (e) {
                    var formChildren = $("#flightSearch");
                    if (self != "undefined" && self != null && self.currentResults != "undefined" && self.currentResults != null && self.currentResults.appliedSearch != "undefined" &&
                        self.currentResults.appliedSearch != null && self.currentResults.appliedSearch.Trips != "undefined" && self.currentResults.appliedSearch.Trips.length > 0) {
                        if (self.currentResults.appliedSearch.searchTypeMain.toLowerCase() == "oneway") {
                            if (self.currentResults.Trips[0].FutureTravelDate) {
                                $('#flightSearch #DepartDate').val(formatDateNoWeekDay(self.currentResults.Trips[0].FutureTravelDate));
                            }
                        }
                        else if (self.currentResults.appliedSearch.searchTypeMain.toLowerCase() == "roundtrip") {
                            var tripindexcurrent = self.getTripIndex();
                            if (self.currentResults.Trips[tripindexcurrent] != null && self.currentResults.Trips[tripindexcurrent].FutureTravelDate) {
                                var departDate = new Date(self.currentResults.Trips[tripindexcurrent].FutureTravelDate);
                                if (tripindexcurrent == 1) {
                                    $('#flightSearch #ReturnDate').val(formatDateNoWeekDay(departDate));
                                    if ($('#editFlightSearch').val() == 'True') {
                                        $('#ReturnDateForEditSearch').val(formatDateNoWeekDay(departDate));
                                    }
                                }
                                else {
                                    $('#flightSearch #DepartDate').val(formatDateNoWeekDay(departDate));
                                }
                            }
                        }
                    }
                    $('#flightSearch').submit();
                });

                $document.on('click', '#btn-sign-in-award', $.proxy(this.handleSignInClick, this));
                $document.on('click', "#hdnlnkEditSearch", function (e) {
                    e.preventDefault();
                    $(this).css('outline', 'none');
                    $('#openeditsearchorigin :input').focus();
                });
                $document.on("click", ".filter-check", $.proxy(this.handleCheckBoxFilterClick, this));
                $document.on("click", ".stops-filter-check", $.proxy(this.handleTopStopsFilterClick, this));
                $document.on("click", ".clear-filters", $.proxy(this.handleClearFilters, this));
                if (self.showTopFilters || self.showTopFiltersAward) {
                    $document.on('click', '#filter-search-result', function (e) {
                        self.loadFilterResults(self.currentResults.appliedSearch, null, null, true);
                        e.preventDefault();
                    });
                    $document.on('click', '#btn-select-filter-apply', $.proxy(this.handleFilterApply, this));
                    $document.on('click', '#btn-select-filter-cancel', function () {
                        $.modal.close();
                    });
                    $document.on('change', '#select-filter-search-fare-family', $.proxy(this.handleFareFamilySelect, this));
                }
                if (self.searchFilterMode == "footerondemand" || self.searchFilterMode == "footer") {
                    $document.on('click', '.filter-only, .filter-me-only', $.proxy(this.handleOnlyFilterClick, this));
                    $document.on('click', '#frm-filter .filter-toggle-link', function (e) {
                        var $this = $(this);
                        var $filterContainer = $('#fl-filter-container');
                        if ($this.attr("data-trigger") == "toggler-close") {
                            $filterContainer.css({
                                'height': $('#frm-filter .filter-header-container').height()
                            });
                        } else {
                            if ($this.parent().parent().attr("aria-expanded") == "true") {
                                var $filterLinkDiv = $($(this).parent().parent().attr("data-toggler-target"));
                                if ($filterLinkDiv[0]) {
                                    $filterLinkDiv.css('height', 'auto');
                                    $filterContainer.css({
                                        'height': $filterLinkDiv.height() + $('#frm-filter .filter-header-container').height()
                                    });
                                }
                            } else {
                                $filterContainer.css({
                                    'height': $('#frm-filter .filter-header-container').height()
                                });
                            }
                        }
                        if (self.searchFilterMode === 'footerondemand') {
                            if ($('.filter-content-container').length == 0) {
                                var filterSection = $(this).parent().parent().attr('data-toggler-target');
                                self.loadFilterResults(self.currentResults.appliedSearch, true, null, filterSection);
                            }
                        }
                    });
                }
                if (self.searchFilterMode == "footerondemand" || self.searchFilterMode == "footer") {
                    $document.on('change', '#select-fare-family', $.proxy(this.handleFareFamilySelect, this));
                }
                if ($('#editFlightSearch').val() == "True") {
                    $document.on('click', '.edit-search-submit', $.proxy(this.handleEditSearch, this));
                    $document.on('blur', '.materialDesign.airport-code-input', $.proxy(this.ShowEditSearchError, this, "OD"));
                    $document.on('blur', '.editSearch-datepicker', $.proxy(this.ShowEditSearchError, this, "date"));
                }
                if ($('#hdnFareMatrixSwitch').length > 0 && $('#hdnFareMatrixSwitch').val() == 'True') {
                    $document.on('click', '#fare-matrix-link', $.proxy(this.handleFareMatrixLinkClick, this));
                    $document.on('mouseover focusin mouseleave focusout', '.fare-matrix-hover', $.proxy(this.handleFareMatrixHover, this));
                    $document.on('click', '.fare-matrix-cell-link', $.proxy(this.handleFareMatrixCellClick, this));
                    $document.on('click', '.farematrix-nonstop-check', $.proxy(this.handleFareMatrixNotStopFilterCheck, this));
                    $document.on('change', '#fareMatrixCabinType', $.proxy(this.RefreshFareMatrixOnCabinSelection, this));
                }
                $document.on('mouseenter mouseover focusin click', '.filter-connection-list', $.proxy(this.handleLastAirportOnly, this));
                if (this.isSingleColumnDesignEnabled()) {
                    $document.on('click', '.lnk-previous-column-nav', $.proxy(this.handlePreviousColumnClick, this))
                    $document.on('click', '.next-column-nav-container', $.proxy(this.handleNextColumnClick, this))
                }
                if (fsrTipsPhase2) {
                    $document.on('click', '#fl-search-header-nearbyerror.btn, #fl-search-nearbyerror-searchnow-link', $.proxy(this.handleNearbyErrorSearchNow, this));
                    $document.on('click', '#fl-search-header-nearby.btn, #fl-search-nearby-searchnow-link, #fl-no-flight-nearby-airport-link', $.proxy(this.handleNearbySearchNow, this));
                    $document.on('click', '#fl-search-header-nonstopsuggestion', $.proxy(this.handleNonstopMessageSearchNow, this));
                    $document.on('click', '#fl-search-header-betteroffers', $.proxy(this.handleBetterOffersSelect, this));
                    $document.on('click', '.fl-search-nearbycities', $.proxy(this.handleNearbyCitiesSelect, this));
                } else {
                    $document.on('click', '.fl-search-nonstopsuggestion-select', $.proxy(this.handleNonstopMessageSearchNow, this));
                    $document.on('click', '.fl-search-betteroffers-select', $.proxy(this.handleBetterOffersSelect, this));
                    $document.on('click', '.fl-search-nearbycities-select', $.proxy(this.handleNearbyCitiesSelect, this));
                }
                //tabbedFarewheel click 
                $document.on('click', '.tabbedFW-tab-link', $.proxy(this.handleFareWheelChange, this));
                $document.on('click', '.btn-flexible-calendar', $.proxy(this.handleFlexibleCalendar, this));
                $document.on('click', '#fl-no-flight-flexible-calendar-link', $.proxy(this.loadFlexibleCalendar, this));
                
                $document.on('click', '.btn-plusminus-3day-matrix', $.proxy(this.handlePlusMinus3Days, this));
                $document.on('click', '#lnkRevenueSearch', $.proxy(this.handleLinkRevenueSearch, this));
                if ($('#hdnAward').val() == "True" && $('#hdnIsSignedIn').val() === "False") {
                    $document.on('click', '.simplemodal-close', $.proxy(this.handleFSRModalPopupClose, this));
                }
                if (this.getFSRVersion() == '3') {
                    $document.on('click', '.flt-details-click', $.proxy(this.handleFlightDetailClick, this));
                    //$document.on('click', '.fsr-flt-select', $.proxy(this.handleUpgradeFareSelection, this));
                    $document.on('click', '.fsr-flt-select', $.proxy(this.handleFareSelection, this));
                    $document.on('click', '.flt-seatdetails-click', $.proxy(this.handleFlightSeatDetailClick, this));                }
                //***************************UPGRADE FILTER SELECTION*************************************************
                $(document).on('keypress click', '#showalloptions, #showonlyoptions', $.proxy(this.handleUpgradesFilterClick, this));

                $(document).on('keypress click', '.lowest-price-banner', $.proxy(this.handleLowestPriceBannerClick, this));
            },
            handleLowestPriceBannerClick: function () {
                this.showFullPageLoader();               
                var flightSearchForm = $("#flightSearch");                
                $('#AwardTravel_False', flightSearchForm).trigger('click');
                flightSearchForm.append("<input type='hidden' name='PortOx' id='PortOx' value='" + this.currentResults.appliedSearch.portOx + "' />");
                if (this.currentResults.appliedSearch != null && this.currentResults.appliedSearch.travelwPet > 0) {
                    var objTrips = this.currentResults.appliedSearch.Trips;
                    flightSearchForm.append("<input type='hidden' name='NumberOfPets' id='NumberOfPets' value='" + this.currentResults.appliedSearch.NumberOfPets + "' />");
                    flightSearchForm.append("<input type='hidden' name='TravelwPet' id='TravelwPet' value='1' />");
                    var i;
                    for (i = 0; i < objTrips.length; i++) {
                        if (objTrips[i].PetIsTraveling) {
                            flightSearchForm.append("<input type='hidden' name='Trips[" + i + "].PetIsTraveling' id='Trips[" + i + "].PetIsTraveling' value='" + objTrips[i].PetIsTraveling + "' />");
                        }
                    }
                }
                flightSearchForm.submit();
            },
            awardRevenueAnalytics: function ($element, amount) {
                var moduleInfo = null;
                if ($('#hdnLowestRevenueBannerOption1').val() == "True") {
                    moduleInfo = "{\"variant\": \"1\", \"price\": \"" + amount + "\"}";
                }
                else if ($('#hdnLowestRevenueBannerOption2').val() == "True") {
                    moduleInfo = "{\"variant\": \"2\", \"price\": \"" + amount + "\", \"resultIndex\": \"" + $('#hdnLowestRevenueBannerOption2Index').val() + "\"}";
                }
                $element.removeAttr("data-module-info").attr("data-module-info", moduleInfo);
                $element.data("module-info", JSON.parse(moduleInfo));
                UA.UI.processModule($element);
            },
            handleLastAirportOnly: function (e) {
                if ($('.filter-connection-list li').length > 6) {
                    if ($(".filter-connection-list li:last-child").find('a').length) {
                        $(".filter-connection-list").append('<li class="EmptyLionlylink"></li>');
                    }
                }
            },
            handleFSRModalPopupClose: function () {
                $.modal.close();
                IsSignModalClosed = true;
                this.readPageContentOnPageLoad();

            },
            readPageContentOnPageLoad: function () {

                try {

                    if ((IsPageContentRead == false) && IsSignModalClosed && IsServiceCallCompleted) {

                        IsPageContentRead = true;


                        setTimeout(function () {
                            window.setTimeout(function () { $('.logo').focusWithoutScrolling(); }, 1);
                            window.setTimeout(function () { $('.head-adjunct').focusWithoutScrolling(); }, 100);
                            window.setTimeout(function () { $('#main-content').focusWithoutScrolling(); }, 300);
                            window.setTimeout(function () { $('footer').focusWithoutScrolling(); }, 400);
                            window.setTimeout(function () { $('.logo').focusWithoutScrolling(); }, 500);
                        }, 1000);
                    }
                } catch (e) {

                }
            },
            handlePlusMinus3Days: function (e) {
                if (!$(".btn-plusminus-3day-matrix").hasClass("btn-calendar-toggle-selected")) {
                    $(".btn-plusminus-3day-matrix").addClass("btn-calendar-toggle-selected");
                    $(".btn-flexible-calendar").removeClass("btn-calendar-toggle-selected");
                    var url = window.location.href;
                    url = this.removeParams(['flxbl', 'co', 'fm', 'tl', 'mt','d','r']);
                    window.location.href = url + "&d=" + this.currentResults.Trips[0].DepartDate + "&r=" + this.currentResults.Trips[0].ReturnDate + "&mt=1";
                }
            },
            handleLinkRevenueSearch: function (e) {
                    e.preventDefault();
                    var url = window.location.href;

                    if (url && url.toLowerCase().indexOf('changetrip') > -1) {

                        var changeTripUrl = $('#hdnChangeTripUrl').val();

                        var postHtml = '<form style="display:none;" id="cartupdate" method="post" action="' + changeTripUrl + '"> \n' +
                                       ' <input type="hidden" name="CancelCorporateLeisurePath" value="true" /> \n' +
                                       '</form>';

                        jQuery('<div/>')
                            .append(postHtml)
                            .appendTo('body')
                            .find('#cartupdate')
                            .submit();
                    }
                    else {

                        url = this.removeParams(['cl']);
                        window.location.href = url;
                    }
            },
            handleFlexibleCalendar: function (e) {
                if (!$(".btn-flexible-calendar").hasClass("btn-calendar-toggle-selected")) {
                    $(".btn-flexible-calendar").addClass("btn-calendar-toggle-selected");
                    $(".btn-plusminus-3day-matrix").removeClass("btn-calendar-toggle-selected");
                    this.loadFlexibleCalendar();
                }
            },

            loadFlexibleCalendar: function () {
                var url = window.location.href;
                url = this.removeParams(['ct', 'co', 'fm', 'tl', 'mt']);
                var cabinTypeParameter='';
                if (this.currentResults.appliedSearch.cabinType == "businessFirst" || this.currentResults.appliedSearch.cabinType == 1)
                {
                    cabinTypeParameter = "&ct=1";
                }
                var DepartDate, ReturnDate;
                if (this.currentResults.Trips) {
                    DepartDate = this.currentResults.Trips[0].DepartDate;
                    ReturnDate = this.currentResults.Trips[0].ReturnDate;
                }
                else {
                    DepartDate = this.currentResults.appliedSearch.DepartDateBasicFormat;
                    ReturnDate = this.currentResults.appliedSearch.ReturnDateBasicFormat;
                }

                var tripLength = Math.ceil((UA.Utilities.formatting.parseDate("yy-m-d", ReturnDate)
                        - UA.Utilities.formatting.parseDate("yy-m-d", DepartDate)) / (1000 * 3600 * 24));
                window.location.href = url + cabinTypeParameter + "&co=1&fm=" + DepartDate + "&tl=" +tripLength;
            },
            removeParams: function(sParam)
            {
                var url = window.location.href.split('?')[0]+'?';
                var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                    sURLVariables = sPageURL.split('&'),
                    sParameterName,
                    i;
         
                for (i = 0; i < sURLVariables.length; i++) {
                    sParameterName = sURLVariables[i].split('=');
                    if (sParam.indexOf(sParameterName[0]) > -1) {
                        //In the array!
                    } else {
                        url = url + sParameterName[0] + '=' + sParameterName[1] + '&'
                    }                    
                }
                return url.substring(0,url.length-1);
            },
            handleEditSearch: function (e) {
                var serviceUrl = this.elements.container.data('validateairportcodeurl');
                var _this = this,
                    validateAirportCode, validationStatus = true,
                    inputAirportCodes = [];
                var editSearchForm = $('#flightSearch');
                var editSearchValidator = editSearchForm.validate();
                var totalTrips = parseInt($("#hdnTotalTrips").val(), 10);
                totalTrips = 6;
                $('.materialDesign.airport-code-input').find('input').each(function (i, obj) {
                    if (i < (2 * totalTrips)) {
                        var currEl = $(this);
                        if (currEl.attr('id') && currEl.attr('id').length > 19) {
                            var currElNumber = currEl.attr('id').substr(19, 1);
                            if ($('#TripsForEditSearch_' + currElNumber + "__Ignored").length > 0) {
                                if ($('#TripsForEditSearch_' + currElNumber + "__Ignored").val() === "false") {
                                    inputAirportCodes.push({
                                        elementKey: currEl.attr('name'),
                                        elementValue: currEl.val()
                                    });
                                }
                            }
                            else {
                                inputAirportCodes.push({
                                    elementKey: currEl.attr('name'),
                                    elementValue: currEl.val()
                                });
                            }
                        }
                        else {
                            inputAirportCodes.push({
                                elementKey: currEl.attr('name'),
                                elementValue: currEl.val()
                            });
                        }
                    }
                });
                var realSearchTypeMain;
                if ($("#editFlightSearchVersion").length > 0 && $("#editFlightSearchVersion").val() === "1") {
                    realSearchTypeMain = $("#RealSearchTypeMain").val();
                }
                else {
                    realSearchTypeMain = $("#SearchTypeMain").val();
                }
                validateAirportCode = $.ajax({
                    cache: false,
                    url: serviceUrl,
                    type: 'post',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({
                        airportCodes: inputAirportCodes,
                        SearchTypeMain: realSearchTypeMain
                    }),
                    traditional: true
                });
                $.when(validateAirportCode)
                    .done(function (response) {
                        if (response !== null && typeof response !== 'undefined' && response.length > 0) {
                            var errorFields = {};
                            for (var i = 0; i < response.length; i++) {
                                if (response[i].errorType === 2) {
                                    var validatedElement = $('input[name="' + response[i].element + '"]');
                                    if (validatedElement.val().trim() == '')
                                        errorFields[response[i].element] = validatedElement.data('val-required');
                                    else
                                        errorFields[response[i].element] = validatedElement.data('val-regex');
                                    validationStatus = false;
                                } else if (response[i].errorType === 3) {
                                    errorFields[response[i].element] = response[i].errorMsg;
                                    validationStatus = false;
                                }
                            }
                            if (!validationStatus) {
                                if ($("#editFlightSearchVersion").length > 0 && $("#editFlightSearchVersion").val() === "1") {
                                    $("#RealSearchTypeMain").val($("#SearchTypeMain").val());
                                    $("#RealTripTypes").val($("#TripTypes").val());
                                }
                                editSearchValidator.showErrors(errorFields);
                            } else {
                                UA.Booking.EditSearch.beforeSubmitEditSearch();
                                if (_this.currentResults.appliedSearch.flexible === true) {
                                    $("#FromFlexibleCalendar").val("True");
                                } else {
                                    $("#FromFlexibleCalendar").val("False");
                                }
                                editSearchForm.submit();
                            }
                        } else {
                            UA.Booking.EditSearch.beforeSubmitEditSearch();
                            if ($("#AwardTravel_False").prop('checked') && _this.currentResults.appliedSearch.Matrix3day && $('#RealSearchTypeMain').val() == "roundTrip" && UA.Utilities.formatting.tryParseDate($('#DepartDate').val()) && UA.Utilities.formatting.tryParseDate($('#flightSearch #ReturnDateForEditSearch').val())) {
                                $('#Matrix3day').val("true");
                            }
                            else {
                                $('#Matrix3day').val("false");
                            }
                            if (_this.currentResults.appliedSearch.flexible === true) {
                                $("#FromFlexibleCalendar").val("True");
                            } else {
                                $("#FromFlexibleCalendar").val("False");
                            }
                            editSearchForm.submit();
                        }
                        setTimeout(function () {
                            _this.hideEditSearchPopuponError(inputAirportCodes);
                        }, 1);
                    })
                    .fail(function (jqXHR, status) {
                        if ($("#editFlightSearchVersion").length > 0 && $("#editFlightSearchVersion").val() === "1") {
                            $("#RealSearchTypeMain").val($("#SearchTypeMain").val());
                            $("#RealTripTypes").val($("#TripTypes").val());
                        }
                        UA.Booking.EditSearch.beforeSubmitEditSearch();
                        if (_this.currentResults.appliedSearch.flexible === true) {
                            $("#FromFlexibleCalendar").val("True");
                        } else {
                            $("#FromFlexibleCalendar").val("False");
                        }
                        editSearchForm.submit();
                    });
            },
            hideEditSearchPopuponError: function (inputAirportCodes) {
                _.forEach(inputAirportCodes, function (ele) {
                    var currEl = $('input[name="' + ele.elementKey + '"]')
                    if (currEl.parent().parent().hasClass("input-validation-error")) {
                        currEl.attr('aria-describedby', currEl.attr('id') + '-error');
                        currEl.parent().find('.field-validation-error').show();
                        currEl.focus();
                        currEl.parent().find('.tt-menu').hide();
                    }
                });
                $('.editSearch-datepicker').each(function (i, obj) {
                    var currEl = $(this);
                    if (currEl.parent().hasClass("input-validation-error")) {
                        currEl.datepicker('hide');
                        currEl.attr('aria-describedby', currEl.attr('id') + '-error');

                    }

                });
            },
            ShowEditSearchError: function (inputtype, e) {
                var currEl = $(e.currentTarget);
                if (currEl.hasClass("input-validation-error")) {
                    if (inputtype == "OD") {
                        currEl.find('.tt-menu').hide();
                        currEl.find('.field-validation-error').css("display", "block");
                        currEl.find('.field-validation-error').css("color", "#CD202c");
                        if ($("#flightSearch").find("#multiCityOption").length > 0) {
                            if ($("#editFlightSearchVersion").length > 0 && $("#editFlightSearchVersion").val() === "1") {
                                currEl.find('.field-validation-error').width(190);
                                currEl.find('.field-validation-error span').width(190);
                            }
                            else {
                                currEl.find('.field-validation-error').width(225);
                                currEl.find('.field-validation-error span').width(225);
                            }
                        }
                        else {
                            currEl.find('.field-validation-error').width(300);
                            currEl.find('.field-validation-error span').width(300);
                        }
                    }
                    else {
                        if (!isDatePickerErrorOpened) {
                            currEl.datepicker('hide');
                        }
                        currEl.parent().find('.field-validation-error').css("display", "block");
                        currEl.parent().find('.field-validation-error').css("color", "#CD202c");
                        if ($("#flightSearch").find("#multiCityOption").length > 0) {
                            if ($("#editFlightSearchVersion").length > 0 && $("#editFlightSearchVersion").val() === "1") {
                                currEl.parent().find('.field-validation-error').width(110);
                                currEl.parent().find('.field-validation-error span').width(110);
                            }
                            else {
                                currEl.parent().find('.field-validation-error').width(120);
                                currEl.parent().find('.field-validation-error span').width(120);
                            }
                        }
                        else {
                            currEl.parent().find('.field-validation-error').width(130);
                            currEl.parent().find('.field-validation-error span').width(130);
                        }
                        isDatePickerErrorOpened = true;
                    }
                }
            },
            handleFilterApply: function (e) {
                filterActionClick = true;

                var isAwardCalendarNonstop = false;
                var i, tripIndex, i,
                 airportsStop = $.map($('.filter-connection-list' + ' input:checkbox:checked'), function (ev, i) {
                     return $(ev).val();
                 });
                this.currentResults.appliedSearch.SearchFilters.AirportsStop = airportsStop.join();
                tripIndex = this.getTripIndex();
                var tempResult = this.currentResults;
                //CSi-1312 -Fixed
                if (typeof (tempResult.Trips[tripIndex]) === 'undefined') {
                    tripIndex = 0;
                }
                if ($.isEmptyObject(airportsStop)) {//uncheck top one stop and bottom one and two stops
                    isAwardCalendarNonstop = true;
                    this.currentResults.appliedSearch.Trips[tripIndex].oneStop = false;
                    this.currentResults.appliedSearch.Trips[tripIndex].twoPlusStop = false;
                } else {
                    var keeper = this.currentResults;
                    $(keeper.Trips[tripIndex].Flights).each(function (i) {
                        switch (this.StopsandConnections) {
                            case 1:
                                keeper.appliedSearch.Trips[tripIndex].oneStop = true; //recheck the one stop
                                break;
                            case 2:
                                keeper.appliedSearch.Trips[tripIndex].twoPlusStop = true; //recheck the two stop
                                break;
                            default:
                                keeper.appliedSearch.Trips[tripIndex].oneStop = true;
                                keeper.appliedSearch.Trips[tripIndex].twoPlusStop = true;
                                break;
                        }
                        if (keeper.appliedSearch.Trips[tripIndex].oneStop === true && keeper.appliedSearch.Trips[tripIndex].twoPlusStop === true) {
                            return false;
                        }
                    });
                }

                this.setFilterFromTrip(this.currentResults.appliedSearch.SearchFilters, tripIndex + 1);
                $.modal.close();
                if ($('#newfilter_nonStop').is(':checked') || ($('#notstoponlyv2').is(':checked') || $('#allflightsv2').is(':checked'))) {
                    this.currentResults.appliedSearch.SearchFilters.nonStop = true;
                } else {
                    if (!this.currentResults.SearchFilters.HideNoneStop) {
                        isAwardCalendarNonstop = false;
                    }
                    this.currentResults.appliedSearch.SearchFilters.nonStop = false;//CSI-1370
                }
                this.loadFilterResults(this.currentResults.appliedSearch, true, true, null);

                if (this.showTopFiltersAward === true && this.currentResults.appliedSearch.flexibleAward === false) {
                    this.handleAwardCalendarNonstopFilterChangeFunc(isAwardCalendarNonstop);
                }
            },
            handleFilterSearchResult: function (data) {
                var _this = this;
                var selectedLabel = $("#select-fare-family option:selected").text();
                if (!this.currentResults.appliedSearch.SearchFilters.FareFamilyDescription) {
                    selectedLabel = _.where(this.currentResults.Trips[0].Columns, {
                        Selected: true
                    });
                    if (selectedLabel && selectedLabel.length > 0) {
                        selectedLabel = selectedLabel[0].ColumnName + " " + selectedLabel[0].Description;
                    } else {
                        selectedLabel = this.currentResults.appliedSearch.SearchFilters.FareFamily;
                    }
                }
                data.SearchFilters.FareFamilyDescription = selectedLabel;
                var minPrice = data.SearchFilters.MinPrices[this.currentResults.appliedSearch.SearchFilters.FareFamily];
                var maxPrice = data.SearchFilters.MaxPrices[this.currentResults.appliedSearch.SearchFilters.FareFamily];
                if (minPrice === maxPrice) {
                    data.SearchFilters.HidePrice = true;
                }
                data.SearchFilters.nonStop = this.currentResults.appliedSearch.SearchFilters.nonStop;
                data.SearchFilters.oneStop = this.currentResults.appliedSearch.SearchFilters.oneStop;
                data.SearchFilters.twoPlusStop = this.currentResults.appliedSearch.SearchFilters.twoPlusStop;
                data.SearchFilters.nonStopOnly = this.currentResults.appliedSearch.SearchFilters.nonStopOnly;
                data.SearchFilters.calendarStops = this.currentResults.appliedSearch.SearchFilters.calendarStops;
                if (!data.SearchFilters.NonStopMinPricesByColumn[this.currentResults.appliedSearch.SearchFilters.FareFamily] ||
                    data.SearchFilters.NonStopMinPricesByColumn[this.currentResults.appliedSearch.SearchFilters.FareFamily] <= 0) {
                    data.SearchFilters.NonStopFormattedAmount = "N/A";
                }
                if (!data.SearchFilters.OneStopMinPricesByColumn[this.currentResults.appliedSearch.SearchFilters.FareFamily] ||
                    data.SearchFilters.OneStopMinPricesByColumn[this.currentResults.appliedSearch.SearchFilters.FareFamily] <= 0) {
                    data.SearchFilters.OneStopFormattedAmount = "N/A";
                }
                if (!data.SearchFilters.TwoPlusMinPricesByColumn[this.currentResults.appliedSearch.SearchFilters.FareFamily] ||
                    data.SearchFilters.TwoPlusMinPricesByColumn[this.currentResults.appliedSearch.SearchFilters.FareFamily] <= 0) {
                    data.SearchFilters.TwoPlusStopFormattedAmount = "N/A";
                }
                $('.trip-count-shown').text(data.SearchFilters.CurrentFlightCount);
                var filterResult = _this.templates.filterSearchFilters(data);
                var isModelOpen = $('#filter-search-result-modal-placeholder').parent().hasClass('simplemodal-wrap');
                if (!isModelOpen) {
                    $("#filter-search-result-modal-placeholder").modal({
                        onOpen: function (dialog) {
                            dialog.overlay.show();
                            dialog.container.show();
                            //dialog.container.loader();
                            dialog.data.html(filterResult).show();
                            UA.UI.reInit($(dialog.container));
                            $.modal.update();
                        }
                    });
                } else {
                    $('#filter-search-result-modal-placeholder').empty().html(filterResult);
                    UA.UI.reInit($('#filter-search-result-modal-placeholder'));
                }
                if (data.SearchFilters.HideAirportSection && data.SearchFilters.AirportsStopList.length === 0) {
                    $('#btn-select-filter-apply').attr('disabled', 'disabled');
                }

            },
            handleSort: function (response) {
                var _this = this,
                    flightsResults = response.Trips[0].Flights;

                if (!_this.currentResults.appliedSearch.SearchFilters.FareFamily) {
                    _this.currentResults.appliedSearch.SearchFilters.FareFamily = response.SearchFilters.FareFamily;
                }

                if (!_this.currentResults.appliedSearch.SearchFilters.SortFareFamily) {
                    _this.currentResults.appliedSearch.SearchFilters.SortFareFamily = _this.currentResults.appliedSearch.SearchFilters.FareFamily;
                }

                if (!_this.currentResults.appliedSearch.SortType) {
                    _this.currentResults.appliedSearch.SortType = "bestmatches";
                }                
                var orderbycolumn;

                if (_this.currentResults.appliedSearch.awardTravel) {
                    if (_this.currentResults.appliedSearch.SortType === "price_high") {
                        orderbycolumn = [false, true];
                    } else if (_this.currentResults.appliedSearch.SortType === "price_low") {
                        orderbycolumn = [true, true];
                    }
                }
                flightsResults = _.sortByOrder(flightsResults, function (sortFlight) {
                    var price = null,
                        sortedPrice, dateParsed, sortedValue, bestmatchsortedValue, indextosortby = 0;

                    if (sortFlight.PricesByColumn && sortFlight.PricesByColumn[_this.currentResults.appliedSearch.SearchFilters.SortFareFamily]) {
                        price = sortFlight.PricesByColumn[_this.currentResults.appliedSearch.SearchFilters.SortFareFamily];
                    }

                    price = parseInt(price, 10);

                    //Fix for defect# 618038, When the flight prices for award travel are of different length(number of digits ex. min price 90000 miles and max price 100000 miles), 
                    //in that case this funtion was not comparing prices as expected and sorting was not correct on fare columns in FSR page, so implemented below condition to handle this scenario.
                    if (_this.currentResults.appliedSearch.awardTravel) {
                        if (_this.currentResults.appliedSearch.SortType === "price_low" || _this.currentResults.appliedSearch.SortType === "price_high") {
                            if (_this.currentResults.appliedSearch.SearchFilters && _this.currentResults.appliedSearch.SearchFilters.PriceMax && _this.currentResults.appliedSearch.SearchFilters.PriceMin) {
                                if (!isNaN(price) && (price.toString().length < _this.currentResults.appliedSearch.SearchFilters.PriceMax.toString().length)) {
                                    var lengthDifference = _this.currentResults.appliedSearch.SearchFilters.PriceMax.toString().length - price.toString().length;
                                    for (var i = 0; i < lengthDifference; i++) {
                                        price = String("0").concat(price);
                                    }
                                }
                            }
                        }
                    }
                    var columns = _.map(_this.currentResults.Trips[0].Columns, function (column) {
                        return column.FareFamily;
                    });
                    indextosortby = _.indexOf(columns, _this.currentResults.appliedSearch.SearchFilters.SortFareFamily);
                    if (indextosortby == -1) {
                        bestmatchsortedValue = parseInt(sortFlight.Products[0].BestMatchSortOrder, 10);
                    } else {
                        bestmatchsortedValue = parseInt(sortFlight.Products[indextosortby].BestMatchSortOrder, 10);

                    }
                    if (bestmatchsortedValue < 10) {
                        bestmatchsortedValue = String("0").concat(bestmatchsortedValue);
                    }

                    if (_this.currentResults.appliedSearch.SortType === "price_low") {
                        sortedValue = !isNaN(price) ? price : 9999999;
                    } else if (_this.currentResults.appliedSearch.SortType === "price_high") {
                        if (!_this.currentResults.appliedSearch.awardTravel) {
                            sortedValue = !isNaN(price) ? -price : 0;
                        } else {
                            sortedValue = !isNaN(price) ? price : 0;
                        }
                    } else if (_this.currentResults.appliedSearch.SortType === "departure_early" || _this.currentResults.appliedSearch.SortType === "departure_afternoon" || _this.currentResults.appliedSearch.SortType === "departure_evening") {
                        dateParsed = _this.parseDateTime(sortFlight.DepartDateTime);
                        sortedValue = Math.round(dateParsed.getTime() / 1000);
                    } else if (_this.currentResults.appliedSearch.SortType === "departure_late") {
                        dateParsed = _this.parseDateTime(sortFlight.DepartDateTime);
                        sortedValue = -Math.round(dateParsed.getTime() / 1000);
                    } else if (_this.currentResults.appliedSearch.SortType === "arrival_early") {
                        dateParsed = _this.parseDateTime(sortFlight.LastDestinationDateTime);
                        sortedValue = Math.round(dateParsed.getTime() / 1000);
                    } else if (_this.currentResults.appliedSearch.SortType === "arrival_late") {
                        dateParsed = _this.parseDateTime(sortFlight.LastDestinationDateTime);
                        sortedValue = -Math.round(dateParsed.getTime() / 1000);
                    } else if (_this.currentResults.appliedSearch.SortType === "duration_fastest") {
                        sortedValue = sortFlight.TravelMinutesTotal;
                    } else if (_this.currentResults.appliedSearch.SortType === "duration_longest") {
                        sortedValue = -sortFlight.TravelMinutesTotal;
                    } else if (_this.currentResults.appliedSearch.SortType === "stops_low") {
                        sortedValue = sortFlight.AirportsStopList.length;
                    } else if (_this.currentResults.appliedSearch.SortType === "stops_high") {
                        sortedValue = -sortFlight.AirportsStopList.length;
                    }

                    if (_this.currentResults.appliedSearch.SortType === "bestmatches") {
                        return bestmatchsortedValue;
                    }

                    if (!_this.currentResults.appliedSearch.awardTravel) {
                        return sortedValue;
                    } else {
                        if (_this.currentResults.appliedSearch.SortType === "price_low" || _this.currentResults.appliedSearch.SortType === "price_high") {
                            return [sortedValue, bestmatchsortedValue];
                        } else {
                            return sortedValue;
                        }
                    }

                }, orderbycolumn);
                if (_this.currentResults.appliedSearch.SortType === "departure_afternoon" || _this.currentResults.appliedSearch.SortType === "departure_evening") {
                    var afternoonFlights = _.filter(flightsResults, function (flight) {
                        var departHours = new Date(flight.DepartDateTime).getHours();
                        if (departHours >= 12 && departHours < 17) {
                            return flight;
                        }
                    });
                    var eveningFlights = _.filter(flightsResults, function (flight) {
                        var departHours = new Date(flight.DepartDateTime).getHours();
                        if (departHours >= 17 && departHours < 24) {
                            return flight;
                        }
                    });
                    var morningFlights = _.filter(flightsResults, function (flight) {
                        var departHours = new Date(flight.DepartDateTime).getHours();
                        if (departHours >= 0 && departHours < 12) {
                            return flight;
                        }
                    });
                    if (_this.currentResults.appliedSearch.SortType === "departure_afternoon")
                        flightsResults = [].concat(afternoonFlights, eveningFlights, morningFlights);
                    else
                        flightsResults = [].concat(eveningFlights, morningFlights, afternoonFlights);
                }

                response.Trips[0].Flights = flightsResults;

                return response;
            },
            initPagination: function (response, refreshFilters, sorting) {
                var _this = this,
                    perPage = 25,
                    numItems = response.Trips[0].Flights.length;
                if (response != null && response.SearchType != null && response.SearchType.toLowerCase() === 'roundtrip' && (!response.IsAward || ($('#hdnNoPaginationForRtAwardSearch').val() === "True" && response.IsAward))) {
                    perPage = numItems;
                }
                var sortedResults;
                if (sorting) {
                    sortedResults = _this.handleSort(response);
                } else {
                    sortedResults = response;
                }

                var reDrawFilter = true,
                    Allflightfeature = $('#Allflightfeature').val().toLowerCase() == 'true' ? true : false,
                    AllflightfeatureAward = $('#Allflightfeatureawd').val().toLowerCase() == 'true' ? true : false,
                    showallresults = false;
                AllflightfeatureAward = (response.IsAward && !AllflightfeatureAward);
                AllflightfeatureAward &= !_this.showTopFiltersAward;
                var tripsShowAllResults, tripindex;
                //Init Pagination Control
                $("#fl-results-pager").find('.simple-pagination').remove();
                $("#fl-results-pager")
                    .append("<div id='fl-results-pager-container' class='simple-pagination'/>");
                if (AllflightfeatureAward || !Allflightfeature) {
                    $("#fl-results-pager").show()
                        .find('#fl-results-pager-container')
                        .pagination({
                            items: numItems,
                            itemsOnPage: perPage,
                            cssStyle: "united-theme",
                            onPageClick: function (pageNumber, event) {

                                var showFrom = perPage * (pageNumber - 1),
                                    showTo = showFrom + perPage,
                                    flightsResultsNew = jQuery.extend(true, {}, sortedResults),
                                        flightsNew;

                                flightsNew = flightsResultsNew.Trips[0].Flights.slice(showFrom, showTo);
                                flightsResultsNew.Trips[0].Flights = flightsNew;

                                _this.elements.resultsContainer.fadeTo(400, 0, function () {
                                    _this.render(flightsResultsNew, refreshFilters, !reDrawFilter);
                                    reDrawFilter = false;
                                    _this.hidePageLoader(true);
                                    _this.hideLineLoader();
                                });

                                if (event) {
                                    $("html, body").animate({
                                        scrollTop: 0
                                    }, 0);
                                }


                                return false;
                            }
                        }).show();
                } else {
                    perPage = parseInt($('#AllflightfeaturePageSize').val()) || 35;
                    showallresults = _this.getShowAllResultsCookie();
                    setTimeout(function () {
                        _this.pagingNew(sortedResults, refreshFilters, !reDrawFilter, showallresults);
                        reDrawFilter = false;
                        _this.hidePageLoader(true);
                        if (_this.isSingleColumnDesignActive()) {
                            _this.initStickyElements();
                        }

                        if (_this.currentResults.appliedSearch.awardTravel && _this.showTopFiltersAward && !AllflightfeatureAward) {
                            if ($("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").length > 0) {
                                if ($("#fl-results-pager > #search-result-feedback").length > 0) {
                                    $("#dvShowallresults > #a-results-show-all").removeClass("visiblehidden");
                                    if (numItems > perPage) {
                                        $("#fl-results-pager > #search-result-feedback").remove().insertBefore($("#dvShowallresults > div.pagerShowAll-padding > #fl-results-pagerShowAll")).hide();
                                    } else {
                                        $("#fl-results-pager > #search-result-feedback").remove().insertBefore($("#dvShowallresults > div.pagerShowAll-padding > #fl-results-pagerShowAll")).show();
                                    }
                                } else {
                                    if (numItems > perPage) {
                                        if (showallresults) {
                                            $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").show();
                                        } else {
                                            $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").hide();
                                        }
                                    } else {
                                        if (numItems > 0) {
                                            $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").show();
                                        } else {
                                            $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").hide();
                                        }
                                        $("#dvShowallresults > #a-results-show-all").removeClass("visiblehidden").addClass("visiblehidden");
                                        $("#dvShowallresults").show();
                                    }
                                }
                            } else {
                                if ($("#fl-results-pager > #search-result-feedback").length > 0) {
                                    $("#dvShowallresults > #a-results-show-all").removeClass("visiblehidden");
                                    if (numItems > perPage) {
                                        if (showallresults) {
                                            $("#fl-results-pager > #search-result-feedback").remove().insertBefore($("#dvShowallresults > div.pagerShowAll-padding > #fl-results-pagerShowAll")).show();
                                        } else {
                                            $("#fl-results-pager > #search-result-feedback").remove().insertBefore($("#dvShowallresults > div.pagerShowAll-padding > #fl-results-pagerShowAll")).hide();
                                        }
                                    } else {
                                        if (numItems > 0) {
                                            $("#fl-results-pager > #search-result-feedback").remove().insertBefore($("#dvShowallresults > div.pagerShowAll-padding > #fl-results-pagerShowAll")).show();
                                        } else {
                                            $("#fl-results-pager > #search-result-feedback").remove().insertBefore($("#dvShowallresults > div.pagerShowAll-padding > #fl-results-pagerShowAll")).hide();
                                        }
                                        $("#dvShowallresults > #a-results-show-all").removeClass("visiblehidden").addClass("visiblehidden");
                                        $("#dvShowallresults").show();
                                    }
                                }
                            }
                        } else {
                            if ($("#dvShowallresults > .pagerShowAll-padding > #search-result-feedback").length > 0) {
                                if (numItems > perPage) {
                                    if (showallresults) {
                                        $("#dvShowallresults > .pagerShowAll-padding > #search-result-feedback").show();
                                    } else {
                                        $("#dvShowallresults > .pagerShowAll-padding > #search-result-feedback").hide();
                                    }
                                } else {
                                    if (numItems > 0) {
                                        $("#dvShowallresults > .pagerShowAll-padding > #search-result-feedback").show();
                                    } else {
                                        $("#dvShowallresults > .pagerShowAll-padding > #search-result-feedback").hide();
                                    }
                                    $("#dvShowallresults > #a-results-show-all").removeClass("visiblehidden").addClass("visiblehidden");
                                    $("#dvShowallresults").show();
                                }
                            } else {
                                if ($("#fl-results-pager > #search-result-feedback").length > 0) {
                                    $("#fl-results-pager").hide();
                                    $("#dvShowallresults > #a-results-show-all").removeClass("visiblehidden");
                                    if (numItems > perPage) {
                                        if (showallresults) {
                                            $("#fl-results-pager > #search-result-feedback").remove().insertBefore($("#dvShowallresults > div.pagerShowAll-padding > #fl-results-pagerShowAll")).show();
                                        } else {
                                            $("#fl-results-pager > #search-result-feedback").remove().insertBefore($("#dvShowallresults > div.pagerShowAll-padding > #fl-results-pagerShowAll")).hide();
                                        }
                                    } else {
                                        if (numItems > 0) {
                                            $("#fl-results-pager > #search-result-feedback").remove().insertBefore($("#dvShowallresults > div.pagerShowAll-padding > #fl-results-pagerShowAll")).show();
                                        } else {
                                            $("#fl-results-pager > #search-result-feedback").remove().insertBefore($("#dvShowallresults > div.pagerShowAll-padding > #fl-results-pagerShowAll")).hide();
                                        }
                                        $("#dvShowallresults > #a-results-show-all").removeClass("visiblehidden").addClass("visiblehidden");
                                        $("#dvShowallresults").show();
                                    }
                                }
                            }
                        }
                        
                        $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").css("float", "none");
                        $("#dvShowallresults > #a-results-show-all").css("margin-left", "0px");

                        if (numItems > perPage) {
                            $("#a-results-show-all").off('click').on('click', function (e) {
                                e.preventDefault();

                                if ($("#flight-result-elements").length > 0 && $("#flight-result-elements").hasClass("loading")) {
                                    return;
                                }

                                tripsShowAllResults = JSON.parse(UA.Utilities.safeSessionStorage.getItem("tripsShowAllResults"));
                                tripindex = _this.getTripIndex();
                                var tryShowAll;
                                var buttonText;
                                var iconHtml;
                                if ($('#a-results-show-all').text() == $('#showlessreslttext').text()) {
                                    tryShowAll = false;
                                    buttonText = $('#showallreslttext').text();
                                    iconHtml = '<br/><i class="icon-toggle-arrow-down-gray-result"></i>';
                                } else {
                                    tryShowAll = true;
                                    buttonText = $('#showlessreslttext').text();
                                    iconHtml = '<br/><i class="icon-toggle-arrow-up-gray-result"></i>';

                                }

                                _this.showPageLoader();
                                _this.elements.resultsContainer.fadeTo(400, 0, function () {
                                    _this.pagingNew(sortedResults, refreshFilters, !reDrawFilter, tryShowAll);
                                    if (tryShowAll === true) {
                                        $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").show();
                                    } else {
                                        $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").hide();
                                    }
                                    $('#a-results-show-all').text(buttonText);
                                    $('#a-results-show-all').append(iconHtml);
                                    $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").css("float", "none");
                                    $("#dvShowallresults > #a-results-show-all").css("margin-left", "0px"); 
                                    _this.hidePageLoader();
                                    _this.hideLineLoader();
                                });
                                if (tripsShowAllResults != null && tripsShowAllResults.length > tripindex) {
                                    tripsShowAllResults[tripindex].ShowAllResults = tryShowAll;
                                }
                                UA.Utilities.safeSessionStorage.setItem("tripsShowAllResults", JSON.stringify(tripsShowAllResults));
                                $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").css("float", "none");
                                $("#dvShowallresults > #a-results-show-all").css("margin-left", "0px");
                            });

                            $("#dvShowallresults > #a-results-show-all").removeClass("visiblehidden");

                            if (showallresults) {
                                setTimeout(function () {
                                    $('#a-results-show-all').text($('#showlessreslttext').text());
                                    $('#a-results-show-all').append('<br/><i class="icon-toggle-arrow-up-gray-result"></i>');
                                    var scroll = (tripsShowAllResults != null && tripsShowAllResults.length > tripindex) ? tripsShowAllResults[tripindex].flightscrollpos : '';
                                    var selectedflight = $('.flight-block.flight-block-fares[data-flight-hash="' + scroll + '"]');
                                    var offsettop = selectedflight != null && selectedflight.length > 0 ? selectedflight.offset().top : 0;
                                    $("html, body").animate({
                                        scrollTop: offsettop
                                    });
                                }, 5);
                            } else {
                                $('#a-results-show-all').text($('#showallreslttext').text());
                                $('#a-results-show-all').append('<br/><i class="icon-toggle-arrow-down-gray-result"></i>');
                            }
                            $("#dvShowallresults").show();
                        } else {
                            $("#a-results-show-all").removeClass("visiblehidden").addClass("visiblehidden");
                            if (numItems > 0) {
                                $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").show();
                            } else {
                                $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").hide();
                            }
                            $("#dvShowallresults").show();
                        }
                    }, 20);
                }
                $("#fl-results-pager").find('#fl-results-pager-container')
                    .on('search.auxillary.updated', function (event, type, flightPair) {
                        if (!flightPair) {
                            return;
                        }

                        if (type === 'auxillary') {
                            _.forEach(sortedResults.Trips[0].Flights, function (flight) {
                                var updated = flightPair[flight.Hash];
                                if (updated) {
                                    flight.Products = updated.Products;
                                    flight.Auxilliary = updated.Auxilliary;
                                    flight.Connections = updated.Connections;
                                }
                            });
                        } else if (type === 'Amenities') {
                            _.forEach(sortedResults.Trips[0].Flights, function (flight) {
                                var updated = flightPair[flight.FlightNumber];
                                if (updated) {
                                    flight.Amenities = updated.Amenities;
                                }
                                _.forEach(flight.Connections, function (conn) {
                                    updated = flightPair[conn.FlightNumber];
                                    if (updated) {
                                        conn.Amenities = updated.Amenities;
                                    }
                                });
                            });
                        }
                    }).on('search.sort.changed', function (event) {
                        //reDrawFilter = true;
                        var selectedSort = $('#SortType').val();

                        _this.currentResults.appliedSearch.SortType = selectedSort;
                        sortedResults = _this.handleSort(sortedResults);
                        //flightsResults = jQuery.extend(true, {}, sortedResults);
                        if (AllflightfeatureAward || !Allflightfeature) {
                            $(this).pagination('selectPage', 1);
                        } else {
                            showallresults = _this.getShowAllResultsCookie();
                            _this.pagingNew(sortedResults, refreshFilters, !reDrawFilter, showallresults);
                        }
                    }).on('search.filter.changed', function (event, filteredFlights, refresh) {
                        reDrawFilter = true;
                        refreshFilters = refresh;
                        if (sorting) {
                            sortedResults = _this.handleSort(filteredFlights);
                        } else {
                            if (!(typeof filteredFlights === "undefined" || filteredFlights === null)) {
                                sortedResults = filteredFlights;
                            }
                        }
                        numItems = sortedResults.Trips[0].Flights.length;
                        sortedResults.Trips[0].CurrentFlightCount = numItems;
                        if (AllflightfeatureAward || !Allflightfeature) {
                            $(this).pagination('updateItems', numItems);

                            $(this).pagination('selectPage', 1);
                            if (filteredFlights && filteredFlights.Trips && filteredFlights.Trips[0] && filteredFlights.Trips[0].Flights.length > 0) {                            
                            $('#resultnotext').text(filteredFlights.Trips[0].Flights.length);
                            $('#resultnotextTlt').text(sortedResults.Trips[0].Flights.length);
                            }
                        } else {
                            tripsShowAllResults = JSON.parse(UA.Utilities.safeSessionStorage.getItem("tripsShowAllResults"));
                            tripindex = _this.getTripIndex();
                            showallresults = _this.getShowAllResultsCookie();
                            _this.pagingNew(sortedResults, refreshFilters, reDrawFilter, showallresults);
                            if (numItems <= perPage) {
                                $("#a-results-show-all").removeClass("visiblehidden").addClass("visiblehidden");
                                if (numItems > 0) {
                                    $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").show();
                                } else {
                                    $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").hide();
                                }
                                $("#dvShowallresults").show();
                                if (tripsShowAllResults != null && tripsShowAllResults.length > tripindex) tripsShowAllResults[tripindex].ShowAllResults = false;
                                UA.Utilities.safeSessionStorage.setItem("tripsShowAllResults", JSON.stringify(tripsShowAllResults));
                            }
                        }
                        _this.filteredRecommendedFlights = sortedResults.Trips[0].Flights;
                    }).on('search.filter2.changed', function (event, filteredFlights, refresh) {
                        reDrawFilter = true;
                        refreshFilters = refresh;
                        sortedResults = filteredFlights;
                        numItems = sortedResults.Trips[0].Flights.length;
                        sortedResults.Trips[0].CurrentFlightCount = numItems;
                        if (!AllflightfeatureAward && Allflightfeature) {
                            tripsShowAllResults = JSON.parse(UA.Utilities.safeSessionStorage.getItem("tripsShowAllResults"));
                            tripindex = _this.getTripIndex();
                            showallresults = _this.getShowAllResultsCookie();
                            if (numItems <= perPage) {
                                $("#a-results-show-all").removeClass("visiblehidden").addClass("visiblehidden");
                                if (numItems > 0) {
                                    $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").show();
                                } else {
                                    $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").hide();
                                }
                                $("#dvShowallresults").show();
                                if (tripsShowAllResults != null && tripsShowAllResults.length > tripindex) tripsShowAllResults[tripindex].ShowAllResults = false;
                                UA.Utilities.safeSessionStorage.setItem("tripsShowAllResults", JSON.stringify(tripsShowAllResults));
                            }
                        }
                        _this.filteredRecommendedFlights = sortedResults.Trips[0].Flights;
                    }).on('search.view.changed', function () {
                        reDrawFilter = false;
                        refreshFilters = false;
                        if (AllflightfeatureAward || !Allflightfeature) {
                            var currentPage = $(this).pagination('getCurrentPage');

                            $(this).pagination('selectPage', currentPage);
                        } else {
                            showallresults = _this.getShowAllResultsCookie();
                            _this.pagingNew(sortedResults, refreshFilters, reDrawFilter, showallresults);
                        }
                    });
            },
            pagingNew: function (sortedResults, refreshFilters, reDrawFilter, Allresults) {
                var _this = this;
                if (_this.IsFlightRecommendationEnabledWithVTwo() && sortedResults.Trips && sortedResults.Trips.length > 0) {
                    _this.UpdateFlightsForRecommendationVTwo(sortedResults.Trips[0].Flights);
                }
                if (Allresults) {
                    _this.render(sortedResults, refreshFilters, reDrawFilter);
                    $('#resultnotext').text(sortedResults.Trips[0].Flights.length);
                } else {
                    var pagesize = parseInt($('#AllflightfeaturePageSize').val()) || 35;
                    var flightsResultsNew = jQuery.extend(true, {}, sortedResults),
                        flightsNew;
                    flightsNew = flightsResultsNew.Trips[0].Flights.slice(0, pagesize);
                    flightsResultsNew.Trips[0].Flights = flightsNew;
                    _this.render(flightsResultsNew, refreshFilters, reDrawFilter);
                    $('#resultnotext').text(flightsResultsNew.Trips[0].Flights.length);
                }
                $('#resultnotextTlt').text(sortedResults.Trips[0].Flights.length);

                $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").css("float", "none");
                $("#dvShowallresults > #a-results-show-all").css("margin-left", "0px");
            },
            getShowAllResultsCookie: function () {
                var _this = this,
                    i = 0;
                var tripsShowAllResults = JSON.parse(UA.Utilities.safeSessionStorage.getItem("tripsShowAllResults"));
                if (tripsShowAllResults == null) {
                    tripsShowAllResults = [];
                    for (i; i < _this.currentResults.appliedSearch.Trips.length; i++) {
                        tripsShowAllResults.push({
                            ShowAllResults: false,
                            flightscrollpos: ''
                        });
                    }
                    UA.Utilities.safeSessionStorage.setItem("tripsShowAllResults", JSON.stringify(tripsShowAllResults));
                }
                var tripindex = _this.getTripIndex();
                return (tripsShowAllResults != null && tripsShowAllResults.length > tripindex && tripsShowAllResults[tripindex].ShowAllResults) ? true : false;
            },
            render: function (flightResults, refreshFilters, suppressFilterAndSummaryRender) {
                var _this = this;

                flightResults.IsListView = this.fetchResultViewType();
                _this.renderFlightResults(flightResults);
                if ($("#upgrade-option-placeholder").length > 0) {
                    $('#upgrade-option-placeholder').html(this.templates.pprUpgradeRadioButton(flightResults));
                }
                _this.elements.resultsContainer.fadeTo(400, 1, function () {
                    _this.renderFlightResultsFooter();
                });

                if (!suppressFilterAndSummaryRender) {
                    if (_this.showTopFilters || _this.showTopFiltersAward || _this.searchFilterMode === 'footerondemand' || _this.searchFilterMode === 'footer') {
                        if (_this.searchFilterMode === 'footerondemand' && !this.currentResults.appliedSearch.SearchFilters.FilterApplied) {
                            var data = {
                                SearchFilters: {}
                            };
                            data.SearchFilters.hideFilterContent = true;
                            data.SearchFilters.HideAirportSection = flightResults.SearchFilters.HideAirportSection;
                            data.SearchFilters.HideExperienceSection = flightResults.SearchFilters.HideExperienceSection;
                            data.SearchFilters.PriceFilterActive = flightResults.SearchFilters.PriceFilterActive;
                            data.SearchFilters.AirportFilterActive = flightResults.SearchFilters.AirportFilterActive;
                            data.SearchFilters.ExperienceFilterActive = flightResults.SearchFilters.ExperienceFilterActive;
                            data.SearchFilters.CurrFlightCount = flightResults.Trips[0].CurrentFlightCount;
                            data.SearchFilters.TotFlightCount = flightResults.Trips[0].TotalFlightCount;
                            data.SearchFilters.PriceMinFormatted = flightResults.SearchFilters.PriceMinFormatted;
                            if (_this.showTopFilters || _this.showTopFiltersAward) {
                                _this.renderSearchFilters(flightResults, refreshFilters);
                                _this.renderFlightResultsHeader(flightResults);
                                //_this.buildFareWheel(_this.globalFWResponse);
                            }
                            else {//top filters off path
                                if ($("#hdnAward").val() === "True") { //1291 Priya
                                    _this.renderSearchFilters(flightResults, refreshFilters, true);
                                } else {
                                    _this.renderSearchFilters(flightResults, refreshFilters, false);
                                }
                            }
                        } else {
                            _this.renderSearchFilters(flightResults, refreshFilters);
                            if (_this.showTopFilters || _this.showTopFiltersAward) {
                                _this.renderFlightResultsHeader(flightResults);
                                //_this.buildFareWheel(_this.globalFWResponse);
                            }
                        }
                    }
                }                

                
                setTimeout(function () {
                    $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").css("float", "none");
                    $("#dvShowallresults > #a-results-show-all").css("margin-left", "0px");
                }, 5);

                _this.renderShopSearchCount();

                //if (!dcmPopulated) {
                //    var dcmCode = flightResults.IsAward ? "FSRAW" : "FSR";
                //    UA.Common.RulesEngine.setCodesToRetrieve(dcmCode);
                //    UA.Common.RulesEngine.init();
                //    dcmPopulated = true;
                //}

            },

            loadFilterResults: function (search, refresh, sorting, preventPagination, lateSorting, targetLoader) {

                if (!search.SearchFilters) {
                    return;
                }

                if (typeof sorting === "undefined" || sorting === null) {
                    sorting = true;
                }
                if (typeof preventPagination === "undefined" || preventPagination === null) {
                    preventPagination = false;
                }
                var _this = this,
                    response = this.currentResults,
                    filteredFlights,
                    filterStops,
                    priceMin,
                    priceMax,
                    arriveMin,
                    arriveMax,
                    departMin,
                    departMax,
                    durationMin,
                    durationMax,
                    layoverMin,
                    layoverMax,
                    connectionAirports,
                    airportOrigins,
                    airportDestinations,
                    filteredLog,
                    newFlights;


                setTimeout(function () {

                    if (response.Trips !== null && response.Trips.length > 0 &&
                        response.Trips[0].Flights !== null && response.Trips[0].Flights.length > 0 &&
                        _this.elements.resultsContainer !== null) {

                        //filteredFlights = response;
                        filteredFlights = jQuery.extend(true, {}, response); //clone response;
                        search.FareFamilyDescription = response.FareFamilyDescription;
                        filterStops = [];
                        if (search.SearchFilters.nonStop) {
                            filterStops.push(0);
                        }
                        if (search.SearchFilters.oneStop) {
                            filterStops.push(1);
                        }
                        if (search.SearchFilters.twoPlusStop) {
                            filterStops.push(2);
                        }

                        if (!_this.currentResults.appliedSearch.SearchFilters.FareFamily) {
                            _this.currentResults.appliedSearch.SearchFilters.FareFamily = response.SearchFilters.FareFamily;
                        }

                        priceMin = search.SearchFilters.PriceMin;
                        priceMax = search.SearchFilters.PriceMax;
                        if (!priceMin || !priceMax) {
                            priceMin = response.SearchFilters.MinPrices[search.SearchFilters.FareFamily];
                            priceMax = response.SearchFilters.MaxPrices[search.SearchFilters.FareFamily];
                        }

                        arriveMin = search.SearchFilters.TimeArrivalMin;
                        arriveMax = search.SearchFilters.TimeArrivalMax;

                        departMin = search.SearchFilters.TimeDepartMin;
                        departMax = search.SearchFilters.TimeDepartMax;

                        durationMin = search.SearchFilters.DurationMin;
                        durationMax = search.SearchFilters.DurationMax;

                        layoverMin = search.SearchFilters.LayoverMin;
                        layoverMax = search.SearchFilters.LayoverMax;

                        airportOrigins = [];
                        if (search.SearchFilters.AirportsOrigin) {
                            airportOrigins = search.SearchFilters.AirportsOrigin.split(',');
                        }
                        //else if (search.SearchFilters.AirportsOrigin.length == 0) {
                        //    airportOrigins = (search.Origin.toUpperCase()).split(',');
                        //}

                        airportDestinations = [];
                        if (search.SearchFilters.AirportsDestination) {
                            airportDestinations = search.SearchFilters.AirportsDestination.split(',');
                        }
                        //else if (search.SearchFilters.AirportsDestination.length == 0) {
                        //    airportDestinations = (search.Destination.toUpperCase()).split(',');
                        //}

                        var hasConnections = response.SearchFilters.AirportsStopList && response.SearchFilters.AirportsStopList.length > 0 && !response.SearchFilters.HideAirportSection;
                        connectionAirports = [];
                        var avoidedAirports = [];

                        if (search.SearchFilters.AirportsStop) {
                            connectionAirports = search.SearchFilters.AirportsStop.split(',');
                            if (connectionAirports != null && connectionAirports) {
                                avoidedAirports = _this.GetConnectionsToAvoid(connectionAirports, response.SearchFilters.AirportsStopList);
                            }
                        }

                        var filteredCarriers = [];
                        if (search.SearchFilters.CarriersPreference && response.SearchFilters.CarriersPreference && response.SearchFilters.CarriersPreference.length > 1) {
                            filteredCarriers = _.difference(response.SearchFilters.CarriersPreference, search.SearchFilters.CarriersPreference);
                        }

                        var requiredAmenities = [];
                        if (response.SearchFilters.Amenities && response.SearchFilters.Amenities.length > 1 && search.SearchFilters.Amenities) {
                            requiredAmenities = search.SearchFilters.Amenities;
                        }

                        var filteredWarnings = [];
                        if (search.SearchFilters.Warnings && response.SearchFilters.Warnings && response.SearchFilters.Warnings.length > 0) {
                            filteredWarnings = _.difference(response.SearchFilters.Warnings, search.SearchFilters.Warnings);
                        }

                        var fliteredAircraft = [];
                        if (search.SearchFilters.AircraftList && response.SearchFilters.AircraftList && response.SearchFilters.AircraftList.length > 1) {
                            fliteredAircraft = _.difference(response.SearchFilters.AircraftList, search.SearchFilters.AircraftList);
                        }

                        ////var equipmentCodes = searchFilters.SearchFilters.EquipmentCodes.split(',');

                        filteredLog = function (isDataPresent, msg) {
                            if (!isDataPresent) {
                                //log(msg);
                            }
                        };


                        var minPrice, minPriceNonStop, minPriceOneStop, minPriceTwoPlusStop, minDestinationPrice = {},
                            minOriginPrice = {}, minPriceNonStopTop, minPriceStopsTop;

                        if (!_this.currentResults.appliedSearch.SearchFilters.FareFamily) {
                            _this.currentResults.appliedSearch.SearchFilters.FareFamily = response.SearchFilters.FareFamily;
                        }
                        var maxPrice = parseInt(response.SearchFilters.MaxPrices[_this.currentResults.appliedSearch.SearchFilters.FareFamily], 10);
                        minPriceNonStop = parseInt(response.SearchFilters.NonStopMinPricesByColumn[_this.currentResults.appliedSearch.SearchFilters.FareFamily], 10);
                        minPriceOneStop = parseInt(response.SearchFilters.OneStopMinPricesByColumn[_this.currentResults.appliedSearch.SearchFilters.FareFamily], 10);
                        minPriceTwoPlusStop = parseInt(response.SearchFilters.TwoPlusMinPricesByColumn[_this.currentResults.appliedSearch.SearchFilters.FareFamily], 10);

                        if (_this.showTopFilters || _this.showTopFiltersAward) {
                            setTopFiltersMinPricesNonStopAndStops(_this, response, filteredFlights)
                        }
                        if (!isNaN(maxPrice)) {
                            minPrice = Math.ceil(maxPrice);
                        }
                        if (isNaN(minPriceNonStop)) {
                            minPriceNonStop = 0;
                        } else {
                            minPriceNonStop = Math.ceil(minPriceNonStop);
                        }
                        if (isNaN(minPriceOneStop)) {
                            minPriceOneStop = 0;
                        } else {
                            minPriceOneStop = Math.ceil(minPriceOneStop);
                        }
                        if (isNaN(minPriceTwoPlusStop)) {
                            minPriceTwoPlusStop = 0;
                        } else {
                            minPriceTwoPlusStop = Math.ceil(minPriceTwoPlusStop);
                        }

                        newFlights = _.filter(filteredFlights.Trips[0].Flights, function (filterFlight) {
                            var isDataPresent = false,
                                price;

                            if (filterFlight.PricesByColumn && filterFlight.PricesByColumn[search.SearchFilters.FareFamily]) {
                                price = filterFlight.PricesByColumn[search.SearchFilters.FareFamily];
                            }

                            if (filterStops != null && filterStops.length > 0) {
                                isDataPresent = _this.CheckStops(filterStops, filterFlight);
                                filteredLog(isDataPresent, 'filterStops  flight hash' + filterFlight.Hash);
                            }

                            if (_this.showTopFilters !== true && _this.showTopFiltersAward !== true) {
                                if (isDataPresent && priceMin && _.isNumber(priceMin) && priceMax && _.isNumber(priceMax) && _.isNumber(price)) {
                                    isDataPresent = _this.CheckRange(priceMin, priceMax, price);
                                    filteredLog(isDataPresent, 'filtered priceMin && priceMax SearchFilters.FareFamily =' + search.SearchFilters.FareFamily + '  MinPrice =' + price + ' flight hash' + filterFlight.Hash);
                                } else if (isDataPresent && priceMin && _.isNumber(priceMin) && priceMax && _.isNumber(priceMax)) {
                                    if (isNaN(price)) {
                                        isDataPresent = true;
                                    }
                                }
                            }

                            if (isDataPresent && arriveMin && arriveMax) {
                                isDataPresent = _this.CheckDateTimeRange(arriveMin, arriveMax, filterFlight.LastDestinationDateTime);
                                filteredLog(isDataPresent, 'arriveMin && arriveMax filterFlight.LastDestinationDateTime =' + filterFlight.LastDestinationDateTime + '  flight hash' + filterFlight.Hash);
                            }

                            if (isDataPresent && departMin && departMax) {
                                isDataPresent = _this.CheckDateTimeRange(departMin, departMax, filterFlight.DepartDateTime);
                                filteredLog(isDataPresent, 'departMin && departMax filterFlight.DepartDateTime =' + filterFlight.DepartDateTime + '  flight hash' + filterFlight.Hash);
                            }

                            if (_this.showTopFilters !== true && _this.showTopFiltersAward !== true) {
                                if (isDataPresent && durationMin >= 0 && durationMax >= 0) {
                                    isDataPresent = _this.CheckRange(durationMin, durationMax, filterFlight.TravelMinutesTotal);
                                    filteredLog(isDataPresent, 'durationMin && durationMax filterFlight.TravelMinutesTotal =' + filterFlight.TravelMinutesTotal + '  flight hash' + filterFlight.Hash);
                                }

                                if (isDataPresent && layoverMin >= 0 && layoverMax >= 0) {
                                    isDataPresent = _this.CheckLayoverRange(layoverMin, layoverMax, filterFlight);
                                    filteredLog(isDataPresent, 'layoverMin && layoverMax  filterFlight.MaxLayoverTime =' + filterFlight.MaxLayoverTime + '  flight hash' + filterFlight.Hash);
                                }
                            }

                            if (isDataPresent && hasConnections) {
                                isDataPresent = _this.CheckConnectionAirport(connectionAirports, filterFlight, hasConnections);
                                filteredLog(isDataPresent, 'connectionAirports flight hash' + filterFlight.Hash);
                            }
                            if (isDataPresent && hasConnections) {
                                isDataPresent = _this.CheckConnectionAirportToAvoid(avoidedAirports, filterFlight);
                                filteredLog(isDataPresent, 'connectionAirportsToAvoid  flight hash' + filterFlight.Hash);
                            }
                            if (isDataPresent && (airportOrigins.length > 0 || airportDestinations.length > 0)) {
                                isDataPresent = _this.CheckAirportOriginDestination(airportOrigins, airportDestinations, filterFlight);
                                filteredLog(isDataPresent, 'filtered airportOrigins.length > 0 || airportDestinations.length  flight hash' + filterFlight.Hash);
                            }

                            if (_this.showTopFilters !== true && _this.showTopFiltersAward !== true) {
                                if (isDataPresent && requiredAmenities.length > 0) {
                                    isDataPresent = _this.CheckAmenities(requiredAmenities, filterFlight);
                                    filteredLog(isDataPresent, 'filtered CheckAmenities flight number' + filterFlight.FlightNumber);
                                }

                                if (isDataPresent && filteredWarnings.length > 0) {
                                    isDataPresent = _this.CheckWarnings(filteredWarnings, filterFlight);
                                    filteredLog(isDataPresent, 'filtered CheckWarnings  flight hash' + filterFlight.Hash);
                                }

                                if (isDataPresent && fliteredAircraft.length > 0) {
                                    isDataPresent = _this.CheckAircraftType(fliteredAircraft, filterFlight);
                                    filteredLog(isDataPresent, 'filtered CheckAircraftType  flight hash' + filterFlight.Hash);
                                }
                            }

                            if (isDataPresent && filteredCarriers.length > 0) {
                                isDataPresent = _this.CheckCarrierPreference(filteredCarriers, filterFlight);
                                filteredLog(isDataPresent, 'filtered CheckCarrierPreference  flight hash' + filterFlight.Hash);
                            }

                            if (!isNaN(price)) {
                                if (!minPrice) {
                                    minPrice = price;
                                } else if (price < minPrice) {
                                    minPrice = price;
                                }

                                if (!minPriceNonStop && filterFlight.StopsandConnections == 0) {
                                    minPriceNonStop = price;
                                } else if (filterFlight.StopsandConnections == 0 && price < minPriceNonStop) {
                                    minPriceNonStop = price;
                                }

                                if (!minPriceOneStop && filterFlight.StopsandConnections == 1) {
                                    minPriceOneStop = price;
                                } else if (filterFlight.StopsandConnections == 1 && price < minPriceOneStop) {
                                    minPriceOneStop = price;
                                }

                                if (!minPriceTwoPlusStop && filterFlight.StopsandConnections > 1) {
                                    minPriceTwoPlusStop = price;
                                } else if (filterFlight.StopsandConnections > 1 && price < minPriceTwoPlusStop) {
                                    minPriceTwoPlusStop = price;
                                }


                                if (!minOriginPrice[filterFlight.Origin]) {
                                    minOriginPrice[filterFlight.Origin] = {
                                        Code: filterFlight.Origin,
                                        Description: filterFlight.OriginDescription,
                                        Amount: price,
                                        AmountFormated: ''
                                    };
                                } else if (minOriginPrice[filterFlight.Origin] && price < minOriginPrice[filterFlight.Origin].Amount) {
                                    minOriginPrice[filterFlight.Origin].Amount = price;
                                }

                                if (!minDestinationPrice[filterFlight.LastDestination.Code]) {
                                    minDestinationPrice[filterFlight.LastDestination.Code] = {
                                        Code: filterFlight.LastDestination.Code,
                                        Description: filterFlight.LastDestination.Description,
                                        Amount: price,
                                        AmountFormated: ''
                                    };
                                } else if (minDestinationPrice[filterFlight.LastDestination.Code] && price < minDestinationPrice[filterFlight.LastDestination.Code].Amount) {
                                    minDestinationPrice[filterFlight.LastDestination.Code].Amount = price;
                                }
                            }
                            return isDataPresent;
                        });
                        var miles = $("#hdnMiles").val();
                        filteredFlights.SearchFilters.PriceMinFormatted = '';
                        if (!isNaN(minPrice)) {
                            filteredFlights.SearchFilters.PriceMinFormatted = response.IsAward ? UA.Utilities.formatting.formatMoney(minPrice, miles, 0) : UA.Utilities.formatting.formatMoney(_this.evenRound(minPrice), UA.AppData.Data.Session.Currency, 0);
                        }
                        filteredFlights.SearchFilters.NonStopFormattedAmount = '';
                        if (!isNaN(minPriceNonStop)) {
                            filteredFlights.SearchFilters.NonStopFormattedAmount = response.IsAward ? UA.Utilities.formatting.formatMoney(minPriceNonStop, miles, 0) : UA.Utilities.formatting.formatMoney(_this.evenRound(minPriceNonStop), UA.AppData.Data.Session.Currency, 0);
                        }
                        filteredFlights.SearchFilters.OneStopFormattedAmount = '';
                        if (!isNaN(minPriceOneStop)) {
                            filteredFlights.SearchFilters.OneStopFormattedAmount = response.IsAward ? UA.Utilities.formatting.formatMoney(minPriceOneStop, miles, 0) : UA.Utilities.formatting.formatMoney(_this.evenRound(minPriceOneStop), UA.AppData.Data.Session.Currency, 0);
                        }
                        filteredFlights.SearchFilters.TwoPlusStopFormattedAmount = '';
                        if (!isNaN(minPriceTwoPlusStop)) {
                            filteredFlights.SearchFilters.TwoPlusStopFormattedAmount = response.IsAward ? UA.Utilities.formatting.formatMoney(minPriceTwoPlusStop, miles, 0) : UA.Utilities.formatting.formatMoney(_this.evenRound(minPriceTwoPlusStop), UA.AppData.Data.Session.Currency, 0);
                        }
                        filteredFlights.SearchFilters.AirportsOriginList = _.values(minOriginPrice);
                        _.forEach(filteredFlights.SearchFilters.AirportsOriginList, function (origin) {
                            if (!isNaN(origin.Amount)) {
                                origin.AmountFormatted = response.IsAward ? UA.Utilities.formatting.formatMoney(origin.Amount, miles, 0, true) + "<br />" + miles : UA.Utilities.formatting.formatMoney(origin.Amount, UA.AppData.Data.Session.Currency, 0);
                            }
                        });

                        filteredFlights.SearchFilters.AirportsDestinationList = _.values(minDestinationPrice);
                        _.forEach(filteredFlights.SearchFilters.AirportsDestinationList, function (destination) {
                            if (!isNaN(destination.Amount)) {
                                destination.AmountFormatted = response.IsAward ? UA.Utilities.formatting.formatMoney(destination.Amount, miles, 0, true) + "<br />" + miles : UA.Utilities.formatting.formatMoney(destination.Amount, UA.AppData.Data.Session.Currency, 0);
                            }
                        });
                        filteredFlights.Trips[0].Flights = newFlights;
                        UA.UI.logFilterData(search);
                        if (!preventPagination) {
                            if (lateSorting === true) {
                                $("#fl-results-pager-container").trigger('search.filter2.changed', [filteredFlights, refresh]);
                            } else {
                                $("#fl-results-pager-container").trigger('search.filter.changed', [filteredFlights, refresh]);
                            }
                        }
                        //Display only filtered result. No need to trigger search filter changed event to re-render the FSR result
                        else {
                            if (_this.showTopFilters || _this.showTopFiltersAward) {
                                _this.handleFilterSearchResult(filteredFlights);
                            } else if (_this.searchFilterMode === 'footerondemand') {
                                _this.renderSearchFilters(filteredFlights, refresh, true);
                                var filteredSection = preventPagination;
                                var filterArea = $('.filter-header-container').find('[data-toggler-target="' + filteredSection + '"]');
                                if (filterArea.length > 0)
                                    filterArea.toggler('open');
                            }
                        }

                        if ((_this.showTopFilters || _this.showTopFiltersAward) && refresh) {
                            _this.renderFlightResultsHeader(filteredFlights);
                            _this.showFilterLoader();//CSI-1372
                            //_this.buildFareWheel(_this.globalFWResponse);//CSI1303 re rerender fare wheel after interacting with top modal airports SHD

                        }
                    }

                    _this.afterLoadFilter();

                    if (targetLoader !== undefined && targetLoader != null) {
                        //targetLoader.loader("destroy");
                    }

                    $("#dvShowallresults > div.pagerShowAll-padding > #search-result-feedback").css("float", "none");
                    $("#dvShowallresults > #a-results-show-all").css("margin-left", "0px"); 
                    UA.UI.Tooltip.init();
                }, 5);
                if (!preventPagination) {
                    response.SearchType = search.searchTypeMain;
                    _this.initPagination(response, refresh, sorting);
                }
            },

            CheckStops: function (filterStops, filterFlight) {
                var i, present = false;
                for (i = 0; i < filterStops.length; i += 1) {
                    if (filterFlight.StopsandConnections == filterStops[i]) {
                        present = true;
                        break;
                    } else {
                        if (filterStops[i] == 2 && filterFlight.StopsandConnections > 2) {
                            present = true;
                            break;
                        }
                    }
                }
                return present;
            },
            CheckConnectionAirport: function (connectionAirports, filterFlight) {
                var present = true,
                    connections = filterFlight.AirportsStopList,
                    count,
                    connection;
                if (connectionAirports && connectionAirports !== "" && connections && connections.length > 0) {
                    present = false;
                    for (count = 0; count < connections.length; count += 1) {
                        connection = connections[count];
                        if (connection) {
                            if (connection.Code != null) {
                                if ($.inArray(connection.Code.toUpperCase(), connectionAirports) > -1) {
                                    present = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                return present;
            },
            CheckConnectionAirportToAvoid: function (airportsToAvoid, filterFlight) {
                var notPresent = true,
                    connections = filterFlight.AirportsStopList,
                    count,
                    connection;
                if (airportsToAvoid && airportsToAvoid.length > 0 && connections && connections.length > 0) {
                    notPresent = true;
                    for (count = 0; count < connections.length; count += 1) {
                        connection = connections[count];
                        if (connection) {
                            if (connection.Code != null) {
                                if ($.inArray(connection.Code.toUpperCase(), airportsToAvoid) > -1) {
                                    notPresent = false;
                                }
                            }
                        }
                    }
                }
                return notPresent;
            },
            CheckAirportOriginDestination: function (airportOrigins, airportDestinations, filterFlight) {
                var originAirport = filterFlight.Origin,
                    destinationAirport = filterFlight.LastDestination.Code,
                    present = true;
                if (airportOrigins && airportOrigins.length > 0 && originAirport != null) {
                    present = false;
                    if ($.inArray(originAirport.toUpperCase(), airportOrigins) > -1) {
                        present = true;
                    }
                }
                if (present && airportDestinations && airportDestinations.length > 0 && destinationAirport != null) {
                    present = false;
                    if ($.inArray(destinationAirport.toUpperCase(), airportDestinations) > -1) {
                        present = true;
                    }
                }
                return present;
            },
            CheckAmenities: function (requiredAmenities, filterFlight) {
                function HasAllRequiredAmenities(object) {
                    var indicators = object.Amenities,
                        key,
                        name,
                        amenity;
                    if (!indicators || indicators.length < 1) {
                        return false;
                    }
                    for (key in requiredAmenities) {
                        name = requiredAmenities[key];
                        amenity = indicators[name];
                        if (!amenity || !amenity.IsOffered) {
                            return false;
                        }
                    }
                    return true;
                }
                if (!requiredAmenities || requiredAmenities.length < 1) {
                    return true;
                }
                if (HasAllRequiredAmenities(filterFlight)) {
                    return true;
                }
                if (filterFlight.Connections && filterFlight.Connections.length > 0) {
                    if (_.any(filterFlight.Connections, HasAllRequiredAmenities)) {
                        return true;
                    }
                }
                return false;
            },
            CheckWarnings: function (filteredWarnings, filterFlight) {
                function HasAnyFilteredWarning(object) {
                    var key, warning;
                    for (key in object.Warnings) {
                        warning = object.Warnings[key];
                        if (_.contains(filteredWarnings, warning.Key)) {
                            return true;
                        }
                        if (warning.Messages && warning.Messages.length > 0 && _.contains(filteredWarnings, warning.Messages[0])) {
                            return true;
                        }
                    }
                    return false;
                }
                if (!filteredWarnings || filteredWarnings.length < 1) {
                    return true;
                }
                if (HasAnyFilteredWarning(filterFlight)) {
                    return false;
                }
                if (filterFlight.Connections && filterFlight.Connections.length > 0) {
                    if (_.any(filterFlight.Connections, HasAnyFilteredWarning)) {
                        return false;
                    }
                }
                return true;
            },
            CheckCarrierPreference: function (filteredCarriers, filterFlight) {
                function HasAnyFilteredCarrier(object) {
                    if (_.contains(filteredCarriers, "CarrierDefault") && object.IsUnited) {
                        return true;
                    }
                    if (_.contains(filteredCarriers, "CarrierExpress") && object.IsUnitedExpress) {
                        return true;
                    }
                    if (_.contains(filteredCarriers, "CarrierStar") && object.IsStarAlliance) {
                        return true;
                    }
                    if (_.contains(filteredCarriers, "CarrierPartners") && object.IsUnitedPartner) {
                        return true;
                    }
                    return false;
                }
                if (!filteredCarriers || filteredCarriers.length < 1) {
                    return false;
                }
                if (HasAnyFilteredCarrier(filterFlight)) {
                    return false;
                }
                if (filterFlight.Connections && filterFlight.Connections.length > 0) {
                    if (_.any(filterFlight.Connections, HasAnyFilteredCarrier)) {
                        return false;
                    }
                }
                return true;
            },
            CheckAircraftType: function (filteredAircraft, filterFlight) {
                function HasAnyFilteredType(object) {
                    if (_.contains(filteredAircraft, "SingleCabinExist") && object.IsSingleCabin) {
                        return true;
                    }
                    if (_.contains(filteredAircraft, "MultiCabinExist") && !object.IsSingleCabin) {
                        return true;
                    }
                    if (_.contains(filteredAircraft, "TurboPropExist") && object.NonJetEquipment) {
                        return true;
                    }
                    return false;
                }
                if (!filteredAircraft || filteredAircraft.length < 1 || !filterFlight.AllEquipmentDisclosures || filterFlight.AllEquipmentDisclosures.length < 1) {
                    return false;
                }
                return !_.any(filterFlight.AllEquipmentDisclosures, HasAnyFilteredType)
            },
            CheckDateTimeRange: function (minTime, maxTime, compareTime) {
                var _this = this,
                    minTimeDate = _this.parseDateTime(minTime),
                    maxTimeDate = _this.parseDateTime(maxTime),
                    compareTimeDate = _this.parseDateTime(compareTime);
                if (compareTimeDate) {
                    return compareTimeDate.between(minTimeDate, maxTimeDate);
                }
                return false;
            },
            parseDateTime: function (dateString) {
                return Date.parseExact(dateString, 'MM/dd/yyyy HH:mm');
            },
            CheckRange: function (min, max, value) {
                var isWithinRange = false;
                if (value >= min && value <= max) {
                    isWithinRange = true;
                }
                return isWithinRange;
            },
            CheckLayoverRange: function (min, max, filterFlight) {
                var isWithinRange = false;
                var flightMax = filterFlight.MaxLayoverTime;
                if (flightMax >= min && flightMax <= max) {
                    isWithinRange = true;
                }
                return isWithinRange;
            },
            GetConnectionsToAvoid: function (prefferredConnections, airportStopList) {
                var avoidedAirports = [],
                    count,

                    connection,
                    index;
                if (airportStopList && airportStopList.length > 1) {
                    index = 0;
                    for (count = 0; count < airportStopList.length; count += 1) {
                        connection = airportStopList[count];
                        if (connection) {
                            if (connection.Code != null) {
                                if ($.inArray(connection.Code.toUpperCase(), prefferredConnections) == -1) {
                                    avoidedAirports[index] = connection.Code.toUpperCase();
                                    index++;
                                }
                            }
                        }
                    }
                }
                return avoidedAirports;
            },
            evenRound: function (num, decimalPlaces) {
                var d = decimalPlaces || 0;
                var m = Math.pow(10, d);
                var n = +(d ? num * m : num).toFixed(8); // Avoid rounding errors
                var i = Math.floor(n),
                    f = n - i;
                var e = 1e-8; // Allow for rounding errors in f
                var r = (f > 0.5 - e && f < 0.5 + e) ? ((i % 2 == 0) ? i : i + 1) : Math.round(n);
                return d ? r / m : r;
            },
            CheckDepartDate: function (dt) {
                var dvfltErrMsg = $('#FlightResultsError'),
                    li = dvfltErrMsg.find('li');
                li[0].style.display = "block";
                li[1].style.display = "none";
                if (this.currentResults.SearchType === "rt" || this.currentResults.SearchType === "mc" || ($('#editFlightSearch').val() == 'True' && this.currentResults.SearchType == 'multiCity')) {
                    var changedeptdate = new Date(dt),
                        originalDeparturedate;
                    if ((this.currentResults.SelectedTrips !== null && this.currentResults.SelectedTrips.length > 0)) {
                        originalDeparturedate = UA.Utilities.formatting.tryParseDate(this.currentResults.SelectedTrips[this.getTripIndex() - 1].DepartDate);
                        li[0].style.display = "none";
                        li[1].style.display = "block";
                    } else {
                        originalDeparturedate = new Date();
                        var editFlightSearch = $('#editFlightSearch').val() == 'True' ? true : false;
                        if (!editFlightSearch)
                            $('.btn-show-new-search').click();
                    }
                    if ((changedeptdate.getDate() < originalDeparturedate.getDate()) && (changedeptdate.getMonth() <= originalDeparturedate.getMonth()) && (changedeptdate.getFullYear() <= originalDeparturedate.getFullYear())) {
                        var msg = $("#hdnInvalidDateErrorMessage").val();
                        msg = msg.replace("{0}", this.getTripIndex() + 1);
                        msg = msg.replace("{1}", this.getTripIndex());
                        msg = msg.substring(0, msg.indexOf('<!--'));
                        $(li[1]).text(msg);
                        dvfltErrMsg.show();
                        $("html, body").animate({
                            scrollTop: 0
                        });
                        return false;
                    }
                }
                return true;
            },
            handleSignInClick: function (e) {
                UA.Common.Header.showLoginModal(); //use same login method as header sign in
            },
            ProcessRecommendedFlights: function () {
                var _this = this;
                if ((UA.Booking.FlightSearch.IsFlightRecommendationEnabledWithVTwo() || UA.Booking.FlightSearch.IsFlightRecommendationEnabledWithVOne())
                    && UA.Booking.FlightSearch.currentResults && UA.Booking.FlightSearch.currentResults.Trips
                    && UA.Booking.FlightSearch.currentResults.Trips.length > 0 && UA.Booking.FlightSearch.currentResults.Trips[0].Flights.length > 0) {
                    if ($('#hdnMockFlightRecommendation').val() != 'True') {
                        var currentTripIndex = parseInt($("#hdnCurrentTripIndex").val(), 10),
                            request = _this.getRecommendedFlightRequest(_this.currentResults.CartId, currentTripIndex);
                        $.when(request).done(function (response) {
                            if (response && response.length > 0) {
                                $.extend(_this.recommendedFlights, response);
                            }
                            //VariantTwo: FlightRecommendation
                            if (UA.Booking.FlightSearch.IsFlightRecommendationEnabledWithVTwo()) {
                                _this.UpdateFlightsForRecommendationVTwo(UA.Booking.FlightSearch.currentResults.Trips[0].Flights);
                                _this.ApplyDynamicRecommendationForVTWO();
                            }
                            //VariantOne: FlightRecommendation
                            if (_this.IsFlightRecommendationEnabledWithVOne()) {
                                _this.UpdateFlightsForRecommendationVOne(_this.filteredRecommendedFlights);
                                _this.ApplyDynamicRecommendationForVONE();
                            }
                        });
                    }
                    else {
                        var rFirstFlight = Math.floor(Math.random() * UA.Booking.FlightSearch.currentResults.Trips[0].Flights.length), rSecondFlight = 0;
                        if (UA.Booking.FlightSearch.currentResults.Trips[0].Flights.length > 1) {
                            do {
                                rSecondFlight = Math.floor(Math.random() * UA.Booking.FlightSearch.currentResults.Trips[0].Flights.length);
                            } while (rFirstFlight === rSecondFlight);
                        }
                        setTimeout(function () {
                            _this.recommendedFlights[0] = UA.Booking.FlightSearch.currentResults.Trips[0].Flights[rFirstFlight].Hash;
                            _this.recommendedFlights[1] = UA.Booking.FlightSearch.currentResults.Trips[0].Flights[rSecondFlight].Hash;
                            //VariantOne: FlightRecommendation
                            if (_this.IsFlightRecommendationEnabledWithVOne()) {
                                _this.UpdateFlightsForRecommendationVOne(_this.filteredRecommendedFlights);
                                _this.ApplyDynamicRecommendationForVONE();
                            }
                            //VariantTwo: FlightRecommendation
                            if (_this.IsFlightRecommendationEnabledWithVTwo() && UA.Booking.FlightSearch.currentResults && UA.Booking.FlightSearch.currentResults.Trips && UA.Booking.FlightSearch.currentResults.Trips.length > 0) {
                                _this.UpdateFlightsForRecommendationVTwo(UA.Booking.FlightSearch.currentResults.Trips[0].Flights);
                                _this.ApplyDynamicRecommendationForVTWO();
                            }
                        }, 2000);
                    }
                }
            },
            UpdateFlightsForRecommendationVTwo: function (flights) {
                if (this.recommendedFlights && this.recommendedFlights.length > 0 && flights) {
                    _.forEach(this.recommendedFlights, function (hash) {
                        _.forEach(flights, function (flight) {
                            if (flight && flight.Hash == hash.hash) {
                                flight.IsRecommended = true;
                            }
                        });
                    });
                    $('#hdnRecommendationCharacteristics').val(JSON.stringify(this.recommendedFlights[0].characteristics));
                }
            },

            ApplyDynamicRecommendationForVONE: function () {
                var _this = this;
                if (this.recommendedFlights && this.recommendedFlights.length > 0) {
                    _.forEach(this.recommendedFlights, function (hash) {
                        if (hash != null) {
                            var escapedHash = hash.hash.replace(/\|/g, "\\|");
                            if ($('.recommended-flight-container-v1-' + escapedHash).length > 0) {
                                _this.initFlightBlock($('.recommended-flight-container-v1-' + escapedHash).parent());
                            }
                        }
                    });
                }
            },

            ApplyDynamicRecommendationForVTWO: function () {
                var _this = this;
                if (this.recommendedFlights && this.recommendedFlights.length > 0) {
                    _.forEach(this.recommendedFlights, function (hash) {
                        if (hash != null) {
                            var escapedHash = hash.hash.replace(/\|/g, "\\|");
                            if (UA.Booking.FlightSearch.IsFlightRecommendationEnabledWithVTwo && $('.recommended-flight-container-' + escapedHash).length > 0) {
                                $('.recommended-flight-container-' + escapedHash).css("display", "block");
                                $('.recommended-flight-container-' + escapedHash).find("button.icon-tooltip").attr({ "title": hash.message, "data-tooltip-content": hash.message });
                                _this.initFlightBlock($('.recommended-flight-container-' + escapedHash).closest("li.flight-block"));
                            }
                        }
                    });
                }
            },
            UpdateFlightsForRecommendationVOne: function (flights) {
                if (!this.IsFlightRecommendationEnabledWithVOne())
                    return;
                var tmpRecommendedFlights = [];
                if (this.recommendedFlights && this.recommendedFlights.length > 0 && flights) {
                    _.forEach(this.recommendedFlights, function (hash) {
                        _.forEach(flights, function (flight) {
                            if (flight.Hash == hash.hash) {
                                var tmpFlight = {};
                                $.extend(true, tmpFlight, flight);
                                tmpFlight.IsRecommended = true;
                                tmpRecommendedFlights.push(tmpFlight);
                            }
                        });
                    });
                    $('#hdnRecommendationCharacteristics').val(JSON.stringify(this.recommendedFlights[0].characteristics));
                }
                var tmpRecommendedResults = {};
                $.extend(true, tmpRecommendedResults, this.recommendedFlightsResults);
                if (typeof tmpRecommendedResults.Trips != 'undefined')//check for undefined
                    tmpRecommendedResults.Trips[0].Flights = tmpRecommendedFlights;
                if ((typeof tmpRecommendedResults.Trips != 'undefined') && tmpRecommendedResults.Trips[0].Flights && tmpRecommendedResults.Trips[0].Flights.length > 0) {
                    $(this.getRecommendedFlightResultHTML(tmpRecommendedResults)).prependTo(this.elements.resultsContainer);
                    _.forEach(tmpRecommendedFlights, function (flight) {
                        $("#flight-recommendation-variant1 #product_" + flight.Products[flight.Products.length - 1].ProductType + "_" + _.escapeRegExp(flight.Hash)).css('background-color', 'transparent');
                        $("#flight-recommendation-variant1 #product_" + flight.Products[flight.Products.length - 1].ProductType + "_" + _.escapeRegExp(flight.Hash) + ' .pp-remaining-seats').css('padding-right', '2px');
                        $("#flight-recommendation-variant1 .flight-block-details-container").css('background-color', 'transparent');
                        $("#flight-recommendation-variant1 .fare-cabin-mixed").css('border', 'transparent');
                    }
                        )
                }
            },

            IsFlightRecommendationEnabledWithVOne: function () {
                return $('#hdnFlightRecommendationActive').val() == 'True' && $('#hdnSetVariantForRecommendation').val() == '1' && this.currentResults.SearchType && this.currentResults.SearchType.toLowerCase() != "multicity";
            },
            IsFlightRecommendationEnabledWithVTwo: function () {
                return $('#hdnFlightRecommendationActive').val() == 'True' && $('#hdnSetVariantForRecommendation').val() == '2' && this.currentResults.SearchType && this.currentResults.SearchType.toLowerCase() != "multicity";
            },
            handleFareMatrixNotStopFilterCheck: function (e) {
                var tripIndex = this.getTripIndex();
                var trip = this.currentResults.appliedSearch.Trips[tripIndex];
                if ($(e.currentTarget).is(':checked')) {
                    trip.nonStopOnly = true;
                    trip.nonStop = true;
                    trip.oneStop = false;
                    trip.twoPlusStop = false;
                }
                else {
                    trip.nonStopOnly = false;
                    trip.nonStop = true;
                    trip.oneStop = true;
                    trip.twoPlusStop = true;
                }
                this.setFilterFromTrip(this.currentResults.appliedSearch.SearchFilters, tripIndex + 1);
                this.handleFareMatrixLinkClick(e);
            },
            RefreshFareMatrixOnCabinSelection: function (e) {
                var _this = this;
                var fareMatrixCabinTypeValue = $('#fareMatrixCabinType').val();

                _this.currentResults.appliedSearch.cabinType = fareMatrixCabinTypeValue;
                _this.currentResults.appliedSearch.cabinSelection = fareMatrixCabinTypeValue == "businessFirst" ? "FIRST" : "ECONOMY";
                _this.currentResults.appliedSearch.ClassofService = "";
                this.handleFareMatrixLinkClick(e);

            },
            handleFareMatrixLinkClick: function (e) {
                if(e) e.preventDefault();
                var _this = this;
                _this.abortCurrentRequests();
                $("html, body").animate({
                    scrollTop: 0
                });
                _this.hideResultsElements();
                var fareMatrixRequest = _this.fetchFareMatrix(_this.currentResults.appliedSearch);
                this.showFareMatrixLineLoader();
                //$('.fare-matrix-spinner-container').loader();
                $.when(fareMatrixRequest).done(function (response) {
                    if (response !=null && response.data !=null && response.data.FareMatrix != null) {
                        if (response.data.Trips != null && response.data.Trips.length > 0) {
                            if (response.data.Trips[0].OriginDecoded == null && _this.currentResults.Trips && _this.currentResults.Trips[0].OriginDecoded) response.data.Trips[0].OriginDecoded = _this.currentResults.Trips[0].OriginDecoded;
                            if (response.data.Trips[0].DestinationDecoded == null && _this.currentResults.Trips && _this.currentResults.Trips[0].DestinationDecoded) response.data.Trips[0].DestinationDecoded = _this.currentResults.Trips[0].DestinationDecoded;                            
                            $.extend(_this.currentResults, response.data);
                        }
                        if (_this.currentResults.appliedSearch != null && _this.currentResults.appliedSearch.Trips != null
                            && _this.currentResults.appliedSearch.Trips.length > 0 && _this.currentResults.appliedSearch.Trips[0].NonStopMarket) {
                            response.data.NonStopMarket = _this.currentResults.appliedSearch.Trips[0].NonStopMarket;
                        }
                        else {
                            response.data.NonStopMarket = false;
                        }

                        $('#fare-matrix-section').html(_this.templates.fareMatrixCalendar(response.data));
                        _this.currentResults.appliedSearch.Matrix3day = true;
                        UA.UI.reInit($('#farematrix-options-container')); // [CSI-2361] Accessibility 2.0: on +/- 3 Day Calendar
                    }

                    if (response == null || (response != null && response.data !=null && response.data.Errors != null && response.data.Errors.length > 0)) {
                        $('#FlightResultsError, #fl-notices').show();
                        setTimeout(function () { $('#fl-notices').attr('aria-live', 'assertive'); }, 0);
                    }
                    else {
                     
                        setTimeout(function () { $('.header').attr('tabindex', '-1').focus(); }, 1000);
                        setTimeout(function () { $('#main-content').attr('tabindex', '-1').focus(); }, 2000);
                        setTimeout(function () { $('.logo').focus(); }, 3000);

                    }

                    if (_this.currentResults.appliedSearch != null && _this.currentResults.appliedSearch.Trips != null
                            && _this.currentResults.appliedSearch.Trips.length > 0
                            && (_this.currentResults.appliedSearch.Trips[0].oneStop || _this.currentResults.appliedSearch.Trips[0].twoPlusStop)) {

                        $('#farematrix-filter-nonstop').removeAttr('checked');
                    }


                }).then(function () {
                    //$('.fare-matrix-spinner-container').loader('destroy');
                    _this.hideFareMatrixClearLineLoader();
                    _this.hidePageLoader();
                });
            },
            handleFareMatrixHover: function (e) {
                e.preventDefault();
                $('.fare-matrix-hover').removeClass('partial-highlight');
                if (!(e.type == 'mouseleave' || e.type == 'focusout')) {
                    var currentRow = $(e.currentTarget).data('row');
                    var currentColumn = $(e.currentTarget).data('column');
                    if (currentRow && currentRow > 0 && currentColumn && currentColumn > 0) {
                        $('.cell-' + currentRow + '-' + currentColumn).addClass('partial-highlight');
                        for (var i = 1; i < currentRow; i++) {
                            $('.cell-' + i + '-' + currentColumn).addClass('partial-highlight');
                        }
                        for (var j = 1; j < currentColumn; j++) {
                            $('.cell-' + currentRow + '-' + j).addClass('partial-highlight');
                        }
                    }
                }
            },
            handleFareMatrixCellClick: function (e) {
                e.preventDefault();
                this.currentResults.appliedSearch.Matrix3day = false;
                this.resetTabbedFWHeader();
                this.hideResultsElements();
                var $element = $(e.currentTarget);
                var departureDate = $element.data('departure-date');
                var returnDate = $element.data('return-date');
                if (departureDate && returnDate && this.currentResults.appliedSearch.Trips.length == 2 && this.CheckDepartDate(departureDate)) {
                    this.currentResults.appliedSearch.Trips[0].DepartDate = formatDateNoWeekDay(departureDate);
                    this.currentResults.appliedSearch.Trips[1].DepartDate = formatDateNoWeekDay(returnDate);                    
                }
                if (this.CheckDepartDate(departureDate)) {
                    this.currentResults.appliedSearch.fareMatrix = true;
                    this.changeSelectDay(departureDate);
                    $('#ReturnDateForEditSearch').val(formatDateNoWeekDay(returnDate));
                    $('#flight-result-elements').show();
                    $('#fare-matrix-section').empty();
                }
                $("html, body").animate({
                    scrollTop: 0
                });
            },
            hideResultsElements: function () {
                $('#FlightResultsError, #fl-notices').hide();
                if (!showFsrTips) {
                    $('#gridNearByError').hide();
                }
                $('.fl-farewheel-disclaimer-container').hide();
                $('#flight-result-elements').hide();
                this.elements.calendarContainer.empty();
                if (showFsrTips) {
                    if (fsrTipsPhase2) {
                        this.emptyFsrTips();
                    } else {
                        this.elements.resultsHeaderSegmentNearbyCities.empty();
                        this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
                        this.elements.resultsHeaderSegmentBetterOffers.empty();
                    }
                }
                this.elements.resultsHeaderSegmentContainer.empty();
                this.elements.resultsHeaderSegmentFareDisclaimerContainer.empty();
                this.elements.resultsHeaderContainer.empty();
                this.elements.resultsContainer.empty();
                this.elements.filterSortContainer.empty();
                this.elements.resetNotificationContainer.empty();
                this.elements.noFlightMesssageSection.empty();
            },
            abortCurrentRequests: function () {
                if (this.request && this.request.readyState !== 4) {
                    this.request.abort();
                }
                if (this.flightRecommendationRequest && this.flightRecommendationRequest.readyState !== 4) {
                    this.flightRecommendationRequest.abort();
                }
                if (this.fareWheelRequest && this.fareWheelRequest.readyState !== 4) {
                    this.fareWheelRequest.abort();
                }
                if (this.awardCalendarRequest && this.awardCalendarRequest.readyState !== 4) {
                    this.awardCalendarRequest.abort();
                }
            },
            getFlightResultsHeaderHTML: function (data) {
                if (this.isSingleColumnDesignActive()) {
                    return this.templates.flightResultsHeaderV2(this.singleColumnTreatment(data));
                } else {
                    return this.templates.flightResultsHeader(data);
                }
            },
            setDefaultCabinIndex: function (data) {
                scCurrentCabinIndex = -1;
                //getting columns to consider for Single column FSR design, it should be in order of their priority of showing first on UI
                var columns = this.columnsToShow();
                if (columns && columns.length > 0 && data && data.Trips && data.Trips.length > 0) {
                    for (var i = 0; i < columns.length; i++) {
                        var productIndex = this.getColumnIndexbyProductType(columns[i], data.Trips[0].Columns);
                        var isColumnsContainsPrice = false;
                        for (var j = 0; j < data.Trips[0].Flights.length; j++) {
                            var prices = data.Trips[0].Flights[j].Products[productIndex].Prices;
                            if (prices && prices.length > 0) {
                                isColumnsContainsPrice = true;
                                break;
                            }
                        }
                        if (isColumnsContainsPrice) {
                            scCurrentCabinIndex = productIndex;
                            break;
                        }
                    }
                }
                if (scCurrentCabinIndex == -1) {
                    scCurrentCabinIndex = this.getColumnIndexbyProductType("ECONOMY", data.Trips[0].Columns);
                }
            },
            getColumnIndexbyProductType: function(productType, columns){
                for (var i = 0; i < columns.length; i++) {
                    if (columns[i].ProductType == productType) {
                        return i;
                    }
                }
                return 0;
            },
            getFlightResultsHTML: function (data) {
                if (this.isSingleColumnDesignActive()) {
                    return this.templates.flightResultsV2(this.singleColumnTreatment(data));
                } else {
                    if (this.isRemoveSelectDesignActive() && this.templates.flightResultsV4) {
                        return this.templates.flightResultsV4(data);
                    }
                    return this.templates.flightResults(data);
                }
            },
            getRecommendedFlightResultHTML: function(data){
                if (this.isSingleColumnDesignActive()) {
                    return this.templates.recommendedFlightResultsV2(this.singleColumnTreatment(data));
                } else {
                    if (this.isRemoveSelectDesignActive() && this.templates.recommendedFlightResultsV4) {
                        return this.templates.recommendedFlightResultsV4(data);
                    }
                    return this.templates.recommendedFlightResults(data);
                }
            },
            getFlightDetailsHTML: function (data) {
                if (this.isSingleColumnDesignActive()) {
                    var dataSet = {};
                    $.extend(true, dataSet, data);
                    return this.templates.tripDetails(this.flightSingleColumnTreatment(dataSet));
                } else {
                    return this.templates.tripDetails(data);
                }
            },
            singleColumnTreatment: function (dataSet) {
                var data = {}, _this = this;
                $.extend(true, data, dataSet);
                if (data != null && data.Trips != null && data.Trips.length > 0
                    && data.Trips[0].Columns != null && data.Trips[0].Columns.length > 0) {
                    if (scCurrentCabinIndex == -1 || typeof data.Trips[0].Columns[scCurrentCabinIndex] == 'undefined') {
                        this.setDefaultCabinIndex(data);
                    }
                    var t = data.Trips[0].Columns[scCurrentCabinIndex];
                    data.Trips[0].ShowPreviousColumnArrow = scCurrentCabinIndex > 0;
                    if (data.Trips[0].ShowPreviousColumnArrow)
                    {
                        var PrevColumnInformation = data.Trips[0].Columns[scCurrentCabinIndex - 1];
                        if (PrevColumnInformation != null && PrevColumnInformation.ColumnName != null && PrevColumnInformation.Description != null)
                        {
                            data.Trips[0].ShowPreviousColumnDescp = PrevColumnInformation.ColumnName + PrevColumnInformation.Description;
                        }
                    }
                    data.Trips[0].ShowNextColumnArrow = (scCurrentCabinIndex + 1) < data.Trips[0].Columns.length;
                    if (data.Trips[0].ShowNextColumnArrow)
                    {
                        var NextColumnInformation = data.Trips[0].Columns[scCurrentCabinIndex + 1];
                        if (NextColumnInformation != null && NextColumnInformation.ColumnName != null && NextColumnInformation.Description != null)
                            {
                            data.Trips[0].ShowNextCoulmnDescp = NextColumnInformation.ColumnName + NextColumnInformation.Description;
                            }
                    }

                    data.Trips[0].Columns = [];
                    data.Trips[0].Columns[0] = t;
                    data.SearchFilters.RealFareFamily = t.FareFamily;
                    if (UA.Booking.FlightSearch.currentResults.appliedSearch.SearchFilters != undefined) {
                        UA.Booking.FlightSearch.currentResults.appliedSearch.SearchFilters.RealFareFamily = t.FareFamily;
                        UA.Booking.FlightSearch.currentResults.appliedSearch.SearchFilters.SortFareFamily = t.FareFamily;
                    }
                    if (data.Trips[0].Flights != null && data.Trips[0].Flights.length > 0) {
                        _.forEach(data.Trips[0].Flights, function (flight) {
                            _this.flightSingleColumnTreatment(flight);
                        });
                    }
                }

                return data;
            },
            flightSingleColumnTreatment: function (flight) {
                var defaultProduct = flight.Products[scCurrentCabinIndex];
                flight.Products = [];
                flight.Products[0] = defaultProduct;
                if (flight.Connections != null && flight.Connections.length > 0) {
                    _.forEach(flight.Connections, function (connection) {
                        var defaultConnectionProduct = connection.Products[scCurrentCabinIndex];
                        connection.Products = [];
                        connection.Products[0] = defaultConnectionProduct;
                    });
                }
                return flight;
            },
            handlePreviousColumnClick: function (e) {
                var _this = this;
                e.preventDefault();
                scCurrentCabinIndex--;
                try {
                    _this.updateSingleColumn();
                }
                catch (ex) {
                    scCurrentCabinIndex++;
                }
            },
            handleNextColumnClick: function (e){
                var _this = this;
                e.preventDefault();
                scCurrentCabinIndex++;
                try {
                    _this.updateSingleColumn();
                }
                catch (ex) {
                    scCurrentCabinIndex--;
                }
            },
            updateSingleColumn: function () {
                var _this = this;
                scColumnClick = true;
                scOptVal = _this.currentResults.appliedSearch.SortType;
                _this.loadFilterResults(_this.currentResults.appliedSearch, true, true, null, true);
            },

            afterLoadFilter: function () {
                if (scColumnClick === true) {
                    var _this = this;
                    var selectedOptVal = scOptVal;
                    if (selectedOptVal === "price_low" || selectedOptVal === "price_high") {
                        setTimeout(function () {
                            var sorter = $(".sorter.sorter-price-" + _this.currentResults.Trips[0].Columns[scCurrentCabinIndex].FareFamily);
                            var removedClass;
                            var addedClass;
                            if (selectedOptVal === "price_low") {
                                removedClass = "ascending";
                                addedClass = "descending";
                            } else {
                                removedClass = "descending";
                                addedClass = "ascending";
                            }
                            sorter.removeClass(removedClass).addClass(addedClass).addClass("active").trigger("click");
                        }, 10);
                    }
                }
                scColumnClick = false;
                scOptVal = null;

                if (filterActionClick === true) {
                    filterActionClick = false;
                    $("#fl-results").attr("tabIndex", -1).focus();
                    $("html, body").prop("scrollTop", 0);
                }
            },
            isUpSellActive: function () {
                try {
                    if ($('#hdnIsSingleColumnEnabled').val() == 'True' && ($('#hdnMaxymiserIsUpSellEnabled').val() == 'True' || UA.Utilities.safeLocalStorage.getItem('IsUpsell'))) {
                        return true;
                    }
                    return false;
                } catch (ex) {
                    return false;
                }
            },
            isSingleColumnDesignActive: function () {
                try{
                    if (this.isSingleColumnDesignEnabled() && UA.Utilities.safeLocalStorage.getItem('IsSingleColumnFSR')) {
                        return true;
                    }
                    return false;
                } catch (ex) {
                    return false;
                }
            },
            isSingleColumnDesignEnabled: function () {
                try {
                    if ($('#hdnIsSingleColumnEnabled').val() == 'True') {
                        return true;
                    }
                    return false;
                } catch (ex) {
                    return false;
                }
            },

            isRelocateRtiDesignActive: function () {
                try {
                    return (this.isRelocateRtiDesignEnabled()
                        && ($("#hdnMaxymiserIsRelocateRtiEnabled").val() === "true"
                        || UA.Utilities.safeLocalStorage.getItem("IsRelocateRti") === "true"));
                } catch (ex) {
                    return false;
                }
            },

            isRelocateRtiDesignEnabled: function () {
                try {
                    return ($("#hdnIsRelocateRtiEnabled").val() === "True");
                } catch (ex) {
                    return false;
                }
            },
            isRemoveSelectDesignActive: function () {
                try {
                    return (this.isRemoveSelectDesignEnabled()
                        && ($("#hdnMaxymiserIsRemoveSelectEnabled").val() === "true"
                        || UA.Utilities.safeLocalStorage.getItem("IsRemoveSelect") === "true"));
                } catch (ex) {
                    return false;
                }
            },
            isRemoveSelectDesignEnabled: function () {
                try {
                    return ($("#hdnIsRemoveSelectEnabled").val() === "True");
                } catch (ex) {
                    return false;
                }
            },

            removeLmxProductsforSingleColumnDesign: function (resp) {
                var _this = this, columnsIndexToRemove = [];

                try {

                    if (this.isSingleColumnDesignActive() && resp != null && resp.data != null) {

                        _.forEach(resp.data, function (responseFlight, key) {

                            try {
                                if (responseFlight != null && responseFlight.Products != null && responseFlight.Products.length > 0) {

                                    var columnsToShow = _this.columnsToShow();
                                    for (var i = 0; i < responseFlight.Products.length; i++) {
                                        if (columnsToShow.indexOf(responseFlight.Products[i].ProductType) == -1) {
                                            columnsIndexToRemove.push(i);
                                        }
                                    }

                                    if (columnsIndexToRemove != null && columnsIndexToRemove.length > 0) {
                                        for (var n = columnsIndexToRemove.length - 1; n >= 0; n--) {
                                            responseFlight.Products.splice(columnsIndexToRemove[n], 1);
                                        }
                                    }

                                }
                            }
                            catch (err)
                            { }
                        });
                    }

                } catch (ex) { }
            },
            removeCabinsforSingleColumnDesign: function (resp) {
                var _this = this, columnsIndexToRemove = [];
                try {
                    if (this.isSingleColumnDesignActive() && resp != null && resp.data != null && resp.data.Trips != null) {
                        var columnsToShow = _this.columnsToShow();
                        for (var i = 0; i < resp.data.Trips[0].Columns.length; i++) {
                            if (columnsToShow.indexOf(resp.data.Trips[0].Columns[i].ProductType) == -1) {
                                columnsIndexToRemove.push(i);
                            }
                        }
                        if (columnsIndexToRemove != null && columnsIndexToRemove.length > 0 && resp.data.Trips[0].Flights.length > 0) {
                            for (var n = columnsIndexToRemove.length-1; n >= 0; n--) {
                                resp.data.Trips[0].Columns.splice(columnsIndexToRemove[n], 1);
                                for (var j = resp.data.Trips[0].Flights.length-1; j >=0; j--) {
                                    resp.data.Trips[0].Flights[j].Products.splice(columnsIndexToRemove[n], 1);
                                    if(resp.data.Trips[0].Flights[j].Connections != null && resp.data.Trips[0].Flights[j].Connections.length > 0){
                                        for (var k = resp.data.Trips[0].Flights[j].Connections.length - 1; k >= 0;k--){
                                            resp.data.Trips[0].Flights[j].Connections[k].Products.splice(columnsIndexToRemove[n], 1);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (ex) {}
            },
            columnsToShow: function () {
                //it should return columns in sequence of their priority of showing first on FSR page.
                return ["ECONOMY", "ECONOMY-FLEXIBLE", "ECO-BASIC"];
            },
            columnsWithUpsell: function() {
                return ["ECONOMY"];
            },
            handleNearbyErrorSearchNow: function (e) {
                var $element = $(e.currentTarget);
                var cboMiles = $element.data("cbo-miles");
                var cboMiles2 = $element.data("cbo-miles2");
                var formChildren = $("#flightSearch");
                if (cboMiles === "") {
                    ;
                } else {
                    formChildren.append("<input type='hidden' name='CboMiles' id='CboMile' value='" + cboMiles + "' />");
                }
                if (cboMiles2 === "") {
                    ;
                } else {
                    formChildren.append("<input type='hidden' name='CboMiles2' id='CboMile2' value='" + cboMiles2 + "' />");
                }

                if (fsrTipsPhase2) {
                    var $parentElement = $element.parent();
                    var moduleInfo = "{\"action\": \"No results clicked\", \"desc\": \"No flights match your search criteria\"}";
                    $parentElement.removeAttr("data-module-info").attr("data-module-info", moduleInfo);
                    $parentElement.data("module-info", JSON.parse(moduleInfo));
                    UA.UI.processModule($parentElement);
                }

                $('#flightSearch').submit();
            },
            handleNearbySearchNow: function (e) {
                var $element = $(e.currentTarget);
                var cboMiles = $element.data("cbo-miles");
                var cboMiles2 = $element.data("cbo-miles2");
                var formChildren = $("#flightSearch");
                if (cboMiles === "") {
                    ;
                } else {
                    formChildren.append("<input type='hidden' name='CboMiles' id='CboMile' value='" + cboMiles + "' />");
                }
                if (cboMiles2 === "") {
                    ;
                } else {
                    formChildren.append("<input type='hidden' name='CboMiles2' id='CboMile2' value='" + cboMiles2 + "' />");
                }

                if (fsrTipsPhase2) {
                    var $parentElement = $element.parent();
                    var moduleInfo = "{\"action\": \"Nearby airport clicked\", \"desc\": \"Nearby airport\"}";
                    $parentElement.removeAttr("data-module-info").attr("data-module-info", moduleInfo);
                    $parentElement.data("module-info", JSON.parse(moduleInfo));
                    UA.UI.processModule($parentElement);
                }

                $('#flightSearch').submit();
            },
            handleNonstopMessageSearchNow: function (e) {
                var $element = $(e.currentTarget);
                var selectDay = $element.data("select-day");
                var $correspondingFareWheelItem;
                if ($("#tabbed-fare-wheel-section").length > 0 && ($("#tabbed-fare-wheel-section").css("display") === "block" || $("#tabbed-fare-wheel-section").css("display") === "flex")) {
                    $correspondingFareWheelItem = $(".tabbedFW-tab-link[data-select-day='" + selectDay + "']");
                } else {
                    $correspondingFareWheelItem = $(".fare-wheel-item[data-select-day='" + selectDay + "']");
                }
                if ($correspondingFareWheelItem.length > 0) {
                    if (fsrTipsPhase2) {
                        var $parentElement = $element.parent();
                        var moduleInfo = "{\"action\": \"Suggest non stop clicked\", \"desc\": \"Nonstop options\"}";
                        $parentElement.removeAttr("data-module-info").attr("data-module-info", moduleInfo);
                        $parentElement.data("module-info", JSON.parse(moduleInfo));
                        UA.UI.processModule($parentElement);
                    }

                    $correspondingFareWheelItem.click();
                }
            },
            handleBetterOffersSelect: function (e) {
                var $element = $(e.currentTarget);
                var selectId = $element.data("select-id");;
                var $correspondingFareWheelItem;
                if ($("#tabbed-fare-wheel-section").length > 0 && ($("#tabbed-fare-wheel-section").css("display") === "block" || $("#tabbed-fare-wheel-section").css("display") === "flex")) {
                    $correspondingFareWheelItem = $(".tabbedFW-tab-link[data-select-id='" + selectId + "']");
                } else {
                    $correspondingFareWheelItem = $(".fare-wheel-item[data-select-id='" + selectId + "']");
                }

                if (fsrTipsPhase2) {
                    var $parentElement = $element.parent();
                    var moduleInfo = "{\"action\": \"Suggest date cheaper fare clicked\", \"desc\": \"Cheaper fare available on other day\"}";
                    $parentElement.removeAttr("data-module-info").attr("data-module-info", moduleInfo);
                    $parentElement.data("module-info", JSON.parse(moduleInfo));
                    UA.UI.processModule($parentElement);
                }

                if ($correspondingFareWheelItem.length > 0) {
                    $correspondingFareWheelItem.click();
                } else {
                    this.handleFareWheelChange(e);
                }
            },
            handleSortDropdownChangeEvent: function (e) {
                var sortType = UA.Common.SortDropdown.getValue();
                var sorter;
                var data = {fareType: this.currentResults.appliedSearch.SearchFilters.FareFamily};

                this.currentResults.appliedSearch.SortType = sortType;
                $('#SortType').val(this.currentResults.appliedSearch.SortType);
                sorter = this.setSorterState(sortType, data);

                $("#fl-results-pager-container").trigger('search.sort.changed');
            },
            handleNearbyCitiesSelect: function (e) {
                var $element = $(e.currentTarget);
                var selectOrigin = $element.data("select-origin");
                var selectDestination = $element.data("select-destination");
                $("#flightSearch #Origin").val(selectOrigin);
                $("#flightSearch #Destination").val(selectDestination);
                $("#flightSearch #DepartDate").val(this.currentResults.appliedSearch.Trips[0].DepartDate);
                if (this.currentResults.appliedSearch.realSearchTypeMain === "roundTrip") {
                    $("#flightSearch #ReturnDateForEditSearch").val(this.currentResults.appliedSearch.Trips[1].DepartDate);
                } else if (this.currentResults.appliedSearch.realSearchTypeMain === "oneWay") {
                    $("#flightSearch #ReturnDateForEditSearch").val("");
                }

                if (fsrTipsPhase2) {
                    var $parentElement = $element.parent();
                    var moduleInfo = "{\"action\": \"Nearby airport clicked\", \"desc\": \"Nearby airport\"}";
                    $parentElement.removeAttr("data-module-info").attr("data-module-info", moduleInfo);
                    $parentElement.data("module-info", JSON.parse(moduleInfo));
                    UA.UI.processModule($parentElement);
                }

                $(".edit-search-submit").trigger("click");
            },
            handleFlightDetailClick: function (e) {
                e.preventDefault();
                var _this = this;
                var detailContainer = $(e.currentTarget).closest('.flight-block').find(".flt-details-container"),
                    target = $(e.currentTarget),
                    lmxRequest,
                    detailsRendered = detailContainer.data('isRendered'),
                    lmxRendered = detailContainer.data('isLmxRendered');

                if (!detailsRendered || !lmxRendered) {
                    if (detailsRendered && lmxRendered) {
                        return;
                    }

                    if (!target.data('expanded')) {
                        if (detailContainer.data('loaded')) {
                            detailContainer.show();
                        }
                        else {
                            var data = _this.getFlightByHash(target.data('flight-hash'));
                            data.ShowAvailableOnlyUpgrades = _this.currentResults.appliedSearch.ShowAvailableOnlyUpgrades;
                            _this.renderFlightDetailsVersion3(detailContainer, data);

                            if (!_this.currentResults.IsAward) {
                                lmxRequest = _this.loadLmxData(target.data('flight-hash'));

                                $.when(lmxRequest)
                                    .done(function () {
                                        _this.renderFlightDetailsVersion3(detailContainer, data);
                                        UA.UI.Tooltip.init(null, null, null, detailContainer);
                                        detailContainer.data('isLmxRendered', true);
                                    })
                                    .fail(function () {
                                        detailContainer.data('isLmxRendered', false);
                                    });
                            }
                        }
                        target.find('.flt-details-arrow').removeClass('point-down').addClass('point-up');
                        target.data('expanded', true);
                    }
                    else {
                        detailContainer.hide();
                        target.find('.flt-details-arrow').removeClass('point-up').addClass('point-down');
                        target.data('expanded', false);
                    }
                }

                UA.UI.processModule(detailContainer);
            },
            handleFlightSeatDetailClick: function (e) {
                var seatDetailsArrow = $(e.currentTarget).closest('li').find(".flt-seatdetails-click");
                var seatDetailContainer = $(e.currentTarget).closest('li').find(".flt-seatdetails-container");
                //1539144--Added code changes for  calling 3.0 read only seatmap  by replacing old seat map in pluspoints search
                var target = $(e.currentTarget),
                params = target.data('seatSelect');
                var isReactViewOnlySeatMapEnabled = $('#hdnReactViewOnlySeatMap').val().toLowerCase() == "true";
                if (isReactViewOnlySeatMapEnabled && params && params.Flights) {
                    if (seatDetailContainer!=null && seatDetailContainer.length > 0) {
                        var iframe = $(seatDetailContainer[0]).find('iframe').length;
                        if (iframe === 0) {
                            $(seatDetailContainer[0]).parent().loader();
                            $(seatDetailContainer[0]).html(this.renderSeatMapIframe(params));
                        }
                    }
                } else {
                    if (!seatDetailContainer.data('ua-seatmap')) {
                        seatDetailContainer.seatmap({
                            data: params,
                            segments: {
                                enabled: true
                            },
                            seatGrid: {
                                url: this.elements.container.data('seatmapurl')
                            },
                            planeDetails: {
                                enabled: true
                            },
                            afterDisplay: $.proxy(this.initStickyElements, this)
                        });
                    }
                }
                if (!target.data('expanded')) {
                    if (seatDetailContainer.data('loaded')) {
                        seatDetailContainer.show();
                    }
                    else {
                        seatDetailContainer.css({ 'min-height': '100px', 'height': 'auto' });
                        params.Version = 3;
                        this.renderSeatDetailsVersion3(seatDetailContainer, params);
                    }
                    seatDetailContainer.find("segment-list").hide();
                    seatDetailsArrow.find('.flt-details-arrow').removeClass('point-down').addClass('point-up');
                    seatDetailContainer.css({ 'visibility': 'visible' });
                    seatDetailsArrow.data('expanded', true);
                }
                else {
                    seatDetailContainer.hide();
                    seatDetailsArrow.find('.flt-details-arrow').removeClass('point-up').addClass('point-down');
                    seatDetailsArrow.data('expanded', false);
                }
            },

            clearFSRResults: function () {
                $('#FlightResultsError, #fl-notices, #fl-notices2').hide();
                this.elements.calendarContainer.empty();
                    if (showFsrTips) {
                        if (fsrTipsPhase2) {
                            this.emptyFsrTips();
                        } else {
                            this.elements.resultsHeaderSegmentNearbyCities.empty();
                            this.elements.resultsHeaderSegmentNonstopSuggestion.empty();
                            this.elements.resultsHeaderSegmentBetterOffers.empty();
                        }
                    }
                    this.elements.resultsHeaderSegmentContainer.empty();
                    this.elements.resultsHeaderSegmentFareDisclaimerContainer.empty();
                    this.elements.resultsHeaderContainer.empty();
                    this.elements.resultsContainer.empty();
                    this.elements.filterSortContainer.empty();
                    this.elements.newSearchContainer.empty();
                    this.elements.resultsFooter.empty();
                    this.elements.selectedFlightContainer.empty();
                    this.elements.resetNotificationContainer.empty();
                    this.resetTabbedFWHeader();
                    $('.cart-container').empty();
            },

            getFSRVersion: function () {
                if ($('#fsr-version')[0]) {
                    return $('#fsr-version').val();
                }
                return 0;
            },
            resetSettings: function () {
                this.currentResults.appliedSearch.ShowAvailableOnlyUpgrades = false;
            },
            displayWarningMessages: function (resp) {
                if (resp && resp.data && resp.data.IsValidPromotion &&
                    !resp.data.IsPassPlusSecure && !resp.data.IsPassPlusFlex) {
                    $("#ecd-notices-rev").show();
                } else {
                    $("#ecd-notices-rev").hide();
                }
            }

        };
    }());


    $(document).ready(function () {
        UA.Booking.FlightSearch.init();

        

    });

    // WI 255288 -	D2 Booking: PRODUCTION - Flight Search Results (FSR) not loading on iPad and iPhone
    //				Safari on iOS devices was attempting to load the cached version of the FSR. However, the cache
    //				wasn't reloading the results list. The code below allows for the pageshow event to reload
    //				the page if the page is cached.
    $(window).on("pageshow", function (event) {
        if (event.originalEvent.persisted) {
            window.location.reload();
        }
    });

    $(window).on("message", function (event) {
        if (event.originalEvent
            && event.originalEvent.data
            && event.originalEvent.data.indexOf
            && event.originalEvent.data.indexOf('iframe-seatmap-details-') !== -1) {
            var iframeData = event.originalEvent.data;
            if (iframeData.indexOf('EventListener') !== -1) {  // event for sending data to seatmap inside iframe
                var iframeElementId = iframeData.replace('EventListener', '');
                var iframeElement = document.getElementById(iframeElementId);
                var message = {
                    segments: $(iframeElement).data('segments'),
                    channelId: 101,
                    isSmall: true,
                    isFSR: true
                };
                iframeElement.contentWindow.postMessage(message, '*');
            } else if (iframeData.indexOf('Measures') !== -1) { // event for setting seatmap iframe size
                var iframeMeasuresData = iframeData.split('Measures');
                if (iframeMeasuresData.length > 1) {
                    var iframeElementId = iframeMeasuresData[0];
                    var measures = iframeMeasuresData[1].split('-');
                    if (measures.length > 1) {
                        $('#' + iframeElementId).css('height', measures[1] + 'px');
                    }
                }
            }
        }
    });
}(jQuery));

$.fn.focusWithoutScrolling = function () {
    var x = window.scrollX, y = window.scrollY;
    this.attr("tabIndex", -1).focus();
    window.scrollTo(x, y);
    return this;
};
;
/*global jQuery, UA*/

(function ($) {
    'use strict';
    UA.Utilities.namespace('UA.Booking.EditSearch');

    UA.Booking.EditSearch = (function () {
        return {
            elements:{},
            redirectToAdvansearchOnSubmit: false,
            initialized: false,
            init: function () {
                this.elements = {
                    container: $('.new-edit-search'),
                    flexDateSection: $('#flexDateSection'),
                    specificDateSection: $('#specificDateSection'),
                    flexDate: $('#flexDate'),
                    awardTravel: $('#AwardTravel'),
                    flightForm: $('#flightSearch'),
                    returnDate: $('#returnDateTimeDiv'),
                    tripLength: $('#tripLengthSection')
                };
                this.bindEvents();
                this.setFlexDate();
                this.setAwardTravel();
                this.elements.container.find('input[name="SearchTypeMain"]:checked').change();
                this.initAirportAutocomplete();
                this.initTravelersStepper();
                if (($('input[name="CorporateBooking"]').val() === 'True')) {
                    this.handleCorporateBooking();
                }
            },
            handleSearchTypeChange: function (e) {
                if ($(e.currentTarget).val().toLowerCase() === 'oneway') {
                    this.setOneWay();
                } else {
                    this.setRoundTrip();
                }
            },
            setRoundTrip: function () {
                this.elements.returnDate.show();
                this.elements.tripLength.show();
            },
            setOneWay: function () {
                if ($('#editFlightSearch').val() == "True") {
                    this.elements.returnDate.show();
                    this.elements.tripLength.show();
                }
                else
                {
                    this.elements.returnDate.hide();
                    this.elements.tripLength.hide();
                }
            },
            setFlexDate: function () {
                if (this.elements.flexDate.is(':checked')) {
                    this.elements.flexDateSection.show();
                    this.elements.specificDateSection.hide();
                    if (($('input[name="CorporateBooking"]').val() === 'True')) {
                        this.handleCorporateBooking();
                    }
                }
                else {
                    this.elements.flexDateSection.hide();
                    this.elements.specificDateSection.show();
                }
            },
            setAwardTravel: function () {
                if (this.elements.awardTravel.is(':checked')) {
                    $('#uniform-cabinType, #cabinType').hide();
                    $('#uniform-awardCabinType, #awardCabinType').show();
                }
                else {
                    $('#uniform-cabinType, #cabinType').show();
                    $('#uniform-awardCabinType, #awardCabinType').hide();
                }
            },

            resetRadioButtons: function () {
                $('#UpgradeType').val('');
                var selectedElement = document.activeElement;
                var selected = $('#' +selectedElement.id).val();
                if (selected && selected.length > 0 && (selected == 'POINTS' || selected == 'MUA'))
                    $('#UpgradeType').val(selected);
            },
            initAirportAutocomplete: function () {
                UA.UI.Autocomplete.applyAirportAutocomplete($('input[data-autocomplete-airport]', this.elements.container));
            },
            initTravelersStepper: function () {

                var travelersStepper = $('#travelers-selector');
                if (!travelersStepper.data('ua-travelerStepper')) {
                    var maxTravelers = $('#hdnMaxAllowedTravelersCount').val();
                    $('#travelers-selector').travelerStepper({ totalMaxValue: maxTravelers == null || maxTravelers == 'undefined' ? 7 : maxTravelers - 1 });
                }

            },
            handleCorporateBooking: function () {
                $('#AwardTravel').attr("disabled", true);
                $('#uniform-AwardTravel').addClass('disabled');
                $('#uniform-AwardTravel_True :input[type=radio]').attr("disabled", true);
                if ($('#editFlightSearch').val() == "True") {
                    $('#AwardTravel_True').attr('disabled', true);
                }
                $("#NumOfAdults").val("1");
                $("#NumOfChildren01").val("0");
                $("#NumOfChildren02").val("0");
                $("#NumOfChildren03").val("0");
                $("#NumOfChildren04").val("0");
                $("#NumOfLapInfants").val("0");
                $("#NumOfInfants").val("0");
                $("#NumOfSeniors").val("0");
                $('#travelers-selector').travelerStepper('setText');
                if ($('#travelers-selector').data('ua-dropdown')) {
                    $('#travelers-selector').dropdown('disable');
                    $('#calendar-travelers-selector').dropdown('disable');
                }
                //if flex calendar
                if ($('#calendar-travelers-selector').data('ua-dropdown')) {
                    $('#calendar-travelers-selector').dropdown('disable');
                }
            },
            bindEvents: function () {
                var self = this;
                $('#IsEditSearch').val(true);
                $('#EditSearchCartId').val($('#CartId').val());
                this.elements.container.off('change', 'input[name="SearchTypeMain"]').on('change', 'input[name="SearchTypeMain"]', $.proxy(this.handleSearchTypeChange, this));

                this.elements.flexDate.off('change').on('change', $.proxy(this.setFlexDate, this));

                this.elements.awardTravel.off('change').on('change', $.proxy(this.setAwardTravel, this));

                //airport lookup events
                $('.airport-autocomplete').off('click', '.full-airport-list').on('click', '.full-airport-list', function (e) {
                    e.preventDefault();
                    UA.Common.AirportLookup.init({
                        target: self.currentAutocompleteField
                    });
                });

                $(document).off('click', '.tt-suggestion a').on('click', '.tt-suggestion a', function (e) {
                    e.preventDefault();
                });

                if ($("#editFlightSearchVersion").length > 0 && $("#editFlightSearchVersion").val() === "1") {
                    $('.add-destination').off('click').on('click', $.proxy(this.addDestinationClick1, this));
                    $('.remove-destination-existing').off("click").on('click', $.proxy(this.removeDestinationExistingClick, this));
                    $('.remove-destination-new').off("click").on('click', $.proxy(this.removeDestinationClick, this));
                }
                else {
                    $('.add-destination').off('click').on('click', $.proxy(this.addDestinationClick0, this));
                }
                $('.edit-search-submit').off('click').on('click', $.proxy(this.updateSearchClick, this));
                $('.SearchByButtons').off('click').on('click', $.proxy(this.resetRadioButtons, this));
                this.initialized = true;
            },

            beforeSubmitEditSearch: function () {
                if ($('#editFlightSearch').val() == "True") {
                    if ($('#SearchTypeMain').val() == "oneWay" || $('#SearchTypeMain').val() == "roundTrip") {
                        if ($("#editFlightSearchVersion").length > 0 && $("#editFlightSearchVersion").val() === "1") {
                            if ($("#ReturnDateForEditSearch").length > 0 && $("#ReturnDateForEditSearch").val() != '') {
                                $('#RealSearchTypeMain').val("roundTrip");
                                $('#RealTripTypes').val("rt");
                                $('#ReturnDate').val($("#ReturnDateForEditSearch").val());
                            }
                            else {
                                $('#RealSearchTypeMain').val("oneWay");
                                $('#RealTripTypes').val("ow");
                            }
                        }
                    }
                    else {
                        if ($("*[id^='tripdest'][style^='display: block']").length === 1) {
                            $('#RealSearchTypeMain').val("oneWay");
                            $('#RealTripTypes').val('ow');
                        }
                        else if ($("*[id^='tripdest'][style^='display: block']").length > 1) {
                            $('#RealSearchTypeMain').val('multiCity');
                            $('#RealTripTypes').val('mc');
                        }
                    }
                }
            },

            updateSearchClick: function (e) {
                if ($('#editFlightSearch').val() == "True") {
                    $('.materialDesign').each(function (i, obj) {
                        $('.error-group-label').attr('aria-hidden', 'false');
                        $(this).find("span:last").css({ 'display': 'block', 'color': '#CD202c' });
                        var $width = $(this).width(); //get the width
                        $(this).find("span:last").width($width);
                    });
                    if ($('#SearchTypeMain').val() == "oneWay" || $('#SearchTypeMain').val() == "roundTrip") {
                        if ($("#editFlightSearchVersion").length > 0 && $("#editFlightSearchVersion").val() === "1") {
                            if ($("#ReturnDateForEditSearch").length > 0 && $("#ReturnDateForEditSearch").val() != '') {
                                $('#RealSearchTypeMain').val("roundTrip");
                                $('#RealTripTypes').val("rt");
                            }
                            else {
                                $('#RealSearchTypeMain').val("oneWay");
                                $('#RealTripTypes').val("ow");
                            }
                        }
                        else {
                            if ($("#ReturnDateForEditSearch").length > 0 && $("#ReturnDateForEditSearch").val() != '') {
                                $('#SearchTypeMain').val("roundTrip");
                                $('#TripTypes').val("rt");
                                $('#RealSearchTypeMain').val("roundTrip");
                                $('#RealTripTypes').val("rt");
                                $('#ReturnDate').val($("#ReturnDateForEditSearch").val());
                            }
                            else {
                                $('#SearchTypeMain').val("oneWay");
                                $('#TripTypes').val("ow");
                                $('#RealSearchTypeMain').val("oneWay");
                                $('#RealTripTypes').val("ow");
                            }
                        }
                    }
                    else {
                        UA.Booking.EditSearch.hideEmptyLineOfFlights();
                        if ($("*[id^='tripdest'][style^='display: block']").length === 1) {
                            $('#RealSearchTypeMain').val("oneWay");
                            $('#RealTripTypes').val('ow');
                        }
                        else if ($("*[id^='tripdest'][style^='display: block']").length > 1) {
                            $('#RealSearchTypeMain').val('multiCity');
                            $('#RealTripTypes').val('mc');
                        }
                    }
                }
                $('#RealUpgradePath').val("true");

                if (typeof UA.Booking.BillingInfo !== 'undefined') {
                    UA.Booking.BillingInfo.disableAbandonDialog();
                }
                UA.Booking.EditSearch.ResetFlightResultSessionItem();
            },

            hideEmptyLineOfFlights: function () {
                var listOfTrips = $("*[id^='tripdest'][style^='display: block']");
                var lenListOfTrips = listOfTrips.length;
                if (lenListOfTrips > 1) {
                    for (var i = lenListOfTrips - 1; i >= 0; i--) {
                        var destNum = parseInt($(listOfTrips[i]).attr('id').substr($(listOfTrips[i]).attr('id').length - 1), 10);
                        if ($("[name=TripsForEditSearch\\[" + (destNum - 1) + "\\]\\.DepartDate]", listOfTrips[i]).val() == '' &&
                            $("[name=TripsForEditSearch\\[" + (destNum - 1) + "\\]\\.Origin]", listOfTrips[i]).typeahead("val") == '' &&
                            $("[name=TripsForEditSearch\\[" + (destNum - 1) + "\\]\\.Destination]", listOfTrips[i]).typeahead("val") == '') {
                            if ($("*[id^='tripdest'][style^='display: block']").length > 1) {
                                UA.Booking.EditSearch.removeDestinationFunc(destNum);
                                UA.Booking.EditSearch.clearLof(destNum);
                            }   
                        }
                    }
                }
            },

            addDestinationClick0: function (e) {
                var destNum = parseInt($(e.currentTarget).attr('href').substr($(e.currentTarget).attr('href').length - 1), 10)

                $('#dest' + destNum).css('display', 'none');
                $('#tripdest' + destNum).css('display', 'block');
                $("#TripsForEditSearch_" + (destNum - 1) + "__Ignored").val("false");
                if (destNum < 6) {
                    $('#dest' + (destNum + 1)).css('display', 'block');
                }

                e.preventDefault();
            },

            addDestinationClick1: function (e) {
                var destNum = parseInt($(e.currentTarget).attr('href').substr($(e.currentTarget).attr('href').length - 1), 10)
                UA.Booking.EditSearch.addDestinationFunc(destNum);
                UA.Booking.EditSearch.clearLof(destNum);
                setTimeout(function () { $('#tripdest' + destNum + ' .editSearch-datepicker').focus() }, 50);

                e.preventDefault();
            },

            addDestinationFunc: function (destNum) {
                var minIndexVal = 7;
                var minIndex = 6;
                var j;
                for (j = 1; j <= 6; ++j) {
                    if (j === destNum) {
                        ;
                    }
                    else 
                    {
                        if ($('#tripdest' + j).length > 0 && $('#tripdest' + j).css('display') === 'none') {
                            var jVal = parseInt($("#TripsForEditSearch_" + (j - 1) + "__Sequence").val(), 10);
                            if (jVal < minIndexVal) {
                                minIndexVal = jVal;
                                minIndex = j;
                            }
                        }
                    }
                }

                $('#dest' + destNum).css('display', 'none');
                //$('#tripdest' + destNum).css('display', 'block');
                $('#tripdest' + destNum).find(".ifl").css("opacity", "1.0");
                $("#TripsForEditSearch_" + (destNum - 1) + "__Ignored").val("false").change();
                if (minIndexVal < 7) {
                    $('#dest' + minIndex).css('display', 'block');
                }

                var total = 0;
                var k;
                for (k = 1; k <= 6; ++k) {
                    if ($('#tripdest' + k).length > 0 && $('#tripdest' + k).css('display') === 'block') {
                        total++;
                    }
                    else {
                        ;
                    }
                }
                if (total > 0) {
                    for (k = 1; k <= 6; ++k) {
                        if ($('#tripdest' + k).length > 0 && $('#tripdest' + k).css('display') === 'block') {
                            $('#resultdest' + k).prop("disabled", false);
                        }
                        else {
                            ;
                        }
                    }
                }

                var renewElem = $('#tripdest' + destNum).detach();
                var maxIndexVal = 0;
                var maxIndex = 0;
                var maxBlock;
                var l;
                for (l = 1; l <= 6; ++l) {
                    if ($('#tripdest' + l).length > 0 && $('#tripdest' + l).css('display') === 'block') {
                        var lVal = parseInt($("#TripsForEditSearch_" + (l - 1) + "__Sequence").val(), 10);
                        if (lVal > maxIndexVal) {
                            maxIndexVal = lVal;
                            maxIndex = l;
                        }
                    }
                    else {
                        ;
                    }
                }

                if (maxIndex > 0) {
                    var beforeElem = $('#tripdest' + maxIndex);
                    renewElem.insertAfter(beforeElem);
                }
                $('#tripdest' + destNum).css('display', 'block');
            },

            removeDestinationExistingClick: function (e) {
                var destNum = parseInt($(e.currentTarget).attr('id').substr($(e.currentTarget).attr('id').length - 1), 10);
                UA.Booking.EditSearch.removeDestinationFunc(destNum);
                UA.Booking.EditSearch.clearLof(destNum);

                e.preventDefault();
            },

            removeDestinationClick: function (e) {
                var destNum = parseInt($(e.currentTarget).attr('id').substr($(e.currentTarget).attr('id').length - 1), 10);
                UA.Booking.EditSearch.removeDestinationFunc(destNum);
                UA.Booking.EditSearch.clearLof(destNum);

                e.preventDefault();
            },

            clearLof: function (destNum) {
                var currEl0 = $("#tripdest" + destNum).find(".editSearch-datepicker.hasDatepicker").parent();
                currEl0.find(".editSearch-datepicker.hasDatepicker").val("");
                currEl0.find(".editSearch-datepicker.hasDatepicker").typeahead("val", "").change();
                currEl0.find(".field-validation-error").css("color", "#CD202c");
                currEl0.find(".field-validation-error").css("display", "none");
                currEl0.find(".editSearch-datepicker.hasDatepicker").attr("aria-expanded", "false");
                currEl0.find(".editSearch-datepicker.hasDatepicker").removeClass("input-validation-error").removeClass("valid");
                currEl0.find(".ifl").removeClass("visuallyhidden");
                var divNodes = currEl0.find(".tt-menu").find(".tt-dataset");
                var i;
                var len = divNodes.length;
                for (i = 0; i < len; i++) {
                    if ($(divNodes[i]).find(".tt-suggestion.tt-selectable").hasClass("dropdown-footer")) {
                        ;
                    }
                    else {
                        $(divNodes[i]).empty();
                    }
                }
                currEl0.find(".tt-menu").hide();
                currEl0.removeClass("input-validation-error").removeClass("valid");
                currEl0.find(".ifl").css("opacity", "1.0");

                var currEl1 = $("#tripdest" + destNum).find(".tt-input").parent().parent();
                currEl1.find(".tt-input").typeahead("val", "").change();
                currEl1.find(".field-validation-error").css("color", "#CD202c");
                currEl1.find(".field-validation-error").css("display", "none");
                currEl1.find(".tt-input").attr("aria-expanded", "false");
                currEl1.find(".tt-input").removeClass("input-validation-error").removeClass("valid");
                currEl1.find(".ifl").removeClass("visuallyhidden");
                currEl1.find("pre").empty();
                var divNodes = currEl1.find(".tt-menu").find(".tt-dataset");
                var i;
                var len = divNodes.length;
                for (i = 0; i < len; i++) {
                    if ($(divNodes[i]).find(".tt-suggestion.tt-selectable").hasClass("dropdown-footer")) {
                        ;
                    }
                    else {
                        $(divNodes[i]).empty();
                    }
                }
                currEl1.find(".tt-menu").hide();
                currEl1.removeClass("input-validation-error").removeClass("valid");
                currEl1.find(".ifl").css("opacity", "1.0");
            },

            resetLofs: function (sameValue) {
                if ($("#editFlightSearchVersion").length > 0 && $("#editFlightSearchVersion").val() === "1") {
                    var disabled = ($('.remove-destination-existing').length > 1) ? false : true;
                    var first = false;
                    var firstIndex = 0;
                    var i;
                    for (i = 1; i <= 6; ++i) {
                        if ($('#tripdest' + i).length > 0) {
                            $('#resultdest' + i).prop("disabled", disabled).change();
                            $("#TripsForEditSearch_" + (i - 1) + "__Sequence").val(i).change();
                            if (i > 1) {
                                $("#TripsForEditSearch_" + (i - 1) + "__DepartDate").attr("data-previousitem", "TripsForEditSearch_" + (i - 2) + "__DepartDate");
                            }
                            else {
                                $("#TripsForEditSearch_" + (i - 1) + "__DepartDate").removeAttr("data-previousitem");
                            }

                            if ($('#tripdest' + i).find('.remove-destination-existing').length > 0) {
                                $('#dest' + i).css('display', 'none');
                                $('#tripdest' + i).find(".ifl").css("opacity", "1.0");
                                $("#TripsForEditSearch_" + (i - 1) + "__Ignored").val("false").change();
                                $('#tripdest' + i).css('display', 'block');
                            }
                            else if ($('#tripdest' + i).find('.remove-destination-new').length > 0) {
                                $('#tripdest' + i).css('display', 'none');
                                if (first === false) {
                                    first = true;
                                    firstIndex = i;
                                }
                                else {
                                    $('#dest' + i).css('display', 'none');
                                }
                                $("#TripsForEditSearch_" + (i - 1) + "__Ignored").val("true").change();
                                UA.Booking.EditSearch.clearLof(i);
                            }
                        }
                    }

                    if (first === true) {
                        $('#dest' + firstIndex).css('display', 'block');
                    }

                    var elem1 = $('#tripdest1');
                    var elem2 = $('#tripdest2').detach();
                    var elem3 = $('#tripdest3').detach();
                    var elem4 = $('#tripdest4').detach();
                    var elem5 = $('#tripdest5').detach();
                    var elem6 = $('#tripdest6').detach();

                    elem2.insertAfter(elem1);
                    elem3.insertAfter(elem2);
                    elem4.insertAfter(elem3);
                    elem5.insertAfter(elem4);
                    elem6.insertAfter(elem5);
                }
            },

            removeDestinationFunc: function (destNum) {
                $('#tripdest' + destNum).css('display', 'none');
                $("#TripsForEditSearch_" + (destNum - 1) + "__Ignored").val("true").change();
                var destNumVal = parseInt($("#TripsForEditSearch_" + (destNum - 1) + "__Sequence").val());

                var i;
                for (i = 1; i <= 6; ++i) {
                    if (i == destNum) {
                        $("#TripsForEditSearch_" + (destNum - 1) + "__Sequence").val("6").change();
                    }
                    else {
                        var iVal = parseInt($("#TripsForEditSearch_" + (i - 1) + "__Sequence").val(), 10);
                        if (iVal > destNumVal) {
                            $("#TripsForEditSearch_" + (i - 1) + "__Sequence").val(iVal - 1).change();
                        }
                    }
                }

                var l;
                for (l = 1; l <= 6; ++l) {
                    var lVal = parseInt($("#TripsForEditSearch_" + (l - 1) + "__Sequence").val(), 10);
                    if (lVal > 1) {
                        var m;
                        for (m = 1; m <= 6; ++m) {
                            if (parseInt($("#TripsForEditSearch_" + (m - 1) + "__Sequence").val()) === lVal - 1) {
                                $("#TripsForEditSearch_" + (l - 1) + "__DepartDate").attr("data-previousitem", "TripsForEditSearch_" + (m - 1) + "__DepartDate");
                                break;
                            }
                        }
                    }
                    else {
                        $("#TripsForEditSearch_" + (l - 1) + "__DepartDate").removeAttr("data-previousitem");
                    }
                }

                var destIndex = -1;
                var minIndexVal = 7;
                var minIndex = 6;
                var j;
                for (j = 1; j <= 6; ++j) {
                    if ($('#dest' + j).length > 0 && $('#dest' + j).css('display') === 'block') {
                        destIndex = j;
                    }
                    if ($('#tripdest' + j).length > 0 && $('#tripdest' + j).css('display') === 'none') {
                        var jVal = parseInt($("#TripsForEditSearch_" + (j - 1) + "__Sequence").val(), 10);
                        if (minIndexVal > jVal) {
                            minIndexVal = jVal;
                            minIndex = j;
                        }
                    }
                }

                $('#dest' + destIndex).css('display', 'none');
                if (minIndexVal < 7) {
                    $('#dest' + minIndex).css('display', 'block');
                }

                var total = 0;
                var k;
                for (k = 1; k <= 6; ++k) {
                    if ($('#tripdest' + k).length > 0 && $('#tripdest' + k).css('display') === 'block') {
                        total++;
                    }
                    else {
                        ;
                    }
                }
                if (total <= 1) {
                    for (k = 1; k <= 6; ++k) {
                        if ($('#tripdest' + k).length > 0 && $('#tripdest' + k).css('display') === 'block') {
                            $('#resultdest' + k).prop("disabled", true);
                        }
                        else {
                            ;
                        }
                    }
                }
            },

            changeTravelers: function (travelerData) {  //135859: to change traveler details of new search
                $('#NumOfAdults').val(travelerData.numOfAdults);
                $('#NumOfSeniors').val(travelerData.numOfSeniors);
                $('#NumOfChildren04').val(travelerData.numOfChildren04);
                $('#NumOfChildren03').val(travelerData.numOfChildren03);
                $('#NumOfChildren02').val(travelerData.numOfChildren02);
                $('#NumOfChildren01').val(travelerData.numOfChildren01);
                $('#NumOfInfants').val(travelerData.numOfInfants);
                $('#NumOfLapInfants').val(travelerData.numOfLapInfants);
                $('#travelers-selector').travelerStepper('setText');
            },
            ResetFlightResultSessionItem: function () {
                UA.Utilities.safeSessionStorage.removeItem("tripsShowAllResults");
                UA.Utilities.safeSessionStorage.removeItem("tripsAllStopsChecked");
            },
            initDepartReturnDate: function (currentResult) {
                if (currentResult != null && currentResult.appliedSearch != null) {
                    if (currentResult.appliedSearch.searchTypeMain.toLowerCase() != 'multicity') {
                        var isErrorExist = $("#DepartDate").closest('.materialDesign').find('.field-validation-error').length > 0 ? true : false;
                        if (isErrorExist || $("#DepartDate").val() == '') {
                            if (currentResult.appliedSearch.CalendarDateChange && currentResult.appliedSearch.CalendarDateChange != '' && currentResult.SelectedTrips.length == 0) {
                                if (isFinite(new Date(currentResult.appliedSearch.CalendarDateChange))) {
                                    $("#DepartDate").val(this.formatDateNoWeekDay(currentResult.appliedSearch.CalendarDateChange));
                                }
                                else {
                                    $("#DepartDate").val(currentResult.appliedSearch.CalendarDateChange);
                                }
                            }
                            else {
                                if (isFinite(new Date(currentResult.appliedSearch.Trips[0].DepartDate))) {
                                    $("#DepartDate").val(this.formatDateNoWeekDay(currentResult.appliedSearch.Trips[0].DepartDate));
                                }
                                else {
                                    $("#DepartDate").val(currentResult.appliedSearch.Trips[0].DepartDate);
                                }
                            }
                            $('#DepartDate').closest('.materialDesign').find('.label-for-datepicker').addClass('visuallyhidden');
                        }
                        var isOriginErrorExist = $("#Origin").closest('.materialDesign').find('.field-validation-error').length > 0 ? true : false;
                        if (isOriginErrorExist) {
                            $('#Origin').closest('.materialDesign').find('.ifl').addClass('visuallyhidden');
                        }
                        var isDestErrorExist = $("#Destination").closest('.materialDesign').find('.field-validation-error').length > 0 ? true : false;
                        if (isDestErrorExist) {
                            $('#Destination').closest('.materialDesign').find('.ifl').addClass('visuallyhidden');
                        }
                        $('#DepartDate').closest('.materialDesign').find('.field-validation-error').addClass('field-validation-valid');
                        $('#DepartDate').closest('.materialDesign').find('.field-validation-valid').removeClass('field-validation-error').html('');
                        $('#DepartDate').closest('.materialDesign').removeClass('input-validation-error');
                        $('#DepartDate').removeClass('input-validation-error');
                        $('#Origin').closest('.materialDesign').find('.field-validation-error').addClass('field-validation-valid');
                        $('#Origin').closest('.materialDesign').find('.field-validation-valid').removeClass('field-validation-error').html('');
                        $('#Origin').closest('.materialDesign').removeClass('input-validation-error');
                        $('#Origin').removeClass('input-validation-error');
                        $('#Destination').closest('.materialDesign').find('.field-validation-error').addClass('field-validation-valid');
                        $('#Destination').closest('.materialDesign').find('.field-validation-valid').removeClass('field-validation-error').html('');
                        $('#Destination').closest('.materialDesign').removeClass('input-validation-error');
                        $('#Destination').removeClass('input-validation-error');
                        if (currentResult.appliedSearch.searchTypeMain.toLowerCase() == 'roundtrip' && $('#ReturnDateForEditSearch').val() =='') {
                            if (isFinite(new Date(currentResult.appliedSearch.Trips[1].DepartDate))) {
                                $("#ReturnDateForEditSearch").val(this.formatDateNoWeekDay(currentResult.appliedSearch.Trips[1].DepartDate));
                            }
                            else {
                                $("#ReturnDateForEditSearch").val(currentResult.appliedSearch.Trips[1].DepartDate);
                            }
                            $('#ReturnDateForEditSearch').closest('.materialDesign').find('.label-for-datepicker').addClass('visuallyhidden');
                        }
                    }
                    else {
                        if (currentResult.appliedSearch.Trips != null) {
                            for (var i = 0; i < currentResult.appliedSearch.Trips.length; i++) {
                                var isDateErrorExist = $("#TripsForEditSearch_" + i + "__DepartDate").closest('.materialDesign').find('.field-validation-error').length > 0 ? true : false;
                                if (isDateErrorExist || $("#TripsForEditSearch_" + i + "__DepartDate").val() == '') {
                                    if (isFinite(new Date(currentResult.appliedSearch.Trips[i].DepartDate))) {
                                        $("#TripsForEditSearch_" + i + "__DepartDate").val(this.formatDateNoWeekDay(currentResult.appliedSearch.Trips[i].DepartDate));
                                    }
                                    else {
                                        $("#TripsForEditSearch_" + i + "__DepartDate").val(currentResult.appliedSearch.Trips[i].DepartDate);
                                    }
                                    $("#TripsForEditSearch_" + i + "__DepartDate").closest('.materialDesign').find('.label-for-datepicker').addClass('visuallyhidden');
                                }

                                var isSrcErrorExist = $("#TripsForEditSearch_" + i + "__Origin").closest('.materialDesign').find('.field-validation-error').length > 0 ? true : false;
                                if (isSrcErrorExist ||  $("#TripsForEditSearch_" + i + "__Origin").val() == '') {
                                    $("#TripsForEditSearch_" + i + "__Origin").val(currentResult.appliedSearch.Trips[i].OriginFullName);
                                    $("#TripsForEditSearch_" + i + "__Origin").closest('.materialDesign').find('.ifl').addClass('visuallyhidden');
                                }

                                var isDestErrorExist = $("#TripsForEditSearch_" + i + "__Destination").closest('.materialDesign').find('.field-validation-error').length > 0 ? true : false;
                                if (isDestErrorExist || $("#TripsForEditSearch_" + i + "__Destination").val() == '') {
                                    $("#TripsForEditSearch_" + i + "__Destination").val(currentResult.appliedSearch.Trips[i].DestinationFullName);
                                    $("#TripsForEditSearch_" + i + "__Destination").closest('.materialDesign').find('.ifl').addClass('visuallyhidden');
                                }

                                $("#TripsForEditSearch_" + i + "__DepartDate").closest('.materialDesign').find('.field-validation-error').addClass('field-validation-valid');
                                $("#TripsForEditSearch_" + i + "__DepartDate").closest('.materialDesign').find('.field-validation-valid').removeClass('field-validation-error').html('');
                                $("#TripsForEditSearch_" + i + "__DepartDate").closest('.materialDesign').removeClass('input-validation-error');
                                $("#TripsForEditSearch_" + i + "__DepartDate").removeClass('input-validation-error');
                                $("#TripsForEditSearch_" + i + "__Origin").closest('.materialDesign').find('.field-validation-error').addClass('field-validation-valid');
                                $("#TripsForEditSearch_" + i + "__Origin").closest('.materialDesign').find('.field-validation-valid').removeClass('field-validation-error').html('');
                                $("#TripsForEditSearch_" + i + "__Origin").closest('.materialDesign').removeClass('input-validation-error');
                                $("#TripsForEditSearch_" + i + "__Origin").removeClass('input-validation-error');
                                $("#TripsForEditSearch_" + i + "__Destination").closest('.materialDesign').find('.field-validation-error').addClass('field-validation-valid');
                                $("#TripsForEditSearch_" + i + "__Destination").closest('.materialDesign').find('.field-validation-valid').removeClass('field-validation-error').html('');
                                $("#TripsForEditSearch_" + i + "__Destination").closest('.materialDesign').removeClass('input-validation-error');
                                $("#TripsForEditSearch_" + i + "__Destination").removeClass('input-validation-error');
                            }
                        }
                    }
                    if (currentResult.appliedSearch.awardTravel == true) {
                        $("#AwardTravel_True").prop('checked', true);
                    }
                    else {
                        if(currentResult.appliedSearch.UpgradeType != null) {
                            $("#AwardTravel_False").prop('checked', false);
                            if (currentResult.appliedSearch.UpgradeType.toUpperCase() == 'POINTS')
                                $("#AwardTravel_POINTS").prop('checked', true);
                            else
                                $("#AwardTravel_MUA").prop('checked', true);
                        }
                        else {
                                $("#AwardTravel_False").prop('checked', true);
                        }
                    }
                }
            },
            removeValidationOnInitial: function (currentResult) {
                //clearing the validation error on return date value reset -WI546466
                $('#ReturnDateForEditSearch').closest('.materialDesign').find('.field-validation-error').addClass('field-validation-valid');
                $('#ReturnDateForEditSearch').closest('.materialDesign').find('.field-validation-valid').removeClass('field-validation-error').html('');
                $('#ReturnDateForEditSearch').closest('.materialDesign').removeClass('input-validation-error');
                $('#ReturnDateForEditSearch').removeClass('input-validation-error');
                if (currentResult != null && currentResult.appliedSearch != null) {
                    if (currentResult.appliedSearch.searchTypeMain.toLowerCase() != 'multicity') {
                        if ($("#DepartDate").val() != '') {
                            $('#DepartDate').closest('.materialDesign').find('.label-for-datepicker').addClass('visuallyhidden');
                        }
                        if ($('#Origin').val() != '') {
                            $('#Origin').closest('.materialDesign').find('.ifl').addClass('visuallyhidden');
                        }
                        if ($('#Destination').val() != '') {
                            $('#Destination').closest('.materialDesign').find('.ifl').addClass('visuallyhidden');
                        }
                        if (currentResult.appliedSearch.searchTypeMain.toLowerCase() == 'roundtrip' && $('#ReturnDateForEditSearch').val()!='')
                        {
                            $('#ReturnDateForEditSearch').closest('.materialDesign').find('.label-for-datepicker').addClass('visuallyhidden');
                        }
                    }
                    else {
                        for (var i = 0; i < currentResult.appliedSearch.Trips.length; i++) {
                            if ($("#TripsForEditSearch_" +i + "__DepartDate").val() != '') {
                                $("#TripsForEditSearch_" +i + "__DepartDate").closest('.materialDesign').find('.label-for-datepicker').addClass('visuallyhidden');
                            }
                            if ($("#TripsForEditSearch_" +i + "__Origin").val() != '') {
                                $("#TripsForEditSearch_" +i + "__Origin").closest('.materialDesign').find('.ifl').addClass('visuallyhidden');
                            }
                            if ($("#TripsForEditSearch_" +i + "__Destination").val() != '') {
                                $("#TripsForEditSearch_" +i + "__Destination").closest('.materialDesign').find('.ifl').addClass('visuallyhidden');
                            }
                        }
                    }
                }
            },
            formatDateNoWeekDay: function (dt) {
                var dte = new Date(dt);
                return UA.Utilities.formatting.formatShortDateNoWeekDay(dte);
            }
        };
    }());

}(jQuery));

;
/*global jQuery, UA*/
(function ($) {
	'use strict';
	UA.Utilities.namespace("UA.Booking.Cart");

	UA.Booking.Cart = (function () {
		var stickyClass = 'sticky',
			selectorExpColTax = '.expCol-tax',
			selectorExpColTaxContext = '.tax-breakdown-tooltip',            
			selectorTripTooltipTrigger = '.dc-trip',
			selectorTripTooltipContentDataPointer = 'detail-element',
			classTripChangeTrigger = 'cart-change-trip',
			selectorPriceTooltipTrigger = '.qtip-price',
			selectorPriceTooltipContent = '.qtip-price-summary',
			loaderElSelector = '.cart-content',
			safeSessionStorage = UA.Utilities.safeSessionStorage,
			nextFocusElement = undefined;
		function log() {
			return UA.Utilities.log.apply(this, arguments); //ignore jslint - apply call
		}

		return {
			el: $('#bookingCart'),
			init: function (reBind) {
				if (typeof this.activeAjaxCount === 'undefined') {
					this.activeAjaxCount = 0;
				}
				if (safeSessionStorage.getItem("isVendorQuery") === "True" && safeSessionStorage.getItem("directToRTI") === "False") {
					$(".cart-change-trip").hide();
				}
				this.el = $('#bookingCart');
				UA.Booking.EditSearch.init();
				this.initExpandCollapseTax();				
				this.initStickyCart();
				this.setCurrencyConversionTooltip();
			    if (reBind) {
					this.bindEvents();
				}
			},			
			initStickyCart: function () {			    
			    var cartContainer = $('.cart-content'),
					cartEpilogue = $('.cart-epilogue'),
					cartBrazilMessage = $('.cart-brazil-regulation'),
                    cartFranceRegulation = $('.cart-french-regulation');
			    if (cartFranceRegulation && cartFranceRegulation.css('display') != 'none') {
			        if (cartContainer.hasClass(stickyClass)) {
			            cartContainer.stickyheader({
			                offsetPartner: null
			            });
			        }
				}
				else if (cartBrazilMessage && cartBrazilMessage.is(":visible")) {
					if (cartContainer.hasClass(stickyClass)) {
						cartContainer.stickyheader({
							offsetPartner: null
						});
					}
				}
			    else {
			        if (cartContainer.hasClass(stickyClass)) {
			            cartContainer.stickyheader({
			                offsetPartner: cartEpilogue
			            });
			        }
                }
                if (cartContainer.html() !== '') {
                    $('.validation-summary-errors').css('width','595px');

                    if (cartFranceRegulation && $('#hdnTaxRefundContent').val() == 'True') {
                        $('#tax-refund-info').css('display', 'block');
					}
					if (cartBrazilMessage && $('#hdnTaxReimbursableContent').val() == 'True') {
						$('#tax-reimbursable-info').show();
					}                   
                }

                if (cartFranceRegulation && cartFranceRegulation.css('display') != 'none') {
                    cartContainer.on('stuckAdded', function () {
                        cartFranceRegulation.css('top', cartContainer.outerHeight());
                        cartFranceRegulation.css('position', 'fixed');
                        cartEpilogue.css('position', 'fixed');                        
                    });

                    cartContainer.on('stuckRemove', function () {
                        cartFranceRegulation.css('top', 'auto');
                        cartFranceRegulation.css('position', 'relative');
                        cartEpilogue.css('position', 'relative');
                        cartEpilogue.css('top', 'auto');
                    });
				}
				if (cartBrazilMessage && cartBrazilMessage.is(":visible")) {
					cartContainer.on('stuckAdded', function () {
						cartBrazilMessage.css('top', cartContainer.outerHeight());
						cartBrazilMessage.css('position', 'fixed');
						cartEpilogue.css('position', 'fixed');
					});

					cartContainer.on('stuckRemove', function () {
						cartBrazilMessage.css('top', 'auto');
						cartBrazilMessage.css('position', 'relative');
						cartEpilogue.css('position', 'relative');
						cartEpilogue.css('top', 'auto');
					});
				}
			},
			initExpandCollapseTax: function (context) {
				var $TaxContainer = $(selectorExpColTaxContext),
					$taxGroups = $(selectorExpColTax, $TaxContainer);

				$taxGroups.accordion({
					collapsible: true,
					active: false,
					heightStyle: "content",
					icons: {
						"header": "icon-toggle-arrow-right-gray",
						"activeHeader": "icon-toggle-arrow-down-gray"
					},
					activate: function (event, ui) {
						$(document).trigger('resize');
					},
					animate: false
				});				
			},
			handleTripTooltip: function (e) {
				e.preventDefault();
				var target = $(e.currentTarget),
					selector = target.data(selectorTripTooltipContentDataPointer);
				UA.UI.Tooltip.init(target, {
					content: {
						text: ''
					},
					position: {
						my: 'right center',
						at: 'left center',
						adjust: {
							method: 'flip shift'
						},
						effect: false
					},
					show: {
						event: e.type
					},
					events: {
						show: function (event, api) {
							api.set('content.text', $(selector).clone());
						}
					}
				}, 'close-delegated', null, false, e);
				e.preventDefault();
			},
			handleFootnoteClick: function (ev) {
			    var _this = ev.currentTarget;
			    //ev.preventDefault();
			    //ev.stopPropagation();
			    var fntarget = $(_this).attr('href');
			    var fmarkID = $(_this).attr('id');
			    if (!$(fntarget).children('.fn-return').length) {
			        $(fntarget).append(' <a class="fn-return" href="#" >Return to reference</a>');
			    }
			    var returntoref = $(fntarget).children('.fn-return');
			    returntoref.attr('href', '#' + fmarkID).show();
			    $(fntarget).animate({ left: 0 },
                    "slow",
                    function () {
                        $(fntarget).focus();
                    });
			},
			handleBasicEconomyRestrictionsTooltip: function (e) {
			    e.preventDefault();
			    var target = $(e.currentTarget);
			    UA.UI.Tooltip.init(target, {
			        content: {
			            text: ''
			        },
			        style: {
			            classes: "tip-united-closeable tip-no-max-width"
			        },
			        position: {
			            my: 'right center',
			            at: 'left center',
			            adjust: {
			                method: 'flip shift'
			            },
			            effect: false
			        },
			        show: {
			            event: e.type

			        },
			        events: {
			            show: function (event, api) {
			                api.set('content.text', $(".basic-economy-restrictions-tooltip").clone());
                            //make id unique
			                var footMark = $(this).find('a.footmark').eq(0);
			                var uniqueId = footMark.prop('id');
			                footMark.prop('id', uniqueId + "a");
			                var footMarkHref = footMark.attr('href') + 'a';
			                footMark.attr('href', footMarkHref);
			                //create id for footnote from footMarkHref
			                var footNoteId = footMarkHref.substr(1);
			                $(this).find('.footnote').eq(0).attr('id', footNoteId);
			                $(this).off('click');
			                $(this).on('click', UA.Booking.Cart.handleFootnoteClick);
			            }
			        }
			    }, 'close-delegated', null, false, e);
			    e.preventDefault();
			},
			handlePriceTooltip: function (e) {
				var target = $(e.currentTarget);
				UA.UI.Tooltip.init(target, {
						content: {
						text:''
						},
						position: {
						my: 'right center',
						at: 'left center',
							effect: false
						},
					show: {
						event: e.type
					},
						events: {
							show: function (event, api) {
								api.set('content.text', $(selectorPriceTooltipContent, target).clone(true));
							}
						}
				}, 'close-delegated', null, false, e);
				e.preventDefault();
				this.currentCartTooltip = target.qtip('api');
			},
			handleCartMsgTooltip: function (e) {
				var target = $(e.currentTarget), //ignore jslint - each processor
					selector = target.data(selectorTripTooltipContentDataPointer);
				if (selector == null || selector == "" || selector == undefined) {
					selector = "#tooltip-cart-msg";
				}
				UA.UI.Tooltip.init(target, {
					overwrite: false,
					content: {
						text: $(selector).clone(),
					},
					position: {
						at: 'bottom right',
						my: 'top right',
						adjust: {
							method: 'shift shift',
							effect: false
					},
						effect: false
					},
					show: {
						event: e.type
						}
				}, 'close-delegated', null, false, e);
				e.preventDefault();
			},
			handleTravelOptionTooltip: function (e) {
				var $target = $(e.currentTarget);
				UA.UI.Tooltip.init($target, {
					content: {
						text: $('.travel-option-breakdown-tooltip').clone(true)
					},
					position: {
						my: 'right center',
						at: 'left center',
						adjust: {
							method: 'shift shift',
							effect: false
						},
						effect: false
					},
					isPopupEnabled: true,
					show: {
						event: e.type
					}
				}, 'close-delegated', null, false, e);
				e.preventDefault();
				this.currentCartTooltip = $target.qtip('api');
			},
			handleETCTooltip: function (e) {
			    var $target = $(e.currentTarget);
			    UA.UI.Tooltip.init($target, {
			        content: {
			            text: $('.ETC-option-breakdown-tooltip').clone(true)
			        },
			        position: {
			            my: 'right center',
			            at: 'left center',
			            adjust: {
			                method: 'shift shift',
			                effect: false
			            },
			            effect: false
			        },
			        isPopupEnabled: true,
			        show: {
			            event: e.type
			        }
			    }, 'close-delegated', null, false, e);
			    e.preventDefault();
			    this.currentCartTooltip = $target.qtip('api');
			},
			handleTaxBreakdownTooltip: function (e) {
				UA.UI.Tooltip.init($(e.currentTarget), {
					content: {
						text: $('.tax-breakdown-tooltip').clone(true)
					},
					position: {
						my: 'right center',
						at: 'left center',
						adjust: {
							method: 'shift shift',
							effect: false
						},
						effect: false
					},
					show: {
						event: e.type
					}
				}, 'close-delegated', null, false, e);
				e.preventDefault();
			},

			handleTaxRefundBreakdownTooltip: function (e) {
			    UA.UI.Tooltip.init($(e.currentTarget), {
			        content: {
			            text: $('.tax-refund-breakdown-tooltip').clone(true)
			        },
			        position: {
			            my: 'right center',
			            at: 'left center',
			            adjust: {
			                method: 'shift shift',
			                effect: false
			            },
			            effect: false
			        },
			        show: {
			            event: e.type
			        }
			    }, 'close-delegated', null, false, e);
			    e.preventDefault();
			},

			handleFareBreakdownTooltip: function (e) {
				UA.UI.Tooltip.init($(e.currentTarget), {
					content: {
						text: $('.fare-breakdown-tooltip').clone(true)
					},
					position: {
						my: 'right center',
						at: 'left center',
						adjust: {
							method: 'shift shift',
							effect: false
						},
						effect: false
					},
					show: {
						event: e.type
						}
				}, 'close-delegated', null, false, e);
				e.preventDefault();
					},

			handleSurchargeBreakdownTooltip: function (e) {
			    UA.UI.Tooltip.init($(e.currentTarget), {
			        content: {
			            text: $('.fuelSurcharge-breakdown-tooltip').clone(true)
			        },
			        position: {
			            my: 'right center',
			            at: 'left center',
			            adjust: {
			                method: 'shift shift',
			                effect: false
			            },
			            effect: false
			        },
			        show: {
			            event: e.type
			        }
			    }, 'close-delegated', null, false, e);
			    e.preventDefault();
			},
			handleAPDBreakdownTooltip: function (e) {
				UA.UI.Tooltip.init($(e.currentTarget), {
					content: {
						text: $('.apd-breakdown-tooltip').clone(true)
					},
					position: {
						my: 'right center',
						at: 'left center',
						adjust: {
							method: 'shift shift',
							effect: false
						},
						effect: false
					},
					show: {
						event: e.type
					}
				}, 'close-delegated', null, false, e);
				e.preventDefault();
			},
			handleSpecialTravelFeesTooltip: function (e) {
				var $target = $(e.currentTarget);
				UA.UI.Tooltip.init($target, {
					content: {
						text: $('.special-travel-fees-tooltip').clone(true)
					},
					position: {
						my: 'right center',
						at: 'left center',
						adjust: {
							method: 'shift shift',
							effect: false
						},
						effect: false
					},
					show: {
						event: e.type
					}
				}, 'close-delegated', null, false, e);
				e.preventDefault();
				this.currentCartTooltip = $target.qtip('api');
			},
			handleUpgradeWaitlistTooltip: function (e) {
				UA.UI.Tooltip.init($(e.currentTarget), {
					content: {
						text: $('#tooltip-fare-upgrade-waitlist').clone()
					},
					show: {
						event: e.type
						}
				}, 'default-delegated', null, false, e);
			},
			handleUpgradeAvailableTooltip: function (e) {
				UA.UI.Tooltip.init($(e.currentTarget), {
					content: {
						text: $('#tooltip-fare-upgrade-available').clone()
					},
					show: {
						event: e.type
						}
				}, 'default-delegated', null, false, e);
					},
			handleUpgradeEligibleTooltip: function (e) {
				UA.UI.Tooltip.init($(e.currentTarget), {
					content: {
						text: $('#tooltip-fare-upgrade-eligible').clone()
					},
					show: {
						event: e.type
					}
				}, 'default-delegated', null, false, e);
			},
			handleUpgradeNotEligibleTooltip: function (e) {
				UA.UI.Tooltip.init($(e.currentTarget), {
					content: {
						text: $('#tooltip-fare-upgrade-not-eligible').clone()
					},
					show: {
						event: e.type
					}
				}, 'default-delegated', null, false, e);
			},
            showEditModal: function (e) {  
                
				e.preventDefault();
                var clseHTML = "<button class='modalCloseImg simplemodal-close closeImgContrast'><span class='visuallyhidden'>Close</span></button>";
				var newLoc, cameFromAdvanceSearch = this.el.data('disable-modal');
				if (cameFromAdvanceSearch) {
					newLoc = this.el.data('search-url');
					window.href = newLoc;
				} else {
					$('#edit-search-modal').modal({
						overlayClose: true,
                        persist: true,
                        closeHTML : clseHTML
					});
				}
                //WI:667632 D2 Booking_Award travel_GovernmentPath_Flight search results: Per Ruby there should be no award option for government path (Update button)
				var govtPathValue = JSON.parse(UA.Utilities.safeSessionStorage.getItem("GovtPath"));
				if (govtPathValue.GovType !== null && govtPathValue.MilitaryTravelType !== null) {
				    if (govtPathValue.isGovtPath == true && govtPathValue !== undefined && govtPathValue !== null) {
				        $('.form-group-award').hide();

				        var formChildren = $("#flightSearch");
				        formChildren.append("<input type='hidden' name='MilitaryOrGovernmentPersonnelStateCode' id='MilitaryOrGovernmentPersonnelStateCode' value=" + govtPathValue.MilitaryOrGovernmentPersonnelStateCode + " />");
				        formChildren.append("<input type='hidden' name='MilitaryTravelType' id='MilitaryTravelType' value='" + govtPathValue.MilitaryTravelType + "' />");
				        formChildren.append("<input type='hidden' name='GovType' id='GovType' value='" + govtPathValue.GovType + "' />");
				        formChildren.append("<input type='hidden' name='IsGovPath' id='IsGovPath' value='" + govtPathValue.isGovtPath + "' />");
				    }
				}
			},
			changeTrip: function (e) {
				e.preventDefault();
				var postHtml, url = $(e.currentTarget).data('href'),
					data = JSON.parse($(e.currentTarget).attr('data-trip'));

				$(e.currentTarget).loader();
				if (data.TripIndex === "1") {
					data.SolutionSetId = "";
					data.ProductId = "";
					data.EditSearch = true;
				}
                else if (data && !data.ProductId && !data.SolutionSetId){
					data.SolutionSetId = safeSessionStorage.getItem("SolutionSetId" + data.TripIndex);
					data.ProductId = safeSessionStorage.getItem("CellIdSelected" + data.TripIndex);
				}

				postHtml = '<form style="display:none;" id="cartupdate" method="post" action="' + url + '"> \n' +
					' <input type="hidden" name="BbxSessionId" value="' + data.BbxSessionId + '" /> \n' +
					' <input type="hidden" name="SolutionSetId" value="' + data.SolutionSetId + '" /> \n' +
					' <input type="hidden" name="CartId" value="' + data.CartId + '" /> \n' +
					' <input type="hidden" name="ProductId" value="' + data.ProductId + '" /> \n' +
					' <input type="hidden" name="TripIndex" value="' + data.TripIndex + '" /> \n' +
					' <input type="hidden" name="EditSearch" value="' + data.EditSearch + '" /> \n' +
					'</form>';

				jQuery('<div/>')
					.append(postHtml)
					.appendTo('body')
					.find('#cartupdate')
					.submit();


			},
			showCartLoader: function () {
				var loaderEl = $(loaderElSelector);
				loaderEl.loader();
			},
			hideCartLoader: function () {
				var loaderEl = $(loaderElSelector);

				if (loaderEl.data('ua-loader')) {
					loaderEl.loader('destroy');
				}

			},
			addToCart: function (item) {
			    this.showCartLoader();

				var $cartContainer,
					_this = this,
					serviceUrl = location.pathname.toLowerCase().replace('/default', '') + '/AddToCart',
					request = $.ajax({
					        url: serviceUrl,
					        type: "POST",
					        data: JSON.stringify(item),
					        contentType: "application/json; charset=utf-8",
					        dataType: 'html',
					        beforeSend: function () {
							_this.activeAjaxCount += 1;
					}
			});

				$.when(request).done(function (data) {
					_this.activeAjaxCount -= 1;
					_this.el = $('#bookingCart');

					if (_this.activeAjaxCount === 0) {
						_this.hideCartLoader();
				}

					$cartContainer = _this.el.parent().html(data);

					UA.UI.reInit($cartContainer);

					_this.init();

					if (_this.activeAjaxCount !== 0) {
						_this.showCartLoader();
				}

					$(document).trigger("refreshOtherFops");

					_this.CheckOffersTandC($(data));
					_this.checkCart(data);

					$(document).trigger("addToCartDone");
				    //null check
					if (UA.Booking.Uplift) UA.Booking.Uplift.checkAndLoadUplift();

				}).fail(function (jqXHR, textStatus) {

					_this.hideCartLoader();
				}).always(function (data) {
					if (_this.activeAjaxCount === 0) {
						_this.hideCartLoader();
				}
			});
			},
			checkCart: function (data) {
				var item, response = $(data),
					isValid = response.attr("id", "validresponse"),
					productCode = response.attr("data-productcode"),
					subProductCode = response.attr("data-subproductcode"),
					productIds = response.attr("data-productids"),
					status = response.attr("data-status"),
					action = response.attr("data-action"),
					isFromRemoveBtn = response.attr("data-isfromremovebtn");
				if (isValid) {
					item = {
						ProductCode: productCode,
						SubProductCode: subProductCode,
						ProductIds: productIds,
						Action: action,
						Status: status,
						IsFromRemoveBtn: isFromRemoveBtn
					};
					$.event.trigger({
						type: "TravelOptionsAddOrRemove",
						message: item,
						time: new Date()
					});
				}
			},
			CheckOffersTandC: function (e) {
				//check and toggle offers t&c
				var objCart,
					hasOffer = false,
					isFareLock = false,
					hasInSufficientMiles = false,
					tncOffer, tncTicket, tncFareLock, tncReserve, tncFareLockOffer,
					skipChangeTC = false,
					productTCDisplay = {};

				objCart = typeof e === 'undefined' ? $('#bookingCart') : e;

				//reset style to hide
				$('.economy, .premier, .award', '#divALLProdTermsAndConditionModal').hide();

				objCart.find('[data-traveloptiontype]').each(function () {
					switch ($(this).attr('data-traveloptiontype')) {
						case 'SEATASSIGNMENTS':
							hasOffer = true;
							$('.economy', '#divALLProdTermsAndConditionModal').show();
							productTCDisplay.seatPurchase = true;
							if ($(this).attr('data-pids').indexOf('EconomyPlus') !== -1)
							    productTCDisplay.EconomyPlus = true;
							if ($(this).attr('data-pids').indexOf('Standard') !== -1)
							    productTCDisplay.EconomyMinus = true;
							if ($(this).attr('data-pids').indexOf('PreferredZoneSeat1') !== -1)//Added for preferred zone AB247
							    productTCDisplay.PrefferedZone = true;
							break;
						case 'Premium Access':
							hasOffer = true;
							$('.premier', '#divALLProdTermsAndConditionModal').show();
							productTCDisplay.premierAccess = true;
							skipChangeTC = false;
							break;
						case 'Award Accelerator':
							hasOffer = true;
							$('.award', '#divALLProdTermsAndConditionModal').show();
							productTCDisplay.awardAccelerator = true;
							skipChangeTC = false;
                            break;
                        case 'Premier Accelerator':
                            hasOffer = true;
                            $('.award', '#divALLProdTermsAndConditionModal').show();
                            productTCDisplay.premierAccelerator = true;
                            skipChangeTC = false;
                            break;
						case 'EPS':
					    case 'EPE':
					    case 'BE':
							productTCDisplay.Bundles = true;
							hasOffer = true;
							break;
					}
				});

				UA.Booking.Cart.productTCDisplay = productTCDisplay;

				tncOffer = $('#tnc-Offer');
				tncTicket = $('#tnc-normal');
				tncFareLock = $('#tnc-farelock-normal');
				tncFareLockOffer = $('#tnc-farelock-offer-normal');
				tncReserve = $('#tnc-Reserve');
				tncOffer.hide();
				tncTicket.hide();
				tncFareLock.hide();
				tncFareLockOffer.hide();
				tncReserve.hide();

				// WI 122851 - D2 Booking – Payment (FareLock): Displaying message beside of the ‘Purchase’ button is not related to FareLock booking
				isFareLock = $('#FareLock_farelock').is(':checked');
				hasInSufficientMiles = $('#tnc-normal').length === 0;
				if (hasOffer) {
					// 163449
					if (!skipChangeTC) {
						// WI 225059 - Packages - Farelock booking - Farelock discloser message missing next to 'Purchase' button.
						if ((isFareLock) || (hasInSufficientMiles && tncReserve.length == 0))
							tncFareLockOffer.show();
						else
							tncOffer.show();
					}
					else {
						tncTicket.show();
					}
				} else {
					// WI 129280 - D2 Booking – Payment : Disclaimer text beside ‘Reserve’ button is not related to Reserve booking.
					// The second condition occurs when its farelock and doesn't have sufficient miles.
					// isFareLock = false when there are insufficient miles since there is no check box
					if ((isFareLock) || (hasInSufficientMiles && tncReserve.length == 0)) {
					    tncTicket.show();					  
					    tncFareLock.show();
					} else {
						if (tncReserve.length === 0) {
							tncTicket.show();
							tncFareLockOffer
						} else {
							tncReserve.show();
						}
					}
				}
			},
			removeCouponFromCart: function (e) {
			    e.preventDefault();
			    var cartid = $("#bookingCart").data('id'),
			    btn = $(e.currentTarget),
			         _selectedPaymentType = $("input[name='payment-option']:checked").val();

			    if (_selectedPaymentType != 'undefined' && _selectedPaymentType == 'pay-monthly') {

			            if ($('#promoremove-Modal-Content').length > 0)
			            {
			                $("#promoremove-Modal-Content").modal();
			            }
			        }
			        else {
			            var code = $(e.currentTarget).data('promocodevalue');
			            var couponEvent = e;
			            $.ajax({
			                url: $("#coupon-container").data('href-remove-coupon'),
			                type: 'GET',
			                cache: false,
			                dataType: 'json',
			                eventobj:couponEvent,
			                data: {
			                    cartid: cartid,
			                    code: code,
			                },
			                beforeSend: function () {
			                    btn.loader();
			                },
			                error: function (e) {
			                    if ($(btn) != null) {
			                        $(btn).loader('destroy');
			                    }
			                },
			                success: function (response) {
			                   if( response.Status == 1)
			                    {
			                    if ($(btn) != null) {
                                       $(btn).loader('destroy');
			                    }
			                    if ($('#removeCouponError').length > 0) {
			                        $("#removeCouponError").hide();
			                    }
			                    UA.Booking.Cart.refreshCart(this.eventobj);
			                   }
			                   else
			                   {
			                       if ($(btn) != null) {
			                           $(btn).loader('destroy');
			                       }
			                       if (response.Errors[0].MinorCode === "10090") {
			                           if ($('#removeCouponError').length > 0) {
			                               $("#removeCouponError").show();
			                           }
			                       }
			                   }
			                }
			            });
			        }			    
			},
			removeCertFromCart: function (e) {
			    e.preventDefault();
			    var btn = $(e.currentTarget);
			    btn.loader();
			    UA.Booking.Cart.currentCartTooltip.destroy();
			    UA.Booking.BillingInfo.removeETCWithPIN($("#bookingCart").data('id'), $(e.currentTarget).data('pin'));
			},
			removeFromCart: function (e) {
			    e.preventDefault();
			    if (UA.Booking.Cart.currentCartTooltip != null) {
			        nextFocusElement = UA.Booking.Cart.currentCartTooltip.target;
			    }
				var cartid = $("#bookingCart").data('id'),
					btn = $(e.currentTarget),
					offerkey = $(e.currentTarget).attr('id'),
					prodcode = $(e.currentTarget).data('pcode'),
					prodids = $(e.currentTarget).data('pids'),
                    prodid = $(e.currentTarget).data('pid'),
					traveloptiontype = $(e.currentTarget).data('traveloptiontype'),
					logData = {
						action: "remove",
						offerkey: offerkey,
						prodcode: prodcode,
						prodids: prodids,
						traveloptiontype: traveloptiontype
					};			

				    if (offerkey === 'AAC' && typeof $('#PAC').data('pids') !== 'undefined') {
				        prodids = prodids + '|' + $('#PAC').data('pids');
				    }

				    if (offerkey === 'EPE' || 'BE') {
				        if (typeof $('#PAC').data('pids') !== 'undefined') {
				            prodids = prodids + '|' + $('#PAC').data('pids');
				        }
				        if (typeof $('#AAC').data('pids') !== 'undefined') {
				            prodids = prodids + '|' + $('#AAC').data('pids');
				        }
				    }
				    if (offerkey === 'PAS_SubItems') {
				        if ($('#select-flight-wrap').length > 0) {
				            $('#select-flight-wrap li').each(function () {

				                var offerCheckBoxes = $(this).find('.select-flight-wrap input[type=checkbox]:checked'),
                                    offerIds = offerCheckBoxes.map(function () {
                                        return this.value;
                                    }).get().join(', '),
                                    btnOfferIds = $(e.currentTarget).data('pids');

				                if (offerIds === btnOfferIds) {
				                    btn.loader();
				                    UA.Booking.Cart.currentCartTooltip.destroy();
				                    $(this).find('.upper-checkbox').trigger('click');
				                    return false;
				                }
				            });

				            return false;
				        }
				    }
				    if (offerkey === 'PBS_SubItems') {
				        if ($('#select-pb-flight-wrap').length > 0) {
				            $('#select-pb-flight-wrap li').each(function () {

				                var offerCheckBoxes = $(this).find('.select-flight-wrap input[type=checkbox]:checked'),
                                    offerIds = offerCheckBoxes.map(function () {
                                        return this.value;
                                    }).get().join(', '),
                                    btnOfferIds = $(e.currentTarget).data('pids');

				                if (offerIds === btnOfferIds) {
				                    btn.loader();
				                    UA.Booking.Cart.currentCartTooltip.destroy();
				                    $(this).find('.upper-checkbox').trigger('click');
				                    return false;
				                }
				            });

				            return false;
				        }
				    }

				    UA.UI.logCartChange(logData);

				    $.ajax({
				        url: $("#bookingCart").data('href-remove-travel-options'),
				        type: 'GET',
				        cache: false,
				        dataType: 'html',
				        data: {
				            cartid: cartid,
				            key: offerkey,
				            productcode: prodcode,
				            productids: prodids
				        },
				        beforeSend: function () {
				            btn.loader();
				        },
				        error: function (e) {
				            if ($(btn) != null) {
				                $(btn).loader('destroy');
				            }
				        },
				        success: function (response) {
				            var item,
                                hasPAC,
                                hasAAC,
                                hasTPI,
                                hasPAS;

				            try {
				                if (traveloptiontype === "EPS" || traveloptiontype === "EPE" || traveloptiontype === "SEATASSIGNMENTS" || traveloptiontype === "BE") {
				                    self.currentTravelers = $('#travSegments').data('travseat');
				                    var reJson = $.parseJSON(response);
				                    var i, j, displayseatKey;
				                    if (self.currentTravelers != undefined) {
				                        for (i = 0; i < self.currentTravelers.length; i += 1) {
				                            for (j = 0; j < self.currentTravelers[i].SelectedSeat.length; j += 1) {
				                                self.currentTravelers[i].SelectedSeat[j].SeatNumber = "----";
				                                self.currentTravelers[i].SelectedSeat[j].SeatPriceFormatted = "";
				                                self.currentTravelers[i].SelectedSeat[j].SeatPromotionCode = "";
				                                var displaySeats = reJson.DisplayCart.DisplaySeats;
				                                if (displaySeats.length > 0) {
				                                    for (displayseatKey = 0; displayseatKey < displaySeats.length; displayseatKey += 1) {
				                                        var key = displaySeats[displayseatKey];
				                                        if (self.currentTravelers[i].TravIndex == key.TravelerIndex) {
				                                            if (self.currentTravelers[i].SelectedSeat[j].SeatSegmentId == key.FlattenedSeatIndex) {
				                                                self.currentTravelers[i].SelectedSeat[j].SeatNumber = key.Seat;
				                                                self.currentTravelers[i].SelectedSeat[j].SeatPriceFormatted = key.SeatPriceFormatted;
				                                                self.currentTravelers[i].SelectedSeat[j].SeatPromotionCode = key.SeatPromotionCode;
				                                            }
				                                        }
				                                    }
				                                }
				                            }
				                        }
				                    }

				                    if (UA.Booking.BillingInfo) {
				                        // User Story 493059:Re-price TI when Customers Adds or Removes Ancillary
				                        // If trip insurance is offered and bundle or seat was removed then 
				                        // we reprice trip insurance; in case when pet in cabin fee is removed 
				                        // we refresh the whole page.
				                        if ($('input[name=WASCInsuranceOfferOption]:radio').length && (traveloptiontype === "BE" || traveloptiontype === "SEATASSIGNMENTS") ) {
				                            UA.Booking.BillingInfo.getProducts();
				                        }
				                        else {
				                            if (traveloptiontype === "EPE") {
				                                UA.Booking.BillingInfo.getProducts();
				                            }
				                            else if (traveloptiontype === "BE") {
				                                var hasPASInBundle = $("#BundlesSelected_" + prodcode);
				                                if (hasPASInBundle.length > 0) {
				                                    if (hasPASInBundle.val() === "true" && hasPASInBundle.data('pid') === prodid)
				                                        UA.Booking.BillingInfo.getProducts();
				                                }
				                            }
				                        }
				                    }
				                }
				                if (traveloptiontype === 'SEATASSIGNMENTS' || traveloptiontype === "EPS" || traveloptiontype === "EPE" || traveloptiontype === "BE") {
				                    return;
				                }
				                var json = $.parseJSON(response);

				                //if (json.DisplayCart != 'undefined' && json.DisplayCart.TravelOptions != 'undefined')
				                if (json.DisplayCart != null && json.DisplayCart != 'undefined' && json.DisplayCart.TravelOptions != null && json.DisplayCart.TravelOptions != 'undefined') {
				                    switch (offerkey) {
				                        case 'PAC':
				                            hasPAC = false;
				                            if (json.DisplayCart.TravelOptions.length > 0) {
				                                $.each(json.DisplayCart.TravelOptions, function (key) {
				                                    if ($(this).attr('Key') === 'PAC') {
				                                        hasPAC = true;
				                                    }
				                                });
				                            }

				                            if (hasPAC) {
				                                console.log('Error removing Premier Accelerator');
				                            } else {
				                                item = {
				                                    CurrentTarget: 'RemoveButton',
				                                    ProductCode: offerkey
				                                };
				                                $.event.trigger({
				                                    type: "TravelOptionsAddOrRemove",
				                                    message: item,
				                                    time: new Date()
				                                });
				                            }
				                            break;

				                        case 'PAS':
				                            hasPAS = false;

				                            if (json.DisplayCart.TravelOptions.length > 0) {
				                                $.each(json.DisplayCart.TravelOptions, function (key) {
				                                    if ($(this).attr('Key') === 'PAS') {
				                                        hasPAS = true;
				                                    }
				                                });
				                            }

				                            if (hasPAS) {
				                                console.log('Error removing Premier Access');
				                            } else {
				                                item = {
				                                    CurrentTarget: 'RemoveButton'
				                                };

				                                $.event.trigger({
				                                    type: "handleAddPAProductsToCart",
				                                    message: item,
				                                    time: new Date()
				                                });
				                            }
				                            break;

				                        case 'PBS':
				                            hasPAS = false;

				                            if (json.DisplayCart.TravelOptions.length > 0) {
				                                $.each(json.DisplayCart.TravelOptions, function (key) {
				                                    if ($(this).attr('Key') === 'PBS') {
				                                        hasPAS = true;
				                                    }
				                                });
				                            }

				                            if (hasPAS) {
				                                console.log('Error removing Priority Boarding');
				                            } else {
				                                item = {
				                                    CurrentTarget: 'RemoveButton'
				                                };

				                                $.event.trigger({
				                                    type: "handleAddPBProductsToCart",
				                                    message: item,
				                                    time: new Date()
				                                });
				                            }
				                            break;

				                        case 'AAC':
				                            hasAAC = false;

				                            if (json.DisplayCart.TravelOptions.length > 0) {
				                                $.each(json.DisplayCart.TravelOptions, function (key) {
				                                    if ($(this).attr('Key') === 'AAC') {
				                                        hasAAC = true;
				                                    }
				                                });
				                            }
				                            if (hasAAC) {
				                                console.log('Error removing Award Accelerator');
				                            } else {
				                                item = {
				                                    CurrentTarget: 'RemoveButton',
				                                    ProductCode: offerkey,
				                                    ProductIds: prodids
				                                };

				                                $.event.trigger({
				                                    type: "TravelOptionsAddOrRemove",
				                                    message: item,
				                                    time: new Date()
				                                });
				                            }
				                            break;

				                        case 'TPI':
				                            hasTPI = false;
				                            if (json.DisplayCart.TravelOptions.length > 0) {
				                                $.each(json.DisplayCart.TravelOptions, function (key) {
				                                    if ($(this).attr('Key') === 'TPI') {
				                                        hasTPI = true;
				                                    }
				                                });
				                            }

				                            if (hasTPI) {
				                                console.log('Error removing Trip Insurance');
				                            } else {
				                                item = {
				                                    CurrentTarget: 'RemoveButton'
				                                };
				                                $.event.trigger({
				                                    type: "TravelOptionsTripInsurance",
				                                    message: item,
				                                    time: new Date()
				                                });
				                            }
				                            break;
				                    }
				                    UA.Booking.Cart.CheckOffersTandC();
				                }

				            } finally {
				                if (UA.Booking.Cart.currentCartTooltip != null) {
				                    UA.Booking.Cart.currentCartTooltip.destroy();
				                }
				                if ($(btn) != null) {
				                    $(btn).loader('destroy');
				                    $(btn).focus();
				                }
				                UA.Booking.Cart.refreshCart(e);
				                if ($('#divSelectSeat').length > 0) {
				                    UA.Booking.Cart.refreshSeatmap();
				                }
				                if (offerkey === "PET" && ($('#travelerInfoForm').length > 0 || $('#billingInfoForm').length > 0)) {
				                    var tag = $('#aHeaderSignIn'),
                                        redisplayData = tag.data('page-redisplay');
				                    UA.Common.Header.handleRedisplay(redisplayData);
				                }			                
				            }
				        }
				    });
			},
			refreshCart: function (e) {
			    this.refreshCartWithParameter(this.el.data('id'), this.el.data('href'))
			},
			refreshCartWithParameter: function (cartId, authUrl) {
				var load,
					_this = this;

				if (cartId === null) {
					return;
                }
                var totalAmountBeforeRefresh = $('.cart-section-total .number')[0].innerHTML;

				this.showCartLoader();
				
				var params = {
				        CartId: cartId,
				        ProductIds: this.getBundlesProductIds()
				};

				load = $.ajax({				    
					type: "POST",
					url: authUrl,
					contentType: "application/json; charset=utf-8",
					dataType: "html",
					data: JSON.stringify(params)
				});
				load.success(function (response) {
					_this.hideCartLoader();

					var data = $(response);
					var $cartContainer;
					var isShowRTCartEn = $('#showRTCart');
					if (isShowRTCartEn.length > 0) {
					    $('#reviewcartcontainer').length > 0
					    {
					        $('#reviewcartcontainer').html(response);
					    }
					    if (UA.Booking != null && UA.Booking.ReviewFlight != null) {
					        UA.Booking.ReviewFlight.updateBundleTotal();
					    }
				    }
					else {
					     $cartContainer = UA.Booking.Cart.el.parent().html(data);
					}				
				    UA.UI.reInit($cartContainer);

					_this.init(); //this only be called once. can cause multiple bindings

					UA.Booking.EditSearch.init();

					$(document).trigger("refreshOtherFops");

					_this.CheckOffersTandC($(data));
					if ($('#divSelectSeat').length > 0) {
					    $(".cart-section-remainingseats").hide();
					}
					var found = false;
					if ($cartContainer && nextFocusElement !== undefined) {
					    $cartContainer.find('div.grid-row').find('a[href]:not(.cart-remove)').each(function (i, obj) {
					        if (obj.className === $(nextFocusElement)[0].className)
					        {
					            $(obj).focus();
					            found = true;
					            return false;
					        }
					    });
					    if (found === false) {
					        $cartContainer.find('div.cart-section-total').attr("tabindex", "-1").focus();
					    }
					    nextFocusElement = undefined;
                    }

                    if ($('#tripTotal').length > 0) {
                        var newTotalAmount = $('.cart-section-total .number')[0].innerHTML;
                        if (newTotalAmount.length > 0) {
                            if (totalAmountBeforeRefresh != newTotalAmount) { 
                                var tripTotal = $('#tripTotal');
                                if (tripTotal.length > 0)
                                    tripTotal.html("Trip total " + newTotalAmount);
                            }
                        }
                    }
                    //null check
                    if (UA.Booking.Uplift) UA.Booking.Uplift.checkAndLoadUplift();
				    //1532949 - Flight booking :Seat Map displays EPLUS fee  for Gold + more than 1 companion
                    if (UA.Booking.SeatSelector) {
                        var pricingDetail = $('#seat-pricing-info').data('priced-pax');
                        if (pricingDetail && pricingDetail.Travelers)
                            UA.Booking.SeatSelector.resetComplimentarySeatPrices(pricingDetail.Travelers);
                    }
				});
				load.error(function (response) {
					_this.hideCartLoader();
				});
			},
			getBundlesProductIds: function () {
			    if (UA.Booking != null && UA.Booking.ReviewFlight != null) {
			        return UA.Booking.ReviewFlight.getSelectedProductIds();
			    }
			    return null;
			},
            refreshSeatmap: function () {
				var segment = parseInt($("#hdnSelectedId").val(), 10);
				$('.segment-list a[data-tab-key="' + segment + '"]').trigger('click');
			},
			setCurrencyConversionTooltip: function () {
				var _this = this;
				_this.initCurrencyConversionTooltip($("#InternationalFareCurrency").val(), $("#TotalFareAmount").val());
				$.when(_this.CurrencyConversionTooltip).done(function (response) {
					if (response != null) {
						_this.setCurrencyConversionTool(response);
					}
				}).fail(function () {
				});

				if ($("#showFareLoackCurrency").val() == "true") {
					_this.initCurrencyConversionTooltip($("#InternationalFareCurrency").val(), $("#TotalFareLockAmount").val());
					$.when(_this.CurrencyConversionTooltip).done(function (response) {
						if (response != null) {
							$("#farelock-tooltip-cart-msg  #farelockcurrency-conversion").html(response.currencyConversionFormattedStr);
			               
							if (response.totalfareamountstr != "") {
								$("#farelock-tooltip-cart-msg  #total-Fare-Amount").html(response.totalfareamountstr);
							}

							if (response.totalTargetPriceFormattedstr != "") {
								$("#farelock-tooltip-cart-msg  #valid-formatted-fare").html(response.totalTargetPriceFormattedstr);
							}
							//89312 
							$("#farelock-tooltip-cart-msg  #valid-date").text(response.validDate);
							$("#farelock-tooltip-cart-msg  #valid-time").text(response.validTime);

							$("#farelock-tooltip-cart-msg  #fare-typedescription").html($("#farelockTypeDescription").val());
						}
					}).fail(function () {
					});
 
				}

			},
			setCurrencyConversionTool: function(response) {
							if (response != null) {
								$("#currency-conversion").html(response.currencyConversionFormattedStr);

								if (response.totalfareamountstr != "") {
									$("#total-Fare-Amount").html(response.totalfareamountstr);
								}

								if (response.totalTargetPriceFormattedstr != "") {
									$("#valid-formatted-fare").html(response.totalTargetPriceFormattedstr);
								}
								//89312 
								$("#valid-date").text(response.validDate);
								$("#valid-time").text(response.validTime);

								$("#fare-typedescription").html($("#TypeDescription").val());
							}
            },
			initCurrencyConversionTooltip: function (targetCurrencyParam,totalFareAmountParam) {
				//TODO: need to check for True. now its coming false for every product in POS.
				var ret;
				if ($("#UsedMultipleCurrencies").val() == "True" && $("#InternationalFareCurrency").length > 0 && $("#InternationalFareCurrency").val() != "") {
					var params = {
						targetCurrency:  targetCurrencyParam,
						totalFareAmount: totalFareAmountParam,
						cartId: $('#bookingCart').data('id')
					};
					var currencyConversionUrl = $(".tip-cart-msg").data('url-currency-conversion');
					this.CurrencyConversionTooltip = $.ajax({
						url: currencyConversionUrl,
						type: 'POST',
						cache: false,
						data: params,
						dataType: 'json',
						success: function (response) {
							// return response;
							//if (response != null) {
							//	$("#currency-conversion").html(response.currencyConversionFormattedStr);

							//	if (response.totalfareamountstr != "") {
							//		$("#total-Fare-Amount").html(response.totalfareamountstr);
							//	}

							//	if (response.totalTargetPriceFormattedstr != "") {
							//		$("#valid-formatted-fare").html(response.totalTargetPriceFormattedstr);
							//	}
							//	//89312 
							//	$("#valid-date").text(response.validDate);
							//	$("#valid-time").text(response.validTime);

							//	$("#fare-typedescription").html($("#TypeDescription").val());
							//}
						}
					});
				}
			},
			bindEvents: function () {
				var $document = $(document),
					$cartContainer = $('.cart-container');

				$cartContainer.on('click', '#edit-search', $.proxy(this.showEditModal, this));
				$cartContainer.on('click', '.' + classTripChangeTrigger, $.proxy(this.changeTrip, this));
				$cartContainer.on('refresh', $.proxy(this.refreshCart, this));

				$document.on('click', '.cart-remove', this.removeFromCart);
				$document.on('click', '.cert-remove', this.removeCertFromCart);
				$document.on('click', '.coupon-remove', this.removeCouponFromCart);

                // These 4 classes are possible to have binding event handlers in FlightSearch.js
                if (UA.Booking.FlightSearch == null) {
				    $document.on('mouseenter', '.upgrade-eligible', $.proxy(this.handleUpgradeEligibleTooltip, this));
				    $document.on('mouseenter', '.upgrade-not-eligible', $.proxy(this.handleUpgradeNotEligibleTooltip, this));
				    $document.on('mouseenter', '.upgrade-available', $.proxy(this.handleUpgradeAvailableTooltip, this));
				    $document.on('mouseenter', '.upgrade-waitlist', $.proxy(this.handleUpgradeWaitlistTooltip, this));
                }
				$document.on('mouseenter', '.icon-tool-tip-cart-msg', $.proxy(this.handleCartMsgTooltip, this));
				$document.on('click', selectorPriceTooltipTrigger, $.proxy(this.handlePriceTooltip, this));
				$document.on('click', selectorTripTooltipTrigger, $.proxy(this.handleTripTooltip, this));

				$document.on('click', '.fare-breakdown-tooltip-trigger', $.proxy(this.handleFareBreakdownTooltip, this));
				$document.on('click', '.Surcharge-breakdown-tooltip-trigger', $.proxy(this.handleSurchargeBreakdownTooltip, this));
                $document.on('click', '.ETC-tooltip-trigger', $.proxy(this.handleETCTooltip, this));
                $document.on('click', '.travel-option-tooltip-trigger', $.proxy(this.handleTravelOptionTooltip, this));
                $document.on('click', '.tax-breakdown-tooltip-trigger', $.proxy(this.handleTaxBreakdownTooltip, this));
                $document.on('click', '.tax-refund-breakdown-tooltip-trigger', $.proxy(this.handleTaxRefundBreakdownTooltip, this));
				$document.on('click', '.apd-breakdown-tooltip-trigger', $.proxy(this.handleAPDBreakdownTooltip, this));
				$document.on('click', '.special-travel-fees-tooltip-trigger', $.proxy(this.handleSpecialTravelFeesTooltip, this));
				$document.on('click', '.basic-economy-restrictions-tooltip-trigger', $.proxy(this.handleBasicEconomyRestrictionsTooltip, this));		
			}
		};
	}());

	$(document).ready(function () {
		UA.Booking.Cart.init(true);
	});

}(jQuery));;
(function ($) {
    'use strict';
    UA.Utilities.namespace('UA.Common.SortDropdown');
    UA.Common.SortDropdown = (function () {

        function DropDownFSR(el) {

        }

        return {
            init: function (el, OnClickEventName) {

                this.dd = el;
                this.placeholder = this.dd.find('#dropdown-sel-text');
                this.opts = this.dd.find('ul.dropdownFSR > li');
                this.DisplayText = '';
                this.val = '';

                /*
                //When page is loaded set dropdown value to what was selected in earlier pages using local session
                var SortBy = JSON.parse(UA.Utilities.safeSessionStorage.getItem("SortBy"));

                if (this.dd.find('ul.dropdownFSR > li.tick a:first').length > 0) {
                    this.val = this.dd.find('ul.dropdownFSR > li.tick a:first')[0].id;

                    if (SortBy && (this.val != SortBy)) {
                        this.dd.find('ul.dropdownFSR > li').removeClass("tick");

                        this.dd.find('ul.dropdownFSR > li').find("#" + SortBy).parent("li").addClass("tick");
                        this.placeholder.text(this.dd.find('ul.dropdownFSR > li').find("#" + SortBy).text());
                    }
                }
                */
                this.index = -1;
               
                this.bindEvents();

                this.opts.on('click', OnClickEventName);
            },
            bindEvents: function () {

                var obj = this;

                obj.dd.on('click', function (event) {
                    $(this).toggleClass('active');

                    if ($(this).hasClass('active'))
                    {
                        $("#selAllOptions1").text($("#selAllOptions").text());
                    }
                    return false;
                });

                obj.dd.on('keypress', function (event) {
                    //event.stopPropagation();
                    if (event.which == 32) {
                        $(this).addClass('active');

                        if ($(this).hasClass('active')) {
                            $("#selAllOptions1").text($("#selAllOptions").text());
                        }
                    }
                    //return false;
                });

                obj.opts.on('click', function () {

                    obj.dd.find('ul.dropdownFSR > li').removeClass("tick");

                    var opt = $(this);
                    opt.addClass("tick");
                    if (opt.find("a").length > 0) {
                        obj.val = opt.find("a")[0].id;
                        obj.DisplayText = opt.find("a").text();
                    }
                    obj.placeholder.text(obj.DisplayText);
                    //$('.wrapper-dropdown-1').removeClass('active');
                    //console.log('Core part executed');
                });

            },
            getValue: function () {
                return this.val;
            },
            getIndex: function () {
                return this.index;
            },
            setValue: function (SortBy)
            {
                if (this.dd.find('ul.dropdownFSR > li.tick a:first').length > 0) {
                    this.val = this.dd.find('ul.dropdownFSR > li.tick a:first')[0].id;

                    if (SortBy && (this.val != SortBy)) {
                        this.dd.find('ul.dropdownFSR > li').removeClass("tick");

                        this.dd.find('ul.dropdownFSR > li').find("#" + SortBy).parent("li").addClass("tick");
                        var sortByVal = this.dd.find('ul.dropdownFSR > li').find("#" + SortBy).attr("id");
                        if (!sortByVal)
                        {
                            this.placeholder.text($('#dropdownCustomText').val());
                        }
                        else {
                            this.placeholder.text(this.dd.find('ul.dropdownFSR > li').find("#" + SortBy).text());
                        }
                        
                    }
                }
            }
        };

    }());

    //$(document).ready(function () {
    //    UA.Common.SortDropdown.init();
    //});

}(jQuery));;
/**
  stickybits - Stickybits is a lightweight alternative to `position: sticky` polyfills
  @version v3.6.5
  @link https://github.com/dollarshaveclub/stickybits#readme
  @author Jeff Wainwright <yowainwright@gmail.com> (https://jeffry.in)
  @license MIT
**/
!function(t,s){"object"==typeof exports&&"undefined"!=typeof module?module.exports=s():"function"==typeof define&&define.amd?define(s):(t=t||self).stickybits=s()}(this,function(){"use strict";var e=function(){function t(t,s){var e=void 0!==s?s:{};this.version="3.6.5",this.userAgent=window.navigator.userAgent||"no `userAgent` provided by the browser",this.props={customStickyChangeNumber:e.customStickyChangeNumber||null,noStyles:e.noStyles||!1,stickyBitStickyOffset:e.stickyBitStickyOffset||0,parentClass:e.parentClass||"js-stickybit-parent",scrollEl:"string"==typeof e.scrollEl?document.querySelector(e.scrollEl):e.scrollEl||window,stickyClass:e.stickyClass||"js-is-sticky",stuckClass:e.stuckClass||"js-is-stuck",stickyChangeClass:e.stickyChangeClass||"js-is-sticky--change",useStickyClasses:e.useStickyClasses||!1,useFixed:e.useFixed||!1,useGetBoundingClientRect:e.useGetBoundingClientRect||!1,verticalPosition:e.verticalPosition||"top"},this.props.positionVal=this.definePosition()||"fixed",this.instances=[];var i=this.props,n=i.positionVal,o=i.verticalPosition,r=i.noStyles,a=i.stickyBitStickyOffset,l=i.useStickyClasses,c="top"!==o||r?"":a+"px",u="fixed"!==n?n:"";this.els="string"==typeof t?document.querySelectorAll(t):t,"length"in this.els||(this.els=[this.els]);for(var f=0;f<this.els.length;f++){var p=this.els[f];p.style[o]=c,p.style.position=u,("fixed"===n||l)&&this.instances.push(this.addInstance(p,this.props))}}var s=t.prototype;return s.definePosition=function(){var t;if(this.props.useFixed)t="fixed";else{for(var s=["","-o-","-webkit-","-moz-","-ms-"],e=document.head.style,i=0;i<s.length;i+=1)e.position=s[i]+"sticky";t=e.position?e.position:"fixed",e.position=""}return t},s.addInstance=function(t,s){var e=this,i={el:t,parent:t.parentNode,props:s};this.isWin=this.props.scrollEl===window;var n=this.isWin?window:this.getClosestParent(i.el,i.props.scrollEl);return this.computeScrollOffsets(i),i.parent.className+=" "+s.parentClass,i.state="default",i.stateContainer=function(){return e.manageState(i)},n.addEventListener("scroll",i.stateContainer),i},s.getClosestParent=function(t,s){var e=s,i=t;if(i.parentElement===e)return e;for(;i.parentElement!==e;)i=i.parentElement;return e},s.getTopPosition=function(t){if(this.props.useGetBoundingClientRect)return t.getBoundingClientRect().top+(this.props.scrollEl.pageYOffset||document.documentElement.scrollTop);for(var s=0;s=t.offsetTop+s,t=t.offsetParent;);return s},s.computeScrollOffsets=function(t){var s=t,e=s.props,i=s.el,n=s.parent,o=!this.isWin&&"fixed"===e.positionVal,r="bottom"!==e.verticalPosition,a=o?this.getTopPosition(e.scrollEl):0,l=o?this.getTopPosition(n)-a:this.getTopPosition(n),c=null!==e.customStickyChangeNumber?e.customStickyChangeNumber:i.offsetHeight,u=l+n.offsetHeight;s.offset=a+e.stickyBitStickyOffset,s.stickyStart=r?l-s.offset:0,s.stickyChange=s.stickyStart+c,s.stickyStop=r?u-(i.offsetHeight+s.offset):u-window.innerHeight},s.toggleClasses=function(t,s,e){var i=t,n=i.className.split(" ");e&&-1===n.indexOf(e)&&n.push(e);var o=n.indexOf(s);-1!==o&&n.splice(o,1),i.className=n.join(" ")},s.manageState=function(t){var s=t,e=s.el,i=s.props,n=s.state,o=s.stickyStart,r=s.stickyChange,a=s.stickyStop,l=e.style,c=i.noStyles,u=i.positionVal,f=i.scrollEl,p=i.stickyClass,h=i.stickyChangeClass,d=i.stuckClass,y=i.verticalPosition,k="bottom"!==y,m=function(t){t()},g=this.isWin&&(window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame)||m,v=this.toggleClasses,C=this.isWin?window.scrollY||window.pageYOffset:f.scrollTop,S=k&&C<=o&&("sticky"===n||"stuck"===n),w=a<=C&&"sticky"===n;o<C&&C<a&&("default"===n||"stuck"===n)?(s.state="sticky",g(function(){v(e,d,p),l.position=u,c||(l.bottom="",l[y]=i.stickyBitStickyOffset+"px")})):S?(s.state="default",g(function(){v(e,p),v(e,d),"fixed"===u&&(l.position="")})):w&&(s.state="stuck",g(function(){v(e,p,d),"fixed"!==u||c||(l.top="",l.bottom="0",l.position="absolute")}));var b=r<=C&&C<=a;C<r/2||a<C?g(function(){v(e,h)}):b&&g(function(){v(e,"stub",h)})},s.update=function(t){void 0===t&&(t=null);for(var s=0;s<this.instances.length;s+=1){var e=this.instances[s];if(this.computeScrollOffsets(e),t)for(var i in t)e.props[i]=t[i]}return this},s.removeInstance=function(t){var s=t.el,e=t.props,i=this.toggleClasses;s.style.position="",s.style[e.verticalPosition]="",i(s,e.stickyClass),i(s,e.stuckClass),i(s.parentNode,e.parentClass)},s.cleanup=function(){for(var t=0;t<this.instances.length;t+=1){var s=this.instances[t];s.props.scrollEl.removeEventListener("scroll",s.stateContainer),this.removeInstance(s)}this.manageState=!1,this.instances=[]},t}();return function(t,s){return new e(t,s)}});
;
