﻿// Mega Menu Config.
var TabHoverDelay = 100;
var TrimHoverDelay = 50;
var CloseMMDelay = 500;
var BuildYourCarTimeDelay = 2500;
// Buying Tools Config.
var BuyToolAnimationTime = 300;
var HoverClosingTime = 1000;
var BuyToolsDelay = 150;
// Owner Resources Config.
var ORAnimationTime = 700;
var ORHoverClosingTime = 1000;
var ORDelay = 100;
// Carousel Config.
var CarouselSwippingSpeed = 800;
var CarouselSwippingTime = 7000;
// Global Objects.
var SiteID = null;
var Vehicles = null;
var megamenu = null;
var ownerresources = null;
var buyingtool = null;
var is_touch_device = null;

function createVehicleObject() {
    Vehicles = $.parseJSON(car).Subaru;
}

function replaceAll(txt, replace, with_this) {
    return txt.replace(new RegExp(replace, 'g'), with_this);
}

function getSiteID() {
    SiteID = querySt('WebSiteID');
}

function querySt(key) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == key) {
            return ft[1];
        }
    }
}

function MegaMenu() {
    this.SelectedRangeVehicle = null;
    this.SelectedRangeVehicleIndex = null;
    this.SelectedCar = null;
    this.SelectedColour = null;
    this.CurrentTab = null;
    this.HoveringContainer = false;
    this.TimerTracker = null;
    this.TabTimerTracker = null;
    this.TrimTimerTracker = null;
    this.DynamicContent = null;
    this.BuildYourCarTimerTracer = null;
    this.RootContainer = $('#mmContainer');
    this.MMContainer = this.RootContainer.find('.mmContent');
    this.MainMenu = this.RootContainer.find('.tabs li');
    this.TrimMenu = this.MMContainer.find('#mmTrim li');
    this.MMContainer.VehiclePane = this.MMContainer.find('.mmVehicle');
    this.MMContainer.BuildCar = this.MMContainer.find('#BuildCar');
    this.MMContainer.BuildCarText = this.MMContainer.find('#BuildCarText');
    this.MMContainer.CarTooltip = this.MMContainer.BuildCar.find('#CarTooltip');
    this.MMContainer.SmallBeautyImg = this.MMContainer.find('#SmallBeauty');
    this.pricingLink = $('#mmPrice');
    this.tooltip = $('#BuildCar');
    var that = this;
    var tab = null;

    this.tooltip.click(function () {
        var url = $(this).attr('href');
        if (url != undefined && url != '')
            document.location = url;
    });

    this.MMContainer.hover(
        function () {
            that.HoveringContainer = true;
            clearTimeout(that.TimerTracker);
        },
        function () {
            that.HoveringContainer = false;
            if (is_touch_device) {
                this.TimerTracker = setTimeout('megamenu.closeMM()', 0);
            }
            else {
                this.TimerTracker = setTimeout('megamenu.closeMM()', CloseMMDelay);
            }
        }
    );

    this.MMContainer.VehiclePane.hover(
        function () {
            that.MMContainer.HoveringVehicle = true;
            clearTimeout(that.TrimTimerTracker);
        },
        function () {
            that.MMContainer.HoveringVehicle = false;
        }
    );

    if (!is_touch_device) {
        for (var i = this.MainMenu.length; i--; ) {
            if (Vehicles[this.MainMenu[i].id] == undefined)
                continue;
            $(this.MainMenu[i]).find('a').attr('href', 'WebPage.aspx?WebPageID=' + Vehicles[this.MainMenu[i]['id']][0].Overview + '&Range=' + replaceAll(Vehicles[this.MainMenu[i]['id']][0].Range, ' ', '+') + '&ModelYear=' + Vehicles[this.MainMenu[i]['id']][0].year + '&WebSiteID=' + SiteID);
        }
    }
    
    this.MainMenu.hover(
        function () {
            clearTimeout(that.TabTimerTracker);
            clearTimeout(that.TrimTimerTracker);
            that.CurrentTab = 'tab';
            if (is_touch_device) {
                if (tab != null) {
                    if (tab.attr('id') == $(this).attr('id')) {
                        var RangeID = tab.attr('id');
                        location.href = 'WebPage.aspx?WebPageID=' + Vehicles[RangeID][0].Overview + '&Range=' + replaceAll(Vehicles[RangeID][0].Range, ' ', '+') + '&ModelYear=' + Vehicles[RangeID][0].year + '&WebSiteID=' + SiteID;
                        return;
                    }
                    else {
                        tab = $(this);
                    }
                }
                else {
                    tab = $(this);
                }
                that.TabTimerTracker = setTimeout('megamenu.TabHover()', 0);
            }
            else {
                tab = $(this);
                that.TabTimerTracker = setTimeout('megamenu.TabHover()', TabHoverDelay);
            }
        },
        function () {
            that.HoveringContainer = false;
            that.CurrentTab = 'NoTab';
            clearTimeout(that.TabTimerTracker);
            if (is_touch_device) {
                that.TimerTracker = setTimeout('megamenu.closeMM()', 0);
            }
            else {
                that.TimerTracker = setTimeout('megamenu.closeMM()', CloseMMDelay);
            }
        }
    );

    this.TabHover = function () {
        if (this.CurrentTab == 'tab') {
            // Closing other menus immediately.
            this.HoveringContainer = false;
            if (buyingtool != null) {
                buyingtool.isHoveringMenu = false;
                buyingtool.closeMenu();
            }
            if (ownerresources != null) {
                ownerresources.isHoveringOwnerMenu = false;
                ownerresources.closeOwnerMenu();
            }
            if (quoteManager != null) {
                quoteManager.isHoveringQuoteManager = false;
                quoteManager.closeQuoteManager();
            }
            if (startbottommenu != null) {
                if (startbottommenu.bottomMenuContainer.is(':visible')) {
                    startbottommenu.bottomMenuContainer.hide();
                    startbottommenu.restoreBottomMenuImage();
                }
            }
            var RangeID = tab.attr('id');
            if (this.SelectedRangeVehicle != null) {
                if (Vehicles[RangeID] != undefined && this.SelectedRangeVehicle[0].Range != Vehicles[RangeID][0].Range)
                    this.SelectedRangeVehicle = Vehicles[RangeID];
            }
            else {
                this.SelectedRangeVehicle = Vehicles[RangeID];
            }

            var RangeName = (this.SelectedRangeVehicle == undefined) ? '' : (this.SelectedRangeVehicle[0].Range == 'WRX & WRX STI' ? 'WRXSTI' : this.SelectedRangeVehicle[0].Range);
            this.MMContainer.SmallBeautyImg.attr('src', 'content/7907/media/General/webimage/2012/' + (this.SelectedRangeVehicle == undefined ? '' : this.SelectedRangeVehicle[0].year) + '_' + RangeName + '_smallBeauty.jpg').show();

            this.showVehicleToContainer();

            clearTimeout(this.BuildYourCarTimerTracer);
            this.MMContainer.BuildCar.hide();
            this.MainMenu.not(tab).find('span:eq(0)').removeClass('activeTab-left').addClass('inactiveTab');
            this.MainMenu.not(tab).find('span:eq(1)').removeClass('activeTabTxt').addClass('inactiveTabTxt').css('color', '#fff'); ;
            this.MainMenu.not(tab).find('span:eq(2)').removeClass('activeTab-right').addClass('inactiveTab');
            tab.find('span:eq(0)').removeClass('inactiveTab').addClass('activeTab-left');
            tab.find('span:eq(1)').removeClass('inactiveTab').addClass('activeTabTxt').css('color', '#878787');
            tab.find('span:eq(2)').removeClass('inactiveTab').addClass('activeTab-right');
            this.MMContainer.show();
        }
    }

    this.showVehicleToContainer = function () {
        this.DynamicContent = this.MMContainer.find('.mmVehicleDynamic');
        this.DynamicContent.hide();

        if (SiteID == 284) {
            this.MMContainer.find('.dollarsign').insertAfter('.mmVehicle-top-price');
        }

        if (this.SelectedRangeVehicle != undefined) {
            for (var i = 0; i < this.SelectedRangeVehicle.length; i++) {
                var BodyTrim = this.SelectedRangeVehicle[i].BodyTrim.split('/');

                var TrimBase = this.MMContainer.find('.TrimMenu:eq(' + i + ')').find('.mmtrim');
                var TrimDesc = this.MMContainer.find('.TrimMenu:eq(' + i + ')').find('.mmtrimLine');
                var TrimOption = this.MMContainer.find('.TrimMenu:eq(' + i + ')').find('.mmtrimLinePlus');

                TrimOption.text(BodyTrim[2] != null ? BodyTrim[2] : '');
                TrimDesc.text(BodyTrim[1] != null ? BodyTrim[1] : '');
                TrimBase.text(BodyTrim[0] != null ? BodyTrim[0] : '').parent().parent().show();
            }
        }

        if (IE_Version >= 7 && IE_Version < 8) {
            this.MMContainer.find('.mmtrim').css({ 'line-height': '10px', 'padding': '0 0 0 0px', 'margin': '0' });
            this.MMContainer.find('.mmtrimLine').css({ 'line-height': '10px', 'padding': '0 0 0 7px', 'margin': '0' });
            this.MMContainer.find('.mmtrimLinePlus').css({ 'line-height': '9px', 'padding': '0 0 0 8px', 'margin': '0' });
        }

        this.TrimMenu.unbind();
        this.TrimMenu.hover(
        function () {
            clearTimeout(that.TrimTimerTracker);
            that.TrimMenu.hoveringTrim = true;
            that.MMContainer.trim = $(this);
            that.TrimTimerTracker = setTimeout('megamenu.TrimHover()', TrimHoverDelay);
        },
        function () {
            that.TrimMenu.hoveringTrim = false;
            that.TrimOut();
        }
    );

        this.resetTrimClass();

        this.preloadTrimImages();
    }

    this.preloadTrimImages = function () {
        var cacheholder = $('#preloadContainer');
        cacheholder.empty();
        if (this.SelectedRangeVehicle != undefined) {
            for (var i = this.SelectedRangeVehicle.length; i--; ) {
                var ColourIDs = this.SelectedRangeVehicle[i].colourID.split('/');
                cacheImage = 'content/7907/media/General/thumbnail/' + this.SelectedRangeVehicle[i].CarID + '_' + ColourIDs[0] + '.png';
                $('<img src="' + cacheImage + '" style="width:1px" />').appendTo(cacheholder);
            }
        }
    }

    this.TrimHover = function () {
        if (this.MMContainer.HoveringVehicle == true || this.TrimMenu.hoveringTrim == true) {
            clearTimeout(this.BuildYourCarTimerTracer);
            this.MMContainer.BuildCar.hide();
            this.SelectedRangeVehicleIndex = this.TrimMenu.index(this.MMContainer.trim);
            //that.BuildYourCarTimerTracer = setTimeout('showBuildYourCar()', BuildYourCarTimeDelay);

            this.DisplayBodyTrim();

            this.recalculateTrimClass();
        }
    }

    this.TrimOut = function () {
        return;
    }

    this.DisplayBodyTrim = function () {
        if (this.HoveringContainer == true && this.CurrentTab != 'tab') {
            this.showSpec();
            this.DynamicContent.fadeIn('fast');
            this.MMContainer.SmallBeautyImg.fadeOut('fast');
        }
    }

    this.resetTrimClass = function () {
        var BodyTrimCount = (this.SelectedRangeVehicle == undefined) ? 0 : this.SelectedRangeVehicle.length - 1;
        this.TrimMenu.css({ 'background-position': '0 -40px', 'text-shadow': '#fff 0px -1px 0px' });
        this.TrimMenu.find('a').css('color', '#666');
        this.TrimMenu.eq(0).css('background-position', '0 0px');
        this.TrimMenu.eq(0).find('a').css('color', '#666');
        this.TrimMenu.eq(BodyTrimCount).css('background-position', '0 -80px');
        this.TrimMenu.eq(BodyTrimCount).find('a').css('color', '#666');
        this.MMContainer.find('.TrimMenu:gt(' + BodyTrimCount + ')').hide();
    }

    this.recalculateTrimClass = function () {
        var BodyTrimCount = this.SelectedRangeVehicle.length - 1;
        if (this.TrimMenu.index(this.MMContainer.trim) == 0) {
            //First Menu is selected.
            this.TrimMenu.not(this.MMContainer.trim).css({ 'background-position': '0 -40px', 'text-shadow': '#fff 0px -1px 0px' });
            this.TrimMenu.not(this.MMContainer.trim).find('a').css('color', '#666');
            this.TrimMenu.eq(0).css({ 'background-position': '-618px 0', 'text-shadow': '#0A4066 0px -1px 0px' });
            this.TrimMenu.eq(0).find('a').css({ 'color': '#fff' });
            this.TrimMenu.eq(BodyTrimCount).css('background-position', '0 -80px');
            this.TrimMenu.eq(BodyTrimCount).find('a').css('color', '#666');
        }
        else if (this.TrimMenu.index(this.MMContainer.trim) == BodyTrimCount) {
            //Last Menu is selected.
            this.TrimMenu.not(this.MMContainer.trim).css({ 'background-position': '0 -40px', 'text-shadow': '#fff 0px -1px 0px' });
            this.TrimMenu.not(this.MMContainer.trim).find('a').css('color', '#666');
            this.TrimMenu.eq(0).css('background-position', '0 0');
            this.TrimMenu.eq(0).find('a').css('color', '#666');
            this.TrimMenu.eq(BodyTrimCount).css({ 'background-position': '-618px -80px', 'text-shadow': '#0A4066 0px -1px 0px' });
            this.TrimMenu.eq(BodyTrimCount).find('a').css('color', '#fff');
        }
        else {
            //Middle Menu is selected.
            this.TrimMenu.not(this.MMContainer.trim).css({ 'background-position': '0 -40px', 'text-shadow': '#fff 0px -1px 0px' });
            this.TrimMenu.not(this.MMContainer.trim).find('a').css('color', '#666');
            this.TrimMenu.filter(this.MMContainer.trim).css({ 'background-position': '-618px -40px', 'text-shadow': '#0A4066 0px -1px 0px' });
            this.TrimMenu.filter(this.MMContainer.trim).find('a').css('color', '#fff');
            this.TrimMenu.eq(0).css('background-position', '0 0');
            this.TrimMenu.eq(0).find('a').css('color', '#666');
            this.TrimMenu.eq(BodyTrimCount).css('background-position', '0 -80px');
            this.TrimMenu.eq(BodyTrimCount).find('a').css('color', '#666');
        }
    }

    this.showSpec = function () {
        var Range = this.SelectedRangeVehicle[0].Range == 'WRX & WRX STI' ? 'WRXSTI' : this.SelectedRangeVehicle[0].Range;
        var LogoClassName = 'mmLogos-' + Range;
        var TrimLogo = this.MMContainer.find('#mmVLogo');
        TrimLogo.removeClass().addClass('mmVehicle-top-logos').addClass('right').addClass(LogoClassName);
        $.each(this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex], function (SpecKey, SpecValue) {
            var key = '#' + SpecKey;
            var KeyName = that.MMContainer.find(key);
            KeyName.text(SpecValue);
        });

        this.DisplayVehicleColour(this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['CarID'], this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['colourID'], this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['colourName'], Range);
    }

    this.DisplayVehicleColour = function (CarID, ColourID, ColourName, Range) {
        this.MMContainer.find('#VehicleImage').unbind();
        this.MMContainer.find('#ColourList li').unbind();
        this.MMContainer.ColourList = this.MMContainer.find('#ColourList li');

        var ID = ColourID;
        var Name = ColourName;

        var ColourIDs = ID.split('/');
        var ColourNames = Name.split('/');
        var VehicleThumbnail = this.MMContainer.find('#VehicleImage');
        VehicleThumbnail.attr('src', 'content/7907/media/General/thumbnail/' + CarID + '_' + ColourIDs[0] + '.png');

        var cnt = ColourIDs.length;
        for (var i = 0; i < cnt; i++) {
            this.MMContainer.ColourList.eq(i).css('background', 'url(Content/7907/Media/General/Specification/' + ColourIDs[i] + '.jpg)').show();
        }
        this.MMContainer.find('#ColourList li:gt(' + --cnt + ')').hide();

        this.MMContainer.find('#mmVehicleColourName').text(ColourNames[0]);
        this.SelectedCar = CarID;
        this.SelectedColour = ColourIDs[0];

        var RangePath = Range == 'WRXSTI' ? 'WRX+&+WRX+STI' : Range;
        this.createVehicleThumbnailLink(RangePath);

        this.MMContainer.ColourList.hover(function () {
            var idx = that.MMContainer.ColourList.index(this);
            that.MMContainer.find('#mmVehicleColourName').text(ColourNames[idx]);
            that.MMContainer.find('#VehicleImage').attr('src', 'content/7907/media/General/thumbnail/' + CarID + '_' + ColourIDs[idx] + '.png');
            that.SelectedCar = CarID;
            that.SelectedColour = ColourIDs[idx];
            that.createVehicleThumbnailLink(RangePath);

            that.showBuildYourCar();
            if (that.BuildYourCarTimerTracer != null) clearTimeout(that.BuildYourCarTimerTracer);
            that.BuildYourCarTimerTracer = setTimeout('megamenu.HideToolTip()', BuildYourCarTimeDelay);
            that.pricingLink.attr('href', that.GetPricingURL(RangePath));
            that.tooltip.attr('href', that.GetPricingURL(RangePath));
        },
        function () {
            return;
        });

        if (IE_Version == 7) {
            var marginLeft = 19 * (8 - cnt);
            this.MMContainer.ColourList.addClass('UL-Horizental');
            this.MMContainer.ColourList.parent().css('margin-left', marginLeft);
            this.MMContainer.find('#msrp, .dollarsign').addClass('IE7-price');
            this.MMContainer.find('.dollarsign').css({ 'margin-top': 0 });
        }

        this.MMContainer.find('#mmOverview').attr('href', 'WebPage.aspx?WebPageID=' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['Overview'] + '&Range=' + RangePath + '&ModelYear=' + this.SelectedRangeVehicle[that.SelectedRangeVehicleIndex]['year'] + '&WebSiteID=' + SiteID);
        this.MMContainer.find('#mmSpecifications').attr('href', 'WebPage.aspx?WebPageID=' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['Specifications'] + '&Range=' + RangePath + '&ModelYear=' + this.SelectedRangeVehicle[that.SelectedRangeVehicleIndex]['year'] + '&CarID=' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['CarID'] + '&WebSiteID=' + SiteID);
        this.MMContainer.find('#mmAccessories').attr('href', 'WebPage.aspx?WebPageID=' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['Accessories'] + '&Range=' + RangePath + '&ModelYear=' + this.SelectedRangeVehicle[that.SelectedRangeVehicleIndex]['year'] + '&CarID=' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['CarID'] + '&WebSiteID=' + SiteID);
        this.MMContainer.find('#mmPrice').attr('href', 'WebPage.aspx?WebPageID=' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['Price'] + '&Range=' + RangePath + '&ModelYear=' + this.SelectedRangeVehicle[that.SelectedRangeVehicleIndex]['year'] + '&CarID=' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['CarID'] + '&WebSiteID=' + SiteID);
    }

    this.GetPricingURL = function (ModelName) {
        return 'WebPage.aspx?WebPageID=' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['Price'] + '&Range=' + ModelName + '&ModelYear=' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['year'] + '&CarID=' + this.SelectedCar + '&colourID=' + this.SelectedColour + '&WebSiteID=' + SiteID
    };

    this.createVehicleThumbnailLink = function (RangePath) {
        this.MMContainer.find('#VehicleImageLink').attr('href', this.GetPricingURL(RangePath));
    }

    this.showBuildYourCar = function () {
        if (this.tooltip.length > 0 && !this.tooltip.is(':visible')) {
            if (this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['Range'] == 'Tribeca' || this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['Range'] == 'Forester' || this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['Range'] == 'Outback') {
                this.MMContainer.BuildCar.css('top', '20px');
            }
            else {
                this.MMContainer.BuildCar.css('top', '40px');
            }

            if (SiteID == 282)
                this.MMContainer.BuildCarText.text('Build your ' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['year'] + ' ' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['Range']);
            else
                this.MMContainer.BuildCarText.text('Construire votre ' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['year'] + ' ' + this.SelectedRangeVehicle[this.SelectedRangeVehicleIndex]['Range']);
            this.MMContainer.CarTooltip.stop(true, true).css('height', 0);
            this.MMContainer.CarTooltip.animate({ 'height': '+=53px' }, 1000, 'easeOutElastic');
            this.MMContainer.BuildCar.fadeIn('slow');
        }
    }
    this.HideToolTip = function () {
        this.MMContainer.BuildCar.fadeOut('slow');
    };

    this.closeMM = function () {
        if (!this.HoveringContainer && this.CurrentTab != 'tab') {
            tab = null;
            this.MainMenu.find('span:eq(0)').removeClass('activeTab-left').addClass('inactiveTab');
            this.MainMenu.find('span:eq(1)').removeClass('activeTabTxt').addClass('inactiveTabTxt').css('color', '#fff');
            this.MainMenu.find('span:eq(2)').removeClass('activeTab-right').addClass('inactiveTab');
            this.MMContainer.hide();
        }
    }

    this.forcecloseMM = function () {
        tab = null;
        this.MainMenu.find('span:eq(0)').removeClass('activeTab-left').addClass('inactiveTab');
        this.MainMenu.find('span:eq(1)').removeClass('activeTabTxt').addClass('inactiveTabTxt').css('color', '#fff');
        this.MainMenu.find('span:eq(2)').removeClass('activeTab-right').addClass('inactiveTab');
        this.MMContainer.hide();
    }
}

