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

//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 bheaderMouseDown=false;
var startx=0,starty=0,endx=0,endy=0;
function header_mouse_down()
{
	startx=window.event.screenX;
	starty=window.event.screenY;

	bheaderMouseDown=true;
	window.external.OnHeaderMouseDown();
}

function header_mouse_up()
{
	bheaderMouseDown=false;
}
function header_mouse_move()
{
	endx=window.event.screenX;
	endy=window.event.screenY;
	if (startx==endx && starty==endy)
	{
		return;
	}
	
	if (bheaderMouseDown && $('#BtnPin').attr('class').indexOf('Pinned')==-1)
	{
		bheaderMouseDown = false;
		$('#BtnPin').click();
	}
}

function header_mouse_out()
{
	if (bheaderMouseDown && $('#BtnPin').attr('class').indexOf('Pinned')==-1)
	{
		bheaderMouseDown = false;
		$('#BtnPin').click();
	}
}



//------------------------------------------------------------------------------
//BtnPin_oncick()
function BtnPin_onclick()
{
	var obj=document.getElementById('BtnPin');
	if (obj.className.indexOf('Pinned') == -1)
	{
		obj.title='解除固定（快捷键：Alt+P）';
		window.external.OnPin();
		obj.className='Pinned_N';	
	}
    else
	{
		obj.title='固定窗口（快捷键：Alt+P）';
		window.external.OnUnPin();
		obj.className='Pin_N';
	} 
}

//------------------------------------------------------------------------------
//BtnClose
function BtnClose_onclick()
{
    window.external.HideWin();//dont try to close window,only hide it.
	
	if ($('#BtnPin').attr('class').indexOf('Pinned') != -1)
	{
		$('#BtnPin').click();
	}
}
//-----------------------------------------------------------------------------
//btn_back       

var btn_back_available=true;
var btn_forward_available=true;
var recentQuerys;
var curQueryNum;//query
function btn_back_onclick()
{
    //query index,load last query result
	//load the query before this query
	window.external.BtnBackOnClick();
}

//--------------------------------------------------------------------------
//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();
}

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

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


function show_offlineresult(result)
{
	var div=offline_result.window.document.getElementById("offlineResult");
	div.innerHTML=result;
	offline_result.window.checkInNewWordList();//update the status of the AddNewWord picture.
}

function show_offline_noresult(query)
{
	var div=offline_result.window.document.getElementById("offlineResult");
	div.innerHTML="\
	<div class=\"dictBar-hidden\">\
		<div class=\"dictBarTitle\">" + query.ToHtmlEncode() + "</div>\
	</div>\
	本地查询无结果.";
}

function show_ifrm(ifrmID)
{
	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";	
	//offline dict
	window.external.OfflineDictSearch(lang,query);	
}

function showLoading()
{
	$("#results",document.frames("search_result").document).html("\
	<div id=\"loading\">\
        <div id=\"loading-img\">\
        </div>\
        <div id=\"loading-txt\">正在查询,请稍候...</div>\
    </div>\
	");
	window.external.HSWindowHeight($("#main",document.frames("search_result").document).height());
}

function showOnlineLexiconResult(result)
{
	$("#results",document.frames("search_result").document).html("\
<div id=\"lexicon\"></div>\
<div id=\"translation\"></div>\
<div id=\"offline-lexicon\"></div>\
<div id=\"no-result\"></div>\
");
	$("#lexicon",document.frames("search_result").document).html(result);
	window.external.HSWindowHeight($("#main",document.frames("search_result").document).height());
	document.frames("search_result").window.checkInNewWordList();
	document.frames("search_result").window.checkAutoPron();
}


function showOnlineTranslateResult(result)
{
	$("#results",document.frames("search_result").document).html("\
<div id=\"lexicon\"></div>\
<div id=\"translation\"></div>\
<div id=\"offline-lexicon\"></div>\
<div id=\"no-result\"></div>\
");
	$("#translation",document.frames("search_result").document).html(result);
	window.external.HSWindowHeight($("#main",document.frames("search_result").document).height());
}

function showOfflineLexiconResult(result)
{
	$("#results",document.frames("search_result").document).html("\
<div id=\"lexicon\"></div>\
<div id=\"translation\"></div>\
<div id=\"offline-lexicon\"></div>\
<div id=\"no-result\"></div>\
");
	$("#offline-lexicon",document.frames("search_result").document).html(result);
	window.external.HSWindowHeight($("#main",document.frames("search_result").document).height());
	document.frames("search_result").window.checkInNewWordList();
}

function showNoResult(result)
{
	$("#results",document.frames("search_result").document).html("\
<div id=\"lexicon\"></div>\
<div id=\"translation\"></div>\
<div id=\"offline-lexicon\"></div>\
<div id=\"no-result\"></div>\
");
	$("#no-result",document.frames("search_result").document).html(result);
	window.external.HSWindowHeight($("#main",document.frames("search_result").document).height());
}


