(function($){
    var onHide = function(){};
    /*
    *** jQuery plugin
    */
    $.fn.topBarDropDown = function(options) {
        switch (options) {
          case 'hide':
            _hideDropDown();
            return;
          default:
            if ($.isFunction(options)) onHide = options;  
        }
        
        return this.each(function(index){
            var a = $(this);
            //a.bind('onHide',onHide);
            if (a.hasClass('DropOnHover')){
                a.mouseenter(function(){
                  var b  = $('.dd_active');
                  if (b.length > 0) {
                    li = a.closest('li');
                    // if this item is already showing, do nothing
                    // if the item showing is not an onHover item, do nothing
                    if (li[0] == b[0] || b.find('.DropOnHover').length == 0) return false;
                  }
                  _showDropDown(a,false);
                  return false;
                });
            }
            
            a.click(function(){
              _showDropDown(a,true);
              return false;
            });
        });
    }
    
    /*
    *** Supporting Functions ***
    */
    function _showDropDown(elem) {
        var li = elem.closest('li')
            dd = li.closest('li').find(".dropdown");
        if (li.hasClass('dd_active')) {
          _hideDropDown();
          return;
        }
        if (dd.length > 0) {
          _hideDropDown();
          li.addClass('dd_active');

          if (!elem.hasClass('DropFixedSize')) {
            var i = dd.find('.dd_inner');
            i.css({height:'auto','overflow-y':'hidden'});
            var h = dd.position().top + dd.height() - $(window).height();
            if (h > 0) {
              i.css({height: i.height() - h, 'overflow-y':'auto'});
            }
          }
          dd.position({
                of          : li,
                my          : "left top",
                offset      : "0 -1",
                at          : "left bottom",
                collision   : "fit"
          });
          
          $("html").on('click.tb_dropdown',function(e){
              if($(e)==elem || dd[0] != $(e.target).closest(".dropdown")[0]){
                _hideDropDown();
              }
          });
        }
    }
    function _hideDropDown(){
      var active = $('.dd_active');
      if (active.length > 0) { 
          onHide(active);
          active.removeClass('dd_active');
          $("html").off('click.tb_dropdown');
      }
    }
        
    
})(jQuery);

