///////////////////////////////////////////////////
// Latin => Armenian; Latin => Russian converter
// All rights reseved by Genocide.ru
// Please mail to grigor@genocide.ru
///////////////////////////////////////////////////
// Version: 2.0
// In the new version autotranslit has been added.
///////////////////////////////////////////////////
// Global variables for autoconvert
///////////////////////////////////////////////////

var g_lastChar = null;

var g_enbleConvert = true;
var g_enableChar = '';
var g_convEnable = new Array();
g_convEnable['['] = 1; // 001
g_convEnable['{'] = 2; // 010
g_convEnable[']'] = 5; // 101
g_convEnable['}'] = 6; // 110

///////////////////////////////////////////////////
// Global Functions
///////////////////////////////////////////////////

/**
 * Checks whether arrow keys are pressed, by this resets last char
**/ 
function keyIsDown() {
	code = window.event.keyCode;
	if ( (code >= 33 && code <= 40) ||
		  code == 46 || code == 8 || 
		  code == 13 || code == 17)
		  g_lastChar = null;
}
/**
 * Togles (enables or disables) 'Autoconvert' check box
 **/
function togleAutoConvert() {
	with (document.forms[0].autoTrans) {
		checked = !checked;
	}
	activateTextArea();
}

/**
 * Activates Text Area when other functional buttons are pressed
 **/
function activateTextArea() {
	if (getBrowser() != 'ie')
		return;
	with (document.forms[0].txtWindow) {
		setActive();
		focus();
	}
}

/**
 * This function is called when user types in Text Area and 'Autotranslit'
 * is enabled. Function checkes which language is selected. Checkes whether
 * exceptional letter is choosed (in Armenian the letter 'u' is a combinatio
 * of two symbols and there is no single digital code for it).
 * Finds appropriate symbol in alphabeth and changes keycode if needed.
 **/
function autoChange() {
	if ( !document.forms[0].autoTrans.checked )
		return;
	
	ch = String.fromCharCode(window.event.keyCode);
	
	if (!doConvert(ch))
		return;
	
	isArm = document.forms[0].transLang[0].checked;
	alphaTab = isArm ? arm : cyr;

	if (isArm && isExceptionLetter(alphaTab, ch))
		return;
	
	ch = findChar(alphaTab, ch);
	if (ch) 
		window.event.keyCode = ch.charCodeAt(0);
}
/**
 * This function checkes whether convertion must be done or not.
 * During typing text if text is included in square brackets like '[' ']' (also '{' and '}')
 * the text between is not translited and stais like it is. User can 
 * remove these symbols pressing button replace
 * @param  ch - character, the current pressed character to be chekced
 * @return returns 'true' if letter shoud pass convertion otherwise returns 'false'
 **/
function doConvert(ch) {
	var enabSign = g_convEnable[ch];
	if (!enabSign) {
		return g_enbleConvert;
	} else if (g_enbleConvert && enabSign < 4) {
		g_enbleConvert = false;
		g_enableChar = ch;
	} else if ( !g_enbleConvert && (enabSign & g_convEnable[g_enableChar]) ) {
		g_enbleConvert = true;
		g_enableChar = '';
	}
	return g_enbleConvert;
}

/**
 * Ckeckes whether letter is exceptional or not. In Armenian language 
 * the letter 'u' is a combination of two symbols
 * @param alphaTab -- array, the alphabeth table to check letters
 * @param ch -- char, the characketer to be checked
 **/
function isExceptionLetter(alphaTab, ch) {
	var chFound = '';
	
	if ( ch == 'u' || ch == 'U' ) {
		chFound = alphaTab[ch];
		
		var txtRange = document.selection.createRange();
		if (txtRange) {
			g_lastChar = ch;
			window.event.keyCode = 0;
			txtRange.text = chFound;
		} else {
			chFound = '';
		}
	}
	return chFound;
}

