var thumb_defaults = new Array();
var thumb_current = new Array();
var thumb_periodical = 0;

function updateThumb( thumb_id, thumb_url_base, thumb_num ){
  thumb_url = thumb_url_base + "/thumbs/vt_small_" +
                thumb_num.toPaddedString(2) + ".jpg";
  $( thumb_id ).src = thumb_url;
}

function resetThumb( thumb_id ){
  $(thumb_id).src = thumb_defaults[thumb_id];
}

function rotateThumb( thumb_id, thumb_url_base, max_thumbs ) {
  if ( thumb_current[thumb_id] > max_thumbs ){
    thumb_num = 0;
  } else {
    thumb_num = thumb_current[thumb_id];
  }
  updateThumb( thumb_id, thumb_url_base, thumb_num );
  thumb_current[thumb_id] = thumb_num + 1;

  if ( thumb_current[thumb_id] <= max_thumbs ){
    updateThumb( 'hidden_thumb', thumb_url_base, thumb_current[thumb_id] );
  }
}

var RotateThumb = Behavior.create({
  onmouseover: function() {
    thumb_info = this.element.src.match( /^(.*)\/thumbs\/vt_small_(\d*)\.jpg$/ );
    thumb_url_base = thumb_info[1];
    thumb_num = parseInt( thumb_info[2] );
    thumb_id = this.element.id;
    thumb_rot_max = this.element.readAttribute( 'rot_max' );
    thumb_defaults[thumb_id] = this.element.src;
    thumb_current[thumb_id] = 0;

    rotateThumb( thumb_id, thumb_url_base );
    thumb_periodical = new PeriodicalExecuter( new Function("rotateThumb('" +
                             thumb_id + "','" + thumb_url_base + "', " + thumb_rot_max + " )"), 0.6 );
  },
  onmouseout: function() {
    thumb_periodical.stop();
    resetThumb( this.element.id );
  }
  
});

var RateThis = Behavior.create({
  onclick: function() {
    new Ajax.Request( this.element.href, { method : 'post',
                                           asynchronous:true,
                                           evalScripts:true } );
    return false;
  }
});

Event.addBehavior({
  '.video-thumb' : RotateThumb,
  '#star-rating li a' : RateThis
});
