	
function count() {
	if( $("#page_margins").width() >= 480 ) {
		for (i in slideshows) {
			slideshows[i].count();
		}
	}
}

var slideshows;


$(document).ready(function() {


	function Slideshow( element ) {

		var slideshowDiv = element;
		var currentSlide = 0;
		var container = element.find(".slide_container");
		var numberOfSlides = container.children().length;
		var duration = 1800;
		var fadeTime = 1500;
		var counter = 0;
		
		// controls:
		slideshowDiv.find(".slideshow_slide").each( function() {	

			var button = $("<li><span>#</span></li>");
			slideshowDiv.find(".slideshow_controls").append( button );
		
			button.click( function() {
				$(this).parent().find("li").removeClass("active");
				$(this).addClass("active");
				changeTo( $(this).index() );
			});
		});
		//slideshowDiv.find(".slideshow_controls li:first").addClass("active");

		if( numberOfSlides > 1 ) {
			slideshowDiv.find(".slideshow_controls").css("display","block");
		}

		var changeTo = function( slideIndex ) {
			
			container.find(".slideshow_slide").each( function() {
				if( $(this).index() == slideIndex ) {
					$(this).fadeIn(fadeTime, function() {
						$(this).css("filter","");							  
					});
				}
				else {
					$(this).fadeOut(fadeTime);	
				}
			});
			currentSlide = slideIndex;
			
			counter = 0;
		};
		slideshowDiv.find(".slideshow_controls li:first").click();

		return {
			count: function() {
				counter++;
				if( counter >= duration ) {
					var newIndex = (currentSlide+1)%numberOfSlides;
					slideshowDiv.find(".slideshow_controls li:nth-child("+(newIndex+1)+")").click();
					counter = 0;
				}

			}
		};
		
	}
	
    function init() {
    	$($(".slide_container").children()[0]).fadeIn(1500);
    }
	
	slideshows = new Array();
	
	$(".slideshow").each( function() {
		slideshows.push( new Slideshow( $(this) ) );
	});

	// init slideshow
	init();
	
	// start slideshow
	handle = window.setInterval("count()", 1);
});
