/*
File: ImageUtil.js

ImageUtil offers a good wrapper for Image loading

License:
  MIT-style license.

Author:
  Takashi Mizohata <beatak@nydd.org>

Copyright:
  2008 [nydd](http://code.nydd.org/).
*/


/*
Object: ImageUtil
*/
var ImageUtil = {};


/*
Variable: bullpen

ImageUtil.bullpen will holds a reference to where the image will be loaded temporarily.
*/
ImageUtil.bullpen = null;


/*
Method: buildImgBullpen

build bullpen

Return:
  (DOM Div Node)
*/
ImageUtil.buildImgBullpen = function ()
{
  var div = document.createElement('div');
  div.style.position  = 'absolute';
  div.style.top       = '0px';
  div.style.left      = '0px';
  div.style.width     = '1px';
  div.style.height    = '1px';
  div.style.overflow  = 'hidden';
  div.className       = 'imageUtilBullpen';
  document.body.appendChild(div);
  $(div).css({'opacity': 0});
  return div;
}


/*
Method: callbackImageLoaded

Assign wrapper functions to image

Arguments:
  elmImg - (DOM Image Node)
  callback - (Function)

Return:
  (undef)
*/
ImageUtil.callbackImageLoaded = function (elmImg, callback)
{
  // if elmImg is already loaded,
  if 
  (
    elmImg.complete 
    && !(
      (typeof(elmImg) == 'undefined')
      || (elmImg.src == '')
    )
  )
  {
    // NEED TO INTEGRATE WITH CUSTOM EVENT!
    callback(null, elmImg);
    return;
  }
  // other wise set event handlder
  elmImg.finish = function (ev)
  {
    this.onload = null;
    this.onerror = null;
    callback(ev, elmImg);
  }
  elmImg.onload = function (ev)
  {
    this.finish();
  }
  elmImg.onerror = function (ev)
  {
    if ((typeof(this.src) != 'undefined') || (this.src != ''))
    {
      this.onload();
    }
  }
}


/*
Method: setCallbackImageLoaded

For when you want to do it by URL

Arguments:
  url - (String)
  callback - (Function)

Return:
  (undef)
*/
ImageUtil.setCallbackImageLoaded = function (url, callback)
{
  if (ImageUtil.bullpen === null)
  {
    ImageUtil.bullpen = ImageUtil.buildImgBullpen();
  }
  var img = document.createElement('img');
  img.src = url;
  ImageUtil.bullpen.appendChild(img);
  ImageUtil.callbackImageLoaded(img, callback);
}


