var imageTimeout = null;
var imageElements = $(".event-gallery img");
var imageElementsCount = imageElements.length;
var imageCounter = 0;
var firstCall = true;
var allowed = false;

function rotateImage() {
	for (i=imageCounter;i<imageElementsCount;i++) {
		// FADE CURRENT ELEMENT OUT
		if(allowed) {
			if(!firstCall)
			{
				$(imageElements[i]).fadeOut("slow");
			
				if (i+1 == imageElementsCount)
					imageCounter = 0;
				else
					imageCounter = i + 1;
			}
			
			// FADE NEXT ELEMENT IN
			$(imageElements[imageCounter]).fadeIn("slow");
			
			imageTimeout = window.setTimeout("rotateImage()", 5000);
			firstCall = false;	
			break;
		}
	}
}

$(document).ready(function() {
	$("#pause").hide();
	$(".event-gallery").hover(
	  function () {
		  if(allowed) {
			  $("#pause").show();
		  }
	  }, 
	  function () {
	    $("#pause").hide();
	  }
    );
	$("#pause").click(function() {
		$("#pause").hide();
		$("#play").show();
		allowed = false;
    });		
	$("#play").click(function() {
		$("#pause").show();
		$("#play").hide();
		allowed = true;
		rotateImage();
    });
});