/**
Simple string templating using find/replace regex

egample: 

if we have some string
	var s = "Name: @{name}, E-mail: @{email}"
	
and we construct a Template from this:	
	var t = new Template(s);

we can then take formatted output using json object, eg:
	var formatted = t.format({name: 'Jovica', email: 'jveljan@gmail.com'});
	
formatted now will be: 
	Name: Jovica, E-mail: jveljan@gmail.com

*/
Template = function(t) {
	this.init(t);
}

Template.prototype = {

	// begin and end pattern match default @{xxx}
	beginMatch: "\\{",
	endMatch: "\\}",
	
	//private, called in constuctor
	init: function(txt) {
		this.text = txt;
	},
	
	/**
	 * format template using json object - map of name-value pairs.
	 * eg. {name: 'Jovica', Email: 'jveljan@gmail.com'}
	 */
	format: function(obj) {
		var rv = this.text;
		for(var k in obj) {
			var re = new RegExp(this.beginMatch+k+this.endMatch, 'g');
			rv = rv.replace(re, obj[k]);
		}
		return rv;
	},
	
	/**
	 * returns the vars used in template, in 
	 *	eg. in "Name: @{name}, E-mail: @{email}"
	 *	will return ['name', 'email']
	 */
	getVars: function() {
		
		var re = new RegExp(this.beginMatch+"\\w+"+this.endMatch,'g');
		var matches = this.text.match(re);
		if(!matches) return [];
		var rv = [];
		for(var i=0; i<matches.length; i++) {
			var s = matches[i];
			s = s.substring(1, s.length-1);
			rv.push(s);
		}
		return rv;
	}
}

