// Copyright © 2009 Behnevis.com
// Mouse position
// Detect if the browser is IE or not.
// If it is not IE, we assume that the browser is NS.
var IE = document.all?true:false

// If NS -- that is, !IE -- then set up for mouse capture
//if (!IE) document.captureEvents(Event.MOUSEMOVE)
if (!IE) document.addEventListener('mousemove', getMouseXY, false);


// Set-up to use getMouseXY function onMouseMove
document.onmousemove = getMouseXY;

var mousePos = new Object();


// Main function to retrieve mouse x-y pos.s

function getMouseXY(e) {

// Temporary variables to hold mouse x-y pos.s
var tempX = 0
var tempY = 0

if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  
  // show the position values in the form named Show
  // in the text fields named MouseX and MouseY
  mousePos.x = tempX
  mousePos.y = tempY
  return true
}

//*****************************************************************************
// Do not remove this notice.
//
// Copyright 2000-2004 by Mike Hall.
// See http://www.brainjar.com for terms of use.
//*****************************************************************************

//----------------------------------------------------------------------------
// Code to determine the browser and version.
//----------------------------------------------------------------------------

function Browser() {

  var ua, s, i;

  this.isIE    = false;  // Internet Explorer
  this.isOP    = false;  // Opera
  this.isNS    = false;  // Netscape
  this.version = null;

  ua = navigator.userAgent;

  s = "Opera";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isOP = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as Netscape 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }

  s = "MSIE";
  if ((i = ua.indexOf(s))) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }
}

var browser = new Browser();



// auto resizing iframe
//Input the IDs of the IFRAMES you wish to dynamically resize to match its content height:
//Separate each ID with a comma. Examples: ["myframe1", "myframe2"] or ["myframe"] or [] for none:
var iframeids=["popupIframe"]

//Should script hide iframe from browsers that don't support this script (non IE5+/NS6+ browsers. Recommended):
var iframehide="no"

var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
var FFextraHeight=parseFloat(getFFVersion)>=0.1? 3 : 0 //extra height in px to add to iframe in FireFox 1.0+ browsers

function resizeCaller() {
var dyniframe=new Array()
for (i=0; i<iframeids.length; i++){
if (document.getElementById)
resizeIframe(iframeids)
//reveal iframe for lower end browsers? (see var above):
if ((document.all || document.getElementById) && iframehide=="no"){
var tempobj=document.all? document.all[iframeids] : document.getElementById(iframeids)
tempobj.style.display="block"
}
}
}

function resizeIframe(frameid){
var currentfr=document.getElementById(frameid)
if (currentfr && !window.opera){
currentfr.style.display="block"
if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) //ns6 syntax
currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight; 
else if (currentfr.Document && currentfr.Document.body.scrollHeight) //ie5+ syntax
currentfr.height = currentfr.Document.body.scrollHeight;
if (currentfr.addEventListener)
currentfr.addEventListener("load", readjustIframe, false)
else if (currentfr.attachEvent){
currentfr.detachEvent("onload", readjustIframe) // Bug fix line
currentfr.attachEvent("onload", readjustIframe)
}
}
}

function readjustIframe(loadevt) {
var crossevt=(window.event)? event : loadevt
var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement
if (iframeroot)
resizeIframe(iframeroot.id);
}

function loadintoIframe(iframeid, url){
if (document.getElementById)
document.getElementById(iframeid).src=url
}

function initIframe()
{
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id","popupIframe");
	iframe.setAttribute("name","popupIframe");
//	iframe.setAttribute("height","185");

	iframe.setAttribute("width","300"); // 100

	iframe.setAttribute("frameBorder","1");
	iframe.setAttribute("scrolling","no");
	//iframe.setAttribute("src","http://www.yahoo.com");
	iframe.style.position = "absolute";
	iframe.style.display = "block";
	iframe.style.top = 100 + 'px';
	iframe.style.left = 900 + 'px';
	iframe.style.zIndex = "1" ;
	iframe.style.backgroundColor = "#E0ECFF" ;
	iframe.style.visibility = "hidden" ;
	window.document.body.appendChild(iframe);
	setTimeout(";",250);
/*
	if (window.addEventListener)
	window.addEventListener("load", resizeCaller, false)
	else if (window.attachEvent)
	window.attachEvent("onload", resizeCaller)
	else
	window.onload=resizeCaller
*/
	
}

// alternative farsi letters
var alternativeFarsiLetterGroup = Array();
alternativeFarsiLetterGroup[0] = ['ث','س','ص','ش'];
alternativeFarsiLetterGroup[1] = ['ت','ط'];
alternativeFarsiLetterGroup[2] = ['ه','ح'];
alternativeFarsiLetterGroup[3] = ['ز','ذ','ض','ظ','ژ'];
alternativeFarsiLetterGroup[4] = ['غ','ق','گ'];
alternativeFarsiLetterGroup[5] = ['ج','ژ'];
alternativeFarsiLetterGroup[6] = ['أ','ئ'];

