/* Minification of JavaScript failed:
(4153,37-38): run-time error JS1100: Expected ',': =
 */
var frigidaire = (function () {
  var html = $('html'),
        ie = html.hasClass('ie'),
        ie7 = html.hasClass('ie7'),
        ie8 = html.hasClass('ie8'),
        ie9 = html.hasClass('ie9'),
        mobileView = function () { return !!($(window).width() <= 640) || $('html').hasClass('force-mobile', 'ipad'); },
        device = function () {
            var width = $(window).width(),
                deviceClass = width > 1024 ? 'desktop' : width > 640 ? 'tablet' : width < 641 ? 'mobile' : '',
                orientClass = width > 768 && width < 1025 ? 'landscape' : width > 640 && width <= 768 ? 'portrait' : width > 1089 ? 'extrawide' : '';
            $('html').removeClass('js desktop mobile tablet landscape portrait extrawide').addClass('js ' + deviceClass + ' ' + orientClass);
        },
        origView = mobileView(),
        checkMobileDevice = function () { if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/android/i))) { return true; } return false; },
        isMobileDevice = checkMobileDevice(),
        lang = function () { return $('html').attr('lang'); },
        localizedAddressForm = function () { return '/Content/MustacheTemplates/AddressForm_' + $('html').attr('lang') + '.html' };

    // Utility functions
    var util = {
        distance: function (start, end) {
            var distanceX = start.left - end.left, // horizontal
                distanceY = start.top - end.top, // vertical
                distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY); // Pythagoras theorem
            return distance / 1.5;
        },

        stylizeForm: function (method, selector) {
            console.log('stylize it');
            if (method === 'update') {
                $(selector).uniform.update();
            }
        },

        parseUnobtrusiveValidation: function ($el) {
            console.log('parseUnobtrusiveValidation() proxy');
            $.validator.unobtrusive.parse($el);
            $el.data("validator").settings.ignore = "";
        },

        getUrlVars: function () {
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
                console.log('hash [] = ' + hash);
            }
            return vars;
        },

        parseErr: function (err, $targets, method) {
            for (var i = $targets.length; 0 < i--;) {
                $targets.eq(i).trigger(method + 'Error').next('.mtContent').removeClass('mLoading');
            }
            console.error('%cSOMETHING WENT WRONG! Status code: %d - Status message: %s', 'background:red;color:#fff;', err.status, err.statusText);
        },

        newsLetterSignup: function () {
            $.removeCookie('@Model.NewsletterSignupCookieName', { path: '/' });
            var NewsletterCB = document.getElementById('NewsletterCB');
            $(NewsletterCB).on('change.NewsletterCheck', function () {
                var NewsletterVal = (NewsletterCB === null ? false : NewsletterCB.checked);
                $.cookie('@Model.NewsletterSignupCookieName', NewsletterVal, { path: '/' });
            });
        },

        formatCurrency: function (num) {
            return currency(num, {
                decimal: frigidaire.lang() === "fr-ca" ? ',' : '.',
                separator: frigidaire.lang() === "fr-ca" ? '.' : ',',
                pattern: frigidaire.lang() === "fr-ca" ? '# !' : '!#',
                formatWithSymbol: true
            }).format();
        }
    }

    function init() {
        if (typeof console === "undefined") { this.console = { log: function () { } }; }
        setHtmlTag();
        onPageResize();
        //subMenus();
        global();
        deviceChange();
        headerPanel();
        categoryLanding();
        productDetailPage();
        productListPage();
        mobileResize();
        pageTools();
        ownersCenter();
        timeline();
        energySavings();
        sortFunction();
        searchResultsHashReader();
        testimonials();
        accordionTechnologyTM();
        worksWellWith();
        PDPScrollToSpecs();
        faqPage();
        expandCollapseVideo();
        yaToolTip();
        bubbleModal();
        myAccount();
        acMobile();
        createAccount();
        mainNavTabs();
        friTabs();
        searchResults();
        carousel();
        jqueryEasing();
        quizSlider();
        if ($('.jsTooltip').length) { toolTips(); }
        if (!isMobileDevice) {
            var lastWindowHeight = $(window).height(), lastWindowWidth = $(window).width();
            $(window).on('resize.checkViewport', $.throttle(75, function () {
                if ($(window).height() !== lastWindowHeight || $(window).width() !== lastWindowWidth) {
                    lastWindowHeight = $(window).height();
                    lastWindowWidth = $(window).width();
                    setHtmlTag();
                    onPageResize();
                }
            }));
        }
        $(window).on('orientationchange', function () {
            $(window).one('resize', function () {
                setHtmlTag();
                onPageResize();
            });
        });
        $(window).on('resize', function () {
            setHtmlTag();
        });


        //adding a cookie to show the shipping banner at the top of the page...
        if (typeof $.cookie('freeShippingBanner') === 'undefined') {
            $.cookie('freeShippingBanner', 'showBannerTrue', { path: '/' });
        }

        if ($('.product-detail').length && !$('.owners-detail').length && !($('.product-detail').length || $('#pl').length)) {
            $('.product-detail').addClass('productInStock');
        }

        if (frigidaire.lang() === 'en-us') {
            $('.stockLabel').fadeIn(350);
        }

    }

    function jqueryEasing() {
        jQuery.easing.sin = function (p, n, firstNum, diff) {
            return Math.sin(p * Math.PI / 2) * diff + firstNum;
        };
        jQuery.easing.cos = function (p, n, firstNum, diff) {
            return firstNum + diff - Math.cos(p * Math.PI / 2) * diff;
        };
    }

    function checkImage(image) {
        var $selector = image,
            $selectorLength = $selector.length;

        for (i = 0; i < $selectorLength; i++) {
            $($selector[i]).on('error.checkImage', function (e) {
                var $this = $(this);
                var imageType = ($this[0].hasAttribute('data-check-image') ? $this[0].data('check-image') : ""),
                    langType = (frigidaire.lang() === "fr-ca" ? "fr" : "en"),
                    imgErrorImagePath = '/Content/Images/imgError' + imageType + '_' + langType + '.png';
                $($this).attr('src', imgErrorImagePath);
            });
        }
    }

    function sizeConfettiBanner() {
        // Get the confetti banner showing up correctly for air fry day
        // Ideally, refactor the frigidaire-primary-banner
        var hero = $('#confetti-banner-hero'),
            desktopHero = $('.desktop #confetti-banner-hero'),
            tabletHero = $('.tablet #confetti-banner-hero'),
            mobileHero = $('.mobile #confetti-banner-hero');

        if (desktopHero.length) {
            hero.height('unset');
        } else if (tabletHero.length) {
            hero.height(hero.find('.frigidaire-primary-banner__video--desktop').height());
        } else if (mobileHero.length) {
            hero.height(hero.find('.frigidaire-primary-banner__video--mobile video').height());
        } else {
            return;
        }
    }

    function carousel() {
        if (!$('.carouselOuterWrapper').length) return;

        $('img').imagesLoaded(function () {
            var carouselOuterWrapper = $('.carouselOuterWrapper'),
                numOfCarousels = $('.carouselSibling').length;

            if (numOfCarousels > 1) {
                $('.carouselSibling').each(function () {
                    $(this).parent().addClass('grid-' + numOfCarousels.toString() + '-col');
                });
            }

            var cOuterWrapper = $('.carouselWrapper:visible');

            cOuterWrapper.each(function () {
                if (!$(this).is(':visible')) return;

                //if only one slide, then don't show the carousel.

                var $thisCarousel = $(this),
                    itemsToShow,
                    cOffset;

                if ($thisCarousel.is('[class*="show-"]')) {
                    itemsToShow = $thisCarousel.attr('class').split('show-')[1].split(' ')[0],
                        cOffset = 100 / itemsToShow;
                } else {
                    itemsToShow = (frigidaire.mobileView() ? 1 : ($('.carouselSibling').is(':visible') ? 2 : 3)),
                        cOffset = 100 / itemsToShow;
                    $thisCarousel.addClass('show-' + itemsToShow.toString());
                }

                //add nav items before and after the carousel...
                if (!$(this).siblings().hasClass('carouselNavigation')) {
                    $('<a href="#" class="carouselNavigation goLeft"><span class="vAlignContainer"><div class="icon-left-open-1"></div></span></a>').prependTo($(this).parent());
                    $('<a href="#" class="carouselNavigation goRight"><span class="vAlignContainer"><div class="icon-right-open-1"></div></span></a>').appendTo($(this).parent());
                }

                var $thisContainer = $(this),
                    cWrapper = $thisContainer.find('.carousel'),
                    cCells = cWrapper.find('li'),
                    carouselNav = $thisContainer.siblings('.carouselNavigation'),
                    cellWidth = cWrapper.find('li').eq('0').width(),
                    isAnimating = false,
                    totalCells = cCells.length,
                    isInitialized = ($thisContainer.is('.initialized') ? true : false);

                if (isInitialized) {
                    return;
                } else {
                    $thisContainer.addClass('initialized');
                }

                console.log('totalCells:', totalCells);
                console.log('itemsToShow:', itemsToShow);

                if (totalCells <= itemsToShow) {
                    cWrapper.addClass('lessThanMinimum');

                } else {
                    carouselNav.show();
                    //put them in order starting with the first one on the left...
                    cWrapper.find('li').last().insertBefore(cWrapper.find('li').eq(0));
                    cWrapper.find('li').eq(2).addClass('active selected');
                }

                carouselNav.off('click').on('click', function (e) {
                    e.preventDefault();

                    if (isAnimating) return;
                    isAnimating = true;

                    var $this = $(this),
                        direction = ($this.hasClass('goLeft') ? 'right' : 'left'),
                        goThisWay = (direction === 'left') ? cWrapper.position().left - cellWidth : cWrapper.position().left + cellWidth,
                        curr = cWrapper.find('.active'),
                        myClone;

                    if (direction === 'left') {
                        myClone = $thisContainer.find('.carousel li:first').clone().insertAfter($thisContainer.find('.carousel li:last')); //go right
                        curr.removeClass('active').next('li').addClass('active').trigger('click'); //go left
                    } else {
                        curr.removeClass('active').prev('li').addClass('active').trigger('click'); //go right
                    }

                    $thisContainer.find('.carousel:not(:animated)').animate({
                        left: goThisWay
                    }, 500, 'easeOutCubic', function () {
                        if (direction === 'left') {
                            $thisContainer.find('.carousel li:last').after($thisContainer.find('.carousel li:first')); //go left
                            myClone.remove();
                        } else {
                            $thisContainer.find('.carousel li:first').before($thisContainer.find('.carousel li:last')); //go right
                        }
                        $thisContainer.find('.carousel').css({ left: '-' + cOffset + '%' });
                        isAnimating = false;
                    });
                });
            });
        });

    }

    function searchResults() {
        if (!$('.tabSet').length) return;

        $('.tabSet a').off('click').on('click', function () {
            sendTracking('search', 'click_search_nav', $(this).text());
        });

        //tracking when submitting search results page search form
        $(".serp_search").submit(function (e) {
            e.preventDefault();
            var $this = $(this),
                form = this;

            if (!$this.hasClass('submitting')) {
                sendTracking('search', 'click_search', $this.find('.search_input').val());
                $this.addClass('submitting');
            }
            setTimeout(function () {
                form.submit();
            }, 200);
        });
    }

    function sanitizeErrorObject(obj, form) {
        var inputs = $(form).find('[name]'),
            names = [];

        for (var i = inputs.length; 0 < i--;) { // save element names as array
            names.push(inputs.eq(i).attr('name'));
        }
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                if ($.inArray(key, names) === -1) {
                    delete obj[key];
                }
            }
        }
        return obj;
    }
    function quizSlider() {

        $(window).load(function () {
            $('#quizapp').removeClass('hidden');
        });

        var $slider = $('.carousel-inner');
        $slider.slick({
            dots: false,
            infinite: false,
            accesibility: false,
            draggable: false,
            swipe: false,
            touchMove: false,
            prevArrow: false,
            nextArrow: false
        });

        $(".rac-quiz-hero .btn-nopreference").click(function () {
            $(this).parent().parent().find(">a").each(function () {
                $(this).removeClass('selected');
            });
            var slick = $slider.slick('getSlick');
            var curSlide = slick.slideCount === slick.currentSlide ? 0 : slick.currentSlide + 1;
            $slider.slick('slickGoTo', curSlide, false);

            showActiveSlide(curSlide);

        });
        $(".rac-quiz-hero .btn-back").click(function () {
            var slick = $slider.slick('getSlick');
            var curSlide = slick.slideCount === slick.currentSlide ? 0 : slick.currentSlide - 1;
            $slider.slick('slickGoTo', curSlide, false);

            showActiveSlide(curSlide);

        });
        $(".rac-quiz-hero .rac-hero-card-container.select-options  a").click(function () {
            var $this = $(this);
            $this.parent().find(">a").each(function () {
                $(this).removeClass('selected');
            });
            if ($this.hasClass('selected')) {
                $this.removeClass('selected');
            } else {
                $this.addClass('selected');
            }
            var slick = $slider.slick('getSlick');
            var curSlide = slick.slideCount === slick.currentSlide ? 0 : slick.currentSlide + 1;
            $slider.slick('slickGoTo', curSlide, false);

            showActiveSlide(curSlide);
        });
        $(".rac-quiz-hero .rac-hero-card-container.multiselect-options  a").click(function () {
            var $this = $(this);
            if ($this.hasClass('selected')) {
                $this.removeClass('selected');
            } else {
                $this.addClass('selected');
            }
        });

        $(".start-quiz-over").click(function () {
            $(this).closest(".carousel-inner").slick('slickGoTo', 0, false);
        });
    };

    function showActiveSlide(curSlide) {
        var mobileScreenSize = 769;

        if ($(window).width() < mobileScreenSize) {
            $('.rac-quiz-hero').find('.rac-hero').each(function () {
                $(this).css('height', '0');
            });
            var d = $('.rac-quiz-hero').find('.rac-hero')[curSlide];
            $(d).css('height', 'auto');

            var totalSlideCount = $('.rac-quiz-hero').find('.rac-hero').length;
            var resultDiv = $('.rac-quiz-hero').find('.rac-hero')[totalSlideCount - 1];
            $(resultDiv).css('height', 'auto');
        }
    }

    //Main Nav Tabs-- Remove Line Under
    function mainNavTabs() {
        if (frigidaire.mobileView()) {
            $('.plp-title').removeClass('active');
        };
    };

    function friTabs() {
        if (!$('.friTabs').length) return;

        var $tabWrapper = $('.friTabs'),
            $tabs = $tabWrapper.find('> * > li > *'),
            $tabContentWrapper = $tabWrapper.find('>div'),
            $tabContent = $tabContentWrapper.find('>div'),
            realClick = true,
            $friTabsVertHeight;

        $(window).on('hashchange', function (e) {
            realClick = false;
            console.log('hash changed');
            if (location.hash != '') {
                tabAdjuster($('[href=' + location.hash + ']'));
            }
            realClick = true;
        });

        if (frigidaire.mobileView()) {
            $('img').imagesLoaded(function () {
                $friTabsVertHeight = $('.friTabs > *:eq(0)').offset().top - 145;
            });
        }

        if ($tabs.length === 1) {
            if (mobileView()) {
                $tabWrapper.find('>ol').hide();
                return;
            }
        }

        if ($('html').hasClass('ie8') || $('html').hasClass('ie7')) {
            $('.friTabs article > div > div:nth-child(3n+1)').addClass('clear-left');
        }

        $tabs.css({ 'display': 'block' });

        $tabs.off('click.tabs').on('click.tabs', function (e) {
            e.preventDefault();
            var dom = $(this).attr('href'),
                bump = ($('.header-container').is('.fixedHeader') ? 0 : 60);

            //if has anchor on scroll then
            if ($('.proco-landing').length) {
                $('body,html').animate({
                    scrollTop: $(dom).offset().top - $('.anchor-on-scroll').outerHeight() - $('.header-container').outerHeight() + bump
                }, 350);
            } else {
                $('body,html').animate({
                    scrollTop: $(this).parents('.friTabs').offset().top - 60 - ($('.header-container .navNotification:visible').outerHeight() != 'null' ? $('.header-container .navNotification:visible').outerHeight() : 0)
                }, 350);
            }

            if (realClick) {
                history.pushState(null, null, $(this).attr('href'));
            }

            tabAdjuster($(this));
        });

        function tabAdjuster($el) {
            var $this = $el,
                $tabID = $this.attr('href'),
                $tabIDheight = $($tabID).outerHeight(),
                $tabIndex = $this.parents('li').index() + 1,
                $tabName = $($tabID).attr('id');

            $tabContentWrapper.animate({
                height: $tabIDheight
            }, 200, function () {
                $tabContentWrapper.css({
                    height: 'auto'
                });
            });

            $tabs.removeClass('active');
            $this.addClass('active');
            $tabContent.removeClass('active');
            $($tabID).addClass('active');
        }

        $('img').imagesLoaded(function () {
            if (location.hash != '') { //hash exists
                var selectedTab = $('[href=' + location.hash + ']');
            } else { //no hash
                var selectedTab = ($('.friTabs').find('> * > li > *.active').length) ? $('.friTabs').find('> * > li > *.active') : $('.friTabs').find('> * > li:eq(0) > *');
            }

            //if none are active, then force the first one selected...
            if (!$('.friTabs').find('> * > li > *.active').length) {
                selectedTab.addClass('active');
            }

            tabAdjuster(selectedTab);
        });
    }

    function createAccount() {
        if ($('.registrationForm').length) {
            $('.registrationForm > form').addClass('jsUpdateAddress');
        }
    }

    function populateAddress() {
        //Populate address forms that have "populateAddress" id in the dom. (ex: Product Registration and Contact Us pages)
        //Check to see if the user has any 'isDefault = true' addresses
        //Store only the isDefault address
        //Loop through the form fields and populate them.

        $.ajax({
            url: '/api/myaccount/get',
            type: 'GET',
            success: function (data) {
                var addresses = data.User.Addresses,
                    email = data.User.Email,
                    defaultAddress = null,
                    formContainer = $('#populateAddress');

                var defaultAddress = function () {
                    for (var key in addresses) {
                        if (addresses.hasOwnProperty(key) && addresses[key] !== null) {
                            if (addresses[key].isDefault === true) {
                                //console.log(addresses[key]);
                                var defaultAddress = addresses[key];
                                return defaultAddress;
                            }
                        }
                    }
                }

                $.when(defaultAddress).done(function () {
                    console.log("defaultAddress:", defaultAddress());
                    var address = defaultAddress() || {},
                        state = address && address.StateName ? address.StateName : '';

                    //To handle Product Registration form which names Address Line 1 and Line 2 differently then the key that comes from /api/myaccount.
                    address.Email = email,
                        address.VerifyEmail = email,
                        address.AddressLine1 = address.Line1,
                        address.AddressLine2 = address.Line2,
                        address.PhoneNumber = address.Phone,
                        address.ZipCode = address.PostalCode;

                    for (var key in address) {
                        var el = formContainer.find('[name=' + key + ']');

                        if (!address[key]) {
                            continue
                        }

                        el.val(address[key]);
                        el.parent().find(".usePlaceholder").addClass("labelPlaceholder");
                    }

                    //handle state field differently because Lyris contains different values:
                    if (document.getElementById('State')) {
                        $('#State option:contains(' + state + ')').prop({ selected: true });
                        //reinit selects
                        if (frigidaire.mobileView()) {
                            $('#State').uniform();
                        } else {
                            $('#State').selectmenu();
                        }

                    }

                });

            }
        });
    }

    function myAccount() {
        if (!$('.ma-orders').length) return;

        $('.toggle-arrow-link').off('click').on('click', function (e) {
            e.preventDefault();
            var $this = $(this);

            if (!$this.hasClass('active')) {
                $this.addClass('active');
                $this.removeClass('form-right-arrow').addClass('form-down-arrow');
                $this.text($this.data('toggle-text'));
                $this.parents('li').find('.myOrdersItemsWrapper').slideDown();
            } else {
                $this.removeClass('active');
                $this.parents('li').find('.myOrdersItemsWrapper').slideUp(function () {
                    $this.removeClass('form-down-arrow').addClass('form-right-arrow');
                    $this.text($this.data('default-text'));
                });

            }
        });

        $('.hide-order-details').off('click').on('click', function (e) {
            e.preventDefault();
            var $this = $(this);
            $this.parents('li').find('.toggle-arrow-link').trigger('click');
        });

        //execute dom ajax on page load: example - myfrigidaire panel on my account page.
        if (document.querySelector('[data-api-url]') !== null) {
            var dataApiUrl = $('[data-api-url]');

            for (i = 0; i < dataApiUrl.length; i++) {
                var $this = $(dataApiUrl[i]),
                    $target = $this.attr('class');

                $this.next('.mtContent').addClass('mLoading');

                $.ajax({
                    url: $this.data('api-url'),
                    type: 'GET',
                    headers: {
                        'accept-language': frigidaire.lang()
                    },
                    data: $this.data('api-params'),
                    success: function (data) {
                        cartApi.parseData(data, $('.' + $target), $target);
                        frigidaire.accordionTechnologyTM();
                    },
                    error: function (err) {
                        console.log('%cError...', 'background:red;color:white;', err);
                    }
                });
            }
        }

        $(document).on('submit.jsResendVerification', '#jsResendVerification', function (e) {
            e.preventDefault();
            var $this = $(this),
                $button = $this.find('.button');

            $button.addClass('mLoading');
            $button.attr('disabled', '');

            //hardcoding success for now till backend is done:
            console.log('resend verification email...', $this.serializeObject());

            //once backend is done, fill in api and method here: (outputs to: /api/ApiGoesHere/MethodGoesHere)
            frigidaire.ajaxService('MyAccount', 'VerifyEmail', 'GET', $this.serializeObject(), function (data) {
                $button.text(data.Message);
                $button.removeClass('mLoading');
            });

        });
    }

    function acMobile() {
        if (!$('.mobileAcWrapper').length) return;

        var acBtnWrapper = $('.acBtnWrapper'),
            acBtn = acBtnWrapper.find('> div'),
            acNestedBtn = $('.acNestedWrapper > div'),
            acClear = $('.acClear'),
            acStep1 = $('.acStep1'),
            acStep2 = $('.acStep2'),
            acStartBtn = $('.acStartBtn'),
            acCalculate = $('.acCalculate'),
            acResultListWrapper = $('.acResultListWrapper'),
            arrayList = ['windowMountedIds', 'builtInIds', 'portableIds', 'plugType515PIds', 'plugType615PIds', 'plugType620PIds', 'plugType630PIds', 'roomSize150Ids', 'roomSize350Ids', 'roomSize500Ids', 'roomSize640Ids', 'roomSize900Ids', 'roomSize1170Ids'],
            fullArray = roomSize150Ids,
            $acChosen,
            $acLast,
            acResultList = [],
            roomOverlayItem = $('.roomOverlay > div > div'),
            closeOverlay = $('.closeOverlay'),
            acType = [],
            acKitchen = false,
            acPower = [],
            acSize = [];

        if (window.location.search) {
            acStep1.hide();
            acStep2.hide();
        }

        acBtn.off('click').on('click', function (e) {
            //console.clear();
            e.preventDefault();
            var currentlySelected = [];
            if ($(this).hasClass('disabled')) return;
            $('[data-arrayid]').removeClass('disabled');
            currentElement = $(this).data('arrayid'); // needs to be global...
            var thisArray = window[currentElement],
                selected = $(this).hasClass('selected'),
                allSelectedArrays = [],
                uniqueSkus = [],
                similarOnes = [];

            if ($(this).parent().hasClass('acType')) {
                if (!$(this).hasClass('selected')) {
                    acType = thisArray;
                    $(this).siblings().removeClass('selected');
                    $(this).addClass('selected');
                    $(this).parent().prev('h2.error').removeClass('error');
                    $('.acViewAllAcTypes').attr('href', $(this).data('listpageurl'));
                    $('.acViewAllAcTypes span').text($(this).text());
                }
                else {
                    $(this).removeClass('selected');
                    acType = [];
                }
            }

            if ($(this).parent().hasClass('acKitchen')) {
                if (!$(this).hasClass('active')) {
                    acKitchen = $(this).data('arrayid');
                    $(this).siblings().removeClass('active');
                    $(this).addClass('active');
                    $(this).parent().prev('h2.error').removeClass('error');
                }
                else {
                    $(this).removeClass('active');
                    acKitchen = $(this).data('arrayid');
                }
                // check if we already have size array, if so modify with the newly correct one
                if (!!acSize.length) {
                    acSize = []; // remove values
                    selectedElement = $('.roomOverlay .selected').data('arrayid'); // find currently selected room size
                    //console.log(selectedElement);
                    acSize = (acKitchen) ? window[selectedElement + 'Kitchen'] : window[selectedElement];
                }
            }

            if ($(this).parent().hasClass('acPower')) {
                if (!$(this).hasClass('selected')) {
                    acPower = thisArray;
                    $(this).siblings().removeClass('selected');
                    $(this).addClass('selected');
                    $(this).parent().prev('h2.error').removeClass('error');
                }
                else {
                    $(this).removeClass('selected');
                    acPower = [];
                }
            }


            if ($(this).parent().hasClass('acSizeSml')) {

                if (!$(this).hasClass('selected')) {
                    acSize = (acKitchen) ? window[currentElement + 'Kitchen'] : thisArray;
                    //console.log('inside here');
                    $('.roomOverlay .selected').removeClass('selected');
                    $(this).addClass('selected');
                    $('.acNestedWrapper').prev('h2.error').removeClass('error');
                    var acOverlayNameSml = $(this).find('.acOverlayName').text();
                    $('[data-arrayid="acSmallSize"] .acName').text(acOverlayNameSml);
                    acNestedBtn.removeClass('selectedCat');
                    $('[data-arrayid="acSmallSize"]').addClass('selectedCat');
                }
                else {
                    $(this).removeClass('selected');
                    acSize = [];
                    $('[data-arrayid="acSmallSize"]').removeClass('selectedCat');
                }
            }

            if ($(this).parent().hasClass('acSizeMed')) {
                if (!$(this).hasClass('selected')) {
                    acSize = (acKitchen) ? window[currentElement + 'Kitchen'] : thisArray;
                    $('.roomOverlay .selected').removeClass('selected');
                    $(this).addClass('selected');
                    $('.acNestedWrapper').prev('h2.error').removeClass('error');
                    var acOverlayNameMed = $(this).find('.acOverlayName').text();
                    $('[data-arrayid="acMediumSize"] .acName').text(acOverlayNameMed);
                    acNestedBtn.removeClass('selectedCat');
                    $('[data-arrayid="acMediumSize"]').addClass('selectedCat');
                }
                else {
                    $(this).removeClass('selected');
                    acSize = [];
                    $('[data-arrayid="acMediumSize"]').removeClass('selectedCat');
                }
            }

            if ($(this).parent().hasClass('acSizeLrg')) {
                if (!$(this).hasClass('selected')) {
                    acSize = (acKitchen) ? window[currentElement + 'Kitchen'] : thisArray;
                    $('.roomOverlay .selected').removeClass('selected');
                    $(this).addClass('selected');
                    $('.acNestedWrapper').prev('h2.error').removeClass('error');
                    var acOverlayNameLrg = $(this).find('.acOverlayName').text();
                    $('[data-arrayid="acLargeSize"] .acName').text(acOverlayNameLrg);
                    acNestedBtn.removeClass('selectedCat');
                    $('[data-arrayid="acLargeSize"]').addClass('selectedCat');

                }
                else {
                    $(this).removeClass('selected');
                    acSize = [];
                    $('[data-arrayid="acLargeSize"]').removeClass('selectedCat');
                }
            }

            //console.log(acSizeSml,'//////////////////////////////////////');

            allSelectedArrays = allSelectedArrays.concat(acType, acPower, acSize);

            $.each(allSelectedArrays, function (i, el) {
                if ($.inArray(el, uniqueSkus) === -1) uniqueSkus.push(el);
            });

            function getOccurences(sku) {
                return $.grep(allSelectedArrays, function (elem) {
                    return elem === sku;
                }).length;
            }

            for (var i = allSelectedArrays.length; 0 <= --i;) {
                if (getOccurences(allSelectedArrays[i]) === $('.selected').length) {
                    if ($.inArray(allSelectedArrays[i], currentlySelected) === -1) currentlySelected.push(allSelectedArrays[i]);
                }
            }
            acResultList = (!!$('.selected').length) ? currentlySelected : fullArray;

            //console.clear();
            //console.log('allSelectedArrays', allSelectedArrays);
            //console.log('clicked acType: ' + acType);
            //console.log('clicked acKitchen: ' + acKitchen);
            //console.log('clicked acPower: ' + acPower);
            //console.log('clicked acSize: ' + acSize);
            //console.log('/////////////////////////////////////////////////////////');
            //console.log('Real list to send:', acResultList);
            //console.log('Real list to send (COMMA):', acResultList.join(","));

            $.each(arrayList, function (key, value) {
                var currArray = (acKitchen && value.indexOf('roomSize') !== -1) ? value + 'Kitchen' : value, // again, needs to be global
                    doesExist = 0;
                $.each(acResultList, function (key, value) {
                    if ($.inArray(value, window[currArray]) !== -1) {
                        doesExist++;
                    }
                });
                if (currArray.indexOf('Kitchen') !== -1) {
                    currArray = currArray.substring(0, currArray.indexOf('Kitchen'));
                }
                if (!!doesExist) {
                    //console.log('Existing Products: ', currArray);
                    $('[data-arrayid=' + currArray + ']').removeClass('disabled');
                } else {
                    //console.log('No products in this array: ', currArray);
                    $('[data-arrayid=' + currArray + ']').addClass('disabled');

                    if ($('.acStep2').find('.selected, .selectedCat').length === 1) {
                        $('.selected').siblings().removeClass('disabled');
                    }

                    if ($('.acSizeSml > div.disabled').length === $('.acSizeSml > div').length) {
                        $('[data-arrayid="acSmallSize"]').addClass('disabled');
                    }
                    if ($('.acSizeMed > div.disabled').length === $('.acSizeMed > div').length) {
                        $('[data-arrayid="acMediumSize"]').addClass('disabled');
                    }
                    if ($('.acSizeLrg > div.disabled').length === $('.acSizeLrg > div').length) {
                        $('[data-arrayid="acLargeSize"]').addClass('disabled');
                    }
                }
            });

            if ($(this).parent().parent().hasClass('roomOverlay')) {
                //console.log('room overlay item clicked');
                closeOverlay.trigger('click');
            }

            if ($('h2.error').length === 0) { $('.acErrMsg').remove(); }

        });

        acNestedBtn.off('click').on('click', function (e) {
            e.preventDefault();
            if ($(this).hasClass('disabled')) return;
            $("section." + $(this).attr('data-arrayid')).addClass('active');
        });

        acCalculate.off('click').on('click', function (e) {
            e.preventDefault();
            var topLevelCategories = $(".acStep2 > div"),
                topLevelButtons = topLevelCategories.find('> div');

            topLevelCategories.each(function () {
                if ($(this).find("> div[class^='selected']").length === 0) {
                    //console.log('this has no selected children: ' + $(this));
                    $(this).prev().addClass('error');
                }
                else {
                    $(this).parent().find('> h2').removeClass('error');
                }

                if ($('h2.error').length > 0) {
                    $('.acErrMsg').remove();
                    $("<span class='acErrMsg'>*Please make a selection</span>").appendTo('.acStep2');
                }
                else {
                    //console.log('inside!');
                    $('.acErrMsg').remove();
                }
            });

            //if one item is selected in each catetory, then run the service...
            if ($('h2.error').length === 0) {
                var service = new FrigidaireService();
                service.loadAcSelectorResults(acResultList.join(","), "en-US", function (response) {
                    acResultListWrapper.slideUp(350, function () {
                        //console.clear();
                        var acTypeSelected = $('.acType .selected').data('arrayid');
                        var acKitchenSelected = acKitchen;
                        var acPowerSelected = $('.acPower .selected').data('arrayid');
                        var acSizeSelected = $('.roomOverlay .selected').data('arrayid');
                        var minBtuSelected = $('.roomOverlay .selected').data('minbtu');


                        var acBuildQueryString = '%3FacType%3D' + acTypeSelected + '%26acKitchen%3D' + acKitchenSelected + '%26acPower%3D' + acPowerSelected + '%26acSize%3D' + acSizeSelected;
                        $('.acShareWrapper a').each(function () {
                            // save current href
                            var cHref = $(this).attr('href');
                            $(this).attr('href', cHref + acBuildQueryString);
                            // save current onclick
                            var cClick = $(this).attr('onclick'),
                                origPart = cClick.split(/',/g);
                            $(this).attr('onclick', origPart[0] + acBuildQueryString + "'," + origPart[1]);
                        });
                        //acBuildQueryString);

                        $(this).empty().append(response.value);

                        // build array of BTU values
                        //						var btus = [];
                        //						$('.acResultListContainer .acDetails').each(function () {
                        //							btus.push($(this).data('btu'));
                        //						});
                        //						var largestBtu = Math.max.apply(Math, btus); // find highest number

                        //we were grabbing the largest btu from the results set and using it for the results btu,
                        //updated the results btu to use the minimum btu value for the room size based on elux's numbers and adding 4000 if kitchen is selected.
                        var largestBtu = minBtuSelected;
                        var kitchenIsSelected = $('.acKitchen .active').data('arrayid') === true;
                        if (kitchenIsSelected) {
                            largestBtu += 4000;
                        }

                        $('h2.acBtu').text((largestBtu + '').replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + ' BTU'); // change text in result list
                        $('.acResultListContainer').fadeIn(350);
                        acStep2.addClass('hiding');

                        acResultListWrapper.slideDown(350);
                        $('body').scrollView();
                    });
                });
            }

        });

        closeOverlay.off('click').on('click', function (e) {
            e.preventDefault();
            $('.roomOverlay').removeClass('active');
        });

        acStartBtn.off('click').on('click', function (e) {
            e.preventDefault();
            acStep1.fadeOut(350);
            setTimeout(function () { acStep2.fadeIn(350); $('body').scrollView(); }, 350);
        });

        $('.acRecalculate').off('click').on('click', function (e) {
            e.preventDefault();
            acResultListWrapper.slideUp(350, function () {
                $('.acResultListContainer').fadeOut(350);
                acStep2.removeClass('hiding').show();
                acClear.trigger('click');
            });
        });

        acClear.off('click').on('click', function (e) {
            e.preventDefault();

            $('h2.error').removeClass('error');

            acBtn.each(function () {
                $(this).removeClass('disabled selected active');
            });
            acNestedBtn.each(function () {
                $(this).removeClass('disabled selectedCat');
            });

            acResultListWrapper.slideUp(350, function () { $(this).empty(); });

            acType = [],
                acKitchen = false,
                acPower = [],
                acSize = [],
                acResultList = [];

            //console.clear();
            //console.log('clicked acType: ' + acType);
            //console.log('clicked acKitchen: ' + acKitchen);
            //console.log('clicked acPower: ' + acPower);
            //console.log('clicked acSize: ' + acSize);
            //console.log('clicked acResultList: ' + acResultList);
        });

        /// Moved this to frigidaire.util.getUrlVars()

        //function getUrlVars() {
        //	var vars = [], hash;
        //	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        //	for (var i = 0; i < hashes.length; i++) {
        //		hash = hashes[i].split('=');
        //		vars.push(hash[0]);
        //		vars[hash[0]] = hash[1];
        //	}
        //	return vars;
        //}

        if (window.location.search) {
            var firstQs = frigidaire.util.getUrlVars()["acType"],
                secondQs = frigidaire.util.getUrlVars()["acKitchen"],
                thirdQs = frigidaire.util.getUrlVars()["acPower"],
                fourthQs = frigidaire.util.getUrlVars()["acSize"];

            $('[data-arrayid=' + firstQs + ']').trigger('click');
            $('[data-arrayid=' + secondQs + ']').trigger('click');
            $('[data-arrayid=' + thirdQs + ']').trigger('click');
            $('[data-arrayid=' + fourthQs + ']').trigger('click');
            acCalculate.trigger('click');
        }

    }

    function faqPage() {
        if (!$('#search_faqs').length) return;
        if ($('select.faqRefine option').length > 1) {
            $('.faqRefineWrapper').addClass('visible');
        }
    }

    function searchResultsHashReader() {
        if ($('#search_faqs').length && window.location.hash) { // if search bar exists and there is a hash in the url

            var hash = window.location.hash.replace('#', ''),
                selected_tab = hash.substr(0, hash.indexOf('_')),
                allTabs = $('.tabSet li'),
                allResults = $('.tabSection');

            allResults.removeClass('show').addClass('hide'); // hide all results by default
            allTabs.removeClass('active'); // deactivate all tabs by default

            $('#' + selected_tab + '_results').removeClass('hide').addClass('show'); // show selected tab
            $('.' + selected_tab + '_results').addClass('active'); // show selected results
        }
    }

    function searchResultesTabContent() {
        let allTabs = $('.tabSet li a');
        let allResults = $('.tabSection');

        allTabs.click(function () {
            $this = $(this);
            let contentGroup = $this.attr('href').replace('#', '');

            allResults.removeClass('show').addClass('hide'); // hide all results by default
            $('#' + contentGroup + '_results').removeClass('hide').addClass('show'); // show selected content
        });
    }

    function expandCollapseVideo() {
        if (!$('.expandingVideoLink').length) return;
        $('.imageBlock.expandingVideoLink').unwrap().wrapAll('<div class="expandingVideoWrapper"></div>');

        $('.expandingVideoLink').off('click').on('click', function () {
            var $this = $(this),
                vidWrapper = $('.expandingVideoWrapper');
            $this.addClass('active');

            $('<section class="expandingVideoHolder"><div id="expandingVideo">Video</div></section>').prependTo(vidWrapper);
            $('<a href="#" class="closeButton inlineVideoCloseBtn"><i></i><span></span></a>').appendTo('body');

            $('.inlineVideoCloseBtn').css({
                'top': (vidWrapper.offset().top + 20),
                'left': (vidWrapper.offset().left) + (vidWrapper.outerWidth() - 62)
            });

            vidWrapper.animate({ 'padding-bottom': '56%' }, 400, "easeInOutQuint");

            $('.expandingVideoHolder').width(vidWrapper.outerWidth());

            var generatedList = function () {
                var playlist = [],
                    files = $('.expandingVideoLink.active').data('videofiles'),
                    paths = files.split("|");

                for (var t = paths.length; 0 < t--;) {
                    playlist.unshift({ file: paths[t] });
                }
                return playlist;
            }();

            jwplayer("expandingVideo").setup({
                flashplayer: '/Content/jwPlayer6/jwplayer.flash.swf',
                skin: '/Content/jwplayer6/skins/frigidaire.xml',
                width: "100%",
                aspectratio: "16:9",
                stretching: "uniform",
                levels: generatedList,
                image: $(this).parents('li').data('video-poster'),
                autostart: true,
                controls: true,
                icons: true,
                controlbar: true,
                volume: 100,
                'controlbar.position': 'none',
                events: {
                    onComplete: function () {
                        $('.inlineVideoCloseBtn').trigger('click');
                    }
                }
            });

            $('.inlineVideoCloseBtn').off('click').on('click', function (e) {
                e.preventDefault();
                $('.expandingVideoHolder').fadeOut('100', function () {
                    $('.expandingVideoLink').removeClass('active');
                    $('.inlineVideoCloseBtn').fadeOut('100');
                    vidWrapper.animate({ 'padding-bottom': '0' }, 400, "easeInOutQuint", function () {
                        jwplayer().remove();
                        $('.expandingVideoHolder').remove();
                        $('.inlineVideoCloseBtn').remove();
                    });
                });

            });

        });

        $('.expandingWatchVideo').off('click').on('click', function (e) {
            e.preventDefault();
            $(this).parent('.expandingVideoLink').trigger('click');
        });
    }

    function worksWellWith() {
        $('#WorksWellTb').keypress(function (e) {
            if (e.keyCode === 13) {
                e.preventDefault();
                return false;
            }
        });

        if (!$('#WorksWellWithTheseModels').length) return;


        var worksWellForm = $('#worksWellForm'),
            formUrl = worksWellForm.attr('action');

        $(document).on('submit.worksWellForm', '#worksWellForm', function () {
            e.preventDefault();
        });

        worksWellFormLoaded = false;

        $("#WorksWellTb").off('keyup').on('keyup', function (e) {
            var $this = $(this);
            if ($this.val().length > 0) { }
            else { }
        }).autocomplete({
            source:
                function (request, response) {
                    var results = $.ui.autocomplete.filter(worksWellModels, request.term);

                    if (results.length <= 6 || request.term.length === 0) {
                        $('#showMoreLess').hide();
                    } else {
                        $('#showMoreLess').show();
                    }

                    if (request.term.length > 0) {
                        response(results.slice(0, 6));
                    } else {
                        response(results.slice(0, 0));
                    }

                    if (request.term.length > 0 && results.length === 0) {
                        $('.empty-search').show();
                    }
                    else {
                        $('.empty-search').hide();
                    }
                },
            response: function (event, ui) {
                // ui.content is the array that's about to be sent to the response callback.
                if (ui.content.length === 0) {
                    //console.log('No results found');
                    $('#acResultsWorksWell').addClass('importantHide');
                } else {
                    //console.log('results found');
                    $('#acResultsWorksWell').removeClass('importantHide');
                }
            },
            open: function () { },
            autoFocus: true,
            focus: function (event, ui) {
                $(".ui-autocomplete li").removeClass("ui-state-hover");
                $(".ui-autocomplete").find("li:has(a.ui-state-focus)").addClass("ui-state-hover");
            },
            select: function (event, ui) {
                window.location = ui.item.productdetailurl;
            },
            minLength: 0,
            appendTo: "#acResultsWorksWell"
        }).data("autocomplete")._renderItem = function (ul, item) {
            item.label = item.label.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term) + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "$1");

            return $("<li></li>")
                .data("item.autocomplete", item)
                .append('<div><div><img src="' + item.imagepath + '" alt="" onerror="this.style.padding=' + "'5px'" + '" ></div><div class="desc"><div class="blue smaller">' + item.value + '</div><p>' + item.displayname + '</p><a href="' + item.productdetailurl + '">Product details</a></div></div>')
                .appendTo('#acResultsWorksWell ul');
        };

        $("#WorksWellTb").autocomplete("search", "");

        var isClicked = false;
        $(document).off('click.showMoreLess').on('click.showMoreLess', '#showMoreLess', function () {
            var $this = $(this),
                isActive = $this.hasClass('active') ? true : false;
            isClicked = true;

            $("#WorksWellTb").autocomplete({
                source: function (request, response) {
                    var results = $.ui.autocomplete.filter(worksWellModels, $("#WorksWellTb").val());
                    $this.text($this.data('show-more-text'));
                    if (isClicked) {
                        isClicked = false;
                        if (parseInt($this.attr('data-show-more-count')) >= results.length) {
                            $this.text($this.data('show-more-text'));
                            $this.attr('data-show-more-count', 6);
                            response(results.slice(0, 6));
                            $('html, body').animate({ scrollTop: $('#WorksWellWithTheseModels').offset().top - $('.pdp-nav-top').height() - $('.navbar-inverse').height() }, 'slow');
                        } else {
                            response(results.slice(0, parseInt($this.attr('data-show-more-count')) + 6));
                            $this.text($this.data('show-more-text'));
                            $this.attr('data-show-more-count', parseInt($this.attr('data-show-more-count')) + 6);
                            if ($('#WorksWellTb').val().length === 0) {
                                empty = false;
                            }
                            if (parseInt($this.attr('data-show-more-count')) >= results.length) {
                                $this.text($this.data('show-less-text'));
                            }
                        }
                    } else {
                        $('#showMoreLess').attr('data-show-more-count', 6);
                        if (results.length <= 6 || request.term.length === 0) {
                            $('#showMoreLess').hide();
                        } else {
                            $('#showMoreLess').show();
                        }
                        response(results.slice(0, 6));
                    }
                },
                response: function (event, ui) {
                    // ui.content is the array that's about to be sent to the response callback.
                    if (ui.content.length === 0) {
                        //console.log('No results found');
                        $('#acResultsWorksWell').addClass('importantHide');
                    } else {
                        //console.log('results found');
                        $('#acResultsWorksWell').removeClass('importantHide');
                    }
                }
            });
            $("#WorksWellTb").autocomplete("search", "");
        });
    }

    function PDPScrollToSpecs() {
        $('.three-across-info-blocks-container .block-2 a').click(function () {
            var tabToOpen = $(this).attr('href');
            var topPos = 64;
            $('body').animate({ scrollTop: $(tabToOpen).offset().top - topPos }, 1000, "easeOutExpo");
            $(tabToOpen).find('>h2').trigger('click');
        });
    };

    function yaToolTip() { // "Yet Another Tool Tip"
        if (!$('.yaTooltip').length) return;

        var $tooltips = $('.yaTooltip');
        $tooltips.each(function () {
            var $this = $(this),
                $tt = $('<div class="apTT bg leftPos"><div /></div>').appendTo('body'),
                $t = $tt.find('> div');

            $t.html($this.attr('data-tooltip'));

            if (!frigidaire.mobileView()) {
                $this.on('mouseenter', function () {
                    var topPos = $this.offset().top,
                        mLeft = 0;
                    if ($this.data('toolparent')) { topPos = $($this.data('toolparent')).offset().top; }
                    if ($this.data('toolw')) { var amount = parseInt($this.data('toolw')); $tt.css({ width: amount }); }
                    if ($this.data('toolx')) { mLeft = mLeft + parseInt($this.data('toolx')); }
                    if ($this.data('tooly')) { topPos = topPos + parseInt($this.data('tooly')); }

                    // now that we have the width; check the height of it and place it correctly.
                    var tHeight = $tt.css({ visibility: 'hidden', display: 'block', top: -2000, left: -2000 }).height();
                    $tt.css({ visibility: 'visible', display: 'none' });
                    topPos = topPos - (tHeight - 5);
                    var leftPos = ($this.width() / 2) + $this.offset().left;
                    $tt.css({ top: topPos, left: leftPos, marginLeft: -(($tt.width() / 2) - mLeft) }).show();

                    if (navigator.userAgent.match(/iPad/i)) {
                        $(this).trigger('click');
                    }

                    //if the tooltip is running off of the screen, then just position it to the edge of the screen
                    var windowWidth = $(window).width(),
                        thisWidth = $tt.width();

                    if ($tt.position().left + (thisWidth / 2) > windowWidth) {
                        $tt.addClass('toEdgeRelative');
                    }

                }).on('mouseleave', function () {
                    $tt.removeClass('toEdgeRelative');
                    $tt.hide();
                });
            } else {
                $this.off('click').on('click', function (e) {
                    e.preventDefault();
                    friModalSize.openModal($this.attr('data-tooltip'), '500px', '', '', 'html');
                });
            }

        });
    }

    function isVisibleOnScreen(el) {
        var elemTop = el.getBoundingClientRect().top,
            elemBottom = el.getBoundingClientRect().bottom,
            isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
        return isVisible;
    }

    function accordionTechnologyTM() {
        var aW = $('.accordianWrapper'),
            aWSection = aW.find('>*'),
            aWSectionHeader = aWSection.find('>h2'),
            aWContent = aWSection.find('>div'),
            awExpColText = $('<span/>').appendTo(aWSectionHeader),
            awMoreText = aW.attr('data-more-text'),
            awLessText = aW.attr('data-less-text');

        awExpColText.text(awMoreText);

        aWSection.each(function () {
            if ($(this).is('.active')) {
                $(this).find('>h2').next('div').slideDown(200);
                $(this).find('>h2>span').text(awLessText);
            }
        });

        aWSectionHeader.off('click openAccordion closeAccordion').on('click openAccordion closeAccordion', function (e) {
            var $this = $(this);

            if (($this.parent().is('.active') && e.type === 'click') || (e.type === 'closeAccordion')) {
                $this.parent().removeClass('active').end().next('div').slideUp(200);
                $this.find('>span').text(awMoreText);
            } else {
                $this.parent().addClass('active').end().next('div').slideDown(200);
                $this.find('>span').text(awLessText);
            }

            //PDP Featured Tab Match Heights
            if ($this.parent().is('.pdp-features.active')) {
                $('.pdp-features').find('.pdpTabClear').each(function (i) {
                    $(this).addClass('row' + i);
                    $(this).next().addClass('row' + i);
                    $(this).next().next().addClass('row' + i);
                    matchColHeights('.row' + i);
                });
            }
            //PDP Use and Care Tab
            if ($this.parent().is('.pdp-use-and-care')) {
                if (!$(this).parent().hasClass('active')) {
                    if ($('.jwplayer').length) {
                        jwplayer("playlistVideo").stop();
                    }
                } else {
                    playListVideoPlayer();
                }
            }
        });

        //automatically open accordions via query string in url
        if (window.location.search) {

            $('img').imagesLoaded(function () {
                if (getParameterByName('tab')) {
                    var topPos = (mobileView() ? 200 : 64);
                    $('body').animate({ scrollTop: $('#' + getParameterByName('tab')).offset().top - topPos }, 500, "easeOutExpo");
                    $('#' + getParameterByName('tab')).find('>h2').trigger('click');
                }

                if (getParameterByName('writereview').toLowerCase() === 'true' && $('#pdp-sku').text()) {
                    $BV.ui("rr", "submit_review", { productId: $('#pdp-sku').text() });
                    sendTracking('product_detail', 'click_write_review', 'Write Review');
                }

            });

        }

        if (location.hash != '') {
            var urlHash = location.hash;
            $(urlHash).find('>h2').trigger('click');
        }


    }

    function testimonials() {
        if (!$('.testimonialsWrapper').length) return;

        $('.testimonialsMain img').imagesLoaded(function () {

            var testimonialsNav = $('.testimonialsNav'),
                testimonialsNavTop = (frigidaire.lang() === 'fr-ca' ? testimonialsNav.offset().top - 90 : testimonialsNav.offset().top - 70),
                footerAndNavHeight = $('.footer-container').outerHeight() - testimonialsNav.outerHeight(),
                //headerAndBodyHeight = $('#mainContainer').outerHeight() - $('.footer-container').outerHeight() - $('.header-container').outerHeight(), // - 300

                headerAndBodyHeight = $('.testimonialsWrapper').outerHeight() + $('.header-container').outerHeight() + $('.sectionHeadline').outerHeight() + $('.subHeadline').outerHeight() + $('.breadcrumb-container').outerHeight() - 140,
                testimonialsNavHeight = $('.testimonialsNav').outerHeight(),
                testimonialsContentHeight = (headerAndBodyHeight - testimonialsNavHeight) + 100,
                wholePage = $(document).height(),
                scrollY;

            console.log('height: ', headerAndBodyHeight - testimonialsNavHeight);

            if (!mobileView()) {
                if (isMobileDevice) {
                    document.addEventListener("touchmove", touchMove, false);

                    var touchMove = function () {
                        scrollY = window.pageYOffset;
                        if (scrollY >= testimonialsNavTop && scrollY < headerAndBodyHeight) {
                            testimonialsNav.removeClass('absBottom').addClass('fixed');
                        }
                        else if (scrollY < testimonialsNavTop) {
                            testimonialsNav.removeClass('absBottom').removeClass('fixed');
                        }
                        else if (scrollY >= (headerAndBodyHeight - testimonialsNavHeight)) {
                            testimonialsNav.removeClass('fixed').addClass('absBottom');
                        }
                    };
                }

                $(window).scroll(function () {
                    if (!$('html').hasClass('ie8')) {
                        scrollY = window.pageYOffset;
                    } else {
                        scrollY = window.document.documentElement.scrollTop;
                    }
                    //headerAndBodyHeight = $('#mainContainer').outerHeight() - $('.footer-container').outerHeight() - $('.header-container').outerHeight() - 140;

                    if (scrollY >= testimonialsNavTop && scrollY < testimonialsContentHeight) {
                        testimonialsNav.removeClass('absBottom').addClass('fixed');
                    }
                    else if (scrollY < testimonialsNavTop) {
                        testimonialsNav.removeClass('absBottom').removeClass('fixed');
                    }
                    else if (scrollY >= testimonialsContentHeight) {
                        testimonialsNav.removeClass('fixed').addClass('absBottom');
                    }

                });

                $(window).trigger('scroll');
            }
            else {
                //if mobile phone only...
                testimonialsNav.height($('.testimonialsNav li img').height() + 5);
            }

            //scroll to story with hash in url, and open it's video if query string is provided (ex: /Real-Frigidaire-Stories/?video=true#story2)
            var hashIds = $(location.hash);
            var qs = window.location.search;

            if (location.hash !== "") {
                hashIds.scrollView();
            }
            if (qs === '?video=true') {
                setTimeout(function () { $(document.location.hash).find('.playButton a').trigger('click'); }, 1000);
                //console.log('document.location.hash: ', document.location.hash);
                //console.log('the trigger: ', $('.' + document.location.hash).find('.playButton a'));
                //setTimeout(function () { $('.'+document.location.hash).find('.playButton a').trigger('click'); }, 1000);
            }
        });

        var playButton = $('.playButton'),
            thumbnail = $('.testimonialsNav a'),
            story = $('.testimonialsMain ol li'),
            playButtonItem = $('.testimonialsMain .playButton a');

        thumbnail.each(function () {
            var person = $(this).find('.active img').attr('alt');
            $(this).attr('href', '#' + person);
        });

        story.each(function () {
            var person = $.trim($(this).find('.tName').html());
            $(this).attr('id', person);
        });

        //play button events
        if (!isMobileDevice) {
            playButtonItem.off('mouseover').on('mouseover', function () {
                $(this).find('span').fadeIn(200).css("display", "inline-block");
            });

            playButtonItem.off('mouseleave').on('mouseleave', function () {
                $(this).find('span').fadeOut(200);
            });
        }

        if (!isMobileDevice) {
            playButton.off('mouseover').on('mouseover', function () {
                $(this).next().next().find('.active').fadeOut(200);
            });

            playButton.off('mouseleave').on('mouseleave', function () {
                $(this).next().next().find('.active').fadeIn(200);
            });
        }

        //thumbnail events
        if (!isMobileDevice) {
            var makeTall = function () {
                $(this).find('.active').fadeOut(60);
                $(this).find('.slideOutText').stop(true).show().animate({ 'left': '88px' }, 120);
                $(this).find('.slideOutText > span').fadeIn(600);
            };

            var makeShort = function () {
                $(this).find('.active').fadeIn(60);
                $(this).find('.slideOutText').animate({ 'left': '-42px' }, 120);
                setTimeout(function () { $(this).find('.slideOutText').hide(); });
                $(this).find('.slideOutText > span').fadeOut(600);
            };

            $(thumbnail).hoverIntent(makeTall, makeShort);
        }

        thumbnail.off('click').on('click', function (e) {
            var $this = $(this),
                testimonialName = $this.find('img').attr('alt'),
                testimonialSku = $this.data('testimonial-sku');

            //tracking:
            sendTracking('testimonials', 'click_sidenav', testimonialName + " | " + testimonialSku);

            if (isMobileDevice) {
                $('.testimonialsNav a .active').show();
                $this.find('.active').fadeOut(200);
            }

            var goToStory = $(this).attr('href'),
                topPos = (mobileView() ? 65 : 72);

            $('html, body').animate({ scrollTop: $(goToStory).offset().top - topPos }, 500, "easeOutExpo");

        });

        var vidAlreadyExists = null,
            vidDelay = null,
            aVidIsPlaying = null;

        $('.testimonialsVideo').off('click').on('click', function (e) {
            e.preventDefault();

            if ($('.jwplayer').length) {
                vidAlreadyExists = true;
                vidDelay = 0; //because jwplayer removal
                $('.testimonialsMain .closeButton').trigger('click');
            } else {
                vidAlreadyExists = false;
                vidDelay = 500;
            }

            //tracking
            var testimonialName = $(this).parents('li').attr('id'),
                testimonialSku = $(this).parents('li').data('testimonial-sku');
            sendTracking('testimonials', 'click_video', testimonialName + ' | ' + testimonialSku);

            var testimonialContainer = $(this).parents('li'),
                loader = $('<div class="loader"><div></div></div>');

            testimonialContainer.siblings().removeClass('active');
            testimonialContainer.addClass('active');
            loader.prependTo($(this).parents('.testimonialsPhotoWrapper'));

            $('<div id="testimonialVideoImg" />').insertBefore($(this).parents('.testimonialsPhotoWrapper'));

            var img = $('<img src="' + $(this).parents('li').data('videoposter') + '" alt=""/>').load(function () {
                var originalHeight = testimonialContainer.find('.testimonialsPhotoWrapper').height();

                $('#testimonialVideoImg').append(img);
                loader.remove();

                testimonialContainer.find('.testimonialsPhotoWrapper').height(originalHeight).animate({ 'opacity': 0, 'height': $(this).height() }, vidDelay, function () {
                    aVidIsPlaying = true;
                    $('#testimonialVideoImg').addClass('showPoster').fadeIn(vidDelay);

                    $('<div id="testimonialVideo">Video</div>').prependTo($('#testimonialVideoImg'));
                    $('<a href="#" class="closeButton"><i></i><span></span></a>').prependTo('#testimonialVideoImg');

                    var generatedPlaylist = function () {
                        var playlist = [],
                            files = $('#testimonialVideo').parents('li').data('videofiles'),
                            paths = files.split("|");

                        for (var t = paths.length; 0 < t--;) {
                            playlist.unshift({ file: paths[t] });
                        }
                        return playlist;
                    }();

                    jwplayer("testimonialVideo").setup({
                        flashplayer: '/Content/jwPlayer6/jwplayer.flash.swf',
                        skin: '/Content/jwplayer6/skins/frigidaire.xml',
                        width: "100%",
                        aspectratio: "16:9",
                        stretching: "uniform",
                        levels: generatedPlaylist,
                        image: $(this).parents('li').data('video-poster'),
                        autostart: true,
                        controls: true,
                        icons: true,
                        controlbar: true,
                        volume: 100,
                        'controlbar.position': 'none'
                    });

                    jwplayer("testimonialVideo").onTime(function (e) { //tracking for half way through video
                        var halfTime = Math.floor(jwplayer('testimonialVideo').getDuration() / 2),
                            halfTimeBump = halfTime + .20;
                        if (e.position >= halfTime && e.position <= halfTimeBump) {
                            frigidaire.sendTracking('testimonials', 'video_50_complete', testimonialName + ' | ' + testimonialSku);
                        }
                    });

                    jwplayer("testimonialVideo").onComplete(function () {
                        frigidaire.sendTracking('testimonials', 'video_100_complete', testimonialName + ' | ' + testimonialSku);
                    });

                    $('.testimonialsMain .closeButton').off('click').on('click', function (e) {
                        e.preventDefault();
                        jwplayer().remove();
                        $(this).parents('li').find('.testimonialsPhotoWrapper').animate({ 'opacity': 1, 'height': originalHeight }, vidDelay, function () {
                            $('#testimonialVideoImg').fadeOut(vidDelay, function () { $(this).remove(); });
                            $(this).height('auto');
                            aVidIsPlaying = false;
                        });
                    });

                });

            });

        });

        $('.watchVideo.testimonialsVideo').off('click').on('click', function (e) {
            e.preventDefault();
            $(this).parents('li').find('.testimonialsPhotoWrapper .testimonialsVideo').trigger('click');
            var testimonialName = $(this).parents('li').attr('id'),
                testimonialSku = $(this).parents('li').data('testimonial-sku');
            sendTracking('testimonials', 'load_testimonial_video_sub', testimonialName + ' | ' + testimonialSku);
        });

        $('.seeProduct').off('click').on('click', function () {
            var testimonialName = $(this).parents('li').attr('id'),
                testimonialSku = $(this).parents('li').data('testimonial-sku');
            sendTracking('testimonials', 'click_product_detail', testimonialName + ' | ' + testimonialSku);
        });

    }

    function ownersCenter() {
        $('.mobileBrowseByCat').off('click').on('click', function (e) {
            e.preventDefault();
            var $this = $(this);
            if (typeof $this.data('ga-label') === 'undefined') {
                sendTracking($this.data('ga-category'), $this.data('ga-action'));
            } else {
                sendTracking($this.data('ga-category'), $this.data('ga-action'), $this.data('ga-label'));
            }

            $('.mobileModelNumberWrapper').addClass('active');
            $('body').trigger('friModalSize.modalOpen');
        });
        $('.backBtn').off('click').on('click', function (e) {
            $(this).addClass('active');
            e.preventDefault();
            $('.mobileModelNumberWrapper').removeClass('active');
        });
    }

    function mobileResize() {
        if (mobileView()) {
            $('.search_input#ProductCode').attr('placeholder', $('#modelNumber_search').data('mobile-placeholder'));
        } else {
            $('.search_input#ProductCode').attr('placeholder', $('#modelNumber_search').data('desktop-placeholder'));
        }

        //function for image swaping depending on resolution:
        $('[data-desktop-src]').each(function () {
            var $this = $(this),
                desktopSrc = $this.data('desktop-src'),
                mobileSrc = $this.data('mobile-src');
            if (!mobileView()) {
                $this.attr('src', desktopSrc);
            }
            else {
                $this.attr('src', mobileSrc);
            }
        });

        //my account orders mobile styling
        if (!$('.ma-orders').length) return;
        if (mobileView()) {
            $('.respTable > li').each(function () {
                $(this).find('.dateCell, .statusCell, .shippingCell').wrapAll('<div class="mobileCell" />');
            });
        } else {
            if ($('.mobileCell').length) {
                $('.respTable > li').each(function () {
                    $(this).find('.dateCell, .statusCell, .shippingCell').unwrap();
                });
            }
        }

    }

    function energySavings() {
        if ($('.energySavingStepWrapper').length === 0) return;

        $('img').imagesLoaded(function () {
            $('.energySavingsWrapper').addClass('active').fadeIn(500);


            $('.energySavingStepWrapper > section').each(function (i) {
                var i = i + 1;
                $(this).addClass('energyStep' + i);
                $('.energyControls').append('<div class="bullet bullet' + i + '"></div>');
            });

            $('.energyControls > .bullet:eq(0)').addClass('active');

            $('.energyStart').off('click').on('click', function (e) {
                e.preventDefault();
                sendTracking('energy_saving_tips', 'click_enter_now');
                $('.introSlide').fadeOut(200, function () {
                    $('.energySavingStepWrapper > section:eq(0)').removeClass('active');
                });
                $('.energyPager').addClass('active');
                $('.energySavingStepWrapper > section:eq(1), .energyControls > div:eq(1)').addClass('active');

            });

            $('.energyNext').off('click').on('click', function (e) {
                e.preventDefault();
                if ($(this).hasClass('gray')) return;
                var currSlide = $('.energySavingStepWrapper > .active'),
                    currBullet = $('.energyControls > .active');

                currSlide.next('section').addClass('active');
                currSlide.removeClass('active');

                currBullet.next('div').addClass('active');
                currBullet.removeClass('active');
                checkForLast();

                var trkSlideIndex = currSlide.index() + 1;
                sendTracking('energy_saving_tips', 'click_next', 'slide_' + trkSlideIndex);
            });

            $('.energyBack').off('click').on('click', function (e) {
                e.preventDefault();
                var currSlide = $('.energySavingStepWrapper > .active'),
                    currBullet = $('.energyControls > .active');

                currSlide.prev('section').addClass('active');
                currSlide.removeClass('active');

                currBullet.prev('div').addClass('active');
                currBullet.removeClass('active');
                checkForLast();

                var trkSlideIndex = currSlide.index() - 1;
                sendTracking('energy_saving_tips', 'click_back', 'slide_' + trkSlideIndex);
            });

            $('.energyControls .bullet').off('click').on('click', function (e) {
                e.preventDefault();
                var $this = $(this);

                $('.energyControls > div').removeClass('active');
                $this.addClass('active');

                var thisBullet = $this.prevAll('div').length + 1;

                $('.energySavingStepWrapper > section').removeClass('active');
                $('.energySavingStepWrapper > section.energyStep' + thisBullet + '').addClass('active');

                sendTracking('energy_saving_tips', 'click_radio', 'slide_' + $('.energySavingStepWrapper > .active').index());
                checkForLast();
            });

            function checkForLast() {
                if ($('.energyControls > div:last').hasClass('active')) {
                    $('.energyNext').addClass('gray').removeClass('pink');
                } else {
                    $('.energyNext').removeClass('gray').addClass('pink');
                }

                if ($('.introSlide').hasClass('active')) {
                    $('.introSlide').fadeIn(200, function () {

                        $(this).addClass('active');
                    });
                } else {
                    $('.introSlide').fadeOut(200);
                }

            }

        });
    }

    function pageTools() {
        var shareLink = $('.shareLink'),
            shareWrapper = $('#share');

        shareLink.off('click').on('click', function (e) {
            e.preventDefault();
            if (!$(this).hasClass('active')) {
                $(this).addClass('active');
                shareWrapper.fadeIn(200);
                $('body').off('click').on('click', function (e) {
                    if (!$(e.target).is(shareLink) || !$(shareLink).has(e.target)) {
                        shareLink.removeClass('active');
                        shareWrapper.fadeOut(200);
                        $('body').unbind('click');
                    }
                });
            } else {
                $(this).removeClass('active');
                shareWrapper.fadeOut(200);
            }
        });

        //tooltips
        var tooltip = $('.tooltip');

        tooltip.off('mouseenter').on('mouseenter', function (e) {
            e.preventDefault();
            var tooltipText = $(this).data('tooltip-text');
            $('<div class="tooltipWrapper"><div>' + tooltipText + '</div></div>').prependTo($(this).parent()).fadeIn('200');
        });

        tooltip.off('mouseleave').on('mouseleave', function (e) {
            e.preventDefault();
            setTimeout(function () {
                $('.tooltipWrapper').fadeOut('200', function () {
                    $(this).remove();
                });
            }, 350);
        });

    }

    function toolTips() { // general tooltips
        var $el = $('.jsTooltip');

        $el.on('mouseenter.tooltip', function () {
            var $this = $(this);
            if (!$this.attr('data-tooltip').length) return;

            if (!$this.data('ttElement')) {
                var $tt = $('<div class="jsTT bg" style="width:' + $this.data('tooltip-width') + 'px;"><div>' + $this.data('tooltip') + '</div></div>').hide().appendTo('body'), // create new bubble for each, for smooth fading etc when quickly hovering over multiple elements
                    $t = $tt.find('> div'), // inner
                    tipText = $this.attr('data-tooltip'),
                    tHeight;

                if ($('.list-products , .pdp-info').length) {
                    $tt.find('> div').addClass('colorTT');
                }

                $this.data('ttElement', $tt);
                // get real height, so we need to show it quickly then hide again...
                $tt.css({ visibility: 'hidden', display: 'block' });
                tHeight = $tt.height();
                $tt.css({ visibility: 'visible', display: 'none' });

                $tt.css({
                    top: $this.offset().top - (tHeight - 10),
                    left: ($this.offset().left + ($this.width() / 2) - ($tt.width() / 2))
                }).fadeIn(250);

                $($this.data('ttElement')).fadeIn();
            } else {
                $($this.data('ttElement')).fadeIn(); //.stop()
            }
        }).on('mouseleave.tooltip', function () {
            $($(this).data('ttElement')).fadeOut(); //.stop();
        });
    }

    function populateProductPageDocuments() {
        $('.documentItem').removeClass('active').addClass('hidden');
        var varName = $("input[name='language']:checked").val(),
            prodId = $('.product-detail').data('prod-id'),
            prodCat = $('.product-detail').data('prod-cat');

        $('.documentItem[data-item-language=' + varName + ']').removeClass('hidden');
    }

    function productDetailPage() {
        if (document.querySelector('.product-detail') === null) return;

        populateProductPageDocuments();

        $(document).off('click', '.bv-stars-container').on('click', '.bv-stars-container', function (e) {
            var topPos = (mobileView() ? 200 : 131);
            $('html,body').animate({ scrollTop: $('#Reviews').offset().top - topPos }, 500, "easeOutExpo", $('#Reviews').find('>h2').trigger('click'));
        });

        $(document).off('click', '.bv_stars_button_container').on('click', '.bv_stars_button_container', function (e) {
            if ($("#Reviews").length > 0 && $('#Reviews').hasClass('active') === false) {
                var topPos = (mobileView() ? 200 : 131);
                $('html,body').animate({ scrollTop: $('#Reviews').offset().top - topPos }, 500, "easeOutExpo", $('#Reviews').find('>h2').trigger('click'));
            }
        });

        var prodData = $('.product-detail').data(),
            prodId = prodData.prodId,
            prodCat = prodData.prodCat,
            prodName = prodData.prodName,
            prodPrice = $('.product-detail').find('.initPrice').text(),
            isPDP = (!$('.owners-detail').length),
            detailCategory = (isPDP ? 'product_detail' : 'owners_support_detail');

        //tracking
        $(document).off('click', '.bv-write-review').on('click', '.bv-write-review', function () {
            sendTracking(detailCategory, 'click_write_review', prodCat + " | " + prodId);
        });

        $(document).off('click', '.bv-form-actions-submit').on('click', '.bv-form-actions-submit', function () {
            sendTracking(detailCategory, 'click_post_review', prodCat + " | " + prodId);
        });

        //email doc
        var guideTitle,
            countryCode;

        $(document).off('click', '.icon-new-email').on('click', '.icon-new-email', function () {
            var $this = $(this),
                langCode = $this.parents('.documentItem').data('item-language'),
                twoLetterLangCode = function () {
                    switch (langCode) {
                        case "English":
                            return "EN";
                            break;

                        case "Español":
                            return "SP"
                            break;

                        case "Français":
                            return "FR"
                            break;

                        default:
                            break;
                    }
                }
            guideTitle = $(this).parents('.documentItem').find('>p').text();
            countryCode = twoLetterLangCode();
            labelParam = prodCat + " | " + prodId + " | " + guideTitle + " " + countryCode;

            sendTracking(detailCategory, 'click_email_guide_manual', labelParam);

            $('.button.icon-new-email').removeClass('active');
            $this.addClass('active');
        });

        $(document).off('change.SendACopy').on('change.SendACopy', '#SendACopy', function (e) {
            if ((document.getElementById('SendACopy').checked) && (typeof labelParam !== 'undefined')) {
                sendTracking(detailCategory, 'click_send_copy', labelParam);
            }
        });

        $(document).off('change.SendMeEmails').on('change.SendMeEmails', '#SendMeEmails', function (e) {
            if ((document.getElementById('SendMeEmails').checked) && (typeof labelParam !== 'undefined')) {
                sendTracking(detailCategory, 'click_opt_in', labelParam);
            }
        });

        $('.trk-pdp-support').off('click').on('click', function () {
            sendTracking(detailCategory, 'click_productsupport', prodCat + " | " + prodId);
        });

        $('.pdp-features .friModalSize').off('click').on('click', function () {
            var fileName = $(this).attr('href').match('[^/]*$')[0];
            sendTracking(detailCategory, 'click_feature_video', fileName);
        });

        $(document).on("click", ".pdp-guides a.icon-new-download", function () {
            var $this = $(this),
                twoCharLangCode = $("input[name='language']:checked").val().slice(0, 2);

            sendTracking(detailCategory, 'click_download_guide_manual', prodCat + " | " + prodId + " | " + $this.parents('.documentItem').find('>p').text() + " | " + twoCharLangCode);

            //mixpanel
            mpFrigidaire.increment("Total Number of Document Downloads");

            mpFrigidaire.track('Download Guide or Manual', {
                "Document Type": $this.parents('.documentItem').find('>p').text() + " | " + twoCharLangCode,
                "Product Number (document download)": prodId,
                "Product Name (document download)": mpGlobalProperties["Product Name"],
                "Site Section": mpGlobalProperties["Site Section"],
                "Page Category": mpGlobalProperties["Page Category"],
                "Page Sub-Category": mpGlobalProperties["Page Sub-Category"],
                "Product Name": mpGlobalProperties["Product Name"],
                "Product Number": mpGlobalProperties["Product Number"],
                "Product Price": mpGlobalProperties["Product Price"],
                "Page Type": mpGlobalProperties["Page Type"],
                "Content Title": mpGlobalProperties["Page Title"]
            });

        });

        $(document).on("click", ".ptwContent .printLink", function () {
            sendTracking(detailCategory, 'click_print_specs', prodCat + " | " + prodId);
        });

        $(document).on("click", ".wrapper > .pageToolsWrapper a.printLink", function () {
            sendTracking(detailCategory, 'click_print_sku', prodCat + " | " + prodId);
        });

        $(document).on("click", ".pageToolsWrapper .shareLink", function () {
            sendTracking(detailCategory, 'click_social_share', prodCat + " | " + prodId);
        });

        $(document).on("click", ".pageToolsWrapper #share a", function () {
            sendTracking(detailCategory, 'click_' + $(this).attr('title'), prodCat + " | " + prodId);
        });

        $(document).on("click", ".ptwContent .downloadLink", function () {
            sendTracking(detailCategory, 'click_download_specs', prodCat + " | " + prodId);
        });

        //owners faqs
        if ($('#Faqs').length) {
            $(document).on("click", "#Faqs dt", function () {
                sendTracking(detailCategory, 'click_faq', $.trim($(this).text()));
            });
        }

        $(document).off('click.load-carousel', '[data-load="carousel"]').on('click.load-carousel', '[data-load="carousel"]', function () {
            frigidaire.carousel();
        });

        $('.reviewList > li:nth-child(2n+1) > div').addClass('highlightItem');
        $('.slideshowGalleryWrapper').remove();

        if (mobileView()) {
            $('.pdp-reviews h2.clickable').click(function () {
                $('.reviewText').each(function () {
                    $(this).next('.button').remove();
                    if ($(this).height() > 50) {
                        $('<a href="#" class="button pink" />').text($('.pdp-tabs').data('more-text')).on('click', function (e) {
                            e.preventDefault();
                            $(this).prev().toggleClass('active');
                            if ($(this).prev().hasClass('active')) {
                                $(this).text($('.pdp-tabs').data('less-text'));
                            } else {
                                $(this).text($('.pdp-tabs').data('more-text'));
                            }
                        }).appendTo($(this).parent());
                    }
                });
            });

            //begin mobile gallery
            //$('<div class="slideshowGalleryWrapper"><ul class="slider" id="slider_gallery"></ul></div>').insertAfter($('.product-detail .left-col .product-specs'));
            $('<div class="slideshowGalleryWrapper"><ul class="slider" id="slider_gallery"></ul></div>').appendTo($('.product-detail .MediaGallery--mobile'));
            $('#heroImgWrapper .productBadges').clone().appendTo('.slideshowGalleryWrapper');

            if (!$('.galleryThumbs a').length) {
                $('<li style="background-image:url(' + $('#product_image').attr('src') + ')"><img src="/Content/Images/mobileGallerySlide.png" alt="Mobile Gallery Slide"/></li>').appendTo($('#slider_gallery'));
            } else {
                $('.galleryThumbs a').each(function () {
                    if (!$(this).hasClass('video')) {
                        $('<li style="background-image:url(' + $(this).attr('href') + ')" data-zoom-img="' + $(this).attr('data-zoom-img') + '"><img src="/Content/Images/mobileGallerySlide.png" alt="Mobile Gallery Slide"/></li>').appendTo($('#slider_gallery'));
                    }
                    else {
                        $('<li class="mobileVideoSlide" style="background-image:url(' + $('.galleryThumbs li:eq(0) a').attr('href') + ')"><a href="#" class="mobileVideoLink"></a><img src="/Content/Images/mobileGallerySlide.png" alt="Mobile Gallery Slide"/></li>').appendTo($('#slider_gallery'));
                    }
                });
            }

            $('.mobileVideoLink').off('click').on('click', function (e) {
                e.preventDefault();
                var sNav = $('.sNav');
                sNav.fadeOut();
                var $close = $('<a href="#" class="closeButton"><span></span></a>').on('click', function (e) {
                    e.preventDefault();
                    $(this).parent().fadeOut(200, function () {
                        jwplayer('pdpVideo').stop();
                    });
                }, function () {
                    $('#popover').remove();
                }),
                    $vid = $('<div id="pdpVideo" />'),
                    $popover = $('<div class="popover pdpVideoWrapper" id="popover" style="height:' + $('#slider_gallery img').height() + 'px" />').off('click').on('click', function () {
                        $(galleryThumb).removeClass('active');
                    }).append($close, $vid);

                $(document).off('click.pdp-video-close').on('click.pdp-video-close', '#popover .closeButton', function (e) {
                    e.preventDefault();
                    sNav.fadeIn();
                });

                $popover.fadeOut().appendTo($('.slideshowGalleryWrapper'));
                $popover.fadeIn(200);

                jwplayer("pdpVideo").setup({
                    flashplayer: "/Content/jwPlayer6/jwplayer.flash.swf",
                    skin: "/Content/jwplayer6/skins/frigidaire.xml",
                    width: "100%",
                    //aspectratio: "16:9", //taking out aspectratio and adding height and stretching in order to center video within modal.
                    height: $('#slider_gallery img').height(),
                    stretching: "uniform",
                    levels: [
                        { file: $('.video').data('video-mp4') },
                        { file: $('.video').data('video-webm') }
                    ],
                    image: $('.video').data('video-poster'),
                    autostart: true,
                    controls: true,
                    icons: true,
                    controlbar: true,
                    volume: 100,
                    'controlbar.position': 'none',
                    events: {
                        onPlay: function () {
                        },
                        onComplete: function () {
                        }
                    }
                });
            });

            //setup slider
            $('.slider').each(function () {
                var $this = $(this),
                    numOfSlides = $this.find('> li').length;

                $this.find('> li').eq(0).addClass('active');

                if ($this.attr('id') != 'slider_gallery') {
                    var $sControls = $('<div class="sControls"></div>').insertAfter($this);
                    $this.find('> li').each(function () {
                        $('<div class="bullet"/>').appendTo($(this).parents('.slider').next('.sControls'));
                    });
                }

                if ($this.find('> li').length > 1) {
                    $this.nSwipeSlider({ wrapAround: true });
                }
                else {
                    $this.nSwipeSlider({ wrapAround: false });
                    $this.addClass('oneSlide');
                }

                if ($this.attr('id') === 'slider_gallery') {
                    //use arrows
                    if (!$this.hasClass('oneSlide')) {
                        $('<div class="sNav"><a href="#" class="sLeft"><span><i class="icon-left-open"></i></span></a><a href="#" class="sRight"><span><i class="icon-right-open"></i></span></a></div>').insertAfter($this);

                        $(document).on('click.sNav', '.sNav > a', function (e) {
                            e.preventDefault();
                            if ($(this).hasClass('sLeft')) {
                                $('#slider_gallery').find('li.active').trigger('swiperight');
                            } else {
                                $('#slider_gallery').find('li.active').trigger('swipeleft');
                            }
                        });

                        //add caption
                        var sCaption = $('<div class="sCaption text-right"/>').insertAfter($this);
                        sCaption.text('( 1' + ((frigidaire.lang() === 'fr-ca') ? ' de ' : ' of ') + numOfSlides + ' )');

                        //update caption on swipe
                        $this.on('nSwipeSlider.swipeDone', function (e, jQueryDOMObject, i) {
                            sCaption.text('( ' + i + ((frigidaire.lang() === 'fr-ca') ? ' de ' : ' of ') + numOfSlides + ' )');
                        });
                    }

                } else {
                    //use bullets
                    $this.on('nSwipeSlider.swipeDone', function (e, jQueryDOMObject, i) {
                        $this.next('.sControls').find('.bullet').removeClass('active');
                        $this.next('.sControls').find('.bullet').eq(i - 1).addClass('active');
                    });

                    $this.next('.sControls').find('> .bullet').eq(0).addClass('active');

                    $('.bullet').on('click', function () {
                        var $bullet = $(this);
                        $bullet.parent().find('> div').removeClass('active');
                        $bullet.addClass('active');
                        $bullet.parent().prev().find('> li').eq($bullet.index() + 1).trigger('slideTo');
                    });
                }

            });
            //end mobile gallery

        }
        else {
            $('.reviewText').next('.button').remove();

            //if ($('.pdp-subscription').length) {
            //    $('.galleryThumbsWrapper').appendTo('.col.left-col');
            //} 

            //desktop gallery
            var galleryThumbWrapper = $('.galleryThumbs'),
                galleryThumbsWrapper = $('.galleryThumbsWrapper'), // outermost div container
                galleryThumb = galleryThumbWrapper.find('li'),
                heroImgWrapper = $('#heroImgWrapper'), // outermost div container for the center column
                colorChips = $('.colorChips'),
                heroImg = $('#heroImgWrapper > img'), // gets the main product image
                thumbsPerSlide = galleryThumbsWrapper.data('gallery-thumbs'); // this gets the number of thumbnails per slide (usually 6)


            // if more than 8 items, let's create a sliders!
            if (galleryThumb.length > thumbsPerSlide) {  // if there are more thumbs and the number of thumbs per slide...
                galleryThumbWrapper.wrap('<div class="slider gallerySlider">'); // wrap .galleryThumbs in a div
                galleryThumb.unwrap(); // remove wrapping div from each li
                var $newControls = $('<span class="sControls"/>').insertAfter($('.gallerySlider')); // add controls
                for (var i = 0; i < galleryThumb.length; i += thumbsPerSlide) {
                    galleryThumb.slice(i, i + thumbsPerSlide).wrapAll('<ul class="galleryThumbs"/>'); // wrap it!
                    $('<span class="bullet"/>').off('click').on('click', function () { // and also, while we're at it, add a bullet for each to the controls
                        //$('.galleryThumbs').eq($(this).index() + 1).trigger('slideTo');
                        if ($(this).index() != 0) {
                            $('.galleryThumbs.active').next().trigger('slideTo');
                        } else {
                            $('.galleryThumbs.active').prev().trigger('slideTo');
                        }
                        //console.log('yep: ', $(this).index());
                    }).appendTo($newControls);
                }
                $('.galleryThumbs:eq(0)').addClass('active').parent().next().find('.bullet:eq(0)').addClass('active');

                $('.gallerySlider').nSwipeSlider().on('nSwipeSlider.swipeDone', function (e, $o, i) {
                    $newControls.children().removeClass('active').eq(i - 1).addClass('active');
                });
            } else {
                galleryThumbWrapper.addClass('noCarousel');
            }

            galleryThumbsWrapper.removeClass('invisible');

            galleryThumb.find('a').off('click').on('click', function (e) {
                e.preventDefault();

                var $this = $(this),
                    $index = ($this.parents('li').index()) + 1;

                sendTracking(detailCategory, 'click_gallery', prodCat + " | " + prodId + " | " + $index);

                galleryThumb.find('a').removeClass('active');
                $this.addClass('active');
                var zoomImgPath = $this.attr('href');

                if ($this.hasClass('heroImgUpdate')) {
                    $('<div class="loader"><div></div></div>').show().appendTo(heroImgWrapper);
                    heroImg.attr('src', zoomImgPath);
                    heroImg.imagesLoaded(function () {
                        $('.loader').remove();
                        heroImg.attr('data-zoom-img', $this.attr('data-zoom-img'));
                        heroImg.trigger('heroImg-loaded');
                    });
                }
                else {
                    if ($this.hasClass('video')) {
                        var mp4video = $this.data('video-mp4'),
                            webmvideo = $this.data('video-webm');

                        var $close = $('<a href="#" class="closeButton"><span></span></a>').on('click', function (e) {
                            e.preventDefault();
                            $('.popover.pdpVideoWrapper').fadeOut(350, function () {
                                $('.popover.pdpVideoWrapper').slideUp(350, function () {
                                    jwplayer('pdpVideo').remove();
                                    $('.popover.pdpVideoWrapper').remove();
                                });
                            });
                        }),
                            $vid = $('<div id="pdpVideo" />'),
                            $popover = $('<div class="popover pdpVideoWrapper" id="popover" />').off('click').on('click', function () {
                                $(galleryThumb).removeClass('active');
                            }).append($close, $vid);

                        $popover.fadeOut(200).insertAfter((galleryThumb.length > 8) ? $('.gallerySlider') : $('.product-detail > .right-col'));
                        $popover.fadeIn(200);

                        jwplayer("pdpVideo").setup({
                            flashplayer: '/Content/jwPlayer6/jwplayer.flash.swf',
                            skin: '/Content/jwplayer6/skins/frigidaire.xml',
                            width: "100%",
                            aspectratio: "16:9",
                            stretching: "fill", // uniform, none, exactfit, fill
                            levels: [
                                { file: mp4video },
                                { file: webmvideo }
                            ],
                            image: $('.video').data('video-poster'),
                            autostart: true,
                            controls: true,
                            icons: true,
                            controlbar: true,
                            volume: 100,
                            'controlbar.position': 'none',
                            events: {
                                onPlay: function () {
                                    setTimeout(function () { $('.pdpVideoWrapper .titleTimeWrapper').fadeOut(200); }, 2000);
                                },
                                onTime: function () {
                                    showDuration();
                                },
                                onPause: function () {
                                    $('.pdpVideoWrapper .titleTimeWrapper').fadeIn(200);
                                }
                            }
                        });

                        function showDuration() {
                            if ($('.pdpVideoWrapper .titleTimeWrapper').length) return;
                            var seconds = jwplayer("pdpVideo").getDuration(),
                                secondsConverted = Math.floor(seconds / 60) + ":" + (seconds % 60).toFixed();
                            $('<div class="titleTimeWrapper"><strong>' + secondsConverted + '</strong> <span>' + $('.video.active').data('video-title') + '</span></div>').appendTo('.pdpVideoWrapper');
                            setTimeout(function () {
                                $('.pdpVideoWrapper .titleTimeWrapper').fadeOut(200);
                            }, 2000);
                        }

                    }
                    else {
                        var $close = $('<a href="#" class="icon-close" />').on('click', function (e) {
                            e.preventDefault();
                            $(this).parent().hide(200);
                            colorChips.removeClass('invisible').addClass('visible');
                        }),
                            $img = $('<img src="" width="669" height="463" alt="" />'),
                            $popover = $('<div class="popover" id="popover" />').off('click').on('click', function () {
                                galleryThumb.find('a').removeClass('active');
                                $(this).hide(200);
                                colorChips.removeClass('invisible').addClass('visible');
                            }).append($close, $img);

                        $popover.hide().insertAfter((galleryThumb.length > 8) ? $('.right-col') : $('.right-col'));

                        $img.attr('src', this.getAttribute('href')).imagesLoaded(function () {
                            $popover.show(200);
                            colorChips.removeClass('visible').addClass('invisible');
                        });
                    }
                }
            });

        }

        //WaterFilers Video
        $('.pdp-video .video').click(function (e) {
            e.preventDefault();
            var $this = $(this);
            var zoomImgPath = $this.attr('href');
            var mp4video = $this.data('video-mp4'),
                webmvideo = $this.data('video-webm');
            var $close = $('<a href="#" class="closeButton"><span></span></a>').on('click', function (e) {
                e.preventDefault();
                $('.popover.pdpVideoWrapper').fadeOut(350, function () {
                    $('.popover.pdpVideoWrapper').slideUp(350, function () {
                        jwplayer('pdpVideo').remove();
                        $('.popover.pdpVideoWrapper').remove();
                    });
                });
            }),
                $vid = $('<div id="pdpVideo" />'),
                $popover = $('<div class="popover pdpVideoWrapper" id="popover" />').off('click').on('click', function () {
                    $(galleryThumb).removeClass('active');
                }).append($close, $vid);

            $popover.fadeOut(200).insertAfter((galleryThumb.length > 8) ? $('.gallerySlider') : $('.product-detail > .subscription-col'));
            $popover.fadeIn(200);

            jwplayer("pdpVideo").setup({
                flashplayer: '/Content/jwPlayer6/jwplayer.flash.swf',
                skin: '/Content/jwplayer6/skins/frigidaire.xml',
                width: "100%",
                aspectratio: "16:9",
                stretching: "fill", // uniform, none, exactfit, fill
                levels: [
                    { file: mp4video },
                    { file: webmvideo }
                ],
                image: $('.video').data('video-poster'),
                autostart: true,
                controls: true,
                icons: true,
                controlbar: true,
                volume: 100,
                'controlbar.position': 'none',
                events: {
                    onPlay: function () {
                        setTimeout(function () { $('.pdpVideoWrapper .titleTimeWrapper').fadeOut(200); }, 2000);
                    },
                    onTime: function () {
                        showDuration();
                    },
                    onPause: function () {
                        $('.pdpVideoWrapper .titleTimeWrapper').fadeIn(200);
                    }
                }
            });

            function showDuration() {
                if ($('.pdpVideoWrapper .titleTimeWrapper').length) return;
                var seconds = jwplayer("pdpVideo").getDuration(),
                    secondsConverted = Math.floor(seconds / 60) + ":" + (seconds % 60).toFixed();
                $('<div class="titleTimeWrapper"><strong>' + secondsConverted + '</strong> <span>' + $('.video.active').data('video-title') + '</span></div>').appendTo('.pdpVideoWrapper');
                setTimeout(function () {
                    $('.pdpVideoWrapper .titleTimeWrapper').fadeOut(200);
                }, 2000);
            }

        });

        //use and care
        $('.swipeThumbs li').each(function (i) {
            i = i + 1;
            $(this).find('>a').addClass('v' + i);
        });

        var swipeThumbWrapper = $('.swipeThumbs'),
            swipeThumb = swipeThumbWrapper.find('li'),
            playlistVideo = $('#playlist .video');

        // if more than 4 items, let's create a sliders!
        if (swipeThumb.length > 4) {
            swipeThumbWrapper.wrap('<div class="slider swipeThumbSlider">');
            swipeThumb.unwrap();
            var $newSwipeControls = $('<span class="sControls"/>').insertAfter($('.swipeThumbSlider')); // add controls
            for (var i = 0; i < swipeThumb.length; i += 4) {
                swipeThumb.slice(i, i + 4).wrapAll('<ul class="swipeThumbs"/>'); // wrap it!
                $('<span class="bullet"/>').off('click').on('click', function () { // and also, while we're at it, add a bullet for each to the controls
                    $('.swipeThumbs').eq($(this).index() + 1).trigger('slideTo');
                }).appendTo($newSwipeControls);
            }
            $('.swipeThumbs:eq(0)').addClass('active').parent().next().find('.bullet:eq(0)').addClass('active');
            $('.swipeThumbSlider').nSwipeSlider().on('nSwipeSlider.swipeDone', function (e, $o, i) {
                $newSwipeControls.children().removeClass('active').eq(i - 1).addClass('active');
            });
        }

        $('#playlist li a').off('click').on('click', function (e) {
            e.preventDefault();
            $('#playlist .video.active').removeClass('active');
            $(this).addClass('active');
            var thisVideoNumber = $(this).attr('class').replace(/[^0-9.]/g, "");
            jwplayer("playlistVideo").playlistItem(thisVideoNumber - 1);
        });

        //temporary frigpro hack for the ratings stars to be purple...
        if ($('.professional').length) {
            var fline = $('[src="/Content/Images/fline5.png"]'),
                star = $('[src="/Content/Images/starsFive.png"]');

            fline.each(function () {
                var $this = $(this);
                $this.attr('src', '/Content/Images/fline5professional.png');
            });

            star.each(function () {
                var $this = $(this);
                $this.attr('src', '/Content/Images/starsFiveprofessional.png');
            });
        }

    }

    function productListPage() {
        if (!$('.list-products').length) return;

        //counter depth
        $.fn.wrapInTag = function (opts) {
            var tag = opts.tag || 'strong', words = opts.words || [], regex = RegExp(words.join('|'), 'gi'), replacement = '<' + tag + '>$&</' + tag + '>';
            return this.html(function () {
                return $(this).text().replace(regex, replacement);
            });
        };

        if (!checkMobileDevice()) {

            // Removing for plp redesign. Moved to side bar filters

            $('.counter-depth-helper').off('mouseenter').on('mouseenter', function () {
                var topOffset = 40;
                var leftOffset = useNewTemplate() ? 100 : 300;
                var $this = $(this), tty = $this.offset().top - topOffset, ttx = $this.offset().left + leftOffset;
                if (tty < 400) {
                    tty = 400;
                }
                $('<div class="plpTooltip"></div>').appendTo('body');
                $('.plpTooltip').css({ top: tty, left: ttx });
                $('.plpTooltip').animate({ 'opacity': 1, 'top': tty + 40 }, 150, "easeInOutExpo");
                //console.log('topOffset: ' + $this.offset().top + ', leftOffset: ' + $this.offset().left);
                //console.log('tty: ' + tty + ', ttx: ' + ttx);
                //console.log('plpTooltip.top: ' + $('.plpTooltip').offset().top + ', plpTooltip.left: ' + $('.plpTooltip').offset().left);
            }).off('mouseleave').on('mouseleave', function () {
                $('.plpTooltip').animate({ 'opacity': 0, 'top': $(this).offset().top - 40 }, 150, "easeInOutExpo", function () {
                    $('.plpTooltip').remove();
                });
            });

            $('.flag-custom-flex').off('mouseenter').on('mouseenter', function () {
                var topOffset = 40;
                var $this = $(this), tty = $this.offset().top - topOffset, ttx = $this.offset().left;
                $('<div class="ttSlide"><h3>Custom-Flex Door</h3><p>Customize to meet your lifestyle with unique bins you can add, move, and adjust.</p></div>').appendTo('body');
                $('.ttSlide').css({ top: tty, left: ttx });
                $('.ttSlide').animate({ 'opacity': 1, 'top': tty + 40 }, 150, "easeInOutExpo");
            }).off('mouseleave').on('mouseleave', function () {
                $('.ttSlide').animate({ 'opacity': 0, 'top': $(this).offset().top - 40 }, 150, "easeInOutExpo", function () {
                    $('.ttSlide').remove();
                });
            });

        } else {
            $('.counter-depth-helper').off('click').on('click', function () {
                var topOffset = 40;
                var leftOffset = 100;
                var $this = $(this), tty = $this.offset().top - topOffset, ttx = $this.offset().left + leftOffset;
                if (tty < 400) {
                    tty = 400;
                }
                $('<div class="plpTooltip"></div>').appendTo('body');
                $('.plpTooltip').css({ top: tty, left: ttx });
                $('.plpTooltip').animate({ 'opacity': 1, 'top': tty + 40 }, 150, "easeInOutExpo");
                //console.log('topOffset: ' + $this.offset().top + ', leftOffset: ' + $this.offset().left);
                //console.log('tty: ' + tty + ', ttx: ' + ttx);
                //console.log('plpTooltip.top: ' + $('.plpTooltip').offset().top + ', plpTooltip.left: ' + $('.plpTooltip').offset().left);
            }).off('mouseleave').on('mouseleave', function () {
                $('.plpTooltip').animate({ 'opacity': 0, 'top': $(this).offset().top - 40 }, 150, "easeInOutExpo", function () {
                    $('.plpTooltip').remove();
                });
            });
        }

        $('.img img').imagesLoaded(function () {
            $('#pl').addClass('loadComplete');
        });

        $('.mobileFilterBtn').off('click').on('click', function (e) {
            e.preventDefault();
            var mobileModalClose = $('<a href="#" class="mobileModalClose">close</a>').off('click').on('click', function () {
                $('.mobileFilterBtn').trigger('click');
            }).appendTo('.filterWrapper');
            if (!$(this).hasClass('active')) {
                $('<div class="modal-wrapper" />').appendTo('body').fadeIn(200);
                $(this).addClass('active');
                $('.filterWrapper').addClass('active').fadeIn(200);
                mobileModalClose.fadeIn(200);
            } else {
                $('.modal-wrapper').remove();
                $(this).removeClass('active');
                $('.filterWrapper').removeClass('active').fadeOut(200);
                mobileModalClose.fadeOut(200);
            }
            if (mobileView()) {
                $('.modal-wrapper').off('click').on('click', function () {
                    $('.mobileModalClose').trigger('click');
                });
            }
        });

        $('[data-select]').off('click.filter-select').on('click.filter-select', function (e) {
            e.preventDefault();
            var target = $(this).data('select');
            if (document.getElementById(target).checked) return;
            $("#" + target + "").trigger('click');
        })

    }

    function timeline() {
        if ($('.tlWrapper').length === 0) return;

        $(".tlSlider").slider({
            value: 0,
            min: 0,
            max: $('.yearWrapper').length - 1,
            step: 1,
            //slide: function (event, ui) {
            //    $('.tlYears > li').removeClass('active').eq(ui.value).addClass('active');
            //},
            stop: function (event, ui) {
                $('.tlFirstSlide').fadeOut(350);
                $('.tlYears > li').eq(ui.value).trigger('click');
                sendTracking('innovations', 'click_slider', $('.tlYears > li.active').text());
            }
        });

        $(document).on('click', '.tlFirstSlide a', function (e) {
            e.preventDefault();
            sendTracking('innovations', 'click_go_now');
            $('.tlFirstSlide').fadeOut(350);
            $('.tlNavFuture').show();
            $('.tlFooter').addClass('active');
        });

        //temporarily remove 2013 slide from the french site, uncomment following line when timeline is ready.
        //$('.en-ca .yearWrapper[data-year="2013"], .fr-ca .yearWrapper[data-year="2013"], .en-ca .tlYears > li:last-child, .fr-ca .tlYears > li:last-child').remove();

        $('.yearWrapper').last().find('.innovationModal:eq(2)').find('.nextInnovation').remove();
        $('.yearWrapper').first().find('.innovationModal').first().find('.prevInnovation').remove();

        var yearWrapperContainers = $('.yearWrapper');
        var yearItemFrame = $('.yearWrapper > .yearItem');

        //add links for nested items
        yearWrapperContainers.each(function () {
            var totNestedItems = $(this).find('.yearItem').size();
            if (totNestedItems > 1) {
                $(this).addClass('multipleNestedItems');
                $(this).find('.yearItem').eq(0).addClass('active');
            }
        });

        yearItemFrame.each(function () {
            var totModalsInsideSlide = $(this).find('.innovationModal').size();
            if (totModalsInsideSlide > 1) { $(this).addClass('multipleLearnMoreLinks'); }
        });

        //open modal
        $(document).on('click', '.tlLearnMore', function (e) {
            sendTracking('innovations', 'click_learn_more', $(this).parents('.yearWrapper').find('.tlHeadlines').text());
            e.preventDefault();
            $('.tlOverlay').each(function () {
                $(this).remove();
            });
            $('.tlMainFooter').fadeOut(200);
            $('.tlNavPast').fadeOut(200);
            $('.tlNavFuture').fadeOut(200);
            var id = $(this).attr('href');
            $(id).fadeIn(200);
            calcModalHeight(id);
            $('<div class="tlOverlay">overlay</div>').prependTo('.yearWrapper.active .yearItem').fadeIn(200);
        });

        //close modal
        $(document).on('click', '.tlWrapper .modalClose', function (e) {
            e.preventDefault();
            $('.tlMainFooter').fadeIn(200);

            if ($(this).parent().parent().parent().parent().parent().attr('data-year') === "1929") {
                $('.tlNavFuture').show();
                $('.tlNavPast').show();
            }
            else if ($(this).parent().parent().parent().parent().parent().attr('data-year') === "2013") {
                $('.tlNavFuture').hide();
                $('.tlNavPast').show();
            }
            else if ($(this).parent().parent().parent().parent().parent().attr('data-year') === "1918") {
                $('.tlNavPast').hide();
                $('.tlNavFuture').show();
            }
            else {
                $('.tlNavPast').show();
                $('.tlNavFuture').show();
            }

            $(this).parents('.innovationModal').fadeOut(200);
            $('.tlOverlay').fadeOut(200).remove();
        });

        //navigate slides
        var years = $('.tlYears > li'),
            yearActiveSlide = $('.tlMainContent > div.active'),
            yearSlides = $('.tlMainContent > div'),
            activeYear = 0;

        //click next year
        $(document).on('click', '.nextYear', function (e) {
            e.preventDefault();
            var id = $('.tlYears > li.active').index() + 1;
            $('.tlYears > li:eq(' + id + ')').trigger('click');
            sendTracking('innovations', 'click_arrow', $('.tlYears > li.active').text());
        });

        //click prev year
        $(document).on('click', '.prevYear', function (e) {
            e.preventDefault();
            var id = $('.tlYears > li.active').index() - 1;
            $('.tlYears > li:eq(' + id + ')').trigger('click');
            sendTracking('innovations', 'click_arrow', $('.tlYears > li.active').text());
        });

        //click first year
        $(document).on('click', '.firstYear', function (e) {
            e.preventDefault();
            $('.tlYears > li:first').trigger('click');
        });

        //click last year
        $(document).on('click', '.lastYear', function (e) {
            e.preventDefault();
            $('.tlYears > li:last').trigger('click');
        });

        //click next innovation inside of modal
        $(document).on('click', '.nextInnovation', function (e) {
            e.preventDefault();
            var yearItems = $(this).closest('.yearWrapper').find('.yearItem');

            //show next item in the same year slide
            if (yearItems.length > 1 && !yearItems.eq(1).is(':visible')) {
                yearItems.eq(1).fadeIn(200).addClass('active');
                $('.nestedItemLink.nextOne').fadeOut(200);
                $('.modalClose').trigger('click');
                $('.nestedItemLink.nextOne').fadeOut(200);
            }

            //go to next modal within same yearItem
            else if (($(this).closest('.yearWrapper > .yearItem').find('.innovationModal').length > 1) && !$(this).prev().hasClass('lastBtn2012')) {
                $(this).parent().parent().parent().parent().fadeOut(200);
                $('.tlOverlay').fadeOut(200);
                $(this).parent().parent().parent().parent().parent().find('.tlLinks > .tlLearnMore:eq(1)').trigger('click');
            }

            else {
                var id = $('.tlYears > li.active').index() + 1;
                $('.tlYears > li:eq(' + id + ')').trigger('click');
            }
        });

        //click previous innovation inside of modal
        $(document).on('click', '.prevInnovation', function (e) {
            e.preventDefault();
            var yearItems = $(this).closest('.yearWrapper').find('.yearItem');

            if ($(this).hasClass('lastBtn2012')) {
                $(this).parent().parent().parent().parent().fadeOut(200);
                $('.tlOverlay').fadeOut(200);
                $(this).parent().parent().parent().parent().parent().find('.tlLinks > .tlLearnMore:eq(0)').trigger('click');
            }

            else if (yearItems.length > 1 && yearItems.eq(1).hasClass('active')) {
                yearItems.eq(1).fadeOut(200).removeClass('active');
                yearItems.eq(0).fadeIn(200);
                $('.nestedItemLink.nextOne').fadeIn(200);
                yearItems.find('.modalClose').trigger('click');
            }

            else if ((yearItems.hasClass('multipleLearnMoreLinks')) && (yearItems.find('.innovationModal').eq(0).is(':visible'))) {
                var id = $('.tlYears > li.active').index() - 1;
                $('.tlYears > li:eq(' + id + ')').trigger('click');
            }

            else if (($(this).closest('.yearWrapper > .yearItem').find('.innovationModal').length > 1) && ($(this).closest('.yearWrapper > .yearItem').find('.innovationModal').eq(1))) {
                $(this).parent().parent().parent().parent().fadeOut(200);
                $('.tlOverlay').fadeOut(200);
                $(this).parent().parent().parent().parent().parent().find('.tlLinks > .tlLearnMore:eq(0)').trigger('click');
            }
            else {
                var id = $('.tlYears > li.active').index() - 1;
                $('.tlYears > li:eq(' + id + ')').trigger('click');
            }
        });

        //open next nested item (example: 1929b)
        $(document).on('click', '.nestedItemLink.nextOne', function () {
            var yearItems = $(this).closest('.yearWrapper').find('.yearItem');
            yearItems.eq(1).fadeIn(200).addClass('active');
            yearItems.eq(0).removeClass('active');
            $('.nestedItemLink.nextOne').fadeOut(200);
        });

        //open prev nested item (example: 1929b)
        $(document).on('click', '.nestedItemLink.prevOne', function () {
            var yearItems = $(this).closest('.yearWrapper').find('.yearItem');
            yearItems.eq(1).fadeOut(400);
            setTimeout(function () { yearItems.eq(0).addClass('active'); yearItems.eq(1).removeClass('active'); }, 400);
            $('.nestedItemLink.nextOne').fadeIn(400);

        });

        if (mobileView()) {
            $('.tlWrapper').touchwipe({
                wipeLeft: function () { $('.nextYear').trigger('click'); },
                wipeRight: function () { $('.prevYear').trigger('click'); },
                min_move_x: 40,
                preventDefaultEvents: false
            });
        }

        $(document).on('click', '.tlYears > li', function () {
            if ($('.tlFirstSlide').is(':visible')) {
                $('.tlFirstSlide').fadeOut(350);
                $('.tlNavFuture').show();
                $('.tlFooter').addClass('active');
            }
            $('.innovationModal').hide();

            if ($('.secondOne').hasClass('active')) {
                setTimeout(function () { $('.nestedItemLink.prevOne').trigger('click'); $(this).removeClass('active'); $('.secondOne').hide(); }, 1000);
            }

            if ($(this).hasClass('active')) return;
            if ($('.yearWrapper').is(':animated')) return;

            $('.tlMainFooter, .tlNavPast, .tlNavFuture').show();
            $('.tlOverlay').remove();
            $('.tlLearnMore, .nextYear span, .prevYear span, .firstYear span, .lastYear span').hide();

            $('.tlYears > li').removeClass('active');
            $(this).addClass('active');

            var id = $(this).index(),
                yearWrapperWidth = $('.yearWrapper').width(),
                beforeClone = $('[data-year=' + $(this).text() + ']'),
                afterClone = beforeClone.clone();

            beforeClone.addClass('currentImage').before(afterClone);

            //load img
            afterClone.find('img.timelineBgImage').attr({ src: '' });
            var acImgDataSource = afterClone.find('img.timelineBgImage').attr({ src: afterClone.find('img.timelineBgImage').attr('data-img-src') });

            //might need to uncomment the code below for mobile since the width of the slides may have to be wider in order to make them taller.
            //if (!$('html').hasClass('mobile')) {
            $('.yearWrapper > div > img').width($('.tlMainContent').width());
            //} else {
            //    $('.yearWrapper > div > img').width($('.tlMainContent').width() + 100);
            //}

            //fade in Learn More link once the img loads
            acImgDataSource.imagesLoaded(function () {
                afterClone.find('.tlLearnMore').fadeIn(1000);
            });

            if (afterClone.attr('data-year') === "2013") {
                $('.tlNavFuture').fadeOut(600);
            }
            else if (afterClone.attr('data-year') === "1918") {
                $('.tlNavPast').fadeOut(600);
            }

            if (id > activeYear) {
                $('.slideLoader').fadeIn(200);
                acImgDataSource.imagesLoaded(function () {
                    $('.slideLoader').fadeOut(200);
                    $('.currentImage').css({ "left": 0, "right": "auto" });
                    $('.currentImage').animate({ left: -yearWrapperWidth }, 1500, "easeInOutExpo", function () { currentImage(); });
                    afterClone.appendTo('.tlMainContent').addClass('active');
                    afterClone.css({ "right": -yearWrapperWidth, "left": "auto" });
                    afterClone.animate({ right: 0 }, 1500, "easeInOutExpo", function () { afterClone.addClass('currentImage'); });
                });
            }
            else {
                $('.slideLoader').fadeIn(200);
                acImgDataSource.imagesLoaded(function () {
                    $('.slideLoader').fadeOut(200);
                    $('.currentImage').css({ "right": 0, "left": "auto" });
                    $('.currentImage').animate({ right: -yearWrapperWidth }, 1500, "easeInOutExpo", function () { currentImage(); });
                    afterClone.prependTo('.tlMainContent').addClass('active');
                    afterClone.css({ "left": -yearWrapperWidth, "right": "auto" });
                    afterClone.animate({ left: yearWrapperWidth - yearWrapperWidth }, 1500, "easeInOutExpo", function () { afterClone.addClass('currentImage'); });
                });
            }

            function currentImage() {
                beforeClone.remove();
                $('.currentImage').removeClass('active');
                $('.currentImage').removeClass('currentImage');
            }

            activeYear = id;

            $('.tlSlider').slider({ value: $(this).index() });
        });

        //image preloads for hovers
        preHover1 = new Image();
        preHover2 = new Image();
        preHover1.src = "/Content/Images/Timeline/learnMoreLeftHover.png";
        preHover2.src = "/Content/Images/Timeline/learnMoreRightHover.png";

        $('.yearWrapper > div > img:eq(0)').attr({ src: $('.yearWrapper > div > .timelineBgImage:eq(0)').attr('data-img-src') });

        //if (!$('html').hasClass('mobile')) {
        $('.yearWrapper > div > img').width($('.tlMainContent').width());
        //} else {
        //    $('.yearWrapper > div > img').width($('.tlMainContent').width() + 100);
        //}

        $('.yearWrapper > div > img:eq(0)').imagesLoaded(function () {

            $('.prevInnovation > span').each(function () {
                $(this).html($('.tlMainContent').attr('data-prevInnovationText'));
            });
            $('.nextInnovation > span').each(function () {
                $(this).html($('.tlMainContent').attr('data-nextInnovationText'));
            });
            $('.tlLearnMore').each(function () {
                $(this).find('> span').before($('.tlMainContent').attr('data-learnMoreText'));
            });

            $('.slideLoader').fadeOut(600);
            $('.tlMainContent').height($('.yearWrapper > div > img:eq(0)').height());
            $('.tlMainContent > .yearWrapper:eq(0) .tlLearnMore').fadeIn(800);
        });

        //timeline tracking
        jwplayer("videoChip").onTime(function (e) { //tracking for half way through video
            var halfTime = Math.floor(jwplayer('videoChip').getDuration() / 2),
                halfTimeBump = halfTime + .20;
            if (e.position >= halfTime && e.position <= halfTimeBump) {
                frigidaire.sendTracking('innovations', 'video_50_complete');
            }
        });

        jwplayer("videoChip").onPlay(function () {
            frigidaire.sendTracking('innovations', 'video_play');
        });

        jwplayer("videoChip").onComplete(function () {
            frigidaire.sendTracking('innovations', 'video_play', 'video_100_complete');
        });
    }

    function onPageResize() {
        // Confetti banner hack for air fry day
        sizeConfettiBanner();

        //Product Detail Page
        if ($('.product-detail').length) {
            //tab clears/column heights
            if (mobileView()) {
                $('.pdpTabContents > .col').removeClass('pdpTabClear');
                $('.pdpTabContents > .col:nth-child(2n+1)').addClass('pdpTabClear');
                $('.pdp-features').click(function () {
                    $('.pdpTabClear').each(function (i) {
                        $(this).addClass('row' + i);
                        $(this).next().addClass('row' + i);
                        $('img').imagesLoaded(function () { matchColHeights('.row' + i); });
                    });
                });
            }
            else {
                $('.pdpTabContents > .col').removeClass('pdpTabClear');
                $('.pdpTabContents > .col:nth-child(3n+1), section .slider > li:nth-child(3n+1)').addClass('pdpTabClear');
            }
        }

        if (($('.quarterBlock').length) || ($('.equalHeight').length)) {
            $('img').imagesLoaded(function () {
                matchColHeights('.quarterBlock');
                matchColHeights('.equalHeight');
            });
        }
    }

    //function subMenus() {
    //    var menuClicked = false,
    //		id = 'subMenuContainer',
    //		$submenus = $('.header-container .nav-links > li > div'),
    //           closeText = $('.header-nav').data('close-text'),
    //		closeBtn = $('<a href="#" class="icon-close right dd-close">' + closeText + '</a>'),
    //		$menuContainer = ($('#' + id).length > 0) ? $('#' + id) : $('<div id="' + id + '" />').appendTo('.header-container header'),
    //		$body = $('body'),
    //		headerWrapper = $('.header-container'),
    //		$headerContainer = $('.header-container > header'),
    //		bodyPaddDesktop = ($('html').is('.tablet.portrait')) ? 57 : 126,
    //		scrollPosWasZero = false,
    //		menuTimer = -1,
    //		$menuObject = null,
    //		initialHover = null,
    //		paddTop = parseInt($headerContainer.css('paddingTop')),  //parseInt($('.header-container > header').css('paddingTop'))
    //		scroll = $(window).scrollTop(),
    //		padd = 0,
    //           initialHeaderHeight = headerWrapper.outerHeight(),
    //           banner = $('.NotifyBanner--alt');

    //    var diffcheck = banner.is('.is-active');

    //       globHeaderHeight = frigidaire.headerHeight();

    //       //navHeader = $('.header-container').outerHeight();

    //	closeBtn.hide().appendTo('#subMenuContainer');

    //	$('#subMenuContainer').off('mouseenter').off('mouseleave');

    //	$submenus.each(function ()
    //	{
    //		$(this).find('ul').addClass('menuItems' + $(this).find('ul li').length); //added to style menus that have different amounts of links

    //		$(this).prevAll('a').parent().off('click').on('click', function (e)
    //		{
    //			if ($(this).find('ul a, ol a, table').length === 0) return;
    //			e.preventDefault();
    //			$menuObject = $(this);

    //			if (!$(this).hasClass('open')) {
    //				if ($(this).siblings().hasClass('open')) {
    //					hideMenu(function () { showMenu(); });
    //				} else {
    //					showMenu();
    //					closeBtn.fadeIn(300);
    //				}
    //			} else {
    //				hideMenu();
    //				closeBtn.fadeOut(300);
    //			}

    //		});
    //	});

    //	$('#subMenuContainer').off('mouseenter').on('mouseenter', function () {
    //		$(this).addClass('menuOver');
    //	})
    //	.off('mouseleave').on('mouseleave', function () {
    //		$(this).removeClass('menuOver');
    //	});

    //	//animate the top menu on scroll
    //	if (!mobileView()) {
    //	    $(window).on('scroll menuPadd', function () {
    //	        scroll = $(window).scrollTop();
    //	        padd = Math.max(paddTop - (scroll / 2));

    //	        if (scroll === 0) {
    //				headerWrapper.removeClass('fixedHeader');
    //				$headerContainer.css('padding', padd + 'px 0');
    //				document.body.style.paddingTop = 0;
    //				globHeaderHeight = frigidaire.headerHeight();
    //				return;
    //	        }

    //	        $body.css('paddingTop', globHeaderHeight);
    //	        headerWrapper.addClass('fixedHeader');

    //	        if (frigidaire.lang() !== 'en-us' && ($('.NotifyBanner--lrgFixed').length)) {
    //	            return;
    //	        }

    //			$headerContainer.css('padding', padd + 'px 0');
    //		});
    //	    $(window).trigger('menuPadd');
    //	}

    //	var animating = false;
    //	function showMenu(quick) {
    //		if (animating) return;
    //		animating = true;
    //		$menuObject.addClass('open');
    //		$menuObject.find('>div').clone().appendTo($menuContainer);

    //		var maxScrollHeight = $(window).height() - ($('.header-nav').outerHeight() + parseInt($('header').css('paddingTop')));

    //		$menuContainer.css({'max-height':maxScrollHeight});

    //		$menuContainer.animate({ height: $menuContainer.find('>div').outerHeight() }, 300, function () {
    //			// turn off scrolling of cart in header...
    //		    $('.cart .scroller').scrollLock();
    //		    animating = false;
    //		    if ($('html').hasClass('tablet')) {
    //		        $('#subMenuContainer > div').scrollLock();
    //		    }
    //		});

    //		$('#subMenuContainer .icon-close').off('click').on('click', function (e) {
    //			e.preventDefault();
    //		    if (!!$('#subMenuContainer').find('.cart').length && !!$(this).hasClass('dd-close')) { //if on ecom, then send tracking
    //		        frigidaire.sendTracking('topnav', 'click_close_cart');
    //		    }
    //			hideMenu();
    //		});

    //		$('body').off('click scroll').on('click scroll', function (e) {
    //			if (!$(e.target).is('header *') || !$('header *').has(e.target)) {
    //				$('#subMenuContainer .icon-close').trigger('click');
    //				$('body').unbind('click scroll');
    //			}
    //		});

    //		initScrollPos = $(window).scrollTop();
    //		$(window).on('scroll.hidemenu', function () {
    //				newScrollPos = $(window).scrollTop();
    //				if (initScrollPos === 0) {
    //					scrollPosWasZero = true;
    //				} else {
    //					scrollPosWasZero = false;
    //				}

    //				if(Math.abs(newScrollPos - initScrollPos) > 150){
    //					hideMenu();
    //				}
    //		});

    //	}

    //	function hideMenu(callback)
    //	{
    //		if (animating) return;
    //		clearTimeout(menuTimer);
    //		menuTimer = -1;
    //		$submenus.parents('ul').find('.open').removeClass('open');

    //		if (typeof callback === "function") {
    //			$menuContainer.empty();
    //			closeBtn.appendTo('#subMenuContainer');
    //			callback();
    //		} else {
    //			animating = true;
    //			closeBtn.fadeOut(150);
    //			setTimeout(function () {
    //				$menuContainer.animate({ height: 0 }, 300, function () {
    //					$(this).empty();
    //					closeBtn.appendTo('#subMenuContainer');
    //					animating = false;
    //				});
    //				if (($(window).scrollTop() === 0) || (scrollPosWasZero === true)) {
    //					//$body.animate({ paddingTop: bodyPaddDesktop }, 300);
    //					scrollPosWasZero = false;
    //				}
    //			}, 10);
    //			$(window).off('scroll.hidemenu');
    //		}

    //	}

    //	if (mobileView()) {
    //		var mobileNav = $('#mobileNav'),
    //			mainContainer = $('#mainContainer');

    //		if ($('.mainMobileNav .nav-links').length) return;

    //		$('.wrapper .nav-links').clone().removeClass('mobile-hide').prependTo('.mainMobileNav');

    //		$(".mobile-icon").touchwipe({
    //			wipeLeft: function () { $('.mobile-icon').trigger('click'); },
    //			wipeRight: function () { $('.mobile-icon').trigger('click'); }
    //		});

    //		$('.mobile-icon').off('click').on('click', function (e) {
    //			e.preventDefault();
    //			$('#mobileNav').height($('body').height());
    //			if (!$('body').hasClass('mobileNavActive')) {
    //				$('body').addClass('mobileNavActive');
    //			}
    //			else {
    //				$('body').removeClass('mobileNavActive');
    //			}
    //		});

    //		$('#mobileNav ul.nav-links li a').off('click').on('click', function (e) {
    //			if ($(this).next('div').find('li').length) {
    //				e.preventDefault();
    //				$('.nestedNav > span').text($(this).text());
    //				$(this).next('div').clone().appendTo('.nestedNav');
    //				$('ul.nav-links').addClass('subNavHide');
    //				$('.nestedNav').addClass('active');
    //			}
    //		});

    //		$('.backToMainMenu').off('click').on('click', function (e) {
    //			e.preventDefault();
    //			$(this).parent().find('>div').remove();
    //			$('ul.nav-links').removeClass('subNavHide');
    //			$('.nestedNav').removeClass('active');
    //		});
    //	}

    //}


    // Header: Search & Login panels
    function headerPanel(useOverlay) {
        useOverlay = useOverlay || false;

        var animateStyle = 'swing',
            animateRate = 350,
            panelHeight = '142px',
            header = '.header-container',
            sectionHeader = $('.topPanel', header),
            loginSection = $('.login_form', sectionHeader),
            searchSection = $('.search_form', sectionHeader),
            searchBar = $('.search_input', searchSection),
            searchBtn = $('.searchButton', header),
            loginBtn = $('.loginButton', header),
            langClose = (frigidaire.lang() === 'fr-ca' ? 'fermer' : 'close'),
            $close = $('<a href="#" class="icon-close">' + langClose + '</a>'),

            searchFunctions = function () {
                searchSection.find('label').addClass('transition');

                searchBar.on('keyup change', function (e) {
                    searchSection[e.target.value ? 'addClass' : 'removeClass']('typing');
                });
            },

            overlay = {

                o: $('<div class="overlay" />'),

                place: function (fn) {
                    if (!useOverlay) return;
                    this.o.hide().appendTo('body').on('click', function () {
                        overlay.close(fn);
                    });
                },

                close: function (fn) {
                    if (!useOverlay) return;
                    if (typeof fn === 'function') fn(); // callback

                    //this.o.show(animateRate);
                    this.o.animate({ 'height': 0, 'top': 0, 'opacity': 0 }, animateRate, animateStyle);
                },

                open: function () {
                    if (!useOverlay) return;
                    //this.o.hide(animateRate);
                    var h = $('body').height() + 'px';
                    this.o.animate({ 'height': h, 'top': panelHeight, 'opacity': 1 }, animateRate, animateStyle);
                }

            },

            panelClose = function (e) {
                $('.searchButton').removeClass('active');
                if (e) e.preventDefault();
                //loginSection.add(searchSection).hide();
                $close.fadeOut(200);
                sectionHeader.animate({ 'margin-top': '-' + panelHeight }, animateRate, animateStyle, function () {
                    overlay.close();
                    $(this).hide();
                });
                $(window).off('scroll.hidemenu');
            },

            panelOpen = function (e) {
                e.preventDefault();
                if ($(this).hasClass('active')) {
                    panelClose();
                }
                else {

                    $(this).addClass('active');
                    var hasSearchBtn = $(e.target).hasClass('searchButton'),
                        visibleSection = hasSearchBtn ? searchSection.show(125) : loginSection.show(125),
                        hiddenSection = hasSearchBtn ? loginSection.hide(125) : searchSection.hide(125);

                    sectionHeader.css({ 'margin-top': '-' + panelHeight }).show().animate({ 'margin-top': 0 }, animateRate, animateStyle, function () {
                        $close.fadeIn(200);
                        if (!$('html').is('ie8')) {
                            visibleSection.find('input').eq(0).focus();
                        }
                    });

                    overlay.open();
                    searchFunctions();

                }

                if (!mobileView()) {
                    //if (!$('html').is('.tablet.portrait')) {
                    if (!checkMobileDevice()) {
                        $(window).on('scroll.hidemenu', function () {
                            panelClose();
                        });
                    }
                }

                $('body').off('click').on('click', function (e) {
                    if (!$(e.target).is('.header-container *') || !$('.header-container *').has(e.target)) {
                        panelClose();
                        $('body').unbind('click');
                    }
                });

            };

        // init //
        (function () {
            panelHeight = sectionHeader.css('height');
            searchBtn.add(loginBtn).on('click', panelOpen);
            loginSection.add(searchSection).hide();
            $close.hide().prependTo(sectionHeader).on('click', panelClose);
            overlay.place(panelClose); // passes callback
        })();
    }

    function bubbleModal() {
        var modalContact = $('.modal-contact');

        if (!modalContact.length) return;

        var $collapseBtn = $('<a href="#" class="icon-collapse">close</a>'),
            $expandBtn = $('<a href="#" class="icon-expand">expandBtn</a>'),
            $closeBtn = $('<a class="closeIconX" href="#"></a>'),
            modalContact = $('.modal-contact'),
            expandedModalConent = $('.expandedModalConent'),
            collapsedModalConent = $('.collapsedModalConent'),
            devHeight = mobileView() ? 57 : 200;

        if (!!$('#sideCart').length) {
            modalContact.insertAfter($('#sideCart').parent().parent());
        } else {
            modalContact.show().animate({ height: devHeight, opacity: 1 }, 500, function () {
                if (mobileView()) {
                    $closeBtn.appendTo($(this));
                } else {
                    $collapseBtn.appendTo($(this));
                    $expandBtn.appendTo(modalContact);
                }
            });
        }

        $closeBtn.off('click').on('click', function (e) {
            e.preventDefault();
            modalContact.remove();
            sendTracking(tracking.pageTrackingCategory(), 'click_close_float');
        });

        $collapseBtn.off('click').on('click', function (e) {
            e.preventDefault();
            modalContact.animate({ height: collapsedModalConent.height() }, 100);
            expandedModalConent.hide();
            collapsedModalConent.show();
            $collapseBtn.hide();
            $expandBtn.show();
            sendTracking(tracking.pageTrackingCategory(), 'click_close_float');
        });

        $expandBtn.off('click').on('click', function (e) {
            e.preventDefault();
            modalContact.animate({ height: expandedModalConent.height() }, 100);
            expandedModalConent.show();
            collapsedModalConent.hide();
            $expandBtn.hide();
            $collapseBtn.show();
        });

        $('.bubble-email').off('click').on('click', function () {
            sendTracking(tracking.pageTrackingCategory(), 'click_email');
        });

        $('.bubble-call').off('click').on('click', function () {
            sendTracking(tracking.pageTrackingCategory(), 'click_call');
        });

    }

    function filterRadioAndCheckboxes() {
        // checkboxes and radiobuttons
        $('.form-filter input[type=checkbox], .form-filter input[type=radio]').each(function (i) {
            // if it's the filterbar AND it's ie7 or ie8, don't set any events at all.
            if ($('html').hasClass('ie7') || $('html').hasClass('ie8')) return;
            var tempclass = ($(this).attr('type') === 'checkbox') ? 'jsCheckBox' : 'jsRadioButton';
            $('<div class="' + tempclass + '"><a href="#"></a></div>').insertAfter($(this)).find('a').unbind('click').bind('click', function (e) {
                e.preventDefault();
                $(this).parent().prev().trigger('click').trigger('change.jsCheckbox');
            });
            $(this).hide();

            if ($(this).is(':checked')) $(this).next().find('a').addClass('active');

            $(this).bind('change.jsCheckbox', function () {
                // if radiobutton, loop through all with same name and uncheck before checking... (no change event on the one getting unchecked!)
                if ($(this).attr('type') === 'radio') {
                    var name = $(this).attr('name');
                    $('input[type=radio]').each(function () { if ($(this).attr('name') === name) { $(this).next().find('a').removeClass('active'); } });
                }

                if ($(this).is(':checked')) {
                    $(this).next().find('a').addClass('active');
                } else {
                    $(this).next().find('a').removeClass('active');
                }
            });

            $(this).on('wzp.fixDisabled', function () {
                if ($(this).is(':disabled')) {
                    $(this).next().find('a').addClass('disabled');
                } else {
                    $(this).next().find('a').removeClass('disabled');
                }
            });
        });
    }

    function deviceChange() {
        var $cartButtonNav = $('.cartButton');

        if (!mobileView()) {
            $cartButtonNav.detach().appendTo($('.cartButtonWrapper'));
        }
        else {
            $cartButtonNav.detach().insertAfter($('.mobile-icon'));
        }
    }

    function global() {
        if (!mobileView()) {
            $('select:not(".ignore")').selectmenu();
        }
        else {
            $('select:not(".ignore")').uniform();
        }

        $(document).off('change.selectbox').on('change.selectbox', '.pageContWrapper select:not(".ignore"), .friModalWrapper select:not(".ignore")', function () {
            if (!mobileView()) {
                $('select').selectmenu();
            }
            else {
                $('select').uniform.update();
            }
            if ($('.addNewOrEditAddressWrapper').length) {
                $('#StateName').val($('#State option:selected').text());
            }
        });

        langCode = $('.topPanel .search_input').data('lang');

        $('.chipTT').off('mouseenter').on('mouseenter', function () {
            var $this = $(this), tty = $this.offset().top - 40, ttx = $this.offset().left;
            $('<div class="chipTTwrapper ' + $this.data('chip-style') + '"></div>').appendTo('body');
            $('.chipTTwrapper').css({ top: tty, left: ttx });
            $('.chipTTwrapper').animate({ 'opacity': 1, 'top': tty + 40 }, 150, "easeInOutExpo");
        }).off('mouseleave').on('mouseleave', function () {
            $('.chipTTwrapper').animate({ 'opacity': 0, 'top': $(this).offset().top - 40 }, 150, "easeInOutExpo", function () {
                $('.chipTTwrapper').remove();
            });
        });

        $('.triggerVideo').off('click').on('click', function (e) {
            e.preventDefault();
            $(this).parents('.featureBlock').find('.relative .friModalSize').trigger('click');
        });

        $('.pressListing .col:nth-child(3)').addClass('newRow');

        $('input[type=radio]:not(".ignore"), input[type=checkbox]:not(".ignore")').uniform();

        $('.mobile-navigation').clone().appendTo('footer .col.pink > div'); //cloning part of footer nav to show on mobile

        if ($('html').is('.ie8')) {
            $('.col-2 > .col:nth-child(2n+1), .col-3 > .col:nth-child(3n+1), .col-4 > .col:nth-child(4n+1)').addClass('nth'); //nthchild for ie8
        }

        $(document).off('click', '.print-page').on('click', '.print-page', function (e) {
            e.preventDefault();
            window.print();
        });

        $(document).off('click', '.share-page').on('click', '.share-page', function (e) {
            e.preventDefault();
            if (frigidaire.mobileView() && $('.mobile-div-sharelinks').length > 0) {
                var sharelinks = $('.mobile-div-sharelinks')[0].innerHTML;
                friModalSize.openModal(sharelinks, '300px', '', '', 'html');

                $(".trigger-mobile-share").click(function (e) {
                    sharingHandler(e, $(this));
                });
                $(".trigger-mobile-share-mail").click(function (e) {
                    e.preventDefault();
                    $('.friModalWrapper').remove();
                    $('.loaderModal').remove();
                    friModalSize.openModal('/modal/emailafriend/index/id?url=' + window.location.href, '300px', '', '', '');
                });
            }
            else if ($(".div-sharelinks").length > 0) {
                if ($(".div-sharelinks").is(":visible"))
                    $(".div-sharelinks").hide();
                else
                    $(".div-sharelinks").show();
            }

            $(".trigger-share-mail").click(function (e) {
                e.preventDefault();
                friModalSize.openModal('/modal/emailafriend/index/id?url=' + window.location.href, '450px', '', '', '', function () {
                    if ($('#SubmitEmail').length > 0) {
                        $('#SubmitEmail').addClass('btn--primary');
                    }
                });
                if ($('.closeModal').length > 0) {
                    $('.closeModal').addClass('vbi-close-modal');
                }

            });
        });
        //recipe email shopping list modal 
        $(".recipe-email-shopping-list").click(function (e) {
            e.preventDefault();
            friModalSize.openModal(window.location.href + "/EmailShoppingList", '450px', '', '', '');
            if ($('.closeModal').length > 0) {
                $('.closeModal').addClass('vbi-close-modal');
            }
        });

        //Share Icon menu on the blog recipe pages
        if ($('.container-div-iconbar').length > 0) {
            if ((navigator.userAgent.toLowerCase().indexOf("msie") != -1 || navigator.userAgent.match(/Trident\/7\./))) {
                $('.container-div-iconbar').removeClass('flex-item');
            }
        }

        //Article card Video
        $('.article-card-video').each(function () {
            if ($(this).closest('.article-card')[0].getAttribute("play-inline-video") === "True") {
                $(this).click(function (e) {
                    return setupArticleCardInlineVideo(e, this);
                })
            }
        })

        $('.article-card-video-button').each(function () {
            if ($(this).closest('.article-card')[0].getAttribute("play-inline-video") === "True") {
                $(this).off('click');
                $(this).click(function (e) {
                    return setupArticleCardInlineVideo(e, this);
                })
            }
        })
        //tooltip left
        if ($('.tooltipBubble').length) {
            $('.tooltipBubble').off('click').on('click', function (e) {
                e.preventDefault();
                var $this = $(this),
                    ttLeft = $('.ttLeft'),
                    posY = $this.offset().top,
                    posX = (!mobileView() ? $this.offset().left : 0);

                var clonedTT = ttLeft.clone().appendTo('body');
                clonedTT.wrap('<div class="ttWrapper"></div>');
                $('.ttWrapper').css({
                    'height': $('.ttWrapper').outerHeight(),
                    'top': posY,
                    'left': posX
                });
                clonedTT.css({ 'visibility': 'visible' });
                clonedTT.animate({
                    top: (!mobileView() ? 'auto' : 25),
                    left: (!mobileView() ? 35 : 0),
                    opacity: 1
                }, 350, 'easeOutCubic');

                $('.buttonClose').off('click').on('click', function (e) {
                    e.preventDefault();
                    clonedTT.animate({
                        top: (!mobileView() ? 'auto' : 0),
                        left: 0,
                        opacity: 0
                    }, 350, 'easeOutCubic', function () {
                        $('.ttWrapper').remove();
                    });
                });
            });
        }

        //old school accordian as seen on pages such as compare
        var manualAccordion = $('.manualAccordions .accordion > section');

        manualAccordion.find('> h2').off('click').on('click', function () {
            if (!$(this).hasClass('active')) {
                $(this).addClass('active');
                $(this).next().slideDown(350);
            } else {
                $(this).removeClass('active');
                $(this).next().slideUp(350);
            }
        });

        //search textbox styling
        $('.search_form').find('label').addClass('transition');

        $('.search_wrapper').each(function () {
            $('<div class="pressEnterTxt">' + $(this).data('searching-text') + '</div>').prependTo($(this));
        });

        $(document).on('keyup.pressEnterText change.pressEnterText', '.search_input', function (e) {
            if ($(this).val().length > 0) {
                $(this).parents('.search_form')[e.target.value ? 'addClass' : 'removeClass']('typing');
                $('.movingText').remove();
                $('<span class="movingText">' + $(this).val() + '</span>').prependTo($(this).parent());
                $(this).parent().find('.pressEnterTxt').css({ 'left': $('.movingText').width() + 50 }).show();
            }
            else {
                $('.pressEnterTxt').hide();
                $(this).parents('.search_form').removeClass('typing');
            }

            if ($('.movingText').width() >= 730) {
                $(this).addClass('tbSizeMedium');
            }
            else {
                $(this).removeClass('tbSizeMedium');
            }
        });

        //add autofocus to browsers that don't support it
        $('[autofocus]:not(:focus)').eq(0).focus();

        //this adds rows and match col heights: will clean up later to make more modular
        if ($('.buyingGuide').length) {
            $('.buyingGuide').parent().addClass('bgItem');

            $('.buyingGuided img').imagesLoaded(function () {
                $('.bgItem:nth-child(3n+1)').addClass('rc');
            });

            $('.buyingGuide .icon-new-download').off('click').on('click', function () {
                var bgTitle = $(this).parents('.bgItem').find('h2').text();
                sendTracking('buying_guides', 'click_download_buying_guide', bgTitle);
            });
        }

        //forms
        if ($('html').is('.ie9,.ie8')) {
            $(document).on('keydown', 'input[data-val-required]', function () {
                //to force ie8/9 to validate on keypress
                $(this).valid();
            });
        }

        if ($('.formValidateBtn').length) {
            $('.formValidateBtn').each(function () {
                $(this).parents('form').validate();
            });
        }

        $(document).on('change', 'select[data-val=true]', function () {
            $(this).valid();
        });

        $('.paymentMethodButton').off('click').on('click', function () {
            var $this = $(this);
            $this.siblings().removeClass('active');
            if ($this.find('label.radio').hasClass('checked')) {
                $this.addClass('active');
            }
        });

        // Autoplay videos via query string:
        // DOM: <a href="path" class="friModalSize videoModal" data-autoplay-title="video-title-here">Play</a>
        // 1) check if query string is present
        // 2) store the value of the query string in a variable
        // 3) find that element on the dom
        // 4) trigger event to load it

        if (/[?&]autoplay=/.test(location.href)) {
            var apVal = getParameterByName('autoplay');
            if (!apVal.length) return;
            if (apVal == 'true') {
                //soon to be depricated (else statement is better as it can trigger more than one video)
                setTimeout(function () { $('.autoPlay a.videoModal').trigger('click'); }, 1000);
            } else {
                var el = document.querySelector('[data-autoplay-title="' + apVal + '"]');
                if (el === undefined || el === null) return;

                //if the video opens in a modal, then just open it
                if ($(el).hasClass('friModalSize')) {
                    $(el).trigger('loadModal');
                } else {
                    //else the video is embedded on the page, so let's scroll down to it, shall we?
                    setTimeout(function () {
                        var topPos = (frigidaire.mobileView() ? 100 : 200);
                        $('body').animate({ scrollTop: $(el).parent().offset().top - topPos }, 500, "easeOutExpo", function () {
                            $(el).trigger('click');
                            $('<div id="featured-video"/>').appendTo('#video-wrapper');
                            $('.abs-fill').addClass('active');
                        });
                    }, 1000);
                }
            }
        }

        //have only on start page after this works. open newsletter modal
        if (getParameterByName("newslettersignup")) {
            $('footer').find('.newsletterModal').trigger('click');
        }

        //sharing
        $(document).off('click.sharing').on('click.sharing', '.trigger-share', function (e) {
            sharingHandler(e, $(this));
        });

        if ($(".datepicker").length) {
            $(".datepicker").datepicker({
                maxDate: "+0D",
                changeYear: true,
                dateFormat: $(".datepicker").data('date-format'),
                onSelect: function () {
                    $(this).valid();
                },
                onClose: function () {
                    $(this).focus();
                }
            });
        }

        //in view video player (will clean up code later and move to a better spot)

        //inline video player
        if ($('.inline-video-player').length) {

            $(document).off('click.inlineVideo', '.inline-video-player').on('click.inlineVideo', '.inline-video-player',
                function (e) {
                    e.preventDefault();
                    $('<div class="abs-fill" style="height:100% !important; z-index:99;"><div id="inline-video-player"></div></div>')
                        .prependTo($('.inline-video-wrapper'));
                    var generatedList = function () {
                        var playlist = [],
                            files = $('.inline-video-player').data('videofiles'),
                            paths = files.split("|");

                        for (var t = paths.length; 0 < t--;) {
                            playlist.unshift({ file: paths[t] });
                        }
                        return playlist;
                    }();

                    jwplayer("inline-video-player").setup({
                        autostart: true,
                        flashplayer: '/Content/jwPlayer6/jwplayer.flash.swf',
                        skin: '/Content/jwplayer6/skins/frigidaire.xml',
                        levels: generatedList,
                        width: '100%',
                        height: '100%',
                        image: $('.inline-video-player').data('poster'),
                        controls: true,
                        icons: true,
                        controlbar: true
                    });
                    //   jwplayer().play();
                });
        }

        //generic video player
        if ($('#video-player').length) {
            var generatedList = function () {
                var playlist = [],
                    files = $('#video-player').data('videofiles'),
                    paths = files.split("|");

                for (var t = paths.length; 0 < t--;) {
                    playlist.unshift({ file: paths[t] });
                }
                return playlist;
            }();


            var autoplay = ($('#video-player').data('autoplay') != undefined ? $('#video-player').data('autoplay') : false);

            function setupVideo() {
                jwplayer("video-player").setup({
                    flashplayer: '/Content/jwPlayer6/jwplayer.flash.swf',
                    skin: '/Content/jwplayer6/skins/frigidaire-purple.xml',
                    levels: generatedList,
                    width: '100%',
                    image: $('#video-player').data('poster'),
                    autostart: autoplay,
                    controls: true,
                    icons: true,
                    controlbar: true,
                    mute: true
                });
            }

            setupVideo();
        }

        /*Scroll To an element:
         * Example: <a href="#pl" class="jsScrollTo">Goes to #pl</a>
         */
        $(document).on('click.jsScrollTo', '.jsScrollTo', function (e) {
            e.preventDefault();
            var goTo = this.getAttribute('href');
            $(goTo).scrollView();
        });

        //JS code for the InlineVideoBlock.
        $('.embedded-video-wrapper').click(function () {
            if ($(this).children(".embedded-video").get(0).paused) {
                $(this).children(".embedded-video").get(0).play();
                $(this).children(".embedded-video-play-icon").fadeOut();
            } else {
                $(this).children(".embedded-video").get(0).pause();
                $(this).children(".embedded-video-play-icon").fadeIn();
            }
        });

        $(document).on('click.closeParent', '.Close--parent', function (e) {
            e.preventDefault();
            $(this).parent().removeClass('is-active');
            setTimeout(function () {
                $('body').removeClass('cb-show');
                globHeaderHeight = frigidaire.headerHeight();
            }, 350);

            //remove padding top from the body for mobile
            if ($('html').hasClass('mobile')) {
                $('body').animate({
                    'padding-top': document.querySelectorAll('.header-container')[0].clientHeight + 'px'
                }, 350);
            }

            //cookie
            var elemCookie = $(this).parents('.NotifyBanner--alt').attr('id');
            $.cookie(elemCookie, 'hide', { path: '/' });
        });

    }

    function setupArticleCardInlineVideo(e, obj) {
        e.preventDefault();
        obj.$root = $(obj).parent().parent();
        obj.$modal = obj.$root.find('.modal');
        obj.video = obj.$modal.find('video').get(0);

        obj.$modal.modal({ show: true })
        obj.video.play();

        obj.$modal.on('shown.bs.modal', onShowModal.bind(obj));
        obj.$modal.on('hidden.bs.modal', onHideModal.bind(obj));
        function onShowModal() {
            obj.video.play();
        }
        function onHideModal() {
            obj.video.pause();
        }
        return false;
    }

    function sharingHandler(e, $this) {
        e.preventDefault();
        if ($('.closeModal').length > 0) $('.closeModal').trigger('click');

        var $shareType = $this.data('share-type'),
            $shareTitle = $this.data('share-title'),
            $shareCat = $this.data('share-category'),
            $shareaction = $this.data('share-action'),
            $shareTitleEnc = encodeURIComponent($shareTitle),
            $shareUrl = location.href,
            $shareUrlEnc = encodeURIComponent($shareUrl),
            $shareImage = ((/http/i.test($this.data('share-image'))) ? $this.data('share-image') : location.protocol + '//' + location.host + $this.data('share-image')),
            $shareImageEnc = encodeURIComponent($shareImage),
            $shareDescription = $this.data('share-description'),
            $shareCaption = (!$this.data('share-caption') ? 'FRIGIDAIRE' : $this.data('share-caption')),
            $builtUrl = "",
            $width = 600,
            $height = 400,
            $left = (screen.width / 2) - ($width / 2),
            $top = (screen.height / 2) - ($height / 2);

        //console.log({
        //    'TYPE': $shareType,
        //    'TITLE': $shareTitle,
        //    'URL': $shareUrl,
        //    'IMG': $shareImage,
        //    'DESCRIPTION': $shareDescription,
        //    'CAPTION': $shareCaption
        //});

        switch ($shareType) {
            case "facebook":
                //share to feed
                var catvalue = 'Facebook';
                if ($shareCat !== undefined && $shareCat !== '') {
                    catvalue = $shareCat;
                }
                var actionvalue = 'Share';
                if ($shareaction !== undefined && $shareaction !== '') {
                    actionvalue = $shareaction;
                }
                frigidaire.sendTracking(catvalue, actionvalue, $shareTitle);

                FB.ui({
                    method: 'feed',
                    link: $shareUrl,
                    picture: $shareImage,
                    name: $shareTitle,
                    description: $shareDescription,
                    caption: $shareCaption
                }, function (response) {
                    //Send to GA...
                    // frigidaire.sendTracking('Facebook', 'Share', $shareUrl);
                });



                //LIVE SITE TEST CODE:  FB.ui({method: 'feed', picture: 'http://support.frigidaire.com/Global/Chips/connected-ac/Homepage-Lower_Chip-2.jpg', link: 'http://www.frigidaire.com/Special-Offers/', name: 'Test Name', description: 'Test Description', caption: 'An example caption' });
                break;

            case "facebook-share-page":
                var catvalue = 'Facebook';
                if ($shareCat !== undefined && $shareCat !== '') {
                    catvalue = $shareCat;
                }
                var actionvalue = 'Share';
                if ($shareaction !== undefined && $shareaction !== '') {
                    actionvalue = $shareaction;
                }
                frigidaire.sendTracking(catvalue, actionvalue, $shareTitle);
                //share whole page (use og meta tags)
                try {
                    FB.ui({
                        method: 'share',
                        href: $shareUrl
                    }, function (response) {
                    });
                } catch (e) { console.log(e) }


                break;
            case "twitter":
                $builtUrl = 'http://twitter.com/share?url=' + $shareUrlEnc + "&text=" + $shareTitleEnc;

                var w = window.open($builtUrl, 'sharewindow', 'location=1,status=1,scrollbars=1, width=' + $width + ', height=' + $height + ', top=' + $top + ', left=' + $left + '');
                var catvalue = 'Twitter';
                if ($shareCat !== undefined && $shareCat !== '') {
                    catvalue = $shareCat;
                }
                var actionvalue = 'Tweet';
                if ($shareaction !== undefined && $shareaction !== '') {
                    actionvalue = $shareaction;
                }
                frigidaire.sendTracking(catvalue, actionvalue, $shareTitle);
                break;

            case "pinterest":
                $builtUrl = 'http://pinterest.com/pin/create/button/?url=' + $shareUrlEnc + '&media=' + $shareImageEnc + '&description=' + $shareTitleEnc;
                var w = window.open($builtUrl, 'sharewindow', 'location=1,status=1,scrollbars=1, width=' + $width + ', height=' + $height + ', top=' + $top + ', left=' + $left + '');

                var catvalue = 'Pinterest';
                if ($shareCat !== undefined && $shareCat !== '') {
                    catvalue = $shareCat;
                }
                var actionvalue = 'Pin';
                if ($shareaction !== undefined && $shareaction !== '') {
                    actionvalue = $shareaction;
                }
                frigidaire.sendTracking(catvalue, actionvalue, $shareTitle);
                break;

            case "googleplus":
                $builtUrl = 'https://plus.google.com/share?url=' + $shareUrlEnc;

                frigidaire.sendTracking('GooglePlus', 'Share', $shareUrl);
                var w = window.open($builtUrl, 'sharewindow', 'location=1,status=1,scrollbars=1, width=' + $width + ', height=' + $height + ', top=' + $top + ', left=' + $left + '');
                break;
            case "email":
                var catvalue = 'email';
                if ($shareCat !== undefined && $shareCat !== '') {
                    catvalue = $shareCat;
                }
                var actionvalue = 'email';
                if ($shareaction !== undefined && $shareaction !== '') {
                    actionvalue = $shareaction;
                }

                frigidaire.sendTracking(catvalue, actionvalue, $shareTitle);
                break;

            default:
                break;
        }

        //mixpanel
        mpFrigidaire.increment("Total Number of Social Shares");
        mpFrigidaire.track('Social Share Event', {
            "Content Title": $shareTitle,
            "Share Type": $shareType,
            "Page Category": mpGlobalProperties["Page Category"],
            "Page Sub-Category": mpGlobalProperties["Page Sub-Category"],
            "Page Title": mpGlobalProperties["Page Title"],
            "Site Section": mpGlobalProperties["Site Section"],
            "Page Type": mpGlobalProperties["Page Type"]
        });
    }
    //match heights of blocks
    function matchColHeights(selector) {
        var maxHeight = 0,
            $selection = $(selector); // cache the jquery object to win some speed and function calls...

        $selection.css({ 'height': 'auto' })
            .each(function () {
                var height = $(this).height();
                if (height > maxHeight) {
                    maxHeight = height;
                }
            });
        $selection.height(maxHeight);
    }

    function categoryLanding() {
        if (!$('.cat-images').length) return;

        $('.fbVideo').find('a').addClass('videoModal'); //makes feature block video's open in the correct position

        var $slider = $('.cat-images > div'),
            $items = $slider.find('> div');

        if (mobileView()) {
            if ($items.length > 3) {
                setupSwipe();
            }
        } else {
            cleanup();
        }

        function setupSwipe() {
            $slider.addClass('slider catSlider');
            for (var i = 0; i < $items.length; i += 3) { // wrap new div around every three items
                $items.slice(i, i + 3).wrapAll("<div/>");
            }
            $slider.find('> div:eq(0)').addClass('active'); // add active on first one

            $('li.singleBrowseImg').parent().addClass('singleBrowseImg'); //fix for slides that have only one item and are wider than the other images. example is freezer cat.

            var $sControls = $('<div class="sControls"></div>').insertAfter($slider);
            $slider.children().each(function () {
                $('<div class="bullet" />').appendTo($sControls);
            });

            $slider.on('nSwipeSlider.swipeDone', function (e, jQueryDOMObject, i) {
                $sControls.find('.bullet').removeClass('active');
                $sControls.find('.bullet').eq(i - 1).addClass('active');
            });

            $sControls.find('> .bullet').eq(0).addClass('active');

            $('.bullet').on('click', function () {
                $(this).parent().find('> div').removeClass('active');
                $(this).addClass('active');
                $(this).parent().prev().find('> div').eq($(this).index() + 1).trigger('slideTo');
            });

            $slider.nSwipeSlider(); // start slider
        }

        function cleanup() {
            if (typeof ($slider.data('nSwipeSlider')) === 'undefined') return;
            var _items = $slider.find('> div');
            $slider.removeClass('slider catSlider').nSwipeSlider.destroy();
            $slider.next('.sControls').remove();
            $slider.find('.active').removeClass('active');
            $slider.find('> div > div').unwrap();
        }

        function clpTooltips() {
            var rolledOverAlready = null;

            //for clp toys tooltip, need to move later to a good spot.
            $(document).off('mouseenter', '.tt-sib').on('mouseenter', '.tt-sib', function (e) {
                var theLink = this,
                    //ttOverlay = $(theLink).attr('href'),
                    //$ttOverlayBlock = $(ttOverlay),
                    $ttOverlayBlock = $('.tt-container'),
                    $targetPos = $('.target-pos');

                //position it
                if (rolledOverAlready === null) {
                    var positionToHere = $targetPos.position();
                    $ttOverlayBlock.offset({
                        top: positionToHere.top,
                        left: positionToHere.left
                    });
                    $ttOverlayBlock.width($targetPos.outerWidth(true) + $targetPos.outerWidth());
                    $ttOverlayBlock.height($targetPos.height());
                    rolledOverAlready = true;
                }

                $ttOverlayBlock.show();
                $ttOverlayBlock.removeClass('fadeLeft').addClass('fadeRight');
            });

            $(document).off('mouseleave', '.tt-sib').on('mouseleave', '.tt-sib', function (e) {
                $('.tt-container').removeClass('fadeRight').addClass('fadeLeft');
                setTimeout(function () { $('.tt-container').hide(); }, 250);
            });

            $(document).off('click', '.tt-sib').on('click', '.tt-sib', function (e) {
                e.preventDefault();
            });
        }

        clpTooltips();

        //look for recipe and if it exists, the load the modal...
        if (getParameterByName('recipe')) {
            var qs = $('.qsRecipe .button').attr('href');
            friModalSize.openModal(qs, '900px');
        }
    }
    //indicate if plp-sort was clicked
    $('#plp-sort').click(function () {
        $(this).attr('clicked', true);
    })
    function sortFunction(firstload = "") {
        //Add data-rating to product-group wrapper for sorting by rating
        $('#pl div.product-group-wrapper').each(function (i) {
            var rating = $(this).children('div.product-item').attr('data-rating');
            $(this).attr("data-rating", rating);
        })



        if (!$('select.jsSort').length) return;

        if (frigidaire.lang() === 'fr-ca') {
            var $items = (!!$('#pl>div').length) ? $('#pl>div') : $('#pl>section>div');
            $items.each(function () {
                var $this = $(this),
                    msrp = $this.data('msrp'),
                    stripped = '';

                if (msrp) {
                    stripped = msrp.replace(",", "");
                }

                $this.attr('data-msrp', stripped);
            });
        }

        var $sortBoxes = $('select.jsSort');
        for (var i = $sortBoxes.length; 0 <= --i;) {
            $sortBoxes.eq((i - 1)).off('change.sorting').on('change.sorting', function () {
                var $this = $(this),
                    selector = $(this).data('selector'),
                    childSelector = $(this).data('child-selector'),
                    options = {};

                // Check if product groups exist and if sidebar filters are selected. 
                // If Groups and no Filters, then presort the items in the group to bring forward the item that matches the sort.
                // Eg, bring forward the lowest price item of group if searching by lowest price
                if ($('.product-group-wrapper').length > 0) {
                    sortGroupItems($this.find(':selected').data('order'));
                }
                var actualattr = "";

                //now that we have multiple attributes to sort on, the original onchange js only grabs the attribute
                //of the last div in the option list  
                //use click to capture the actual item clicked on in case find(:selected) defaults to the last item in the list
                $('.sort-option').click(function () {
                    //get attr of element clicked on
                    actualattr = $(this).attr("data-attr");

                    //get attribute to sort using :selected  i.e. data-msrp
                    if (!!$this.find(':selected').data('attr')) {
                        var sortattr = $this.find(':selected').data('attr');
                        if (sortattr != actualattr)
                            sortattr = actualattr;
                        options.attr = sortattr;
                    }
                    if (!!$this.find(':selected').data('order')) {
                        options.order = $this.find(':selected').data('order');
                    }
                    if (!selector && !options.attr && !options.order) {
                        return; // nothing to filter on, most surely a default text...
                    }
                     

                     
                    //Remove the plp image when sorting - but need to make certain user clicked and made a selection
                     if ($('#plp-sort').attr('clicked') == "true") {
                         $('.plpImageContainer', '.list-products #pl').remove();
                         //only sort if manually clicked
                         if (!$this.data('has-sections')) {
                             tinysort(selector, options);
                         } else {
                             var $selector = $(selector);
                             for (var i = $selector.length; i--;) {
                                 var $obj = $selector.eq(i).find(childSelector)
                                 tinysort($obj.toArray(), options);
                             }
                         }
                     }
                    else
                         $('.plpImageContainer', '.list-products #pl').show();
                });
            });
            if (!!$sortBoxes.eq((i - 1)).find('option[selected]').length) { // if default selected, sort it!
                $sortBoxes.eq((i - 1)).trigger('change');
            }
        }



        $(document).off('change.track-sort', 'select.jsSort').on('change.track-sort', 'select.jsSort', function () {
            frigidaire.sendTracking('category_list', 'click_sort', $.trim($(this).find(':selected').text()));
        });

    }

    // Bring forward product that matches sort order in order to sort groups by price
    function sortGroupItems(order) {
        var colorGroups = $('#pl .product-group-wrapper');
        for (i = 0; i < colorGroups.length; i++) {
            var groupMsrp = [];
            var children = $(colorGroups[i]).children('.product-item');

            // Loop through children collecting msrp
            if (children.length > 1) {
                for (j = 0; j < children.length; j++) {
                    console.log('msrp collection', i, j, $(children[j]).data('itemid'), $(children[j]).data('msrp'));
                    groupMsrp.push(parseInt($(children[j]).data('msrp')));
                    // Hide yo children
                    $(children[j]).addClass('outoffilter');
                }
                var index = 0;
                var value = groupMsrp[0];

                // Loop through msrp array and find lowest value and its index
                for (var k = 1; k < groupMsrp.length; k++) {
                    if ((groupMsrp[k] < value) && (order == 'asc')) {
                        value = groupMsrp[k];
                        index = k;
                    } else if ((groupMsrp[k] > value) && (order == 'desc')) {
                        value = groupMsrp[k];
                        index = k;
                    }
                }

                // Show child that matches msrp high/low request
                $(children[index]).removeClass('outoffilter');
                var msrp = $(children[index]).data('msrp');
                $(colorGroups[i]).attr('data-msrp', msrp);
            }
        }
    }

    function setHtmlTag() {
        if (mobileView() !== origView) {
            origView = mobileView();
            reInit();
        }
        device();
    }

    function initForms(parent, all) {
        //target parent and search it's children for selectmenu's or radio buttons.
        //if mobile, then uniform everything
        //if desktop, then uniform radio's, and selectmenu everything else.

        if (frigidaire.mobileView()) {
            if (all !== undefined) {
                $(parent).find('select').uniform();
            } else {
                $(parent).find('select').not('.ignore').uniform();
            }

            $(parent).find('input[type=radio], input[type=checkbox]').uniform();

            //$('select:visible').not(".ignore").uniform();
            //$('select').selectmenu('destroy');
            //$.uniform.restore();
        } else {
            if (all !== undefined) {
                $(parent).find('select').selectmenu();
                $(parent).find('input[type=radio], input[type=checkbox]').uniform();
            } else {
                $(parent).find('select').not('.ignore').selectmenu();
                $(parent).find('input[type=radio]:not(".ignore"), input[type=checkbox]:not(".ignore")').uniform();
            }

            //$('input[type=radio]:not(".ignore"), input[type=checkbox]:not(".ignore")').uniform();
            //if there's already a select menu, then: $($0).next('span').find('.ui-selectmenu').length
            //$('select').not(".ignore").selectmenu();
        }
    }

    function reInit() {
        productDetailPage();
        //subMenus();
        categoryLanding();
        mobileResize();
        deviceChange();
        if (!mobileView()) {
            $.uniform.restore();
            $('input[type=radio], input[type=checkbox]').not('.ignore').uniform();
            $('select:not(".ignore")').selectmenu();
        }
        else {
            $('select').not('.ignore').selectmenu('destroy');
            $('select').not('.ignore').uniform();
        }
    }

    function sendTracking(category, action, label) {
        $(document).trigger({ type: 'tracking', category: category, action: action, label: label });
    }

    function headerHeight() {
        if ($('.NotifyBanner--alt').is('.is-active')) {
            return $('.header-container').outerHeight();
        } else {
            return $('.header-container').outerHeight() - $('.NotifyBanner--alt').outerHeight();
        }

    }

    function ajaxService(api, method, methodType, callData, callback, $targets) {
        var deferred = $.Deferred();

        if ($targets) {
            $targets.trigger(method + 'Start').next('.mtContent').addClass('mLoading');
        }

        callData.CultureCode = frigidaire.lang();

        $.ajax({
            url: '/api/' + api + '/' + method,
            type: methodType,
            data: callData,
            headers: {
                'accept-language': frigidaire.lang()
            },
            success: function (data) {
                deferred.resolve();

                if ($targets) {
                    parseAjaxData(data, $targets, method, callback);
                }

                if (callback) {
                    callback(data);
                    $(window).trigger({
                        type: method + 'Done',
                        responseData: data
                    });
                }

            },
            error: function (err) {
                deferred.reject();
                callback(err);
                $(window).trigger(method + 'Error');
            }
        });

    }

    function parseAjaxData(data, $targets, method, preserveContent, callback) {
        console.log('%cRECEIVING: %o', 'background:yellow;color:green', data);

        for (var i = $targets.length; 0 < i--;) {
            var template = $targets.eq(i).html(),
                output = Mustache.render(template, data);

            if (preserveContent) {
                $targets.eq(i).trigger({
                    type: method + 'Done',
                    responseData: data
                }).next('.mtContent').append(output).removeClass('mLoading');
            } else {
                $targets.eq(i).trigger({
                    type: method + 'Done',
                    responseData: data
                }).next('.mtContent').html(output).removeClass('mLoading');
            }

            frigidaire.initForms($targets.eq(i).next('.mtContent'));

            //render selectmenu in modal
            if ($targets.eq(i).parents().is('.mContent')) {
                frigidaire.initForms($targets.eq(i).next('.mtContent'), true);
            }

            if (callback) {
                callback(data);
            }
        }
    }

    function sendTrackingWithValue(category, action, label, evalue) {
        $(document).trigger({ type: 'tracking', category: category, action: action, label: label, value: evalue });
    }

    return {
        init: init,
        populateProductPageDocuments: populateProductPageDocuments,
        mobileView: mobileView,
        device: device,
        matchColHeights: matchColHeights,
        checkMobileDevice: checkMobileDevice,
        accordionTechnologyTM: accordionTechnologyTM,
        sendTracking: sendTracking,
        lang: lang,
        localizedAddressForm: localizedAddressForm,
        sanitizeErrorObject: sanitizeErrorObject,
        yaToolTip: yaToolTip,
        carousel: carousel,
        populateAddress: populateAddress,
        isVisibleOnScreen: isVisibleOnScreen,
        checkImage: checkImage,
        initForms: initForms,
        ajaxService: ajaxService,
        parseAjaxData: parseAjaxData,
        headerHeight: headerHeight,
        toolTips: toolTips,
        util: util,
        sizeConfettiBanner: sizeConfettiBanner,
        sendTrackingWithValue: sendTrackingWithValue,
    };
})(frigidaire);

