var WorkBrowser = Class.create({
  
  initialize: function(t, r, l) {
    this.imageList = new Array();
    this.target = t;
    this.currentImage=0;
    this.rule = r;
    
    if(l>1) {
      this.target.observe('click', this.nextImage.bindAsEventListener(this));
      this.target.observe('load', this._finishLoading.bindAsEventListener(this));
      this.target.observe('mouseover', this._overImage.bindAsEventListener(this));
    }
    
    var rmatch = $$(this.rule);
    for(i=0; i<rmatch.length; i++) {
      rmatch[i].observe('click', this.jumpImage.bindAsEventListener(this, i));
    }
    
  },
  
  registerImage: function(url) {
    this.imageList.push(url);
  },
  
  loadImage:function(url) {
    this._startLoading();
    this.target.src = url;
  },
  
  nextImage: function() {
    this.currentImage++;
    if(this.currentImage == this.imageList.length) {
      this.currentImage = 0;
    }
    this.loadImage(this.imageList[this.currentImage]);
    
    this._updateDOMState();
  },
  
  jumpImage: function() {
    var i = arguments[1];
    if(i >= this.imageList.length) {
      i = 0;
    }
    
    this.currentImage = i;
    this.loadImage(this.imageList[this.currentImage]);
    
    this._updateDOMState();
    
    arguments[0].target.blur();
  },
  
  _overImage: function() {
    this.target.setStyle({cursor: 'pointer'});
  },
  
  _startLoading:function() {
    this.target.setOpacity(0.5);
    $$(this.rule)[this.currentImage].addClassName('loading');
  },
  
  _finishLoading:function() {
    this.target.setOpacity(0.99);
	var rmatch = $$(this.rule);
    for(i=0; i<rmatch.length; i++) {
      rmatch[i].removeClassName('loading');
    }
  },
  
  _updateDOMState: function() {
    var rmatch = $$(this.rule);
    for(i=0; i<rmatch.length; i++) {
      rmatch[i].removeClassName('selected');
      if(i == this.currentImage) {
        rmatch[i].addClassName('selected');
      }
    }
  }
  
});

var wb;
Event.observe(document, 'dom:loaded', function() {
  if(typeof(photoList) != "undefined") {
    wb = new WorkBrowser($('splash-image'), '#splash ul li a', photoList.length);
    for(i=0;i<photoList.length; i++) {
      wb.registerImage(photoList[i]);
    }
  }
} );