﻿$(document).ready(function ()
{
    if (Modernizr.touch)
    {
        var lastCLicked = null;

        /******************************************************************************************************************
        *  Remove the href from the topitems to prevent click navigation, but keep the value for later use                *
        ******************************************************************************************************************/
        $("a.TopItem").each(function (index) { if ($(this).siblings().length >= 1) { $(this).attr("name", $(this).attr("href")); } });
        $("a.TopItem").each(function (index) { if ($(this).siblings().length >= 1) { $(this).removeAttr("href"); } });


        /******************************************************************************************************************
        *  Add the hover functionality to show and hide the sub-menu items                                                *
        ******************************************************************************************************************/
        $("a.TopItem").closest("li").hover(
        function (event)
        {
            $(this).children(".SubMenuItemsShadow, .SubMenuModelItemsShadow").css("display", "block").bgiframe();
        },
        function (event)
        {
            $(this).children(".SubMenuItemsShadow, .SubMenuModelItemsShadow").css("display", "none");
            lastCLicked = null;
        });



        $('.SubMenuModelItemsShadow:not("a, li")').click(function (event) { event.PreventDefault(); });


        /******************************************************************************************************************
        *  Add the click logic to the topitems so the link will only navigate if this is the second click                 *
        ******************************************************************************************************************/
        $("a.TopItem").click(function ()
        {
            if (lastCLicked != null && $(this).html() == lastCLicked.html())
            {
                window.location.href = $(this).attr("name");
            }

            lastCLicked = $(this);
        });

        $(".popupShadow").closest("li").children("a").click(function (event)
        {
            event.preventDefault();
        });

    }
    else
    {
        /******************************************************************************************************************
        *  Configure the hoverIntent plugin options                                                                       *
        ******************************************************************************************************************/
        var config = {
            sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
            interval: 150, // number = milliseconds for onMouseOver polling interval
            over: function () { $(this).children(".SubMenuItemsShadow, .SubMenuModelItemsShadow").fadeIn("fast").bgiframe(); $("select").trigger('blur'); },
            timeout: 100, // number = milliseconds delay before onMouseOut
            out: function () { $(this).children(".SubMenuItemsShadow, .SubMenuModelItemsShadow").hide(); }
        };


        /******************************************************************************************************************
        *  Wire the hoverIntent plugin to the top level (always visible) menu items                                       *
        ******************************************************************************************************************/
        $(".TopItem").parent().hoverIntent(config);
    }


    /******************************************************************************************************************
    *  Apply the menu highlighting logic                                                                              *
    ******************************************************************************************************************/
    $(function ($)
    {
        var path = location.pathname.substring(1).toLowerCase();
        if (path.lastIndexOf("/") == path.length - 1)
        {
            path = path + "default.aspx";
        }

        var current;
        if (path == "default.aspx")
        {
            current = $('#Menu a[href="/' + path + '"]');
        }
        else
        {
            if (path.indexOf("byohome.aspx") > 0)
            {
                current = $('#Menu a[href$="standard/content/byo/default.aspx"]');
            }
            else if ((path.indexOf("testdrive.aspx") > 0) || ((path.indexOf("allbmws/compare") > 0)) || ((path.indexOf("leaseoffers.aspx") > 0)) || ((path.indexOf("/financingoffer/") > 0)))
            {
                current = $('#Menu a[href$="' + path + '"]');
            }
            else
            {
                current = $('#Menu a[href*="' + path + '"]');
            }
        }

        current.addClass("selectMenuItem");
        current.closest('.SubMenuModelItemsShadow').prev("a").addClass("selectMenuItem");
        current.closest('.SubMenuItemsShadow').prev("a").addClass("selectMenuItem");
    });


    /******************************************************************************************************************
    *  Apply highlighting to the current menu item as we hover over it, or one of the child objects                   *
    ******************************************************************************************************************/
    $("a.TopSubMenu").siblings().hover(
        function ()
        {
            $(this).closest("li").children(".TopSubMenu").addClass("highlightMenuItem");
        },
        function ()
        {
            $(this).closest("li").children(".TopSubMenu").removeClass("highlightMenuItem");
        });


    /******************************************************************************************************************
    *  Position the menu layout for the last item (to ensure it does not exceed the right-hand boundary)                *
    ******************************************************************************************************************/
    $("#MenuTop .MenuLast").hover(function ()
    {
        var startItem = $(this).siblings().eq(0);
        var startItemWidth = startItem.width();
        var parentPosWidth = startItem.parent().width();
        var leftAdjust = "-" + ((startItemWidth - parentPosWidth) - 5) + "px";
        startItem.css("left", leftAdjust)
    });


    /******************************************************************************************************************
    *  Position the menu layout for the non-vehicle menus with sub-groups (".WideContainer")                            *
    ******************************************************************************************************************/
    $(".WideContainer").closest("li").children(".TopSubMenu").hover(function ()
    {
        var parentPosLeft = $(this).parent().offset().left;
        var firstItemlOffset = $(".mainRow li").eq(0).offset().left + 3;
        var leftAdjust = "-" + (parentPosLeft - firstItemlOffset) + "px";
        $(this).next().css("left", leftAdjust);
    });


    /******************************************************************************************************************
    *  handle the click event for the search button                                                                   *
    ******************************************************************************************************************/
    $("#imgSearchButton").click(function ()
    {
        var url = $("#searchUrl").attr("value");
        var query = $("#tbSearch").attr("value");
        var search = url + query;
        document.location = search;
    });


    /******************************************************************************************************************
    *  Mozilla specific layout corrections for the search text-box                                                    *
    ******************************************************************************************************************/
    if ($.browser.mozilla)
    {
        $("#tbSearch").css("padding-top", "2px");

        var isOnMac = navigator.userAgent.toLowerCase().indexOf("macintosh") > 0 ? true : false;

        if (isOnMac)
        {
            $("#tbSearch").css("padding-top", "3px");
            $("#tbSearch").css("height", "12px");
        }
    }


    /******************************************************************************************************************
    *  Handle the search text-box focus event (remove the "search" text)                                              *
    ******************************************************************************************************************/
    $("#tbSearch").focus(function ()
    {
        if ($(this).val() == "Search")
        {
            $(this).val("");
        }
    });


    /******************************************************************************************************************
    *  Handle the search text-box blur event (re-add the "search" text if no value was entered)                       *
    ******************************************************************************************************************/
    $("#tbSearch").blur(function ()
    {
        if ($(this).val() == "")
        {
            $(this).val("Search");
        }
    });


    /******************************************************************************************************************
    *  Handle the enter key within the search text-box                                                                *
    ******************************************************************************************************************/
    $("#tbSearch").keydown(function (e)
    {
        var event;
        var key;
        event = (e) ? e : window.event;

        if (event)
        {
            key = (event.charCode) ? event.charCode : (event.keyCode) ? event.keyCode : 0;
        }

        if (key && key == 13)
        {
            event.preventDefault();
            var url = $("#searchUrl").attr("value");
            var query = $(this).attr("value");
            var search = url + query;
            window.location = search;
        }
    });


    /******************************************************************************************************************
    *  Add the divide image for vehicles if there is a shopping items entry                                           *
    ******************************************************************************************************************/
    $("a.Vehicle:not(:contains('All BMW'))").hover(function ()
    {
        var siblings = $(this).siblings(".SubMenuModelItemsShadow");
        if (!$("#shoppingDivide", siblings).length)
        {
            $("ul:contains('Shopping')", siblings).before("<img src=\"https://cache.bmwusa.com/image_079a59df-be66-47c1-b4d5-c0dd0da3628f.arox\" id=\"shoppingDivide\" alt=\"\" style=\"float: left; display: inline-block; margin: 0px 10px 0px 0px; padding: 0px; width: 1px; overflow: hidden;\" />");
        }
    });


    /******************************************************************************************************************
    *  Display and position the model info menu sub-section                                                           *
    ******************************************************************************************************************/
    $(".mainRow li").hover(function ()
    {
        if ($(this).children("a.Vehicle:not(:contains('All BMW'))").length > 0)
        {
            var hrLeft = $("#hr").offset().left;
            var parentLeft = $(this).children("a.Vehicle:not(:contains('All BMW'))").parent().offset().left;
            var offsetAdjustment = 4;
            var newLeft = -((parentLeft - hrLeft) - offsetAdjustment);

            $(this).children("a.Vehicle:not(:contains('All BMW'))").next().css("left", newLeft);
        }
    });


    /******************************************************************************************************************
    *  Display and position the model info menu items on hover, also assign the model image                           *
    ******************************************************************************************************************/
    var seriesBottomItem;
    var seriesBottomItemHtml;

    $("#Menu li .modelSubMenuTop ul li").hover(function ()
    {
        seriesBottomItem = $(this).closest(".modelSubMenuTop").siblings(".modelSubMenuBottom");
        seriesBottomItemHtml = seriesBottomItem.html();

        var itemToMove = $(this).children(".modelSubMenuBottom");
        if (itemToMove.length)
        {
            var defaultEmpty = "http://cache.bmwusa.com/image_d5cf7777-efd4-4294-84aa-397cbefe220e.arox";
            var imageNa = "http://cache.bmwusa.com/image_0e52178e-2f6e-4ca8-884d-f295b7c298ca.arox";

            var src = $("img.modelImage", this).attr("src");
            var alt = $("img.modelImage", this).attr("alt");

            if (alt.length)
            {
                if (src.toLowerCase().indexOf("image_6256c981-6f02-4006-bf23-5868c0fb613c.arox") > 0 && (alt.toLowerCase().indexOf("brand=wbbm") > 0 || alt.toLowerCase().indexOf("image_") > 0))
                {
                    $("img.modelImage", this).attr("src", alt);
                    $("img.modelImage", this).attr("alt", "");
                }
                else
                {
                    $("img.modelImage", this).attr("src", imageNa);
                }
            }

            seriesBottomItem.html(itemToMove.html());
        }
    },
    function ()
    {
        seriesBottomItem = $(this).closest(".modelSubMenuTop").siblings(".modelSubMenuBottom");
        seriesBottomItem.html(seriesBottomItemHtml);
    });


    /******************************************************************************************************************
    *  Display and position the pop-up menu items on hover                                                            *
    ******************************************************************************************************************/
    $(".popupShadow").closest("li").hover(
    function ()
    {
        var ruleLimiter = $(this).closest(".SubMenuModelItemsContainer").children(".hr");
        var ruleLimiterTop = ruleLimiter.offset().top;

        var popUpShadow = $(this).children(".popupShadow");
        var popUpShadowTop = popUpShadow.offset().top;
        var popUpShadowHeight = popUpShadow.outerHeight();

        if ($.browser.msie && $.browser.version < 8)
        {
            popUpShadowTop = ($(this).offset().top) - 10;
        }

        var popUpBase = popUpShadowTop + popUpShadowHeight;

        var linkWidth = $(this).children("a").outerWidth() + 10;

        //console.info("PopUp offset.top: %d", popUpShadowTop);
        //console.info("PopUp base: %d", popUpBase);

        if (!popUpShadow.is('.o'))
        {
            if (popUpBase > ruleLimiterTop)
            {
                var topAdjust = popUpBase - ruleLimiterTop + 8;
                popUpShadow.css("top", -topAdjust);
                popUpShadow.addClass("o");

                var notch = $(".popupMenu img", this);
                var notch = notch.css("top", topAdjust + 5);

                //console.warn("Breach: %d over", topAdjust);
            }
        }

        popUpShadow.css("left", linkWidth + "px");
    });


    /******************************************************************************************************************
    *  Tracking logic - triggered by click events                                                                     *
    ******************************************************************************************************************/
    $("#Menu a").click(function ()
    {
        var trackingName = "TopNav-";
        if ($(this).closest("a.TopItem").length)
        {
            trackingName += $(this).closest("a.TopItem").html() + "-" + $(this).html();
        }
        else if ($(this).closest(".SubMenuItemsShadow").length)
        {
            trackingName += $(this).closest(".SubMenuItemsShadow").prev("a.TopItem").html() + "-" + $(this).html();
        }
        else if ($(this).closest(".SubMenuModelItemsShadow").length)
        {
            trackingName += $(this).closest(".SubMenuModelItemsShadow").prev("a.TopItem").html() + "-" + $(this).closest("li").children().eq(0).html() + "-" + $(this).html();
        }
        else
        {
            trackingName += "Uncaught parent in jQuery";
        }
        trackingName = trackingName.replace("&amp;", "and");
        trackingName = trackingName.replace("™", "");

        var accountName = "bmwdev";
        if (document.location.href.indexOf("//www.bmwusa.com") > 0)
        {
            accountName = "bmwprod";
        }
        var s = s_gi(accountName);
        s.tl(this, 'o', trackingName);
    });


    /******************************************************************************************************************
    *  Replace mangled characters in the menu items                                                                   *
    ******************************************************************************************************************/
    $("#Menu .SubMenuItemsContainer a").each(function ()
    {
        var newValue = $(this).html().replace("â„¢", "&trade;");
        newValue = newValue.replace("Â®", "&reg;");
        newValue = newValue.replace("Â ", "");
        $(this).html(newValue);
    });


    /******************************************************************************************************************
    *  Pre-cache vahicle images once the whole window has loaded                                                      *
    ******************************************************************************************************************/
    $(window).load(function ()
    {
        $("#TopNavNew img").each(function ()
        {
            if ($(this).attr("alt").length && $(this).attr("alt").toLowerCase().indexOf(".arox") > 0)
            {
                var newImage2 = new Image();
                newImage2.src = $(this).attr("alt");
                $("#modelPreLoad").append(newImage2);
            }
        });
    });
});


