var prevText = "";
var prevWordNum = 0;
var resultText = "";
var infoNum = 8;
var maxChar = 300;
var LINEBREAK_CODE = 10;
var playingSound = false;
var prevPronounceWord = -1;
var prevPronounceWordClass = "translateDict_char";
var readySearch = true;
var newSearch = true;
var soundList = new Array();
var pinyinList = new Array();
var charList = new Array();
var otherPinYinList = new Array();
var otherSimplePinYinList = new Array();
var otherPinYinExampleList = new Array();
var thirdSound = new Array("ă", "ě", "ĭ", "ŏ", "ŭ", "ǚ");

function FormatResult(txtResult, charPerRow)
{
	if (txtResult == "") return;
	var cssClassList = new Array("translateDict_char", "translateDict_phrase", "translateDict_word", "translateDict_char", "translateDict_mchar");
	var resultList = txtResult.split("|");
	var noOfToken = resultList.length / infoNum;
	var curRow = 0;
	var charWrote = 0;
	var totalChar = 0;
	var rowStart = 0;
	var totalCharWrote = 0;

	if (resultList.length < infoNum) return;
	for (var i = 0; i < noOfToken; ++i)
	{
		totalChar += parseInt(resultList[noOfToken * 3 + i], 10);
	}

	var returnResult = ""; 
	var haveOtherPinYin = false;
	
	while (totalCharWrote < totalChar)
	{
		i = rowStart;
		charWrote = 0;
		
		if (totalCharWrote + charPerRow >= totalChar) //last row
		{
			returnResult += "<table border=\"0\"><tr>";	
		}
		else
		{
			returnResult += "<table id=\"tblResult\"" + curRow + "\" border=\"0\" style=\"width: " + SetTableWidth(resultList, i, charPerRow) + "\"><tr>";
		}
		
		while ((charWrote < charPerRow) && (i < noOfToken) && (resultList[i].charCodeAt(0) != LINEBREAK_CODE))
		{
			if (newSearch)
			{
				pinyinList[i] = resultList[i];
				charList[i] = resultList[noOfToken + i];
				otherPinYinList[i] = resultList[noOfToken * 5 + i];
				otherSimplePinYinList[i] = resultList[noOfToken * 6 + i];
				otherPinYinExampleList[i] = resultList[noOfToken * 7 + i];
			}
			
			returnResult += '<td id="tdPinYin_'+i+'" class="'+cssClassList[parseInt(resultList[noOfToken * 4 + i], 10)]+'" align="center" nowrap>';
			returnResult += '<div class="translateDict_pinyinResult" style="z-index:'+(maxChar-i)+'" >';
			returnResult += '<div id="pinyin_'+i+'" '+(cssClassList[parseInt(resultList[noOfToken * 4 + i], 10)]=='translateDict_mchar'?'class="translateDict_mPinYin"':'')+'>' + (newSearch ? resultList[i] : pinyinList[i]) + '</div>';
			var otherPinYinDivContent = GetOtherPinYinDiv(i)
			haveOtherPinYin = (otherPinYinDivContent != "" || haveOtherPinYin);
			returnResult += otherPinYinDivContent;
			returnResult += "</div>"
			returnResult += "</td>";
			
			charWrote += parseInt(resultList[noOfToken * 3 + i], 10);
			++i;
		}
		if (resultList[i].charCodeAt(0) == 13)
		{
			++i;
			++charWrote;
		}
		returnResult += "</tr>";

		returnResult += "<tr>";
		if (document.getElementById("chkShowBig5").checked)
		{
			i = rowStart;
			charWrote = 0;
			while ((charWrote < charPerRow) && (i < noOfToken) && (resultList[noOfToken + i].charCodeAt(0) != LINEBREAK_CODE))
			{
				returnResult += "<td class=\""+cssClassList[parseInt(resultList[noOfToken * 4 + i], 10)]+"\" align=\"center\" nowrap>";
				returnResult += resultList[noOfToken + i];
				returnResult += "</td>";
				
				charWrote += parseInt(resultList[noOfToken * 3 + i], 10);
				++i;
			}
		}
		if (resultList[noOfToken + i].charCodeAt(0) == LINEBREAK_CODE)
		{
			++i;
			++charWrote;
		}
		returnResult += "</tr>";

		returnResult += "<tr>";
		if (document.getElementById("chkShowGB").checked)
		{
			i = rowStart;
			charWrote = 0;
			while ((charWrote < charPerRow) && (i < noOfToken) && (resultList[noOfToken * 2 + i].charCodeAt(0) != LINEBREAK_CODE))
			{
				returnResult += "<td class=\""+cssClassList[parseInt(resultList[noOfToken * 4 + i], 10)]+"\" align=\"center\" nowrap>";
				returnResult += resultList[noOfToken * 2 + i];
				returnResult += "</td>";
				
				charWrote += parseInt(resultList[noOfToken*3 + i], 10);
				++i;
			}
		}
		returnResult += "</tr></table>";
		if (resultList[noOfToken * 2 + i].charCodeAt(0) == LINEBREAK_CODE)
		{
			++i;
			++charWrote;
		}
	
		totalCharWrote += charWrote;
		rowStart = i;
		++curRow;
	}
	
	if (haveOtherPinYin)
	{
		returnResult += "<br><font color='#C00000'>*</font>多音字的拼音以紅色標示，可選擇其他拼音。";
	}
	newSearch = false;
	document.getElementById("lblResult").innerHTML = returnResult;
}

