

$.fn.menu = function(options){
    var m = new Menu(this, options);
    
    $(this).hover(
        function(){
            m.showMenu();
        }
        ,
        function(){
            m.hideMenu();
        }
        );
}

var Menu = function(container, options) {
    var menu = this;
    var exists = false; //Define if the menu exists or not (If the HTML is created)
    var container = $(container);
    var options = jQuery.extend({
        items : null,
        offset : {
            top : 0
        }
    }, options);
    this.showMenu = function() {        
        if (!menu.exists) {
            menu.createMenuHTML();
        }
        $('.r-menu-submenu.' + container.attr('id')).hide().slideDown(200);
    }

    this.hideMenu = function() {
        $('.r-menu-submenu.' + container.attr('id')).stop(true, true).hide();
        exists = false;
    }
    
    this.createMenuHTML = function() {
        
        var dimensions = {
            top : container.offset().top,
            left : container.offset().left,
            height : container.getTotalHeight()
        }
        
        var submenuHTML = $('<div class="r-menu-submenu ' + container.attr('id') + '"><ul></ul></div>');
        submenuHTML.css({
            'position'    : 'absolute',
            'top'         : dimensions.top + dimensions.height,
            'left'        : dimensions.left,
            'width'       : 'auto',
            'height'      : 'auto'
        });
        container.append(submenuHTML.append(submenuHTML.find('ul').append($(options.items).html())));
        menu.exists = true;
    }
}


/*
 * Utilities to get the Total height and width of an element. This code has been copied from
 * Filamen Group jQuery menu and modified by Rainit Vildo
 *
 */
jQuery.fn.getTotalWidth = function(){
    return $(this).width() + parseInt($(this).css('paddingRight')) + parseInt($(this).css('paddingLeft')) + parseInt($(this).css('borderRightWidth')) + parseInt($(this).css('borderLeftWidth'));
};

jQuery.fn.getTotalHeight = function(){
    var height = $(this).height();
    var paddingTop = parseInt($(this).css('paddingTop'));
    var paddingBottom = parseInt($(this).css('paddingBottom'));
    var borderTopWidth = parseInt($(this).css('borderTopWidth'));
    var borderBottomWidth = parseInt($(this).css('borderBottomWidth'));
    if (isNaN(height)) {
        height = 0;
    }
    if (isNaN(paddingTop)) {
        paddingTop = 0;
    }
    if (isNaN(paddingBottom)) {
        paddingBottom = 0;
    }
    if (isNaN(borderTopWidth)) {
        borderTopWidth = 0;
    }
    if (isNaN(borderBottomWidth)) {
        borderBottomWidth = 0;
    }
    return height+paddingTop+paddingBottom+borderTopWidth+borderBottomWidth;
};
