var refreshEvery = 30.0;
var runningX = 0;

Array.prototype.removeItemAtIndex = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

anims = new Array();
function Animation(id)
{
	this.id= id;
	this.u = randomIntBetween(15, 50);
	this.a = 0.0;
	this.t = new Date();
	
	this.move = function()
	{
		if (!this.id.length)
			return;

		var el = document.getElementById(id);
		if ((typeof el) == "undefined" || !el)
			return;
		
		
		
		var now = new Date();
		var dt = (now.getTime() - this.t.getTime()) / 1000;
		var stringLeft = el.style.left;
		
		if (parseFloat(stringLeft) - parseFloat(el.style.width) > window.innerWidth)
		{
			//alert("and OUT");
			anims.removeItemAtIndex(anims.indexOf(this));
			runningX = randomIntBetween(0, 200);
			initCloud(Number(this.id.substring(5)));
		
		}
		else
		{					
			el.style.left = parseFloat(stringLeft) + this.u * dt + this.a * Math.pow(dt, 2) / 2.0; //Thank god I did Mechanics and not Statistics
			this.u += this.a * dt;
			this.t = now;
		}
	}
	
}

function randomIntBetween(x, y)
{
	return Math.floor(Math.random()*(y+1)) + x;
}
function randomFloatBetween(x, y)
{
	return Math.random()*(y+1) + x;
}



function initCloud(n)
{
	
	var cloud = document.getElementById("cloud" + n);
	cloud.style.left = - parseFloat(cloud.style.width) - runningX - parseFloat(cloud.style.width);
	runningX = -parseFloat(cloud.style.left);
	if (n == 5)
		runningX = 0;

	cloud.style.top = randomIntBetween(-parseFloat(cloud.style.height)/2 + 37, 100);
	cloud.style.visibility = "visible";
  
	var cloud1Anim = new Animation(cloud.id);
	anims.push(cloud1Anim);
}

function onload()
{
	initCloud(1);
	initCloud(2);
	initCloud(3);
	initCloud(4);
	
	setTimeout(refresh, refreshEvery);
}
function refresh()
{
	for (var i = 0; i < anims.length; i++)
	{
		anims[i].move();
	}
	
	setTimeout(refresh, refreshEvery);
}
