$(document).ready(function() {
  safeMail();
  $("ul.top-submenu").wrap('<div class="shadow"></div>');
  $("ul.top-menu > li").hover(function() {
    $("a:first",this).addClass("hovered");
    $("ul.top-submenu",this).show().css("top","0px").parent().show();
    $("ul.top-submenu",this).parent().height($("ul.top-submenu",this).height());
   },function() {
     $("ul.top-submenu",this).hide().parent().hide();
     $("a:first",this).removeClass("hovered");
   });
   $("#sidebar #submenu li").hover(function() {
     $(this).addClass("hovered");
   },function() {
      $(this).removeClass("hovered");
   });
   if ($("a.lightbox").length > 0)
    $("a.lightbox").lightBox({'overlayOpacity' : 0.8,'txtImage' : 'Ekran','txtOf' : 'z'});

   $("table.expandable").collapseTables();
   $("pre.expander").expander({
     slicePoint: 170,
     expandText: '(więcej)',
     userCollapseText: '(mniej)',
     expandEffect: 'show',
     expandPrefix: ''
   })
});

(function($) {
  $.fn.collapseTables = function() {
    if (this.length == 0)
      return;
    var $tables = $(this);
    $tables.hideTableRows();
    $tables.addHashChangeEvent();
  };

  $.fn.showTableRows = function() {
    $tables = $(this);
    $tables.each(function() {
      var $table = $(this);
      $("tbody tr, thead tr:gt(0)", $table).show();
      $("thead tr:eq(0) th:eq(0)", $table).removeClass("collapsed").addClass("expanded");
    });
  };

  $.fn.hideTableRows = function() {
    $tables = $(this);
    $tables.each(function() {
      var $table = $(this);
      $("tbody tr, thead tr:gt(0)", $table).hide();
      $("thead tr:eq(0) th:eq(0)", $table).addClass("collapsed").removeClass("expanded");
    });
  };

  $.fn.addHashChangeEvent = function() {
    var firstTimer = true;
    $tables = $(this);
    $tables.each(function(index) {
      var $table = $(this);
      $("thead tr:eq(0) th:eq(0)", $table).click(function(){
        if ($(this).hasClass("expanded")) {
          $table.hideTableRows();
          $.bbq.removeState();
        }
        else {
          var id = $table.attr("id");
          if (!id)
            id = (index + 1);
          $.bbq.pushState("#" + id);
        }
      });
    });
    $(window).bind("hashchange", function(e) {
      var hash = $.param.fragment();
      if (!hash)
        return;
      var $target = null;
      if (parseInt(hash))
        $target = $("table.expandable:eq(" + (hash - 1) + ")");
      else
        $target = $("table.expandable[id='" + hash + "']");
      $target.showTableRows();
      if (firstTimer)
        window.scrollTo($target.offset().left, $target.offset().top);
      firstTimer = false;
    })
    var hash = $.param.fragment();
    if (hash)
      $(window).trigger("hashchange");
    else {
      //$("table.expandable:eq(0)").showTableRows();
      firstTimer = false;
    }
  }
})(jQuery);