var slides, slide_dots, specials;

$(document).ready(function(){ 

// Setup menu
	if (document.body.id === 'page-menu')
	{
		// Fire up correct sub-menu
		var menuSectionID = (window.location.href.indexOf('#') > 0) ?
							 window.location.href.substring(window.location.href.indexOf('#')+1, window.location.href.length) :
							 'appetizers';
		$('#menu-section-' + menuSectionID).addClass('active');
		$('#sub-nav A[href="#'+menuSectionID+'"]').parent().addClass('active');
		
		// Apply onclicks
		$('#sub-nav A').bind('click', function()
		{
			$('#sub-nav .active').removeClass('active');
			$('#content .active').removeClass('active');
			$(this).parent().addClass('active');
			$('#menu-section-' + $(this).attr('href').substring($(this).attr('href').indexOf('#')+1, $(this).attr('href').length)).addClass('active');
		});
	}
	
	$('FORM.validate').bind('submit', function(){
		var bReturn = true;
		$(this).find('.required').each(function(){
			if (!$(this).val()) {
				$(this).addClass('error').bind('focus', function(){
					$(this).removeClass('error');
				});
				bReturn = false;
			}
		});

		if (!bReturn && !document.getElementById('error-message'))
			$('<div id="error-message" class="error-message">Please fill out all the fields.</div>').insertBefore($(this));

		return bReturn;
	});


	// Specials
	specials = $('.special');
	if (specials.length > 1)
	{
		specials.bind('cycle', function(e){
			$(this).fadeOut(800);
			var next_special = ($(this).next('li').length > 0) ? $(this).next('li') : $(this).siblings('li').first();
			var this_special = $(this);
			next_special.fadeIn(800);
		});
		specials.hide(); // Hide all specials via JS
		specials.first().show(); // Show first one only
		special_cycle = setInterval(function(){specials.filter(':visible').trigger('cycle');}, 4000);
	}
	

	// Slides
	slides = $('#slides li');
	slide_dots = $('#slide-dots li');
	slides.bind('cycle', function(e){
		$(this).fadeOut(800);

		var next_slide = ($(this).next('li').length > 0) ? $(this).next('li') : $(this).siblings('li').first();
		var this_slide = $(this);
		next_slide.fadeIn(800, function(){
			slide_dots.eq( slides.index(this_slide) ).removeClass('active');
			slide_dots.eq( slides.index(next_slide) ).addClass('active');
		});

	});	
	slide_dots.bind('click', function(e){
		e.preventDefault();
		clearInterval(slide_cycle);

		if (!$(this).hasClass('active'))
		{
			$(this).siblings('.active').removeClass('active');
			$(this).addClass('active');

			var target = slides.eq( slide_dots.index($(this)) );
			slides.filter(':visible').fadeOut(400);
			target.fadeIn(400);
		}
	});
	slides.hide(); // Hide all slides via JS
	slides.first().show(); // Show first one only
	slide_dots.first().addClass('active'); // Activate the first dot
	// Only activate cycling if we have more than one slide
	if (slides.length > 1)
		slide_cycle = setInterval(function(){slides.filter(':visible').trigger('cycle');}, 4000);

});

