// Copyright 2010 University of California, Berkeley Integrative Biology.

/**
 * @fileoverview Banner code for main UCB IB homepage. Requires gweb library
 * located at http://www.google.com/js/gweb/core.js;
 * @author mrigoli@gmail.com (Mike Rigoli)
 */

/**
 * Create berkib namespace if it hasn't already been created.
 */
var berkib = berkib || {};



/**
 * Banner constructor.
 * @constructor
 */
berkib.Banner = function(bannerDict) {
  this.BANNER_CONTROLS = gweb.dom.getElementsByTagNameAndClass('li', null, gweb.dom.getElement('banner-control'));
  this.AUTO_ROTATE_INTERVAL = 10000;
  this.FADE_INTERVAL = 300;
  this.controlDict = bannerDict;
  this.eventInit();
  this.autoRotate();
};


/***
 * Display function
 */
berkib.Banner.prototype.display = function(target) {

  for (var i = 0; i < this.BANNER_CONTROLS.length; i++) {
    var controlStyle = this.BANNER_CONTROLS[i].style;
    gweb.dom.getElement(this.controlDict[this.BANNER_CONTROLS[i].id][0]).style.display = 'none';

    if (target.id == this.BANNER_CONTROLS[i].id) {
      controlStyle.backgroundColor = this.controlDict[target.id][1][1];
    } else {
      controlStyle.backgroundColor = this.controlDict[target.id][1][0];
    }
  }

  gweb.fx.fadeIn(gweb.dom.getElement(this.controlDict[target.id][0]), this.FADE_INTERVAL);
  gweb.dom.getElement(this.controlDict[target.id][0]).style.display = 'block';
};

/**
 * Sets up events and behavior for the banner and its UI.
 */
berkib.Banner.prototype.eventInit = function () {
  for (var i = 0, len = this.BANNER_CONTROLS.length; i < len; i++) {
    gweb.events.listen(this.BANNER_CONTROLS[i], 'click', function(e) {
      clearInterval(this.randomRotation);
      this.display(e.target);
      e.target.style.backgroundColor = this.BANNER_CONTROLS_DOWN_STATE_COLOR;
    }, null, this);
  }
}

berkib.Banner.prototype.generateRandomNumber = function() {
  return Math.floor(Math.random() * this.BANNER_CONTROLS.length);
}

berkib.Banner.prototype.autoRotate = function() {
  var winLoadRandNum = this.generateRandomNumber();
  this.display(this.BANNER_CONTROLS[winLoadRandNum]);
  this.BANNER_CONTROLS[winLoadRandNum].style.backgroundColor = this.BANNER_CONTROLS_DOWN_STATE_COLOR;

  this.randomRotation = setInterval(gweb.bind(function() {
    var randNum = this.generateRandomNumber();
    this.display(this.BANNER_CONTROLS[randNum]);
    this.BANNER_CONTROLS[randNum].style.backgroundColor = this.BANNER_CONTROLS_DOWN_STATE_COLOR;
  }, this), this.AUTO_ROTATE_INTERVAL);
};

