/* Minification failed. Returning unminified contents.
(3321,1-6): run-time error JS1195: Expected expression: class
(3323,19-20): run-time error JS1004: Expected ';': {
(3329,18-19): run-time error JS1004: Expected ';': {
(3332,40-41): run-time error JS1195: Expected expression: >
(3332,74-75): run-time error JS1004: Expected ';': )
(3337,21-22): run-time error JS1004: Expected ';': {
(3341,40-41): run-time error JS1195: Expected expression: >
(3343,10-11): run-time error JS1195: Expected expression: )
(3348,17-18): run-time error JS1004: Expected ';': {
(3354,21-22): run-time error JS1004: Expected ';': {
(3355,46-47): run-time error JS1195: Expected expression: )
(3355,49-50): run-time error JS1195: Expected expression: >
(3355,74-75): run-time error JS1195: Expected expression: ,
(3362,20-21): run-time error JS1004: Expected ';': {
(3377,20-21): run-time error JS1004: Expected ';': {
(3378,46-47): run-time error JS1014: Invalid character: `
(3378,58-59): run-time error JS5008: Illegal assignment: =
(3378,82-83): run-time error JS1014: Invalid character: `
(3382,1-2): run-time error JS1002: Syntax error: }
(3384,29-30): run-time error JS1195: Expected expression: )
(3384,31-32): run-time error JS1004: Expected ';': {
(3386,2-3): run-time error JS1195: Expected expression: )
(3390,19-20): run-time error JS1004: Expected ';': {
(3396,18-19): run-time error JS1004: Expected ';': {
(3399,40-41): run-time error JS1195: Expected expression: >
(3399,74-75): run-time error JS1004: Expected ';': )
(3404,22-23): run-time error JS1004: Expected ';': {
(3408,40-41): run-time error JS1195: Expected expression: >
(3410,10-11): run-time error JS1195: Expected expression: )
(3415,17-18): run-time error JS1004: Expected ';': {
(3421,22-23): run-time error JS1004: Expected ';': {
(3422,47-48): run-time error JS1195: Expected expression: )
(3422,50-51): run-time error JS1195: Expected expression: >
(3422,75-76): run-time error JS1195: Expected expression: ,
(3429,20-21): run-time error JS1004: Expected ';': {
(3444,20-21): run-time error JS1004: Expected ';': {
(3445,46-47): run-time error JS1014: Invalid character: `
(3445,58-59): run-time error JS5008: Illegal assignment: =
(3445,82-83): run-time error JS1014: Invalid character: `
(3449,1-2): run-time error JS1002: Syntax error: }
(3452,37-38): run-time error JS1004: Expected ';': {
(3713,98-99): run-time error JS1100: Expected ',': =
(3713,107-108): run-time error JS1002: Syntax error: ,
(3713,126-127): run-time error JS1100: Expected ',': =
(3713,135-136): run-time error JS1002: Syntax error: ,
(3713,152-153): run-time error JS1100: Expected ',': =
(3713,161-162): run-time error JS1002: Syntax error: ,
(3713,169-170): run-time error JS1100: Expected ',': =
(3713,178-179): run-time error JS1197: Too many errors. The file might not be a JavaScript file: )
 */

//// Ajax function to get the function URL for all js.
BMWAjax = function () {
    return {
        lib: function () {
            return {
                beforeSend: function (p) {
                    return function (x) {

                        x.name = p.name || 'N/A';
                        x.passthru = p.passthru || {};
                        x.passthru.requestUrl = x.passthru.requestUrl || this.url;
                    }
                },
                complete: function (p) {
                    return function () {

                        var args = [].slice.call(arguments);
                        if (args[1] != null && args[1] != "success" && args[0] != "") {
                            arguments[0].responseJSON = args[0].responseText;
                            args.push(args[0].responseText);
                        }
                        else {
                            arguments[0].responseJSON = JSON.parse(args[0].responseText);
                            args.push(JSON.parse(args[0].responseText));
                        }
                        setTimeout(function () { p.complete.apply(this, args); }, 100);
                        $('#dvLoader').hide();
                    }
                },
                request: function (p1, p2) {
                    p1 = p1 || {};
                    p2 = p2 || {};
                    p1.method = p1.method || 'GET';
                    p2.complete = p2.complete || function () { };
                    p2.name = p1.name || 'N/A';

                    var o = {
                        beforeSend: BMWAjax.lib.beforeSend(p2),
                        complete: BMWAjax.lib.complete(p2),
                        contentType: 'application/json',
                        dataType: 'json',
                        processData: false,
                        type: p1.method
                    }
                    //$('#dvLoader').show();
                    if (p1.data !== null && typeof (p1.data === 'object')) o.data = JSON.stringify(p1.data);
                    if (p1.url !== null) o.url = p1.url;
                    return o;
                },
                0: {} // terminator
            }
        }(),
        Urls: {
            DealerLocator: {
                GetZipcode: '../../DealerLocator/GetZip',
                DealerPopIcon: '../../DealerLocator/DealerPopIcon',
                GetDealerSearchQueryResult: '../../DealerLocator/GetDealerSearchQueryResult'
            },
            Products: {
                GetRelatedProducts: '../../Products/GetRelatedProducts',
                NoStockDealerNotificationForProduct: '../../Products/NoStockDealerNotificationForProduct'
            },
            Motorsports: {
                ValidateUser: "../../MotorSports/ValidateUser"
            },
            Home: {
                SetAlertClose: "../../Home/SetAlertClose",
                CloseBlackoutMsg: "../../Home/CloseBlackoutMsg",
                SetSessionvalue: '../../Home/StoreEventInSession'
            },
            Visualizer: {
                GetVisualizerProductOptionDetails: "../../Visualizer/GetVisualizerProductOptionDetails",
                AddVisualizerProductsToSummary: "../../Visualizer/AddVisualizerProductsToSummary",
                LoadVisualizerData: "../../Visualizer/LoadVisualizerData",
                LoadVisualizerHeader: "../../Visualizer/LoadVisualizerHeader",
                InsertVisualizerShareDetails: "../../Visualizer/InsertVisualizerShareDetails",
                GetSharedProductOptionDetails: "../../Visualizer/GetSharedProductOptionDetails"
            },
            Cart: {
                UpdateDeliveryType: "../../Cart/UpdateDeliveryType",
                UpdateCart: "../../Cart/UpdateCart",
                CheckSpecialsInventoryCount: '../../Cart/CheckSpecialsInventoryCount',
                UpdateSpecialsInventoryCount: '../../Cart/UpdateSpecialsInventoryCount',
                ApplyPromoCode:"../../Cart/ApplyPromoCode"
            },
            VehicleSelector: {
                GetYearList: "../../VehicleSelector/GetYearList",
                GetSeriesList: "../../VehicleSelector/GetSeriesList",
                GetYearListForProductSelection: "../../VehicleSelector/GetYearListForProductSelection",
                GetYourBMW: "../../VehicleSelector/GetYourBMW",
                ClearModelSelection: "../../VehicleSelector/ClearModelSelection",
                CheckProductFitment: "../../VehicleSelector/CheckProductFitment",
                GetModelList: "../../VehicleSelector/GetModelList",
                GetShoppableImagePoints: "../../LandingPage/GetShoppableImagePoints"
            },
            Specials: {
                GetSpecialCategoryProducts: '../../LandingPage/GetSpecialCategoryProducts',
            },
            VehicleLanding: {
                GetMPPProducts: '../../Products/GetMPPCollections',
                GetAccCategoryProducts: '../../LandingPage/GetFeaturedCategoryProducts',
                GetTopCategories: '../../LandingPage/GetTopCategories',
                GetFeaturedProducts: '../../LandingPage/GetFeaturedProducts',
                GetLifestyleProducts: '../../Products/Lifestyle'
            },
            
                
            0: {}
        }
    }
}();

//For scroll handler in Product list  page
var page = 0,
    inCallback = false,
    isReachedScrollEnd = false;
var numberOfPages = 0;
var lastScrollTop = 0;
//Global functions called from Razor pages
var addSubmitSpinner = function (submitButtonId) {
    $("#" + submitButtonId).prop('disabled', true);
    $("#" + submitButtonId).find('.primary-text').toggleClass('d-none');
    $("#" + submitButtonId).find('.spinner').toggleClass('d-none');
};

var removeSubmitSpinner = function (submitButtonId) {
    $("#" + submitButtonId).prop('disabled', false);
    $("#" + submitButtonId).find('.primary-text').toggleClass('d-none');
    $("#" + submitButtonId).find('.spinner').toggleClass('d-none');
};

//Common Jquery behavior throughout site
$(document).ready(function () {

    //hide image in safari 
    if ( navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome') && !navigator.userAgent.includes('Edge')) {
        $('#Pictsafary').css('display', 'none');
        $('#imgsafari').css('display', 'block');
    }
    if (navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome') && !navigator.userAgent.includes('Edge')) {
        $('#Wheelssafari').css('display', 'none');
        $('#Wheelsimgsafari').css('display', 'block');
    }
    //else if ( navigator.userAgent.includes('iPhone') && !navigator.userAgent.includes('Chrome') && !navigator.userAgent.includes('Edge')) {
        //$('#Pictsafary').css('display', 'none');
       // $('#imgsafari').css('display', 'block');
    //}

    // handling browser resubmission message after post action page load.
    $("#select-your-bmw").click(function () {
        commonGA4Tracking('Navigation', 'Select Your BMW', 'Navigation');
    });

    $("#locateDealerClick, #divSelectedDealerLarge").click(function () {
        commonGA4Tracking('Navigation', 'Locate A Dealer', 'Navigation');
    });

    var vehicleSelect = $("#hdnVehicleSelect").val();
    if (vehicleSelect == "true") {
        showModelPopup();
    }

    var urlStr = window.location.href;
    if (urlStr.toLowerCase().indexOf('visualizer') > 0 || urlStr.toLowerCase().indexOf('cart') > 0) {
        if (window.history.replaceState) {
            window.history.replaceState(null, null, window.location.href);
        }
    }
    else if (urlStr.toUpperCase().indexOf('BMW-IX-PRE-ORDER') > 0 || urlStr.toUpperCase().indexOf('BMW-I4-PRE-ORDER') > 0 || urlStr.toUpperCase().indexOf('BMW-PRE-ORDER-TEMPLATE') > 0 || urlStr.toUpperCase().indexOf('BMW-8-X-JEFF-KOONS-PRE-ORDER') > 0 || urlStr.toUpperCase().indexOf('BMW-I7-PRE-ORDER') > 0 ) {
        if (!$("footer").hasClass("d-none"))
            $("footer").addClass("d-none");
        if ($(".iXWrapper").hasClass("I4White")) {
            $(".iXWrapper").removeClass("I4White");
            $("body").addClass("I4White");
        }
        $("body").addClass("i4Scroll");

    }
    else if (window.location.href.toLowerCase().indexOf('/preorder/') > 0) {
        $("body").addClass("i4Scroll");
    }
    //vehicle modal backdrop
    $('.vehicle-modal').on('show.bs.modal', function (e) {
        setTimeout(function () {
            $('.modal-backdrop').addClass('overall-index');
        });
    });

    var width = window.innerWidth;
    if (width < 768) {
        $('input:hidden[id ^= "hdnFMAItem"]').each(function (index, obj) {
            var divId = obj.id.replace("hdnFMAItem", "divFMAItem");
            var mblUrl = $("#" + obj.id).val();
            $("#" + divId).css("background-image", "url(" + mblUrl + ")");
        });
    }
    if ($('.InstockCon-body-overlay').is(":visible")) {
        $('body').addClass('body-fixed');
        $('html').css('overflow', 'hidden');
    }

    if ($("#divFreeshipHead").html() != undefined && $("#divMBadgeHead").html() != undefined) {
        if (!$("#divBody").hasClass("MBadgeFreeShipSpacing")) {
            $("#divBody").addClass("MBadgeFreeShipSpacing");
        }
        $("#divBody").removeClass("MBadgeSpacing");
    }
    else if ($("#divMBadgeHead").html() != undefined) {
        if (!$("#divBody").hasClass("MBadgeSpacing")) {
            $("#divBody").addClass("MBadgeSpacing");
        }
        $("#divBody").removeClass("MBadgeFreeShipSpacing");
    }
    if (window.location.href.toLowerCase().indexOf('/visualizer') > -1 && ($("#divFreeshipHead").html() != undefined || $("#divMBadgeHead").html() != undefined)) {
        if (!$(".SecVisualTab").hasClass("SecVisualTabActive")) {
            $(".SecVisualTab").addClass("SecVisualTabActive");
        }
    }
    else {
        if ($(".SecVisualTab").hasClass("SecVisualTabActive")) {
            $(".SecVisualTab").removeClass("SecVisualTabActive");
        }
    }
    
    window.addEventListener("pageshow", function (event) {
        var historyTraversal = event.persisted ||
            (typeof window.performance != "undefined" &&
                window.performance.navigation.type === 2);
        if (historyTraversal) {
            // Handle browser back             
           
            if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Opera") != -1 || navigator.userAgent.indexOf('OPR') != -1 || (navigator.userAgent.search("Safari") != -1 && navigator.userAgent.search("Chrome") == -1)) {
                window.location.reload(true);
            }
        }
    });

    if ($("#divAlertBarMobile").html() != undefined || $("#divAlertBarDesktop").html() != undefined) {
        $("#app").addClass("has-alert");
    }
    
    $('#sel-bmw').click(function () {
        $("#navMain").removeClass('Navbar-fixed').addClass('Navbar-changed');
        $("#fitment-widget_t").removeClass('NavSub-changed').addClass('NavSub-fixed');
    });

    $('.back-to-menu').click(function () {
        $("#fitment-widget_t").removeClass('NavSub-fixed').addClass('NavSub-changed');
        $("#navMain").removeClass('Navbar-changed').addClass('Navbar-fixed');
    });

    $('#nav-icon1').click(function () {
        $('#mobileMenu').scrollTop(0);

    });

    //When a modal appears, autofocus on any inputfields with autofocus set
    $('.modal').on('shown.bs.modal', function () {
        $(this).find('[autofocus]').focus();
    });

    //Locate a dealer icon
    $(".SelectedDealerLarge").click(function () {
        if ($("#mobileMenu").hasClass('active')) {
            $("#mobileMenu").removeClass('show');
            $("#nav-icon1").removeClass('open');
            $('#divHeaderBodyOverlay').css('display', 'none');
        }
        else if ($("#cartSummary").is(':visible')) {
            closeCartFlyout();
            $('#divHeaderBodyOverlay').css('display', 'block');
        }

    });

    //Cart in Checkout section
    $('#ShowCart').click(function () {
        //$("#ChkCart").removeClass('d-none').addClass('d-block');
        if ($("#ChkCart").hasClass("d-none")) { $("#ChkCart").removeClass('d-none').addClass('d-block'); }
        else if ($("#ChkCart").hasClass("d-block")) { $("#ChkCart").removeClass('d-block').addClass('d-none'); }
    });
    //select bmw  
    $("#sel-bmwId").click(function () {
        commonGA4Tracking('Navigation', 'Select Your BMW', 'Navigation');
        selectYearSeriesModel();
    });
    $("#modelBtn").click(function () {
        $('#rightToggleMenu').addClass("active");
        if (document.getElementById("hdnModelName")) {
            var modelName = document.getElementById("hdnModelName").value;
            if (modelName !== "") {
                var divSelectBMW = document.getElementById("sel-bmwId").textContent;
                if (divSelectBMW.includes(modelName) === false) {
                    $('#rightToggleMenu, #OverlayRight').css('display', 'none');
                    window.location.reload(true);
                }
            }
        }
    });
    //Cart
    $("#cartContainer").click(function () {
        if ($("#dealerSearch").is(':visible')) {
            $("#dealerSearch").removeClass('show');
            $('#dealerOverlay').css('display', 'none');
            $('#divHeaderBodyOverlay').css('display', 'none');
        }
        else if ($("#mobileMenu").hasClass('active')) {
            $("#mobileMenu").removeClass('show');
            $("#nav-icon1").removeClass('open');
            $('#divHeaderBodyOverlay').css('display', 'none');
            $('#dealerOverlay').css('display', 'none');
        }

    });

    //START Cart Summary   
    $(document).mouseup(function (e) {
        if ($(e.target).closest(".cart-summary").length === 0) {
            closeCartFlyout();
        }
    });

    //END Cart summary

    //right menu overlay
    $(".link-text-light").click(function () {
        $('#OverlayRight').css('display', 'block');
        $('body').addClass('body-fixed');
        $('body').css('overflow-y', 'hidden');
        $('html').css('overflow', 'hidden');
    });

    setOverLay();
    $("#OverlayRight, .back-to-menu").click(function () {
        var modelName = document.getElementById("hdnModelName").value;
        var url = window.location.href.toLowerCase();
        if (url.indexOf('/bmw-flowcode') < 0 || (url.indexOf('/bmw-flowcode') > 0 && modelName != "" && modelName != null && modelName != undefined)) {
            $(".right-toggle").removeClass("show");
            $('#OverlayRight').css('display', 'none');
            $('body').removeClass('body-fixed');
            $('body').css('overflow-y', 'auto');
            $('html').css('overflow-y', 'auto');
        }
        
    });
    $(".year-list a").click(function () {
        if (!$('body').hasClass('body-fixed')) {
            $('body').addClass('body-fixed');
        }
    });
    $(".change-selected").click(function () {
        if (!$('body').hasClass('body-fixed')) {
            $('body').addClass('body-fixed');
        }
    });
    
    $("#txtBxSearch").click(function () {
        commonGA4Tracking('Navigation', 'Search', 'Navigation');
        if (document.getElementById("hdnReload"))
            window.location.reload(true);
        $(".right-toggle").removeClass("show");
        $("#mobileMenu").removeClass("show");
        $('#OverlayRight').css('display', 'none');
        $('#divHeaderBodyOverlay').css('display', 'none');
    });
    $("#Navtoggle").click(function () {
        if (document.getElementById("hdnReload"))
            window.location.reload(true);
        $(".right-toggle").removeClass("show");
        $('#OverlayRight').css('display', 'none');
    });

    //END right menu overlay

    //menu icon
    $("#nav-icon1").click(function () {
        if ($("#dealerSearch").is(':visible')) {
            $("#dealerSearch").removeClass('show');
            $('#dealerOverlay').css('display', 'none');
            $('#divHeaderBodyOverlay').css('display', 'none');
        }
        else if ($("#cartSummary").is(':visible')) {
            closeCartFlyout();
            $('#divHeaderBodyOverlay').css('display', 'none');
            $('#dealerOverlay').css('display', 'none');
        }
    });

    //scroll - resposive 
    $('.trigger-overlay').on('click', function (e) {
        //if (!($("#divHeaderBodyOverlay").is(':visible') && $("#mobileMenu").hasClass('active'))) {
        if (!($("#divHeaderBodyOverlay").is(':visible') && $("#mobileMenu").hasClass('active'))) {
            $('#divHeaderBodyOverlay').toggle();
        }
        setTimeout(function () {
            if ($("#divHeaderBodyOverlay").is(':visible')) {
                $('body').addClass('body-fixed');
                $('body').css('overflow-y', 'hidden');
                $("#divTopCategories").css('overflow', 'hidden');
                $('html').css('overflow', 'hidden');
            }
            else {
                //$('#divHeaderBodyOverlay').toggle();
                $('body').css('overflow-y', 'auto');
                $('body').removeClass('body-fixed');
                $("#divTopCategories").css('overflow', 'auto');
                $('html').css('overflow-y', 'auto');
            }
        }, 150);

    });

    $("#divSelectedDealerLarge").click(function () {
        if ($("#isIxI4DealerLocator").val() !== undefined && $("#isIxI4DealerLocator").val() !== null && $("#isIxI4DealerLocator").val() === "true") {
            //IxI4DealerLocator checking
            $('html').css('overflow-y', '');
        }
        else {
            $('html').css('overflow-y', 'hidden');
            $('body').addClass('body-fixed');
        }
        $('#dealerOverlay').css('display', 'block');
        $('body').css('overflow-y', 'hidden');

    });
    $(".dealer-overlay").click(function () {
        $('#dealerOverlay').css('display', 'none');
        $(".mobile-menu-dealer-search").removeClass('show');
        $('body').removeClass('body-fixed');
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow-y', 'auto');
        visDealerPopUp();
    });

    $(".DealerInfo a").click(function () {
        $('#dealerOverlay').css('display', 'none');
        $('body').removeClass('body-fixed');
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow-y', 'auto');
    });


    $("#divSelectOptOverlay").click(function () {
        $("#divSelectOpt").removeClass('ProD-block');
        $("#divSelectOpt").addClass('ProD-none');
        $("#divSelectOptOverlay").removeClass('d-block');
        $("#divSelectOptOverlay").addClass('d-none');
        $('body').removeClass('body-fixed');
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow-y', 'auto');
    });

    //Hamburger Icon
    $('#nav-icon1').click(function () {
        $(this).toggleClass('open');
    });

    //floating form labels
    $('input').blur(function () {
        $label = $(this).siblings("label");
        $value = $(this).val();

        if ($value !== "") {
            $label.addClass("input-not-empty");
        } else {
            $label.removeClass("input-not-empty");
        }
    });

    $('#divHeaderBodyOverlay').click(function () {
        setTimeout(function () { popupClose(); }, 150);

    });
    $('#dealerOverlay').click(function () {
        setTimeout(function () { popupClose(); }, 150);
        closeDealerPopUp();

    });
    $('#cartSummaryOverlay').click(function () {
        closeCartFlyout();
    });
    //Colours visible on mouseover
    setColorVisibilityOnMouseOver();

    //Sort option shadow
    $("#description2").on('show.bs.collapse', function () {
        $('#cardHeading2').addClass("SortShadow");
    });
    $("#description2").on('hidden.bs.collapse', function () {
        $('#cardHeading2').removeClass("SortShadow");
    });

    //product detail carousel height for align video vertically center
    var cw = $('.productImageControl .calc-height').width();
    $('.calc-height .carousel-item').css({
        'height': cw + 'px'
    });

    //if ($("#hdnIsAlertEnabled").val() != undefined && $("#hdnIsAlertEnabled").val().toLowerCase() == "true")
    //    $("#AlertModalHome").modal("show");

    if (window.location.pathname != '/') {
        var pathname = window.location.pathname.toLowerCase();
        if (pathname == '/visualizer/intro' || (pathname == '/yourvehicle') || pathname.indexOf('/specials/') > -1) {
            if (pathname == '/yourvehicle') {
                $("#divBody").css('overflow-x', 'hidden');
            }
            if (window.location.pathname == '/yourvehicle' && $("#divBody").hasClass("MppLandingBlack")) {
                $("body").addClass("VehicleLandBlack");
                $("header[id='app']").addClass("BlackTheme");
            }
            if (!$("header[id='app']").find("nav").hasClass("ThemeTrans")) {
                $("header[id='app']").find("nav").addClass("ThemeTrans");
            }
            if (pathname == '/visualizer/intro') {
                if ($("header[id='app']").hasClass("WhiteTheme")) {
                    $("header[id='app']").removeClass("WhiteTheme");
                }
            }
        }
        else {
            if (!$("header[id='app']").hasClass("WhiteTheme") && !$("header[id='app']").hasClass("PreOrderHeader") && pathname.indexOf('bmw-flowcode') < 0) {
                $("header[id='app']").addClass("WhiteTheme");
            }
            if ($("header[id='app']").find("nav").hasClass("ThemeTrans")) {
                $("header[id='app']").find("nav").removeClass("ThemeTrans");
            }
        }
        if (pathname == '/wheels-and-tires/overview') {
            $(".MptopSubNav").addClass("mppHeaderBorder");
        }
    }
    else {
        if ($("header[id='app']").hasClass("WhiteTheme")) $("header[id='app']").removeClass("WhiteTheme");
        if (!$("header[id='app']").find("nav").hasClass("ThemeTrans")) $("header[id='app']").find("nav").addClass("ThemeTrans");
    }
    
    if (window.location.pathname.toLowerCase() == '/blackthemedemo' || window.location.pathname.toLowerCase() == "/m-performance/overview" || ($("#divPrdListMain") != null && $("#divPrdListMain").hasClass("MPBlacklist"))
        || ($(".productDetailContainer") != null && $(".productDetailContainer").is(":visible") && $("#divBody").hasClass("MBlackTheme")) || (window.location.pathname.toLowerCase() == '/yourvehicle' && $("#divBody").hasClass("MppLandingBlack"))) {
        if ($("header[id='app']").hasClass("WhiteTheme")) {
            $("header[id='app']").removeClass("WhiteTheme");
            if (window.location.pathname.toLowerCase() == '/yourvehicle' && $("#divBody").hasClass("MppLandingBlack")) {
                $("header[id='app']").addClass("DarkTheme");
                $('body').addClass('bodyBlack');
            }
            else {
                $("header[id='app']").addClass("BlackTheme");
                $('body').addClass('bodyBlack');
            }
        }
        if ($(".productDetailContainer").is(":visible")) {
            $(".DivDetailMBadge").removeClass("d-none");
            $("#divBMWOrg").addClass("d-none");
        }
        $('footer').attr('id', "Mfooter");
        $('.NavFooterDiv').find("footer").attr('id', "Catfooter");
        if (window.location.pathname.toLowerCase() == "/m-performance/overview") {
            if (!$("header[id='app']").find("nav").hasClass("border-0"))
                $("header[id='app']").find("nav").addClass("border-0");
            if (!$("#divHeadLineMPP").hasClass("mpmenubg"))
                $("#divHeadLineMPP").addClass("mpmenubg");
            $('body').addClass('bodyBlack');
        }
        if (!$("#divBody").hasClass("MppLandingBlack")) {
            if ($("header[id='app']").find("nav").hasClass("ThemeTrans"))
                $("header[id='app']").find("nav").removeClass("ThemeTrans");
        }
    }

    //START flyout transitions jQuery
    $('#Navtoggle').on('click', function (e) {
        $('.mobile-menu.browse-menu').addClass("active");
        $('#divHeaderBodyOverlay').css('display', 'block');
        e.preventDefault();
    });
    $('#divHeaderBodyOverlay').click(function () {
        $(".mobile-menu.browse-menu").removeClass("active");
    });

    $('.pro-fitment-pop').on('click', function (e) {
        $('.mobile-menu.right-toggle').addClass("active");
        e.preventDefault();
    });
    $('#OverlayRight').click(function () {
        var modelName = document.getElementById("hdnModelName").value;
        var url = window.location.href.toLowerCase();
        if (url.indexOf('/bmw-flowcode') < 0 || (url.indexOf('/bmw-flowcode') > 0 && modelName != "" && modelName != null && modelName != undefined)) {
            $(".mobile-menu.right-toggle").removeClass("active");
        }
    });

    //for mobile
    $('.fitment-shortlist .year-tag, .fitment-shortlist .change-selected').on('click', function (e) {
        $('.m-modal-fitment').addClass("active");
        e.preventDefault();
    });

    $('.m-modal-fitment').on('shown.bs.modal', function () {
        $('.modal-backdrop').addClass('m-overlay');
    });

    $('.show-fitment').on('click', function (e) {
        $('.product-fitment').addClass("active");
        e.preventDefault();
    });

    $('.show-fitment-cart').on('click', function () {
        $('#rightToggleMenu').addClass("active");
    });

    $('.m-overlay').click(function () {
        $(".m-modal-fitment").removeClass("active");
    });
    //END flyout transitions jQuery
    
    //handling fmaimages in edge and safari
    if ((navigator.userAgent.toLowerCase().indexOf("safari") != -1 && navigator.userAgent.toLowerCase().indexOf("chrome") == -1) || navigator.userAgent.toLowerCase().indexOf("edg") != -1) {
        //navigator.userAgent.indexOf("MSIE") > -1 ||  navigator.userAgent.indexOf("rv:") > -1
        if ($('html').hasClass("avif")) {
            $("html").removeClass("avif");
        }
    }

    var pageTitle = $("#hdnPageTitle").val();
    var modelSelected = $("#hdnModelSelected").val();
    if ((window.location.pathname == "/" || window.location.pathname.toLowerCase() == "/home" || pageTitle == "Shop Original BMW Parts, Accessories and Apparel") && (modelSelected == undefined || modelSelected=="" )) {
        //home page notification popup should only display if home page and model is not selected
        setTimeout(function () {
            if (!$("#OverlayRight").is((':visible'))) {
                $('.DivNotification').addClass("DivNotificationActive");
                $('.DivoverlayRotate').removeClass("d-none");
            }
        }, 5000);

        setTimeout(function () {
            if ($('.DivNotification').hasClass("DivNotificationActive")) {
                $('.DivNotification').removeClass("DivNotificationActive");
                $('.DivoverlayRotate').addClass("d-none");
            }
        }, 15000);
    }

    if ($("#hdnShowHideDealerPopup").val() != undefined && $("#hdnShowHideDealerPopup").val() != null && $("#hdnShowHideDealerPopup").val().toLowerCase() == "true") {
        if ($("#lnkdealersearch") != undefined && $("#lnkdealersearch") != null)
            $("#lnkdealersearch").click();
    }

});

$(document).on('keydown', function (e) {
    if (e.keyCode === 27) { // ESC
        setTimeout(function () { popupClose(); closeCartFlyout(); }, 100);
    }
});

//Scroll shadow
$('#dealer-locator-results').scroll(function () {
    $('#dealer-locator-results').addClass('Boxshadow');
});
//Owl Carousel Custom
$('#carousel-home').owlCarousel({
    loop: false,
    margin: 15,
    nav: false,
    lazyLoad: false,
    autoplay: false,
    smartSpeed: 400,
    mouseDrag: true,
    responsive: {
        0: {
            items: 2
        },
        576: {
            items: 3
        },
        768: {
            items: 4
        },
        1200: {
            items: 5,
            autoplay: false,
            loop: false,
            mouseDrag: false
        }
    }
});


$('.productRecomCarousel').owlCarousel({
    loop: true,
    margin: 16,
    nav: false,
    lazyLoad: true,
    autoplay: true,
    smartSpeed: 200,
    autoplayTimeout: 3500,
    autoplayHoverPause: true,
    mouseDrag: true,
    responsive: {
        0: {
            items: 2
        },
        576: {
            items: 3
        },
        768: {
            items: 5
        },
        992: {
            items: 5
        },
        1200: {
            items: 6,
            autoplay: false,
            loop: false,
            mouseDrag: false
        }
    }
});

$('.owl-carouselProNav').owlCarousel({
    loop: false,
    margin: 15,
    nav: true,
    lazyLoad: true,
    autoplay: false,
    autoWidth: true,
    smartSpeed: 200,
    autoplayTimeout: 3500,
    autoplayHoverPause: false,
    mouseDrag: true,
    dots: false,
    responsive: {
        0: {
            items: 2,
            autoplay: false,
            loop: false,
            mouseDrag: false
        },
        576: {
            items: 3
        },
        768: {
            items: 4
        },
        1200: {
            items: 5,
            autoplay: false,
            loop: false,
            mouseDrag: true
        }
    }
});

//Alert carousel
$('#alert-carousel').owlCarousel({
    loop: false,
    rewind: true,
    margin: 0,
    nav: true,
    dots: false,
    lazyLoad: false,
    autoplay: false,
    smartSpeed: 600,
    autoWidth: false,
    autoplayTimeout: 7000,
    autoplayHoverPause: true,
    mouseDrag: true,
    items: 1
});

//Alert carousel desktop
$('#alert-carousel-desktop').owlCarousel({
    loop: false,
    rewind: true,
    margin: 0,
    nav: true,
    dots: false,
    lazyLoad: false,
    autoplay: false,
    smartSpeed: 600,
    autoWidth: false,
    autoplayTimeout: 7000,
    autoplayHoverPause: true,
    mouseDrag: true,
    items: 1
});

//Scroll shadow
$('#dealer-locator-results').scroll(function () {

    var ScrollTop = $('#dealer-locator-results').scrollTop().toString();
    if (ScrollTop == "0") {
        $('#dealer-locator-results').removeClass('Boxshadow');
    }
    else
        $('#dealer-locator-results').addClass('Boxshadow');
});
//Fly in Sitemap

$("#mobileSitemap").click(function () {
    $("#helpSectionSitemap").removeClass("flyOutSite");
    $("#helpSectionSitemap").addClass("flyInSite");

});
$("#siteMapClose").click(function () {
    $("#helpSectionSitemap").removeClass("flyInSite");
    $("#helpSectionSitemap").addClass("flyOutSite");
});

function setOverLay() {
    $('.ListNameColor[data-ajax-update="#select-bmw-pop-up-rightId"]').click(function () {
        $('#OverlayRight').css('display', 'block');
        $('body').addClass('body-fixed');
        $('body').css('overflow-y', 'hidden');
        $('html').css('overflow', 'hidden');
    });
    $('.ProductListName[data-ajax-update="#select-bmw-pop-up-rightId"]').click(function () {
        $('#OverlayRight').css('display', 'block');
        $('body').addClass('body-fixed');
        $('body').css('overflow-y', 'hidden');
        $('html').css('overflow', 'hidden');
    });
}

function setColorVisibilityOnMouseOver() {
    $('.colorOpt').find('div').removeClass('SpncolorOpt').addClass('SpncolorOptDNone');
    $('.card').on('mouseover', function () {
        $(this).find('.colorOpt').find('div').removeClass('SpncolorOptDNone').addClass('SpncolorOpt');
        $(this).find('a.carousel-control-next, a.carousel-control-prev').addClass('CatListOpacity');
    });
    $('.card').on('mouseleave', function () {
        $(this).find('.colorOpt').find('.SpncolorOpt').removeClass('SpncolorOpt').addClass('SpncolorOptDNone');
        $(this).find('a.carousel-control-next, a.carousel-control-prev').removeClass('CatListOpacity');
    });
}

var dataFromJsonFile = [];
$.getJSON(window.location.origin + "/JSON/Search.json", function (data) {
    dataFromJsonFile = data.slice();
});

function searchSuggestion() {
    var ex = window.event.keyCode;
    var searchText = $("#txtBxSearch").val();
    if (searchText !== "") {
        $("#txtBxSearch").attr("aria-expanded", true);
        $("#SearchResult").addClass("show");
    }
    else if (ex != 8 && ex != 38 && ex != 40) {
        $("#txtBxSearch").attr("aria-expanded", false);
        $("#SearchResult").removeClass("show");
    }
    var resultArray = [];
    var indexOfExisting = [];
    if (!String.prototype.startsWith) {
        Object.defineProperty(String.prototype, 'startsWith', {
            value: function (search, pos) {
                pos = !pos || pos < 0 ? 0 : +pos;
                return this.substring(pos, pos + search.length) === search;
            }
        });
    }
    if (!String.prototype.includes) {
        String.prototype.includes = function (search, start) {
            'use strict';
            if (typeof start !== 'number') {
                start = 0;
            }

            if (start + search.length > this.length) {
                return false;
            } else {
                return this.indexOf(search, start) !== -1;
            }
        };
    }
    if (window.event.type == "keyup") {
        if (validateSearchBox()) {
            if (window.event.keyCode == 8) {
                $("#SearchResultDiv").empty();
                $("#PopularSearchList").show();
            }
            if (searchText != "" && searchText != "undefined" && searchText != "" && searchText.length > 1) {
                if (dataFromJsonFile.length > 0) {
                    $.each(dataFromJsonFile, function (index, object) {

                        var SearchKey = object.SearchKey;
                        SearchKey = SearchKey.toLowerCase();
                        if (SearchKey.startsWith(searchText.toLowerCase())) {
                            resultArray.push(object);
                            indexOfExisting.push(index);
                        }
                    });

                    $.each(dataFromJsonFile, function (index, object) {
                        var SearchKey = object.SearchKey;
                        var SearchKeyWords = SearchKey.split(' ');
                        var matchFound = false;
                        if (SearchKeyWords.length > 1) {

                            for (var i = 0; i < SearchKeyWords.length; i++) {
                                if (SearchKeyWords[i].toLowerCase().startsWith(searchText.toLowerCase())) {
                                    matchFound = true;
                                    break;
                                }
                            }
                        }
                        if (matchFound) {
                            if (indexOfExisting.indexOf(index) < 0) { resultArray.push(object); }
                        }
                    });
                }
                else {
                    $.getJSON(window.location.origin + "/JSON/Search.json", function (data) { dataFromJsonFile = data.slice(); });
                    searchSuggestion();
                }
            }
            if (resultArray.length > 0) {
                $("#SearchResultDiv").empty();
                var text = "<ul id='SearchResultList' class='es-list-item'>";
                for (var i = 0; i < 10; i++) {
                    if (i > (resultArray.length - 1)) {
                        break;
                    }
                    text += "<li role='application' onkeyup='navigateSearchSuggestion();' aria-label='" + resultArray[i].SearchKey + "' id='SearchResultListItem" + i + "' onkeypress='GetSearchText(\"" + resultArray[i].SearchKey + '","' + resultArray[i].Url + "\")' tabindex='0'>";// <li role="application" aria-label="Floor Mats link" id="list1" onkeypress="SearchItemSelected()" tabindex="0"><a tabindex="-1" id="Floor" >Floor Mats</a></li> 
                    text += "<a tabindex='-1' onclick='GetSearchText(\"" + resultArray[i].SearchKey + '","' + resultArray[i].Url + "\")'>" + resultArray[i].SearchKey + "</a></li>";
                }
                text += "</ul>";
                $("#PopularSearchList").hide();
                $("#SearchResultDiv").append(text);
            }
            else {
                if (searchText != "" && searchText.length > 0) {
                    $("#SearchResultDiv").empty();
                    $("#PopularSearchList").hide();
                    $("#txtBxSearch").attr("aria-expanded", false);
                    $("#SearchResult").removeClass("show");
                }
                else if (searchText == "") {
                    $("#SearchResult").addClass("show");
                    $("#PopularSearchList").show();
                }
            }
        }
        else {
            $("#txtBxSearch").val(searchText);
        }
        navigateSearchSuggestion();
    }
}

function navigateSearchSuggestion() {
    if (window.event.keyCode == 38 || window.event.keyCode == 40) {
        var first = $('#list').children()[0];
        var maininput = $('#txtBxSearch');
        var ln = $("ul.es-list-item > li:visible").length;
        switch (window.event.keyCode) {
            case 38://up arrow

                if (document.activeElement.id == ("txtBxSearch" || first)) {
                    $('ul.es-list-item').children()[ln - 1].childNodes[0].focus();
                    $("#listNo").val(ln - 1);
                    $("#txtBxSearch").val($('ul.es-list-item').children()[ln - 1].childNodes[0].text);
                    window.event.preventDefault();
                }
                else {
                    var m = parseInt($("#listNo").val());
                    if (m == 0) {
                        $("#txtBxSearch").focus();
                        $("#txtBxSearch").val("");
                        window.event.preventDefault();
                        return false;
                    }
                    else {
                        $('ul.es-list-item').children()[m - 1].childNodes[0].focus();
                        $("#listNo").val(m - 1);
                        $("#txtBxSearch").val($('ul.es-list-item').children()[m - 1].childNodes[0].text);
                        window.event.preventDefault();
                    }
                }
                break;
            case 40://down arrow
                if (document.activeElement.id == "txtBxSearch") {
                    if ($('ul.es-list-item').is(':visible')) {
                        $('ul.es-list-item').children()[0].childNodes[0].focus();
                        $("#txtBxSearch").val($('ul.es-list-item').children()[0].childNodes[0].text);
                    }
                }
                else {
                    var m = parseInt($("#listNo").val());
                    if (m == (ln - 1)) {
                        window.event.preventDefault();
                        $("#listNo").val("0");
                        $("#txtBxSearch").focus();
                        $("#txtBxSearch").value = "";
                        return false;

                    }
                    else {

                        $('ul.es-list-item').children()[0].childNodes[0].focus();
                        $("#txtBxSearch").val($('ul.es-list-item').children()[0].childNodes[0].text);

                        if (m >= ln) {

                            return false;
                            window.event.preventDefault();
                        }
                        $('ul.es-list-item').children()[m + 1].childNodes[0].focus();
                        $("#listNo").val(m + 1);
                        $("#txtBxSearch").val($('ul.es-list-item').children()[m + 1].childNodes[0].text);
                        window.event.preventDefault();
                    }
                }
                break;
        }
    }

}
function GetSearchText(searchText, searchUrl) {
    $("#txtBxSearch").val(searchText);
    searchText = searchText.replace(" ", "-").replace(/ +/g, '-');
    searchText = searchText.replace(/[%'_<>!₹π÷×¶∆!=°¢¥€©®™✓~`&:;"?',@#.*+?^/${}()|[\]\\]/g, '-');
    searchText = searchText.replace(" ", "-");
    if (searchUrl == "") {
        window.location.href = '/search/' + searchText;
    }
    else {
        window.location.href = '/' + searchUrl;
    }

    return false;
}

//scroll to top on page load of category list pages
$(window).on('load', function () {
    window.setTimeout(function () {
        $(window).scrollTop(0);
    }, 0);
});

function validateSearchBox(searchText) {
    var keycode = window.event.keyCode;
    var allowedKeyCode = [8, //backspace
        13, //enter
        32, // space
        48, 49, 50, 51, 52, 53, 54, 55, 56, 57, // 0-9 numbers
        65, 66, 67, 68, 69, 70, 71, 72, 73, 74, // A-Z and a-z 
        75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
        85, 86, 87, 88, 89, 90,
        188, // comma
        189, //Hyphen and Underscore
        222  //Apostrophe and Quotes
    ];
    if (allowedKeyCode.indexOf(keycode) > -1) {
        return true;
    }
    else {
        return false;
    }
}


function popupClose() {
    if ($("#divHeaderBodyOverlay").is(':visible')) {
        $('#divHeaderBodyOverlay').css('display', 'none');
        $("#dealerSearch").removeClass('show');
        $("#mobileMenu").removeClass('show');
        $('body').removeClass('body-fixed');
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow-y', 'auto');
    }
    else if ($("#dealerOverlay").is(':visible')) {
        $('#dealerOverlay').css('display', 'none');
        $("#dealerSearch").removeClass('show');
        $("#mobileMenu").removeClass('show');
        $('body').removeClass('body-fixed');
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow-y', 'auto');
        visDealerPopUp();
    }
    else if (!($("#dealerOverlay").is(':visible')) && $("#dealerSearch").hasClass("active")) {
        $('#dealerOverlay').css('display', 'block');
    }
    $("#nav-icon1").removeClass('open');
}


function isDark(color) {
    //var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
    if (color != undefined) {
        var colorValue = color.replace("rgb", "").replace("(", "").replace(")", "").split(",");
        var cVsum = 0.0;
        $.each(colorValue, function (index, object) {
            cVsum += parseFloat(object);
        });
        return cVsum < 3 * 256 / 2; // r+g+b should be less than half of max (3 * 256)
    }
    else return true;
}

//Nav indicator

if (window.matchMedia("(min-width: 360px)").matches) {
    $(function () {
        var menu = $(".TabMainDiv .nav-tabs");
        var indicator = $('<span class="indicator"></span>');
        menu.append(indicator);
        position_indicator(menu.find("a.active"));
        setTimeout(function () { indicator.css("opacity", 1); }, 1000);
        menu.find("a").mouseenter(function () {
            position_indicator($(this));
        });
        menu.find("a").mouseleave(function () {
            position_indicator(menu.find("a.active"));
        });

        function position_indicator(ele) {
            var left = 0;
            var width = 0;
            if (ele.length > 0) {
                left = ele.position().left;
                width = ele.width();
            }

            indicator.stop().animate({
                left: left,
                width: width
            });
        }
    });
}


$('.nav-linka').on('click', function () {
    $('.active-link').removeClass('active-link');
    $(this).addClass('active-link');

});


//wheels and tire secondary nav
//var scrollPaddingFlag = true;
//$('#wtNavSec .nav-linka, #mpMenuwtNavSec .nav-linka').on('click', function () {
//    //debugger;
//    $('.WhScrollPadding').removeClass('WhScrollPadding');
//    var id = $(this).children("a").attr("href"); 
//    $(id).addClass('WhScrollPadding');
//    scrollPaddingFlag = false;

//    setTimeout(function () {
//        scrollPaddingFlag = true;
//    }, 100);
//});


//$(window).scroll(function () {
//    if (scrollPaddingFlag === true)
//        $('.WhScrollPadding').removeClass('WhScrollPadding');
//});

//Mperformance Nav indicator

//if (window.matchMedia("(min-width: 360px)").matches) {
//    $(function () {
//        var menu = $(".PNav .nav-tabs");
//        var indicator = $('<span class="indicator"></span>');
//        menu.append(indicator);
//        position_indicator(menu.find("a.active"));
//        setTimeout(function () { indicator.css("opacity", 1); }, 1000);
//        menu.find("a").mouseenter(function () {
//            position_indicator($(this));
//        });
//        menu.find("a").mouseleave(function () {
//            position_indicator(menu.find("a.active"));
//        });

//        function position_indicator(ele) {
//            var left = 0;
//            var width = 0;
//            if (ele.length > 0) {
//                left = ele.position().left;
//                width = ele.width();
//            }

//            indicator.stop().animate({
//                left: left,
//                width: width
//            });
//        }
//    });
//}

//Sort body click
$(document).on("click", function (e) {
    if ($(e.target).is('[id^=btnSort]') === false && $(e.target).is('[id^=cardHeading2]') === false) {
        setTimeout(function () { $('[id^=description2]').removeClass("show"); }, 100);
        $('[id^=cardHeading2]').removeClass('SortShadow');
    }
});

//To remove all special charater except space from a string
function removeAllSpecialCharater(InputString) {
    return InputString.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, "");
}

function closeCartFlyout() {
    if ($('#cartSummaryOverlay').is(':visible')) {
        $(".cart-summary").removeClass("show");
        $('#cartSummaryOverlay').css('display', 'none');
        $('body').removeClass('body-fixed');
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow-y', 'auto');
        $(".cart-btn").removeClass("active");
    }
}
//Alert mobile
$(window).scroll(function () {
    var scroll = $(window).scrollTop();

    if (scroll > 200) {
        $(".has-alert").removeClass("active");
    } else {
        $(".has-alert").addClass("active");
    }
});

//To prevent html scroll when BS modal is open
$('.modal').on('shown.bs.modal', function () {
    $('html').css('overflow', 'hidden');
}).on('hidden.bs.modal', function () {
    $('html').css('overflow-y', 'auto');
});
$('#SummaryModel').on('shown.bs.modal', function () {
    $('html').css('overflow', 'hidden');
}).on('hidden.bs.modal', function () {
    $('html').css('overflow', '');
});

function closeBlackoutMsg() {
    $.ajax(BMWAjax.lib.request({ method: 'GET', url: BMWAjax.Urls.Home.CloseBlackoutMsg, data: {} }, {
        complete: function () {
            $("#closeBlackout").hide();
            if ($(".MptopSubNav").hasClass("MpFreeshiptopSubNav"))
                $(".MptopSubNav").removeClass("MpFreeshiptopSubNav");
        }
    }));
}

function viewCartSummary() {
    commonGA4Tracking('Navigation', 'View Cart', 'Navigation');
    $("#btnViewCartSummary").click();
  
}
function showCartFlyout() {
    $('#cartSummaryOverlay').css('display', 'block');
    $(".cart-summary").addClass("show");
    $('body').addClass('body-fixed');
    $('body').css('overflow-y', 'hidden');
    $('html').css('overflow', 'hidden');
    $(".cart-btn").addClass("active");
    $(window).scrollTop(0);
    setTimeout(function () { closeCartFlyout(); }, 5000);
}

//navigation
function navigateSecondary(primaryCategoryId) {
    $("#navMain").removeClass('Navbar-fixed').addClass('Navbar-changed');
    $("#navSub" + primaryCategoryId).removeClass('NavSub-changed').addClass('NavSub-fixed');
    $("#navSub" + primaryCategoryId).css('right', '0px');
}
function navigateBackToPrimary(primaryCategoryId) {
    $("#navSub" + primaryCategoryId).removeClass('NavSub-fixed').addClass('NavSub-changed');
    $("#navMain").removeClass('Navbar-changed').addClass('Navbar-fixed');
    $("#navSub" + primaryCategoryId).css('right', '-418px');
}

//mperformance
function navigateMperfomTertiary(primaryCategoryId) {
    //nav dark
    $("#navSub" + primaryCategoryId).removeClass('NavSub-fixed').addClass('NavSub-changed');
    $("#navDark" + primaryCategoryId).removeClass('NavSub-changed').addClass('NavSub-fixed');
    $("#navSub" + primaryCategoryId).css('right', '-418px');
    $("#navDark" + primaryCategoryId).css('right', '0px');
    $(".mobile-menu").addClass('theme-dark');
}
function navigateBacktoMperform(primaryCategoryId) {
    $("#navDark" + primaryCategoryId).removeClass('NavSub-fixed').addClass('NavSub-changed');
    $("#navSub" + primaryCategoryId).removeClass('NavSub-changed').addClass('NavSub-fixed');
    $("#navDark" + primaryCategoryId).css('right', '-418px');
    $("#navSub" + primaryCategoryId).css('right', '0px');
    $(".mobile-menu").removeClass('theme-dark');
}

function navigateBackToSecondary(primaryCategoryId, childCategoryId) {
    $("#navTertiary" + childCategoryId).removeClass('NavSub-fixed').addClass('NavSub-changed');
    $("#navSub" + primaryCategoryId).removeClass('NavSub-changed').addClass('NavSub-fixed');
    $("#navTertiary" + childCategoryId).css('right', '-418px');
    $("#navSub" + primaryCategoryId).css('right', '0px');
}

function navigateTeritiary(primaryCategoryId, childCategoryId) {
    $("#navSub" + primaryCategoryId).removeClass('NavSub-fixed').addClass('NavSub-changed');
    $("#navTertiary" + childCategoryId).removeClass('NavSub-changed').addClass('NavSub-fixed');
    $("#navTertiary" + childCategoryId).css('right', '0px');
    $("#navSub" + primaryCategoryId).css('right', '-418px');
}

$.getJSON('https://api.ipify.org?format=jsonp&callback=?', function (data) {
    $("#HdnCurrentIp").val(data != undefined ? data.ip : "Ip not found");
});
$("#HdnCurrentUrl").val(window.location.href);
$("#HdnCurrentTime").val(new Date());


function validateFeedBackForm() {
    if (window.location.href.toLowerCase().indexOf('/product/') > 0)
        var reCaptchaResponse = grecaptcha.getResponse(1);
    else
        var reCaptchaResponse = grecaptcha.getResponse();
    var result = [];
    $("#feedbackdiv").find("input").removeClass("border-danger");
    $("#feedbackdiv").find("textarea").removeClass("border-danger");
    if ($("#txtFeedBackName").val() == "") {
        $("#txtFeedBackName").addClass("border-danger");
        result.push(false);
    }
    if ($("#txtFeedBackEmail").val() == "") {
        $("#txtFeedBackEmail").addClass("border-danger");
        result.push(false);
    }
    if (!validateEmail($("#txtFeedBackEmail").val())) {
        $("#txtFeedBackEmail").addClass("border-danger");
        result.push(false);
    }
    if ($("#txtFeedBackSubject").val() == "") {
        $("#txtFeedBackSubject").addClass("border-danger");
        result.push(false);
    }
    if ($("#txtFeedBackmessage").val() == "") {
        $("#txtFeedBackmessage").addClass("border-danger");
        result.push(false);
    }
    if (result.indexOf(false) > -1) return false;
    if (reCaptchaResponse == "") { FeedBackSubmitSuccess("CloseForm"); }
    return true;
}

function validatePreOrderWaitingForm() {
    var result = true;
    if (!$("#divSuccess").hasClass("d-none"))
        $("#divSuccess").addClass("d-none");
    $("#orderWaitingdiv").find("input").removeClass("border-danger");
    if ($("#txtWlistFirstName").val() == "") {
        $('#txtWlistFirstName').removeClass("RightInput");
        $('#txtWlistFirstName').addClass("InvalidSearch");
        $('#spanWlistFirstName').removeClass("d-none");
        result = false;
    }
    else {
        $('#txtWlistFirstName').removeClass("InvalidSearch");
        $('#txtWlistFirstName').addClass("RightInput");
        $('#spanWlistFirstName').addClass("d-none");
    }
    if ($("#txtWlistLastName").val() == "") {
        $('#txtWlistLastName').removeClass("RightInput");
        $('#txtWlistLastName').addClass("InvalidSearch");
        $('#spanWlistLastName').removeClass("d-none");
        result = false;
    }
    else {
        $('#txtWlistLastName').removeClass("InvalidSearch");
        $('#txtWlistLastName').addClass("RightInput");
        $('#spanWlistLastName').addClass("d-none");
    }
    if (!validateEmail($("#txtWlistEmail").val())) {
        $('#txtWlistEmail').removeClass("RightInput");
        $('#txtWlistEmail').addClass("InvalidSearch");
        $('#spanWlistEmail').removeClass("d-none");
        result = false;
    }
    else {
        $('#txtWlistEmail').removeClass("InvalidSearch");
        $('#txtWlistEmail').addClass("RightInput");
        $('#spanWlistEmail').addClass("d-none");
    }
    if ($("#txtWlistZipCode").val() == "" || $("#txtWlistZipCode").val().length != 5) {
        $('#txtWlistZipCode').removeClass("RightInput");
        $('#txtWlistZipCode').addClass("InvalidSearch");
        $('#spanWlistZipCode').removeClass("d-none");
        result = false;
    }
    else {
        $('#txtWlistZipCode').removeClass("InvalidSearch");
        $('#txtWlistZipCode').addClass("RightInput");
        $('#spanWlistZipCode').addClass("d-none");
    }
    if (validateLeadCheck("customWlistCheck"))
        result = false;
    return result;
}
function validateLeadCheck(id) {
    const $label = $('#' + id).siblings('label');
    if ($('#' + id).prop("checked") != true) {
        $label.addClass('ChkPrivary');
        $("#" + id).closest("div").addClass("terms-validation");
        return true;//error
    }
    else {
        $label.removeClass('ChkPrivary');
        $("#" + id).closest("div").removeClass("terms-validation");
        return false; //no error
    }
}
function orderWaitingSubmitSuccess(context) {
    $("#orderWaitingdiv").find("input").removeClass("border-danger");
    $("#txtWlistFirstName").val("");
    $("#txtWlistLastName").val("");
    $("#txtWlistEmail").val("");
    $("#txtWlistZipCode").val("");
    $("#customWlistCheck").prop("checked", false);
    $("#divSuccess").removeClass("d-none");
    $("#divWaitingList").addClass("d-none");
    $("#orderWaitingdiv").find("input").removeClass("RightInput");
    //var scrollValue = $(window).scrollTop();
    var scrollValue = $("#divSuccess").parent().offset().top;
    $(window).scrollTop(scrollValue);
}

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}
function validateRequiredFields(control, controlType) {
    var data = $('#' + control).val();
    regex = /^\s+|\s+$/g;
    data = data.replace(regex, "");
    $('#' + control).val(data);
    var spanId = control.replace(controlType, "span");
    if (data.toString() == "") {
        errorFlag = true;
        $('#' + control).removeClass("RightInput");
        $('#' + control).addClass("InvalidSearch");
        $('#' + spanId).removeClass("d-none");
    }
    else {
        $('#' + control).removeClass("InvalidSearch");
        $('#' + control).addClass("RightInput");
        $('#' + spanId).addClass("d-none");
        if (control.toLowerCase().indexOf("phone") >= 0) {
            var phoneNumber = $('#' + control).val().replace(/\-/g, '');
            var strDigits = stripCharsNotInBag(phoneNumber, "1234567890");
            if (strDigits.length == 10) {
                var formatPhoneNumber = $('#' + control).val();
                //formatPhoneNumber = "("+ strDigits.substring(0, 3) + ")" + strDigits.substring(3, 6) + "-" + strDigits.substring(6, 10);
                $('#' + control).val(formatPhoneNumber);
                $('#' + control).removeClass("InvalidSearch");
                $('#' + control).addClass("RightInput");
            }
            else {
                errorFlag = true;
                $('#' + control).removeClass("RightInput");
                $('#' + control).addClass("InvalidSearch");
            }
        }
        if (control.toLowerCase().indexOf("zipcode") >= 0) {
            var zipcode = $('#' + control).val();
            if (!validateZipCode(zipcode)) {
                //if (zipcode.length != 5) {
                errorFlag = true;
                $('#' + control).addClass("InvalidSearch");
                $('#' + control).removeClass("RightInput");
                //}
            }
        }
        if (control.toLowerCase().indexOf("email") >= 0) {
            var email = $('#' + control).val();
            if (!validateEmail(email)) {
                errorFlag = true;
                $('#' + control).addClass("InvalidSearch");
                $('#' + control).removeClass("RightInput");
            }
        }
        if (control.toLowerCase().indexOf("expdate") >= 0) {
            if (!validateExpiryDate()) {
                $('#' + control).addClass("InvalidSearch");
                $('#' + control).removeClass("RightInput");
            }
        }
        if (control.toLowerCase().indexOf("seccode") >= 0) {
            var seccode = $('#' + control).val();
            if (!validateCVV(seccode)) {
                errorFlag = true;
                $('#' + control).addClass("InvalidSearch");
                $('#' + control).removeClass("RightInput");
            }
        }
    }
}
function onChangeFeedBackForm() {
    $("#" + window.event.target.id).removeClass("border-danger");
}

function FeedBackSubmitSuccess(context) {
    var classname = $("#myModal12")[0].className;
    var thankyoumsg = $("#divMessageReport")[0].className;
    if (context == "Success") {
        $("#myModal12").removeClass("d-block");
        $("#divMessageReport").addClass("d-block");
    }
    else if (context == "Failed") { FeedBackSubmitSuccess("Success"); }
    if (context == "ShowForm" || context == "CloseForm") {
        if (classname.indexOf("d-block") == -1) {
            $('html').css('overflow', 'hidden');  //ADD THIS
            $("#myModal12").addClass("d-block");
        }
        else {
            $('html').css('overflow-y', 'auto');  //ADD THIS
            $("#myModal12").removeClass("d-block");
        }
        if (context == "ShowForm") {
            var scripts = document.getElementsByTagName('script');
            var scriptExist = false;
            for (var i = scripts.length; i--;) {
                if (scripts[i].src == "https://www.google.com/recaptcha/api.js")
                    scriptExist = true;
            }
            if (!scriptExist) {
                var script = document.createElement("script");
                script.src = "https://www.google.com/recaptcha/api.js";
                script.async = true;
                script.defer = true;
                document.getElementsByTagName("head")[0].appendChild(script);
            }
        }
        if (!($("#feedBackSubmitButton")[0].hasAttribute("disabled")))
            $('#feedBackSubmitButton').prop('disabled', true);
    }
    else {
        if (thankyoumsg.indexOf("d-block") == -1) {
            $('html').css('overflow', 'hidden');  //ADD THIS
            $("#divMessageReport").addClass("d-block");
        }
        else {
            $('html').css('overflow-y', 'Auto');  //ADD THIS
            $("#divMessageReport").removeClass("d-block");
        }
    }
    $("#feedbackdiv").find("input").removeClass("border-danger");
    $("#feedbackdiv").find("textarea").removeClass("border-danger");
    $("#txtFeedBackName").val("");
    $("#txtFeedBackEmail").val("");
    $("#txtFeedBackSubject").val("");
    $("#txtFeedBackmessage").val("");
    if (typeof grecaptcha != 'undefined' && grecaptcha != null) {
        if (window.location.href.toLowerCase().indexOf('/product/') > 0) {
            if (grecaptcha.getResponse != undefined && grecaptcha.getResponse(1).length != 0)
                grecaptcha.reset(1);
        }
        else {
            if (grecaptcha.getResponse != undefined && grecaptcha.getResponse().length != 0)
                grecaptcha.reset();
        }
    }
    $("#HdnCaptcha").val("Failed");
}

var resetCaptcha = function () {
    if (window.location.href.toLowerCase().indexOf('/product/') > 0)
        var reCaptchaResponse = grecaptcha.getResponse(1);
    else
        var reCaptchaResponse = grecaptcha.getResponse();
    if (reCaptchaResponse != "") {
        if ($("#feedBackSubmitButton")[0].hasAttribute("disabled")) $("#feedBackSubmitButton").removeAttr("disabled");
        $("#HdnCaptcha").val("Success");
    }
    else {
        if (!($("#feedBackSubmitButton")[0].hasAttribute("disabled"))) $("#feedBackSubmitButton").attr("disabled");
        $("#HdnCaptcha").val("Failed");
    }
}

function voucherPageLink() {
    window.location = "/Help/VoucherPage";
}
function emptySearch() {
    var searchItem = $('#txtBxSearch').val();
    if (searchItem.trim() == "")
        return false;
    else
        return true;
}
function scrollHandler() {
    if ($('#hdnNumOfPages').length > 0) {//scrollHandler works in ProductList page only
        numberOfPages = parseInt($('#hdnNumOfPages').val());
        var nextPage = page + 1;
        if (numberOfPages == 0 || (numberOfPages == nextPage))
            isReachedScrollEnd = true;

        var sbHeight = window.innerHeight * (window.innerHeight / document.body.offsetHeight);
        var scrollBottom = $(document).height() - ($(document).scrollTop() + sbHeight);

        if (!isReachedScrollEnd &&
            ($(document).scrollTop() > scrollBottom)) {
            //($(window).scrollTop() > $(document).height() / 3)) {
            var url = window.location.pathname;
            loadMoreProducts(url);
        }
    }
    //else {//For review page floating button in mobile screen
    //    checkOffset();
    //}
}

$(window).scroll(function (event) {
    var st = $(this).scrollTop();
    var pathname = window.location.pathname.toLowerCase();
    if (st > 29 && st > lastScrollTop) {
        if (pathname.indexOf("/m-performance/overview") > -1) {
            $(".MptopSubNav").addClass("Ptitlefixed");
            $("#app").addClass("mpactive");
            //$(".PBrowsebtn").addClass("Pbuttonfixed ");
        }
        // downscroll code 
        scrollHandler();
    }
    else {
        if (pathname.indexOf("/m-performance/overview") > -1) {
            $(".MptopSubNav").removeClass("Ptitlefixed");
            $("#app").removeClass("mpactive");
            //$(".PBrowsebtn").removeClass("Pbuttonfixed ");
        }
    }

    if (st < 30 && pathname != '/wheels-and-tires/overview') {// page top checking
        $(".MptopSubNav").removeClass("mppHeaderBorder");
    }
    else {
        if (!$(".MptopSubNav").hasClass("mppHeaderBorder"))
            $(".MptopSubNav").addClass("mppHeaderBorder");
    }
    //upscroll code 
    //checkOffset();
    lastScrollTop = st;
});

$(window).scroll(function () {
    var pathname = window.location.pathname.toLowerCase();
    var isMobile = false;
    var isIpad = false;
    if (navigator.userAgent.toLowerCase().indexOf("mobile") > -1 && navigator.userAgent.toLowerCase().indexOf("ipad") < 0) {
        isMobile = true;
    }
    else if (navigator.userAgent.toLowerCase().indexOf("ipad") > -1) {
        isIpad = true;
    }
    if ($(this).scrollTop() > 50) {
        $("#app").addClass("mpactive");
        $(".MptopSubNav").addClass("Ptitlefixed");
    }
    else {
        $("#app").removeClass("mpactive");
        $(".MptopSubNav").removeClass("Ptitlefixed");
    }

    if (pathname.indexOf("/wheels-and-tires/overview") > -1) {
        var modelName = "";
        modelName = $("#hdnModelName").val();
        var ifModelSelected = false;
        if (modelName != "" && modelName != undefined) {
            ifModelSelected = true;
        }
        var heightWindow;
        var clientHeight = 0;
        if (!ifModelSelected) {
            clientHeight = $("#modelSelection").outerHeight() + $("#overview").outerHeight();
        }
        else {
            clientHeight = $("#WhMainSec").outerHeight();
        }

        if (isMobile) {
            if (!ifModelSelected) {
                heightWindow = $('#WhMainSec').outerHeight() + $("#overview").outerHeight();
                //heightWindow = $('#WhMainSec').height();
                heightWindow = (heightWindow / 2) - 150;
            }
            else {
                heightWindow = clientHeight;//- 100
            }
        }
        else if (isIpad) {
            if (!ifModelSelected) {
                //heightWindow = $('#WhMainSec').outerHeight() + $("#overview").outerHeight();
                heightWindow = $('#WhMainSec').outerHeight();
                heightWindow = heightWindow - 100;
                //heightWindow = (heightWindow / 2) - 100;
            }
            else {
                heightWindow = clientHeight - 100;
            }
        }
        else {
            if (!ifModelSelected) {
                heightWindow = (clientHeight / 2) + 100;
            }
            else {
                heightWindow = (clientHeight / 2) + 100;
            }
        }
        if ($(this).scrollTop() > heightWindow) {
            //console.log($(this).scrollTop())
            $("#wheelsJumbingBar").removeClass("PNavActive");
        }

        else if (!$("#wheelsJumbingBar").hasClass("PNavActive")) {
            $("#wheelsJumbingBar").addClass("PNavActive")
        }
    }
});

function loadMoreProducts(loadMoreRowsUrl) {
    if (page > -1 && !inCallback) {
        inCallback = true;
        page++;
        var args = { pageNum: page, sortField: $('#hdnSortField').val(), isMPPRedirect: $('#hdnIsMPPRedirect').val() };
        $('#loader').removeClass('d-none').addClass('d-block');
        $.ajax(BMWAjax.lib.request({ method: 'POST', url: loadMoreRowsUrl, data: args }, {
            complete: function (json) {
                if (json.responseJSON !== null && json.responseJSON !== '') {
                    $("div.divProductsList").append(json.responseJSON);
                    setOverLay();
                    setColorVisibilityOnMouseOver();
                }
                else {
                    page--;
                }
                inCallback = false;
                $('#loader').removeClass('d-block').addClass('d-none');
            }
        }));
    }
}

$("#divHeaderBodyOverlay").click(function () {
    if ($('[id^=navSub]').css('right', '-1px')) {
        $('[id^=navSub]').css('right', '-418px');
    }
    if ($('[id^=navTertiary]').css('right', '-1px')) {
        $('[id^=navTertiary]').css('right', '-418px');
    }
    if ($('[id^=navDark]').css('right', '-1px')) {
        $('[id^=navDark]').css('right', '-418px');
        $(".mobile-menu").removeClass('theme-dark');
    }

});

// Custom modal backdrop
$('.modal-custom').on('show.bs.modal', function (e) {
    setTimeout(function () {
        $('.modal-backdrop').addClass('modal-backdrop-custom');
    });
});

//Cart Promo section
function showPromoAdd() {
    $("#divIdPromo").removeClass('d-none').addClass('d-flex');
}
function cancelPromoAdd() {
    $("#divIdPromo").removeClass('d-flex').addClass('d-none');
    $("#promoErrMsg").removeClass('d-block').addClass('d-none');
    $("#promoCode").removeClass("InvalidSearch");

    //update promo msg and removed promocode
    $.ajax({
        type: "POST",
        url: "/Cart/CancelPromo",
        // data: ,
        contentType: 'application/x-www-form-urlencoded',
        //datatype: "html",
        success: function (data) {
            if (data.msg == true) {
                $("#promoCode").val("");
            }
        },
        error: function () {
            alert("Error occured!!")
        }
    });
}

//Review page dynamic height 
$('.ReviewContainer').each(function () {
    $(this).css('min-height', $('.DivLgPosition', this).outerHeight() + 100);
});

//product detail carousel height for align video vertically center
$(window).resize(function () {
    var cw = $('.productImageControl .calc-height').width();
    $('.calc-height .carousel-item').css({
        'height': cw + 'px'
    });
});

//promo loader
function addPromoCode() {
    addSubmitSpinner("btnPromoApply");
}

//preview bar body scolling
$('.preview-bar .content-right a').click(function () {
    $('body').css('overflow-y', 'hidden');
    $('html').css('overflow-y', 'hidden');
});
$('.pre-popup-header button, .pre-popup-footer button').click(function () {
    $('body').css('overflow-y', 'auto');
    $('html').css('overflow-y', 'auto');
});

$("#seeCategories").click(function () {
    $("#previewCategory").removeClass("d-none");
});

$("#seeFitmentItems").click(function () {
    $("#previewFitmentItem").removeClass("d-none");
});

function previewPopUpClose(id) {
    $("#" + id).addClass('d-none');
}
function previewLoginSuccess() {
    $("#preview").removeClass("show").addClass("d-none");
    $("#preview-msg").addClass("d-none").removeClass("d-block");
}
function previewLoginFailure() {
    $("#preview-msg").removeClass("d-none").addClass("d-block").text("Username Or Password Is Incorrect..!");
}


$(window).ready(function () {
    $('#dealernamepop').focus();
    setTimeout(function () {
        $('.DivDealerPopIcon').addClass("fadeIcon");
    }, 2000);

});

$(".DealerCheckicon").click(function () {
    $(".DivDealerPopIcon").removeClass("fadeIcon");

    var params = {};
    $.ajax(BMWAjax.lib.request({
        method: 'POST',
        url: BMWAjax.Urls.DealerLocator.DealerPopIcon,
        data: params
    }, {
            complete: function (json) {
            }
        }));
    $('.DealerCheckicon').addClass('todealerselect');
});

$(".DealerEditicon").click(function () {

    $('.DivDealerPopIcon').removeClass("fadeIcon");
    $('#dealerOverlay').css('display', 'block');
    $('body').addClass('body-fixed');
    $('body').css('overflow-y', 'hidden');
    $('html').css('overflow-y', 'hidden');
    $('.DealerEditicon').addClass('todealerselect');
});
$(".dealer-overlayedit").click(function () {
    $(".mobile-menu-dealer-search").removeClass('show');
    $('body').removeClass('body-fixed');
    $('body').css('overflow-y', 'none');
    $('html').css('overflow-y', 'none');
});

//for ADA
function applyKeypress(e, obj) {
    e = e || window.event;
    var keynum = 0;
    if (window.event) // IE
    {
        keynum = e.keyCode
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which
    }
    var isEnterPressed = (e.key === 'Enter' || keynum === 13); /*|| keynum === 32 || e.key === 'space'*/
    if (!isEnterPressed) {
        return;
    }
    else {
        if (obj == "dealerClosepopup") {
            document.getElementById(obj).click();
            if ($("#mobileMenu").hasClass('active')) {
                $("#categoryMenuFooter").find('a').eq(0).focus();
            }
            else {
                $("#cartBtn").focus();
            }
            e.preventDefault();
            e.stopPropagation();
        }
    }
}

function focusPopup(e, idValue) {
    var keyValue = e.keyCode;
    if (keyValue == 9) {
        if (idValue == "divOthersAlsoBought") {
            var isMotorsports = $("#hdnIsMotorSport").val().toLowerCase();
            if (isMotorsports == "false") {
                $("#" + idValue).find('h2:first').focus();
                event.preventDefault();
            }
            else {
                return null;
            }
        }
        else if (idValue == "preOrderBtn") {
            var pageTitle = $("#hdnPageTitle").val();
            if (pageTitle == "Pre-Order") {
                $("#" + idValue).focus();
            }
            else if (pageTitle == "Cart") {
                $('.DivCartProDetails').find('h1:first').focus();
            }
            else if (pageTitle == "Checkout") {
                $("#divContactInfo").find('h2:first').focus();
            }
            else if (pageTitle == "Review") {
                $('.SecReview').find('h1:first').focus();
            }
            else if (pageTitle == "OrderSummary") {
                $('.DivCongr').find('h1:first').focus();
            }
        }
        else if (idValue == 'logo-link') {
            $(".logo-link").find('a:first').focus();
        }
        else if (idValue == 'JKReturnToGallery' || idValue == 'btn_reserve' || idValue == 'JKSignUpNow') {
            $('#dealerLocated').focus();
        }
        else if (idValue == 'JKconfirmReservation') {
            if ($('.JKConfirmPopup').hasClass("d-none")) {
                $('#dealerLocated').focus();
            } else {
                $("#hedJKConfirmReservation").focus();
            }
        }
        else if (idValue == 'JKConfirmPopupCancel') {
            $("#hedJKConfirmReservation").focus();
        }
        else if (idValue == 'paypalTermsCondtnText') {
            if ($('#DivTermsCondtnPop').hasClass("AddDivQuesPop")) {
                $('.QuesContentHgt').find('h1:first').focus();
            } else {
                $("#JKconfirmReservation").focus();
            }
        }
        else if (idValue == 'JKTermsFooter' || idValue == 'i7TermsFooter') {
            $(".BtnTermsCondtnPopClose").focus();
        }
        else if (idValue == 'BtnTermsCondtnPopClose') {
            $('.QuesContentHgt').find('h1:first').focus();
        }
        else if (idValue == 'btn_i7preordernow') {
            $('#SecOfferDetails').focus();
        }
        else if (idValue == 'SecOfferDetails') {
            if ($('#DivPaymentPop').hasClass("AddDivpayPop")) {
                $("#hedFinanceOptions").focus();
            } else {
                $('#DivOfferfaq').focus();
            }
        }
        else if (idValue == 'i7PaymentPopEnd') {
            $(".BtnQuesPopClose1").focus();
        }
        else if (idValue == 'BtnQuesPopClose1') {
            $("#hedFinanceOptions").focus();
        }
        else if (idValue == 'DivOfferfaq' || idValue == 'iFeatureEndSecfaq') {
            if ($('#DivQuesPop').hasClass("AddDivQuesPop")) {
                $("#hedFaq").focus();
            } else {
                $('#dealerLocated').focus();
            }
        }
        else if (idValue == 'i7FaqEnd') {
            $(".BtnQuesPopClose").focus();
        }
        else if (idValue == 'BtnQuesPopClose') {
            $("#hedFaq").focus();
        }
        else if (idValue == 'payWithAmazonDiv') {
            $("#SecOfferDetails").focus();
        }
        else if (idValue == 'btni7CardPlaceOrder' || idValue == 'btni7AmazonPlaceOrder' || idValue == 'btni7PaypalPlaceOrder') {
            $("#SecOfferDetails").focus();
        }
        else if (idValue == 'i7termsCondtnText') {
            if ($('#DivTermsCondtnPop').hasClass("AddDivQuesPop")) {
                $('#hedTermsAndConditions').focus();
            } else {
                $("#btni7CardPlaceOrder").focus();
            }
        }
        else if (idValue == 'i7amazonTermsCondtnText') {
            if ($('#DivTermsCondtnPop').hasClass("AddDivQuesPop")) {
                $('#hedTermsAndConditions').focus();
            } else {
                $("#btni7AmazonPlaceOrder").focus();
            }
        }
        else if (idValue == 'i7paypalTermsCondtnText') {
            if ($('#DivTermsCondtnPop').hasClass("AddDivQuesPop")) {
                $('#hedTermsAndConditions').focus();
            } else {
                $("#btni7PaypalPlaceOrder").focus();
            }
        }
        else if (idValue == 'Btni7TermsCondtnPopClose') {
            $('#hedTermsAndConditions').focus();
        }
        else if (idValue == 'OfferDet') {
            if ($('#DivPaymentPop').hasClass("AddDivpayPop")) {
                $("#hedFinanceOptions").focus();
            } else {
                $("#divLeasingstarts").focus();
            }
        }
        else if (idValue == 'OfferLease') {
            if ($('#DivPaymentPop').hasClass("AddDivpayPop")) {
                $("#hedFinanceOptions").focus();
            } else {
                $("#divPaymentOption").focus();
            }
        }
        else if (idValue == 'aLearnMoreFinance') {
            if ($('#DivPaymentPop').hasClass("AddDivpayPop")) {
                $("#hedFinanceOptions").focus();
            } else {
                $("#divDueToday").focus();
            }
        }
        else if (idValue == 'madeMatchWheels') {
            if (window.location.href.toUpperCase().indexOf('/WHEELS-AND-TIRES/OVERVIEW') > 0) {
                if ($('#WhModelH').hasClass("d-none")) {
                    $("#shopWheelsModel").find('h3:first').focus();
                }
                else {
                    $("#madeMatchWheels").find('h1:first').focus();
                }
            }
        }
        else if (idValue == 'relatedWheels') {
            $("#relatedWheels").find('a:first').focus();
        }
        else if (idValue == 'dealerSearchQueryEvent') {
            $("#dealerSearchQueryResult .dropdown-menu").find('a:first').focus();
        }
        else {
            $("#" + idValue).focus();
        }
        e.preventDefault();
    }
    if (keyValue == 13) {
        if (idValue == 'JKconfirmReservation') {
            $("#hedJKConfirmReservation").focus();
        }
        else if (idValue == 'JKConfirmPopupCancel') {
            $('.JKConfirmPopup').addClass("d-none");
            $('#dealerLocated').focus();
        }
        else if (idValue == 'BtnTermsCondtnPopClose') {
            $('#DivTermsCondtnPop').removeClass("AddDivQuesPop");
            $('.DivQuesPopoverlay').removeClass("d-block");
            $("#JKconfirmReservation").focus();
        }
        else if (idValue == 'thanksNoti') {
            notifiedProductClose();
        }
        else if (idValue == 'SecOfferDetails' || idValue == 'aLearnMoreFinance') {
            $('#DivPaymentPop').addClass("AddDivpayPop");
            $('.DivQuesPopoverlay').addClass("d-block");
            $("#hedFinanceOptions").focus();
        } else if (idValue == 'OfferDet') {
            $('#DivPaymentPop').addClass("AddDivpayPop");
            $('.DivQuesPopoverlay').addClass("d-block");
            $("#PaymentOpt2").click();
            $("#hedFinanceOptions").focus();
        } else if (idValue == 'OfferLease') {
            $('#DivPaymentPop').addClass("AddDivpayPop");
            $('.DivQuesPopoverlay').addClass("d-block");
            $("#PaymentOpt3").click();
            $("#hedFinanceOptions").focus();
        }
        else if (idValue == 'BtnQuesPopClose1') {
            $('#DivPaymentPop').removeClass("AddDivpayPop");
            $('.DivQuesPopoverlay').removeClass("d-block");
            $("#DivOfferfaq").focus();
        } else if (idValue == 'DivOfferfaq') {
            $('#DivQuesPop').addClass("AddDivQuesPop");
            $('.DivQuesPopoverlay').addClass("d-block");
            $("#hedFaq").focus();
        } else if (idValue == 'BtnQuesPopClose') {
            $('#DivQuesPop').removeClass("AddDivQuesPop");
            $('.DivQuesPopoverlay').removeClass("d-block");
            $("#dealerLocated").focus();
        } else if (idValue == 'iFeatureEndSecfaq') {
            $('#DivQuesPop').addClass("AddDivQuesPop");
            $('.DivQuesPopoverlay').addClass("d-block");
            $("#hedFaq").focus();
        } else if (idValue == 'i7termsCondtnText' || idValue == 'i7amazonTermsCondtnText' || idValue == 'i7paypalTermsCondtnText') {
            $('#DivTermsCondtnPop').addClass("AddDivQuesPop");
            $('.DivQuesPopoverlay').addClass("d-block");
            $('#hedTermsAndConditions').focus();
        } else if (idValue == 'Btni7TermsCondtnPopClose') {
            $('#DivTermsCondtnPop').removeClass("AddDivQuesPop");
            $('.DivQuesPopoverlay').removeClass("d-block");
            $(".placebtn").focus();
        }
    }
}
function setAlertClose() {
    $.ajax(BMWAjax.lib.request({ method: 'GET', url: BMWAjax.Urls.Home.SetAlertClose, data: {} }, {
        complete: function () {
            $("#AlertModalHome").modal("hide");
            //refocusingtoHome();
        }
    }));
}

//for dealer widget start
function focusWidgetedit(e) {
    if ($('.DealerEditicon').hasClass('todealerselect')) {
        $('#flyoutDealer').focus();
        e.preventDefault();
    }
    else {
        $('#dealernamepop').focus();
        e.preventDefault();
    }
}
function focusWidgetTick(e) {
    if ($('.DealerCheckicon').hasClass('todealerselect')) {
        $('.logoMainDiv').focus();
        e.preventDefault();
    }
    else {
        $('.DealerEditicon').focus();
        e.preventDefault();
    }
}
//for dealer widget end

//tabbing in flyout when dealer is not selected
function dealerFlyout(e) {
    var keyValue = e.keyCode;
    if (keyValue == 9) {
        if (!($('#dealer_result').is(":visible") || $('#dealer_noresult').is(":visible") || $('.dealer').is(":visible"))) {
            focusPopup(event, 'flyoutDealer');
        }
    }
}

//MotorSports
$(document).ready(function () {
    $('#MotorSptPwd').on('keyup keypress', function (e) {
        var keyCode = e.keyCode || e.which;
        if (keyCode === 13) {
            e.preventDefault();
            //return false; 
            validateMotorspotLogin();
        }
    });
    $('#divMotorSportsTrackList .motorsports-dealer-div').on('click', function () {
        $('#hdnTrackId').val($(this).data('id'));
    });
    $('#divEditMotorSportsTrackList .motorsports-dealer-div').on('click', function () {
        $('#divEditMotorSportsTrackList .hdnEditTrackId').val($(this).data('id'));
    });
    if (document.getElementById("HdnIsMotorsport")) {
        SetWebPageTimer();
    }
    if ($("#hdnIsAlertEnabledForMotorsport") != undefined && $("#hdnIsAlertEnabledForMotorsport").val() != undefined && $("#hdnIsAlertEnabledForMotorsport").val().toLowerCase() == "true") {
        $("#AlertModalHomeForMs").modal("show");
    }
});
function validateMotorspotLogin() {
    var password = $("#MotorSptPwd").val();
    if (password == "") {
        $("#motorSportsValidationMsg").removeClass("d-none");
        $("#motorSportsValidationMsg li").html("Password is required.");
        return false;
    }
    var args = { UserName: "MotorSportsUser", Password: password };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.Motorsports.ValidateUser, data: args }, {
        complete: function (json) {
            var result = json.responseJSON;
            if (result == "True") {
                //show track list 
                //$('body').addClass('body-fixed');
                //$('body').css('overflow-y', 'hidden');
                $("#motorSportsValidationMsg").addClass("d-none");
                //$("#divMotorSportTrackList").removeClass("d-none"); 
                $("#btnLoginSubmit").click();
                return true;
            }
            else {
                //Invalid 
                $("#motorSportsValidationMsg").removeClass("d-none");
                //$("#divMotorSportTrackList").addClass("d-none"); 
                $("#motorSportsValidationMsg li").html("Invalid Password.");
                return false;
            }
        }
    }));
}
$('#divMotorSportsTrackList .Divdealer').click(function () {
    $('.DivMotorBtn').show();
    // $('#btnSetDealer').show(); 
    $('#divMotorSportsTrackList .Divdealer').each(function (index) {
        $(this).removeClass('MtrActive');
    });
    $(this).addClass('MtrActive');
});
$('#divEditMotorSportsTrackList .Divdealer').click(function () {
    $('.DivMotorBtn').show();
    //$('#btnEditSetDealer').show();
    $('#divEditMotorSportsTrackList .Divdealer').each(function (index) {
        $(this).removeClass('MtrActive');
    });
    $(this).addClass('MtrActive');
    //$("#btnEditSetDealer").attr('tabindex','0');
});
function validatemotorSportTrack() {
    if ($("#hdnTrackId").val() == "0" || $("#hdnTrackId").val() == "") {
        event.preventDefault();
    }
}
function showEditTrackEventPage() {
    $('body').addClass('body-fixed');
    $('body').css('overflow-y', 'hidden');
    $("#divEditMotorSportTrackList").removeClass("d-none");
    var pageTitle = $("#hdnPageTitle").val();
    if (pageTitle != "Track Select") {
        $("#hdnPageTitle").val("Track Select");
    }
}

//model selectionpopup  - ADA
function modelFlyout(e, sideValue) {
    //flyout is opened 
    if (sideValue == '1' && $("#rightToggleMenu").hasClass('active')) { // for rightside //$("#rightToggleMenu").hasClass('show')
        modelFlyEvent(e);
    }
    else if (sideValue == '0' && (($("#selectBmw").is(":visible") && $("#fitment-widget_t").hasClass('NavSub-fixed')) || $("#yourBmw").is(":visible"))) { //for leftside
        modelFlyEvent(e);
    }
}

function modelFlyEvent(event) {
    var keyValue = event.keyCode;
    var modelValue = $('#hdnModelName').val();
    var url = window.location.href.toLowerCase();
    if (keyValue == 9) {
        if ((modelValue != null) && (modelValue != "")) {
            focusPopup(event, 'yourBmw');
        }
        else if (((modelValue == null) || (modelValue == "")) && $('#NoShopimg').hasClass('d-none')) {
            focusPopup(event, 'selectBmw');
        }
        else if (((modelValue == null) || (modelValue == "")) && !$('#NoShopimg').hasClass('d-none')) {
            focusPopup(event, 'NoShopimg');
        }
    }
}

//left side menu navigation
function menuNavigation(e, mainIdValue, idValue) {
    var keyValue = e.keyCode;
    if (mainIdValue == "navMain") {
        if (keyValue == 9 && $("#" + mainIdValue).hasClass('Navbar-changed')) {
            $("#" + idValue).find('a:first').focus();
            e.preventDefault();
        }
    }
    else {
        if (keyValue == 9 && $("#" + mainIdValue).find('a:last').is(":focus")) {
            if (keyValue == 9 && $("#" + mainIdValue).hasClass('NavSub-changed')) {
                $("#" + idValue).find('a:first').focus();
                e.preventDefault();
            }
            else {
                $("#" + mainIdValue).find('a:first').focus();
                e.preventDefault();
            }
        }
        else if (keyValue == 9 && ($("#" + mainIdValue).hasClass('NavSub-changed') || $("#" + idValue).hasClass('NavSub-fixed'))) {
            $("#" + idValue).find('a:first').focus();
            e.preventDefault();
        }
    }
}
function backNavigation(event, idValue) { //tertiary popup inside navigation
    var keyValue = event.keyCode;
    if ((keyValue == 9) && $("#" + idValue).find('a:last').is(":focus")) {
        $("#" + idValue).find('a:first').focus();
        event.preventDefault();
    }
}

function footerMenu(event, idValue) {
    if (idValue == "heading-8") {//heading-8 for browsemenu and heading-4 for homepage
        if (event.keyCode == 9 && $("#" + idValue).find('a:first').hasClass('collapsed')) {
            if ($("#nav466").hasClass('link-disabled')) {//hardparts disable - skipping  focus
                $("#navMain").find('a').eq(1).focus();
                event.preventDefault();
            }
            else {
                $("#navMain").find('a:first').focus();
                event.preventDefault();
            }
        }
    }
    else if (idValue == "collapse-8") {//contact us from leftside menu
        if (event.keyCode == 9 && $("#" + idValue).find('a:last').is(":focus")) {
            if ($("#nav466").hasClass('link-disabled')) {//hardparts disable - skipping  focus
                $("#navMain").find('a').eq(1).focus();
                event.preventDefault();
            }
            else {
                $("#navMain").find('a:first').focus();
                event.preventDefault();
            }
        }
    }
    else if (idValue == "collapse-4") {//contact us from home page
        if (event.keyCode == 9) {
            $(".logo-link").find('a:first').focus();
            event.preventDefault();
        }
    }
}

function backClick(event, idValue, className) {
    var keyValue = event.keyCode;
    //if (window.event) // IE
    //{
    //    keyValue = event.keyCode
    //}
    //else if (event.which) // Netscape/Firefox/Opera
    //{
    //    keyValue = event.which
    //}
    if (keyValue == 13 || event.key === 'Enter') {
        if (className == "back-to-primary" || className == "nav-dark-back") {
            if (className == "back-to-primary") {
                navigateBackToPrimary(idValue);
            }
            else {
                navigateBacktoMperform(idValue);
            }

            setTimeout(function () {
                if ($("#navMain").find('li').eq(0).hasClass('link-disabled')) {
                    $("#navMain").find('a').eq(1).focus();
                    event.preventDefault();
                }
                else {
                    $("#navMain").find('a:first').focus();
                    event.preventDefault();
                }
            }, 500);
        }
        else if (className == "back-to-secondary") {
            var arr = idValue.split('+');
            navigateBackToSecondary(arr[0], arr[1]);
            idValue = "navSub" + arr[0];
            setTimeout(function () {
                $("#" + idValue).find('a:first').focus();
            }, 300);
            event.preventDefault();
        }
        //else if (className == "nav-dark-back") {
        //    navigateBacktoMperform(idValue);
        //    setTimeout(function () {
        //        $("#navSub" + idValue).find('a:first').focus();
        //    }, 300);
        //    event.preventDefault();
        //}
    }
}

function focusMenu(event) { //hardparts disable - skipping  focus
    var keyValue = event.keyCode;
    if (keyValue == 9 && $("#mobileMenu").hasClass('active')) {
        if ($("#nav466").hasClass('link-disabled')) {
            $("#navMain").find('a').eq(1).focus();
            event.preventDefault();
        }
        else {
            $("#navMain").find('a').eq(0).focus();
            event.preventDefault();
        }
    }
    else {
        if (keyValue == 9 && !$("#mobileMenu").hasClass('active')) {
            $("#txtVisualiser").focus();
            //$("#txtBxSearch").focus();
            event.preventDefault();
        }
    }
}

//Refocusing to next item after clicking on cancel button in Model Popup
function reFocusing(event, sideValue, className) {
    var keyValue = event.keyCode;
    //if (keyValue == 13) {
    if (sideValue == 0 && className == "fitment-bottom") {//leftside
        closeMenu(sideValue);
        setTimeout(function () {
            $("#select-your-bmw").focus(); //model is not selected
        }, 500);
    }
    else if (sideValue == 0 && className == "fitment-bottom buttons") {
        $("#your-bmw").focus(); //when model is selected
    }
    //}
}

//Focusing dealer flyout from footer and leftside menu and dealer flyout when add to cart button is clicked 
function reFocusingDealerFlyout(event) {
    //var keyValue = event.keyCode;
    if ($("#dealerSearch").hasClass('active')) {//keyValue == 13
        // setTimeout(function () {
        $("#flyoutDealer").focus();
        //}, 100);

    }
}

//Product Details page Choose Options
function chooseOptionsFlyout(event) {
    var keyValue = event.keyCode; //keyvalue checking is removed because NVDA doesn't firing enter key press to onkeydown function's
    // if (keyValue == 13) {
    setTimeout(function () {
        if ($("#validateOption").hasClass('d-block')) {
            $("#validateOption").focus();
            event.preventDefault();
        }
        if ($("#divSelectOpt").hasClass('ProD-block')) {
            $("#backProducts").focus();
            event.preventDefault();
        }
    }, 50);

    //}
}
$("#validateOption").keydown(function (e) {
    var keyValue = e.keyCode;
    if (keyValue == 9) {
        focusPopup(e, "bmwOriginal");
    }

});

//Back to products after add to cart in choose options menu
function backProducts(event, idValue, parentId) {
    var keyValue = event.keyCode;
    if (keyValue == 9 && parentId != "" && parentId != null) {
        if ($("#" + parentId).hasClass('ProD-block')) {
            focusPopup(event, idValue);
        }
        else if ($("#" + parentId).hasClass('ProD-none')) {
            if (parentId.indexOf('divVisualizer') > -1) {
                event.preventDefault();
            }
            else {
                $("#btnChooseOption").focus();
                event.preventDefault();
            }
        }

    }
    else if (keyValue == 9 && parentId == "") {
        if ($("#divSelectOpt").hasClass('ProD-block')) {
            focusPopup(event, idValue);
        }
        //else if ($("#divSelectOpt").hasClass('ProD-none')) {
        //    $("#btnChooseOption").focus();
        //    event.preventDefault();
        //}
    }
    else if (keyValue == 13 && parentId == "") {
        hideProductOptionPopup();
        $("#btnChooseOption").focus();
        event.preventDefault();
    }
    else if (keyValue == 13 && parentId != "") {
        hideVisualizerOptionPopup();
        $('.DivFeatured').find('a:first').focus();
        event.preventDefault();
    }
}


//refocusing to dealer locater after covid popup closing
function refocusingtoHome() {
    setTimeout(function () {
        ////$("#divSelectedDealerLarge").find('a').eq(0).focus(); refocusing to locate a dealer before ci update
        $("#Navtoggle").focus();
    }, 100);
}

//refocusing popups - returnpolicy and submitting your order loader
function focustoPolicy(idValue) {
    if (idValue == "modalForTerms") {
        setTimeout(function () {
            if ($("#modalForTerms").hasClass('show')) {
                $("#returnDiv").focus();
            }
        }, 100);

    } else if (idValue == "reviewLoaderId") {
        //setTimeout(function () {
        if ($("#reviewLoaderId").hasClass('d-block')) {
            $("#reviewLoaderId").focus();
        }
        //}, 100);

    }
}

//save and continue button in billing page
function focusonCard(idValue) {
    //if (idValue == "paymentHeading") {
    $("#" + idValue).focus();
    //}
}

//dealer flyout issue after ci update
function dealerFlyoutFocus(event, idValue) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        if (idValue == "cartBtn") {
            if (!$("#dealerSearch").hasClass('active')) {//when dealer popup is not opened
                $("#cartBtn").focus();
                event.preventDefault();
            }
        }
        else if (idValue == "sel-bmwId") {
            $("#sel-bmwId").find('a').eq(0).focus();
            event.preventDefault();
        }

    }
    else if (keyValue == 13) {
        if (idValue == "cartBtn") {
            if ($("#dealerSearch").hasClass('active')) {
                $("#flyoutDealer").focus();
                event.preventDefault();
            }
        }
    }
}
//function LinkKeypress(e, obj) {
//    if (e.keyCode === 13 || e.key === 'Enter') {
//        var linkHref = $(obj).find('a').attr('href');
//        window.location = linkHref;
//        e.preventDefault();
//    }
//}

//Visualiser new button in header reading 
function focusSearch(event) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        $("#txtBxSearch").focus();
        event.preventDefault();
    }
}
/**************Redirect to log out page after session expire****************/
var pagetime;
var timelimit = 1800;
signoutpage = '../../MotorSports/Logout';
function SetWebPageTimer() {
    setTimeout('timecheck();', 10);
    var docbody = document.getElementsByTagName('body')[0];
    if (docbody.addEventListener) {
        docbody.addEventListener('mouseover', AddTime, false);
        docbody.addEventListener('keydown', AddTime, false);
    } else if (docbody.attachEvent) {
        docbody.attachEvent('onmousemove', AddTime);
        docbody.attachEvent('onkeydown', AddTime);
    } pagetime = -1;
}
function timecheck() {
    if (pagetime == -1) {
        pagetime = parseInt(timelimit);
    }
    pagetime = pagetime - 1;
    if (pagetime < 0) {
        document.location.href = signoutpage;
        return;
    } else {
        setTimeout('timecheck()', 1000);
    }
}
function AddTime() {
    if (pagetime <= 0) {
        return;
    } pagetime = timelimit;
}
/************************************************/
$(window).on('scroll', function () {
    var pathname = window.location.pathname.toLowerCase();
    if (pathname == '/' || (pathname == '/yourvehicle') || pathname == '/visualizer/intro' || pathname.indexOf('/specials/') > -1) {
        //(window.location.pathname == '/yourvehicle' && !$("#divBody").hasClass("MppLandingBlack"))
        if ($(window).scrollTop() < 1) {
            if (!($("header[id='app']").find("nav").hasClass("ThemeTrans"))) $("header[id='app']").find("nav").addClass("ThemeTrans");
            
        }
        else if ($(window).scrollTop() >= 1) {
            if (($("header[id='app']").find("nav").hasClass("ThemeTrans"))) $("header[id='app']").find("nav").removeClass("ThemeTrans");
        }
    }
});

function selectYearSeriesModel()
{
    $('#rightToggleMenu').addClass("active");
    if ($("#dealerSearch").is(':visible')) {
        $("#dealerSearch").removeClass('show');
        $('#divHeaderBodyOverlay').css('display', 'none');
        $('#dealerOverlay').css('display', 'none');
    }
    else if ($("#mobileMenu").hasClass('active')) {
        $("#mobileMenu").removeClass('show');
        $("#nav-icon1").removeClass('open');
        $('#divHeaderBodyOverlay').css('display', 'none');
        $('#dealerOverlay').css('display', 'none');
    }
    else if ($("#cartSummary").is(':visible')) {
        closeCartFlyout();
        $('#divHeaderBodyOverlay').css('display', 'none');
        $('#dealerOverlay').css('display', 'none');
    }
    if (document.getElementById("hdnModelName")) {
        var modelName = document.getElementById("hdnModelName").value;
        if (modelName !== "") {
            var divSelectBMW = document.getElementById("sel-bmwId").textContent;
            if (divSelectBMW.includes(modelName) === false) {
                $('#rightToggleMenu, #OverlayRight').css('display', 'none');
                window.location.reload(true);
            }
        }
    }
}

//for generating blue highlighting on tab 
document.body.addEventListener('mousedown', function () {
    document.body.classList.add('using-mouse');
});

//skiptocontent - start //
var isTabReaded = 0;
document.body.addEventListener('keydown', function (event) {
    if (window.location.href.toUpperCase().indexOf('BMW-I7-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-8-X-JEFF-KOONS-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-IX-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('/PREORDER/') > 0 || window.location.href.toUpperCase().indexOf('ACCESSIBILITY') > 0) {
        isAccessible = 1;
    }
    if (event.keyCode == 13) {
        if (event.target.id == "skiptoContent" || $(event.target).hasClass('VisAddIcon') || event.target.id.includes('vis') || event.target.id.includes('divProducts_') || $(event.target).hasClass('visactive') || event.target.id == "finishDesk" || event.target.id.includes('color_') || event.target.id.includes('li_tabs_') || event.target.id == "JKconfirmReservation" || event.target.id == "NAFLearnMoreCloseId") {
            isTabActive = 1;
        }
        else {
            isTabActive = 0;
        }
        skipContentClick();
    }
    if (event.keyCode == 9 && isTabActive == "0" && isAccessible == "1") {
        if (!($("#divSelectOptOverlay").is(":visible") || $("#divHeaderBodyOverlay").is(":visible") || $("#OverlayRight").is(":visible") || $("#dealerOverlay").is(":visible") || $("#AlertModalHome").hasClass("show") || $("#ModelConfirmationPopUp").hasClass('show') || $("#divVisualizerSelectOptOverlay").hasClass('d-block') || $("#SummaryModel").hasClass('show') || $("#myModalPreCamp").hasClass('show') || $("#NAFLearnMore").hasClass('show') || $('.DivFeaturePopOverlay').hasClass('d-block') || $('.DivQuesPopoverlay').hasClass('d-block'))) {
            setTimeout(function () {
                $(".SkipContent").removeClass("d-none");
                $("#skiptoContent").focus(); //setting second focus to Skip to content
                $(':root').removeClass('TabFixed');
            }, 100);
        }
        else if (window.location.href.toLowerCase().indexOf('bmw-flowcode') > 0 && $("#OverlayRight").is(":visible") && isTabReaded=="0") {
            isTabReaded = 1;
            modelFlyEvent(event);
        }
        
    }
    else if (event.keyCode == 9 && isTabActive == "0" && isAccessible == "0" && (!$('.InstockCon-body-overlay').is(":visible"))) {
        if (!($("#divSelectOptOverlay").is(":visible") || $("#divHeaderBodyOverlay").is(":visible") || $("#OverlayRight").is(":visible") || $("#dealerOverlay").is(":visible") || $("#AlertModalHome").hasClass("show") || $("#ModelConfirmationPopUp").hasClass('show') || $("#divVisualizerSelectOptOverlay").hasClass('d-block') || $("#SummaryModel").hasClass('show') || $("#myModalPreCamp").hasClass('show') || $("#NAFLearnMore").hasClass('show') || $('.DivFeaturePopOverlay').hasClass('d-block') || $('.DivQuesPopoverlay').hasClass('d-block') || $("#modalForTerms").hasClass("show"))) {
            $(':root').addClass('TabFixed');
            $("#collapse-3 #accessibility-3").focus(); //setting first focus to accessibility without page scroll
            event.preventDefault();
        }
        else if (window.location.href.toLowerCase().indexOf('bmw-flowcode') > 0 && $("#OverlayRight").is(":visible") && isTabReaded == "0") {
            isTabReaded = 1;
            modelFlyEvent(event);
        }
    }
    else if (event.keyCode == 9 && isTabActive == "0" && isAccessible == "0" && $('.InstockCon-body-overlay').is(":visible")) {//setting 1st focus to customerinventry notification popup be-10460
        $("#thanksNoti").focus();
        isTabActive = 1;
        event.preventDefault();
    }
    document.body.classList.remove('using-mouse');
});

// checkout page tabbing through billing section without interfearance of skip to content
$("#divBillingSection ,#divPayment,#divContactSection,#divBillingAddressForm,#orderWaitingdiv,.DivUserInfo,.DivCardInfo").on('keydown', function (event) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        isTabActive = 1;
    }
});


function skiptoContentFocus() {
    var pageTitle = $("#hdnPageTitle").val();
    var pageInfo = $("#hdnPageInfo").val(); //for details page and listing page only
    var dealerInfo = $("#hdnDealerId").val();
    if (pageTitle == "Shop Original BMW Parts, Accessories and Apparel") {//home page
        $('.hero-text').find('a:first').focus();
    }
    else if (pageInfo != null && pageInfo != "" && pageInfo != undefined) {
        if (pageInfo == "Product List") {
            if (pageTitle == "BMW PERFORMANCE PARTS 3" || pageTitle == "BMW-PERFORMANCE-PARTS-1")//landing pages
            {
                $("#videoPauseId").focus();
            }
            else {
                $('.divProductsList').find('.card-group:first').find('a').eq(1).focus();
            }
        }
        else if (pageInfo == "Product Details") {
            $('.pagedetails').find('a:first').focus();
        }
        else if (pageInfo == "Landing Page") {//yourvehicle
            if (pageTitle == "Index") {
                $('.DivLandBannerInner').find('a:first').focus();
            }
        }
    }
    else if (pageTitle == "Cart" || pageTitle == "Checkout") {
        $('.DivCartHead').find('div:first').focus();
    }

    else if (pageTitle == "Review") {
        $('.SecReview').find('h1:first').focus();
    }
    else if (pageTitle == "OrderSummary") {
        $('.DivCongr').find('h1:first').focus();
    }
    else if (pageTitle == "Order Help" || pageTitle == "Shipping" || pageTitle == "Return" || pageTitle == "Refund" || pageTitle == "Privacy") {
        if (dealerInfo != null && dealerInfo != "") {
            $('.tabContentViewer').find('h2:first').focus();
        }
        else {
            $('.tabContentViewer').find('h4:first').focus();
        }
    }
    else if (pageTitle == "Security") {
        $('.tabContentViewer').find('h2:first').focus();
    }
    else if (pageTitle == "SiteMap") {
        $('.DivSiteHeader').find('h3:first').focus();
    }
    else if (pageTitle == "Contact") {
        $('.tabContentViewer').find('h2:first').focus();
    }
    else if (pageTitle == "Accessibility") {
        $('.tabContentViewer').find('h4:first').focus();
    }
    else if (pageTitle == "Pre-Order") {
        $('.ixPaymentDiv').find('button:first').focus();
        $('.addCartBtn').find('button:first').focus();

    }
    else if (pageTitle == "MotorSports Login") {//motorsports
        $("#MotorSptPwd").focus();
    }
    else if (pageTitle == "Track Select") {//motorsports
        $("#divMotorSportsTrackList").find('.Divdealer:first').focus();
    }
    else if (pageTitle == "Dealer Select") {//motorsports
        $("#divMotorSportsDealerList").find('.Divdealer:first').focus();
    }
    else if (pageTitle == "Product Search") {
        $("#txtBxSearchMotorSports").focus();
    }
    else if (pageTitle == "ProductVisualizer") { //visualizer
        if ($("#SummaryModel").is(':Visible')) {
            $("#btnAddToCartVizFromPopUp").focus();
        }
        else {
            $('.DivFeatured').find('a:first').focus();
        }
    }
    else if (pageTitle == "BMWShoppable") {
        $('.SecShopBlock2').find('h1:first').focus();
    }
    $(".SkipContent").addClass("d-none");
    //event.preventDefault();
}
function validateModelForVisualizer() {
    var modelName = $('#hdnmodelIdForVisualizer').val();
    if (modelName == null || modelName == "") {
        $("#lnkBMWModelVis").trigger("click");
        $('#rightToggleMenu').addClass("active");
        $("#OverlayRight").css("display", "block");
        //Disabling body scroll modelpopup is visible
        $('body').addClass('body-fixed');
        $('body').css('overflow-y', 'hidden');
        $('html').css('overflow', 'hidden');
    }
    return false
}
function changeModelForVisualizer() {
    $("#lnkChangeBMWModelVis").trigger("click");
    $('#rightToggleMenu').addClass("active");
    $("#OverlayRight").css("display", "block");
    //Disabling body scroll modelpopup is visible
    $('body').addClass('body-fixed');
    $('body').css('overflow-y', 'hidden');
    $('html').css('overflow', 'hidden');
}
function showModelPopupinVisLandingpage() {
    $("#lnkBMWModelVisLanding").trigger("click");
    $('#rightToggleMenu').addClass("active");
    $("#OverlayRight").css("display", "block");
    //Disabling body scroll modelpopup is visible
    $('body').addClass('body-fixed');
    $('body').css('overflow-y', 'hidden');
    $('html').css('overflow', 'hidden');
}
function showModelPopup() {
    $("#lnkBMWModelHeader").trigger("click");
    $('#rightToggleMenu').addClass("active");
    $("#OverlayRight").css("display", "block");
    //Disabling body scroll modelpopup is visible
    $('body').addClass('body-fixed');
    $('body').css('overflow-y', 'hidden');
    $('html').css('overflow', 'hidden');
}
var isTabActive = 0;
function focusHeader(event) {

    var keyValue = event.keyCode;
    if (keyValue == 9) {
        isTabActive = 1;
        //setTimeout(function () {
        $(".SkipContent").addClass("d-none");
        //}, 300);
        var freeshipping = $("#isFreeshipping").val();
        var mBanner = $("#isMbannerEnabled").val();
        if (freeshipping != null) {
            $('.DivFreeship').focus();
        }
        else if (mBanner != null) {
            $(".MBadgeLarge").find('h1:first').focus();
        }
        else {
            $(".logo-link").find('a:first').focus();
        }
        if (window.location.href.toUpperCase().indexOf('BMW-I7-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-8-X-JEFF-KOONS-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('/PREORDER/PREORDERWAITLIST') > 0) {
            $('#dealerLocated').focus();
        }
        event.preventDefault();
    }
    if (keyValue == 13) {
        if (window.location.href.toUpperCase().indexOf('BMW-I7-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-8-X-JEFF-KOONS-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('/PREORDER/PREORDERWAITLIST') > 0) {
            $('.IModel').find('h1:first').focus();
        }
    }
}
document.body.addEventListener('click', function (event) { //hiding skip to content on mouse click anywhere in body
    //start - Hiding shoppable popup on mouse click in yourvehicle page when ada active
    var isShoppable = $("#hdnIsShoppable").val();
    var ecode = $("#hdnModelEcode").val();
    if (ecode != "" && ecode != null && ecode != "undefined")
        ecode = ecode.replace(" ", "");
    if ((window.location.pathname.toLowerCase() == '/yourvehicle' && isShoppable != "" && isShoppable != null && isShoppable != "undefined" && isShoppable.toLowerCase() == "true" && isTabActive == "1") || (window.location.pathname.toLowerCase().indexOf('bmw-flowcode') > 0 && isTabActive == "1")) {
        if (window.location.pathname.toLowerCase().indexOf('bmw-flowcode') > 0 ) {
            ecode = $("#hdnShoppableECode").val().replace(" ", "").toUpperCase();
        }
        $('div[id*="point"],div[id*="Point"]').each(function () {
            var id = this.id;
            if (id.indexOf('_2') > 0) {
                var idVal = id.replace("_2", "");
                var arrayval = idVal.split("_");
                var point = arrayval[1]+"_2";
                if ($("#" + id).hasClass(point + "SecActive") && !event.target.className.includes(ecode + 'point') && !event.target.parentElement.className.includes(ecode + 'point') && !event.target.className.includes(ecode + 'Point') && !event.target.parentElement.className.includes(ecode + 'Point')) {
                    $("#" + id).removeClass(point + "SecActive");
                    $("." + point).removeClass(point + "Hover");
                }
            } else {
                var arrayval = id.split("_");
                var point = arrayval[1];
                if ($("#" + id).hasClass(point + "SecActive") && !event.target.className.includes(ecode + 'point') && !event.target.parentElement.className.includes(ecode + 'point') && !event.target.className.includes(ecode + 'Point') && !event.target.parentElement.className.includes(ecode + 'Point')) {
                    $("#" + id).removeClass(point + "SecActive");
                    $("." + point).removeClass(point + "Hover");
                }
            }

        });
    }
    //end
    if (window.location.href.toUpperCase().indexOf('BMW-IX-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-I4-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('/PREORDER/') > 0 || window.location.href.toUpperCase().indexOf('BMW-8-X-JEFF-KOONS-PRE-ORDER') > 0) {
        isAccessible = 1;
    }
    if (event.target.id == "skiptoContent" || $(event.target).hasClass('VisAddIcon') || event.target.id.includes('vis') || event.target.id == "finishDesk" || event.target.id == "NAFLearnMoreCloseId") {
        isTabActive = 1;
    } else if (window.location.pathname.toLowerCase() == '/yourvehicle' && isShoppable != "" && isShoppable != null && isShoppable != "undefined" && isShoppable.toLowerCase() == "true" && isTabActive == "1" && (event.target.className.includes(ecode + 'point') || event.target.parentElement.className.includes(ecode + 'point') || event.target.className.includes(ecode + 'Point') || event.target.parentElement.className.includes(ecode + 'Point'))) {
        //setting tab active on shoppable popup and point click
        isTabActive = 1;
    } else if (window.location.pathname.toLowerCase().indexOf('bmw-flowcode') > 0 && isTabActive == "1" && (event.target.className.includes(ecode + 'point') || event.target.parentElement.className.includes(ecode + 'point') || event.target.className.includes(ecode + 'Point') || event.target.parentElement.className.includes(ecode + 'Point'))) {
        //setting tab active on shoppable popup and point click
        isTabActive = 1;
    }
    else {
        isTabActive = 0;
        isAccessible = 0;
    }
    skipContentClick();
   
});

function skipContentClick() {
    $(".SkipContent").addClass("d-none");
}

//skiptocontent - end //

//Motorsport ADA
function dealerFocus(event, idValue) {
    var keyValue = event.keyCode;
    var pageTitle = $("#hdnPageTitle").val();
    var pageInfo = $("#hdnPageInfo").val();
    if (keyValue == 9) {
        if (idValue == 'trackEdit') {
            if ($("#txtBxSearch").is(":visible")) {
                $("#txtBxSearch").focus();
            }

            else if ($("#trackEdit").is(':visible')) {
                $("#trackEdit").focus();
            }
            else {
                setTimeout(function () {
                    if ($("#divSelectedMotorSportsDealerLarge").is(':visible')) {
                        $("#divSelectedMotorSportsDealerLarge").find('a').focus();
                    }
                }, 50);
            }

            event.preventDefault();
        }
        else if (idValue == 'search') {
            if ($("#trackEdit").is(':visible')) {
                $("#trackEdit").focus();
                event.preventDefault();
            }
        }
        else if (idValue == 'locateDealerClick') {
            setTimeout(function () {
                if ($("#divSelectedMotorSportsDealerLarge").is(':visible')) {
                    $("#divSelectedMotorSportsDealerLarge").find('a').focus();
                }
            }, 50);
        }
    }
}

function logoutFocus(event) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        if ($("#app").hasClass('MotorSportHeader')) {
            setTimeout(function () {
                $('.DivLogout').find('a:first').focus();
            }, 50);
        }
        else if (window.location.href.toUpperCase().indexOf('/WHEELS-AND-TIRES/OVERVIEW') > 0) {
            $("#pageHeader").focus();
            event.preventDefault();
        }
    }
}

function focusToContent(event) {
    var keyValue = event.keyCode;
    var pageTitle = $("#hdnPageTitle").val();
    var pageInfo = $("#hdnPageInfo").val(); //for details page and listing page
    if (keyValue == 9) {
        if (pageTitle == "MotorSports Login") {//motorsports
            $("#MotorSptPwd").focus();
        }
        else if (pageTitle == "Track Select") {//motorsports
            if ($("#divEditMotorSportTrackList").is(':visible')) {
                $("#divEditMotorSportTrackList").find('.Divdealer:first').focus();
            }
            else {
                $("#divMotorSportsTrackList").find('.Divdealer:first').focus();
            }
        }
        else if (pageTitle == "Dealer Select") {//motorsports
            $("#divMotorSportsDealerList").find('.Divdealer:first').focus();
        }
        else if (pageTitle == "Product Search") {
            $("#txtBxSearchMotorSports").focus();
        }
        else if (pageInfo != null && pageInfo != "" && pageInfo != undefined) {
            if (pageInfo == "Product List") {
                $('.divProductsList').find('.card-group:first').find('a').eq(1).focus();
            }
            else if (pageInfo == "Product Details") {
                $('.pagedetails').find('a:first').focus();
            }
        }
        else if (pageTitle == "Cart" || pageTitle == "Checkout") {
            $('.DivCartHead').find('div:first').focus();
        }
        else if (pageTitle == "Review") {
            $('.SecReview').find('h1:first').focus();
        }
        else if (pageTitle == "OrderSummary") {
            $('.DivCongr').find('h1:first').focus();
        }
        event.preventDefault();
    }

}

$('#divMotorSportsTrackList .motorsports-dealer-div').on('keydown', function () {
    var keyValue = event.keyCode;
    if (keyValue == 13) {
        $('#hdnTrackId').val($(this).data('id'));
    }
});

$('#divMotorSportsDealerList .motorsports-dealer-div').on('keydown', function () {
    var keyValue = event.keyCode;
    if (keyValue == 13) {
        $('#hdnMotorSportsDealerId').val($(this).data('id'));
    }
});

$('#divEditMotorSportsTrackList .motorsports-dealer-div').on('keydown', function () {
    var keyValue = event.keyCode;
    if (keyValue == 13) {
        $('#divEditMotorSportsTrackList .hdnEditTrackId').val($(this).data('id'));
    }
});

$('#divMotorSportsTrackList .Divdealer').keydown(function (event) {
    var keyValue = event.keyCode;
    if (keyValue == 13) {
        $('.DivMotorBtn').show();
        $('#divMotorSportsTrackList .Divdealer').each(function (index) {
            $(this).removeClass('MtrActive');
        });
        $(this).addClass('MtrActive');
        $("#btnSetDealer").focus();//for ADA
        event.preventDefault();
    }

});

$('#divMotorSportsDealerList .Divdealer').keydown(function (event) {
    var keyValue = event.keyCode;
    if (keyValue == 13) {
        $('#btnSetDealer').show();
        $('#divMotorSportsDealerList .Divdealer').each(function (index) {
            $(this).removeClass('MtrActive');
        });
        $(this).addClass('MtrActive');
        $($(this).find('input[type=radio]')[0]).prop('checked', true);
        $("#btnSetDealer").focus(); //for ada
        event.preventDefault();
    }
});

$('#divEditMotorSportsTrackList .Divdealer').keydown(function (event) {
    var keyValue = event.keyCode;
    if (keyValue == 13) {
        $('.DivMotorBtn').show();
        //$('#btnEditSetDealer').show();
        $('#divEditMotorSportsTrackList .Divdealer').each(function (index) {
            $(this).removeClass('MtrActive');
        });
        $(this).addClass('MtrActive');
        $("#btnEditSetDealer").focus();//for ADA
        event.preventDefault();
    }
});
//function fmaTracking(fmaName) {
//    _gaq.push(['commonTracker._trackEvent', 'BMW Home Page - FMA CTA', 'click', fmaName]);

//}
function fmaTrackingGA4(fmaName) {
    if ($("#hdnIsEnabledGA4").val() == 'true') {
        gtag("event", 'BMW Home Page - FMA CTA', {
            event_label: fmaName,
            event_category: 'BMW Home Page - FMA CTA'
        });
    }

}
function commonGA4Tracking(event, event_label, event_category) {
   
    if ($("#hdnIsEnabledGA4").val() == 'true') {
        var ga4Valu = $("#hdnGA4Value").val()
        gtag("event", event, {
            event_label: event_label,
            event_category: event_category,
            send_to: ga4Valu

        });

        if (!/(checkout|review|cart|preorder)/i.test(event)) {
            var eventData = {
                key: event,
                value_event_label: event_label,
                value_event_category: event_category
            };

            $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.Home.SetSessionvalue, data: eventData }, {
                complete: function (json) {
                }
            }));
        }
    }
}
function shopConfirmationModelChange() {

    commonGA4Tracking('BMW Home Page - FMA CTA', 'Main FMA - Q2 2020', 'BMW Home Page - FMA CTA');

    if ($("#hdnModelChange").val() == 'true') {
        $("#ModelConfirmationPopUp").modal("show");
        event.preventDefault();
        return false;
    }
    else {
        return true;
    }
}
function closePopupModelChange(isOk) {

    $("#ModelConfirmationPopUp").modal("hide");
    if (isOk == 0) {
        event.preventDefault();
        return false;
    }
    else
        return true;
}

function focusPopupFMA(event) {
    var keyValue = event.keyCode;
    if (keyValue == 13) {
        setTimeout(function () {
            if ($("#ModelConfirmationPopUp").hasClass('show')) {
                $("#ModelConfirmationPopUp").find('p').focus();
                event.preventDefault();
            }
        }, 200);
    }
}
// product detail option selectio functions
function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
}
function getObjectItem(value) {
    var ProductItem = [];
    $.each(ProductItemDetails, function (MainIndex, MainObject) {
        $.each(MainObject.ProductOptions, function (index, object) {
            var OptionValue = object.OptionValue.replace(/[^a-z0-9\s\-]/gi, '').replace(/[_\s]/g, ' ');
            if (OptionValue == value.replace(/©/g, " ")) {
                ProductItem = ProductItemDetails[MainIndex];
                return ProductItem;
            }
        });
    });
    return ProductItem;
}

function billingAddressChange(event) {
    var keyValue = event.keyCode;
    if (keyValue == 13) {
        changeBillingAddress();
        setTimeout(function () {
            $("#divBillingAddressForm").find('h1:first').focus();
        }, 200);
        event.preventDefault();
    }
}

//update cart page freeshiping message when applying and removeing promocode
function UpdateFreeshipInfo() {
      if (($('#IsFreeshipMsg').val() != undefined && $('#IsFreeshipMsg').val() === "true") || ($('#IsFreeshipApplicable').val() == undefined || $('#IsFreeshipApplicable').val() === "false")) {
         if (!$(".DivCartFreeShipMd, .DivCartFreeShipSm").hasClass("d-none"))
            $(".DivCartFreeShipMd, .DivCartFreeShipSm").addClass("d-none");
    }
    else {
        if ($(".DivCartFreeShipMd, .DivCartFreeShipSm").hasClass("d-none"))
            $(".DivCartFreeShipMd, .DivCartFreeShipSm").removeClass("d-none");
    }


}

jQuery(document).ready(function ($) {

    $("#author_bio_wrap_toggleinner").click(function () {

        //$(".MpMenu").fadeToggle("slow");

        //if ($("#author_bio_wrap_toggle").text() == "Overview") {
        //    $("#author_bio_wrap_toggle").html("Overview")
        //}
        //else {
        //    $("#author_bio_wrap_toggle").text("Overview")
        //}

    });

});

$(window).scroll(function () {
    if ($(this).scrollTop() > 50) {
        //$('header').addClass('active1');
        //$('.PHeader').addClass('active2');
    } else {
        //$('header').removeClass('active1');
        //$('.PHeader').removeClass('active2');
    }
});

$('.drop-box').click(function () {

});
$("#author_bio_wrap_toggle").click(function () {
    // debugger;
    $(this).toggleClass("highlight");
    //$('.MpMenu').toggleClass('d-block');
    var pathname = window.location.pathname.toLowerCase();
    if (pathname.indexOf("/m-performance/overview") > -1 || pathname.indexOf("/wheels-and-tires/overview") > -1) {
        var html = jQuery('html');
        if ($('.MpMenu').css('display') == 'none') {
            html.css('overflow', 'hidden');
        }
        else {
            html.css('overflow', 'auto');
        }
    }
    $('.MpMenu').fadeToggle();
    $('#mpparrow').toggleClass('animatemppinner');


});
$("#mppmenuclose").click(function () {
    //$('.MpMenu').addClass('d-none');
    $(".MpMenu").fadeToggle();
    var pathname = window.location.pathname.toLowerCase();
    if (pathname.indexOf("/m-performance/overview") > -1 || pathname.indexOf("/wheels-and-tires/overview") > -1) {
        var html = jQuery('html');
        html.css('overflow', 'auto');
    }
});
$("#author_bio_wrap_toggleinner").click(function () {
    //$('.MpMenu').addClass('d-none');
    //$(".MpMenu").fadeToggle();
    $(".MpMenu").fadeToggle("slow");
    var pathname = window.location.pathname.toLowerCase();
    if (pathname.indexOf("/m-performance/overview") > -1 || pathname.indexOf("/wheels-and-tires/overview") > -1) {
        var html = jQuery('html');
        html.css('overflow', 'auto');
    }
    $('#mpparrowinner').toggleClass('animatemppinner');
});


function playMPPAudio(isPlay) {
    if (isPlay == 0) {
        document.getElementById('MPPAudio').pause();
        $('#MPPAudio').stop();
        $("#imgAudioPlay").removeClass('d-none');
        $("#imgAudioPause").addClass('d-none');
    }
    else {
        document.getElementById('MPPAudio').play();
        $("#imgAudioPause").removeClass('d-none');
        $("#imgAudioPlay").addClass('d-none');
    }
}
function redirectToMPP() {
    window.location = "/m-performance?isMPPRedirect=True";
}

class Slideshow {

    constructor() {
        this.initSlides();
        this.initSlideshow();
    }

    // Set a `data-slide` index on each slide for easier slide control.
    initSlides() {
        this.container = $('[data-slideshow]');
        this.slides = this.container.find('img');
        this.slides.each((idx, slide) => $(slide).attr('data-slide', idx));
    }

    // Pseudo-preload images so the slideshow doesn't start before all the images
    // are available.
    initSlideshow() {
        this.imagesLoaded = 0;
        this.currentIndex = 0;
        this.setNextSlide();
        this.slides.each((idx, slide) => {
            $('<img>').on('load', $.proxy(this.loadImage, this)).attr('src', $(slide).attr('src'));
        });
    }

    // When one image has loaded, check to see if all images have loaded, and if
    // so, start the slideshow.
    loadImage() {
        this.imagesLoaded++;
        if (this.imagesLoaded >= this.slides.length) { this.playSlideshow() }
    }

    // Start the slideshow.
    playSlideshow() {
        this.slideshow = window.setInterval(() => { this.performSlide() }, 3500);
    }

    // 1. Previous slide is unset.
    // 2. What was the next slide becomes the previous slide.
    // 3. New index and appropriate next slide are set.
    // 4. Fade out action.
    performSlide() {
        if (this.prevSlide) { this.prevSlide.removeClass('prev fade-out') }

        this.nextSlide.removeClass('next');
        this.prevSlide = this.nextSlide;
        this.prevSlide.addClass('prev');

        this.currentIndex++;
        if (this.currentIndex >= this.slides.length) { this.currentIndex = 0 }

        this.setNextSlide();

        this.prevSlide.addClass('fade-out');
    }

    setNextSlide() {
        this.nextSlide = this.container.find(`[data-slide="${this.currentIndex}"]`).first();
        this.nextSlide.addClass('next');
    }

}

$(document).ready(function () {
    new Slideshow;
});

class Slideshowa {

    constructor() {
        this.initSlides();
        this.initSlideshowa();
    }

    // Set a `data-slide` index on each slide for easier slide control.
    initSlides() {
        this.container = $('[data-slideshowa]');
        this.slides = this.container.find('img');
        this.slides.each((idx, slide) => $(slide).attr('data-slide', idx));
    }

    // Pseudo-preload images so the slideshow doesn't start before all the images
    // are available.
    initSlideshowa() {
        this.imagesLoaded = 0;
        this.currentIndex = 0;
        this.setNextSlide();
        this.slides.each((idx, slide) => {
            $('<img>').on('load', $.proxy(this.loadImage, this)).attr('src', $(slide).attr('src'));
        });
    }

    // When one image has loaded, check to see if all images have loaded, and if
    // so, start the slideshow.
    loadImage() {
        this.imagesLoaded++;
        if (this.imagesLoaded >= this.slides.length) { this.playSlideshowa() }
    }

    // Start the slideshow.
    playSlideshowa() {
        this.slideshowa = window.setInterval(() => { this.performSlide() }, 3500);
    }

    // 1. Previous slide is unset.
    // 2. What was the next slide becomes the previous slide.
    // 3. New index and appropriate next slide are set.
    // 4. Fade out action.
    performSlide() {
        if (this.prevSlide) { this.prevSlide.removeClass('prev fade-out') }

        this.nextSlide.removeClass('next');
        this.prevSlide = this.nextSlide;
        this.prevSlide.addClass('prev');

        this.currentIndex++;
        if (this.currentIndex >= this.slides.length) { this.currentIndex = 0 }

        this.setNextSlide();

        this.prevSlide.addClass('fade-out');
    }

    setNextSlide() {
        this.nextSlide = this.container.find(`[data-slide="${this.currentIndex}"]`).first();
        this.nextSlide.addClass('next');
    }

}


function thumbnaillImageOnClick(id) {
    var SelectedClass = $(".thumbnail-image");
    $.each(SelectedClass, function (index, object) {
        $("#" + object.id).removeClass("thumb-selected");
    });
    $("#product-thumbnail-" + id).addClass("thumb-selected");
}
$(".carousel-control-prev").on('click', function () {
    var imageId = $(this).closest("[id^='productCarousel']").find('.active').find('img').attr('id');
    if (imageId === undefined)
        imageId = $(this).closest("[id^='productCarousel']").find('.active').find('video').attr('id');
    if (imageId !== undefined) {
        var components = imageId.split("-");
        var photoNum = components[components.length - 1];
        var index = parseInt(photoNum) - 1;
        var assetCount = parseInt($(this).closest("[id^='productCarousel']").find('.carousel-item').length);
        if (index < 0)
            index = assetCount - 1;
        thumbnaillImageOnClick(index);
    }
});
$(".carousel-control-next").on('click', function () {
    var imageId = $(this).closest("[id^='productCarousel']").find('.active').find('img').attr('id');
    if (imageId === undefined)
        imageId = $(this).closest("[id^='productCarousel']").find('.active').find('video').attr('id');
    if (imageId !== undefined) {
        var components = imageId.split("-");
        var photoNum = components[components.length - 1];
        var assetCount = parseInt($(this).closest("[id^='productCarousel']").find('.carousel-item').length);
        var index = parseInt(photoNum) + 1;
        if (index >= assetCount)
            index = 0;
        thumbnaillImageOnClick(index);
    }
});

$(document).ready(function () {
    new Slideshowa;
});

var isAccessible = 0;
//after first tab to accessibility  second tab to skip to content.
$("#collapse-3 #accessibility-3").keydown(function (event) {
    var keyValue = event.keyCode;
    if (keyValue == 9 && $(".SkipContent").hasClass("d-none") && isTabActive == "0") {
        setTimeout(function () {
            $(".SkipContent").removeClass("d-none");
            $("#skiptoContent").focus(); //setting first focus to Skip to content
        }, 100);
        isAccessible = 1;
        event.preventDefault();
    }
});

//Used in Product details and Visualizer
function getProductObjectItem(value) {
    var ProductItem = [];
    var item_options = value.split(',');
    //debugger;
    $.each(ProductItemDetails, function (MainIndex, MainObject) {
        $.each(MainObject.ProductOptions, function (index, object) {

            var OptionValue = object.OptionId;
            if (OptionValue == item_options[0].replace(/©/g, " ")) {
                // if (name == "alloption") {
                ProductItem.push(ProductItemDetails[MainIndex]);
                //return ProductItem;
                //}
                // 
            }
        });
    });
    if (item_options.length > 1) {
        var ProductItemOpt = [];
        $.each(ProductItem, function (MainIndex, MainObject) {
            $.each(MainObject.ProductOptions, function (index, object) {
                //debugger;
                var OptionValue = object.OptionId;
                if (OptionValue == item_options[1].replace(/©/g, " ")) {
                    // if (name == "alloption") {
                    //debugger;
                    ProductItemOpt.push(ProductItem[MainIndex]);
                    //return ProductItemOpt;
                    //}
                    // 
                }
            });
        });
        if (item_options.length > 2) {
            var ProductItemOpt1 = [];
            $.each(ProductItemOpt, function (MainIndex, MainObject) {
                $.each(MainObject.ProductOptions, function (index, object) {
                    // var OptionValue = object.OptionValue.replace(/[^a-z0-9\s\-]/gi, '').replace(/[_\s]/g, ' ');
                    var OptionValue = object.OptionId;
                    if (OptionValue == item_options[2].replace(/©/g, " ")) {
                        // if (name == "alloption") {
                        ProductItemOpt1.push(ProductItemOpt[MainIndex]);
                        return ProductItemOpt1;
                        //}
                        // 
                    }
                });
            });
        }
        else {
            return ProductItemOpt;
        }
    }
    else
        return ProductItem;
}
$('#browseClose').click(function () {
    $('#divHeaderBodyOverlay').click();
});


function notifiedProductClose() {
    $("#inventoryPopUp").addClass("d-none");
    const url = new URL(window.location.href);
    var searchUrl = location.search;
    url.search = "";
    window.history.replaceState(null, null, url); //removing querystring from url
    $('body').removeClass('body-fixed');
    $('html').css('overflow', 'auto');
}


//wheels landing ADA readability
function focustoYear(event) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        if ($("#divYear").hasClass('whYearHideMain')) {
            // $("#select-bmw-model-wheels").children().attr('tabindex', '-1');
            $("#yearH").focus();
            event.preventDefault();
        }

    }
}

function focusSelectedSeries(event, idValue) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        if (idValue == 'seleYear') {
            $("#select-bmw-model-wheels").children().attr('tabindex', '-1');
            $("#seleYear").focus();
        }
        else if (idValue == 'selectSeries') {
            $("#select-bmw-model-wheels-series").children().attr('tabindex', '-1');
            $("#selectSeries").focus();
        }
        else if (idValue == 'selectModel') {
            $("#select-bmw-model-wheels-model").find('a').eq(1).focus();
        }
        event.preventDefault();

    }
}

function focusSelectedyearSeries(event, idValue) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        if (idValue == 'Whtxt1') {
            if ($("#seriesSelect").hasClass('d-none')) {
                $("#selectSeriesmodel").find('h2').eq(1).focus();
            }
            else {
                $("#seriesSelect").focus();
            }
           
        }
        else if (idValue == 'idModelt2') {
            $("#idModelt2").focus();
        }
        event.preventDefault();
    }
}

$("#seriesSelect").on('keydown', function (event) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        $("#select-bmw-model-wheels-series").find('a').eq(1).focus();
        event.preventDefault();

    }
});

function focustoMperformance(event, count) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        if (count == 3) {
            $("#aMPerformance").focus();
            event.preventDefault();
        }
    }
}

$("#divShowMoreYears").on('keydown', function (event) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        $("#overview").find('h1:first').focus();
        event.preventDefault();
        }
});

$("#changePayment , #changePaymentAmazon").on('keydown', function (event) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        $("#inyourCart").focus();
        //event.preventDefault();
    }
});

function focusReview(event, idValue){
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        if (idValue == "footerdivDes") {
            $(".footer-container").find('span:first').focus();
            event.preventDefault();
        }
        else {
            if (window.location.href.toUpperCase().indexOf('CART/REVIEW') > 0 || window.location.href.toUpperCase().indexOf('CART/ACCEPTRETURNPOLICY') > 0) {
                $("#" + idValue).find('button:first').focus();
                event.preventDefault();
            }
        }
       
    }
}

function TopVehicleTracking(fitement, fitmentPath) {
    if (fitement != undefined && fitement != null) {
        //GA - vehicle Ecode traking when vehicle seleted
        commonGA4Tracking('Top Vehicles', fitement, 'Top Vehicles');
    }
    if (fitmentPath != undefined && fitmentPath != null) {
        //GA - vehicle page selection traking when vehicle is seleted
        commonGA4Tracking('Vehicle Selection - Page Path', fitmentPath, 'Vehicle Selection - Page Path');
    }
    //GA - Visualizer landing page with non-fitment selection and with out fitment selection
    //ga track with non-fitment selection
    var pathname = window.location.pathname.toLowerCase();
    if (pathname.indexOf("/visualizer/intro") == 0 || pathname.indexOf("/visualizer/intro/") == 0) {
        if ($('#IsModelSelected').val() !== undefined && $('#IsModelSelected').val() !== null && $('#IsModelSelected').val() !== '') {
            if ($('#IsModelSelected').val() == "true") {
                if ($('#SelectedModelName').val() !== undefined && $('#SelectedModelName').val() !== null && $('#SelectedModelName').val() !== '') {
                    commonGA4Tracking('Visualizer - non-visualizable fitment Selection', '"' + $('#SelectedModelName').val() + '"', 'Visualizer Fitment Selection');
                }
            }
        }
    }
}
function PopularItemsTrack(PopularItemPage, ProductName) {
    if (PopularItemPage == 'cart') {
        commonGA4Tracking('Cart - Popular items might interest', '"' + ProductName + '"', 'Cart - Popular items might interest');
    } else if (PopularItemPage == 'search') {
        commonGA4Tracking('Search - Popular items might interest', '"' + ProductName + '"', 'Search - Popular items might interest');
    } else {
        commonGA4Tracking('Popular items might interest', '"' + ProductName + '"', 'Popular items might interest');
    }
}
function TrackListPageProduct(IsSpecialProduct, ProductName, ParentCategoryName, IsWheelsLanding = "false", IsVehicleLanding = "false", IsCategoryGrid = "false", IsMPP = "false") {
    if (ParentCategoryName.toLowerCase() == "main category") {
        ParentCategoryName = "Lifestyle & Apparel";
    }
    if (IsSpecialProduct.toLowerCase() == "true") {
        if (ParentCategoryName == "search") {
            commonGA4Tracking('SPECIALS Search Page', ProductName, 'SPECIALS Search Page');
        } else if (IsWheelsLanding.toLowerCase() == "true") {
            commonGA4Tracking('SPECIALS Wheels Landing Page', ProductName, 'SPECIALS Wheels Landing Page');
        } else if (IsVehicleLanding.toLowerCase() == "true" && IsCategoryGrid.toLowerCase() != "true" && IsMPP.toLowerCase() != "true") {
            commonGA4Tracking('SPECIALS your vehicle Page - FEATURED PRODUCTS', ProductName, 'SPECIALS your vehicle Page - FEATURED PRODUCTS');
        } else if (IsVehicleLanding.toLowerCase() == "true" && IsCategoryGrid.toLowerCase() == "true") {
            commonGA4Tracking('SPECIALS Your vehicle Page - FEATURED CATEGORIES - ' + ParentCategoryName, ProductName, 'SPECIALS Your vehicle Page - FEATURED CATEGORIES - ' + ParentCategoryName);
        } else if (IsVehicleLanding.toLowerCase() == "true" && IsMPP.toLowerCase() == "true") {
            commonGA4Tracking('SPECIALS Your vehicle Page - M PERFORMANCE PARTS', ProductName, 'SPECIALS Your vehicle Page - M PERFORMANCE PARTS');
        }
        else {
            commonGA4Tracking('SPECIALS List Page - ' + ParentCategoryName, ProductName, 'SPECIALS List Page - ' + ParentCategoryName);
        }
    } else if (IsVehicleLanding.toLowerCase() == "true" && IsCategoryGrid.toLowerCase() != "true" && IsMPP.toLowerCase() != "true") {
        commonGA4Tracking('Your vehicle Page - FEATURED PRODUCTS', ProductName, 'Your vehicle Page - FEATURED PRODUCTS');
    } else if (IsVehicleLanding.toLowerCase() == "true" && IsCategoryGrid.toLowerCase() == "true") {
        commonGA4Tracking('Your vehicle Page - FEATURED CATEGORIES - ' + ParentCategoryName, ProductName, 'Your vehicle Page - FEATURED CATEGORIES - ' + ParentCategoryName);
    } else if (IsVehicleLanding.toLowerCase() == "true" && IsMPP.toLowerCase() == "true") {
        commonGA4Tracking('Your vehicle Page - M PERFORMANCE PARTS', ProductName, 'Your vehicle Page - M PERFORMANCE PARTS');
    }
}
$('.DivHOverview').click(function () {
    //$('.DivVehicleLandHNav').toggleClass('d-flex');
    $('.DivVehicleLandHNav').fadeToggle();
});
$('#Landmenuclose').click(function () {
    $('.DivVehicleLandHNav').fadeToggle();
});

function setYourVehicleVisualImage(PaintCode, PaintName) {
    $('#YourVehicleVisualImgLoader').addClass("d-block");
    $("#VehiclePaintColor").text(PaintName+" ");
    if (PaintName.toLowerCase().indexOf('metallic') > 0) {
        $("#VehiclePaintColor").append('<label>Metallic</label>');
    } else {
        $("#VehiclePaintColor").append('<label>Non-Metallic</label>');
    }
    var imgSrc = "/Images/VisualizerImage/ColorTheme/"+PaintCode + ".jpg";
    $('#dropdownMenuImgSrc').attr("src", imgSrc);
    var yourVehicleImgSrc = $('#hdnYourVehicleImgSrc').val();
    $.urlParam = function (name) {
        var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(yourVehicleImgSrc);
        return results[1] || 0;
    };
    var paint = $.urlParam('paint').toLowerCase();
    newYourVehicleImgSrc = yourVehicleImgSrc.toLowerCase().replace("paint=" + paint, "paint=" + PaintCode);
    $('#hdnYourVehicleImgSrc').val(newYourVehicleImgSrc);
    var tmpImg = new Image();
    tmpImg.src = newYourVehicleImgSrc;
    $(tmpImg).one('load', function () {
        orgWidth = tmpImg.width;
        orgHeight = tmpImg.height;
        if (orgHeight < 500 && orgWidth < 500) {
            newYourVehicleImgSrc = "/Images/VisualizerImage/Visualize_ImageDefault.png";
        }
        $('#YourVehicleImgSrc').attr("src", newYourVehicleImgSrc);
        $('#YourVehicleVisualImgLoader').removeClass("d-block");
        $('#YourVehicleVisualImgLoader').addClass("d-none");
    });
}
function rightToggleMenuActive() {
    $('#rightToggleMenu').addClass("active");
}

function selectYourBmw() { //home page model selection notification click 
    $("#select-your-bmw-pop").trigger("click");
    $('#rightToggleMenu').addClass("active");
    $("#OverlayRight").css("display", "block");
    //Disabling body scroll modelpopup is visible
    $('body').addClass('body-fixed');
    $('body').css('overflow-y', 'hidden');
    $('html').css('overflow', 'hidden');

}
$("#select-your-bmw-pop").click(function () {
    if ($('.DivNotification').hasClass("DivNotificationActive")) {
        $('.DivNotification').removeClass("DivNotificationActive");
        $('.DivoverlayRotate').addClass("d-none");
    }
});

function visualizeOptions(event, productId) {
    var keyValue = event.keyCode;
    if (keyValue == 13 && productId == 0) {
        $("#hdnEventValue").val(keyValue);
    }
    else if (keyValue == 13 && productId != 0) {
        $("#hdnValueVisualizer_" + productId).val(keyValue);
    }
}
function validateZipCode(zipcode) {
    var pattern = /^\d{5}([\-]\d{4})?$/;
    if (pattern.test(zipcode)) {
        return true;
    }
    return false;
}
function handleLastYearKeyDown(event) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        modelFlyEvent(event);
    }
}
function focusShoppablePoints(e, idValue) {
    var keyValue = e.keyCode;
    if (keyValue == 9) {
        if (idValue == 'pShoppableHead') {
            var divid = $(".DivPopPosition").find('div:first').attr('id');
            if (divid.indexOf('_2') > 0) {
                divid = divid.replace("_2", "");
                var arrayval = divid.split("_");
                var point = arrayval[1] + "_2";
                $(".DivPopPosition").find('div:first').addClass(point + "SecActive");
                $("." + point).addClass(point + "Hover");
            } else {
                var arrayval = divid.split("_");
                var point = arrayval[1];
                $(".DivPopPosition").find('div:first').addClass(point + "SecActive");
                $("." + point).addClass(point + "Hover");
            }
        }
        else {
            if (idValue.indexOf('_2') > 0) {
                var idValue = idValue.replace("_2", "");
                var arrayVal = idValue.split("_");
                var pointval = arrayVal[0].replace("adiv", "");
                var nextPoint = parseInt(pointval) + 1;
                var point = arrayVal[1]+"_2";
                var divid = "div" + pointval + "_" + point;
                $("#" + divid).removeClass(point + 'SecActive');
                $("." + point).removeClass(point + 'Hover');
                $('div[id^="div' + nextPoint + '"]').each(function () {
                    var nextDivId = $(this).attr('id');
                    var nextPointClass = nextDivId.replace("div" + nextPoint + "_", "");
                    $("#" + nextDivId).addClass(nextPointClass + 'SecActive');
                    $("." + nextPointClass).addClass(nextPointClass + 'Hover');
                });
            } else {
                var arrayVal = idValue.split("_");
                var pointval = arrayVal[0].replace("adiv", "");
                var nextPoint = parseInt(pointval) + 1;
                var point = arrayVal[1];
                var divid = "div" + pointval + "_" + point;
                $("#" + divid).removeClass(point + 'SecActive');
                $("." + point).removeClass(point + 'Hover');
                $('div[id^="div' + nextPoint + '"]').each(function () {
                    var nextDivId = $(this).attr('id');
                    var nextPointClass = nextDivId.replace("div" + nextPoint + "_", "");
                    $("#" + nextDivId).addClass(nextPointClass + 'SecActive');
                    $("." + nextPointClass).addClass(nextPointClass + 'Hover');
                });
            }


        }
    }
}
;

$(document).ready(function () {
    var ecode = $("#hdnModelEcode").val();
    var namodelcode = $("#hdnModelNAcode").val();
    var isShoppable = $("#hdnIsShoppable").val();
    if (isShoppable != "" && isShoppable != null && isShoppable != "undefined" && isShoppable.toLowerCase() == "true") {
        //loadShoppableView('G80', '22TN');
        loadShoppableView(ecode, namodelcode);
    }
});
function closeMenu(isRightMenu) {
    if (isRightMenu === 1) {
        $('.mobile-menu').removeClass('show');
        $(".mobile-menu.right-toggle").removeClass("active");
        $('#OverlayRight').css('display', 'none');
        $(this).addClass('show');
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow-y', 'auto');
        $(".year-list-overlay").remove('active');
        $('body').removeClass('body-fixed');
    }
    else if (isRightMenu === 2) {
        $('body').removeClass('body-fixed');
        $(".m-modal-fitment").removeClass("active");
    }
    else if (isRightMenu === 3 || isRightMenu === 4 || isRightMenu === 5) {
        $("#rightToggleMenu2").removeClass("show");
        $('#OverlayRight').css('display', 'none');
        $('body').removeClass('body-fixed');
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow-y', 'auto');
        $(".product-fitment").removeClass("active");
        $(".mobile-menu.right-toggle").removeClass("active");
    }
    else {
        $("#fitment-widget_t").removeClass('NavSub-fixed').addClass('NavSub-changed');
        $("#navMain").removeClass('Navbar-changed').addClass('Navbar-fixed');
    }
    $('#divYearId').css("display", "block");
    $('#divSeriesId').css("display", "none");
    $('#divModelId').css("display", "none");
    $('#divYourBMWId').css("display", "none");
    $('#year-listId').empty();
    $('#mbl-year-listId').empty();
    // window.location.reload(true);
}
function closeProductModelSelection() {
    $('.mobile-menu').removeClass('show');
    $('#OverlayRight').css('display', 'none');
    $(this).addClass('show');
    $('body').css('overflow', 'auto');
    $(".year-list-overlay").remove('active');
    $('#divYearId').css("display", "block");
    $('#divSeriesId').css("display", "none");
    $('#divModelId').css("display", "none");
    $('#divYourBMWId').css("display", "none");

}

$('.ModelDivDesktop').on('click', function (e) {
    $('#OverlayRight').toggle();
    if ($("#OverlayRight").is(':visible')) {
        $("#OverlayRight").css("display", "block");
        $('body').addClass('body-fixed');
        $('body').css('overflow-y', 'hidden');
        $('html').css('overflow', 'hidden');
    }
    else {
        $("#OverlayRight").css("display", "none");
        $('body').removeClass('body-fixed');
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow-y', 'auto');
    }
});

$(".ModelSelection").click(function () {
    $("#mobileMenu").removeClass("show");
    $('#divHeaderBodyOverlay').css('display', 'none');
    $("#nav-icon1").removeClass('open');
});
$('.ModelSelection').on('click', function (e) {
    $('#OverlayRight').toggle();
    if ($("#OverlayRight").is(':visible')) {
        $("#OverlayRight").css("display", "block");
        $('body').addClass('body-fixed');
        $('body').css('overflow-y', 'hidden');
        $('html').css('overflow', 'hidden');
    }
    else {
        $("#OverlayRight").css("display", "none");
        $('body').removeClass('body-fixed');
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow-y', 'auto');
    }
});

function ShowPopup() {
    $('#fitment-popup').modal('show');
}
function ShowMoreYear() {
    $("#year-list-overlay-Id").addClass("active");
    $("#year-list-overlay-Id-mb").addClass("active");
    $('#divShowMoreYears').css("display", "none");
    $('#divShowMoreYears-mobile').css("display", "none");
    $(".showMore").css("display", "none");
}
function ShowPopupForShowMoreYear() {
    $('#fitment-popup').modal('show');
    $('#divShowMoreYears').css("display", "block");
}
//right menu
function clearRightMenu() {
    $('#divYearId').css("display", "block");
    $('#divSeriesId').css("display", "none");
    $('#divModelId').css("display", "none");
    if (document.getElementById("hdnModelName")) {
        var modelName = document.getElementById("hdnModelName").value;
        if (modelName == "" || modelName == "undefined") {
            $('#divYourBMWId').css("display", "none");
        }
    }
    //flowcode change
    var IsSelectedModelShoppable = "";
    IsSelectedModelShoppable = $("#hdnIsSelectedModelShoppable").val();
    if (IsSelectedModelShoppable != "" && IsSelectedModelShoppable != null && IsSelectedModelShoppable != "undefined" && IsSelectedModelShoppable.toLowerCase() == "false") {
        $(".NoShopimg").removeClass("d-none");
    }
}

function ClearPopUp() {
    $("#fitment-widget_t").removeClass('NavSub-fixed').addClass('NavSub-changed');
    $("#navMain").removeClass('Navbar-changed').addClass('Navbar-fixed');
    //Category navigation
    if ($('[id^=navSub]').css('right', '-1px')) {
        $('[id^=navSub]').css('right', '-418px');
    }
    if ($('[id^=navTertiary]').css('right', '-1px')) {
        $('[id^=navTertiary]').css('right', '-418px');
    }
    if ($('[id^=navDark]').css('right', '-1px')) {
        $('[id^=navDark]').css('right', '-418px');
        $(".mobile-menu").removeClass('theme-dark');
    }

    if ($("#mobileMenu").hasClass('active')) {
        $("#mobileMenu").removeClass('show');
    }
    else {
        $("#mobileMenu").addClass('show');
        $('#divHeaderBodyOverlay').css('display', 'block');
    }

}

function closeRightTagMenu() {
    window.location.reload(true);
    $("#rightToggleMenu2").removeClass("show");
    $('#OverlayRight').css('display', 'none');
}
function closeMenuWithReload(isRightMenu) {
    closeMenu(isRightMenu);
    window.location.reload(true);
}
function changePopup() {
    $("#OverlayRight").css("display", "none");
    $('#fitment-popup').modal('show');
}

$("#OverlayRight").click(function () {
    var modelName = document.getElementById("hdnModelName").value;
    var url = window.location.href.toLowerCase();
    if (url.indexOf('/bmw-flowcode') < 0 || (url.indexOf('/bmw-flowcode') > 0 && modelName != "" && modelName != null && modelName != undefined)) {
        $("#rightToggleMenu").removeClass("show");
        $("#rightToggleMenu2").removeClass("show");
        $('#OverlayRight').css('display', 'none');
        $('body').removeClass('body-fixed');
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow-y', 'auto');
        $('#year-listId').empty();
        $('#mbl-year-listId').empty();
        if (document.getElementById("hdnReload"))
            window.location.reload(true);
        else {
            if (modelName !== "") {
                var divSelectBMW = document.getElementById("sel-bmwId").textContent;
                if (divSelectBMW.includes(modelName) === false) {
                    window.location.reload(true);
                }
            }
        }
    }
});
$("#divHeaderBodyOverlay").click(function () {
    if (document.getElementById("hdnReload"))
        window.location.reload(true);
    else {
        if (document.getElementById("hdnModelName")) {
            var modelName = document.getElementById("hdnModelName").value;
            if (modelName !== "") {
                var divSelectBMW = document.getElementById("sel-bmwId").textContent;
                if (divSelectBMW.includes(modelName) === false) {
                    window.location.reload(true);
                }
            }
        }
    }
});
function ShowModelpopUpforTags() {
    $("#rightToggleMenu2").addClass("show");
}

function hideModelPopupOnAddtoCart(isRightMenu) {
    closeMenu(isRightMenu);
    window.location.reload(true);
    $('#btnAddToCart').click();
}
$('#divHeaderBodyOverlay').click(function () {
    $('#year-listId').empty();
    $('#mbl-year-listId').empty();
});

function changeModelId(IsMenu, mId) {
    if (document.getElementById("hdnModelName")) {
        var modelName = document.getElementById("hdnModelName").value;
        if (modelName !== "") {
            var divSelectBMW = document.getElementById("sel-bmwId").textContent;
            if (divSelectBMW.includes(modelName) === false) {
                $("#sel-bmwId").find('a').attr('href', "VehicleSelector/GetYourBMW?isMenu=" + IsMenu + "&modelId=" + mId + "&isModelPage=false");
            }
        }
    }
}

//Wheels landing vehicle selector

function modelSelected(IsMenu, mId) {
    $(".ModelSelectedImg").addClass('ModelSelectedImgToggle');
    $(".WhModelSel").addClass('WhModelSelHeight');
    $("#WhModelH").addClass('d-none');
    $("#WhModelSelected").removeClass('d-none');

    $("#selected-model-image").removeClass('d-none');

    $("#shopWheelsModel").removeClass('d-none');
    $("#WhSecModelSelected").removeClass('d-none');
    $("#overview").addClass('d-none');

    if (document.getElementById("hdnModelName")) {
        var modelName = document.getElementById("hdnModelName").value;
        var modelnameUpdated = document.getElementById("hdnModelNameUpdated").value;
        if (modelName != "" && modelnameUpdated != "" && modelName != "undefined" && modelnameUpdated != "undefined") {
            if (modelName === modelnameUpdated) {

            }
            else {
                modelName = modelnameUpdated;
            }
        }

        if (modelName !== "") {
            var divSelectBMW = document.getElementById("sel-bmwId").textContent;
            if (divSelectBMW.includes(modelName) === false) {
                $("#sel-bmwId").find('a').attr('href', "/VehicleSelector/GetYourBMW?isMenu=1&modelId=" + mId + "&isModelPage=true");
                
            }
        }
    }
    //adjustHeight();
    getDivHeight();
    var modelImageHeight = $("#selected-model-image").height();
    $("#modelList").css("height", modelImageHeight);

    $("#DivWheelModelCon").addClass('DivWheelModelConActive');
    var selectedWheelsHeight = $("#DivWheelModelCon").height();
    $("#WhMainSec").css("height", selectedWheelsHeight);

}
function seeMore() {
    $("#hdnChangeModel").val('true');
    $("#divShowMoreYears").addClass('d-none');
    //getDivHeight();
    getDivHeightYear();
}


$('.WhYearsel').click(function () {
    $(".WhYearBlk").addClass('whYearHideMain');
    $(".WhSeriBlk").addClass('WhSerHideMain');
    $(".HidePointSeries").addClass('d-none');
    $(".WhSerHide").addClass('d-flex');
});
//changeBm
$('#WhChangeModel').click(function () {
    changeBmWheel();
});

function getDivHeight() {
    var showheight = 0;
    var seriesHeight = 0;
    var modelHeight = 0;
    var isMobile = false;
    if (navigator.userAgent.toLowerCase().indexOf("mobile") > -1) {
        isMobile = true;
    }

    if ($(".divShowMoreYears").hasClass('d-none')) {
        showheight = $('.MoreYear').height();
    }
    if ($(".WhSeriBlk").hasClass('WhSerHideMain')) {
        seriesHeight = $('.WhSerHide').height();
    }
    if ($(".WhModelBlk").hasClass('whModelHideMain')) {
        modelHeight = $('.WhModelList').height();
        modelHeight = modelHeight + 50;
    }
    var totalheight = 0;
    totalheight = showheight > seriesHeight ? (showheight > modelHeight ? showheight : modelHeight) : (seriesHeight > modelHeight ? seriesHeight : modelHeight);
    totalheight = totalheight + 70;
    var currentHeight = 0;
    var selHeight = 0;
    currentHeight = $('.WhModelSelHeight').height();
    selHeight = $('.WhModelSel').height();
    currentHeight = currentHeight > selHeight ? currentHeight : selHeight;
    if (totalheight > 170) {
        if ($("#modelList").hasClass('WhModelSelHeight')) {
            $(".WhModelSelHeight").css("height", totalheight);
        }
        else {
            $(".WhModelSel").css("height", totalheight);
        }
    }
    else if (currentHeight > 240) {
        if ($("#modelList").hasClass('WhModelSelHeight')) {
            $(".WhModelSelHeight").css("height", 240);
        }
        else {
            $(".WhModelSel").css("height", 250);
        }
    }
    else if (isMobile) {
        var selectedWheelsHeight = $("#DivWheelModelCon").height();
        if (selectedWheelsHeight > 240) {
            $("#WhMainSec").css("height", selectedWheelsHeight);
        }
    }

}


$(window).scroll(function () {
    var pathname = window.location.pathname.toLowerCase();
    if (pathname.indexOf("/wheels-and-tires/overview") > -1) {
        getDivHeight();
    }
});


//previous click to year after selecting series or model
function getDivHeightYear() {
    var showheight = 0;
    showheight = $('.MoreYear').height();
    showheight = showheight + 40;
    if (showheight > 240) {
        if ($("#modelList").hasClass('WhModelSelHeight')) {
            $(".WhModelSelHeight").css("height", showheight);
        }
        else {
            $(".WhModelSel").css("height", showheight);
        }
    }
}
function changeBmWheel() {
    $("#hdnChangeModel").val('true');
    $(".ModelSelectedImg").removeClass('ModelSelectedImgToggle');
    $(".WhModelSel").removeClass('WhModelSelHeight');
    $(".WhModelH").removeClass('d-none');
    $(".WhModelSelected").addClass('d-none');
    $("#selected-model-image").addClass('d-none');


    $(".WhSeriList").removeClass('whSeriesHideMain');
    $(".WhSerHide").removeClass('d-flex');
    $(".HidePoint").removeClass('d-none');
    $(".Whtxt1").removeClass('d-none');
    $(".Whtxt2").removeClass('d-block');
    $(".WhModelBlk").removeClass('whModelHideMain');
    $("#idModelt2").removeClass('Modelt2');
    $(".Modelt1").removeClass('d-none');

    $(".WhYearBlk").removeClass('whYearHideMain');
    $(".WhSeriBlk").removeClass('WhSerHideMain');
    $(".HidePointSeries").removeClass('d-none');
    $(".WhSerHide").removeClass('d-flex');
}

//function adjustHeight() {
//    var selHeight = $(".WhModelSelected").height();

//    if (selHeight > 0) {
//        $('.WhModelHead').css("height", selHeight);
//    }
//    else {
//        $('.WhModelHead').css("height", 97);
//    }
//}

$(function () {
    $(window).resize(
        function () {
            //adjustHeight();
            var vehicleSelect = "";
            vehicleSelect = $("#hdnModelName").val();
            var modelnameUpdated = $("#hdnModelNameUpdated").val();
            if (vehicleSelect != "" && modelnameUpdated != "" && vehicleSelect != "undefined" && modelnameUpdated != "undefined") {
                if (vehicleSelect === modelnameUpdated) {

                }
                else {
                    vehicleSelect = modelnameUpdated;
                }
            }
            var chnageModel = $("#hdnChangeModel").val();
            if (vehicleSelect != "" && vehicleSelect != undefined && chnageModel != 'true') {
                var selectedWheelsHeight = $("#DivWheelModelCon").height();
                $("#WhMainSec").css("height", selectedWheelsHeight);
            }
            else {
                var yearHeight = $('.WhYearBlk').height();
                $(".WhModelSel").css("height", yearHeight);
            }
        });
});

function loadShoppableView(modelEcode,naModelCode) {
    var params = { ecode: modelEcode, naModelCode: naModelCode};
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.VehicleSelector.GetShoppableImagePoints, data: params }, {
        complete: function (json) {
            if (json.responseJSON != null) {
                $("#divShoppable").html(json.responseJSON);
            }
        }
    }));
}


function loadTopCategories() {
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.VehicleLanding.GetTopCategories, data: { isVehicleLanding: "true" } }, {
        complete: function (json) {
            if (json.responseJSON !== null) {
                $("#divTopCategories").html(json.responseJSON);
                if (window.matchMedia("(min-width: 360px)").matches) {
                    $(function () {
                        var menu = $(".TabMainDiv .nav-tabs");
                        var indicator = $('<span class="indicator"></span>');
                        menu.append(indicator);
                        position_indicator(menu.find("a.active"));
                        setTimeout(function () { indicator.css("opacity", 1); }, 1000);
                        menu.find("a").mouseenter(function () {
                            position_indicator($(this));
                        });
                        menu.find("a").mouseleave(function () {
                            position_indicator(menu.find("a.active"));
                        });

                        function position_indicator(ele) {
                            var left = 0;
                            var width = 0;
                            if (ele.length > 0) {
                                left = ele.position().left;
                                width = ele.width();
                            }

                            indicator.stop().animate({
                                left: left,
                                width: width
                            });
                        }
                    });
                }
            }

        }
    }));
}

var interiorPageNum = 0;
var exteriorPageNum = 0;
var wheelsPageNum = 0;
var generalPageNum = 0;
var lifestylePageNum = 0;
var counter = 0;
function loadCategoryProducts(parentCategoryName, categoryName, divName, sortField, category, isLoadMore,isTab,event) { 

    var actionUrl = BMWAjax.Urls.VehicleLanding.GetAccCategoryProducts;
    var pageLimit = 0;
    var pageNum = 0;
    //pageNumber
    var pageNumLifestyle = $("#hdnLifestylePageNum").val();
    var pageNumExterior = $("#hdnExteriorPageNum").val();
    var pageNumInterior = $("#hdnInteriorPageNum").val();
    var pageNumWheels = $("#hdnWheelsPageNum").val();
    var pageNumGeneral = $("#hdnGeneralPageNum").val();
    //Sortfield
    var sortLifestyle = $("#hdnLifestyleSort").val();
    var sortExteriror = $("#hdnExteriorSort").val();
    var sortInterior = $("#hdnInteriorSort").val();
    var sortWheels = $("#hdnWheelsSort").val();
    var sortGeneral = $("#hdnGeneralSort").val();

    if (window.matchMedia("(max-width: 767px)").matches) {
        pageLimit = 4;
    }
    else if (window.matchMedia("(min-width: 768px)").matches && window.matchMedia("(max-width: 1999px)").matches) {
        pageLimit = 5;
    }
    else if (window.matchMedia("(min-width: 2000px)").matches) {
        pageLimit = 6;
    }

    if (parentCategoryName != undefined && parentCategoryName != "") {
        if (parentCategoryName.toUpperCase() == "BMW M PERFORMANCE") {
            actionUrl = BMWAjax.Urls.VehicleLanding.GetMPPProducts;
        }
    }
    if ((categoryName != undefined && categoryName != "" && categoryName.toUpperCase() == "LIFESTYLE") || (parentCategoryName != undefined && parentCategoryName != "" && parentCategoryName.toUpperCase() == "MAIN CATEGORY")
        || (category != undefined && category != "" && !(divName != undefined && divName != "") && category.toUpperCase() == "LIFESTYLE")) {

        $("#Main-Category").addClass("d-none"); //hiding loadmore button during Loading
        divName = "divLifestyleProducts";
        if (parentCategoryName != undefined && parentCategoryName != "" && parentCategoryName.toLowerCase()=="main category" && categoryName == "") {
            //ALL click in subcategories section
            categoryName = "overview";
        }
        if (pageNumLifestyle != undefined && pageNumLifestyle != "" && isLoadMore) {
            pageNumLifestyle++;
            pageNum = pageNumLifestyle;
        }
        else if ((pageNumLifestyle == undefined || pageNumLifestyle == "") && isLoadMore ) {
            pageNumLifestyle = 0;
            pageNumLifestyle++;
            pageNum = pageNumLifestyle;
        }
        if ((sortField == undefined || sortField == "") && isLoadMore) {
            sortField = sortLifestyle;
        }
    }
    if (category != undefined && category != "" && !(divName != undefined && divName != "")) {
        if (category.toUpperCase() == "EXTERIOR STYLE") {
            $("#Exterior").addClass("d-none");
            divName = "divExteriorProducts";
            if (pageNumExterior != undefined && pageNumExterior != "" && isLoadMore) {
                pageNumExterior++;
                pageNum = pageNumExterior;
            }
            else if ((pageNumExterior == undefined || pageNumExterior == "") && isLoadMore) {
                pageNumExterior = 0;
                pageNumExterior++;
                pageNum = pageNumExterior;
            }
            if ((sortField == undefined || sortField == "") && isLoadMore) {
                sortField = sortExteriror;
            }
        }
        else if (category.toUpperCase() == "INTERIOR DESIGN" || category.toUpperCase() == "INTERIOR") {
            $("#Interior").addClass("d-none");
            divName = "divInteriorProducts";
            if (pageNumInterior != undefined && pageNumInterior != "" && isLoadMore) {
                pageNumInterior++;
                pageNum = pageNumInterior;
            }
            else if ((pageNumInterior == undefined || pageNumInterior == "") && isLoadMore) {
                pageNumInterior = 0;
                pageNumInterior++;
                pageNum = pageNumInterior;
            }
            if ((sortField == undefined || sortField == "") && isLoadMore) {
                sortField = sortInterior;
            }
        }
        else if (category.toUpperCase() == "WHEEL ACCESSORIES") {
            $("#Wheels-and-Wheel-Accessories").addClass("d-none");
            divName = "divWheelProducts";
            if (pageNumWheels != undefined && pageNumWheels != "" && isLoadMore) {
                pageNumWheels++;
                pageNum = pageNumWheels;
            }
            else if ((pageNumWheels == undefined || pageNumWheels == "") && isLoadMore) {
                pageNumWheels = 0;
                pageNumWheels++;
                pageNum = pageNumWheels;
            }
            if ((sortField == undefined || sortField == "") && isLoadMore) {
                sortField = sortWheels;
            }
        }
        else if (category.toUpperCase() == "GENERAL") {
            $("#General").addClass("d-none");
            divName = "divGeneralProducts";
            if (pageNumGeneral != undefined && pageNumGeneral != "" && isLoadMore) {
                pageNumGeneral++;
                pageNum = pageNumGeneral;
            }
            else if ((pageNumGeneral == undefined || pageNumGeneral == "") && isLoadMore) {
                pageNumGeneral = 0;
                pageNumGeneral++;
                pageNum = pageNumGeneral;
            }
            if ((sortField == undefined || sortField == "") && isLoadMore) {
                sortField = sortGeneral;
            }
        }
    }
    var displayedProdCount = 0;
    displayedProdCount = $("#" + divName + ' > div.DivInteriorProductsGrid').find("div.DivInteriorProSlider").length;
   
    if (isLoadMore) {
        var params = { parentCategoryName: parentCategoryName, categoryName: categoryName, sortField: sortField, pageNum: pageNum, pageLimit: pageLimit, isLoadMore: isLoadMore };
    }
    else if (divName == "divMPerformanceProducts" || divName == "divMPerformProducts"){
        var params = { parentCategoryName: parentCategoryName, categoryName: categoryName, sortField: sortField, isVehicleLanding: true };
    }
    else {
        var params = { parentCategoryName: parentCategoryName, categoryName: categoryName, sortField: sortField, pageNum: pageNum, pageLimit: pageLimit };
    }
    $("#" + divName + ' > div.DivInteriorProductsGrid').find("#loader_div").addClass('d-block');
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: actionUrl, data: params }, {
        complete: function (json) {
            if (json.responseJSON !== null) {
                if (isLoadMore != undefined && isLoadMore) {
                    $("#" + divName + ' > div.DivInteriorProductsGrid').append(json.responseJSON);
                    if (divName == "divInteriorProducts") {
                        $("#hdnInteriorPageNum").val(pageNum);
                    }
                    else if (divName == "divExteriorProducts") {
                        $("#hdnExteriorPageNum").val(pageNum);
                    }
                    else if (divName == "divWheelProducts") {
                        $("#hdnWheelsPageNum").val(pageNum);
                    }
                    else if (divName == "divGeneralProducts") {
                        $("#hdnGeneralPageNum").val(pageNum);
                    }
                    else if (divName == "divLifestyleProducts") {
                        $("#hdnLifestylePageNum").val(pageNum);
                    }
                }
                else {
                    $("#" + divName).html(json.responseJSON);
                    //initial loader
                    if (divName == "divInteriorProducts") {
                        counter++;
                    }
                    else if (divName == "divExteriorProducts") {
                        counter++;
                    }
                    else if (divName == "divWheelProducts") {
                        counter++;
                    }
                    else if (divName == "divGeneralProducts") {
                        counter++;
                    }
                    
                }
                setColorVisibilityOnMouseOver();
            }
            loadMoreCategoryButtonLoading(displayedProdCount, isLoadMore, divName);
            $("#" + divName + ' > div.DivInteriorProductsGrid').find("#loader_div").removeClass('d-block');
            if (isTab) {
                var productcount = displayedProdCount + 1;
                $("#" + divName + ' > div.DivInteriorProductsGrid').find("#product_" + productcount).focus();
                event.preventDefault();
            }
            if (counter == 4 && !$("#featuredCatgLoader").hasClass('d-none')) {
                $("#featuredCatgLoader").addClass('d-none');
            }
        }
    }));
}

function loadFeaturedProducts(parentCategoryName, categoryName, divName, sortField, isVehicleLanding) {
    var actionUrl = BMWAjax.Urls.VehicleLanding.GetFeaturedProducts;
    var params = { parentCategoryName: parentCategoryName, categoryName: categoryName, sortField: sortField, isVehicleLanding: isVehicleLanding };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: actionUrl, data: params }, {
        complete: function (json) {
            if (json.responseJSON !== null) {
                $("#" + divName).html(json.responseJSON);
            }
            setColorVisibilityOnMouseOver();
        }
    }));

}

function loadMoreCategoryButtonLoading(displayedProdCount, isLoadMore, divName) {
    var countLifestyle = $("#hdnLifestyleProdCount").val();
    var countExteriror = $("#hdnExteriorProd").val();
    var countInterior = $("#hdnInteriorProd").val();
    var countWheels = $("#hdnWheelsProd").val();
    var countGeneral = $("#hdnGeneralProd").val();
    var countLimit = 0;
    if (window.matchMedia("(max-width: 767px)").matches) {
        countLimit = 4;
    }
    else if (window.matchMedia("(min-width: 768px)").matches && window.matchMedia("(max-width: 1999px)").matches) {
        countLimit = 5;
    }
    else if (window.matchMedia("(min-width: 2000px)").matches) {
        countLimit = 6;
    }

    if (displayedProdCount != undefined && displayedProdCount != 0 && isLoadMore != undefined) {
        countLimit = displayedProdCount + countLimit;
    }
    else if (isLoadMore == undefined) {// in sorting count will be as initial loading
        displayedProdCount = countLimit;
    }

    if (countLifestyle != undefined && divName == "divLifestyleProducts") {
        if (countLifestyle > countLimit && countLifestyle > displayedProdCount) {
            $("#Main-Category").removeClass("d-none");
        }
        else if (!$("#Main-Category").hasClass("d-none")) {
            $("#Main-Category").addClass("d-none");
        }
    }
    if (countExteriror != undefined && divName == "divExteriorProducts") {
        if (countExteriror > countLimit && countExteriror > displayedProdCount) {
            $("#Exterior").removeClass("d-none");
        }
        else if (!$("#Exterior").hasClass("d-none")) {
            $("#Exterior").addClass("d-none");
        }
    }
    if (countInterior != undefined && divName == "divInteriorProducts") {
        if (countInterior > countLimit && countInterior > displayedProdCount) {
            $("#Interior").removeClass("d-none");
        }
        else if (!$("#Interior").hasClass("d-none")) {
            $("#Interior").addClass("d-none");
        }
    }
    if (countWheels != undefined && divName == "divWheelProducts") {
        if (countWheels > countLimit && countWheels > displayedProdCount) {
            $("#Wheels-and-Wheel-Accessories").removeClass("d-none");
        }
        else if (!$("#Wheels-and-Wheel-Accessories").hasClass("d-none")) {
            $("#Wheels-and-Wheel-Accessories").addClass("d-none");
        }
    }
    if (countGeneral != undefined && divName == "divGeneralProducts") {
        if (countGeneral > countLimit && countGeneral > displayedProdCount) {
            $("#General").removeClass("d-none");
        }
        else if (!$("#General").hasClass("d-none")) {
            $("#General").addClass("d-none");
        }
    }
}

function focustoFeatured(event, count) {
    var keyValue = event.keyCode;
    if (keyValue == 9) {
        if (window.location.href.toLowerCase().indexOf("/yourvehicle") && count == 4) {
            $("#featuredProducts").focus();
            event.preventDefault();
        }
        if (window.location.href.toLowerCase().indexOf("/wheels-and-tires/overview") > -1 && count == 3) {
            $("#aWheelTire").focus();
            event.preventDefault();
        }
    }
}

function loadmoreCategoryProducts(event, parentCategoryName, categoryName, divName, sortField, category, isLoadMore) {
    if (event.keyCode == 13) {
        var isTab = true;
        loadCategoryProducts(parentCategoryName, categoryName, divName, sortField, category, isLoadMore,isTab,event);
        event.preventDefault();
    }
}

function setYourVehicleColor(event) {
    //if (event.keyCode == 13) {
    //    $("#dropMenuShow").addClass('show');
    //    if ($("#dropMenuShow").hasClass('show')) {
    //        $('.ColorDrop').find('a:first').focus();
    //        event.preventDefault();
    //    }
    //}
    //else 
    if (event.keyCode == 9) {
        if ($("#dropMenuShow").hasClass('show')) {
            $('.ColorDrop').find('a:first').focus();
            event.preventDefault(); 
        }
        
    }
}
;
$(document).ready(function () {
    $('.DealerInfo').on('click', function () {
        //$('#divHeaderBodyOverlay').css('display', 'none');
        $('#dealerOverlay').css('display', 'none');
        $(".mobile-menu-dealer-search").removeClass("active");
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow', '');
        closeDealerPopUp();
    });
    $("#searchQuery").val("");

    $('#divMotorSportsDealerList .motorsports-dealer-div').on('click', function () {
        $('#hdnMotorSportsDealerId').val($(this).data('id'));
    });

    $('.dealer-selector').on('click', function (e) {
        $('.mobile-menu-dealer-search').addClass("active");
        e.preventDefault();
    });
    $('#divHeaderBodyOverlay').click(function () {
        $(".mobile-menu-dealer-search").removeClass("active");
    });
    $('#dealerOverlay').click(function () {
        $(".mobile-menu-dealer-search").removeClass("active");
        $('#dealerOverlay').css('display', 'none');
        visDealerPopUp();
    });
});

$('.SelectedDealerLarge .dealer-overlay').on('click', function (e) {
    $('.mobile-menu-dealer-search').addClass("active");
    e.preventDefault();
});
$('#dealerOverlay, #dealerClosepopup').click(function () {
    $(".mobile-menu-dealer-search").removeClass("active");
});

function getUserLocation() {

    var options = {
        enableHighAccuracy: true,
        timeout: 2000,
        maximumAge: 1000
    };
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, positionError, options);
    }
}
function showPosition(position) {
    var coordinates = position.coords;

    var args = { latitude : coordinates.latitude, longitude : coordinates.longitude };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.DealerLocator.GetZipcode, data: args }, {
        complete: function (json) {
            if (json.responseJSON !== null && json.responseJSON[1] === "true") {
                var zip = json.responseJSON[0];
                $('[id$=lblsearchQuery]').hide();
                document.getElementById("searchQuery").value = zip;      
                $("#frmDealerSearch").submit();  // calling lookup button submit 
            }
        }
    }));
}

function positionError(error) {
    //var msg = "some other error";
    //switch (error.code) {
    //    case error.PERMISSION_DENIED:
    //        msg = "User denied the request for Geolocation.";
    //        break;
    //    case error.POSITION_UNAVAILABLE:
    //        msg = "Location information is unavailable.";
    //        break;
    //    case error.TIMEOUT:
    //        msg = "The request to get user location timed out.";
    //        break;
    //    case error.UNKNOWN_ERROR:
    //        msg = "An unknown error occurred.";
    //        break;
    //}
            $("#searchQuery").val("");
            $("#searchQuery").addClass("InvalidSearch");
            $("#searchQuery").css({ borderColor: "red" });
            $("#dealer_noresult").remove();
            $("#dealer_result").remove();
            $('#commentsId').text('');
            $("#location_resultsId").show();

}

var dealerHtml = "";
function closeDealerPopUp() {
    if (dealerHtml != "") {
        document.getElementById("dealer-locator-results").innerHTML = dealerHtml;
    }
    $("#dealerSearchQueryResult .dropdown-menu").removeClass('show');
    $("#dealerSearch").removeClass('hide');
    $("#dealer_noresult").remove();
    document.getElementById("location_resultsId").style.display = "none";
    $("#searchQuery").val("");
    $("#searchQuery").removeClass("InvalidSearch");
    $("#searchQuery").css({ borderColor: "" });
    $('#dealerOverlay').css('display', 'none');
    //$('#divHeaderBodyOverlay').css('display', 'none');
    if (!$("#searchQuery").is(":focus")) {
        $("#lblsearchQuery").removeClass("input-not-empty");
    }
    $("#dealer-locator-results").removeClass("Boxshadow");
    //$('body').removeClass('body-fixed');
    $('body').css('overflow-y', 'auto');
    $('html').css('overflow', '');

    $('body').addClass('body-fixed');
    //$('body').css('overflow-y', 'hidden');
    //$('html').css('overflow', 'hidden');
    $('.DealerEditicon').removeClass('todealerselect');

    if (!($("#mobileMenu").hasClass('active'))) {
        $('#divHeaderBodyOverlay').css('display', 'none');
        $('body').removeClass('body-fixed');
        $('body').css('overflow-y', 'auto');
        $('html').css('overflow', '');
    }

    //Dealer popup should not closed without selecting dealer
    visDealerPopUp();
 }

function validateDealerLookup() {
    if (dealerHtml == "") {
        dealerHtml = document.getElementById("dealer-locator-results").innerHTML;
    }
    var dealerLookup = $("#searchQuery").val();
    if (dealerLookup == null || dealerLookup == "") {
        $("#searchQuery").addClass("InvalidSearch");
        $("#searchQuery").css({ borderColor: "red" });
        document.getElementById("location_resultsId").style.display = "none";
        return false;
    }
    else {
        $("#searchQuery").removeClass("InvalidSearch");
        $("#searchQuery").css({ borderColor: "" });
        document.getElementById("location_resultsId").style.display = "none";
        commonGA4Tracking('ShopDealerLocator', 'Global DealerLocator-Search - ' + dealerLookup, 'Dealer Locator Search Button click ' );
        
    }
} 

$('#divMotorSportsDealerList .Divdealer').click(function () {
    $('#btnSetDealer').show();
    $('#divMotorSportsDealerList .Divdealer').each(function (index) {
        $(this).removeClass('MtrActive');
    });
    $(this).addClass('MtrActive');
    $($(this).find('input[type=radio]')[0]).prop('checked', true);
});

function validateMotorSportsDealer() {
    if ($("#hdnMotorSportsDealerId").val() == "") {
        event.preventDefault();
    }
}

function cartAlert(event,count) {
    var hdnCartCount = $("#hdnCartCount").val();
    var hdnDealer = $("#hdnDealerId").val();
    if (hdnDealer != "" && hdnCartCount > 0) {
        $("#dealer_result").find('form  .DivChangeDealer').eq(count-1).removeClass('d-none');
        event.preventDefault();
    }
}

function cartAlertMessage() {
    $('.DivChangeDealer').addClass('d-none');
}

//Dealer popup should not closed without selecting dealer
function visDealerPopUp() {
    var isVisualizer = $("#hdnPageTitle").val();
    if (isVisualizer == "ProductVisualizer") {
        var dealerVisualizer = $("#hdnDealerIdVisualizer").val();
        var dealerId = $("#hdnDealerId").val();
        if ((dealerVisualizer == null || dealerVisualizer == 0 || dealerVisualizer == undefined) && (dealerId == null || dealerId == 0 || dealerId == undefined)) {
            var link = document.getElementById('locateDealerClick');
            link.click();
            $("#dealerClosepopup").addClass("d-none");
        }
    }
}
function dealerSearchQuery(e) {
    var keyValue = e.keyCode;
    $('#hdnSearchCenterId').val('');
    var args = { searchQuery: $("#searchQuery").val() };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.DealerLocator.GetDealerSearchQueryResult, data: args }, {
        complete: function (json) {
            var result = json.responseJSON;
            if (result !== null && result.length > 0 && keyValue != 13) {
                $("#dealerSearchQueryResult .dropdown-menu").addClass('show');
                $("#dealerSearchQueryResult .dropdown-menu").empty();
                var text = "";
                for (var key in result) {
                    var dealerName = result[key].Name;
                    var dealerId = result[key].Id;
                    var CenterId = result[key].CenterId;
                    text += "<a tabindex='0' class='dropdown-item' onclick='GetTypeAheadDealer(\"" + dealerId + '","' + CenterId + "\")' id='dealerSearchId_" + dealerId + "'>" + dealerName + "</a>";
                }
                $("#dealerSearchQueryResult .dropdown-menu").append(text);
            }
            else {
                $("#dealerSearchQueryResult .dropdown-menu").removeClass('show');
            }
        }
    }));
}
function GetTypeAheadDealer(dealerId, CenterId) {
    var searchQueryDealerName = $("#dealerSearchId_" + dealerId).text();
    $("#dealerSearchId_" + dealerId).focus();
    $('#hdnSearchCenterId').val(CenterId);
    $('#searchQuery').val(searchQueryDealerName);
    $('#dealerSearchSubmit').click();
}
$('#dealerSearchSubmit').click(function () {
    $("#dealerSearchQueryResult .dropdown-menu").removeClass('show');
});
$("#searchQuery").focus(function () {
    $("#lblsearchQuery").addClass("input-not-empty");
});
function dealerSearchQueryEvent(e) {
    var keyValue = e.keyCode;
    if (keyValue == 9) {
        if ($("#dealerSearchQueryResult .dropdown-menu").hasClass('show')) {
            focusPopup(event, 'dealerSearchQueryEvent');
        }
    }
}
function isAlphaNum(e) {
    // Define a regular expression pattern to match special characters except comma, period, ampersand, and space
    var specialCharsPattern = /^[0-9a-zA-Z,&.\s]+$/;
    var keyValue = String.fromCharCode(e.keyCode || e.charCode);
    var allowedChars = specialCharsPattern.test(keyValue);
    if (allowedChars)
         return true;
    else
        return false;
}
var inputField = document.getElementById('searchQuery');
var searchInputField = document.getElementById('txtBxSearch');
if (inputField != null) {
    inputField.addEventListener('paste', handlepaste('dealerSearch'));
    inputField.addEventListener('input', function (event) {
        const inputValue = event.target.value;
        var specialCharsPattern = /^[0-9a-zA-Z,&.\s]+$/;
        var containsSpecialChars = specialCharsPattern.test(inputValue);
        if (!containsSpecialChars) {
            document.getElementById('searchQuery').innerText = "";
            $("#searchQuery").val("");
            $("#searchQuery").addClass("InvalidSearch");
            $("#searchQuery").css({ borderColor: "red" });
            document.getElementById("location_resultsId").style.display = "none";
            event.preventDefault();
        }
    });
}
if (searchInputField != null) {
    searchInputField.addEventListener('paste', handleSearchpaste('search'));
    searchInputField.addEventListener('input', function (event) {
        const inputValue = event.target.value;
        const specialCharsPattern = /^[-,.()/"':*\n\t\sA-Za-z0-9]+$/;
        var containsSpecialChars = specialCharsPattern.test(inputValue);
        if (!containsSpecialChars) {
            $("#txtBxSearch").val("");
            document.getElementById('txtBxSearch').innerText = "";
            event.preventDefault();
        }
    });
}
function handlepaste(pageInfo) {
    return function (event) {
        // Define a regular expression pattern to match special characters except comma, period, ampersand, and space
        var specialCharsPattern = /^[0-9a-zA-Z,&.\s]+$/;///[!@#$%^&*()_+\-=\[\]{};':"\\|<>\?~]/
        var textVal = event.clipboardData.getData('text');
        // Use the test() method of the regular expression to check if the string contains special characters
        var containsSpecialChars = specialCharsPattern.test(textVal);
        if (!containsSpecialChars) {
            if (pageInfo == "dealerSearch") {
                document.getElementById('searchQuery').innerText = "";
                $("#searchQuery").val("");
                $("#searchQuery").addClass("InvalidSearch");
                $("#searchQuery").css({ borderColor: "red" });
                document.getElementById("location_resultsId").style.display = "none";
            }
            else if (pageInfo == "search") {
                $("#txtBxSearch").val("");
                document.getElementById('txtBxSearch').innerText = "";
            }
            event.preventDefault();
        }
    }
}

function handleSearchpaste(pageInfo) {
    return function (event) {
        // Define a regular expression that accepts  - , . () / " : ' * , enter , tab ,space ,uppercase and lowercase letters and numbers
        const pattern = /^[-,.()/"':*\n\t\sA-Za-z0-9]+$/;
        var textVal = event.clipboardData.getData('text');
        // Use the test() method of the regular expression to check if the string contains special characters
        var containsSpecialChars = pattern.test(textVal);
        if (!containsSpecialChars) {
            if (pageInfo == "dealerSearch") {
                document.getElementById('searchQuery').innerText = "";
                $("#searchQuery").val("");
                $("#searchQuery").addClass("InvalidSearch");
                $("#searchQuery").css({ borderColor: "red" });
                document.getElementById("location_resultsId").style.display = "none";
            }
            else if (pageInfo == "search") {
                $("#txtBxSearch").val("");
                document.getElementById('txtBxSearch').innerText = "";
            }
            event.preventDefault();
        }
    }
}
function isSearchHasAlphaNum(e) {
    // Define a regular expression pattern to match special characters except comma, period, ampersand, and space
    const pattern = /^[-,.()/"':*\n\t\sA-Za-z0-9]+$/;
    var keyValue = String.fromCharCode(e.keyCode || e.charCode);
    var allowedChars = pattern.test(keyValue);
    if (allowedChars)
        return true;
    else
        return false;
}







  ;
$(document).ready(function () {
    if (navigator.userAgent != undefined && navigator.userAgent.indexOf("Firefox") > -1) {
        $("#divProdSpecHolder").removeClass("DetailsMarginclass");
    }

    //var isMerformanceProduct = $("#hdnIsMPerformanceProduct").val().toString();
    //var modelSeries = $("#hdnModelSeries").val().toString();
    //if ($(".productDetailContainer").is(":visible") && (isMerformanceProduct == "True" || modelSeries == "M MODELS")) {
    //    $("#divBody").addClass("MBlackTheme");
    //    $("#app").removeClass("WhiteTheme");
    //    $("#app").addClass("BlackTheme");
    //    $('footer').attr('id', "Mfooter");
    //}
    //else {
    //    $("#divBody").removeClass("MBlackTheme");
    //    $("#app").addClass("WhiteTheme");
    //    $("#app").removeClass("BlackTheme");
    //    $('footer').removeAttr('id');
    //}
    // select if only single option exists
    $('.hdnSingleItemSelection').each(function () {
        var id = $(this).val();
        $("#" + id).click();
        var ids = id.split("£");
        var drpDivId = "ColorLargeopt_" + ids[1];
        if ($("#" + drpDivId) != undefined) {
            $("#" + drpDivId).css("display", "none").removeClass("show");
        }
    });


    //When thumbnail image is clicked, show larger image
    $('.thumbnail-image').on('click', function () {
        var id = $(this).prop('id');
        var components = id.split("-");
        var photoNum = components[components.length - 1];
        $("[id^='productCarousel']").carousel(parseInt(photoNum));
    });
    $("#priceAddition").show();
    //commented as per new requirement in BE 13628
    //$("#installPrice").hide();
    //$("#totalPrice").show();
    $("input[name='InstallOptionRadioGroup']").on("change", function () {
        //commented as per new requirement in BE 13628
        //if ($(this).val() === "Install" && $("#customRadioInstalled").is(':visible') && $("#customRadioInstalled").is(":checked")) {
        //    $("#priceReduction").show();
        //    $("#priceAddition").hide();
        //    if ($("#hdnPriceRange") != null && $("#hdnPriceRange").val() != "") {
        //        $("#installPrice").empty();
        //        var totalInstallationPrice = parseFloat($("#hdnItemPrice").val().replace("$", "").replace(",", "")) + parseFloat($("#hdnInstallationPrice").val());
        //        var formatedPrice = "$" + totalInstallationPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
        //        $("#installPrice").text(formatedPrice);
        //    }
        //    $("#installPrice").show();
        //    $("#totalPrice").hide();
        //}
        //else {
        //    $("#priceReduction").hide();
        //    $("#priceAddition").show();
        //    $("#installPrice").hide();
        //    if ($("#hdnItemPrice") != undefined && $("#hdnItemPrice").val() != "") {
        //        $("#totalPrice").empty();
        //        var totalPrice = parseFloat($("#hdnItemPrice").val().replace("$", "").replace(",", ""));
        //        var formatedPrice = "$" + totalPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
        //        $("#totalPrice").text(formatedPrice);
        //    }
        //    $("#totalPrice").show();
        //}
        $('#validateInstallOption').removeClass("d-block").addClass("d-none");
    });
    if ($("input[name='InstallOptionRadioGroup']").length == 1) {
        $("input[name='InstallOptionRadioGroup']").change();
    }
    else if ($("#customRadioInstalled").is(':visible')) {
        $("#customRadioInstalled").change();
    }
    //dealer locater Popup
    var dealerCenterId = $("#hdnProdDealerId").val();
    var pageTitle = $("#hdnTitle").val();
    if ((dealerCenterId == "0") && (pageTitle != "SiteMap")) {
        showDealerPopup();
    }

    var videoTags = $('#productCarousel3').find(".carousel-item").find("video");
    if (videoTags.length > 0) {
        $.each(videoTags, function () {
            if (this.id.indexOf("-0") == -1) {
                this.pause();
                this.onpause = function () {
                    played = false;
                };
                this.onplay = function () {
                    played = true;
                };
            }
        });
    }

    //$(".ImgZoom").css("cursor", "pointer");

    if ($("#hdnProdId") != undefined && $("#hdnProdId").val() != undefined && $("#hdnIsMotorSport").val().toLowerCase() != "true")
        loadReltedProducts();


    // codes from window.onload
    // Set Variables
    allOSB = document.getElementsByClassName("detailsDivMain");

    if (allOSB.length > 0) {
        mxh = window.getComputedStyle(allOSB[0]).getPropertyValue('max-height');
        mxh = parseInt(mxh.replace('px', ''));

        // Add read-more button to each OSB section
        for (var i = 0; i < allOSB.length; i++) {
            var el = document.createElement("button");
            el.innerHTML = "Show More";
            el.setAttribute("type", "button");
            el.setAttribute("class", "MoreDiv hid");
            el.setAttribute('onkeydown', 'focusPopup(event,"divOthersAlsoBought");');
            $('.Hideshadow').show();
            insertAfter(allOSB[i], el);
        }
    }

    // Add click function to buttons
    var readMoreButtons = document.getElementsByClassName("MoreDiv");
    for (var i = 0; i < readMoreButtons.length; i++) {
        readMoreButtons[i].addEventListener("click", function () {
            revealThis(this);
        }, false);
    }

    // Update buttons so only the needed ones show
    updateReadMore();
    if ($("#hdnInstallationPrice").length > 0) {
        if ($("input[name='InstallOptionRadioGroup']").length > 0 && $("input[name='InstallOptionRadioGroup']:checked")[0].value == "Install") {
            $("#deliveryType").val("installed");
        }
        else if ($("input[name='InstallOptionRadioGroup']").length > 0 && $("input[name='InstallOptionRadioGroup']:checked")[0].value == "uninstall") {
            if ($("#hdnPickupOnly").val().toLowerCase() == "true") {
                $("#deliveryType").val("pickup in store");
            }
        }
    }
    if ($("#hdnIsInInventory").val() == "true" || $("#hdnIsStateWiseHide").val() == "true" || $("#hdnIsItemAvailable").val() == "true" || $("#hdnIsPickupOnly").val() == "true") inventory_check();

});


function loadReltedProducts() {
    var categoryType = $("#hdnCategoryType").val();
    var modelId = $("#hdnModelId").val() == "" ? 0 : $("#hdnModelId").val();
    var dealerId = $("#hdnProdDealerId").val() == "" ? 0 : $("#hdnProdDealerId").val();
    var prodId = $("#hdnProdId").val() == "" ? 0 : $("#hdnProdId").val();
    var catId = $("#hdnCatId").val() == "" ? 0 : $("#hdnCatId").val();
    if (prodId != 0) {
        var params = { categoryType: categoryType, productId: prodId, categoryId: catId, dealerId: dealerId, modelId: modelId };
        $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.Products.GetRelatedProducts, data: params }, {
            complete: function (json) {
                if (json.responseJSON !== null) {
                    $("#divOthersAlsoBought").html(json.responseJSON);
                    //carousel resetting after data load
                    $('.productRecomCarousel').owlCarousel({
                        loop: true,
                        margin: 16,
                        nav: false,
                        lazyLoad: true,
                        autoplay: true,
                        smartSpeed: 200,
                        autoplayTimeout: 3500,
                        autoplayHoverPause: true,
                        mouseDrag: true,
                        responsive: {
                            0: {
                                items: 2
                            },
                            576: {
                                items: 3
                            },
                            768: {
                                items: 5
                            },
                            992: {
                                items: 5
                            },
                            1200: {
                                items: 6,
                                autoplay: false,
                                loop: false,
                                mouseDrag: false
                            }
                        }
                    });
                }
            }
        }));
    }
}
$(document).mouseup(function (e) {
    DropDownCloseAction: {
        var IDs = [];
        $("button[id^=ColorLarge_]").each(function () { IDs.push(this.id); });
        if (IDs.indexOf(e.target.id) == -1) {
            $('div[id^="ColorLargeopt_"]').css("display", "none").removeClass("show");
        }
        else {
            var option = e.target.id.split("_");
            dropdownClosingFuctionality(option[1]);
        }

    }
});

$('#productCarousel3').on('slide.bs.carousel', function () {
    var activeVideoTag = $(this).find(".carousel-item.active").find("video");
    if (activeVideoTag.length > 0) {
        $.each(activeVideoTag, function () {
            VideoPlayPause(this)
        });
    }
})

$('#productCarousel3').on('slid.bs.carousel', function () {
    var activeVideoTag = $(this).find(".carousel-item.active").find("video");
    if (activeVideoTag.length > 0) {
        $.each(activeVideoTag, function () {
            VideoPlayPause(this);
        });
    }
});

var played = true;
function VideoPlayPause(control) {
    if (played) {
        control.pause();
        played = false;
    }
    else {
        control.play();
        played = true;
    }
}

function detailsVisibility() {
    if ($(".detailsDivHide").is(':visible')) {
        $(".detailsDivHide").css({ display: 'none' });
        $(".detailsDivMain").css({ display: 'block' });
    }
    else if ($(".detailsDivMain").is(':visible')) {
        $(".detailsDivHide").css({ display: 'block' });
        $(".detailsDivMain").css({ display: 'none' });
    }
}

function showOtherProductOptionPopup() {
    $('#validateOption').removeClass("d-block").addClass("d-none");
    //$('.SelectOptionDiv').height($(window).innerHeight());
    $('body').addClass('body-fixed');
    $('body').css('overflow-y', 'hidden');
    $('html').css('overflow', 'hidden');
    $(window).scrollTop(0);
    $("#divSelectOpt").removeClass("ProD-none").addClass("ProD-block");
    $("#divSelectOptOverlay").removeClass("d-none").addClass("d-block");
    calculateProductSummary();

    if ($("#hdnIsTypeDProduct").val().toLowerCase() === "true") {
        if ($("#hdnIsSpecialProduct").val().toLowerCase() == "true") {
            $.each($('[id^="dropdown-menu_"]'), function (i, itmObj) {
                var pdtItemName = itmObj.id.replace("dropdown-menu_", "");
                var numQty = document.getElementById("lblDetailsQty").innerHTML;
                $("#lblDetailsQty_" + pdtItemName).text(numQty);
                updateSpecialProductQtyFlyOutDropDown(pdtItemName, numQty);
            });
            calculateProductSummary();
        }
    }
}

function hideProductOptionPopup() {
    $("#divSelectOpt").css({ display: 'none' });
    $('body').removeClass('body-fixed');
    $('body').css('overflow-y', 'auto');
    $('html').css('overflow-y', 'auto');
    $('html').css('overflow-x', 'hidden');
    $("#divSelectOpt").removeClass("ProD-block").addClass("ProD-none");
    $("#divSelectOptOverlay").removeClass("d-block").addClass("d-none");
}

function validateOptionSelection() {

    if ($("input[name='optionRadBtn']:checked").val()) {
        if ($(".SizeHead").is(':visible')) {
            $("#sizeSpan").css({ display: 'none' });
        }
    }
}

function optionSelectionPriceChange(price, itemName, orgPrice, offerPrice) {
    $('#validateOption').removeClass("d-block").addClass("d-none");
    if ($("#hdnIsSpecialProduct").val().toLowerCase() == "true") {
        if (offerPrice != undefined && offerPrice != "") {
            orgPrice = orgPrice.toString();
            offerPrice = offerPrice.toString();
            if (itemName == "AllOptions") {
                $("#OrgPriceRange").empty();
                $("#OfferPriceRange").empty();
                $("#OrgTotalPrice").empty();
                $("#OfferTotalPrice").empty();
                $("#OrgPriceRange").text("$" + orgPrice);
                $("#OfferPriceRange").text("$" + offerPrice);
                if ($("#hdnItemPrice") != undefined)
                    $("#hdnItemPrice").val(offerPrice);
                $("#OrgTotalPrice").text("$" + parseFloat(orgPrice.replace(",", "")).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", ""));
                $("#OfferTotalPrice").text("$" + parseFloat(offerPrice.replace(",", "")).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", ""));
            }
            else {
                var labelId = "lblPrice_" + itemName;
                var formatedPrice = "$" + parseFloat(offerPrice.replace(",", "")).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
                $("#" + labelId).empty();
                $("#" + labelId).append(formatedPrice);
                var orgLabelId = "lblOrgPrice_" + itemName;
                var formatedOrgPrice = "$" + parseFloat(orgPrice.replace(",", "")).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
                $("#" + orgLabelId).empty();
                $("#" + orgLabelId).append(formatedOrgPrice);
            }
        }
    } else if (price != undefined && price != "") {
        price = price.toString();
        if (itemName == "AllOptions") {
            $("#PriceRange").empty();
            $("#totalPrice").empty();
            $("#PriceRange").text("$" + price);
            if ($("#hdnItemPrice") != undefined)
                $("#hdnItemPrice").val(price);
             // Commenting as per new requirement on BE 13628
            //if ($("#customRadioInstalled").is(':visible') && $("#customRadioInstalled").is(":checked") && $("#hdnPriceRange") != null && $("#hdnPriceRange").val() != "") {
            //    $("#installPrice").empty();
            //    var totalInstallationPrice = parseFloat(price.replace(",", "")) + parseFloat($("#hdnInstallationPrice").val());
            //    var formatedPrice = "$" + totalInstallationPrice.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
            //    $("#installPrice").text(formatedPrice);
            //    $("#totalPrice").text(formatedPrice);
            //}
            //else {
            //    $("#totalPrice").text("$" + parseFloat(price.replace(",", "")).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", ""));
            //}
           
            $("#totalPrice").text("$" + parseFloat(price.replace(",", "")).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", ""));
        }
        else {
            var labelId = "lblPrice_" + itemName;
            var formatedPrice = "$" + parseFloat(price.replace(",", "")).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
            $("#" + labelId).empty();
            $("#" + labelId).append(formatedPrice);
        }
    }
}

function colorSquareClicked(id, productItemname, optionCategory, relatedOptions, selectedCatOption, itemPrice, orgPrice, offerPrice, quantityLeft) {//"BMW©All©Weather©Cargo©Liner£Color£Beige£0","AllOptions","Color","Color£Beige^Seat©Option£With©3rd©Row©Seats:Seat©Option£Without©3rd©Row©Seats,Color£Black^Seat©Option£With©3rd©Row©Seats:Seat©Option£Without©3rd©Row©Seats,Color£Gray^Seat©Option£With©3rd©Row©Seats:Seat©Option£Without©3rd©Row©Seats,Seat©Option£With©3rd©Row©Seats^Color£Beige:Color£Black:Color£Gray,Seat©Option£Without©3rd©Row©Seats^Color£Beige:Color£Black:Color£Gray","Color£Beige","97"
    var passedOption = id.replace("colorSquare-", "").split("£");
    var hdnOption = "", hdnFlyoutOption = "";
    if (optionCategory != "") {
        hdnOption = "hdnOption_" + optionCategory;
        if ($("#hdnOptionId_" + id) != undefined && $("#hdnOptionId_" + id).val() != 0)
            if (productItemname == "AllOptions") {
                if ($('input[type=hidden][id^="hdnOptionId_' + id.split("£").splice(0, 3).join("£") + '"]').length > 0) {
                    var optionId = $('input[type=hidden][id^="hdnOptionId_' + id.split("£").splice(0, 3).join("£") + '"]')[0].value;
                    $("#" + hdnOption).val(optionId);
                }
            }
            else $("#" + hdnOption).val($("#hdnFlyOutOptionId_" + id).val());
        else
            $("#" + hdnOption).val(passedOption[2].replace(/©/g, " "));
        $('input:hidden[id ^="hdnFlyOutOption_"][id $="_' + optionCategory + '"]').each(function () {
            hdnFlyoutOption = this.id;
            var flyoutId = this.id.replace(/_/g, "£").replace("hdnFlyOutOption£", "hdnFlyOutOptionId_") + "£" + passedOption[2].replace(/©/g, " ");
            if ($('input:hidden[id^="' + flyoutId + '"]') != undefined && $('input:hidden[id^="' + flyoutId + '"]').val() != 0)
                // Both condition executes same code but difference is if any change in option slected in flyout, 
                // ONLY coresponding hdnFlyOutOption will be updated, all hdnFlyOutOption will be updated 
                // ONLY IF productItemname = AllOptions i.e a common option is selcetd
                if (productItemname == "AllOptions") $("#" + hdnFlyoutOption).val($('input:hidden[id^="' + flyoutId + '"]').val());
                else {
                    if (productItemname == hdnFlyoutOption.replace("hdnFlyOutOption_", "").split('_')[0]) {
                        $("#" + hdnFlyoutOption).val($('input:hidden[id^="' + flyoutId + '"]').val());
                    }
                }
            else
                $("#" + hdnFlyoutOption).val(passedOption[2].replace(/©/g, " "));
            var price = $("#" + flyoutId.replace("hdnFlyOutOptionId_", "hdnFlyOutPrice_")).val();
            optionSelectionPriceChange(price, productItemname);
        });
    }
    else {
        hdnOption = "hdnOption_" + passedOption[1];
        if ($("#hdnOptionId_" + id) != undefined && $("#hdnOptionId_" + id).val() != 0)
            $("#" + hdnOption).val($("#hdnOptionId_" + id).val());
        else
            $("#" + hdnOption).val(passedOption[2].replace(/©/g, " "));
        $('input:hidden[id ^="hdnFlyOutOption_"][id $="_' + passedOption[1] + '"]').each(function () {
            hdnFlyoutOption = this.id;
            var flyoutId = this.id.replace(/_/g, "£").replace("hdnFlyOutOption£", "hdnFlyOutOptionId_") + "£" + passedOption[2].replace(/©/g, " ");
            if ($('input:hidden[id^="' + flyoutId + '"]') != undefined && $('input:hidden[id^="' + flyoutId + '"]').val() != 0)
                $("#" + hdnFlyoutOption).val($('input:hidden[id^="' + flyoutId + '"]').val());
            else
                $("#" + hdnFlyoutOption).val(passedOption[2].replace(/©/g, " "));
            var price = $("#" + flyoutId.replace("hdnFlyOutOptionId_", "hdnFlyOutPrice_")).val();
            optionSelectionPriceChange(price, productItemname);
        });
    }
    imageSelection(id.replace("colorSquare-", ""));
    var ItemOption = $("#hdnItemOption_" + id).val();
    if (productItemname.indexOf("AllOption") > -1) {
        $('label[id="lblSelectedItemColor"]').each(function () {
            $(this).text(ItemOption);
        });
    }
    else {
        $("#lblSelectedItemColor" + productItemname).text(ItemOption);
    }
    var SelectOptionDetails = getProductObjectItem(getAllSelectedOptionsOfProductItem());
    if (SelectOptionDetails != undefined && SelectOptionDetails !== null && SelectOptionDetails.length > 0) {
        optionSelectionPriceChange(SelectOptionDetails[0].Price, productItemname, SelectOptionDetails[0].ItemOrgPrice, SelectOptionDetails[0].ItemOfferPrice);
        specialsOptionSelectionQuantityUpdateAfterCart(productItemname, SelectOptionDetails[0].RemainingQtyLeft);
    }
    else if (itemPrice === "0") {
        SelectOptionDetails = getProductObjectItem(passedOption[2]);
        optionSelectionPriceChange(SelectOptionDetails[0].Price, SelectOptionDetails[0].ProductItemName.replace(/\s/g, "©"));
    }
    else {
        optionSelectionPriceChange(itemPrice, productItemname, orgPrice, offerPrice);
        specialsOptionSelectionQuantityUpdateAfterCart(productItemname, quantityLeft);
    }
    var productItemName = "";
    if (productItemname.indexOf("AllOption") > -1) {
        var colourSquaresList = $(".colourSquares");
        $.each(colourSquaresList, function (index, object) {
            $("#" + object.id).removeClass("active").css("background-image", "none");
        });
        var CommonDiv = $('div[id*="' + '£' + passedOption[1] + '£' + passedOption[2] + '£"]');
        $('input[type=checkbox][id^="customCheckSelected_"]').prop("checked", false);
        $.each(CommonDiv, function (index, object) {
            $("#" + object.id).removeClass("active").css("background-image", "none");
            var optionObj = id.replace("colorSquare-", "").split("£");
            if (optionObj[2] == passedOption[2]) {
                $("#" + object.id).addClass("active");
                $("#" + object.id + ".colourSquares.active").css("background-image", function () { return isDark($("#" + object.id + ".active").css("background-color")) ? "url(/images/checkboxtick.png)" : "url(/images/checkboxtickBlue.png)"; });
                if (object.className.indexOf('outer') == -1) {
                    var ItemName = object.id.replace('colorSquare-', '').split('£');
                    $('#customCheckSelected_' + ItemName[0]).prop("checked", true);
                    var price = $("#hdnFlyOutPrice_" + ItemName[0] + "£" + ItemName[1] + "£" + ItemName[2] + "£1").val();
                    var orgPrice = $("#hdnFlyOutOrgPrice_" + ItemName[0] + "£" + ItemName[1] + "£" + ItemName[2] + "£1").val();
                    optionSelectionPriceChange(price, ItemName[0], orgPrice, price);
                    var qtyLeft = $("#hdnFlyOutQuantityLeft_" + ItemName[0] + "£" + ItemName[1] + "£" + ItemName[2] + "£1").val();
                    specialsOptionSelectionQuantityUpdateAfterCart(ItemName[0], qtyLeft);
                }
            }
        });
        productItemName = "AllOptions";
    }
    else {
        var colourSquaresList2 = $(".colourSquares." + passedOption[0]);
        $.each(colourSquaresList2, function (index, object) {
            $("#" + object.id).removeClass("active").css("background-image", "none");
        });
        $("#colorSquare-" + id).addClass("active");
        $("#colorSquare-" + id + ".colourSquares.active").css("background-image", function () { return isDark($("#" + id + ".active").css("background-color")) ? "url(/images/checkboxtick.png)" : "url(/images/checkboxtickBlue.png)"; });
    }
    //productItemName = passedOption[0].replace(/©/g, " ");
    if (relatedOptions != "") {
        changeOptionBasedOnCombination(relatedOptions, selectedCatOption);
    }
    var isTypeD = $("#hdnIsTypeDProduct");
    if (isTypeD[0].value != "False") {
        onProductItemOptionsClick(productItemName, passedOption[1].replace(/©/g, " "), passedOption[2].replace(/©/g, " "));
        calculateProductSummary();
    }
    if ($("#hdnIsInInventory").val() == "true" || $("#hdnIsStateWiseHide").val() == "true" || $("#hdnIsItemAvailable").val() == "true" || $("#hdnIsPickupOnly").val() == "true") inventory_check();

}

var selectedItemId = [];
function onProductItemOptionsClick(ProductItemName, OptionCategory, productOption, controlId) {
    if (ProductItemName == "AllOptions") selectedItemId = [];
    if (ProductItemName != "AllOptions") {
        // var flyoutId = ProductItemName.replace(/\s/g, "©") + '£' + OptionCategory.replace(/\s/g, "©") + '£' + productOption.replace(/\s/g, "©") + '£';
        var hdnSelectedValue = $('input:hidden[id^="hdnFlyOutOptionId_"][id*="' + OptionCategory.replace(/\s/g, "©") + "£" + productOption.replace(/\s/g, "©") + '"]').val();
        if ($('input:hidden[id^="hdnFlyOutOption_' + ProductItemName.replace(/\s/g, "©") + '_' + OptionCategory.replace(/\s/g, "©") + '"]').length > 0) {
            $('input:hidden[id^="hdnFlyOutOption_' + ProductItemName.replace(/\s/g, "©") + '_' + OptionCategory.replace(/\s/g, "©") + '"]').val(hdnSelectedValue);
        }
    }
    if (ProductItemDetails != "" && ProductItemDetails.length > 0) {
        var DivClass = ProductItemName.replace(/\s/g, "©") + "summary";
        //var item = getObjects(selectedItemId, "name", ProductItemName);
        //var item = getProductObjectItem(productOption);
        var item = getProductObjectItem(getAllSelectedOptionsOfProductItem(ProductItemName));
        if (item != undefined && item.length > 0) {
            $.each(selectedItemId, function (indexxl, objectxl) {
                if (objectxl !== undefined) {
                    if (objectxl.name == ProductItemName && selectedItemId.length > 0) {
                        selectedItemId.splice(indexxl, 1);
                    }
                }
            });
        }
        $.each(ProductItemDetails, function (index, object) {
            $.each(object.ProductOptions, function (optionIndex, optionObject) {
                if ((object.ProductItemName == ProductItemName || ProductItemName == "AllOptions") && optionObject.OptionCategory == OptionCategory && removeAllSpecialCharater(optionObject.OptionValue) == productOption) {
                    //var item = getObjects(selectedItemId, "name", object.ProductItemName);
                    //item = getObjects(item, "OptionCategory", OptionCategory);
                    //var item = getProductObjectItem(object.ProductItemName);
                    //item = getProductObjectItem(OptionCategory);
                    var item = getProductObjectItem(getAllSelectedOptionsOfProductItem(object.ProductItemName));

                    if (item !== undefined && item.length === 0) {
                        selectedItemId.push({
                            id: object.ProductItemId,
                            name: object.ProductItemName,
                            OptionCategory: optionObject.OptionCategory,
                            OptionValue: optionObject.OptionValue,
                            price: object.Price,
                            IsStateWiseHide: object.IsStateWiseHide,
                            StateWiseHideNote: object.StateWiseHideNote,
                            ItemOrgPrice: object.ItemOrgPrice,
                            ItemOfferPrice: object.ItemOfferPrice
                        });
                    }
                }
            });
        });
        //price update for combination products
        //var selectedItemId = getProductObjectItem(getAllSelectedOptionsOfProductItem());
        $("#SummaryListDiv").empty();
        var total = 0;
        $.each(selectedItemId, function (index, object) {
            if (!object.IsStateWiseHide) {
                var pName = (object.name).replace(/[^a-z0-9-_\s]/gi, '').replace(/[_\s]/g, ' ');
                if ($("input[type=checkbox][id=customCheckSelected_" + $.escapeSelector(pName.replace(/\s/g, "©")) + "]").is(':checked')) {
                    var selectedItem = "<div class='float-left " + DivClass + "'><img class=''  alt='' src=" + $(".OptMainDiv.OptSpacing." + $.escapeSelector(object.name.replace(/\s/g, "©")) + "div").find(".carousel-item.active").find("img").attr("src") + " /><label id='itemName'>" + object.name + " ,(" + object.OptionValue + ")</label></div>";
                    selectedItem += "<div class='float-left justify-content-end " + DivClass + "'><span id='ItemPrice'>$" + object.price + "</span> </div>";
                    total = parseFloat(total) + parseFloat(object.price);
                    $("#SummaryListDiv").append(selectedItem);
                    $("input[type=checkbox][id=customCheckSelected_" + $.escapeSelector(pName.replace(/\s/g, "©")) + "]").prop("checked", true);
                    if ($("#hdnIsSpecialProduct").val().toLowerCase() == "true") {
                        $("#lblPrice_" + $.escapeSelector(pName.replace(/\s/g, '©'))).text("$" + parseFloat(object.ItemOfferPrice).toFixed(2).replace(".00", ""));
                    } else {
                        $("#lblPrice_" + $.escapeSelector(pName.replace(/\s/g, '©'))).text("$" + parseFloat(object.price).toFixed(2).replace(".00", ""));
                    }
                }
            }
        });
        $("#SummarySubTotal").text("$" + parseFloat(total).toFixed(2).replace(".00", ""));
    }
    if ($("#hdnIsInInventory").val() == "true" || $("#hdnIsStateWiseHide").val() == "true" || $("#hdnIsItemAvailable").val() == "true" || $("#hdnIsPickupOnly").val() == "true") inventory_check();
}

function getObjects(obj, key, val) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjects(obj[i], key, val));
        } else if (i == key && obj[key] == val) {
            objects.push(obj);
        }
    }
    return objects;
}

//function getAllSelectOptionProductDetails(ProductItemName, OptionCategory, productOption) {
//    var selectedItemId = [];
//    $.each(ProductItemDetails, function (index, object) {
//        $.each(object.ProductOptions, function (optionIndex, optionObject) {
//            if ((object.ProductItemName == ProductItemName || ProductItemName == "AllOptions") && optionObject.OptionCategory == OptionCategory && removeAllSpecialCharater(optionObject.OptionValue) == productOption) {
//                var item = getObjects(selectedItemId, "name", object.ProductItemName);
//                item = getObjects(item, "OptionCategory", OptionCategory);
//                if (item.length == 0) {
//                    selectedItemId.push({
//                        id: object.ProductItemId,
//                        name: object.ProductItemName,
//                        OptionCategory: optionObject.OptionCategory,
//                        OptionValue: optionObject.OptionValue,
//                        price: object.Price,
//                        IsStateWiseHide: object.IsStateWiseHide,
//                        StateWiseHideNote: object.StateWiseHideNote,
//                        IsInInventory: object.IsInInventory,
//                        NotifyMe:false
//                    });
//                }
//            }
//        });
//    });
//    return selectedItemId;
//}


function getAllSelectOptionProductDetails(ProductItemName, OptionCategory, productOption) {
    var selectedItemId = [];
    $.each(ProductItemDetails, function (index, object) {
        $.each(object.ProductOptions, function (optionIndex, optionObject) {
            if ((object.ProductItemName == ProductItemName || ProductItemName == "AllOptions") && optionObject.OptionCategory == OptionCategory && (removeAllSpecialCharater(optionObject.OptionValue) == productOption || optionObject.OptionId.toString() == productOption)) {
                //var item = getObjects(selectedItemId, "name", object.ProductItemName);
                //item = getObjects(item, "OptionCategory", OptionCategory);
                //var item = getProductObjectItem(object.ProductItemName);
                // item = getProductObjectItem(OptionCategory);
                var item = getProductObjectItem(getAllSelectedOptionsOfProductItem(object.ProductItemName));
                if (item != undefined) {
                    if (item.length == 0) {
                        selectedItemId.push({
                            id: object.ProductItemId,
                            name: object.ProductItemName,
                            OptionCategory: optionObject.OptionCategory,
                            OptionValue: optionObject.OptionValue,
                            price: object.Price,
                            IsStateWiseHide: object.IsStateWiseHide,
                            StateWiseHideNote: object.StateWiseHideNote
                        });
                    }
                }
            }
        });
    });
    return selectedItemId;
}

function imageSelection(controlId) {
    var get_value = controlId.split("£");
    var SelectOptionDetails = getObjectItem(get_value[2]);
    var colorOptSelected = $("#hdnOption_Color").val() != undefined ? $("#hdnOption_Color").val() : "";
    ///product/4944/BMW-MOTORSPORT-DRIFT-CAT-5-SHOES - This has one image for the first white option, and one image for the first blue option,
    //but when selecting the size that is shared with
    //the white shoe(which happens to be the size with the white image option), it switches over.
    var setImage = false;
    if (SelectOptionDetails.length != 0 && SelectOptionDetails != null) {
        if (get_value[0] == "AllOptions") {
            var CommonImageDiv = $(".CommonImageContainer").find(".carousel-item>img");
            $.each(CommonImageDiv, function (index, image) {
                $.each(SelectOptionDetails, function (index, SelectOptionDetail) {
                    if (setImage == false && colorOptSelected != "") {//for Multi Variation Image Upload for Color Functionality
                        $.each(SelectOptionDetail.ProductOptions, function (index, optInfo) {
                            if (setImage == false && optInfo.OptionCategory == "Color" && optInfo.OptionId == colorOptSelected) {
                                if (image.src.toLowerCase().indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                                    $(".CommonImageContainer").find(".carousel-item").removeClass("active");
                                    $($(image)[0].parentElement).addClass("active");
                                    setImage = true;
                                }
                            }
                        });
                    }
                    else if (setImage == false && image.src.toLowerCase().indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                        $(".CommonImageContainer").find(".carousel-item").removeClass("active");
                        $($(image)[0].parentElement).addClass("active");
                        setImage = true;
                    }
                });
            });
            if ($("#divSelectOpt").length > 0) {
                setImage = false;
                $.each($(".OptMainDiv"), function (index, OptMainDiv) {
                    var flyoutImageDiv = $(OptMainDiv).find(".flyoutImageContainer").find(".carousel-item>img");
                    $.each(flyoutImageDiv, function (index, image) {
                        $.each(SelectOptionDetails, function (index, SelectOptionDetail) {
                            if (setImage == false && colorOptSelected != "") {
                                $.each(SelectOptionDetail.ProductOptions, function (index, optInfo) {
                                    if (optInfo.OptionCategory == "Color" && optInfo.OptionId == colorOptSelected) {
                                        if (setImage == false && image.src.toLowerCase().indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                                            $(OptMainDiv).find(".flyoutImageContainer").find(".carousel-item").removeClass("active");
                                            $($(image)[0].parentElement).addClass("active");
                                            setImage = true;
                                        }
                                    }
                                });
                            }
                            else if (setImage == false && image.src.toLowerCase().indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                                $(OptMainDiv).find(".flyoutImageContainer").find(".carousel-item").removeClass("active");
                                $($(image)[0].parentElement).addClass("active");
                                setImage = true;
                            }
                        });
                    });
                });
            }
            setImage = false;
            var thumbnails = $(".thumbnails").find(".thumbnail-image-container>img");
            $(".thumbnail-image-container>img").removeClass("thumb-selected");
            $.each(thumbnails, function (index, thumbnail) {
                $.each(SelectOptionDetails, function (index, SelectOptionDetail) {
                    if (setImage == false && colorOptSelected != "") {
                        $.each(SelectOptionDetail.ProductOptions, function (index, optInfo) {
                            if (optInfo.OptionCategory == "Color" && optInfo.OptionId == colorOptSelected) {
                                if (setImage == false && (thumbnail.src.toLowerCase()).indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                                    $($(thumbnail)[0]).addClass("thumb-selected");
                                    setImage = true;
                                }
                            }
                        });
                    }
                    else if (setImage == false && (thumbnail.src.toLowerCase()).indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                        $($(thumbnail)[0]).addClass("thumb-selected");
                        setImage = true;
                    }
                });
            });
        }
        else if ($("#divSelectOpt").length > 0) {
            setImage = false;
            if ($(".OptMainDiv").hasClass(get_value[0] + "div")) {
                var FlyoutImages = $(".OptMainDiv." + get_value[0] + "div").find(".flyoutImageContainer").find(".carousel-item>img");
                $.each(FlyoutImages, function (index, image) {
                    $.each(SelectOptionDetails, function (index, SelectOptionDetail) {
                        if (setImage == false && colorOptSelected != "") {
                            $.each(SelectOptionDetail.ProductOptions, function (index, optInfo) {
                                if (optInfo.OptionCategory == "Color" && optInfo.OptionId == colorOptSelected) {
                                    if (setImage == false && image.src.toLowerCase().indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                                        $(".OptMainDiv." + get_value[0] + "div").find(".flyoutImageContainer").find(".carousel-item").removeClass("active");
                                        $($(image)[0].parentElement).addClass("active");
                                        setImage = true;
                                    }
                                }
                            });
                        }
                        else if (setImage == false && image.src.toLowerCase().indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                            $(".OptMainDiv." + get_value[0] + "div").find(".flyoutImageContainer").find(".carousel-item").removeClass("active");
                            $($(image)[0].parentElement).addClass("active");
                            setImage = true;
                        }
                    });

                });
            }
            else {
                setImage = false;
                $.each($(".OptMainDiv"), function (index, OptMainDiv) {
                    var flyoutImageDiv = $(OptMainDiv).find(".flyoutImageContainer").find(".carousel-item>img");
                    $.each(flyoutImageDiv, function (index, image) {
                        $.each(SelectOptionDetails, function (index, SelectOptionDetail) {
                            if (setImage == false && colorOptSelected != "") {
                                $.each(SelectOptionDetail.ProductOptions, function (index, optInfo) {
                                    if (setImage == false && optInfo.OptionCategory == "Color" && optInfo.OptionId == colorOptSelected) {
                                        if (image.src.toLowerCase().indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                                            $(OptMainDiv).find(".flyoutImageContainer").find(".carousel-item").removeClass("active");
                                            $($(image)[0].parentElement).addClass("active");
                                            setImage = true;
                                        }
                                    }
                                });
                            }
                            else if (setImage == false && image.src.toLowerCase().indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                                $(OptMainDiv).find(".flyoutImageContainer").find(".carousel-item").removeClass("active");
                                $($(image)[0].parentElement).addClass("active");
                                setImage = true;
                            }
                        });
                    });

                });
            }
        }
        else {
            setImage = false;
            var CommonImageDiv = $(".CommonImageContainer").find(".carousel-item>img");
            $.each(CommonImageDiv, function (index, image) {
                $.each(SelectOptionDetails, function (index, SelectOptionDetail) {
                    if (setImage == false && colorOptSelected != "") {
                        $.each(SelectOptionDetail.ProductOptions, function (index, optInfo) {
                            if (optInfo.OptionCategory == "Color" && optInfo.OptionId == colorOptSelected) {
                                if (setImage == false && image.src.toLowerCase().indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                                    $(".CommonImageContainer").find(".carousel-item").removeClass("active");
                                    $($(image)[0].parentElement).addClass("active");
                                    setImage = true;
                                }
                            }
                        });
                    }
                    else if (setImage == false && image.src.toLowerCase().indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                        $(".CommonImageContainer").find(".carousel-item").removeClass("active");
                        $($(image)[0].parentElement).addClass("active");
                        setImage = true;
                    }
                });
            });
            setImage = false;
            var thumbnails = $(".thumbnails").find(".thumbnail-image-container>img");
            $(".thumbnail-image-container>img").removeClass("thumb-selected");
            $.each(thumbnails, function (index, thumbnail) {
                $.each(SelectOptionDetails, function (index, SelectOptionDetail) {
                    if (setImage == false && colorOptSelected != "") {
                        $.each(SelectOptionDetail.ProductOptions, function (index, optInfo) {
                            if (optInfo.OptionCategory == "Color" && optInfo.OptionId == colorOptSelected) {
                                if (setImage == false && (thumbnail.src.toLowerCase()).indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                                    $($(thumbnail)[0]).addClass("thumb-selected");
                                    setImage = true;
                                }
                            }
                        });
                    }
                    else if (setImage == false && (thumbnail.src.toLowerCase()).indexOf(encodeURIComponent(SelectOptionDetail.ItemImage).toLowerCase()) > 0) {
                        $($(thumbnail)[0]).addClass("thumb-selected");
                        setImage = true;
                    }
                });
            });
        }
    }
}

function onProductRadioButtonCheck(controlId, selectedCategory, itemPrice, orgPrice, offerPrice, QuantityLeft) {
    //"AllOptions£Seat©Option£With©3rd©Row©Seats£0","Seat©Option","60"
    var get_value = controlId.split("£");
    var selectedItemOptionDetails = getAllSelectOptionProductDetails(get_value[0].replace(/©/g, " "), get_value[1].replace(/©/g, " "), get_value[2].replace(/©/g, " "));
    if (get_value[0] == "AllOptions") {
        if ($("#hdnIsTypeDProduct").val() == "True") {
            $.each(selectedItemOptionDetails, function (index, object) {
                if (!object.IsStateWiseHide) {
                    $("input[type=checkbox][id=customCheckSelected_" + $.escapeSelector(object.name.replace(/\s/g, "©")) + "]").prop("checked", true);
                }
            });
        }
    }
    //optionSelectionPriceChange(itemPrice, get_value[0]);
    imageSelection(controlId);

    if (controlId.indexOf("AllOptions") > -1) {// common option selected
        var RadioButtonSelectedValue = $("#" + controlId).val();
        if ($("#hdnOptionId_" + controlId) != undefined && $("#hdnOptionId_" + controlId).val() != 0)
            $("#hdnOption_" + selectedCategory).val($("#hdnOptionId_" + controlId).val());
        else
            $("#hdnOption_" + selectedCategory).val(RadioButtonSelectedValue);
        var flyOutCntrId = "£" + get_value[1] + "£" + get_value[2];
        if ($('input:hidden[id ^= "hdnFlyOutOptionId_"][id *= "' + flyOutCntrId + '"]') != undefined && $('input:hidden[id ^= "hdnFlyOutOptionId_"][id *= "' + flyOutCntrId + '"]').val() != 0) {
            $('input:hidden[id ^= "hdnFlyOutOptionId_"][id *= "' + flyOutCntrId + '"]').each(function (index, obj) {
                var itemName = obj.id.replace("hdnFlyOutOptionId_", "").split('£')[0];
                var price = $("#" + obj.id.replace("hdnFlyOutOptionId_", "hdnFlyOutPrice_")).val();
                var orgPrice = $("#" + obj.id.replace("hdnFlyOutOptionId_", "hdnFlyOutOrgPrice_")).val();
                optionSelectionPriceChange(price, itemName, orgPrice, price);
                $("#hdnFlyOutOption_" + itemName + "_" + selectedCategory).val($('input:hidden[id ^= "hdnFlyOutOptionId_"][id *= "' + flyOutCntrId + '"]').val());
            });
        }
        else {
            $("#hdnFlyOutOption_" + selectedCategory).val(RadioButtonSelectedValue);
        }
        //if ($('input:hidden[id ^= "hdnFlyOutOptionId_"][id *= "' + flyOutCntrId + '"]') != undefined && $('input:hidden[id ^= "hdnFlyOutOptionId_"][id *= "' + flyOutCntrId +'"]').val() != 0)
        //    $("#hdnFlyOutOption_" + selectedCategory).val($('input:hidden[id ^= "hdnFlyOutOptionId_"][id *= "' + flyOutCntrId +'"]').val());
        //else
        //    $("#hdnFlyOutOption_" + selectedCategory).val(RadioButtonSelectedValue);
        if ($("#hdnIsTypeDProduct").val() == "True") {
            $('input:hidden[id^="hdnOption_"]').each(function () {
                var category = this.id.replace("hdnOption_", "");
                var CollectiveIds = $("[id*=" + RadioButtonSelectedValue.replace(/\s/g, '©') + "]");
                $.each(CollectiveIds, function (index, object) {
                    var RadioId = object.id;
                    $("#" + $.escapeSelector(RadioId)).prop("checked", true);
                    onProductItemOptionsClick(get_value[0].replace(/©/g, " "), get_value[1].replace(/©/g, " "), get_value[2].replace(/©/g, " "), controlId);
                });
            });
            $("input[type=radio][id=" + controlId + "]").attr("checked", true);
        }
    }
    else {
        onProductItemOptionsClick(get_value[0].replace(/©/g, " "), get_value[1].replace(/©/g, " "), get_value[2].replace(/©/g, " "), controlId);
        calculateProductSummary();
    }
    if ($("#hdnIsInInventory").val() == "true" || $("#hdnIsStateWiseHide").val() == "true" || $("#hdnIsItemAvailable").val() == "true" || $("#hdnIsPickupOnly").val() == "true") inventory_check();
    var selectedOptionsIds = getAllSelectedOptionsOfProductItem().toString();
    var SelectOptionDetails = getProductObjectItem(selectedOptionsIds);
    if (SelectOptionDetails != undefined && SelectOptionDetails !== null && SelectOptionDetails.length > 0) {
        optionSelectionPriceChange(SelectOptionDetails[0].Price, get_value[0], SelectOptionDetails[0].ItemOrgPrice, SelectOptionDetails[0].ItemOfferPrice);
        specialsOptionSelectionQuantityUpdateAfterCart(get_value[0], SelectOptionDetails[0].RemainingQtyLeft);
    }
    else {
        optionSelectionPriceChange(itemPrice, get_value[0], orgPrice, offerPrice);
        specialsOptionSelectionQuantityUpdateAfterCart(get_value[0], QuantityLeft);
    }
    $("#maximumQtyMsg").addClass("d-none");
}
function getProductObjectItem(value) {
    var ProductItem = [];
    var item_options = value.split(',');
    $.each(ProductItemDetails, function (MainIndex, MainObject) {
        $.each(MainObject.ProductOptions, function (index, object) {
            //var OptionValue = object.OptionValue.replace(/[^a-z0-9\s\-]/gi, '').replace(/[_\s]/g, ' ');
            var OptionValue = object.OptionId;
            if (OptionValue == item_options[0].replace(/©/g, " ")) {
                // if (name == "alloption") {
                ProductItem.push(ProductItemDetails[MainIndex]);
                //return ProductItem;
                //}
                // 
            }
        });
    });
    if (item_options.length > 1) {
        var ProductItemOpt = [];
        $.each(ProductItem, function (MainIndex, MainObject) {
            $.each(MainObject.ProductOptions, function (index, object) {
                //var OptionValue = object.OptionValue.replace(/[^a-z0-9\s\-]/gi, '').replace(/[_\s]/g, ' ');
                var OptionValue = object.OptionId;
                if (OptionValue == item_options[1].replace(/©/g, " ")) {
                    // if (name == "alloption") {
                    ProductItemOpt.push(ProductItem[MainIndex]);
                    //return ProductItemOpt;
                    //}
                    // 
                }
            });
        });
        if (item_options.length > 2) {
            var ProductItemOpt1 = [];
            $.each(ProductItemOpt, function (MainIndex, MainObject) {
                $.each(MainObject.ProductOptions, function (index, object) {
                    // var OptionValue = object.OptionValue.replace(/[^a-z0-9\s\-]/gi, '').replace(/[_\s]/g, ' ');
                    var OptionValue = object.OptionId;
                    if (OptionValue == item_options[2].replace(/©/g, " ")) {
                        // if (name == "alloption") {
                        ProductItemOpt1.push(ProductItemOpt[MainIndex]);
                        return ProductItemOpt1;
                        //}
                        // 
                    }
                });
            });
        }
        else {
            return ProductItemOpt;
        }
    }
    else
        return ProductItem;
}

function getAllSelectedOptionsOfProductItem(flyoutItemName = "") {
    //get the option id of all selected options 
    //181,1361
    var selectedOptions = "";
    var isTypeDProduct = $("#hdnIsTypeDProduct").val().toLowerCase();
    //console.log(isTypeDProduct);
    if (isTypeDProduct === "false") {

        if ($('input:hidden[id^="hdnOption_"]').length > 0) {

            $.each($('input:hidden[id^="hdnOption_"]'), function (index, object) {

                var optionValue = $("#" + object.id).val().replace("©", "");
                if (optionValue !== "" && optionValue !== undefined) {
                    if (selectedOptions === "")
                        selectedOptions = optionValue;
                    else
                        selectedOptions = selectedOptions + "," + optionValue;
                }
            });
        }
    }
    else {

        if (flyoutItemName !== null && flyoutItemName !== undefined && flyoutItemName !== "") {
            if ($('input:checkbox[id^="customCheckSelected_"]:checked').length > 0) {
                $.each($('input:checkbox[id^="customCheckSelected_"]:checked'), function (i, itmObj) {
                    var itemName = itmObj.id.replace("customCheckSelected_", "");
                    //if (itemName === flyoutItemName) {
                    if ($('input:hidden[id^="hdnFlyOutOption_' + itemName + '_"]').length > 0) {
                        $.each($('input:hidden[id^="hdnFlyOutOption_' + itemName + '_"]'), function (index, object) {
                            var optionValue = $("#" + object.id).val().replace("©", "");
                            if (optionValue !== "" && optionValue !== undefined) {
                                if (selectedOptions === "")
                                    selectedOptions = optionValue;
                                else
                                    selectedOptions = selectedOptions + "," + optionValue;
                            }

                        });

                        //}
                    }
                });
            }
        }
    }
    return selectedOptions;
}

function onProductListClick(controlId, selectedCategory, itemPrice, orgPrice, offerPrice, quantityLeft) {
    var get_value = controlId.split("£");
    optionSelectionPriceChange(itemPrice, get_value[0], orgPrice, offerPrice);
    specialsOptionSelectionQuantityUpdateAfterCart(get_value[0], quantityLeft);
    imageSelection(controlId);

    if (controlId.indexOf("AllOptions") > -1) {// common option selected
        var RadioButtonSelectedValue = $("#hdnOptionValue_" + controlId).val();
        if ($("#hdnOptionId_" + controlId) != undefined && $("#hdnOptionId_" + controlId).val() != 0)
            $("#hdnOption_" + selectedCategory).val($("#hdnOptionId_" + controlId).val());
        else
            $("#hdnOption_" + selectedCategory).val(RadioButtonSelectedValue);
        $("#ColorLarge_" + selectedCategory).html(RadioButtonSelectedValue);
        $("#ColorLargeopt_" + selectedCategory).toggleClass("show");
        if ($("#hdnIsTypeDProduct").val() == "True") {
            $('input:hidden[id^="hdnOption_"]').each(function () {
                //var category = this.id.replace("hdnOption_", "");
                var CollectiveIds = $("[id*=" + RadioButtonSelectedValue.replace(/\s/g, '©') + "]");
                $.each(CollectiveIds, function (index, object) {
                    var RadioId = object.id;
                    $("#" + $.escapeSelector(RadioId)).prop("checked", true);
                    onProductItemOptionsClick(get_value[0].replace(/©/g, " "), get_value[1].replace(/©/g, " "), get_value[2].replace(/©/g, " "), controlId);
                });
            });
            $("input[type=radio][id=" + controlId + "]").attr("checked", true);
        }
    }
    else {
        onProductItemOptionsClick(get_value[0].replace(/©/g, " "), get_value[1].replace(/©/g, " "), get_value[2].replace(/©/g, " "), controlId);
        calculateProductSummary();
    }
    if ($("#hdnIsInInventory").val() == "true" || $("#hdnIsStateWiseHide").val() == "true" || $("#hdnIsItemAvailable").val() == "true" || $("#hdnIsPickupOnly").val() == "true") inventory_check();
}

function getObjectItem(value) {
    var ProductItem = [];
    $.each(ProductItemDetails, function (MainIndex, MainObject) {
        $.each(MainObject.ProductOptions, function (index, object) {
            var OptionValue = object.OptionValue.replace(/[^a-z0-9\s\-]/gi, '').replace(/[_\s]/g, ' ');
            if (OptionValue == value.replace(/©/g, " ")) {
                // if (name == "alloption") {
                ProductItem.push(ProductItemDetails[MainIndex])
                return ProductItem;
                //}
                // 
            }
        });
    });
    return ProductItem;
}

function InstallOptionChanged(id) {
    var item_name = id.split('_');
    if (id.indexOf('_') > -1) {
        if (item_name[0] == 'customRadioInstalled') {
            //if (!$("#FlyoutDeliveryOptionDiv_" + item_name[1]).hasClass("d-none")) $("#FlyoutDeliveryOptionDiv_" + item_name[1]).addClass("d-none");
            $('input[type=radio][id="customRadioInstalled_' + item_name[1] + '"]').attr("checked", true);
            $('input[type=radio][id="customRadioInstalled_' + item_name[1] + '"]').prop("checked", true);
            $('input[type=radio][id="customRadioUninstalled_' + item_name[1] + '"]').attr("checked", false);
            $('input[type=radio][id="customRadioUninstalled_' + item_name[1] + '"]').prop("checked", false);
            $('#PriceInstalled_' + item_name[1]).hide();
            $('#PriceUnInstalled_' + item_name[1]).show();

            $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').removeAttr("disabled");
            $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').prop("disabled", false);

            $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').removeAttr("checked");
            $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').prop("checked", false);

            $('input[type=radio][id="customRadioPickinStore_' + item_name[1] + '"]').removeAttr("checked");
            $('input[type=radio][id="customRadioPickinStore_' + item_name[1] + '"]').prop("checked", false);

            $("#deliveryType").val("installed");

        }
        else {
            //if ($("#FlyoutDeliveryOptionDiv_" + item_name[1]).hasClass("d-none")) $("#FlyoutDeliveryOptionDiv_" + item_name[1]).removeClass("d-none");

            $('input[type=radio][id="customRadioInstalled_' + item_name[1] + '"]').attr("checked", false);
            $('input[type=radio][id="customRadioInstalled_' + item_name[1] + '"]').prop("checked", false);
            $('input[type=radio][id="customRadioUninstalled_' + item_name[1] + '"]').attr("checked", true);
            $('input[type=radio][id="customRadioUninstalled_' + item_name[1] + '"]').prop("checked", true);
            $('#PriceInstalled_' + item_name[1]).show();
            $('#PriceUnInstalled_' + item_name[1]).hide();

            if ($("#hdnPickupOnly").val().toLowerCase() == "true" || $("#ItemAvailability").val() == "6") {
                $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').attr("disabled", true);
                $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').prop("disabled", true);

                $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').removeAttr("checked");
                $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').prop("checked", false);

                $('input[type=radio][id="customRadioPickinStore_' + item_name[1] + '"]').attr("checked", true);
                $('input[type=radio][id="customRadioPickinStore_' + item_name[1] + '"]').prop("checked", true);

                $("#deliveryType").val("pickup in store");
            }
            else {
                $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').removeAttr("disabled");
                $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').prop("disabled", false);

                $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').attr("checked", true);
                $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').prop("checked", true);

                $('input[type=radio][id="customRadioPickinStore_' + item_name[1] + '"]').removeAttr("checked");
                $('input[type=radio][id="customRadioPickinStore_' + item_name[1] + '"]').prop("checked", false);

                $("#deliveryType").val("ship to me");
            }
        }
    }
    else {
        $("input:radio[name^='InstallOptionRadioGroup']").each(function () {
            $("#" + this.id).attr("checked", false);
        });
        if (id == 'customRadioInstalled') {
            if (!$("#DeliveryOptionDiv").hasClass("d-none")) $("#DeliveryOptionDiv").addClass("d-none");

            $('input[type=radio][id="customRadioShipMe_CommonOption"]').prop("disabled", false);
            $('input[type=radio][id="customRadioShipMe_CommonOption"]').removeAttr("disabled");

            $('input[type=radio][id="customRadioShipMe_CommonOption"]').prop("checked", false);
            $('input[type=radio][id="customRadioShipMe_CommonOption"]').removeAttr("checked");

            $('input[type=radio][id="customRadioPickinStore_CommonOption"]').prop("checked", false);
            $('input[type=radio][id="customRadioPickinStore_CommonOption"]').removeAttr("checked");
            $("#deliveryType").val("installed");
        }
        else {
            if ($("#DeliveryOptionDiv").hasClass("d-none")) $("#DeliveryOptionDiv").removeClass("d-none");
            if ($("#hdnPickupOnly").val().toLowerCase() == "true" || $("#ItemAvailability").val() == "6") {
                $('input[type=radio][id="customRadioShipMe_CommonOption"]').attr("disabled", true);
                $('input[type=radio][id="customRadioShipMe_CommonOption"]').prop("disabled", true);

                $('input[type=radio][id="customRadioShipMe_CommonOption"]').removeAttr("checked");
                $('input[type=radio][id="customRadioShipMe_CommonOption"]').prop("checked", false);

                $('input[type=radio][id="customRadioPickinStore_CommonOption"]').attr("checked", true);
                $('input[type=radio][id="customRadioPickinStore_CommonOption"]').prop("checked", true);

                $("#deliveryType").val("pickup in store");
            }
            else {
                $('input[type=radio][id="customRadioShipMe_CommonOption"]').removeAttr("disabled");
                $('input[type=radio][id="customRadioShipMe_CommonOption"]').prop("disabled", false);

                $('input[type=radio][id="customRadioShipMe_CommonOption"]').attr("checked", true);
                $('input[type=radio][id="customRadioShipMe_CommonOption"]').prop("checked", true);

                $('input[type=radio][id="customRadioPickinStore_CommonOption"]').removeAttr("checked");
                $('input[type=radio][id="customRadioPickinStore_CommonOption"]').prop("checked", false);

                $("#deliveryType").val("ship to me");
            }
        }
        $("input:radio[id^='" + id + "']").each(function () {
            $("#" + this.id).attr("checked", true);
            if (this.id.indexOf('_') > -1) {// flyout install option
                var item_name = this.id.split('_');
                if (item_name[0] == 'customRadioInstalled') {

                    //if (!$("#FlyoutDeliveryOptionDiv_" + item_name[1]).hasClass("d-none")) $("#FlyoutDeliveryOptionDiv_" + item_name[1]).addClass("d-none");

                    $('input[type=radio][id="customRadioInstalled_' + item_name[1] + '"]').attr("checked", true);
                    $('input[type=radio][id="customRadioInstalled_' + item_name[1] + '"]').prop("checked", true);
                    $('input[type=radio][id="customRadioUninstalled_' + item_name[1] + '"]').attr("checked", false);
                    $('input[type=radio][id="customRadioUninstalled_' + item_name[1] + '"]').prop("checked", false);
                    $('#PriceInstalled_' + item_name[1]).hide();
                    $('#PriceUnInstalled_' + item_name[1]).show();

                    $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').prop("disabled", false);
                    $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').removeAttr("disabled");

                    $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').prop("checked", false);
                    $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').removeAttr("checked");

                    $('input[type=radio][id="customRadioPickinStore_' + item_name[1] + '"]').prop("checked", false);
                    $('input[type=radio][id="customRadioPickinStore_' + item_name[1] + '"]').removeAttr("checked");

                    $("#deliveryType").val("installed");
                }
                else {
                    //if ($("#FlyoutDeliveryOptionDiv_" + item_name[1]).hasClass("d-none")) $("#FlyoutDeliveryOptionDiv_" + item_name[1]).removeClass("d-none");

                    $('input[type=radio][id="customRadioInstalled_' + item_name[1] + '"]').attr("checked", false);
                    $('input[type=radio][id="customRadioInstalled_' + item_name[1] + '"]').prop("checked", false);
                    $('input[type=radio][id="customRadioUninstalled_' + item_name[1] + '"]').attr("checked", true);
                    $('input[type=radio][id="customRadioUninstalled_' + item_name[1] + '"]').prop("checked", true);
                    $('#PriceInstalled_' + item_name[1]).show();
                    $('#PriceUnInstalled_' + item_name[1]).hide();
                    //$("#FlyoutDeliveryOptionDiv_" + item_name[1]).removeClass("d-none");

                    if ($("#hdnPickupOnly").val().toLowerCase() == "true" || $("#ItemAvailability").val() == "6") {
                        $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').attr("disabled", true);
                        $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').prop("disabled", true);

                        $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').removeAttr("checked");
                        $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').prop("checked", false);

                        $('input[type=radio][id="customRadioPickinStore_' + item_name[1] + '"]').attr("checked", true);
                        $('input[type=radio][id="customRadioPickinStore_' + item_name[1] + '"]').prop("checked", true);

                        $("#deliveryType").val("pickup in store");
                    }
                    else {
                        $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').removeAttr("disabled");
                        $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').prop("disabled", false);

                        $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').attr("checked", true);
                        $('input[type=radio][id="customRadioShipMe_' + item_name[1] + '"]').prop("checked", true);

                        $('input[type=radio][id="customRadioPickinStore_' + item_name[1] + '"]').removeAttr("checked");
                        $('input[type=radio][id="customRadioPickinStore_' + item_name[1] + '"]').prop("checked", false);

                        $("#deliveryType").val("ship to me");
                    }
                }
            }
            else {
                if (id == 'customRadioInstalled') {
                    if (!$("#DeliveryOptionDiv").hasClass("d-none")) $("#DeliveryOptionDiv").addClass("d-none");

                    $('input[type=radio][id^="customRadioShipMe"]').removeAttr("disabled");
                    $('input[type=radio][id^="customRadioShipMe"]').prop("disabled", false);

                    $('input[type=radio][id^="customRadioShipMe"]').removeAttr("checked");
                    $('input[type=radio][id^="customRadioShipMe"]').prop("checked", false);

                    $('input[type=radio][id^="customRadioPickinStore"]').removeAttr("checked");
                    $('input[type=radio][id^="customRadioPickinStore"]').prop("checked", false);

                    $("#deliveryType").val("installed");
                }
                else {
                    if ($("#DeliveryOptionDiv").hasClass("d-none")) $("#DeliveryOptionDiv").removeClass("d-none");
                    if ($("#hdnPickupOnly").val().toLowerCase() == "true" || $("#ItemAvailability").val() == "6") {
                        $('input[type=radio][id^="customRadioShipMe"]').attr("disabled", true);
                        $('input[type=radio][id^="customRadioShipMe"]').prop("disabled", true);

                        $('input[type=radio][id^="customRadioShipMe"]').removeAttr("checked");
                        $('input[type=radio][id^="customRadioShipMe"]').prop("checked", false);

                        $('input[type=radio][id^="customRadioPickinStore"]').attr("checked", true);
                        $('input[type=radio][id^="customRadioPickinStore"]').prop("checked", true);

                        $("#deliveryType").val("pickup in store");
                    }
                    else {
                        $('input[type=radio][id^="customRadioShipMe"]').removeAttr("disabled");
                        $('input[type=radio][id^="customRadioShipMe"]').prop("disabled", false);

                        $('input[type=radio][id^="customRadioShipMe"]').attr("checked", true);
                        $('input[type=radio][id^="customRadioShipMe"]').prop("checked", true);

                        $('input[type=radio][id^="customRadioPickinStore"]').removeAttr("checked");
                        $('input[type=radio][id^="customRadioPickinStore"]').prop("checked", false);

                        $("#deliveryType").val("ship to me");
                    }
                }
            }
        });
    }
    calculateProductSummary();
}

function DeliveryOptionChanged(id) {
    if (id.split('_')[1] == "CommonOption") {
        $("input:radio[name^='DeliveryOptionRadioGroup']").each(function () {
            $("#" + this.id).removeAttr("checked");
        });
        $("input:radio[id^='" + id.split('_')[0] + "']").each(function () {
            var selectedDeliveryOption = this.id.split('_');
            if (selectedDeliveryOption[1] != "CommonOption") {
                if (selectedDeliveryOption[0] == "customRadioShipMe") {
                    $('input[type=radio][id="customRadioShipMe_' + selectedDeliveryOption[1] + '"]').attr("checked", true);
                    $('input[type=radio][id="customRadioShipMe_' + selectedDeliveryOption[1] + '"]').prop("checked", true);
                    $('input[type=radio][id="customRadioPickinStore_' + selectedDeliveryOption[1] + '"]').attr("checked", false);
                    $('input[type=radio][id="customRadioPickinStore_' + selectedDeliveryOption[1] + '"]').prop("checked", false);
                    $("#deliveryType").val("ship to me");
                }
                else if (selectedDeliveryOption[0] == "customRadioPickinStore") {
                    $('input[type=radio][id="customRadioShipMe_' + selectedDeliveryOption[1] + '"]').attr("checked", false);
                    $('input[type=radio][id="customRadioShipMe_' + selectedDeliveryOption[1] + '"]').prop("checked", false);
                    $('input[type=radio][id="customRadioPickinStore_' + selectedDeliveryOption[1] + '"]').attr("checked", true);
                    $('input[type=radio][id="customRadioPickinStore_' + selectedDeliveryOption[1] + '"]').prop("checked", true);
                    $("#deliveryType").val("pickup in store");
                }
            }
            else {
                if (selectedDeliveryOption[0] == "customRadioShipMe") {
                    $('input[type=radio][id="customRadioPickinStore_CommonOption"]').removeAttr("checked");
                    $('input[type=radio][id="customRadioPickinStore_CommonOption"]').prop("checked", false);
                    $('input[type=radio][id="customRadioShipMe_CommonOption"]').attr("checked", true);
                    $('input[type=radio][id="customRadioShipMe_CommonOption"]').prop("checked", true);
                    $("#deliveryType").val("ship to me");
                }
                else if (selectedDeliveryOption[0] == "customRadioPickinStore") {
                    $('input[type=radio][id="customRadioShipMe_CommonOption"]').removeAttr("checked");
                    $('input[type=radio][id="customRadioShipMe_CommonOption"]').prop("checked", false);
                    $('input[type=radio][id="customRadioPickinStore_CommonOption"]').attr("checked", true);
                    $('input[type=radio][id="customRadioPickinStore_CommonOption"]').prop("checked", true);
                    $("#deliveryType").val("pickup in store");
                }
            }
        });
    }
    else {
        var selectedDeliveryOption = id.split('_');
        if (selectedDeliveryOption[0] == "customRadioShipMe") {
            $('input[type=radio][id="customRadioShipMe_' + selectedDeliveryOption[1] + '"]').attr("checked", true);
            $('input[type=radio][id="customRadioShipMe_' + selectedDeliveryOption[1] + '"]').prop("checked", true);
            $('input[type=radio][id="customRadioPickinStore_' + selectedDeliveryOption[1] + '"]').attr("checked", false);
            $('input[type=radio][id="customRadioPickinStore_' + selectedDeliveryOption[1] + '"]').prop("checked", false);
            $("#deliveryType").val("ship to me");
        }
        else if (selectedDeliveryOption[0] == "customRadioPickinStore") {
            $('input[type=radio][id="customRadioShipMe_' + selectedDeliveryOption[1] + '"]').attr("checked", false);
            $('input[type=radio][id="customRadioShipMe_' + selectedDeliveryOption[1] + '"]').prop("checked", false);
            $('input[type=radio][id="customRadioPickinStore_' + selectedDeliveryOption[1] + '"]').attr("checked", true);
            $('input[type=radio][id="customRadioPickinStore_' + selectedDeliveryOption[1] + '"]').prop("checked", true);
            $("#deliveryType").val("pickup in store");
        }
    }
}

function calculateProductSummary() {
    var total = 0.0;
    var count = 0;
    $("#SummarySubTotal").text('');
    $("#SummaryListDiv").empty();
    $('div[id="FlyoutValidateOption"]').hide();
    $('#maximumQtyMsg').addClass("d-none");
    $('[id^="maximumQtyMsg_"]').each(function () {
        var itemName = this.id.replace("maximumQtyMsg_", "");
        $('#maximumQtyMsg_' + itemName).addClass("d-none");
    });

    if ($("div[class=OpionsOfProductItem]").length > 0) {
        var OptionTypeColor = $("div[class=OpionsOfProductItem]").find(".colourSquares ");
        if (OptionTypeColor.length > 0) {
            OptionTypeColor = $("div[class=OpionsOfProductItem]").find(".colourSquares.active");
            //$('input:checkbox[id^="customCheckSelected_"]:checked').each(function () {
            //    $("#" + this.id).prop("checked", false);
            //});
            $.each(OptionTypeColor, function (index, object) {
                var className = object.className.replace("colourSquares ", "").replace(" active", "");
                //$("input:checkbox[id*=customCheckSelected_" + className + "]").prop("checked", true); getAllSelectOptionProductDetails(ProductItemName, OptionCategory, productOption)
                //colorSquare-Front©Floor©Mats£Color£Gray£1
                var selectItemOption = (object.id).replace("colorSquare-", "").replace(/©/g, " ").split("£");
                var selectedOption = getAllSelectOptionProductDetails(selectItemOption[0], selectItemOption[1], selectItemOption[2]);
                //if (selectedOption.length > 0 && !selectedOption[0].IsStateWiseHide) $("input:checkbox[id*=customCheckSelected_" + className + "]").prop("checked", true);
                if (selectedOption.length > 0 && selectedOption[0].IsInInventory) $("input:checkbox[id*=customCheckSelected_" + className + "]").prop("checked", true);
                $("#lblSelectedItemColor" + className).text(selectItemOption[2]);
            });
        }
        else {
            var RadioButtonNames = [];
            $.each($("div[class=OpionsOfProductItem]").find("input:radio"), function (index, object) {
                //var data = getObjects(RadioButtonNames, 'name', object.name);
                var data = getProductObjectItem(getAllSelectedOptionsOfProductItem(object.name));
                if (data !== undefined && data.length === 0) {
                    if ($("div[class=OpionsOfProductItem]").find("input:radio:checked").length == 0) {
                        RadioButtonNames.push({
                            name: object.name,
                            id: object.id
                        });
                    }
                }
            });
            if (RadioButtonNames.length > 0) {
                $(RadioButtonNames).each(function (index, object) {
                    //var flyoutId = this.id.replace(/_/g, "£").replace("hdnFlyOutOption£", "hdnFlyOutOptionId_") + "£" + passedOption[2].replace(/©/g, " ");
                    $('#' + object.id).attr('checked', "true");
                    var selectedOption = $('#hdnFlyOutOptionId_' + object.id).val();
                    var productItem = object.id.split('£');
                    var hdnSelectedOptionId = "hdnFlyOutOption_" + productItem[0] + "_" + productItem[1];
                    $("#" + hdnSelectedOptionId).val(selectedOption);
                    $('input:checkbox[id^="customCheckSelected_' + productItem[0] + '"]').prop("checked", true);
                    var price = $('#hdnFlyOutPrice_' + object.id).val();
                    optionSelectionPriceChange(price, productItem);
                    //$('#PriceInstalled_' + ProductItem[0]).show();
                    //$('#PriceUnInstalled_' + ProductItem[0]).hide();
                });
            }
        }
        if ($('div[id="FlyoutInsatllOption"]').length > 0) {
            if ($('div[id="FlyoutInsatllOption"]').find('input:radio:checked').length == 0) {
                $.each($('div[id="FlyoutInsatllOption"]').find('input:radio[id^="customRadioUninstalled_"]'), function (index, object) {
                    $('#' + object.id).prop("checked", true);
                    var productItem = object.id.replace("customRadioUninstalled_", "");
                    $('#PriceInstalled_' + productItem).show();
                    $('#PriceUnInstalled_' + productItem).hide();
                    $('input:checkbox[id^="customCheckSelected_' + productItem + '"]').prop("checked", true);
                });
            }
        }
        if ($("#hdnIsInInventory").val() == "true" || $("#hdnIsStateWiseHide").val() == "true" || $("#hdnIsItemAvailable").val() == "true" || $("#hdnIsPickupOnly").val() == "true") inventory_check();
        $('input:checkbox[id^="customCheckSelected_"]:checked').each(function () {
            count = count + 1;
            var itemName = this.id.replace("customCheckSelected_", "");
            var OptionName = "";
            var optionCategory = "";
            $("." + itemName + "div>#FlyoutValidateOption").hide();
            if ($("input[type=radio][id^=" + $.escapeSelector(itemName).replace(/\s/g, "") + "]").length > 0) {

                if ($("input[type=radio][id^=" + $.escapeSelector(itemName.replace(/\s/g, "")) + "]:checked").length > 0) {
                    $("#validateOption_" + $.escapeSelector(itemName)).removeClass("d-block").addClass("d-none");
                    $("input[type=radio][id^=" + $.escapeSelector(itemName.replace(/\s/g, "")) + "]:checked").each(function () {
                        controlId = this.id;
                        if (OptionName == "") {
                            OptionName = this.id.replace(itemName + "-", "").split("£")[2].replace(/©/g, " ");
                            optionCategory = this.id.replace(itemName + "-", "").split("£")[1].replace(/©/g, " ");
                        }
                        else {
                            OptionName += "|" + this.id.replace(itemName + "-", "").split("£")[2].replace(/©/g, " ");
                            optionCategory += "|" + this.id.replace(itemName + "-", "").split("£")[1].replace(/©/g, " ");
                        }
                    });
                }
                else {
                    $("input:checkbox[id=" + this.id + "]").removeAttr("checked");
                    $("#validateOption_" + $.escapeSelector(itemName)).removeClass("d-none").addClass("d-block");
                    $("#SummaryListDiv").empty();
                }
            }
            if ($(".colourSquares." + $.escapeSelector(itemName) + ".active").length > 0) {
                controlId = this.id.replace("colorSquare-", "");
                OptionName = $(".colourSquares." + $.escapeSelector(itemName) + ".active")[0].id.split("£")[2];
                optionCategory = $(".colourSquares." + $.escapeSelector(itemName) + ".active")[0].id.split("£")[1];
            }
            var price = $('#lblPrice_' + $.escapeSelector(itemName))[0].innerHTML.replace("$", "");
            if (price.toString().indexOf(",") > -1) price = price.replaceAll(",", "");
            var imageUrl = $(".OptMainDiv.OptSpacing." + $.escapeSelector(itemName) + "div").find(".carousel-item.active").find("img");
            imageUrl = $(".OptMainDiv.OptSpacing." + $.escapeSelector(itemName) + "div").find(".carousel-item.active").find("img");
            if (imageUrl.length == 0 && $(".OptMainDiv.OptSpacing." + $.escapeSelector(itemName) + "div").find(".carousel-item>img").length > 0) {
                imageUrl = $(".OptMainDiv.OptSpacing." + $.escapeSelector(itemName) + "div").find(".carousel-item>img");
            }
            else if (imageUrl.length == 0 && $(".OptMainDiv.OptSpacing." + $.escapeSelector(itemName) + "div").find(".DivProSlider>img").length > 0) {
                imageUrl = $(".OptMainDiv.OptSpacing." + $.escapeSelector(itemName) + "div").find(".DivProSlider>img");
            }
            else if (imageUrl.length == 0 && $(".OptMainDiv.OptSpacing." + $.escapeSelector(itemName) + "div").find(".DivProSlider>img").length == 0) {
                imageUrl = $(".OptMainDiv.OptSpacing." + $.escapeSelector(itemName) + "div").find(".carousel-itemSlider>img");
            }
            var selectedItem = "<div class='float-left ProSummaryLeft'><img class='' alt='' src=\"" + imageUrl[0].src + "\" />";
            if (OptionName != "" && optionCategory != "") {
                var OptionNames = OptionName.split("|");
                var OptionCategorys = optionCategory.split("|");
                $.each(OptionCategorys, function (index, object) {
                    var id = [];
                    var xx = $('input:hidden[id^="hdnFlyOutOption_' + itemName + '_"]').each(function () {
                        if (this.id.indexOf(object) > -1)
                            id.push(this.id);
                    });
                    if (id.length > 0) {
                        var hdnCatOptionId = id[0].replace(/_/g, "£").replace("hdnFlyOutOption£", "hdnFlyOutOptionId_") + "£" + OptionNames[index].replace(/\s/g, "©");
                        //var hdnSelectedValue = $('input:hidden[id^="hdnFlyOutOptionId_"][id*="' + ProductItemName.replace(/\s/g, "©") + '_' + OptionCategory.replace(/\s/g, "©") + '"]').val();
                        $("#" + id[0]).val($('input:hidden[id^="' + hdnCatOptionId + '"]').val());
                        // $("#" + id[0]).val(OptionNames[index]);
                    }
                });
                selectedItem += "<label id='itemName_" + count + "'>" + itemName.replace(/©/g, " ") + ", (" + OptionName.replace(/©/g, " ") + ") ";
            }
            else
            {
                selectedItem += "<label id='itemName_" + count + "'>" + itemName.replace(/©/g, " ") + "";
            }

            //if ($('div[id="FlyoutInsatllOption"]').length > 0)
            //{
            //    $('div[id="FlyoutInsatllOption"]').find('input:radio[id$="' + itemName + '"]:checked').each(function (index, object) {
            //        switch (object.value) {
            //            case "Install": {
            //                price = $('#SpanInstalledPrice_' + itemName).html();
            //                $('#lblPrice_' + $.escapeSelector(itemName)).text("$" + parseFloat(price).toFixed(2).replace(".00", ""));
            //                $('#PriceInstalled_' + itemName).hide();
            //                $('#PriceUnInstalled_' + itemName).show();
            //            } break;
            //            case "uninstall": {
            //                price = $('#SpanRealPrice_' + itemName).html();
            //                $('#lblPrice_' + $.escapeSelector(itemName)).text("$" + parseFloat(price).toFixed(2).replace(".00", ""));
            //                $('#PriceInstalled_' + itemName).show();
            //                $('#PriceUnInstalled_' + itemName).hide();
            //            } break;
            //            default: {
            //                price = price;
            //                $('#lblPrice_' + $.escapeSelector(itemName)).text("$" + parseFloat(price).toFixed(2).replace(".00", ""));
            //            } break;
            //        }
            //    });
            //}
            if ($("#lblDetailsQty_" + $.escapeSelector(itemName)).text() !== undefined && $("#lblDetailsQty_" + $.escapeSelector(itemName)).text() !== "" && $("#lblDetailsQty_" + $.escapeSelector(itemName)).text() > 1)
                price = price * $("#lblDetailsQty_" + $.escapeSelector(itemName)).text();
            selectedItem += "</label></div><div class='float-left justify-content-end ProSummaryRight'><span id='ItemPrice'>$" + price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "</span> </div>";
            if ($("#SummaryListDiv").html() == "")
                $("#SummaryListDiv").append("<h3>Summary</h3>");
            $("#SummaryListDiv").append(selectedItem);
            var sum = $("#SummarySubTotal").text();
            sum = sum.substr(1);
            if (sum.trim() == "" || sum == "NaN") sum = "00";
            if (sum.indexOf(",") > -1) sum = sum.replaceAll(",", "");
            total = parseFloat(sum) + parseFloat(price);
            $("#SummarySubTotal").text("$" + total.toFixed(2).replace(".00", "").toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));

        });
    }
    else {
        if ($('div[id="FlyoutInsatllOption"]').length > 0) {
            if ($('div[id="FlyoutInsatllOption"]').find('input:radio:checked').length == 0) {
                $.each($('div[id="FlyoutInsatllOption"]').find('input:radio[id^="customRadioUninstalled_"]'), function (index, object) {
                    $('#' + object.id).prop("checked", true);
                    var productItem = object.id.replace("customRadioUninstalled_", "");
                    $('#PriceInstalled_' + productItem).show();
                    $('#PriceUnInstalled_' + productItem).hide();
                    $('input:checkbox[id^="customCheckSelected_' + productItem + '"]').prop("checked", true);
                });
            }
        }
        $('input:checkbox[id^="customCheckSelected_"]:checked').each(function () {
            count = count + 1;
            var itemName = this.id.replace("customCheckSelected_", "");
            $("." + itemName + "div>#FlyoutValidateOption").hide();
            //if ($('div[id="FlyoutInsatllOption"]').length > 0) {
            //    $('div[id="FlyoutInsatllOption"]').find('input:radio[id$="' + itemName + '"]:checked').each(function (index, object) {
            //        switch (object.value) {
            //            case "Install": {
            //                price = $('#SpanInstalledPrice_' + itemName).html();
            //                $('#lblPrice_' + $.escapeSelector(itemName)).text("$" + parseFloat(price).toFixed(2).replace(".00", ""));
            //                $('#PriceInstalled_' + itemName).hide();
            //                $('#PriceUnInstalled_' + itemName).show();
            //            } break;
            //            case "uninstall": {
            //                price = $('#SpanRealPrice_' + itemName).html();
            //                $('#lblPrice_' + $.escapeSelector(itemName)).text("$" + parseFloat(price).toFixed(2).replace(".00", ""));
            //                $('#PriceInstalled_' + itemName).show();
            //                $('#PriceUnInstalled_' + itemName).hide();
            //            } break;
            //            default: {
            //                price = price;
            //                $('#lblPrice_' + $.escapeSelector(itemName)).text("$" + parseFloat(price).toFixed(2).replace(".00", ""));
            //            } break;
            //        }
            //    });
            //}

        });
        if ($("#hdnIsInInventory").val() == "true" || $("#hdnIsStateWiseHide").val() == "true" || $("#hdnIsItemAvailable").val() == "true" || $("#hdnIsPickupOnly").val() == "true") inventory_check();
        $.each($('input:checkbox[id^="customCheckSelected_"]:checked'), function (index, object) {
            var itemName = object.id.replace("customCheckSelected_", "");
            //var price = $("div[class*= " + itemName + "div]").find("#lblPrice_" + itemName)[0].innerText;
            var price = $("#lblPrice_" + itemName);
            price = price[0].innerHTML.replace("$", "");
            if (price.toString().indexOf(",") > -1) price = price.replaceAll(",", "");
            var imageUrl = $(".OptMainDiv.OptSpacing." + itemName + "div").find(".carousel-item.active").find("img");
            if (imageUrl.length == 0 && $(".OptMainDiv.OptSpacing." + itemName + "div").find(".carousel-item>img").length > 0) {
                imageUrl = $(".OptMainDiv.OptSpacing." + itemName + "div").find(".carousel-item>img");
            }
            else if (imageUrl.length == 0 && $(".OptMainDiv.OptSpacing." + itemName + "div").find(".DivProSlider>img").length > 0) {
                imageUrl = $(".OptMainDiv.OptSpacing." + itemName + "div").find(".DivProSlider>img");
            }
            else if (imageUrl.length == 0 && $(".OptMainDiv.OptSpacing." + $.escapeSelector(itemName) + "div").find(".DivProSlider>img").length == 0) {
                imageUrl = $(".OptMainDiv.OptSpacing." + $.escapeSelector(itemName) + "div").find(".carousel-itemSlider>img");
            }
            var selectedItem = "<div class='float-left ProSummaryLeft'><img class='' alt='' src=\"" + imageUrl[0].src + "\" />";
            selectedItem += "<label id='itemName_" + count + "' tabindex='0'>" + $("#hFlyoutName_" + itemName).html() + "";

            if ($("#lblDetailsQty_" + $.escapeSelector(itemName)).text() !== undefined && $("#lblDetailsQty_" + $.escapeSelector(itemName)).text() !== "" && $("#lblDetailsQty_" + $.escapeSelector(itemName)).text() > 1)
                price = price * $("#lblDetailsQty_" + $.escapeSelector(itemName)).text();

            selectedItem += "</label></div><div class='float-left justify-content-end ProSummaryRight'><span id='ItemPrice' tabindex='0'>$" + price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") + "</span> </div>";
            if ($("#SummaryListDiv").html() == "")
                $("#SummaryListDiv").append("<h3>Summary</h3>");
            $("#SummaryListDiv").append(selectedItem);
            var sum = $("#SummarySubTotal").text();
            sum = sum.substr(1);
            if (sum.trim() == "" || sum == "NaN") sum = "00";
            if (sum.indexOf(",") > -1) sum = sum.replaceAll(",", "");
            total = parseFloat(sum) + parseFloat(price);
            $("#SummarySubTotal").text("$" + total.toFixed(2).replace(".00", "").toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
        });
    }
}
//--------PreOrder Functions----------//
function changePreOrderSummery(preOrderPrice, PreOrderName) {
    var total = 0.0;
    var count = 0;
    var selectedItem = "<h3>Summary</h3>";
    var preOrderImage = $('.productDetailContainer .thumbnails').find('img');
    selectedItem += "<div class='float-left ProSummaryLeft'>";
    if (preOrderImage.length > 0) {
        selectedItem += "<img class='' alt='' src=\"" + preOrderImage[0].src + "\" />";
    }
    selectedItem += "<label id='itemName_PreOrder'>" + PreOrderName + "";
    selectedItem += "</label></div><div class='float-left justify-content-end ProSummaryRight'><span id='ItemPrice'>$" + preOrderPrice + "</span> </div>";

    $("#SummarySubTotal").text("$" + preOrderPrice.toFixed(2).replace(".00", ""));

    $('input:checkbox[id^="customCheckSelected_"]:checked').each(function (index, object) {
        count = count + 1;
        var itemName = object.id.replace("customCheckSelected_", "");
        //var price = $("div[class*= " + itemName + "div]").find("#lblPrice_" + itemName)[0].innerText;
        var price = $("#lblPrice_" + itemName);
        price = price[0].innerHTML.replace("$", "");
        var imageUrl = $(".OptMainDiv.OptSpacing." + itemName + "div").find(".carousel-item.active").find("img");

        if (imageUrl.length == 0 && $(".OptMainDiv.OptSpacing." + itemName + "div").find(".carousel-item>img").length > 0) {
            imageUrl = $(".OptMainDiv.OptSpacing." + itemName + "div").find(".carousel-item>img");
        }
        else if (imageUrl.length == 0 && $(".OptMainDiv.OptSpacing." + itemName + "div").find(".DivProSlider>img").length > 0) {
            imageUrl = $(".OptMainDiv.OptSpacing." + itemName + "div").find(".DivProSlider>img");
        }
        else if (imageUrl.length == 0 && $(".OptMainDiv.OptSpacing." + $.escapeSelector(itemName) + "div").find(".DivProSlider>img").length == 0) {
            imageUrl = $(".OptMainDiv.OptSpacing." + $.escapeSelector(itemName) + "div").find(".carousel-itemSlider>img");
        }

        selectedItem += "<div class='float-left ProSummaryLeft'><img class='' alt='' src=\"" + imageUrl[0].src + "\" />";
        selectedItem += "<label id='itemName_" + count + "' tabindex='0'>" + $("#hName_" + itemName).html() + "";
        selectedItem += "</label></div><div class='float-left justify-content-end ProSummaryRight'><span id='ItemPrice' tabindex='0'>$" + price + "</span> </div>";

        var sum = $("#SummarySubTotal").text();
        sum = sum.substr(1);
        //if (sum.trim() == "" || sum == "NaN") sum = "00";

        if (sum.trim() == "" || sum == "NaN") sum = preOrderPrice;
        total = parseFloat(sum) + parseFloat(price);
        $("#SummarySubTotal").text("$" + total.toFixed(2).replace(".00", ""));
        //$("#SummarySubTotal").text("$" + preOrderPrice.toFixed(2).replace(".00", ""));
    });

    $("#SummaryListDiv").html(selectedItem);
}

$('#frmAddtoCart-PreOrder-accessories').on("submit", function () {
    var ids = [];
    $.each($('input:checkbox[id^="customCheckSelected_"]:checked'), function (index, object) {
        ids.push($(this).data('id'));
    });
    $('#accessories_itemDetails').val(ids.join(','));
});
//--------PreOrder Functions----------//
function changeOptionBasedOnCombination(relatedOptions, selectedCatOption) {
    var countOptions = $('div[id^="divOption_"]').length;
    if (countOptions == 1) {
        return;
    }
    else {
        //relatedOptions =Color£Black^Gender£Mens:Size£S,Color£White^Gender£Mens:Gender£Ladies:Size£S:Size£XL,Color£Titan^Gender£Ladies:Size£XL,Gender£Mens^Color£Black:Color£White:Size£S,Gender£Ladies^Color£Titan:Color£White:Size£XL,Size£S^Color£Black:Color£White:Gender£Mens,Size£XL^Color£Titan:Color£White:Gender£Ladies
        if (relatedOptions != "") {
            var listCatOptionCombinations = [];
            var listSelectedOptionCombinations = [];
            var lstRelCatOptions = relatedOptions.split(',');
            $.each(lstRelCatOptions, function (index, data) {
                var mainOptionValues = data.split('^');//data=Color£Black^Gender£Mens:Size£S
                if (listCatOptionCombinations.indexOf(mainOptionValues[0]) < 0)
                    listCatOptionCombinations.push(mainOptionValues[0]);
                if (selectedCatOption == mainOptionValues[0] && listSelectedOptionCombinations.indexOf(mainOptionValues[0]) < 0) {
                    listSelectedOptionCombinations.push(mainOptionValues[0]);
                }
                if (mainOptionValues.length == 2) {
                    var lstRelatedOption = mainOptionValues[1].split(':');
                    $.each(lstRelatedOption, function (i, val) {
                        //val=Gender£Mens                       
                        if (selectedCatOption == mainOptionValues[0] && listSelectedOptionCombinations.indexOf(val) < 0) {
                            listSelectedOptionCombinations.push(val);// getting last selected option's related options
                        }
                        if (listCatOptionCombinations.indexOf(val) < 0)
                            listCatOptionCombinations.push(val);// getting all category option
                    });
                }
            });
            var lstSelectedOptions = [];
            var colorSelected = "";
            var colourSquaresList = $(".colourSquares.outer");
            var colorRelatedOptions = [];
            var selectedRelatedOptions = [];
            $.each(colourSquaresList, function (index, object) {
                if ($("#" + object.id).hasClass("active")) {
                    if (lstSelectedOptions.indexOf(object.id) < 0) {
                        var idSplit = object.id.split("£");
                        var selectedOption = "";
                        if (idSplit.length <= 4)
                            selectedOption = idSplit[1] + "£" + idSplit[2]
                        if (selectedOption != "") {
                            colorSelected = selectedOption;
                            colorRelatedOptions.push(colorSelected);
                            lstSelectedOptions.push(selectedOption)// getting if any colorsquare in common option is selected
                        }
                    }
                }
            });
            $.each(listCatOptionCombinations, function (index, data) {
                var rdId = "AllOptions£" + data + "£0";
                var category = data.split("£")[0];
                if (category.toLowerCase().indexOf('color') > -1 || (($("#divOption_" + category).is(':visible') && $("#" + data).is(':visible')) && listSelectedOptionCombinations.indexOf(data) > -1)) {// checking the selected item option is visible or not
                    if ($("input[id=" + rdId + "]").is(':checked')) {
                        if (lstSelectedOptions.indexOf(data) < 0) {
                            lstSelectedOptions.push(data); // getting all selected options except colorsquare
                        }
                    }
                }
                else if (listSelectedOptionCombinations.indexOf(data) < 0) {
                    rdId = "AllOptions£" + data + "£0";
                    $('input:radio[class=custom-control-input][id=' + rdId + ']').prop('checked', false);
                }
            });
            $('button[id^="ColorLarge_"]').each(function (index, obj) {// selected checking in dropdown option
                $.each(listCatOptionCombinations, function (index, data) {
                    if (obj.id.indexOf(data.split("£")[0]) > -1) {
                        var rdId = "AllOptions£" + data + "£0";
                        var category = data.split("£")[0];
                        var selectText = "Select " + category.replace(/©/g, " ").trim();
                        var selectedOption = $("#" + rdId).text().trim();
                        if (category.toLowerCase().indexOf('color') > -1 || ($("#divOption_" + category).is(':visible') && $("#" + obj.id).text().trim() != selectText)) {// checking the selected item option is visible or not
                            if ($("#" + obj.id).text().trim() == selectedOption) {
                                lstSelectedOptions.push(data);
                                if (category.toLowerCase().indexOf("paint©color©family") > -1) {
                                    colorSelected = data;
                                    colorRelatedOptions.push(colorSelected);
                                }
                            }

                        }
                    }

                });
            });
            $.each(lstRelCatOptions, function (index, data) {
                var mainOptionValues = data.split('^');//data=Color£Black^Gender£Mens:Size£S
                if (mainOptionValues.length == 2) {
                    if (mainOptionValues[0] == colorSelected) {
                        var lstRelatedOption = mainOptionValues[1].split(':');
                        $.each(lstRelatedOption, function (i, val) {
                            selectedRelatedOptions.push(val);// getting all the related options of each selected options
                            colorRelatedOptions.push(val);
                        });
                    }
                }
            });
            if (colorRelatedOptions.length > 0) {// if color is selected
                $.each(lstSelectedOptions, function (i, d) {
                    if (colorRelatedOptions.indexOf(d) < 0)
                        lstSelectedOptions.splice(i, 1);//if the selected item not in selected color related options, remove that item
                });
            }
            var countSelectedOption = lstSelectedOptions.length;
            $.each(lstSelectedOptions, function (i, d) {
                selectedRelatedOptions.push(d);
                if (d != colorSelected) {
                    $.each(lstRelCatOptions, function (index, data) {
                        var mainOptionValues = data.split('^');//data=Color£Black^Gender£Mens:Size£S
                        if (mainOptionValues.length == 2) {
                            if (mainOptionValues[0] == d) {
                                var lstRelatedOption = mainOptionValues[1].split(':');
                                $.each(lstRelatedOption, function (i, val) {
                                    selectedRelatedOptions.push(val);// getting all the related options of each selected options
                                });
                            }
                        }
                    });
                }
            });
            var countRelated = selectedRelatedOptions.reduce(function (obj, elem) {
                obj[elem] = obj[elem] || 0;
                obj[elem]++;
                return obj;
            }, {});
            var relatedOptionsToShow = [];
            var selectedCat = selectedCatOption.split("£")[0];
            for (data in countRelated) {
                var cat = data.split("£")[0];
                var selected = lstSelectedOptions.join(",");
                if (((countRelated[data] == countSelectedOption || ((selected.indexOf(cat + "£") > -1) && (countRelated[data] == countSelectedOption - 1)))
                    || ((selectedCat.toLowerCase().indexOf("color") > -1 && $('div[id^="ColorLargeopt_"]').length <= 0 && countSelectedOption == 1) || selectedCat.toLowerCase().indexOf("paint©color©family") > -1))
                    && (colorRelatedOptions.length == 0 || colorRelatedOptions.indexOf(data) > -1)) {
                    relatedOptionsToShow.push(data);// getting related options common to all the selected options
                }
            }
            var divOptionShow = [];
            $.each(listCatOptionCombinations, function (index, data) {
                // showing option if it exists in relatedOptionsToShow other wise hiding the options
                var cat = data.split("£")[0];
                var selectedCat = selectedCatOption.split("£")[0];
                if (relatedOptionsToShow.indexOf(data) > -1 || selectedCatOption == data) {//data=Paint©Color©Family£SilverGrey
                    if ((cat.toLowerCase().indexOf("color") > -1 && $('div[id^="ColorLargeopt_"]').length <= 0) || cat.toLowerCase().indexOf("paint©color©family") > -1) {
                        if (divOptionShow.indexOf("divOption_" + cat) < 0) {// color squares never hide
                            divOptionShow.push("divOption_" + cat);
                        }
                    }
                    else {
                        var rdId = "AllOptions£" + data + "£0";
                        if ($('div[id^="ColorLargeopt_"]').length > 0 && $("#" + data).parent().attr('id') == rdId) {// dropdown option checking
                            $("#" + rdId).css("display", "flex");
                            if (divOptionShow.indexOf("divOption_" + cat) < 0) {
                                divOptionShow.push("divOption_" + cat);
                            }
                        }
                        else {
                            $("#" + data).css("display", "flex");
                            var parentDiv = $("#" + data).parent().parent().attr('id');
                            if (divOptionShow.indexOf(parentDiv) < 0) {
                                divOptionShow.push(parentDiv);
                            }
                        }
                    }
                }
                else if (cat != selectedCat) {
                    if ((cat.toLowerCase().indexOf("color") > -1 && $('div[id^="ColorLargeopt_"]').length <= 0) || cat.toLowerCase().indexOf("paint©color©family") > -1) {// color squares or paint color family never hide
                        if (divOptionShow.indexOf("divOption_" + cat) < 0) {
                            divOptionShow.push("divOption_" + cat);
                        }
                    }
                    else {
                        var rdId = "AllOptions£" + data + "£0";
                        if ($('div[id^="ColorLargeopt_"]').length > 0 && $("#" + data).parent().attr('id') == rdId) {// dropdown option checking
                            if (selectedCat != "Scale") {
                                $("#" + rdId).css("display", "none");
                                var btnId = "ColorLarge_" + cat;
                                var selectText = "Select " + cat.replace(/©/g, " ").trim();
                                $("#hdnOption_" + cat).val("");
                                $("#" + btnId).text(selectText);
                            }
                        }
                        else {
                            var rdId = "AllOptions£" + data + "£0";
                            $('input:radio[class=custom-control-input][id=' + rdId + ']').prop('checked', false);// remove selection of already selected option which is not a related option of last selected option
                            if ($("#hdnOption_" + cat).val() == $("#hdnOptionId_" + rdId).val()) {
                                $("#hdnOption_" + cat).val("");
                            }
                            $("#" + data).css("display", "none");
                        }

                    }
                }
            });
            $('div[id^="divOption_"]').each(function () {
                if (divOptionShow.indexOf(this.id) < 0) {
                    $(this).css("display", "none");
                }
                else {
                    $(this).css("display", "block");
                }
            });
        }
    }
}

if ($('.ProInfoDescrip').height() <= 50) {
    $('.Hideshadow').hide();
} else {
    $('.Hideshadow').show();
}

function AddToCartButton_OnClick() {
    if ($("input:checkbox[id^=customCheckSelected_]").length > 0) {
        if ($("input:checkbox[id^=customCheckSelected_]:checked").length == 0) {
            $('div[id="FlyoutValidateOption"]>span').each(function () {
                this.innerText = "Please choose an option.";
            })
            $('div[id="FlyoutValidateOption"]').show();
            return false;
        }
        else {
            $('div[id="FlyoutValidateOption"]').hide();
            return true;
        }
    }
}
//Details Hide Show
var allOSB = [];
var mxh = '';

// Update on resize
window.onresize = function () {
    updateReadMore();
}

// show only the necessary read-more buttons
function updateReadMore() {
    if (allOSB.length > 0) {
        for (var i = 0; i < allOSB.length; i++) {
            if (allOSB[i].scrollHeight > mxh) {
                if (allOSB[i].hasAttribute("style")) {
                    updateHeight(allOSB[i]);
                }
                allOSB[i].nextElementSibling.className = "MoreDiv";
            }
            else {
                allOSB[i].nextElementSibling.className = "MoreDiv hid";
            }
        }
    }
}

function revealThis(current) {
    var el = current.previousElementSibling;
    if (el.hasAttribute("style")) {
        current.innerHTML = "Show More";
        el.removeAttribute("style");
        $('.Hideshadow').show();
    } else {
        updateHeight(el);
        current.innerHTML = "Show Less";
        el.setAttribute('onkeydown', 'focusPopup(event,"divOthersAlsoBought");');
        $('.Hideshadow').hide();
    }
}

function updateHeight(el) {
    el.style.maxHeight = el.scrollHeight + "px";
}

function dropdownClosingFuctionality(id) {
    $('div[id^="ColorLargeopt_"]').each(function (index, object) {
        var className = object.className;
        if (object.id == "ColorLargeopt_" + id) {
            if (className.indexOf("show") > -1) {
                $("#ColorLargeopt_" + id).css("display", "none").removeClass("show");
            }
            else {
                $("#ColorLargeopt_" + id).css("display", "flex").addClass("show");
            }
        }
        else {
            $("#" + object.id).css("display", "none").removeClass("show");
        }


    });
}

function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}


//changes for iwallbox product
var count = 0;
function QmeritModelBtn(status) {
    if (status === "yes")
        $("#frmAddtoCart").submit();
    //$("#btnAddToCart").removeAttr("data-target");
    $('#QmeritModel').modal('hide');
}
function btnAddToCartQmeritModal() {
    return false;
}
//changes for iwallbox product
function validateProductOptions(isTypeDProduct, btnId) {
    $("#divSelectOpt").css("display", "block");
    if ($("input[name='InstallOptionRadioGroup']").length <= 0 || $("input[name='InstallOptionRadioGroup']:checked").val()) {
        $('#validateInstallOption').removeClass("d-block").addClass("d-none");
        var isValid = true;
        if ($('input:hidden[id^="hdnOption_"]').length > 0) {
            $.each($('input:hidden[id^="hdnOption_"]'), function (index, object) {
                var divId = object.id.replace("hdnOption_", "divOption_");
                var value = $("#" + object.id).val();
                if ((value == "" || value == undefined) && ($("#" + divId).is(':visible'))) {
                    isValid = false;
                }
            });
        }
        else
            isValid = true;
        if (isValid) {
            if (isTypeDProduct == "True") {
                showOtherProductOptionPopup();
            }
            else {
                var modelId = $("#hdnModelId").val();
                var isModelProduct = $("#hdnIsModelProduct").val();
                if (isModelProduct == true && (modelId == "0" || modelId == "")) {
                    //var link = document.getElementById('aModelFitPopup'); 
                    //link.click();               
                    return true;
                }
                var dealerCenterId = $("#hdnProdDealerId").val();
                if (dealerCenterId == "0") {
                    var link = document.getElementById('locateDealerClick');
                    if (link != null)
                        link.click();
                    return false;
                }
                else {
                    addSubmitSpinner(btnId);
                    $('#validateOption').removeClass("d-block").addClass("d-none");
                    return true;
                }
            }
        }
        else {
            $('#validateOption').removeClass("d-none").addClass("d-block");
            return false;
        }
        return false;

    }
    else {
        $('#validateInstallOption').removeClass("d-none").addClass("d-block");
        var isValid = true;
        if ($('input:hidden[id^="hdnOption_"]').length > 0) {
            $.each($('input:hidden[id^="hdnOption_"]'), function (index, object) {
                var divId = object.id.replace("hdnOption_", "divOption_");
                var value = $("#" + object.id).val();
                if ((value == "" || value == undefined) && ($("#" + divId).is(':visible'))) {
                    isValid = false;
                }
            });
        }
        if (!isValid) {
            $('#validateOption').removeClass("d-none").addClass("d-block");
        }
        return false;
    }
}

function validateProductItems(btnId) {
    if ($("input:checkbox[id^=customCheckSelected_]").length > 0) {
        if ($("input:checkbox[id^=customCheckSelected_]:checked").length == 0) {
            $.each($('input:checkbox[id^="customCheckSelected_"]'), function (i, itmObj) {
                var itemName = itmObj.id.replace("customCheckSelected_", "");
                $("." + itemName.trim() + "div>#FlyoutValidateOption>span")[0].innerText = "Please choose an option";
                if ($('#NoStockNote_' + itemName).hasClass('d-none')) {
                    $('.' + itemName.trim() + 'div > div[id="FlyoutValidateOption"]').show();
                }
                else {

                    $('.' + itemName.trim() + 'div > div[id="FlyoutValidateOption"]').hide();
                }
            });

            //$('div[id="FlyoutValidateOption"]>span').each(function () {
            //    this.innerText = "Please choose an option.";
            //})
            //$('div[id="FlyoutValidateOption"]').show();
            return false;
        }
        else if ($("div[class=OpionsOfProductItem]").find(".colourSquares").length > 0) {//Color option validation checking
            var flag = 0;
            $.each($('input:checkbox[id^=customCheckSelected_]:checked'), function (i, itmObj) {
                var itemName = itmObj.id.replace("customCheckSelected_", "");
                $("." + itemName.trim() + "div>#FlyoutValidateOption>span")[0].innerText = "Please choose an option";
                if ($('div[id*="' + 'colorSquare-' + itemName + '"]').length > 0 && !$('div[id*="' + 'colorSquare-' + itemName + '"]').hasClass('active')) {
                    if ($('#NoStockNote_' + itemName).hasClass('d-none')) {
                        $('.' + itemName.trim() + 'div > div[id="FlyoutValidateOption"]').show();
                    }
                    else {
                        $('.' + itemName.trim() + 'div > div[id="FlyoutValidateOption"]').hide();
                    }
                    flag = 1;
                }
            });
            if (flag == 1) { return false; }
            else {
                addSubmitSpinner(btnId);
                $('div[id="FlyoutValidateOption"]').hide();
                //  getAllselectedOptions();
                return true;
            }
        }
        else {
            addSubmitSpinner(btnId);
            $('div[id="FlyoutValidateOption"]').hide();
            //  getAllselectedOptions();
            return true;
        }
    }

}

function getAllSelectedPartKeys() {
    var isTypeDProduct = $("#hdnIsTypeDProduct").val().toLowerCase();

    if (isTypeDProduct == "false") {
        if ($('input:hidden[id^="hdnOption_"]').length > 0) {
            var selectedPartKeys = "";
            $.each($('input:hidden[id^="hdnOption_"]'), function (index, object) {
                // var optionCategory = object.id.replace("hdnOption_", "").replace("©", "");
                var optionValue = $("#" + object.id).val().replace("©", "");
                var hdnPartkey = $("#hdnPartKey_" + optionValue);
                var selectedPartKey = hdnPartkey.val();
                if (selectedPartKey != "" && selectedPartKey != undefined) {
                    if (selectedPartKeys == "")
                        selectedPartKeys = selectedPartKey;
                    else
                        selectedPartKeys = selectedPartKeys + "," + selectedPartKey;
                }
                var itemNameId = object.id.replace("hdnOption_", "hdnItemName_");
                itemName = $("#" + itemNameId) != undefined ? $("#" + itemNameId).val() : "";
            });
            $("#hdnSelectedPartKeys").val(selectedPartKeys);
        }
    }
    else {
        var selectedPartKeys = "";
        $.each($('input:checkbox[id^="customCheckSelected_"]:checked'), function (i, itmObj) {
            var itemName = itmObj.id.replace("customCheckSelected_", "");
            var instDiv = itmObj.id.replace("customCheckSelected_", "customRadioInstalled_");
            if ($("#" + instDiv).length > 0) {
                if ($("#" + instDiv).is(':visible') && $("#" + instDiv).is(":checked")) {
                    //$("#FlyoutDeliveryOptionDiv_" + itemName).addClass("d-none");
                    deliveryType = "installed";
                }
            }
            else if ($("#hdnPickupOnly").val().toLowerCase() == "true") {
                deliveryType = "pickup in store";
            }
            else {
                deliveryType = "ship to me";
            }

            //if (!$("#FlyoutDeliveryOptionDiv_" + itemName).hasClass("d-none")) {
            //    var DeliveryOptionRadioGroup = instDiv.replace("customRadioInstalled_", "DeliveryOptionRadioGroup_");
            //    var DeliveryOption = $("input[name^='" + DeliveryOptionRadioGroup + "']:checked")[0].value;
            //    switch (DeliveryOption) {
            //        case "ShipMe": deliveryType = "ship to me"; break;
            //        case "PickinStore": deliveryType = "pickup in store"; break;
            //    }
            //}
            if ($('input:hidden[id^="hdnFlyOutOption_' + itemName + '_"]').length > 0) {
                var selectedOptions = "";
                $.each($('input:hidden[id^="hdnFlyOutOption_' + itemName + '_"]'), function (index, object) {
                    // var optionCategory = object.id.replace("hdnOption_", "").replace("©", "");
                    var optionValue = $("#" + object.id).val().replace("©", "");
                    var hdnPartkey = $("#hdnFlyOutPartKey_" + optionValue);
                    var selectedPartKey = hdnPartkey.val();
                    if (selectedPartKey != "" && selectedPartKey != undefined) {
                        if (selectedPartKeys == "")
                            selectedPartKeys = selectedPartKey;
                        else
                            selectedPartKeys = selectedPartKeys + "," + selectedPartKey;
                    }

                });
                //var selectedItem = {};
                //selectedItem.SelectedOptions = selectedOptions;
                ////alert(itemName);
                //selectedItem.ProductItemName = document.getElementById("hFlyoutName_" + itemName).innerText;
                //selectedItem.IsPickUpOnly = $("#hdnPickupOnly").val().toLowerCase();
                ////selectedItem.IsInstallable = isInstallable;// type d installable checking need to be added
                //selectedItem.DeliveryType = deliveryType;
                //selectedItems.push(selectedItem);

            }
            else {
                //var selectedItem = {};
                //selectedItem.SelectedOptions = "";
                //selectedItem.ProductItemName = document.getElementById("hFlyoutName_" + itemName).innerText;
                //// selectedItem.IsInstallable = isInstallable;// type d installable checking need to be added
                //selectedItem.DeliveryType = deliveryType;
                //selectedItems.push(selectedItem);
            }
        });
        $("#hdnSelectedPartKeys").val(selectedPartKeys);
    }
}

function DetailsQtyChange(qty) {
    if (qty !== null && qty !== undefined && qty !== "") {
        $("#lblDetailsQty").text(qty);

        if ($("#hdnIsTypeDProduct").val().toLowerCase() === "true") {
            if ($("#hdnIsSpecialProduct").val().toLowerCase() == "true") {
                $.each($('[id^="dropdown-menu_"]'), function (i, itmObj) {
                    var pdtItemName = itmObj.id.replace("dropdown-menu_", "");
                    var numQty = $('#dropdown-menu_' + pdtItemName).children('a').length;
                    var prodQty = qty > numQty ? numQty : qty;
                    $("#lblDetailsQty_" + pdtItemName).text(prodQty);
                    updateSpecialProductQtyFlyOutDropDown(pdtItemName, prodQty);
                });

            } else {
                $.each($('input:checkbox[id^="customCheckSelected_"]'), function (i, itmObj) {
                    var pdtItemName = itmObj.id.replace("customCheckSelected_", "");
                    $("#lblDetailsQty_" + pdtItemName).text(qty);
                });
            }

            calculateProductSummary();
        }
        $("#pdtQuantity").val(qty);
    }
}
function DetailsFlyoutQtyChange(qty, pdtItemName) {
    if (qty !== null && qty !== undefined && qty !== "" && pdtItemName !== null && pdtItemName !== undefined && pdtItemName !== "") {
        $("#lblDetailsQty_" + pdtItemName).text(qty);
        calculateProductSummary();
    }
}
function getAllselectedOptions() {
    var itemName = "";
    var selectedItems = new Array();
    var deliveryType = "ship to me";
    var isTypeDProduct = $("#hdnIsTypeDProduct").val().toLowerCase();
    var isPickupOnly = $("#hdnPickupOnly").val();
    if ($("#customRadioInstalled").is(':visible') && $("#customRadioInstalled").is(":checked")) {
        $("#DeliveryOptionDiv").addClass("d-none");
        deliveryType = "installed";
    }
    else if (isPickupOnly != undefined && isPickupOnly.toLowerCase() == "true") {
        deliveryType = "pickup in store";
    }
    else {
        deliveryType = "ship to me";
    }
    if (!$("#DeliveryOptionDiv").hasClass("d-none")) {
        switch ($("input[name^='DeliveryOptionRadioGroup']:checked")[0].value) {
            case "ShipMe": deliveryType = "ship to me"; break;
            case "PickinStore": deliveryType = "pickup in store"; break;
        }
    }
    //$('#deliveryType').val(deliveryType);
    if (isTypeDProduct == "false") {

        if ($('input:hidden[id^="hdnOption_"]').length > 0) {
            var selectedOptions = "";
            $.each($('input:hidden[id^="hdnOption_"]'), function (index, object) {
                // var optionCategory = object.id.replace("hdnOption_", "").replace("©", "");
                var optionValue = $("#" + object.id).val().replace("©", "");
                if (optionValue != "" && optionValue != undefined) {
                    if (selectedOptions == "")
                        selectedOptions = optionValue;
                    else
                        selectedOptions = selectedOptions + "," + optionValue;
                    // selectedOptions = selectedOptions + optionCategory + "£" + optionValue
                }
                var itemNameId = object.id.replace("hdnOption_", "hdnItemName_");
                itemName = $("#" + itemNameId) != undefined ? $("#" + itemNameId).val() : "";
            });

            //selected item - ispickuponly flag //BE - 7651 change
            var ItemIsPickupOnly = false;
            ItemIsPickupOnly = $('#customRadioPickinStore_CommonOption').attr("data-ispickuponly");
            var ItemAvailability = $("#ItemAvailability").val();
            var InstallationPrice = $("#InstallationPrice").val();
            var selectedItem = {};
            selectedItem.SelectedOptions = selectedOptions;
            selectedItem.ProductItemName = itemName;//document.getElementById("hName_" + itemName).innerText;
            selectedItem.IsPickUpOnly = ItemIsPickupOnly;//$("#hdnPickupOnly").val().toLowerCase();
            if (ItemAvailability === "1" && deliveryType === "installed") {
                if (ItemIsPickupOnly.toString() === "true")
                    selectedItem.DeliveryType = "pickup in store";
                else
                    selectedItem.DeliveryType = "ship to me";
            }
            else if (ItemAvailability === "2" && InstallationPrice != 0 && InstallationPrice != null && InstallationPrice != "") {
                selectedItem.DeliveryType = "installed";
            }
            else {
                selectedItem.DeliveryType = deliveryType;
            }
            selectedItem.Quantity = $("#lblDetailsQty").text();
            selectedItem.ItemAvailability = parseInt(ItemAvailability);
            selectedItems.push(selectedItem);             
        }
    }
    else {
        $.each($('input:checkbox[id^="customCheckSelected_"]:checked'), function (i, itmObj) {
            const el = document.querySelector("#" + itmObj.id).parentNode
            var hidproductitemid = el.querySelector("input[type='hidden']")
            var pickupOnly = $("#hdnPickupOnly").val();
            var itemName = itmObj.id.replace("customCheckSelected_", "");
            var instDiv = itmObj.id.replace("customCheckSelected_", "customRadioInstalled_");
            // BE-7961 removed install and delivery options from flyout
            if (!$("#DeliveryOptionDiv").hasClass("d-none")) {
                var commonDeliveryType = $("input[name^='DeliveryOptionRadioGroup']:checked")[0].value;
            }
            // uncommented below code to fix deliveryType issue.
            if ($("#" + instDiv).length > 0 && commonDeliveryType != "PickinStore") {
                if ($("#" + instDiv).is(":checked")) {
                    //$("#FlyoutDeliveryOptionDiv_" + itemName).addClass("d-none");
                    deliveryType = "installed";
                }
            }
            else if (pickupOnly != undefined && pickupOnly.toLowerCase() == "true") {
                deliveryType = "pickup in store";
            }
            else {
                deliveryType = "ship to me";
            }
            if ($("#FlyoutDeliveryOptionDiv_" + itemName).length > 0 && deliveryType != "installed") {
                var DeliveryOptionRadioGroup = instDiv.replace("customRadioInstalled_", "DeliveryOptionRadioGroup_");
                var DeliveryOption = $("input[name^='" + DeliveryOptionRadioGroup + "']:checked")[0].value;
                switch (DeliveryOption) {
                    case "ShipMe": deliveryType = "ship to me"; break;
                    case "PickinStore": deliveryType = "pickup in store"; break;
                }
            }

            //selected item - ispickuponly flag //BE - 7651 change
            var ItemIsPickupOnly = false;
            ItemIsPickupOnly = $('#customRadioPickinStore_' + itemName).attr("data-ispickuponly");
            var ItemAvailability = $('#customRadioPickinStore_' + itemName).attr("data-ItemAvailability");
            var InstallationPrice = $('#customRadioPickinStore_' + itemName).attr("data-InstallationPrice");

            if ($('input:hidden[id^="hdnFlyOutOption_' + itemName + '_"]').length > 0) {
                var selectedOptions = "";
                $.each($('input:hidden[id^="hdnFlyOutOption_' + itemName + '_"]'), function (index, object) {
                    // var optionCategory = object.id.replace("hdnOption_", "").replace("©", "");
                    var optionValue = $("#" + object.id).val().replace("©", "");
                    if (optionValue != "" && optionValue != undefined) {
                        if (selectedOptions == "")
                            selectedOptions = optionValue;
                        else
                            selectedOptions = selectedOptions + "," + optionValue;
                        // selectedOptions = selectedOptions + optionCategory + "£" + optionValue
                    }

                });
                var selectedItem = {};
                selectedItem.SelectedOptions = selectedOptions;
                selectedItem.ProductItemName = document.getElementById("hFlyoutName_" + itemName).innerText;
                selectedItem.IsPickUpOnly = ItemIsPickupOnly;//$("#hdnPickupOnly").val().toLowerCase();
                //selectedItem.IsInstallable = isInstallable;// type d installable checking need to be added
                if (ItemAvailability === "1" && deliveryType === "installed") {
                    if (ItemIsPickupOnly.toString() === "true")
                        selectedItem.DeliveryType = "pickup in store";
                    else
                        selectedItem.DeliveryType = "ship to me";
                }
                else if (ItemAvailability === "2" && InstallationPrice != 0 && InstallationPrice != null && InstallationPrice != "") {
                    selectedItem.DeliveryType = "installed";
                }
                else
                    selectedItem.DeliveryType = deliveryType;
                selectedItem.Quantity = $("#lblDetailsQty_" + itemName).text();
                selectedItem.ItemAvailability = parseInt(ItemAvailability);
                selectedItems.push(selectedItem);

            }
            else {
                var selectedItem = {};
                selectedItem.SelectedOptions = "";
                selectedItem.ProductItemId = hidproductitemid.value
                selectedItem.ProductItemName = document.getElementById("hFlyoutName_" + itemName).innerText;
                selectedItem.IsPickUpOnly = ItemIsPickupOnly;
                // selectedItem.IsInstallable = isInstallable;// type d installable checking need to be added
                if (ItemAvailability === "1" && deliveryType === "installed") {
                    if (ItemIsPickupOnly.toString() === "true")
                        selectedItem.DeliveryType = "pickup in store";
                    else
                        selectedItem.DeliveryType = "ship to me";
                }
                else if (ItemAvailability === "2" && InstallationPrice != 0 && InstallationPrice != null && InstallationPrice != "") {
                    selectedItem.DeliveryType = "installed";
                }
                else
                    selectedItem.DeliveryType = deliveryType;
                selectedItem.Quantity = $("#lblDetailsQty_" + itemName).text();
                selectedItem.ItemAvailability = parseInt(ItemAvailability);
                selectedItems.push(selectedItem);
            }
            

        });
    }
    if (selectedItems.length > 0) {
        $('#itemDetails').val(JSON.stringify(selectedItems));
    }
    return true;
}

function productTabChange(tabName) {
    if (tabName == "warranty") {
        if ($("div.TabMainDiv") != undefined && $("div.TabMainDiv") != null)
            $("div.TabMainDiv").removeClass('TabMainDiv').addClass('TabMainWithoutShadow');
    }
    else {
        if ($("div.TabMainWithoutShadow") != undefined && $("div.TabMainWithoutShadow") != null)
            $("div.TabMainWithoutShadow").removeClass('TabMainWithoutShadow').addClass('TabMainDiv');
    }
}

$("#frmAddtoCart").on("submit", function (e) {
    if ($("#btnAddToCart").hasClass("btnDisabled"))
        return false;
    else {
        getAllselectedOptions();

        if ($("#hdnIsSpecialProduct").val().toLowerCase() == "true") {
            var itemDetails = $("#itemDetails").val();
            var pId = $("#hdnProdId").val();
            var params = {
                itemDetails: itemDetails, productId: pId
            };
            $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.Cart.CheckSpecialsInventoryCount, data: params }, {
                complete: function (json) {
                    var result = json.responseJSON;
                    if (result !== null && result.length > 0) {
                        for (var key in result) {
                            if (key != undefined) {
                                var ProductItemName = result[key].ProductItemName;
                                $("#maximumQtyMsg").removeClass("d-none");
                                if ($("#hdnIsTypeDProduct").val().toLowerCase() === "true") {
                                    $("#maximumQtyMsg").text("You have already added the maximum count of the selected product item(s) to the cart.");
                                    $("#maximumQtyMsg_" + ProductItemName.replace(/[^\w\s]/gi, '').replace(/\s/g, "©")).removeClass("d-none");
                                }
                            }
                        }
                    }
                }
            }));
        }
    }
});
$("#frmVisualizer").on("submit", function () { getAllSelectedPartKeys(); });

function addToCartOnCompleted(result) {
    if (result.responseText == "")
        window.location = '/MotorSports/logout';
    if ($("#hdnIsSpecialProduct").val().toLowerCase() == "true") {
        updateSpecialProductQtyDropDown("AllOptions");
        setTimeout(function () {
            if ($('#maximumQtyMsg').hasClass("d-none")) {
                showCartFlyout();
            }
            removeSubmitSpinner('btnAddToCart');
        }, 1000);
    } else {
        removeSubmitSpinner('btnAddToCart');
        showCartFlyout();
    }

}

function addToCartOnCompletedFlyout(result) {
    if (result.responseText == "")
        window.location = '/MotorSports/logout';
    //alert(result);
    if ($("#hdnIsSpecialProduct").val().toLowerCase() == "true") {
        updateSpecialProductQtyDropDown("AllOptions");
        setTimeout(function () {
            var countChecked = 0;
            var countMsg = 0;
            $('[id^="maximumQtyMsg_"]').each(function () {
                var itemName = this.id.replace("maximumQtyMsg_", "");
                if (!$('#maximumQtyMsg_' + itemName).hasClass("d-none")) {
                    countMsg++;
                }
            });
            $('input:checkbox[id^="customCheckSelected_"]:checked').each(function () {
                countChecked++;
            });

            if (countChecked == countMsg) {
                hideProductOptionPopup();
                removeSubmitSpinner('btnAddToCart');
            } else {
                hideProductOptionPopup();
                removeSubmitSpinner('btnAddToCart');
                showCartFlyout();
            }
        }, 1000);
    } else {
        hideProductOptionPopup();
        removeSubmitSpinner('btnAddToCart');
        showCartFlyout();
    }
}
function onAddPdtFail() {
    alert("Failed");
}

$("#btnCartModelSelectionPopup").click(function () {
    $('#OverlayRight').css('display', 'block');
    $('body').addClass('body-fixed');
    $('body').css('overflow-y', 'hidden');
    $('html').css('overflow', 'hidden');
});

function showDealerPopup() {
    var link = document.getElementById('locateDealerClick');
    if (link != null)
        link.click();
}

//----Pre-Order------/ 
$(function () {
    $('[data-toggle="popover"]').popover()
});

function preOrderDetailsSubmitClick() {
    $($('.addCartBtn').find('.add-to-cart')[0]).click();
    document.body.scrollTop = 0; // For Safari
    document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera 

    $($('.addCartBtn').find('.add-to-cart')[0]).popover({
        container: 'body'
    });
}
//----Pre-Order------/

//$(function () {
//    $(".zoom-close").on("click", function () {
//        $(".zoom-close").toggleClass("transform", 1000);
//    });
//});

$(".ImgZoom").hover(function () {
    if (!$(".ProZooming").hasClass("zoom-closeTop")) {
        $(".ImgZoom").css("cursor", "pointer")
    }
})
//Image Zooming
$(function () {
    $(".ImgZoom").on("click", function () {
       
        if (!$(".ProZooming").hasClass("zoom-closeTop")) {
            $(".ImgZoom").css("cursor", "default")
            ImageZooming();
        }
    });
});
function flyoutzoom(id, elem, idx) {
    
    $("a.ZoomDirection.carousel-control-prev.Preleft.Icon-dnone.d-block").css("z-index", 0);
    $("a.ZoomDirection.carousel-control-next.NextRight.Icon-dnone.d-block").css("z-index", 0);

    if (elem.parentNode.querySelector("a")) {

      

        const el = document.querySelector(`.flyoutImageContainer-${idx} .carousel-item.active img`);
      


            if (!$("#divSelectOpt").hasClass("ProD-block")) {
                var srcdata = el.getAttribute('src')

                $("#zoom-tempimg").attr("src", srcdata);

                $("#prdtZoom").attr("style", 'display:none');
                $("#chooseOptZoom").removeAttr("style");

            }

        //});
    }
    else {

        const img = elem.parentNode.querySelector("img");
        const src = img.getAttribute("src");
        if (!$("#divSelectOpt").hasClass("ProD-block")) {
            var srcdata = src

            $("#zoom-tempimg").attr("src", srcdata);

            $("#prdtZoom").attr("style", 'display:none');
            $("#chooseOptZoom").removeAttr("style");

        }

        //const element = document.getElementById(id);
        //element.scrollIntoView();
    }
}

function ImageZooming() {


    $(".zoom-close").toggleClass("transform", 1000);
    $("#SelectOptionDiv").toggleClass("width-100", 1000);
    if (!$(".ProZooming").hasClass("zoom-closeTop")) {
       
        $('html').addClass('ZoomScroll');
        if ($("#divSelectOpt").hasClass("ProD-block")) {
            
            $("#divSelectOpt").removeClass("ProD-block").addClass("ProD-none");
            $("#divSelectOpt").css("display", "none")
            $('html').css('overflow-y', 'auto');
            $('html').css('overflow-x', 'hidden');
         
        }
        else {
            
            $('#divSelectOpt').attr('style', 'display: none');

            $('html').css('overflow', '');
        }

        $(".product-image-container").addClass("ZoomImgWrapper");
        $(".ProZooming").addClass("zoom-closeTop");
        $(".ImgZoom").css("cursor", "pointer")
        $('.ProZooming').attr('style', 'top: 10px !important');
    }
    else {
        
        $(".OptMainDiv").attr("style", 'display:block');
        
        $("#details-flex-zoom").attr("style", 'display:none');
        //test.map(item => {
             
        //    item.style.display = "block";
        //      console.log(item.style.display)
        //})
        
    //    $('.chooseOpt').attr('style', 'display: block');

        //$("#visualzerimageid").attr("src", "");
     
    //    var test = document.querySelectorAll(".carousel-item");
    //    console.log(test)
    //var dd =    test.forEach(item => {
    //    if (!item.className.includes("active")) {
    //        item.style.display = "";
                
    //        }
            
    //    })
    //    console.log(dd)


        $("body").removeClass("body-fixed")
        $("a.ZoomDirection.carousel-control-prev.Preleft.Icon-dnone.d-block").css("z-index", 10013);
        $("a.ZoomDirection.carousel-control-next.NextRight.Icon-dnone.d-block").css("z-index", 10013);

        $("#chooseOptZoom").attr("style", 'display:none');

        $('html').removeClass('ZoomScroll');
        $(".product-image-container").removeClass("ZoomImgWrapper");
        if ($("#divSelectOpt").hasClass("ProD-block")) {
          
            $('html').css('overflow', '');
          
        }
        else if ($("#divVisualizerSelectOpt").hasClass("ProD-block")) {
            $('html').css('overflow', 'hidden');
            
        }
        else {
            $('html').css('overflow-y', 'auto');
            $('html').css('overflow-x', 'hidden');
            $("#prdtZoom").removeAttr("style");
        }
        $(".ProZooming").removeClass("zoom-closeTop");
        $(".ProZooming").css("top", "");
    }

   
    let originX = 50;

    if (!$(".carousel-item").hasClass("ZoomImg")) {
        $(".carousel-item").addClass("ZoomImg");
       
        $(".carousel-item").css("transform-origin", "50% 26%");
        $("#imgMoveleft").unbind('click');
        $("#imgMoveleft").bind('click', function () {
            if (originX > 0) {
                originX -= 5;
                $(".carousel-item").css("transform-origin", originX + "% 26%");
            }
        });
        $("#imgMoveright").unbind('click');
        $("#imgMoveright").bind('click', function () {
            if (originX < 100) {
                originX += 5;
                $(".carousel-item").css("transform-origin", originX + "% 26%");
            }
        });

    }
    else {

        $(".carousel-item").removeClass("ZoomImg");
    }

    if (!$(".DivProSlider").hasClass("ZoomImg")) {
        $(".DivProSlider").addClass("ZoomImg");

        $(".DivProSlider").css("transform-origin", "50% 26%");
        $("#imgMoveleft").unbind('click');
        $("#imgMoveleft").bind('click', function () {
            if (originX > 0) {
                originX -= 5;
                $(".DivProSlider").css("transform-origin", originX + "% 26%");
            }
        });
        $("#imgMoveright").unbind('click');
        $("#imgMoveright").bind('click', function () {
            if (originX < 100) {
                originX += 5;
                $(".DivProSlider").css("transform-origin", originX + "% 26%");
            }
        });

    }
    else {
        $(".DivProSlider").removeClass("ZoomImg");
    }

    if (!$(".carousel-control-prev").hasClass("Icon-dnone")) {
        $(".carousel-control-prev").addClass("Icon-dnone");
    }
    else {
        $(".carousel-control-prev").removeClass("Icon-dnone");
    }

    if (!$(".carousel-control-next").hasClass("Icon-dnone")) {
       
        $(".carousel-control-next").addClass("Icon-dnone");
    }
    else {
        $(".carousel-control-next").removeClass("Icon-dnone");
    }

    if (!$(".ZoomDirection").hasClass("d-block")) {
        $(".ZoomDirection").addClass("d-block");
    }
    else {
        $(".ZoomDirection").removeClass("d-block");
    }

    if (!$(".carousel-inner").hasClass("ZoomVisible")) {
        $(".carousel-inner").addClass("ZoomVisible");
    }
    else {
        $(".carousel-inner").removeClass("ZoomVisible");
    }

    if (!$(".details-flex").hasClass("ZoomimgLarge")) {
        $(".details-flex").addClass("ZoomimgLarge");
    }
    else {
        $(".details-flex").removeClass("ZoomimgLarge");
    }

    if (!$(".carousel-inner").hasClass("ZoomDisplay")) {
        $(".carousel-inner").addClass("ZoomDisplay");
    }
    else {
        $(".carousel-inner").removeClass("ZoomDisplay");
    }

    if (!$(".Thumbimg").hasClass("d-none")) {
        $(".Thumbimg").addClass("d-none");
    }
    else {
        $(".Thumbimg").removeClass("d-none");
    }

    if (!$("#zoomdnone").hasClass("zoomdnone")) {
        $("#zoomdnone").addClass("zoomdnone");
    }
    else {
        $("#zoomdnone").removeClass("zoomdnone");
    }

    if (!$("[id^='ZoomWidth']").hasClass("w-100")) {
        $("[id^='ZoomWidth']").addClass("w-100");
    }
    else {
        $("[id^='ZoomWidth']").removeClass("w-100");
    }
    if (!$("body").hasClass("ZoomScroll-hidden")) {
        $("body").addClass("ZoomScroll-hidden");
    }
    else {
        $("body").removeClass("ZoomScroll-hidden");
    }
    var tempid = $(".active").find(".product-image")[0].id

    if ($(".ProZooming").hasClass("zoom-closeTop")) {
        $('html, body').animate({
            scrollTop: $("#" + tempid).offset().top
        }, 0);
        $(".zoom-closeTop").css("position", "fixed")
    }
    else {
        $("html, body").animate({ scrollTop: 0 }, 0);
        $(".ProZooming").css("position", "")
    }
    //$(".ProZooming").attr("href", "#"+$(".active").find("img")[38].id)
    if (!$(".carousel-item").hasClass("ZoomImg")) {

        var cw = $('.carousel-item.active').find('.product-image').width();

        $('.calc-height .carousel-item').css({
            'height': cw + 'px'
        });

    }


    if ($(".CommonImageContainer .carousel-control-prev").length >0) {

        var elem = $('.CommonImageContainer .carousel-item.active').attr('id')

        $('#' + elem)[0].scrollIntoView();

    }
  
}


$('.OptMainDiv').on('click', '.flyoutImageContainer', function (event) {


    if (!$("#divSelectOpt").hasClass("ProD-block")) {
     
        $("a.ZoomDirection.carousel-control-prev.Preleft.Icon-dnone.d-block").css("z-index", 0);
        $("a.ZoomDirection.carousel-control-next.NextRight.Icon-dnone.d-block").css("z-index", 0);
        
        var srcdata = event.target.getAttribute('src')
         
        $("#zoom-tempimg").attr("src", srcdata);

        $("#prdtZoom").attr("style", 'display:none');
        $("#chooseOptZoom").removeAttr("style");
      
    }

});

var SelectedProductItemOptionNames = "";
var SelectedProductItemsName = "";
var OptionItemDetails = "";



function inventory_check() { //priority - itemavilability, ispickuponly, inventory
    if (typeof (ProductItemDetails) === "undefined") {
        return;
    }
    var btnTextChanged = false;
    var stopper = false;
    var optionDetails = [];
    var selectedOptions = "";
    var selectedProducts = [];
    var productId = $("#hdnProdId").val();
    var modelId = $("#hdnModelId").val();
    var isModelProduct = $("#hdnIsModelProduct").val();
    var isTypeDProduct = $("#hdnIsTypeDProduct").val().toLowerCase();
    var isProductBundle = $("#hdnIsProductBundle").val().toLowerCase();
    var deliveryType = $('input[name="DeliveryOptionRadioGroup"]:checked').val();
    if (ProductItemDetails.length > 1) { //more than one items for a product

        if (isTypeDProduct == "false") {//no type d products checking

            $("#noStock").addClass('d-none');
            if ($('input:hidden[id^="hdnOption_"]').length > 0) {//Finding all selected options in radio button, checkbox, color options etc
                $.each($('input:hidden[id^="hdnOption_"]'), function (index, object) {
                    var optionValue = $("#" + object.id).val().replace("©", "");// gettting the id of selected option
                    var optionName = object.id;// gettting the name of selected option
                    optionName = optionName.split('_');
                    if (optionValue != "" && optionValue != undefined) {
                        if (selectedOptions == "")
                            selectedOptions = optionValue;
                        else
                            selectedOptions = selectedOptions + "," + optionValue;
                    }
                });
            }

            $.each(ProductItemDetails, function (ind, obj) {
                var items = "";
                var itemsCategory = "";
                var itemsValue = "";
                var ProductOptionsMatched = false;
                if (obj.ProductOptions.length >= 1) {// checking that the productitem have same option name and same category, then select the first option by deafult 
                    for (var i = 0; i < obj.ProductOptions.length - 1; i++) {
                        if (obj.ProductOptions[0].OptionCategory === obj.ProductOptions[i + 1].OptionCategory && obj.ProductOptions[0].OptionValue === obj.ProductOptions[i + 1].OptionValue) {
                            ProductOptionsMatched = true;
                        }
                    }
                }
                if (ProductOptionsMatched === true) {
                    items = obj.ProductOptions[0].OptionId + ",";
                    itemsCategory = obj.ProductOptions[0].OptionCategory + ",";
                    itemsValue = obj.ProductOptions[0].OptionValue + ",";
                }
                else {
                    $.each(obj.ProductOptions, function (indx, ob) {
                        items += ob.OptionId + ",";
                        itemsCategory += ob.OptionCategory + ",";
                        itemsValue += ob.OptionValue + ",";
                    });
                }

                items = items.slice(0, -1);
                itemsCategory = itemsCategory.slice(0, -1);
                itemsValue = itemsValue.slice(0, -1);
                optionDetails.push({
                    IsInInventory: obj.IsInInventory,
                    SoldOutUrl: obj.SoldOutURL,
                    Items: items,
                    ItemsCategory: itemsCategory,
                    ItemsValue: itemsValue,
                    IsStateWiseHide: obj.IsStateWiseHide,
                    StateWiseHideNote: obj.StateWiseHideNote,
                    PartNumber: obj.PartNumber,
                    ProductItemId: obj.ProductItemId,
                    ItemAvailability: obj.ItemAvailabilityId,
                    IsPickupOnly: obj.IsPickupOnly,
                    InstalledPrice: obj.InstalledPrice
                });
            });



            $.each(optionDetails, function (idx, obj) {
                if (stopper == false) {
                    if (obj.Items == selectedOptions) {
                        //if (obj.IsStateWiseHide == true) {
                        //    $("#btnAddToCart").css("display", "none");
                        //    $("#btnSoldOut").css("display", "block");
                        //    $("#btnSoldOut").attr("disabled", "true");
                        //    $("#btnSoldOut>.primary-text")[0].innerText = obj.StateWiseHideNote;
                        //    $("#btnSoldOut").css("cursor", "no-drop");
                        //    $("#noStock").addClass('d-none');
                        //    btnTextChanged = true;
                        //    stopper = true;
                        //}
                        //else
                        $("#ItemAvailability").val(obj.ItemAvailability);
                        if (obj.ItemAvailability === "6") { //only enable pickup only delivery
                            $('label[for="customRadioShipMe_CommonOption"]').find("span").text("Unavailable for shipping");
                            $("#customRadioPickinStore_CommonOption").attr("checked", "checked").prop("checked", true);
                            $("#customRadioShipMe_CommonOption").attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                            $('label[for="customRadioShipMe_CommonOption"]').find("span").attr("id", "spanDisableShip");
                            if (isProductBundle)
                                stopper = true; //any item is 6, then change the delivery option and exist

                            optionDetails.map(function (v) {
                                if (v.ItemAvailability === "0")
                                    stopper = false;
                            });
                        }
                        else if (obj.IsPickupOnly === true) {
                            if ($("#dealerPickupMsg").hasClass("d-none"))
                                $("#dealerPickupMsg").removeClass("d-none");

                            $('label[for="customRadioShipMe_CommonOption"]').find("span").text("Unavailable for shipping");
                            $("#customRadioPickinStore_CommonOption").attr("checked", "checked").prop("checked", true);
                            $("#customRadioShipMe_CommonOption").attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                            $('label[for="customRadioShipMe_CommonOption"]').find("span").attr("id", "spanDisableShip");

                            if (($('#customRadioPickinStore_CommonOption').attr("data-ispickuponly") === "false" || !$('#customRadioPickinStore_CommonOption').attr("data-ispickuponly")) && obj.IsPickupOnly === true)
                                $('#customRadioPickinStore_CommonOption').attr("data-ispickuponly", "true");
                        }
                        else {

                            if (obj.IsPickupOnly === false) {
                                if (!$("#dealerPickupMsg").hasClass("d-none"))
                                    $("#dealerPickupMsg").addClass("d-none");

                                $('label[for="customRadioShipMe_CommonOption"]').find("span").text("Ship to me");
                                $("#customRadioShipMe_CommonOption").removeAttr("disabled").attr('checked', 'true').prop("checked", true);
                                $("#customRadioPickinStore_CommonOption").removeAttr("checked");
                                $('label[for="customRadioShipMe_CommonOption"]').find("span").removeAttr("id");

                                if ($('#customRadioPickinStore_CommonOption').attr("data-ispickuponly") === "true" || $('#customRadioPickinStore_CommonOption').attr("data-ispickuponly"))
                                    $('#customRadioPickinStore_CommonOption').attr("data-ispickuponly", "false");

                            }
                        }
                        if (obj.ItemAvailability === '0') {//addToCart button text as  not available message and btn disable
                            $("#btnAddToCart").css('display', '');
                            $("#btnCartModelSelectionPopup").css('display', '');
                            $("#btnAddToCart").find('span.primary-text').text('Currently not available from this dealer');
                            $("#btnCartModelSelectionPopup").find('span.primary-text').text('Currently not available from this dealer');
                            $("#btnSoldOut").css("display", "none");
                            $("#btnAddToCart").attr('disabled', 'disabled');
                            $("#btnCartModelSelectionPopup").attr('disabled', 'disabled');
                            if (isProductBundle)
                                stopper = true;
                        }
                        else if (obj.IsInInventory === false) {// Item not avilable for sale
                            if (dealer !== null && dealer !== 0) {
                                if (availability !== null && availability !== "0") {
                                    //Model Product - Show the Model Nutton
                                    if (modelId === '' && isModelProduct === "1") {
                                        $("#btnCartModelSelectionPopup").css('display', '');
                                        $("#btnCartModelSelectionPopup").find('span.primary-text').text('Add To Cart');
                                    }
                                    else {//Reset All Input Fields
                                        NoSTockEmailValidationReset();
                                        btnTextChanged = true;
                                        IsSoldOutCount++;
                                        $("#noStock").removeClass('d-none');
                                        if ($("#divModelVinNote") != undefined)
                                            $("#divModelVinNote").css("display", "none");
                                        $("#btnAddToCart").css('display', 'none');
                                        $("#btnCartModelSelectionPopup").css('display', 'none');
                                        $("#btnSoldOut").css("display", "");
                                        $("#btnSoldOut").attr('disabled', 'disabled');
                                        $("#btnSoldOut").find('span.primary-text').text('Temporarily out of Stock');
                                        //Notified ProductItem Checking from Session Data
                                        var sessionNotify = $("#hdnNotifyMeSession").val();
                                        var notified = false;
                                        if (sessionNotify != undefined && sessionNotify != '') {
                                            if (sessionNotify.split(',').indexOf(obj.ProductItemId.toString()) != -1) {
                                                notified = true;
                                            }
                                        }
                                        if (notified == true) {
                                            $("#divNoStockEmail").addClass("d-none").siblings('section').addClass("d-none");
                                            $("#noStockSucMsg").removeClass("d-none");
                                        }
                                        else {
                                            $("#divNoStockEmail").removeClass("d-none").siblings('section').removeClass("d-none");
                                            $("#noStockSucMsg").addClass("d-none");
                                        }
                                        //Collecting Selected ProductItem -Id, PartNumber,Option
                                        OptionItemDetails = obj.PartNumber + '@' + obj.ProductItemId + '@' + obj.ItemsCategory + ":" + obj.ItemsValue;
                                        //Append SoldOut Redirect URL
                                        if (obj.SoldOutUrl == "" || obj.SoldOutUrl == undefined || obj.SoldOutUrl == null) {
                                            $("#btnSoldOut").css("cursor", "no-drop");
                                        }
                                        else {

                                            $("#btnSoldOut").css("cursor", "default").removeAttr("disabled");
                                            $("#btnSoldOut").attr("target", "_blank");
                                            $("#btnSoldOut").attr("onclick", "window.open('" + obj.SoldOutUrl + "')");
                                        }
                                    }//Model Checking
                                }
                                else {
                                    $("#btnSoldOut").css("cursor", "no-drop").attr("disabled", 'disabled');
                                    $("#btnSoldOut").find('span.primary-text').text('Temporarily out of Stock');
                                }
                            }//Dealer
                            else {
                                btnTextChanged = true;
                                $("#btnAddToCart").find('span.primary-text').text('Select Dealer');
                                if (modelId == '' && isModelProduct == "1") {
                                    $("#btnCartModelSelectionPopup").find('span.primary-text').text('Add To Cart');
                                }
                                else {
                                    $("#btnCartModelSelectionPopup").find('span.primary-text').text('Select Dealer');
                                }
                                var link = document.getElementById('locateDealerClick');
                                if (link != null)
                                    link.click();
                            }
                            stopper = true;
                        }//Inventory
                        else {
                            $("#btnAddToCart").css('display', '');
                            $("#btnCartModelSelectionPopup").css('display', '');
                            $("#btnAddToCart").find('span.primary-text').text('Add To Cart');
                            $("#btnCartModelSelectionPopup").find('span.primary-text').text('Add To Cart');
                            $("#btnAddToCart").removeAttr("disabled");
                            $("#btnCartModelSelectionPopup").removeAttr("disabled");
                            $("#btnSoldOut").css("display", "none");
                        }
                    }
                    else {
                        $("#btnAddToCart").css("display", "");
                        $("#btnSoldOut").css("display", "none");
                    }
                }
            });
        }
        else {
            //type d products
            //Type D product - Flyout product have options to select and no options or combination of both.
            var count = -1;
            var selectedProductsCount = 0;// count of all productItmes
            var IsStateWiseHideCount = 0;
            var IsSoldOutCount = 0;// count of no inventory productItems
            var OptionsCountOfItems = 0, noOpitonsCountofItems = 0;


            $.each($('input:checkbox[id^="customCheckSelected_"]'), function (i, itmObj) {
                var itemName = itmObj.id.replace("customCheckSelected_", "");
                $('#deliveryType').val(deliveryType);
                selectedProductsCount++;

                $.each($('input:hidden[id^="hdnFlyOutOption_' + itemName + '_"]'), function (index, object) {// Finding all options of the Product Itmes
                    var optionValue = $("#" + object.id).val().replace("©", "");
                    if (optionValue != "" && optionValue != undefined) {
                        selectedProducts.push({
                            selectedOptions: optionValue,
                            selectedOptionName: object.id.replace("©", "").replace("customCheckSelected_", "").trim(),
                            productItemName: $("#hFlyoutName_" + itemName).html()
                        });
                    }
                });
            });
            //console.log(JSON.stringify(selectedProducts)); 
            //console.log(n);
            //return;


            if (selectedProducts === "" || selectedProducts === null || selectedProducts.length === 0) {//No options to select 

                selectedProductsCount = ProductItemDetails.length;
                $.each($('input:checkbox[id^="customCheckSelected_"]'), function (i, itmObj) {

                    var itemName = itmObj.id.replace("customCheckSelected_", "");//Geting product Item Name from checked productItms
                    $.each(ProductItemDetails, function (indx, ob) {
                        var name = $("#hFlyoutName_" + itemName).html().indexOf("&amp;") > -1 ? $("#hFlyoutName_" + itemName).html().replace("&amp;", "&") : $("#hFlyoutName_" + itemName).html();
                        if (ob.ProductItemName.trim() == name.trim()) {
                            var ProductItemCommonName = (ob.ProductItemName.trim()).replace(/[`~!@#$%&*()_|\=?;:'’®",.<>\{\}\[\]\\\/]/gi, '').replace("+", "plus");
                            ProductItemCommonName = ProductItemCommonName.indexOf("  ") > -1 ? ProductItemCommonName.replace(/\s\s+/g, ' ').trim().replace(/\s/g, "©") : ProductItemCommonName.trim().replace(/\s/g, "©"); //repace multiple white space, tabs, new lines and replace space and special char with ©
                            //if (ob.IsStateWiseHide == true) {
                            //    IsStateWiseHideCount++;
                            //    var commonIdentification = (ob.ProductItemName).replace(/[^\w\s]/gi, '').replace(/\s/g, "©");
                            //    //if ((selectedProductsCount == IsStateWiseHideCount) || (IsSoldOutCount + IsStateWiseHideCount) == selectedProductsCount) {
                            //    //    alert(33);
                            //    //    $("#btnAddToCart").css("display", "none");
                            //    //    $("#btnSoldOut").css("display", "block");
                            //    //    $("#btnSoldOut").attr("disabled", "true");
                            //    //    $("#btnSoldOut>.primary-text")[0].innerText = ob.StateWiseHideNote;
                            //    //    $("#btnSoldOut").css("cursor", "no-drop");
                            //    //    btnTextChanged = true;
                            //    //}
                            //    //else if (selectedProductsCount > IsStateWiseHideCount) {
                            //    $('input[type=checkbox][id^="customCheckSelected_' + commonIdentification + '"]').prop("checked", false);
                            //    $('input[type=checkbox][id^="customCheckSelected_' + commonIdentification + '"]').removeAttr("checked");
                            //    $("." + commonIdentification + "div>#divFlyoutStateWiseHide>span")[0].innerText = ob.StateWiseHideNote;
                            //    $('input[type=checkbox][id^="customCheckSelected_' + commonIdentification + '"]').attr("disabled", true);
                            //    $("." + commonIdentification + "div>#divFlyoutStateWiseHide").show();
                            //    //}
                            //    //else {
                            //    //    $("." + commonIdentification + "div>#divFlyoutStateWiseHide").hide();
                            //    //}
                            //    $("#noStock").addClass('d-none');
                            //    // stopper = true;
                            //}
                            //else 
                            $("#customRadioPickinStore_" + ProductItemCommonName).attr("data-ItemAvailability", ob.ItemAvailabilityId);
                            if (ob.ItemAvailabilityId === "6") {
                                $('label[for="customRadioShipMe_' + ProductItemCommonName + '"]').find("span").text("Unavailable for shipping");
                                $("#customRadioPickinStore_" + ProductItemCommonName).attr("checked", "checked").prop("checked", true);
                                $("#customRadioShipMe_" + ProductItemCommonName).attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                                $('label[for="customRadioShipMe_' + ProductItemCommonName + '"]').find("span").attr("id", "spanDisableShip");

                                $('label[for="customRadioShipMe_CommonOption"]').find("span").text("Unavailable for shipping");
                                $("#customRadioPickinStore_CommonOption").attr("checked", "checked").prop("checked", true);
                                $("#customRadioShipMe_CommonOption").attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                                $('label[for="customRadioShipMe_CommonOption"]').find("span").attr("id", "spanDisableShip");

                                if (ob.InstalledPrice !== null && ob.InstalledPrice !== "" && ob.InstalledPrice !== undefined) {
                                    //installed product - update installed price by product price
                                    var price = "$" + parseFloat(ob.Price).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
                                    $("#lblPrice_" + ProductItemCommonName).text(price);
                                }
                            }
                            else if (ob.ItemAvailabilityId === "1" && ob.InstalledPrice !== null && ob.InstalledPrice !== "" && ob.InstalledPrice !== undefined) {
                                var price = "$" + parseFloat(ob.Price).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
                                $("#lblPrice_" + ProductItemCommonName).text(price);

                                // this code copied from below else if statement

                                if (ob.IsPickupOnly === true) {
                                    if ($("#dealerPickupMsg").hasClass("d-none") && ob.IsPickupOnly === true)
                                        $("#dealerPickupMsg").removeClass("d-none");

                                    $('label[for="customRadioShipMe_' + ProductItemCommonName + '"]').find("span").text("Unavailable for shipping");
                                    $("#customRadioPickinStore_" + ProductItemCommonName).attr("checked", "checked").prop("checked", true);
                                    $("#customRadioShipMe_" + ProductItemCommonName).attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                                    $('label[for="customRadioShipMe_' + ProductItemCommonName + '"]').find("span").attr("id", "spanDisableShip");
                                }
                            }
                            else if (ob.IsPickupOnly === true) {
                                if ($("#dealerPickupMsg").hasClass("d-none") && ob.IsPickupOnly === true)
                                    $("#dealerPickupMsg").removeClass("d-none");

                                $('label[for="customRadioShipMe_' + ProductItemCommonName + '"]').find("span").text("Unavailable for shipping");
                                $("#customRadioPickinStore_" + ProductItemCommonName).attr("checked", "checked").prop("checked", true);
                                $("#customRadioShipMe_" + ProductItemCommonName).attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                                $('label[for="customRadioShipMe_' + ProductItemCommonName + '"]').find("span").attr("id", "spanDisableShip");
                            }
                            else if (deliveryType != 'PickinStore') {
                                if (!$("#dealerPickupMsg").hasClass("d-none"))
                                    $("#dealerPickupMsg").addClass("d-none");

                                $('label[for="customRadioShipMe_' + ProductItemCommonName + '"]').find("span").text("Ship to me");
                                $("#customRadioShipMe_" + ProductItemCommonName).removeAttr("disabled").attr('checked', 'true').prop("checked", true);
                                $("#customRadioPickinStore_" + ProductItemCommonName).removeAttr("checked");
                                $('label[for="customRadioShipMe_' + ProductItemCommonName + '"]').find("span").removeAttr("id");
                            }
                            if (ob.ItemAvailabilityId == '0') {
                                if (!$('input[type=checkbox][id^="customCheckSelected_' + ProductItemCommonName + '"]').is("[disabled]") || $('input[type=checkbox][id^="customCheckSelected_' + ProductItemCommonName + '"]').is(":checked")) {
                                    //Checkbox disable and uncheck
                                    $('input[type=checkbox][id^="customCheckSelected_' + ProductItemCommonName + '"]').prop("checked", false).attr("disabled", "disabled");
                                }
                                //Hide the checkbox
                                $("#FlyoutCheckbox_" + ProductItemCommonName).addClass("d-none");
                                //Show Item Not Available Note
                                $("#ItemAvilabilityNote_" + ProductItemCommonName).removeClass("d-none");


                                $("." + ProductItemCommonName + "div>#divFlyoutStateWiseHide_" + ProductItemCommonName).hide();
                                $("#btnAddToCart").css("display", "").find("span.primary-text").text("Add To Cart");
                                $("#btnSoldOut").css("display", "none");


                                $("#FlyoutNoStockNotifyMe_" + ProductItemCommonName).addClass('d-none');
                                $("#NoStockNote_" + ProductItemCommonName).addClass("d-none");
                                $('.' + ProductItemCommonName + 'div>.DivNotifySec').addClass('d-none');
                                $('#FlyoutNoStockNotifyMe_' + ProductItemCommonName).find('button').removeAttr('disabled');

                            }
                            else if (ob.IsInInventory == false) {
                                if (dealer != null && dealer != 0) {
                                    if (availability != null && availability != "0") {
                                        btnTextChanged = true;
                                        IsSoldOutCount++;


                                        if (name != undefined && name != null)
                                            SelectedProductItemOptionNames += name + ",";

                                        //Checkbox disable and uncheck
                                        $('input[type=checkbox][id^="customCheckSelected_' + ProductItemCommonName + '"]').prop("checked", false).attr("disabled", "disabled");
                                        //Hide the checkbox
                                        $("#FlyoutCheckbox_" + ProductItemCommonName).addClass("d-none");
                                        //Show the Notify Button
                                        $("#FlyoutNoStockNotifyMe_" + ProductItemCommonName).removeClass("d-none");
                                        $("#FlyoutNoStockNotifyMe_" + ProductItemCommonName).find("button").attr("data-notifypartnumber", ob.PartNumber.trim()).attr("data-notifyitemid", ob.ProductItemId);
                                        //Show Out of stock Note
                                        $("#NoStockNote_" + ProductItemCommonName).removeClass("d-none");
                                        //Check this Item Already notified by geting Session Items
                                        var sessionNotify = $("#hdnNotifyMeSession").val();
                                        var notified = false;
                                        if (sessionNotify != undefined && sessionNotify != '') {
                                            if (sessionNotify.split(',').indexOf(ob.ProductItemId.toString()) != -1) {
                                                notified = true;
                                            }
                                        }
                                        if (notified == true) {
                                            $('.' + ProductItemCommonName + 'div>.DivNotifySec').removeClass('d-none');
                                            $('#FlyoutNoStockNotifyMe_' + ProductItemCommonName).find('button').attr('disabled', 'disabled');
                                        }
                                        else {
                                            $('.' + ProductItemCommonName + 'div>.DivNotifySec').addClass('d-none');
                                            $('#FlyoutNoStockNotifyMe_' + ProductItemCommonName).find('button').removeAttr('disabled');
                                        }
                                        //All product Items are Out of stock Remove the Add to Cart Button With Out Of Stock Button
                                        if (selectedProductsCount == IsSoldOutCount)
                                        //if ((selectedProductsCount == IsSoldOutCount) || (IsSoldOutCount + IsStateWiseHideCount) == selectedProductsCount) 
                                        {
                                            stopper = true;
                                            $("#btnAddToCart").css("display", "none");
                                            $("#btnSoldOut").css("display", "").attr("disabled", "disabled");
                                            $("#btnSoldOut").find('span.primary-text').text("Temporarily out of Stock");
                                            //if (IsStateWiseHideCount > 0)
                                            //    $("#btnSoldOut").find('span>primary-text').text(ob.StateWiseHideNote);

                                        }
                                        //SoldOut URL redirection
                                        if (ob.SoldOutUrl != "" && ob.SoldOutUrl != undefined && ob.SoldOutUrl != null) {
                                            $("#FlyoutNoStockNotifyMe_" + ProductItemCommonName).find("span").attr("target", "_blank");
                                            $("#FlyoutNoStockNotifyMe_" + ProductItemCommonName).find("span").attr("onclick", "window.open('" + ob.SoldOutUrl + "')");
                                        }
                                    }
                                }

                                //stopper = true;
                            }
                            else {//Have items avilable for sale
                                if ($('input[type=checkbox][id^="customCheckSelected_' + ProductItemCommonName + '"]').is("[disabled]")) {
                                    $('input[type=checkbox][id^="customCheckSelected_' + ProductItemCommonName + '"]').prop("checked", true).attr("checked");
                                    $('input[type=checkbox][id^="customCheckSelected_' + ProductItemCommonName + '"]').removeAttr("disabled");
                                }

                                $("." + ProductItemCommonName + "div>#divFlyoutStateWiseHide_" + ProductItemCommonName).hide();
                                $("#btnAddToCart").css("display", "").find("span.primary-text").text("Add To Cart");
                                $("#btnSoldOut").css("display", "none");

                                $("#FlyoutCheckbox_" + ProductItemCommonName).removeClass("d-none");
                                $("#FlyoutNoStockNotifyMe_" + ProductItemCommonName).addClass('d-none');
                                $("#NoStockNote_" + ProductItemCommonName).addClass("d-none");
                                $('.' + ProductItemCommonName + 'div>.DivNotifySec').addClass('d-none');
                                $('#FlyoutNoStockNotifyMe_' + ProductItemCommonName).find('button').removeAttr('disabled');

                                $("#ItemAvilabilityNote_" + ProductItemCommonName).addClass("d-none");
                            }

                        }

                    });
                });
            }
            else {//Have options or combination of Options and No options


                var notfyInfoOptions = '';

                if (selectedProductsCount === null || selectedProductsCount === '' || selectedProductsCount === undefined || selectedProductsCount === 0) {

                    selectedProductsCount = selectedProducts.length;
                }
                $.each(selectedProducts, function (ind, obj) {
                    var commonIdentification = (obj.productItemName).trim().replace('&amp;', '').replace(/[`~!@#$%&*()_|\=?;:'’®",.<>\{\}\[\]\\\/]/gi, '').replace("+", "plus");
                    commonIdentification = commonIdentification.indexOf("  ") > -1 ? commonIdentification.replace(/\s\s+/g, ' ').trim().replace(/\s/g, "©") : commonIdentification.trim().replace(/\s/g, "©");
                    var isProdHide = false;
                    var selectedProductItemDetails = getAllSelectOptionProductDetails(obj.productItemName.trim(), obj.selectedOptionName.split('_')[2], obj.selectedOptions);
                    var hdnSelectedId = $("#hdnFlyOutOption_" + commonIdentification + "_" + obj.selectedOptionName.split('_')[2].replace(/\s/g, "©")).val();


                    $.each(ProductItemDetails, function (indx, ob) {
                        var productItemCommonName = (ob.ProductItemName.trim()).replace(/[`~!@#$%&*()_|\=?;:'’®",.<>\{\}\[\]\\\/]/gi, '').replace("+", "plus");
                        productItemCommonName = productItemCommonName.indexOf("  ") > -1 ? productItemCommonName.replace(/\s\s+/g, ' ').trim().replace(/\s/g, "©") : productItemCommonName.trim().replace(/\s/g, "©");

                        if (ob.ProductOptions.length > 0 && obj.productItemName.trim() == ob.ProductItemName.trim()) {

                            $.each(ob.ProductOptions, function (idx, objct) {

                                $("#customRadioPickinStore_" + productItemCommonName).attr("data-ItemAvailability", ob.ItemAvailabilityId);
                                if (hdnSelectedId == objct.OptionId.toString() && obj.productItemName.trim() == ob.ProductItemName.trim()) {
                                    if (stopper === false) {
                                        if (ob.ItemAvailabilityId === '6') {
                                            $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").text("Unavailable for shipping");
                                            $("#customRadioPickinStore_" + productItemCommonName).attr("checked", "checked").prop("checked", true);
                                            $("#customRadioShipMe_" + productItemCommonName).attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                                            $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").attr("id", "spanDisableShip");


                                            $('label[for="customRadioShipMe_CommonOption"]').find("span").text("Unavailable for shipping");
                                            $("#customRadioPickinStore_CommonOption").attr("checked", "checked").prop("checked", true);
                                            $("#customRadioShipMe_CommonOption").attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                                            $('label[for="customRadioShipMe_CommonOption"]').find("span").attr("id", "spanDisableShip");
                                            if (ob.InstalledPrice !== null && ob.InstalledPrice !== "" && ob.InstalledPrice !== undefined) {
                                                //installed product - update installed price by product price
                                                var price = "$" + parseFloat(ob.Price).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
                                                $("#lblPrice_" + productItemCommonName).text(price);
                                            }
                                        }
                                        else if (ob.ItemAvailabilityId === "1" && ob.InstalledPrice !== null && ob.InstalledPrice !== "" && ob.InstalledPrice !== undefined) {
                                            var price = "$" + parseFloat(ob.Price).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
                                            $("#lblPrice_" + productItemCommonName).text(price);

                                            if (ob.IsPickupOnly === true) {
                                                if ($("#dealerPickupMsg").hasClass("d-none") && ob.IsPickupOnly === true)
                                                    $("#dealerPickupMsg").removeClass("d-none");

                                                $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").text("Unavailable for shipping");
                                                $("#customRadioPickinStore_" + productItemCommonName).attr("checked", "checked").prop("checked", true);
                                                $("#customRadioShipMe_" + productItemCommonName).attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                                                $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").attr("id", "spanDisableShip");
                                            }
                                        }
                                        else if (ob.IsPickupOnly === true) {
                                            if ($("#dealerPickupMsg").hasClass("d-none") && ob.IsPickupOnly === true)
                                                $("#dealerPickupMsg").removeClass("d-none");

                                            $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").text("Unavailable for shipping");
                                            $("#customRadioPickinStore_" + productItemCommonName).attr("checked", "checked").prop("checked", true);
                                            $("#customRadioShipMe_" + productItemCommonName).attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                                            $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").attr("id", "spanDisableShip");
                                        }
                                        else if (deliveryType != 'PickinStore') {
                                            if (!$("#dealerPickupMsg").hasClass("d-none"))
                                                $("#dealerPickupMsg").addClass("d-none");

                                            $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").text("Ship to me");
                                            $("#customRadioShipMe_" + productItemCommonName).removeAttr("disabled").attr('checked', 'true').prop("checked", true);
                                            $("#customRadioPickinStore_" + productItemCommonName).removeAttr("checked");
                                            $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").removeAttr("id");
                                        }
                                        if (ob.ItemAvailabilityId === '0') {
                                            if (!$('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').is("[disabled]") || $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').is(":checked")) {
                                                //Checkbox disable and uncheck
                                                $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').prop("checked", false).attr("disabled", "disabled");
                                            }
                                            //Hide the checkbox
                                            $("#FlyoutCheckbox_" + productItemCommonName).addClass("d-none");
                                            //Show Item Not Available Note
                                            $("#ItemAvilabilityNote_" + productItemCommonName).removeClass("d-none");

                                            $("." + productItemCommonName + "div>#divFlyoutStateWiseHide_" + productItemCommonName).hide();
                                            $("#btnAddToCart").css("display", "").find("span.primary-text").text("Add To Cart");
                                            $("#btnSoldOut").css("display", "none");


                                            $("#FlyoutNoStockNotifyMe_" + productItemCommonName).addClass('d-none');
                                            $("#NoStockNote_" + productItemCommonName).addClass("d-none");
                                            $('.' + productItemCommonName + 'div>.DivNotifySec').addClass('d-none');
                                            $('#FlyoutNoStockNotifyMe_' + productItemCommonName).find('button').removeAttr('disabled');

                                        }
                                        else if (ob.IsInInventory === false) {
                                            btnTextChanged = true;
                                            IsSoldOutCount++;
                                            notfyInfoOptions = objct.OptionCategory + ":" + objct.OptionValue + ",";


                                            //Check box Disable and Uncheck
                                            $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').removeAttr("checked");
                                            $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').prop("checked", false).attr("disabled", "disabled");

                                            //Hide the Checkbox
                                            $("#FlyoutCheckbox_" + productItemCommonName).addClass("d-none");
                                            //Show Button And Note
                                            $("#FlyoutNoStockNotifyMe_" + productItemCommonName).removeClass("d-none");
                                            $("#FlyoutNoStockNotifyMe_" + productItemCommonName).find("button").attr("data-notifyoption", notfyInfoOptions).attr("data-notifypartnumber", ob.PartNumber).attr("data-notifyitemid", ob.ProductItemId);
                                            $("#NoStockNote_" + productItemCommonName).removeClass("d-none");
                                            //Check Already notfied by getting session data
                                            var sessionNotify = $("#hdnNotifyMeSession").val();
                                            var notified = false;
                                            if (sessionNotify != undefined && sessionNotify != '') {
                                                if (sessionNotify.split(',').indexOf(ob.ProductItemId.toString()) != -1) {
                                                    notified = true;
                                                }
                                            }
                                            if (notified == true) {
                                                $('.' + productItemCommonName + 'div>.DivNotifySec').removeClass('d-none');
                                                $('#FlyoutNoStockNotifyMe_' + productItemCommonName).find('button').attr('disabled', 'disabled');
                                            }
                                            else {
                                                $('.' + productItemCommonName + 'div>.DivNotifySec').addClass('d-none');
                                                $('#FlyoutNoStockNotifyMe_' + productItemCommonName).find('button').removeAttr('disabled');
                                            }
                                            //Soldout redirection URL
                                            if (obj.SoldOutUrl != "" || obj.SoldOutUrl != undefined || obj.SoldOutUrl != null) {

                                                $("#NoStockNote_" + productItemCommonName).find("span").attr("target", "_blank");
                                                $("#NoStockNote_" + productItemCommonName).find("span").attr("onclick", "window.open('" + ob.SoldOutUrl + "')");
                                            }
                                            //Replace Add to Cart Button By Out of Stock if all items are out of stock
                                            if (selectedProductsCount == IsSoldOutCount)
                                            //if ((selectedProductsCount == IsSoldOutCount) || (IsSoldOutCount + IsStateWiseHideCount) == selectedProductsCount)
                                            {
                                                //stopper = true;
                                                $("#btnAddToCart").css("display", "none");
                                                $("#btnSoldOut").css("display", "").attr("disabled", "disabled");
                                                //if (IsStateWiseHideCount > 0)
                                                //    $("#btnSoldOut").find('span>primary-text').text(ob.StateWiseHideNote);
                                                //else
                                                $("#btnSoldOut").find('span>primary-text').text("Temporarily out of Stock");
                                            }
                                        }//inventory 
                                        else {
                                            if ($('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').is("[disabled]")) {
                                                $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').attr("checked");
                                                $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').prop("checked", true);
                                                $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').removeAttr("disabled");
                                            }

                                            $("." + productItemCommonName + "div>#divFlyoutStateWiseHide_" + productItemCommonName).hide();
                                            $("#btnAddToCart").css("display", "").find("span.primary-text").text("Add To Cart");
                                            $("#btnSoldOut").css("display", "none");

                                            $("#FlyoutCheckbox_" + productItemCommonName).removeClass("d-none");
                                            $("#FlyoutNoStockNotifyMe_" + productItemCommonName).addClass('d-none');
                                            $("#NoStockNote_" + productItemCommonName).addClass("d-none");
                                            $('.' + productItemCommonName + 'div>.DivNotifySec').addClass('d-none');
                                            $('#FlyoutNoStockNotifyMe_' + productItemCommonName).find('button').removeAttr('disabled');

                                            $("#ItemAvilabilityNote_" + productItemCommonName).addClass("d-none");
                                        }//invnetory
                                    }//stopper
                                }//checking id and name

                            });
                        }
                        else if (ob.ProductOptions.length == 0) {
                            //No options - ie. no slectedProducts for such item

                            $("#customRadioPickinStore_" + productItemCommonName).attr("data-ItemAvailability", ob.ItemAvailabilityId);
                            if (obj.productItemName.trim() != ob.ProductItemName.trim() && ob.ProductOptions.length == 0) {
                                //alert(obj.productItemName.trim() + ob.ProductItemName.trim());

                                if (ob.ItemAvailabilityId === '6') {
                                    $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").text("Unavailable for shipping");
                                    $("#customRadioPickinStore_" + productItemCommonName).attr("checked", "checked").prop("checked", true);
                                    $("#customRadioShipMe_" + productItemCommonName).attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                                    $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").attr("id", "spanDisableShip");
                                    if (ob.InstalledPrice !== null && ob.InstalledPrice !== "" && ob.InstalledPrice !== undefined) {
                                        //installed product - update installed price by product price
                                        var price = "$" + parseFloat(ob.Price).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
                                        $("#lblPrice_" + productItemCommonName).text(ob.price);
                                    }
                                }
                                else if (ob.ItemAvailabilityId === "1" && ob.InstalledPrice !== null && ob.InstalledPrice !== "" && ob.InstalledPrice !== undefined) {
                                    var price = "$" + parseFloat(ob.Price).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
                                    $("#lblPrice_" + productItemCommonName).text(price);

                                    if (ob.IsPickupOnly === true) {
                                        if ($("#dealerPickupMsg").hasClass("d-none"))
                                            $("#dealerPickupMsg").removeClass("d-none");

                                        $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").text("Unavailable for shipping");
                                        $("#customRadioPickinStore_" + productItemCommonName).attr("checked", "checked").prop("checked", true);
                                        $("#customRadioShipMe_" + productItemCommonName).attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                                        $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").attr("id", "spanDisableShip");
                                    }
                                }
                                else if (ob.IsPickupOnly === true) {
                                    if ($("#dealerPickupMsg").hasClass("d-none"))
                                        $("#dealerPickupMsg").removeClass("d-none");

                                    $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").text("Unavailable for shipping");
                                    $("#customRadioPickinStore_" + productItemCommonName).attr("checked", "checked").prop("checked", true);
                                    $("#customRadioShipMe_" + productItemCommonName).attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
                                    $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").attr("id", "spanDisableShip");
                                }
                                else if (deliveryType != 'PickinStore') {
                                    if (!$("#dealerPickupMsg").hasClass("d-none"))
                                        $("#dealerPickupMsg").addClass("d-none");

                                    $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").text("Ship to me");
                                    $("#customRadioShipMe_" + productItemCommonName).removeAttr("disabled").attr('checked', 'true').prop("checked", true);
                                    $("#customRadioPickinStore_" + productItemCommonName).removeAttr("checked");
                                    $('label[for="customRadioShipMe_' + productItemCommonName + '"]').find("span").removeAttr("id");
                                }
                                if (ob.ItemAvailabilityId === '0') {
                                    if (!$('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').is("[disabled]") || $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').is(":checked")) {
                                        $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').prop("checked", false);
                                        $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').removeAttr("checked");
                                        $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').attr("disabled", "disabled");
                                    }
                                    $("#FlyoutCheckbox_" + productItemCommonName).addClass("d-none");
                                    $("#ItemAvilabilityNote_" + productItemCommonName).removeClass("d-none");


                                    $("." + productItemCommonName + "div>#divFlyoutStateWiseHide_" + productItemCommonName).hide();
                                    $("#btnAddToCart").css("display", "").find("span.primary-text").text("Add To Cart");
                                    $("#btnSoldOut").css("display", "none");


                                    $("#FlyoutNoStockNotifyMe_" + productItemCommonName).addClass('d-none');
                                    $("#NoStockNote_" + productItemCommonName).addClass("d-none");
                                    $('.' + productItemCommonName + 'div>.DivNotifySec').addClass('d-none');
                                    $('#FlyoutNoStockNotifyMe_' + productItemCommonName).find('button').removeAttr('disabled');

                                }
                                else if (ob.IsInInventory == false) {
                                    if (dealer != null && dealer != 0) {
                                        if (availability != null && availability != "0") {
                                            btnTextChanged = true;
                                            IsSoldOutCount++;
                                            if (name != undefined && name != null)
                                                SelectedProductItemOptionNames += name + ",";

                                            $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').prop("checked", false).attr("disabled", "disabled");

                                            $("#FlyoutCheckbox_" + productItemCommonName).addClass("d-none");
                                            $("#FlyoutNoStockNotifyMe_" + productItemCommonName).removeClass("d-none");
                                            $("#FlyoutNoStockNotifyMe_" + productItemCommonName).find("button").attr("data-notifypartnumber", ob.PartNumber.trim()).attr("data-notifyitemid", ob.ProductItemId);

                                            $("#NoStockNote_" + productItemCommonName).removeClass("d-none");
                                            var sessionNotify = $("#hdnNotifyMeSession").val();
                                            var notified = false;
                                            if (sessionNotify != undefined && sessionNotify != '') {
                                                if (sessionNotify.split(',').indexOf(ob.ProductItemId.toString()) != -1) {
                                                    notified = true;
                                                }
                                            }
                                            if (notified == true) {
                                                $('.' + productItemCommonName + 'div>.DivNotifySec').removeClass('d-none');
                                                $('#FlyoutNoStockNotifyMe_' + productItemCommonName).find('button').attr('disabled', 'disabled');
                                            }
                                            else {
                                                $('.' + productItemCommonName + 'div>.DivNotifySec').addClass('d-none');
                                                $('#FlyoutNoStockNotifyMe_' + productItemCommonName).find('button').removeAttr('disabled');
                                            }
                                            //All product Items are Out of stock Remove the Add to Cart Button With Out Of Stock Button
                                            if (selectedProductsCount == IsSoldOutCount)
                                            //if ((selectedProductsCount == IsSoldOutCount) || (IsSoldOutCount + IsStateWiseHideCount) == selectedProductsCount) 
                                            {
                                                //stopper = true;
                                                $("#btnAddToCart").css("display", "none");
                                                $("#btnSoldOut").css("display", "").attr("disabled", "disabled");
                                                $("#btnSoldOut").find('span.primary-text').text("Temporarily out of Stock");
                                                //if (IsStateWiseHideCount > 0)
                                                //    $("#btnSoldOut").find('span>primary-text').text(ob.StateWiseHideNote);

                                            }
                                            //SoldOut URL redirection
                                            if (ob.SoldOutUrl != "" && ob.SoldOutUrl != undefined && ob.SoldOutUrl != null) {
                                                $("#FlyoutNoStockNotifyMe_" + productItemCommonName).find("span").attr("target", "_blank");
                                                $("#FlyoutNoStockNotifyMe_" + productItemCommonName).find("span").attr("onclick", "window.open('" + ob.SoldOutUrl + "')");
                                            }
                                        }
                                    }

                                    //stopper = true;
                                }
                                else {
                                    if ($('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').is("[disabled]")) {
                                        $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').prop("checked", true).attr("checked");
                                        $('input[type=checkbox][id^="customCheckSelected_' + productItemCommonName + '"]').removeAttr("disabled");
                                    }

                                    $("." + productItemCommonName + "div>#divFlyoutStateWiseHide_" + productItemCommonName).hide();
                                    $("#btnAddToCart").css("display", "").find("span.primary-text").text("Add To Cart");
                                    $("#btnSoldOut").css("display", "none");

                                    $("#FlyoutCheckbox_" + productItemCommonName).removeClass("d-none");
                                    $("#FlyoutNoStockNotifyMe_" + productItemCommonName).addClass('d-none');
                                    $("#NoStockNote_" + productItemCommonName).addClass("d-none");
                                    $('.' + productItemCommonName + 'div>.DivNotifySec').addClass('d-none');
                                    $('#FlyoutNoStockNotifyMe_' + productItemCommonName).find('button').removeAttr('disabled');

                                    $("#ItemAvilabilityNote_" + productItemCommonName).addClass("d-none");
                                }
                            }
                        }

                    });
                    if (isProdHide) {
                        $("." + commonIdentification + "div>#divFlyoutStateWiseHide_" + commonIdentification).show();
                    }
                    else {
                        $("." + commonIdentification + "div>#divFlyoutStateWiseHide_" + commonIdentification).hide();
                    }
                });
            }
        }
    }
    else {

        //if (ProductItemDetails[0].IsStateWiseHide == true) {
        //    $("#btnAddToCart").css("display", "none");

        //    $("#btnCartModelSelectionPopup").css("display", "none");

        //    $("#btnSoldOut span.primary-text").text(ProductItemDetails[0].StateWiseHideNote);
        //    $("#btnSoldOut").css("display", "");
        //    $("#btnSoldOut").attr("disabled", "true");
        //    $("#btnSoldOut").css("cursor", "no-drop");
        //    $("#noStock").addClass('d-none');
        //    btnTextChanged = true;
        //    stopper = true;
        //}
        //else 
        $("#ItemAvailability").val(ProductItemDetails[0].ItemAvailabilityId);
        $("#InstallationPrice").val(ProductItemDetails[0].InstalledPrice);
        var price = "$0.0";
        var productItemCommonName = (ProductItemDetails[0].ProductItemName.trim()).replace(/[`~!@#$%&*()_|\=?;:'’®",.<>\{\}\[\]\\\/]/gi, '').replace("+", "plus");
        productItemCommonName = productItemCommonName.indexOf("  ") > -1 ? productItemCommonName.replace(/\s\s+/g, ' ').trim().replace(/\s/g, "©") : productItemCommonName.trim().replace(/\s/g, "©");
        if (ProductItemDetails[0].ItemAvailabilityId === '6') {

            $('label[for="customRadioShipMe_CommonOption"]').find("span").text("Unavailable for shipping");
            $("#customRadioPickinStore_CommonOption").attr("checked", "checked").prop("checked", true);
            $("#customRadioShipMe_CommonOption").attr("disabled", "disabled").removeAttr("checked").prop("checked", false);
            $('label[for="customRadioShipMe_CommonOption"]').find("span").attr("id", "spanDisableShip");
            $("#deliveryType").val("pickup in store");
            if (ProductItemDetails[0].InstalledPrice !== null && ProductItemDetails[0].InstalledPrice !== "" && ProductItemDetails[0].InstalledPrice !== undefined) {
                //installed product - update installed price by product price
                price = "$" + parseFloat(ProductItemDetails[0].Price).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
                $("#lblPrice_" + productItemCommonName).text(price);
            }
        }
        else if (ProductItemDetails[0].ItemAvailabilityId === "1" && ProductItemDetails[0].InstalledPrice !== null && ProductItemDetails[0].InstalledPrice !== "" && ProductItemDetails[0].InstalledPrice !== undefined) {
            price = "$" + parseFloat(ProductItemDetails[0].Price).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,').replace(".00", "");
            $("#lblPrice_" + productItemCommonName).text(price);
        }

        if (ProductItemDetails[0].ItemAvailabilityId === '0') {

            $("#btnAddToCart").attr("disabled", "disabled").find("span.primary-text").text("Currently not available from this dealer");

            if (modelId == '' && isModelProduct == "1") {
                $("#btnCartModelSelectionPopup").css('display', '');
                $("#btnCartModelSelectionPopup").find('span.primary-text').text('Add To Cart');
            }
            else {
                $("#btnCartModelSelectionPopup").attr("disabled", "disabled").find("span.primary-text").text("Currently not available from this dealer");
            }


        }
        else if (ProductItemDetails[0].IsInInventory == false) {
            if (dealer == null || dealer == 0) {
                btnTextChanged = true;
                $("#btnCartModelSelectionPopup").css("display", "none");
                $("#btnAddToCart").css("display", "none");
                if (modelId == '' && isModelProduct == "1") {
                    $("#btnCartModelSelectionPopup").css("display", "").find('span.primary-text').text('Add To Cart');
                    $("#btnSoldOut").css("display", "none");
                }
                else {
                    $("#btnSoldOut").css("display", "").find('span.primary-text').text('Select Dealer');
                }

                var link = document.getElementById('locateDealerClick');
                if (link != null)
                    link.click();
            }
            else {

                if (modelId == '' && isModelProduct == "1") {
                    $("#btnCartModelSelectionPopup").css('display', '');
                    $("#btnCartModelSelectionPopup").find('span.primary-text').text('Add To Cart');
                }
                else {

                    OptionItemDetails = ProductItemDetails[0].PartNumber + "@" + ProductItemDetails[0].ProductItemId + "@empty";
                    btnTextChanged = true;
                    $("#btnAddToCart").css("display", "none");
                    $("#noStock").removeClass('d-none');
                    if ($("#divModelVinNote") != undefined)
                        $("#divModelVinNote").css("display", "none");
                    $("#btnCartModelSelectionPopup").css("display", "none");
                    $("#btnSoldOut").css("display", "").attr("disabled", "disabled");
                    $("#btnSoldOut span.primary-text").text('Temporarily out of Stock');
                    if (ProductItemDetails[0].SoldOutURL == "" || ProductItemDetails[0].SoldOutURL == undefined || ProductItemDetails[0].SoldOutURL == null) {

                        $("#btnCartModelSelectionPopup").attr("disabled", "true");
                        $("#btnCartModelSelectionPopup").css("cursor", "no-drop");
                        $("#btnSoldOut").css("cursor", "no-drop");
                    }
                    else {

                        $("#btnCartModelSelectionPopup").removeAttr("disabled");
                        $("#btnCartModelSelectionPopup").css("cursor", "default");
                        $("#btnCartModelSelectionPopup").attr("target", "_blank");
                        $("#btnCartModelSelectionPopup").attr("onclick", "window.open('" + ProductItemDetails[0].SoldOutURL + "')");

                        $("#btnSoldOut").removeAttr("disabled").css("cursor", "default").attr("target", "_blank").attr("onclick", "window.open('" + ProductItemDetails[0].SoldOutURL + "')");
                    }
                }
            }
        }
        else {
            $("#btnAddToCart").removeAttr("disabled").find("span.primary-text").text("Add To Cart");
            $("#btnCartModelSelectionPopup").removeAttr("disabled").find("span.primary-text").text("Add To Cart");
        }
    }

    if (!btnTextChanged) {
        $("#btnSoldOut span.primary-text").text("Add To Cart");
        $("#btnSoldOut").removeAttr("disabled");
        $("#btnSoldOut").css("cursor", "pointer");
    }
}



//nostock email notification
$("#btnNoStock").click(function (e) {
    e.preventDefault();
    var ItemOptionInfo = 'empty@';
    var partNumber = '';
    var modelId = $("#hdnModelId").val();
    var isModelProduct = $("#hdnIsModelProduct").val();
    var category = $("#hdnCategoryType").val().toLowerCase();
    var prodId = $("#hdnProdId").val();
    var pdtName = $("#hdnProductName").val().replace(/\s/g, "©");
    var productName = $("#hName_" + pdtName).text();
    var productItemId = "";
    var price = 0.0;

    //GroupName@PartNumber@ProductItemId@optionCategory1,optionCategory2:OptionValue1,OptionValue2
    //empty@required@required@empty
    if (SelectedProductItemOptionNames != null && SelectedProductItemOptionNames != '' && SelectedProductItemOptionNames != undefined) {
        ItemOptionInfo += SelectedProductItemOptionNames;
    }
    if (SelectedProductOptionToNotify != '' && SelectedProductOptionToNotify != null && SelectedProductOptionToNotify != undefined) {
        SelectedProductItemOptionNames = SelectedProductOptionToNotify;
        ItemOptionInfo = SelectedProductItemOptionNames;
        price = $("#lblPrice_" + SelectedProductOptionToNotify.split("@")[0].replace(/\s/g, "©")).text().slice(1);
    }
    else {
        if (OptionItemDetails != null && OptionItemDetails != undefined && OptionItemDetails != '') {
            ItemOptionInfo += OptionItemDetails;
        }
        else {
            ItemOptionInfo += "@empty@empty@empty";
        }
        if ($("#totalPrice").text() != '' && $("#totalPrice").text() != undefined && $("#totalPrice").text() != null)
            price = $("#totalPrice").text().trim().slice(1);
        else if ($("#PriceRange").text() != '' && $("#PriceRange").text() != undefined)
            price = $("#PriceRange").text().trim().slice(1);

    }
    if (ItemOptionInfo != '' && ItemOptionInfo != undefined) {
        productItemId = ItemOptionInfo.split('@')[2];
    }
    //Product is Bundled, then Collect All Product Item Ids
    if ($("#hdnIsProductBundle").val() != undefined && $("#hdnIsProductBundle").val() != "" && $("#hdnIsProductBundle").val().toLowerCase() == "true") {
        productItemId = "";
        $.each(ProductItemDetails, function (ind, obj) {
            if (obj.ProductItemId != "") {
                productItemId += obj.ProductItemId + ",";
            }
        });
        productItemId = productItemId.substring(0, productItemId.length - 1);
        productItemId = productItemId.toString();
    }

    if (dealer != null && dealer != 0 && dealer != undefined) {

        if (prodId != null && prodId != '' && prodId != undefined && productName != null && productName != '') {
            // checkbox
            var validateCheckboxErr = false;
            validateCheckboxErr = validteCheckoutChekbox('defaultUnchecked11a');
            //captcha
            var reCaptchaResponse = grecaptcha.getResponse();
            if ($("#txtNoStockEmail").val() != null && $("#txtNoStockEmail").val() != '' && $("#txtNoStockEmail").val() != undefined) {
                //email 
                var validateEmailErr = validateEmail($("#txtNoStockEmail").val());
                if (validateEmailErr && !validateCheckboxErr && reCaptchaResponse.length != 0) {
                    var params = {
                        emailAddress: $("#txtNoStockEmail").val(), productId: prodId, productName: productName, productItemsInfo: ItemOptionInfo, captcha: reCaptchaResponse, modelProduct: (isModelProduct == "1" || category == "accessories") ? 1 : 0, productItemId: productItemId, price: parseFloat(price)
                    };

                    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.Products.NoStockDealerNotificationForProduct, data: params }, {
                        complete: function (json) {
                            if (json.responseJSON != null && json.responseJSON == "success") {
                                grecaptcha.reset();
                                $("#divNoStockEmail").addClass("d-none").siblings('section').addClass("d-none");
                                $("#noStockSucMsg").removeClass("d-none");
                                //Update Session Notify Hidden Filed
                                var sessionNotify = $("#hdnNotifyMeSession").val();
                                var notified = false;
                                if (sessionNotify != undefined && sessionNotify != null && sessionNotify != '') {
                                    sessionNotify = sessionNotify + "," + productItemId;
                                    $("#hdnNotifyMeSession").val(sessionNotify);
                                    if (sessionNotify.split(',').indexOf(productItemId) != -1) {
                                        notified = true;
                                    }
                                }
                                else {
                                    sessionNotify = productItemId;
                                    $("#hdnNotifyMeSession").val(sessionNotify);
                                    notified = true;
                                }
                                if (notified == true) {

                                    if (SelectedProductItemOptionNames != null && SelectedProductItemOptionNames != undefined && SelectedProductItemOptionNames != '') {
                                        //show the success msg and hide the notify button
                                        SelectedProductItemOptionNames = SelectedProductItemOptionNames.split("@")[0].trim().replace(/[`~@$%&*()\:'’®",.{\}\[\]\\\/]/gi, '').replace("+", "plus").replace(/\s/g, "©");//.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '').replace(/\s/g, "©");
                                        $('.' + SelectedProductItemOptionNames + 'div>.DivNotifySec').removeClass('d-none');
                                        $('#FlyoutNoStockNotifyMe_' + SelectedProductItemOptionNames).find('button').attr('disabled', 'disabled');
                                    }
                                }
                                //Hide Pop up Model and Handle Input Fields - on Success
                                $('#NotifyModal').modal('hide');
                                $('#txtNoStockEmail,#NotifyModal>input:text').val('');
                                $("#defaultUnchecked11a").prop("checked", false);
                                if (!($("#spanNoStockCaptch").hasClass("d-none")))
                                    $("#spanNoStockCaptch").addClass("d-none");
                            }
                            else if (json.responseJSON == "Bad Request") {
                                $("#spanNoStockCaptch").text("Please Try Again..!").removeClass("d-none");
                            }
                        }
                    }));
                }
                else {

                    if (!validateEmailErr) {
                        $("#txtNoStockEmail").addClass("InvalidSearch");
                        $("#spanNoStockEmail").text("Please enter a valid email address").removeClass("d-none");
                    }
                    else {
                        $("#txtNoStockEmail").removeClass("InvalidSearch");
                        $("#spanNoStockEmail").text("").addClass("d-none");
                    }

                    if (reCaptchaResponse.length == 0) {
                        $("#spanNoStockCaptch").text("You can't leave Captcha Code empty").removeClass("d-none");
                    }
                }
            }
            else {
                $("#txtNoStockEmail").addClass("InvalidSearch");
                $("#spanNoStockEmail").text("Please enter a valid email address").removeClass("d-none");

                if (reCaptchaResponse.length == 0) {
                    $("#spanNoStockCaptch").text("You can't leave Captcha Code empty").removeClass("d-none");
                }
            }
        } else {
            $("#txtNoStockEmail").addClass("InvalidSearch");
            $("#spanNoStockEmail").text("Please Try Again...!").removeClass("d-none");
        }
    }
    else {
        var link = document.getElementById('locateDealerClick');
        $("#spanNoStockEmail").text("Select Dealer...!").removeClass("d-none");
        //link.click();
    }

});


//find the options by notify button click
var SelectedProductOptionToNotify;
function OptionProductItemForNotify(event, ItemName) {
    if (ItemName != null && ItemName != undefined) {
        //Flyout Section - Getting Partnumber and Item Id
        SelectedProductOptionToNotify = ItemName;//.replace("©", /\s/g);

        //Geting partnumber of the selected Option 
        var notifyPartNumber = $(event.target).attr("data-notifypartnumber");
        if (notifyPartNumber != undefined) {
            SelectedProductOptionToNotify += "@" + notifyPartNumber;
        }

        //Geting productitemid of the selected Option 
        var notifyProductItemId = $(event.target).attr("data-notifyitemid");
        if (notifyProductItemId != undefined) {
            SelectedProductOptionToNotify += "@" + notifyProductItemId;
        }

        //Geting selected Option 
        var notifyInfo = $(event.target).attr("data-notifyoption");
        if (notifyInfo != undefined) {
            SelectedProductOptionToNotify += "@" + notifyInfo.slice(0, -1);
        }
    }
    else {
        SelectedProductOptionToNotify = null;
    }

    NoSTockEmailValidationReset();

}

function verifyCaptcha() {
    $("#spanNoStockCaptch").text("").addClass("d-none");
}

function NoSTockEmailValidationReset() {
    if (!$("#spanNoStockEmail").hasClass("d-none")) {
        //email check
        $("#txtNoStockEmail").removeClass("InvalidSearch").val('');
        $("#spanNoStockEmail").text("").addClass("d-none");
    }
    if ($("#txtNoStockEmail").val('') != '') {
        //email check
        $("#txtNoStockEmail").val('');
    }
    if (!$("#spanNoStockCaptch").hasClass("d-none")) {
        //captcha msg
        $("#spanNoStockCaptch").text("").addClass("d-none");
    }
    $('#NotifyModal input:text').val(''); //empty the input fields
    $('label[for="defaultUnchecked11a"]').siblings("input").removeAttr("checked").prop("checked", false);
    if ($('label[for="defaultUnchecked11a"]').closest("div").hasClass("terms-validation")) {
        //checkbox validation
        $("#defaultUnchecked11a").closest("div").removeClass("terms-validation");
    }
    if (typeof grecaptcha != 'undefined' && grecaptcha != null) {
        if (grecaptcha.getResponse != undefined && grecaptcha.getResponse().length != 0)
            grecaptcha.reset();
    }
}

$("#clickinst").click(function () {
    $("#InstallationFailed").removeClass("d-none").addClass("d-block");
});
$("#clickremoveinst").click(function () {
    $("#InstallationFailed").removeClass("d-block").addClass("d-none");
});



$(document).ready(function () {
    $(".Thumbimg").css({ 'height': ($("#prdtZoom").height() + 'px') });
});

function specialsOptionSelectionQuantityUpdate(itemName, qtyLeft) {
    if ($("#hdnIsSpecialProduct").val().toLowerCase() == "true") {
        var dropdownId = "dropdown-menu_" + itemName;
        if (qtyLeft != "0" && parseInt(qtyLeft) < 10) {
            if (itemName == "AllOptions" && $("#hdnIsTypeDProduct").val().toLowerCase() != "true") {
                var detailsqtyText = $("#lblDetailsQty").text();
                if (parseInt(detailsqtyText) > parseInt(qtyLeft)) {
                    $("#lblDetailsQty").text(qtyLeft);
                }
                $("#dropdownMenuQty").empty();
                var text = "";
                for (var i = 1; i <= parseInt(qtyLeft); i++) {
                    text += "<a class='dropdown-item' data-ajax='true' onclick='DetailsQtyChange(\"" + i + "\")' >" + i.toString() + " </a >";
                }
                $("#dropdownMenuQty").append(text);
                if (parseInt(qtyLeft) <= 5) {
                    $("#lblQtyLeft").text("Limited Stock Available");
                } else {
                    $("#lblQtyLeft").text("");
                }
            } else {
                var qtyText = $("#lblDetailsQty_" + itemName).text();
                if (parseInt(qtyText) > parseInt(qtyLeft)) {
                    $("#lblDetailsQty_" + itemName).text(qtyLeft);
                } else {
                    $("#lblDetailsQty_" + itemName).text(qtyText);
                }
                if (parseInt(qtyLeft) <= 5) {
                    $("#lblQtyLeft_" + itemName).text("Limited Stock Available");
                } else {
                    $("#lblQtyLeft_" + itemName).text("");
                }
                $("#" + dropdownId).empty();
                var text = "";
                for (var i = 1; i <= parseInt(qtyLeft); i++) {
                    text += "<a class='dropdown-item' data-ajax='true' onclick='DetailsFlyoutQtyChange(\"" + i + '","' + itemName + "\")' >" + i.toString() + " </a >";
                }
                $("#" + dropdownId).append(text);
            }
        } else {
            if (itemName == "AllOptions" && $("#hdnIsTypeDProduct").val().toLowerCase() != "true") {
                $("#dropdownMenuQty").empty();
                var text = "";
                for (var i = 1; i <= 10; i++) {
                    text += "<a class='dropdown-item' data-ajax='true' onclick='DetailsQtyChange(\"" + i + "\")' >" + i.toString() + " </a >";
                }
                $("#dropdownMenuQty").append(text);
                $("#lblQtyLeft").text("");
            } else {
                $("#lblDetailsQty_" + itemName).text($("#lblDetailsQty").text());
                $("#lblQtyLeft_" + itemName).text("");
                $("#" + dropdownId).empty();
                var text = "";
                for (var i = 1; i <= 10; i++) {
                    text += "<a class='dropdown-item' data-ajax='true' onclick='DetailsFlyoutQtyChange(\"" + i + '","' + itemName + "\")' >" + i.toString() + " </a >";
                }
                $("#" + dropdownId).append(text);
            }
        }
    }
}

function specialsOptionSelectionQuantityUpdateAfterCart(itemName, qtyLeft) {
    if ($("#hdnIsSpecialProduct").val().toLowerCase() == "true") {
        var dropdownId = "dropdown-menu_" + itemName;
        getAllselectedOptions();
        var itemDetails = $("#itemDetails").val();
        var pId = $("#hdnProdId").val();
        var params = {
            itemDetails: itemDetails, productId: pId
        };
        $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.Cart.UpdateSpecialsInventoryCount, data: params }, {
            complete: function (json) {
                var result = json.responseJSON;
                if (result !== null && result.length > 0) {
                    if (itemName != "AllOptions") {
                        for (var i = 0; i < result.length; i++) {
                            if (result[i].OptionName == itemName) {
                                if (parseInt(result[i].RemainingQtyLeft) > 0 && parseInt(result[i].RemainingQtyLeft) <= 10)
                                    specialsOptionSelectionQuantityUpdate(itemName, parseInt(result[i].RemainingQtyLeft));
                                else
                                    specialsOptionSelectionQuantityUpdate(itemName, '10');

                                if (itemQty > result[i].RemainingQtyLeft)
                                    $("#lblDetailsQty_" + itemName).text(result[i].RemainingQtyLeft);
                                else
                                    $("#lblDetailsQty_" + itemName).text(itemQty);
                            }
                        }
                    }
                    else {
                        if (parseInt(result[0].RemainingQtyLeft) > 0 && parseInt(result[0].RemainingQtyLeft) <= 10)
                            specialsOptionSelectionQuantityUpdate("AllOptions", result[0].RemainingQtyLeft);
                        else
                            specialsOptionSelectionQuantityUpdate("AllOptions", '10');
                    }
                }
            }
        }));
    }
}


function updateSpecialProductQtyDropDown(itemName) {
    if ($("#hdnIsSpecialProduct").val().toLowerCase() == "true") {
        getAllselectedOptions();
        var itemDetails = $("#itemDetails").val();
        var pId = $("#hdnProdId").val();
        var params = {
            itemDetails: itemDetails, productId: pId
        };
        $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.Cart.UpdateSpecialsInventoryCount, data: params }, {
            complete: function (json) {
                var result = json.responseJSON;
                if (result !== null && result.length > 0) {
                    if (parseInt(result[0].RemainingQtyLeft) > 0 && parseInt(result[0].RemainingQtyLeft) <= 10)
                        specialsOptionSelectionQuantityUpdate(itemName, result[0].RemainingQtyLeft);
                    else
                        specialsOptionSelectionQuantityUpdate(itemName, '10');
                }
            }
        }));
    }
}


function updateSpecialProductQtyFlyOutDropDown(itemName, itemQty) {
    if ($("#hdnIsSpecialProduct").val().toLowerCase() == "true") {
        getAllselectedOptions();
        var itemDetails = $("#itemDetails").val();
        var pId = $("#hdnProdId").val();
        var params = {
            itemDetails: itemDetails, productId: pId
        };
        $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.Cart.UpdateSpecialsInventoryCount, data: params }, {
            complete: function (json) {
                var result = json.responseJSON;
                if (result !== null && result.length > 0) {
                    for (var i = 0; i < result.length; i++) {
                        if (result[i].OptionName == itemName) {
                            if (parseInt(result[i].RemainingQtyLeft) > 0 && parseInt(result[i].RemainingQtyLeft) <= 10)
                                specialsOptionSelectionQuantityUpdate(itemName, parseInt(result[i].RemainingQtyLeft));
                            else
                                specialsOptionSelectionQuantityUpdate(itemName, '10');

                            if (itemQty > result[i].RemainingQtyLeft)
                                $("#lblDetailsQty_" + itemName).text(result[i].RemainingQtyLeft == "0" ? "1" : result[i].RemainingQtyLeft);
                            else
                                $("#lblDetailsQty_" + itemName).text(itemQty);
                        }
                    }
                }
            }
        }));
    }
}

//$(document).ready(function () {
//    $("#imgTooltip").hover(function () {
//        $('#Divtooltip').toggleClass('d-block');
//    });
//    const el = document.getElementById('imgTooltip');
//    const divTool = document.getElementById('Divtooltip');
//    el.addEventListener('focusin', function handleFocusIn() {
//        $('#Divtooltip').addClass('d-block');
//    });
//    divTool.addEventListener('focusout', function handleFocusOut() {
//        $('#Divtooltip').removeClass('d-block');
//    });
//    el.addEventListener('mouseover', function handleMouseOver() {
//        $('#Divtooltip').addClass('d-block');
//    });
//    el.addEventListener('mouseout', function handleMouseOut() {
//        $('#Divtooltip').removeClass('d-block');
//    });
//});
;
var flagIsShipping = false;
var errorFlag = false;
var cardType = "";
var isCardNumberValid = true;
var isCardLengthValid = true;
var stripeCard = "";
$(document).ready(function () {
    $('#chkSameBilling').click(function () {
        if ($('#chkSameBilling').prop("checked") == false) {
            changeBillingAddress();
            clearBillingFields();
        }
        else {
            setShippingAddressAsBilling();
        }
    });
    if ($('#hdnDeliveryType').val() != null) {
        if ($('#hdnDeliveryType').val().toString() == "true") {
            flagIsShipping = true;
        }
        $("#txtExpDate").inputmask("datetime", {
            inputFormat: "mm/yyyy",
            oncleared: function () {
                $("#txtExpDate").val("");

            },
            //outputFormat: "mm/yyyy",
            inputEventOnly: true
        });
        
        $(".tel-data").mask("(999) 999-9999");
        $('.tel-data').on('keyup', function () {
            var new_val = $(this).val().replace(/[^0-9\s()-]/g, '');
            if (new_val == '() -' || new_val == '(' || new_val == ')' || new_val == '-' || new_val == '() ')
                new_val = "";
            $(this).val(new_val);
        });

        var isStripeEnabled = "false";
        var isPayNowCheckout = "false";
        isStripeEnabled = $('#hdnIsStripeEnabled').val().toString();
        isBraintreeEnabled = $('#hdnIsBraintreeEnabled').val().toString();
        if (isStripeEnabled == "true" && isBraintreeEnabled == "true") { //when stripe and braintree is enabled , first priority is for stripe
            isBraintreeEnabled = "false";
        }
        isPayNowCheckout = $('#hdnIsStripeCheckout').val().toString();
        if (isStripeEnabled == "false" && isBraintreeEnabled == "false") {
            $(function () {
                $('#txtCardNo').validateCreditCard(function (result) {
                    cardType = result.card_type == null ? '' : result.card_type.name;
                    isCardNumberValid = result.valid;
                    isCardLengthValid = result.length_valid;
                    if ($('#hdnInvalidCards').val() != "") {
                        var invalidCards = $('#hdnInvalidCards').val().split(",");
                        for (var i = 0; i < invalidCards.length; i++) {
                            if (invalidCards[i].toString().toLowerCase() == cardType.toLowerCase()) {
                                $('#divInvalidCardtype').addClass("ChkRedTxt");
                                break;
                            }
                            else {
                                $('#divInvalidCardtype').removeClass("ChkRedTxt");
                            }
                        }
                    }
                });
            });
            $("#txtExpDate").mouseover(function () {
                $("#lblExpDate").addClass('input-not-empty');
            });
            $("#txtExpDate").mouseout(function () {
                if ($("#txtExpDate").val() == "")
                    $("#lblExpDate").removeClass('input-not-empty');
            });
        }
        else if (isStripeEnabled == "true") {
            //if (isPayNowCheckout == "false") {
            bindStripeCardElement();
            //}
        }
        else if (isBraintreeEnabled == "true") {
            bindBraintreeCardElement();
        }
        if (flagIsShipping) {
            $('.shipping-info').removeClass("d-none");
            $('.contact-info').addClass("d-none");
            $('#divBillingVin').addClass("d-none");
            if ($('#hdnIsEditCheckout').val().toString() == "false") {
                $('.btn-checkout-first').removeClass("d-none");
                $('.btn-checkout-second').addClass("d-none");
                $('.billing-info').addClass("d-none");
            }
            else {
                $('.btn-checkout-first').addClass("d-none");
                $('.btn-checkout-second').removeClass("d-none");
                if ($('#chkSameBilling').prop("checked") == true) {
                    setShippingAddressAsBilling();
                } else {
                    $('#divBillingAddressForm').removeClass("d-none");
                }
            }
        }
        else {
            $('.contact-info').removeClass("d-none");
            $('.shipping-info').addClass("d-none");
            $('#divBillingAddressForm').removeClass("d-none");
            $('.btn-checkout-second').removeClass("d-none");
            $('.btn-checkout-first').addClass("d-none");
        }

        clearBillingFields();
        if ($('#hdnIsEditCheckout').val().toString() == "true" && $('#hdnIsFitment').val().toString() == "true") {
            $('#divBillingVin').removeClass("d-none");
        }
    }
});
//start - validation functions for shipping/Billing form
function isAlphabetKey(evt, id) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
        return true;
    else {
        if (charCode == 32) {
            if ($("#" + id).val() != "") {
                return true;
            }
            else {
                return false;
            }
        }
        else
            return false;
    }
}

function isAlphaNumeric(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (((charCode >= 48 && charCode <= 57) || (charCode >= 96 && charCode <= 105)) || ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123)))
        return true;
    else
        return false;
}

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    var numbers = /^[0-9]+$/;
    if (evt.key.match(numbers) || evt.key.toLowerCase() == "backspace" || evt.key.toLowerCase() == "delete" || (charCode < 31 && (charCode > 48 || charCode < 57))) {
        return true;
    }
    //if (charCode > 31 && (charCode < 48 || charCode > 57))
    //    return false;
    else
        return false;

}
function isCardNumberKey(evt, id) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    var numbers = /^[0-9]+$/;
    if (evt.key.match(numbers) || evt.key.toLowerCase() == "backspace" || evt.key.toLowerCase() == "delete" || (charCode < 31 && (charCode > 48 || charCode < 57))) {
        if ($("#" + id).val().toString() == "") {
            $('#divInvalidCardtype').removeClass('ChkRedTxt')
        }
        if ($('#divInvalidCardtype').hasClass('ChkRedTxt')) {
            if ($("#" + id).val().toString().length >= 2) {
                if (evt.key.toLowerCase() == "backspace" || evt.key.toLowerCase() == "delete") {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
        return true;
    }
    //if (charCode > 31 && (charCode < 48 || charCode > 57))
    //    return false;
    else
        return false;

}

function validateCardOnPaste(txtId) {
    var data = $('#' + txtId).val();
    data = data.replace(/\s/g, '');
    //cardType = $('#hdnCardType').val();
    if (isCardNumberValid.toString() == "true" && isCardLengthValid.toString() == "true") {
        $('#' + txtId).val(data);
    }
    else {
        indicateInvalidData(txtId);
    }
}
function validatePhoneNumber(phoneNumber) {
    var pattern = /^(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$/;
    if (pattern.test(phoneNumber)) {
        return true;
    }
    else {
        return false;
    }
}

function isAllAlphabets(inputtxt) {
    var letters = /^[A-Za-z\s]+$/;
    if (inputtxt.match(letters)) {
        return true;
    }
    else {
        return false;
    }
}

function isAllAlphanumeric(inputtxt) {
    var letterNumber = /^[0-9a-zA-Z]+$/;
    if (inputtxt.match(letterNumber)) {
        return true;
    }
    else {
        return false;
    }
}

function validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (re.test(email)) {
        return true;
    }
    else {
        return false;
    }

}

function validateCVV(seccode) {
    var regex = /^[0-9]{3,4}$/;
    if (seccode == null) {
        return false;
    }
    else if (regex.test(seccode) == true) {
        return true;
    }
}

function formatPhoneNumber_bkp(control) {
    var formatPhoneNumber = "";
    var phoneNumber = $('#' + control.id).val();
    var strDigits = stripCharsNotInBag(phoneNumber, "1234567890");
    if (strDigits.length == 9) {
        formatPhoneNumber = strDigits.substring(0, 3) + "-" + strDigits.substring(3, 6) + "-" + strDigits.substring(6, 9);
        $('#' + control.id).val(formatPhoneNumber);
        $('#' + control.id).removeClass("InvalidSearch");
        $('#' + control.id).addClass("RightInput");
    }
    else {
        $('#' + control.id).removeClass("RightInput");
        $('#' + control.id).addClass("InvalidSearch");
    }
}

function formatPhoneNumber(control, evt) {
    var formatPhoneNumber = "";
    var phoneNumber = $('#' + control.id).val();
    if (phoneNumber.length == 12) {
        if (evt.key.toLowerCase() == "backspace" || evt.key.toLowerCase() == "delete") {
            return true;
        }
        else {
            return false;
        }
    }
    else {
        var numbers = /^[0-9]+$/;
        if (evt.key.match(numbers) || evt.key.toLowerCase() == "backspace" || evt.key.toLowerCase() == "delete") {
            var strDigits = stripCharsNotInBag(phoneNumber, "1234567890");
            if (strDigits.length == 9) {
                formatPhoneNumber = strDigits.substring(0, 3) + "-" + strDigits.substring(3, 6) + "-" + strDigits.substring(6, 9);
                $('#' + control.id).val(formatPhoneNumber);
                $('#' + control.id).removeClass("InvalidSearch");
                $('#' + control.id).addClass("RightInput");
            }
            else {
                $('#' + control.id).removeClass("RightInput");
                $('#' + control.id).addClass("InvalidSearch");
            }
        }
        else {
            return false;
        }
    }
}

function stripCharsNotInBag(s, bag) {
    var i;
    var returnString = "";
    for (i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }
    return returnString;
}

//end - validation functions for shipping/Billing form

function changeBillingAddress() {
    //if ($('#divBillingAddressForm').hasClass("d-none")) {
    //    $('#divBillingAddressForm').removeClass("d-none");
    //    $('#divBillingAddress').addClass("d-none");
    //}
    //else {
        var controls = "FirstName,LastName,CName,StrtAddress,AprtAddress,City,ZipCode,Phone,Email";
        var controlArray = controls.split(",");
        for (var i = 0; i < controlArray.length; i++) {
            $('#txtBill' + controlArray[i]).val("");
            $('#txtBill' + controlArray[i]).focus();
        }
        var ddlControls = "State";
        var ddlcontrolArray = ddlControls.split(",");
        for (var i = 0; i < ddlcontrolArray.length; i++) {
            $('#ddlBill' + ddlcontrolArray[i]).val("");
            $('#ddlBill' + ddlcontrolArray[i]).focus();
        }
    //}
    $('#divBillingAddressForm').removeClass("d-none");
    $('#divBillingAddress').addClass("d-none");
    $('#chkSameBilling').prop("checked", false);
}

function setShippingAddressAsBilling() {
    //setting address same as billing address
    //var controls = "FirstName,LastName,CName,StrtAddress,AprtAddress,City,ZipCode,Phone,Email";
    //var controlArray = controls.split(",");
    //for (var i = 0; i < controlArray.length; i++) {
    //    var value = $('#txt' + controlArray[i]).val();
    //    $('#txtBill' + controlArray[i]).val(value);
    //    $('#txtBill' + controlArray[i]).focus();
    //}
    //var ddlControls = "State";
    //var ddlcontrolArray = ddlControls.split(",");
    //for (var i = 0; i < ddlcontrolArray.length; i++) {
    //    var value = $('#ddl' + ddlcontrolArray[i]).val();
    //    $('#ddlBill' + ddlcontrolArray[i]).val(value);
    //    $('#ddlBill' + ddlcontrolArray[i]).focus();
    //}

    //clearing the fields
     var controls = "FirstName,LastName,CName,StrtAddress,AprtAddress,City,ZipCode,Phone,Email";
        var controlArray = controls.split(",");
        for (var i = 0; i < controlArray.length; i++) {
            $('#txtBill' + controlArray[i]).val("");
            $('#txtBill' + controlArray[i]).focus();
        }
        var ddlControls = "State";
        var ddlcontrolArray = ddlControls.split(",");
        for (var i = 0; i < ddlcontrolArray.length; i++) {
            $('#ddlBill' + ddlcontrolArray[i]).val("");
            $('#ddlBill' + ddlcontrolArray[i]).focus();
    }
    loadPaymentSection();
    $('#divBillingAddressForm').addClass("d-none");
    $('#divBillingAddress').removeClass("d-none");

}

function validateBeforeSubmit(sectionDivId) {
    errorFlag = false;// gloabal variable
    var flagError = false;
    var txtControls = "";
    var ddlControls = "";
    $('#' + sectionDivId + ' .required').each(function () {
        var type = this.type || this.tagName.toLowerCase();
        if (type.toLowerCase() == "text" || type.toLowerCase() == "tel")
            txtControls = txtControls + this.id + ",";
        if (type.toLowerCase().indexOf('select') >= 0)
            ddlControls = ddlControls + this.id + ",";
    });
    txtControls = txtControls.replace(/,\s*$/, "");
    ddlControls = ddlControls.replace(/,\s*$/, "");
    var controlArray = txtControls.split(",");
    var ddlcontrolArray = ddlControls.split(",");
    for (var i = 0; i < controlArray.length; i++) {
        if (controlArray[i] != "")
            validateRequiredFields(controlArray[i], "txt");
    }
    for (var i = 0; i < ddlcontrolArray.length; i++) {
        if (ddlcontrolArray[i] != "")
            validateRequiredFields(ddlcontrolArray[i], "ddl");
    }
    $('#' + sectionDivId + ' .text-data').each(function () {
        if ($(this).hasClass('required')) {
            if (!isAllAlphabets($(this).val())) {
                $(this).removeClass("RightInput");
                $(this).addClass("InvalidSearch");
                flagError = true;
            }
            else {
                $(this).removeClass("InvalidSearch");
                $(this).addClass("RightInput");
            }
        }
    });
    $('#' + sectionDivId + ' .tel-data').each(function () {
        if (!validatePhoneNumber($(this).val())) {
            $(this).removeClass("RightInput");
            $(this).addClass("InvalidSearch");
            flagError = true;
        }
        else {
            $(this).removeClass("InvalidSearch");
            $(this).addClass("RightInput");
        }
    });
    $('#' + sectionDivId + ' .email-data').each(function () {
        if (!validateEmail($(this).val())) {
            $(this).val('');
            $(this).removeClass("RightInput");
            $(this).addClass("InvalidSearch");
            flagError = true;
        }
        else {
            $(this).removeClass("InvalidSearch");
            $(this).addClass("RightInput");
        }
    });
    if (errorFlag == false && flagError == false)
        return false;//no error
    else
        return true;
}

function validateShippingInfo() {
    var flagError = false;
    // var chkboxFlagErr = true;
    flagError = validateBeforeSubmit('divBillingSection');
    var chkboxFlagErr = validteCheckoutChekbox('defaultUnchecked11');
    if (chkboxFlagErr == true) {
        if (flagError == false) {
            return false;
        }
        flagError = true;
    }
    if (!flagError) {
        loadPaymentSection();
        focusonCard('paymentHeading');
    }

    else
        $("html, body").animate({ scrollTop: 0 }, "slow");

}

var isProrder = $("#hdnIsPreOrder").val();
function validteCheckoutChekbox(id) {
    //var id = "#defaultUnchecked1";
    const $label = $('label[for="' + id + '"]');//$('#' + id).siblings('label');
    if ($('#' + id).prop("checked") != true) {
        $label.addClass('ChkPrivary');
        $label.siblings("input").removeAttr("checked");
        $label.closest("div").addClass("terms-validation");
        //$("#" + id).closest("div").addClass("terms-validation");
        //(id).focus();
        return true;//error
    }
    else {
        $label.siblings("input").attr("checked", "true");
        $label.removeClass('ChkPrivary');
        $label.parent("div").removeClass("terms-validation");
        return false; //no error
    }
}
function validateAllCheckBoxes(sectionDivId) {
    var chkErrorFlag = false;

    if (isProrder) {// preorder - check all ccpa checkboxs are checked
        // alert("preorder");
        $('#' + sectionDivId + ' .custom-control-input').each(function () {
            var checkId = this.id;
            if (validteCheckoutChekbox(checkId)) {
                chkErrorFlag = true;
            }
        });
    }
    else {// normal case - i instruct checkbox only
        // alert("normal");
        if (validteCheckoutChekbox("defaultUnchecked11")) {
            chkErrorFlag = true;
        }
    }
    return chkErrorFlag;
}


function validatePaymentOption() {
    var shippingError = false;
    var billingAddressError = false;
    var contactError = false;
    var cardError = false;
    var chkboxFlagErr = validateAllCheckBoxes('divTermsAndConditions');
    //if (chkboxFlagErr == true) {
    //    document.getElementById("divTermsAndConditions").scrollIntoView({ behavior: "smooth", block: "center", inline: "nearest" });
    //    //var targetOffset = $('#defaultUnchecked1').offset().top;//$('html, body').animate({ scrollTop: targetOffset - 170 }, 10); //alert(targetOffset);
    //    return false;
    //}
    if (flagIsShipping) {
        shippingError = validateBeforeSubmit('divBillingSection');//validate shipping section again
    }

    if (!$("#divBillingAddressForm").hasClass("d-none")) {
        billingAddressError = validateBeforeSubmit('divBillingAddressForm');
    }
    if (!$("#divContactInfo").hasClass("d-none")) {
        contactError = validateBeforeSubmit('divContactInfo');
    }

    if ($('#defaultChecked2').is(':checked')) {
        if ($('#hdnIsStripeEnabled').val().toString() == "false" && $('#hdnIsBraintreeEnabled').val().toString() == "false") {
            cardError = validateCreditCard("txt");
        }
        else if ($('#hdnIsStripeEnabled').val().toString() == "true") {
            cardError = validateStripeCard();
        }
        else {
            cardError = validateBrainTreeCard();
        }
    }
    if (!shippingError && !billingAddressError && !contactError && !cardError && !chkboxFlagErr) {
        $('html').css('overflow', 'hidden');
        var addressDetails = {};
        var billingAddressDetails = {};
        var paymentDetails = {};
        var vinDetails = [];
        var generalDetails = {};
        //BE-12497
        var btnSaveAndContinue = document.getElementById("btnPaymentSaveAndContinue");
        if (!(btnSaveAndContinue.hasAttribute('data-target'))) {
            btnSaveAndContinue.setAttribute('data-target', '#ValidateAddressModal');
        }
        
        if ($('#hdnIsFitment').val().toString() == "true") {
            if (!$("#divBillingVin").hasClass("d-none")) {
                $('#divBillingVin input').each(function () {
                    var id = this.id.replace("txtVinDigit_", "");
                    var modelname = $(this).data('modelname');
                    var value = $(this).val();
                    vinDetails.push({ ModelId: id, VIN: value, ModelNameForVin: modelname });
                });
                vinDetails = JSON.stringify(vinDetails);
                $('#hdnVinList').val(vinDetails);
            }
        }
        if (!$("#divBillingSection").hasClass("d-none")) {
            $('#divBillingSection input').each(function () {
                var name = this.id.replace("txt", "");
                var value = $(this).val();
                addressDetails[name] = value;
            });
            $('#divBillingSection select').each(function () {
                var name = this.id.replace("ddl", "");
                var value = $(this).val();
                addressDetails[name] = value;

            });
        }
        if (!$("#divContactInfo").hasClass("d-none")) {
            $('#divContactInfo input').each(function () {
                var name = this.id.replace("txtContact", "");
                var value = $(this).val();
                addressDetails[name] = value;
            });
        }
        addressDetails = JSON.stringify(addressDetails);
        $('#hdnAddressList').val(addressDetails);

        if (!$("#divAddressTerms").hasClass("d-none") && $('#chkSameBilling').prop("checked") == true) {
            $('#hdnBillingArrayList').val(addressDetails);
        }
        else {
            if (!$("#divBillingAddressForm").hasClass("d-none")) {
                $('#divBillingAddressForm input').each(function () {
                    var name = this.id.replace("txtBill", "");
                    var value = $(this).val();
                    billingAddressDetails[name] = value;
                });

                $('#divBillingAddressForm select').each(function () {
                    var name = this.id.replace("ddlBill", "");
                    var value = $(this).val();
                    billingAddressDetails[name] = value;

                });
            }
            billingAddressDetails = JSON.stringify(billingAddressDetails);
            $('#hdnBillingArrayList').val(billingAddressDetails);
        }

        if ($('#hdnIsStripeEnabled').val().toString() == "false" && $('#hdnIsBraintreeEnabled').val().toString() == "false")
        {
            $('.card-payment').each(function () {
                var name = this.id.replace("txt", "");
                var value = $(this).val();
                paymentDetails[name] = value;

            });
            if (cardType.toLowerCase() == "visa")
                cardType = "Visa";
            if (cardType.toLowerCase() == "mastercard")
                cardType = "MasterCard";
            if (cardType.toLowerCase() == "discover")
                cardType = "Discover";
            if (cardType.toLowerCase() == "amex")
                cardType = "American Express";
            paymentDetails["CardType"] = cardType;
            paymentDetails["PaymentType"] = "creditcard";
            paymentDetails = JSON.stringify(paymentDetails);
            $('#hdnPaymentList').val(paymentDetails);
            var isAcceptTerms = false;
            if ($('#defaultUnchecked1').prop("checked") == true) {
                isAcceptTerms = true;
            }
            var isBillingSameAsShipping = false;
            if ($('#chkSameBilling').prop("checked") == true) {
                isBillingSameAsShipping = true;
            }
            generalDetails["IsAcceptedTerms"] = isAcceptTerms;
            generalDetails["IsBillingSameAsShipping"] = isBillingSameAsShipping;
            generalDetails = JSON.stringify(generalDetails);
            $('#hdnGeneralDetailList').val(generalDetails);
            
            if (!flagIsShipping)
                $('#btnPaymentSaveAndContinue').removeAttr('data-target');
            //else {
            //    var btnSaveAndContinue = document.getElementById("btnPaymentSaveAndContinue");
            //    if (!(btnSaveAndContinue.hasAttribute('data-target'))) {
            //        btnSaveAndContinue.setAttribute('data-target','#ValidateAddressModal');
            //    }
            //}
            $("#frmValidateAddress").submit();
            return true;
        }
        else if ($('#hdnIsStripeEnabled').val().toString() == "true") {
            $('#stripeLoaderId').addClass("d-block");
            stripeCheckout.createToken(stripeCard).then(function (result) {
                if (result.error) {
                    // Inform the user if there was an error.
                    var errorElement = document.getElementById('card-errors');
                    errorElement.textContent = result.error.message;
                    return false;
                }
                else {
                    var token = result.token.id;
                    //Send the token to your server.
                    //stripeTokenHandler(result.token);
                    
                    paymentDetails["CardNo"] = result.token.card.last4;
                    paymentDetails["ExpDate"] = result.token.card.exp_month + "/" + result.token.card.exp_year;
                    cardType = result.token.card.brand;
                    paymentDetails["CardType"] = cardType;
                    paymentDetails["PaymentType"] = "stripe";
                    paymentDetails["CardToken"] = token;
                }
                paymentDetails = JSON.stringify(paymentDetails);
                $('#hdnPaymentList').val(paymentDetails);
                var isAcceptTerms = false;
                if ($('#defaultUnchecked1').prop("checked") == true) {
                    isAcceptTerms = true;
                }
                var isBillingSameAsShipping = false;
                if ($('#chkSameBilling').prop("checked") == true) {
                    isBillingSameAsShipping = true;
                }
                generalDetails["IsAcceptedTerms"] = isAcceptTerms;
                generalDetails["IsBillingSameAsShipping"] = isBillingSameAsShipping;
                generalDetails = JSON.stringify(generalDetails);
                $('#hdnGeneralDetailList').val(generalDetails);
                if (!flagIsShipping)
                    $('#btnPaymentSaveAndContinue').removeAttr('data-target');

                $("#frmValidateAddress").submit();
                return true;
            });
        }
        else if ($('#hdnIsBraintreeEnabled').val().toString() == "true") {
            $('#stripeLoaderId').addClass("d-block");

            if (!nonceBraintree) {
                return false;
            }

            else {
                paymentDetails["PaymentType"] = "braintree";
                //paymentDetails["CardToken"] = nonce.value;
                paymentDetails["CardToken"] = braintreeNonce.value;
                paymentDetails = JSON.stringify(paymentDetails);
                $('#hdnPaymentList').val(paymentDetails);
                var isAcceptTerms = false;
                if ($('#defaultUnchecked1').prop("checked") == true) {
                    isAcceptTerms = true;
                }
                var isBillingSameAsShipping = false;
                if ($('#chkSameBilling').prop("checked") == true) {
                    isBillingSameAsShipping = true;
                }
                generalDetails["IsAcceptedTerms"] = isAcceptTerms;
                generalDetails["IsBillingSameAsShipping"] = isBillingSameAsShipping;
                generalDetails = JSON.stringify(generalDetails);
                $('#hdnGeneralDetailList').val(generalDetails);
                if (!flagIsShipping) {
                    $('#btnPaymentSaveAndContinue').removeAttr('data-target');
                }
               
                $("#frmValidateAddress").submit();
                return true;
            }
        }
    }
    else {
        if (shippingError)
            focusonCard("headShippingInfo");
        else if (cardError)
            focusonCard("paymentHeading");
        $('#btnPaymentSaveAndContinue').removeAttr('data-target');
        return false;
    }
}
function editShippingAddress() {
    $("html, body").animate({ scrollTop: 0 }, "slow");
}
var stripeCheckout = "";
function loadPaymentSection() {
    var billingName = $('#txtFirstName').val() + " " + $('#txtLastName').val();
    var billingStreet = $('#txtStrtAddress').val();
    var billingCityStateZip = $('#txtCity').val() + ", " + $('#ddlState').val() + " " + $('#txtZipCode').val();
    $('#lblBillName').text(billingName);
    $('#lblStreet').text(billingStreet);
    $('#lblCityStateZip').text(billingCityStateZip);
    $('.btn-checkout-first').addClass("d-none");
    $('.btn-checkout-second').removeClass("d-none");
    $('.billing-info').removeClass("d-none");
    $('#divBillingVin').removeClass("d-none");
    if ($('#hdnIsStripeEnabled').val().toString() == "true") {
        bindStripeCardElement();
    }
    //Avoiding Issue of loading required fields as invalid on first page load: Only on Ipad and Mobile versions.
    clearBillingFields();
}
function bindStripeCardElement() {
    // Create a Stripe client.
    var pubKey = document.getElementById('hdnPubKey').value;
    var accountId = document.getElementById('hdnAccountId').value;
    stripeCheckout = Stripe(pubKey, {
        stripeAccount: accountId
    });

    // Create an instance of Elements.
    var elements = stripeCheckout.elements();

    // Custom styling can be passed to options when creating an Element.
    // (Note that this demo uses a wider set of styles than the guide below.)
    var style = {
        base: {
            color: '#32325d',
            fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
            fontSmoothing: 'antialiased',
            fontSize: '16px',
            '::placeholder': {
                color: '#aab7c4'
            }
        },
        invalid: {
            color: '#fa755a',
            iconColor: '#fa755a'
        }
    };

    // Create an instance of the card Element.
    stripeCard = elements.create('card', { style: style });

    // Add an instance of the card Element into the `card-element` <div>.
    stripeCard.mount('#card-element');

    // Handle real-time validation errors from the card Element.
    stripeCard.on('change', function (event) {
        var displayError = document.getElementById('card-errors');
        if (event.error) {
            displayError.textContent = event.error.message;
        } else {
            displayError.textContent = '';
        }
        if ($('#card-element').hasClass("InvalidSearch")) {
            $('#card-element').removeClass("InvalidSearch");
        }
    });
}
function stripeTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var form = document.getElementById('payment-form');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);

    // Submit the form
    form.submit();
}

//start - CreditCard Validations
function validateBrainTreeCard() {
    var cardNumber = false;
    var cvv = false;
    var expiryDate = false;
    if ($('#card-number').hasClass('braintree-hosted-fields-valid')) {
        cardNumber = true;
        if ($('#card-number').hasClass('InvalidSearch')) {
            $('#card-number').removeClass("InvalidSearch");
        }
    }
    else {
        $('#card-number').addClass("InvalidSearch");
    }
    if ($('#cvv').hasClass('braintree-hosted-fields-valid')) {
        cvv = true;
        if ($('#cvv').hasClass('InvalidSearch')) {
            $('#cvv').removeClass("InvalidSearch");
        }
    }
    else {
        $('#cvv').addClass("InvalidSearch");
    }
    if ($('#expiration-date').hasClass('braintree-hosted-fields-valid')) {
        expiryDate = true;
        if ($('#expiration-date').hasClass('InvalidSearch')) {
            $('#expiration-date').removeClass("InvalidSearch");
        }
    }
    else {
        $('#expiration-date').addClass("InvalidSearch");
    }
    if (cardNumber && cvv && expiryDate) {
        return false;
    }
    else
        return true;
}

function validateStripeCard() {
    if ($('#card-element').hasClass('StripeElement--invalid') || $('#card-element').hasClass('StripeElement--empty') || !($('#card-element').hasClass('StripeElement--complete'))) {
        $('#card-element').addClass("InvalidSearch");
        return true;
    }
    else {
        return false;
    }
}
function validateCreditCard(type) {
    var cardNo = "";
    var cvv = $('#' + type + 'SecCode').val();
    var isValidExpDate = true;
    var isValidCVC = true;
    cardNo = $('#' + type + 'CardNo').val();
    var isDealerSupported = true;
    var creditCardType = cardType;
    if ($('#' + type + 'SecCode').val() == "") {
        isValidCVC = false;
    }
    else if ($('#' + type + 'SecCode').val() != "") {
        isValidCVC = validateCVV(cvv);
    }
    if (type.indexOf("txtPre") > -1) {
        isValidExpDate = true;//inthe case of iXpreorder, checking separately added
    }
    else {
        isValidExpDate = validateExpiryDate();
    }
    if ($("#divInvalidCardtype").hasClass("d-block ChkRedTxt")) {
        isDealerSupported = false;
    }
    if (isCardNumberValid && isCardLengthValid && isValidExpDate && isValidCVC && isDealerSupported) {
        return false;
    }
    else {
        if (!isCardNumberValid || !isCardLengthValid || !isDealerSupported) {
            $('#' + type + 'CardNo').removeClass("RightInput");
            $('#' + type + 'CardNo').addClass("InvalidSearch");
        }
        if (!isValidExpDate) {
            $('#' + type + 'ExpDate').removeClass("RightInput");
            $('#' + type + 'ExpDate').addClass("InvalidSearch");
        }
        if (!isValidCVC) {
            $('#' + type + 'SecCode').removeClass("RightInput");
            $('#' + type + 'SecCode').addClass("InvalidSearch");
        }
        return true;
    }

}

function validateExpiryDate() {
    isValidMonth = true;
    isValidYear = true;
    var expDate = $('#txtExpDate').val();
    if ($('#txtExpDate').val() == "") {
        return false;
    }
    else {
        var expDateArray = expDate.split("/");
        var month = (expDateArray != "" && expDateArray[0] != "") ? expDateArray[0] : "";
        var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
        if (!numericReg.test(month)) {
            isValidMonth = false;
        }
        var year = (expDateArray != "" && expDateArray[1] != "") ? expDateArray[1] : "";
        if (!numericReg.test(year)) {
            isValidYear = false;
        }
        if (isValidMonth && isValidYear) {
            var currentDate = new Date();
            var ptmonth = currentDate.getMonth();
            var val = 1;
            var presentmonth = ptmonth + val;
            var presentyear = currentDate.getFullYear();
            if (year == presentyear) {
                if (month < presentmonth) {
                    return false;
                }
                else {
                    return true;
                }
            }
            else if (year < presentyear) {
                return false;
            }
            else {
                return true;
            }
        }
        else {
            return false;
        }
    }
}
//end - CreditCard Validations

function updateCartProductQuantity(productQuantity, productCount, newQuantity) {
    $(".CartOverlay").hide();
    if ($("#hdnCartUpdated").val().toLowerCase() != "true") {
        productCount = productCount + newQuantity - productQuantity;
        $("#spnCartCount").text(productCount);
        $("#hdnCartCount").val(productCount);
        setTimeout(function () {
            if ($("#clickDisableOverlay").hasClass("clickDisable")) {
                $("#clickDisableOverlay").removeClass("clickDisable");
            }
        }, 200);
    }
    var promo = $('#promoCode').val(); 
    if (promo != null) {
        if (validatePromoCode()) {
            
            applyPromoCode(promo);
        }
    }
}
function validatePromoCode() {
    if ($("#promoCode").val() != "") {
        //debugger;
        $('#aPromoClick').text($("#promoCode").val());
        return true;
    }
    else {
        return false;
    }
}
function removePromoCode(btnId) {
    $("#" + btnId).click();
}
function validatePaypalInfo() {

    //var flagError = false;
    //flagError = validateBeforeSubmit('divContactSection');
    //if (!flagError)
    //    loadPaymentSection();
    //else
    //    $("html, body").animate({ scrollTop: 0 }, "slow");

    // var chkboxFlagErr = true;
    var vinDetails = [];
    if ($('#hdnIsFitment').val().toString() == "true") {
        if (!$("#divPaypalVin").hasClass("d-none")) {
            $('#divPaypalVin input').each(function () {
                var id = this.id.replace("txtVinDigit_", "");
                var modelname = $(this).data('modelname');
                var value = $(this).val();
                vinDetails.push({ ModelId: id, VIN: value, ModelNameForVin: modelname });
            });
            vinDetails = JSON.stringify(vinDetails);
            $('#hdnPaypalVinList').val(vinDetails);
        }
    }
    var chkboxFlagErr = validateAllCheckBoxes('divTermsAndConditions');
    var contactFlag = validateBeforeSubmit('divPaypalContactInfo')

    if (contactFlag == true || chkboxFlagErr == true) {
        $("html, body").animate({ scrollTop: 0 }, "slow");
        return false;
    }
    else {
        return true;
    }

}

function validateAmazonContactInfo() {
    var vinDetails = [];
    if ($('#hdnIsFitment').val().toString() == "true") {
        if (!$("#divBillingVin").hasClass("d-none")) {
            $('#divBillingVin input').each(function () {
                var id = this.id.replace("txtVinDigit_", "");
                var modelname = $(this).data('modelname');
                var value = $(this).val();
                vinDetails.push({ ModelId: id, VIN: value, ModelNameForVin: modelname });
            });
            vinDetails = JSON.stringify(vinDetails);
            $('#hdnVinList').val(vinDetails);
        }
    }
    var contactError = validateBeforeSubmit('divAmazonContactInfo');
    var chkboxFlagErr = validateAllCheckBoxes('divTermsAndConditions');
    if (!contactError && !chkboxFlagErr)
        return true;
    else {
        $("html, body").animate({ scrollTop: 0 }, "slow");
        return false;
    }
}

function clearBillingFields() {
    //Avoiding Issue of Overlapping label on Text box content when browser back to prev page is clicked from Review page.
    $('.BillingSection input[type=text],input[type=tel],.card-payment').each(function () {
        if ($(this).val() != "") {
        //var controls = "FirstName,LastName,CName,StrtAddress,AprtAddress,City,ZipCode,Phone,Email";
        //var controlArray = controls.split(",");
        //for (var i = 0; i < controlArray.length; i++) {
        //    $('#txtBill' + controlArray[i]).val("");
        //    $('#txtBill' + controlArray[i]).focus();
        //}
        //var ddlControls = "State";
        //var ddlcontrolArray = ddlControls.split(",");
        //for (var i = 0; i < ddlcontrolArray.length; i++) {
        //    $('#ddlBill' + ddlcontrolArray[i]).val("");
        //    $('#ddlBill' + ddlcontrolArray[i]).focus();
        //}
            $('label[for="' + this.id + '"]').addClass('input-not-empty');
        }
    });

    //Avoiding Issue of loading required fields as invalid on first page load: Only on Ipad and Mobile versions.
    $('.BillingSection .required,.card-payment').each(function () {
        $(this).removeClass("InvalidSearch");
        $(this).parent().find('span').addClass("d-none");
    });
}
function UpdateDeliveryType(ProductItemId, DeliveryType, newDeliveryType, Quantity) {
    $(".CartOverlay").show();
    var args = { ProductItemId: ProductItemId, DeliveryType: DeliveryType, newDeliveryType: newDeliveryType, Quantity: Quantity };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.Cart.UpdateDeliveryType, data: args }, {
        complete: function (json) {
            $(".CartOverlay").hide();
            if (json.responseJSON !== null) {
                applyPromoCode();
                var promo = $('#promoCode').val(); 
                if (promo != null) {
                    if (validatePromoCode()) {
                        
                        applyPromoCode(promo);
                    }
                }
                //$("#cartSummaryContainer").html(json.responseJSON);
                $("#cartSummaryDeliveryType").html(json.responseJSON);
            }
        }
    }));
}

function applyPromoCode(promoCode) {
    $(".CartOverlay").show();
    var args = { promoCode: promoCode };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.Cart.ApplyPromoCode, data: args }, {
        complete: function (json) {
            $(".CartOverlay").hide();
            if (json.responseJSON !== null) {
                $("#PriceSummary").html(json.responseJSON);
            }
        }
    }));
}

//moving ajax calls from _Vehicle selector for preorder end page #BE-5753
function selectYourYear(isMenu, isShowMoreYear) {
    var args = { isMenu: isMenu, isShowMoreYear: isShowMoreYear };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.VehicleSelector.GetYearList, data: args }, {
        complete: function (json) {
            //if (json.responseJSON != null && json.responseJSON[1] === "true") {
            if (isMenu == 1) {
                clearRightMenu();
                $("#select-bmw-pop-up-rightId").html(json.responseJSON);
            }
            else if (isMenu == 0) {
                $("#select-bmw-pop-up-Id").html(json.responseJSON);

            }
            //}
        }
    }));
    //return false;
}

function getYourBMWHome(isMenu, modelId, isModelPage) {
    var args = { isMenu: isMenu, modelId: modelId, isModelPage: isModelPage };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.VehicleSelector.GetYourBMW, data: args }, {
        complete: function (json) {
            //if (json.responseJSON != null && json.responseJSON[1] === "true") {
            if (isMenu == 1) {
                $("#select-bmw-pop-up-rightId").html(json.responseJSON);
            }
            else if (isMenu == 0) {
                $("#select-bmw-pop-up-Id").html(json.responseJSON);
            }
            //}
        }
    }));
}

function selectYourSeries(IsRightMenu, YearList, productName, productLink, categoryId, isReloadPage, isAddtoCart, isMoreInformationNeed, targetId) {
    isReloadPage = Boolean(isReloadPage);
    isAddtoCart = Boolean(isAddtoCart);
    isMoreInformationNeed = Boolean(isAddtoCart);
    var args = { isMenu: IsRightMenu, selectedYear: YearList, productName: productName, productLink: productLink, categoryId: categoryId, isReloadPage: isReloadPage, isAddtoCart: isAddtoCart, isMoreInformationNeed: isMoreInformationNeed };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.VehicleSelector.GetSeriesList, data: args }, {
        complete: function (json) {
            //clearRightMenu(); //Model.IsRightMenu 
            // if (json.responseJSON != null && json.responseJSON[1] === "true") {
            $("#" + targetId).html(json.responseJSON);
            //}
        }
    }));

}

function getYearListForProductSelection(isMenu, isShowMoreYear, productName, productLink, categoryId, isAddtoCart, targetId) {
    isAddtoCart = Boolean(isAddtoCart);
    var args = { isMenu: isMenu, isShowMoreYear: isShowMoreYear, productName: productName, productLink: productLink, categoryId: categoryId, isAddtoCart: isAddtoCart };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.VehicleSelector.GetYearListForProductSelection, data: args }, {
        complete: function (json) {
            if (isShowMoreYear == true) {
                ShowMoreYear();
            }
            $("#" + targetId).html(json.responseJSON);
        }
    }));
}

function selectYourYearShowMore(isMenu, isShowMoreYear, IsReloadPage, IsAddtocart, isMoreInformationNeed, targetId) {
    IsAddtocart = Boolean(IsAddtocart);
    isMoreInformationNeed = Boolean(isMoreInformationNeed);
    var args = { isMenu: isMenu, isShowMoreYear: isShowMoreYear, isAddtocart: IsAddtocart, isReloadPage: IsReloadPage, isMoreInformationNeed: isMoreInformationNeed };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.VehicleSelector.GetYearList, data: args }, {
        complete: function (json) {
            if (isShowMoreYear == true) {
                ShowMoreYear();
            }
            $("#" + targetId).html(json.responseJSON);
        }
    }));
}

function getModelList(isMenu, selectedYear, selectedSeries, productName, productLink, categoryId, isReloadPage, isAddtoCart, isMoreInformationNeed, targetId) {

    isReloadPage = Boolean(isReloadPage);
    isAddtoCart = Boolean(isAddtoCart);
    isMoreInformationNeed = Boolean(isMoreInformationNeed);
    var args = { isMenu: isMenu, selectedYear: selectedYear, selectedSeries: selectedSeries, productName: productName, productLink: productLink, categoryId: categoryId, isReloadPage: isReloadPage, isAddtocart: isAddtoCart, isMoreInformationNeed: isMoreInformationNeed };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.VehicleSelector.GetModelList, data: args }, {
        complete: function (json) {
            //ShowMoreYear();
            $("#" + targetId).html(json.responseJSON);
        }
    }));
}

function getYourBMW(isMenu, modelId, productName, productLink, categoryId, isShowYourBMW, isMoreInformationNeed, targetId) {
    isMoreInformationNeed = Boolean(isMoreInformationNeed);
    var args = { isMenu: isMenu, modelId: modelId, productName: productName, productLink: productLink, categoryId: categoryId, isShowYourBMW: isShowYourBMW, isMoreInformationNeed: isMoreInformationNeed };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.VehicleSelector.GetYourBMW, data: args }, {
        complete: function (json) {
            changeModelId(isMenu, modelId);
            if (json.responseJSON.toString().toLowerCase() == "location.reload(true)") {
                location.reload(true);
            }
            else {
                $("#" + targetId).html(json.responseJSON);
            }

        }
    }));
}

function clearModelSelection(isMenu, isShowMoreYear, targetId) {
    var args = { isMenu: isMenu, isShowMoreYear: isShowMoreYear };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.VehicleSelector.ClearModelSelection, data: args }, {
        complete: function (json) {
            if (json.responseJSON.toString().toLowerCase() == "location.reload(true)") {
                location.reload(true);
            }
            //$("#" + targetId).html(json.responseJSON);
        }
    }));
}

function checkProductFitment(isMenu, productName, categoryId) {
    var args = { isMenu: isMenu, productName: productName, categoryId: categoryId };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.VehicleSelector.CheckProductFitment, data: args }, {
        complete: function (json) {
            closeProductModelSelection();
        }
    }));
}


//var submitButton = document.querySelector('#submit-button');
//var braintreeToken = "";
//var nonce = document.querySelector("#braintreeNonce");
var nonceBraintree = false;

function bindBraintreeCardElement() {
    braintree.client.create(
        { 
         authorization: hdnBrainTreeClientToken.value
        },
        function (clientError, clientInstance) {
            if (clientError) {
                console.error(clientError);
                return;
            }

            braintree.hostedFields.create({
                client: clientInstance,
                styles: {
                    'input': {
                        'font-size': '14px',
                        'padding-left': '10px'
                    },
                    'input.invalid': {
                        'color': 'red'
                    },
                    'input.valid': {
                        'color': ''
                    }
                },
                fields: {
                    number: {
                        selector: '#card-number',
                        placeholder: 'Card Number'
                    },
                    cvv: {
                        selector: '#cvv',
                        placeholder: 'CVV'
                    },
                    expirationDate: {
                        selector: '#expiration-date',
                        placeholder: 'Expiration Date'
                    }
                }
            }, function (hostedFieldsError, hostedFieldsInstance) {
                if (hostedFieldsError) {
                    console.error(hostedFieldsError);
                    return;
                }
                
                btnPaymentSaveAndContinue.addEventListener('click', function (event) {
                    hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
                        if (tokenizeErr) {
                            console.error(tokenizeErr);
                            return;
                        }
                        //alert(payload.nonce);
                        //nonce.value = payload.nonce;

                        braintreeNonce.value = payload.nonce;
                        nonceBraintree = true;
                        validatePaymentOption();
                        //form.submit();
                    });
                }, false);
            });
        });
}

function bindBraintreePaypalElement() {
    //$("#frmPaypal").addClass("d-none");
    var priceAmt = parseFloat($("#lblPriceSummary").html().replace('$', ''));

    braintree.client.create({
        authorization: paypalBraintreeClientToken.value
    },
        function (clientErr, clientInstance) {
            //console.error(clientInstance);
            // Stop if there was a problem creating the client.
            // This could happen if there is a network error or if the authorization
            // is invalid.
            if (clientErr) {
                console.error('Error creating client:', clientErr);
                return;
            }

            // Create a PayPal Checkout component.
            braintree.paypalCheckout.create({
                client: clientInstance
            }, function (paypalCheckoutErr, paypalCheckoutInstance) {
                if (paypalCheckoutInstance != undefined) {// braintree missing paypal account link
                    paypalCheckoutInstance.loadPayPalSDK({

                        currency: 'USD',
                        intent: 'authorize'
                    }, function () {
                        $('#paypalBraintreeButtonloader').addClass('d-none');
                        paypal.Buttons({
                            style: {
                                color: 'black',
                                shape: 'rect',
                                label: 'pay',//label: 'checkout',
                                height: 50
                            },
                            fundingSource: paypal.FUNDING.PAYPAL,

                            createOrder: function () {
                                //console.log('PayPal paypalCheckoutInstance');
                                return paypalCheckoutInstance.createPayment({

                                    flow: 'checkout', // Required
                                    amount: priceAmt, // Required
                                    currency: 'USD', // Required, must match the currency passed in with loadPayPalSDK

                                    intent: 'authorize', // Must match the intent passed in with loadPayPalSDK

                                    enableShippingAddress: true,
                                    enableBillingAddress: true,
                                    shippingAddressEditable: false

                                });

                            },

                            onApprove: function (data, actions) {
                                return paypalCheckoutInstance.tokenizePayment(data, function (err, payload) {
                                    //console.log(payload.details); 
                                    //alert(JSON.stringify(payload.details));
                                    paypalBraintreeNonce.value = payload.nonce;
                                    braintreepaypalAddressfetching(payload.details);
                                    if ($('#paypalBraintreeShipAddress').val() == "") {
                                        return false;
                                    }

                                    $("#frmPaypalBraintree").submit();
                                    //Submit `payload.nonce` to your server
                                });
                            },

                            onCancel: function (data) {
                                console.log('PayPal payment cancelled', JSON.stringify(data, 0, 2));
                            },

                            onError: function (err) {
                                console.error('PayPal error', err);
                            }
                        }).render('#braintree-paypal-button').then(function () {

                            //console.error('#paypal-button');
                            // The PayPal button will be rendered in an html element with the ID
                            // `paypal-button`. This function will be called when the PayPal button
                            // is set up and ready to be used
                        });

                    });
                }
                else {
                    $("#frmPaypal").removeClass("d-none");
                    $("#frmPaypalBraintree").addClass("d-none");
                }

            });
        });
}

function braintreepaypalAddressfetching(shipAddress) {
    var addressDetails = {};
    //{ "email": "binup_1361514395_per@realityi.com", "firstName": "Binu", "lastName": "Paul", "payerId": "TA8CG3X2QWJ74", "shippingAddress": { "recipientName": "Binu Paul", "line1": "1 Main St", "city": "San Jose", "state": "CA", "postalCode": "95131", "countryCode": "US" }, "countryCode": "US" }

    addressDetails['FirstName'] = shipAddress.firstName;
    addressDetails['LastName'] = shipAddress.lastName;
    addressDetails['Email'] = shipAddress.email;

    var shippingaddress = shipAddress.shippingAddress;

    addressDetails['StrtAddress'] = shippingaddress.line1;
    addressDetails['City'] = shippingaddress.city;
    addressDetails['State'] = shippingaddress.state;
    addressDetails['ZipCode'] = shippingaddress.postalCode;
    addressDetails['Country'] = shippingaddress.countryCode;

    addressDetails = JSON.stringify(addressDetails);
    $('#paypalBraintreeShipAddress').val(addressDetails);
    $('#paypalBraintreeBillAddress').val(addressDetails);
    if ($('#paypalBraintreeShipAddress').val() == "")
    {
        return false;
    }}
//end-braintreefunction validateCountryCode(phone)
{
    var data = $('#' + phone).val();
    data = stripCharsNotInBag(data, "1234567890");
    if (data.indexOf('+1') === 0 || data.indexOf('01') === 0 || data.indexOf('1') === 0) {
        $(".CountryCodeWarning").removeClass('d-none');
        $('#' + phone).removeClass("RightInput");
        $('#' + phone).addClass("InvalidSearch");
    }
    else if (!$(".CountryCodeWarning").hasClass('d-none')) {
        $(".CountryCodeWarning").addClass('d-none');
    }
    return;
}
   function cartClickDisable() {
    $(".CartOverlay").show();
    $("#clickDisableOverlay").addClass("clickDisable");
};
//Track the purchase using FbpixelTracker
//FbPixelTrackPurchase(value=true/false,partnumber='number',quantity=1,price=10)
//The quantity/price sent must be a decimal number greater than or equal to zero. It cannot include letters, special characters, currency symbols or commas.
function FbPixelTrackPurchase(value, cookiecontent, total, transactionId, taxTotal, shippingTotal, centerid) {
    if (value.toLowerCase().trim() == 'false')
        fbq('track', 'Purchase');
    else
        fbq('track', 'Purchase', {
            contents: cookiecontent,
            content_type: 'product',
            value: total,
            currency: 'USD',
            transactionid: transactionId,
            tax: taxTotal,
            estimated_shipping: shippingTotal,
            centerid: centerid
        });
}

//Track the Lead using FbpixelTracker
function FbPixelTrackLead() {
    fbq('track', 'Lead');
}

//Track the CompleteRegistration using FbpixelTracker
function FbPixelTrackRegistration() {
    fbq('track', 'CompleteRegistration');
}

//Track the PaymentInfo using FbpixelTracker
function FbPixelTrackPaymentInfo(value, TotalAmount, PaymentGateway,TransactionId,CenterId) {
    if (value.toLowerCase().trim() == 'false')
        fbq('track', 'AddPaymentInfo');
    else
        fbq('track', 'AddPaymentInfo', {
            value: TotalAmount,
            content_type: 'product',
            currency: 'USD',
            paymentGateway: PaymentGateway,
            transactionid: TransactionId,
            centerid: CenterId,
        });
}

//Track the AddToCart using FbpixelTracker
function FbPixelTrackAddToCart(value, partnumber, quantity, price,itemname) {
    var date = new Date();
    var time = date.getTime();
    //here we are passing time parameter as unique id so that two adjacent calls will not
    //get clashed
    if (value.toLowerCase().trim() == 'false')
        fbq('track', 'AddToCart');
    else
        fbq('track', 'AddToCart', {
            value: price,
            currency: 'USD',
            content_type: 'product',
            content_ids:time,
            contents: [
                {
                    id: partnumber,
                    quantity: quantity,
                    item_price: price,
                    name:itemname,
                }
            ],
        });
}

//Track the Wishlist using FbpixelTracker
function FbPixelTrackWishlist() {
    fbq('track', 'AddToWishlist');
}

//Track the InitiateCheckout using FbpixelTracker
function FbPixelTrackInitiateCheckout(value, cookiecontent, total, centerid) {
    if (value.toLowerCase().trim() == 'false')
        fbq('track', 'InitiateCheckout');
    else
        fbq('track', 'InitiateCheckout', {
            contents: cookiecontent,
            content_type: 'product',
            value: total,
            currency: 'USD',
            centerid: centerid
        });
}

//Track the Search using FbpixelTracker
//value=true/false,searchvalue='searchtext'
function FbPixelTrackSearch(value, searchvalue) {
    if (value.toLowerCase().trim() == 'false')
        fbq('track', 'Search');
    else
        fbq('track', 'Search', {
            search_string: [searchvalue],
            content_type: 'Product',
        });
}

//Track the ViewContent using FbpixelTracker
//value=true/false,elementid='id',typeofelment='div/span' // lifestyle/accessories
function FbPixelTrackViewContent(value, elementid, typeofelement,modelid) {
    if (value.toLowerCase().trim() == 'false')
        fbq('track', 'ViewContent');
    else
        fbq('track', 'ViewContent', {
            content_ids: [elementid],
            content_type:'product',
        });
}

//Track the Lead using FbpixelTracker
function fbPixelLeadForPreorder(contentName) {
    fbq('track', 'Lead', {
        content_name: contentName
    });
}




  




    


 
    



 
    




    







  
    

  

;
//page load
$(document).ready(function () {
    var isStripeEnabled = "false";
    var isBraintreeEnabled = "false";
    var preorderURL = window.location.href.toUpperCase();
    if (preorderURL.indexOf('BMW-IX-PRE-ORDER') > 0 || preorderURL.indexOf('BMW-I4-PRE-ORDER') > 0 || preorderURL.indexOf('BMW-PRE-ORDER-TEMPLATE') > 0) {
        //show dealer popup when dealer is not selected on page load
        var dealerId = $("#hdnDealerId").val();
        if (dealerId === undefined || dealerId === "0")
            showDealerPopup();

        //BMWUSADCMFloodlightPreorderPageLoadEvent();
    }
    if (window.location.href.toUpperCase().indexOf('BMW-IX-PRE-ORDER') > 0 ) 
    {
        fbPixelLeadForPreorder('iX Pre-Order Landing Page Page Load');
    }
    if (window.location.href.toUpperCase().indexOf('BMW-I4-PRE-ORDER') > 0) {
        fbPixelLeadForPreorder('i4 Pre-Order Landing Page Page Load');
    }
    if (window.location.href.toUpperCase().indexOf('/PREORDER/') > 0) {
        isStripeEnabled = $('#hdnPreIsStripeEnabled').val().toString(); 
        isBraintreeEnabled = $('#hdnIsPreOrderBraintreeEnabled').val().toString();
        if (isStripeEnabled == "true") {
            bindPreStripeCardElement();
        }
        else if (isBraintreeEnabled == "true") {
            bindPreOrderBraintreeCardElement();
        }

        if ($("#hdnPreModel") != undefined && $("#hdnModelName2") != undefined && $("#hdnPreModel").val() == $("#hdnModelName2").val()) {
            selectPreModel('i4model1');
        }
       
    }

    //for jk preorder show dealer popuplways.
    if (preorderURL.indexOf('BMW-I7-PRE-ORDER') > 0 || preorderURL.indexOf('BMW-8-X-JEFF-KOONS-PRE-ORDER') > 0 || preorderURL.indexOf('/PREORDER/PREORDERWAITLIST') > 0) {
        var dealerId = $("#hdnDealerId").val();
        if (dealerId === undefined || dealerId === "0") {
            showDealerPopup();
        }
        else {
            if ($("#hdnShowDealerPopup").val() != "True") {
                $('#dealerLocated').click();
            }
        }
    }



        //$(".carousel-control-prev").on('click', function () {
        //    var imageId;
        //    if (window.location.href.toUpperCase().indexOf('BMW-IX-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-PRE-ORDER-TEMPLATE') > 0) {

        //        imageId = $(this).closest("[id^='ixSlider']").find('div').find('.active').attr('id');
        //        //if (imageId == undefined)
        //        //    imageId = $(this).closest("[id^='ixSlider']").find('.active').find('video').attr('id');
        //        var assetCount = parseInt($(this).closest("[id^='ixSlider']").find('.carousel-item').length);

        //    }
        //    else if (window.location.href.toUpperCase().indexOf('BMW-I4-PRE-ORDER') <= 0) {
        //        imageId = $(this).closest("[id^='productCarousel']").find('.active').find('img').attr('id');
        //        if (imageId == undefined)
        //            imageId = $(this).closest("[id^='productCarousel']").find('.active').find('video').attr('id');
        //        var assetCount = parseInt($(this).closest("[id^='productCarousel']").find('.carousel-item').length);
        //    }
        //    var components = imageId.split("-");
        //    var photoNum = components[components.length - 1];
        //    var index = parseInt(photoNum) - 1;
        //    // var assetCount = parseInt($(this).closest("[id^='productCarousel']").find('.carousel-item').length);
        //    if (index < 0)
        //        index = assetCount - 1;
        //    thumbnaillImageOnClick(index);
        //});

        //$(".carousel-control-next").on('click', function () {
        //    var imageId;
        //    if (window.location.href.toUpperCase().indexOf('BMW-IX-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-PRE-ORDER-TEMPLATE') > 0) {
        //        imageId = $(this).closest("[id^='ixSlider']").find('div').find('.active').attr('id');
        //        //if (imageId == undefined)
        //        //    imageId = $(this).closest("[id^='ixSlider']").find('.active').find('video').attr('id');
        //        var assetCount = parseInt($(this).closest("[id^='ixSlider']").find('.carousel-item').length);
        //    }
        //    else if (window.location.href.toUpperCase().indexOf('BMW-I4-PRE-ORDER') <= 0) {
        //        imageId = $(this).closest("[id^='productCarousel']").find('.active').find('img').attr('id');
        //        if (imageId == undefined)
        //            imageId = $(this).closest("[id^='productCarousel']").find('.active').find('video').attr('id');
        //        var assetCount = parseInt($(this).closest("[id^='productCarousel']").find('.carousel-item').length);
        //    }
        //    var components = imageId.split("-");
        //    var photoNum = components[components.length - 1];
        //    //var assetCount = parseInt($(this).closest("[id^='productCarousel']").find('.carousel-item').length);
        //    var index = parseInt(photoNum) + 1;
        //    if (index >= assetCount)
        //        index = 0;
        //    thumbnaillImageOnClick(index);
        //});

        //$(".i4Model1-prev").on('click', function () {
        //    var imageId;
        //    if ( window.location.href.toUpperCase().indexOf('BMW-I4-PRE-ORDER') > 0 ) {
        //        imageId = $(this).closest("[id^='ixSliderModel1']").find('div').find('.active').attr('id');
        //        //if (imageId == undefined)
        //        //    imageId = $(this).closest("[id^='ixSlider']").find('.active').find('video').attr('id');
        //        var assetCount = parseInt($(this).closest("[id^='ixSliderModel1']").find('.carousel-item').length);

        //    }       
        //    var components = imageId.split("-");
        //    var photoNum = components[components.length - 1];
        //    var index = parseInt(photoNum) - 1;
        //    // var assetCount = parseInt($(this).closest("[id^='productCarousel']").find('.carousel-item').length);
        //    if (index < 0)
        //        index = assetCount - 1;
        //    thumbnaillImageOnClick_i4(index, "ixSliderModel1");
        //});

        //$(".i4Model1-next").on('click', function () {
        //    var imageId;
        //    if ( window.location.href.toUpperCase().indexOf('BMW-I4-PRE-ORDER') > 0 ) {
        //        imageId = $(this).closest("[id^='ixSliderModel1']").find('div').find('.active').attr('id');
        //        //if (imageId == undefined)
        //        //    imageId = $(this).closest("[id^='ixSlider']").find('.active').find('video').attr('id');
        //        var assetCount = parseInt($(this).closest("[id^='ixSliderModel1']").find('.carousel-item').length);
        //    }       
        //    var components = imageId.split("-");
        //    var photoNum = components[components.length - 1];
        //    //var assetCount = parseInt($(this).closest("[id^='productCarousel']").find('.carousel-item').length);
        //    var index = parseInt(photoNum) + 1;
        //    if (index >= assetCount)
        //        index = 0;
        //    thumbnaillImageOnClick_i4(index, "ixSliderModel1");
        //});    
    });
//function thumbnaillImageOnClick(id) {
//    //var SelectedClass = $(".thumbnail-image");  
//    if (window.location.href.toUpperCase().indexOf('BMW-IX-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-I4-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-PRE-ORDER-TEMPLATE') > 0) {
//        var SelectedClass = $("#ixSlider .carousel-item");
//        $.each(SelectedClass, function (index, object) {
//            $("#ixSlider > #" + object.id).removeClass("active");
//        });
//        $("#ixSlider > #product-thumbnail-" + id).addClass("active");
//    }
//    else {
//        var SelectedClass = $(".thumbnail-image");
//        $.each(SelectedClass, function (index, object) {
//            $("#" + object.id).removeClass("thumb-selected");
//        });
//        $("#product-thumbnail-" + id).addClass("thumb-selected");

//    }
//}
//function thumbnaillImageOnClick_i4(id,divId) {
//    //var SelectedClass = $(".thumbnail-image");  
//    if ( window.location.href.toUpperCase().indexOf('BMW-I4-PRE-ORDER') > 0 ) {
//        var SelectedClass = $("#" + divId+" .carousel-item");
//        $.each(SelectedClass, function (index, object) {
//            $("#" + divId +" > #" + object.id).removeClass("active");
//        });
//        $("#" + divId +" > #product-thumbnail-" + id).addClass("active");
//    }
//    else {
//        var SelectedClass = $(".thumbnail-image");
//        $.each(SelectedClass, function (index, object) {
//            $("#" + object.id).removeClass("thumb-selected");
//        });
//        $("#product-thumbnail-" + id).addClass("thumb-selected");

//    }
//}

//Dealer-OptOut form validations - start
function submitOptOutDealer() {
    var flagError = false;
    flagError = validateOptOutBeforeSubmit("DealerOptOutDetails");
    if (!flagError) {
        var optOutDetails = {};
        if (!$("#divOptOutForm").hasClass("d-none")) {
            $('#divOptOutForm input').each(function () {
                var name = this.id.replace("txt", "");
                var value = $(this).val();
                optOutDetails[name] = value;
            });
            $('#divOptOutForm textarea').each(function () {
                var name = this.id.replace("txt", "");
                var value = $(this).val();
                optOutDetails[name] = value;
            });
        }
        optOutDetails = JSON.stringify(optOutDetails);
        $('#hdnOptOutDeails').val(optOutDetails);
        return true;
    }
    else {
        return false;
    }
}
var errorOptFlag = false;
function validateOptOutRequiredFields(control, controlType) {
    var data = $('#' + control).val();
    regex = /^\s+|\s+$/g;
    data = data.replace(regex, "");
    $('#' + control).val(data);
    var spanId = control.replace(controlType, "span");
    if (data.toString() == "") {
        errorOptFlag = true;
        $('#' + control).removeClass("RightInput");
        $('#' + control).addClass("InvalidSearch");
        $('#' + spanId).removeClass("d-none");
    }
    else {
        $('#' + control).removeClass("InvalidSearch");
        $('#' + control).addClass("RightInput");
        $('#' + spanId).addClass("d-none");
        if (control.toLowerCase().indexOf("phone") >= 0) {
            var phoneNumber = $('#' + control).val().replace(/\-/g, '');
            var strDigits = stripCharsNotInBag(phoneNumber, "1234567890");
            if (strDigits.length == 10) {
                var formatPhoneNumber = $('#' + control).val();
                $('#' + control).val(formatPhoneNumber);
                $('#' + control).removeClass("InvalidSearch");
                $('#' + control).addClass("RightInput");
            }
            else {
                errorOptFlag = true;
                $('#' + control).removeClass("RightInput");
                $('#' + control).addClass("InvalidSearch");
            }
        }
        if (control.toLowerCase().indexOf("centerid") >= 0) {
            var centerid = $('#' + control).val();
            if (centerid.length < 5) {
                errorOptFlag = true;
                $('#' + control).addClass("InvalidSearch");
                $('#' + control).removeClass("RightInput");
            }
            else {
                $('#' + control).removeClass("InvalidSearch");
                $('#' + control).addClass("RightInput");
            }
        }
    }
}

function validateOptOutBeforeSubmit(sectionDivId) {
    errorOptFlag = false;// global variable
    var flagError = false;
    var txtControls = "";
    var ddlControls = "";
    $('#' + sectionDivId + ' .required').each(function () {
        var type = this.type || this.tagName.toLowerCase();
        if (type.toLowerCase() == "text" || type.toLowerCase() == "tel")
            txtControls = txtControls + this.id + ",";
    });
    txtControls = txtControls.replace(/,\s*$/, "");
    var controlArray = txtControls.split(",");
    //alert(controlArray);
    for (var i = 0; i < controlArray.length; i++) {
        if (controlArray[i] != "")
            validateOptOutRequiredFields(controlArray[i], "txt");
    }
    $('#' + sectionDivId + ' .text-data').each(function () {
        if (!isAllAlphabets($(this).val())) {
            $(this).removeClass("RightInput");
            $(this).addClass("InvalidSearch");
            flagError = true;
        }
        else {
            $(this).removeClass("InvalidSearch");
            $(this).addClass("RightInput");
        }
    });
    $('#' + sectionDivId + ' .tel-data').each(function () {
        if (!validatePhoneNumber($(this).val())) {
            $(this).removeClass("RightInput");
            $(this).addClass("InvalidSearch");
            flagError = true;
        }
        else {
            $(this).removeClass("InvalidSearch");
            $(this).addClass("RightInput");
        }
    });
    $('#' + sectionDivId + ' .email-data').each(function () {
        if (!validateOptOutEmail($(this).val())) {
            $(this).val('');
            $(this).removeClass("RightInput");
            $(this).addClass("InvalidSearch");
            flagError = true;
        }
        else {
            $(this).removeClass("InvalidSearch");
            $(this).addClass("RightInput");
        }
    });
    $('#' + sectionDivId + ' .centerid-data').each(function () {
        var digits = stripCharsNotInBag($(this).val(), "1234567890");
        if ($(this).val().length != digits.length) {
            $(this).removeClass("RightInput");
            $(this).addClass("InvalidSearch");
            flagError = true;
        }
        else {
            if (digits.length < 5) {
                $(this).removeClass("RightInput");
                $(this).addClass("InvalidSearch");
                flagError = true;
            }
            else {
                $(this).removeClass("InvalidSearch");
                $(this).addClass("RightInput");
            }
        }
    });
    if (errorOptFlag == false)
        return false;//no error
    else
        return true;
}
function validateOptOutEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (re.test(email)) {
        return true;
    }
    else {
        return false;
    }

}
function formatCenterId() {
    var newvalue = "";
    var centerid = "";
    if ($("#txtCenterId") != null) {
        centerid = $("#txtCenterId").val();
        var digits = stripCharsNotInBag(centerid, "1234567890");
        if (strDigits.length == 6) {
            newvalue = digits.substring(0, 5) + "-" + digits.substring(5, 8);
            $("#txtCenterId").val(newvalue);
        }
    }
}
//Dealer-OptOut form validations - end
function onSuccessOptOut(response) {
    if (response.indexOf("success") !== -1) {
        response = response.replace("success", "");
        alert(response.replace(/<br\s*\/?>/mg, "\n"));
        $("#txtName").val("");
        $("#txtEmail").val("");
        $("#txtPhone").val("");
        $("#txtCenterId").val("");
        $("#txtComments").val("");
        $("#divOptOutForm").find("input").removeClass("InvalidSearch");
        $("#divOptOutForm").find("input").removeClass("RightInput");
        $('#myModalPreCamp').modal("hide");
    }
    else {
        alert(response.replace(/<br\s*\/?>/mg, "\n"));
    }
}

$("#txtComments").focus(function () {
    $("#lblComments").addClass("input-not-empty");
});

$("#txtComments").blur(function () {
    if ($("#txtComments").val() == "") {
        if ($("#lblComments").hasClass("input-not-empty")) {
            $("#lblComments").removeClass("input-not-empty");
        }
    }
});

function setPreOrderOptions(obj) {
    if ($(obj).val().toString().toLowerCase() == "true") {
        $('#optionDetails').val('Captain\'s Chair');
    }
}
function setOptionValue() {
    var isOptionSelected = "false";
    var preorderurl = $("#hdnPreOrderUrl").val();
    var optionDetailsValue = "";
    if (preorderurl.toLowerCase().toString().includes("x7")) {
        isOptionSelected = $("input[name='OptionCaptainChairRadioGroup']:checked").val().toString();
        if (isOptionSelected == "true") {
            $('#optionDetails').val('Captain\'s Chair');
        }
    }
    else if (preorderurl.toLowerCase().toString().includes("m4")) {
        var val = "";
        var option = "";
        isOptionSelected = $("#paint_checkbox").is(':checked');
        if (isOptionSelected.toString() == "true") {
            val = colorNames;
            option = val.getElementsByClassName("PreOptColorName activeName");
            optionDetailsValue = option[0].textContent;
            isOptionSelected = "false";
        }
        isOptionSelected = $("#wheel_checkbox").is(':checked');
        if (isOptionSelected.toString() == "true") {
            val = wheelColor;
            option = val.getElementsByClassName("PreOptColorName activeName");
            optionDetailsValue += '+' + option[0].textContent;
            isOptionSelected = "false";
        }
        isOptionSelected = $("#kithroof_checkbox").is(':checked');
        if (isOptionSelected.toString() == "true") {
            optionDetailsValue += '+' + $("#div_kith").find('h1:first').text() + ', ' + $("#div_kith").find('p:first').text();
            //optionDetailsValue += '+Carbon Fiber Kith Roof, $4,500';
            isOptionSelected = "false";
        }
        isOptionSelected = $("#driving_checkbox").is(':checked');
        if (isOptionSelected.toString() == "true") {
            optionDetailsValue += '+' + $("#div_assistance").find('h1:first').text() + ', ' + $("#div_assistance").find('p:first').text();
            //optionDetailsValue += '+Driving Assistance Plus, $1,700';
            isOptionSelected = "false";
        }
        $("#optionDetails").val(optionDetailsValue);
    }

}

function removePreorderCart(quantity, productItemId, deliveryType, productCount) {
    var args = { quantity: quantity, productItemId: productItemId, deliveryType: deliveryType };
    $.ajax(BMWAjax.lib.request({ method: 'POST', url: BMWAjax.Urls.Cart.UpdateCart, data: args }, {
        complete: function (json) {
            //if (json.responseJSON != null && json.responseJSON[1] === "true") {
            $("#cartSummaryContainer").html(json.responseJSON);
            updateCartProductQuantity(quantity, productCount, 0);
            //}
        }
    }));
}

function colorOptionPreorder(colorSquare) {
    if ($("#preColorsdiv_Paint").children().hasClass("bactive")) {
        $("#preColorsdiv_Paint").children().removeClass("bactive");
    }
    if ($('#colorNames p').hasClass('activeName')) {
        $('#colorNames p').addClass('d-none').removeClass('activeName');
    }

    //if ($('#optionImage1').children().hasClass('carousel-item active')){
    //    $("#optionImage1").children().removeClass("active");
    //}
    $("#" + colorSquare).addClass("bactive");
    $("#" + colorSquare.replace('div_', '')).removeClass('d-none').addClass('activeName');
    //$("#" + colorSquare.replace('div', 'img')).parent().addClass('active');
}

function wheelcolorOption(colorOption) {
    if ($("#preColorsdiv_wheel").children().hasClass("bactive")) {
        $("#preColorsdiv_wheel").children().removeClass("bactive");
    }
    if ($('#wheelColor p').hasClass('activeName')) {
        $('#wheelColor p').addClass('d-none').removeClass('activeName');
    }

    if ($('#optionImage2').children().hasClass('carousel-item active')) {
        $("#optionImage2").children().removeClass("active");
    }
    $("#" + colorOption).addClass("bactive");
    $("#" + colorOption.replace('div', 'p')).removeClass('d-none').addClass('activeName');
    $("#" + colorOption.replace('div', 'img')).parent().addClass('active');
}

function selectedOptionPreOrder(checkboxId, parentDiv) {
    if ($('input[type=checkbox][id^="' + checkboxId + '"]').prop("checked") == true) {
        $("#" + parentDiv).addClass('PreOptBactive');
        $("#" + checkboxId).parent().addClass('custom-controlselected');
    }
    else {
        $("#" + parentDiv).removeClass('PreOptBactive');
        $("#" + checkboxId).parent().removeClass('custom-controlselected');
    }
}

$("#FeaturesLink").click(function () {
    $('#DivFeaturePop').addClass("AddDivFeaturePop");
    $('.DivFeaturePopOverlay').addClass("d-block");
});
$(".DivFeaturePopOverlay").click(function () {
    $('#DivFeaturePop').removeClass("AddDivFeaturePop");
    $('.DivFeaturePopOverlay').removeClass("d-block");

});
$("#nav-icon2").click(function () {
    $('#DivFeaturePop').removeClass("AddDivFeaturePop");
    $('.DivFeaturePopOverlay').removeClass("d-block");

});

$(".DivFaq").click(function () {
    $('#DivQuesPop').addClass("AddDivQuesPop");
    $('.DivQuesPopoverlay').addClass("d-block");

});
$(".iFeatureEndSecfaq").click(function () {
    $('#DivQuesPop').addClass("AddDivQuesPop");
    $('.DivQuesPopoverlay').addClass("d-block");

});
$(".BtnQuesPopClose").click(function () {
    $('#DivQuesPop').removeClass("AddDivQuesPop");
    $('.DivQuesPopoverlay').removeClass("d-block");
});

$("#termsCondtnText").click(function () {
    $('#DivTermsCondtnPop').addClass("AddDivQuesPop");
    $('.DivQuesPopoverlay').addClass("d-block");
});
$("#paypalTermsCondtnText").click(function () {
    $('#DivTermsCondtnPop').addClass("AddDivQuesPop");
    $('.DivQuesPopoverlay').addClass("d-block");
});
$("#amazonTermsCondtnText").click(function () {
    $('#DivTermsCondtnPop').addClass("AddDivQuesPop");
    $('.DivQuesPopoverlay').addClass("d-block");
});
$(".BtnTermsCondtnPopClose").click(function () {
    $('#DivTermsCondtnPop').removeClass("AddDivQuesPop");
    $('.DivQuesPopoverlay').removeClass("d-block");
});
$("#Featurelink").click(function () {
    $('#DivSpecs').addClass("AddDivQuesPop");
    $('.DivQuesPopoverlay').addClass("d-block");

});
$("#nav-icon5").click(function () {
    $('#DivSpecs').removeClass("AddDivQuesPop");
    $('.DivQuesPopoverlay').removeClass("d-block");

});
$(".DivQuesPopoverlay").click(function () {
    $('#DivSpecs').removeClass("AddDivQuesPop");
    $('.DivQuesPopoverlay').removeClass("d-block");

});
//Payment Option

$(".PaymentSec").click(function () {
    $('#DivPaymentPop').addClass("AddDivpayPop");
    $('.DivQuesPopoverlay').addClass("d-block");
    $("#PaymentOpt1").click();
});
$(".DivQuesPopoverlay").click(function () {
    $('.DivPaymentopt').removeClass("AddDivpayPop");
    $('.DivQuesPopoverlay').removeClass("d-block");
    $('.DivQuesPop').removeClass("AddDivQuesPop");
});

$("#aLearnMoreFinance").click(function () {
    $('#DivPaymentPop').addClass("AddDivpayPop");
    $('.DivQuesPopoverlay').addClass("d-block");
    $("#PaymentOpt1").click();

});
$("#nav-icon4").click(function () {
    $('#DivPaymentPop').removeClass("AddDivpayPop");
    $('.DivQuesPopoverlay').removeClass("d-block");
    $("#PaymentOpt1").click();
});
$("#OfferDet").click(function () {
    $('#DivPaymentPop').addClass("AddDivpayPop");
    $('.DivQuesPopoverlay').addClass("d-block");
    $("#PaymentOpt2").click();

});
$("#OfferLease").click(function () {
    $('#DivPaymentPop').addClass("AddDivpayPop");
    $('.DivQuesPopoverlay').addClass("d-block");
    $("#PaymentOpt3").click();
});
$("#OfferLease1").click(function () {
    $('#DivPaymentPop').addClass("AddDivpayPop");
    $('.DivQuesPopoverlay').addClass("d-block");
    $("#PaymentOpt3").click();
});
//$("#PaymentOpt2").click(function () {
//    $('#PaymentOpt1').removeClass("active1");
//    $('#PaymentOpt2').addClass("active1 active2");
//    $('#PaymentOpt3').removeClass("active");
//});
//$("#PaymentOpt3").click(function () {
//    $('#PaymentOpt2').removeClass("active");
//    $('#PaymentOpt3').addClass("active");
//    $('#PaymentOpt1').removeClass("active");
//});
//$("#PaymentOpt1").click(function () {
//    $('#PaymentOpt2').removeClass("active");
//    $('#PaymentOpt3').removeClass("active");
//    $('#PaymentOpt1').addClass("active");
//});

$("#PaymentOpt2").click(function () {
    $('.active1').addClass("active2");
    $('.active1').removeClass("active3");
    $('#PaymentOpt2').addClass("activez");
    $('#PaymentOpt1').removeClass("activez");
    $('#PaymentOpt3').removeClass("activez");
    $('#ixCash').addClass("d-none");
    $('#ixLoan').removeClass("d-none");
    $('#ixLease').addClass("d-none");

});
$("#PaymentOpt3").click(function () {
    $('.active1').addClass("active3");
    $('.active1').removeClass("active2");
    $('#PaymentOpt3').addClass("activez");
    $('#PaymentOpt1').removeClass("activez");
    $('#PaymentOpt2').removeClass("activez");
    $('#ixCash').addClass("d-none");
    $('#ixLoan').addClass("d-none");
    $('#ixLease').removeClass("d-none");
});
$("#PaymentOpt1").click(function () {
    $('.active1').removeClass("active3");
    $('.active1').removeClass("active2");
    $('#PaymentOpt1').addClass("activez");
    $('#PaymentOpt2').removeClass("activez");
    $('#PaymentOpt3').removeClass("activez");
    $('#ixCash').removeClass("d-none");
    $('#ixLoan').addClass("d-none");
    $('#ixLease').addClass("d-none");
});



function preOrderContinuePayment() {
    $('#btnixAddToCart').click();
    document.body.scrollTop = 0; // For Safari
    document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera 
}

function showCheckoutButtons() {
    $('.checkout-buttons').removeClass("d-none");
    $(window).scrollTop(0);
    $('.back-home').removeClass("d-none");
    $('.home-page').removeClass("d-block");
    $('.home-page').addClass("d-none");
}


function showAccountDetailsForm() {
    $('.checkout-buttons').removeClass("d-none");
    $('.iFeatureBillingSec').removeClass("d-none");
    //$(window).scrollTop(0);
    $('.back-home').removeClass("d-none");
    $('.home-page').removeClass("d-block");
    $('.home-page').addClass("d-none");
    //var isWaitListActive = $('#hdnWaitListActive').val().toString();
    //if (isWaitListActive !== null && isWaitListActive !== undefined && isWaitListActive !== "" && isWaitListActive.toLowerCase() === "true")
    //    loadAdobeDTMWaitListScript();
    //else
        loadAdobeDTMBillingScript();
}

//JK preorder
function validateAccountDetailsForm(isWaitList) { //JK
    if (isWaitList.toLowerCase().toString() == "false") {
        event.preventDefault();
    }
    var billingAddressError = false;
    var chkboxFlagErr = false; 
    var isAcceptTerms = false;
    if (!$("#iFeatureBillingSec").hasClass("d-none")) {
        billingAddressError = validateBeforeSubmit('iFeatureBillingSec');
    }

    if (!$('#chkAcceptPolicy').is(':checked')) {
        
        chkboxFlagErr = true;
        $("#chkAcceptPolicyTxt").addClass("invalidTerms");
    }
    else {
        isAcceptTerms = true;
        $('.chkAcceptPolicyTxt').removeClass("invalidTerms");
    }

    if (!$('#chkPaypaldealertermsCondtn').is(':checked')) {

        chkboxFlagErr = true;
        $("#paypaldealertermsCondtnText").addClass("invalidTerms");
    }
    else {
        $('.paypaldealertermsCondtnText').removeClass("invalidTerms");
    }
    if (isWaitList.toLowerCase().toString() =="false") {
        if (!$('#chkPaypaltermsCondtn').is(':checked')) {

            chkboxFlagErr = true;
            $("#paypalTermsCondtnText").addClass("invalidTerms");
        }
        else {
            $('.paypalTermsCondtnText').removeClass("invalidTerms");
        }
    }



    if (!billingAddressError && !chkboxFlagErr) {
        var addressDetails = {};
        var generalDetails = {};

        var contactPhone = "";
        generalDetails["IsAcceptedTerms"] = isAcceptTerms;
        generalDetails = JSON.stringify(generalDetails);
        if (!$(".iFeatureBillingSec").hasClass("d-none")) {
            $('.bill-address').each(function () {
                var name = "";
                if (this.id.indexOf("txtPre") > -1) {
                    name = this.id.replace("txtPre", "");
                }
                else {
                    name = this.id.replace("ddlPre", "");
                }
                var value = $(this).val();
                addressDetails[name] = value;
            });
        }
        addressDetails = JSON.stringify(addressDetails);
        $('#hdnPreAddressList').val(addressDetails);
        $('#hdnPreGeneralDetailList').val(generalDetails);
        if (isWaitList.toLowerCase().toString() == "false") {
            $('#submit-body-overlayId').addClass("d-block");
            $('.JKConfirmPopup').removeClass("d-none");//shown reservation model pop up
            $('#preorderLoaderId').removeClass("d-none").addClass("d-block");
            BMWUSADCMFloodlightPreorderPlaceOrderClickEvent();
            loadAdobeDTMBillingReviewScript();
        }
        else if (isWaitList.toLowerCase().toString() == "true") {
            $('#reviewLoaderId').removeClass("d-none").addClass("d-block");
            $('html').css('overflow', 'hidden');
        }
        return true;
    }
    else {
        return false;
    }
}

function validateAccountDetailsFormEvent(event, isWaitList) { //JK
    var keyValue = event.keyCode;
    if (keyValue == 13) {
        if (isWaitList.toLowerCase().toString() == "false") {
            event.preventDefault();
        }
        var billingAddressError = false;
        var chkboxFlagErr = false;
        var isAcceptTerms = false;
        if (!$("#iFeatureBillingSec").hasClass("d-none")) {
            billingAddressError = validateBeforeSubmit('iFeatureBillingSec');
        }

        if (!$('#chkAcceptPolicy').is(':checked')) {

            chkboxFlagErr = true;
            $("#chkAcceptPolicyTxt").addClass("invalidTerms");
        }
        else {
            isAcceptTerms = true;
            $('.chkAcceptPolicyTxt').removeClass("invalidTerms");
        }

        if (!$('#chkPaypaldealertermsCondtn').is(':checked')) {

            chkboxFlagErr = true;
            $("#paypaldealertermsCondtnText").addClass("invalidTerms");
        }
        else {
            $('.paypaldealertermsCondtnText').removeClass("invalidTerms");
        }
        if (isWaitList.toLowerCase().toString() == "false") {
            if (!$('#chkPaypaltermsCondtn').is(':checked')) {

                chkboxFlagErr = true;
                $("#paypalTermsCondtnText").addClass("invalidTerms");
            }
            else {
                $('.paypalTermsCondtnText').removeClass("invalidTerms");
            }
        }



        if (!billingAddressError && !chkboxFlagErr) {
            var addressDetails = {};
            var generalDetails = {};

            var contactPhone = "";
            generalDetails["IsAcceptedTerms"] = isAcceptTerms;
            generalDetails = JSON.stringify(generalDetails);
            if (!$(".iFeatureBillingSec").hasClass("d-none")) {
                $('.bill-address').each(function () {
                    var name = "";
                    if (this.id.indexOf("txtPre") > -1) {
                        name = this.id.replace("txtPre", "");
                    }
                    else {
                        name = this.id.replace("ddlPre", "");
                    }
                    var value = $(this).val();
                    addressDetails[name] = value;
                });
            }
            addressDetails = JSON.stringify(addressDetails);
            $('#hdnPreAddressList').val(addressDetails);
            $('#hdnPreGeneralDetailList').val(generalDetails);
            if (isWaitList.toLowerCase().toString() == "false") {
                $('#submit-body-overlayId').addClass("d-block");
                $('.JKConfirmPopup').removeClass("d-none");//shown reservation model pop up
                $('#preorderLoaderId').removeClass("d-none").addClass("d-block");
                BMWUSADCMFloodlightPreorderPlaceOrderClickEvent();
                loadAdobeDTMBillingReviewScript();
                focusPopup(event, 'JKconfirmReservation');
            }
            else if (isWaitList.toLowerCase().toString() == "true") {
                $('#reviewLoaderId').removeClass("d-none").addClass("d-block");
                $('html').css('overflow', 'hidden');
                //focusPopup(event, 'JKconfirmReservation');
            }
            return true;
        }
        else {
            return false;
        }
    }
    if (keyValue == 9) {
        focusPopup(event, 'JKconfirmReservation');
    }
}

$("#JKConfirmPopupCancel").click(function () {
    $('.JKConfirmPopup').addClass("d-none");//hide reservation model pop up
});

//JK preorder
function showHomePage(preordeUrl) {
    var currentPage = $('#hdnCurrentPage').val();
    $('.checkout-buttons').removeClass("d-block");
    $('.checkout-buttons').addClass("d-none");
    $('.back-home').removeClass("d-block");
    $('.back-home').addClass("d-none");
    $('.home-page').removeClass("d-none");
    if (currentPage != "home")
        window.location = "/" + preordeUrl;
    // window.location.reload(true);
}
function showCheckoutPage() {
    loadAdobeDTMBillingScript();
    $('.checkout-buttons').removeClass("d-none");
    $('.checkout-page').removeClass("d-none");
    $('.back-home').removeClass("d-none");
    $('.home-page').removeClass("d-block");
    $('.home-page').addClass("d-none");
    if ($('.iXbtnpaypal').hasClass("iXbtnpayActive"))
        $('.iXbtnpaypal').removeClass('iXbtnpayActive');
    if ($('.iXbtnamazon').hasClass("iXbtnAmazonActive"))
        $('.iXbtnamazon').removeClass("iXbtnAmazonActive");
    $('.iXbtnCard').addClass('iXbtnCardActive');
    $('#txtPreFirstName').focus();
    $('#divAmazonCheckout').addClass("d-none");
    $('.iFeatureAmazonSec').addClass("d-none");
    $('.iFeaturePaypalSec').addClass("d-none");
}
function loadAdobeDTMWaitListScript() {

    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.setAttribute('data-name', 'preorder-waitList-page');

    var content = 'BMWdataLayer = {};';
    content += '\n  BMWdataLayer = {  "page" :{  \n   "name" : "shopbmwusa:waitlist", \n   "section" : "waitlist", \n    "template" : "shopbmwusa_preorder_template", \n   "baseDomain" :"shopbmwusa", \n  "TLD" : "com", \n  "primarySection" : "waitlist", \n  "pageLevel2" : "", \n "pageHier" : "waitlist" \n }, \n "dataLayerVersion" : "shopbmwusa v1"}; \n';


    content += '\n BMWdataLayer.page.title =  "waitlist";';

    content += '\n BMWdataLayer.page.path =  "' + window.location.pathname + '" ;';

    content += '\n BMWdataLayer.page.url =  "' + window.location.href + '" ;';

    content += '\n BMWdataLayer.page.urlNoParams =  "' + window.location.protocol + '//' + window.location.host + window.location.pathname + '" ;';

    content += '\n BMWdataLayer.page.domain = "' + document.domain + '" ;';

    content += '\n BMWdataLayer.page.name = "' + window.location.pathname.substr(1) + '";';

    script.text = content;
    head.insertBefore(script, head.firstElementChild);
    $("script[data-name = 'preorder-end-page']").remove();
}
function loadAdobeDTMBillingScript() {

    if (window.location.href.toUpperCase().indexOf('BMW-IX-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-I4-PRE-ORDER') > 0) {

        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.setAttribute('data-name', 'preorder-cart-page');

        var content = 'BMWdataLayer = {};';
        content += '\n  BMWdataLayer = {  "page" :{  \n   "name" : "shopbmwusa:billing", \n   "section" : "billing", \n    "template" : "shopbmwusa_preorder_template", \n   "baseDomain" :"shopbmwusa", \n  "TLD" : "com", \n  "primarySection" : "billing", \n  "pageLevel2" : "", \n "pageHier" : "billing" \n }, \n "dataLayerVersion" : "shopbmwusa v1"}; \n';


        content += '\n BMWdataLayer.page.title =  "billing";';

        content += '\n BMWdataLayer.page.path =  "' + window.location.pathname + '" ;';

        content += '\n BMWdataLayer.page.url =  "' + window.location.href + '" ;';

        content += '\n BMWdataLayer.page.urlNoParams =  "' + window.location.protocol + '//' + window.location.host + window.location.pathname + '" ;';

        content += '\n BMWdataLayer.page.domain = "' + document.domain + '" ;';

        content += '\n BMWdataLayer.page.name = "' + window.location.pathname.substr(1) + '";';

        script.text = content;
        //script.setAttribute("async", "false");
        head.insertBefore(script, head.firstElementChild);
        $("script[data-name = 'preorder-product-page']").remove();
    }
    if (window.location.href.toUpperCase().indexOf('BMW-8-X-JEFF-KOONS-PRE-ORDER') > 0) {

        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.setAttribute('data-name', 'preorder-billing-page');

        var content = 'BMWdataLayer = {};';
        content += '\n  BMWdataLayer = {  "page" :{  \n   "name" : "shopbmwusa:billing", \n   "section" : "billing", \n    "template" : "shopbmwusa_preorder_template", \n   "baseDomain" :"shopbmwusa", \n  "TLD" : "com", \n  "primarySection" : "billing", \n  "pageLevel2" : "", \n "pageHier" : "billing" \n }, \n "dataLayerVersion" : "shopbmwusa v1"}; \n';


        content += '\n BMWdataLayer.page.title =  "THE 8 X JEFF KOONS-billing";';

        content += '\n BMWdataLayer.page.path =  "' + window.location.pathname + '" ;';

        content += '\n BMWdataLayer.page.url =  "' + window.location.href + '" ;';

        content += '\n BMWdataLayer.page.urlNoParams =  "' + window.location.protocol + '//' + window.location.host + window.location.pathname + '" ;';

        content += '\n BMWdataLayer.page.domain = "' + document.domain + '" ;';

        content += '\n BMWdataLayer.page.name = "' + window.location.pathname.substr(1) + '";';

        script.text = content;
        //script.setAttribute("async", "false");
        var dtmhead = $("#hdnDTMHeadTag").val();
        if (dtmhead !== null && dtmhead !== undefined)
            $("script[src = '" + dtmhead + "']").after(script);
        else
            head.insertBefore(script, head.firstElementChild);
        $("script[data-name = 'preorder-product-page']").remove();
    }


}
function loadAdobeDTMBillingReviewScript() {

    if (window.location.href.toUpperCase().indexOf('BMW-8-X-JEFF-KOONS-PRE-ORDER') > 0) {

        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.setAttribute('data-name', 'preorder-billing-review-page');

        var content = 'BMWdataLayer = {};';
        content += '\n  BMWdataLayer = {  "page" :{  \n   "name" : "shopbmwusa:billing review", \n   "section" : "billing", \n    "template" : "shopbmwusa_preorder_template", \n   "baseDomain" :"shopbmwusa", \n  "TLD" : "com", \n  "primarySection" : "billing", \n  "pageLevel2" : "review", \n "pageHier" : "billing / review" \n }, \n "dataLayerVersion" : "shopbmwusa v1"}; \n';


        content += '\n BMWdataLayer.page.title =  "THE 8 X JEFF KOONS-billing review";';

        content += '\n BMWdataLayer.page.path =  "' + window.location.pathname + '" ;';

        content += '\n BMWdataLayer.page.url =  "' + window.location.href + '" ;';

        content += '\n BMWdataLayer.page.urlNoParams =  "' + window.location.protocol + '//' + window.location.host + window.location.pathname + '" ;';

        content += '\n BMWdataLayer.page.domain = "' + document.domain + '" ;';

        content += '\n BMWdataLayer.page.name = "' + window.location.pathname.substr(1) + '";';

        script.text = content;
        //script.setAttribute("async", "false");
        var dtmhead = $("#hdnDTMHeadTag").val();
        if (dtmhead !== null && dtmhead !== undefined) 
            $("script[src = '" + dtmhead + "']").after(script);
        else
            head.insertBefore(script, head.firstElementChild);
        $("script[data-name = 'preorder-billing-page']").remove();
    }


}
//start Preorder checkout
function validatePreOrderPaymentOption(paymentType) {
    var shippingError = false;
    var billingAddressError = false;
    var contactError = false;
    var cardError = false;
    var chkboxFlagErr = false;
    errorFlag = false;
    var isAcceptTerms = false;
    var preorder = $("#hdnPreorderName").val();
    if (paymentType == "creditcard") {
        if (!$("#iFeatureBillingSec").hasClass("d-none")) {
            billingAddressError = validateBeforeSubmit('iFeatureBillingSec');
        }
        cardType = $('#hdnCardType').val();
        isCardNumberValid = $('#hdnCardNumberValid').val();
        isCardLengthValid = $('#hdnCardLengthValid').val();
        //cardError = validateCreditCard("txtPre");

        if ($('#hdnPreIsStripeEnabled').val().toString() == "false" && $('#hdnIsPreOrderBraintreeEnabled').val().toString() == "false" || (preorder != null && preorder.toLowerCase().indexOf("i7") > -1) ) {
            cardError = validateCreditCard("txtPre");
            if (!cardError) {
                var isValidExpDate = validatePreOrderExpiryDate();
                if (!isValidExpDate) {
                    cardError = true;
                }
            }
        }
        else if ($('#hdnPreIsStripeEnabled').val().toString() == "true" && !(preorder != null && preorder.toLowerCase().indexOf("i7") > -1) ) {
            cardError = validateStripeCard();
        }
        else if ($('#hdnPreIsStripeEnabled').val().toString() == "false" && $('#hdnIsPreOrderBraintreeEnabled').val().toString() == "true" && !(preorder != null && preorder.toLowerCase().indexOf("i7") > -1)) {
            cardError = validateBrainTreeCard();
        }
        if (!$('#chktermsCondtn').is(':checked')) {
            chkboxFlagErr = true;
            //$('.sectermsCondtn').addClass("invalidTerms");
            $("#termsCondtnText").addClass("invalidTerms");
            if ($('.sectermsCondtn').hasClass("i4Dark"))
                $('.sectermsCondtn').removeClass("i4Dark");
        }
        else {
            $('.sectermsCondtn').removeClass("invalidTerms");
            if ($('.sectermsCondtn').hasClass("i4Terms"))
                $('.sectermsCondtn').addClass("i4Dark");
        }
        if (!$('#chkdealertermsCondtn').is(':checked')) {
            chkboxFlagErr = true;
            //alert(chkboxFlagErr);
            $("#ixvalidation").addClass("ixdealertermsvalidation");
            $("#ixvalidation").removeClass("ixvalidation");
            //$('.sectermsCondtn').addClass("invalidTerms");
            if ($("#dealertermsCondtnText").hasClass("i4Dark"))
                $('#dealertermsCondtnText').removeClass("i4Dark");
        }
        else {
            if ($("#ixvalidation").hasClass("ixdealertermsvalidation")) {
                $("#ixvalidation").removeClass("ixdealertermsvalidation");
                $("#ixvalidation").addClass("ixvalidation");
            }
            if ($("#dealertermsCondtnText").hasClass("i4Terms"))
                $("#dealertermsCondtnText").addClass("i4Dark");
        }
        if ($('#chkAcceptPolicy').is(':checked')) {
            isAcceptTerms = true;
        }


    }
    else if (paymentType == "paypal") {
        validateRequiredFields("txtPrePaypalContactPhone", "txt");
        if (errorFlag) {
            contactError = true;
        }
        if (!$('#chkPaypaltermsCondtn').is(':checked')) {
            chkboxFlagErr = true;
            $('#paypalTermsCondtnText').addClass("invalidTerms");
            if ($('.secPaypaltermsCondtn').hasClass("i4Dark"))
                $('.secPaypaltermsCondtn').removeClass("i4Dark");
        }
        else {
            $('.secPaypaltermsCondtn').removeClass("invalidTerms");
            if ($('.secPaypaltermsCondtn').hasClass("i4Terms"))
                $('.secPaypaltermsCondtn').addClass("i4Dark");
        }
        if (!$('#chkPaypaldealertermsCondtn').is(':checked')) {
            chkboxFlagErr = true;
            // debugger;
            //alert($('#chkdealertermsCondtnText').is(':checked'));
            $("#ixvalidationpaypal").addClass("ixdealertermsvalidation");
            $("#ixvalidationpaypal").removeClass("ixvalidation");
            //$('.sectermsCondtn').addClass("invalidTerms");
            if ($("#paypaldealertermsCondtnText").hasClass("i4Dark"))
                $('#paypaldealertermsCondtnText').removeClass("i4Dark");
        }
        else {
            if ($("#ixvalidationpaypal").hasClass("ixdealertermsvalidation")) {
                $("#ixvalidationpaypal").removeClass("ixdealertermsvalidation");
                $("#ixvalidationpaypal").addClass("ixvalidation");
            }
            if ($("#paypaldealertermsCondtnText").hasClass("i4Terms"))
                $("#paypaldealertermsCondtnText").addClass("i4Dark");
        }

        if ($('#chkPaypalAcceptPolicy').is(':checked')) {
            isAcceptTerms = true;
        }
    }
    else if (paymentType == "stripe") {
        validateRequiredFields("txtPreStripeContactPhone", "txt");
        if (errorFlag) {
            contactError = true;
        }
        if (!$('#chkStripetermsCondtn').is(':checked')) {
            chkboxFlagErr = true;
            $('.secStripetermsCondtn').addClass("invalidTerms");
            if ($('.secStripetermsCondtn').hasClass("i4Dark"))
                $('.secStripetermsCondtn').removeClass("i4Dark");
        }
        else {
            $('.secStripetermsCondtn').removeClass("invalidTerms");
            if ($('.secStripetermsCondtn').hasClass("i4Terms"))
                $('.secStripetermsCondtn').addClass("i4Dark");
        }
        if ($('#chkStripeAcceptPolicy').is(':checked')) {
            isAcceptTerms = true;
        }
    }
    else {
        validateRequiredFields("txtPreAmazonContactPhone", "txt");
        if (errorFlag) {
            contactError = true;
        }
        if (!$('#chkAmazontermsCondtn').is(':checked')) {
            chkboxFlagErr = true;
            $('.secAmazontermsCondtn').addClass("invalidTerms");
            if ($('.secAmazontermsCondtn').hasClass("i4Dark"))
                $('.secAmazontermsCondtn').removeClass("i4Dark");
        }
        else {
            $('.secAmazontermsCondtn').removeClass("invalidTerms");
            if ($('.secAmazontermsCondtn').hasClass("i4Terms"))
                $('.secAmazontermsCondtn').addClass("i4Dark");
        }

        if (!$('#chkAmazondealertermsCondtn').is(':checked')) {
            chkboxFlagErr = true;
            //alert(chkboxFlagErr);
            $("#ixvalidationamazon").addClass("ixdealertermsvalidation");
            $("#ixvalidationamazon").removeClass("ixvalidation");
            //$('.sectermsCondtn').addClass("invalidTerms");
            if ($("#amazondealertermsCondtnText").hasClass("i4Dark"))
                $('#amazondealertermsCondtnText').removeClass("i4Dark");
        }
        else {
            if ($("#ixvalidationamazon").hasClass("ixdealertermsvalidation")) {
                $("#ixvalidationamazon").removeClass("ixdealertermsvalidation");
                $("#ixvalidationamazon").addClass("ixvalidation");
            }
            if ($("#amazondealertermsCondtnText").hasClass("i4Terms"))
                $("#amazondealertermsCondtnText").addClass("i4Dark");
        }

        if ($('#chkAmazonAcceptPolicy').is(':checked')) {
            isAcceptTerms = true;
        }
    }

    
    if (preorder !=null && preorder.toLowerCase().indexOf("i7") > -1) {
        $('div[id^=divContactMethod]').each(function () {
            if (!$(this).hasClass("d-none") && !$(this).find("input").is(":checked")) {
                console.log(this);
                $(this).find("p").addClass("invalidTerms");
                chkboxFlagErr = true;
            }
            else {
                if ($(this).find("p").hasClass("invalidTerms")) {
                    $(this).find("p").removeClass("invalidTerms");
                }
            }
        });
    }


    if (!billingAddressError && !cardError && !chkboxFlagErr && !contactError) {
        var addressDetails = {};
        var billingAddressDetails = {};
        var paymentDetails = {};
        var generalDetails = {};
        var stripe = {};
        var contactPhone = "";
        generalDetails["IsAcceptedTerms"] = isAcceptTerms;
        generalDetails = JSON.stringify(generalDetails);
        if (paymentType == "creditcard") {
            if (!$(".iFeatureBillingSec").hasClass("d-none")) {
                $('.bill-address').each(function () {
                    var name = "";
                    if (this.id.indexOf("txtPre") > -1) {
                        name = this.id.replace("txtPre", "");
                    }
                    else {
                        name = this.id.replace("ddlPre", "");
                    }
                    var value = $(this).val();
                    addressDetails[name] = value;
                });
            }
            addressDetails = JSON.stringify(addressDetails);
            if ($('#hdnPreIsStripeEnabled').val().toString() == "false" && $('#hdnIsPreOrderBraintreeEnabled').val().toString() == "false") {
                $('.card-payment').each(function () {
                    if (this.id.indexOf("txtPre") > -1) {
                        var name = this.id.replace("txtPre", "");
                        var value = $(this).val();
                        paymentDetails[name] = value;
                    }
                    var expDate = $('#ddlPreExpiryMonth').val() + "/" + $('#ddlPreExpiryYear').val();
                    paymentDetails["ExpDate"] = expDate;

                });
                if (cardType.toLowerCase() == "visa")
                    cardType = "Visa";
                if (cardType.toLowerCase() == "mastercard")
                    cardType = "MasterCard";
                if (cardType.toLowerCase() == "discover")
                    cardType = "Discover";
                if (cardType.toLowerCase() == "amex")
                    cardType = "American Express";
                paymentDetails["CardType"] = cardType;
                paymentDetails["PaymentType"] = "creditcard";
                paymentDetails = JSON.stringify(paymentDetails);
                $('#hdnPreAddressList').val(addressDetails);
                $('#hdnPrePaymentList').val(paymentDetails);
                $('#hdnPreGeneralDetailList').val(generalDetails);
            }
            else if ($('#hdnPreIsStripeEnabled').val().toString() == "true" ) {
                stripeCheckout.createToken(stripeCard).then(function (result) {
                    if (result.error) {
                        // Inform the user if there was an error.
                        var errorElement = document.getElementById('card-errors');
                        errorElement.textContent = result.error.message;
                    }
                    else {
                        var token = result.token.id;
                        // Send the token to your server.
                        // stripeTokenHandler(result.token);
                        paymentDetails["CardNo"] = result.token.card.last4;
                        paymentDetails["ExpDate"] = result.token.card.exp_month + "/" + result.token.card.exp_year;
                        cardType = result.token.card.brand;
                        paymentDetails["CardType"] = cardType;
                        paymentDetails["PaymentType"] = "stripe";
                        paymentDetails["CardToken"] = token;
                    }
                    paymentDetails = JSON.stringify(paymentDetails);
                    $('#hdnPreAddressList').val(addressDetails);
                    $('#hdnPrePaymentList').val(paymentDetails);
                    $('#hdnPreGeneralDetailList').val(generalDetails);
                    //return true;
                });
                if ($('#hdnPrePaymentList').val() == "") {
                    return false;
                }
            }
            else if ($('#hdnPreIsStripeEnabled').val().toString() == "false" && $('#hdnIsPreOrderBraintreeEnabled').val().toString() == "true") {
                if (!noncePreOrderBraintree) {
                    return false;
                }

                else {
                    paymentDetails["PaymentType"] = "braintree";
                    paymentDetails["CardToken"] = braintreePreOrderNonce.value;
                    paymentDetails = JSON.stringify(paymentDetails);
                    $('#hdnPreAddressList').val(addressDetails);
                    $('#hdnPrePaymentList').val(paymentDetails);
                    $('#hdnPreGeneralDetailList').val(generalDetails);
                    if ($('#hdnPrePaymentList').val() == "") {
                        return false;
                    }
                   // return true;
                }
            }
        }
        else if (paymentType == "amazon") {
            paymentDetails["PaymentType"] = "amazon";
            paymentDetails = JSON.stringify(paymentDetails);
            contactPhone = $("#txtPreAmazonContactPhone").val();
            $('#hdnPreAddressList1').val(addressDetails);
            $('#hdnPrePaymentList1').val(paymentDetails);
            $('#hdnPreGeneralDetailList1').val(generalDetails);
            $('#hdnAmazonNumber').val(contactPhone);
        }
        else if (paymentType == "paypal") {
            paymentDetails["PaymentType"] = "paypal";
            paymentDetails = JSON.stringify(paymentDetails);
            contactPhone = $("#txtPrePaypalContactPhone").val();
            $('#hdnPreAddressList2').val(addressDetails);
            $('#hdnPrePaymentList2').val(paymentDetails);
            $('#hdnPreGeneralDetailList2').val(generalDetails);
            $('#hdnPaypalNumber').val(contactPhone);
        }
        else if (paymentType == "stripe") {
            paymentDetails["PaymentType"] = "stripe";
            paymentDetails = JSON.stringify(paymentDetails);
            contactPhone = $("#txtPreStripeContactPhone").val();
            $('#hdnPreAddressList3').val(addressDetails);
            $('#hdnPrePaymentList3').val(paymentDetails);
            $('#hdnPreGeneralDetailList3').val(generalDetails);
            $('#hdnStripeNumber').val(contactPhone); 
            //alert("contact number" + contactPhone);
            
        }
        $('#submit-body-overlayId').addClass("d-block");
        $('#preorderLoaderId').removeClass("d-none").addClass("d-block");
        BMWUSADCMFloodlightPreorderPlaceOrderClickEvent();

        //if ($('#hdnPrePaymentList').val() == "") {
        //    return false;
        //}
        return true;
    }
    else {
        return false;
    }
}
function validatePreOrderExpiryDate() {
    isValidMonth = true;
    isValidYear = true;
    var expDate = $('#ddlPreExpiryYear').val();
    if ($('#ddlPreExpiryYear').val() == "") {
        return false;
    }
    else {
        var month = $('#ddlPreExpiryMonth').val();
        var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
        if (!numericReg.test(month)) {
            isValidMonth = false;
        }
        var year = $('#ddlPreExpiryYear').val()
        if (!numericReg.test(year)) {
            isValidYear = false;
        }
        if (isValidMonth && isValidYear) {
            var currentDate = new Date();
            var ptmonth = currentDate.getMonth();
            var val = 1;
            var presentmonth = ptmonth + val;
            var presentyear = currentDate.getFullYear();
            if (year == presentyear) {
                if (month < presentmonth) {
                    $("#ddlPreExpiryMonth").removeClass("RightInput");
                    $("#ddlPreExpiryMonth").addClass("InvalidSearch");
                    return false;
                }
                else {
                    $("#ddlPreExpiryMonth").removeClass("InvalidSearch");
                    $("#ddlPreExpiryMonth").addClass("RightInput");
                    return true;
                }
            }
            else if (year < presentyear) {
                $("#ddlPreExpiryYear").removeClass("RightInput");
                $("#ddlPreExpiryYear").addClass("InvalidSearch");
                return false;
            }
            else {
                $("#ddlPreExpiryYear").removeClass("InvalidSearch");
                $("#ddlPreExpiryYear").addClass("RightInput");
                $("#ddlPreExpiryMonth").removeClass("InvalidSearch");
                $("#ddlPreExpiryMonth").addClass("RightInput");
                return true;
            }
        }
        else {
            $("#ddlPreExpiryMonth").removeClass("RightInput");
            $("#ddlPreExpiryMonth").addClass("InvalidSearch");
            $("#ddlPreExpiryYear").removeClass("RightInput");
            $("#ddlPreExpiryYear").addClass("InvalidSearch");
            return false;
        }
    }
}
function changeExpiryDate() {
    var isValidExpDate = validatePreOrderExpiryDate();
}
//end preorder checkout

function preOrderFocus(event, idValue) { //ixi4preorder
    var keyValue = event.keyCode;
    var currentPage = "";
    currentPage = $('#hdnCurrentPage').val();
    if (keyValue == 9) {
        if (idValue == "preorderName") {
            if (!$("#dealerSearch").hasClass('active')) {//when dealer popup is not opened
                if (window.location.href.toUpperCase().indexOf('BMW-I7-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-IX-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-I4-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('BMW-8-X-JEFF-KOONS-PRE-ORDER') > 0 || window.location.href.toUpperCase().indexOf('/PREORDER/PREORDERWAITLIST') > 0 ) {
                    $('.IModel').find('h1:first').focus();
                }
                else if (currentPage != "" & currentPage.toLowerCase().includes("billing")) {
                    $('.DivUserInfo').find('h1:first').focus();
                }
                else if (currentPage != "" & currentPage.toLowerCase().includes("confirmation")) {
                    if ($('.iFeatureEndSecHead').find('h1:first').hasClass('d-none')) {
                        $('.iFeatureEndSecHead').find('h2:first').focus();
                    }
                    else {
                        $('.iFeatureEndSecHead').find('h1:first').focus();
                        $(".JKErrorHead").focus();
                    }
                    //$('.iDiscoverbtn').find('a:first').focus();
                }
                else {
                    $('.CountiFeatureEndSec').find('h1:first').focus();
                }
            }
            else if ($("#dealerSearch").hasClass('active')) {
                $("#flyoutDealer").focus();
            }
            event.preventDefault();
        }

    }
}

function selectPreModel(selectedModel) {
    if (!$("#" + selectedModel).hasClass("d-none")) {
        $("#" + selectedModel).addClass("d-none");
        if (selectedModel == 'i4model2') {
            $("#divi4model1").removeClass("d-none");
            $("#divi4model2").addClass("d-none");
            $(".i4model2").addClass("d-none");
            $(".i4model1").removeClass("d-none");
            $("#startModelPrice").html($("#hdnModelPrice1").val());
            $("#hModelName").html($("#hdnModelName1").val());
            $("#lblModelPrice").html($("#hdnModelPrice1").val());
            $("#divModelPrice").html($("#hdnModelPrice1").val());
            $('#hdnPreModel').val($("#hdnModelName1").val());
            $('#hdnPreModelPaypal').val($("#hdnModelName1").val());
            $('#hdnPreModelCard').val($("#hdnModelName1").val());

        }
        else if (selectedModel == 'i4model1') {
            $("#divi4model2").removeClass("d-none");
            $("#divi4model1").addClass("d-none");
            $(".i4model1").addClass("d-none");
            $(".i4model2").removeClass("d-none");
            $("#startModelPrice").html($("#hdnModelPrice2").val());
            $("#hModelName").html($("#hdnModelName2").val());
            $("#lblModelPrice").html($("#hdnModelPrice2").val());
            $("#divModelPrice").html($("#hdnModelPrice2").val());
            $('#hdnPreModel').val($("#hdnModelName2").val());
            $('#hdnPreModelPaypal').val($("#hdnModelName2").val());
            $('#hdnPreModelCard').val($("#hdnModelName2").val());

        }
    }
}
//function selectedModel() {
//    if ($(".iXSelModel").hasClass("iXModel1Hover")) {
//        $('#hdni4PreModel').val($(".iXModel1Hover div").text());
//    }
//}


function UpdateCountDownTimer() {
    //debugger;
    var now = getESTTime();
    // Find the difference between now and the count down date    
    var countDownEndDate = $("#hdnCountDownEnd").val();// 01-06-2021 06:00:00 AM 
    var stringDateFull = countDownEndDate.split(' ');
    var stringDate = stringDateFull[0].split('-');
    var countDownEndDateString = stringDate[1] + "/" + stringDate[0] + "/" + stringDate[2] + " " + stringDateFull[1] + " " + stringDateFull[2];//"06/01/2021 6:00:00";
    //alert(countDownEndDateString);
    var timeDifference = (new Date(countDownEndDateString).getTime()) - now;
    // Time calculations for days, hours, minutes and seconds      
    var days = Math.floor(timeDifference / (1000 * 60 * 60 * 24)).toString();
    var hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString();
    var minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60)).toString();
    var seconds = Math.floor((timeDifference % (1000 * 60)) / 1000).toString();
    // If the count down is over, write some text    
    days = days.length == 1 ? "0" + days : days;
    hours = hours.length == 1 ? "0" + hours : hours;
    minutes = minutes.length == 1 ? "0" + minutes : minutes;
    seconds = seconds.length == 1 ? "0" + seconds : seconds;
    var timerStart = days + ":" + hours + ":" + minutes + ":" + seconds;
    if (timerStart == "00:00:00:00" || timerStart.indexOf('-') >= 0) {
        setTimeout(function () {
            window.location.reload();
        });
    }
    initTimer(timerStart); // other ways --> "0:15" "03:5" "5:2"

}

var timerEl = document.querySelector('.timer');
function initTimer(t) {
    var self = this,
        timerEl = document.querySelector('.timer'),
        dayGroupEl = timerEl.querySelector('.days-group'),
        hrGroupEl = timerEl.querySelector('.hr-group'),
        minutesGroupEl = timerEl.querySelector('.minutes-group'),
        secondsGroupEl = timerEl.querySelector('.seconds-group'),
        hrGroup = {
            firstNum: hrGroupEl.querySelector('.first'),
            secondNum: hrGroupEl.querySelector('.second')
        },
        dayGroup = {
            firstNum: dayGroupEl.querySelector('.first'),
            secondNum: dayGroupEl.querySelector('.second')
        },
        minutesGroup = {
            firstNum: minutesGroupEl.querySelector('.first'),
            secondNum: minutesGroupEl.querySelector('.second')
        },

        secondsGroup = {
            firstNum: secondsGroupEl.querySelector('.first'),
            secondNum: secondsGroupEl.querySelector('.second')
        };

    var time = {
        day: t.split(':')[0],
        hr: t.split(':')[1],
        min: t.split(':')[2],
        sec: t.split(':')[3]
    };

    var timeNumbers;

    function updateTimer() {
        var timestr;
        var now = getESTTime();
        // Find the difference between now and the count down date    
        var countDownEndDate = $("#hdnCountDownEnd").val();// 01-06-2021 06:00:00 AM 
        var stringDateFull = countDownEndDate.split(' ');
        var stringDate = stringDateFull[0].split('-');
        var countDownEndDateString = stringDate[1] + "/" + stringDate[0] + "/" + stringDate[2] + " " + stringDateFull[1] + " " + stringDateFull[2];//"06/01/2021 6:00:00";
        var timeDifference = (new Date(countDownEndDateString).getTime()) - now;
        // Time calculations for days, hours, minutes and seconds      
        var days = Math.floor(timeDifference / (1000 * 60 * 60 * 24)).toString();
        var hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)).toString();
        var minutes = Math.floor((timeDifference % (1000 * 60 * 60)) / (1000 * 60)).toString();
        var seconds = Math.floor((timeDifference % (1000 * 60)) / 1000).toString();
        time.day = days.length == 1 ? "0" + days : days;
        time.hr = hours.length == 1 ? "0" + hours : hours;
        time.min = minutes.length == 1 ? "0" + minutes : minutes;
        time.sec = seconds.length == 1 ? "0" + seconds : seconds;
        timestr = time.day + time.hr + time.min + time.sec;
        timeNumbers = timestr.split('');
        updateTimerDisplay(timeNumbers);
        if (timestr == '00000000' || timestr.indexOf('-') >= 0) {
            setTimeout(function () {
                window.location.reload();
            });
        }
        else if (timestr != '00000000') {
            setTimeout(updateTimer, 1000);
        }

    }

    function updateTimerDisplay(arr) {
        animateNum(dayGroup.firstNum, arr[0]);
        animateNum(dayGroup.secondNum, arr[1]);
        animateNum(hrGroup.firstNum, arr[2]);
        animateNum(hrGroup.secondNum, arr[3]);
        animateNum(minutesGroup.firstNum, arr[4]);
        animateNum(minutesGroup.secondNum, arr[5]);
        animateNum(secondsGroup.firstNum, arr[6]);
        animateNum(secondsGroup.secondNum, arr[7]);

    }

    function animateNum(group, arrayValue) {
        TweenMax.killTweensOf(group.querySelector('.number-grp-wrp'));
        TweenMax.to(group.querySelector('.number-grp-wrp'), 1, {
            y: - group.querySelector('.num-' + arrayValue).offsetTop
        });
    }
    setTimeout(updateTimer, 1000);
}
function getESTTime() {
    var offset = new Date().getTimezoneOffset();// getting offset to make time in gmt+0 zone (UTC) (for gmt+5 offset comes as -300 minutes)
    var date = new Date();
    date.setMinutes(date.getMinutes() + offset);// date now in UTC time
    var easternTimeOffset = -300; //for dayLight saving, CST time become 5 hours behind UTC thats why its offset is -4x60 = -240 minutes. So when Day light is not active the offset will be -300
    date.setMinutes(date.getMinutes() + easternTimeOffset);
    return date.getTime();
}

function financeOptions(chkId) {
    if ($('input[type=checkbox][id^="' + chkId + '"]').prop("checked") == true) {
        $('input[type=checkbox][id^=chk]').each(function () {
            $(this).prop('checked', false);
        });
        $("#" + chkId).prop('checked', true);
    }
    else
        $("#" + chkId).prop('checked', false);
    var chck_label = $("#" + chkId).parent("label").text();
    if (chck_label.toLowerCase() == "financing" || chck_label.toLowerCase() === "finance") {
        chck_label = "Financing(APR)";
    }
    $('#hdnfinanceOption').val(chck_label);
    $('#hdnfinanceOption1').val(chck_label);
    $('#hdnfinanceOptionPaypal').val(chck_label);
    $('#hdnfinanceOptionAmazon').val(chck_label);
    $('#hdnfinanceOptionCard').val(chck_label)  
    $('#hdnfinanceOptionStripe').val(chck_label);
    // $('#hdnfinanceOption').val($("#" + chkId).parent("label").text());
    //$('input[name="financeOption"]').val(chck_label);
}
function preferredContactMethod(Id, parentId) {
    $('#' + parentId + ' input[type=radio][id^=radio_cm]').each(function () {
        $(this).prop('checked', false);
        $(this).val();
        });
    $("#" + parentId + " #" + Id).prop('checked', true);
    var radio_label = $("#" + parentId +" #" + Id).parent("label").text();
    $('#' + parentId + ' #' + Id).val(radio_label);

    var pMethod = parentId.replace("contactMethod", "");
    if (radio_label.toLowerCase() === "call" || radio_label.toLowerCase() === "text") {
        $("#divContactMethod" + pMethod).removeClass("d-none");
    }
    else {
        $("#divContactMethod" + pMethod).addClass("d-none");
        if ($("#divContactMethod" + pMethod).find().children("p").hasClass("invalidTerms")) {
            $("#divContactMethod" + pMethod).find().children("p").removeClass("invalidTerms");
        }
    }
}
function paymentSelectionGA() {

    if (window.location.href.toUpperCase().indexOf('BMW-IX-PRE-ORDER') > 0) {
        commonGA4Tracking('IX Preorder', 'Payment Selection - AZ', 'IX Preorder');
    }
    else if (window.location.href.toUpperCase().indexOf('BMW-I4-PRE-ORDER') > 0) {
        commonGA4Tracking('I4 Preorder', 'Payment Selection - AZ', 'I4 Preorder');
    }
    else if (window.location.href.toUpperCase().indexOf('BMW-I7-PRE-ORDER') > 0) {
        commonGA4Tracking('I7 Preorder', 'Payment Selection - AZ', 'I7 Preorder');
    }
}

function learnMore(event) {
    var keyValue = event.keyCode;
    if (keyValue == 13) {
        $("#FeaturesLink").click();
        event.preventDefault();
    }
}

function validateOnPaste(txtId) {
    var data = $('#' + txtId).val();
    if (txtId == "txtPreLastName" || txtId == "txtPreFirstName" || txtId == "txtPreCardName") {
        if (!isAllAlphabets(data)) {
            indicateInvalidData(txtId);
        }
    }
    else if (txtId == "txtPreEmail") {
        if (!validateEmail(data)) {
            indicateInvalidData(txtId);
        }
    }
    else if (txtId == "txtPrePhone") {
        if (!validatePhoneNumber(data)) {
            indicateInvalidData(txtId);
        }
    }
    else if (txtId == "txtPreCardNo") {
        data = data.replace(/\s/g, '');
        cardType = $('#hdnCardType').val();
        isCardNumberValid = $('#hdnCardNumberValid').val();
        isCardLengthValid = $('#hdnCardLengthValid').val();
        if (isCardNumberValid.toString() == "true" && isCardLengthValid.toString() == "true") {
            $('#' + txtId).val(data);
        }
        else {
            indicateInvalidData(txtId);
        }
    }
    else if (txtId == "txtPreSecCode") {
        data = data.replace(/\s/g, '');
        if ($.isNumeric(data)) {
            if (data.length <= 4) {
                $('#' + txtId).val(data);
            }
            else {
                indicateInvalidData(txtId);
            }
        }
        else {
            indicateInvalidData(txtId);
        }
    }
}
function indicateInvalidData(txtId) {
    $('#' + txtId).val("");
    $('#' + txtId).addClass("InvalidSearch");
    $('#' + txtId).removeClass("RightInput");
}

function BMWUSADCMFloodlightPreorderPlaceOrderClickEvent() {

    var IsFloodlightTurnOn = $("#hdnIsFloodlightTurnOn").val();
    if (window.location.href.toLowerCase().indexOf('preorder/preordercheckout') > 0 && IsFloodlightTurnOn !== undefined && IsFloodlightTurnOn !== null && IsFloodlightTurnOn === "true") {

        var body = document.getElementsByTagName('body')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.setAttribute('data-name', 'preorder-dcmfloodlight-placeorder');
        var radomno = Math.random() + "";
        var rand = radomno * 10000000000000000;
        var dataImg = "https://ad.doubleclick.net/ddm/activity/src=3864313;type=bmwus003;cat=bmwus01t;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;npa=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ord=" + rand + "?";
        var sendto = "DC-3864313/bmwus003/bmwus01t+standard";
        var comments = "<!-- Event snippet for BMWUSA|Brand|Checkout|Confirmation Page|Button Click|PlaceOrder on https://www.shopbmwusa.com/PreOrder/PreOrderCheckout: Please do not remove. Place this snippet on pages with events you're tracking. Creation date: 06/04/2021-->";
        var data = "";
        data += "gtag('event', 'conversion', { ";
        data += "'allow_custom_scripts': true, ";
        data += "'send_to': '" + sendto + "'";
        data += "}); ";
        var content = "";
        //content += "<noscript>";
        content += "<img src=" + dataImg + " width=\"1\" height=\"1\" alt=\"\"/> ";
        //content += "</noscript>";
        script.text = data;


        var noscript = document.createElement('noscript');
        $(noscript).text(content);
        body.insertBefore(noscript, body.firstElementChild);
        body.insertBefore(script, body.firstElementChild);

        //alert("dcm");

        /*var image = document.createElement('img');
        image.setAttribute('src', dataImg);
        image.setAttribute('width',1);
        image.setAttribute('height', 1);
        image.setAttribute('alt', '');
        body.insertBefore(image, body.firstElementChild);*/
        //body.insertBefore(script, body.firstElementChild);  



        //$("body script:first-child").next().attr("src", dataImg);
        $(comments).insertBefore("script [data-name='preorder-dcmfloodlight-placeorder']");
        //$(content).insertAfter("script [data-name='preorder-dcmfloodlight-placeorder']");
    }
}


function BMWUSADCMFloodlightPreorderCheckoutWithPaypalClickEvent() {

    var IsFloodlightTurnOn = $("#hdnIsFloodlightTurnOn").val();
    var PreOrderProdName = $("#hdnPreOrderProdName").val();
    if ((window.location.href.toLowerCase().indexOf('ix') > 0 || window.location.href.toLowerCase().indexOf('i4') > 0) && IsFloodlightTurnOn !== undefined && IsFloodlightTurnOn !== null && IsFloodlightTurnOn === "true" && PreOrderProdName !== undefined && PreOrderProdName !== null) {

        var body = document.getElementsByTagName('body')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.setAttribute('data-name', 'preorder-dcmfloodlight-placeorder');
        var radomno = Math.random() + "";
        var rand = radomno * 10000000000000000;


        var dataImg = "";
        var sendto = "";
        var comments = "";

        if (PreOrderProdName.toLowerCase().indexOf("ix") > 0) {
            dataImg = "https://ad.doubleclick.net/ddm/activity/src=3864313;type=bmwus003;cat=bmwus01s;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;npa=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ord=" + rand + "?";
            sendto = "DC-3864313/bmwus003/bmwus01s+standard";
            comments = "<!--Event snippet for BMWUSA|Brand|iX Pre - Order|Confirmation Page|Button Click|Checkout with PayPal on https://www.shopbmwusa.com/BMW-iX-PRE-ORDER: Please do not remove. Place this snippet on pages with events you're tracking.Creation date: 06/04/2021 -->";
        }
        else if (PreOrderProdName.toLowerCase().indexOf("i4") > 0) {
            dataImg = "https://ad.doubleclick.net/ddm/activity/src=3864313;type=bmwus003;cat=bmwus01r;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=;tfua=;npa=;gdpr=${GDPR};gdpr_consent=${GDPR_CONSENT_755};ord=" + rand + "?";
            sendto = "DC-3864313/bmwus003/bmwus01r+standard";
            comments = "<!--Event snippet for BMWUSA|Brand|i4 Pre - Order|Confirmation Page|Button Click|Checkout with PayPal on https://www.shopbmwusa.com/BMW-i4-PRE-ORDER: Please do not remove. Place this snippet on pages with events you're tracking.Creation date: 06/04/2021 -->";
        }


        var data = "";
        data += "gtag('event', 'conversion', { ";
        data += "'allow_custom_scripts': true, ";
        data += "'send_to': '" + sendto + "'";
        data += "}); ";
        script.text = data;

        var content = "";
        //content += "<noscript>";
        content += "<img src=" + dataImg + " width=\"1\" height=\"1\" alt=\"\"/> ";
        //content += "</noscript>";

        var noscript = document.createElement('noscript');
        $(noscript).text(content);
        body.insertBefore(noscript, body.firstElementChild);
        body.insertBefore(script, body.firstElementChild);

        //$("body script:first-child").text(data).next().attr("src", dataImg);

        $(comments).insertBefore("script [data-name='preorder-dcmfloodlight-placeorder']");
        //$(content).insertAfter("script [data-name='preorder-dcmfloodlight-placeorder']");

        //alert("dcm");
    }
}

function bindPreStripeCardElement() {
    // Create a Stripe client.
    var pubKey = document.getElementById('hdnPubKey').value;
    var accountId = document.getElementById('hdnAccountId').value;
    stripeCheckout = Stripe(pubKey, {
        stripeAccount: accountId
    });
    // Create an instance of Elements.
    var elements = stripeCheckout.elements();

    // Custom styling can be passed to options when creating an Element.
    // (Note that this demo uses a wider set of styles than the guide below.)
    var style = {
        base: {
            color: '#32325d',
            fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
            fontSmoothing: 'antialiased',
            fontSize: '16px',
            '::placeholder': {
                color: '#aab7c4'
            }
        },
        invalid: {
            color: '#fa755a',
            iconColor: '#fa755a'
        }
    };

    // Create an instance of the card Element.
    stripeCard = elements.create('card', { style: style });

    // Add an instance of the card Element into the `card-element` <div>.
    stripeCard.mount('#card-element');
    // Handle real-time validation errors from the card Element.
    stripeCard.on('change', function (event) {
        var displayError = document.getElementById('card-errors');
        if (event.error) {
            displayError.textContent = event.error.message;
        } else {
            displayError.textContent = '';
        }
    });
}
function stripeTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var form = document.getElementById('payment-form');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);

    // Submit the form
    form.submit();
}
//start - CreditCard Validations
//function validateStripeCard() {
//    if ($('#card-element').hasClass('StripeElement--invalid')) {
//        return true;
//    }
//    else {
//        return false;
//    }
//}


function LinkClickDTMPixelTracking(event, buttonText, link = null) {

    if (link != null)
        event.preventDefault();
    var preorder = $("#hdnPreorderName").val();
    if (preorder.toLowerCase().indexOf("i7") > -1) {
        BMWevent.push({
            "event": "linkClick",
            "link": {
                "name": buttonText,
                "type": "button"
            }
        });

        if (link != null)
            window.open(link, "_blank");
    }
}

function FinanceOptionandFAQModelDTMPixelTracking(modelName) {

    //modelName = financeoptions ||faqs
    var preorder = $("#hdnPreorderName").val();
    if (preorder.toLowerCase().indexOf("i7") > -1) {


        if (dealerInfo !== null && dealerInfo !== undefined) {
            BMWevent.push({
                "event": "pageChange",
                "page": {
                    "name": "shopbmwusa:product:The BMW i7 pre-order:" + modelName,
                    "url": window.location.href
                },
                "process": {
                    "name": "shopbmw i7 pre-order",
                    "status": "no data layer value"
                },
                "dealer": {
                    "address": dealerInfo["Address"],
                    "centerID": dealerInfo["CenterId"],
                    "city": dealerInfo["City"],
                    "name": dealerInfo["Name"],
                    "phone": dealerInfo["Phone"],
                    "state": dealerInfo["State"],
                    "url": dealerInfo["Url"],
                    "zipCode": dealerInfo["Zipcode"]
                }
            });
        }
        else {
            BMWevent.push({
                "event": "pageChange",
                "page": {
                    "name": "shopbmwusa:product:The BMW i7 pre-order:" + modelName,
                    "url": window.location.href
                },
                "process": {
                    "name": "shopbmw i7 pre-order",
                    "status": "no data layer value"
                },
                "dealer": {
                    "address": "",
                    "centerID": "",
                    "city": "",
                    "name": "",
                    "phone": "",
                    "state": "",
                    "url": "",
                    "zipCode": ""
                }
            });
        }


        //BMWevent.push({
        //    "event": "pageChange",
        //    "page": {
        //        "name": "shopbmwusa:product:The BMW i7 pre-order:" + modelName,
        //        "url": '"' + window.location.href.toUpperCase() + '"'
        //    },
        //    "process": {
        //        "name": "shopbmw i7 pre-order",
        //        "status": "no data layer value"
        //    },
        //    "dealer": {
        //        "address": '"' + dealerInfo["Address"] +'"',
        //        "centerID": '"' + dealerInfo["CenterId"] + '"',
        //        "city": '"' + dealerInfo["City"] + '"',
        //        "name": '"' + dealerInfo["Name"] + '"',
        //        "phone": '"' + dealerInfo["Phone"] + '"',
        //        "state": '"' + dealerInfo["State"] + '"',
        //        "url": '"' + dealerInfo["Url"] + '"',
        //        "zipCode": '"' + dealerInfo["Zipcode"] + '"'
        //    }
        //});
    }
}

//braintree
//var nonce = document.querySelector('#brainPretreeNonce');
var noncePreOrderBraintree = false;
function bindPreOrderBraintreeCardElement() {
    braintree.client.create(
        { authorization: hdnPreOrderBrainTreeClientToken.value },
        function (clientError, clientInstance) {
            if (clientError) {
                console.error(clientError);
                return;
            }

            braintree.hostedFields.create({
                client: clientInstance,
                styles: {
                    'input': {
                        'font-size': '14px',
                        'margin-left': '10px'
                    },
                    'input.invalid': {
                        'color': 'red'
                    },
                    'input.valid': {
                        'color': ''
                    }
                },
                fields: {
                    number: {
                        selector: '#card-number',
                        placeholder: 'Card Number'
                    },
                    cvv: {
                        selector: '#cvv',
                        placeholder: 'CVV'
                    },
                    expirationDate: {
                        selector: '#expiration-date',
                        placeholder: 'Expiration Date'
                    }
                }
            }, function (hostedFieldsError, hostedFieldsInstance) {
                if (hostedFieldsError) {
                    console.error(hostedFieldsError);
                    return;
                }
                //submitButton.removeAttribute('disabled');
                placeOrder.addEventListener('click', function (event) {
                    //event.preventDefault();
                    hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
                        if (tokenizeErr) {
                            console.error(tokenizeErr);
                            return;
                        }
                        braintreePreOrderNonce.value = payload.nonce;
                        noncePreOrderBraintree = true;
                        validatePreOrderPaymentOption("creditcard");
                        $("#frmSubmitPreorder").submit();
                        
                        //form.submit();
                    });
                }, false);
            });
        });
}

function bindBraintreePreOrderPaypalElement() {
    $("#frmPaypalPreorder").addClass("d-none");
    var priceAmt = parseFloat($("#spnPrice").html().replace('$', ''));

    braintree.client.create({
        authorization: hdnPreOrderBrainTreeClientToken.value
    },
        function (clientErr, clientInstance) {
            //console.error(clientInstance);
            // Stop if there was a problem creating the client.
            // This could happen if there is a network error or if the authorization
            // is invalid.
            if (clientErr) {
                console.error('Error creating client:', clientErr);
                return;
            }

            // Create a PayPal Checkout component.
            braintree.paypalCheckout.create({
                client: clientInstance
            }, function (paypalCheckoutErr, paypalCheckoutInstance) {
                if (paypalCheckoutInstance != undefined) {// braintree missing paypal account link
                    paypalCheckoutInstance.loadPayPalSDK({

                        currency: 'USD',
                        intent: 'authorize'
                    }, function () {
                        //console.error('paypal.Buttons');
                        paypal.Buttons({
                            style: {
                                color: 'white',
                                shape: 'rect',
                                label: 'pay',//label: 'checkout',
                                height: 50
                            },
                            fundingSource: paypal.FUNDING.PAYPAL,

                            createOrder: function () {
                                //console.log('PayPal paypalCheckoutInstance');
                                return paypalCheckoutInstance.createPayment({

                                    flow: 'checkout', // Required
                                    amount: priceAmt, // Required
                                    currency: 'USD', // Required, must match the currency passed in with loadPayPalSDK

                                    intent: 'authorize', // Must match the intent passed in with loadPayPalSDK

                                    enableShippingAddress: true,
                                    enableBillingAddress: true,
                                    shippingAddressEditable: false

                                });

                            },

                            onApprove: function (data, actions) {
                                return paypalCheckoutInstance.tokenizePayment(data, function (err, payload) {
                                    paypalBraintreePreNonce.value = payload.nonce;
                                    braintreepaypalPreAddressfetching(payload.details);
                                    if ($('#hdnAddressListBraintree').val() == "") {
                                        return false;
                                    }

                                    $("#frmPaypalBraintreePreorder").submit();
                                    //Submit `payload.nonce` to your server
                                });
                            },

                            onCancel: function (data) {
                                console.log('PayPal payment cancelled', JSON.stringify(data, 0, 2));
                            },

                            onError: function (err) {
                                console.error('PayPal error', err);
                            }
                        }).render('#braintree-paypal-preorder-button').then(function () {

                            //console.error('#paypal-button');
                            // The PayPal button will be rendered in an html element with the ID
                            // `paypal-button`. This function will be called when the PayPal button
                            // is set up and ready to be used
                        });

                    });
                }
                else {
                    $("#frmPaypalPreorder").removeClass("d-none");
                    $("#frmPaypalBraintreePreorder").addClass("d-none");
                }

            });
        });
}

function braintreepaypalPreAddressfetching(shipAddress) {
    var addressDetails = {};
    //{ "email": "binup_1361514395_per@realityi.com", "firstName": "Binu", "lastName": "Paul", "payerId": "TA8CG3X2QWJ74", "shippingAddress": { "recipientName": "Binu Paul", "line1": "1 Main St", "city": "San Jose", "state": "CA", "postalCode": "95131", "countryCode": "US" }, "countryCode": "US" }

    addressDetails['FirstName'] = shipAddress.firstName;
    addressDetails['LastName'] = shipAddress.lastName;
    addressDetails['Email'] = shipAddress.email;

    var shippingaddress = shipAddress.shippingAddress;

    addressDetails['StrtAddress'] = shippingaddress.line1;
    addressDetails['City'] = shippingaddress.city;
    addressDetails['State'] = shippingaddress.state;
    addressDetails['ZipCode'] = shippingaddress.postalCode;
    addressDetails['Country'] = shippingaddress.countryCode;

    addressDetails = JSON.stringify(addressDetails);
    
    $('#hdnAddressListBraintree').val(addressDetails);
    if ($('#hdnAddressListBraintree').val() == "") {
        return false;
    }
}
;
