window.addEvent('domready', function() {
	
	//create an Array
	holgaArray = $$(".photo");
	
	//initialize counter
	actual = 0;
	prev = holgaArray.length-1;
	
	//start first transition automatically
	nextPhoto();
	
	//this flag stop the click Event during transitions
	transitionsEnd = false;
	
	//add Events
	$('next').addEvent('click', function(e){
		e.stop();
		if(transitionsEnd){
			increaseCounter();
			nextPhoto();
		}
	});
	
	$('prev').addEvent('click', function(e){
		e.stop();
		if(transitionsEnd){
			decreaseCounter();
			prevPhoto();
		}
	});
	
	function increaseCounter(){
		actual++;
		prev = actual-1;

		if(actual >= holgaArray.length || actual == 0){
			actual = 0;
			prev = holgaArray.length-1;
		}
	}
	
	function decreaseCounter(){
		actual--;
		prev = actual+1;

		if(actual < 0){
			actual = holgaArray.length-1;
			prev = 0;
		}else if(actual == holgaArray.length){
			actual = 0;
			prev = actual+1
		}
	}

	
	function nextPhoto(){
		transitionsEnd = false;
		$(holgaArray[actual]).set("class", "goLeft");
		//I add an Event Listener to listen the end of Transition - CSS3 transitions supports CALLBACKS
		$(holgaArray[actual]).addEventListener('webkitTransitionEnd', backtoTop ,false );
	}
	
	function prevPhoto(){
		transitionsEnd = false;
		$(holgaArray[actual]).set("class", "goRight");
		//I add an Event Listener to listen the end of Transition - CSS3 transitions supports CALLBACKS
		$(holgaArray[actual]).addEventListener('webkitTransitionEnd', backtoTop ,false );
	}
	
	function backtoTop(){
		$(holgaArray[actual]).set("class", "goTop");
		$(holgaArray[actual]).removeEventListener('webkitTransitionEnd', backtoTop ,false );
		$(holgaArray[actual]).addEventListener('webkitTransitionEnd', hidePrev ,false );
		$(holgaArray[prev]).set("class", "goBottom");
	}
	
	function hidePrev(){
		$(holgaArray[actual]).removeEventListener('webkitTransitionEnd', hidePrev ,false );
   		//Now  		
		transitionsEnd = true;
		//you can enlarged the actual photo
		$(holgaArray[actual]).set("class", "onTop");
		//toggle class "goBottom" from previous photo
		$(holgaArray[prev]).set("class", "");
	}

});