function updateAutoPlay(){
    g_AutoPlay = g_Pref.GetIntPref("skpref.playlang");
}
/*TEXT Size*/
function updateTextSize(){
    var aWin = skPopup.getAllWindowPopupArray();
    aWin.push(window);
    for(var z=0; z<aWin.length; z++){
        var doc = aWin[z].document;
        var aElementTextSize = new Array(doc.getElementsByTagName("skFs"), doc.getElementsByTagName("skVirtualList"), doc.getElementsByTagName("iframe"))
        var size;
        switch(parseInt(g_Pref.GetIntPref("skpref.fontsize"))){
            case 0 :
                size = 0.8;
                break;
            case 1 :
                size = 1;
                break;
            case 2 :
                size = 1.2;
                break;
            case 3 :
                size = 1.4;
                break;
        }
        for(var i=0; i<aElementTextSize.length;i++){
            for(var j=0; j<aElementTextSize[i].length; j++){
                aElementTextSize[i][j].contentWindow.textZoom = size;
                if(aElementTextSize[i][j].checkResize) aElementTextSize[i][j].checkResize();
            }
        }
    }
}
/*TEXT Size*/

function prefInit(){
    g_Pref = Components.classes["@mozilla.org/preferences;1"].getService(Components.interfaces.nsIPref);
    g_Pref.SetBoolPref("prefs.converted-to-utf8", true);

    // Set default font size on first launch
    try      { g_Pref.GetIntPref("skpref.fontsize"); }
    catch(e) { g_Pref.SetIntPref("skpref.fontsize", "1"); }
    // Get autoplay value, or set the pref on first launch (value is already
    // set to 0 in const.js)
    try      { g_AutoPlay = g_Pref.GetIntPref("skpref.playlang"); }
    catch(e) { g_Pref.SetIntPref("skpref.playlang", "1"); }

    updateTextSize();
    updateAutoPlay();
}

function init_plugs(){
    skTabManager.cdName = g_CDLABEL;
    skTabManager.titleBox = "Data not found";
    skTabManager.messageBox = "Please insert the Oxford Collocations CD-ROM to access this feature";

    skResourceManager.dataPrefix = g_CDLABEL.toLowerCase() + ".data";
    skResourceManager.addPath("uk_pron", "pron.skn");
    skResourceManager.addPath("us_pron", "pron.skn");
    /*skResourceManager.setScrollHandler("LdoceAZ", "dict");
    skResourceManager.addPath("LdoceAZ", "fs.skn");
    skResourceManager.defaultPopupSettings.url = "chrome://ldoce5/content/popup/dict_intern_link.xul";
    skResourceManager.setPopupSelfHandler("LdoceAZ",
            "chrome://ldoce5/content/popup/dict_intern_xref.xul");*/
}

function app_init()
{
    prefInit();
    init_plugs();
    goHistory = new skHistoryManager("mainHistory",
                             document.getElementById("history-back-btn"),
                             document.getElementById("history-next-btn"),
                             function(xml) {
                                  var type = xml.firstChild.getAttribute('type');
                                  var entry = xml.firstChild.getAttribute("entry");
                                  if (type == "hist_dict")
                                      skGroups.selectedGroup.searchSystem.azList.placeInVlist(entry);
                             });
    setHistoryBtnStates = function(disable, mode) {
        goHistory.backbtn = document.getElementById("history-" + (mode ? mode + "-" : "") + "back-btn");
        goHistory.nextbtn = document.getElementById("history-" + (mode ? mode + "-" : "") + "next-btn");
        if (disable)
            goHistory.setButtonStates(false, false);
        else
            goHistory.setCurrentButtonStates();
    }
    try
    {

        var i, j, k;

        g_Simplifier = Components.classes["@idm.fr/sk_core_service;3"].
            getService().GetStringSimplifier("unicode:uni_case,uni_comp");



        g_bInitializing = false;
        
        skGroups.add(new ActiveGroup("dict", {// main dictionary
                createSearchSystem: function() {
                    var searchSystem = createSimpleSearchSystem("simpleSearch", false, true);
                    var dictFilterFunction = function(filePath, display, klass) {
                        // this is a closure... the value of g_DictAllowedClasses will
                        // be changed by the callback on the 'See this word in' combo, and
                        // the function will take this change into account automatically
                        for (var i in g_DictAllowedClasses) {
                            if (g_DictAllowedClasses[i]==klass)
                                return true;
                        }
                        return false;
                    };
                    // filter according to the current value of 'see this word in'
                    searchSystem.filter = dictFilterFunction;
                    var oldSearch = searchSystem.search;
                    // Make sure we store the last query string
                    searchSystem.search = function(searchString, codes, idToSelect, doSpellSearch) {
                        lastDictQueryString = searchString || searchSystem.input.value;
                        return oldSearch.apply(searchSystem, [searchString, codes, idToSelect, doSpellSearch]);
                    }
                    searchSystem.searchFromIndex = false;
                    return searchSystem;
                },
                enableHook: function() {
                    setHistoryBtnStates();
                },
                saveHistoryCallback: function(params) {
                    var sXml = "<HISTO type='hist_dict' entry='" + params.entry + "'/>";
                    goHistory.saveXmlToBasket(sXml);
                }
            })
        );
        skGroups.add(new ActiveGroup("popup", {// popup mode
                createSearchSystem: function() {
                    return createSimpleSearchSystem("simpleSearchPopup", true, true);
                }
            })
        );

        activateGroup("dict");

        initMp3Player();


    } catch(e) { jsLog("app_init failed: " + e); }
    skCopy.copyrightTop = CLIPBOARD_TOP;
    skCopy.copyrightBottom = CLIPBOARD_BOTTOM;
}

/**
 * Creates the search system for the simple or advanced search
 */
