/**
* A simple JavaScript image loaderimage loader
* @author Cuong Tham
* @url http://thecodecentral.com/2008/02/21/a-useful-javascript-image-loader
* @usage
* var loader = new ImageLoader('IMAGE_URL');
* //set event handler
* loader.loadEvent = function(url, image){
*   //action to perform when the image is loaded
*   document.body.appendChild(image);
* }
* loader.load();
*/

//source: http://snipplr.com/view.php?codeview&id=561
// Cross-browser implementation of element.addEventListener()

function ScaleImage(image, maxwidth, maxheight) 
{
	w = parseInt(image.width);
	h = parseInt(image.height);
	
	if(h > w)
	{
		if(maxheight > maxwidth)
		{
			multiplier = maxwidth / w;
		}
		else
		{
			multiplier = maxheight / h;
		}
	}
	else
	{
		if(maxwidth > maxheight)
		{
			multiplier = maxwidth / w;
		}
		else
		{
			multiplier = maxheight / h;
		}
	}
	
	newWidth = w * multiplier;
	newHeight = h * multiplier

	if(newWidth > maxwidth)
	{
		multiplier = maxwidth / w;
	}
	
	if(newHeight > maxheight)
	{
		multiplier = maxheight / h;
	}
	
	image.width = w * multiplier;
	image.height = h * multiplier;
	
	return image;
}

function addListener(element, type, expression, bubbling)
{
  bubbling = bubbling || false;
  if(window.addEventListener)	{ // Standard
    element.addEventListener(type, expression, bubbling);
    return true;
  } else if(window.attachEvent) { // IE
    element.attachEvent('on' + type, expression);
    return true;
  } else return false;
}

var ImageLoader = function(url, eid){
  this.url = url;
  this.image = null;
  this.eid = eid;
  this.loadEvent = null;
};

ImageLoader.prototype = {
  load:function(){
    this.image = document.createElement('img');
    var url = this.url;
    var image = this.image;
    var eid = this.eid;
    var loadEvent = this.loadEvent;
    addListener(this.image, 'load', function(e){
      if(loadEvent != null){
        loadEvent(url, image, eid);
      }
    }, false);
    this.image.src = this.url;
  },
  getImage:function(){
    return this.image;
  }
};