var letterDeleteItemName =  'حذف';
var virtualSpaceName = '-';

var minDistanceToLeftEdge = 5; // minimum iframe left value 

function alternativeFarsiLetters(letter, alternatives)
{

	var alternatives = new Array;
	alternatives[0] = letter; // first alternative is always input letter
	
	var n = 1;
	for (var g = 0; g < alternativeFarsiLetterGroup.length; g++) 
	{
		if (alternativeFarsiLetterGroup[g].indexOf(letter) != -1)
		{
			for (var le = 0; le < alternativeFarsiLetterGroup[g].length; le++) 
			{
				if (alternativeFarsiLetterGroup[g][le] != letter) // exclude input letter since we have already added it
				{	
					alternatives[n] = alternativeFarsiLetterGroup[g][le];
					n++; 
				}
			}
		}
	}
	return alternatives;
}


function farsiLetterOptions(farsiLetter, farsiWord, latinWord, positonInfarsiLetter)
{		


	var originalFarsiLetter = farsiLetter;
	farsiLetter = mapFromActualLetterToLetterName(originalFarsiLetter); // for things like tashdid, hamze...

	if (originalFarsiLetter != farsiLetter) // for cases like tashdid, hamze which we have the name of the letter instead of actual character
	{
		// only include the letter name, like tashdid and hazf in options.
		var letterOption = new Array();
		letterOption[0] = farsiLetter;		
		letterOption[1] = letterDeleteItemName;
		return letterOption;
	}

	alternatives = alternativeFarsiLetters(farsiLetter);
	n = 0;
	var letterOption = new Array();
	
	for (var i = 0; i < alternatives.length; i++) 
	{
		letterOption[n] = alternatives[i];
		n++;
	}
	

	for (var i = 0; i < alternatives.length; i++) 
	{
		if (alternatives[i]!='ا') //  prevent double aa
		{
			letterOption[n] = alternatives[i] + 'ا'; // alef
			n++;
		}
	}

	for (var i = 0; i < alternatives.length; i++) 
	{
		letterOption[n] = alternatives[i] + 'ع'; 
		n++;
	}


	if (positonInfarsiLetter == 0)
	{

		if (letter = 'ا')
		{
			letterOption[n] = 'آ'; // change a to aa in teh beginning
			n++;		
			
			letterOption[n] = 'ع'; // change a to a` (ein) in teh beginning
			n++;		
		}

		for (var i = 0; i < alternatives.length; i++) 
		{
			if (alternatives[i]!='ا') //  prevent double aa
			{
				letterOption[n] = 'آ' +alternatives[i] + 'ع'; 
				n++;
			}
		}
		
	} 
	
	if (positonInfarsiLetter == (farsiWord.length-1) && latinWord && latinWord.charAt(latinWord.length-1) == 'e') // e at end to he
	{
		for (var i = 0; i < alternatives.length; i++) 
		{
			letterOption[n] = alternatives[i] + 'ه';
			n++;
		}
	} 
	

	if (positonInfarsiLetter == (farsiWord.length-1) && latinWord && latinWord.charAt(latinWord.length-1) == 'n') // e at end to he
	{
		for (var i = 0; i < alternatives.length; i++) 
		{
			letterOption[n] =  'ا'; // 'an' at the end
			n++;
		}
	} 

	if (farsiLetter == 'خ') // e at end to he

	{
			letterOption[n] =  'خو'; // 'an' at the end
			n++;
			letterOption[n] =  'خوا'; // 'an' at the end
			n++;
	} 


	if (farsiLetter == 'ی' && positonInfarsiLetter != (farsiWord.length-1) ) // ی to ئ
	{
			letterOption[n] =  'ئ'; // 'an' at the end
			n++;
			
			letterOption[n] =  'ی' + ' ' + virtualSpaceName; // virtual space after ی
			n++;						
	} 

	if (farsiLetter == 'ه' && positonInfarsiLetter != (farsiWord.length-1) ) // ه to نیم‌فاصله+ه
	{

			letterOption[n] =  'ه' + ' ' + virtualSpaceName; // virtual space after ی
			n++;						
	} 



	if (latinWord.indexOf('o')>-1 && farsiLetter != 'خ') // latin word has at least one o
	{
		for (var i = 0; i < alternatives.length; i++) 
		{
			letterOption[n] =  alternatives[i] + 'و'; // 'an' at the end
			n++;
		}
	} 


	if (letterOption[0] == virtualSpace)
	{
		letterOption = new Array();
		letterOption[0] = virtualSpaceName;
		n = 1;
	}
	
	letterOption[n] =  letterDeleteItemName; //  remove letter 
	n++;

	return letterOption;
}