function preloadSBImages() {
    var cacheholder = $('#preloadContainer');
    $.each(Vehicles, function (key, val) {
        var RangeName = Vehicles[key][0].Range == 'WRX & WRX STI' ? 'WRXSTI' : Vehicles[key][0].Range;
        var cacheImage = 'content/7907/media/General/webimage/2012/' + Vehicles[key][0].year + '_' + RangeName + '_smallBeauty.jpg';
        $('<img src="' + cacheImage + '" style="width:1px" />').appendTo(cacheholder);
    });
}

function BuyingTool() {
    this.isHoveringMenu = false;
    this.HoverTimerTracker = null;
    this.buyingWidth = null;
    this.HoveringMenu = null;
    this.RootBuyingTool = $('.TopBuyingTool');
    this.BuyingTool = this.RootBuyingTool.find('.buyingTool');
    this.FirstMenu = this.BuyingTool.find('.FirstList');
    this.FirstMenuContainer = this.FirstMenu.parent();
    this.SecondMenu = this.BuyingTool.find('.SecondList');
    this.BuyingTool.show();
    this.buyingWidth = this.BuyingTool.outerWidth() + 10;
    this.BuyingTool.find('ul').hide();
    this.BuyingTool.width(this.buyingWidth);
    this.buyingToolFlag = true;

    var that = this;

    if (is_touch_device) {
        //Resetting href to prevent automatic redirecting.
        this.BuyingTool.find('> li > a').attr('href', '#');
        this.SecondMenu.parent().parent().find('> a').attr('href', '#');

        this.BuyingTool.click(
            function () {
                if (megamenu != null)
                    megamenu.forcecloseMM();
                if (ownerresources != null) {
                    ownerresources.isHoveringOwnerMenu = false;
                    ownerresources.closeOwnerMenu();
                }
                if (quoteManager != null) {
                    quoteManager.isHoveringQuoteManager = false;
                    quoteManager.closeQuoteManager();
                }
                if (startbottommenu != null) {
                    if (startbottommenu.bottomMenuContainer.is(':visible')) {
                        startbottommenu.bottomMenuContainer.hide();
                        startbottommenu.restoreBottomMenuImage();
                    }
                }
                that.isHoveringMenu = true;
                if (that.FirstMenuContainer.is(':visible')) {
                    if (that.buyingToolFlag)
                        document.location = that.BuyingTool.find('> li > a').attr('name');
                }
                else {
                    $(this).find('li, li a').css({ 'background-color': '#444444', 'color': '#fff' });
                    that.FirstMenuContainer.animate({ 'height': 'show' }, { queue: false, easing: 'easeOutExpo', duration: BuyToolAnimationTime });
                    that.BuyingTool.addClass('buyingTool-Shadow');
                    that.SecondMenu.parent().hide();
                }
            }
        );

        this.FirstMenu.click(
            function () {
                that.isHoveringMenu = true;
                if (that.HoveringMenu != null) {
                    if (that.HoveringMenu.find('> a').attr('name') == $(this).find('> a').attr('name')) {
                        document.location = that.HoveringMenu.find('> a').attr('name');
                    }
                    else {
                        that.HoveringMenu = $(this);
                        if (!that.HoveringMenu.find('> ul').is(':visible')) {
                            that.HoverTimerTracker = setTimeout('buyingtool.FirstMenuMouseover()', 0);
                        }
                        that.buyingToolFlag = false;
                    }
                }
                else {
                    that.HoveringMenu = $(this);
                    if (!that.HoveringMenu.find('> ul').is(':visible')) {
                        that.HoverTimerTracker = setTimeout('buyingtool.FirstMenuMouseover()', 0);
                    }
                    that.buyingToolFlag = false;
                }
            }
        );
    }
    else {
        this.BuyingTool.hover(
            function () {
                if (megamenu != null)
                    megamenu.forcecloseMM();
                if (ownerresources != null) {
                    ownerresources.isHoveringOwnerMenu = false;
                    ownerresources.closeOwnerMenu();
                }
                if (quoteManager != null) {
                    quoteManager.isHoveringQuoteManager = false;
                    quoteManager.closeQuoteManager();
                }
                that.isHoveringMenu = true;
                $(this).find('li, li a').css({ 'background-color': '#444444', 'color': '#fff' });
                that.FirstMenuContainer.animate({ 'height': 'show' }, { queue: false, easing: 'easeOutExpo', duration: BuyToolAnimationTime });
                that.BuyingTool.addClass('buyingTool-Shadow');
                that.SecondMenu.parent().hide();
            },
            function () {
                that.isHoveringMenu = false;
                that.HoverTimerTracker = setTimeout('buyingtool.closeMenu()', HoverClosingTime);
            }
        );

        this.FirstMenuContainer.mouseout(
            function () {
                that.isHoveringMenu = false;
            }
        );

        this.FirstMenu.mouseover(
            function () {
                that.isHoveringMenu = true;
                that.HoveringMenu = $(this);
                that.HoverTimerTracker = setTimeout('buyingtool.FirstMenuMouseover()', BuyToolsDelay);
            }
        );

        this.SecondMenu.hover(
            function () {
                that.isHoveringMenu = true;
                $(this).css('background-color', '#fff');
                $(this).find('a').css({ 'color': '#000', 'background-color': '#fff' });
            },
            function () {
                that.isHoveringMenu = false;
                $(this).css('background-color', '#444444');
                $(this).find('a').css({ 'color': '#fff', 'background-color': '#444444' });
                if (IE_Version > 0 && IE_Version < 9)
                    that.HoverTimerTracker = setTimeout('buyingtool.closeMenu()', HoverClosingTime);
            }
        );
    }

    this.FirstMenuMouseover = function () {
        if (that.isHoveringMenu == true) {
            if (IE_Version >= 7 && IE_Version < 8) that.HoveringMenu.find('ul li').css('width', that.HoveringMenu.find('ul').width() - 10);

            that.FirstMenu.not(that.HoveringMenu).css('background-color', '#444444');
            that.FirstMenu.not(that.HoveringMenu).find('a').css({ 'color': '#fff', 'background-color': '#444444' });
            that.HoveringMenu.css('background-color', '#fff');
            that.HoveringMenu.find('> a').css({ 'color': '#000', 'background-color': '#fff' });
            that.FirstMenu.find('ul').css({ 'right': that.buyingWidth });
            //that.FirstMenu.find('ul').css({ 'right': that.buyingWidth + 1 });
            var SecondMenuContainer = that.HoveringMenu.find('> ul');
            if (IE_Version >= 7 && IE_Version < 8) {
                SecondMenuContainer.css('top', that.HoveringMenu.position().top);
                SecondMenuContainer.stop(true, true).show();
            }
            else {
                SecondMenuContainer.css('top', that.HoveringMenu.position().top - 1);
                SecondMenuContainer.stop(true, true).animate({ 'width': 'show' }, { queue: false, easing: 'easeOutExpo', duration: BuyToolAnimationTime });
            }
            that.SecondMenu.parent().not(SecondMenuContainer).stop(true, true).fadeOut(BuyToolAnimationTime);
        }
    }

    this.closeMenu = function () {
        if (this.isHoveringMenu == false) {
            that.FirstMenu.parent().stop(true, true).hide();
            that.BuyingTool.find('li, li > a').css('background-color', '#898989');
            that.BuyingTool.removeClass('buyingTool-Shadow');
        }
    }
}