$(window).on('resize.slideshow', $.throttle(75, function () {
    var w = $('.slideshowGallery').width() - $('#pT').width() - 12;
    if (w) $('#pCurr').width(w); //recalculate the width of the gallery for responsive.
}));


/* This is the script for Stepping */
var prodList = (function () {
    var $pl = $('#pl'),
        $items = $pl.find('> div'),
        $curr = null,
        $currList = null,
        listWidth = 0,
        perRow = 0,
        diff = 0,
        quickFirst = 0,
        animating = false,
        lastWindowHeight = $(window).height(),
        lastWindowWidth = $(window).width(),
        productCardWidth = $items.eq(0).outerWidth(),
        plWidth = $pl.outerWidth();


    function init() {
        if ($('#cp').length > 0) {
            compare.init();
        }

        if (!$pl.length) return; // if no prodList on page, just return...
        //initQuickview();
        checkAndHandleCompareInputs();

        $(window).on('resize', function () {
            // ie8 workaround - check if event triggered by actually window resize and not just page getting taller
            // (bug was elusive - only happened when page got taller by adding another row of products)
            if ($(window).height() !== lastWindowHeight || $(window).width() !== lastWindowWidth) {
                //set this windows size
                lastWindowHeight = $(window).height();
                lastWindowWidth = $(window).width();
                // call hideQV
                //if ($curr) hideQV($curr.parent());
            }
        });
    }

    function fileExist(path, callback) {
        $.ajax({ url: path, type: 'HEAD', error: function () { callback(false); }, success: function () { callback(true); } });
    }

    function getImagePath(pc, i, type) {
        i = i > 0 ? ('_' + i) : '';
        type = type ? ('_' + type) : '';
        return '/Global/Products/' + pc + i + type + '.png';
    }

    function checkAndHandleCompareInputs() {
        if (!$('#pl input').length) return;

        var compareLabelOffText = $('#pl').data('compare-label-off'),
            compareLabelOnText = $('#pl').data('compare-label-on'),
            cookieValue = unescape($.cookie('compareProducts')),
            compareProducts = (typeof $.cookie('compareProducts') === 'undefined') ? [] : cookieValue.split(','),
            listingPageUrl = (typeof $.cookie('listingPageUrl') === 'undefined') ? [] : $.cookie('listingPageUrl'),
            $cpInputs = $('#pl').find('input'),
            pLoad = false;

        $cpInputs.off('change.compare').on('change.compare', function () {
            var $this = $(this);

            if ($this.is(':checked')) {
                if (pLoad === false) {

                    if (compareProducts.length > 3) {
                        $this.prop('checked', false);
                        $this.parent().removeClass('checked');
                        prodList.compare.showAmountWarning($(this));
                    } else {
                        $this.parents('.qvItem').addClass('active');
                        if ($.inArray($this.attr('id'), compareProducts) === -1) {
                            compareProducts.push($this.attr('id'));
                        }
                    }

                } else {
                    $this.parents('.qvItem').addClass('active');
                    if ($.inArray($this.attr('id'), compareProducts) === -1) {
                        compareProducts.push($this.attr('id'));
                    }
                }

            } else {
                $this.parents('.qvItem').removeClass('active');
                var index = $.inArray($this.attr('id'), compareProducts);
                compareProducts.splice(index, 1);

                $this.parents('.compare').find('label').text(compareLabelOffText).removeClass('pink').off('click.compare');
            }
            if (compareProducts.length > 0) {
                $.cookie('compareProducts', escape(compareProducts.join(',')), { path: '/' });
            } else {
                $.removeCookie('compareProducts');
            }

            if (compareProducts.length > 1 && compareProducts.length < 5) {
                $cpInputs.filter(':checked').parents('.compare').find('label').text(compareLabelOnText + ' (' + compareProducts.length + ')').addClass('pink').off('click.compare').on('click.compare', function (e) {
                    e.preventDefault();

                    //set cookie and save url
                    $.cookie('listingPageUrl', window.location.href, { path: '/' });

                    var products = "",
                        productsPiped = "";

                    for (var i = compareProducts.length; 0 < i--;) {
                        products += ',' + compareProducts[i].substr(2);
                        productsPiped += ' | ' + compareProducts[i].substr(2);
                    }

                    $cpInputs.prop('checked', false);

                    var prodCat = $('.productCategory').text(),
                        prodId = $(this).parents('.qvItem').attr("data-product-id");

                    frigidaire.sendTracking('category_list', 'click_compare', prodCat + productsPiped);

                    setTimeout(function () {
                        window.location = PRODUCT_COMPARE_PAGE + '?products=' + products.substr(1);
                    }, 150);

                });
            } else if (compareProducts.length === 1) {
                $cpInputs.filter(':checked').parents('.compare').find('label').text(compareLabelOffText).removeClass('pink').off('click.compare');
            }

        });

        // check if no products, if so it's not the same category, hence remove cookie
        var numOfProds = 0;
        for (var i = compareProducts.length; 0 < i--;) {
            if ($('#' + compareProducts[i]).is(':visible'))
                numOfProds++;
        }
        if (!numOfProds) {
            $.removeCookie('compareProducts', { path: '/' });
            compareProducts = [];
        }

        if (compareProducts.length >= 1 && numOfProds > 0) {
            pLoad = true;
            for (var i = compareProducts.length; 0 < i--;) {
                $('#' + compareProducts[i]).trigger('click');
            }
            pLoad = false;
        }

    }

    var compare = function () { // compare page...
        function init() {
            $('#cp .header').off('click').on('click', function (e) {
                e.preventDefault();
                var vis = $(this).next('table').is(':visible');
                $(this).find('a').text((vis) ? $(this).find('a').data('expand-text') : $(this).find('a').data('collapse-text')).end().toggleClass('collapsed').next('table').slideToggle(500);
            });

            if (!$('.tooltip').length) return;
            tooltip();
        }

        function tooltip() {
            var $tt = $('.tooltip'), $cpTool = $('<div id="tooltip"></div>').appendTo('body');

            $tt.each(function () {
                var $_this = $(this);
                // bind mouseover/mouseleave event to parent
                $_this.parent().off('mouseenter').on('mouseenter', function () {
                    $_this.clone().appendTo($cpTool);
                    $cpTool.css({
                        top: $(this).offset().top - $cpTool.height() + 3,
                        left: $(this).offset().left
                    }).fadeIn(200);
                }).off('mouseleave').on('mouseleave', function () {
                    $cpTool.hide();
                    $cpTool.find('> div').remove();
                });
            });
        }

        function showAmountWarning(obj) {
            var compareMaxTxt = $('#pl').data('compare-max-txt'),
                $aW = $('<div id="aW"><div><p>' + compareMaxTxt + '</p></div></div>').appendTo('body').hide();
            $obj = $(obj);

            $aW.css({ left: $obj.offset().left - 120, top: $obj.offset().top - 50 }).fadeIn(200);
            setTimeout(function () {
                $aW.fadeOut(200, function () {
                    $aW.remove();
                    $aW = null;
                });
            }, 5000);
        }

        return {
            init: init,
            showAmountWarning: showAmountWarning
        };
    }();


    return {
        init: init, compare: compare
    };
})(prodList);


