var Promotions = function(dom_id, channel) {
  this.currentIndex = 0;
  this.items = [];
  this.dom_id = '#' + dom_id;
  this.image_path = '/images/barkers/';
  this.channel = channel
}

Promotions.prototype = {
  add: function(data) {
    this.items.push(data);
  }
  ,
  getItem: function(index) {
    var length = this.items.length;
    if (length == 0) return null;
    if (index < 0) index = 0;
    
    while(index > length) index -= length;
    return this.items[index];
  }
  ,
  html: function(index) {
    var promotion = this.getItem(index);
    if (promotion == null) return null;
    
    var template = 
      '<div class="promotion content clearfix" style="display: none;" id="DOM-ID">'
    + '  <a href="URL" onClick="javascript: pageTracker._trackPageview(\'/' + this.channel +  '/brandpromo/TRACK_GA\');" target="_blank"><img src="SRC" alt="image" /></a>'
    + '  <div class="actionlink"><a href="URL" onClick="javascript: pageTracker._trackPageview(\'/' + this.channel +  '/brandpromo/TRACK_GA\');" target="_blank">TITLE</a></div>'
    + '</div>';
    
    // promotion.src is a complete path
    if (promotion.src.indexOf('/') > -1) {
        template = template.replace(/SRC/g, promotion.src);
        
    // DEPRECATED: promotion.src is only the filename, prepend the image path
    } else {
        template = template.replace(/SRC/g, this.image_path + promotion.src);
    }
      
    return template.
      replace(/DOM/g, this.dom_id.slice(1)).
      replace(/ID/g, index).
      replace(/URL/g, promotion.url).      
      replace(/TITLE/g, promotion.title).
      replace(/TRACK_GA/g, promotion.url.replace( "http://", "" ).toLowerCase());
  }
  ,
  render: function(index) {
    if (index == null) index = this.currentIndex;
    $(this.dom_id + '-' + index).show();
  }
  ,
  build: function() {
    var html = [];
    for(var i = 0; i < this.items.length; i++) {
      html.push(this.html(i));
    } // end for

    html = html.join("\n");
    // alert(html);
    // console.log($('#promotions div.contentWrap').html());
    $(this.dom_id + ' div.contentWrap').html(html);
  }
  ,
  run: function() {
    this.build();
    this.render();
    
    // data  = "Asset:\n";
    // data2 = "Brand:\n";
    // for(i = 0; i < this.items.length; i++) {
    //   item = this.items[i];
    //   data += "  " + item.title + ":\n" +
    //           "    type_id: 1\n" +
    //           "    name: " + item.src + "\n" +
    //           "    path: html/images/barkers/" + item.src + "\n"
    //           ;
    //   
    //   data2 += "  " + item.title + ":\n" +
    //            "    name: " + item.title + "\n" +
    //            "    url:  " + item.url + "\n"
    //            ;
    // }
    // 
    // document.write('<pre>' + data + data2);
    
    
    $(this.dom_id + ' div.contentWrap').innerfade({timeout: 4000, containerHeight: '145px' });
  }
}