var Lingo =
{
    HomePageCtrl:
    {
        ChangePic: function (source, picUrl, word, chs, audio) {
            var albumPicArea = document.getElementById('homeAlbumPicArea');
            var homeAlbumChooser = document.getElementById('homeAlbumChooser');
            // Get a hold of the pic area and set its defaults
            //            albumPicArea.onclick = null;
            //            albumPicArea.style.cursor = '';
            //            albumPicArea.title = '';

            // Load and show the image. Do this in the background while showing a loading graphic.
            var choosers = homeAlbumChooser.getElementsByTagName("a");
            for (var count = 0; count < choosers.length; count++)
                choosers[count].className = "";

            source.className = "current";

            albumPicArea.style.backgroundImage = 'url(img/load.gif)';

            var img = new Image();
            var picUrl = "http://dict.bing.com.cn" + picUrl;
            img.onload = function () {
                albumPicArea.style.backgroundImage = 'url(' + picUrl + ')';
            };
            img.src = picUrl;
            document.getElementById('homeAlbumInfoArea').innerHTML = "<a title=\"点击获取释义\" href=\"#def\" onclick=\"window.external.QueryWordFromSelf(&quot;" + word + "&quot;);return false;\">" + word + "</a>&nbsp;"
                                                    + "<a class=\"aud\" href=\"#tts\" onclick=\"window.external.PlayWord('" + audio + "');return false;\" title=\"点击朗读\">点击朗读</a><br>"
                                                    + "<span class=\"albumWord\">" + chs + "</span>";

        },

        NextPic: function () {
            var homeAlbumChooser = document.getElementById('homeAlbumChooser');
            var choosers = homeAlbumChooser.getElementsByTagName("a");
            for (var count = 0; count < choosers.length; count++) {
                if (choosers[count].className == "current") {
                    choosers[(++count % choosers.length)].onmousedown();
                    return;
                }


            }
        }
    },
    AlignMan:
    {

        elArrayByClass: function (sClassName, elNode, sTag, dontAssertOnFailToFind) {
            var rgClassElements = [];
            if (elNode === null || elNode === undefined) {
                elNode = document;
            }
            if (sTag === null || sTag === undefined) {
                // Compatibility note: the following does not work on <= IE5.5
                sTag = '*';
            }
            var rgEls = elNode.getElementsByTagName(sTag);
            var len = rgEls.length;
            var rxp = new RegExp('(^|\\s)' + sClassName + '(\\s|$)');
            var i, j;
            for (i = 0, j = 0; i < len; i++) {
                if (rxp.test(rgEls[i].className)) {
                    rgClassElements[j] = rgEls[i];
                    j++;
                }
            }

            return rgClassElements;
        },
        getElText: function (el) {
            var txt = null;
            if (el.textContent) {
                txt = el.textContent;
            }
            else {
                txt = el.innerText;
            }

            return txt;
        },
        alignWords: function (wordAlignmentTagIdOrEl, fHighlight, fDontAssertOnFailToFindTag, fStopAnimation) {



            // Extract the link ID
            var wordAlignmentTagLink = wordAlignmentTagIdOrEl.className ? wordAlignmentTagIdOrEl.className : wordAlignmentTagIdOrEl;
            // Determine scope of alignment tag, if we are given an element, then crawl to a container tag such as LI or DIV (optimization), otherwise default is entire vpage container (slower)
            var elCntrToSearchForAlignment;
            if (wordAlignmentTagIdOrEl.className) {
                elCntrToSearchForAlignment = wordAlignmentTagIdOrEl;
                while (elCntrToSearchForAlignment.tagName != "LI" && elCntrToSearchForAlignment.tagName != "DIV" && elCntrToSearchForAlignment != document /*prevent hang*/) {
                    elCntrToSearchForAlignment = elCntrToSearchForAlignment.parentNode;
                }
            }
            //alert(elCntrToSearchForAlignment.nodeName);
            var alignedTags = this.elArrayByClass(wordAlignmentTagLink, elCntrToSearchForAlignment, 'span', fDontAssertOnFailToFindTag);

            if (!alignedTags || alignedTags.length < 1) {
                return false; //<--- Exit point
            }

            for (var i = 0; i < alignedTags.length; i++) {
                var alignedTag = alignedTags[i];
                // If needed, attach event handlers to this aligned tag. Do it as needed for memory optimization purposes.

                if (!alignedTag.onmouseout) {
                    alignedTag.onmouseout = function () {
                        Lingo.AlignMan.alignWords(this, 0, 1); return false;
                    }
                }

                if (!alignedTag.getAttribute("data-nclk")) { // no click elements can't be looked up, like pinyin
                    if (!alignedTag.onclick) {

                        alignedTag.onclick = function () {

                            window.external.QueryWordFromSelf(this.innerText);
                            return false;
                        }
                    }
                    if (!alignedTag.title) {
                        alignedTag.title = "点击获取释义"; //set $CLICK_TO_LOOKUP$
                    }
                }

                // See if there are any decoration images inside of this alignment tag
                var alignImages = alignedTag.getElementsByTagName('i'); // <i></i> tag is representing images
                var decorationImage = null;
                if (alignImages && alignImages[0]) {
                    decorationImage = alignImages[0];
                }

                // Turn on / off
                if (fHighlight) {
                    alignedTag.style.color = 'white';
                    alignedTag.style.backgroundColor = "#00b5f0";
                    alignedTag.style.cursor = "pointer";
                    if (decorationImage &&
                       this._animeIntervalID /*only show image during animation*/) {
                        decorationImage.style.visibility = '';
                    }
                }
                else {
                    alignedTag.style.backgroundColor = '';
                    alignedTag.style.color = '';
                    alignedTag.style.cursor = "";
                    if (decorationImage) decorationImage.style.visibility = 'hidden';
                }
            }

            return true;
        }
    },
    EC_TIP: "英汉释义",
    CE_TIP: "汉英释义",
    EE_TIP: "英英释义",
    CC_TIP: "汉汉释义",
    onSetDefLangView: function (ele) {

        if (ele.value == 'cc') {

            $(".defLangTitle").each(function () {
                if (this.innerText == Lingo.CE_TIP) {
                    this.innerText = Lingo.CC_TIP;
                    $(".defCnt_ce").hide();
                    $(".defCnt_cc").show();
                }
                else if (this.innerText == Lingo.EC_TIP) {
                    this.innerText = Lingo.EE_TIP;
                    $(".defCnt_ec").hide();
                    $(".defCnt_ee").show();
                }
            })
            $("input:[class=dl_homo]:radio").attr("checked", true);
            window.external.ChangeDefStatus(true);
        }
        else if (ele.value == 'ce') {

            $(".defLangTitle").each(function () {
                if (this.innerText == Lingo.CC_TIP) {
                    this.innerText = Lingo.CE_TIP;
                    $(".defCnt_cc").hide();
                    $(".defCnt_ce").show();
                }
                else if (this.innerText == Lingo.EE_TIP) {
                    this.innerText = Lingo.EC_TIP;
                    $(".defCnt_ee").hide();
                    $(".defCnt_ec").show();
                }
            })
            $("input:[class=dl_cross]:radio").attr("checked", true);
            window.external.ChangeDefStatus(false);
        }
        else if (ele.value == 'ec') {

            $(".defLangTitle").each(function () {
                if (this.innerText == Lingo.EE_TIP) {
                    this.innerText = Lingo.EC_TIP;
                    $(".defCnt_ee").hide();
                    $(".defCnt_ec").show();
                }
                else if (this.innerText == Lingo.CC_TIP) {
                    this.innerText = Lingo.CE_TIP;
                    $(".defCnt_cc").hide();
                    $(".defCnt_ce").show();
                }
            })
            $("input:[class=dl_cross]:radio").attr("checked", true);
            window.external.ChangeDefStatus(false);
        }
        else if (ele.value == 'ee') {

            $(".defLangTitle").each(function () {
                if (this.innerText == Lingo.EC_TIP) {
                    this.innerText = Lingo.EE_TIP;
                    $(".defCnt_ec").hide();
                    $(".defCnt_ee").show();
                }
                else if (this.innerText == Lingo.CE_TIP) {
                    this.innerText = Lingo.CC_TIP;
                    $(".defCnt_ce").hide();
                    $(".defCnt_cc").show();
                }
            })
            $("input:[class=dl_homo]:radio").attr("checked", true);
            window.external.ChangeDefStatus(true);
        }


    }
}
function DisabledProxy() {
    if ($('#enableProxy'))
        $('#enableProxy').attr("checked", false);
}
function SaveProxySetting() {
    document.body.focus();
}
function SaveProxySettingSlient() {
    var prama = Setting.GetProxySetting();
    if (prama) {
        window.external.SaveProxySetting(prama[0], prama[1], prama[2], prama[3], prama[4], false);
    }
}
function CheckProxySetting() {
    var prama = Setting.GetProxySetting();
    if (prama) {
        return window.external.CheckProxySetting(prama[0], prama[1], prama[2], prama[3], prama[4]);
    }
    return true;
}
var Setting =
{
    SaveProxySetting: function () {
        var prama = Setting.GetProxySetting();
        if (prama) {
            window.external.SaveProxySetting(prama[0], prama[1], prama[2], prama[3], prama[4], true);
        }
    },
    SaveProxyServer: function () {
        var server = $('#proxyAddress').val() ? $('#proxyAddress').val() : "";
        window.external.SaveProxyServer(server, $('#enableProxy').is(':checked'));
    },
    SaveProxyPort: function () {
        var port = $('#proxyPort').val() ? $('#proxyPort').val() : "";
        window.external.SaveProxyPort(port, $('#enableProxy').is(':checked'));
    },
    SaveProxyUsername: function () {
        var username = $('#proxyUserName').val() ? $('#proxyUserName').val() : "";
        window.external.SaveProxyusername(username, $('#enableProxy').is(':checked'));
    },
    SaveProxyPassword: function () {
        var passwd = $('#proxyPasswd').val() ? $('#proxyPasswd').val() : "";
        window.external.SaveProxyPassword(passwd, $('#enableProxy').is(':checked'));
    },
    GetProxySetting: function () {
        var server = $('#proxyAddress').val() ? $('#proxyAddress').val() : "";
        var port = $('#proxyPort').val() ? $('#proxyPort').val() : "";
        var username = $('#proxyUserName').val() ? $('#proxyUserName').val() : "";
        var passwd = $('#proxyPasswd').val() ? $('#proxyPasswd').val() : "";
        return new Array(server, port, username, passwd, $('#enableProxy').is(':checked'));
    },
    FilterPortPrama: function () {
        var e = window.event;
        var key = e.which || e.keyCode;

        if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
        // numbers   
         key >= 48 && key <= 57 ||
        // Numeric keypad
         key >= 96 && key <= 105 ||
        // Backspace and Tab and Enter
         key == 8 || key == 9 || key == 13 ||
        // Home and End
         key == 35 || key == 36 ||
        // left and right arrows
         key == 37 || key == 39 ||
        // Del and Ins
         key == 46 || key == 45)
            return true;

        return false;
    },
    RunProxyTest: function () {
        var prama = Setting.GetProxySetting();
        if (prama)
            window.external.RunProxyTest(prama[0], prama[1], prama[2], prama[3]);
    }
}
function EnableProxyTestButton() {
    if ($('#testProxyBtn'))
        $('#testProxyBtn').attr('disabled', false);
}
function DisabledProxyTestButton() {
    if ($('#testProxyBtn'))
        $('#testProxyBtn').attr('disabled', true);
}
var Shortcut = {

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

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

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

                192: '`',

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

                19: 'Pause',

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

                35: 'End',

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

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

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

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


            }

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

            }


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

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

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

                    }
                    if (this.value == "无") {
                        window.external.SetHotkey(this.id, false, false, false, 0);
                        return false;
                    }
                }
                ele.onblur = function () {

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

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

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

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

                result += character;
                if (Shortcut.CheckHotkeyIsValid(result)) {
                    ele.value = result;

                    window.external.SetHotkey(ele.id, e.ctrlKey, e.shiftKey, e.altKey, code);
                    return false;
                }

                ele.value = "无";
            }
            else {
                if (e.keyCode) code = e.keyCode;

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

            }
            return false;
        }

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

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

}

