var ImageButton = new Class(
{
	options: {
		allowHover: true,
		allowPressed: true
	},
	
	initialize: function(element, options)
	{
		// Setup
		this.element = $(element);
		this.setOptions(options);
		this.isPressed = false;
		this.isHovered = false;
		this.imageBasePath = this.element.src.substr(0, this.element.src.lastIndexOf("/")+1);
		this.imageBaseName = this.element.src.substr(this.imageBasePath.length, this.element.src.lastIndexOf(".")-this.imageBasePath.length);
		this.imageBaseExtension = this.element.src.substr(this.element.src.lastIndexOf(".")+1);
		
		// Events
		this.events = {
			"mousedown": this.mouseDown.bindWithEvent(this),
			"mouseup": this.mouseUp.bindWithEvent(this),
			"mouseenter": this.mouseEnter.bindWithEvent(this),
			"mouseout": this.mouseLeave.bindWithEvent(this)
		};
		
		// Listen to events
		this.element.addEvent("mousedown", this.events.mousedown);
		this.element.addEvent("mouseenter", this.events.mouseenter);
		this.element.addEvent("mouseout", this.events.mouseout);
		
		// Load images
		this.preloadImages();
	},
	
	preloadImages: function()
	{
	  if( this.options.allowHover )
	  {
	    var hoverImage = new Image();
	    hoverImage.src = this.imageBasePath + this.imageBaseName + "hover" + "." + this.imageBaseExtension;
	  }

    if( this.options.allowPressed )
    {
	    var hoverImage = new Image();
	    hoverImage.src = this.imageBasePath + this.imageBaseName + "pressed" + "." + this.imageBaseExtension;
    }
	},
	
	mouseDown: function(event)
	{
		this.isPressed = true;
		document.addEvent("mouseup", this.events.mouseup);
		event.stop();
		
		// Set image state
		if( this.isPressed && this.options.allowPressed )
			this.setImageState("pressed");
	},
	
	mouseUp: function(event)
	{
		this.isPressed = false;
		document.removeEvent("mouseup", this.events.mouseup);
		event.stop();
		
		// Set image state
		if( this.isHovered && this.options.allowHover )
			this.setImageState("hover");
		else
			this.setImageState("");
		
		if( this.isHovered )
			this.fireEvent("onClick", [this]);
	},
	
	mouseEnter: function(event)
	{
		this.isHovered = true;
		
		// Set image state
		if( this.isPressed && this.options.allowPressed )
			this.setImageState("pressed");
		else
		if( this.options.allowHover )
			this.setImageState("hover");
		else
			this.setImageState("");
	},
	
	mouseLeave: function(event)
	{
		this.isHovered = false;

		// Set image state
		if( this.isPressed && this.options.allowPressed && this.options.allowHover )
			this.setImageState("hover");
		else
			this.setImageState("");
	},
	
	setImageState: function(state)
	{
		var imagePath = this.imageBasePath + this.imageBaseName;
		
		switch(state)
		{
			case "pressed":
				imagePath += "pressed";
				break;
			
			case "hover":
				imagePath += "hover";
				break;
		}
		
		imagePath += "." + this.imageBaseExtension;
		this.element.src = imagePath;
	}
});

ImageButton.implement(new Options);
ImageButton.implement(new Events);