function OwnerResources() {
    this.isHoveringOwnerMenu = false;
    this.HoverOwnerTimerTracker = null;
    this.OwnerWidth = null;
    this.HoveringOwnerMenu = null;
    this.SecondOwnerMenuRight = null;
    this.SecondMenuOriginalLeftPosition = null;
    $('.TopOwnerResources').unbind();
    this.RootOwnerResource = $('.TopOwnerResources');
    this.OwnerResource = this.RootOwnerResource.find('.OwnerResources');
    this.FirstOwnerMenu = this.OwnerResource.find('.FirstChildMenu');
    this.FirstOwnerMenuContainer = this.FirstOwnerMenu.parent();
    this.SecondOwnerMenu = this.OwnerResource.find('.SecondChildMenu');
    this.SecondMenuContainer = this.SecondOwnerMenu.parent();

    this.OwnerResource.show();
    this.OwnerWidth = this.OwnerResource.outerWidth();
    this.OwnerResource.find('ul').hide();
    this.OwnerResource.width(this.OwnerWidth);

    var that = this;

    if (IE_Version < 0)
        this.SecondMenuContainer.addClass('OwnerResources-Shadow');
    else if (IE_Version >= 9)
        this.SecondMenuContainer.addClass('OwnerResources-Shadow-IE');

    this.OwnerResource.hover(
        function () {
            if (megamenu != null)
                megamenu.forcecloseMM();
            if (buyingtool != null) {
                buyingtool.isHoveringMenu = false;
                buyingtool.closeMenu();
            }
            if (quoteManager != null) {
                quoteManager.isHoveringQuoteManager = false;
                quoteManager.closeQuoteManager();
            }
            if (startbottommenu != null) {
                if (startbottommenu.bottomMenuContainer.is(':visible')) {
                    startbottommenu.bottomMenuContainer.hide();
                    startbottommenu.restoreBottomMenuImage();
                }
            }
            that.isHoveringOwnerMenu = true;
            $(this).find('li').removeClass('OwnerResources-hover');
            $(this).find('li').removeClass('OwnerResourcesRadius');
            $(this).find('li > a').css('color', '#666');
            that.FirstOwnerMenuContainer.animate({ 'height': 'show' }, { queue: false, easing: 'easeOutExpo', duration: ORAnimationTime });
            if (IE_Version < 0)
                that.OwnerResource.addClass('OwnerResources-Shadow');
            else if (IE_Version >= 9)
                that.OwnerResource.addClass('OwnerResources-Shadow-IE');
            that.SecondOwnerMenu.parent().hide();
        },
        function () {
            that.isHoveringOwnerMenu = false;
            that.HoverOwnerTimerTracker = setTimeout('ownerresources.closeOwnerMenu()', ORHoverClosingTime);
        }
    );

    this.FirstOwnerMenu.mouseover(
        function () {
            that.isHoveringOwnerMenu = true;
            that.HoveringOwnerMenu = $(this);
            that.SecondOwnerMenuRight = that.FirstOwnerMenuContainer.position().left + that.FirstOwnerMenuContainer.width() + 2;
            that.HoverOwnerTimerTracker = setTimeout('ownerresources.FirstOwnerMenuMouseover()', ORDelay);
        }
    );

    this.FirstOwnerMenuContainer.mouseout(
        function () {
            that.isHoveringOwnerMenu = false;
            if (IE_Version > 0 && IE_Version < 9)
                that.HoverOwnerTimerTracker = setTimeout('ownerresources.closeOwnerMenu()', ORHoverClosingTime);
        }
    );

    this.FirstOwnerMenuMouseover = function () {
        if (that.isHoveringOwnerMenu == true) {
            that.HoveringOwnerMenu.addClass('OwnerResources-hover');
            that.HoveringOwnerMenu.find('> a').css('color', '#fff');
            that.FirstOwnerMenu.not(that.HoveringOwnerMenu).removeClass('OwnerResources-hover');
            that.FirstOwnerMenu.not(that.HoveringOwnerMenu).find('a').css('color', '#666');
            that.HoveringOwnerMenu.addClass('OwnerResourcesRadius');
            this.SecondOwnerMenuContainer = that.HoveringOwnerMenu.find('> ul');
            if (IE_Version >= 7 && IE_Version < 8) {
                if (that.SecondMenuOriginalLeftPosition == null)
                    that.SecondMenuOriginalLeftPosition = this.SecondOwnerMenuContainer.position().left;
                else
                    this.SecondOwnerMenuContainer.css('left', that.SecondMenuOriginalLeftPosition);
                var SecondMenuWidth = this.SecondOwnerMenuContainer.width();

                that.FirstOwnerMenu.find('ul').css({ 'left': that.SecondOwnerMenuRight });
                this.SecondOwnerMenuContainer.width(SecondMenuWidth);
            }
            else {
                that.FirstOwnerMenu.find('ul').css({ 'left': that.SecondOwnerMenuRight });
            }
            this.SecondOwnerMenuContainer.css('top', that.HoveringOwnerMenu.position().top + 2);
            if (IE_Version > 0 && IE_Version < 9)
                that.SecondOwnerMenu.parent().not(this.SecondOwnerMenuContainer).stop(true, true).hide();
            else
                that.SecondOwnerMenu.parent().not(this.SecondOwnerMenuContainer).stop(true, true).fadeOut(BuyToolAnimationTime);

            if (IE_Version >= 7 && IE_Version < 8)
                this.SecondOwnerMenuContainer.stop(true, true).show();
            else
                this.SecondOwnerMenuContainer.stop(true, true).animate({ 'height': 'show' }, { queue: true, easing: 'easeOutExpo', duration: ORAnimationTime + 300 });
        }
    }

    this.SecondOwnerMenu.hover(
        function () {
            that.isHoveringOwnerMenu = true;
            $(this).css('background-color', '#4C4C4C');
            $(this).find('a').css({ 'color': '#fff', 'background-color': '#4C4C4C' });
            $(this).addClass('OwnerResourcesRadius');
        },
        function () {
            that.isHoveringOwnerMenu = false;
            $(this).css('background-color', '#fff');
            $(this).find('a').css({ 'color': '#666', 'background-color': '#fff' });
        }
    );

    this.closeOwnerMenu = function () {
        if (this.isHoveringOwnerMenu == false) {
            that.FirstOwnerMenu.parent().stop(true,true).hide();
            if (IE_Version < 0)
                that.OwnerResource.removeClass('OwnerResources-Shadow');
            else if (IE_Version >=9)
                that.OwnerResource.removeClass('OwnerResources-Shadow-IE');
        }
    }
}

