
var cloud_manager = function (cloud_div, cloud_list) {
  this.cloud_div = cloud_div;
  this.clouds = $(cloud_div).children("img");
  this.locs = [];
  this.speeds = [];
  this.images = cloud_list;

  var that = this;
  this.clouds.each(function () {
    that.locs.push($(this).position().left);
    that.speeds.push((Math.random() * 0.9) + 0.2);
  });
  
  setTimeout(function () { that.step() }, 100);
}

cloud_manager.prototype.step = function () {
  var len = this.locs.length;
  var boundry = $(window).width();
  for (var i = 0; i < len; i++) {
    this.locs[i] += this.speeds[i];
    $(this.clouds[i]).css({"right": this.locs[i] + "px" });

    if (this.locs[i] > boundry + $(this.clouds[i]).width()) {
      this.destroyCloud(i);
      this.spawnCloud();
    }
  }
  var that = this;
  setTimeout(function () { that.step() }, 40);
}

cloud_manager.prototype.destroyCloud = function (idx) {
  $(this.clouds[idx]).remove();
  this.locs.splice(idx, 1);
  this.speeds.splice(idx, 1);
}


cloud_manager.prototype.spawnCloud = function () {
  var img = $('<img src="img/' + this.rndImage() + '" />');
  var h = this.cloud_div.height();

  img.css({ "right" : "-200px", "top" : Math.random() * h + "px" });

  this.cloud_div.append(img);
  this.clouds = $(this.cloud_div).children("img");
  this.locs.push(-200);
  this.speeds.push((Math.random() * 0.9) + 0.3);
}

cloud_manager.prototype.rndImage = function () {
  var rnd = this.lastRnd;
  while (rnd == this.lastRnd)
        rnd = Math.floor(Math.random() * this.images.length);
  this.lastRnd = rnd;
  return this.images[rnd];
}


