$(function () {

    // Place Megamenu
    function placeDropdown(menuitem, dropdown) {
        $("#nav li." + menuitem + " a").addClass("hover");
        // Get a position reference
        var pos = $("#nav li").offset();
        var mheight = $("#nav li." + menuitem).height();
        // Place the menu acording to the reference
        $("." + dropdown).css({ "left": "auto", "right": (pos.left - 400) + "px", "top": (pos.top + mheight) + "px" });
    }

    function hideDropdown(menuitem, dropdown) {
        $("." + dropdown).css({ "left": -9999 + "px", "right": "auto" });
        $("#nav li." + menuitem + " a").removeClass("hover");
    }

    // Support for iPhone, iPod and iPad
    if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
        $("#nav li.products a").click(function (e) {
            e.preventDefault();
            if ($(".megamenu").css("left") == "-9999px") {
                placeDropdown('products', 'megamenu.products');
            }
            else {
                hideDropdown('products', 'megamenu.products');
            }
        });
    }
    else {

        $(".megamenu.products, #nav li.products a").hover(function () {
            placeDropdown('products', 'megamenu.products');
        }, function () {
            hideDropdown('products', 'megamenu.products');
        });


        $(".megamenu.brands, #nav li.brands a").hover(function () {
            placeDropdown('brands', 'megamenu.brands');
        }, function () {
            hideDropdown('brands', 'megamenu.brands');
        });
    }
});
