var stash = '';
var counter = 1;
var max = 3;

$(function(){
	$(".date-input").datepicker();

	$('div.menu ul').masonry({
		// options
		itemSelector : 'div.menu ul > li',
		columnWidth : 180
	});

    // apply classes for sizing
    $('#nav-main > li:nth-child(3n+1)').addClass('col1');
    $('#nav-main > li:nth-child(3n+2)').addClass('col2');
    $('#nav-main > li:nth-child(3n+3)').addClass('col3');
    
    // move child items to after the row
    $('#nav-main > li').each(function(){
    
    	// find all child ul's and move to stash
    	children = $(this).find('ul').html();
    	if(children)
    	{
    		parent_id = findTabId(this);
    		$(this).addClass('has-subnav');
    		stash += '<li id="page-child-'+parent_id+'" class="subnav"><ul>'+children+'</ul></li>';
    	}
    	$(this).find('ul').remove();
 
    	
    	// if this is the last in the row, show the stash
    	// after the current li and empty the stash
    	if(counter == max && stash != '')
    	{
    		$(this).after(stash);
    		stash = '';
    	}
    	$(this).show();
    	
    	// increment and reset counter if needed
    	counter++;
    	if(counter > max)
    		counter = 1;
    
    });

});


var lastHover;
var lastHoverId;
var tabOver = 0;
var tabTimeout;
var childOver = 0;
var childTimeout;
 
$('#nav-main > li.has-subnav > a').live({
	
	mouseover: function(){
		lastHoverId = findTabId( $(this).parent() );
 
		clearTimeout(tabTimeout);
		clearTimeout(childTimeout);
		
		tabOver = 1;
		
		clearTimeout(lastHover);
		lastHover = setTimeout(function(){
 
			collapseTabs();
		
			$('#page-child-'+lastHoverId).show();
			$('.page-item-'+lastHoverId).addClass('open');
		},200);
	},
	mouseout: function() {
		tabOver = 0;
	
		tabTimeout = setTimeout(function(){
			if(childOver == 0 && tabOver == 0)
				collapseTabs();
		},500);
	}
 
});
 
$('#nav-main li.subnav').live({
	mouseover: function(){
	
		childOver = 1;
	
		clearTimeout(tabTimeout);
		clearTimeout(childTimeout);
		
	},
	mouseout: function(){
		childOver = 0;
		
		childTimeout = setTimeout(function(){
			if(childOver == 0 && tabOver == 0)
				collapseTabs();
		},500);
	}
});
	


function collapseTabs()
{
	$('#nav-main li.open').each(function(){
 
		$(this).removeClass('open');
 
		thisId = findTabId(this);		
		$('#page-child-'+thisId).hide();
 
	});
}
 
function findTabId(obj)
{
	parent_classes = $(obj).attr('class');
	classes = parent_classes.split(' ');
	parent_id = classes[1].split('page-item-');
	return parent_id[1];
}
