$(function(){
	
	var menuTimers = [];
	var isMenuReady = [];
	
	// Load news titles from blog feed
	loadHeadlines();
	
	// Wire up drop down menus
	$('#header .nav > ul > li > img').map(function(index){
		isMenuReady[index] = true;
		$(this).bind('mouseenter', function(){
			//$(this).css('z-index', 1000);
			//alert('hi');
			showMenu(index);
		});
		$(this).bind('mouseleave', function(){
			hideMenu(index, 0);
		});		
	});
	
	$('#header .nav div').map(function(index){
		$(this).bind('mouseenter', function(){
			clearTimeout(menuTimers[index]);
		});
		$(this).bind('mouseleave', function(){
			menu = $(this);
			hideMenu(index, 250);
		});
	});
		
	function showMenu(index){
		clearTimeout(menuTimers[index]);
		$('#header .nav > ul > li').eq(index).css('z-index', 1010);
		img = $('#header .nav > ul > li > img').get(index);
		if (img.src.indexOf('-over.gif') == -1) img.src = img.src.replace('.gif', '-over.gif');
		if (isMenuReady[index] == true) {
			isMenuReady[index] = false;
			$('#header .nav div').eq(index).fadeIn(function(){
				isMenuReady[index] = true;
			});
		}
	}
	
	function hideMenu(index, wait){
		menuTimers[index] = setTimeout(function(){
			img = $('#header .nav > ul > li > img').get(index);
			img.src = img.src.replace('-over.gif', '.gif');	
			$('#header .nav > ul > li').eq(index).css('z-index', 1000);
			$('#header .nav div').eq(index).fadeOut();
		}, wait);
	}
	
	function loadHeadlines() {
		$('#sidebar div.articlesBlock .content').hide();
		$('#sidebar div.articlesBlock .content').html('');
		$.get('/blog/category/news-stories/feed', function(data){
			var i = 0;
			var html = '<ul>';
			for (i=0;i<3;i++) {
				var item = $(data).find('item').eq(i);
				var title = item.find('title').text();
				var link = item.find('link').text();
				if (title && link) html += '<li><a href="' + link + '">' + title + '</a></li>';
			}
			html += '</ul>';
			$('#sidebar div.articlesBlock .content').html(html);
			$('#sidebar div.articlesBlock .content').slideDown(750);
		});		
	}
	
	$('#header .primaryNav img').bind('mouseover', function(){
		this.src = this.src.replace(/(.*)\.(jpg|gif|png)$/i, "$1-over.$2");
	});
	$('#header .primaryNav img').bind('mouseout', function(){
		this.src = this.src.replace(/(.*)-over\.(jpg|gif|png)$/i, "$1.$2");
	});	
	
	$('div.videoBlock .more a').bind('click', function(){
		if ($('div.videoBlock .additionalVideos').css('display') == 'none') {
			$('div.videoBlock .additionalVideos').slideDown(500, function(){
				$('div.videoBlock .more a img').get(0).src = 'images/text/less-videos.gif';
			});
		} else {
			$('div.videoBlock .additionalVideos').slideUp(500, function(){
				$('div.videoBlock .more a img').get(0).src = 'images/text/more-videos.gif';
			});
		}		
		return false;
	});
	
});