
function JSLoad(url, container, type, defer, language, title)
   {
      // verify / attain container
      if(container == undefined || container == null) container = this;

      // setup container
      if(typeof container.write == "undefined")
         if(typeof container.document != "undefined")
            container = container.document;
         else throw "Invalid container. Unable to load [" + url + "]";

      // no type set
      if(type == undefined || type == null)
      {
         type = '';

         // no language so set default type
         if(language == undefined || language == null)
         {
            language = undefined;
            type = "text/javascript";
         }
      }

      // set default language
      if(language == undefined || language == null) language = "JavaScript";

      // set title
      if(title == undefined || title == null) title = '';

      // set defer
      if(defer == undefined) defer = false;

      // build the script object
      var script = container.createElement("script");
      script.defer = defer;
      script.language = language;
      script.title = title;
      script.type = type;
      script.charset = "UTF-8";//charset="UTF-8"
      script.src = url;

      // dynamically load the script via it's container
      var head = container.getElementsByTagName("head")[0];
      head.appendChild(script);
   }

String.prototype.trim=function(){ return this.replace(/(^\s*)|(\s*$)/g, "");　}
var config = {
	Paragraphs:{}
	,Paragraphslength:0
	,maxlength:384
	,transCursor:''
	,to_language:''
	,transCursor:0
	,translateresault:''
	,translatepage:0
	,isIE:null
	,slen:0
	,tlen:0
	,totalHeight:0
	,dicttrans:false
	,googletrans:false
	,isDoing:false
}
function checkLanguage (content)
{
	var rex; 
	/*
	rex = /^[\u3040-\u309F\u30A0-\u30FF]+$/; 
	if (rex.exec(content)) { 
		return "ja"; 
	} 
	*/
	//content = content.substring(0,20);
	//alert(content.lenght content.replace(/[^\x00-\xff]/g,"**").length);
	var reg = /[a-zA-Z]+/g;
	var enWord = content.match(reg);
	if(enWord)var enNum = enWord.length;
	else var enNum=0;
	

	reg = /[\u4e00-\u9fa5]/g;
	var zhcnWord = content.match(reg);	
	if(zhcnWord)var zhcnNum = zhcnWord.length;
	else var zhcnNum=0;
	if(zhcnNum==0) return 1;
	if(enNum==0) return -1;
	return 0;
	//alert(enNum);
	return zhcnNum==0?"en":"zh-CN";
	/*
	rex = /[\u4e00-\u9fa5]+/; 
		if (rex.exec(content)) { 
		return "zh-CN"; 
	} 
	*/
	/*
	rex = /^(\w)+$/; 
	if (rex.exec(content)) { 
		return "en"; 
	} 
	*/
	//return "en"; 
}
function translate()
{
	//alert('口语翻译测试结束，谢谢大家支持');
	//return;
	if(config.isDoing){
		alert('请等待正在翻译');
		return ;
	}
	initTranslate();
	config.Paragraphs = new Array();
	config.Paragraphslength =0;	
	var text = $("content").value.trim();
	if(text=="")
	{
		alert("翻译原文不能为空");
		return false;
	}
	if($('iV4fySelect').value == 'auto')
	{
		config.from_language=checkLanguage(text);
		//alert(config.from_language);
		config.to_language = config.from_language=="zh-CN"?"en":"zh-CN";
		//config.from_language ="";
	}
	else{
		config.from_language  = $('sl').value;
		config.to_language  = $('tl').value;	
	}
	//alert( text);
//	url = "http://219.232.254.45:8080/api/trans.pl?js=1&q="+encodeURIComponent(text);;
	url = "http://58.68.226.9:8080/api/trans.pl?js=1&q="+encodeURIComponent(text);;
	try{
		config.isDoing= true;
		JSLoad(url);
	}catch(e){
		config.isDoing= false;
	}
}