function submitCorrection(latinText, farsiText)
{
	ajax("/php/correct.php", "farsi="+ encodeURI(farsiText)+"&" + "latin="+encodeURI(latinText));
}

function replaceWordInSingleEditor(fromWord, toWord)
{
	// replace word enclosed by spaces
	myregexp = new RegExp(' ' + fromWord + ' ', "g");
	document.getElementById(latinControlId).value = document.getElementById(latinControlId).value.replace(myregexp, ' ' + toWord + ' ');

	// replace word at the beginning, ^ is the beginning of the line
	myregexp = new RegExp('^' + fromWord + ' ', "g");
	document.getElementById(latinControlId).value = document.getElementById(latinControlId).value.replace(myregexp, toWord + ' ');

	// replace word at the end, $ is the end of the line orstring
	myregexp = new RegExp(' ' + fromWord + '$', "g");
	document.getElementById(latinControlId).value = document.getElementById(latinControlId).value.replace(myregexp, ' '+ toWord + ' ');

}

function removeHarekatLettersFromFarsiWord(farsiWord) // remove fathme, kasre and zamme from a farsi word
{
    var myregexp = new RegExp(kasreLetter + '|' + fatheLetter + '|' + zammeLetter, 'g');
    farsiWord = farsiWord.replace(myregexp, '');
	return farsiWord;
}

function updateFarsiConversion()
{
  var iframeDOM = window.frames["popupIframe"].document;
  var latinWord= latinFromFarsiWordsTable.getItem(originalFarsiWord);
  var farsiWord = iframeDOM.getElementById("farsiWordCell").innerHTML;
  knownWordsTable.setItem(latinWord, farsiWord);
  latinFromFarsiWordsTable.setItem(farsiWord, latinWord);
  
// in case of one-line editor, do a replace 
  if (latinControlId == farsiControlId)
  {
	  replaceWordInSingleEditor(farsiSelection.expanded, farsiWord);
  }

  farsiWord = removeHarekatLettersFromFarsiWord(farsiWord); // prevent harekats (zamme, fathe, kasre) to be submitted along with other farsi letters
  
  submitCorrection(latinWord, farsiWord);
  
  // save correction into local storge (where HTML 5 is enabled)
  if (typeof localStorage != "undefined")
  {
	  localStorage.setItem(latinWord, farsiWord); 
  }
  
  convertAnyTypeOFLatinEditorTextToFarsi();
  hidePopup();
  
}

var iframeDOM;

function updateFarsiWordInFrame()
{
 var farsiWord = "";
 var selectBox;
 if (window)
 {
	 var iframeDOM = window.frames["popupIframe"].document;
//	 var iframeDOM = document;
 }
 else
 {
	 var iframeDOM = document;
 }

 if(!iframeDOM.getElementById("farsiWordCell"))
 	return;

var selectBox;
var selectRow = iframeDOM.getElementById("selectRow");
var letterName, actualLetter; // actualLetter means the letter (character) to be added to the word

 for (var i = selectRow.cells.length-1; i>=0; i--) 
 if (selectRow.cells[i].childNodes[0].tagName == 'SELECT')
 {
 	//selectBox = iframeDOM.getElementById("wordSegment"+i);
	selectBox = selectRow.cells[i].childNodes[0];
	letterName = selectBox.options[selectBox.selectedIndex].text; 
	actualLetter = mapFromLetterNameToActualLetter(letterName);
	
	farsiWord = farsiWord + actualLetter;	
 }


// replace ' -' with virtual space
 var myregexp = new RegExp(virtualSpaceName, 'g');
 farsiWord = farsiWord.replace(myregexp, virtualSpace);
 farsiWord = farsiWord.replace(/\s/g, ''); // remove space

 
 iframeDOM.getElementById("farsiWordCell").innerHTML = farsiWord;
}

function bringFarsiControlInFocus()
{
	if (latinTextIsHtml)
	{
		farsiTinyMCE.focus();
		tinyMCE.activeEditor.selection.moveToBookmark(htmlSelectionBookmark);		
	}
	else
	{
		document.getElementById(farsiControlId).focus();
	}
}



function turnWordIntoLatin() { // forced replace is when there are no unknown words and we want to replace with farsi
	var latinWord= latinFromFarsiWordsTable.getItem(originalFarsiWord);
	var myregexp = new RegExp('\\b' + latinWord +'\\b', 'gi'); // needs to be more restriced so it does not replace all 'ha's
	if (latinTextIsHtml)
	{
		var x = latinTinyMCE.getDoc();
		var result = new String;
		arr = Array();
        arr = traverseDOM(x, arr);
        
		for (var i = 0; i < arr.length; i++) {
			if (arr[i] && arr[i].nodeType==3)

			{
				if (arr[i].textContent)  // for firefox that uses this
				{
					arr[i].textContent = arr[i].textContent.replace(myregexp,"/"+ latinWord);			
				}
				else	// for IE
				{	
					arr[i].nodeValue = arr[i].nodeValue.replace(myregexp,"/"+ latinWord);	
				}				
			}
			
        }
	}
	else
	{
		if (latinControlId == farsiControlId)
		{		
			replaceWordInSingleEditor(originalFarsiWord,  "/"+ latinWord);
		}
		else
		{
			document.getElementById(latinControlId).value = document.getElementById(latinControlId).value.replace(myregexp, "/"+ latinWord);
		}

	}

	// refresh the conversion
	setConversionFinishedStatusDisplay(false);
	submitAjaxRequestIfNecessary();
}