function SetCharPerRow(num, delta)
{
	var target = parseInt(num, 10) + delta;
	if (!(parseInt(num, 10)))
	{
		target = 15;
	}
	
	target = (target < 1 ? 1 : target)
	document.getElementById('txtCharPerRow').value = target;
	FormatResult(resultText, target);
}

function RefreshResult(num)
{
	var numReg = /(^\d+$)/;
	if (numReg.test(num))
	{
		if (parseInt(document.getElementById("txtCharPerRow").value, 10) < 1)
		{
			document.getElementById("txtCharPerRow").value = 1;
		}
		FormatResult(resultText, parseInt(document.getElementById("txtCharPerRow").value, 10));
	}
}

function CopyResult()
{
	var copyBig5 = document.getElementById("chkCopyBig5").checked;
	var copyGB = document.getElementById("chkCopyGB").checked;
	var copyPinYin = document.getElementById("chkCopyPinYin").checked;
	var charPerRow = (document.getElementById("chkWrapText").checked ? parseInt(document.getElementById("txtCharPerRow").value, 10) : 99999);
	var currentToken = 0;
	var charWrote = 0;
	
	if ((resultText == "") || (!copyBig5 && !copyGB && !copyPinYin)) return;
	var resultList = resultText.split("|");
	var noOfToken = resultList.length / infoNum;
	var clipboardText = "";
	
	while (currentToken < noOfToken)
	{
		if (copyPinYin)
		{
			i = currentToken;
			while ((charWrote < charPerRow) && (i < noOfToken) && (resultList[i].charCodeAt(0) != LINEBREAK_CODE))
			{
				//if (resultList[i])
				if (pinyinList[i])
				{
					//clipboardText += resultList[i].RemoveExtraSpace();
					clipboardText += pinyinList[i].RemoveExtraSpace();
					clipboardText += ((i == noOfToken - 1) || (resultList[i].charCodeAt(resultList[i].length - 1) == 32) ? "" : " ");
				}
				
				charWrote += parseInt(resultList[noOfToken * 3 + i], 10);
				++i;
			}
			
			clipboardText += "\n";
			charWrote = 0;
		}
		
		if (copyBig5)
		{
			i = currentToken;
			while ((charWrote < charPerRow) && (i < noOfToken) && (resultList[noOfToken + i].charCodeAt(0) != LINEBREAK_CODE))
			{
				if (resultList[i])
				{
					clipboardText += resultList[noOfToken + i].RemoveExtraSpace();
				}
				
				charWrote += parseInt(resultList[noOfToken * 3 + i], 10);
				++i;
			}
			
			if (i != currentToken)
			{
				clipboardText += "\n";
			}
			charWrote = 0;
		}
		
		if (copyGB)
		{
			i = currentToken;
			while ((charWrote < charPerRow) && (i < noOfToken) && (resultList[noOfToken * 2 + i].charCodeAt(0) != LINEBREAK_CODE))
			{
				if (resultList[i])
				{
					clipboardText += resultList[noOfToken * 2 + i].RemoveExtraSpace();
				}
				
				charWrote += parseInt(resultList[noOfToken * 3 + i], 10);
				++i;
			}
			
			if (i != currentToken)
			{
				clipboardText += "\n";
			}
			charWrote = 0;
		}
		if (resultList[i].charCodeAt(0) == LINEBREAK_CODE)
		{
			++i;
		}
		currentToken = i;
	}

	CopyToClipboard(clipboardText);
}

