/***************************************************************************
 *                                fastprinter.js
 *                            -------------------
 *   begin                : Friday, Feb 21, 2003
 *   copyright            : (C) 2003 Nicolas Grekas
 *   email                : nicolas.grekas@espci.fr
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   You can not redistribute and/or modify this program without express
 *   permission of the author ; restricted use to IntellAgence
 *
 ***************************************************************************/

function fastprinter(code)
{
	this._tpldata = new Array();
	this._tplroot = new Array();

	this.code = code;
	this.win = window;
	
	return this;
}

fastprinter.prototype.o = function(str) {this.win.document.write(str);}

fastprinter.prototype.destroy = function()
{
	this._tplroot = new Array();
	this._tpldata = new Array();
}

/**
 * This will print out the results of executing the template.
 */
fastprinter.prototype.pparse = function(win)
{
	if (!win) win = window;
	this.win = win;

	with (this)
	{
		win.document.open();
		win.document.clear();

		eval(code);
		win.document.close();
	}
}

/**
 * Block-level variable assignment. Adds a new block iteration with the given
 * variable assignments. Note that this should only be called once per block
 * iteration.
 */
fastprinter.prototype.assign_block_vars = function(blockname, vararray)
{
	if ( blockname.indexOf('.')!=-1 )
	{
		var blocks = blockname.split('.');
		var blockcount = blocks.length - 1;
		var str = 'this._tpldata';
		var tpldata = this._tpldata;
		var i;
		for (i = 0; i < blockcount; i++)
		{
			tpldata = tpldata[ blocks[i] ];
			str += '.'+blocks[i]+'['+(tpldata.length-1)+']';
			tpldata = tpldata[ tpldata.length-1 ];
		}
		// Now we add the block that we're actually assigning to.
		// We're adding a new iteration to this block with the given
		// variable assignments and we evaluate this assignment we've built up.
		i = blocks[blockcount];
		str += '[\''+i+'\']';
		eval( str + (tpldata[i]?'.push(vararray);':'=new Array(vararray);') + 'tplref='+str);
	}
	else
	{
		// Top-level block.
		// Add a new iteration to this block with the variable assignments
		// we were given.
		if ( !this._tpldata[blockname] ) this._tpldata[blockname] = new Array();

		tplref = this._tpldata[blockname];
		tplref.push( vararray );
	}
	
	return tplref;
}

/**
 * Root-level variable assignment. Adds to current assignments, overriding
 * any existing variable assignment with the same name.
 */
fastprinter.prototype.assign_var = function(varname, varval)
{
	this._tplroot[varname] = varval;
}
