/**
 * Parsing subtemplates class
 * @param string string - string to parse
 */
cAIParser = function ( string ) {
	this.myString = string;
}

// Setting prototype
mixin(cAIParser.prototype, {
	/**
	 * Setting string function
	 * @param string string - new string
	 */
	string: function ( string )	{
		this.myString = string;
		return this;
	},
	
	/**
	 * Generating string subtemplates map function
	 */
	map: function () {
		map = [];
		
		subtemplate_level = 0;
		mark = 0;
		for (var i = 0; i < this.myString.length; i++)
		{
			//  Current mark
			mark = subtemplate_level;

			// Checking current character is unescaped '{' or '}'
			if (i == 0 || this.myString.charAt(i - 1) != "\\")
			{
				if (this.myString.charAt(i) == "{")
				{
					mark = subtemplate_level;
					subtemplate_level++;
				}
				if (this.myString.charAt(i) == "}")
				{
					subtemplate_level--;
					mark = subtemplate_level;
				}
			}
			
			map[i] = mark;
		}
			
		return map;
	},
	
	/**
	 * Getting first subtemplate function
	 */
	firstSubtemplate: function ()
	{
		map = this.map();
		i = 0;
		
		// Finding subtemplate start
		while (map[i] != 1 && i < map.length)
			i++;
		start = i;
		
		// Finding subtemplate end
		while (map[i] != 0 && i < map.length)
			i++;
		end = i - 1;
		
		// No subtemplate found
		if (end < start)
			return false;
			
		return this.myString.substr(start, end - start + 1);
	},
	
	/**
	 * Exploding string function
	 */
	explode: function ()
	{
		map = this.map();
		
		parts = [];
		parts_num = 0;
		start = 0;
		for (i = 0; i < this.myString.length; i++)
		{
			// Checking current symbol is unescaped delimeter on zero subtemplate level
			if ((i == 0 || this.myString.charAt(i - 1) != "\\") &&
				this.myString.charAt(i) == "|" && map[i] == 0)
			{
				parts[parts_num++] = this.myString.substr(start, i - start);
				start = i + 1;
			}
		}

		// Setting last part
		parts[parts_num++] = this.myString.substr(start, this.myString.length - start);
		
		return parts;
	},
	
	/**
	 * Replace all first level templates function
	 * @param string from - string to replace
	 * @param string to - string to replace with
	 * @return this
	 */
	replaceTemplates: function ( from, to )
	{
		offset = 0;
		while ((pos = this.myString.indexOf(from, offset)) != -1)
		{
			if (this.map()[pos] == 0)
			{
				this.myString = this.myString.substr(0, pos) + to + this.myString.substr(pos + from.length);
				offset = pos + to.length
			}
			else
				offset = pos + from.length;
		}
		
		return this;
	}
});