$(document).ready(function () {
    frigidaire.init();
    prodList.init();
});

// Size the confetti banner when it's ready
// This is a hack for air fry day confetti frigidaire-primary-banner to size correctly
// Wait for everything to load before calling, depends on videos height so video must be loaded
$(window).on('load', function () {
    if ($('#confetti-banner-hero').length) {
        frigidaire.sizeConfettiBanner();
    }

    //preload click functionality on sort button
    var plp = document.querySelector(".plpWrapper #sort-options");
    if (plp != null) { 
          $('.sort-option').click();
    }
   /*  tinysort('data-rating', 'desc'); */
});

function doPrint() {
    if ((window.print) && (document.all)) {
        window.print();
    } else if (window.print) {
        window.print();
    } else if ((document.all) && !(navigator.userAgent.indexOf("Mac") !== -1)) {
        var printWindowObject = "<object id='printWindowObject1' width=0 height=0 classid='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2'></object>";
        document.body.insertAdjacentHTML("BeforeEnd", printWindowObject);
        window.document.printWindowObject1.ExecWB(6, 1);
    }
}

function openPopup(url, pwidth, pheight) {
    var posLeft = (parseInt(screen.width) / 2) - (parseInt(pwidth) / 2);
    var posTop = ((parseInt(screen.height) / 2) - (parseInt(pheight) / 2)) - 50;

    var newwindow = window.open(url, null, 'toolbar=0,menubar=0,location=0,directories=0,status=0,resizable=0,scrollbars=1,HEIGHT=' + pheight + ',WIDTH=' + pwidth + ',left=' + posLeft + ',top=' + posTop);
    if (window.focus) {
        newwindow.focus();
    }
}