function ContentReady() {
    //Default Action

    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active"); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    $("ul.tabs li").click(function () {
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        var id = activeTab.substring(activeTab.lastIndexOf("#") + 1);
        if (id == "LinkFeedback") {
            window.external.OpenFeedback();
        }
        else if (id == "LinkFQA") {
            window.external.OpenFQA();
        }
        else {
            $("ul.tabs li").removeClass("active"); //Remove any "active" class
            $(this).addClass("active"); //Add "active" class to selected tab
            $(".tab_content").hide(); //Hide all tab content
            $(".tab_content[id=" + id + "]").fadeIn(); //Fade in the active content        
        }
        return false;
    });

}

function SwitchToAbout() {
    $("ul.tabs li").removeClass("active"); //Remove any "active" class
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li[id=LiAbout]").addClass("active"); //Activate first tab
    $(".tab_content[id=tabAbout]").fadeIn(); //Show first tab content
}
function SwitchToSetting() {
    $("ul.tabs li").removeClass("active"); //Remove any "active" class
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li[id=LiGeneral]").addClass("active"); //Activate first tab
    $(".tab_content[id=tabGeneral]").fadeIn(); //Show first tab content
}
function GetSelection() {
    if (window.getSelection) {

        return window.getSelection().toString();
    }
    else if (document.getSelection) {

        return document.getSelection();
    }
    else if (document.selection) {

        return document.selection.createRange().text;

    }
}
function document.onkeydown() {
    if ((event.keyCode == 116)                // disable F5  
          || (event.ctrlKey && event.keyCode == 76) //disable ctrl+L
          || (event.ctrlKey && event.keyCode == 78) //disable ctrl+N
          || (event.ctrlKey && event.keyCode == 79) //disable ctrl+O
          || (event.ctrlKey && event.keyCode == 80) //disable ctrl+P
          || (event.ctrlKey && event.keyCode == 82) //disable ctrl+R
          || (event.ctrlKey && event.keyCode == 70) //disable ctrl+F
          || (window.event.srcElement.tagName == "A" && window.event.shiftKey) // disable shift+mouse left click open new window
          ) {
        event.keyCode = 0;
        event.returnValue = false;
    }
}

function SaveSettingSuccessfully() {
    if ($('#save_success').offset().top != -100)
        $('#save_success').css({ 'top': 0 });
    else
        $('#save_success').animate({ top: "0px" }, 800).delay(1500).animate({ top: "-100px" }, 800);
}

function SaveSettingFailed() {
    if ($('#save_failed').offset().top != -100)
        $('#save_failed').css({ 'top': 0 });
    else
        $('#save_failed').animate({ top: "0px" }, 800).delay(1500).animate({ top: "-100px" }, 800);
}

function PlayWord(url) {

    if (url == null)
        return;
    var audioPlayer = document.getElementById("_aplayer");
    try {
        audioPlayer.SetVariable("hash", url);
        audioPlayer.GotoFrame(2); // Stop potentially any playing sounds
        audioPlayer.GotoFrame(1);
    } catch (e) {
        audioPlayer.Settings.PlayCount = 1; // Call Settings.PlayCount especially to draw an exception if this is not present
        audioPlayer.URL = url;
    }
}