function icibaFyCallback(str){
	//alert(str);
	if(config.totalHeight<600)$("comparemain").style.height="600px";
	$("contentout").style.color = "#000";
	$("contentout").value= str;
	config.isDoing=false;
	gTf= str.trim() ==''?false:true;
	if(!gTf){
		$("contentout").style.color = "red";
		$("contentout").value= "译文过长....";
	}
	Statistics(getStrActualLen($("content").value),gTf,true);
}

function counting(){
	lang= checkLanguage(  $('content').value );
	$("sbLanguage").innerHTML= lang== 1?'英文':'非英文';
	var maxLength= lang== 1?60:15 ;
	shZhishu= maxLength - parseInt($('content').value.length);//"中文";
	if(shZhishu<0)shZhishu =0;
	$("zhishu").innerHTML = lang== 1?'您还可以输入<b>'+shZhishu+'</b>个字母':'您还可以输入<b>'+shZhishu+'</b>个字';//:'<font color="red">您已经超过输入'+(-shZhishu)+'字</font>';
	if(shZhishu<=0) $('content').value= $('content').value.substr(0,maxLength);
}

function initTranslate()
{
		document.getElementById('dictTrans').style.display="none";
		document.getElementById('dict').style.height="212px";
		document.getElementById('contentout').style.height="212px";
		document.getElementById('slab').style.display="block";
		document.getElementById('contentout').style.display="block";
		document.getElementById('dict').style.color="#BFBFBF";
		document.getElementById('contentout').style.color="#BFBFBF";
		document.getElementById('contentout').value="感谢您使用爱词霸翻译产品,翻译中,请稍候...";
		config.googletrans=false;
		config.dicttrans=false;

}
function Statistics(l,g,n)
{
	//return ;//
	var str=document.getElementById('content').value;
	var url='./writeLog.hit.php';
	var postStr='q='+getStrActualLen(str)+"&sl="+config.from_language+"&tl="+config.to_language+"&g="+g+"&n="+n+'&str='+encodeURIComponent(str);
	xmlhttp_request=InitAjax();//调用创建XMLHttpRequest的函数
	xmlhttp_request.open('POST', url, true);
	xmlhttp_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp_request.send(postStr);
}
function dictTranslate()
{
	var str=document.getElementById('content').value.trim();
	/*var url='./dict.ajax.php';
	var postStr='q='+str+"&sl="+config.from_language+"&tl="+config.to_language;
	xmlhttp_request=InitAjax();//调用创建XMLHttpRequest的函数
	xmlhttp_request.open('POST', url, true);
	xmlhttp_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp_request.send(postStr);
	xmlhttp_request.onreadystatechange = showDictTranslate;*/

	//var itf=document.getElementById('webDictInterfase');	
	//alert(itf.src);
	jsFile='http://netdictweb.iciba.com:8080/iciba_netdict.php?type=js&q='+encodeURIComponent(str);
	JSLoad(jsFile);
	
}
function showDictTranslate()
{
	if (xmlhttp_request.readyState == 4) 
	{
		// 收到完整的服务器响应
		if (xmlhttp_request.status == 200) 
		{
			if(xmlhttp_request.responseText!="")
			{
				config.dicttrans = true;
				document.getElementById('dictTrans').style.display="inline";
				document.getElementById('dict').style.height="138px";
				document.getElementById('contentout').style.height="50px";
				document.getElementById('dict').style.color="#000";
				document.getElementById('dict').value=xmlhttp_request.responseText;
			}
			else
			{;}
		}
	}
}
function IsUrl (str_url) 
{ 
	var strRegex = /^http:\/\/[\w\/\.-]+[\.]+([a-zA-Z]{2,6})+[a-zA-Z0-9\/\.\-\+\?\=\_%\&]*$/g
	var re=new RegExp(strRegex); 	
	if (re.test(str_url.Trim())){
		return (true); 
	}else{ 
		return (false); 
	}
} 
function googleTranslate()
{	
	config.slen=0;
	if(encodeURI(config.Paragraphs[config.transCursor])!="%0D"){
		$("comparesoure").innerHTML=$("comparesoure").innerHTML+"<div id=\"comparesoure"+config.transCursor+"\" onmouseout=\"return mousefunc(0,"+config.transCursor+");\" onmouseover=\"return mousefunc(1,"+config.transCursor+");\">"+config.Paragraphs[config.transCursor]+"</div>";
		config.slen=getStrActualLen(config.Paragraphs[config.transCursor]);
		google.language.translate(config.Paragraphs[config.transCursor], config.from_language, config.to_language, setTranslateToText);
	}
	else
	{
		
		config.transCursor++;
		if(config.transCursor<config.Paragraphslength)
		{
			googleTranslate();
		}
		else
		{
			if(config.totalHeight<600)$("comparemain").style.height="600px";
			$("contentout").style.color = "#000";
			$("contentout").value=config.translateresault;
		}
	}
}
setTranslateToText = function(result)
{	
	config.tlen=0;
	if(config.transCursor>0)
	{
		config.translateresault=config.translateresault+"\n"+result.translation;
		$("comparetranslate").innerHTML=$("comparetranslate").innerHTML+"<div id=\"comparetranslate"+config.transCursor+"\" onmouseout=\"return mousefunc(0,"+config.transCursor+");\" onmouseover=\"return mousefunc(1,"+config.transCursor+");\">"+result.translation+"</div>";
		config.tlen=getStrActualLen(result.translation);
	}
	else
	{
		config.translateresault=result.translation;
		$("comparetranslate").innerHTML=$("comparetranslate").innerHTML+"<div id=\"comparetranslate"+config.transCursor+"\" onmouseout=\"return mousefunc(0,"+config.transCursor+");\" onmouseover=\"return mousefunc(1,"+config.transCursor+");\">"+result.translation+"</div>";
		config.tlen=getStrActualLen(result.translation);
	}
	var textlen = config.slen>config.tlen?config.slen:config.tlen;
	var tempHeight = getTextHeight(textlen);
	$("comparetranslate"+config.transCursor).style.height=tempHeight;
	$("comparesoure"+config.transCursor).style.height=tempHeight;
	config.transCursor++;
	if(config.transCursor<config.Paragraphslength)
	{		
		$('contentout').value=$('contentout').value+'...';
		if(($('contentout').value.length/40)>config.translatepage)
		{
			$('contentout').value=$('contentout').value+'\n';
			config.translatepage++;
		}
		googleTranslate();
	}
	else
	{
		$("contentout").style.color = "#000";
		//$("contentout").value=htmlspecialchars_decode(config.translateresault);
		$("contentout").value=config.translateresault.replace(/&#39;/g,"'").replace(/&quot;/g,"\"");
		if($("contentout").value==$("content").value&&config.dicttrans)
		{
			$("contentout").style.display='none';
			$("slab").style.display='none';
			document.getElementById('dict').style.height="212px";
			Statistics(getStrActualLen($("content").value),false,config.dicttrans);
		}
		else
		{
			Statistics(getStrActualLen($("content").value),true,config.dicttrans);
			$("googleCopyRight").innerHTML='翻译结果由<a href="http://www.google.com" target="_blank"><img src="./img/v4/gg.gif" align="absmiddle"></a>提供';
		}
		
		if(config.totalHeight<300)$("comparesoure").style.height="300px";
		if(config.totalHeight<300)$("comparetranslate").style.height="300px";
		
	}
}
function getTextHeight (num)
{
	var lineNum = 62;
	var h = (Math.ceil(num/lineNum))*18;
	config.totalHeight=config.totalHeight+h;
	return h+"px";
}
function getStrActualLen (sChars){  
	sChars = sChars.replace(/(^[\\s]*)|([\\s]*$)/g, "");
	var len = 0;
	for(i=0;i<sChars.length;i++){
		iCode = sChars.charCodeAt(i);
		if((iCode>=0 && iCode<=255)||(iCode>=0xff61 && iCode<=0xff9f)){
			len += 1;
		}else{
			len += 2;
		}
	}
	return len;
}
/**
 *文章截取段落 按照空行截取
 */
function interceptionAtricle (str){
	var reg = /\n/g;
	str=str.split(reg); 
	return str;
}
//将需要翻译的文章按段落换行划分为小段
function getParagraphs (str)
{
	var tempParagraphs = interceptionAtricle(str);
	for(var i=0 ;i<tempParagraphs.length;i++)
	{
		//getStrActualLen
		if(getStrActualLen(tempParagraphs[i])>config.maxlength)cutTo2K(tempParagraphs[i]);
		else config.Paragraphs.push(tempParagraphs[i]);
	}
	return config.Paragraphs;
}
function cutTo2K(str)
{
	var temp			= "";
	var startIndex		= 0;
	var endIndex		= 0;
	var n				= 0;
	//var paragraphs		= interceptionAtricle(str);
	var reg				= /[.|。|！|\!|？|\?|,|，]/g
	var shortCutArray	=str.split(reg); 
	//	alert("d");
	for(var i=0;i <shortCutArray.length;i++){
		//alert(shortCutArray[i]);
		//endIndex = str.indexOf(shortCutArray[i]);
		
		//alert(endIndex);
		if (getStrActualLen(temp + shortCutArray[i])>config.maxlength){
			endIndex = startIndex+temp.length;
			config.Paragraphs.push(str.substring(startIndex,endIndex));
			startIndex		= endIndex;
			temp			= "";
		}else{
			temp += shortCutArray[i]+"/";
			//alert(" df" + temp);
		}
	} 
	config.Paragraphs.push(str.substring(startIndex,str.length));
	return config.Paragraphs;
}
/**
 * 最大段落不得超过2k 这里限制为2000字节。
 */
function wordCounter (str){
	if(encodeURI(str).length>1000)	return false;
	return true;
}
function $(lable)
{
	return document.getElementById(lable);
}
function compare()
{		
	
	function rand(a){return Math.floor(Math.random()*a)+1};
	var img = new Image(0,0);
	img.src="http://counter.kds.iciba.com/ds2rd.php?p=509&rand="+rand(9999);
	if($('content').value == "content"||$('content').value == "")return false;
	obj=$("forbid");
	var width=document.body.clientWidth;
	var height=(document.body.clientHeight<config.totalHeight)?(config.totalHeight-145):document.body.clientHeight;
	obj.style.width=width+"px";
	obj.style.height=height+"px";
	obj.style.visibility = "visible";
	$("compatearea").style.top = "134px";
	$("compatearea").style.display = "block";
	$("iV4fySelect").style.display = "none";
	K.config.enabled=false;
}
function copy()
{
	var data=$('contentout').value+"\n\n"+$('dict').value;
	copyToClipboard(data);
}
function reset()
{
	initTranslate ();
	$('content').style.color='#BFBFBF';
	$('contentout').style.color='#BFBFBF';
	$('content').value='请输入15个字以内的汉语句子或60个字符以内的英语句子';
	$('contentout').value='感谢您使用爱词霸翻译产品......';
	$('comparesoure').innerHTML='';
	$('comparetranslate').innerHTML='';
	$('compatearea').style.display='none';
}
function changeLang ()
{
	if($('sl').options[$('sl').selectedIndex].value=="auto")return false;
	var slText = $('sl').options[$('sl').selectedIndex].text;
	var tlText = $('tl').options[$('tl').selectedIndex].text;
	jsSelectItemByValue($('tl'),slText);
	jsSelectItemByValue($('sl'),tlText);
}
function jsSelectItemByValue (objSelect, objItemText) { 
    for (var i = 0; i < objSelect.options.length; i++) {        
        if (objSelect.options[i].text == objItemText) {        
            objSelect.options[i].selected = true;        
            isExit = true;        
            break;        
        }        
    }     
}    
var hotWord = '请输入15个字以内的汉语句子或60个字符以内的英语句子';
google.load("language", "1");
config.isIE = (document.all && window.ActiveXObject && !window.opera) ? true : false;
String.prototype.Trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); }  
String.prototype.LTrim = function() { return this.replace(/(^\s*)/g, ""); }  
String.prototype.RTrim = function() { return this.replace(/(\s*$)/g, ""); } 