var originalFarsiWord;

function adjustIframeWidth()
{
	var wordListTable = iframeDOM.getElementById('wordListTable');
	var buttonsTable =  iframeDOM.getElementById('buttonsTable');
	iframe.setAttribute("width", Math.max(parseInt(wordListTable.clientWidth)+10, parseInt(buttonsTable.clientWidth))+10);

	resizeIframe('popupIframe');
	
//	resizeIframe('popupIframe');

	iframe.style.visibility = "visible" ;
	
	// becuase i found out in IE, you cannot assign a width until the iframe is visible!
	iframe.setAttribute("width", Math.max(parseInt(wordListTable.clientWidth)+10, parseInt(buttonsTable.clientWidth))+10);	
}

function formatWordListSelectElement(wordList)
{
	wordList.size = 1;
	wordList.setAttribute("dir","rtl");
	wordList.setAttribute("border","1");
	wordList.style.backgroundColor = "#E0ECFF" ;
	if (IE) 
	{
		wordList.style.fontSize = "16"; 
		wordList.style.fontWeight = "bold";
	}
	else
	{
		wordList.style.fontSize = "14";  

	}
	wordList.style.border = "1";
	wordList.style.margin = "0";
	wordList.style.marginTop = "0";
	return wordList;
}

var plusLinkNameBasePart = "plusLink";
var wordListNameBasePart = "additionalWordList"

function hidePlusLinkAndShowLetterSelect(plusLink)
{
	// save the width before new elements are made visible
	var wordListTable = iframeDOM.getElementById('wordListTable');
	var originalTableWidth = wordListTable.clientWidth;
	
	plusLink.style.display = 'none';
	
	// extract letterNumber from link ID and make the additional word select visible
	var letterNumberAsString = plusLink.id.slice(plusLinkNameBasePart.length);

	// IE has some issues with display styles
	if (IE)
	{
		iframeDOM.getElementById(wordListNameBasePart + letterNumberAsString).style.display = '';
	}
	else
	{
		iframeDOM.getElementById(wordListNameBasePart + letterNumberAsString).style.display = 'inherit';
	}
	
	// here we just adjust the width of irafem and its left side position after new elements are shown
	adjustIframeWidth();
	iframe.style.left = Math.max(minDistanceToLeftEdge, parseInt(iframe.style.left) - (parseInt( wordListTable.clientWidth) - parseInt(originalTableWidth))) +'px'; // prevent the edge to get closer than 5 pixels to the left edge of the browser window
	
	return false;
}

// add plus to the word list table for adding new letters
function addPlusToWordList(selectRow, letterNumber)
{


	plusLink = iframeDOM.createElement("a");
	plusLink.setAttribute("id",plusLinkNameBasePart + letterNumber);
	plusLink.setAttribute("name",plusLinkNameBasePart + letterNumber);
//	plusLink.setAttribute("type","button");
	plusLink.setAttribute("align","center");
	plusLink.setAttribute("href","#");
	plusLink.title = 'افزودن حرف جدید در اینجا';
	plusLink.innerHTML = "+";
	plusLink.style.textDecoration = 'none'; // no underline for the link
	plusLink.style.color = '#CC0000'; // no underline for the link
	if (IE)
	{
		plusLink.style.fontFamily = "Tahoma, Arial, Helvetica, sans-serif";
		plusLink.style.fontSize = "12pt";
	}
	else
	{
		plusLink.style.fontSize = "normal";
	}

	plusLink.style.fontWeight = 'bold';
	plusLink.style.display =  'none'; // at the begining the plus links are hidden
	
	plusLink.onclick = function(){return hidePlusLinkAndShowLetterSelect(this);}; 
	
	var newSelectCell = selectRow.insertCell(0);
	newSelectCell.appendChild(plusLink);
	
	
	// add a select button after it
	
	var wordList = iframeDOM.createElement("select");
	
	wordList.setAttribute("id", wordListNameBasePart + letterNumber);
	wordList.setAttribute("name", wordListNameBasePart + letterNumber);

	wordList.options[0] =  new Option(letterDeleteItemName); // hazf to remove letter
	var letterToBeAdded;
	for (var j = 0; j < AllFarsiLettersThatCanBeAdded.length; j++) 
	{
		letterToBeAdded = AllFarsiLettersThatCanBeAdded.charAt(j);
		wordList.options[j+1] = new Option(mapFromActualLetterToLetterName(letterToBeAdded));
	}

	wordList = formatWordListSelectElement(wordList);

	// at first all additional letter selects are hidden, they will display after their + link is clicked
	wordList.style.display =  'none';
	wordList.onchange=function(){updateFarsiWordInFrame(this);};
	
	// insert a new column 
	var newSelectCell = selectRow.insertCell(0);
	newSelectCell.appendChild(wordList);
}