function handleSearchBox() {
    var SearchBox = $('.searchInput');
    this.SearchInputString = SearchBox.val();

    SearchBox.mousedown(
        function () {
            if (SearchBox.val() == SearchInputString) {
                SearchBox.val('');
            }
        }
    );
}

function adjustMyAccountCss(){
    if (IE_Version >= 7 && IE_Version < 8) {
        $('.accountDiv').css('margin-top', '0');
        $('.myAccount').css('padding', '3px 10px 5px 10px');
    }
}

function startBottomMenu() {
    this.bmVehicleContainer = $('.modelselect_div');
    this.bottomMenu = this.bmVehicleContainer.find('.bottom-menu');
    this.bottomMenuList = this.bottomMenu.find('li');
    this.bottomMenuContainer = $('#bottom-menu-container');
    this.clickedButton = null;
    this.selectedVehicle = null;

    var that = this;

    if (IE_Version >= 8 && IE_Version < 9) {
        this.bmVehicleContainer.css('margin-top', '-70px');
    }

    for (var i = this.bottomMenuList.length; i--; ) {
        if (Vehicles[this.bottomMenuList[i].className] == undefined)
            continue;
        if(is_touch_device)
            $(this.bottomMenuList[i]).find('a').attr('name', 'WebPage.aspx?WebPageID=' + Vehicles[this.bottomMenuList[i]['className']][0].Overview + '&Range=' + replaceAll(Vehicles[this.bottomMenuList[i]['className']][0].Range, ' ', '+') + '&ModelYear=' + Vehicles[this.bottomMenuList[i]['className']][0].year + '&WebSiteID=' + SiteID);
        else
            $(this.bottomMenuList[i]).find('a').attr('href', 'WebPage.aspx?WebPageID=' + Vehicles[this.bottomMenuList[i]['className']][0].Overview + '&Range=' + replaceAll(Vehicles[this.bottomMenuList[i]['className']][0].Range, ' ', '+') + '&ModelYear=' + Vehicles[this.bottomMenuList[i]['className']][0].year + '&WebSiteID=' + SiteID);
    }

    if (is_touch_device) {
        this.bottomMenu.find('li').click(
            function () {
                if (megamenu != null)
                    megamenu.forcecloseMM();
                if (buyingtool != null) {
                    buyingtool.isHoveringMenu = false;
                    buyingtool.closeMenu();
                }
                if (ownerresources != null) {
                    ownerresources.isHoveringOwnerMenu = false;
                    ownerresources.closeOwnerMenu();
                }
                if (quoteManager != null) {
                    quoteManager.isHoveringQuoteManager = false;
                    quoteManager.closeQuoteManager();
                }

                if (that.selectedVehicle == $(this).find('img').attr('alt')) {
                    document.location = that.clickedButton;
                }
                else {
                    that.clickedButton = $(this).find('a').attr('name');
                    that.bottomMenuContainer.prependTo($(this));
                    that.bottomMenuContainer.css({ 'left': $(this).position().left - 30, 'bottom': $(this).position().top + 95 });
                    that.selectedVehicle = $(this).find('img').attr('alt');
                    that.restoreBottomMenuImage();
                    that.resetBottomMenuImage();
                    that.putBottomBemuValues();
                    that.bottomMenuContainer.show();
                    if (megamenu != null)
                        megamenu.forcecloseMM();
                    if (buyingtool != null) {
                        buyingtool.isHoveringMenu = false;
                        buyingtool.closeMenu();
                    }
                    if (ownerresources != null) {
                        ownerresources.isHoveringOwnerMenu = false;
                        ownerresources.closeOwnerMenu();
                    }
                    if (quoteManager != null) {
                        quoteManager.isHoveringQuoteManager = false;
                        quoteManager.closeQuoteManager();
                    }
                }
            }
        );
    }
    else {
        this.bottomMenu.find('li').hover(
            function () {
                if (megamenu != null)
                    megamenu.forcecloseMM();
                if (buyingtool != null) {
                    buyingtool.isHoveringMenu = false;
                    buyingtool.closeMenu();
                }
                if (ownerresources != null) {
                    ownerresources.isHoveringOwnerMenu = false;
                    ownerresources.closeOwnerMenu();
                }
                if (quoteManager != null) {
                    quoteManager.isHoveringQuoteManager = false;
                    quoteManager.closeQuoteManager();
                }
                that.bottomMenuContainer.prependTo($(this));
                that.bottomMenuContainer.css({ 'left': $(this).position().left - 30, 'bottom': $(this).position().top + 95 });
                that.selectedVehicle = $(this).find('img').attr('alt');
                that.resetBottomMenuImage();
                that.putBottomBemuValues();
                that.bottomMenuContainer.show();
            },
            function () {
                that.bottomMenuContainer.hide();
                that.restoreBottomMenuImage();
            }
        );
    }

    this.putBottomBemuValues = function () {
        this.bottomMenuContainer.find('#yearBottom').text(Vehicles[this.selectedVehicle][0].year);
        this.bottomMenuContainer.find('#msrpBottom').text(Vehicles[this.selectedVehicle][0].msrp);
        if (SiteID == 284) {
            this.bottomMenuContainer.find('.dollarsignBottom').insertAfter('.mmVehicle-bottom-price');
            this.bottomMenuContainer.find('.mmVehicle-bottom-price').css('float', 'left');
        }
        else {
            if ($.browser.mozilla) {
                this.bottomMenuContainer.find('.msrp-bottom').css('float', 'none');
            }
            if (IE_Version >= 7 && IE_Version < 8) {
                this.bottomMenuContainer.find('.msrp-bottom').css({ 'position': 'absolute', 'padding-top': '23px' });
            }
        }

        if (IE_Version >= 7 && IE_Version < 8) {
            this.bottomMenuContainer.find('.mmVehicle-bottom-price-wrap').css({ 'top': '13px' });
            this.bottomMenuContainer.find('.mmVehicle-bottom-price').css({ 'padding-top': '2px', 'height': '37px', 'line-height': '37px' });
            this.bottomMenuContainer.find('.dollarsignBottom').css({ 'height': '26px', 'line-height': '26px', 'padding-top': '7px' });
            this.bottomMenuContainer.find('.bmLinks').css({ 'padding-top': '18px' });
        }

        this.bottomMenuContainer.find('#bmGallery').attr('href', 'WebPage.aspx?WebPageID=' + Vehicles[this.selectedVehicle][0].Gallery + '&Range=' + replaceAll(Vehicles[this.selectedVehicle][0].Range, ' ', '+') + '&ModelYear=' + Vehicles[this.selectedVehicle][0].year + '&WebSiteID=' + SiteID);
        this.bottomMenuContainer.find('#bmExplore').attr('href', 'WebPage.aspx?WebPageID=' + Vehicles[this.selectedVehicle][0].Explore + '&Range=' + replaceAll(Vehicles[this.selectedVehicle][0].Range, ' ', '+') + '&ModelYear=' + Vehicles[this.selectedVehicle][0].year + '&WebSiteID=' + SiteID);
        this.bottomMenuContainer.find('#bmAccessories').attr('href', 'WebPage.aspx?WebPageID=' + Vehicles[this.selectedVehicle][0].Accessories + '&Range=' + replaceAll(Vehicles[this.selectedVehicle][0].Range, ' ', '+') + '&ModelYear=' + Vehicles[this.selectedVehicle][0].year + '&WebSiteID=' + SiteID);
        this.bottomMenuContainer.find('#bmPrice').attr('href', 'WebPage.aspx?WebPageID=' + Vehicles[this.selectedVehicle][0].Price + '&Range=' + replaceAll(Vehicles[this.selectedVehicle][0].Range, ' ', '+') + '&ModelYear=' + Vehicles[this.selectedVehicle][0].year + '&WebSiteID=' + SiteID);
    }

    this.resetBottomMenuImage = function () {
        var menuImage = null;
        for (var i = that.bottomMenuList.length; i--; ) {
            menuImage = $(that.bottomMenuList[i]).find('img');
            if (that.selectedVehicle != menuImage.attr('alt')) {
                menuImage.attr('src', menuImage.attr('src').replace('.jpg', '_dimmed.jpg'));
            }
        }
    }

    this.restoreBottomMenuImage = function () {
        var menuImage = null;
        for (var i = that.bottomMenuList.length; i--; ) {
            menuImage = $(that.bottomMenuList[i]).find('img');
            menuImage.attr('src', menuImage.attr('src').replace('_dimmed.jpg', '.jpg'));
        }
    }
}

