/**
 * Outputtable object representation data type
 * @param string template - initial object template
 */
cAIOutputtable = function ( template ) {
	this.myTemplate = template;
	this.myArguments = [];
	this.myIds = [];
}

// Ids counter
cAIOutputtesNextId = 1;

// Setting prototype
mixin(cAIOutputtable.prototype, {
	/**
	 * Setting template function
	 * @param string template - new template
	 */
	template: function ( template )
	{
		this.myTemplate = template;
		return this;
	},
	
	/**
	 * Releasing variable value function
	 * @param mixed $value - variable value
	 * @return variable string
	 */
	variableRelease: function ( value )
	{
		if (typeof(value) != "object")
			return value;
		else if (value.html)
			return value.html();
		else
		{
			var res = "";
			for (var i = 0; i < value.length; i++)
				res += this.variableRelease(value[i]);
			return res;
		}
	},

	/**
	 * Returning next id function
	 */
	nextId: function ()
	{
		return "idjs_" + (cAIOutputtesNextId++);
	},
	
	/**
	 * Returning next value for named id function
	 * @param string name - id name
	 */
	id: function ( name )
	{
		this.myIds[name] = this.nextId();
		return this.myIds[name];
	},
	
	/**
	 * Returning object HTML function
	 */
	html: function ()
	{
		// Result html
		var result_html = this.myTemplate;
		
		// Founding variables
		var variables_re = /{v \S+}/g;
		var variables = result_html.match(variables_re);
		if (variables == null)
			variables = new Array();
		
		// Replacing variables
		for (var i = 0; i < variables.length; i++)
		{
			// Founding variable name
			var name_re = / [^}]+/;
			var name = variables[i].match(name_re)[0].substr(1);
			
			// Replacing variable with it value
			if (this.myArguments[name])
				result_html = result_html.replace("{v " + name + "}", this.variableRelease(this.myArguments[name]));
			else
				result_html = result_html.replace("{v " + name + "}", "");
		}
		
		// Founding ids
		var ids_re = /{id \S+}/g;
		var ids = result_html.match(ids_re);
		if (ids == null)
			ids = new Array();

		// Replacing ids
		for (var i = 0; i < ids.length; i++)
		{
			// Founding id name
			var name_re = / [^}]+/;
			var name = ids[i].match(name_re)[0].substr(1);
			
			// Replacing id with it value
			if (!this.myIds[name])
				this.myIds[name] = this.nextId();
			
			result_html = result_html.replace("{id " + name + "}", this.myIds[name]);
		}
		
		return result_html;
	},
	
	/**
	 * Setting argument value function
	 * @param string name - argument name
	 * @param mixed value - argument value
	 */
	set: function ( name, value )
	{
		this.myArguments[name] = value;
	}
});