function TextStateChanged()
{ 
	if (textXmlHttp.readyState == 4)
	{ 
		resultText = textXmlHttp.responseText.split("||")[0];
		resultText = resultText.substr(2);
		
		document.getElementById("trDescription").style.display = "none";
		document.getElementById("trDescription").style.visibility = "hidden";
		
		FormatResult(resultText, parseInt(document.getElementById("txtCharPerRow").value, 10));
		document.getElementById("trResult").style.display = "block";
		document.getElementById("trResult").style.visibility = "visible";
		HideDivLoading();
		document.getElementById("txtTranslateText").disabled = false;
		document.getElementById("txtTranslateText").focus();
		
		soundList = textXmlHttp.responseText.split("||")[1].split(",");
		readySearch = true;
	}
}

function HotTextStateChanged() 
{ 
	if (hotCharXmlHttp.readyState==4)
	{
		document.getElementById("tblHotCharSearch").innerHTML = hotCharXmlHttp.responseText;
	}
}

function RelatedWordStateChanged() 
{ 
	if (relatedWordXmlHttp.readyState==4)
	{
		document.getElementById("tblRelatedSearch").innerHTML = relatedWordXmlHttp.responseText;
	}
}

function TranslateText(translateText, toTranslate, e)
{
	if (!readySearch) return;
	
	if (!(e && e.ctrlKey && e.keyCode == 13 && translateText.length > 0 && translateText.length < maxChar))
	{
		if (translateText.length > maxChar)
		{
			document.getElementById("btnSearch").disabled = true;
			document.getElementById("txtTranslateText").style.color = "#FF0000";
			
			if (translateText.length > prevWordNum)
			{
				ShowSlideMessage(1, 8);
			}
			
			prevWordNum = translateText.length;
			return true;
		}
		else if (prevWordNum > maxChar)
		{
			document.getElementById("btnSearch").disabled = false;
			document.getElementById("txtTranslateText").style.color = "#000000"; 
		}
		
		prevWordNum = translateText.length;
		if (!(toTranslate || (document.getElementById("chkInstantTranslate").checked && (translateText != prevText)) ))
		{
			return true;
		}
		
		if (translateText.length == 0)
		{
			prevText = "";
			document.getElementById("lblResult").innerHTML = ""; 
			return true;
		}
	}
	
	prevText = translateText;
	
	textXmlHttp = GetXmlHttpObject();
	
	if (textXmlHttp == null)
	{
	  alert (errAjax);
	  return true;
	} 
	
	Flash_FinishPlay();
	FlashStopPlay();
	
	var url = "../agent/translateagent.php";
	var postContent = "translateText=" + translateText.Trim().NormalizeInput();
	postContent += "&cantonToPTH=" + (document.getElementById("chkCantonPTH").checked ? "1" : "0");
	postContent += "&useRelatedWord=1";
	postContent += "&showBig5=" + (document.getElementById("chkShowBig5").checked ? "1" : "0");
	postContent += "&showGB=" + (document.getElementById("chkShowGB").checked ? "1" : "0");
	textXmlHttp.onreadystatechange = TextStateChanged;
	textXmlHttp.open("POST", url, true);
	textXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	textXmlHttp.send(postContent);

	ShowDivLoading(420);
	readySearch = false;
	newSearch = true;
	return true;
	
}