function copyToClipboard (txt) {
	if(window.clipboardData) {
		window.clipboardData.clearData();
		try{
			window.clipboardData.setData("Text", txt);
			alert("复制成功！");
		}catch(e){
		}
	} else {

	}
} 

//对比
function iciba_fy_Compare (){
	$('compare').style.display="block";
}


function InitAjax()
{
    var http_request = false;

    if (window.XMLHttpRequest)
    {
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType)
        {
            http_request.overrideMimeType('text/xml');
        }
    }
    else if (window.ActiveXObject)
    {
        try
        {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {}
        }
    }
    if (!http_request)
    {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
    return http_request;
}


function mousefunc(type,objid)
{
	//alert(document.getElementById("comparesoure"+objid).style.height+" "+document.getElementById("comparetranslate"+objid).style.height);
	if(type==1)
	{
		addClass(document.getElementById("comparesoure"+objid),"comparediv");
		document.getElementById("comparesoure"+objid).style.backgroundColor="#EAF1F7";
		addClass(document.getElementById("comparetranslate"+objid),"comparediv");
		document.getElementById("comparetranslate"+objid).style.backgroundColor="#EAF1F7";
	}
	else
	{
		removeClass(document.getElementById("comparesoure"+objid),"comparediv");
		document.getElementById("comparesoure"+objid).style.backgroundColor="#fff";
		removeClass(document.getElementById("comparetranslate"+objid),"comparediv");
		document.getElementById("comparetranslate"+objid).style.backgroundColor="#fff";
	}
}
function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}
function charchange(){
	cValue=document.getElementById("content").value;
	if(cValue == "请输入15个字以内的汉语句子或60个字符以内的英语句子") {			   
		document.getElementById("content").value="";
		document.getElementById("content").style.color = "#666";
	}
	else{
		document.getElementById("content").style.color = "#666";
	}
}

