// Vron... This is a rather modified script thats been floating around for a while. It uses a jQuery plugin called hoverIntent so it's important to make that available.
// Also, theres a very slight chance that it'll clash with BC's included JQuery framework. See the note in gurtmenu.htm about that.

var $j = jQuery.noConflict();


$j(document).ready(function(){
    
    function grainHoverOver(){
        
        var nhlo =$j("#grainnav-holder").offset().left; //nhlp = topnav-holder left
        var tlo = $j(this).offset().left; //tlp = this position left
        var nlo = tlo-nhlo; //nlp = new left position
        
        $j(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
        $j(this).find(".sub").css({'left' :-nlo}); //Set width
        
        (function($j) {//Function to calculate total width of all ul's. This might freak out a bit with large layout changes. We'll have to adapt it to your needs.
            jQuery.fn.calcSubWidth = function() {
                rowWidth = 0;
                $j(this).find("ul").each(function() { //for each ul...
                    rowWidth += $j(this).width(); //Add each ul's width together
                });
            };
        })(jQuery); 

        if ( $j(this).find(".row").length > 0 ) { //If row exists...

            var biggestRow = 0;	

            $j(this).find(".row").each(function() {	//for each row...
                $j(this).calcSubWidth(); //Call function to calculate width of all ul's
                //Find biggest row
                if(rowWidth > biggestRow) {
                    biggestRow = rowWidth;
                }
            });

            $j(this).find(".sub").css({'width' :biggestRow}); //Set width
            $j(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin

        } else { //If row does not exist...

            $j(this).calcSubWidth();  //Call function to calculate width of all ul's
            $j(this).find(".sub").css({'width' : 940}); //Set Width (can be set to 'rowWidth' for dynamic use. Will break on Grainsite though.

        }
    }

    function grainHoverOut(){
      $j(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
          $j(this).hide();  //after fading, hide it
      });
    }
    
    //Set custom configurations
    var config = {
         sensitivity: 2, // 1 or higher
         interval: 50, // milliseconds onMouseOver polling
         over: grainHoverOver, // function = onMouseOver callback (REQUIRED)
         timeout: 500, // number = milliseconds delay before onMouseOut
         out: grainHoverOut // function = onMouseOut callback (REQUIRED)
    };

    $j("ul#grainnav li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
    $j("ul#grainnav li").hoverIntent(config); //Trigger Hover intent with custom configurations
    
});
