google.load("language", "1");

/**
 * 取得Flash元件
 */
function getSwfApp(appName)
{
	return (navigator.appName.indexOf("Microsoft") !=-1) ? window[appName] : document[appName];
}

/**
 * 透過Flash發音
 */
function Ypronounce(s)
{
	var swf = getSwfApp("loadSound");
	swf.playSound(s);
}

/**
 * 功能：取得Yahoo!字典發音(Ajax)
 */
function doYpronounce(URL, param)
{
	$.post(URL, { input: escape(param)},
		function(data){
			var body = data.replace(/\r\n/g, '');
			
			if(isSpaceSeg == false) //for 中文發音
				body = body.substr(1);

			Ypronounce(body);
		}
	);
}

/**
 * Yahoo!搜尋
 */
function doYBOSS(URL, param ,_id)
{
	$.getJSON("http://boss.yahooapis.com/ysearch/web/v1/"+escape(param)+"?appid=TSB9517V34GB6xVMuvkDdWqE.vq2k0qLkO3pkXXAdMWgVjVxDO1fLB1t3qMHWxHqmnWZA57M&format=json&callback=?",
		function(data){
			var result_html = "";
			for ( _x in data.ysearchresponse.resultset_web)
			{
				x = data.ysearchresponse.resultset_web[_x];
				result_html += '<a href="' + x.clickurl + '" target="_blank">' + x.title + '</a><p>' + x.abstract + '</p>';
			}
			result_html = result_html.replace(/<b>\.\.\.<\/b>/g,'...');
			$('#'+_id).html(result_html);
	});
}

var dict = new Array();
var stem = new Array();
/**
 * 匯出字卡
 */
function exportAllWord()
{
	var content = "";

	//sort by alphabetical
	var keys = new Array();
	for(k in dict)
		keys.push(k);
	
	keys.sort( function (a, b){return (a > b) - (a < b);} );
	var len = keys.length;

	for (var i = 0; i < len; i++)
		content += "<div class='ytrans'><div class='transtitle'>TransNote</div><div class='word'>"+keys[i]+"</div><div class='transword'>"+dict[keys[i]]+"</div></div>";
		
	
	$('#input').val(content);
	var form = document.forms["transnote"];
	form.action = "./export/word";
	form.submit();
}

/**
 * 顯示對應的字詞翻譯
 */
function focusDict(s,m)
{
	//alert(focusDict.caller);
	var _stem = stem[s];
	var _s;
	if(_stem != undefined)
	{
		$('#yinput').val(_stem);
		$('#'+__ID).html("<div id='@"+_stem+"' class='yexplain'><div>"+dict[_stem]+"</div></div>");
		_s = _stem;
	}else{
		$('#yinput').val(s);
		if(String(dict[s]) != 'undefined')
		{
			$('#'+__ID).html("<div id='@"+s+"' class='yexplain'><div>"+dict[s]+"</div></div>");
		}
		else
		{
			__PARAM = s;
			$.getScript("http://tw.dictionary.yahoo.com/suggest_data.php?of=js&p="+s,null);
		}	
		_s = s;
	}	

	if(isYpron)
	{
		if(isSpaceSeg)
			doYpronounce("./yahoo/pronounce",_s);
		
	}
	focusUnderline(m);
}

/**
 * 
 */
function unfocusDict(m)
{
	unfocusUnderline(m);
}

/**
 * 顯示underline
 */
function focusUnderline(m)
{
	m.style.textDecoration = 'underline';
}

var __URL = "./yahoo/dictionary";
var __PARAM;
var __ID = "transcontent";
var ENTER = 13;

/**
 * 檢查是否有此單字存在(透過Yahoo! Dictionary Suggest)
 */
function doYahooDict(URL, param ,_id)
{
	__PARAM = param;
	__URL = URL;
	__ID = _id;
	$.getScript("http://tw.dictionary.yahoo.com/suggest_data.php?of=js&p="+param,null);
}

/**
 * 取得Yahoo!字典翻譯(Ajax)
 */
