
/* classes/lazy_image_loader.js */

 if (typeof Prototype === 'undefined') {
  throw new Error('Lazy Image Loader requires Prototype');
}

var SPINNER_URL = "/mmh/images/indicator.gif";
var DEBUG = false;

function log( message ) {
  if( DEBUG && typeof console !== 'undefined' ) {
    console.log( message );
  }
}

ImageLoader = Class.create();
ImageLoader.prototype = {
  
  initialize: function( img ) {
    this.loaded = false;
    this.image  = $(img);
    this.url    = this.image.readAttribute( "true_src" );
    this.image.src = "/mmh/images/spacer.gif";
    this.image.setStyle( {
      backgroundImage: "url( " + SPINNER_URL + " )",
      backgroundPosition: "50% 50%",
      backgroundRepeat: "no-repeat"
    });
  },
  
  doLoad: function() {
    log( "load image... " + this.url );
    this.image.removeClassName( "lazy_load" );
    this.image.src = this.url;
  }
}

LazyImageLoader = Class.create();
LazyImageLoader.prototype = {
  loaders: null,
  
  initialize: function() {
    log( "image loader initialize" );
    
    this.loaders = $$('img.lazy_load').collect( function(element) {
      return new ImageLoader( element );
    });

    if ( /MSIE 6.0/.test( navigator.userAgent ) ) {
      this.loaders.invoke( "doLoad" );
    } else {
      this.load_image( this.loaders );
    }
  },
  
  load_image: function( loaders ) {
    if( this.loaders.size() == 0 ) return;

    loader = this.loaders.shift();

    var callback = function() { this.load_image( loaders ) };
    loader.image.observe( "load", callback.bindAsEventListener( this ) );
    loader.doLoad();
  }
}

function init_image_loader() {
  log( "init_image_loader" );
  loader = new LazyImageLoader();
}