function formatButton(button)
{
	button.setAttribute("type","button");
	button.setAttribute("align","center");
	if (IE)
	{
		button.style.fontFamily = "Tahoma, Arial, Helvetica, sans-serif";
		button.style.fontSize = "9pt";
	}
	else
	{
		button.style.fontSize = "small";
	}
	
	return button;
}

function showAllPlusLinks()
{
	// save the width before new elements are made visible
	var wordListTable = iframeDOM.getElementById('wordListTable');
	var originalTableWidth = wordListTable.clientWidth;
	
	for (var i = 0; i < originalFarsiWord.length+1; i++) 
	{	
		if (IE)
		{
			iframeDOM.getElementById(plusLinkNameBasePart + i).style.display = '';
		}
		else
		{
			iframeDOM.getElementById(plusLinkNameBasePart + i).style.display = 'inherit';
		}
	}
	
	// here we just adjust the width of irafem and its left side position after new elements are shown
	adjustIframeWidth();
	iframe.style.left = Math.max(minDistanceToLeftEdge, parseInt(iframe.style.left) - (parseInt( wordListTable.clientWidth) - parseInt(originalTableWidth))) +'px';

}

function populateIframe(farsiWord)
{
	
	originalFarsiWord = farsiWord;
	iframe = document.getElementById("popupIframe");
	iframeDOM = window.frames["popupIframe"].document;

	// overcome IE bug
	iframeDOM.open();
	iframeDOM.write('<body bgcolor="#E0ECFF">');
//	iframeDOM.write("<script type='text/javascript' src='/javascript/correctionpopup.js'>");
	iframeDOM.write('</' + 'script>'); 
	iframeDOM.close();


	iframe.setAttribute("width",0); // reset the width so it wil not be affected by what it was before


	var latinAndfarsiWordsTable = iframeDOM.createElement("table");	
	var latinAndfarsiWordsTableRow = latinAndfarsiWordsTable.insertRow(0);
	var latinCell = latinAndfarsiWordsTableRow.insertCell(0);
	var farsiCell = latinAndfarsiWordsTableRow.insertCell(1);
	latinCell.innerHTML = latinFromFarsiWordsTable.getItem(farsiWord);
	farsiCell.innerHTML = farsiWord;
	iframeDOM.body.appendChild(latinAndfarsiWordsTable);

	latinAndfarsiWordsTable.setAttribute("align","center");
	latinAndfarsiWordsTable.setAttribute("width","70%");
	latinAndfarsiWordsTable.style.fontSize = "large";

	latinCell.setAttribute("align","center");	
	farsiCell.setAttribute("align","center");	
	latinAndfarsiWordsTable.style.fontWeight = "bold";
	latinAndfarsiWordsTable.style.marginBottom = "7";
	latinCell.style.color = "#666";

	farsiCell.setAttribute("id","farsiWordCell");
	farsiCell.setAttribute("name","farsiWordCell");

	// table that contains alternative letter select boxes
	var wordListTable = iframeDOM.createElement("table");	
	wordListTable.setAttribute("id","wordListTable");
	wordListTable.setAttribute("name","wordListTable");
	wordListTable.setAttribute("align","center");
	wordListTable.setAttribute("width","90%");
	wordListTable.style.fontSize = "large";
	iframeDOM.body.appendChild(wordListTable);
	
	var selectRow = wordListTable.insertRow(0);
	selectRow.setAttribute("id","selectRow");
	selectRow.setAttribute("name","selectRow");
	
	var newSelectCel;
	
	for (var i = 0; i < farsiWord.length; i++) 
	{
		if (farsiWord.charAt(i) !='')
		{

			addPlusToWordList(selectRow, i);

			var wordList = iframeDOM.createElement("select");
			var farsiLetter = farsiWord.charAt(i);
			letterOptions = farsiLetterOptions(farsiLetter, farsiWord, latinFromFarsiWordsTable.getItem(farsiWord), i);
			
			for (var j = 0; j < letterOptions.length; j++) 
			{
				wordList.options[j] = new Option(letterOptions[j]);
			}
		
			wordList.setAttribute("id","wordSegment"+i); // first they are letter, then they may contain more letters
			wordList.setAttribute("name","wordSegment"+i);
			
			wordList = formatWordListSelectElement(wordList);

			var newSelectCell = selectRow.insertCell(0);
			newSelectCell.appendChild(wordList);

			wordList.onchange=function(){updateFarsiWordInFrame(this);};
		}
	}
	
	// add one plus after the last letter
	addPlusToWordList(selectRow, farsiWord.length);
	
	var buttonsTable = iframeDOM.createElement("table");
	buttonsTable.setAttribute("id","buttonsTable");
	buttonsTable.setAttribute("name","buttonsTable");
	buttonsTable.style.fontSize = "small";
	buttonsTable.setAttribute("align","center");
	buttonsTable.style.width = "95%";
	buttonsTable.setAttribute("dir","rtl");
	buttonsTable.style.fontWeight = "bold";
	buttonsTable.style.marginTop = "7";
	buttonsTable.style.marginBottom = "7";
	iframeDOM.body.appendChild(buttonsTable);
	
	var buttonsTableTableRow = buttonsTable.insertRow(0);
	buttonsTableTableRow.setAttribute("align","center");
	
	var okButtonTableTableCell = buttonsTableTableRow.insertCell(0);
	var latinButtonTableTableCell = buttonsTableTableRow.insertCell(1);
	var addLetterButtonTableTableCell = buttonsTableTableRow.insertCell(2);
	var cancelButtonTableTableCell = buttonsTableTableRow.insertCell(3);
	
	okButtonTableTableCell.setAttribute("align","center");
	cancelButtonTableTableCell.setAttribute("align","center");
	
	okButton = iframeDOM.createElement("input");
	okButton.setAttribute("id","okButton");
	okButton.setAttribute("name","okButton");
	okButton.setAttribute("value"," قبول ");
	okButton = formatButton(okButton);		
	okButton.onclick = function(){ updateFarsiConversion(this);bringFarsiControlInFocus();};
	okButtonTableTableCell.appendChild(okButton);

	latinButton = iframeDOM.createElement("input");
	latinButton.setAttribute("id","latinButton");
	latinButton.setAttribute("name","latinButton");
	latinButton.setAttribute("value","لاتین");
	latinButton = formatButton(latinButton);	
//	latinButton.style.marginRight = "15";
	latinButton.onclick = function(){turnWordIntoLatin(); hidePopup(this);};
	latinButtonTableTableCell.appendChild(latinButton);

	addLetterButton = iframeDOM.createElement("input");
	addLetterButton.setAttribute("id","addLetterButton");
	addLetterButton.setAttribute("name","addLetterButton");
	addLetterButton.setAttribute("value","افزودن حرف");
	addLetterButton = formatButton(addLetterButton);	
	addLetterButton.onclick = function(){showAllPlusLinks();};
	addLetterButtonTableTableCell.appendChild(addLetterButton);

	cancelButton = iframeDOM.createElement("input");
	cancelButton.setAttribute("id","cancelButton");
	cancelButton.setAttribute("name","cancelButton");
	cancelButton.setAttribute("value","انصراف");
	cancelButton = formatButton(cancelButton);
	cancelButton.onclick = function(){hidePopup(this);bringFarsiControlInFocus()};

	cancelButtonTableTableCell.appendChild(cancelButton);

	adjustIframeWidth();
	
}


