
// Can edit the following variables:
var Classes = ["img1", "img2", "img3", "img4"]; // Classes to load
var Timeout = 4000; // Timeout between slides.
var Fade = 1000; // Time it takes to fade.

// Do not edit variables bellow this line:
var Current = 0;
var Mouseover = false
var LastTime = 0;

// In Array function
Array.prototype.in_array = function(val) {
	for(var z = 0, l = this.length; z < l; z++) {
		if(this[z] == val) {
			return z;
		}
	}
	return -1;
}

function curTime() {
    return( new Date().getTime() );
}

$(document).ready(function() { 
	// Run the fader
	setTimeout("fade()", Timeout);
	
	// Buttons hover
	$('.buttons img').hover( function() { 
		if( LastTime > 0 && (curTime() - LastTime) <= ( Timeout * 0.2 ) ) {
			return;
		}
		
		LastTime = curTime();
		
		Mouseover = true;
		
		var ImgId = $(this).attr("id");
		
		// Fade out existing item
		$('.' + Classes[ Current ]).fadeOut("slow", function() {
			$('.' + ImgId).fadeIn("slow", function() {
				// Update the current
				Current = Classes.in_array( ImgId );
			});
		});
		
	}, function() {
		Mouseover = false;
		setTimeout("fade()", Timeout);
	});
	
});

function fade() {
	if( Mouseover == true) return;
	
	// Run yet?
	if( LastTime > 0 && (curTime() - LastTime) <= ( Timeout * 0.9 ) ) {
		return;
	}

	var Next = ( Current == ( Classes.length - 1 ) ) ? 0 : Current + 1;

	// Hide everything
	for(var z = 0, l = Classes.length; z < l; z++) {
		if( z != Current ) {
			$('.' + Classes[ z ]).hide();
		}
	}

	// Only run if we haven't hovered over a button.
	if( Mouseover == false ) {
		$('.' + Classes[ Current ]).fadeOut(Fade, function() {
			if( Mouseover == false) {
				$('.' + Classes[ Next ]).fadeIn(Fade);
			}
		
			Current++;
			if( Current == ( Classes.length ) ) Current = 0;
			
			// Run again
			LastTime = curTime();
			setTimeout("fade()", Timeout);
		});
	}
}
