
/* 高亮标记代码 开始 */
var highlightId = "data-uuid";
var highlightName = 'eudic-annotation';

//高亮 选中区域
function strikeSelection(color) {
    if (typeof window.getSelection !== 'undefined') {
        var selection = window.getSelection();
        if (selection.rangeCount === 0) {
            return;
        }

        var range = selection.getRangeAt(0);
        if (!isValidHighlightRange(range)) {
            return '__RANGE_ERROR__';
        }
        else {
            var d = new Date();
            var timeStamp = d.getTime().toString();
            var comment = new Object();
            comment.text = selection.toString();
            var selTxt = hpath(range.startContainer) + '|' + range.startOffset + '|' + hpath(range.endContainer) + '|' + range.endOffset
                 + '|' + color + '|' + highlightId +'=' + timeStamp + '|' + JSON.stringify(comment);
            selTxt = selTxt.replace(/(\/EUDIC\[.*?\])/g,'')
            if (gPlatform == 'ios') {
                document.getElementById('viewport').setAttribute('content', 'initial-scale=1.0, minimum-scale=1.0,  maximum-scale=1.0, shrink-to-fit=no');
            } else if (gPlatform == 'android') {
                window.location.href = 'cmd://highLightRange?' + selTxt;
            }
            document.designMode = 'on';
            document.execCommand('strikeThrough', false, '');
            document.designMode = 'off';
            if (gPlatform == 'ios') {
                document.getElementById('viewport').setAttribute('content', 'initial-scale=1.0, minimum-scale=1.0, shrink-to-fit=no');
            }            
            if (gPlatform != 'android') {
                selection.removeAllRanges();
            }            
            setStrikeAttribute(timeStamp, color);
            return selTxt;
        }
    }
}

function isValidHighlightRange(range)
{
    if (range != null) {
        var ancNode = range.commonAncestorContainer;
        if (ancNode && !(/body/i).test(ancNode.tagName) && !(/expBody/i).test(ancNode.id)) {
            return true;
        }
    }
    return false;
}

