
//ban drag of <img> and select of header
$(document).ready(
function(e)
{
    $('img').bind('dragstart', function(){return false;});
    $('#header').bind('selectstart', function(){return false;});
	

	$(window).bind('resize',function()
	{
		window.external.RestoreZoom();
	}
	);
}
);

//show the new features panel if it is firstStart
$(document).ready(
function (e) {
    if (Number(window.external.IsFirstRun()) != 0 && ie > 6) {
        showNewFeaturesBox();
    }
});

function alertMsg(msg, mode) { //mode为空，即只有一个确认按钮，mode为1时有确认和取消两个按钮
    msg = msg || '';
    mode = mode || 0;
    var top = document.body.scrollTop || document.documentElement.scrollTop;
    var isIe = (document.all) ? true : false;
    var isIE6 = isIe && !window.XMLHttpRequest;
    var sTop = document.documentElement.scrollTop || document.body.scrollTop;
    var sLeft = document.documentElement.scrollLeft || document.body.scrollLeft;
    var winSize = function () {
        var xScroll, yScroll, windowWidth, windowHeight, pageWidth, pageHeight;
        // innerHeight获取的是可视窗口的高度，IE不支持此属性
        if (window.innerHeight && window.scrollMaxY) {
            xScroll = document.body.scrollWidth;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }

        if (self.innerHeight) {    // all except Explorer
            windowWidth = self.innerWidth;
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }

        // for small pages with total height less then height of the viewport
        if (yScroll < windowHeight) {
            pageHeight = windowHeight;
        } else {
            pageHeight = yScroll;
        }

        // for small pages with total width less then width of the viewport
        if (xScroll < windowWidth) {
            pageWidth = windowWidth;
        } else {
            pageWidth = xScroll;
        }

        return {
            'pageWidth': pageWidth,
            'pageHeight': pageHeight,
            'windowWidth': windowWidth,
            'windowHeight': windowHeight
        }
    }();
    //alert(winSize.pageWidth);
    //遮罩层
    var styleStr = 'top:0;left:0;position:absolute;z-index:10000;background:#666;width:' + winSize.pageWidth + 'px;height:' + (winSize.pageHeight + 30) + 'px;';
    styleStr += (isIe) ? "filter:alpha(opacity=80);" : "opacity:0.8;"; //遮罩层DIV
    var shadowDiv = document.createElement('div'); //添加阴影DIV
    shadowDiv.style.cssText = styleStr; //添加样式
    shadowDiv.id = "shadowDiv";
    //如果是IE6则创建IFRAME遮罩SELECT
    if (isIE6) {
        var maskIframe = document.createElement('iframe');
        maskIframe.style.cssText = 'width:' + winSize.pageWidth + 'px;height:' + (winSize.pageHeight + 30) + 'px;position:absolute;visibility:inherit;z-index:-1;filter:alpha(opacity=0);';
        maskIframe.frameborder = 0;
        maskIframe.src = "about:blank";
        shadowDiv.appendChild(maskIframe);
    }
    document.body.insertBefore(shadowDiv, document.body.firstChild); //遮罩层加入文档
    //弹出框
    var styleStr1 = 'display:block;position:fixed;_position:absolute;left:' + (winSize.windowWidth / 2 - 200) + 'px;top:' + (winSize.windowHeight / 2 - 150) + 'px;_top:' + (winSize.windowHeight / 2 + top - 150) + 'px;'; //弹出框的位置
    var alertBox = document.createElement('div');
    alertBox.id = 'alertMsg';
    alertBox.style.cssText = styleStr1;
    //创建弹出框里面的内容P标签
    var alertMsg_info = document.createElement('P');
    alertMsg_info.id = 'alertMsg_info';
    alertMsg_info.innerHTML = msg;
    alertBox.appendChild(alertMsg_info);
    //创建按钮
    var btn1 = document.createElement('a');
    btn1.id = 'alertMsg_btn1';
    btn1.href = 'javas' + 'cript:void(0)';
    btn1.innerHTML = '<cite>了解更多</cite>';
    btn1.onclick = function () {
        window.open("https://www.microsoft.com/zh-cn/servicesagreement/");
        document.body.removeChild(alertBox);
        document.body.removeChild(shadowDiv);
        return true;
    };
    alertBox.appendChild(btn1);
    if (mode === 1) {
        var btn2 = document.createElement('a');
        btn2.id = 'alertMsg_btn2';
        btn2.href = 'javas' + 'cript:void(0)';
        btn2.innerHTML = '<cite>拒绝</cite>';
        btn2.onclick = function () {
            document.body.removeChild(alertBox);
            document.body.removeChild(shadowDiv);
            return false;
        };
        alertBox.appendChild(btn2);
    }
    document.body.appendChild(alertBox);

}
function showNewFeaturesBox()
{
	$('#NewFeaturesBox').css('display','block');
}
function hideNewFeaturesBox()
{
	$('#NewFeaturesBox').css('display','none');
}
function NFBGoto(num)
{
	$('#NewFeaturesBox .NFBImage').css('display','none');
	$('#NewFeaturesBox .NFBImage_'+num).css('display','block');
}
function NFBGoToPrev(obj)
{
	$('#NewFeaturesBox .NFBImage').css('display','none');
	
	if($(obj).parent().prev().hasClass('NFBImage'))
	{
		$(obj).parent().prev().css('display','block');
	}
	else
	{
		$('#NewFeaturesBox .NFBImage').last().css('display','block');
	}
}
function NFBGoToNext(obj)
{
	$('#NewFeaturesBox .NFBImage').css('display','none');
	
	if($(obj).parent().next().hasClass('NFBImage'))
	{
		$(obj).parent().next().css('display','block');
	}
	else
	{
		$('#NewFeaturesBox .NFBImage').first().css('display','block');
	}
}


//add back-top button to $('.SettingArea')
$(document).ready(
function(e)
{
	if (ie!=false && ie<=6){return;}
	
	// hide .back-top first
	$('.back-top').hide();
	
	// fade in/out .back-top
	$('.Setting').bind("scroll",function () 
	{
		var backTopBtnBottom=0;
		backTopBtnBottom+=$('.frm_ads').is(':hidden')?0:$('.frm_ads').height();
		backTopBtnBottom+=$('#footer').height();
		backTopBtnBottom+=$('.frm_bottom').height();
		backTopBtnBottom+=10;
		$(this).find('.back-top').css('bottom',(backTopBtnBottom)+'px');
		if ($(this).scrollTop() > 10) 
		{
			$(this).find('.back-top').fadeIn(100);
		} 
		else
		{
			$(this).find('.back-top').fadeOut(100);
		}
	});

	// scroll body to 0px on click
	$('.back-top').bind(
	{
		click:function() 
		{
			$(this).parent().animate({scrollTop:0}, 100);
			return false;
		},
		mouseover:function() 
		{
			$(this).removeClass('back-top-hovered').removeClass('back-top-pressed').addClass('back-top-hovered');
		},
		mousedown:function() 
		{
			$(this).removeClass('back-top-hovered').removeClass('back-top-pressed').addClass('back-top-pressed');
		},
		mouseup:function() 
		{
			$(this).removeClass('back-top-hovered').removeClass('back-top-pressed').addClass('back-top-hovered');
		},
		mouseout:function() 
		{
			$(this).removeClass('back-top-hovered').removeClass('back-top-pressed');
		}
	});
});


//if ie6-,checkWindowResize every 1 second 
$(document).ready(
function(e)
{
	if (ie!=false && ie<=6)
	{
		checkWindowResize();
	}
});


function checkWindowResize() 
{
    var winHeightOld = $("frm_middle").height();
    docheck();
    function docheck() 
	{
        var winHeightNew = $("frm_middle").height();
        if (winHeightOld != winHeightNew) 
		{
            window.external.AdjustWin(0);
            winHeightOld = winHeightNew = $(".frm_middle").height();
        }
        else 
		{
            setTimeout(docheck, 1000);
        }
    }
}


//create the dynamic objects as soon as document ready
//to make sure they can recieve the events correctly
$(document).ready(
function(e) 
{
	//the create order should be as below,
	//else the SentQueryHist cannot recieve mouseenter/mouseleave
	createSentQueryHist();
	createQueryHist();

	createAutoSuggesion();
	createMainMenu();
});

//get the IE version
var ie = function()
{ 
    var undef, 
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');
    while ( 
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', 
        all[0]
    );
    return v > 4 ? v : false;
} ();

//decide whether we should ban Backspace key in current condition
function shouldBanBackspace()
{
    var obj = document.activeElement;//获取当前焦点的对象  

	if (document.activeElement==undefined || document.activeElement.tagName=="IFRAME"||document.activeElement.type==undefined)
	{
		return true;
	}

    var t = obj.type || obj.getAttribute('type');//获取事件源类型       
    //获取作为判断条件的事件类型   
    var vReadOnly = obj.readOnly;  
    var vDisabled = obj.disabled;  
    //处理undefined值情况   
    vReadOnly = (vReadOnly == undefined) ? false : vReadOnly;  
    vDisabled = (vDisabled == undefined) ? true : vDisabled;  
    //当敲Backspace键时，事件源类型为密码或单行、多行文本的，    
    //并且readOnly属性为true或disabled属性为true的，则退格键失效    
    var flag1 = (t == "password" || t == "text" || t == "textarea") && (vDisabled == true);  
    //当敲Backspace键时，事件源类型非密码或单行、多行文本的，则退格键失效      
    var flag2 = (t != "password" && t != "text" && t != "textarea");  
	
	if (flag1||flag2)
	{
		return true;
	}
	else 
	{
		return false;
	}
	
}
 
function SearchOnFL() 
{
    setTimeout(SearchOnFirstLoad, 100);
}
function SearchOnFirstLoad() 
{
    window.external.SearchOnFirstLoad();
}

var ContextArea=0;
function getContextArea()
{
	return ContextArea;
}
//1:input-menu  2:translate-input 4:result-page-menu
function detectContextArea()
{
	$("#input_text").bind("mouseenter",function(){ContextArea=1;});
	$("#input_text").bind("mouseleave",function(){ContextArea=0;});
	
	$("#translate_input_text").bind("mouseenter",function(){ContextArea=2;});
	$("#translate_input_text").bind("mouseleave",function(){ContextArea=0;});
	
	$("#main").bind("mouseenter",function(){ContextArea=4;});
	$("#main").bind("mouseleave",function(){ContextArea=0;});
	
	$("#translate_output").bind("mouseenter",function(){ContextArea=4;});
	$("#translate_output").bind("mouseleave",function(){ContextArea=0;});
	
	$("#sent-input-text").bind("mouseenter",function(){ContextArea=1;});
	$("#sent-input-text").bind("mouseleave",function(){ContextArea=0;});
	$("#sent-main").bind("mouseenter",function(){ContextArea=4;});
	$("#sent-main").bind("mouseleave",function(){ContextArea=0;});
	
 	$("#exapp-items #NewWordList").bind("mouseenter",function(){ContextArea=8;});
	$("#exapp-items #NewWordList").bind("mouseleave",function(){ContextArea=0;});
	$("#exapp-items #MSFlashCard").bind("mouseenter",function(){ContextArea=9;});
	$("#exapp-items #MSFlashCard").bind("mouseleave",function(){ContextArea=0;});
	$("#exapp-items #FMRadio").bind("mouseenter",function(){ContextArea=10;});
	$("#exapp-items #FMRadio").bind("mouseleave",function(){ContextArea=0;});
	$("#exapp-items #WordChallenge").bind("mouseenter",function(){ContextArea=11;});
	$("#exapp-items #WordChallenge").bind("mouseleave",function(){ContextArea=0;});
	$("#exapp-items #OralEnglish").bind("mouseenter",function(){ContextArea=12;});
	$("#exapp-items #OralEnglish").bind("mouseleave",function(){ContextArea=0;});
	
	$("#exapp-items .promote-app-item").bind("mouseenter",function(){ContextArea=32;CurPromoteAppId=this.id;});
	$("#exapp-items .promote-app-item").bind("mouseleave",function(){ContextArea=0;CurPromoteAppId='';});
}

var CurPromoteAppId='';
function getCurrentPromoteAppId()
{
	return CurPromoteAppId;
}


//to detect whether a function exists
function funExists(funName)
{ 
	try
	{  
		if (typeof eval(funName)=="undefined"){return false;} 
		if (typeof eval(funName)=="function"){return true;}
	}
	catch(e)
	{
		return false;
	} 
} 

//------------------------------------------------------------
//header 
var startx=0,starty=0,endx=0,endy=0;
function header_mouse_down()
{
	window.external.OnHeaderMouseDown();
}
//------------------------------------------------------------
//BtnMiniMode
function BtnMiniMode_onclick()
{
    window.external.OnMin();
    window.external.ShowMiniModeDlg();
}

//------------------------------------------------------------
//BtnMin
function BtnMin_onclick()
{
    window.external.OnMin();
}
//--------------------------------------------------------------------
//BtnMax
function BtnMax_StatusChangeTo(MaxOrRestore)
{
	var BtnMax=document.getElementById("BtnMax");
	if (MaxOrRestore=='Restore')
	{
		BtnMax.title = '还原（快捷键：Alt+M）';
		BtnMax.className='Restore_N';
	}
	else if (MaxOrRestore=='Max')
	{
	    BtnMax.title = '最大化（快捷键：Alt+M）';
		BtnMax.className='Max_N';
	}
}

function BtnMax_onclick()
{
	var BtnMax=document.getElementById("BtnMax");
	if (BtnMax.className.indexOf('Max') != -1)
	{
		BtnMax_StatusChangeTo('Restore');
		window.external.OnMax();
	}
    else
	{
		BtnMax_StatusChangeTo('Max');
		window.external.OnRestore();
	} 
}
//------------------------------------------------------------------------------
//BtnClose
function BtnClose_onclick()
{
    window.external.OnClose();
}
//-----------------------------------------------------------------------------
//btn_back       
function btn_back_onclick()
{
    //query index,load last query result
	//load the query before this query
	window.external.BtnBackOnClick();
}

function disableBtnBack()
{
	$("#back").addClass("back_disable").removeClass("normal_ba").removeClass("hover_ba").removeClass("press_ba");
}
function enableBtnBack()
{
    $("#back").addClass("normal_ba").removeClass("back_disable");
}

//--------------------------------------------------------------------------
//btn_forward
/* sprite icons : mouse out,mouse down,mouse over, not available.mouse up  mouse over */
function btn_forward_onclick()
{
    //load last query result
	window.external.BtnForwardOnClick();
}

function disableBtnForward()
{
	$("#forward").addClass("forward_disable").removeClass("normal_ba").removeClass("hover_ba").removeClass("press_ba");
}
function enableBtnForward()
{
	$("#forward").addClass("normal_ba").removeClass("forward_disable");
}




//------------------------------------------------------------------------------
//btn_dictsearch
//

function isChn(str)
{
    var pattern = /[\u4E00-\u9FA5]+/;
    return pattern.test(str);
}


function btn_dictsearch_onclick2(bLogOption) 
{
	//instrumentation
    window.external.AddToLog('DictSearch');
	
	//init state
	hideAutoSuggestion();
	hideQueryHist();
	$('#input_text').focus().select();

	//get query
	var query = document.getElementById("input_text").value.Trim();
	if (typeof query != "string" || query.length <= 0)
	{
	    showHomepage();
	    return;
	}
	else
	{
	    show_ifrm("offline_result");
	    $("#OnlineSearchStatus", document.frames("offline_result").document).css("display", "block").html('').html("正在进行在线查询,请稍候...");
	}

	//record query
    if (bLogOption != "dont-log") 
    {
        window.external.AddToQueryNavList(query);
        window.external.AddToQueryRecList(query);
    }
	
	//-----------------------------------------------//
    //get encoded query
	var query2 = encodeURIComponent(query).substring(0, 1800);
	var newSrc = "https://cn.bing.com/dict/clientsearch?mkt=zh-CN&setLang=zh&form=BDVEHC&ClientVer=BDDTV3.5.1.4320&q=" + query2;

    //try load online result
	$('#online_result').attr('src', newSrc);
	window.external.MySetTimer("Timer_SearchOnlineTimeout");
} 

//called by cpp when timeout
function SearchOnlineTimeout()
{
    $("#OnlineSearchStatus", window.frames["offline_result"].document).css("display", "block").html('').html("在线查询超时,请检查您的网络连接.");
}

function show_offlineresult(result)
{
    $("#offlineResult", window.frames["offline_result"].document).html('').html(result);
	$("#OnlineSearchStatus",window.frames["offline_result"].document).css("display","none");
	window.frames["offline_result"].window.checkInNewWordList();//update the status of the AddNewWord picture.
}

