/*
	Collection ADT
	Copyright (C) 200, 2007. Chonla.

	Version: 1.0
	Author: Chonla
	Update: 22 feb. 2007

	More infomation, visit: http://www.siamexperts.net/
*/

function $collection(keyattr)
{
	var col = {
		_col: null,
		_key: "",
		keyattribute:function (attributename)
		{
			this._key = "." + attributename;
		},
		add:function (item)
		{
			var k = eval("item" + this._key);
			if (this.exists(k)==-1)
				this._col.push(item);
			return this._col.length;
		},
		remove:function (key)	// remove by key
		{
			var k = eval("item" + this._key);
			var i = this.exists(k);
			if (i > -1)
			{
				if (i == 0)
				{
					this._col.shift();
				}
				else if (i == (this._col.length - 1))
				{
					this._col.pop();
				}
				else
				{
					var sa1 = this._col.slice(0, i);
					var sa2 = this._col.slice(i + 1, this._col.length);
					this._col = sa1.concat(sa2);
				}
			}
			return this._col.length;
		},
		toarray:function ()
		{
			return this._col.slice();
		},
		exists:function (val)
		{
			var compare = "this._col[i]" + this._key + "==val";
			for (var i = 0; i < this._col.length; i++) {
				if (eval(compare)) return i;
			}
			return -1;
		},
		count:function()
		{
			if (this._col)
				return this._col.length;
			return 0;
		},
		empty:function()
		{
			this._col = null;
			this._col = new Array();
		},
		swap:function(pos1, pos2)
		{
			if ((pos1 >= this._col.length) || (pos2 >= this._col.length) || (pos1 < 0) || (pos2 < 0))
				return false;
			var tmp;
			tmp = this._col[pos1];
			this._col[pos1] = this._col[pos2];
			this._col[pos2] = tmp;
			return true;
		},
		shuffle:function()
		{
			var v = -1;
			var mx = this.count();
			var t = 0;
			for (var j = 0; j < 3; j++)
			{
				v = -1;
				for (var i = 0; i < mx; i++)
				{
					do
					{
						t = parseInt(Math.random() * 777777) % mx;
					}
					while (t == v);
					v = t;
					this.swap(i, t);
				}
			}
		},
		item:function(ind)
		{
			if ((ind < 0) || (ind >= this.count()))
				return null;
			return this._col[ind];
		}
	};
	if (keyattr!=null)
	{
		col.keyattribute(keyattr);
	}
	col._col = new Array();
	return col;
}

