function init() {

   $( "#super-menu > .page_item" ).each( 
      function() {
         var amountOfChildren = $( this ).find( ".children a" ).length;
         if( amountOfChildren > 0 ) {
            $( this ).addClass( "menu-item-with-submenu" );
            $( this ).find( "ul" ).addClass( "sub-menu sub-menu-" + amountOfChildren )
               .find( "li" ).addClass( "sub-menu-item" );
         }
      }
   );

  $( "#super-menu .menu-item-with-submenu" ).each( 
     function() {
        $( this ).hover( overMenu, outMenu ); //.mousemove( movingOverMenu );
        $.proxy( setMinWidth, this )();
     }
  );
  
   $( "#super-menu .sub-menu-item" ).hover( overSubMenu, outSubMenu );
   setInterval( menuLoop, 15 );
}

function menuLoop() {
  $( "#super-menu .menu-item-with-submenu" ).each( movingOverMenu );
}

function overMenu() { 
  $( this ).data( "mouse-over", true );
  $( this ).data( "awaiting-mouse-out", false );
}

function outMenu() { 
  var func = $.proxy( 
     function() { 
        if( $( this ).data( "awaiting-mouse-out" ) ) {
           $( this ).data( "mouse-over", false ); 
        }
     }, this 
  );
  setTimeout( func, 100 );
  $( this ).data( "awaiting-mouse-out", true );
}

function movingOverMenu( e ) {
   var rightMargin = 5 + 3; 
   var hasActiveChild = $( this ).has( ".sub-menu .current_page_item" ).length;
   var toRight = 0; 
   if( $( this ).data( "mouse-over" ) ) toRight = $( this ).data( "to-right" ) + rightMargin;
   else if( hasActiveChild ) toRight = $( this ).find( ".sub-menu .current_page_item" ).data( "my-width" ) + rightMargin;
   var right = parseFloat( $( this ).data( "current-right" ) );
   right += ( toRight - right ) * 0.5;
   $( this ).css({ "margin-right": right }).data( "current-right", right );
}

function setMinWidth() {  
   $( this ).data({ "child-width": 1000, "current-right": 0 });
   $( this ).find( ".sub-menu-item" ).each( 
     $.proxy( 
        function( index ) {
           var child = $( this ).find( ".sub-menu-item:eq(" + index + ")" );
           var width = child.width();
           child.data( "my-width", width );
           $( this ).data( "child-width", Math.min( $( this ).data( "child-width" ), width ) );
        }, this
     )
   );
   $( this ).data( "to-right", $( this ).data( "child-width" ) );
}
	  
function overSubMenu() { 
  var width = $( this ).children().width();
  $( this ).parent().parent().data( "to-right", parseInt( width ) );
}

function outSubMenu() { 
  $( this ).parent().parent().data( "to-right", $( this ).parent().parent().data( "child-width" ) );
}

$( window ).load( init );