//check if current query in NWList,then 
//if yes,change the add button on offline result page from pending to added.
//if no,change the add button on offline result page from added to pending.
function checkInNewWordList()
{
	window.frames["offline_result"].window.checkInNewWordList();
}
var last_input_text;
function input_text_onkeyup()
{
	if (last_input_text==$("#input_text").attr("value"))
	{
		return;
    }
    else 
    {
        hideQueryHist();
    }

	//trim the input text to make a valid query
	var query = $("#input_text").attr("value")==null ? query="" : query=$("#input_text").attr("value").toString().replace(/(^\s*)|(\s*$)/g,""); 

	if (query.length<=0)
	{
		hideAutoSuggestion();
		showHomepage();
		setTimeout(function(){$("#input_text").focus();},0);//bug fix:focus is lost when query.length <= 0
	}
	else
	{
		show_ifrm("offline_result");
		
		//hide the node showing search online status 
		$("#OnlineSearchStatus",document.frames("offline_result").document).css("display","none").html(""); 
		
		searchOfflineDict(query);
		showAutoSuggestion(query);
	}
	last_input_text=$("#input_text").attr("value");
	//change online dict iframe to ../Common/blank.html
	var ifrm2=document.getElementById("online_result");
	ifrm2.src="../Common/blank.html";
}

function input_text_onmouseover()
{
	if ($('#QueryHist').css('display')!='block' //if query history tab is not shown
	&& document.activeElement.id!='input_text')//if input_text is not focused yet
	{
		GetFocus('input_text');
	}
}

function input_text_onclick(obj)
{
	obj.value.length<=0?(function(){showQueryHistPageContains(0);})():(function(){hideQueryHist();})();
}
function input_text_onfocus(obj)
{
	obj.parentNode.parentNode.className='input_focus';
}
function input_text_onblur(obj)
{
	obj.parentNode.parentNode.className='input_blur';
	
	var bInQH=bInQHArea;//add this line to avoid some unknown bug in ie6
	if (bInQH)
	{
		obj.focus();
		return false;
	}
	else
	{
		hideAutoSuggestion();
		hideQueryHist();
	}
}

function input_text_onpropertychange(obj)
{
	if (obj.value.length<=0){input_text_onkeyup();}
}

//use to show auto suggestion
function showAutoSuggestion(query)
{
	createAutoSuggesion();
	changeAutoSugPosition();
	clearAutoSug();
	getAutoSugItems();
	SelectedASItem = -1;
}
	
function createAutoSuggesion()
{
	var ItemString = '\
	<div id="AutoSuggestion" class="DynamicEle">\
	</div>\
	\
	';
	var autoSuggestion=document.getElementById("AutoSuggestion");
	if (autoSuggestion==undefined || autoSuggestion==null)
	{
		var a=document.createElement("div");//
		a.innerHTML =ItemString;
		document.body.appendChild(a);
	}
	document.getElementById("AutoSuggestion").style.display='none';
	return;
}

	
function changeAutoSugPosition()
{
	var autoSuggestion=document.getElementById("AutoSuggestion");
	var obj=document.getElementById("input");
	if (autoSuggestion==undefined)
	{
		return;
	}

	var x=getLeft(obj);
	var y=getTop(obj);
	var x2=x+2;
	var y2=y+obj.offsetHeight+1;	

	autoSuggestion.style.top=y2+'px';
	autoSuggestion.style.left=x2+'px';
	//bug fixed:when drag border in '翻译' tab,obj.offsetWidth==0,obj.offsetWidth-1<0,this will cause error.
	autoSuggestion.style.width=(obj.offsetWidth-1>0?obj.offsetWidth-1:0)+'px'; 

	return;
}
	

function clearAutoSug()
{
	var autoSuggestion=document.getElementById("AutoSuggestion");
	autoSuggestion.innerHTML='';
	autoSuggestion.style.display='none';
}

function showAutoSug()
{
	var autoSuggestion=document.getElementById("AutoSuggestion");
	autoSuggestion.style.display="block";
}

function getAutoSugItems()
{
	var query = query||document.getElementById("input_text").value;
	
	if (typeof query != "string" || query.length<=0)
	{
		return;
	}
	var lang=isChn(query)?"zh-cn":"en-us";	
	//offline dict
	window.external.GetAutoSuggestionItems(lang,query);
}
	
function insertAutoSuggestionItem(itemStr)
{
	if (CurrentTab().toLowerCase()!='li_1'||$('iframe#offline_result').css('display')!='block')
	{
		//current tab is not the dict tab or offline result page is not shown
		return;
	}

	var autoSuggestion=document.getElementById("AutoSuggestion");
	autoSuggestion.innerHTML=itemStr;
	autoSuggestion.style.display="block";
}

function hideAutoSuggestion()
{
	$('#AutoSuggestion').css('display','none');
}



function changeInputText(query) 
{
	query=query.replace(/(^\s*)|(\s*$)/g,"");
	
	document.getElementById("input_text").value=query;
	last_input_text=query;//don't forget to update last_input_text~
	
	if (query.length<=0)
	{
		showHomepage();
	}
	else
	{
		show_ifrm("offline_result");
		searchOfflineDict(query);
	}
	
	//change online dict iframe to ../Common/blank.html
	$("#online_result").attr("src","../Common/blank.html");
}




function ASItem_onclick(obj) 
{
    window.external.AddToLog('ViewASItem');
	var nodes=obj.childNodes;
	var word="";
	for (var i=0;i<nodes.length;i++)
	{
		if (nodes[i].className=="ASHighlight")
		{
			word+=nodes[i].innerHTML;
		}
		if (nodes[i].className=="ASWord")
		{
			word+=nodes[i].innerHTML;
		}
	}
	word=word.replace(/&nbsp;/g," ");

	changeInputText(word);
	setTimeout(function(){btn_dictsearch_onclick2();},10);
}

//-----------------------------------------
function toggle_queryhistory()
{
	if (document.activeElement.id=='input_text')
	{
		$('#input_text').blur();
	}
	setTimeout(function(){btn_queryhistory_onclick();},50);
}

function btn_queryhistory_onclick() 
{
	$('#btn_queryhistory').focus();
	var queryHist=document.getElementById('QueryHist');
	if (queryHist==undefined||queryHist.style.display=="none")
	{
	    showQueryHistPageContains(0);
	    window.external.AddToLog('ViewSearchHistory');
	}
	else
	{
		hideQueryHist();
	}
}
//use to show the query history page which containning the indexed query
function showQueryHistPageContains(QueryIndex)
{
	createQueryHist();
	changeQueryHistPosition();
	clearQueryHist();
	//showQueryHist();
	getQueryHistPageContains(QueryIndex);
}

var bInQHArea=false;//true if in div#QueryHist area

function queryhistory_onblur(obj)
{
	var queryHist=document.getElementById('QueryHist');
	if (queryHist==undefined || queryHist.style.display=='none')
	{
		bInQHArea=false;
	}
	if (bInQHArea)
	{
		obj.focus();
		return false;
	}
	else
	{
		hideQueryHist();
		GetFocus('input_text');
	}
}

function createQueryHist()
{
	var ItemString = '\
	<div id="QueryHist" class="DynamicEle" onmouseenter="bInQHArea=true;"  onmouseleave="bInQHArea=false;">\
		<div class="ie6-select-mask">\
			<iframe class="ie6-select-mask-iframe" scrolling="no"  frameborder="0">\
			</iframe>\
		</div>\
		<div id="QueryHistItems">\
			<div class="QueryHistItem"\
            onmouseover="$(\'.QueryHistItem.Hovered\').removeClass(\'Hovered\');$(this).addClass(\'Hovered\');"\
			onmouseout="$(\'.QueryHistItem.Hovered\').removeClass(\'Hovered\');$(this).removeClass(\'Hovered\');"\
			>\
            	<div class="QueryHistIndex">6</div>\
            	<div class="QueryHistContent"\
				 onmousedown="QueryHistContent_onclick(this);"\
				>\
                    <div class="QueryHistWord">111111111</div>\
                    <div class="QueryHistDef">00000000000000000000000000000000</div>\
                </div>\
                <div class="QueryHistDelete">\
					<div id="BtnQueryHistDelete" title="删除此条" class="normal_ba"\
                    onmouseover="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');"\
                    onmousedown="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'press_ba\');"\
                    onmouseup="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');"\
                    onmouseout="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'normal_ba\');"\
					onclick="javascript:BtnQueryHistDelete_onclick(this)"\
					>\
					</div>\
                </div>\
            </div>\
		</div>\
		<div id="QueryHistFooter">\
			<div id="QueryHistBack">\
				<div id="BtnQueryHistBack" title="上一页" class="BtnQueryHistBack_D"\
	            onmouseover="if ($(this).hasClass(\'BtnQueryHistBack_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');}"\
	            onmousedown="if ($(this).hasClass(\'BtnQueryHistBack_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'press_ba\');}"\
	            onmouseup="if ($(this).hasClass(\'BtnQueryHistBack_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');}"\
	            onmouseout="if ($(this).hasClass(\'BtnQueryHistBack_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'normal_ba\');}"\
				onclick="javascript:BtnQueryHistBack_onclick()"\
				>\
				</div>\
			</div>\
			<div id="QueryHistCurrentPos">1/1</div>\
			<div id="QueryHistForward">\
				<div id="BtnQueryHistForward" title="下一页" class="BtnQueryHistForward_D"\
	            onmouseover="if ($(this).hasClass(\'BtnQueryHistForward_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');}"\
	            onmousedown="if ($(this).hasClass(\'BtnQueryHistForward_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'press_ba\');}"\
	            onmouseup="if ($(this).hasClass(\'BtnQueryHistForward_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');}"\
	            onmouseout="if ($(this).hasClass(\'BtnQueryHistForward_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'normal_ba\');}"\
				onclick="javascript:BtnQueryHistForward_onclick()"\
				>\
				</div>\
			</div>\
            <div id="QueryHistClear">\
				<div id="BtnQueryHistClear" title="清空查询历史" class="normal_ba"\
	            onmouseover="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');"\
	            onmousedown="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'press_ba\');"\
	            onmouseup="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');"\
	            onmouseout="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'normal_ba\');"\
				onclick="javascript:BtnQueryHistClear_onclick()"\
				>\
				</div>\
            </div>\
		</div>\
	</div>\
	';
	var queryHist=document.getElementById("QueryHist");
	if (queryHist==undefined || queryHist==null)
	{
		var a=document.createElement("div");
		a.innerHTML =ItemString;
		document.body.appendChild(a);
	}
	document.getElementById("QueryHist").style.display='none';
	return;
}

	
function changeQueryHistPosition()
{
	var queryHist=document.getElementById("QueryHist");
	var obj=document.getElementById("input");
	if (queryHist==undefined)
	{
		return;
	}
	
	var x=getLeft(obj);
	var y=getTop(obj);
	var x2=x+2;
	var y2=y+obj.offsetHeight+1;	

	queryHist.style.top=y2+'px';
	queryHist.style.left=x2+'px';
	//bug fixed:when drag border in '翻译' tab,obj.offsetWidth==0,obj.offsetWidth-1<0,this will cause error.
	queryHist.style.width=(obj.offsetWidth-1>0?obj.offsetWidth-1:0)+'px'; 
	return;
}
	

function clearQueryHist()
{
	var queryHist=document.getElementById("QueryHist");
	$("#QueryHistItems").html('');
	queryHist.style.display='none';
}

function showQueryHist()
{
	var queryHist=document.getElementById("QueryHist");
	queryHist.style.display="block";
}
function hideQueryHist()
{
	$('#QueryHist').css('display','none');
}

function getQueryHistPageContains(QueryIndex)
{
	//offline dict
    window.external.GetQueryRecPageContains(QueryIndex);
}

//cpp will check the query history list and compute which set of query items are to be inserted
function insertQueryHistItem(itemStr)
{
	var queryHist=document.getElementById("QueryHist");
	$("#QueryHistItems").html('').html(itemStr);
	queryHist.style.display="block";
}

//after insertion,cpp then update the page,tell js about current page and total pages
function updateQueryHistPage(currentPageIndex,totalPageIndex)
{
	//use this information to update the BtnQueryHistBack,QueryHistCurrentPos,BtnQueryHistForward
	if (currentPageIndex<=1)
	{
		currentPageIndex=1;
		$("#BtnQueryHistBack").attr("class", "BtnQueryHistBack_D");
	}
	else 
	{
		$("#BtnQueryHistBack").attr("class","normal_ba");
	}
	
	if (currentPageIndex>=totalPageIndex)
	{
		currentPageIndex=totalPageIndex;
		$("#BtnQueryHistForward").attr("class","BtnQueryHistForward_D");
	}
	else
	{
	    $("#BtnQueryHistForward").attr("class", "normal_ba");
	}
	
	$("#QueryHistCurrentPos").html(currentPageIndex.toString()+"/"+totalPageIndex.toString());
}


function QueryHistContent_onclick(obj) 
{
    window.external.AddToLog('ViewHistoryItem');
	//obj is div.QueryHistItem
	hideQueryHist();
	var content=obj;
	var word="";
	for (var j=0;j<content.childNodes.length;j++)
	{
		if (content.childNodes[j].className=="QueryHistWord")
		{
			word=(content.childNodes[j].innerHTML).ToHtmlDecode();
			break;
		}
	}
	changeInputText(word);
	setTimeout(function(){btn_dictsearch_onclick2();},10);
}

function BtnQueryHistDelete_onclick(obj) 
{
    window.external.AddToLog('DeleteHistoryItem');
	//delete the word
	//1.find the index represent this query
	//obj is img.BtnQueryHistDelete
	var nodes=obj.parentNode.parentNode.childNodes;
	var index=-1;
	for (var i=0;i<nodes.length;i++)
	{
		if (nodes[i].className=="QueryHistIndex")
		{	
			index=parseInt(nodes[i].innerHTML);
			break;
		}
	}
	
	if (isNaN(index)||index<0)
	{//this is impossible to happen
		return;
	}
	//2.call window.external to delete the query
    window.external.DeleteQueryRecItem(index);
	//reload the items in the query history list
	showQueryHistPageContains(index);
}


function BtnQueryHistBack_onclick()
{
    if ($("#BtnQueryHistBack").hasClass('BtnQueryHistBack_D'))
    {
	    return;
	}
    //find the first item in this page,and find out its index
	var index = getQHCurrentPageFirstItemIndex();
    //then
	if (isNaN(index) || index < 0)
	{//this is impossible to happen
	    return;
	}
	showQueryHistPageContains(index - 10);
}

function BtnQueryHistForward_onclick()
{
    if ($("#BtnQueryHistForward").hasClass('BtnQueryHistForward_D'))
    {
	    return;
	}
    //find the first item in this page,and find out its index
	var index = getQHCurrentPageFirstItemIndex();
    //then
	if (isNaN(index) || index < 0)
	{//this is impossible to happen
	    return;
	}
	showQueryHistPageContains(index + 10);
}

function getQHCurrentPageFirstItemIndex()
{
	var index=-1;
	
	var nodes=document.getElementById("QueryHistItems").childNodes;
	for (var i=0;i<nodes.length;i++)
	{
		if (nodes[i].className=="QueryHistItem")
		{
			var item=nodes[i];
			
			for (var j=0;j<item.childNodes.length;j++)
			{
				if (item.childNodes[j].className=="QueryHistIndex")
				{
					index= parseInt(item.childNodes[j].innerHTML.toString());
					break;
				}
			}
			break;
		}
	}
	return index;
}

function BtnQueryHistClear_onclick() 
{
    window.external.AddToLog('ClearSearchHistory');
	//clear all the items
    window.external.ClearQueryNavList();
    window.external.ClearQueryRecList();
	//reload the items in the query history list
	showQueryHistPageContains(0);
}


//~----------------------------------------


function show_ifrm(ifrmID)
{
	hideAutoSuggestion();
	
	var main=document.getElementById("main");
	var ifrms=main.childNodes;

	for (var i=0;i<ifrms.length;i++)
	{
		
		var item = ifrms.item(i);
		if (item.id==ifrmID)
		{
			item.style.display='block';
		}
		else if (item.id!=undefined)
		{
			item.style.display='none';
		}
	}	
}

function searchOfflineDict(query)
{
	var query = query||document.getElementById("input_text").value;

	if (typeof query != "string" || query.length<=0)
	{
		return;
	}

	var lang=isChn(query)?"zh-cn":"en-us";	

	window.external.OfflineDictSearch(lang,query);	
}


//----------------------------------------------------------------------
//btn_bingsearch_onclick
function btn_bingsearch_onclick()
{
    //instrumentation
    window.external.AddToLog('BingSearch');

    var query2 = document.getElementById("input_text").value;
    window.open('https://cn.bing.com/search?mkt=zh-CN&setLang=zh&form=BDCAD1&q=' + encodeURIComponent(query2).substring(0, 1800));
}


