﻿
$(document).ready(function() {

  function mouseEnter() {
    $(this).find('.sub').stop().fadeTo('fast', 1).show();

    // calculate width of all ul's
    (function($) {
      jQuery.fn.calcSubWidth = function() {
        rowWidth = 0;
        // calculate row
        $(this).find('ul').each(function() {
          rowWidth += $(this).width();
        });
      };
    })(jQuery);

    if ($(this).find('.row').length > 0) { // if row exists...
      var biggestRow = 0;
      // calculate each row
      $(this).find('.row').each(function() {
        $(this).calcSubWidth();
        // find biggest row
        if (rowWidth > biggestRow) {
          biggestRow = rowWidth;
        }
      });
      // set width
      $(this).find('.sub').css({ 'width': biggestRow });
      $(this).find('.row:last').css({ 'margin': '0' });

    } else { // if row does not exist...

      $(this).calcSubWidth();
      // set width
      $(this).find('.sub').css({ 'width': rowWidth });

    }
  }

  function mouseLeave() {
    $(this).find('.sub').stop().fadeTo('fast', 0, function() {
      $(this).hide();
    });
  }

  $('div.categories ul.menu li .sub').css({ 'opacity': '0' });

  $('div.categories ul.menu li').mouseenter(function(e) {
    mouseEnter.call(this);
  });

  $('div.categories ul.menu li').mouseleave(function(e) {
    mouseLeave.call(this);
  });

});
