$(document).ready(function() {
	// running vars
	var slideQty = 5;
	var slideHeight = 380;
	var slideWidth = 900;
	var delay = 7000;
	var speed = 650;
	var position = 0;
	var buttonHeight = 20;
	var buttonWidth = 20;
	var timer = null;
	// set up the width of the slide container
	var totalWidth = slideWidth*(slideQty+1)+'px';
	$('.slideWrapper').css({'width':totalWidth});
	// add the first image again at the end for smooth scrolling back to the first one
	$('.slide:first').clone().appendTo('.slideWrapper');
	// create buttons
	$('.topimg').css({'position':'relative'});
	for (var b=0;b<slideQty;b++) {
		$('.slideWrapper').parent().append('<div class="button button-'+b+'">&nbsp;</div>');
		$('.button-'+b).css({
			'height':buttonHeight+'px',
			'width':buttonWidth+'px',
			'position':'absolute',
			'textIndent':'-9999px',
			'z-index':'99',
			'right':'0',
			'top':((slideHeight-(slideQty*buttonHeight))/2)+(b*buttonHeight)+'px',
			'backgroundRepeat':'no-repeat',
			'backgroundPosition':'0,0',
			'backgroundImage':'url(\'/images/topimg/large/button-'+(b==0?'on':'off')+'.png\')',
			'cursor':'pointer'
		});
	}
	$('.button').click(function() {
		// get the button id
		var temp = $(this).attr('class').split('-');
		var newSlide = parseInt(temp[1]);
		// jump to it
		position = newSlide;
		moveSlider(newSlide);
	});
	// create faders
	$('.topimg').append('<div class="slideFadeL">&nbsp;</div>');
	$('.topimg').append('<div class="slideFadeR">&nbsp;</div>');
	// move to desired position
	function moveSlider( pos , end ) {
		// show the current position for debugging
		//window.location = '#'+pos;
		// stop any current animation
		$('.slideWrapper').stop(true,true);
		// clear the time
		clearTimeout(timer);
		// if the position is invalid, look
		if (pos<0||pos>=slideQty) pos = 0;
		// if we're at the end move onto the extra one we created then jump to the start
		if (end) {
			var newPos = slideWidth*slideQty;
		} else {
			var newPos = slideWidth*pos;
		}
		// turn off buttons
		$('.button').css({'backgroundImage':'url(\'/images/topimg/large/button-off.png\')'});
		// turn the current button on
		$('.button-'+pos).css({'backgroundImage':'url(\'/images/topimg/large/button-on.png\')'});
		// move the slide along
		$('.slideWrapper').animate(
			{
				'marginLeft':'-'+newPos+'px'
			},
			speed,
			'swing',
			function() {
				if (end) {
					// jump back to the start if we used the extra end image
					$('.slideWrapper').css({'marginLeft':'0px'});
				}
				// set up the timer to move the next one
				moveOne();
			}
		);
	}
	// move the image along after the delay
	function moveOne() {
		timer = setTimeout(function() {
			position++;
			if (position>=slideQty) position = 0;
			moveSlider(position , (position==0?true:false) );
		},(delay));
	}
	// start
	moveOne();
});
