jQuery(function() {				
	
	// random number
	rand = function(l,u)
	 {
	     return Math.floor((Math.random() * (u-l+1))+l);
	 }

	// Animations
	function animateSmoke() {
		jQuery("#smoke").css({'opacity':0, 'visibility':'visible'}).animate({'opacity':1},1000, function(){
			setTimeout(function() {
				jQuery("#smoke").animate({'opacity':0},1000);
			}, 500);
		});
	}
	
	
	
	function animateSky(element){
		var container = jQuery('#containment-wrapper');
		var minLeft = container.offset().left + container.width() - element.width() - 115;
		var minTop = container.offset().top + element.height() + 100;
		var maxTop = minTop + container.height() - element.height() - 200;			
		var actualTop = rand(minTop, maxTop);
		var speed = rand(15000, 30000);
		element.css({'left':minLeft, 'top':actualTop}).fadeIn(500).animate({
			'left': container.offset().left + 20
		}, speed).fadeOut(500);
		setTimeout(function(){
			animateSky(element);
		}, speed+1000);
	}
	
	// on ready
	
	jQuery(document).ready(function(){
		
		animateSky(jQuery("#sky1"));
		setTimeout(function() {
			animateSky(jQuery("#sky2"));
		}, 10000);
		setTimeout(function() {
			animateSky(jQuery("#sky3"));
		}, 20000);
		
		jQuery(".sky").bind('click', function(){
			jQuery(this).stop().fadeOut(500, function(){
				jQuery(this).remove();
			});
		});
	});
	
	// Make em draggable! 
	jQuery("#icons").draggable({ 
		containment: '#containment-wrapper', 
		scroll: false, 
		revert: 'invalid'
	});
	jQuery("#interface").draggable({ 
		containment: '#containment-wrapper', 
		scroll: false, 
		revert: 'invalid'
	});
	jQuery("#type").draggable({ 
		containment: '#containment-wrapper', 
		scroll: false, 
		revert: 'invalid'
	});
	
	// Make it droppable!
	jQuery("#droppable").droppable({
		drop: function(event, ui) {
			var that = jQuery(this);
			var container = "#" + ui.draggable.attr('alt');
			ui.draggable.css('opacity',0);
			jQuery(container).find("img").fadeOut(500, function(){
				$(this).next().fadeIn(500);
			});
			setTimeout(function() {
				that.animate({'opacity':0},1000, function(){
					that.removeClass('hovering');
				});
			}, 300);
			animateSmoke();
			jQuery('html,body').animate({scrollTop: jQuery('#containment-wrapper').offset().top}, 500);
		},
		over: function(event, ui) { 
			jQuery(this).addClass('hovering').animate({'opacity':1},1000);
		},
		out: function(event, ui) {
			jQuery(this).stop().animate({'opacity':0},1000, function(){
				jQuery(this).removeClass('hovering');
			});
		} 	
	});
});