/*
 * Keep randomly an element according to a probability distribution.
 * If fn is not specified returns a random item.
 * @param {Function} fn Is't the function that, given an array item, returns the probability.
 * @return {Object} The randomly selected array item.
 */
Array.prototype.random = function(fn) {
    var l = this.length;
    if (l == 0) throw "The array cannot be empty";
    if (!fn) return this[Math.floor(Math.random() * l - 1)];

    var rnd;
    do {
        rnd = Math.floor(l * (Math.random() % 1));
    }
    while (Math.random() > fn(this[rnd]))
    {
        return this[rnd];
    }

    throw "Unexpected error";
}

String.prototype.format = function() {
    var txt = this;
    for (var i = 0; i < arguments.length; i++) {
        var exp = new RegExp('\\{' + (i) + '\\}', 'gm');
        txt = txt.replace(exp, arguments[i]);
    }
    return txt;
}

var yahoo = function() {
}

/*
* Banner Rotator widget.
*/
function BannerRotator(format, data) {
    if (!format) throw "format cannot be empty";

    this.format = format;
    this.data = data;
}

BannerRotator.prototype.prob = function(item) {
    return item.prob;
}

BannerRotator.prototype.advercy = function() {
    var b = Banner[this.campaign.campaignid];
    if (!b) throw "No banner defined for campaign " + this.campaign.campaignid;

    var f = b[this.format];
    if (!f) throw "No banner defined for format " + this.format + " for the campaign " + this.campaign.campaignid;

    // Code to track the click.
    document.write('<img src="{0}/scripts/click.php?a_aid={1}&a_bid={2}&data1={3}" />', root_url, a_aid, f.a_bid, this.data);

    // Code to emit the banner.
    document.write('<script type="text/javascript" src="{0}/scripts/banner.php?a_aid={1}&a_bid={2}"></script>', root_url, a_aid, f.a_bid);
}



BannerRotator.prototype.run = function() {
    // Select randomly a campaign.
    this.campaign = Campaign.random(this.prob);

    // Run the randomly selected campaign.
    if (typeof this.campaign.src != "function")
        throw "Campaign source not recognized";

    this.campaign.src.apply(this, new Array( this.data, this.format, this.campaign[ "campaignid" ] ));

    
    
}