function doTrans()
{
	var word = $('#yinput').val();
        var re = /[a-zA-Z-']+/gi;
        word = word.match(re);
        if(word != null)
        {
		$('#'+__ID).html("<div align='center'><img src='./images/trans-loading.gif'/></div>");
                $.post(__URL, { input: word},
                function(data){
                	var body = data.replace(/\r\n/g, '');
			body = $.trim(body);
                        if(body == "")
				body =  "查無此單字";

                        dict[word] = body;
                        $('#'+__ID).html("<div id='@"+word+"' class='yexplain'><div>"+body+"</div></div>");
                });
	}

}

/**
 * Yahoo!字典翻譯(Button)
 */
function doYahooTrans(e)
{
	var key = e.keyCode;
	if (key == ENTER) 
	{
		doTrans();
	}
	return false;
}

/**
 * Yahoo! Dictionary Suggest Callback Function
 */
function fxsearch(sugglist)
{
	var scount = sugglist[1].length;
	var term = sugglist[0];
	
	if(scount > 0)
	{
		$('#yinput').val(term);
		$.post(__URL, { input: term},
			function(data){
				var body = data.replace(/\r\n/g, '');
				dict[term] = body;
				$('#'+__ID).html("<div id='@"+term+"' class='yexplain'><div>"+body+"</div></div>");
			}
		);
	}else{
		var w = stemWord(term);

		//delete non-alphabet characters
		w = w.replace(/[^a-z-']/gi, "");

		$('#yinput').val(w);
		if(w != term)
		{
			stem[term] = w;
			$.post(__URL, { input: w},
				function(data){
					var body = data.replace(/\r\n/g, '');
					body = $.trim(body);
					if(body == "")
						body = "查無此單字";
					
					dict[w] = body;

					$('#'+__ID).html("<div id='@"+w+"' class='yexplain'><div>"+body+"</div></div>");
				}
			);
		}else{
			var body = "查無此單字";
			dict[w] = body;
			$('#'+__ID).html("<div id='@"+w+"' class='yexplain'><div>"+body+"</div></div>");
		}
	}
}

/**
 * 判斷是否啟用Yahoo發音
 */
function enabledYpron()
{
	var a = $("#Ypron");
	if(isYpron)
	{
		isYpron = false;
		//a.attr('checked',false);
		a.removeClass('btnPress');
	}
	else
	{
		isYpron = true;
		//a.attr('checked',true);
		 a.addClass('btnPress');
	}
}

/**
 * 判斷是否啟用同詞翻譯
 */
function enabledAllTrans()
{
	var a = $('#allTrans');
        if(isAllTrans)
        {
		isAllTrans = false;
    		//a.attr('checked',false);
			a.removeClass('btnPress');
  	}
        else
        {
                isAllTrans = true;
                //a.attr('checked',true);
                a.addClass('btnPress');
        }
}

var _z = 122;
var _s = 115;
var _ROLLBACK = "";

/**
 * 功能：熱鍵處理
 */
function handleKeyPress(evt)
{
	var key = (window.event)?event.keyCode:evt.which;
	var ctrl = evt.ctrlKey;
	if(isReading)
	{
		//啟用復原功能
		if(ctrl && key == _z)
		{
			$('#transloading').html('回復中...');
			$('#hcontent').css('display','none');
			setTimeout("revert()",100);
			return false;
		}
		//啟用文章儲存
		if(ctrl && key == _s)
		{
			boxOpen('save');
			//$("a[rel='save']").click();
			return false;
		}
		//啟用同詞翻譯
		if(key == 96)
		{
			enabledAllTrans();
			return false;
		}
	}
}
/**
 * 功能：回復上一個操作
 */
function revert()
{
	$('#hcontent').html(_ROLLBACK);
	//$(".rt").colorbox({width:"50%", inline:true, href:"#modify", title:"TransNote"});
	startTag = -1;
	$('#rb'+startTag_rev).css('textDecoration','none');
	$('#transloading').html('');
	$('#hcontent').css('display','inline');
}
//========================================================================================================= 2008.07.01
var isSpaceSeg = true; //非CJK語系以空格斷詞
var isAllTrans = false; //是否啟用同詞翻譯
var isYpron = false; //是否啟用Yahoo發音
var previewText = ""; //儲存原文
var startTag = -1; //和endTag並用於click翻譯
var startTag_rev = -1; //
var endTag = -1; //和startTag並用於click翻譯
var sl = "en";
var tl = "zh-TW";
var _curr = 0;
var splitCount = 1;
var _readyTransTag = null;
var _parentColor = '#ffffff';
var _hasNext = false;
var maxID = -1;
var isReading = false;

function preViewNew()
{
	if(isReading == false)
	{
		var item = $('#content');
		if(item.val() == "")
		{
			item.focus();
			alert("Please enter some text.");
			return;
		}
		item.css('display','none');
		$('#transloading').html('Loading...');
	}
	setTimeout("preViewNew2()",100);
}
function preViewNew2()
{
	if(isReading == false)
	{
		isReading = true;
		var item = $('#content');
		
		var src = item.val();
		previewText = src;
		
		/*
		var _ex = $("#exfile");	
		_ex.attr('disabled', false);
		_ex.addClass('fon');
		
		var _br = $("#brfile");	
		_br.attr('disabled', false);
		_br.addClass('fon');
		*/
		$('#exfile').css('display','inline');
		$('#brfile').css('display','inline');
		$('#savefile').css('display','inline');
		
		//$('#preview').val("編輯原文");
		$('#preview').attr('title', '原文');
		$('#preview').html('原文');

	        //$("#sound").css('display','inline');
	        $("#toolkit").css('display','inline');

//		src = src.replace(/<|>|;/g, "");

		if(isSpaceSeg)
		{
			//src = src.replace(/\-\n/g, "");
			src = src.replace(/\n/g, " <br/> ");
			var s = src.split(" ");	
			src = "";
			var len = s.length;
			maxID = len;
			for(var i = 0 ; i < len ; i++)
			{
				if(s[i] == "<br/>")
					src += "<br pos=\""+i+"\"/>";
				else
					src += "<span class='ruby' id=ry"+i+"><span class='rb' id=rb"+i+" onMouseOver=\"focusUnderline(this)\" onMouseOut=\"unfocusUnderline(this)\" onClick=\"doPhraseTranslate(this,'"+i+"')\">"+s[i]+" </span><span class='rt' id=s"+i+" onClick=\"editWord('"+i+"')\"></span></span>";
			}
		}else{
			var s = src.split("");
			src = "";
			var len = s.length;
			maxID = len;
			for(var i = 0 ; i < len ; i++)
			{
				if(s[i] == "\n")
					src += "<br pos=\""+i+"\"/>";
				else
					src += "<span class='ruby' id=ry"+i+"><span class='rb' id=rb"+i+" onMouseOver=\"focusUnderline(this)\" onMouseOut=\"unfocusUnderline(this)\" onClick=\"doPhraseTranslate(this,'"+i+"')\">"+s[i]+"</span><span class='rt' id=s"+i+" onClick=\"editWord('"+i+"')\"></span></span>";
			}
		}
		
		var _h = $('#hcontent');
		_h.html(src);
		_h.css('display','inline');
		/*$(".rt").colorbox({width:"50%", inline:true, href:"#modify", title:"TransNote"});*/
		$('#transloading').html('');
	}else{
		var answer = confirm("您確定要回「編輯畫面」？\n請注意：翻譯格式將會遺失!!");
		
		if($('#frameBottom').css('display') === 'block')
		{
			$('#frameBottom').css('display','none');
			$('#btnYboss').removeClass('btnPress');
		}
		
		if(!answer)
			return;

		$("#hcontent").css('display','none');
		
		//$('#preview').val("開始閱讀");
		$('#preview').attr('title', '閱讀');
		$('#preview').html('閱讀');

		/*
		var _ex = $("#exfile");	
		_ex.attr('disabled', true);
		_ex.addClass('foff');

		var _br = $("#brfile");	
		_br.attr('disabled', true);
		_br.addClass('foff');
		*/
		$('#exfile').css('display','none');
		$('#brfile').css('display','none');
		$('#savefile').css('display','none');
		$('#twit').css('display','none');

		//$("#sound").css('display','none');
		$("#toolkit").css('display','none');
	
		var c = $("#content");
		c.css('display','inline');
		c.val(previewText);
		
		isReading = false;
		previewText = "";
		startTag = -1;
		endTag = -1;
		_curr = 0;
		splitCount = 1;
		_readyTransTag = null;
		_hasNext = false;
		maxID = -1;
		
	}
}

/**
 * 編輯Google翻譯文字
 */
function editWord(_id)
{
	boxOpen('modify',function(){$('#destarea').focus();});
	
	var rb = $('#rb'+_id);
	var s = $('#s'+_id);
	$('#src').html(rb.html());
	$('#destarea').val(s.html());
	$('#sid').val(_id);
	
}

/**
 * 關閉underline
 */
function unfocusUnderline(s)
{
	s.style.textDecoration = 'none';
}

var c_COMBINE = '#FFDFF8'; //
var c_WORD = '#FFFF88';
//var c_WORD = '#FFCAA6';
//var c_SPACE = '#CDCBBE';
var c_SPACE = '';
var c_PHRASE = '#FFFF88';
//var c_PHRASE = '#C2DDEA';

/**
 * TransNote核心介面設計
 * 組合單字或片語的功能, 並交由Google翻譯。
 */ 
function doPhraseTranslate(s,myid)
{
	myid = parseInt(myid);
	if(startTag == -1)
	{
		_ROLLBACK = $('#hcontent').html();
		startTag = myid;
		startTag_rev = myid;
		_parentColor = s.style.backgroundColor;
		s.style.backgroundColor = c_COMBINE;
		_readyTransTag = s;
	}
	else
	{
		var sid = startTag;
		startTag = Math.min(sid,myid);
		endTag = Math.max(sid,myid);
		if(startTag == endTag)
		{
			//檢查此單字是否已有翻譯字串
			if($('#s'+myid).html() == "")
			{
				var phraseText = $('#rb'+myid).text();
				doGoogleTranslation(phraseText,$("#s"+myid),false);
				doYBOSS("./yahoo/boss",phraseText,"yboss_content");
				
				if(isSpaceSeg)
				{
					var re = /[a-zA-Z-']+/gi;
					phraseText = phraseText.match(re); //過濾英文字
					if(phraseText != null)
					{
						if(sl == "en")
							doYahooDict("./yahoo/dictionary",phraseText,"transcontent");
					}						
				}
				if(phraseText != null && isYpron == true)
				{
					if(isSpaceSeg)
						doYpronounce("./yahoo/pronounce",phraseText);
					
				}
				
				s.onmouseover = new Function("focusDict(\""+phraseText+"\",this)");
				s.onmouseout = new Function("unfocusDict(this)");
				
				s.style.backgroundColor = c_WORD;
			}else{
				var targetNode = null;
				var rbmyid = document.getElementById("rb"+myid);
				rbmyid.onmouserover = new Function("focusUnderline(this)");
				rbmyid.onmouseout = new Function("unfocusUnderline(this)");
				var IDcounter = myid+1;
				//alert(IDcounter+" "+maxID);
				while(targetNode == null)
				{
					if(IDcounter < maxID)
						targetNode = document.getElementById("ry"+(IDcounter++));
					else
						break;
				}

				if(targetNode != null && targetNode.style.display == "none")
				{
					var content = document.getElementById("hcontent");
					var len = content.childNodes.length;
					var nodes = content.childNodes;
					nodes[startTag].firstChild.style.backgroundColor = c_SPACE;

					var rb = nodes[startTag].childNodes[0];
					rb = $(rb);
					var rt = nodes[startTag].childNodes[1];
					rt = $(rt)
					rt.text("");
					var src = rb.text();

					if(isSpaceSeg)
					{
						var s = src.split(" ");
						rb.text(s[0]+" ");
						var slen = s.length-1;
					}else{
						var s = src.split("");
						rb.text(s[0]);
						var slen = s.length;
					}
						
					var idx = 1;
					for(var i = myid+1; i < maxID ;i++)
					{
						var _tag = document.getElementById("ry"+i);
						if(_tag != null && _tag.nodeName == "SPAN" && _tag.style.display == "none")
						{
							_tag.style.display = "";
						
							var _rb = $('#rb'+i);
						
							if(isSpaceSeg)
								_rb.html(s[idx++]+" ");
							else
								_rb.html(s[idx++]);
						
							_rb.css('background-color',c_SPACE);
						}	
						if(idx == slen)
							break;
					}

				}else{
					$('#s'+myid).html('');
					s.style.backgroundColor = c_SPACE;
				}
			}
		}else{
			var content = document.getElementById("hcontent");
			var nodes = content.childNodes;
			nodes[startTag].firstChild.style.backgroundColor = c_PHRASE;
			
			var rb = nodes[startTag].childNodes[0];
			orb = rb;
			rb = $(rb);
			var rt = nodes[startTag].childNodes[1];
			rt = $(rt);
			var rb_str = "";
			var _i = 0;
			var _nodes = new Array();

			for(var i = startTag+1 ; i <= endTag ; i++)
			{
				if(nodes[i].nodeName == "BR" || nodes[i].style.display == "none")
				{
					continue;					
				}
				var _v = nodes[i].childNodes[0].innerHTML;

				if(_v == "")
					rb_str += " ";
				else	
					rb_str += _v;

				_nodes[_i++] = i;
			}
			
			var _body = rb.text() + rb_str;
			var count = 0;
			
			if(isSpaceSeg)
				count = _body.split(" ").length;
			else
				count = _body.split("").length;
		
			if(count > 220)
			{
				alert('您要翻譯的字元過多!');
				startTag = -1;
				endTag = -1;
				_readyTransTag.style.backgroundColor = _parentColor;
				return;
			}

			orb.onmouseover = new Function("focusUnderline(this)");
			orb.onmouseout = new Function("unfocusUnderline(this)");
			rb.text(_body);

			for(var _j = 0 ; _j < _i ; _j++)
			{
				nodes[_nodes[_j]].childNodes[1].innerHTML = "";
				nodes[_nodes[_j]].style.display = "none";
			}
			
			
			
			if(sl == "zh-TW")
				doYahooDict("./yahoo/dictionaryTW",_body,"transcontent");
					
			doGoogleTranslation(_body,rt,true);
			doYBOSS("./yahoo/boss",_body,"yboss_content");
		}

		startTag = -1;
		endTag = -1;
		_readyTransTag = null;
	}
}

/**
 * 同詞翻譯
 * ==========================
 * _text : 詞
 * tr_txt : 翻譯後的文字
 * sl : 來源語系
 * isPhrase : 是否為片語
 */
function doAllTrans(_text,tr_txt,sl,isPhrase)
{
	var content = document.getElementById("hcontent");
	var len = content.childNodes.length;
	var nodes = content.childNodes;

	/*
	if(isSpaceSeg)
		_text = _text.replace(/ /g, " ");
	*/
	
	if(isPhrase)
	{
		if(isSpaceSeg)
		{
			var s = _text.split(" ");
			var slen = s.length-1;
		}else{
			var s = _text.split("");
			var slen = s.length;
		}
		
		var correct = 0;
		
		for(var i = 0 ; i < len ; i++)
		{
			var mynode = nodes[i];

			if(mynode.nodeName == "SPAN" && mynode.style.display != "none")
			{
				for(var j = 0 ; j < slen ; j++)
				{
					if(nodes[i+j].nodeName == "SPAN" && nodes[i+j].style.display != "none")
					{
						if(isSpaceSeg)
							var mm = s[j]+" ";
						else
							var mm = s[j];

						if(mm == nodes[i+j].childNodes[0].innerHTML)
						{
							correct++;
						}
					}
				}

				if(correct == slen)
				{
					mynode.childNodes[1].innerHTML = tr_txt;
					mynode.childNodes[0].style.backgroundColor = c_PHRASE;
					mynode.childNodes[0].innerHTML = _text;

					for(var j = 1 ; j < slen ; j++)
					{
						nodes[i+j].childNodes[1].innerHTML = "";
						nodes[i+j].style.display = "none";
					}
				}
				correct = 0;
				i+=correct;
				
			}
		}
			
	}else{
		for(var i = 0 ; i < len ; i++)
		{
			var mynode = nodes[i];
			if(mynode.nodeName == "SPAN" && mynode.style.display != "none" && mynode.childNodes[0].innerHTML == _text)
			{
				mynode.childNodes[1].innerHTML = tr_txt;
				var s = mynode.childNodes[0];
				s.style.backgroundColor = c_WORD;
				s.onmouseover = new Function("focusDict(\""+_text+"\",this)");
				s.onmouseout = new Function("unfocusDict(this)");
			}
		}
	}	
}

/**
 * Google翻譯
 */
function doGoogleTranslation(_text,rt,isPhrase)
{
	google.language.translate(_text, sl, tl, function(result)
	{
		if (!result.error)
		{
			rt.text(result.translation);
			if(isAllTrans)
				doAllTrans(_text,rt.text(),sl,isPhrase);
  		}
	});	
}


var YCONTENT = "<div id='yinputbar' class='ytrans'><input id='yinput' type='text' onkeyup='doYahooTrans(event)' value=''><input type='button' onClick='doTrans()' value='翻譯'></div><hr/><div id='transcontent'>&nbsp;</div>";

function checkSpaceSegSL(s)
{
	if(s != "en")
	{
		$('#ycontent').html("目前僅支援英文辭典。");
	}else{
		$('#ycontent').html(YCONTENT);
	}
	$('#sl').val(s);

	$('#slimg').attr("src","flags/"+s+".png");	
	
	sl = s;
	if(sl == "en" || sl == "es" || sl == "fr" || sl == "da" || sl == "hi" || sl == "hr" || sl == "el" || sl == "pl" || sl == "fi" || sl == "ar" || sl == "bg" || sl == "ru" || sl == "no" || sl == "cs" || sl == "nl" || sl == "sv" || sl == "it" || sl == "pt" || sl == "de" || sl == "ro")
		isSpaceSeg = true;
	else
		isSpaceSeg = false;
	
	//$(".srclanguage").colorbox.close();
	boxClose();
}
function checkSpaceSegTL(s)
{
	$('#tl').val(s);
	$('#tlimg').attr("src","flags/"+s+".png");	

	tl = s;
	if(sl == "en" || sl == "es" || sl == "fr" || sl == "da" || sl == "hi" || sl == "hr" || sl == "el" || sl == "pl" || sl == "fi" || sl == "ar" || sl == "bg" || sl == "ru" || sl == "no" || sl == "cs" || sl == "nl" || sl == "sv" || sl == "it" || sl == "pt" || sl == "de" || sl == "ro")
		isSpaceSeg = true;
	else
		isSpaceSeg = false;
	
	//$(".destlanguage").colorbox.close();
	boxClose();
}

/**
 * 匯出全文
 */
function exportAllDoc()
{
	$('#maxid').val(maxID);
	$('#isSpaceSeg').val(isSpaceSeg);
	$('#input').val($('#hcontent').html());
	
	var form=document.forms["transnote"];
	form.action = "./export/doc";
	form.submit();
}

/**
 * 功能：匯出XML格式
 * 參數：_t : 標題 , _u：URL
 */
function exportXML(_t,_u)
{
	var content = "";
	var _xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	_xml += "<transnote title=\""+_t+"\" uri=\""+_u+"\">";
	_xml += "<page rbs=\""+maxID+"\">";
	
	var hc = document.getElementById("hcontent");
		
	if(hc.innerHTML.length < 1)
		return "";
			
			
	var len = hc.childNodes.length;
	for(var j = 0 ; j < len ; j++)
	{
		var subnode = hc.childNodes[j];
		if(subnode.nodeName == "BR")
		{
			_xml += "<br pos=\""+j+"\"/>";
			
		}else{
			var rb = $(subnode.childNodes[0]);
			var rt = $(subnode.childNodes[1]);
			
			_xml += "<ruby id=\""+j+"\" display=\"";
			//_xml += (subnode.style.display == "none") ? "0\">" : "1\">";
			if(subnode.style.display == "none")
			{
				//隱藏模式
				_xml += "0\">";
			}else if(rt.text() == "")
			{
				//正常模式
				_xml += "1\">";
			}else if(rb.text().split(" ").length == 2)
			{
				//單詞模式
				_xml += "2\">";
			}else{
				//片語模式
				_xml += "3\">";
			}
			
			_xml += "<rb>"+rb.text()+"</rb>";
			_xml += "<rt>"+rt.text()+" </rt>";
			_xml += "</ruby>";
		}
	}
	_xml += "</page>";
	_xml += "</transnote>";
	return _xml
}

/**
 * 儲存手動編輯Google翻譯的文字
 */
function saveChange()
{
	var sid = $('#sid').val();
	$('#s'+sid).html($('#destarea').val());
	//$(".rt").colorbox.close();
	boxClose();
}
function saveChangeKeyUp(evt)
{
	var key = (window.event)?event.keyCode:evt.which;
	var ctrl = evt.ctrlKey;
	if(key == ENTER && ctrl)
	{
		saveChange();
	}
}
function tryit(){
	var txt = "Click「開始閱讀」to start: \n-------------------------------------------------\nThe Tower of Babel\n\nNow the whole world had one language and a common speech. As men moved eastward, they found a plain in Shinar and settled there.\n\nThey said to each other, \"Come, let\'s make bricks and bake them thoroughly.\" They used brick instead of stone, and tar for mortar. Then they said, \"Come, let us build ourselves a city, with a tower that reaches to the heavens, so that we may make a name for ourselves and not be scattered over the face of the whole earth.\"\n\nBut the LORD came down to see the city and the tower that the men were building. The LORD said, \"If as one people speaking the same language they have begun to do this, then nothing they plan to do will be impossible for them. Come, let us go down and confuse their language so they will not understand each other.\"\n\nSo the LORD scattered them from there over all the earth, and they stopped building the city. That is why it was called Babel —because there the LORD confused the language of the whole world. From there the LORD scattered them over the face of the whole earth. (From the Bible Genesis 11:1)";
	$('#content').val(txt);
}

/**
 * 帳號註冊
 */
function register()
{
	var _a = $('#_account').val();
	var _pd = $('#_password').val();
	var _cpd = $('#_cpassword').val();
	
	$.ajax({
			type: "POST",
			url: "./user/register",
			dataType: "json",
			data: "account="+_a+"&password="+_pd+"&cpassword="+_cpd,
			success: function(msg){
				var status = msg.Status;
				var user = msg.User;
				if(status == "1")
				{
					alert('註冊成功');
					$('#nonLogin').hide();
					$('#Logined').show();
					$('#logout').html("登出("+user+")");
					
					//$("a[rel='register']").colorbox.close();
					regCallback();
					boxClose();
					
					$('#_account').val("");
					$('#_password').val("");
					$('#_cpassword').val("");
				}else if(status == "-2"){
					alert('註冊失敗');
				}
			}
	});	
	return false;
}

/**
 * 帳號登入
 */
function login()
{
	
	var _a = $('#account').val();
	var _pd = $('#passwd').val();
	
	$.ajax({
			type: "POST",
			url: "./user/login",
			dataType: "json",
			data: "account="+_a+"&password="+_pd,
			success: function(msg){
				var status = msg.Status;
				var user = msg.User;
				if(status == "1")
				{
					//alert('登入成功');
					$('#nonLogin').hide();
					$('#Logined').show();
					$('#logout').html("登出("+user+")");
					
					loginCallback();
					boxClose();
					
					$('#account').val("");
					$('#passwd').val("");
				}else{
					alert('登入失敗');
				}
			}
	});	
	return false;
}

/**
 * 檢查是否已登入
 */
function chklogin()
{
	$.ajax({
			type: "GET",
			url: "./user/chklogin",
			dataType: "json",
			success: function(msg){
				var status = msg.Status;
				if(status == "1")
				{
					if(isReading)
					{
						var c = confirm("您決定放棄目前閱讀頁面？");
						if(c)
							window.location.href = "./user/index";
						else
							return false;
					}
					window.location.href = "./user/index";
				}else{
					alert('請先登入!');
					$('#nonLogin').show();
					$('#Logined').hide();
				}
			}
	});
}

/**
 * 檢查帳號是否被註冊
 */
function chkaccount()
{
	var _a = $('#_account').val();
	if(_a == "")
		return;

	$.ajax({
			type: "POST",
			url: "./user/chkaccount",
			dataType: "json",
			data: "account="+_a,
			success: function(msg){
				var status = msg.Status;
				if(status == "1")
				{
					$('#chkaccount').html('此帳號可註冊');
				}else if(status == "-2"){
					$('#chkaccount').html('');
					$('#_account').val('').focus();
					alert('此帳號已被使用');
				}
			}
	});	

}

/**
 * 登出
 */
function doLogout()
{
	$.ajax({
			type: "GET",
			url: "./user/logout",
			dataType: "json",
			success: function(msg){
				var status = msg.Status;
				if(status == "1")
				{
					alert('登出成功');
					$('#nonLogin').show()
					$('#Logined').hide()
				}
			}
	});	
}

/**
 * 儲存文章
 */
function doSave()
{
	var _t = $('#sTitle').val();
	var _u = $('#sUrl').val();
	var _c = $('#sComment').val();
	var _a = $('#sTag').val();
	var _id = $('#sKey').val();
	
	var _b = exportXML(_t,_u);
	_b = encodeURIComponent(_b);

	if(_b.length  < 1)
	{
		alert("請輸入文章內容!");
		//$("a[rel='save']").colorbox.close();
		saveCallback();
		boxClose('save');
		return;
	}
	if(_t.length  < 1)
	{
		alert("請輸入文章標題!");
		$('#sTitle').focus();
		return;
	}

	$.ajax({
			type: "POST",
			url: "./user/save",
			dataType: "json",
			data: "title="+_t+"&url="+_u+"&comment="+_c+"&tag="+_a+"&body="+_b+"&id="+_id,
			success: function(msg){
				var status = msg.Status;
				if(status == "1")
				{
					alert('儲存成功');
					//$("a[rel='save']").colorbox.close();
					saveCallback();
					boxClose('save');
				}else if(status == "-1"){
					alert('請先登入');
					//$("a[rel='save']").colorbox.close();
					saveCallback();
					boxClose('save');
				}else if(status == "-2"){
					alert('請輸入文章標題!');
				}else if(status == "-3"){
					alert('請輸入文章內容!');
				}
			}
	});	
}

/**
 * 取得文章XML
 */
function doTransNote(_id)
{
	$('#transloading').html('Loading...');
	$('#hcontent').css('display','none');
	$('#content').css('display','none');

	$.ajax({
			type: "POST",
			url: "./user/view",
			dataType: "xml",
			data: "id="+_id,
			success: function(msg){
				TransNotePraser(msg);
			}
	});	
}

var id_set = new Array();
var txt_set = new Array();

/**
 * 剖析文章XML格式，並轉換成TransNote
 */
function TransNotePraser(xmldoc)
{
	var index = 0;

	var title = parseInt($(xmldoc).children().attr("title"));
	var uri = parseInt($(xmldoc).children().attr("uri"));
	var _m = "";
	var _s = "";
	maxID = -1;

	var page = $(xmldoc).children().children();
	var rbs = page.attr("rbs");

	maxID = parseInt(rbs);	
			
	var plen = page.children().length;
	var mypage = page.children();

	for(var z = 0 ; z < plen ; z++)
	{
		if(mypage[z].nodeName == "ruby")
		{
			var ruby = mypage[z];
			
			var rubyid = ruby.getAttribute("id");
			var display = ruby.getAttribute("display");
			var rb = ruby.childNodes[0];
			var rt = ruby.childNodes[1];

			var rbv = (rb.firstChild == null) ? "" : rb.firstChild.nodeValue;		

			var _rbv = rbv.split(" ").length;
			rbv = rbv.replace(/ /g, " ");

			if(display == "0")
			{
				_m+="<span style=\"display: none;\" class=\"ruby\" id=\"ry"+rubyid+"\">";
				_m+="<span class=\"rb\" id=\"rb"+rubyid+"\" onclick=\"doPhraseTranslate(this,'"+rubyid+"')\" onmouseover=\"focusUnderline(this)\" onmouseout=\"unfocusUnderline(this)\">";
			}else if(display == "1")
			{
				_s += rbv;
				_m+="<span class=\"ruby\" id=\"ry"+rubyid+"\">";
				_m+="<span class=\"rb\" id=\"rb"+rubyid+"\" onclick=\"doPhraseTranslate(this,'"+rubyid+"')\" onmouseover=\"focusUnderline(this)\" onmouseout=\"unfocusUnderline(this)\">";
			}else if(display == "2")
			{
				_s += rbv;
				_m+="<span class=\"ruby\" id=\"ry"+rubyid+"\">";
				_m+="<span style=\"background-color: rgb(255, 255, 136);\" class=\"rb\" id=\"rb"+rubyid+"\" onclick=\"doPhraseTranslate(this,'"+rubyid+"')\" onmouseover='focusDict(\""+rbv+"\",this)' onmouseout='unfocusDict(this)'>";
			}else{
				//記錄片語資訊
				id_set[index] = rubyid;
				txt_set[index++] = rbv;

				_s += rbv;
				_m+="<span class=\"ruby\" id=\"ry"+rubyid+"\">";
				_m+="<span style=\"background-color: rgb(255, 255, 136);\" class=\"rb\" id=\"rb"+rubyid+"\" onclick=\"doPhraseTranslate(this,'"+rubyid+"')\" onmouseover=\"focusUnderline(this)\" onmouseout=\"unfocusUnderline(this)\">";
			}
			_m += rbv;
			_m += "</span>";
			_m += "<span class=\"rt\" id=\"s"+rubyid+"\" onclick=\"editWord('"+rubyid+"')\">";
			_m += (rt.firstChild == null) ? "" : rt.firstChild.nodeValue.replace(/ /g, "");
			_m += "</span>";
			_m += "</span>";
		}else{
			_s += "\n";
			_m += "<br pos=\""+mypage[z].getAttribute("pos")+"\">";
		}
	}
	previewText = _s;
	onImportShow(_m)
}

/**
 * 呈現TransNote編輯畫面
 */
function onImportShow(content)
{
		$('#preview').attr('title', '原文');
		$('#preview').html('原文');
		
		$("#dict").css('visibility','visible');		
		$("#content").css('display','none');

		$('#exfile').css('display','inline');
		$('#brfile').css('display','inline');
		$('#savefile').css('display','inline');
		
		$("#toolkit").css('display','inline');
		
		var _h = $("#hcontent");
		_h.html(content);
		_h.css('display','inline');

		//將片語資訊重寫入 for IE
		for(var i = 0 ; i < id_set.length ; i++)
			$('#rb'+id_set[i]).text(txt_set[i]);


		_ROLLBACK = content;
		isReading = true;

		$('#transloading').html('');
}
