window._imageCache = [];
var PhotoRotator = Class.create({
  initialize: function(params) {
    this._container    = $(params.imageContainer) || null;
    this._mapAgainst   = $(params.map)            || null;
    this._images       = $A(params.imageList)     || [];
    this._rotateSpeed  = params.speed             || 3;
    this._fadeDuration = params.duration          || 3.0;
    this._whtl         = {};
    this._ptr          = 0;
    this._run          = false;
    if (this._images.size() > 1) {
      this._init();
    }
  },
  _init: function() {
    this._mapAgainst.absolutize();
    var widthHeight = this._mapAgainst.getDimensions();
    var topLeft     = this._mapAgainst.positionedOffset();
    this._whtl = {
      width:  widthHeight.width,
      height: widthHeight.height,
      top:    topLeft.top,
      left:   topLeft.left
    };
    var inlineStyle = 'top:' + this._whtl.top + 'px;left:' + this._whtl.left +
                      'px;position:absolute;display:none;z-index:1;';
    for (var i = 0; i < this._images.size(); i++) {
      window._imageCache[i] = new Element('img', {
        style:  inlineStyle,
        width:  this._whtl.width,
        height: this._whtl.height,
        src:    this._images[i]
      });
    }
    this._images = null;

    this._container.insert({top:window._imageCache[0]});
    new PeriodicalExecuter(function(pe) {
      window._imageCache[0].show();
      this._mapAgainst.fade({
        duration: this._fadeDuration,
        afterFinish: function() {
          this._mapAgainst.remove();
          this._run = true;
        }.bind(this)
      });
      pe.stop();
    }.bind(this), this._rotateSpeed);

    new PeriodicalExecuter(function() {
      this._rotate();
    }.bind(this), this._rotateSpeed);

    if (Prototype.Browser.IE) {
      // Make sure the 'view more photos' link and image show above the
      // rotating images.
      $('curled_page').up('a').setStyle({
        zIndex: 1000,
        marginTop: '-7px'
      });
    }
  },
  _rotate: function() {
    if (!this._run) {
      return;
    }
    window._imageCache[this._ptr].style.zIndex = 75;
    this._ptr++;
    if (this._ptr == window._imageCache.size()) {
      this._ptr = 0;
    }
    window._imageCache[this._ptr].style.zIndex = 1;
    this._container.insert({top:window._imageCache[this._ptr]});
    window._imageCache[this._ptr].show();
    var fadeIndex = (this._ptr == 0) ? window._imageCache.size() - 1 : this._ptr - 1;
    window._imageCache[fadeIndex].fade({
      duration: this._fadeDuration,
      afterFinish: function() {
        window._imageCache[fadeIndex].remove();
      }.bind(this)
    });
  }
});