document.observe("dom:loaded", function() {
  ajaxify_thumbs();
});

function ajaxify_thumbs() {
  $('content').style.backgroundImage = 'url(/images/loading.gif)';
  $('content').style.backgroundRepeat = 'no-repeat';
  $('content').style.backgroundPosition = '200px 200px';
  
  $('main_image').onload = function() { this.all_the_way_loaded = true }
  
  $$('.thumb a').each(function(a) {
    a.new_image = new Image();

    a.onclick = function() {
      if(this.classNames().include('current')) return false;
      if(window.busy == true) return false;
      this.drop_out();
      return false;
    }

    a.drop_out = function() {
      window.busy = true;
      this.id_no = this.id.split('_')[1]; // get database id from id attribute
      this.tag_info = $H(tags[this.id_no]); // get tag info from global JSON data dump
      this.new_image.src = '/images/items/'+this.id_no+'/normal.jpg';
      new Effect.Parallel( [
        new Effect.Move('shade', { y: -200, sync: true }),
        new Effect.Opacity('shade', { from: 1.0, to: 0.0, sync: true }),

        new Effect.Move('tag', { x: 200, sync: true }),
        new Effect.Opacity('tag', { from: 1.0, to: 0.0, sync: true })
      ], {
        firer: this,
        afterFinish: function(effect) {
          a = effect.options.firer
          $('main_image').all_the_way_loaded = false
          $('main_image').src = a.new_image.src
          a.drop_in()
        }
      });
    }

    a.drop_in = function() {
      if($('main_image').all_the_way_loaded) {
        $$('.thumb a.current').each(function(a) { a.classNames().remove('current') });
        this.classNames().add('current');
        new Effect.Parallel( [
          new Effect.Move('shade', { y: 200, sync: true }),
          new Effect.Opacity('shade', { from: 0.0, to: 1.0, sync: true }),

          new Effect.Move('tag', { x: -200, sync: true }),
          new Effect.Opacity('tag', { from: 0.0, to: 1.0, sync: true })
        ], {
          afterFinish: function() { 
            window.busy = false;
          }
        });
        this.tag_info.each(function(pair) {
          $(pair.key).innerHTML = pair.value;
        })
        $('purchase_button').style.display = ($('paypal_button').innerHTML.length > 0) ? '' : 'none'
      } else {
        window.setTimeout("$('"+this.id+"').drop_in()", 250);
      }
    }
    
  });
}
