var timeout = 4000;
var speed = 2000;
var cur_img = 0;
var new_img = 0;
var img_len = 0;
var dir = 1;
var cont_width;
var interval;

$(document).ready(function(){
	//get the total size
	cont_width = $("#header_image_cont").width();
	
	//set the images length
	img_len = $(".header_images").length;

	//set the initial timeout
	interval = setTimeout('changeImages('+dir+')',timeout);
	
	$("#button_left").click(function(){
		changeImages(-1);
	});
	
	$("#button_right").click(function(){
		changeImages(1);
	});
});

function changeImages(new_dir){
	//return false if animated
	if($(".header_images").eq(cur_img).is(":animated") || $(".header_images").eq(new_img).is(":animated")) return false;
	
	//clear the timeout
	clearTimeout(interval);
	
	//check greater than
	if(cur_img + new_dir >= img_len){
		new_img = 0;
	} else if(cur_img + new_dir < 0){
		new_img = img_len - 1;
	} else {
		new_img += new_dir;
	}
	
	//check the direction
	if(new_dir > 0){
		$(".header_images").eq(new_img).css({'left':cont_width}).addClass('header_active').animate({ 'left':'0' }, speed);
		$(".header_images").eq(cur_img).animate({'left':-cont_width}, speed,function(){
			$(this).css({'left':'0'}).removeClass('header_active');
			interval = setTimeout('changeImages('+dir+')',timeout);
		});
		
		//set the current image to the new image
		cur_img = new_img;
	} else {
		$(".header_images").eq(new_img).css({'left':-cont_width}).addClass('header_active').animate({ 'left':'0' }, speed);
		$(".header_images").eq(cur_img).animate({'left':cont_width}, speed,function(){
			$(this).css({'left':'0'}).removeClass('header_active');
			interval = setTimeout('changeImages('+dir+')',timeout);
		});
		
		//set the current image to the new image
		cur_img = new_img;
	}
}
