$(function(){
  var hoverTimeout;
  var menuOpen;
  var clicked;
  var open = function(){
    clearTimeout(hoverTimeout);
    $this = $(this).addClass('hover').parent().addClass('hover').end();
    $link = $this.children('a');
    $menu = $this.children('div.pulldown');
    menuOpen = $link.attr('href');
    var dif = $menu.outerWidth() - $link.outerWidth();
    if(dif < 15) {
      var $cols = $menu.width($menu.width()-dif).find('div.pulldown-col');
      var numcols = $cols.length;
      $cols.each(function(){
        var difpart = Math.ceil(dif/numcols);
        dif -= difpart;
        --numcols;
        var $col = $(this);
        $col.width($col.width()-difpart);
      });
    }
    $menu.css(($this.position().left + $menu.width() > $this.parent().width()) ? {right:0,left:'auto'} : {left:0});
  };
  var close = function(){
    var $parent = $(this).removeClass('hover').parent();
    menuOpen = null;
    $this.children('div.pulldown').css('left','')
    hoverTimeout = setTimeout(function(){ $parent.removeClass('hover'); },200);
  }
  $('#nav li').hover(open,close);
  $('#nav li.pulldown a.navtop').bind('tap click',function(e){
    e.stopPropagation();
    if(e.type=='tap') $(this).unbind('click').bind('click',false);
    var ret = ($(this).attr('href')==menuOpen); 
    $(this).parent().each(open);
    return ret;
  });
  $('div.pulldown').bind('tap click',function(e){ e.stopPropagation(); });
  $('#header_bg, #wrapper').bind('tap click',function(){ $('#nav li.hover').each(close); });
});
