/* Function used by Search Bar */
function installSearchEngine() {
 if (window.external && ("AddSearchProvider" in window.external)) {
   // Firefox 2 and IE 7, OpenSearch
   window.external.AddSearchProvider("http://www.ldoceonline.com/widgets/ldoce_opensearch.xml");
// } else if (window.sidebar && ("addSearchEngine" in window.sidebar)) {
   // Firefox <= 1.5, Sherlock
//   window.sidebar.addSearchEngine("http://example.com/search-plugin.src",
//                                  "http://example.com/search-icon.png",
//                                  "Search Plugin", "");
 } else {
   // No search engine support (IE 6, Opera, etc).
   alert("No search engine support");
 }
}


/*Function used to return an element of type 'elt' and whose classname is known*/
function getElementByClassName(poDoc, poElt, psClass){
    try {
        var oElts = poDoc.getElementsByTagName(poElt);
        for(var i=0; i<oElts.length; i++) {
            if(oElts.item(i).className == psClass){
                return oElts.item(i);
            }
        }
        return false;
    } catch (err) {
       return false;
    }
}

/*Function used to scroll to a specified element*/
function scrollToElt(poWindow, poEltId) {
    try {
        var iHeight = 0;
        var oElt = poWindow.document.getElementById(poEltId);
        if (oElt) {
            while(oElt.nodeName != "BODY") {
                iHeight += oElt.offsetTop;
                oElt = oElt.offsetParent;
            }
            if (poWindow.scrollTo)
                poWindow.scrollTo(0, iHeight-5);
        }
    } catch (err) { }
}

function changeClass(poNode){
    try {
        var sClass = poNode.className;
        if (sClass.indexOf("-over") != -1) {
            poNode.className = sClass.substring(0, sClass.length-5);
        } else
            poNode.className = sClass + "-over";
    } catch (err) { }
}