//stop the bubble of event
function stopEvent(evt)
{
   var event = evt?evt:window.event;//window.event?window.event:evt;
   if (event.preventDefault) //firefox
   {
	 event.preventDefault();
	 event.stopPropagation();
   } 
   else //ie
   {
	 event.returnValue = false;
   }
} 


//----------------------------------------------------------------------
//detect onmouseout ,onmouseover,and change dlg's transparency respectively.
var bAlreadyOver = false;
function detectOnMouseOutOnMouseOver(evt) 
{
    if (document.body.attachEvent)//ie5+ and other
    {
        document.body.attachEvent("onmouseover", function () { document_onmouseover(evt); });
        document.body.attachEvent("onmouseout", function () { document_onmouseout(evt); });
    }
    else if (document.body.addEventListener) //firefox only
    {
        document.body.addEventListener("onmouseover", function () { document_onmouseover(); }, false);
        document.body.addEventListener("onmouseout", function () { document_onmouseout(); }, false);
    }

    function document_onmouseover(evt) 
	{
        if (!bAlreadyOver) 
		{
            window.external.OnMouseOver();
            bAlreadyOver = true;
        }
    }

    function document_onmouseout(evt) 
	{
        var evt = evt ? evt : window.event;
        var x = evt.clientX;
        var y = evt.clientY;
		
        var w = document.body.clientWidth;
        var h = document.body.clientHeight;
        if (x >= 0 && x < w && y >= 0 && y < h) //eliminate the false onblur event
        {
            //do nothing,just return.
            return false;
        }
        window.external.OnMouseOut();
        bAlreadyOver = false;
    }
}

//------------------------------------------------------
//when click BtnMainMenu ,call cpp to CreateWindow the menu dlg


function BtnMainMenu_onclick()
{
	$('#MainMenu').focus();
	var mainMenu=document.getElementById('Main_Menu');
	if (mainMenu==undefined||mainMenu.style.display=="none")
	{
		showMainMenu();
	}
	else
	{
		hideMainMenu();
	}
}

var bInMain_Menu_Area = false;
function BtnMainMenu_onblur(obj) 
{
    var mainMenu = document.getElementById('Main_Menu');
    if (mainMenu == undefined || mainMenu.style.display == 'none') 
	{
        bInMain_Menu_Area = false;
    }
	
    if (bInMain_Menu_Area) 
	{ 
		obj.focus();
		return false;
	}
    else 
	{ 
        hideMainMenu();
    }
}


//you may call this every time you need to show the main menu,just to make sure 
function createMainMenu()
{
	var ItemString = '\
	<div id="Main_Menu" class="DynamicEle" onmouseenter="bInMain_Menu_Area=true;" onmouseleave="bInMain_Menu_Area=false;">\
		<div class="MainMenu_Item" id="MainMenu_Item1"\
		onmousedown="javascript:Settings_onclick();this.parentNode.style.display=\'none\';" \
		onmouseover="$(this).siblings().removeClass(\'Hovered\');$(this).addClass(\'Hovered\');"\
		onmouseout="$(this).removeClass(\'Hovered\');"\
		>\
			<div class="MainMenuTxt">软件设置</div>\
		</div>\
		<div class="MainMenu_Segment">\
        	<div class="MainMenuTxt"></div>\
        </div>\
		<div class="MainMenu_Item" id="MainMenu_Item4"\
		onmousedown="javascript:About_onclick();this.parentNode.style.display=\'none\';"\
		onmouseover="$(this).siblings().removeClass(\'Hovered\');$(this).addClass(\'Hovered\');"\
		onmouseout="$(this).removeClass(\'Hovered\');"\
		>\
			<div class="MainMenuTxt">关于</div>\
		</div>\
	</div>\
    ';

	var menu=document.getElementById("Main_Menu");
	if (menu==undefined || menu==null)
	{
		var a=document.createElement("div");
		a.innerHTML =ItemString;
		document.body.appendChild(a);
	}
	menu=document.getElementById("Main_Menu");
	menu.style.display="none";
	return;
}

function changeMainMenuPosition()
{
	var BtnMainMenu=document.getElementById("MainMenu");
	var x=getLeft(BtnMainMenu);
	var y=getTop(BtnMainMenu);
	var x2=x+1;
	var y2=y-51;

	var menu=document.getElementById("Main_Menu");
	menu.style.top=y2+'px';
	menu.style.left=x2+'px';

	return;
}

function showMainMenu()
{
	createMainMenu();
	changeMainMenuPosition()
	$('#Main_Menu .MainMenu_Item').removeClass('Hovered');
	var menu=document.getElementById("Main_Menu");
	menu.style.display = "block";
}

function hideMainMenu()
{
	$('#Main_Menu').css('display','none');
}
function toggleMainMenu()
{
	createMainMenu();
	var menu=document.getElementById("Main_Menu");
	if (menu.style.display!="block")
	{
		menu.style.display="block";
	}
	else if (menu.style.display=="block")
	{
		menu.style.display="none";
	}
}


function Settings_onclick()
{
	var obj=document.getElementById("Settings");
	showTab2(obj.className);
}

function CheckUpdate_onclick()
{
	var obj=document.getElementById("CheckUpdate");
	showTab2(obj.className);
}

function FeedBack_onclick()
{
    window.open('http://bing.msn.cn/dict/feedback/web?p=pc&v=3.5.1');
}

function About_onclick()
{
	var obj=document.getElementById("About");
	showTab2(obj.className);
}

function ChangeSkin_onclick()
{
	window.external.SuspendHooks(100);
	var obj=document.getElementById("ChangeSkin");
	showTab2(obj.className);
	GetAllSkins();
}

function Help_onclick()
{
	if($('#help_page').attr('src') == ''){$('#help_page').attr('src','HelpPage.html');}
	var obj=document.getElementById("Help");
	showTab2(obj.className);
	
	window.external.AddToLog('Help_onclick');
}


function BtnExtendedApp_onclick()
{
	var obj=document.getElementById("ExApp");
	showTab2(obj.className);
}
function BtnMsnToday_onclick() 
{
	window.external.ShowMSNToday();
}

function BtnPluginItem_onclick(obj)
{
	var itemName=$(obj).attr('id');
	window.external.OpenPlugin(itemName,'');
	window.external.AddToLog(itemName);
}

function BtnPromoteItem_onclick(obj)
{
	if ($('#QRCode_mask').css('display')!='none')
	{
		hideQRCode();
	}
	else 
	{
		showQRCode(obj);
	}
}

function showQRCode(obj)
{
	$('#QRCode_image').css('background-image','url('+$(obj).find('.exapp-item-qrcode').html()+')');
	$('#QRCode_text').html('扫描二维码，下载' + $(obj).find('.exapp-item-title').html()).unbind().bind(
	{
		'click':function()
		{
			var url = $(obj).find('.exapp-item-downloadurl').html().Trim();

			if (url.IsUrl())
			{
				window.open(url);
			}
		}
	});
	$('#QRCode_mask').css('display','block');
	
	$('.li_5 .SettingArea').bind("scroll",updateQRCodeMask).bind("resize",updateQRCodeMask).scroll();
	
	var itemName=$(obj).attr('id');
	window.external.AddToLog('ShowPromoteApp:'+itemName);
}

function updateQRCodeMask() 
{
	if ($('#QRCode_mask').css('display')!='none')
	{
		var scrollTop=$(this).scrollTop();
		var height=$(this).height();
		$(this).find('#QRCode_mask').css({'top':scrollTop>50?scrollTop-50:0}).height(scrollTop>50?height:height-50+scrollTop);
		$(this).find('#QRCode').css({'left':$(this).width()*0.5,'margin-top':scrollTop>50?-150+25:-150+scrollTop*0.5});
	}
}

function hideQRCode()
{
	$('#QRCode_mask').css('display','none');;
}

function getPromoteAppItems()
{
	var xmlhttp;
	try
	{
		if (window.XMLHttpRequest)
		{
			//code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			//code for IE5, IE6
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	catch(e)
	{
		//FAIL: on creating xmlHttpRequest
		return;
	}
	
	var url = 'https://dictionary.blob.core.chinacloudapi.cn/app/pc/promotes' + '?timestamp=' + (new Date()).getTime();

	xmlhttp.open("GET",url,true); 
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState == 0)
		{
			if (xmlhttp.status == 0)
			{
				rawResponseText = xmlhttp.responseText; //store the raw reponseText for futrue use.
				var resTxt = xmlhttp.responseText;

				var newTxt = resTxt.replace(/\n/g,'');
				var resultObj = eval(newTxt);
				processPromoteAppItems(resultObj);
			}
			else
			{
				//FAIL: on getting server response
				return;
			}
		}
	}
	xmlhttp.send();
}

function processPromoteAppItems(resultObj)
{
	var items='';
	$(resultObj).each(function(i, promoteItem)
	{
		var item ='\
		<div id="'+promoteItem["PromoteAppID"]+'" class="exapp-item promote-app-item" title="'+promoteItem["PromoteAppName"]+'"\
		onclick="BtnPromoteItem_onclick(this);"\
		onmouseenter="$(this).siblings().removeClass(\'hovered\');$(this).addClass(\'hovered\');"\
		onmouseleave="$(this).siblings().removeClass(\'hovered\');$(this).removeClass(\'hovered\');"\
		>\
			<div id="exapp-item-img"'+i+' class="exapp-item-img" style="background-image:url('+promoteItem["PromoteAppIconUrl"]+');\
			_background-image:none;\
			_filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+promoteItem["PromoteAppIconUrl"]+'\');">\
			</div>\
			<div class="exapp-item-qrcode" style="display:none;">\
			'+promoteItem["PromoteAppQRCodeImgUrl"]+'\
			</div>\
			<div class="exapp-item-downloadurl" style="display:none;">\
			'+promoteItem["PromoteAppDownloadUrl"]+'\
			</div>\
			<div class="exapp-item-txt">\
				<div class="exapp-item-title">\
				'+promoteItem["PromoteAppName"]+'\
				</div>\
				<div class="exapp-item-intro">\
				'+(promoteItem["PromoteAppDsc"]!=''?promoteItem["PromoteAppDsc"]:'居家旅行，必备神器')+'\
				</div>\
			</div>\
		</div>\
		';
		items+=item;
		
		var img = new Image(); //pre-load     
    	img.src = promoteItem["PromoteAppQRCodeImgUrl"]; 
	});
	if ($('#exapp-items .promote-app-item').length<=0)
	{
		$('#exapp-items').html($('#exapp-items').html()+items);
		
		//detectContextArea
		$("#exapp-items #NewWordList").bind("mouseenter",function(){ContextArea=8;});
		$("#exapp-items #NewWordList").bind("mouseleave",function(){ContextArea=0;});
		$("#exapp-items #MSFlashCard").bind("mouseenter",function(){ContextArea=9;});
		$("#exapp-items #MSFlashCard").bind("mouseleave",function(){ContextArea=0;});
		$("#exapp-items #FMRadio").bind("mouseenter",function(){ContextArea=10;});
		$("#exapp-items #FMRadio").bind("mouseleave",function(){ContextArea=0;});
		$("#exapp-items #WordChallenge").bind("mouseenter",function(){ContextArea=11;});
		$("#exapp-items #WordChallenge").bind("mouseleave",function(){ContextArea=0;});
		$("#exapp-items #OralEnglish").bind("mouseenter",function(){ContextArea=12;});
		$("#exapp-items #OralEnglish").bind("mouseleave",function(){ContextArea=0;});
		
		$("#exapp-items .promote-app-item").bind("mouseenter",function(){ContextArea=32;CurPromoteAppId=this.id;});
		$("#exapp-items .promote-app-item").bind("mouseleave",function(){ContextArea=0;CurPromoteAppId='';});
	}
	
}


function HoverSelectOnOffChange(id) 
{
	if (id == 'HoverTranslate') 
	{
		BtnHoverTranslate_onclick();
	}
	else if (id == 'SelectTranslate')
	{
		BtnSelectTranslate_onclick();
	}
	else
	{
		//do nothing
	}
}

function BtnHoverTranslate_onclick()
{
    if ($('#HoverTranslate').hasClass('HoverTranslate_D'))
    {
	    window.external.AddToLog('EnableHover');
	    EnableHoverTranslate();
	}
    else if ($('#HoverTranslate').hasClass('HoverTranslate_E'))
    {
	    window.external.AddToLog('DisableHover');
	    DisableHoverTranslate();
	}
}

function EnableHoverTranslate() 
{
    $('#HoverTranslate').attr('class','HoverTranslate_E normal_ba').attr('title', '取词已启用');
    window.external.SettingOnChange("hover_select_translate", "turn_on_hover_translate", "true");
}

function DisableHoverTranslate() 
{
    $('#HoverTranslate').attr('class','HoverTranslate_D').attr('title', '取词未启用');
    window.external.SettingOnChange("hover_select_translate", "turn_on_hover_translate", "false");
}

function BtnSelectTranslate_onclick()
{
	if ($('#SelectTranslate').hasClass('SelectTranslate_D'))
	{
	    window.external.AddToLog('EnableSelect');
	    EnableSelectTranslate();
	}
	else if ($('#SelectTranslate').hasClass('SelectTranslate_E'))
	{
	    window.external.AddToLog('DisableSelect');
	    DisableSelectTranslate();
	}
}

function EnableSelectTranslate() 
{
    $('#SelectTranslate').attr('class','SelectTranslate_E normal_ba').attr('title', '划译已启用');
    window.external.SettingOnChange("hover_select_translate", "turn_on_select_translate", "true");
}

function DisableSelectTranslate() 
{
    $('#SelectTranslate').attr('class','SelectTranslate_D').attr('title', '划译未启用');
    window.external.SettingOnChange("hover_select_translate", "turn_on_select_translate", "false");
}


//-------------------------------
function SetTopWindow()
{
	window.external.SetTopWindow();
}

//获取元素的纵坐标 
function getTop(e)
{ 
	var offset=e.offsetTop; 
	if (e.offsetParent!=null) offset+=getTop(e.offsetParent); 
	return offset; 
} 
//获取元素的横坐标 
function getLeft(e)
{ 
	var offset=e.offsetLeft; 
	if (e.offsetParent!=null) offset+=getLeft(e.offsetParent); 
	return offset; 
} 

//获取所有class==n的元素
function getElementsByClassName(n) 
{ 
	var classElements = [] , allElements = document.getElementsByTagName('*'); 
	for (var i=0; i< allElements.length; i++ ) 
	{ 
		if (allElements[i].className == n ) 
		{ 
			classElements[classElements.length] = allElements[i]; //某类集合
		} 
	} 
	return classElements; 
}

//获取非内联样式
function getRealStyle(el,cssName)
{
	var len=arguments.length, sty, f, fv;
	'currentStyle' in el ? sty=el.currentStyle : 'getComputedStyle' in window ? sty=window.getComputedStyle(el,null) : null; 
	
	if (cssName==="opacity" && document.all)
	{
		f = el.filters;
		f && f.length>0 && f.alpha ? fv=f.alpha.opacity/100 : fv=1;
		return fv;
	}
	
	cssName==="float" ? document.all ? cssName='styleFloat' : cssName='cssFloat' : cssName;
	sty = (len==2) ? sty[cssName] : sty;
	return sty;
} 

//内存回收,every 60 seconds
window.setInterval(
function gc(){ if (document.all) CollectGarbage(); }, 
60000
); 


function setMsnTodayStatus(status)
{
	if (status == 'true')
	{
		$('.li_3 #open_msntoday').attr('checked', true);
	}
	else if (status == 'false')
	{
		$('.li_3 #open_msntoday').attr('checked', false);
	}
}
	

function SettingCheckBoxOnChange(settingSection,obj) 
{
    SaveSettingSuccessfully();
    var eventName;
    switch (obj.id) {
        case 'auto_check_update':
            eventName = 'AutoUpdate';
            break;
        case 'open_at_startup':
            eventName = 'AutoRun';
            break;
        case 'minimizetotray_at_startup':
            eventName = 'StartToTray';
            break;
        case 'open_msntoday':
            eventName = 'ShowToday';
            break;
        case 'check_homepage_search':
            eventName = 'CheckHP';
            break;
        case 'minimizetotray_at_close':
            eventName = 'CloseToTray';
            break;
        case 'remember_windowplacement':
            eventName = 'RememberWindowPlacement';
            break;
        case 'show_hide_with_ctrl':
            eventName = 'DoubleCtrl';
            break;
        case 'minimode_remember_windowplacement':
            eventName = 'MiniModeRememberWindowPlacement';
            break;
        case 'minimode_show_hide_with_alt':
            eventName = 'MiniModeDoubleAlt';
            break;
        case 'open_mousegesture_hotkey':
            eventName = 'MouseGesture';
            break;
        case 'open_chinese_hover_translate':
            eventName = 'ChineseHover';
            break;
        case 'open_ui_hover_translate':
            eventName = 'SystemHover';
            break;
        case 'show_select_translate_icon':
            eventName = 'ShowIcon';
            break;

    }
	if (obj.checked==true)
	{
	    window.external.SettingCheckBoxOnChange(settingSection, obj.id, "true");
	    window.external.AddToLog('Enable' + eventName);
	}
	else
	{
	    window.external.SettingCheckBoxOnChange(settingSection, obj.id, "false");
	    window.external.AddToLog('Disable' + eventName);
	}
}