function showPopup()
{
	// position the iframe
	iframe = document.getElementById("popupIframe");
/*	
	// remove all child nodes, why?!
	 while (iframe.childNodes[0])
	 {
     	iframe.removeChild(iframe.childNodes[0]);
      }
*/
	//opera Netscape 6 Netscape 4x Mozilla 
	if (window.innerWidth || window.innerHeight){ 
		documentWidth = window.innerWidth; 
		documentHeight = window.innerHeight; 
	} 
	//IE Mozilla 
	if (document.body.clientWidth || document.body.clientHeight){ 
		documentWidth = document.body.clientWidth; 
		documentHeight = document.body.clientHeight; 		
		
	//	documentHeight = document.documentElement.clientHeight;
	//	documentWidth = document.documentElement.clientHWidth;
	} 

	if (documentWidth>700 && documentHeight>600) // where there is enough space, else place it in the center
	{
	  // make sure it does not go outside the main window
	  if (parseInt(mousePos.x) + parseInt(iframe.width)<documentWidth-5)
	  {
		  iframe.style.left = mousePos.x + 'px';
	  }
	  else
	  {
		  iframe.style.left = parseInt(mousePos.x) - parseInt(iframe.width)+ 'px';
	  }
  
	  if (parseInt(mousePos.y) + parseInt(iframe.height)<documentHeight-5)
	  {
		  iframe.style.top = mousePos.y + 'px';
	  }
	  else
	  {
		  iframe.style.top = parseInt(mousePos.y) - parseInt(iframe.height)+ 'px';
	  }
	}
	else // when the parent docuemnt is too small, place it in the center
	{
   		  iframe.style.left = Math.round((documentWidth - parseInt(iframe.width))/2) + 'px';
		  
		  if (IE) // since IE window is a bit larger, sometimes not enough vertical space is available
		  {
		  	iframe.style.top = 5 + 'px';
		  }
		  else
		  {
			iframe.style.top = Math.round((documentHeight - parseInt(iframe.height))/2) + 'px';			
		  }
		
	}

	iframe.style.visibility = "visible" ;
}


