var animating = false;
var timer;
var FADETIME = 2000; //The time to fade between pictures
var HOLDTIME = 5000; //Time used to display picture.
var offsetX = 78; //The initial offset to use for button location
var boxWidth = 25; //What is the width of the button + padding
//var link =['http://dunsterhouse.co.uk/log-cabins/','http://dunsterhouse.co.uk/special-offers/','http://dunsterhouse.co.uk/wood-burning-stoves/'];
var link =['/','/log-cabins/','/climbing-frames/'];
//var title =['<font style="color:#2568DD;">19mm Log Cabins</font>','<font style="color:#F15200;">Clearance Products</font>','<font style="color:#1C1E24;">Murphy Stoves</font>'];
var title =['<font style="color:red;">Sale Now on</font>','<font style="color:red;">Log Cabins</font>','<font style="color:red;">Climbing Frames</font>'];
var currentId=0,nextId=1;
var numberOfPics=3;
var banCurrent,waiting;

jQuery(function() { //call script at page load
	
	$('#kamil').click(function(){
		rotateSpecific(0);
	});
	
	//create the image array
	imgArray = ['sale1.jpg','sale2.jpg','sale3.jpg'];
	
	createButtons();
	
	timer=setTimeout("animateRotation()", HOLDTIME);
});

function animateRotation() {

	animating=true;
	
	jQuery(".banCurrent").animate({opacity:0.0},FADETIME, function () {
		
		waiting=jQuery('#photoShow .waiting');
		banCurrent=jQuery('#photoShow .banCurrent');
		waiting.removeClass("waiting").addClass("banCurrent");
		banCurrent.removeClass("banCurrent").addClass("waiting").css('opacity','1.0');
				
		nextId+=1;
		if (nextId == numberOfPics)
			nextId=0;
		
		currentId=nextId-1;
		if (currentId == -1)
			currentId=2;
		
		jQuery('#photoShow .waiting img').attr('src',"/img/" + imgArray[nextId]);
		jQuery('#photoShow .waiting a').attr('href', link[nextId]);
		
		updateButtons();
		
		animating=false;
		timer=setTimeout("animateRotation()", HOLDTIME);
	});		
}

function rotateSpecific(rotateId) {
	
	if(!animating) {
		animating=true;
		
		nextId=rotateId;
		jQuery('#photoShow .waiting img').attr('src',"/img/" + imgArray[nextId]);
		jQuery('#photoShow .waiting a').attr('href', link[nextId]);
		
		clearTimeout(timer);	
		animateRotation();
	}
}

function createButtons() {
		
	for(var k = 0; k < numberOfPics; k++) {
	//Create first selected box
		if (k!=0) { jQuery('#numberBoxes').append('<span id="but' + k + '" style="font-size:12px;"><strong>' + title[k] + '</strong></span>'); }
		else { jQuery('#numberBoxes').append('<span id="but' + k + '" style="font-size:12px;" class="selected"><strong>' + title[k] + '</strong></span>'); }
	}

	m = numberOfPics * boxWidth;
	jQuery('#numberBoxes').css({ left: (offsetX - m)});
	
	for (var i=0;i<3;i++)
		jQuery('#but'+i).click(function(){rotateSpecific(parseInt($(this).attr('id').charAt($(this).attr('id').length-1)))});
}

function updateButtons() {

	jQuery('span[id^=but]').removeClass('selected');
	jQuery("#but"+ currentId).addClass("selected");
}