function SettingTextOnChange(settingSection,obj) 
{
	window.external.SettingTextOnChange(settingSection,obj.id,obj.value);
}

function SettingSelectOnChange(settingSection,obj) 
{
    SaveSettingSuccessfully();
    if (obj.id == 'hover_manner' || obj.id == 'select_manner')
    {
        window.external.AddToLog(obj.value);
    }
    
	window.external.SettingSelectOnChange(settingSection,obj.id,obj.value);
}
function SettingOnChange(settingSection,obj)
{
	window.external.SettingOnChange(settingSection,obj.id,obj.value);
}

function RestoreDefSetting(groupName)
{
	SaveSettingSuccessfully();
	switch(groupName)
	{
	case 'general':
		$('.li_3 input#open_at_startup').attr('checked',true).click().attr('checked',true);
		$('.li_3 input#minimizetotray_at_startup').attr('checked',false).click().attr('checked',false);
		$('.li_3 input#open_msntoday').attr('checked',true).click().attr('checked',true);
		$('.li_3 input#check_homepage_search').attr('checked',true).click().attr('checked',true);
		$('.li_3 input#follow_system_dpi').attr('checked',true).click().attr('checked',true);
		break;
		
	case 'main':
		$('.li_3 input#main_auto_pron').attr('checked',false).click().attr('checked',false);
		$('.li_3 input#main_show_at_topmost').attr('checked',false).click().attr('checked',false);
		$('.li_3 input#minimizetotray_at_close').attr('checked',true).click().attr('checked',true);
		$('.li_3 input#remember_windowplacement').attr('checked',true).click().attr('checked',true);
		$('.li_3 input#show_hide_with_ctrl').attr('checked',true).click().attr('checked',true);
		$('.li_3 input#show_hide_with_hotkey').val('无');window.external.SetHotkey('show_hide_with_hotkey', false, false, false, 0);
		break;
		
	case 'minimode':
		$('.li_3 input#minimode_auto_pron').attr('checked',false).click().attr('checked',false);
		$('.li_3 input#minimode_remember_windowplacement').attr('checked',true).click().attr('checked',true);
		$('.li_3 input#minimode_show_hide_with_alt').attr('checked',true).click().attr('checked',true);
		$('.li_3 input#minimode_show_hide_with_hotkey').val('无');window.external.SetHotkey('minimode_show_hide_with_hotkey', false, false, false, 0);
		break;
		
	case 'hover':
		$('.li_3 input#hover_auto_pron').attr('checked',false).click().attr('checked',false);
		$('.li_3 input#open_mousegesture_hotkey').attr('checked',true).click().attr('checked',true);
		$('.li_3 input#open_chinese_hover_translate').attr('checked',true).click().attr('checked',true);
		$('.li_3 input#open_ui_hover_translate').attr('checked',true).click().attr('checked',true);
		$('.li_3 input#open_ocr').attr('checked',false).click().attr('checked',false);
		$('.li_3 input#hover_translate_hotkey').val('无');window.external.SetHotkey('hover_translate_hotkey', false, false, false, 0);
		$('.li_3 select#hover_manner option[value="mouse"]').attr('selected',true).change();
		break;
		
	case 'select':
		$('.li_3 input#select_auto_pron').attr('checked',false).click().attr('checked',false);
		$('.li_3 input#show_select_translate_icon').attr('checked', true).click().attr('checked', true);
		$('.li_3 input#trigger_select_by_dbclick').attr('checked', true).click().attr('checked', true);
		$('.li_3 input#select_translate_hotkey').val('无');window.external.SetHotkey('select_translate_hotkey', false, false, false, 0);
		$('.li_3 select#select_manner option[value="select"]').attr('selected',true).change();
		break;
	}
}

function SettingGetValue(settingSection,key)
{
	return window.external.SettingGetValue(settingSection,key);
}

function SetProxy_onclick()
{
	if ($(".li_3 #open_proxy").attr("checked")=="checked")
	{
		var strServer,strPort,strUsername,strPassword;
		$(".li_3 #ip").val($(".li_3 #ip").val().Trim());
		$(".li_3 #port").val($(".li_3 #port").val().Trim());
		$(".li_3 #user_name").val($(".li_3 #user_name").val().Trim());
		$(".li_3 #password").val($(".li_3 #password").val().Trim());
		strServer=$(".li_3 #ip").val()==null||$(".li_3 #ip").val()==""?" ":$(".li_3 #ip").val();
		strPort=$(".li_3 #port").val()==null||$(".li_3 #port").val()==""?"80":$(".li_3 #port").val();
		strUsername=$(".li_3 #user_name").val()==null||$(".li_3 #user_name").val()==""?" ":$(".li_3 #user_name").val();
		strPassword=$(".li_3 #password").val()==null||$(".li_3 #password").val()==""?" ":$(".li_3 #password").val();
		window.external.EnableProxy(strServer,strPort,strUsername,strPassword);
	}
	else
	{
		window.external.DisableProxy();
	}
}
function set_open_proxy(value)
{
	if (value==null || value=="unchecked")
	{
		$(".li_3 #open_proxy").attr("checked",false);
	}
	else if (value=="checked")
	{
		$(".li_3 #open_proxy").attr("checked",true);
	}
}

function TestProxy_onclick() 
{
	var strServer,strPort,strUsername,strPassword;
	$(".li_3 #ip").val($(".li_3 #ip").val().Trim());
	$(".li_3 #port").val($(".li_3 #port").val().Trim());
	$(".li_3 #user_name").val($(".li_3 #user_name").val().Trim());
	$(".li_3 #password").val($(".li_3 #password").val().Trim());
	strServer=$(".li_3 #ip").val()==null||$(".li_3 #ip").val()==""?" ":$(".li_3 #ip").val();
	strPort=$(".li_3 #port").val()==null||$(".li_3 #port").val()==""?"80":$(".li_3 #port").val();
	strUsername=$(".li_3 #user_name").val()==null||$(".li_3 #user_name").val()==""?" ":$(".li_3 #user_name").val();
	strPassword=$(".li_3 #password").val()==null||$(".li_3 #password").val()==""?" ":$(".li_3 #password").val();
	//$(".li_3 #connect_proxy").attr("disabled",true);
	window.external.TestProxy(strServer,strPort,strUsername,strPassword);	
}

function port_validate(evt)
{
    $(".li_3 #port").val($(".li_3 #port").val().replace(/\D/g, ''));

	if (parseInt($(".li_3 #port").val())<0||parseInt($(".li_3 #port").val())>65535)
	{
		$(".li_3 #port").val($(".li_3 #port").val().replace(/.$/g,''));
	}
}


function translate_do_onclick() 
{
	if ($('#translate_input_text').val().Trim()==''||$('#translate_input_text').hasClass('translate_input_text_empty'))
	{
		$('#translate_warning').css({'opacity':0,'display':'block'})
		.animate({'opacity':1},200)
		.delay(500).animate({'opacity':0},200,function(){ $('#warning').css('display','none');} );
		return;
	}
    //init state:hide offline,show online with blank page
	$("#translate_result_online").css("display", "none");
	$("#translate_result_offline").css("display","block");	
	$("#translate-timeout", window.frames["translate_result_offline"].document).css("display", "none");
	$("#translate-loading", window.frames["translate_result_offline"].document).css("display", "none");
	ShowHideTranslatedOptions('hide');
	
	//get query
	var query=$('#translate_input_text').val().Trim();
	if (query.length <= 0)
	{
	    return;
	}
	
	window.external.AddToLog('StartTranslate');
	
	if (query.IsIP()||query.IsUrl())
	{
		var from=$('#translate_from .TranslateQueryLang').html();
		if (from=='auto-detect'){from='';}
		var to=$('#translate_to .TranslateQueryLang').html();
		window.open('http://www.microsofttranslator.com/bv.aspx?from='+from+'&to='+to+'&a='+encodeURIComponent(query));
		
		window.external.AddToLog('DoTranslate:WebPageTranslate');
		return;
	}

	window.external.AddToLog('DoTranslate:TextTranslate');
	$("#translate_result_online").css("display", "none")
	$("#translate_result_offline").css("display", "block");
	$("#translate-timeout", window.frames["translate_result_offline"].document).css("display", "none");
	$("#translate-loading", window.frames["translate_result_offline"].document).css("display", "block");

    //-----------------------------------------------//
	var from=$('#translate_from .TranslateQueryLang').html();
	if (from=='auto-detect'){from='';}
	var to=$('#translate_to .TranslateQueryLang').html();
	window.frames["translate_result_online"].window.translateTxt(from,to,query);
	window.external.MySetTimer("Timer_TranslateTimeout");
}

function TranslateTimeout()
{
    $("#translate_result_online").css("display", "none");
    $("#translate_result_offline").css("display", "block");
    $("#translate-loading", window.frames["translate_result_offline"].document).css("display", "none");
    $("#translate-timeout", window.frames["translate_result_offline"].document).css("display", "block");
	ShowHideTranslatedOptions('hide');
}


function TranslateSuccess()
{
    $("#translate_result_online").css("display", "block");
	$("#translate_result_offline").css("display","none");
	
	translate_wordalign_updatestatus();
}

function ShowHideTranslatedOptions(show) 
{
    if (show == 'show')
    {
        $("#translate_options").css("display", "block");
    }
    else {
        $("#translate_options").css("display", "none");
    }

}


function translate_clear_onclick()
{
	//clear input
    $('#translate_input_text').val('');
	
	//init state:hide offline,show online with blank page
	$("#translate_result_online").css("display", "none");
	$("#translate_result_offline").css("display", "block");
	$("#translate-timeout", window.frames["translate_result_offline"].document).css("display", "none");
	$("#translate-loading", window.frames["translate_result_offline"].document).css("display", "none");
	ShowHideTranslatedOptions('hide');

	//get focus back to input
	$('#translate_input_text').focus().select();
}

/*
* Timer类
* 方法: 
* 构造函数: Timer(间隔, 回调函数)
* 清除: clear()
* 使用示例: var timer = new Timer(200, function(t) {alert('nana'); t.clear();} );    
*/
function Timer(interval, functor) 
{
	this.id = 'timer_'+Math.ceil(Math.random()*900000000+100000000);
	eval(this.id+' = this;');
	this.tid = setInterval(this.id+'.callback()',interval)
	this.functor = functor;
	this.callback = function(){
		this.functor(this);
	}
	this.clear = function(){
		clearInterval(this.tid);
	}
}

//-----------tab------------

//显示标签页
var lastTabClassName="li_1";//default value is the dictionary tab.

function showTab2(liname) //this,this.className
{
    //switch to the targeted tab
    switchToTab(liname);

	//copy query between dict and sentence input box if needed
	if (lastTabClassName=='li_1' && liname=='li_2' 
	&& last_sent_input_text != last_input_text 
	&& last_input_text.Trim().length>0)
	{
	    var word = $('#input_text').val();
	    changeSentInputText(word);
	    setTimeout(function () { sent_dictsearch_onclick(); }, 10);
	}
	else if (lastTabClassName=='li_2' && liname=='li_1' 
	&& last_sent_input_text != last_input_text 
	&& last_sent_input_text.Trim().length>0)
	{
	    var word = $('#sent-input-text').val();
	    changeInputText(word);
	    setTimeout(function () { btn_dictsearch_onclick2(); }, 10);
	}

}

//when back button is clicked,go back to the last activated tab
function BtnBack_onclick()
{
	switchToTab(lastTabClassName);
}

function switchToTab(tabClassName)
{
    var tabObj = $('div.tab_control_tag ul li.' + tabClassName)[0];
    if (tabObj)
    {
        $('.DynamicEle').css('display','none');
        //focus the tab in order to hide AS,QH,and menus.
        $(tabObj).focus();

        //do nothing if target is already shown
        if ($(tabObj).hasClass('selected')) return;

        //change the background img of tabs
        $('div.tab_control_tag ul li img').attr('class', 'Tab_U');
        $(tabObj).find('img').attr('class', 'Tab_S');

        //hide the formerly shown 
        lastTabClassName = CurrentTab();
        $('div.tab_control_tag ul li.selected').attr('class', lastTabClassName);
        $('div.tab_control_content div.' + lastTabClassName).css('display', 'none');

        //show the target
        tabObj.className += ' selected';
        $('div.tab_control_content div.' + tabClassName).css('display', 'block');


        /****************************************************************/

        //get promote app items if there's none present
        if (tabClassName == 'li_5' && $('div#exapp-items div.promote-app-item').length <= 0)
        {
            getPromoteAppItems();
        }
		
		if(tabClassName == 'li_4')
		{
			window.external.UpdateTranslateLang();
		}

        //Set Focus for the inputbox
        TryFocusInput();

        //trick to fix ie6 bug
        if (ie != false && ie <= 6)
        {
            window.external.AdjustWin(0);
        }
    }
}

//return the tab being selected
function  CurrentTab()
{
    return $('div.tab_control_tag ul li.selected').attr('class').replace(' selected', '');
}

function SwitchTabs()
{
    var curTab = CurrentTab();
    if (curTab == 'li_1')
    {
        switchToTab('li_2');
    }
    else if (curTab == 'li_2')
    {
        switchToTab('li_4');
    }
    else if (curTab == 'li_4')
    {
        switchToTab('li_5');
    }
    else if (curTab == 'li_5')
    {
        switchToTab('li_1');
    }
    else
    {
        switchToTab('li_1');
    }
}



var HotKeyIdList = ["select_translate_hotkey", "hover_translate_hotkey", "show_hide_with_hotkey","minimode_show_hide_with_hotkey"];
var originalKeyString = '';

var Shortcut = {

    ShowShortcut: function (eleId) {
        var ele;
        if (typeof eleId == 'string') ele = document.getElementById(eleId);
        if (ele) {
            e = window.event;

            var invaild_keys = {
                27: 'Escape',
                9: 'Tab',
                32: 'Space',
                13: 'Enter',
                8: 'Backspace',
                46: 'Delete',
                93: 'Menu',
                91: 'WinL',
                92: 'WinR'
            }
            var delete_keys =
            {
                8: 'Backspace',
                46: 'Delete',
                110: 'Num Del'
            }

            //Special Keys - and their codes
            var special_keys = {

                192: '`',

                145: 'Scroll Lock',
                20: 'Caps Lock',
                144: 'Num Lock',

                19: 'Pause',

                45: 'Insert',
                36: 'Home',

                35: 'End',

                33: 'Page Up',
                34: 'Page Down',

                37: 'Left',
                38: 'Up',
                39: 'Right',
                40: 'Down',

                96: 'Num 0',
                97: 'Num 1',
                98: 'Num 2',
                99: 'Num 3',
                100: 'Num 4',
                101: 'Num 5',
                102: 'Num 6',
                103: 'Num 7',
                104: 'Num 8',
                105: 'Num 9',
                106: 'Num *',
                107: 'Num +',
                108: 'Num Separator',
                109: 'Num -',
                110: 'Num Del',
                111: 'Num /',

                186: ';',
                187: '=',
                188: ',',
                189: '-',
                190: '.',
                191: '/',
                219: '[',
                220: '\\',
                221: ']',
                222: '\''


            }

            var indivdual_keys = {
                112: 'F1',
                113: 'F2',
                114: 'F3',
                115: 'F4',
                116: 'F5',
                117: 'F6',
                118: 'F7',
                119: 'F8',
                120: 'F9',
                121: 'F10',
                122: 'F11',
                123: 'F12'
            }
            var modifiers_keys = {
                16: 'Shift',
                17: 'Ctrl',
                18: 'Atl'

            }


            //must have modifier
            if (e.ctrlKey || e.shiftKey || e.altKey) {

                var result = "";
                var character = "";
                var code;
                if (e.ctrlKey) result += "Ctrl + ";
                if (e.shiftKey) result += "Shift + ";
                if (e.altKey) result += "Alt + ";
                if (e.metaKey) result += "Meta + ";
                ele.onkeyup = function () {

                    if (result.length == 0 || result.substr(result.length - 1, 1) == ' ') {
                        this.value = "无";

                    }
                    if (this.value == "无") {
                        window.external.SetHotkey(this.id, false, false, false, 0);
                        return false;
                    }
                }
                //Find Which key is pressed,      
                if (e.keyCode) code = e.keyCode;

                if (modifiers_keys[code]) {
                    ele.value = result;
                    return false;
                }
                else if (invaild_keys[code] || code == 229) {
                    ele.value = "无";
                    return false;
                }
                else if (special_keys[code]) {
                    character = special_keys[code];
                }
                else if (indivdual_keys[code]) {
                    character = indivdual_keys[code];
                }
                else {
                    character = String.fromCharCode(code);
                }

                if (code == 188) character = ","; //If the user presses , when the type is onkeydown
                if (code == 190) character = "."; //If the user presses , when the type is onkeydown

                result += character;
                if (Shortcut.CheckHotkeyIsValid(result)) {
                    ele.value = result;
                    for (var index in HotKeyIdList) {
                        if (window.external.GetHotkeyStringFromId(HotKeyIdList[index]) == ele.value) {
                            ele.value = '无';
                            return false;
                        }
                    }
                    window.external.SetHotkey(ele.id, e.ctrlKey, e.shiftKey, e.altKey, code);
                    return false;
                }
                ele.value = "无";
            }
            else {
                if (e.keyCode) code = e.keyCode;

                if (delete_keys[code]) {
                    ele.value = "无";
                    ele.onkeyup = function () {
                        window.external.SetHotkey(this.id, false, false, false, 0);
                        return false;
                    }
                }
                if (indivdual_keys[code]) {
                    ele.value = indivdual_keys[code];
                    originalKeyString = window.external.GetHotkeyStringFromId(ele.id);
                    for (var index in HotKeyIdList) {
                        if (window.external.GetHotkeyStringFromId(HotKeyIdList[index]) == ele.value) {
                            ele.value = originalKeyString;
                            return false;
                        }
                    }
                    ele.onkeyup = function () {
                        window.external.SetHotkey(this.id, false, false, false, code);
                        return false;
                    }
                }

            }
            return false;
        }

    },
    Invalid_hotkeys: {
        "Ctrl + C": 1,
        "Ctrl + V": 1,
        "Ctrl + Z": 1,
        "Ctrl + A": 1,
        "Ctrl + F": 1,
        "Alt + F4": 1
    },
    CheckHotkeyIsValid: function (hotkey) {

        if (typeof hotkey == 'string') {
            if (!Shortcut.Invalid_hotkeys[hotkey])
                return true;
        }
        return false;
    }

}
var isHotKeySetting = false;
function MarkOnBlur() 
{
    isHotKeySetting = false;
}

