var gallery = {};

$(document).ready(function() {

	var count = 0;
	$("#slideshow").each(function(){
		count ++;
		if(count > 1){
			$(this).remove();
		}
	}); 
	
	// Get slides
	var viewRows = $("#slideshow .slide");
	
	// If more than one slide, animate them
	if (viewRows.length > 1){
		count = 0;
		var pagerHtml = "";
		viewRows.each(function(){
			count ++;
			
			// Add unique class and command attribute
			$(this).addClass("slide-" + count);
			$(this).attr("command", count);
			
			// Create pager items
			var classes = "slide-page-item ";
			classes += " pager-"+count + " ";
			pagerHtml += "<div class=\""+classes+"\" command=\""+count+"\" ></div>";
		}); 
		
		// Add pager
		$("#slide-page").html(pagerHtml);
		
		// Set timer for first slide change
		gallery.timer = setTimeout( "nextImage()", 5000 );
		
		// Add classes & css slides and first pager
		$("#slide-page .slide-page-item:first").addClass("active");
		$("#slideshow .slide").css({'z-index': 50});
		$("#slideshow .slide:first").css({'z-index': 51});
		$("#slideshow .slide:first").addClass("active");
		
		// Add onlick function to pagers
		$("#slide-page .slide-page-item").click(function(){
			var target = $("#slideshow .slide-"+$(this).attr("command"));		
			if(target || target.length != 0) showImage(target, 500)
		});
	}
});

function getCurrentImage(){
	var current = $("#slideshow .active");	
	if(!current || current.length == 0) current = $("#slideshow .slide:last");
	return current;
}

// Show next slide
function nextImage(){
	var current = getCurrentImage();
	var target = current.next();
	if(!target || target.length == 0) target = $("#slideshow .slide:first");
	showImage(target);	
}

function showImage(target, speed){
	
	// Default speed
	if(!speed || speed == "undefined") speed= 1000;

	// Get current slide
	var current = getCurrentImage();

	// Remove active class and reset z-index
	$("#slideshow .slide").removeClass("active");
	$("#slideshow .slide").css({'z-index': 50});

	// Set current slide z-index
	current.css({'z-index': 51});	
	
	// Add active class to new slide, and fade in
	target.addClass("active");
	target.css({'z-index': 52, 'opacity': 0, 'position': 'absolute'});
	target.animate({'opacity': 1}, speed);
	
	// Reset timer
	clearTimeout(gallery.timer);
	gallery.timer = setTimeout( "nextImage()", 5000 );
	
	// Change active pager
	$("#slide-page .slide-page-item.active").removeClass("active");
	$("#slide-page .pager-" + target.attr("command")).addClass("active");
}
