/**
 * Function that transliterates latin characters into cyrillic characters.
 * It also escapes html <tags></tags>, html special &tags; and bbcode [tags][/tags], leaving their
 * content intact.
 * 
 * @author Alexei Mikhailov (kblcuk@gmail.com)
 * @version 0.2
 */
 
// Object containing key-value pairs of characters and their transliterations.
// Last row is a pair of open symbol and close symbol for special 
var characters = {
	A : 'А', B : 'Б',	V : 'В', G : 'Г', D : 'Д', E : 'E', YO : 'Ё', Yo : 'Ё', JO : 'Ё', Jo : 'Ё',
	ZH : 'Ж', Zh : 'Ж',	Z : 'З', I : 'И', K : 'К', L : 'Л', M : 'М', N : 'Н', O : 'О', P : 'П',
	R : 'Р', S : 'С', T : 'Т',	U : 'У', F : 'Ф', H : 'Х', C : 'Ц', CH : 'Ч', Ch : 'Ч', SH : 'Ш',
	Sh : 'Ш', SCH : 'Щ', Sch : 'Щ', W : 'Щ', Y : 'Ы',
	JE : 'Э', Je : 'Э', JU : 'Ю', Ju : 'Ю', YA : 'Я', Ya : 'Я',
	a : 'а', b : 'б',	v : 'в', g : 'г' ,d : 'д', e : 'e', yo : 'ё', jo : 'ё',
	zh : 'ж', z : 'з', i : 'и', k : 'к', l : 'л', m : 'м', n : 'н', o : 'о', p : 'п',
	r : 'р', s : 'с', t : 'т',	u : 'у', f : 'ф', h : 'х', c : 'ц', ch : 'ч', sh : 'ш',
	sch : 'щ', w : 'щ', '#' : 'ъ', y : 'ы', '\'' : 'ь', je : 'э', ju : 'ю', ya : 'я',
	'<' : '>', '[' : ']', '&' : ';'
};

/**
 * This function is called from html page. It takes a string object,
 * and returns transliterated string.
 *
 * @param {String} str String to transliterate
 * @return A transliterated string
 */
function translitTagAware( /*String*/ str ) 
{
	var result = [];
	var len = str.length;
	
	for( var i = 0; i < len; i++ )
	{
		var currentChar = str[ i ];
		
		if( currentChar == '<' || currentChar == '[' || currentChar == '&' )
		{
			// Looks like this is a start of a tag
			var closingTagIndex = str.indexOf( characters[ currentChar ], i );
			// If there is an end tag, push the whole tag into result array,
			// else proceed as in case with normal character.
			if( -1 != closingTagIndex )
			{
				var tagString = str.substring( i, closingTagIndex + 1 );
				result.push( tagString );
				i = closingTagIndex;
			}
			else result.push( currentChar );
		}
		else if( undefined != characters[ currentChar ] )
		{
			// Found match in characters table
			result.push( characters[ currentChar ] );
		}
		else
		{
			// No match found, so push character into array unchanged
			result.push( currentChar );
		}
	}
	return result.join( '' );
}

