// Main portal functions - to be included in the top frame
// @author Daniel Lichtenberger, UCS

// --------- shopping cart-related functions ---------

function keepCartPupup() {
    popupDispatcher.keepCartPopup = true;
}

function updateJobName(name) {
    name = name.substring(0, Math.min(name.length, 12));
    var container = getObj("currentJobName");
    container.innerHTML = name;
    container.style.visibility = "visible";
}

function addToCart(oid, openCart, toggleItem, resolveMedia, recordXPath, recordOptions) {
    if (cartAvailable) {
        // call cart directly
        if (openCart) {
            cartPopup.show();
        }
        cartAvailable = false;
        cartPopup.getFrame().addOid(oid, toggleItem == true, resolveMedia == true, recordXPath, recordOptions);
    } else {
        // store OID in queue to be processed when cart becomes available again
        cartOidQueue.push(oid);
        cartToggleQueue.push(toggleItem == true);
        cartResolveMediaQueue.push(resolveMedia == true);
    }
}

function addToLightBox(oid){
        if (lightBoxAvailable) {
        // call lightBox directly
        lightBoxAvailable = false;
        lightboxesPopup.getFrame().addOid(oid);
        }
        else {
        // store OID in queue to be processed when lightBox becomes available again
            var alreadyIn = false;
            for (var i=0;i<lightBoxOidQueue.length;i++) {
                if (lightBoxOidQueue[i] == oid) {
                    alreadyIn = true;
                    break;
                }
            }
            if (!alreadyIn) {
                lightBoxOidQueue.push(oid);
            }
        }
}

function removeFromLightBox(oid){
    lightboxesPopup.getFrame().removeOid(oid);
}

function openPricePopup(oid) {
    loadWindow(getBase() + "cart/priceTable.popup.jsp?oid=" + oid + "&addToCart=true");
}

function cartLoaded() {
    if (cartOidQueue.length > 0) {
        // process queued items
        cartAvailable = false;
        cartPopup.getFrame().addOids(cartOidQueue, cartToggleQueue, cartResolveMediaQueue);
    } else {
        cartAvailable = true;
    }
    cartOidQueue = new Array();
    cartToggleQueue = new Array();
    cartResolveMediaQueue = new Array();
    frameLoaded();
}

function lightBoxLoaded() {
    if (lightBoxOidQueue.length > 0) {
        // process queued items
        lightBoxAvailable = false;
        lightboxesPopup.getFrame().addOids(lightBoxOidQueue);
    } else {
        lightBoxAvailable = true;
    }
    lightBoxOidQueue = new Array();
    frameLoaded();
}

function cartHasOid(oid) {
    return cartOids["" + oid] != null;
}

function lightBoxHasOid(oid) {
    return lightBoxOids["" + oid] != null;
}

// called when cart frame is opened (except for the first time)
function onCartShow() {
    var cart = cartPopup.getFrame();
    if (cartAvailable && cart.isEmptyContent) {
        // lazy-load content
        cart.loadContent();
        cartAvailable = false;
    }
}

function onSearchFormShow() {
    var frame = searchFormPopup.getFrame();
    if (searchFormPopup.visible && searchFormPopup.initialized && frame.searchForm) {
        frame.focus();  // focus first input field
        /*if (frame.searchForm["queryExactPhrase"] && frame.searchForm["queryExactPhrase"].focus) {
            frame.searchForm["queryExactPhrase"].focus();
        } */
    }
}

function setCartItems(numItems) {
    cartItems = numItems;
    var link = document.getElementById("cartMenuLink");
    if (msg.CARTMENU.indexOf("[0]") != -1 && link) {
        link.innerHTML = msg.CARTMENU.replace("[0]", numItems > 0 ? numItems : msg.CARTEMPTY);
    }
}

function setLightBoxItems(numItems) {
    lightBoxItems = numItems;
    var link = document.getElementById("lightBoxMenuLink");
    if (msg.LIGHTBOXMENU.indexOf("[0]") != -1 && link) {
        link.innerHTML = msg.LIGHTBOXMENU.replace("[0]", numItems > 0 ? numItems : msg.LIGHTBOXEMPTY);
    }
}

// ----------- misc helper functions -------------
function submitenter(myfield,e) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == 13) {
        // execute last search type
        if ("details" == lastSearchType) {
            loadResults(myfield.value);
        } else {
            loadSiteMap(myfield.value);
        }
        return false;
    } else {
        return true;
    }
}

function showStartPage() {
    topicsTree.collapseAll();
    loadFrame('conframe', getBase() + 'index.content.jsp');
}


// -------------- content resizing functions ------------------

// keep calculated sizes in JS variables to avoid browser DOM troubles...
var contentHeight = 0;