//stop the bubble of event
function stopEvent(evt)//firefox
{
   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;
    }
}

function hideHeaderFooter() 
{
    document.getElementById('middle').style.top = '0px';
    document.getElementById('middle').style.bottom = '0px';
    document.getElementById('header').style.display = 'none';
    document.getElementById('footer').style.display = 'none';
}
function showHeaderFooter()
{
    document.getElementById('middle').style.top = '25px';
    document.getElementById('middle').style.bottom = '25px';
    document.getElementById('header').style.display = 'block';
    document.getElementById('footer').style.display = 'block';
}


//-------------------------------
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;
} 

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

function SettingCheckBoxOnChange(settingSection,obj)
{
    if (obj.id == "open_proxy") {
        var proxyIp = document.getElementById("ip");
        if (proxyIp.value == null || proxyIp.value == "")
        {
            obj.checked = false;
            alert("代理地址不能为空");
            return;
        }
    }
	if (obj.checked==true)
	{
		window.external.SettingCheckBoxOnChange(settingSection,obj.id,"true");
	}
	else
	{
		window.external.SettingCheckBoxOnChange(settingSection,obj.id,"false");
	}
}

function connect_proxy_onclick()
{
	window.external.connect_proxy_onclick();
}

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

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

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

function changeInputText(query) 
{
	document.getElementById("input_text").value=query;
	show_ifrm("offline_result");
	searchOfflineDict(query);
}

function ASItem_onclick(obj)
{
	
	var nodes=obj.childNodes;
	var word="";
	for (var i=0;i<nodes.length;i++)
	{
		if (nodes[i].className=="ASWord")
		{
			
			word=nodes[i].innerHTML;
			break;
		}
	}

	changeInputText(word);
}