/**
 * Finds characketer in Alphabeth table. If symbol is a complex combination
 * Function also makes changes and returns empty string to stop further changes.
 * @param alphaTab -- array, the chosen alphabeth table
 * @param ch -- char, the current pressed character
 * @return returns found character if it should be changed by changing current kyecode
 **/
function findChar(alphaTab, ch) {
	var chFound = '';
	
	if (g_lastChar)
		chFound = alphaTab[g_lastChar + ch];
	g_lastChar = ch;
	
	if (chFound) {		
		var txtRange = document.selection.createRange();
		if (txtRange) {
			window.event.keyCode = 0;
			txtRange.moveStart('character', -1);
			txtRange.text = chFound;
		
			chFound = null;
			g_lastChar = null;
		} else {
			chFound = alphaTab[ch];
		}
	} else {
		chFound = alphaTab[ch];
	}
	return chFound;
}

/**
 * This function is called when 'Convert' button is pressed. It manually converts
 * text in the text area and returns changed text
 * @param text -- string, the current text in the text area.
 * @return returns changed text to be replaced in the text area.
 **/
function onTranslit(text) { 
	var result = '';
	with (document.forms[0]) {
		if (ASCII_conv.checked) {
			result = convertAscii8ToUnicode(text, arm_ascii8);
			ASCII_conv.checked = 0;
			transLang[1].disabled = false;
		} else {
			result = translit(text, transLang[1].checked ? cyr : arm);
		}		
	}
	activateTextArea();
	return result;
}

/**
 * This function makes convertion of letters according of given alphabeth
 * table and text.
 * @param text -- string, the text which should be changed
 * @param alphabeth -- array, the chosen alphabeth table to be used
 * @return returns changed (converted) text.
 **/
function translit(text, alphabet) {
	var buffer = "";
	var ch = "";
	var index = "";
	var i, ind;
	var len = text.length;
  
	for (i = 0; i < len; i ++) {
		ind = skip(text, i);
		if (ind > 0) {
			buffer += text.substr(i, ind - i + 1);
			i = ind;
			continue;
		}
    
		index = text.substr(i, (i < len - 1 ? 2 : 1));
		ch = alphabet[index];
		if (ch == null ) {
			index = text.substr(i, 1);
			ch = alphabet[index];
		} else {
			i ++;
		}
		buffer += ch == null ? index : ch;
	}
	return buffer;
}

/**
 * Checkes if a portion of text should be skiped.
 * The text is skiped if it is included between square brackets like '[' ']'
 * Also it is skiped if the text is between '{' and '}'
 * @param text -- string, the current buffered text which should be ckecked
 * @param startAt -- integer, the current position in the buffer
 * @return returns the length to be skiped during convertion.
 **/
function skip(text, startAt) {
	var ch = text.substr(startAt, 1);
	if (ch == '[')
	  return text.indexOf(']', startAt);
	else if (ch == '{')
	  return text.indexOf('}', startAt)
	else
	  return -1;
}

/**
 * Closes window
 **/
function closeWnd() {
  if (window.opener != null) {
    window.opener.focus();
  }
  window.close();
}

/**
 * Get browser type.
 * @return returns the following results:
 *			1. 'ie' if current browser is MS Internet Explorer
 *			2. 'ns' if current browser in Netscape
 *			3. 'opera' if current browser in Opera
 *			4. for other browsers it returns 'unknown'
 **/
function getBrowser() {
  var browser = navigator.appName;
  if ( browser == 'Microsoft Internet Explorer' )
    return('ie'); // Internet Explorer type
  else if ( browser.indexOf('Netscape') != -1 )
    return('ns'); // Netscape Communicator type
  else if ( (browser == 'Opera') || (navigator.userAgent.indexOf('Opera') > 0) )
    return('opera'); // Opera type
  else
    return('unknown'); // unknown type
}

/**
 * Opens new window according of given size and passes URL
 * @param openURL -- string, the URL to be passed to new opened window
 * @Param sizes -- string, the size of new window
 * @return retuns new opened window object
 **/