function MarkOnFocus() 
{
    isHotKeySetting = true;
}

function IsInHotkeyInputBox() 
{
    if (isHotKeySetting) 
	{
        return "true";
    }
    else 
	{
        return "false";
    }
}

function CheckHotkeyIsValid(hotkey) 
{

    var Invalid_hotkeys = [
        "Ctrl + C",
        "Ctrl + V",
        "Ctrl + Z",
        "Ctrl + A",
        "Ctrl + F"
    ];
    for (var i in Invalid_hotkeys) 
	{
        if (hotkey == Invalid_hotkeys[i])
            return false;
    }
    return true;
}

function initSettings()
{
    setTimeout(function ()
    {
        initMainSettings();
        window.external.Initialize();
    }, 500);
}

function initMainSettings()
{
    var inputButtons = document.getElementsByTagName("input");

    //init checkbox status checked or unchecked
    for (var i = 0; i < inputButtons.length; ++i) 
	{
        if (inputButtons[i].type == "checkbox")
        {
            inputButtons[i].checked = Boolean(window.external.GetCheckboxStatus(inputButtons[i].id));
        }
        else if (inputButtons[i].type == "text")
        {
            for (var index in HotKeyIdList) 
            {
                if (inputButtons[i].id == HotKeyIdList[index]) 
                {
                    inputButtons[i].value = window.external.GetHotkeyStringFromId(inputButtons[i].id);
                }
            }
			
            //initialize proxy values
            var proxyArr = ["ip", "user_name", "port"];
            for (var index in proxyArr) 
            {
                if (inputButtons[i].id == proxyArr[index]) 
                {
                    inputButtons[i].value = window.external.GetProxySetting(inputButtons[i].id);
                }
            }
        }
        else if (inputButtons[i].type == "password") 
        {
            //proxy port number
            if (inputButtons[i].id == "password") 
            {
                inputButtons[i].value = window.external.GetProxySetting(inputButtons[i].id);
            }
        }
        else
        {
        }
    }

    //init mouse capture mode value
    var captureName = "mouse";
    switch (window.external.GetCaptureMode())
	{
        case 0:
            captureName = "mouse";
            break;
        case 2:
            captureName = "ctrl_mouse";
            break;
        case 4:
            captureName = "shift_mouse";
            break;
        case 1:
            captureName = "alt_mouse";
            break;
    }

    $("select#hover_manner option[value='"+ captureName + "']").attr('selected', true);
	
    //init select translate mode value
    var selectName = "select";
    switch (window.external.GetSelectMode())
    {
        case 0:
            selectName = "select";
            break;
        case 2:
            selectName = "ctrl_select";
            break;
		case 4:
            captureName = "shift_select";
            break;
        case 1:
            captureName = "alt_select";
            break;
    }

    $("select#select_manner option[value='" + selectName + "']").attr('selected', true);

}


function GetFocus(id) 
{
    var ele = document.getElementById(id);
    if (ele && document.activeElement.id!=id) 
	{
        ele.focus();
        ele.select();
    }
}

function TryFocusInput()
{
	setTimeout(function () 
	{
		var currentTab = CurrentTab();
		if (currentTab.toLowerCase()=='li_1' && document.activeElement.id!='input_text')//dict
		{
			GetFocus('input_text');
		}
		else if (currentTab.toLowerCase()=='li_2' && document.activeElement.id!='sent-input-text')//sentence
		{
			GetFocus('sent-input-text');
		}
		else if (currentTab.toLowerCase() == 'li_4' && document.activeElement.id != 'translate_input_text' && !$('#translate_input_text').hasClass('translate_input_text_empty'))//translate
		{
			var obj = document.getElementById('translate_input_text');
			
			obj.focus();
			var len = obj.value.length;
			if (document.selection) 
			{
				var sel = obj.createTextRange();
				sel.moveStart('character',len);
				sel.collapse();
				sel.select();
			} 
			else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') 
			{
				obj.selectionStart = obj.selectionEnd = len;
			}
		}
	},0);
}

function BtnCheckUpdateNow_onclick() 
{
    window.external.AddToLog('CheckUpdateNow');
	window.external.CheckUpdateNow();
}


function initIframeUrl()
{
    $("#home_page_online").attr("src", "../Common/blank.html");
	$("#home_page_online2").attr("src", "../Common/blank.html");
	$("#home_page_offline").attr("src","HomepageOffline.html");
	reloadOnlineHomepage();
	window.external.AddToLog('LoadOnlineHomepageOnLaunch');

	$("#offline_result").attr("src","OfflineResult.html");
	$("#online_result").attr("src","../Common/blank.html");
	
	$("#translate_result_offline").attr("src","TanslateResultOffline.html");
	$("#translate_result_online").attr("src", "TanslateResultOnline.html");
	
	$("#sent-offline-homepage").attr("src", "SentOfflineHomepage.html");
	$("#sent-offline-result").attr("src", "SentOfflineResult.html");
	$("#sent-online-result").attr("src", "../Common/blank.html");
	
	$("#help_page").attr("src","HelpPage.html");

	setTimeout(function ()
	{
	    getPromoteAppItems();
	}, 100);

	setTimeout(function ()
	{
		displayAds();
	},100);
	
}


//------------------------------------------------------------------
function displayAds()
{
	var xmlhttp;
	try
	{
		if (window.XMLHttpRequest)
		{
			//code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			//code for IE5, IE6
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	catch(e)
	{
		//FAIL: on creating xmlHttpRequest
		return;
	}
	
	var url = 'http://wordchallenge.blob.core.windows.net/dictdownload/bingdict_serverside_settings.txt'+ '?timestamp=' + (new Date()).getTime();

	xmlhttp.open("GET",url,true); 
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState == 4)
		{
			if (xmlhttp.status == 200)
			{
				
				rawResponseText = xmlhttp.responseText; //store the raw reponseText for futrue use.
				var resTxt = xmlhttp.responseText;

				var newTxt = resTxt.replace(/\n/g,'');
				var resultObj = eval("("+newTxt+")");
				processAdsSetting(resultObj);
			}
			else
			{
				//FAIL: on getting server response
				return;
			}
		}
	}
	xmlhttp.send();
}

function processAdsSetting(resultObj)
{
	if(resultObj["BannerAds"]["MsnTxtAdDisplay"] == "show_on_startup")
	{
		setTimeout(function ()
		{
			LoadIframe(
			"TxtAdsContent",
			resultObj["BannerAds"]["MsnTxtAdUrl"] + "?timestamp=" + (new Date()).getTime(),
			ShowTxtAd,
			HideTxtAd
			);
		}, resultObj["BannerAds"]["MsnTxtAdDelay"]);
	}
	
	
	if(resultObj["BannerAds"]["MsnImgAdDisplay"] == "show_on_startup" && HasFlash())
	{
		setTimeout(function ()
		{
			LoadIframe(
			"ImgAdsContent",
			resultObj["BannerAds"]["MsnImgAdUrl"] + "?timestamp=" + (new Date()).getTime(),
			ShowImgAd,
			HideImgAd
			);
		}, resultObj["BannerAds"]["MsnImgAdDelay"]);
	}
}
//------------------------------------------------------------------


var currentHomepageId="home_page_offline";
var reloadingOnlineHomepageId="home_page_online";
function showHomepage()
{
	if (currentHomepageId=="home_page_offline"||currentHomepageId=="home_page_online"||currentHomepageId=="home_page_online2")
	{
		show_ifrm(currentHomepageId);
	}
	
	//if current homepage is offline homepage,and network is alive,should try to show the online result.
	if (currentHomepageId=="home_page_offline")
	{
	    reloadOnlineHomepage();
	    window.external.AddToLog('LoadOnlineHomepageOnMeetOfflineHomepage');
	}
}

function reloadOnlineHomepage()
{	
	if (currentHomepageId=="home_page_offline")
	{
		reloadingOnlineHomepageId="home_page_online";
	}
	else if (currentHomepageId=="home_page_online")
	{
		reloadingOnlineHomepageId="home_page_online2";
	}
	else if (currentHomepageId=="home_page_online2")
	{
		reloadingOnlineHomepageId="home_page_online";
	}
	$("#" + reloadingOnlineHomepageId).attr("src","../Common/blank.html");
	$("#" + reloadingOnlineHomepageId).attr("src","https://cn.bing.com/dict/clienthomepagev2?mkt=zh-CN&setLang=zh&form=BDVEHC&ClientVer=BDDTV3.5.1.4320");

	window.external.MySetTimer("Timer_HomepageOnlineTimeout");
}

function getHomepageId(currentOrReloading)
{
	if (currentOrReloading=="currentHomepageId")
	{
		return currentHomepageId;
	}
	else if (currentOrReloading=="reloadingOnlineHomepageId")
	{
		return reloadingOnlineHomepageId;
	}
}

function setCurrentHomepage(home_page_id)
{
	if (home_page_id=="home_page_offline"||home_page_id=="home_page_online"||home_page_id=="home_page_online2")
	{
		currentHomepageId=home_page_id;
		
		//set unused homepage iframes as blank page
		//if (home_page_id!="home_page_offline"){$("#home_page_offline").attr("src","../Common/blank.html");}
		//if (home_page_id!="home_page_online"){$("#home_page_online").attr("src","../Common/blank.html");}
		//if (home_page_id!="home_page_online2"){$("#home_page_online2").attr("src","../Common/blank.html");}
	}

}
//update homepage to currentHomepage if currently homepage should be shown
function updateHomepage()
{
	if ($("#home_page_offline").css("display")!="none"||$("#home_page_online").css("display")!="none"||$("#home_page_online2").css("display")!="none")
	{
		showHomepage();
	}
}


//copy TranslatedTxt to clipboard
function CopyTranslatedTxtToClipboard()
{
    window.external.AddToLog('CopySource');
	window.external.CopyTranslatedTxtToClipboard();
}

var isSaving = false;
function SaveSettingSuccessfully() 
{
    if (isSaving) 
	{
        return;
    }
    isSaving = true;
    $('#settings_saved').css({ 'opacity': 0 });
    $('#settings_saved').css({ 'display': 'block' });
    $('#settings_saved').animate({ opacity: 1 }, 500).delay(1000).animate({ opacity: 0 }, 500, function () { $('#settings_saved').css({ 'display': 'none' }); isSaving = false; });
}

function SetSpecifiedValue(id, value) {
    var ele = document.getElementById(id);
    ele.value = value;
}



//EventUtil
var EventUtil = {
    addHandler: function(oTarget, sEventType, fnHandler){
        if (oTarget.addEventListener) {
            oTarget.addEventListener(sEventType, fnHandler, false);
        } else if (oTarget.attachEvent) {
            oTarget.attachEvent("on" + sEventType, fnHandler);
        } else {
            oTarget["on" + sEventType] = fnHandler;
        }
    },
    removeHandler: function(){
        if (oTarget.removeEventListener) {
            oTarget.removeEventListener(sEventType, fnHandler, false);
        } else if (oTarget.detachEvent) {
            oTarget.detachEvent("on" + sEventType, fnHandler);
        } else {
            oTarget["on" + sEventType] = null;
        }
    },
    getEvent: function(event){
        return event ? event : window.event;
    },
    getTarget: function(event){
        return event.target || event.srcElement;
    },
    preventDefault: function(event){
        if (event.preventDefault){
            event.preventDefault();
        } else {
            event.returnValue = false;
        }
    },
    stopPropagation: function(event){
        if (event.stopPropagation){
            event.stopPropagation();
        } else {
            event.cancelBubble = true;
        }
    },
    getRelatedTarget: function(event){
        if (event.relatedTarget){
            return event.relatedTarget;
        } else if (event.toElement){
            return event.toElement;
        } else if (event.fromElement){
            return event.fromElement;
        } else {
            return null;
        }
    },
    getButton: function(event){
        if (document.implementation.hasFeature("MouseEvents","2.0")){
            return event.button;
        } else {                                                   // IE
            switch (event.button){
                case 0:                                          //什么都没按
                case 1:                                          //按下住鼠标左键
                case 3:                                          //同时按下了鼠标左右键
                case 5:                                          //同时按下了住鼠标左键和中间按钮
                case 7:                                          //同时按下3个鼠标按钮
                    return 0;
                case 2:                                          //按下了鼠标右键
                case 6:                                          //同时按下了鼠标右键和中间按钮
                    return 2;
                case 4:                                          //按下了鼠标中间按钮
                    return 1;
            }
        }
    },
    getCharCode: function(event){
        if (typeof event.charCode == "number"){
            return event.charCode;
        } else {
            return event.keyCode;
        }
    },
    getWheelDelta: function(event){
        if (event.wheelDelta){
            return (client.engine.opera && client.engine.opera < 9.5 ? -event.wheelDelta : event.wheelDelta);
        } else {
            return -event.detail * 40;
        }
    },
    getClipboardText: function(event){
        var clipboardData = (event.clipboardData || window.clipboardData);
        return clipboardData.getData("text");
    },
    setClipboardText: function(event, value){
        if (event.clipboardData){
            return event.clipboardData.setData("text/plain", value);
        } else if (window.clipboardData){
            return window.clipboardData.setData("text", value);
        }
    }
}


//DotNet
function DownloadDotNet() 
{
	window.external.DownloadDotNet();
}

function hideExAppMask()
{
    $('div.tab_control_content  div.exapp-mask').css('display','none');
}

function showExAppMask()
{
    $('div.tab_control_content  div.exapp-mask').css('display','block');
    $('.li_5 .SettingArea').bind("scroll", updateExAppMask).bind("resize", updateExAppMask).scroll();
}



function updateExAppMask()
{
    if ($('div.tab_control_content  div.exapp-mask').css('display') != 'none')
    {
        var scrollTop = $(this).scrollTop();
        var height = $(this).height();
        $(this).find('div.exapp-mask').css({'top': scrollTop > 50 ? scrollTop - 50 : 0 }).height(scrollTop > 50 ? height : height - 50 + scrollTop);
       	$(this).find('div.exapp-mask-content').css({ 'margin-top': scrollTop > 50 ? -180 + 25 : -180 + scrollTop * 0.5 });
    }
} 

function DotNetInstalled()
{
	hideExAppMask();
}

function DotNetNotInstalled()
{
	showExAppMask();
	
	$('div.exapp-mask div.exapp-mask-txt').show().html('您的扩展应用需要.Net Framework才能正常运行。<br/>正在为您下载中，请稍候。');
	$('div.exapp-mask div.exapp-mask-btn').hide();
	$('div.exapp-mask div.exapp-mask-img').show();
}