/**
 * 切换语言
 * author wanghaizhou@gmail.com
 * date 2008-8-18
 */
function v4SetLang(val)
{
	var sl = null;
	var tl = null;
	if (val == 'gb2ko' )
	{
		sl = 'zh-CN';
		tl = 'ko';
	}
	else if( val == 'en2gb' )
	{
		sl = 'en';
		tl = 'zh-CN';	
	}
	else if( val == 'gb2en' )
	{
		sl = 'zh-CN';
		tl = 'en';	
	}
	else if( val == 'ko2gb' )
	{
		sl = 'ko';
		tl = 'zh-CN';	
	}
	else if(val == 'gb2big')
	{
		sl = 'zh-CN';
		tl = 'zh-TW';			
	}
	else if(val == 'big2gb')
	{
		sl = 'zh-TW';
		tl = 'zh-CN';		
	}
	else if(val == 'gb2ja')
	{
		sl = 'zh-CN';
		tl = 'ja';		
	}
	else if(val == 'ja2gb')
	{
		sl = 'ja';
		tl = 'zh-CN';		
	}
	else if(val == 'all')
	{

		document.getElementById('iV4fySelect').style.display ='none';		
		document.getElementById('allselect').style.display = 'inline';
		document.getElementById('shortcut').style.width = '0px';
		return;
	}
	document.getElementById('sl').value= sl;
	document.getElementById('tl').value= tl;
}