// adjust the divs, for all child div the function adjustDiv is called
function adjustDiv() {
    var leftarea = getObj("navigation");
    var rightarea = getObj("content");
    var spacer = getObj("navconspacer");

    var windowHeight = getWindowHeight(document);
    contentHeight = Math.max(1, windowHeight - dimensions.headerHeight - dimensions.menuBarHeight );
      rightarea.style.height = contentHeight + "px";
    leftarea.style.height = Math.max(1, windowHeight
            - dimensions.headerHeight -  dimensions.menuBarHeight - dimensions.topicHeaderHeight) - 32 + "px";
    spacer.style.height = Math.max(1, windowHeight -  dimensions.headerHeight) + "px";

    // adjust content divs in popup frames
    for (var i = 0; i < popupDispatcher.popups.length; i++) {
        var popup = popupDispatcher.popups[i];
        if (popup.iframeRendered) {
            popup.refresh();
            if (popup.getFrame().adjustDiv) {
                // call adjust div on popup...
                popup.getFrame().adjustDiv(windowHeight);
            }
        }
    }
}

// general resize function for popup frame content
// assuming that there is a content frame with an optional footer and an optional header
function adjustPopupDiv(document, windowHeight, paddingTop, contentDiv, footerDiv, headerDiv) {
    // is called by adjustDiv (for each popup frame)!
    var content = document.getElementById(contentDiv);
    if (content == null)
        return;
    var headerHeight = 0;
    if (headerDiv != "undefined" && headerDiv != null) {
        var header = document.getElementById(headerDiv);
        headerHeight = trimPx(header.style.height);
    }
    var footherHeight = 0;
    if (footerDiv != "undefined" && footerDiv != null) {
        // nove footer
        var footer = document.getElementById(footerDiv);

        footer.style.top = Math.max(1, windowHeight -24 -dimensions.headerHeight - dimensions.menuBarHeight - footherHeight)  + "px";
    }
    content.style.height = Math.max(1, windowHeight -24 -dimensions.headerHeight - dimensions.menuBarHeight - headerHeight - footherHeight - paddingTop) + "px";
}

// hides all popups
function showMainContentFrame() {
    popupDispatcher.hide();
}

// ------------------- loading screen handler -----------------------

// counter to represent loaded frames
var loadingFrames = 3;      // frame list: topic tree, topic nav frame, shopping cart

function frameLoaded() {
    if (--loadingFrames <= 0) {
        getObj("contentWrapper").style.visibility = "visible";
        getObj("loadingMessage").style.display = "none";
        // Force refresh for Firefox 1.0.x
        getObj("conframe").style.display = "block";
        getObj("navframe").style.display = "block";
        if (popupDispatcher.showOnFrameLoaded != null) {
            popupDispatcher.show(popupDispatcher.showOnFrameLoaded);
            popupDispatcher.showOnFrameLoaded = null
        }
    }
}

// -------------------- search results helper functions -------------------------


/* We have to create the search results here in the top frame to avoid
   having IE's "garbage" collection throw away our results */
function createSearchResult(searchResult, par, doc, searchForm, thumbScale) {
    eval(searchResult + " = new SearchResult(par, doc, searchForm, RESULT_PAGESIZES);");
}

function getSearchResult(resultType) {
    eval("var result = searchResult" + resultType);
    return result;
}

function getRelationsResult() {
    return getSearchResult(SEARCH_OBJ2OBJ);
}

function getSubnodesResult() {
    return getSearchResult(SEARCH_TOPICS);
}

function setSearchValue(key, value) {
    searchFormState[key] = value;
}

function getSearchValue(key) {
    return searchFormState[key];
}

function getSearchContainer() {
    return searchFormState;
}

// updates the cart link/button for the given OID in the current search result
// and in the current lightbox
function updateResultCartIcon(oid) {
    if (lastSearchResult != null) {
        lastSearchResult.updateCartIcon(oid);
    }
    if (lastLightBoxSearchResult != null && lightBoxHasOid(oid)) {
        lastLightBoxSearchResult.updateCartIcon(oid);
    }
}

// updates the cart link/button for the given OIDs in the current search result
// and in the current lightbox
function updateResultCartIcons(oids) {
    if (lastSearchResult != null) {
        for (var i = 0; i < oids.length; i++) {
            lastSearchResult.updateCartIcon(oids[i]);
        }
    }
    if (lastLightBoxSearchResult != null) {
        for (var i = 0; i < oids.length; i++) {
            lastLightBoxSearchResult.updateCartIcon(oids[i]);
        }
    }
}

// updates ONLY the lightbox link/button for the given OID in the current search result
function updateResultLightBoxIcon(oid) {
    if (lastSearchResult != null) {
        lastSearchResult.updateLightBoxIcon(oid);
    }
}