function enableCommunityPanel() {
    var CommunityPanel = $('.smFooter');

    if (CommunityPanel.length > 0) {
        var CollapsableButton = CommunityPanel.find('.smf-tabTopTip');
        var CollapsablePanel = CommunityPanel.find('.smFooter-wrapper');
        var smContent = CommunityPanel.find('.smf-content');
        var closeImage = CollapsableButton.find('#smf_button');
        CollapsableButton.click(function () {
            if (CollapsablePanel.height() > 0) {
                if (is_touch_device) {
                    smContent.hide();
                    CollapsablePanel.css({ 'height': '0' });
                }
                else {
                    smContent.fadeOut('fast');
                    CollapsablePanel.animate({ 'height': '0' }, 500, 'easeOutExpo');
                }
                if (SiteID == 282) {
                    closeImage.removeClass('smf_tabTopTip_image_close').addClass('smf_tabTopTip_image');
                    $('.smf_title_image').remove();
                }
                else {
                    closeImage.removeClass('smf_tabTopTip_image_close_french').addClass('smf_tabTopTip_image_french');
                    $('.smf_title_image_french').remove();
                }
            }
            else {
                var position = $(this).position();
                if (is_touch_device) {
                    CollapsablePanel.css({ 'height': '557px' });
                    smContent.show();
                    $("html, body").scrollTop(position.top);
                }
                else {
                    CollapsablePanel.animate({ 'height': '557px' }, 500, 'easeOutExpo');
                    smContent.fadeIn('slow');
                    if (IE_Version < 0 || IE_Version >= 8) {
                        $("html, body").animate({ scrollTop: position.top }, 500, 'easeOutExpo');
                    }
                }
                if (SiteID == 282) {
                    closeImage.removeClass('smf_tabTopTip_image').addClass('smf_tabTopTip_image_close');
                    $('<div class="smf_title_image"></div>').appendTo('.smf-title');
                }
                else {
                    closeImage.removeClass('smf_tabTopTip_image_french').addClass('smf_tabTopTip_image_close_french');
                    $('<div class="smf_title_image_french"></div>').appendTo('.smf-title');
                }
            }
        });
    }
}

