$(document).ready(function() {	
	
	// Nav Utilities Menu
	$('ul.nav-utilities li:first-child').hover(function() {
		$(this).children('div.menu').show();
		$(this).children('a').addClass('selected');
	}, function() {
		$(this).children('div.menu').hide();
		$(this).children('a').removeClass('selected');
	});
	
	
	// Language Menu
	$('ul.nav-utilities li.language').click(function() {
		$('.header .countries').show();
		
		return false;
	});
	
	$('.header .countries .options ul li:last-child, .main-content').click(function() {
		$('.header .countries').hide();
	});
	
	$('.header .countries .flags ul li').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
	
	$('.header .countries .flags ul li').click(function() {
		var myCookie = $.cookie("MDCCountry");
		var preserveCookie = $("#remember").is(":checked");
		var newCookie = $(this).attr('id');
		var newCountryName = $(this).attr('id');
		var cookieOptions = { path: '/' };
		if (preserveCookie) {
			$.extend(cookieOptions, {expires: 365});
		}
		$.cookie("MDCCountry", newCookie, cookieOptions);
		// Set the country in the header
		var newCountryName = $(this).find('span:first').html();
		$(".language").find('a:first').find('span:first').html( newCountryName );
		// Set the flag
		var newCountryFlag = $(".language").find('a:first').find('img:first').attr('src');
		var period = newCountryFlag.lastIndexOf(".");
		var lastSlash = newCountryFlag.lastIndexOf("/");
		newCountryFlag = newCountryFlag.substring(0,lastSlash + 1 ) + newCookie + newCountryFlag.substring(period );
		$(".language").find('a:first').find('img:first').attr('src',newCountryFlag );
		$(".language").find('a:first').find('img:first').attr('alt',newCountryName );
		$('.header .countries').hide();
		// Refresh the page
		location.reload();
	});
	// Set the country in the header
	// currently a hack, should create a jQuery function.
	var myCookie = $.cookie("MDCCountry");
	if ( myCookie != null) {
		var myCountryElementName = '#' + myCookie;
		var newCountryName = $(myCountryElementName).find('span:first').html();
		$(".language").find('a:first').find('span:first').html( newCountryName );
		// Set the flag
		var newCountryFlag = $(".language").find('a:first').find('img:first').attr('src');
		var period = newCountryFlag.lastIndexOf(".");
		var lastSlash = newCountryFlag.lastIndexOf("/");
		newCountryFlag = newCountryFlag.substring(0,lastSlash + 1 ) + myCookie + newCountryFlag.substring(period );
		$(".language").find('a:first').find('img:first').attr('src',newCountryFlag );
		$(".language").find('a:first').find('img:first').attr('alt',newCountryName );
	}
	
});
