
var gallery = {};

$(document).ready(function() {

	var count = 0;
	$(".gallery-images .block").each(function(){
		count ++;
		if(count > 1){
			$(this).remove();
		}
	}); 
	
	var viewRows = $(".gallery-images .views-row");
	if (viewRows.length > 1){
		count = 0;
		var pagerHtml = "";
		viewRows.each(function(){
			count ++;
			$(this).addClass("views-row-" + count);
			$(this).attr("command", count);
			var classes = "pager-item ";
			classes += " pager-"+count + " ";
			if(count == 1){ classes += " pager-item-first ";}
			if(count == viewRows.length){ classes += " pager-item-last ";}
			
			pagerHtml += "<div class=\""+classes+"\" command=\""+count+"\" ></div>";
		}); 
		
		// add pager
		
		$(".gallery-pager-left").css('display','inline');
		$(".gallery-pager-left").css('width',(count) * 22 -4);
		$(".gallery-pager-center").html(pagerHtml);
		
		//
		gallery.count = count;
		//clearTimeout(gallery.timer);
		gallery.timer = setTimeout( "nextImage()", 8000 );
		
		//nextImage();
		$(".gallery-pager-center .pager-item:first").addClass("active");
		$(".gallery-images .views-row").css({'z-index': 50});
		$(".gallery-images .views-row:first").css({'z-index': 51});
		$(".gallery-images .views-row:first").addClass("active");
		
		$(".gallery-pager-center .pager-item").click(function(){
			
			var target = $(".gallery-images .views-row-"+$(this).attr("command"));
			
			if(!target || target.length == 0){
				//target = $(".gallery-images .views-row:first");
			} else {
				showImage(target, 500);	
			}
			
			
		});
		
	}
	
});

function getCurrentImage(){
	var current = $(".gallery-images .active");
	
	if(!current || current.length == 0){
		current = $(".gallery-images .views-row:last");
	}
	return current;
}

function nextImage(){
	
	var current = getCurrentImage();
		
	var target = current.next();
	if(!target || target.length == 0){
		target = $(".gallery-images .views-row:first");
	}
	
	showImage(target);	
}

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

	var current = getCurrentImage();

	$(".gallery-images .views-row").removeClass("active");
	target.addClass("active");
	
	$(".gallery-images .views-row").css({'z-index': 50});
	current.css({'z-index': 51});
	target.css({'z-index': 52, 'opacity': 0});
	target.animate({'opacity': 1}, 1000);
	
	clearTimeout(gallery.timer);
	gallery.timer = setTimeout( "nextImage()", 8000 );
	
	$(".gallery-pager-center .pager-item").removeClass("active");
	$(".gallery-pager-center .pager-" + target.attr("command")).addClass("active");
}

