/*
Written by Ben Norskov in Feb. 2011
*/

var current = 0;
var next = current+1;
var elements_to_fade;
var fade_time = 1000;
var wait_time = 6000;

var dots;
var elapsed_time = 0;
var waiter = "";

$(document).ready(function(){
	//set all the elements with the "main_pic_holder" class to an array
	elements_to_fade = $("*.main_pic_holder");
	
	/// all the dot elements
	dots = $("#dots a");
	$(dots).click( function() {
		//add click listener to dots
		changePic($(this));	
	});
	
	//set up wait timer
	wait();
});
function wait() {
	//alert( currentTime.getTime() - elapsed_time  );
	if (waiter == "") {
		waiter = window.setInterval( checkTime, 100);
	}
	//wait for wait_time amount then fade the next element in
	//setTimeout ( fadeNext, wait_time );
};
function checkTime() {
	elapsed_time += 100;
	if (elapsed_time >= wait_time) {
		elapsed_time = 0;
		if (waiter != "") {
		   window.clearInterval(waiter);
		   waiter = "";
		}
		fadeNext();
	}
};
function fadeNext() {
	$(elements_to_fade[current]).fadeOut(fade_time);
	$(elements_to_fade[next]).fadeIn(fade_time, increment); 
	//after the fade, increment the current and next vars
};
function increment() {
	//get the next elements to fade
	current = limit(current);
	next = limit(next);
	
	//switch dots
	$(dots).removeClass("selected");
	$(dots[current]).addClass("selected");
	//wait some more
	wait();
};
function limit(_curVar) {
	//used to make sure there isn't an out of index error
	_curVar++;
	if (_curVar >= elements_to_fade.length) {
		_curVar = 0;
	}
	return _curVar;
};
function changePic(_clickd) {
	var the_id = _clickd.attr("id").substr(4);
	for (var i = 0; i < elements_to_fade.length; i++) {
		if ( $(elements_to_fade[i]).attr("id") == the_id ) {
			current = limit(i); //-1 cause it is incremented in limit();
			next = limit(current);
			elapsed_time += wait_time;//to switch immediately
			i += elements_to_fade.length;//kicks the loop out
			checkTime();
		};
	};
};
