"use strict";

this.name        = "market_ads_service"; 
this.author      = "spara";
this.description = "Pooling ad service";

this.$horzAdPool = [];

//public function for adding horizontal ad to pool. the parameter is the filename of the ad.
this._setHorzAd = function(ad) {
  this.$horzAdPool.push(ad);
}

this.startUp = function() {
  //add horizontal ads to pools
  for (var i = 1; i <= 379; i++) {
    this.$horzAdPool.push("market_ad_horz_" + i + ".png");
  }
}

this.startUpComplete = function() {
  //shuffle the pools
  this.$horzAdPool = this._shuffle(this.$horzAdPool);
  
	//Pools are divided to two parts to prevent the same ad to be seen in a quick succession. Pools are split into two parts and a primary part is randomly selected. When the active part is emptied, then the secondary part is used. When that is emptied too, pool is initialized and we draw from the primary part again.

  this._initHorzPool();
	this.$horzPrimary = Math.round(Math.random());
}

this._shuffle = function(pool) {
  var shuffled = new Array();
  var poolSize = pool.length;
  for (var i = poolSize; i > 0; i--) {
    shuffled.push(pool.splice(Math.floor(Math.random() * i), 1)[0]);
  }
  return shuffled;
}

this._initHorzPool = function() {
	var horzPoolSize = this.$horzAdPool.length;
  this.$horzPool = [this.$horzAdPool.slice(0, Math.floor(horzPoolSize / 2)), this.$horzAdPool.slice(Math.ceil(horzPoolSize / 2), horzPoolSize - 1)];
}

//public function that returns a random horizontal ad filename from the pool
this._getHorizontalAd = function() {
	if (this.$horzPool[this.$horzPrimary].length === 0) {
		this.$horzPrimary = (this.$horzPrimary + 1) % 2;
		if (this.$horzPool[this.$horzPrimary].length === 0) {
			this._initHorzPool();
		};
	};
	var adNum = Math.floor(Math.random() * this.$horzPool[this.$horzPrimary].length);
	return this.$horzPool[this.$horzPrimary].splice(adNum, 1)[0];
}
