$(window).load(function() {
	var photoIndex;
	var frames = ['frame1', 'frame2', 'frame3', 'frame4'];
	var framesDump = [];
	var frame1Deg = -2.5;
	var frame2Deg = 0;
	var frame3Deg = 1.9;
	var frame4Deg = 3.1;
	var start = true;

	var photos = $('<div></div>');
	var photosDump = $('<div></div>');
	$('#photos .slide').css({visibility:'visible', display:'none'}).appendTo(photos);

	function randomXToY(minVal,maxVal)
	{
	  var randVal = minVal+(Math.random()*(maxVal-minVal));
	  return Math.round(randVal);
	}

	var play = function() {
		var i = Math.floor(Math.random() * frames.length);

		fade(i);

		framesDump.push(frames[i]);
		frames.splice(i,1);
		if(frames.length == 0) {
			frames = framesDump;
			framesDump = [];
		}

		setTimeout(play, randomXToY(1000, 2000));
	}

	var fade = function(i) {
		photoIndex = Math.floor(Math.random() * $(photos).children().length);

		/* set old element */
		$('#photos .'+frames[i]).removeClass('new').addClass('old');

		nth = parseInt(photoIndex)+parseInt(1);

		/* set new element */
		$(photos).children(':nth-child('+nth+')').addClass(frames[i]+' new').appendTo('#photos');

		$('.'+frames[i]+'.new').css({visibility:'hidden', display:'block'}).rotate({angle: eval(frames[i]+'Deg'), callback: function() {
			$('.'+frames[i]+'.new').css({visibility:'visible', display:'none'}).fadeIn(500, function() {
				$('.old').appendTo($(photosDump)).attr('class', 'slide');
				if($(photos).children().length == 0) {
					$(photosDump).children().appendTo($(photos));
				}
			});
			$('.'+frames[i]+'.old').fadeOut(600);
		}});
	}

	for (i=0;i<frames.length;i++) {
		$('#'+frames[i]).hide().css('visibility', 'visible').fadeIn(600);
		fade(i);
	}

	setTimeout(play, 2000);
});
