var carousel = $('#carousel')
, carouselImages = $('#carouselImages img')
, carouselCount = carouselImages.length -1
, carouselBtn = $('.carouselBtn')
, carouselAutoplay = true
, carouselInterval = 2500
, carouselFade = 800
, t // timer
, pause; //pause after clicking through

$(document).ready(function(){
	$('body').addClass('js');
	
	initCarousel();
	
	initFormValidation();
})

$(function() {
	var lightboxItem = $('a[rel="lightbox"]');
	
	if (lightboxItem.length > 0){
		$('a[rel="lightbox"]').lightBox({
			fixedNavigation:true,
			keyToClose: 'esc',
			keyToPrev: 'LEFT' ,
			keyToNext: 'RIGHT' 
		});
	}
});

function initFormValidation(){
	var siteForm = $('.siteForm');
	
	if (siteForm.length > 0){

		var container = $('div.errors');
		var validator = $('.siteForm').validate({
			errorContainer: container,
			rules:{
				Postcode:{rangelength: [6, 8],}
				}
		});
	}
}

function initCarousel(){
	// if there is more than 1 image in the carousel show the navigation
	if (carouselCount > 0){
		$('#carousel #prev, #carousel #next').show();
	}
		
	carousel.css('height',carouselImages.first().height());
	carouselImages.hide().first().addClass('active').show();
	
	autoPlayCarousel();
	
	carouselBtn.click(function(e){
		e.preventDefault();

		carouselAutoplay=false;
		clearInterval(t);
		clearTimeout(pause);

		var direction = $(this).attr('id');
		var active = $('#carouselImages .active');
		var index = active.index();
		// fade out all images
		carouselImages.removeAttr('class').fadeOut(carouselFade);
		
		// determine direction button clicked and pass through active element with its index
		shiftCarousel(active,index,direction);
		pause = setTimeout(autoPlayReset,carouselInterval*2);
	});
}

function autoPlayReset() {
	carouselAutoplay=true;
	autoPlayCarousel();
}

function autoPlayCarousel() {
	
	t = setInterval(function() {
		var active = $('#carouselImages .active')
		, index = active.index();
		carouselImages.removeAttr('class').fadeOut(carouselFade);
		shiftCarousel(active,index,"next")
	}
	,carouselInterval);
}


// shiftCarousel moves the carousel backwards or forwards as needed
function shiftCarousel (active,index,direction) {
	
	// if the prev button clicked select the previous carousel image
	if (direction == "prev"){
		if (index == "0"){
			// if the active item is the first then display the last image
			carouselImages.last().fadeIn(carouselFade).addClass('active');
		} else {
			active.prev().fadeIn(carouselFade).addClass('active');
		}
		
	// if the next button clicked select the next carousel image
	} else if (direction == "next"){
		if (index == carouselCount){
			// if the active item is the last then display the first image
			carouselImages.first().fadeIn(carouselFade).addClass('active');
		} else {
			active.next().fadeIn(carouselFade).addClass('active');
		}
	}
	//carouselAutoplay=true;
	//autoRotateCarousel();
}