function DotNetDownloadSuccess()
{
	showExAppMask();
	
	$('div.exapp-mask div.exapp-mask-txt').show().html('您的扩展应用需要.Net Framework才能正常运行。<br/>下载成功，是否立即开始安装？');
	$('div.exapp-mask div.exapp-mask-btn').hide();
	$('div.exapp-mask div#exapp-mask-btn1').show();
	$('div.exapp-mask div.exapp-mask-img').hide();
}


function DotNetDownloadFail()
{
	showExAppMask();
	
	$('div.exapp-mask div.exapp-mask-txt').show().html('您的扩展应用需要.Net Framework才能正常运行。<br/>下载失败，请您点击‘重试下载’按钮，或者点击&nbsp;<a href=\'http://download.microsoft.com/download/0/8/c/08c19fa4-4c4f-4ffb-9d6c-150906578c9e/NetFx20SP1_x86.exe\' target=\'_blank\'>这里</a>&nbsp;手动下载并安装。');
	$('div.exapp-mask div.exapp-mask-btn').hide();
	$('div.exapp-mask div#exapp-mask-btn2').show();
	$('div.exapp-mask div.exapp-mask-img').hide();
		
}

function InstallDotNet()
{
	showExAppMask();
	
	$('div.exapp-mask div.exapp-mask-txt').show().html('您的扩展应用需要.Net Framework才能正常运行。<br/>正在为您安装中，请稍候。');
	$('div.exapp-mask div.exapp-mask-btn').hide();
	$('div.exapp-mask div.exapp-mask-img').show();
	window.external.InstallDotNet();
}


function DotNetInstallSuccess()
{
	hideExAppMask();
}

function DotNetInstallFail()
{
	showExAppMask();
	
	$('div.exapp-mask div.exapp-mask-txt').show().html('您的扩展应用需要.Net Framework才能正常运行。<br/>下载失败，请您点击‘重新安装’按钮，或者点击&nbsp;<a href=\'http://download.microsoft.com/download/0/8/c/08c19fa4-4c4f-4ffb-9d6c-150906578c9e/NetFx20SP1_x86.exe\' target=\'_blank\'>这里</a>&nbsp;手动下载并安装。');
	$('div.exapp-mask div.exapp-mask-btn').hide();
	$('div.exapp-mask div#exapp-mask-btn3').show();
	$('div.exapp-mask div.exapp-mask-img').hide();
	
}




/********skin********/

function GetAllSkins()
{
    window.external.GetAllSkins();
}
function ShowAllSkins(skins)
{
    $("#skin-items").html(skins);
}
function SelectSkinItem(skinName)
{
    $("#skin-items #" + skinName).addClass("selected");
}

function BtnSetSkin_onclick(obj)
{
    if ($(obj).hasClass('selected') == false)
    {
		window.external.SetSkin(obj.id);

		$('div.tab_control_content div#skin-items div.selected').removeClass('selected');
		$(obj).addClass('selected');
		window.external.AddToLog('SetSkin:' + obj.id);
    }
}


/********skin********/
function UpdateSkinForAll()
{
    setTimeout('window.external.UpdateSkin()', 0);
}

var CurSkinModel = "DefaultModel";
var CurSkinColor = "Blue.css";
var CurSkinImage = "";
function GetCurrentSkinModel()
{
    return CurSkinModel;
}

function GetCurrentSkinColor()
{
    return CurSkinColor;
}

function GetCurrentSkinImage()
{
    return CurSkinImage;
}

function UpdateSkinForPage(model, color, image)
{
    CurSkinModel = model;
    CurSkinColor = color;
    CurSkinImage = image;
    $("link#_NewSkinModel").attr("href", "").attr("href", "../../../skin/Model/" + model + "/BingDictDlg/BingDictDlg.css");
    $("link#_NewSkinColor").attr("href", "").attr("href", "../../../skin/Color/" + color + ".css");
    $("link#_NewSkinImage").attr("href", "").attr("href", "../../../skin/Image/" + image + "/BgImg.css");

    window.frames["home_page_offline"].window.UpdateSkinForPage(model, color, image);
    window.frames["offline_result"].window.UpdateSkinForPage(model, color, image);
    window.frames["sent-offline-homepage"].window.UpdateSkinForPage(model, color, image);
    window.frames["sent-offline-result"].window.UpdateSkinForPage(model, color, image);
    window.frames["translate_result_offline"].window.UpdateSkinForPage(model, color, image);
    window.frames["translate_result_online"].window.UpdateSkinForPage(model, color, image);
	window.frames["help_page"].window.UpdateSkinForPage(model, color, image);
}



/*************key board event***************/
function OnKeyDown_PageUpPageDown(para)
{
	OnKeyDown_PageUpPageDown_CheckQueryNav(para);
	OnKeyDown_PageUpPageDown_CheckSentQueryNav(para);
}

function OnKeyDown_PageUpPageDown_CheckQueryNav(para)
{
	if (CurrentTab()!='li_1')
	{
		return;
	}
	
	if (para=='pageup')
	{
		$('#search #back').click();
	}
	else if (para=='pagedown')
	{
		$('#search #forward').click();
	}
	return;
}

function OnKeyDown_PageUpPageDown_CheckSentQueryNav(para)
{
	if (CurrentTab()!='li_2')
	{
		return;
	}
	
	if (para=='pageup')
	{
		$('#sent-search #sent-back').click();
	}
	else if (para=='pagedown')
	{
		$('#sent-search #sent-forward').click();
	}
	return;
}


function OnKeyDown_UpDown(para)
{
	OnKeyDown_UpDown_CheckQueryHist(para);
	OnKeyDown_UpDown_CheckAutoSug(para);
	OnKeyDown_UpDown_CheckSentQueryHist(para);
	OnKeyDown_UpDown_CheckMainMenu(para);
}

function OnKeyDown_UpDown_CheckQueryHist(para)
{
	if (CurrentTab()!='li_1')
	{
		return;
	}
	
	var queryHist=document.getElementById('QueryHist');
	if (queryHist==undefined||queryHist.style.display=="none")
	{
	    return;
	}
	else
	{
		//highlight the next of query hist item, then try to 
		if ($('.QueryHistItem').length>0)
		{
			var query='';
			if ($('.QueryHistItem.Hovered').length>=1)
			{
				if (para=='down')
				{
					var theItem=$('.QueryHistItem.Hovered').next();
					if (theItem.length==0)
					{
						theItem=$('.QueryHistItem').first();
					}
					$('.QueryHistItem.Hovered').removeClass('Hovered');
					theItem.addClass('Hovered');
					query = (theItem.find('.QueryHistWord').html()).ToHtmlDecode();
				}
				else if (para=='up')
				{
					var theItem=$('.QueryHistItem.Hovered').prev();
					if (theItem.length==0)
					{
						theItem=$('.QueryHistItem').last();
					}
					$('.QueryHistItem.Hovered').removeClass('Hovered');
					theItem.addClass('Hovered');
					query = (theItem.find('.QueryHistWord').html()).ToHtmlDecode();
				}
			}
			else
			{
				if (para=='down')
				{
					var theItem=$('.QueryHistItem').first();
					$('.QueryHistItem.Hovered').removeClass('Hovered');
					theItem.addClass('Hovered');
					query = (theItem.find('.QueryHistWord').html()).ToHtmlDecode();
				}
				else if (para=='up')
				{
					var theItem=$('.QueryHistItem').last();
					$('.QueryHistItem.Hovered').removeClass('Hovered');
					theItem.addClass('Hovered');
					query = (theItem.find('.QueryHistWord').html()).ToHtmlDecode();
				}
			}
		
			show_ifrm("offline_result");
			value=query.replace(/&nbsp;/g," ");
			$("#input_text").attr("value", value);
			last_input_text = value;
			setTimeout('searchOfflineDict($("#input_text").attr("value"))',10);
			
		}/*if ($('.QueryHistItem').length>0)*/
		
	}
}

function OnKeyDown_UpDown_CheckAutoSug(para)
{
	if (CurrentTab()!='li_1')
	{
		return;
	}
	
	var queryHist=document.getElementById('AutoSuggestion');
	if (queryHist==undefined||queryHist.style.display=="none")
	{
	    return;
	}
	else
	{
		if (para=='up') //up
		{
		   AutoSugMenuItemUp();
		}
		else if (para=='down') //down
		{
		   AutoSugMenuItemDown();
		}
	}
}
//AutoSugestion response to Up/Down key
var SelectedASItem = -1;
function SetSelectedASItem(index) 
{
    if (index != SelectedASItem) {
        //normalize highlight item
        var autoSuggestion = document.getElementById("AutoSuggestion");
        var ASItems = autoSuggestion.childNodes;
        var i = SelectedASItem;
        if (i != -1) {
            ASItems[i].className = ASItems[i].className.replace(' selected', '');
        }
        SelectedASItem = index;
    }
}

function AutoSugMenuItemUp()
{
	var autoSuggestion=document.getElementById("AutoSuggestion");
	if (autoSuggestion==null||autoSuggestion.style.display=='none')
	{
		return;
	}
	
	var ASItems=autoSuggestion.childNodes;
	var findSelected = false;
	if (SelectedASItem != -1) {
	    findSelected = true;
	    var i = SelectedASItem;
	    ASItems[i].className = ASItems[i].className.replace(' selected', '');
	    while (ASItems[(i + ASItems.length - 1) % (ASItems.length)].nodeType !== 1) {
	        i++;
	    }
	    ASItems[(i + ASItems.length - 1) % (ASItems.length)].className = 'ASItem selected';
	    SelectedASItem = (i + ASItems.length - 1) % (ASItems.length);
	}
	if (!findSelected) {
	    ASItems[(ASItems.length - 1) % (ASItems.length)].className = 'ASItem selected';
	    SelectedASItem = (ASItems.length - 1) % (ASItems.length);
    }
	var value = $("#AutoSuggestion .ASItem.selected div.ASHighlight").html()
	+ $("#AutoSuggestion .ASItem.selected div.ASWord").html();	
	value=value.replace(/&nbsp;/g," ");
	$("#input_text").attr("value", value);
	last_input_text = value;
	 
	setTimeout('searchOfflineDict($("#input_text").attr("value"))',10);

}

function AutoSugMenuItemDown()
{
	var autoSuggestion=document.getElementById("AutoSuggestion");
	if (autoSuggestion==null||autoSuggestion.style.display=='none')
	{
		return;
	}
	
	var ASItems=autoSuggestion.childNodes;
	var findSelected = false;
	if (SelectedASItem != -1) {
	    findSelected = true;
	    var i = SelectedASItem;
	    ASItems[i].className = ASItems[i].className.replace(' selected', '');
	    while (ASItems[(i + 1) % (ASItems.length)].nodeType !== 1) {
	        i++;
	    }
	    ASItems[(i + 1) % (ASItems.length)].className = 'ASItem selected';
	    SelectedASItem = (i + 1) % (ASItems.length);
	}
	if (!findSelected) {
	    ASItems[0].className = 'ASItem selected';
	    SelectedASItem = 0;
	}
	var value=$("#AutoSuggestion .ASItem.selected div.ASHighlight").html()
	+$("#AutoSuggestion .ASItem.selected div.ASWord").html();
	value=value.replace(/&nbsp;/g," ");
	$("#input_text").attr("value",value);
	last_input_text=value;
	setTimeout('searchOfflineDict($("#input_text").attr("value"))',10);

}


function OnKeyDown_UpDown_CheckMainMenu(para)
{
	var mainMenu=document.getElementById('Main_Menu');
	if (mainMenu==undefined||mainMenu.style.display=="none")
	{
		return;
	}
	
	var $Items = $('#Main_Menu .MainMenu_Item');
	var $hoveredItem = $Items.siblings('.Hovered');
	var $theItem;
	
	if ($hoveredItem.length==0)
	{
		if (para=='up')
		{
			$theItem=$Items.last();
		}
		else if (para=='down')
		{
			$theItem=$Items.first();
		}	
	}
	else if ($hoveredItem.length>=1)
	{
		if (para=='up')
		{
			$theItem = (function()
			{
				var item=$hoveredItem.prev();
				while (!item.hasClass('MainMenu_Item') && item.prev().length>0)
				{
					item=item.prev();
				}
				return item;
			})();
			
			if ($theItem.length==0)
			{
				$theItem=$Items.last();
			}
		}
		else if (para=='down')
		{
			$theItem = (function()
			{
				var item=$hoveredItem.next();
				while (!item.hasClass('MainMenu_Item') && item.next().length>0)
				{
					item=item.next();
				}
				return item;
			})();
			
			if ($theItem.length==0)
			{
				$theItem=$Items.first();
			}
		}	
	}
	$Items.siblings('.Hovered').removeClass('Hovered');
	$theItem.addClass('Hovered');
}


function OnKeyDown_LeftRight(para)
{
	OnKeyDown_LeftRight_CheckPluginItem(para);
	OnKeyDown_LeftRight_CheckSkinItem(para);
}

function OnKeyDown_LeftRight_CheckPluginItem(para)
{
	//return directly if not in plugin tab
	if (CurrentTab()!='li_5')
	{
		return;
	}
	
	if ($('#QRCode_mask').css('display')!='none')
	{
		hideQRCode();
		return;
	}
	
	var $Items = $('#exapp-items .exapp-item');
	var $hoveredItem = $Items.siblings('.hovered');
	var $theItem;
	
	if ($hoveredItem.length==0)
	{
		if (para=='left')
		{
			$theItem=$Items.last();
		}
		else if (para=='right')
		{
			$theItem=$Items.first();
		}	
	}
	else if ($hoveredItem.length>=1)
	{
		if (para=='left')
		{
			$theItem = (function()
			{
				var item=$hoveredItem.prev();
				while (!item.hasClass('exapp-item') && item.prev().length>0)
				{
					item=item.prev();
				}
				return item;
			})();
			
			if ($theItem.length==0)
			{
				$theItem=$Items.last();
			}
		}
		else if (para=='right')
		{
			$theItem = (function()
			{
				var item=$hoveredItem.next();
				while (!item.hasClass('exapp-item') && item.next().length>0)
				{
					item=item.next();
				}
				return item;
			})();
			
			if ($theItem.length==0)
			{
				$theItem=$Items.first();
			}
		}
	}
	$Items.siblings('.hovered').removeClass('hovered');
	$theItem.addClass('hovered');
}

function OnKeyDown_LeftRight_CheckSkinItem(para)
{
	//return directly if not in skin tab
	if (CurrentTab()!='li_7')
	{
		return;
	}
	//TODO: use left/right key to set a skin item as hovered
	//then user can press enter to set the hovered skin items as selected,
	//i.e., user can change skin without using a mouse
	var $Items = $('#skin-items .skin-item');
	var $hoveredItem = $Items.siblings('.hovered');
	var $theItem;
	
	if ($hoveredItem.length==0)
	{
		if (para=='left')
		{
			$theItem=$Items.last();
		}
		else if (para=='right')
		{
			$theItem=$Items.first();
		}	
	}
	else if ($hoveredItem.length>=1)
	{
		if (para=='left')
		{
			$theItem = (function()
			{
				var item=$hoveredItem.prev();
				while (!item.hasClass('skin-item') && item.prev().length>0)
				{
					item=item.prev();
				}
				return item;
			})();
			
			if ($theItem.length==0)
			{
				$theItem=$Items.last();
			}
		}
		else if (para=='right')
		{
			$theItem = (function()
			{
				var item=$hoveredItem.next();
				while (!item.hasClass('skin-item') && item.next().length>0)
				{
					item=item.next();
				}
				return item;
			})();
			
			if ($theItem.length==0)
			{
				$theItem=$Items.first();
			}
		}
	}
	$Items.siblings('.hovered').removeClass('hovered');
	$theItem.addClass('hovered');
}

/*********************************sentence tab*************************************/

function sent_back_onclick()
{
    //query index,load last query result
	//load the query before this query
	window.external.SentBackOnClick();
}
function disable_sent_back()
{
    $("#sent-back").addClass("sent_back_disable").removeClass("normal_ba").removeClass("hover_ba").removeClass("press_ba");
}
function enable_sent_back()
{
    $("#sent-back").addClass("normal_ba").removeClass("sent_back_disable");
}

function sent_forward_onclick()
{
	window.external.SentForwardOnClick();
}
function disable_sent_forward()
{
    $("#sent-forward").addClass("sent_forward_disable").removeClass("normal_ba").removeClass("hover_ba").removeClass("press_ba");
}
function enable_sent_forward()
{
    $("#sent-forward").addClass("normal_ba").removeClass("sent_forward_disable");
}

