// always remove outlines
$("a").each(function(){
	this.onmouseup = this.blur();
});
// document ready
$(document).ready(function() {
	// user settings
	siftSpeed = 3800; // how often to switch slides
	actionPause = 8800; // how long to pause if action

	// internal script settings
	// (do not change below here unless you know what you're doing)
	var images = $("#gallery img");
	var thumbs = $("#thumbs");
	var thumbimages = $("#thumbs img");
	var thumblinks = $("#thumbs a");
	var thumbslist = $("#thumbs ul");
	var thumbitems = $("#thumbs li");
	var index = thumbitems.length-1;
	var thumbsHeight = 100;
	var areaHeight = 300;


	
	
	
	
	// clone markup for thumbs to create thumbs above the last thumb
	thumbitems.slice(0, 1).clone().attr('rel', '2').appendTo(thumbslist);
	thumbitems.slice(1, 2).clone().attr('rel', '2').appendTo(thumbslist);
	thumbitems.slice(2, 3).clone().attr('rel', '2').appendTo(thumbslist);

	// assign css classes to images and thumbs
	for (i=0; i<thumbimages.length; i++) {
		var tdiff = (images.length - i - 1);
		//$(thumbimages[i]).addClass("thumb-"+tdiff);
		$(images[i]).addClass("image-"+tdiff);
	}

	// reverse the order of the thumbs
	thumbslist.children().each(function(i,li){thumbslist.prepend(li)});

	// run the show function to show the first image
	show(index);

	// run the sift function every so often
	var $timer = setInterval(function() { sift(); }, siftSpeed);

	function sift(num) {
		if(num) { index = num; }
		if ( index < thumbimages.length && index > 0) {index -= 1 ; }
		else { index = thumbimages.length-1 }
		show ( index );
	}
	function show(num) {
		images.fadeOut(200);
		$("img.image-"+num).stop().fadeIn(1200);
		var scrollPos = (num * thumbsHeight) - areaHeight;
		if(scrollPos < 400) scrollPos = scrollPos + areaHeight;
		if (num == thumbitems.length-1 || num > thumbitems.length-4) {
		    thumbs.stop().animate({scrollTop: scrollPos+thumbsHeight}, -1).animate({scrollTop: scrollPos}, 200);
		    console.log("number: "+num, ", scrollPos: "+scrollPos+"+"+thumbsHeight, ", duration: -1");
		} else {
		    thumbs.stop().animate({scrollTop: scrollPos}, 200);
		}
		console.log("number: "+num, ", scrollPos: "+scrollPos, ", duration: 200");
	}

	// after the actionPause takes place start the timer again
	function resetTimer() {
	    clearInterval($timer);
	    $timer = setInterval(function() { sift(); }, siftSpeed);
	}

	// add onclick function to thumb links
	thumbslist.find('a').each(function(){
		$(this).click(function() {
		    var showid = $(this).attr("class");
		    console.log("showid: "+showid, ", timer: "+$timer);
		    show(showid);
		    index = showid;
		    clearInterval($timer);
		    var $timer = setTimeout(resetTimer, actionPause);
		    return false;
		});
	});
});
