// DarkOne4Mod - Drawbutton Object
// Code by tedGo, based on a sample by T.P. Wang

var ButtonStates = {normal: 0, hover: 1, down: 2, hide: 3};
var Buttons = {};
var g_down = false;

// ----- CREATE DRAWBUTTON OBJECT --------------------------------------
var g_tooltip;

function Button(x, y, w, h, btn_col, func, tiptext) {
	this.left = x;
	this.top = y;
	this.w = w;
	this.h = h;
	this.right = x + w;
	this.bottom = y + h;
	this.func = func;
	this.tiptext = tiptext;
	this.state = ButtonStates.normal;
	this.col_normal = btn_col && btn_col.normal ? btn_col.normal : null;
	this.col_hover = btn_col && btn_col.hover ? btn_col.hover : this.col_normal;
	this.col_down = btn_col && btn_col.down ? btn_col.down : this.col_hover;
	this.col = this.col_normal;

	this.traceMouse = function(x, y) {
		if (this.state == ButtonStates.hide) return false;

		var b = (this.left < x) && (x < this.right) && (this.top < y) && (y < this.bottom);

		if (b)
			g_down ? this.changeState(ButtonStates.down) : this.changeState(ButtonStates.hover);
		else
			this.changeState(ButtonStates.normal);
		return b;
	}

	this.changeState = function(newstate) {
		newstate != this.state && window.RepaintRect(this.left, this.top, this.w, this.h);
		this.state = newstate;
		switch (this.state) {
			case ButtonStates.normal:
				this.col = this.col_normal;
				break;

			case ButtonStates.hover:
				this.col = this.col_hover;
				break;

			case ButtonStates.down:
				this.col = this.col_down;
				break;

			default:
				this.col = null;
		}
	}

	this.changePos = function(x, y, w, h) {
		this.left = x;
		this.top = y;
		this.w = w;
		this.h = h;
		this.right = x + w;
		this.bottom = y + h;
	}

	this.draw = function(gr) {
		gr.FillSolidRect(this.left, this.top, this.w, this.h, this.col);
		gr.DrawRect(this.left, this.top, this.w, this.h, 1, 0xFF000000);
	}

	this.repaint = function() {
		window.RepaintRect(this.left, this.top, this.w, this.h);
	}

	this.onClick = function() {
		this.func && this.func();
	}

	this.onMouseIn = function() {
		g_tooltip = window.CreateTooltip();
		g_tooltip.Text = this.tiptext;
		g_tooltip.Activate();
	}

	this.onMouseOut = function() {
		g_tooltip.Deactivate();
		g_tooltip.Dispose();
	}
}

function buttonsDraw(gr) {
	for (var i in Buttons) {
		Buttons[i].draw(gr);
	}
}

function buttonsTraceMouse(x, y) {
	var btn = null;
	for (var i in Buttons) {
		if (Buttons[i].traceMouse(x, y) && !btn)
			btn = Buttons[i];
	}
	return btn;
}