function showpost(a,b)
{
     
    var menuObj = document.getElementById(b);
    var titleObj = document.getElementById(a);
    var posObj = new findPos(titleObj);
    var menu_left = posObj.left;
    var menu_top = posObj.top + parseInt(titleObj.offsetHeight);

    menuObj.style.position = 'absolute';
    menuObj.style.display  = '';
    
    // 计算显示位置
    if (posObj.left + menuObj.offsetWidth >= document.body.clientWidth && 0)
    {
        menu_left = parseInt(posObj.left) - parseInt(menuObj.offsetWidth) + parseInt(titleObj.offsetWidth);
    }
    if (posObj.top + menuObj.offsetHeight >= document.body.clientHeight && 1)
    {
        menu_top = parseInt(posObj.top) - parseInt(menuObj.offsetHeight);
    }
    
    menuObj.style.left =  (menu_left - 36) + "px";
    menuObj.style.top = menu_top + "px";
}

function hiddenpost(a,b)
{
    str=document.getElementById(a).value;
    chkarr = str.split(' ');
    if(chkarr.length==3)ckid=1;
    if(ckid==1) document.getElementById(b).style.display='none';
}

function closepost(b)
{
    document.getElementById(b).style.display='none';
}
function findPos(o)     { 
    this.top  = o.offsetTop;
    this.left = o.offsetLeft;
    while(o = o.offsetParent)
    {
        this.top  += o.offsetTop;
        this.left += o.offsetLeft;
    }
}
//以下EF操作
function changeOp()
{
    var zt=document.getElementById("changee").src;
	/*if((document.getElementById('chatroom').innerHTML == ''))
	{
		document.getElementById('barAd').style.top = (document.getElementById('fyad').style.display == 'none') ? '-401px' : '-220px';
	}
	else
	{
		document.getElementById('barAd').style.top = (document.getElementById('fyad').style.display == 'none') ? '-681px' : '-416px';
	}*/
	//alert('asdf');
	document.getElementById('barAd').style.top = (document.getElementById('fyad').style.display == 'none') ? '-402px' : '-214px';
	document.getElementById('fyad').style.display = (document.getElementById('fyad').style.display == 'none') ? 'block' : 'none';
	document.getElementById("changee").src = (document.getElementById('fyad').style.display == 'none') ? './img/v4/open.jpg' : './img/v4/close.jpg';
	document.getElementById('changee').style.display="none";
	document.getElementById('changee').style.height="0px";
}