var virtualSpace = String.fromCharCode(0x200C);
var tashdidLetter = 'ّ'; // it has tashdid but cannot be seen !
var tashdidName = 'تشدید';
var hamzeLetter = 'ٔ';
var hamzeName = 'همزه';
var tanvinLetter = String.fromCharCode(0x64b);
var tanvinName = 'تنوین';
var kasreLetter = String.fromCharCode(0x650);
var kasreName = 'کسره';
var fatheLetter = String.fromCharCode(0x64e);
var fatheName = 'فتحه';
var zammeLetter = String.fromCharCode(0x64f);
var zammeName = 'ضمه';


var AllFarsiLetters = 'اآبپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیهأئ';
var AllFarsiLettersAllowedInWord = AllFarsiLetters + virtualSpace + hamzeLetter + tashdidLetter + tanvinLetter + kasreLetter + fatheLetter + zammeLetter;
var AllFarsiLettersThatCanBeAdded = virtualSpaceName + AllFarsiLetters + hamzeLetter + tashdidLetter + tanvinLetter + kasreLetter + fatheLetter + zammeLetter; 

var mappingBetweenSelectLetterNamesAndActualLetters = new Hash();
mappingBetweenSelectLetterNamesAndActualLetters.setItem('-', virtualSpace);
mappingBetweenSelectLetterNamesAndActualLetters.setItem(' -', virtualSpace);
mappingBetweenSelectLetterNamesAndActualLetters.setItem(letterDeleteItemName, '');
mappingBetweenSelectLetterNamesAndActualLetters.setItem(tashdidName, tashdidLetter);
mappingBetweenSelectLetterNamesAndActualLetters.setItem(hamzeName, hamzeLetter);
mappingBetweenSelectLetterNamesAndActualLetters.setItem(tanvinName, tanvinLetter);
mappingBetweenSelectLetterNamesAndActualLetters.setItem(kasreName, kasreLetter);
mappingBetweenSelectLetterNamesAndActualLetters.setItem(fatheName, fatheLetter);
mappingBetweenSelectLetterNamesAndActualLetters.setItem(zammeName, zammeLetter);


function mapFromLetterNameToActualLetter(letterName)
{
	if (mappingBetweenSelectLetterNamesAndActualLetters.hasItem(letterName))
	{
		return  mappingBetweenSelectLetterNamesAndActualLetters.getItem(letterName);
	}
	else
	{
		return  letterName;
	}	
}


function mapFromActualLetterToLetterName(actualLetter)
{
	if (typeof(mappingBetweenSelectLetterNamesAndActualLetters.firstKeyForValue(actualLetter))!= 'undefined')
	{
		return  mappingBetweenSelectLetterNamesAndActualLetters.firstKeyForValue(actualLetter);
	}
	else
	{
		return  actualLetter;
	}	
}

function removeNonFarsiLettersFromText(inputText)
{
	var result = new String;
	for (var z = 0; z < inputText.length; z++)
	{
		if (AllFarsiLettersAllowedInWord.indexOf(inputText.charAt(z)) >-1)
		{
			result = result + inputText.charAt(z);			
		}
	}
	return result;
}


