/*
    Document   : jquery.dropdown.css
    Created on : Jun 18, 2010, 1:44:36 PM
    Author     : damian.ignacio@gmail.com

    Comments: This is not a jQuery plugin. It is an encapsulated code that works in conjunction with jquery
        and has a specific function. I mean I do not know if it would be useful in generic cases.
        For any questions contact me.

*/


(function($) {

    var countItems = 0;
    var widthItems = 0;
    var toPad = restToPad = 0;
    var inner = 0;

    $.fn.dropDownMenu = function() {

        inner = $(this).parent().innerWidth();
        
        var items = $(this).children('li');

        countItems = items.length;

        items.each(function(i,obj){
            widthItems+= $(obj).outerWidth();
        });        

        toPad = ($(this).innerWidth() - widthItems) /(countItems);
        toPad = parseInt(toPad);
        
        if(toPad%2 != 0){ toPad--; }
        
        restToPad = $(this).innerWidth() - (countItems * toPad + widthItems);

        var padAfter ,padBefore;
        
        if(restToPad%2 != 0 && restToPad != 0){            
            padBefore = restToPad/2 + 1/2;
            padAfter = restToPad/2 - 1/2;
        }else{
            padBefore = padAfter = restToPad/2;
        }
        
        items.each(function(i,obj){
            if(i == 0){
                $(obj).css('padding-left', (toPad/2 + padBefore) + 'px');
                $(obj).css('padding-right',(toPad/2 + padAfter) +'px');                
            }else{
                $(obj).css('padding-left',toPad/2 + 'px');
                $(obj).css('padding-right',toPad/2 + 'px');
            }
        });

        items.each(function(i,obj){

            /* var subItem = $(obj).children('ul');

            if(subItem.length > 0 && subItem.outerWidth() < $(obj).innerWidth()){
                subItem.width($(obj).outerWidth());

                subItem.children('li').each(function(i,obj){
                    $(obj).css('min-width',$(obj).parent('ul').width());
                });
            } */

        });

        items.css('visibility','visible');

        items.hover(function(){
            var ccsRule;
            if($(this).children('ul').outerWidth() + $(this).position().left < inner){
                ccsRule = {'left':'-1px','overflow':'hidden'};
            }else{
                ccsRule = {'right':'-1px','overflow':'hidden'};
                
            }           
            
            $(this)
                .addClass('hover')
                .children('a')
                .addClass('hover').next('ul').css(ccsRule).show();
        },function(){            
            $(this)
                .removeClass('hover')
                .children('a')
                .removeClass('hover').next('ul').hide();
        });
        
    }
})(jQuery);