
$(document).ready(
function () 
{
    $('img').bind('dragstart', function () { return false; });//ban drag of <img>
   
	$('#dict-search').bind('dragstart', function () { return false; });
	$('#dict-search').bind('mousedown', function () { return false; });
}
);


/*
* 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 isChn(str)
{
    var pattern = /[\u4E00-\u9FA5]+/;
    return pattern.test(str);
}


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

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

function header_mouse_down()
{
	window.external.OnHeaderMouseDown();
}


function BtnMiniModeMenu_onclick()
{
    window.external.ShowMiniModeMenu();
}

//------------------------------------------------------------------------------
//BtnClose
function BtnClose_onclick()
{
    window.external.HideWin();
}

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

/********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 + "/MiniModeDlg/MiniModeDlg.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);
}



var last_input_text;
function get_last_input_text()
{
	return last_input_text;
}

function dict_input_text_onkeyup()
{
	if (last_input_text==$("#dict-input-text").attr("value"))
	{
		return;
    }
    else 
    {
        hideQueryHist();
		
		
		hideSearchResultPanel();
    }

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

	if (query.length<=0)
	{
		hideAutoSuggestion();
		
		
		hideSearchResultPanel();
	}
	else
	{
		showDictAutoSuggestion(query);
	}
	last_input_text=$("#dict-input-text").attr("value");
}


function dict_input_text_onmouseover()
{
	if (Number(window.external.IsQueryHistShown())==0 	//if query history is not shown
	&& document.activeElement.id!='dict-input-text')	//if dict-input-text is not focused yet
	{
		GetFocus('dict-input-text');
	}
}

function dict_input_text_onclick(obj)
{
	obj.value.length<=0?(function(){getQueryHistPageContains(0);})():(function(){hideQueryHist();})();
}

function dict_input_text_onfocus(obj)
{
	obj.parentNode.parentNode.className='DictInput_Focus';
}
function dict_input_text_onblur(obj)
{
	obj.parentNode.parentNode.className='DictInput_Blur';
	window.external.InputText_OnBlur();
}

function dict_input_text_onpropertychange(obj)
{
	if (obj.value.length<=0){dict_input_text_onkeyup();}
}


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

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

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


function dict_dictsearch_onclick(bLogOption) 
{
	//instrumentation
    window.external.AddToLog('MiniMode_MiniDictSearch');
	
	//init state
	hideAutoSuggestion();
	hideQueryHist();
	$('#dict-input-text').focus().select();

	//get query
	var query = document.getElementById("dict-input-text").value.Trim();
	if (typeof query != "string" || query.length <= 0) 
	{
		
		hideSearchResultPanel();
	    return;
	}
	//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 lang=isChn(query)?"zh-cn":"en-us";
	window.external.MySetTimer("Timer_ShowAsyncLoading");
	window.external.GetSearchResultAsync(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>\
	");
	
	$("#footer").hide();
	$("#middle").css('bottom','0px');
	window.external.HSWindowHeight(10+$("#main",document.frames("search_result").document).height());
}

function showAsyncSearchResult(result)
{
	$("#results",document.frames("search_result").document).html("\
<div id=\"result\"></div>\
");
	$("#result",document.frames("search_result").document).html(result);
	document.frames("search_result").window.checkInNewWordList();
	document.frames("search_result").window.checkAutoPron();
	showSearchResultPanel();
}

function showSearchResultPanel()
{
	$("#footer").show();
	$("#middle").css('bottom','25px');
	window.external.HSWindowHeight(15+$("#main",document.frames("search_result").document).height()+25);
}

function hideSearchResultPanel()
{
	$("#footer").hide();
	$("#middle").css('bottom','0px');
	window.external.HSWindowHeight(0);
}

function TryFocusInput()
{
    setTimeout(function () 
    {
        GetFocus('dict-input-text');
    },0);
}


function changeInputText(query) 
{
	query=query.replace(/(^\s*)|(\s*$)/g,"");
	
	document.getElementById("dict-input-text").value=query;
	last_input_text=query;//don't forget to update last_input_text~
}


var ContextArea=0;
//1:input-menu  2:translate-input 4:result-page-menu
function detectContextArea()
{
	$("#dict-input-text").bind("mouseenter",function(){ContextArea=1;});
	$("#dict-input-text").bind("mouseleave",function(){ContextArea=0;});
}
function getContextArea()
{
	return ContextArea;
}

//----------------------------------------------------------------------
//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 toggle_dict_queryhistory()
{
	if (document.activeElement.id=='dict-input-text')
	{
		$('#dict-input-text').blur();
	}
	setTimeout(function(){dict_queryhistory_onclick();},50);
}

function dict_queryhistory_onclick()
{
	$('#dict-btn-queryhistory').focus();
	
	//use setTimeout to fix IE6 bug:response to blur of input box blur is later than response to click of queryhistory button  
	setTimeout(function(){window.external.QueryHist_OnClick();},50);
}
function dict_queryhistory_onblur(obj)
{
	window.external.QueryHist_OnBlur();
}

function dict_back_onclick()
{
	//load the query before current query
	window.external.BtnBackOnClick();
}

function dict_forward_onclick()
{
	//load the query after current query
	window.external.BtnForwardOnClick();
}

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

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


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

function hideQueryHist()
{
	window.external.HideQueryHist();
}

//------------------------------------------------------------
function hideAutoSuggestion()
{
	window.external.HideAutoSuggestion();
}

function showDictAutoSuggestion(query)
{
	var lang=isChn(query)?"zh-cn":"en-us";
	window.external.ShowAutoSuggestion(lang,query);
}


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

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