var last_sent_input_text;
function sent_input_text_onkeyup()
{
	if (last_sent_input_text==$("#sent-input-text").attr("value"))
	{
		return;
    }
    else 
    {
        hideSentQueryHist();
    }

	//trim the input text to make a valid query
	var query= $("#sent-input-text").attr("value")==null ? query="" : query=$("#sent-input-text").attr("value").toString().replace(/(^\s*)|(\s*$)/g,""); 

	if (query.length<=0)
	{
		showSentHomepage();
		setTimeout(function(){$("#sent-input-text").focus();},0);//bug fix:focus is lost when query.length <= 0
	}
	else
	{ 
		show_sent_ifrm("sent-offline-result");
		//hide the node showing search online status 
		$("#OnlineSearchStatus",document.frames("sent-offline-result").document).css("display","none").html(""); 
		searchOfflineSent(query);
		//showSentAS(query);
	}
	last_sent_input_text=$("#sent-input-text").attr("value");
	//change online dict iframe to ../Common/blank.html
	var ifrm2=document.getElementById("sent-online-result");
	ifrm2.src="../Common/blank.html";
}


function sent_input_text_onmouseover()
{
	if ($('#SentQueryHist').css('display')!='block' //if query history tab is not shown
	&& document.activeElement.id!='sent-input-text')//if input_text is not focused yet
	{
		GetFocus('sent-input-text');
	}
}

function sent_input_text_onclick(obj)
{
	obj.value.length<=0?(function(){showSentQueryHistPageContains(0);})():(function(){hideSentQueryHist();})();
}

function sent_input_text_onfocus(obj)
{
	obj.parentNode.parentNode.className='SentInput_Focus';
}

function sent_input_text_onblur(obj)
{
	obj.parentNode.parentNode.className='SentInput_Blur';
	
	var bInSentQH=bInSentQHArea;//add this line to avoid some unknown bug in ie6
	if (bInSentQH)
	{
		obj.focus();
		return false;
	}
	else
	{
		hideSentQueryHist();
	}
}

function sent_input_text_onpropertychange(obj)
{
	if (obj.value.length<=0){sent_input_text_onkeyup();}
}

function searchOfflineSent(query)
{
	var query = query||document.getElementById("sent-input-text").value;

	if (typeof query != "string" || query.length<=0)
	{
		return;
	}

	var lang=isChn(query)?"zh-cn":"en-us";	

	window.external.OfflineSentSearch(lang,query);	
}
function showSentOfflineResult(result)
{
    $("#offlineResult", window.frames["sent-offline-result"].document).html('').html(result);
	$("#OnlineSearchStatus",window.frames["sent-offline-result"].document).css("display","none");
	window.frames["sent-offline-result"].window.checkInNewWordList();//update the status of the AddNewWord picture.
}

function showSentHomepage()
{
	show_sent_ifrm('sent-offline-homepage');
}

function show_sent_ifrm(ifrmID)
{
	var main=document.getElementById("sent-main");
	var ifrms=main.childNodes;

	for (var i=0;i<ifrms.length;i++)
	{
		var item = ifrms.item(i);
		if (item.id==ifrmID)
		{
			item.style.display='block';
		}
		else if (item.id!=undefined)
		{
			item.style.display='none';
		}
	}
}



function sent_queryhistory_onblur(obj)
{
	var queryHist=document.getElementById('SentQueryHist');
	if (queryHist==undefined || queryHist.style.display=='none')
	{
		bInSentQHArea=false;
	}
	
	if (bInSentQHArea)
	{
		obj.focus();
		return false;
	}
	else
	{
		hideSentQueryHist();
		GetFocus('sent-input-text');
	}
}

function toggle_sent_queryhistory()
{
	if (document.activeElement.id=='sent-input-text')
	{
		$('#sent-input-text').blur();
	}
	setTimeout(function(){sent_queryhistory_onclick();},50);
}

function sent_queryhistory_onclick()
{
	$('#sent-btn-queryhistory').focus();
	var queryHist=document.getElementById('SentQueryHist');
	if (queryHist==undefined||queryHist.style.display=="none")
	{
	    showSentQueryHistPageContains(0);
	    window.external.AddToLog('ViewSentSearchHistory');
	}
	else
	{
		hideSentQueryHist();
	}	
}


//use to show the sent query history page which containning the indexed query
function showSentQueryHistPageContains(QueryIndex)
{
	createSentQueryHist();
	changeSentQueryHistPosition();
	clearSentQueryHist();
	getSentQueryHistPageContains(QueryIndex);
}



var bInSentQHArea=false;//true if in div#SentQueryHist area
function createSentQueryHist()
{
	var ItemString = '\
	<div id="SentQueryHist" class="DynamicEle" onmouseenter="bInSentQHArea=true;"  onmouseleave="bInSentQHArea=false;">\
		<div class="ie6-select-mask">\
			<iframe class="ie6-select-mask-iframe" scrolling="no"  frameborder="0">\
			</iframe>\
		</div>\
		<div id="SentQueryHistItems">\
			<div class="SentQueryHistItem"\
            onmouseover="$(\'.SentQueryHistItem.Hovered\').removeClass(\'Hovered\');$(this).addClass(\'Hovered\');"\
			onmouseout="$(\'.SentQueryHistItem.Hovered\').removeClass(\'Hovered\');$(this).removeClass(\'Hovered\');"\
			>\
            	<div class="SentQueryHistIndex">6</div>\
            	<div class="SentQueryHistContent"\
				 onmousedown="SentQueryHistContent_onclick(this);"\
				>\
                    <div class="SentQueryHistWord">111111111</div>\
                    <div class="SentQueryHistDef">00000000000000000000000000000000</div>\
                </div>\
                <div class="SentQueryHistDelete">\
					<div id="SentBtnQueryHistDelete" title="删除此条"class="normal_ba"\
                    onmouseover="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');"\
                    onmousedown="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'press_ba\');"\
                    onmouseup="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');"\
                    onmouseout="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'normal_ba\');"\
					onclick="javascript:SentBtnQueryHistDelete_onclick(this)"\
					>\
					</div>\
                </div>\
            </div>\
		</div>\
		<div id="SentQueryHistFooter">\
			<div id="SentQueryHistBack">\
				<div id="SentBtnQueryHistBack" title="上一页" class="SentBtnQueryHistBack_D"\
	            onmouseover="if ($(this).hasClass(\'SentBtnQueryHistBack_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');}"\
	            onmousedown="if ($(this).hasClass(\'SentBtnQueryHistBack_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'press_ba\');}"\
	            onmouseup="if ($(this).hasClass(\'SentBtnQueryHistBack_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');}"\
	            onmouseout="if ($(this).hasClass(\'SentBtnQueryHistBack_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'normal_ba\');}"\
				onclick="javascript:SentBtnQueryHistBack_onclick()"\
				>\
				</div>\
			</div>\
			<div id="SentQueryHistCurrentPos">1/1</div>\
			<div id="SentQueryHistForward">\
				<div id="SentBtnQueryHistForward" title="下一页" class="SentBtnQueryHistForward_D"\
	            onmouseover="if ($(this).hasClass(\'SentBtnQueryHistForward_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');}"\
	            onmousedown="if ($(this).hasClass(\'SentBtnQueryHistForward_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'press_ba\');}"\
	            onmouseup="if ($(this).hasClass(\'SentBtnQueryHistForward_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');}"\
	            onmouseout="if ($(this).hasClass(\'SentBtnQueryHistForward_D\')==false){$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'normal_ba\');}"\
				onclick="javascript:SentBtnQueryHistForward_onclick()"\
				>\
				</div>\
			</div>\
            <div id="SentQueryHistClear">\
				<div id="SentBtnQueryHistClear" title="清空查询历史" class="normal_ba"\
	            onmouseover="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');"\
	            onmousedown="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'press_ba\');"\
	            onmouseup="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'hover_ba\');"\
	            onmouseout="$(this).removeClass(\'normal_ba\').removeClass(\'hover_ba\').removeClass(\'press_ba\').addClass(\'normal_ba\');"\
				onclick="javascript:SentBtnQueryHistClear_onclick()"\
				>\
				</div>\
            </div>\
		</div>\
	</div>\
	';
	var queryHist=document.getElementById("SentQueryHist");
	if (queryHist==undefined || queryHist==null)
	{
		var a=document.createElement("div");//
		a.innerHTML = ItemString;
		document.body.appendChild(a);
	}
	document.getElementById("SentQueryHist").style.display='none';
	return;
}


function changeSentQueryHistPosition()
{
	var queryHist=document.getElementById("SentQueryHist");
	var obj=document.getElementById("sent-input");
	if (queryHist==undefined)
	{
		return;
	}
	
	var x=getLeft(obj);
	var y=getTop(obj);
	var x2=x+2;
	var y2=y+obj.offsetHeight+1;	

	queryHist.style.top=y2+'px';
	queryHist.style.left=x2+'px';
	//bug fixed:when drag border in '翻译' tab,obj.offsetWidth==0,obj.offsetWidth-1<0,this will cause error.
	queryHist.style.width=(obj.offsetWidth-1>0?obj.offsetWidth-1:0)+'px'; 
	return;
}
	

function clearSentQueryHist()
{
	var queryHist=document.getElementById("SentQueryHist");
	$("#SentQueryHistItems").html('');
	queryHist.style.display='none';
}

function showSentQueryHist()
{
	var queryHist=document.getElementById("SentQueryHist");
	queryHist.style.display="block";
}
function hideSentQueryHist()
{
	$('#SentQueryHist').css('display','none');
}

function getSentQueryHistPageContains(QueryIndex)
{
	//offline dict
    window.external.GetSentQueryRecPageContains(QueryIndex);
}

//cpp will check the query history list and compute which set of query items are to be inserted
function insertSentQueryHistItem(itemStr)
{
	var queryHist=document.getElementById("SentQueryHist");
	$("#SentQueryHistItems").html('').html(itemStr)
	queryHist.style.display="block";
}

//after insertion,cpp then update the page,tell js about current page and total pages
function updateSentQueryHistPage(currentPageIndex,totalPageIndex)
{
	//use this information to update the BtnQueryHistBack,QueryHistCurrentPos,BtnQueryHistForward
	if (currentPageIndex<=1)
	{
		currentPageIndex=1;
		$("#SentBtnQueryHistBack").attr("class", "SentBtnQueryHistBack_D");
	}
	else 
	{
	    $("#SentBtnQueryHistBack").attr("class", "normal_ba");
	}
	
	if (currentPageIndex>=totalPageIndex)
	{
		currentPageIndex=totalPageIndex;
		$("#SentBtnQueryHistForward").attr("class", "SentBtnQueryHistForward_D");
	}
	else
	{
	    $("#SentBtnQueryHistForward").attr("class", "normal_ba");
	}
	
	$("#SentQueryHistCurrentPos").html(currentPageIndex.toString()+"/"+totalPageIndex.toString());
}

function SentQueryHistContent_onclick(obj) 
{
    window.external.AddToLog('ViewSentHistoryItem');
	//obj is div.QueryHistItem
	hideSentQueryHist();
	var content=obj;
	var word="";
	for (var j=0;j<content.childNodes.length;j++)
	{
		if (content.childNodes[j].className=="SentQueryHistWord")
		{
		    word = (content.childNodes[j].innerHTML).ToHtmlDecode();
			break;
		}
	}
	changeSentInputText(word);
	setTimeout(function(){sent_dictsearch_onclick();},10);
}

function SentBtnQueryHistDelete_onclick(obj) {
    window.external.AddToLog('DeleteSentHistoryItem');
	//delete the word
	//1.find the index represent this query
	//obj is img.BtnQueryHistDelete
	var nodes=obj.parentNode.parentNode.childNodes;
	var index=-1;
	for (var i=0;i<nodes.length;i++)
	{
		if (nodes[i].className=="SentQueryHistIndex")
		{	
			index=parseInt(nodes[i].innerHTML);
			break;
		}
	}
	
	if (isNaN(index)||index<0)
	{//this is impossible to happen
		return;
	}
	//2.call window.external to delete the query
    window.external.DeleteSentQueryRecItem(index);
	//reload the items in the query history list
	showSentQueryHistPageContains(index);
}


function SentBtnQueryHistBack_onclick()
{
	if ($("#SentBtnQueryHistBack").hasClass('SentBtnQueryHistBack_D'))
	{
		return;
	}
	//find the first item in this page,and find out its index
	var index=getSentQHCurrentPageFirstItemIndex();
	//then
	if (isNaN(index)||index<0)
	{//this is impossible to happen
		return;
	}
	showSentQueryHistPageContains(index-10);
}

function SentBtnQueryHistForward_onclick()
{
    if ($("#SentBtnQueryHistForward").hasClass('SentBtnQueryHistForward_D'))
	{
		return;
	}
	//find the first item in this page,and find out its index
	var index=getSentQHCurrentPageFirstItemIndex();
	//then
	if (isNaN(index)||index<0)
	{//this is impossible to happen
		return;
	}
	showSentQueryHistPageContains(index+10);
}

function getSentQHCurrentPageFirstItemIndex()
{
	var index=-1;
	
	var nodes=document.getElementById("SentQueryHistItems").childNodes;
	for (var i=0;i<nodes.length;i++)
	{
		if (nodes[i].className=="SentQueryHistItem")
		{
			var item=nodes[i];
			
			for (var j=0;j<item.childNodes.length;j++)
			{
				if (item.childNodes[j].className=="SentQueryHistIndex")
				{
					index= parseInt(item.childNodes[j].innerHTML.toString());
					break;
				}
			}
			break;
		}
	}
	return index;
}

function SentBtnQueryHistClear_onclick() 
{
    window.external.AddToLog('ClearSentSearchHistory');
	//clear all the items
    window.external.ClearSentQueryNavList();
    window.external.ClearSentQueryRecList();
	//reload the items in the query history list
	showSentQueryHistPageContains(0);
}



function sent_dictsearch_onclick(bLogOption) 
{
	//instrumentation
    window.external.AddToLog('SentSearch');
	
	//init state
	hideSentQueryHist();
	$('#sent-input-text').focus().select();

	//get query
	var query = document.getElementById("sent-input-text").value.Trim();
	if (typeof query != "string" || query.length <= 0) 
	{
		showSentHomepage();
	    return;
	}
	else
	{
	    show_sent_ifrm("sent-offline-result");
	    $("#OnlineSearchStatus", document.frames("sent-offline-result").document).css("display", "block").html('').html("正在进行在线查询,请稍候...");
	}

	//record query
    if (bLogOption != "dont-log") 
    {
        window.external.AddToSentQueryNavList(query);
        window.external.AddToSentQueryRecList(query);
    }

    //-----------------------------------------------//
    //get encoded query
	var query2 = encodeURIComponent(query).substring(0, 1800);
	var newSrc = "https://cn.bing.com/dict/clientsentence?mkt=zh-CN&setLang=zh&form=BDVEHC&ClientVer=BDDTV3.5.1.4320&q=" + query2;

    //try load online result	
	$('#sent-online-result').attr('src', newSrc);
	window.external.MySetTimer("Timer_SentTimeout");
}
//called by cpp when timeout
function SentSearchOnlineTimeout()
{
    $("#OnlineSearchStatus", window.frames["sent-offline-result"].document).css("display", "block").html('').html("在线查询超时,请检查您的网络连接.");
}


function sent_bingsearch_onclick()
{
	window.external.AddToLog('SentBingSearch');
    var query2 = document.getElementById("sent-input-text").value;
    window.open('https://cn.bing.com/search?mkt=zh-CN&setLang=zh&form=BDCAD1&q=' + encodeURIComponent(query2).substring(0, 1800));
}

function changeSentInputText(query) 
{
	query=query.replace(/(^\s*)|(\s*$)/g,"");
	
	document.getElementById("sent-input-text").value=query;
	last_sent_input_text=query;//don't forget to update last_sent_input_text~
	
	if (query.length<=0)
	{
		showSentHomepage();
	}
	else
	{
		show_sent_ifrm("sent-offline-result");
		searchOfflineSent(query);
	}
	
	//change online dict iframe to ../Common/blank.html
	$("#sent-online-result").attr("src","../Common/blank.html");
}

//called by cpp when timeout
function SentenceTimeout()
{
    $("#OnlineSearchStatus", window.frames["sent-offline-result"].document).css("display", "block").html('').html("在线查询超时,请检查您的网络连接.");
}

