/**
 * buttons.js
 *
 * JavaScript Library that provides simple image buttons generation
 *
 * @package Legajo
 * @author alvaro
 * @version 0.3
 *
 * @TODO - proveer una interfase sencilla para el activar y desactivar
 *
 */

var toolsets = {};

function ToolSet(name) {
	this.name = name;
	this.buttons = {};
	this.active_button = null;
	this.push = function (but) {
		if (but) this.buttons[(but.id || but.name || Math.random())] = but;
	}
	toolsets[name] = this;
	return this;
}

function Button(button) {
	var toolset_name = (button.getAttribute("toolset")||arguments[1]);
	if (toolset_name) {
		if (!toolsets[toolset_name]) {
			new ToolSet(toolset_name);
		}
		button.toolset = toolsets[toolset_name];
		button.toolset.push(button);
	}
	button.style.cursor = 'pointer';
	button.active = false;
	button.disabled = false;
	button.out = button.src;
	var x = new Image(); //cache all button instances
	button.over = x.src = (button.getAttribute("over") || button.out);
	button.down = x.src = (button.getAttribute("down") || button.out);
	button.dis = x.src = (button.getAttribute("dis") || button.out);
	/**
	 * Methods
	 */
	button.activate = function () {
		if (!this.disabled) {
			this.src = this.down;
			if (this.toolset) {
				this.active = true;
				if (this.toolset.active_button && this.toolset.active_button != this) {
					this.toolset.active_button.deactivate();
				}
				this.toolset.active_button = this;
			}
			{eval(button.getAttribute("action"))} //executes action code
		}
	}
	button.deactivate = function () {
		if (!this.disabled) {
			this.src = this.out;
			this.active = false;
			if (this.toolset) {
				this.toolset.active_button = null;
			}
		}
	}
	button.enable = function () {
		this.disabled = false;
		this.src = this.out;
		this.style.cursor = 'pointer';
	}
	button.disable = function () {
		this.disabled = true;
		this.src = this.dis;
		this.style.cursor = 'default';
	}
	/**
	 * Events Handlers
	 */
	button.onclick = function () {
		if (!this.active && !this.disabled) {
			this.activate();
		}
	}
	button.onmouseover = function () {
		if (!this.active && !this.disabled) {
			this.src = this.over;
		}
	}
	button.onmouseout = function () {
		if (!this.active && !this.disabled) {
			this.src = this.out;
		}
	}
	return button;
}


