
//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 startx=0,starty=0,endx=0,endy=0;
function header_mouse_down()
{
	window.external.OnHeaderMouseDown();
}


//------------------------------------------------------------
//BtnMin
function BtnMin_onclick()
{
    window.external.OnMin();
}

//------------------------------------------------------------------------------
//BtnClose
function BtnClose_onclick()
{
    window.external.OnClose();
}
//-----------------------------------------------------------------------------
//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

function btn_forward_onclick()
{
    //load last query result
	window.external.BtnForwardOnClick();
}

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

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


//use to show auto suggestion
function showAutoSuggestion(query)
{
	createAutoSuggesion();
	changeAutoSugPosition();
	clearAutoSug();
	//showAutoSug();
	getAutoSugItems();
}
	
function createAutoSuggesion()
{
	var ItemString = '\
	<div id="AutoSuggestion" class="dynamicElement" style="display:none;position:absolute;z-index:10000;text-align:left;border:1px solid #8db2e3;\
	background:#e0e0e0;filter: alpha(opacity=85);"\
	\
	>\
	</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");//=$('#input');

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

	autoSuggestion.style.top=y2+'px';
	autoSuggestion.style.left=x2+'px';
	//bug fixed:when drag border in '翻译' tab,obj.offsetWidth==0,obj.offsetWidth-2<0,this will cause error.
	autoSuggestion.style.width=(obj.offsetWidth-2>0?obj.offsetWidth-2: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)
{
	var autoSuggestion=document.getElementById("AutoSuggestion");
	autoSuggestion.innerHTML=itemStr;
	autoSuggestion.style.display="block";
}

function hideAutoSuggestion()
{
	var as=document.getElementById('AutoSuggestion');

	if (as!=undefined)as.style.display='none';
}

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='';
		}
		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 Utf8ToUnicode(strUtf8) {  
    var bstr = "";  
    var nTotalChars = strUtf8.length; // total chars to be processed.  
    var nOffset = 0; // processing point on strUtf8  
    var nRemainingBytes = nTotalChars; // how many bytes left to be converted  
    var nOutputPosition = 0;  
    var iCode, iCode1, iCode2; // the value of the unicode.  
    while (nOffset < nTotalChars) {  
        iCode = strUtf8.charCodeAt(nOffset);  
        if ((iCode & 0x80) == 0) // 1 byte.  
        {  
            if (nRemainingBytes < 1) // not enough data  
                break;  
            bstr += String.fromCharCode(iCode & 0x7F);  
            nOffset++;  
            nRemainingBytes -= 1;  
        }  
        else if ((iCode & 0xE0) == 0xC0) // 2 bytes  
        {  
            iCode1 = strUtf8.charCodeAt(nOffset + 1);  
            if (nRemainingBytes < 2 || // not enough data  
                    (iCode1 & 0xC0) != 0x80) // invalid pattern  
            {  
                break;  
            }  
            bstr += String  
                    .fromCharCode(((iCode & 0x3F) << 6) | (iCode1 & 0x3F));  
            nOffset += 2;  
            nRemainingBytes -= 2;  
        } else if ((iCode & 0xF0) == 0xE0) // 3 bytes  
        {  
            iCode1 = strUtf8.charCodeAt(nOffset + 1);  
            iCode2 = strUtf8.charCodeAt(nOffset + 2);  
            if (nRemainingBytes < 3 || // not enough data  
                    (iCode1 & 0xC0) != 0x80 || // invalid pattern  
                    (iCode2 & 0xC0) != 0x80) {  
                break;  
            }  
            bstr += String.fromCharCode(((iCode & 0x0F) << 12)  
                    | ((iCode1 & 0x3F) << 6) | (iCode2 & 0x3F));  
            nOffset += 3;  
            nRemainingBytes -= 3;  
        } else  
            // 4 or more bytes -- unsupported  
            break;  
    }  
    if (nRemainingBytes != 0) { // bad UTF8 string.                  
        return "";  
    }  
    return bstr;  
}  


//-----------------------------------------------------------------------
//drag the dragbar div to resize the content div and sidebar div
var startX ;
var startWidth;
var isDrag = false;

var MIN_LEFT_WIDTH = 150;//
var MIN_RIGHT_WIDTH=200;

//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 the dialog's border for change the size of dialog
var hitTest="";
var TOTAL_WIDTH;
var TOTAL_HEIGHT;