var friModalSize = friModalSize || {};
friModalSize = (function ($) {
    $(document).off('click.friModalSize loadModal').on('click.friModalSize loadModal', '.friModalSize', function (e) {
        e.preventDefault();

        if (!$(this).hasClass('bubbleUp')) {
            e.stopPropagation();
        }

        if ($(this).hasClass('scSubscriptionOptions')) {
            frigidaire.sendTracking(tracking.pageTrackingCategory(), 'click_subscribe', $(this).parents('[data-itemid]').data('itemid'));
        }

        var $this = $(this),
            modalWidth = $this.data('modal-width'),
            src = $this.data("modal-url") || $this.attr('href'),
            modalWrapper = (!$this.is('.friModalSize.videoModal')
                ? $('<div class="friModalWrapper"><div class="friInnerModal"><a href="#" class="closeModal"><span class="icon-close-modal">Close</span></a><div><div class="mLeft"></div><div class="mRight"></div><div class="modalContent scroller"><div class="mContent"></div></div></div></div></div>')
                : $('<div class="friModalWrapper videoModalWrapper"><div class="friInnerModal"><a href="#" class="closeButton"><i></i><span></span></a><div><div class="modalContent scroller"><div class="mContent"></div></div></div></div></div>')),
            modalContent = modalWrapper.find('.mContent'),
            modalLoader = $('<div class="loaderModal"><div></div></div>');

        modalLoader.appendTo('body').fadeIn(350);
        modalWrapper.appendTo('body');
        if (src.substring(0, 1) === '#') {
            modalContent.html($(src).html());
            showModal(modalLoader, modalWrapper, modalWidth, $this);
        } else {
            modalContent.load(src, function (response, status, xhr) {
                //console.log(xhr.status + " " + xhr.statusText);

                if (status === "error") {
                    showModal(modalLoader, modalWrapper, modalWidth, $this, status);
                    return;
                }

                $('.mContent').imagesLoaded(function () {
                    if (!$this.is('.friModalSize.videoModal')) {
                        showModal(modalLoader, modalWrapper, modalWidth, $this);
                    } else {
                        var isOld = ($('html').hasClass('ie7') || $('html').hasClass('ie8'));
                        if (!isOld) {
                            $('body').on('videoLoaded', function () {
                                showModal(modalLoader, modalWrapper, modalWidth, $this);
                            });
                        } else {
                            showModal(modalLoader, modalWrapper, modalWidth, $this);
                        }
                    }
                });

                FrenchDip.initializeComponents(null, modalContent[0]);
            });
        }
    });

    function showModal(modalLoader, modalWrapper, modalWidth, triggeringElement, status) {
        var friInnerModal = modalWrapper.find('.friInnerModal');

        if (status == "error") {
            var errorMessage = frigidaire.lang() != "fr-ca" ? "We're sorry, but there has been an error. Please try again. If the problem continues, call 1-800-724-7519 and a Frigidaire representative will assist you with your issue." : "Désolé, une erreur est survenue. Veuillez réessayer. Si le problème persiste, composez le 1-800-724-7519 pour obtenir de l'aide d'un(e) représentant(e) Frigidaire.",
                friInnerModal = modalWrapper.find('.friInnerModal');
            friInnerModal.find('.mContent').html("<p class='margin0 padding2'>" + errorMessage + "</p>");
        }

        $('.loaderModal > div').remove();
        friInnerModal.css({ 'max-width': modalWidth });
        if ($('html').hasClass('ie7') || $('html').hasClass('ie8')) {
            friInnerModal.css({ 'height': '450px' });
        }
        modalWrapper.fadeIn(300, function () {
            $('body').trigger('friModalSize.modalOpen', [modalWrapper, triggeringElement]);

            //if mobile, then position it in the center of the screen since it's gonna be absolute
            if (frigidaire.mobileView()) {
                friInnerModal.animate({ 'margin-top': ($(window).height() / 2) - (modalWrapper.find('.friInnerModal').height() / 2) + window.scrollY, 'opacity': 1 }, 300, 'easeOutCubic').off('click').on('click', function (e) { }).on('scroll.scrollModal', function (e) {
                    e.stopPropagation();
                });
            } else {
                friInnerModal.animate({ 'margin-top': ($(window).height() / 2) - (modalWrapper.find('.friInnerModal').height() / 2), 'opacity': 1 }, 300, 'easeOutCubic').off('click').on('click', function (e) { }).on('scroll.scrollModal', function (e) {
                    e.stopPropagation();
                });
            }

            //$('.modalContent').scrollLock();

        });
        closer(modalWrapper, modalLoader, status);
    }

    $('.friModalIframe').off('click').on('click', function (e) {
        e.preventDefault();
        var modalWrapperIframe = $('<div class="friModalWrapper iframeWrapper"><div class="friInnerModal"><a href="#" class="closeModal"><span class="icon-close-modal">Close</span></a><div><div class="mLeft"></div><div class="mRight"></div><div class="modalContent"><iframe class="scroller"/></div></div></div></div>');
        modalWidth = $(this).data('modal-width'),
            modalHeight = $(this).data('modal-height');

        modalWrapperIframe.appendTo('body');
        $('.friModalWrapper iframe').attr('src', $(this).attr('href'));
        var friInnerModal = $('.friInnerModal'),
            iframeContents = $('.iframeWrapper iframe').css({ 'height': modalHeight - 6, 'width': modalWidth }).contents();

        friInnerModal.css({ 'height': modalHeight, 'width': modalWidth });

        $('.friInnerModal').css({ 'margin-top': ($('.friInnerModal').height() / 2) - $('.friInnerModal').height() });

        $('.friModalWrapper').fadeIn('200');
        friInnerModal.animate({ 'opacity': 1 }, 200);

        parent.$('.closeModal').off('click').on('click', function (e) {
            e.preventDefault();
            parent.$('.friModalWrapper').fadeOut('200', function () { parent.$('.friModalWrapper').remove(); });
        });
    });

    $(document).off('reanimateModal').on('reanimateModal', function () {
        $('.friInnerModal:visible').animate({
            'margin-top': ($(window).height() / 2) - ($('.friInnerModal:visible').height() / 2) + (frigidaire.mobileView() ? window.scrollY : 0),
            'max-width': $('.nested-modal:visible').css('max-width')
        }, 200, 'easeOutCubic');
    });

    function loadModal(el, selector) {
        var src = selector,
            modalWidth = $(el).data('modal-width'),
            modalWrapper = $('<div class="friModalWrapper friModalWrapper-full"><div class="friInnerModal"><a href="#" class="closeModal mobile-hide"><span class="icon-close-modal">Close</span></a><div><div class="mContent u-dropShadow"></div></div></div></div>'),
            modalContent = modalWrapper.find('.mContent'),
            modalLoader = $('<div class="loaderModal"><div></div></div>');

        if (modalWidth != undefined) modalWrapper.find('.friInnerModal').css({ 'max-width': modalWidth });

        modalLoader.appendTo('body').fadeIn(350);
        modalWrapper.appendTo('body');

        if (src.substring(0, 1) === '#') {
            modalContent.html($(src).html());
            handleModal(modalLoader, modalWrapper);
        } else {
            modalContent.load(src, function (response, status, xhr) {
                //console.log(xhr.status + " " + xhr.statusText);

                if (status === "error") {
                    //showModal(modalLoader, modalWrapper, modalWidth, status);

                    //close the modal
                    $('.loaderModal').remove();

                    alert('error has occurred');
                    return;
                }

                $('.mContent').imagesLoaded(function () {
                    handleModal(modalLoader, modalWrapper);
                });

            });
        }

        function handleModal(modalLoader, modalWrapper) {
            var friInnerModal = modalWrapper.find('.friInnerModal');
            $('.loaderModal > div').remove();

            modalWrapper.fadeIn(300, function () {
                $('body').trigger('friModalSize.modalOpen');
                friInnerModal.addClass('is-active');
                if (!frigidaire.mobileView()) {
                    friInnerModal.animate({
                        'margin-top': ($(window).height() / 2) - (modalWrapper.find('.friInnerModal').height() / 2),
                        'opacity': 1
                    }, 300, 'easeOutCubic').off('click').on('click', function (e) { }).on('scroll.scrollModal', function (e) { });
                }
                //$('.mContent').scrollLock();
                frigidaire.yaToolTip();
                frigidaire.initForms($('.friModalWrapper-full'), true);
            });

            closer(modalWrapper, modalLoader);
        };


    }

    function openModal(src, modalWidth, bgColor, cookieName, type, callback, cookieDuration) {
        //Create cookie if needed
        if (cookieName) {
            if (typeof $.cookie(cookieName) === 'undefined') {
                $.cookie(cookieName, 'autoModalCookie', { expires: (!cookieDuration ? 30 : cookieDuration), path: '/' });
            } else {
                return;
            }
        }

        var modalWrapper = null;

        switch (bgColor) {
            case "pink":
                modalWrapper = $('<div class="friModalWrapper pinkBg"><div class="friInnerModal"><a href="#" class="closeModal"><span class="icon-close-modal">Close</span></a><div><div class="modalContent scroller"><div class="mContent"></div></div></div></div></div>');
                break;

            case "green":
                modalWrapper = $('<div class="friModalWrapper greenBg"><div class="friInnerModal"><a href="#" class="closeModal"><span class="icon-close-modal">Close</span></a><div><div class="modalContent scroller"><div class="mContent"></div></div></div></div></div>');
                break;

            default:
                modalWrapper = $('<div class="friModalWrapper"><div class="friInnerModal"><a href="#" class="closeModal"><span class="icon-close-modal">Close</span></a><div><div class="mLeft"></div><div class="mRight"></div><div class="modalContent scroller"><div class="mContent"></div></div></div></div></div>');
                break;
        }

        var modalContent = modalWrapper.find('.mContent'),
            modalLoader = $('<div class="loaderModal"><div></div></div>');

        modalLoader.appendTo('body').fadeIn(350);
        modalWrapper.appendTo('body');

        if (frigidaire.mobileView()) {
            modalWrapper.animate({ 'margin-top': (modalWrapper.find('.friInnerModal').height() / 2) + window.scrollY, 'opacity': 1 }, 300, 'easeOutCubic').off('click').on('click', function (e) { }).on('scroll.scrollModal', function (e) {
                e.stopPropagation();
            });
        }

        if (type === 'html') {
            modalContent.append(src);
            loadingWrapper();
            if (callback) callback();
        } else {
            modalContent.load(src, function () {
                loadingWrapper();
                if (callback) callback();
            });
        }

        function loadingWrapper() {
            var friInnerModal = modalWrapper.find('.friInnerModal');
            $('.loaderModal > div').remove();
            friInnerModal.css({ 'max-width': modalWidth });

            if (getParameterByName('recipe')) {
                $('#' + getParameterByName('recipe')).find('>h2').trigger('click');
            }

            modalWrapper.fadeIn(300, function () {
                friInnerModal.animate({
                    'margin-top': ($(window).height() / 2) - (modalWrapper.find('.friInnerModal').height() / 2), 'opacity': 1
                }, 300, 'easeOutCubic').off('click').on('click', function (e) {
                    e.stopPropagation();
                }).on('scroll.scrollModal', function (e) {
                    e.stopPropagation();
                });
            });
            closer(modalWrapper, modalLoader);
        }

    }

    function closerWithCallback(callback, timer) {
        window.setTimeout(function () {
            $('.friModalWrapper').animate({
                'top': -(($(window).height() / 2) - ($('.friModalWrapper').find('.friInnerModal').height() / 2)),
                'opacity': 0
            }, 400, 'easeOutCirc', function () {
                callback();
                $('.friModalWrapper:last').remove();
                $('.loaderModal').fadeOut(400, function () {
                    $('.loaderModal:last').remove();
                });
            });
        }, timer);

        $('.friInnerModal .closeModal').off('click').on('click', function (e) {
            window.clearTimeout(timer);
            $('.friModalWrapper').trigger('click');
            callback();
        });
    }

    function closer(modalWrapper, modalLoader, status) {
        $('.friModalWrapper').off('click').on('click', function (e) {
            if (!$(e.target).is($(this))) return;
            if ($(this).hasClass('videoModalWrapper')) {
                if (status != 'error') {
                    jwplayer("modalVideo").stop();
                }
            }
            $(this).animate({ 'top': -(($(window).height() / 2) - (modalWrapper.find('.friInnerModal').height() / 2)), 'opacity': 0 }, 400, 'easeOutCirc', function () {
                $('.friModalWrapper:last').remove(); $('body').trigger('friModalSize.modalClose');
                modalLoader.fadeOut(400, function () { $('.loaderModal:last').remove(); });
            });
        });

        //if hit escape, then trigger close modal 
        $(document).off('keyup.escapeKey').on('keyup.escapeKey', function (e) {
            if (e.which == '27') {
                $('.closeModal').trigger('click.closeThisModal');
            }
        });

        $('.jsCloseModal').off('click.closeThisModal').on('click.closeThisModal', function (e) {
            e.preventDefault();
            $('.friInnerModal').removeClass('is-active');

            setTimeout(function () {
                $('.friModalWrapper:last').remove(); $('body').trigger('friModalSize.modalClose');
                modalLoader.fadeOut(400, function () { $('.loaderModal:last').remove(); });
            }, 350);
        });

        $('.closeButton, .closeModal').off('click.closeThisModal').on('click.closeThisModal', function (e) {
            e.preventDefault();
            $(this).parents('.friModalWrapper').trigger('click');
            $('body').off('videoLoaded');
            $(document).off('keyup.escapeKey');
            $('.friInnerModal').removeClass('is-active');
        });

    }

    return {
        openModal: openModal,
        loadModal: loadModal,
        closerWithCallback: closerWithCallback
    };

})(jQuery);

