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',
							opacity: '0.01'
						});
					}
				}
				
				maxheight = maxheight + 30;
				
				pictureElements[counter].setStyle({
					height: maxheight + 'px'
				});
				
				startRotateImageAnimation(imageboxes, 0 ,0);
			}
		}
	}
});

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