function recordborder()
{
	if (window.attachEvent)//ie
	{
		window.attachEvent("onresize", windowOnresize);    
	} 
	else if (window.addEventListener) //firefox
	{       
		window.addEventListener("onresize", windowOnresize, false);
	}
	windowOnresize();
	function windowOnresize()
	{
		TOTAL_HEIGHT=window.innerHeight ? window.innerHeight : document.body.clientHeight;
		TOTAL_WIDTH=window.innerWidth ? window.innerWidth : document.body.clientWidth;
		
//		var resizeAutoSug=(function ()
//		{
//			createAutoSuggesion();
//			changeAutoSugPosition();
//		})();
	}
}
function detectborder(evt)
{ 
	recordborder();
  	if (document.attachEvent)//ie
	{
		document.attachEvent("onmousemove", window_onmousemove); 
		document.attachEvent("onmousedown", window_onmousedown);         
	} 
	else if (document.addEventListener) //firefox
	{       
		document.addEventListener("onmousemove", window_onmousemove, false);
		document.addEventListener("onmousedown", window_onmousedown, false);
	}

	function window_onmousemove(evt)
	{
		var evt = evt?evt:window.event;//window.event?window.event:evt;
		var cursorStyle="";
	
		if (evt.clientY <= 5 &&evt.clientX <= 5)//top left
		{
			cursorStyle="nw-resize";
			hitTest="HTTOPLEFT";
		}
		else if (evt.clientY <= 5 && evt.clientX >= TOTAL_WIDTH-5)//top right
		{
			cursorStyle="ne-resize";
			hitTest="HTTOPRIGHT";
		}
		else if (evt.clientY >= TOTAL_HEIGHT-5 && evt.clientX <= 5)//bottom left
		{
			cursorStyle="sw-resize";
			hitTest="HTBOTTOMLEFT";
		}
		else if (evt.clientY >= TOTAL_HEIGHT-5 && evt.clientX >= TOTAL_WIDTH-5)//bottom right
		{
			cursorStyle="se-resize";
			hitTest="HTBOTTOMRIGHT";
		}
		else if (evt.clientY <= 5)//top
		{
			cursorStyle="n-resize";
			hitTest="HTTOP";
		}
		else if (evt.clientY >= TOTAL_HEIGHT-5)//bottom
		{
			cursorStyle="s-resize";
			hitTest="HTBOTTOM";
		}
		else if (evt.clientX <= 5)//left
		{
			cursorStyle="w-resize";
			hitTest="HTLEFT";
		}
		else if (evt.clientX >= TOTAL_WIDTH-5)//right
		{
			cursorStyle="e-resize";
			hitTest="HTRIGHT";
		}
		
		if (cursorStyle=="")//restore the cursor if event doesnt occur in areas above
		{
			cursorStyle="default";
			hitTest="";
		}
		
		$("body").css("cursor",cursorStyle);
		//stopEvent(evt);
	}
	
	function window_onmousedown(evt)
	{
		var evt = evt?evt:window.event;//window.event?window.event:evt;
		if (evt.button==1 && hitTest!="")//if in the areas
		{//send message to switch to changing-size mode
			window.external.OnChangeSize(hitTest,evt.clientX,evt.clientY);
		}	
	}	
}

//----------------------------------------------------------------------
//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 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);
	//obj.style.display='none';
}


/*
* 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 PortNumberValidate(e)
{
    var keynum;
    var keychar;
    var numcheck;

    if (window.event) // IE
    {
        keynum = e.keyCode
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which
    }
    keychar = String.fromCharCode(keynum)
    numcheck = /\d/
    return numcheck.test(keychar)
}



//BingDictUpdater------------------------------------------
function installUpdate_onclick()
{
	window.external.OnInstallUpdate();
}

function prepareInstall_onclick() 
{
    window.external.prepareInstall();
}


function downloadUpdate_onclick()
{
	switchToPanel("is-downloading");
	window.external.OnDownloadUpdate();
}

function visitWebsite_onclick()
{
    window.open("http://dict.bing.msn.cn/");
	window.external.OnClose();
}

var global_intervalId = 0;
function installImmediate_onclick() {
    clearInterval(global_intervalId);
    window.external.OnInstallUpdate();
}

function InstallDelayCallBack() 
{

    var ele = document.getElementById("installDelay");
    if (ele) 
    {
        var count = parseInt(ele.innerHTML);
        if (count <= 0) {
            clearInterval(global_intervalId);
            window.external.OnInstallUpdate();
            return;
        }
        count -= 1;
        ele.innerHTML = count.toString();
    }
}

function SetInstallDelay() {
    global_intervalId=setInterval(InstallDelayCallBack, 1000);
}

function startMainProgram_onclick()
{
	window.external.OnOpenMainProgram();
	window.external.OnClose();
}

function switchToPanel(panelId)
{
	var panels=document.getElementById("panels");

	var nodes=panels.childNodes;

	for (var i=0;i<nodes.length;i++)
	{
		if (nodes[i].nodeType === 1 && nodes[i].className.toString().indexOf(" selected") !=-1)
		{
			nodes[i].className=nodes[i].className.toString().replace(" selected","");
			break;
		}
	}
	for (var i=0;i<nodes.length;i++)
	{
		if (nodes[i].nodeType === 1 &&nodes[i].id==panelId )
		{
			nodes[i].className="panel selected";
			break;
		}
	}
}


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