/*
* Timer类
* @author: kmlxk@yahoo.com.cn
* @created: 2011-2-12 18:51
* 方法: 
* 构造函数: 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);
	}
}

function ShowShortcut(eleId) {
    var 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 == "无") {
                    //unregister hot key and delete the code from registry table
                    window.external.DictUnregisterHotKey(ele.id, "true");
                    return false;
                }
                return false;
            }
            ele.onblur = function () {

                if (result.length == 0 || result.substr(result.length - 1, 1) == ' ') {
                    this.value = "无";
                }
                if (this.value == "无") {
                    window.external.DictUnregisterHotKey(ele.id, "true");
                }
                RegisterALLHotKey();
                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;
            var originalKeyString = window.external.GetOriginalKeyString(ele.id);
            if (CheckHotkeyIsValid(result)) {
                ele.value = result;
                if (result == window.external.GetOriginalKeyString("show_hide_with_hotkey") || result == window.external.GetOriginalKeyString("hover_translate_hotkey") || result == window.external.GetOriginalKeyString("select_translate_hotkey")) {
                    //the hot key has been registered
                    ele.value = "无";
                    window.external.DictUnregisterHotKey(ele.id, "true");
                    return false;
                }
                var res = Boolean(window.external.DictRegisterHotKey(ele.id, e.ctrlKey, e.shiftKey, e.altKey, code));
                if (!res) {
                    //registering new hotkey failed
                    ele.value = originalKeyString;
                }
                if (document.activeElement.id == ele.id) 
                {
                     UnregisterALLHotKey();
                 }
                return false;
            }
            ele.value = "无";
        }
        else {
            if (e.keyCode) code = e.keyCode;
            if (delete_keys[code]) {
                ele.value = "无";
                ele.onkeyup = function () {
                    window.external.DictUnregisterHotKey(ele.id, "true");
                    return false;
                }
            }
            if (indivdual_keys[code]) {
                var originalKeyString = window.external.GetOriginalKeyString(ele.id);
                if (indivdual_keys[code] == originalKeyString) {
                    return false;
                }
                if (indivdual_keys[code] == window.external.GetOriginalKeyString("show_hide_with_hotkey") || indivdual_keys[code] == window.external.GetOriginalKeyString("hover_translate_hotkey") || indivdual_keys[code] == window.external.GetOriginalKeyString("select_translate_hotkey")) {
                    ele.value = originalKeyString;
                    return false;
                }
                ele.value = indivdual_keys[code];
                ele.onkeyup = function () {
                    var res = Boolean(window.external.DictRegisterHotKey(ele.id, e.ctrlKey, e.shiftKey, e.altKey, code));
                    if (!res) {
                        //failed
                        ele.value = originalKeyString;
                    }
                    if (document.activeElement.id == ele.id) {
                        UnregisterALLHotKey();
                    }
                    return false;
                }
            }
            return false;
        }
    }
}




function SearchInBrowser() 
{
    window.external.AddToLog("BingSearchInCrossTran");
    var query = ($(".query", window.frames["search_result"].document).html()).ToHtmlDecode();
    window.open('https://cn.bing.com/?mkt=zh-CN&setLang=zh&form=BDCCK4&q=' + encodeURIComponent(query).substring(0, 1800));
}

function More_onclick() 
{
    window.external.AddToLog("MoreInCrossTran");
    var query = ($(".query", window.frames["search_result"].document).html()).ToHtmlDecode();
    window.external.SearchOnline(query);
}


function checkInNewWordList()
{
    var obj = document.getElementById("addToNewWordList");
    if (obj == undefined) 
    {
        return;
    }
	var dictBarChildNodes= obj.parentNode.childNodes;//childNodes in dictBar
	var headword="",pron="",def="";

	for (var i=0;i<dictBarChildNodes.length;i++)
	{
		var item=dictBarChildNodes[i];
		if (item.nodeType===1)
		{
			if (item.className.toLowerCase()=="dictbartitle")
			{
			    headword = (item.innerHTML).ToHtmlDecode();
				break;
			}
		}
	}
	
	//the following call will lead to crash when headword containning a single qutation mark :window.external.IsInNewWordList
	if (Number(window.external.IsInNewWordList(headword))==0)
	{
		obj.className="addToNewWordList_Pending";
		obj.title="添加到生词本";
	}
	else
	{	
		obj.className="addToNewWordList_Added";
		obj.title="移出生词本"; 
	}
	
}


function addToNewWordList_onclick(obj)
{
	var dictBarChildNodes= obj.parentNode.childNodes;//childNodes in dictBar
	var headword="",pron="",def="";
	for (var i=0;i<dictBarChildNodes.length;i++)
	{
		var item=dictBarChildNodes[i];
		if (item.nodeType===1)
		{
			if (item.className.toLowerCase()=="dictbartitle")
			{
			    headword = (item.innerHTML).ToHtmlDecode();
			}
			if (item.className.toLowerCase()=="dictbarprons")
			{
				for (var j=0;j<item.childNodes.length;j++)
				{
					var dictBarPron=item.childNodes[j];
			
					if (dictBarPron.nodeType===1 && dictBarPron.className.toLowerCase()=="dictbarpron")
					{
				
						for (var k=0;k<dictBarPron.childNodes.length;k++)
						{
							var dictBarPronValue=dictBarPron.childNodes[k];
							if (dictBarPronValue.className=="dictBarPronValue")
							{
								pron=dictBarPronValue.innerHTML;
								break;
							}
						}
						
					}
				}
			}
		}
	}
	var defGroupChildNodes=obj.parentNode.nextSibling.childNodes;//childNodes in defGroups
	for (var i=0;i<defGroupChildNodes.length;i++)
	{
		var defGroup=defGroupChildNodes[i];
		for (var j=0;j<defGroup.childNodes.length;j++)
		{
			var item3=defGroup.childNodes[j];
			if (item3.nodeType===1)
			{
				if (item3.className=="defPos")
				{
					def+=item3.innerHTML;
				}
				if (item3.className=="defCnt")
				{
					def+=item3.innerHTML;
				}
			}		
		}		
	}
	
	if (obj.className=="addToNewWordList_Pending")
	{
		window.external.AddNewWord(headword,pron,def);
		if (Number(window.external.IsInNewWordList(headword))!=0)
		{
			obj.className="addToNewWordList_Added";
			obj.title="移出生词本"; 
		}
	}
	else if (obj.className=="addToNewWordList_Added")
	{
		window.external.DeleteNewWord(headword);
		if (Number(window.external.IsInNewWordList(headword))==0)
		{
			obj.className="addToNewWordList_Pending";
			obj.title="添加到生词本";
		}
	}
}
//called by cpp when timeout
function SearchOnlineTimeout()
{
	$("#OnlineSearchStatus",window.frames["offline_result"].document).html("在线查询超时,请检查您的网络连接.");
}


function OnlineDictSearch(query)
{
	window.external.MySetTimer("Timer_SearchOnlineTimeout");

	$("#OnlineSearchStatus", document.frames("offline_result").document).css("display", "block").html("正在进行在线查询,请稍候..."); 
	var offline_result_scrollHeight=$("#main",document.frames("offline_result").document).height()+30;
	window.external.HSWindowHeight(offline_result_scrollHeight);

	var query2 = encodeURIComponent(query).substring(0, 1800);

	var ifrm=document.getElementById("online_result");
	ifrm.src="../Common/blank.html";
	ifrm.src = "https://cn.bing.com/dict/clienthover?mkt=zh-CN&setLang=zh&form=BDVEHC&q=" + query2;

}



/********skin********/
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 + "/SelectTranslateDlg/SelectTranslateDlg.css");
    $("link#_NewSkinColor").attr("href", "").attr("href", "../../../skin/Color/" + color + ".css");
    $("link#_NewSkinImage").attr("href", "").attr("href", "../../../skin/Image/" + image + "/BgImg.css");

    window.frames["search_result"].window.UpdateSkinForPage(model, color, image);
}
