SBN.Poll = Class.create();
SBN.Poll.prototype = {
  
  initialize: function(poll_container) {
    this.poll_container = $(poll_container);
    this.max_width = this.poll_container.getWidth();
    this.update_interval = 13;
    this.duration = 2000;
    this.options = [];
    this.poll_background_image_length = 800;
  },
    
  animateResults: function(opts) {
    opts = Object.extend({
      renderImmediately:false
    }, opts);

    if (opts.renderImmediately) this.duration = 0;

    var effects = [];
    var options = Selector.findChildElements(this.poll_container, [".poll_option"]);
    
    options.each(function(option) {
      var poll_option_bar = Selector.findChildElements(option, [".poll_option_bar"]).first();
      poll_option_bar.poll_option_percentage = Selector.findChildElements(option, [".poll_option_percentage"]).first();
      poll_option_bar.percentage = poll_option_bar.poll_option_percentage.innerHTML.replace("%", "");
      poll_option_bar.max_width = this.max_width * poll_option_bar.percentage / 100;
      poll_option_bar.vote_count_container = Selector.findChildElements(option, [".vote_count"]).first();
      poll_option_bar.vote_count = poll_option_bar.vote_count_container.innerHTML;
      
      this.options.push(poll_option_bar);
            
      poll_option_bar.poll_option_percentage.innerHTML = "0%";
      poll_option_bar.poll_option_percentage.show();

    }.bind(this));

    this.startTime = new Date().getTime();
    this.from = 0;
    this.to = 1.0;
    
    this.timer = setInterval(
      this.step.bind(this),
      this.update_interval
    );  
  
  },
  
  step: function() {
    var time = new Date().getTime();
    if (time >= this.duration + this.startTime) {
      clearInterval(this.timer);
      this.timer = null;
      this.now = this.to;
      this.options.each(function(option) {
        option.poll_option_percentage.innerHTML = option.percentage + "%";
        option.vote_count_container.innerHTML = option.vote_count;
        var backgroundPos = (option.percentage / 100 * this.max_width) - this.poll_background_image_length;
        option.style.backgroundPosition = backgroundPos + "px";
      }.bind(this));
    } else {
      var tpos = (time - this.startTime) / (this.duration);
      var percentage_complete = (( - Math.cos(tpos * Math.PI) / 2) + 0.5) * (this.to - this.from) + this.from;
      for (var i = 0; i < this.options.length; ++i) {
        var option = this.options[i];
        option.poll_option_percentage.innerHTML = Math.round((percentage_complete * option.percentage)) + "%";
        option.vote_count_container.innerHTML = Math.round(percentage_complete * option.vote_count);
        var backgroundPos = (percentage_complete * option.max_width) - this.poll_background_image_length;
        option.style.backgroundPosition = backgroundPos + "px";
      }
    }
  }
};