//恢复 高亮内容
function restoreHighLight(selectionDetailsList) {
    if (selectionDetailsList != null) {
        //更新老版本高亮颜色
        selectionDetailsList = selectionDetailsList.replace(/#fdf2a0/gi, '#FFFF00');
        selectionDetailsList = selectionDetailsList.replace(/(\/EUDIC\[.*?\])/g,'');
        selectionDetailsList = selectionDetailsList.split('$');
        var i = 0;
        if (gPlatform == 'ios') {
            document.getElementById('viewport').setAttribute('content', 'initial-scale=1.0, minimum-scale=1.0,  maximum-scale=1.0, shrink-to-fit=no');
        }
        document.designMode = 'on';
        for (i = 0; i < selectionDetailsList.length; i++) {
            var selectionDetails = selectionDetailsList[i].split('|');
            if (typeof window.getSelection != 'undefined' && selectionDetails.length > 3) {
                var selection = window.getSelection();
                selection.removeAllRanges();
                try {
                    var range = document.createRange();
                    range.setStart(document.evaluate(selectionDetails[0], document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[1]));
                    range.setEnd(document.evaluate(selectionDetails[2], document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue, Number(selectionDetails[3]));
                    selection.addRange(range);
                    document.execCommand('strikeThrough', false, '');
                    selection.removeAllRanges();

                    if (selectionDetails.length > 6) {
                        var timeStamp = selectionDetails[5].match(/data-uuid=(\w+)/)[1];
                        if (selectionDetails[6].match('"has_comment":true')) {//定死字段
                            setStrikeAttribute(timeStamp, selectionDetails[4], 'true');
                        } else {
                            setStrikeAttribute(timeStamp, selectionDetails[4]);
                        }
                    } else {//向后兼容
                        setStrikeAttribute(i, selectionDetails[4]);
                    }
                } catch (e) { ;}
            }
        }
    }
    document.designMode = 'off';
    if (gPlatform == 'ios') {
        document.getElementById('viewport').setAttribute('content', 'initial-scale=1.0, minimum-scale=1.0, shrink-to-fit=no');
    }
}

function hpath(node, currentPath) {
    currentPath = currentPath || '';
    if (node.className == 'explain_wrap' || node.className == 'explain_wrap_styleless')
        return '//DIV[@id=\"' + node.id + '\"]/' + currentPath;
    switch (node.nodeType) {
        case 3:
        case 4:
            return hpath(node.parentNode, 'text()[' + (document.evaluate('preceding-sibling::text()', node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']');
        case 1:
            return hpath(node.parentNode, node.nodeName + '[' + (document.evaluate('preceding-sibling::' + node.nodeName, node, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null).snapshotLength + 1) + ']' + (currentPath ? '/' + currentPath : ''));
        case 9:
            return '/' + currentPath;
        default:
            return '';
    }
}

//修改 选中区域内，所有标记的颜色
function changeStrikeSelection(color) {
    var tags = getSelectedElements();
    var timestamps = [];
    if (tags.length == 1) {
        var oneTag = tags[0];
        while(oneTag) {
            if (oneTag.getAttribute('name') === highlightName) {
                var sign = oneTag.getAttribute(highlightId);
                timestamps.push(sign);
                setStrikeColor(sign, color);
                break;
            } else {
                oneTag = oneTag.parentElement;
            }
        }
    } else {
        for (var i = 0, el; el = tags[i]; i++) {
            if (el.getAttribute('name')) {
                var sign = el.getAttribute(highlightId);
                timestamps.push(sign);
                setStrikeColor(sign, color);
            }
        }
    }
    return timestamps.toString();
}

//修改 指定标记的dom节点 的颜色
function setStrikeColor(timeStamp, color) {
    var tags = document.getElementsByName(highlightName)
    for (var i = 0; i < tags.length; i++) {
        var tag = tags[i];
        if (tag.getAttribute(highlightId) === timeStamp) {
            setStrikeColorStyle(tag, color);
             if (hasClass(tag.nextSibling, 'strikeComment')) {
                tag.nextSibling.style.color = RGBColor(tag.style.backgroundColor).toStrikeCommentColor();
            }   
        }
    }
    return tags;
}

//设置 未带标识的strike标签 的标志，及颜色。
function setStrikeAttribute(timeStamp, color, hasComment) {
    var tags = document.getElementsByTagName('strike');
    var lasttag = null;
    for (var i = 0; i < tags.length; i++) {
        var tag = tags[i];
        if (tag.getAttribute('name') === null) {
            tag.setAttribute('name', highlightName);
            tag.setAttribute(highlightId, timeStamp);
            setStrikeColorStyle(tag, color); 
        }
        if (tag.getAttribute(highlightId) === timeStamp) {
        	lasttag = tag;
        }
    }
    if (lasttag) {
    	setStrikeCommentStyle(lasttag, hasComment);
    }
    return tags;
}

//修改 特定标记 的颜色，以及标注状态
function changeStrikeAtrribute(timeStamp, color, hasComment) {
    var tags = document.getElementsByName(highlightName)
    var lasttag = null;
    for (var i = 0; i < tags.length; i++) {
        var tag = tags[i];
        if (tag.getAttribute(highlightId) === timeStamp) {       
            setStrikeColorStyle(tag, color);
            lasttag = tag;            
        }
    }
    if (lasttag) {
        setStrikeCommentStyle(lasttag, hasComment);
    }
    return tags;
}

function setStrikeColorStyle (tag, color) {
    if ((typeof(color) !== undefined) && (color !== 'default')) { //oc 传递参数只有字符串,default就不改动
        tag.style.backgroundColor=color;
    }
}

function setStrikeCommentStyle (tag, hasComment) { 
    var nextSibling = tag.nextSibling || tag;
    if (hasComment == null || hasComment === 'false'|| hasComment === '0') {
        if (hasClass(nextSibling, 'strikeComment'))
        {
            var el = nextSibling;
            el.parentNode.removeChild(el);
        }
    } else {
        if (!hasClass(nextSibling, 'strikeComment')) {
            var commentIcon = document.createElement('span');
            commentIcon.className = 'icon-web-comment-icon strikeComment';
            commentIcon.style.color = RGBColor(tag.style.backgroundColor).toStrikeCommentColor();
            commentIcon.addEventListener('click', function() {window.location = 'cmd://highlight/comment/' + tag.getAttribute(highlightId);})

            if (nextSibling === tag) {
                tag.parentNode.appendChild(commentIcon);
            } else {
                tag.parentNode.insertBefore(commentIcon, tag.nextSibling);
            }
        }        
    }
}

//移除 选中内所有的标记
function removeSeletedStrike() {
    var tags = getSelectedElements();
    var timestamps = [];

    if (tags.length == 1) {
        //当只有一个时，一直往上遍历父节点，查找到有标记的父节点，再进行删除操作。
        //否则会有部分标签，比如button标签，无法直接查找到。
        var oneTag = tags[0];
        while(oneTag) {
            if (oneTag.getAttribute('name') === highlightName) {
                var sign = oneTag.getAttribute(highlightId);
                timestamps.push(sign);
                removeStrike(sign);
                break;
            } else {
                oneTag = oneTag.parentElement;
            }
        }
    } else {
        for (var i = 0, el; el = tags[i]; i++) {
            if (el.getAttribute('name')) {
                var sign = el.getAttribute(highlightId);
                timestamps.push(sign);
                removeStrike(sign);
            }
        }
    }
    return timestamps.toString();
}

//返回所有选中区域的dom
function getSelectedElements() {
    // http://stackoverflow.com/questions/4220478/get-all-dom-block-elements-for-selected-texts
    var selection = window.getSelection();
    if (selection.rangeCount === 0) {
        return [];
    }
    var range = selection.getRangeAt(0);
    var commonDiv = range.commonAncestorContainer;
    if (commonDiv.childNodes.length == 0) {
        return [commonDiv.parentElement];
    }
    
    var allWithinRangeParent = commonDiv.getElementsByTagName("*");
    var allSelected = [];
    for (var i = 0, el; el = allWithinRangeParent[i]; i++) {
        // The second parameter says to include the element
        // even if it's not fully selected
        if (selection.containsNode(el, true)) {
            allSelected.push(el);
        }
    }
    var list = [];
    for (node in allSelected) {
        if (allSelected[node].childElementCount > 0) {;} 
        else {
            list.push(allSelected[node]);
        }
    }
    return list;
}

function selectedInCustomNote() {
    var list = getSelectedElements()
    for (var i=0, el; el = list[i]; i++) {
        var parentE = el;
        while (parentE.parentElement.nodeName != 'BODY') {
            if (parentE.getAttribute('id') === 'expCustomNote') {
                return true;
            }
            parentE = parentE.parentElement;
        }
    }
    return false;
}

//移除 含有对应标志dom节点
function removeStrike(sign) {
    var tags = document.getElementsByName(highlightName)
    var index = 0;
    while (index < tags.length){
        var newTag = tags[index];
        //在词典中，某些tag一旦replace，那么tags的就会移除一个tag，导致遗漏一个查找。此时不增加index。
        if (newTag.getAttribute(highlightId) === sign) {
            setStrikeCommentStyle(newTag, 'false');
            if (newTag.childElementCount > 0){
                removeSelf(newTag);
            }
            else if ( typeof(newTag.replaceWith) === 'undefined') {
                removeSelf(newTag);
            } else {
                newTag.replaceWith(newTag.innerText);
            }
        } else {
            index ++;
        }
    }
    return tags;
}

//查询 是否含有高亮内容
function hasHighlight() {
    var tags = getSelectedElements();
    for (var i = 0, el; el = tags[i]; i++) {
        var timestamp = getParentHighlightId(el);
        if (timestamp.length > 0) {
            return timestamp;
        }
    }
    return '';
}

function getParentHighlightId(tag) {
    while(tag) {
        if (tag.getAttribute('name') === highlightName) {
            return tag.getAttribute(highlightId);
        } else {
            tag = tag.parentElement;
        }
    }
    return '';
}

//删除 自身节点，保留子节点。
function removeSelf(node) {
    while (node.firstChild) {
        node.parentNode.insertBefore(node.firstChild, node);
    }
    node.parentNode.removeChild(node);
}

//返回 选中区域rect
function getRangeRect() {
    if (typeof window.getSelection != 'undefined') {
        var selection = window.getSelection();
        var range = selection.getRangeAt(0);
        if (range != null) {
            var zoomRatio = document.body.getBoundingClientRect().width / document.getElementById("expBody").getBoundingClientRect().width;
            var offset = range.getBoundingClientRect();
            var rect = {
            top: zoomRatio * (offset.boundingTop || offset.top),
            left: zoomRatio * (offset.boundingLeft || offset.left),
            width: zoomRatio * (range.boundingWidth || offset.width),
            height: zoomRatio * (range.boundingHeight || offset.height),
            }
            window.location.href = 'cmd://highlight/rect/' + JSON.stringify(rect);
            return "{{" + rect.left + "," + rect.top + "}, {" + rect.width + "," + rect.height + "}}"
        }
    }
}

//监听选中区域变化
function selectChangeFun() {
    var t = selectedText();
    if (!!t) {
        if (gPlatform === 'android') {
            window.TextSelection.textChanged(t);
        }
        var highlightId = hasHighlight();
        if (highlightId.length > 0) {
            window.location.href = 'cmd://highlight/select/' + highlightId;
        } else {
            window.location.href = 'cmd://highlight/select/none';
        }        
    }
    else if (gPlatform === 'ios')
    {
        window.location.href = 'cmd://highlight/select/noselection';
    }
}

function selectedText() {
    return window.getSelection().toString();
}
/* 高亮标记代码 结束 */


function smoothScrollTo(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        increment = 20;

    var animateScroll = function(elapsedTime) {        
        elapsedTime += increment;
        var position = easeInOut(elapsedTime, start, change, duration);                        
        element.scrollTop = position; 
        if (elapsedTime < duration) {
            setTimeout(function() {
                animateScroll(elapsedTime);
            }, increment);
        }
    };

    animateScroll(0);
}

function easeInOut(currentTime, start, change, duration) {
    currentTime /= duration / 2;
    if (currentTime < 1) {
        return change / 2 * currentTime * currentTime + start;
    }
    currentTime -= 1;
    return -change / 2 * (currentTime * (currentTime - 2) - 1) + start;
}

function hasClass(element, cls) {
    if (element === null) return false;
    if (!element.className) return false;
    return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

//颜色转换相关
function RGBColor(color_string)
{
    this.ok = false;

    // strip any leading #
    if (color_string.charAt(0) == '#') { // remove # if any
        color_string = color_string.substr(1,6);
    }

    color_string = color_string.replace(/ /g,'');
    color_string = color_string.toLowerCase();
 
    // array of color definition objects
    var color_defs = [
        {
            re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
            example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
            process: function (bits){
                return [
                    parseInt(bits[1]),
                    parseInt(bits[2]),
                    parseInt(bits[3])
                ];
            }
        },
        {
            re: /^(\w{2})(\w{2})(\w{2})$/,
            example: ['#00ff00', '336699'],
            process: function (bits){
                return [
                    parseInt(bits[1], 16),
                    parseInt(bits[2], 16),
                    parseInt(bits[3], 16)
                ];
            }
        },
        {
            re: /^(\w{1})(\w{1})(\w{1})$/,
            example: ['#fb0', 'f0f'],
            process: function (bits){
                return [
                    parseInt(bits[1] + bits[1], 16),
                    parseInt(bits[2] + bits[2], 16),
                    parseInt(bits[3] + bits[3], 16)
                ];
            }
        }
    ];

    // search through the definitions to find a match
    for (var i = 0; i < color_defs.length; i++) {
        var re = color_defs[i].re;
        var processor = color_defs[i].process;
        var bits = re.exec(color_string);
        if (bits) {
            channels = processor(bits);
            this.r = channels[0];
            this.g = channels[1];
            this.b = channels[2];
            this.ok = true;
        }
    }

    // validate/cleanup values
    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);

    // some getters
    this.toRGB = function () {
        return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
    }
    this.toHex = function () {
        var r = this.r.toString(16);
        var g = this.g.toString(16);
        var b = this.b.toString(16);
        if (r.length == 1) r = '0' + r;
        if (g.length == 1) g = '0' + g;
        if (b.length == 1) b = '0' + b;
        return '#' + r + g + b;
    }

    this.toHsv = function () {
        return RGBtoHSV(this.r, this.g, this.b);
    }

    //高亮笔记中使用，动态计算批注标示的颜色
    this.toStrikeCommentColor = function() {
        var hsl = toHsv();
        var newColor = HSVtoRGB(hsl.h, 0.84, 0.87);
        this.r = newColor.r; this.g = newColor.g; this.b = newColor.b;
        return toHex();
    }
    function HSVtoRGB(h, s, v) {
        var r, g, b, i, f, p, q, t;
        if (arguments.length === 1) {
            s = h.s, v = h.v, h = h.h;
        }
        i = Math.floor(h * 6);
        f = h * 6 - i;
        p = v * (1 - s);
        q = v * (1 - f * s);
        t = v * (1 - (1 - f) * s);
        switch (i % 6) {
            case 0: r = v, g = t, b = p; break;
            case 1: r = q, g = v, b = p; break;
            case 2: r = p, g = v, b = t; break;
            case 3: r = p, g = q, b = v; break;
            case 4: r = t, g = p, b = v; break;
            case 5: r = v, g = p, b = q; break;
        }
        return {
            r: Math.round(r * 255),
            g: Math.round(g * 255),
            b: Math.round(b * 255)
        };
    }
    
    function RGBtoHSV(r, g, b) {
        if (arguments.length === 1) {
            g = r.g, b = r.b, r = r.r;
        }
        var max = Math.max(r, g, b), min = Math.min(r, g, b),
            d = max - min,
            h,
            s = (max === 0 ? 0 : d / max),
            v = max / 255;

        switch (max) {
            case min: h = 0; break;
            case r: h = (g - b) + d * (g < b ? 6: 0); h /= 6 * d; break;
            case g: h = (b - r) + d * 2; h /= 6 * d; break;
            case b: h = (r - g) + d * 4; h /= 6 * d; break;
        }

        return {
            h: h,
            s: s,
            v: v
        };
    }
 
    return this;
}
var gPlatform = 'win';
 
function SetInnerHTML(elName, _html)
{
    var thisEl;
    thisEl = document.getElementById(elName);
    thisEl.innerHTML = _html;
}

function ErrorSetting(msg, file_loc, line_no)
{return true;}

function xreplace(checkMe,toberep,repwith){
var temp = checkMe;
var i = temp.indexOf(toberep);
while(i > -1)
{
temp = temp.replace(toberep, repwith);
i = temp.indexOf(toberep, i + 1);
}
return temp;
}

// 全球发音
var createGlobalVoiceDiv={
    main:function(data){
        var g=document.getElementsByClassName("globalVoiceLink")[0],b=document.getElementById("expBody"),d=JSON.parse(data),s='';
 
        for(var i in d.pronounces){
            var o=d.pronounces[i]
            var sex=o.sex=="m" ? "男" : "女";
            s+='<div class="gv_item" ><a class="gv_button" href="cmd://dict/global_voice/speak/'+o.mp3url+'"></a><span class="gv_person">'+sex+'</span><span class="gv_contury">'+o.country_cn+'</span><span class="likeItem" data-id="'+o.id+'" data-show="false" id=""><a class="like" onclick="createGlobalVoiceDiv.showPraiseNum(this)" data-number="'+o.voteup+'" >赞</a><a class="disLike" onclick="createGlobalVoiceDiv.showPraiseNum(this)" data-number="'+o.votedown+'">踩</a></span></div>';
        }
 
        var g_div=document.createElement("DIV");
        if(document.getElementsByClassName("gv_content")[0]){
            document.getElementsByClassName("gv_content")[0].style.display="block";
        }else{
             g_div.style.cssText="position:absolute;left:"+g.offsetLeft+";top:"+g.offsetTop;
             g_div.innerHTML='<div class="gv_content" ><span class="gv_arrtop"></span><span class="gv_arrtopSide"></span><div class="gv_title"><p>有<em class="gv_count">'+d.pronounces.length+'</em>个发音</p><a class="gv_close" onclick="createGlobalVoiceDiv.closeGlobalVoiceDiv()">+</a></div><div class="gv_details">'+s+'</div></div>'
             b.appendChild(g_div)
        }

        g_div.addEventListener('click',function(e){
            e.stopPropagation()
        },false)
        document.addEventListener('click',createGlobalVoiceDiv.closeGlobalVoiceDiv,false)
         
    },
    closeGlobalVoiceDiv:function(){
        document.getElementsByClassName("gv_content")[0].style.display="none";
    },
    showPraiseNum:function(e){
        var _self=e,
            _self_p=e.parentNode,
            id=_self_p.getAttribute("data-id"),
            like=_self_p.getElementsByClassName("like")[0],
            disLike=_self_p.getElementsByClassName("disLike")[0];
 
        if(_self_p.getAttribute("data-show")==="false"){
            like.innerHTML=like.getAttribute("data-number");
            disLike.innerHTML=disLike.getAttribute("data-number");
            _self_p.setAttribute("data-show","true");
 
            if(e.className==="like"){
                window.location.href="cmd://dict/global_voice/voteup/"+id
            }else{
                window.location.href="cmd://dict/global_voice/votedown/"+id
            }
 
        }
    }
}
//置顶
if(document.getElementById("scrollToTop")){
    function fncScrollTop(){
        window.scrollTo(0,0)
    }

    var tops = document.getElementById('scrollToTop');
    function f(){
        var z=document.documentElement.scrollTop || document.body.scrollTop;
        if(z>50){
            tops.style.display="block";
        }else{
            tops.style.display="none";
        }
    }

    function fncSroll(f,s,s1){
        var time=null;
        var previous=null;
        return function(){
            var now=+new Date();
            if(!previous) previous=now;
            if(now-previous>s1){
                f();
                previous=now;
                   //clearTimeout(timer);
            }else{
                clearTimeout(time)
                time=setTimeout(function(){f()},s)
            }
        }
    }    
    window.onscroll=fncSroll(f,100,3000)
    
}

function expandAll(){
    expandAllByClassName("explain_wrap");
    expandAllByClassName("explain_wrap_styleless")
}

function expandAllByClassName(classname){
    var nodes=document.getElementsByClassName(classname);
    var firstElStatus = null;
    for(var i=0;i<nodes.length;i++){
        var thisId=nodes[i].id;
        var thisEl=document.getElementById(thisId+"Child");
        if(thisEl!=null){
            if(thisEl.style.display != "none"){
                thisEl.style.display="block"
            }if(firstElStatus == null){
                firstElStatus = thisEl.style.display
            }if(thisEl.style.display == firstElStatus){
                expandIt(thisId)
            }
        }
    }
}

function expandIt(el) {
	var parent = document.getElementById(el), thumbImg = document.getElementById('word-thumbnail-image'), hideFlag = false;
	if(thumbImg!= null && thumbImg.parentNode == parent){
		hideFlag = true;
	}
    whichEl = document.getElementById(el + "Child");
    whichIm = document.getElementById(el + "Img");
    if (whichEl.style.display != "none") {
        whichEl.style.display = "none";
        whichIm.src = "expand.png";
        if(hideFlag){
        	thumbImg.style.display = 'none';
        }
    }
    else {
        whichEl.style.display = "block";
        whichIm.src = "collapse.png";
      
        if(hideFlag){
        	thumbImg.style.display = 'block';
        }
    }
 }
 
 function getIndex(el) {
    ind = null;
    for (i=0; i<document.layers.length; i++) {
        whichEl = document.layers[i];
        if (whichEl.id == el) {
            ind = i;
            break;
        }
    }
    return ind;
}

//annotation
var gHighLightedElements;
var curHighlightId;
var MAX_SEARCH_HIGHLIGHT_COUNT = 100;

function highlight (rootnode, pattern) {
	//init
	removeHighlight();
	curHighlightId = -1;
	gHighLightedElements = new Array;
	
	//highlight
	var nodelist = new Array();
	var upattern = pattern.toUpperCase();
 
	nodelist.push(rootnode);
	while(nodelist.length>0)
	{
		var pos;
		var node = nodelist.shift();
		if (node.nodeType == 3) {
			pos = node.data.toUpperCase().indexOf(upattern);
			if (pos >= 0) {
				var spannode = document.createElement('span');
				spannode.className = 'highlight';
				m = node.splitText(pos);
				e = m.splitText(upattern.length);
				mclone = m.cloneNode(true);
				spannode.appendChild(mclone);
				m.parentNode.replaceChild(spannode, m);
				gHighLightedElements.push(spannode);
				nodelist.unshift(e);
				if (gHighLightedElements.length >= MAX_SEARCH_HIGHLIGHT_COUNT)
					break;
			};
		} else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
			for (var i = node.childNodes.length - 1; i >= 0; i--){
				nodelist.unshift(node.childNodes[i]);
			};
		}
	}
	return gHighLightedElements.length;
}

function removeHighlight() {
	var nodelist = document.getElementsByTagName('span');
	for (var i = nodelist.length - 1; i >= 0; i--){
		var node = nodelist[i];
		if (node.className == 'highlight' || node.className == 'cur-highlight') {
			with (node.parentNode) {
				replaceChild(node.firstChild, node);
				normalize();
			}
		};
	};
};

function clearHighLight()
{
	document.execCommand("SelectAll");
	document.designMode = 'on'; 
	document.execCommand('backcolor', false, 'transparent'); 
	document.designMode = 'off';
	window.getSelection().removeAllRanges();
}

function scrollToHighlight(step) {
	if(gHighLightedElements.length == 0)
		return;
	
	index = curHighlightId + step;
	
	if (index>=gHighLightedElements.length)
		index = 0;
	else if (index < 0)
		index = gHighLightedElements.length + index;
	var e = gHighLightedElements[index];
	makeVisible(e);
	e.scrollIntoView(true);
	window.scrollBy(0,-20);
	if(curHighlightId!=-1)
		gHighLightedElements[curHighlightId].className = "highlight";
	setCurHighlight(e);	
	curHighlightId = index;
};

function setCurHighlight(e) {
	e.className = "cur-highlight";
}

function addNoteImages(files, append)
{
	noteEl = document.getElementById('elCustomNoteChild');
	imgsEl = document.getElementById('customeNoteImage');
	if (!imgsEl)
	{
		imgsEl = document.createElement('div');
		imgsEl.id = 'customeNoteImage';
		imgsEl.className = 'customeNoteImage';
		noteEl.appendChild(imgsEl);	
	}
	else if (!append)
	{
		imgsEl.innerHTML = '';
	}
	var images = files.split("|");
	for (var i = 0; i < images.length; i++) {
		if (images[i] !== "")
		{		
			var imgdiv = new Image(100,100);
			imgdiv.setAttribute('height', 'auto');
			imgdiv.src = images[i];
			imgsEl.appendChild(imgdiv);		
		}		
	}
}

//确保要查询的节点是可见的
function makeVisible(e)
{
	if (e == document)
		return;

	var style = window.getComputedStyle(e);
	if (style.display == 'none') {
		e.style.display = 'block';
	}

	if (style.visibility == 'hidden') {
		e.style.visibility = 'visible';
	}
	makeVisible(e.parentNode);
}

//wiki
function setup_wiki()
{
	$("#logo").click(function() {$("#nav").toggle();})
	$("h2.section_heading").click(function() {
	  //var section_idx = parseInt($(this).get(0).id.replace( /section_(\d+)/, "$1" ));
	  //wm_toggle_section( section_idx );
	  wm_toggle_section($(this));
	})
	$("a").click(function() {
				 var link = $(this).get(0)
				 if( link.hash.indexOf("#") == 0 ) {
				 wm_reveal_for_hash( link.hash )
				 }
				 })
	
	if( document.location.hash.indexOf("#") == 0 ) {
		wm_reveal_for_hash( document.location.hash )
	}
	updateOrientation();
	decode = $("#searchField");
	decode.val(unescape(decode.val()));
	decode = $("title");
	decode.html(unescape(decode.html()));
}


function wm_reveal_for_hash( hash ) {
	var targetel = $(hash)
	if(targetel) {
		var parentdiv = targetel.parents("div.content_block")
		if(parentdiv.length > 0 && ! parentdiv.is(':visible')) {
			var section_idx = parseInt(parentdiv.get(0).id.replace( /content_(\d+)/, "$1" ));
			wm_toggle_section( section_idx )
		}
	}
}

function wm_toggle_section(section_item ) {
    section_item.children("button.show").toggle();
	section_item.children("button.hide").toggle();
	
	section_item.next().toggle();
    section_item.next().next().toggle();
    //$("div#content_" + section_id).toggle()
	//$("div#anchor_" + section_id).toggle()
}


//study flag
function SetCaptureStudyFlag(f)
{
	thisEl = document.getElementById('studyFlag');
	var studyHtml = "";
	//if (f > 0)
		//studyHtml += "<a id=\"studyCatPicker\" href=\"cmd://studyflag0\"><img border=0 width=20 height=20 align=\"middle\" alt=生词本分组 src=\"starGroup.png\" style=\"padding-right:10px;padding-top:5px;\"></img></a>";
	
	for (i=1; i<=5; i++) {
		if(i<=f)
		{studyHtml += "<a href=cmd://studyflag" + i +"><img width=20 height=20 border=0 alt=生词本等级" + f + " src=\"star.png\"></img></a> ";}
		else
		{studyHtml += "<a href=cmd://studyflag" + i +"><img width=20 height=20 border=0 alt=生词本等级" + f + " src=\"starGhost.png\"></img></a> ";}
	}
    thisEl.innerHTML = studyHtml;
}


var levelChooseUtil = {
	hasCls : function(el, cls) {
		var flag = false;
		if(el != null && "className" in el) {
			var clss = el.className.split("\s+");
			for(var i = 0; i < clss.length; i++) {
				if(clss[i] == cls) {
					flag = true;
					break;
				}
			}
		}
		return flag;
	},
	offset : function(el) {
		var parent = el, top, left, width, height;
		top = parent.offsetTop;
		left = parent.offsetLeft;
		width = parent.offsetWidth;
		height = parent.offsetHeight;
		while(parent != parent.offsetParent && parent != document.body) {
			parent = parent.offsetParent;
			top += parent.offsetTop;
			left += parent.offsetLeft;
			width += parent.offsetWidth;
			height += parent.offsetHeight;
		}
		return {
			top : top,
			left : left,
			width : width,
			height : height
		}
	},
	bind : function(el, ev, fn, caller) {
		var caller = caller;
		el.addEventListener(ev, function(ev) {
                            var el = ev.target;
                            fn.call(caller, ev);
                            }, false);
	},
	parentByCls : function(el, cls) {
		var parent = el, flag = false;
		do {
			if(this.hasCls(parent, cls)) {
				flag = true;
			}
			parent = parent.parentNode;
		} while(parent);
		if(flag == false) {
			parent = null;
		}
		return parent;
	}
};
 
var levelChoose = function(config) {
	var starWidth = this.starWidth = 30;

	if("el" in config && config.el != null) {
		if( typeof config.el == "string") {
			config.el = document.getElementById(config.el);
			if(config.el == null) {
				config.el = document.getElementsByName(config.el);
				if(config.el != null && config.el.length) {
					config.el = config.el[0];
				} else {
					return;
				}
			}
            
		}
	} else {
		return;
	}
    
	var cfg = {
		level : 0,
		rank : [0, starWidth * 1, starWidth * 2, starWidth * 3, starWidth * 4, starWidth * 5],
		opacityOnMove : 0.3,
		scaleOnMove : 2,
		minLevel : 1
	}, self = this;
	for(var p in config) {
		cfg[p] = config[p];
	}
	this.config = config = cfg;
	this.backgroundStar = config.el;
	this.selectedStar = this.backgroundStar.children[0];
	//
	config.el.onselect = config.el.onselectstart = function() {
		return false;
	}
//	levelChooseUtil.bind(config.el, "touchstart", self.touchDown, self);
//	levelChooseUtil.bind(config.el, "touchmove", self.touchMove, self);
//	levelChooseUtil.bind(config.el, "touchend", self.touchLeave, self);
	//
	levelChooseUtil.bind(config.el, "mousedown", self.touchDown, self);
	levelChooseUtil.bind(config.el, "mousemove", self.touchMove, self);
	levelChooseUtil.bind(config.el, "mouseup", self.touchLeave, self);
	levelChooseUtil.bind(config.el, "mouseout", self.mouseout, self);
	//levelChooseUtil.bind(this.backgroundStar, "mouseout", self.touchLeave, self);
	/*
	 * reset
	 */
	if(config.level != null) {
		this.initLevel(config.level);
	}
};
levelChoose.prototype = {
	touchDown : function(ev) {
		this.mouseDownFlag = true;
		this.mouseMoveFlag = false;
		var el, ev1;
		if("targetTouches" in ev) {
			ev1 = ev.targetTouches[0];
			el = document.elementFromPoint(ev1.clientX, ev1.clientY)
		} else {
			ev1 = ev;
			el = ev.target;
		}
		var offset = levelChooseUtil.offset(this.selectedStar);
        var clickTarget = ev1.target;
        var item;
        if(clickTarget && /level/.test(clickTarget.className)){
            item = clickTarget.className.substring(5)-1;
        }else{
            item = 6;
        }
		var move = item*this.starWidth;
        this.move = move;
		var self = this;
		this.timeoutMove = setTimeout(function() {
                                      var f1 = true;
                                      if(self.isStar(el)) {
                                      f1 = false;
                                      }
                                      for(var i = 0; i < self.selectedStar.children.length; i++) {
                                      var o = self.selectedStar.children[i];
                                      if(f1) {
                                      o.style.opacity = 0;
                                      } else {
                                      o.style.opacity = self.config.opacityOnMove;
                                      }
                                      if(o == el && f1 == false) {
                                      f1 = true;
                                      }
                                      }
                                      }, 100);
		ev.preventDefault();
	},
	touchMove : function(ev) {
		var el, ev1;
		if("targetTouches" in ev) {
			ev1 = ev.targetTouches[0];
			el = document.elementFromPoint(ev1.clientX, ev1.clientY)
		} else {
			ev1 = ev;
			el = ev.target;
		}
		if(this.mouseDownFlag == true) {
			this.mouseMoveFlag = true;
			var offset = levelChooseUtil.offset(this.selectedStar);
			var move = this.move;
			if(this.isStar(el)) {
				var f1 = true;
				for(var i = 0; i < this.selectedStar.children.length; i++) {
					var o = this.selectedStar.children[i];
					if(f1) {
						o.style.opacity = this.config.opacityOnMove;
					} else {
						o.style.opacity = 0;
					}
					if(o == el) {
						o.style["-webkit-transform"] = "scale(" + this.config.scaleOnMove + ")";
						f1 = false;
					} else {
						o.style["-webkit-transform"] = "scale(1)";
					}
				}
			}
		}
		ev.preventDefault();
	},
	isStar : function(el) {
		if("className" in el && el.className.indexOf("level") == 0) {
			return true;
		}
		return false;
	},
	touchLeave : function(ev) {
		clearTimeout(this.timeoutMove);
		var rnk = this.config.rank;
		var el = ev.target;
		var move = this.move;
		for(var i = this.config.minLevel; i < rnk.length; i++) {
			if(this.move >= rnk[i - 1] && this.move < rnk[i]) {
				/*if(this.mouseMoveFlag == true) {
				 if(i > 0 && this.move < (rnk[i - 1] + (rnk[i] - rnk[i - 1]) / 2)) {
				 this.setLevel(i - 1);
				 } else {
				 this.setLevel(i);
				 }
				 } else {
				 this.setLevel(i);
				 }*/
				this.setLevel(i);
				break;
			} else {
				if(move < rnk[0]) {
					this.setLevel(this.config.minLevel);
				}
			}
		}
		this.mouseDownFlag = false;
		this.mouseMoveFlag = false;
	},
	mouseout : function(ev) {
		if(this.mouseDownFlag == true && this.mouseMoveFlag == true) {
			clearTimeout(this.timeoutMove);
			var rnk = this.config.rank;
			var move = this.move;
			for(var i = 1; i < rnk.length; i++) {
				if(this.move >= rnk[i - 1] && this.move < rnk[i]) {
					this.setLevel(i);
					break;
				}
			}
			this.mouseDownFlag = false;
			this.mouseMoveFlag = false;
		}
	},
	setLevel : function(i) {
		var a = this.selectedStar.children;
		for(var j = 0; j < a.length; j++) {
			a[j].style["-webkit-transform"] = "scale(1)";
			if(j < i) {
				a[j].style.opacity = 1;
			} else {
				a[j].style.opacity = 0;
			}
		}
		//
		var btnGroup = document.getElementById(this.config.group);
		if(i > 0) {
			btnGroup.style.display = "block";
		} else {
			btnGroup.style.display = "none";
		}
		var defaultTips = document.getElementById("J_LevelChooseDefaultTips");
		var successTips = document.getElementById("J_LevelChooseSuccessTips");
		if(i > 0) {
			defaultTips.style.display = "none";
			successTips.style.display = "block";
			successTips.style["-webkit-animation-name"] = "changeLevelSuccessShow";
			setTimeout(function() {
                       successTips.style.display = "none";
                       }, 2000);
		} else {
			defaultTips.style.display = "block";
		}
 
		window.location = "cmd://studyflag" + i;
	},
	initLevel : function(i) {
        var a;
        if(this.selectedStar==undefined){
            return false;
        }else{
            a=this.selectedStar.children;
        }
		for(var j = 0; j < a.length; j++) {
			a[j].style["-webkit-transform"] = "scale(1)";
			if(j < i) {
				a[j].style.opacity = 1;
			} else {
				a[j].style.opacity = 0;
			}
		}
		// 
		var btnGroup = document.getElementById(this.config.group);
		if(i > 0) {
			btnGroup.style.display = "block";
		} else {
			btnGroup.style.display = "none";
		}
		var defaultTips = document.getElementById("J_LevelChooseDefaultTips");
		var successTips = document.getElementById("J_LevelChooseSuccessTips");
		if(i > 0) {
			defaultTips.style.display = "none";
		}
	}
};

function setStarLevel(rate)
{
    if (window.starLevel != null) {
        window.starLevel.initLevel(rate);
    }
    else
    {
        window.starLevel = new levelChoose({ el: "J_LevelChoose", level: rate, group: "J_BtnCatePicker" });
	} 	 

	//Collection star
	var startCollection =document.getElementById('cap_word_star');
    if(startCollection){
        if(gPlatform == 'mac'){
            document.getElementById("cap_btn_detail").style.display="none";
        }
        var s=startCollection.getElementsByTagName("img")[0]
        if(rate>0){
            startCollection.getElementsByTagName("img")[0].src="star.png";
            s.style.display="block";
        }else{
            s.src="starGhost.png";
            if(gPlatform == 'mac'){
                s.style.display="none";
            }
        }
    }

}

function processWikiDict() {    
    /* 添加图片点击方法 */
    var lang = document.getElementsByClassName("wiki-content");
    for (var j = 0; j < lang.length; j++) {
        var imgLangNow = lang[j].getElementsByClassName('image-wrap');
        if (imgLangNow) {
            for (var idx = 0, len = imgLangNow.length; idx < len ; idx++) {
                var eachImg = imgLangNow[idx].getElementsByTagName('img')[0];
                eachImg.setAttribute('lang', lang[j].getAttribute('lang'));
                eachImg.onclick = function (ev) {
                    var imgSrc = this.getAttribute('src');
                    var thislang = this.getAttribute('lang');
                    var imgName = imgSrc.substring(imgSrc.lastIndexOf('/') + 1);
                    window.location.href = 'cmd://wiki/' + thislang + "/" + imgName;
                }
            }
        }
    }
}

function getWikiDictImg() {
   /* 图片列表方法 */
    var imgList = [];
    var lang = document.getElementsByClassName("wiki-content");
    for (var j = 0; j < lang.length; j++) {
        var imgLangNow = lang[j].getElementsByClassName('image-wrap');
        if (imgLangNow) {
            for (var i = 0, len = imgLangNow.length; i < len ; i++) {
                var imginfo = {};
                var imgAlt = '';
                var eachImg = imgLangNow[i].getElementsByTagName('img')[0];
                var imgSrc = eachImg.getAttribute('src');
                if (eachImg.getAttribute('alt')) {
                    imgAlt = imgLangNow[i].getAttribute('alt');
                } else {
                    imgAlt = '';
                }
                var imgName = imgSrc.substring(imgSrc.lastIndexOf('/') + 1);
                imginfo['cmd'] = "cmd://wiki/" + lang[j].getAttribute('lang') + "/" + imgName;
                imginfo['imgurl'] = imgSrc;
                imginfo['imgAlt'] = imgAlt;
                imgList.push(imginfo);
            }
        }
    }
    return JSON.stringify(imgList);
}

function resizeInfoColumn($node, reset) {
  var table = document.getElementById($node);
  var normal = table.getElementsByClassName('normal-item');
  var title = table.getElementsByClassName('title');
  function setHeight($dom) {
  	if(reset) {
  		for(var i = 0, l = $dom.length; i < l; i++) {
	    var p = $dom[i].getElementsByTagName('p');
	      for(var j = 0, k = p.length; j < k; j++) {
	        p[j].removeAttribute('style');
	      }
	    }	
  	}
    for(var i = 0, l = $dom.length; i < l; i++) {
    var h = $dom[i].currentStyle?$dom[i].currentStyle:window.getComputedStyle($dom[i], null),
        th = h.height,
        p = $dom[i].getElementsByTagName('p');
      for(var j = 0, k = p.length; j < k; j++) {
        p[j].style.height = parseInt(th) - 32 + 'px';
      }
    }
  }
  setHeight(normal);
  setHeight(title);
}

function eudic_tiku_answer(obj) {
    var curParent = obj.parentNode,
        flag = curParent.getAttribute('data-hasAnswered');
    if(flag == 0) {
        var data = curParent.getAttribute('data-trueAnswer'),
        allAnswer = curParent.getElementsByTagName('li');
        for(var i = 0, l = allAnswer.length; i < l; i++) {
            allAnswer[i].index = i;
        }
        if(allAnswer[data - 1]) {
            allAnswer[data - 1].setAttribute('class', 'correct');
        }
        if((data - 1) == obj.index) {
            obj.setAttribute('class', 'correct clickThis');
        } else {
            obj.setAttribute('class', 'error clickThis');
        }
        curParent.setAttribute('data-hasAnswered', '1');
    }                   
};

//sound
function init_sound(divid) {
    var node = document.getElementById(divid);    
    var lines = node.getElementsByClassName('line'),
        line, lineText = '', vnode, voice, isLiju = false;
    for (var i = 0; i < lines.length; i++) {
        line = lines[i];
        lineText = line.innerHTML;
		if(lineText.indexOf('tingSpeak') != -1) return;
        vnode = line.parentNode.getElementsByClassName('ljid');
        if (vnode.length > 0) {
            vnode = vnode[0];
            voice = vnode.getAttribute('voice');
            if (!voice) {
                lineText += '<img src="speak.png" class="tingSpeak" onclick="sound(this);" />';
            } else {
                if (/normal_voice/.test(voice)) {
                    lineText += '<img src="humannormal.png" class="humanSpeak" onclick="soundHuman(this);" />';
                }
                if (/slow_voice/.test(voice)) {
                    lineText += '<img src="humanslow.png" class="humanSpeak" onclick="soundHumanSlow(this);" />';
                }
            }
        } else {
            lineText += '<img src="speak.png" class="tingSpeak" onclick="sound(this);" />';
        }
        line.innerHTML = lineText;
    }
    var ljTing = document.getElementById('lj_ting');
	if (ljTing)
	{
		ljTing.addEventListener('click', function(e) {
			if (e.target.parentNode.className == 'channel') {
				sound(e.target, 'ting');
			}
		}, false);
		var iconTings = ljTing.getElementsByClassName('channel');
		for (var i = 0; i < iconTings.length; i++) {		 
			toggleTingChannelTitle(iconTings[i]);
		}
	}	
};

function toggleTingChannelTitle(el)
{
	el.onmouseover = function() {
		el.getElementsByClassName('channel_title')[0].style.visibility = "visible";
	};
	el.onmouseout = function() {
		el.getElementsByClassName('channel_title')[0].style.visibility = "hidden";
	};
}

function soundHuman(target) {
    sound(target, 'human');
}

function soundHumanSlow(target) {
    sound(target, 'slow');
}

function sound(target, flag) {
    var dataNode = target.parentNode.parentNode.parentNode;
	   if (flag && flag == 'ting') {
        dataNode = target.parentNode.parentNode;
    }
    var data = dataNode.getAttribute('data'),
        source = dataNode.getAttribute('source'),
        type = dataNode.getAttribute('type'),
        media;
    if (!data) {
        data = target.parentNode.innerText;
        data = encodeURIComponent(data);
        source = '';
        type = 'dict';
    }
    var cmdData = '?data=' + data + '&source=' + source + '&type=' + type;
    var cmd = 'cmd://speak_liju' + cmdData;
    if (flag) {
        if (flag == 'ting') {
            media = dataNode.getAttribute('media');
            cmd = 'cmd://play_ting' + cmdData + '&media=' + media;
        } else if (flag == 'human') {
            cmd = 'cmd://speak_liju' + cmdData + '&voice=human_normal';
        } else if (flag == 'slow') {
            cmd = 'cmd://speak_liju' + cmdData + '&voice=human_slow';
        }
    }
    window.location = cmd;
}
function capAddStudy(e){
    if(e.getAttribute("src").indexOf("starGhost")==-1){
        //收藏
        window.location.href='cmd://studyflag-1';
        e.setAttribute('src','starGhost.png');
    }else{
        //取消收藏
        window.location.href='cmd://studyflag1';
        e.setAttribute('src','star.png');
    }
}

//单词输入框 显示/隐藏
function capWordInputClick(){
    var wordInput=document.getElementById("cap_word_input");
    var headWord=document.getElementById("cap_word_text");
    wordInput.value=headWord.innerText;
    wordInput.style.display="block";
    wordInput.focus();
}

//单词输入框 回车
function capInputKeyPress(){
    var wordInput=document.getElementById("cap_word_input");
    var headWord=document.getElementById("cap_word_text");    
    if (event.keyCode == 13 & wordInput.value != ""){ 
        window.location.href="dic://word/" + wordInput.value; 
        wordInput.style.display="none";
        headWord.innerText=wordInput.value;
    }   
}

//单词输入框 失去焦点
function capInputBlur(){
   var wordInput=document.getElementById("cap_word_input");
    wordInput.style.display="none";
}

    var sentenceLang;
    function setBienvenuContent(json,lang) {
        var json=JSON.parse(json);
        bienvenuSetSentence(json.sentence,lang)
        bienvenuSetTing(json.ting,lang)
        sentenceLang=lang;
        document.getElementsByClassName("indexLeft")[0].getElementsByTagName("table")[0].style.display="table"
        document.getElementsByTagName("body")[0].setAttribute("class",lang+"Theme")
    }

    //兼容 window字体大小改变
    window.onresize=function(){
        if(document.getElementsByClassName("indexMain")[0]!="undenfined"){
            zoomChange()
        }
    }
    
    function zoomChange(){
        var indexMain=document.getElementsByClassName("indexMain")[0]
        var indexLeft=document.getElementsByClassName("indexLeft")[0]
        var indexRight=document.getElementsByClassName("indexRight")[0]
        var informationDiv=document.getElementsByClassName("informationDiv")
        var z=document.body.style.zoom
        if(window.innerWidth<z*800){
            indexMain.style.display="flex";
            indexMain.style.flexDirection="column";
            indexLeft.style.width="100%";
            indexRight.style.width="100%";

            for(var i=0;i<informationDiv.length;i++){
                informationDiv[i].style.paddingLeft="30px"
            }
        }else{
            indexMain.style.display="table-row";
            indexLeft.style.flex="1";
            indexLeft.style.width="auto";
            indexRight.style.width="38%";

            for(var i=0;i<informationDiv.length;i++){
                informationDiv[i].style.paddingLeft="15px"
            }
        }
    }

    //语音播放
    var pronounce=document.getElementsByClassName("pronounceList")[0]
    var pronounceList=document.getElementsByClassName("pronounceList")[0].getElementsByTagName("li");

     //动态创建audio
    var sentenceAudio = document.createElement("audio");
    document.getElementsByTagName("body")[0].appendChild(sentenceAudio)

    //QT未兼容音频播放停止事件 暂时注释
    // sentenceAudio.onended=function(){
    //     pronounceImgReset()
    //     for(var j=0;j<pronounceList.length;j++){
    //         (function(i){
    //             pronounceList[j].setAttribute("data-play","false")
    //         })(i)
    //     }
    //     pronounce.setAttribute("data-play","false")
    // }

    // for(var i=0;i<pronounceList.length;i++){
    //     (function(x){
    //         pronounceList[x].onclick=function(e){
    //             e = e || window.event;
    //             e.target = e.target || e.srcElement;
    //             var _self=e.target.tagName=="LI"?e.target:e.target.parentNode;
    //             var src=_self.getAttribute("data-src")
    //             if(pronounce.getAttribute("data-play")=="true"){
    //                 pronounceImgReset()
    //             }
    //             if(pronounceList[x].getAttribute("data-play")=="true"){
    //                 pronounceImgReset()
    //                 pronounceList[x].setAttribute("data-play","false")
    //                 pronounce.setAttribute("data-play","false")

    //                 sentenceAudio.pause();
    //                 sentenceAudio.currentTime = 0;
    //             }else{
    //                 pronounceImgChange(x)
    //                 sentenceAudio.src = src;
    //                 sentenceAudio.play();

    //                 pronounceList[x].setAttribute("class","active")
    //             }
    //         }
    //     })(i)
    // }

    // function pronounceImgReset(){
    //     clearInterval(interval)
    //     for(var i=0;i<pronounceList.length;i++){
    //         (function(i){
    //             pronounceList[i].getElementsByClassName("pronounceImg")[0].style.background="";
    //             pronounceList[i].setAttribute("class","")
    //         })(i)
    //     }
    // }

    // function pronounceImgChange(i){
    //     var obj=pronounceList[i].getElementsByClassName("pronounceImg")[0];
    //     var url="./"+sentenceLang+"_bienvenu_voice.png";
    //     pronounce.setAttribute("data-play","true")
    //     for(var j=0;j<pronounceList.length;j++){
    //         (function(j){
    //             pronounceList[j].setAttribute("data-play","false")
    //         })(j)
    //     }
    //     pronounceList[i].setAttribute("data-play","true")

    //     var x=6;
    //     interval=setInterval(function(){
    //         if(x==-54){
    //             x=-14;
    //         }else{
    //             x=x-20;
    //         }
    //         obj.style.background="url("+url+")"+x+"px 0 no-repeat";
    //     },450)
    // }

    for(var i=0;i<pronounceList.length;i++){
        (function(x){
            pronounceList[x].onclick=function(e){
                e = e || window.event;
                e.target = e.target || e.srcElement;
                var _self=e.target.tagName=="LI"?e.target:e.target.parentNode;
                var src=_self.getAttribute("data-src")
                sentenceAudio.src = src;
                sentenceAudio.play();
            }
        })(i)
    }


    //各个语种当前日期
    function bienvenuGetMonth(l){
        var date;
        var m=(new Date()).getMonth();
        var t=(new Date()).getDate()
        var month = [
          {
            //法语
            m: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre']
          },
          { 
            //英语
            m: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
          },
          {
            //德语
            m: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']
          },
          {
            //西语
            m: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']
          }
        ]

        switch (l) {
          case 'fr':
            date=month[0].m[m]+"<span>"+t+"</span>";
            break;
          case 'en':
            date=month[1].m[m]+"<span>"+t+"</span>";
            break;
          case 'de':
            date=month[2].m[m]+"<span>"+t+"</span>";
            break;
          case 'es':
            date=month[3].m[m]+"<span>"+t+"</span>";
            break;
        }

        return date;
    }

    //每日一句数据
    function bienvenuSetSentence(d,l){
        var itemTable=document.getElementsByClassName("itemTable")[0];
        var en=itemTable.getElementsByClassName("sentencesEN")[0];
        var zh=itemTable.getElementsByClassName("sentencesZH")[0];
        var analysis=itemTable.getElementsByClassName("analysis")[0];
        var sentencesDate=itemTable.getElementsByClassName("sentencesDate")[0];

        en.innerHTML=d.line
        zh.innerHTML=d.linecn
        analysis.innerHTML=d.explain
        sentencesDate.innerHTML=bienvenuGetMonth(l)

        if(d.mp3url==null){
            pronounceList[0].style.display="none";
        }else{
            pronounceList[0].setAttribute("data-src",d.mp3url)
        }

        if(d.mp3url_slow==null){
            pronounceList[1].style.display="none";
        }else{
            pronounceList[1].setAttribute("data-src",d.mp3url_slow)
        }

        if(d.mp3url_explain==null){
            pronounceList[2].style.display="none";
        }else{
            pronounceList[2].setAttribute("data-src",d.mp3url_explain)
        }
    }

    //咨询数据
    function bienvenuSetTing(d,lang){
        var s="";
        switch(lang){
            case "fr":
                s="每日法语听力";
                break;
            case "de":
                s="每日德语听力";
                break;
            case "en":
                s="每日英语听力";
                break;
            case "es":
                s="每日西语听力";
                break;  
        }

        var tbody=document.getElementsByClassName("linkTable")[0].getElementsByTagName("tbody")[0];
        var str='<tr><th><div class="TitleFix"><span class="TitleBlock"></span><span class="TitleOpen">'+s+'</span><span class="TitleLine"></span></div></th></tr>';        
        d.forEach(function(o,i){
            str+="<tr><td><a href="+o.source_url+"><div class='informationDiv'><div><div class='informationImg'><img src='"+o.image_url_origin+"' alt='资讯图片'></div><div class='informationText'><span>"+o.title+"</span><span class='specialtitle'>"+o.specialtitle+"</span></div></div></div></a></td></tr>";
        })
        tbody.innerHTML=str;
        zoomChange()
    }
function setTransShortCut()
{
    var btnRead = document.getElementById("btnRead"); 
    var btnTrans = document.getElementById("btnTranslate"); 
    
    if (gPlatform == 'mac')
    {        
        btnRead.value = " 朗读该内容 (⌘R)";
        btnTranslate.value = "开始翻译  (⌥⌘↵)";
    }
    else
    {
        btnRead.value = " 朗读该内容 ";
        btnTranslate.value = "开始翻译 ";
    }    
}

function startTrans() {document.location = "cmd://dotrans";}
function startRead() {setStatusWaiting(false); document.location = "cmd://dotrans_read";}
function startSaveSound() {setStatusWaiting(true); document.location = "cmd://dotrans_saveSound";}
function selectTextRange(divid, start, len){var ta = document.getElementById(divid);ta.setSelectionRange(start,start+ len);}
function setStatusWaiting(isSaveBtn) {
var btnRead = document.getElementById("btnRead");
if (isSaveBtn)
	btnRead.disabled = true;
else
	btnRead.value = " 停止朗读 ";
var btnSave = document.getElementById("btnSave"); btnSave.disabled = true; var status_panel = document.getElementById("waitstatus"); status_panel.innerHTML = " <img src=\"waiticon.gif\" />正在生成，请稍候...";}
function setStatusFinish(msg) {
    var btnRead = document.getElementById("btnRead"); btnRead.disabled = false; var btnSave = document.getElementById("btnSave"); btnSave.disabled = false; var status_panel = document.getElementById("waitstatus"); status_panel.innerHTML = msg;
    setTransShortCut();
}
function langSwapClick()
{
	var t = document.getElementById("trans_orglangSel").selectedIndex;
	if (t == 0) t = 1;
	document.getElementById("trans_orglangSel").selectedIndex = document.getElementById("trans_destlangSel").selectedIndex + 1; //自动检测
	document.getElementById("trans_destlangSel").selectedIndex = t - 1;
}