/**
	@ Author: ser
*/
(function($) {
    $.fn.subMenu = function(options) {
        var hoverIntentConfig = {
            sensitivity: 200,
            interval: 200,
            over: slideDown,
            timeout: 500,
            out: slideUp
        };
        var obj = $(this);
        /*var mCount = (obj.children('ul').children('li').length + 1) / 2;
        var itemWidth = (obj.width() - obj.children('ul').width()) / mCount;
        obj.children('ul').children('li').not('.separator').each(function() {
        var curWidth = $(this).width();
        $(this).css('width', itemWidth + curWidth);
        });*/

        var sub = obj.children('ul').children('li').children('ul');
        /*var subHeight = sub.children('li').children('a').innerHeight();
        obj.css('padding-bottom', subHeight);*/


        var subWidth;
        sub.each(function(i) {
            subWidth = getWidth($(this));
            $(this).css('width', subWidth);
            var left = $(this).parent().offset().left - $(this).parent().parent().offset().left;
            var end = left + subWidth;
            if (end > $(this).parent().parent().parent().width() && left > $(this).parent().parent().parent().width() / 2) {
                var pos = 0 - subWidth + $(this).parent().outerWidth();
                $(this).css('left', pos);
            }
        });

        obj.children('ul').children('li').find('ul').hide();

        obj.children('ul').children('li:has(ul > li)').hoverIntent(hoverIntentConfig);

        function getWidth(subMenu) {
            var w = 0;
            subMenu.find('li').each(function() {
                w += $(this).outerWidth();
            })
            var curW;
            var left = subMenu.parent().offset().left - subMenu.parent().parent().offset().left;
            if (left > subMenu.parent().parent().parent().width() / 2) {
                curW = left + subMenu.find('li').width();
            } else {
                curW = subMenu.parent().parent().parent().width() - left;
            }

            if (w > curW) w = curW;
            return w;
        }

        function slideDown() {
            $(this).find('ul').css('visibility', 'visible');
            $(this).find('ul').slideDown('fast');
        }

        function slideUp() {
            $(this).find('ul').slideUp('fast');
        }

        function heightFix() {
            if ($('.all_page').height() < $('body').height()) $('.all_page').css('height', $('body').height());
        }
        heightFix();

    }
})(jQuery);