var editAccountInfo = editAccountInfo || {};
editAccountInfo = (function ($) {
    if (!$('.ma-account .edit').length) return;

    var $steps = $('.ma-account .edit'),
        $user = $steps.find('.jsUserName'),
        user = $user.val();

    $steps.hide().eq(0).show();
    $steps.find('.jsEdit').off('click').on('click', function (e) {
        e.preventDefault();
        $steps.eq(1).find('.field-validation-error').hide();
        $steps.hide().eq(1).show();
    });
    $steps.find('.jsForgotPassword').off('click').on('click', function (e) {
        e.preventDefault();
        $steps.eq(1).find('.field-validation-error').hide();
        $steps.hide().eq(4).show();
    });
    $steps.find('.jsCancel').off('click').on('click', function (e) {
        e.preventDefault();
        $steps.find('.jsRemoveWhenDone').remove();
        $steps.not($steps.eq(0)).hide().find('input').val('');
        $steps.find('.jsHaveEmail').val(user); // rewrite email fields with new email address
        $steps.find('form').data('validator').resetForm();
        $steps.eq(0).show();
    });

    $steps.find('form').off('submit.editAccount').on('submit.editAccount', function (e) {
        e.preventDefault();
        var $t = $(this),
            $sBtn = $t.find('[type=submit]');
        if ($t.valid()) {
            $sBtn.attr('disabled', 'disabled');
            $sBtn.addClass('mLoading');
            // the different steps...
            if ($t.hasClass('enterPassword')) { // submit from enter old password
                cartApi.callApiWithCallback('myaccount', 'validate', { email: user, password: $t.find('[type=password]').val() }, function (data) {
                    if (data === "Found") {
                        $steps.hide().eq(2).show(); // goto change email and password
                    } else {
                        $t.find('.field-validation-error').show();
                        $t.find('[type=password]').val('');
                    }
                    $sBtn.removeClass('mLoading');
                    $sBtn.removeAttr('disabled');
                });
            } else if ($t.hasClass('changeEmail')) { // submit from change email
                cartApi.callApiWithCallback('myaccount', 'updateUserEmail', { UserId: $t.find('input').data('userid'), Email: $t.find('input').val() }, function (data) {
                    if (typeof data === "object") { // it went through!
                        $steps.find('.jsHaveEmail').val(data.User.Email); // rewrite email fields with new email address
                        user = $steps.find('.jsUserName'); // set new email as user name
                        $steps.hide().eq(6).show(); // goto confirmation screen
                    } else {
                        $t.find('.field-validation-error').remove();
                        $('<p class="field-validation-error no-indent jsRemoveWhenDone">' + data + '</p>').insertAfter($t.find('input'));
                    }
                    $sBtn.removeClass('mLoading');
                    $sBtn.removeAttr('disabled');
                });
            } else if ($t.hasClass('changePassword')) { // submit from change password
                var pwd = new RegExp(/^(?=.*[!@#\$%\^&\*])/);
                //var isPasswordValid = $("#NewPassword").val().match(pwd);
                var isPasswordValid = pwd.test($("#NewPassword").val());

                if (isPasswordValid) {
                    $.ajax({
                        url: '/api/myaccount/changePassword',
                        type: 'POST',
                        data: {
                            Email: user,
                            Password: $t.find('input').eq(1).val(),
                            Locale: frigidaire.lang()
                        },
                        headers: { 'accept-language': frigidaire.lang() },
                        success: function () {
                            $steps.hide().eq(5).show(); // goto confirmation screen
                        },
                        error: function (err) {
                            $('<p class="field-validation-error no-indent jsRemoveWhenDone">' + JSON.parse(err.responseText).Message + '</p>').insertAfter($t.find('input'));
                        },
                        complete: function () {
                            $sBtn.removeClass('mLoading');
                            $sBtn.removeAttr('disabled');
                        }
                    });

                } else {
                    //$("div").text("fail");
                    $t.find('.field-validation-error').remove();
                    $('<p class="field-validation-error no-indent jsRemoveWhenDone">' + "Minimum 1 NonalphanumericCharacters required" + '</p>').insertAfter($t.find('input'));
                    $sBtn.removeClass('mLoading');
                    $sBtn.removeAttr('disabled');
                }
            } else if ($t.hasClass('resetPassword')) {
                cartApi.callApiWithCallback('myaccount', 'resetPassword', { EmailAddress: $t.find('input').val(), CultureCode: frigidaire.lang(), TokenExpiration: $t.find('input').data('token-exp') }, function (data) {
                    if (data.responseText) {
                        var obj = $.parseJSON(data.responseText)
                        $t.find('input').next().removeClass('field-validation-valid').addClass('field-validation-error').append('<span>' + obj.Message + '</span>');
                        $sBtn.removeClass('mLoading');
                        $sBtn.removeAttr('disabled');
                        return;
                    }
                    $steps.hide().eq(5).show(); // goto confirmation screen
                    $sBtn.removeClass('mLoading');
                    $sBtn.removeAttr('disabled');
                });
            }
        }
    });

})(jQuery);