function UaaRand(num) {
    return Math.floor(Math.random()*num)+1;
}
function closeChatRoom()
{
	if((document.getElementById('fyad').style.display == 'none'))
	{
		$("barAd").style.top="-218px";
	}
	else
	{
		$("barAd").style.top="-497px";
	}
	$("chatroom").style.height="0px"
	$("chatroom").innerHTML = "";
}



var webDictCallback=function(str){
	
	if(str=='') return ;
	var obj= eval(str);
	var out='';
	//alert(config.to_language);
	//return ;
	for(i=0;i<obj.length;i++){
		out+= obj[i].word+"\n";
		//alert( typeof obj[i].detail );
		if(typeof obj[i].detail !='undefined'){
			for(j=0;j<obj[i].detail.length;j++){
				//out+=obj[i].detail[j].
				//if(config.to_language=='en')
				out+= (j+1)+'.';
				out+= config.to_language=='en'?obj[i].detail[j].en:obj[i].detail[j].cn;
				out+="\n";
			}
			out+="\n";
		}
	}
	config.dicttrans = true;
	document.getElementById('dictTrans').style.display="inline";
	document.getElementById('dict').style.height="138px";
	document.getElementById('contentout').style.height="50px";
	document.getElementById('dict').style.color="#000";
	document.getElementById('dict').value=out;
}

function JSLoad(url, container, type, defer, language, title)
   {
      // verify / attain container
      if(container == undefined || container == null) container = this;

      // setup container
      if(typeof container.write == "undefined")
         if(typeof container.document != "undefined")
            container = container.document;
         else throw "Invalid container. Unable to load [" + url + "]";

      // no type set
      if(type == undefined || type == null)
      {
         type = '';

         // no language so set default type
         if(language == undefined || language == null)
         {
            language = undefined;
            type = "text/javascript";
         }
      }

      // set default language
      if(language == undefined || language == null) language = "JavaScript";

      // set title
      if(title == undefined || title == null) title = '';

      // set defer
      if(defer == undefined) defer = false;

      // build the script object
      var script = container.createElement("script");
      script.defer = defer;
      script.language = language;
      script.title = title;
      script.type = type;
      script.charset = "UTF-8";//charset="UTF-8"
      script.src = url;

      // dynamically load the script via it's container
      var head = container.getElementsByTagName("head")[0];
      head.appendChild(script);
   }
//end EF
//alert('口语翻译测试结束，谢谢大家支持');

