document.observe('dom:loaded', function() {
	var pictureElements = document.getElementsByClassName('csc-textpic-imagewrap');

	for (var counter = 0; counter<pictureElements.length; counter++) {
		
		var images = pictureElements[counter].getElementsByClassName('lightboxSpan');
		
		if(images[0]) {
			var firstlink = images[0].getElementsByTagName('a');
			
			if (RegExp('rotateall').test(firstlink[0].getAttribute('rel'))) {
				
				var imageboxes = pictureElements[counter].getElementsByClassName('csc-textpic-image');
				
				var maxheight = 0;
				maxheight *= 1;
				
				for (var count=0; count<imageboxes.length; count++) {					
					var imagetags = imageboxes[count].getElementsByTagName('img');
					var imageheight = imagetags[0].getAttribute('height');
					imageheight *= 1;
					
					if (imageheight >= maxheight) {
						maxheight = imageheight;
					}
					
					if (count > 0) {
						imageboxes[count].setStyle({
							display: 'none'
						});
					}
				}
				
				maxheight = maxheight + 30;
				
				pictureElements[counter].setStyle({
					height: maxheight + 'px'
				});
				
				startRotateImageAnimation(imageboxes, 0);
			}
		}
	}
});

function startRotateImageAnimation(imageboxes, rand){
	new Effect.Appear(imageboxes[rand], {queue:'end', duration: 1, from: 0.01, to:  1});
	
	window.setTimeout(
		function () {
			new Effect.Fade(imageboxes[rand], {queue:'end', from: 1, to: 0.01, duration: 1, afterFinish: function(effect) {
				
				var random = Math.floor(Math.random()*(imageboxes.length-1));
				
				imageboxes[random].setStyle({
					display: 'block'
				});                                             
				if (rand != random) {
					imageboxes[rand].setStyle({
						display: 'none'
					});
				}
				
				startRotateImageAnimation(imageboxes, random);
				
			}});
			
		}, 4000
	);
}


