﻿jQuery(document).ready(function ($) {

    var openMenu;

    function OpenMenu(e, obj) {
        e.preventDefault();

        // Close any open windows if not the current
        CloseMenu(openMenu);

        obj.addClass("open");
        openMenu = obj.find("div.sub-menu");
        openMenu.stop().fadeTo('fast', 1).show(); //Find sub and fade it in
        (function ($) {
            //Function to calculate total width of all ul's
            jQuery.fn.calcSubWidth = function () {
                rowWidth = 0;
                //Calculate row
                $(this).find("ul").each(function () { //for each ul...
                    rowWidth += $(this).width(); //Add each ul's width together
                });
            };
        })(jQuery);

        if (obj.find(".row").length > 0) { //If row exists...

            var biggestRow = 0;

            obj.find(".row").each(function () {	//for each row...
                obj.calcSubWidth(); //Call function to calculate width of all ul's
                //Find biggest row
                if (rowWidth > biggestRow) {
                    biggestRow = rowWidth;
                }
            });

            if (biggestRow > 800) biggestRow = 800;

            obj.find("div.sub-menu").css({ 'width': biggestRow }); //Set width
            obj.find(".row:last").css({ 'margin': '0' });  //Kill last row's margin
        } else if (obj.find(".column").length > 0) {

            var rowWidth = 0;

            obj.find(".column").each(function () { //for each column...
                rowWidth += $(this).width(); //Add each column together
            });

            if (rowWidth > 800) rowWidth = 800; //Max 800 width;
            obj.find("div.sub-menu").css({ 'width': rowWidth }); //Set width

        } else { //If row or column does not exist...

            obj.calcSubWidth();  //Call function to calculate width of all ul's

            if (rowWidth > 800) rowWidth = 800;
            obj.find("div.sub-menu").css({ 'width': rowWidth }); //Set Width

        }

        obj.unbind('click');

        return false;
    }

    function CloseMenu(obj) {
        if (obj) {
            obj.stop().fadeTo('fast', 0, function () { //Fade to 0 opactiy
                obj.hide();  //after fading, hide it
            });

            obj.parent().removeClass("open");

            obj.parent().click(function (e) {
                return OpenMenu(e, $(this));
            });
        }
    }

    $("ul#topMenu li.parent-menu").click(function (e) {
        return OpenMenu(e, $(this));
    });

    $("body").click(function (e) {
        CloseMenu(openMenu);
    });

    $("ul#topMenu li div.sub-menu").css({ 'opacity': '0' }); //Fade sub nav to 0 opacity on default

});