function cleanSearchString(psWord) {
    try {
        // Replace break lines
        psWord = psWord.replace(/\r\n/gi, "");
        psWord = psWord.replace(/\r/gi, "");
        psWord = psWord.replace(/\n/gi, "");
        // Replace empty words
        psWord = " " + psWord.replace(/ /g,"  ") + " ";
        psWord = psWord.toLowerCase().replace(/(^| )(\-|\*|\.|\#|\||\&)( |$)/g, " ");
        // Replace separators
        psWord = psWord.replace(/[!()+,\[\/:\];<>^_`\[\]{}~\?\']/gi, " ");
        // Replace string with only spaces
        psWord = psWord.replace(/^\s+$/, "");
        return psWord.replace(/( )+/g," ");
    } catch (err) { }
}

function checkSearchString(psSearch, pbValidForm) {
   try {
      var sSearch = String(psSearch);
      sSearch = cleanSearchString(sSearch);

      if (sSearch.length == 0)
          return false;

      if (sSearch.split(" ").length <= 10)
         return true;
      else {
         if (pbValidForm)
            alert("Your search must contain less than 10 words");
         return false;
      }
   } catch(err) { }
}
var gsPwdLocation = "/";
var strCurHwd     = null;
var prevEntryId   = null;
var nextEntryId   = null;
var giHlightId    = null;
// Used to set the page where the search, etc, will occur
// Can be overrided (for instance, in wapopup.html)
var displayLocation = "display/display.html";

function closeAllHwd() {
    try {
        var i, oCurDiv;
        var oListDivs = document.getElementsByTagName('div');

        var strFolded="";
        for (i=0; i<oListDivs.length; i++) {
            oCurDiv = oListDivs.item(i);
            oCurId = oCurDiv.getAttribute("id")
            if(oCurDiv.className == "folded" || oCurDiv.className == "unfolded") {
                if(strFolded.length == 0)
                    strFolded += oCurId;
                else
                    strFolded += "," + oCurId;
            }
        }
        document.location = gsPwdLocation + displayLocation + "?ids=" + strFolded;
    } catch (err) { }
}

function UnfoldHwdDico(poImg) {
    try {
        var i, oCurDiv;
        var oListDivs = document.getElementsByTagName('div');
        var oFoldedId = poImg.parentNode.parentNode.parentNode.parentNode.parentNode.id;

        var strFolded="";
        var strUnfolded="";
        for (i=0; i<oListDivs.length; i++) {
            oCurDiv = oListDivs.item(i);
            oCurId = oCurDiv.getAttribute("id");
            if(oCurDiv.className == "folded" || oCurDiv.className == "unfolded") {
                if(oCurId == oFoldedId)
                    strUnfolded = oCurId;
                //Build the string strFolded
                if(strFolded.length == 0)
                    strFolded += oCurId;
                else
                    strFolded += "," + oCurId;
            }
        }
        document.location = gsPwdLocation + displayLocation + "?unfolded=" + strUnfolded + "&ids=" + strFolded;
    } catch (err) { }
}

function openBox(poNode){
    try {
        var oNode;
        switch (poNode.parentNode.className) {
            case 'activebutton':
                oNode = poNode.parentNode.nextSibling;
                while(oNode.nodeType != 1)
                    oNode = oNode.nextSibling;
                poNode.parentNode.style.display = "none";
                oNode.style.display = "block";
                break;
            case 'activebox':
            case 'grammarbox':
                oNode = poNode.parentNode.previousSibling;
                while(oNode.nodeType != 1)
                    oNode = oNode.previousSibling;
                poNode.parentNode.style.display = "none";
                oNode.style.display = "block";
                break;
        }
    } catch (err) { }
}

function openCrossref(poNode){
        var iHwd = poNode.getAttribute("destid");
        var sSense = poNode.getAttribute("contextid");
        if (parent.gbIsPM) {
            var oResultWin = parent.document.getElementById("resultFrame").contentWindow;
            parent.giPMEntryId = iHwd;
            parent.gsPMFoldedIds = "";
        //    document.location = gsPwdLocation + displayLocation + "?" + (parent.gbIsPM ? "popupmode=1&" : "") + "unfolded=" + iHwd + "&ids=" + iHwd + (sSense ? "&senseid=" + String(sSense) : "");
        //    oResultWin.location = gsPwdLocation + "empty.html";
        } else
            document.location = gsPwdLocation + displayLocation + "?unfolded=" + iHwd + "&ids=" + iHwd + (sSense ? "&senseid=" + String(sSense) : "");
}

/*Function used by the popup Menu to scroll to a specified sense and highlighted it (and by the function goToSenseNum after a click on a crossref)*/
function highlightsense(psEltId) {
    try {
    	var oMainWin = (window.opener) ? window.opener : window;
        var oDest = oMainWin.document.getElementById(psEltId);

        //Uncolorize the previous hightlighted element
        if(oMainWin.parent.giHlightId) {
            var oHlight = oMainWin.document.getElementById(oMainWin.parent.giHlightId);
            if(oHlight){
                if(oHlight.style.setAttribute)
                    oHlight.style.setAttribute("backgroundColor", ""); //for IE
                else
                    oHlight.setAttribute("style", ""); //for Netscape & Mozilla
            }
        }

        //Scroll to the destination element
        scrollToElt(oMainWin, oDest.getAttribute("id"));

        //Colorize the destination element
        if(oDest.style.setAttribute)
            oDest.style.setAttribute("backgroundColor", "#F0F0F0"); //for IE
        else
            oDest.setAttribute("style","background-color:#F0F0F0;"); //for Netscape & Mozilla

        oMainWin.parent.giHlightId = psEltId;
        oMainWin.setTimeout("uncolorizeSense();", 1000);
    } catch (err) { }
}

function uncolorizeSense() {
    try {
        if(parent.giHlightId) {
            var oDest = document.getElementById(parent.giHlightId);
            if (oDest)
                oDest.removeAttribute("style");
        }
    } catch (err) { }
}

function openSoundPlayer(psSoundPath, piType, piHwdId, piSentenceNum){
    try {
        var sPopupPath = gsPwdLocation + "pronunciation/sound_player.html?soundpath=" + psSoundPath + "&soundtype=" + piType + (piHwdId != null ? "&hwdid=" + piHwdId : "") + (piSentenceNum != null ? "&sentnum=" + piSentenceNum : "");
        window.open(sPopupPath, "LDOCE_SOUNDPLAYER", "width=400,height=175,left=320,top=200,scrollbars=no,status=no,dependent=yes");
    } catch (err) { }
}

function playActive(poNode) {
    try {
        poNode.setAttribute("src", "/images/btnplaya.gif");
    } catch (err) { }
}

function playPassive(poNode) {
    try {
        poNode.setAttribute("src", "/images/btnplay.gif");
    } catch (err) { }
}

function openPicurePopup(poNode){
    try {
        var sPopupPath = gsPwdLocation + "picture/media.html?path=" + poNode.id + ".jpg";
        window.open(sPopupPath, "LDOCE_MEDIA", "width=420,height=470,left=320,top=200,scrollbars=no,status=no");
    } catch (err) { }
}

function openMenuPopup(piHwdId) {
    try {
        if (!piHwdId)
            return;
        var sPopupPath = gsPwdLocation + "popup/menu.html?hwdid=" + piHwdId;
        window.open(sPopupPath, "LDOCE_MENU", "width=370,height=400,left=320,top=200,scrollbars=yes,status=no,resizable=no");
    } catch (err) { }
}

function openPronPopup(piHwdId, piPronGbId, piPronUsId) {
    try {
        var sPopupPath = gsPwdLocation + "pronunciation/pron.html?hwdid=" + piHwdId + (piPronGbId ? ("&prongbdid=" + piPronGbId) : "") + (piPronUsId ? ("&pronusdid=" + piPronUsId) : "");
        window.open(sPopupPath, "LDOCE_PRON", "width=350,height=395,left=320,top=200,scrollbars=no,status=no");
    } catch (err) { }
}

/*Fonction used after a click on the title of the popup Menu*/
function goTopOfPage() {
    try {
    	scrollToElt(window.opener, window.opener.parent.curEntryId);
    } catch (err) { }
}

/* HTML MAPS */
function OpenArea(piHwdId) {
    try {
        window.close();
        opener.location = gsPwdLocation + displayLocation + "?unfolded=" + piHwdId + "&ids=" + piHwdId;
    } catch (err) { }
}

/* Pronunciation popup */
function playPronunciation(piPronId, psLang) {
    try {
        var sPath = gsPwdLocation + "pronunciation/pron.html?hwdid=" + giHwdId + (giPronGbId ? ("&prongbdid=" + giPronGbId) : "") + (giPronUsId ? ("&pronusdid=" + giPronUsId) : "") + "&pronsentidx=" + giPronsentIdx;
        sPath += "&playpron" + (psLang == "gb" ? "gb=" : "us=") + piPronId;
        document.location = sPath;
    } catch (err) { }
}

function playSentence(){
    try {
        var sPath = gsPwdLocation + "popup/pron.html?hwdid=" + giHwdId + (giPronGbId ? ("&prongbdid=" + giPronGbId) : "")
                  + (giPronUsId ? ("&pronusdid=" + giPronUsId) : "") + "&pronsentidx=" + giPronsentIdx + "&playpronsent=1";
        document.location = sPath;
    } catch (err) { }
}
if(window.addEventListener)
    window.addEventListener("dblclick", DblClickInDoc, true);//work at least with NN6
document.ondblclick=DblClickInDoc;//IE

/*Function called by the dblclick event handler to display the definition of the selected word*/
function DblClickInDoc(e) {
    try {
        var text = (document.all) ? document.selection.createRange().text : window.getSelection();
        var oMainWin = (parent.gbIsPM ? parent.opener : window);
        if (checkSearchString(text, false)) {
            var sPopupPath = gsPwdLocation + "popup/popupmode.html?search_str=" + text;
            oMainWin.open(sPopupPath, "LDOCE_PM", "width=405,height=450,left=320,top=200,scrollbars=no,status=no,dependent=yes,hotkeys=no,resizable=no");
        }
    } catch (err) { }
}

function setfocus() {
    if (document.getElementById('q')) {
        document.getElementById('q').focus();
    }
}

/*Function called when the document containing the entries is loading*/
function initEntry() {
//    try {
        // try to retrieve the id after #
        var regex = new RegExp("#(.+)$");
        var results = regex.exec(window.location.href);

        if (results != null && results[1] != null) {
            parent.gsSenseId = results[1];
            parent.giPhrId = results[1];
        }

        if (parent.gsSenseId != null)
            highlightsense(parent.gsSenseId);

        if (parent.giPhrId != null) {
            var oPhrNode = document.getElementById("PH." + parent.giPhrId);
            if (!oPhrNode)
                return;
            oPhrNode.style.backgroundColor = "#C1E7FC";
            scrollToElt(window, oPhrNode.id);
        }
        gapi.plusone.go();
//    } catch (err) {
//      alert('error in initEntry() :'+err);
//    }
}

/*Function that scroll to the unfolded entry*/
function scrollToOpenEntry() {
    try {
        var oDivs, oUnfold;
        oDivs = document.getElementsByTagName('div');
        for (var i=0;i<oDivs.length;i++) {
            if (oDivs.item(i).className == "unfolded") {
                oUnfold = oDivs.item(i);
                break;
            }
        }
        if (oUnfold)
            scrollToElt(this, oUnfold.getAttribute("id"));
    } catch (err) { }
}

/*Function that gives the complete name of the current opening headword*/
function giveCurHwdName(dispWordclass) {
    try {
        var oOpenEntry;
        var oDivs = document.getElementsByTagName('div');
        var sHwd = "";
        for (var i=0; i<oDivs.length ; i++) {
            if (oDivs.item(i).className == "unfolded")
                oOpenEntry = oDivs.item(i);
        }
        if (oOpenEntry) {
            var oSpanHwdselected = getElementByClassName(oOpenEntry,'span','headwordSelected');
            var oSpanHmgselected = getElementByClassName(oOpenEntry,'span','homographsSelected');
            var oSpanWdselected = getElementByClassName(oOpenEntry,'span','wordclassSelected');
            sHwd = oSpanHwdselected ? oSpanHwdselected.innerHTML : "";
            sHwd += oSpanHmgselected ? (" " + oSpanHmgselected.innerHTML + " ") : " ";
            sHwd += (oSpanWdselected && dispWordclass) ? oSpanWdselected.innerHTML : "";
        }
        return sHwd;
    } catch (err) { }
}

function openPhrasalPopup(psPhrList) {
    try {
        if (!psPhrList.length)
            return;
        var sPopupPath = gsPwdLocation + "popup/phrasal_result.html?phrids=" + psPhrList;
        open(sPopupPath, "LDOCE_PHRSEARCH", "width=340,height=400,left=320,top=200,scrollbars=no,status=no,dependent=yes,hotkeys=no");

    } catch (err) { }
}
function loadPronPopup(){
    try {
        window.focus();
        var oPronPict = document.getElementById("proncar");
        var oEntryPict = opener.document.getElementById("proncar");
        if (oEntryPict)
            oPronPict.src = oEntryPict.getAttribute("src");
    } catch (err) { }
}

function showSentence(piIncrement){
    try {
        var oPrevBtn = document.getElementById("sentprev");
        var oNextBtn = document.getElementById("sentnext");
        var oSentIdxNode = document.getElementById("sentidx");

        var iOldSentenceId = "0000" + (giPronsentIdx);
        iOldSentenceId = "pronsent" + iOldSentenceId.substr(iOldSentenceId.length-4);
        var iSentenceId = "0000" + (giPronsentIdx + piIncrement);
        iSentenceId = "pronsent" + iSentenceId.substr(iSentenceId.length-4);
        var oOldSentence = document.getElementById(iOldSentenceId);
        var oSentence = document.getElementById(iSentenceId);

        if (oSentence) {
            giPronsentIdx += piIncrement;
            oSentIdxNode.innerHTML = giPronsentIdx;
            oOldSentence.className = "nodisplay";
            oSentence.className = "popup-label";
            oPrevBtn.className = (giPronsentIdx == 1 ? "btn-hidden": "prev-btn");
            oNextBtn.className = (giPronsentIdx == giPronNb ? "btn-hidden": "next-btn");
        }
    } catch (err) { }
}

function goToEntry() {
    try {
        if (!giPMEntryId)
            return;
        opener.location = gsPwdLocation + "/dictionary/?id=" + giPMEntryId;
        window.close();
    } catch (err) { }
}

function unfoldPMEntry(piHwdId){
    try {
        var oEntryIframe = document.getElementById("entryFrame");
        var oResultIframe = document.getElementById("resultFrame");
        giPMEntryId = piHwdId;
        oEntryIframe.setAttribute("src", gsPwdLocation + "display/display.html?popupmode=1&unfolded=" + giPMEntryId + "&ids=" + giPMEntryId);
        oResultIframe.setAttribute("src", gsPwdLocation + "display/display.html?popupmode=1&popupreslist=1&unfolded=" + giPMEntryId + "&ids=" + gsPMFoldedIds);
    } catch (err) { }
}

function openPhrasalRes(piHwdId, piPhrId){
    try {
    	opener.location = gsPwdLocation + "display/display.html?unfolded=" + piHwdId + "&ids=" + piHwdId + "&phrid=" + piPhrId;
    } catch (err) { }
}

/* Sound Player Popup */
function playPronsentence(){
    try {
        var oSentence = document.getElementById("pronsentence");
        if (oSentence)
            oSentence.Play();
    } catch (err) {
       try {
		   window.location.reload(); //Fix to set working the replay on Macintosh (Safari...)
		} catch (e) { }
    }
}
/*Modify the location of the main document to display the precedent entry*/
function goPrev() {
    try {
        var iPrev = parent.prevEntryId;
        var oFrame = parent.document.getElementById('content_frame');
        oFrame.setAttribute("src", gsPwdLocation + "display/display.html?unfolded=" + iPrev + "&ids=" + iPrev);
    } catch (err) { }
}

/*Modify the location of the main document to display the next entry*/
function goNext() {
    try {
        var iNext = parent.nextEntryId;
        var oFrame = parent.document.getElementById('content_frame');
        oFrame.setAttribute("src", gsPwdLocation + "display/display.html?unfolded=" + iNext + "&ids=" + iNext);
    } catch (err) { }
}

function checkInputText(pbSubmit) {
 try {
    var oField = document.getElementById("q");
    var oForm = document.getElementById('toolbar_form');
    var bValid = checkSearchString(oField.value, true);
    if (pbSubmit) {
       if (bValid)
          oForm.submit();
    } else
       return bValid;
 } catch(err) {
     alert("ERROR function checkInputText:\n" + err);
 }
}