function OnKeyDown_UpDown_CheckSentQueryHist(para)
{
	if (CurrentTab()!='li_2')
	{
		return;
	}
	
	var queryHist=document.getElementById('SentQueryHist');
	if (queryHist==undefined||queryHist.style.display=="none")
	{
	    return;
	}
	else
	{
		//highlight the next of query hist item, then try to 
		if ($('.SentQueryHistItem').length>0)
		{
			var query='';
			if ($('.SentQueryHistItem.Hovered').length>=1)
			{
				if (para=='down')
				{
					var theItem=$('.SentQueryHistItem.Hovered').next();
					if (theItem.length==0)
					{
						theItem=$('.SentQueryHistItem').first();
					}
					$('.SentQueryHistItem.Hovered').removeClass('Hovered');
					theItem.addClass('Hovered');
					query = (theItem.find('.SentQueryHistWord').html()).ToHtmlDecode();
				}
				else if (para=='up')
				{
					var theItem=$('.SentQueryHistItem.Hovered').prev();
					if (theItem.length==0)
					{
						theItem=$('.QueryHistItem').last();
					}
					$('.SentQueryHistItem.Hovered').removeClass('Hovered');
					theItem.addClass('Hovered');
					query = (theItem.find('.SentQueryHistWord').html()).ToHtmlDecode();
				}
			}
			else
			{
				if (para=='down')
				{
					var theItem=$('.SentQueryHistItem').first();
					$('.SentQueryHistItem.Hovered').removeClass('Hovered');
					theItem.addClass('Hovered');
					query = (theItem.find('.SentQueryHistWord').html()).ToHtmlDecode();
				}
				else if (para=='up')
				{
					var theItem=$('.SentQueryHistItem').last();
					$('.SentQueryHistItem.Hovered').removeClass('Hovered');
					theItem.addClass('Hovered');
					query = (theItem.find('.SentQueryHistWord').html()).ToHtmlDecode();
				}
			}
		
			show_sent_ifrm("sent-offline-result");
			value=query.replace(/&nbsp;/g," ");
			$("#sent-input-text").attr("value", value);
			last_sent_input_text = value;
			setTimeout('searchOfflineSent($("#sent-input-text").attr("value"))',10);
			
		}/*if ($('.SentQueryHistItem').length>0)*/
		
	}
}

function Enter_onclick()
{
	if ($('#Main_Menu').length>0 &&　$('#Main_Menu').is(':visible'))
	{
		var $hoveredItem = $('#Main_Menu .Hovered');
		
		if ($hoveredItem.length>0)
		{
			$hoveredItem.mousedown();
		}
		else 
		{
			hideMainMenu();
		}
		return;
	}

	var curTab=CurrentTab();
	
	if (curTab=="li_1")//dictionary
	{
		btn_dictsearch_onclick2();
	}
	else if (curTab=="li_2")//sentence
	{
		sent_dictsearch_onclick();
	}
	else if (curTab=="li_4")//translation
	{
		translate_do_onclick();
	}
	else if (curTab=="li_5")
	{
		if ($('#QRCode_mask').css('display')!='none')
		{
			hideQRCode();
			return;
		}
		
		$('#exapp-items .hovered').click();
	}
	else if (curTab=="li_7")//skin
	{
		$('#skin-items .hovered').click();
	}
}

function ChangeStatus_minimizetotray_at_close(status)
{
	var bStatus = (status=='true');
	$('#minimizetotray_at_close').attr('checked',bStatus);
}


/**********************************************/
//flash player checker
function CheckFlash()
{
	setTimeout(function(){window.external.CheckFlash()},1000);
}

function HasFlash()
{
	try
	{
		var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
		if (swf){return true;}
		else{return false;}
	}
	catch(e)
	{
		return false;
	}
}


/**********************************************/
//text and img ads
function LoadIframe(ifrmId,url,CallbackOnSucceed,CallbackOnFail)
{
	var xmlhttp;
	try
	{
		if (window.XMLHttpRequest)
		{
			//code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			//code for IE5, IE6
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	catch(e)
	{
		CallbackOnFail();
		return;
	}
	
	xmlhttp.open("GET",url,true); 
	xmlhttp.onreadystatechange = function()
	{
		if (xmlhttp.readyState == 4)
		{
			if (xmlhttp.status == 200)
			{
				if (CallbackOnSucceed && typeof CallbackOnSucceed == "function")
				{
					CallbackOnSucceed();
				}
			}
			else
			{
				if (CallbackOnFail && typeof CallbackOnFail=="function")
				{
					CallbackOnFail();
				}
			}
		}
	}
	xmlhttp.send();
	document.frames[ifrmId].location.href = url;
}

function ShowTxtAd()
{
	$("#TextAds").css("display", "block");
}

function HideTxtAd()
{
	$("#TextAds").css("display", "none");
}

function ShowImgAd()
{
	if ($('.frm_ads').css('display').toLowerCase()=='block')
	{
		return;
	}
	
	window.external.OnImgAdShown();
	$(".frm_ads").css("display", "block");
    $(".frm_middle").css("bottom", "41px");
	$('.SettingArea').scroll();//to notice the back-top buttons to change the css bottom
}

function HideImgAd()
{
	if ($('.frm_ads').css('display').toLowerCase()=='none')
	{
		return;
	}
	
	window.external.OnImgAdHidden();
	$(".frm_ads").css("display", "none");
	$(".frm_middle").css("bottom", "1px");
	$('.SettingArea').scroll();//to notice the back-top buttons to change the css bottom
}

function BtnImgAdsClose_onclick()
{
	HideImgAd();
}


//functions for translation panel
function translate_input_text_onkeyup()
{
	if ($('#translate_input_text').val().Trim()==''||$('#translate_input_text').hasClass('translate_input_text_empty')){return;}
	if ($('#translate_from .TranslateQueryLang').html()!='auto-detect')
	{
		return;
	}
	
	//note that the from lang should be 'auto-detect'
	
	if (isChn($('#translate_input_text').val()))
	{
		if ($('#translate_to .TranslateQueryLang').html().toLowerCase().indexOf('zh-ch')>=0)//中文翻成中文
		{
			$('#translate_to .TranslateDisplayLang').html('英语');
			$('#translate_to .TranslateQueryLang').html('en');
		}
		
	}
	else //if origin text is not chinese
	{
		if ($('#translate_to .TranslateQueryLang').html().toLowerCase().indexOf('zh-ch')<0)//非中文翻译成非中文
		{
			$('#translate_to .TranslateDisplayLang').html('简体中文');
			$('#translate_to .TranslateQueryLang').html('zh-CHS');
		}
	}
}


//menu of original languages and translated languages
var queryLang=["ar","et","mww","bg","pl","fa","ko","da","de","ru","fr","zh-CHT","fi","ht","nl","ca","zh-CHS","cs","tlh","tlh-Qaak","lv","lt","ro","mt","ms","no","pt","ja","sv","sk","sl","th","tr","ur","uk","es","he","el","hu","it","hi","id","en","vi"];

var displayLang=["阿拉伯语","爱沙尼亚语","白苗文","保加利亚语","波兰语","波斯语","朝鲜语","丹麦语","德语","俄语","法语","繁体中文","芬兰语","海地克里奥尔语","荷兰语","加泰隆语","简体中文","捷克语","克林贡语","克林贡语(pIqaD)","拉脱维亚语","立陶宛语","罗马尼亚语","马耳他语","马来语","挪威语","葡萄牙语","日语","瑞典语","斯洛伐克语","斯洛文尼亚语","泰语","土耳其语","乌尔都语","乌克兰语","西班牙语","希伯来语","希腊语","匈牙利语","意大利语","印地语","印度尼西亚语","英语","越南语"];
//"ar","阿拉伯语","et","爱沙尼亚语","mww","白苗文","bg","保加利亚语","pl","波兰语","fa","波斯语","ko","朝鲜语","da","丹麦语","de","德语","ru","俄语","fr","法语","zh-CHT","繁体中文","fi","芬兰语","ht","海地克里奥尔语","nl","荷兰语","ca","加泰隆语","zh-CHS","简体中文","cs","捷克语","tlh","克林贡语","tlh-Qaak","克林贡语(pIqaD)","lv","拉脱维亚语","lt","立陶宛语","ro","罗马尼亚语","mt","马耳他语","ms","马来语","no","挪威语","pt","葡萄牙语","ja","日语","sv","瑞典语","sk","斯洛伐克语","sl","斯洛文尼亚语","th","泰语","tr","土耳其语","ur","乌尔都语","uk","乌克兰语","es","西班牙语","he","希伯来语","el","希腊语","hu","匈牙利语","it","意大利语","hi","印地语","id","印度尼西亚语","en","英语","vi","越南语"

var freqQueryLang=["zh-CHS","en","ja","ko","fr","de","ru","es"];
var freqDisplayLang=["简体中文","英语","日语","朝鲜语","法语","德语","俄语","西班牙语"];

var bInLangMenuArea=false;
function createLangMenu(menuId)
{
	var menu=document.getElementById(menuId);
	if (menu==undefined || menu==null)
	{
		var langMenu = '';
		var langMenuItems='';
		var langMenuItem='';
		if (menuId=='lang_menu_translate_from')
		{
			langMenuItem='<div class="lang_menu_item" id="auto-detect">自动检测</div>';
			langMenuItems+=langMenuItem;
			langMenuItem='<div class="lang_menu_divider"></div>';
			langMenuItems+=langMenuItem;
		}
		
		for (var i=0;i<freqQueryLang.length;i++)
		{
			langMenuItem='<div class="lang_menu_item" id="'+freqQueryLang[i]+'">'+freqDisplayLang[i]+'</div>';
			langMenuItems+=langMenuItem;
		}
		langMenuItem='<div class="lang_menu_divider"></div>';
		langMenuItems+=langMenuItem;
		
		for (var i=0;i<queryLang.length;i++)
		{
			langMenuItem='<div class="lang_menu_item" id="'+queryLang[i]+'">'+displayLang[i]+'</div>';
			langMenuItems+=langMenuItem;
		}
		langMenu = '<div class="DynamicEle lang_menu normal_boco" id="' + menuId + '">' + langMenuItems + '</div>';
		
		
		var a=document.createElement('div');
		a.innerHTML = langMenu;
		document.body.appendChild(a);
		
		$('#'+menuId).bind(
		{
			'mouseenter':function()
			{
				bInLangMenuArea=true;
			},
			'mouseleave':function()
			{
				bInLangMenuArea=false;
			}
			
		});
		
		$('#'+menuId+' .lang_menu_item').bind(
		{	
			'mouseover':function()
			{
				$(this).addClass('hovered');
			},
			'mouseout':function()
			{
				$('.lang_menu_item').removeClass('hovered');
			},
			'mousedown':function()
			{		
				$('#'+menuId.substring(10)+' .TranslateDisplayLang').html($(this).html());
				$('#'+menuId.substring(10)+' .TranslateQueryLang').html($(this).attr('id'));	
				hideLangMenu(menuId);	
				window.external.SetTranslateLang(menuId.substring(10),$(this).html(),$(this).attr('id'));
			}
		});
		
		var element = $('#'+menuId).jScrollPane(
		{
			showArrows: true,
			verticalGutter: 0,
			mouseWheelSpeed:40,
			arrowButtonSpeed:40
		});
	}
	
	menu=document.getElementById(menuId);
	menu.style.display = 'none';
	return menu;
}

function changeLangMenuPosition(menuId)
{
	var Btn=document.getElementById(menuId.substring(menuId.indexOf('lang_menu_')+10));

	var x=getLeft(Btn);
	var y=getTop(Btn);
	var x2=x+2;
	var y2=y+30;

	var menu=document.getElementById(menuId);
	menu.style.left=x2+'px';
	menu.style.top=y2+'px';
	return;
}

function showLangMenu(menuId)
{
	createLangMenu(menuId);
	changeLangMenuPosition(menuId);
	
	$('#'+menuId+' .lang_menu_item').removeClass('hovered');
	var menu=document.getElementById(menuId);
	menu.style.display = 'block';
	
	var LangMenuAPI = $('#'+menuId).data('jsp');
	LangMenuAPI.reinitialise();
}

function hideLangMenu(menuId)
{
	$('#'+menuId).css('display','none');
}
function toggleLangMenu(menuId)
{
	var menu=document.getElementById(menuId);
	if (!menu || menu.style.display=="none")
	{
		showLangMenu(menuId);
	}
	else
	{
		hideLangMenu(menuId);
	}
}

function UpdateTranslateLang(fromOrTo, displayLang, queryLang)
{
	$('#'+fromOrTo+' .TranslateDisplayLang').html(displayLang);
	$('#'+fromOrTo+' .TranslateQueryLang').html(queryLang);	
}

function translate_from_onclick()
{
	window.external.SuspendHooks(100);
	setTimeout(function()
	{
		$('#translate_from').focus();
		toggleLangMenu('lang_menu_translate_from');
	}, 0);
}

function translate_from_onblur()
{
	if (bInLangMenuArea){$('#translate_from').focus();return false;}
	hideLangMenu('lang_menu_translate_from');
}

function translate_to_onclick()
{
	window.external.SuspendHooks(100);
	setTimeout(function()
	{
		$('#translate_to').focus();
		toggleLangMenu('lang_menu_translate_to');
	}, 0);
}

function translate_to_onblur()
{
	if (bInLangMenuArea){$('#translate_to').focus();return false;}
	hideLangMenu('lang_menu_translate_to');
}

function translate_switch_onclick()
{
	if ($('#translate_from .TranslateQueryLang').html()=='auto-detect')
	{
		return;
	}
	var tmp=$('#translate_from').html();
	$('#translate_from').html($('#translate_to').html());	
	$('#translate_to').html(tmp);
}

function translate_weibohelp_onclick()
{
	if ($('#translate_input_text').val().Trim()==''||$('#translate_input_text').hasClass('translate_input_text_empty'))
	{
		$('#translate_warning').css({'opacity':0,'display':'block'})
		.animate({'opacity':1},200)
		.delay(500).animate({'opacity':0},200,function(){ $('#warning').css('display','none');} );
		return;
	}
	
	var txt='';
	txt+='求助~这段话应该怎么翻译成';
	txt+=$('#translate_to .TranslateDisplayLang').html();
	txt+='呀：\n';
	txt+=$('#translate_input_text').val().Trim();
	
	var txtLength=0;
	var i=0;
	for (i=0;i<txt.length;i++)
	{
		
		if (txt.charCodeAt(i)<=127)
		{
			txtLength+=1;
		}
		else
		{
			txtLength+=2;
		}
		
		if (txtLength > 104*2)
		{
			break;
		}		
	}	
	if (i<txt.length){txt=txt.substring(0,i)+'...';}
	txt+='\n';
	txt+='#必应词典翻译求助#';
	
	window.open('http://service.weibo.com/share/share.php?' + 'url=' + encodeURIComponent('http://dict.bing.msn.cn/') + '&appkey=2546683754&ralateUid=3167273451' + '&title=' + encodeURIComponent(txt), '_blank', 'width=640, height=480, top=320, left=180, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no');
}

function translate_hideorigin_onclick()
{
	if ($('#translate').hasClass('translate_originhidden'))
	{
		$('#translate').removeClass('translate_originhidden');
		$('#translate_hideorigin').attr('title','收起原文（快捷键：Ctrl+H）');
	}
	else
	{
		$('#translate').addClass('translate_originhidden');
		$('#translate_hideorigin').attr('title','显示原文（快捷键：Ctrl+H）');
	}
	
	if (ie!=false && ie<=6)//only ie 6 need do this to fix ie6 bug
	{ 
	    window.external.AdjustWin(0);
	}
}

function translate_bingbar_onclick()
{
    window.open("http://www.bingtoolbar.com/zh-cn");
}

var bTranslateSearch = true;
function translate_search_onclick()
{
	if ($('#translate_search').hasClass('translate_dontsearch'))
	{
		$('#translate_search').removeClass('translate_dontsearch');
		$('#translate_search').attr('title','恢复点击查词');
		bTranslateSearch = false;
	}
	else
	{
		$('#translate_search').addClass('translate_dontsearch');
		$('#translate_search').attr('title','取消点击查词');
		bTranslateSearch = true;
	}
}

function translate_wordalign_onclick()
{
	if ($('#translate_wordalign').hasClass('translate_wordunalign'))
	{
		$('#translate_wordalign').removeClass('translate_wordunalign');
		$('#translate_wordalign').attr('title','逐句对照');
	}
	else
	{
		$('#translate_wordalign').addClass('translate_wordunalign');
		$('#translate_wordalign').attr('title','取消对照');
	}
	
	translate_wordalign_updatestatus();
}

function translate_wordalign_updatestatus()
{
	//show/hide alignment according to status of #translate_wordalign
	if ($('#translate_wordalign').hasClass('translate_wordunalign'))
	{
		$('.originLine',window.frames["translate_result_online"].document).css('display','block');
	}
	else
	{
		$('.originLine',window.frames["translate_result_online"].document).css('display','none');
	}
}

function translateTxt_All_Callback(from,to,text,accessToken)
{
	window.frames["translate_result_online"].window.translateTxt_All_Callback(from,to,text,accessToken);
}

//-----------------------------------
function OpenPromoteAppUrl(promoteAppId)
{
	window.open($('#exapp-items #'+promoteAppId).find('.exapp-item-downloadurl').html().Trim());
}

function ShowPromoteAppQRCode(promoteAppId)
{
	$('#exapp-items #'+promoteAppId).click();
}

//-----------------------------------