function SearchRelatedWord(translateText)
{
	relatedWordXmlHttp = GetXmlHttpObject();

	var url = "../agent/searchwordagent.php";
	var postContent = "searchRelatedChar=true&relatedChar=" + translateText;
	relatedWordXmlHttp.onreadystatechange = RelatedWordStateChanged;
	relatedWordXmlHttp.open("POST", url, true);
	relatedWordXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	relatedWordXmlHttp.send(postContent);
}

function SearchHotChar()
{
	hotCharXmlHttp = GetXmlHttpObject();
	
	var url = "../agent/searchcharagent.php";
	var postContent = "SearchHotCharURL=true";
	hotCharXmlHttp.onreadystatechange = HotTextStateChanged;
	hotCharXmlHttp.open("POST", url, true);
	hotCharXmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	hotCharXmlHttp.send(postContent);
}

function CheckBackspace(e)
{
	return !(e.keyCode == 8 && document.getElementById('txtTranslateText').disabled);
}

function DisplayOption(e)
{
	if (!e) var e = window.event;
	
	var optionDiv = document.getElementById("divOption");

	optionDiv.style.top = (e.clientY + document.body.scrollTop - parseInt(optionDiv.style.height, 10) / 2) + "px";
	optionDiv.style.left = (e.clientX + document.body.scrollLeft + 20) + "px";
	
	optionDiv.style.display = "block";
	optionDiv.style.visibility = "visible";
}

function CloseOption(copyText)
{
	document.getElementById("divOption").style.display = "none";
	document.getElementById("divOption").style.visibility = "hidden";
	
	if (copyText)
	{
		CopyResult();
	}
}

function SetTableWidth(resultList, startPos, rowLength)
{
	var haveBR = false;
	for (var i = startPos; i < startPos + rowLength; ++i)
	{
		if (resultList[i].charCodeAt(0) == LINEBREAK_CODE)
		{
			haveBR = true;
		}
	}
	
	return haveBR ? "" : "100%";
}

function BuildSoundList()
{
	return soundList.join(",");
}

function ChangePinYin(i, pinyinIndex)
{
	document.getElementById("pinyin_"+i).innerHTML = otherPinYinList[i].split(",")[pinyinIndex];
	pinyinList[i] = otherPinYinList[i].split(",")[pinyinIndex];
	var newSimplePinYin = otherSimplePinYinList[i].split(",")[pinyinIndex];
	soundList[i] = newSimplePinYin;
	if (i > 0)
	{
		if (charList[i-1] == "一")
		{
			if (newSimplePinYin.indexOf("4") > 0)
			{
				soundList[i-1] = "yi2";
			}
			else
			{
				soundList[i-1] = "yi4";
			}
		}
		else if (charList[i-1] == "不")
		{
			if (newSimplePinYin.indexOf("4") > 0)
			{
				soundList[i-1] = "bu2";
			}
			else
			{
				soundList[i-1] = "bu4";
			}
		}
		else if (isLastThirdSound(pinyinList[i-1]) && newSimplePinYin.indexOf("3") == -1)
		{
			var prevSound = soundList[i-1].split("-");
			prevSound[prevSound.length-1] = prevSound[prevSound.length-1].replace("2", "3");
			soundList[i-1] = prevSound.join("-");
		}
		else if (newSimplePinYin.indexOf("3") > 0)
		{
			var prevSound = soundList[i-1].split("-");
			prevSound[prevSound.length-1] = prevSound[prevSound.length-1].replace("3", "2");
			soundList[i-1] = prevSound.join("-");
		}
	}
}