// updates ALL the lightbox link/button for the given OID in the current search result
function updateResultLightBoxIcons() {
    if (lastSearchResult != null) {
        lastSearchResult.updateLightBoxIcons();
    }
}

// -------------------- search submit functions --------------------

function checkSearchString(searchString) {
    if (searchString == null || trim(searchString).length == 0) {
        alert(msg.ENTERQUERY);
        return null;
    }
    submitString = trim(searchString)
    if (submitString.length < 2) {
        alert(msg.MIN3CHARS);
        return null;
    }
    return submitString;
}

function loadSiteMap(searchString) {
    var submitString = checkSearchString(searchString);
    if (submitString == null) {
        return;
    }
    lastSearchType = "sitemap";
    sitemapPopup.load(getBase()+'siteMap.content.jsp?searchString='+encodeURIComponent(submitString));
    sitemapPopup.show();
}

function loadResults(searchString, createdLastDays) {
    var submitString = checkSearchString(searchString);
    if (submitString == null) {
        return;
    }
    if (document.getElementById("searchString") != null) {
        document.getElementById("searchString").value = submitString;
    }
    lastSearchType = "details";
    // update form values
    setSearchValue("queryExactPhrase", "");
    setSearchValue("queryOneWord", "");
    setSearchValue("queryAllWords", searchString);
    setSearchValue("fieldsAllWords", SEARCHBY_TITLE);
    setSearchValue("createdLastDays", createdLastDays);
    var url = getBase() + "search/submitSearch.content.jsp?"
        + (createdLastDays != null ? "createdLastDays=" + createdLastDays + "&" : "")
        + "searchString=" + encodeURIComponent(submitString);
    loadUrl('conframe', url);
}

function loadSearchForm(searchString) {
    if (!searchFormPopup.visible) {
        if (!searchString)
            searchString = "";
        searchFormPopup.visible = true;
        searchFormPopup.load(getBase() + "search.do?action=searchForm&searchString=" + encodeURIComponent(searchString) + (lastSearchType != null ?
                                                                                                                           "&searchTarget=" + lastSearchType : ""));
        searchFormPopup.show();
    } else {
        searchFormPopup.hide();
    }
}

function keywordQuery(document, baseInputId) {
    // extract selected keyword checkboxes from source document
    var inputs = document.getElementsByTagName("input");
    var keywords = [];
    for (var i=0;i<inputs.length;i++) {
        var input = inputs[i];
        var id = input.id;
        if (id != null && id.indexOf(baseInputId) == 0 && input.checked) {
            keywords.push(input.value.split('(')[0]);
        }
    }
    if (keywords.length == 0) {
        alert(msg.KEYWORDSEMPTY);
        return;
    }
    //alert(keywords.join(" "));
    loadResults(keywords.join(" "));
    // submit query
    //KeywordSearchCache = keywords.join(" OR ");
    //frames["searchFormFrame"].document.forms[0]["textFilterValue[3]"].value = keywords.join(" OR ");
    //if(frames["searchFormFrame"].document == null) {
    //    extendSearch();
    //}
    //frames["searchFormFrame"].document.Search.elements["textFilterValue\[0\]"].value = "";
    //frames["searchFormFrame"].document.Search.elements["textFilterValue\[1\]"].value = "";
    //frames["searchFormFrame"].document.Search.elements["textFilterValue\[2\]"].value = "";
    //frames["searchFormFrame"].document.Search.elements["textFilterValue\[3\]"].value = keywords.join(" OR ");
    //frames["searchFormFrame"].document.Search.submit();
    //frames["searchFormFrame"].document.Search.elements[8].value = "";
    //frames["searchFormFrame"].submitSearch();
    //loadResults(keywords.join(" OR "));
}
// ------------ finedata download/show functions --------------

function downloadFineData(url) {
    backgroundLoad(url);
}

/** Loads the given URL in the invisible loaded frame (for actions without output or only JS output) */
function backgroundLoad(url) {
    var loaderFrame = frames["loaderFrame"];
    loaderFrame.location.href = url;
}

// --------------- updates the GUI locale ------------------

function updateGuiLanguage(languageId) {
    backgroundLoad(getBase() + "language.do?action=update");

}

function openpressreport() {
    parent.frames["conframe"].document.getElementById("pressreport").style.height="";
    parent.frames["conframe"].document.getElementById("pressreportbutton").href="javascript: top.closepressreport()";
    parent.frames["conframe"].document.getElementById("pressreportbutton").innerHTML= hidePresseReport;
}

function closepressreport() {
    parent.frames["conframe"].document.getElementById("pressreport").style.height="200px";
    parent.frames["conframe"].document.getElementById("pressreportbutton").href="javascript: top.openpressreport()";
    parent.frames["conframe"].document.getElementById("pressreportbutton").innerHTML= showPresseReport;

}