function adjustCSS() {
    if (typeof (IE_Version) == 'undefined') {
        if ($.browser.msie)
            IE_Version = $.browser.version;
        else
            IE_Version = -1;
    }
    if (IE_Version >= 7 && IE_Version < 8)
        $('#mainContent').attr('id', 'expired');
    is_touch_device = 'ontouchstart' in document.documentElement;
}

function Carousel(container) {
    this.container = container;
    this.listElement = this.container.find('ul');
    this.carouselElements = this.listElement.find('li');
    this.carouselElementsSize = this.carouselElements.length;
    this.itemWidth = this.carouselElements.eq(0).width();
    this.listElement.css('width', this.itemWidth * this.carouselElementsSize);
    this.animateID = null;
    this.leftPosition = null;
    this.isPlaying = false;
    this.currentIndex = 1;
    this.Slider_Left = this.container.find('#Slider_Left');
    this.Slider_Right = this.container.find('#Slider_Right');
    this.Slider_Buttons = this.container.find('#Slider_Buttons');

    if (this.listElement.length < 1)
        return;

    var that = this;

    var PreventClick = function (anchor) {
        if (anchor == null)
            return;

        anchor.click(function (e) {
            e.preventDefault();
        });
    };

    this.closeOtherMenu = function () {
        if (megamenu != null)
            megamenu.forcecloseMM();
        if (buyingtool != null) {
            buyingtool.isHoveringMenu = false;
            buyingtool.closeMenu();
        }
        if (ownerresources != null) {
            ownerresources.isHoveringOwnerMenu = false;
            ownerresources.closeOwnerMenu();
        }
        if (quoteManager != null) {
            quoteManager.isHoveringQuoteManager = false;
            quoteManager.closeQuoteManager();
        }
        if (startbottommenu != null) {
            if (startbottommenu.bottomMenuContainer.is(':visible')) {
                startbottommenu.bottomMenuContainer.hide();
                startbottommenu.restoreBottomMenuImage();
            }
        }
    }

    var AddControlClickHandler = function (control) {
        if (control == null)
            return;

        control.click(function (e) {
            if (!that.isPlaying) {
                that.closeOtherMenu();
                that.setAnimationStart();
                var clickedIndex = that.Slider_Button.index($(this)) + 1;

                if (that.currentIndex == that.carouselElementsSize - 2 && clickedIndex == 1)
                    that.currentIndex = that.currentIndex + 1;
                else if (that.currentIndex == 1 && clickedIndex == that.carouselElementsSize - 2)
                    that.currentIndex = 0;
                else
                    that.currentIndex = clickedIndex;
                that.Slider_Button.removeClass('Slider_Button_Selected');
                that.Slider_Button.eq(clickedIndex - 1).addClass('Slider_Button_Selected');
                that.executeAnimation();
            }
        });
    }

    this.AnimateNext = function (direction) {
        if (direction == 'normal')
            this.currentIndex += 1;
        else
            this.currentIndex -= 1;
        this.executeAnimation();
    }

    this.executeAnimation = function () {
        this.setAnimationStart();
        this.leftPosition = this.itemWidth * this.currentIndex * -1;
        this.listElement.animate({ 'left': this.leftPosition }, { queue: true, easing: 'easeOutExpo', duration: CarouselSwippingSpeed, complete: function () { that.completeAnimation(); } });
    }

    this.completeAnimation = function (sender) {
        if (this.currentIndex == 0)
            this.currentIndex = this.carouselElementsSize - 2;
        else if (this.currentIndex == this.carouselElementsSize - 1)
            this.currentIndex = 1;
        this.listElement.css('left', this.itemWidth * this.currentIndex * -1);
        this.update_Slider_Button();
        this.isPlaying = false;
        this.listElement.draggable('enable');
        this.play();
    }

    this.listElement.draggable({ axis: 'x', addClasses: false, distance: 5, calcel: 'SliderButton' });

    this.listElement.bind('dragstart', function (event, ui) {
        if (!that.isPlaying) {
            that.setAnimationStart();
        }
    });

    this.listElement.bind('dragstop', function (event, ui) {
        if (ui.position.left < ui.originalPosition.left) {
            that.AnimateNext('normal');
        }
        else {
            that.AnimateNext('oposit');
        }
    });

    this.Slider_Left.click(
        function () {
            if (!that.isPlaying) {
                that.closeOtherMenu();
                that.setAnimationStart();
                that.AnimateNext('oposit');
            }
        }
    );

    this.Slider_Right.click(
        function () {
            if (!that.isPlaying) {
                that.closeOtherMenu();
                that.setAnimationStart();
                that.AnimateNext('normal');
            }
        }
    );

    this.setAnimationStart = function () {
        clearTimeout(this.animateID);
        this.listElement.draggable('disable');
        this.isPlaying = true;
    }

    if (is_touch_device) {
        this.Slider_Left.stop(true, true).fadeIn('slow');
        this.Slider_Right.stop(true, true).fadeIn('slow');
    }
    else {
        this.container.hover(
            function () {
                that.Slider_Left.stop(true, true).fadeIn('slow');
                that.Slider_Right.stop(true, true).fadeIn('slow');
            },
            function () {
                that.Slider_Left.stop(true, true).fadeOut('slow');
                that.Slider_Right.stop(true, true).fadeOut('slow');
            }
        );
    }

    for (var i = 0; i < this.carouselElementsSize - 2; i++) {
        $('<div class="Slider_Button"></div>').appendTo(this.Slider_Buttons);
    }

    this.Slider_Button = this.container.find('.Slider_Button');
    this.Slider_Button.eq(0).addClass('Slider_Button_Selected');
    this.Slider_Buttons.css('left', (this.itemWidth - this.Slider_Buttons.outerWidth()) / 2);
    this.Slider_Buttons.show();

    this.update_Slider_Button = function () {
        if (this.Slider_Button != null) {
            this.Slider_Button.removeClass('Slider_Button_Selected');
            this.Slider_Button.eq(this.currentIndex - 1).addClass('Slider_Button_Selected');
        }
    }

    this.Slider_Button.each(
        function () {
            AddControlClickHandler($(this));
        }
    );

    this.carouselElements.each(function () {
        var anchor = $(this).find('a');
        if (anchor.attr('href') == '') {
            PreventClick(anchor);
            anchor.addClass('disabled');
        }
    });

    this.play = function () {
        this.animateID = setTimeout('carousel.AnimateNext("normal")', CarouselSwippingTime);
    }

    this.play();
}
var InventorySlide = function () {
    this.AnimationSpeed = 200;
    this.container = $('#slider');
    this.leftPosition = null;
    this.isPlaying = false;
    this.currentIndex = 0;
    //this.currentIndex = 7;
    this.dragStartTime = null;

    if (this.container.length > 0) {
        this.leftButton = this.container.find('.slideLeft');
        this.rightButton = this.container.find('.slideRight');
        this.listElement = this.container.find('.sliderThumb');
        this.carouselElements = this.listElement.find('li');
        this.carouselElementsSize = this.carouselElements.length;
        this.waitFrame = this.carouselElements.find('.inventory_list_wait_image');
        this.vehicleImage = this.carouselElements.find('.dealer_pre-owned_image');
        this.itemWidth = this.carouselElements.eq(0).outerWidth() + 3;
        var that = this;

        this.loadVehicleImages = function () {
            for (var i = 0; i < this.vehicleImage.length; i++) {
                this.vehicleImage.eq(i).attr('src', this.vehicleImage.eq(i).attr('alt')).attr('alt', 'Vehicle Image');
                this.vehicleImage.eq(i).one('load', function () { $(this).show(); });
            }
        }

        if (this.carouselElementsSize <= 7) {
            this.leftButton.hide();
            this.rightButton.hide();
            this.loadVehicleImages();
            return;
        }

        this.leftButton.click(function () {
            if (!that.isPlaying) {
                that.setAnimationStart();
                that.executeAnimation('left')
            }
        });

        this.rightButton.click(function () {
            if (!that.isPlaying) {
                that.setAnimationStart();
                that.executeAnimation('right')
            }
        });

        this.executeAnimation = function (direction) {
            if (direction == 'left') {
                this.currentIndex -= 1;
            }
            else if (direction == 'right') {
                this.currentIndex += 1;
            }
            this.leftPosition = this.itemWidth * this.currentIndex * -1;

            if (this.currentIndex < 0) {
                this.listElement.animate({ 'left': this.leftPosition }, { queue: true, easing: 'easeOutExpo', duration: this.AnimationSpeed, complete: function () { that.gobacktoFirstAnimation(); } });
            }
            else if (this.currentIndex >= this.carouselElementsSize - 7) {
                this.listElement.animate({ 'left': this.leftPosition }, { queue: true, easing: 'easeOutExpo', duration: this.AnimationSpeed, complete: function () { that.gobacktoLastAnimation(); } });
            }
            else {
                this.listElement.animate({ 'left': this.leftPosition }, { queue: true, easing: 'easeOutQuint', duration: this.AnimationSpeed, complete: function () { that.completeAnimation(); } });
            }
        }

        this.gobacktoFirstAnimation = function () {
            this.listElement.animate({ 'left': 0 }, { queue: true, easing: 'easeOutQuint', duration: this.AnimationSpeed * 1.5, complete: function () { that.completeAnimation(); } });
        }
        this.gobacktoLastAnimation = function () {
            this.listElement.animate({ 'left': this.itemWidth * (this.carouselElementsSize - 7) * -1 }, { queue: true, easing: 'easeOutQuint', duration: this.AnimationSpeed * 1.5, complete: function () { that.completeAnimation(); } });
        }

        this.completeAnimation = function () {
            /*if (this.currentIndex == 6)
            this.currentIndex = this.carouselElementsSize - 8;
            else if (this.currentIndex == this.carouselElementsSize - 7)
            this.currentIndex = 7;
            this.listElement.css('left', this.itemWidth * this.currentIndex * -1);*/
            if (this.currentIndex < 0)
                this.currentIndex = 0;
            else if (this.currentIndex > this.carouselElementsSize - 7)
                this.currentIndex = this.carouselElementsSize - 7;
            this.isPlaying = false;
            this.listElement.draggable('enable');
        }

        this.setAnimationStart = function () {
            this.listElement.draggable('disable');
            this.isPlaying = true;
        }

        this.listElement.bind('dragstart', function (event, ui) {
            if (!that.isPlaying) {
                clearTimeout(this.animateID);
                this.dragStartTime = (new Date()).getTime();
            }
        });

        this.listElement.bind('dragstop', function (event, ui) {
            var dragdistance = ui.position.left - ui.originalPosition.left;
            var dragsize = dragdistance / that.itemWidth;
            dragsize = parseInt(dragsize);
            var dragEndTime = (new Date()).getTime();
            var timeDifference = dragEndTime - this.dragStartTime;
            if (dragdistance / that.itemWidth != 0) {
                if (dragdistance < 0) {
                    dragsize--;
                    if (timeDifference < 100)
                        that.currentIndex -= (dragsize * dragsize * -1);
                    else
                        that.currentIndex -= dragsize;
                }
                else {
                    dragsize++;
                    if (timeDifference < 100)
                        that.currentIndex += (dragsize * (dragsize * -1));
                    else
                        that.currentIndex += dragsize * -1;
                }
            }

            if (ui.position.left < ui.originalPosition.left) {
                that.setAnimationStart();
                that.executeAnimation('dragright');
            }
            else {
                that.setAnimationStart();
                that.executeAnimation('dragleft');
            }
        });

        this.listElement.draggable({ axis: 'x', addClasses: false, distance: 5 });
        this.loadVehicleImages();
    }
}

$(document).ready(
function () {
    adjustCSS();
    getSiteID();
    if (typeof (car) != 'undefined') {
        createVehicleObject();
        megamenu = new MegaMenu();
        preloadSBImages();
    }
    ownerresources = new OwnerResources();
    buyingtool = new BuyingTool();
    adjustMyAccountCss();
    handleSearchBox();
    startbottommenu = new startBottomMenu();
    enableCommunityPanel();
    carousel = new Carousel($('#HeaderCarousel2012'));
    inventoryslide = new InventorySlide();
});

