/*
@name: /htdocs/js/lib/oggetti/dataformatter.js
@desc: Componente javascript dataformatter
@authors: Marco Biondi
@lastauthor: Marco Biondi
*/
var DataFormatter = Class.create();
DataFormatter.prototype = {
	initialize: function(divID, globalName, options) {
		this._container = $(divID);
		this._gName = globalName;
		this.options = {
				tmplID: 'template',
				formatMap: {}
			};

		Object.extend(this.options, options || {});

		this.dataSource = null;
		this._curItem = null;
	},

	destroy: function()
	{
		this.releaseDataSource();
	},

	releaseDataSource: function() {
		if(this.dataSource)
			this.dataSource.delListener("onDataChange", this);

		this.dataSource = null;
	},

	bindDataSource: function(ds) {
		if(this.dataSource)
			this.dataSource.delListener("onDataChange", this);

		this.dataSource = ds;
		this._firstRecord = 0;
		this.dataSource.addListener("onDataChange", this);
	},

	onDataChange: function(objEvt) {
		switch(objEvt.dEvType)
		{
			case 'updateAll':
				this.draw();
				break;
		}
	},

	draw: function() {
		var i, tot, dest, foo, tmpl;
		tot = this.dataSource.getLength();
		this._container.innerHTML = "";
		tmpl = $(this.options.tmplID).innerHTML;
		for(i=0; i<tot; i++)
		{
			this._curItem = this.dataSource.getItemAt(i);
			foo = tmpl.replace(/\@\*([a-zA-Z1-9_]+)\*\@/g, this.matchFn.bind(this));
			this._container.innerHTML += foo;
		}
		foo = null;
		this._curItem = null;
	},

	matchFn: function()
	{
		var foo = this._curItem[arguments[1]];
		var bar = this.options.formatMap[arguments[1]];

		if(typeof(foo) != "string")
			foo = "";

		if(bar)
			foo = foo.replace(bar[0], bar[1]);

		return(String(foo));
	}
}
