﻿$(document).ready(function ($) {
    var $mainMenu = $(".menu>ul");
    var $headers = $mainMenu.find("ul").parent();
    $headers.each(function (i) {
        var $objCurrent = $(this);
        var $subUl = $(this).find('ul:eq(0)');
        this._dimensions = { w: this.offsetWidth, h: this.offsetHeight, subulw: $subUl.outerWidth(), subulh: $subUl.outerHeight() }
        this.isTopHeader = $objCurrent.parents("ul").length == 1 ? true : false;
        $subUl.css({ top: this.isTopHeader ? this._dimensions.h + "px" : 0 });
        $objCurrent.children("a:eq(0)").css(this.isTopHeader ? { paddingRight: 25} : {}).append('<img src="' + (this.isTopHeader ? 'images/down.gif' : 'images/right.gif') + '" class="' + (this.isTopHeader ? 'darrow' : 'rarrow') + '" style="border:0;" />');
        $objCurrent.hover(function (e) {
            var $targetUl = $(this).children("ul:eq(0)");
            this._offsets = { left: $(this).offset().left, top: $(this).offset().top }
            var menuLeft = this.isTopHeader ? 0 : this._dimensions.w;
            menuLeft = (this._offsets.left + menuLeft + this._dimensions.subulw > $(window).width()) ? (this.isTopHeader ? -this._dimensions.subulw + this._dimensions.w : -this._dimensions.w) : menuLeft;
            if ($targetUl.queue().length <= 1) { $targetUl.css({ left: menuLeft + "px", width: this._dimensions.subulw + 'px' }).slideDown(100); }
        }, function (e) {
            var $targetUl = $(this).children("ul:eq(0)");
            $targetUl.slideUp(100);
        });
    });
    $mainMenu.find("ul").css({ display: 'none', visibility: 'visible' });
});
