/*
@name: /htdocs/js/lib/oggetti/datasetholder.js
@desc: Componente javascript datasetholder
@authors: Marco Biondi
@lastauthor: Marco Biondi
*/
var DataSetHolder = Class.create();
DataSetHolder.prototype = {
	initialize: function(options) {
		this.options = {
				setName: 'recordset',
				rowName: 'record',
				statusAttr: 'status',
				okValue:	'ok',
				errorAttr: 'message'
			};

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

		//TODO: definire le opzioni che determinano il tipo di dataset
		//Es. aggiornamento periodico, paging o altro
		this._AjaxR = null;

		EventBroadcaster.initialize(this);
	},

	setSchema: function(mixed) {
		//TODO: imposta lo schema per il dataset
		//mixed puņ essere un oggetto ? (come derivare la prototype chain? )
		//un xml
		//come generare lo schema base...
	},

	_onReqComplete: function(req) {
		var foo, bar, t;
		try
		{
			if(req.status != 200)
			{
				throw new Error(req.status+" "+req.statusText);
			}
			else
			{
				//Parsing del dataset
				foo = req.responseXML.getElementsByTagName(this.options.setName);
				foo = foo[0];
				if(!this.options.statusAttr || foo.getAttribute(this.options.statusAttr) == this.options.okValue)
				{
					this._dset = $A();
					bar = foo.firstChild;
					while(bar)
					{
						if(bar.nodeType == 1 && bar.nodeName == this.options.rowName)
						{
							t = new Object();
							foo = bar.firstChild;
							while(foo)
							{
								if(foo.nodeType == 1)
								{
									if(foo.firstChild)
										t[foo.nodeName] = foo.firstChild.nodeValue;
								}
								foo = foo.nextSibling;
							}
							this._dset.push(t);
						}
						bar = bar.nextSibling;
					}

					this._curView = this._dset.toArray();
					this.dispatchEvent({type: "onDataChange", dEvType: "updateAll"});
				}
				else
				{
					throw new Error("Recorset error: "+(foo.getAttribute ? foo.getAttribute(this.options.errorAttr) : 'no recordset!!!'));
				}
			}
		}
		catch(err)
		{
			this.dispatchEvent({type: "onDataError", error: err});
		}
	},

	bindTo: function(urlBind, params, metodo)
	{
		if(!this._AjaxR)
		{
			var rnd = "d=" + Date.parse(new Date()) + "&r=" + Math.random();
			if(urlBind.indexOf('?') >= 0 )
			{
				urlBind += '&'+rnd
			}else
			{
				urlBind += '?'+rnd
			}
			var opts = {onComplete: this._onReqComplete.bind(this) };
			if(params)
				opts['parameters'] = params;
			if(metodo)
				opts['method'] = metodo;
			this._AjaxR = new Ajax.Request( urlBind, opts );
		}                                           				
	},

	getLength: function() {
		if(this._curView)
			return(this._curView.length);
		else
			return(0);
	},

	getItemAt: function(id) {
		if(this._curView)
		{
			if(this._curView[id])
				return(this._curView[id]);
		}
		return(null);
	}
}