var htmlSelectionBookmark;
function getSelectedText()
{
var farsiSelection =new Object();
	
/*	if (browser.isIE)
	{
		var range = document.selection.createRange();
		farsiSelection.original = range.text;
		range.expand("word");
		farsiSelection.expanded = range.text;

		// remove the space at the end of string
		while (farsiSelection.expanded.charAt(farsiSelection.expanded.length-1) == ' ')
		{
					farsiSelection.expanded = farsiSelection.expanded.slice(0,-1);
		}
	}
	else
	{
*/

 if (latinTextIsHtml)
 {
	htmlSelectionBookmark = tinyMCE.activeEditor.selection.getBookmark();
		
	if (browser.isIE)
	{
	// there is a bug here, if two words like ali-nejad are separated by a virtual chaacter, it returns the combination of both
		var range = tinyMCE.activeEditor.selection.getRng();
		
		farsiSelection.original = range.text;
		range.expand("word");
		
		//farsiSelection.expanded = range.text;
		farsiSelection.expandedWithVirtualSpace = range.text;
		farsiSelection.expandedWithoutVirtualSpace = range.text;
		
		return farsiSelection;		

	}
	else // firefox
	{
		var range = tinyMCE.activeEditor.selection.getRng();
		var fValue = range.startContainer.nodeValue;
		var expandedStart = range.startOffset;
		var expandedEnd = range.endOffset;
		
		//var trange = farsiTinyMCE.selection.getRng();
		console.log('fValue', fValue);
	}
 }
 else // in not html editor
 {
	var farsiContorl = document.getElementById(farsiControlId);
		
	if (browser.isIE)
	{
		var txt = farsiContorl.value;
		var len = txt.length;
		var erg = txt.split("\n");
		var pos = -1;
		range_sel = document.selection.createRange();
		range_obj = farsiContorl.createTextRange();
		range_obj.moveToBookmark(range_sel.getBookmark());
		range_obj.moveEnd('character',farsiContorl.value.length);
		pos = len - range_obj.text.length;

		expandedStart = pos;
		expandedEnd = pos+1;
	}
	else // firefox
	{
		var expandedStart = farsiContorl.selectionStart;
		var expandedEnd = farsiContorl.selectionEnd;
		farsiSelection.original = farsiContorl.value.substring(farsiContorl.selectionStart, farsiContorl.selectionEnd);
	}
		var fValue = farsiContorl.value;
 }

originalExpandedStart = expandedStart;
originalExpandedEnd = expandedEnd;

for (var includeVirtualSpace = 0; includeVirtualSpace <= 1; includeVirtualSpace++) 
{

  expandedStart = originalExpandedStart;
  expandedEnd = originalExpandedEnd;
  
  // move to the start of first word
  firstCharacter = fValue.substring(expandedStart, expandedEnd).charAt(0);
  
  while (firstCharacter != " " && (firstCharacter !=String.fromCharCode(0x200C) || includeVirtualSpace==1) && firstCharacter !="\n" && expandedStart > -1)
//  while (firstCharacter != " " && firstCharacter !="\n" && expandedStart > -1)
  {			
	  expandedStart--;
	  firstCharacter = fValue.substring(expandedStart, expandedEnd).charAt(0);
	  
  }
  expandedStart ++;
  
  
  lastCharacter = fValue.substring(expandedEnd-1, expandedEnd);		
  while (lastCharacter != " " && (lastCharacter !=String.fromCharCode(0x200C)  || includeVirtualSpace==1) && lastCharacter !="\n" && expandedEnd <= fValue.length)
//  while (lastCharacter != " " && lastCharacter !="\n" && expandedEnd <= fValue.length)
  {
  expandedEnd++;
	  lastCharacter = fValue.substring(expandedEnd-1, expandedEnd);		
  }
  expandedEnd --;

  if (includeVirtualSpace==1)
  {
	  farsiSelection.expandedWithVirtualSpace = fValue.substring(expandedStart, expandedEnd);
  }
  else
  {
  	  farsiSelection.expandedWithoutVirtualSpace = fValue.substring(expandedStart, expandedEnd);
  }


}


//farsiSelection.expanded = fValue.substring(expandedStart, expandedEnd);

return farsiSelection;
}

function farsiEditorClicked()
{
	//console.log('farsiEditorClicked enetered');
	farsiSelection = getSelectedText();

	console.log('farsi text selected = ' + farsiSelection.expandedWithVirtualSpace );
	//console.log('selection', farsiSelection);
	
	farsiSelection.expandedWithoutVirtualSpace = removeNonFarsiLettersFromText(farsiSelection.expandedWithoutVirtualSpace);
	farsiSelection.expandedWithVirtualSpace = removeNonFarsiLettersFromText(farsiSelection.expandedWithVirtualSpace);

	// first search for the word including the virtual-space, if not found use the section withouth it
	var originalLatinWord =  latinFromFarsiWordsTable.getItem(farsiSelection.expandedWithVirtualSpace);
	if (originalLatinWord)
	{
		farsiSelection.expanded = farsiSelection.expandedWithVirtualSpace;
	}
	else
	{
		originalLatinWord =  latinFromFarsiWordsTable.getItem(farsiSelection.expandedWithoutVirtualSpace);
		farsiSelection.expanded = farsiSelection.expandedWithoutVirtualSpace;
	}

	if (farsiSelection.expanded.length > 0 && originalLatinWord)
	{
		populateIframe(farsiSelection.expanded);
		showPopup();
	}
}


function hidePopup()
{
	iframe = document.getElementById("popupIframe");
	iframe.style.visibility = "hidden" ;	
}




function pageMouseup(event) {

  var el;

  // Find the element that was clicked on.

  if (browser.isIE)
    el = window.event.srcElement;
  else
    el = (event.target.tagName ? event.target : event.target.parentNode);

  // If the active button was clicked on, exit.

  if (el != document.createElement("iframe"))
  {
	hidePopup();
  }
}

function setEventHandlers()
{
	// add mousedown event handler to farsiControl
	document.getElementById(farsiControlId).onclick = farsiEditorClicked;
	
	// mouse down on other parts of the document
	if (browser.isIE)
  		document.onmouseup = pageMouseup;
	else
  		document.addEventListener("mouseup", pageMouseup, true);
}


