$(document).ready( function () {
	window.menuState = 'closed';
	window.activeMenu = 0;
	
	$('a.menu-link').click (
		function (event) {
			event.preventDefault();
			showMenu($(this).attr('data-category-id'));
		}
	);
	
	//$('#menu-holder, #right-nav, #right-nav-tall').mouseleave (
	$('#menu-hover').mouseleave (
		function () {
			if (window.menuState == 'open') {
				$('#nav-menu').animate (
					{ marginLeft: '+=660px' },
					200,
					function () {
						window.menuState = 'closed';
						window.activeMenu = 0;
						$('#menu-holder, #menu-hover').css('zIndex',1);
						$('.subnav').hide();
					}
				);
			}
		}
	);
	
	doModals();
});

function showMenu (category_id) {
	if (window.menuState == 'closed') {
		$('#menu-holder, #menu-hover').css('zIndex',1000);
		$('#nav-menu').animate (
			{ marginLeft: '-=660px' },
			200,
			function () {
				window.menuState = 'open';
				$('#nav_category_'+category_id).fadeIn (
					'fast',
					function () { window.activeMenu = category_id; }
				);
			}
		);
	} else {
		if (window.activeMenu) {
			$('#nav_category_'+window.activeMenu).fadeOut (
				'fast',
				function () {
					$('#nav_category_'+category_id).fadeIn (
						'fast',
						function () { window.activeMenu = category_id; }
					);
				}
			);
		} else {
			$('.subnav').fadeOut (
				'fast',
				function () {
					$('#nav_category_'+category_id).fadeIn (
						'fast',
						function () { window.activeMenu = category_id; }
					);
				}
			);
		}
	}
}

function doModals () {
	$('[rel="modal"]').click (
	   	function (event) {
			event.preventDefault();
			modalPopup($(this).attr('href'));
		});
	$('[rel="hide-modal"]').click (
	   	function (event) {
			event.preventDefault();
			hideModal();
		});
	$('#modal-bg').click (
		function () {
			hideModal();
		});
}

function modalPopup (url) {
	$.get(url, function (data) {
		showModal(data);
	 },'html');
}

function showModal (data) {
	$('#modal').html(data);
	
	$('[rel="hide-modal"]').click (
	   	function (event) {
			event.preventDefault();
			hideModal();
		});

	// Accomodate smaller screens, or larger images
	modalOffset = 160; // hard coded, since jquery incorrectly returns position values on hidden elements
	if ($('#modal').height() + modalOffset > $(window).height()) {
		$('#modal').css ('top', '0px');
		if ($('#modal').height() >= $(window).height()) $('#modal').css ('position', 'absolute');
	}
	
	$('#modal').css ('display','block');
}

function hideModal () {
	$('#modal').css ('display','none');
	$('#modal').html('');
}

function slideshow () {
	if (window.slides != null) {
		for (i=0; i<window.slides.length; i++) {
			$('#headerslideshow').append ('<img src="'+window.slides[i]+'">');
		}
		$('#headerslideshow').cycle({speed: 500});
	}
}