function StopPlay()
{
	FlashStopPlay();
	if (document.getElementById("tdPinYin_"+prevPronounceWord))
	{
		document.getElementById("tdPinYin_"+prevPronounceWord).className = prevPronounceWordClass;
	}
	prevPronounceWord = -1;
}

function PlaySound()
{
	if (playingSound)
	{
		Flash_FinishPlay();
		FlashStopPlay();
	}
	else
	{
		document.getElementById("imgSpeaker").src = "../images/speaker_stop.gif";
		document.getElementById("imgSpeaker").alt = "停止發音";
		if (document.getElementById("tdPinYin_"+prevPronounceWord))
		{
			document.getElementById("tdPinYin_"+prevPronounceWord).className = prevPronounceWordClass;
		}
		prevPronounceWord = -1;
		prevPronounceWordClass = "translateDict_char";
		FlashPlaySound(BuildSoundList(), true);
		playingSound = true;
	}
}

function Flash_GetCurrentWord(wordNo)
{
	if (prevPronounceWord != wordNo)
	{
		if (document.getElementById("tdPinYin_"+prevPronounceWord))
		{
			document.getElementById("tdPinYin_"+prevPronounceWord).className = prevPronounceWordClass;
		}
		
		prevPronounceWord = wordNo;
		prevPronounceWordClass = document.getElementById("tdPinYin_"+wordNo).className;
		
		document.getElementById("tdPinYin_"+wordNo).className = "translateDict_pronounce";
	}
}

function Flash_FinishPlay()
{
	playingSound = false;
	if (document.getElementById("tdPinYin_"+prevPronounceWord))
	{
		document.getElementById("tdPinYin_"+prevPronounceWord).className = prevPronounceWordClass;
	}
	
	document.getElementById("imgSpeaker").src = "../images/speaker.gif";
	document.getElementById("imgSpeaker").alt = "發音";
	prevPronounceWord = -1;
}

function isLastThirdSound(fullPinYin)
{
	var fullPinYinList = fullPinYin.split(" ");
	var lastPinYin = fullPinYinList[fullPinYinList.length-1];
	var containThirdSound = false;
	for (var i = 0; i < thirdSound.length; ++i)
	{
		if (lastPinYin.indexOf(thirdSound[i]) > 0)
		{
			containThirdSound = true;
		}
	}
	
	return containThirdSound
}

function GetOtherPinYinDiv(num)
{
	var returnOtherPinYinDiv = "";
	if (otherPinYinList[num] != "-")
	{
		var divOtherPinYin = document.getElementById("divOtherPinYin");
		pyList = otherPinYinList[num].split(",");
		spyList = otherSimplePinYinList[num].split(",");
		pyeList = otherPinYinExampleList[num].split(",");
		
		divOtherPinYin.innerHTML = otherSimplePinYinList[num] + "<br>";
		returnOtherPinYinDiv = '<div id="divOtherPinYin_'+num+'" class="translateDict_otherPinYinList" style="z-index:'+(maxChar-num)+'">其他拼音：<br>';
		for (var i = 0; i < pyList.length; ++i)
		{
			returnOtherPinYinDiv += (i == 0) ? "" : "<br>";
			returnOtherPinYinDiv += '<a href="#" class="translateDict_otherPinYinItem" onclick="ChangePinYin('+num+', '+i+');return false">' + pyList[i];
			returnOtherPinYinDiv += pyeList[i] ? ' (' + pyeList[i] + ')' : '';
			returnOtherPinYinDiv += '</a>';
		}
		returnOtherPinYinDiv += '</div>';
	}
	
	return returnOtherPinYinDiv
}