function createSimpleSearchSystem(id, singleEntry, selectFirstEntry) {
    try {
        var simpleSearchSystem = new SearchSystem(id, {
            popupUrl: "chrome://ocoll2e/content/popup/skDblClickPopup.xul",
            gotoCallback: gotoDictionary,
            skPrintUrl: "chrome://ocoll2e/content/iframe/fullMD.xml",
            singleEntry: singleEntry,
            selectFirstEntry: selectFirstEntry,
            highlight: true
        });
        // when clicking on an entry, refresh the links on the right side panel
        var doc = document;
        simpleSearchSystem.azList.getContentCallback(function (index, obj) {
            try{
                var entry   = skTabManager.getFile(simpleSearchSystem.fsAz + "/config.cff",
                    index).GetData().GetWStringData();
                entry = entry.replace(/^\s*<\?xml.+\??>/, '');
                entry = "<div class='contentEntryItem'>" + entry + "</div>"
                      + "<div style='clear:both;'> </div>"; //to fix the picture positioning problem (overlaping on other entries)
                return String(entry);
            } catch (err) {
                jsLog("getContentCallback failed: " + err + " ON piIndex : " +
                    index);
            }
        });
        simpleSearchSystem.azList.selectItemCallback(function(skItem, e) {
            if(simpleSearchSystem.indexList)
                skGroups.selectedGroup.saveHistoryCallback( { entry: skItem.index } );
        });
        var inputAutoSelection = function(e) {
            if (e.charCode) {
                simpleSearchSystem.input.value = String.fromCharCode(e.charCode)
                simpleSearchSystem.input.focus();
            }
        }

        simpleSearchSystem.azList.keyPressVlistCallback(inputAutoSelection);
        simpleSearchSystem.resultList.keyPressVlistCallback(inputAutoSelection);
        if(simpleSearchSystem.indexList)
            simpleSearchSystem.indexList.keyPressVlistCallback(inputAutoSelection);
        return simpleSearchSystem;
    }
    catch(e) {
        jsLog("Error in createSimpleSearchSystem: " + e);
    }
}

/**
 * When clicking on a button, activates the group the button belongs to
 * If the button belongs to more than one group, the first group in its list of
 * groups is activated
 */
function activateGroup(id) {
    resizerWin.changeSize(id);
    var searchSystem;
    if(skGroups.selectedGroup)
        searchSystem = skGroups.selectedGroup.searchSystem
    skGroups.enable(id, searchSystem);
}

function app_play(sndUrl, typeSnd)
{
    if(skMp3Manager.isPlaying()) skMp3Manager.stop();
    skMp3Manager.fsName = g_SK_PATH[typeSnd];
    skMp3Manager.play(sndUrl);
}

function initMp3Player(){
    skMp3Manager.cdName = g_CDLABEL;
    skMp3Manager.bInitApp = false;
    skMp3Manager.messageBox = "Please insert the Oxford Collocations CD-ROM if you want to " +
                              "listen to the pronunciations.";
}


function app_quit()
{
    try { document.getElementById('quickfind').disconnect(); } catch (e) { };

    try
    {
        Components.classes[
            "@mozilla.org/commandlinehandler/general-startup;1?type=killAll"].
            createInstance().QueryInterface(
            Components.interfaces.nsICmdLineHandler).chromeUrlForTask();
    }
    catch (e) { top.window.close(); }
}

function UpdateTextSize(val, win)
{
    var doc = win.document;
    var aElementTextSize = new Array(
        doc.getElementsByTagName("skFs"),
        doc.getElementsByTagName("skVirtualList"),
        doc.getElementsByTagName("iframe"));
    var size = val == 0 ? 0.8 : (val == 1 ? 1 : (val == 2 ? 1.2 : 1.4));
    for(var i = 0; i < aElementTextSize.length; i++)
        for(var j = 0; j < aElementTextSize[i].length; j++)
        {
            aElementTextSize[i][j].contentWindow.textZoom = size;
            if(aElementTextSize[i][j].checkResize)
                aElementTextSize[i][j].checkResize();
        }
}

function Quit()
{
    if (!confirm("Are you sure you want to quit the OXFORD?"))
        return;
    app_quit();
}

function launchSpellCheck(){
    skGroups.selectedGroup.searchSystem.spellSearch();
}

function openSoundSearch() {
    document.getElementById("sound-search").openSearchPopup();
}

//callback for the dblclick in entries
function callbackSearch() {
     jsLog('Dblclick !!!');
}


function gotoDictionary(entry) {
    win.setMode("dict");
    win.skGroups.group("dict").searchSystem.placeInAz(entry);
}

/** 'See this word in' callback - changes what classes are displayed */
function changeDictFilter(combo) {
    g_DictAllowedClasses = combo.selectedItem.value.split(",");
    if (lastDictQueryString)
        skGroups.selectedGroup.searchSystem.searchAndDisplay(lastDictQueryString);
}

//open any relative file to the chrome directory
function openChromeFile(path) {
    var file = Components.classes["@mozilla.org/file/directory_service;1"]
                          .getService(Components.interfaces.nsIProperties)
                          .get("CurProcD", Components.interfaces.nsIFile);
    file.append("chrome");
    file.append("ocoll2e");
    file.append("content");
    var splitPath = path.split("/");
    for (var i in splitPath) {
        file.append(splitPath[i]);
    }
    if (!file)
        return;

    //get its its absolute location in "file://"
    var ioService = Components.classes["@mozilla.org/network/io-service;1"]
                               .getService(Components.interfaces.nsIIOService);
    var fileHandler = ioService.getProtocolHandler("file")
                                .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
    var url = fileHandler.getURLSpecFromFile(file);

    //open the pdf in the default browser
    if (url)
        openDefBrowser(url);
}