function openWnd(openURL, sizes) {
  prop = getBrowser() == 'ns' ? 'resizable=yes,menubar=yes,' : 'resizable=yes,';
  prop += sizes == null ? 'width=580,height=465' : sizes;
  
  newWnd=window.open(openURL,'help_wnd', prop); 
  newWnd.focus();
  return newWnd;
}

/**
 * Copies text to clipboard. This function works only for Internet Explorer
 **/
function copyText(text, textObj) {
  if (getBrowser() != 'ie') {
    // supported only for IE
    return;
  }
  
  window.clipboardData.clearData("Text");
  if (text != null) {
    textObj.select();
    window.clipboardData.setData("Text", text);
  }
}

/**
 * This funtion called when 'Replace' button is pressed. It replaces specified text.
 * @param text -- string, the text where replacement should be done
 * @param txtReplace -- string, the semicoma (';') separated symbols 
 *						or text to be replaced
 * @param txtWith -- string, the replaced with text. If this tex is empty the txtReplace
						text will be deleted.
 * @return returns changed text
 **/
function onReplace(text, txtReplace, txtWith) {
  if (txtReplace == null || txtReplace == '')
    return text;
    
  var chars = new Array();
  var start = 0;
  var end = -1;
  var n = 0;
  while ( ( end = txtReplace.indexOf(';', start) ) >= 0) {
    chars[n] = txtReplace.substring(start, end);
    n ++;
    start = end + 1;
  }
  chars[n] = txtReplace.substring(start, txtReplace.length);
  
  var loops = new Array();
  var i = 0;
  var len = chars.length;
  for (i = 0; i < len; i ++) {
    var str = chars[i];
    if (str == null || str == '')
      continue;
      
    var strLen = str.length;
    n = 0;
    start = 0;
    
    while ( ( end = text.indexOf(str, start) ) >= 0) {
      n ++;
      start = end + strLen;
    }
    loops [i] = n;
  }
  
  for (i = 0; i < len; i ++) {
    while (loops[i] > 0) {
      text = text.replace(chars[i], txtWith);
      loops[i] --;
    }
  }
  
  activateTextArea();
  
  return text;
}

/**
 * Togles current active language for translit
 * @param whichObj -- control, radio box control to be changed.
 **/
function togleLanguage(whichObj) {
	if ( !document.forms[0].transLang[1].disabled ) {
		whichObj.checked = 1;
	}
	activateTextArea();
}

/**
 * Enables or disables convertion of 'Armenian ASCII 8' text into Unicode
 * @param isCkeckBox -- boolean, if check box was pressed this is 'true', if
 *						static text was pressed this parameter is 'false'
 **/
function togleASCII(isCkeckBox) {
	with ( document.forms[0].ASCII_conv ) {
		if (!isCkeckBox)
			checked = !checked;			
		if (checked) {
			document.forms[0].transLang[0].checked = true;
			document.forms[0].transLang[1].disabled = true;
		} else {
			document.forms[0].transLang[1].disabled = false;
		}
	}
	activateTextArea();
}

/**
 * Converts ASCII text into Unicode
 * @param text -- string, ASCII string buffer to be converted
 * @param ascii_map -- array, the ASCII and Unicode mapping table
 * @return returns Unicode converted text
 **/
function convertAscii8ToUnicode(text, ascii_map) {
	var buffer = "";
	
	var ch_ascii = '';
	var ch_unicode = '';
	var ch = '';
	
	var length = text.length;
	
	for (var i = 0; i < length; i ++) {
		ch_8 = text.charAt(i);
		
		ch_16 = ascii_map[ch_8];
		buffer += ch_16 != null && ch_16 != '' ? ch_16 : ch_8;
	}
	
	activateTextArea();
	return buffer;
}

/**
 * Cleans text area. It deletes text inside
 **/
function cleanTextArea() {
	document.forms[0].txtWindow.value = '';
	activateTextArea();
}
