// (c)2008 Transinsight GmbH - www.transinsight.com - All rights reserved.

var helpBaseUrl = "Curators/";
var baseUrl = "../Curators/";

applicationSettings.supportCurators = true;


function getTopFrame(){
    try {
        if (this.isTopFrame) {
            return this;
        }
        else
            if (parent.isTopFrame) {
                return parent;
            }
            else
                if (parent.parent.isTopFrame) {
                    return parent.parent;
                }
                else {
                    return null;
                }
    }
    catch (e) {
        return null;
    }
}


/**
 * Start up the curator mode
 * //TODO check whether this method is necessary
 *
 * @param {Object} searchParameters
 */
function startUpCuratorMode(searchParameters){
    if (isCuratorRegistered()) {
        var div = DOM_get('RequestCuratorAccount');
        if (div) {
            div.style.display = 'none';
        }
        curatorEmail = readSetting(applicationSettings, 'curatorEmail');

        if (searchParameters) {
            searchParameters.map['curator'] = curatorEmail;
        }

    }
    else { //automatically register
        if (searchParameters) {
            curatorEmail = searchParameters.map['curator'];

            if (curatorEmail) {
                requestCuratorAccount(curatorEmail, true, true);
            }
        }
    }
}

/**
 * request the curator account
 *
 * @param {Object} email
 */
function requestCuratorAccount(email, quietly, noAutoReload){
    if (isCuratorRegistered()) {
        alert('You have already been registed. \nYou can curate any article by clicking on the curation button.');
        getTopFrame().location.reload();
    }
    else {
        if (!email || email == "") {
            alert('Your email address is required.');
            return;
        }

        if (email.search(/^.*@..+\...+$/) < 0) {
            alert('A valid email address is required.');
            return;
        }

        generateCuratorCode(email, quietly);


        if (getTopFrame().searchParameters && "q" in getTopFrame().searchParameters) {
            startUpCuratorMode(getTopFrame().searchParameters);
            updateSearchParameters(getTopFrame().searchParameters, queryType);
        }

        if (!noAutoReload) {
            //TODO reload the same query
            getTopFrame().location.reload();
        }
    }
}

/**
 * Check whether the user is registered as curator, ie. if the curator email address and curator code
 * are set within the application settings.
 */
function isCuratorRegistered(){
    var cookie = readSetting(applicationSettings, 'curatorCode', '');
    var email = readSetting(applicationSettings, 'curatorEmail', '');
    if (!cookie && !email) {
        return false;
    }
    else {
        return true;
    }
}

/**
 * Given an email address call a generator to get a curator code.
 *
 * @param {Object} email
 * @see curators.xmap (generateCode)
 */
function generateCuratorCode(email, quietly){
    if (!isCuratorRegistered()) {
        var url = helpBaseUrl + 'generateCode';

        var completelocation = getTopFrame().location.href;
        url = completelocation.replace(/\/[^\/]*$/, "/" + url);

        var parameter = {
            'email': email
        };

        connection = new Connection(url);
        connection.on_fail = whenFailed;

        connection.parameters = new Array();
        connection.parameters['email'] = email;

        connection.establishPost(true); //synchron
        var text = connection.transport.responseText;
        var xmlDoc = createDocumentFromXML(text);

        var error = xmlDoc.getElementsByTagName("Error");
        if (error.length == 0) {
            //try with prefix
            error = xmlDoc.getElementsByTagName("ygg:Error");
        }
        var node = xmlDoc.getElementsByTagName("Curator");
        if (node.length == 0) {
            //try with prefix
            node = xmlDoc.getElementsByTagName("ygg:Curator");
        }
        if (error.length > 0 || node.length == 0) {
            var msg = 'The server could not process your request. You should try this later again.\n';
            alert(msg);
            return;
        }

        var code = node[0].getAttribute('code');
        storeSetting(applicationSettings, 'curatorCode', code);
        storeSetting(applicationSettings, 'curatorEmail', email);

        if (!quietly) {
            alert("You can start curating from now on."            /*+"\n\n" +
             "We will send you an email. Please confirm your registration as stated in the email." */
            );
        }
    }
}

/**
 * The action that is executed on click on the "This document does not belong here" icon.
 *
 * @param {Object} documentId
 * @param {Object} curatorId
 * @param {Object} rawString
 * @param {Object} selectedTerm
 */
function doesNotBelong(documentId, curatorId, rawString, selectedTerm){
    curatorEmail = readSetting(applicationSettings, 'curatorEmail', null);
    curatorCode = readSetting(applicationSettings, 'curatorCode', null);

    comment = prompt("Please leave optionally a short comment and press ok if you think this article is viewed erroneously. \nWe are thankful for any feedback to optimize our engine!", "");
    if (comment || comment == "") {
        var url = baseUrl + "doesNotBelong" +
        "?documentId=" +
        encodeURIComponent(documentId) +
        "&q=" +
        encodeURIComponent(rawString) +
        "&term=" +
        encodeURIComponent(selectedTerm) +
        "&comment=" +
        encodeURIComponent(comment);

        if (curatorEmail && curatorCode) {
            url = url + "&curator=" + encodeURIComponent(curatorEmail) + "&code=" + encodeURIComponent(curatorCode);
        }

        var connection = new Connection(url);
        connection.on_finish = function(c){
            checkResult(c);
        };
        connection.on_fail = whenFailed;
        connection.establish(false);
    }
}

/**
 * Remove the specified curation.
 * //TODO clean up parameter list
 *
 * @param {Object} documentId
 * @param {Object} curator
 * @param {Object} termId
 * @param {Object} nodeId
 * @param {Object} numOtherPostive
 * @param {Object} numOtherIrrelevant
 * @param {Object} numOtherNegative
 */
function removeCuration(documentId, curator, termId, nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative){
    curatorEmail = readSetting(applicationSettings, 'curatorEmail', null);
    curatorCode = readSetting(applicationSettings, 'curatorCode', null);

    try {
        var url = baseUrl + "curateTerm" +
        "?documentId=" +
        encodeURIComponent(documentId) +
        "&term=" +
        encodeURIComponent(termId) +
        "&curator=" +
        encodeURIComponent(curatorEmail) +
        "&code=" +
        encodeURIComponent(curatorCode);

        var posimg = document.getElementById('pos:' + nodeId);
        var irrimg = document.getElementById('irr:' + nodeId);
        var negimg = document.getElementById('neg:' + nodeId);
        var discussimg = document.getElementById('discuss:' + nodeId);
        var removeimg = document.getElementById('remove:' + nodeId);

        var connection = new Connection(url);

        var nr = 0;
        connection.on_finish = function(c){
            if (checkResult(c)) {
                replaceIcons(posimg, irrimg, negimg, discussimg, removeimg, null, numOtherPostive, numOtherIrrelevant, numOtherNegative, curator, documentId);

                if (nr++ == 0) {
                    modifyCurationCounts(function(value){
                        return --value;
                    });
                }

                setOnclickEvent(irrimg, function(){
                    storeCuratedTerm(documentId, termId, curator, '0', nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative);
                });
                setOnclickEvent(posimg, function(){
                    storeCuratedTerm(documentId, termId, curator, '1', nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative);
                });
                setOnclickEvent(negimg, function(){
                    storeCuratedTerm(documentId, termId, curator, '-1', nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative);
                });
            }
        };
        connection.on_fail = whenFailed;
        connection.establish(true);
    }
    catch (e) {
        alert(e);
        whenFailed();
    }
}

function setOnclickEvent(node, func){
    if (node) {
        node.onclick = func;
    }
}




/**
 * Store a curation.
 * //TODO clean up parameter list
 *
 *
 * @param {Object} documentId
 * @param {Object} termId
 * @param {Object} curator
 * @param {Object} value one of (-1,0,+1) indicating (not correct, less relevant, highly relevant)
 * @param {Object} nodeId a string determinining the row in the term table (it consists of documentid and termid)
 * @param {Object} numOtherPostive number of other curators that voted +1
 * @param {Object} numOtherIrrelevant number of other curators that voted 0
 * @param {Object} numOtherNegative number of other curators that voted -1
 */
function storeCuratedTerm(documentId, termId, curator, value, nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative){
    curatorEmail = readSetting(applicationSettings, 'curatorEmail', null);
    curatorCode = readSetting(applicationSettings, 'curatorCode', null);

    try {
        var url = baseUrl + "curateTerm" +
        "?documentId=" +
        encodeURIComponent(documentId) +
        "&term=" +
        encodeURIComponent(termId) +
        "&curator=" +
        encodeURIComponent(curatorEmail) +
        "&code=" +
        encodeURIComponent(curatorCode) +
        "&value=" +
        encodeURIComponent(value);

        var connection = new Connection(url);

        var posimg = document.getElementById('pos:' + nodeId);
        var irrimg = document.getElementById('irr:' + nodeId);
        var negimg = document.getElementById('neg:' + nodeId);
        var discussimg = document.getElementById('discuss:' + nodeId);
        var removeimg = document.getElementById('remove:' + nodeId);

        var nr = 0;

        connection.on_finish = function(c){
            if (checkResult(c)) {
                var check = !isCurated(posimg, irrimg, negimg);

                replaceIcons(posimg, irrimg, negimg, discussimg, removeimg, value, numOtherPostive, numOtherIrrelevant, numOtherNegative, curator, documentId);

                if (nr++ == 0 && check) {
                    modifyCurationCounts(function(value){
                        return ++value;
                    });
                }
            }
            if (value == 0) {
                setOnclickEvent(irrimg, function(){
                    removeCuration(documentId, curator, termId, nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative);
                });
                setOnclickEvent(posimg, function(){
                    storeCuratedTerm(documentId, termId, curator, '1', nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative);
                });
                setOnclickEvent(negimg, function(){
                    storeCuratedTerm(documentId, termId, curator, '-1', nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative);
                });
            }
            else
                if (value < 0) {
                    setOnclickEvent(negimg, function(){
                        removeCuration(documentId, curator, termId, nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative);
                    });
                    setOnclickEvent(irrimg, function(){
                        storeCuratedTerm(documentId, termId, curator, '0', nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative);
                    });
                    setOnclickEvent(posimg, function(){
                        storeCuratedTerm(documentId, termId, curator, '1', nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative);
                    });
                }
                else
                    if (value > 0) {
                        setOnclickEvent(posimg, function(){
                            removeCuration(documentId, curator, termId, nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative)
                        });
                        setOnclickEvent(irrimg, function(){
                            storeCuratedTerm(documentId, termId, curator, '0', nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative);
                        });
                        setOnclickEvent(negimg, function(){
                            storeCuratedTerm(documentId, termId, curator, '-1', nodeId, numOtherPostive, numOtherIrrelevant, numOtherNegative);
                        });
                    }
        };
        connection.on_fail = whenFailed;
        connection.establish(true);
    }
    catch (e) {
        whenFailed();
    }
}

var activeregex = /.*Active\.png/;
/**
 * Check whether one of the images tells whether the term has been curated.
 *
 * @param {Object} posimg
 * @param {Object} irrimg
 * @param {Object} negimg
 */
function isCurated(posimg, irrimg, negimg){
    var b = false;
    b |= posimg && activeregex.test(posimg.src);
    b |= irrimg && activeregex.test(irrimg.src);
    b |= negimg && activeregex.test(negimg.src);

    return b;
}

/**
 * After a curation this method is used to replace the curation icons, i.e. grey icons become colored etc.
 *
 * @param {Object} posImg
 * @param {Object} irrImg
 * @param {Object} negImg
 * @param {Object} disImg
 * @param {Object} rmvImg
 * @param {Object} value
 * @param {Object} numOtherPositive
 * @param {Object} numOtherIrrelevant
 * @param {Object} numOtherNegative
 * @param {Object} curator
 */
function replaceIcons(posImg, irrImg, negImg, disImg, rmvImg, value, numOtherPositive, numOtherIrrelevant, numOtherNegative, curator, documentId){
    showCurationSaved(documentId);
    if (value == null) //remove all highlights
    {
        if (posImg != null) {
            if (numOtherPositive > 0) {
                posImg.src = "../Curators/curationIconPositiveFade.png";
            }
            else {
                posImg.src = "../Curators/curationIconPositiveInactive.png";
            }
        }
        if (irrImg != null) {
            if (numOtherIrrelevant > 0) {
                irrImg.src = "../Curators/curationIconNeutralFade.png"
            }
            else {
                irrImg.src = "../Curators/curationIconNeutralInactive.png"
            }
        }

        if (negImg != null) {
            if (numOtherNegative > 0) {
                negImg.src = "../Curators/curationIconNegativeFade.png";
            }
            else {
                negImg.src = "../Curators/curationIconNegativeInactive.png";
            }
        }

        if (disImg != null) {
            disImg.style.display = "none";
        }

        if (rmvImg != null) {
            rmvImg.style.display = "none";
        }


    }
    else {
        if (value > 0) //set to positive
        {
            if (posImg != null) {
                posImg.src = "../Curators/curationIconPositiveActive.png";
            }

            if (irrImg != null) {
                if (numOtherIrrelevant > 0) {
                    irrImg.src = "../Curators/curationIconNeutralFade.png"
                }
                else {
                    irrImg.src = "../Curators/curationIconNeutralInactive.png"
                }
            }

            if (negImg != null) {
                if (numOtherNegative > 0) {
                    negImg.src = "../Curators/curationIconNegativeFade.png";
                }
                else {
                    negImg.src = "../Curators/curationIconNegativeInactive.png";
                }
            }

            if (disImg != null) {
                disImg.style.display = "";
            }
            if (rmvImg != null) {
                rmvImg.style.display = "block";
            }

        }
        else
            if (value < 0) //set to negative
            {
                if (negImg != null) {
                    negImg.src = "../Curators/curationIconNegativeActive.png";
                }

                if (posImg != null) {
                    if (numOtherPositive > 0) {
                        posImg.src = "../Curators/curationIconPositiveFade.png";
                    }
                    else {
                        posImg.src = "../Curators/curationIconPositiveInactive.png";
                    }
                }

                if (irrImg != null) {
                    if (numOtherIrrelevant > 0) {
                        irrImg.src = "../Curators/curationIconNeutralFade.png"
                    }
                    else {
                        irrImg.src = "../Curators/curationIconNeutralInactive.png"
                    }
                }

                if (disImg != null) {
                    disImg.style.display = "";
                }

                if (rmvImg != null) {
                    rmvImg.style.display = "block";
                }

            }
            else /*value == 0*/ //set to irrelevant
            {
                if (irrImg != null) {
                    irrImg.src = "../Curators/curationIconNeutralActive.png";
                }

                if (posImg != null) {
                    if (numOtherPositive > 0) {
                        posImg.src = "../Curators/curationIconPositiveFade.png";
                    }
                    else {
                        posImg.src = "../Curators/curationIconPositiveInactive.png";
                    }
                }

                if (negImg != null) {
                    if (numOtherNegative > 0) {
                        negImg.src = "../Curators/curationIconNegativeFade.png";
                    }
                    else {
                        negImg.src = "../Curators/curationIconNegativeInactive.png";
                    }
                }

                if (disImg != null) {
                    disImg.style.display = "";
                }

                if (rmvImg != null) {
                    rmvImg.style.display = "block";
                }
            }
    }
}


function whenFailed(){
    alert("Sorry, this did not work properly.\nPlease try it again later.");
}

function checkResult(connection){
    if (-1 != connection.body.indexOf("Error")) {
        whenFailed();
        return false;
    }
    return true;
}

function proposeTerms(documentId, curator){
    try {
        var element = document.getElementById("proposeTerms:" + documentId);

        var input_text = element.getElementsByTagName("input")[0];
        var text = "not specified";
        if (input_text.type == "text") {
            text = input_text.value;
        }

        requestTermAmbiguaty(element, documentId, text, curator);
    }
    catch (e) {
        whenFailed();
    }
}



//TODO the creation of term rows should be outsourced to an xslt transformer
function requestTermAmbiguaty(element, documentId, termName, curator){
    try {
        if (!termName) {
            alert("No term specified. \nPlease type a term label or term id first.");
        }
        else {
            var url = baseUrl + "propose?" +
            "q=" +
            encodeURIComponent(termName) +
            "&m=50";

            var connection = new Connection(url);
            connection.on_fail = whenFailed;
            connection.on_finish = checkResult;
            connection.establish(true);

            var text = connection.transport.responseText;
            var xmlDoc = createDocumentFromXML(text);
            var node = document.getElementById("selectTermProposal:" + documentId);

            //remove all children from div
            if (node.childNodes) {
                for (i = 0; i < node.childNodes.length; ++i) {
                    node.removeChild(node.childNodes[i]);
                }
            }

            var terms = xmlDoc.getElementsByTagName("ygg:Term");
            if (terms.length == 0) //try without namespace
            {
                terms = xmlDoc.getElementsByTagName("Term");
            }

            if (terms.length != 0) {
                table = document.createElement("table");
                table.className = "InfoPanel";
                table.width = "100%";

                var thead = document.createElement("thead");
                var theadRow = document.createElement("tr");
                var theadCol = document.createElement("th");

                theadRow.appendChild(theadCol);
                thead.appendChild(theadRow);
                table.appendChild(thead);

                var tbody = document.createElement("tbody");

                var synonymString = "";
                var countNonSynonym = 0;
                for (i = 0; i < terms.length; ++i) {
                    var tr = document.createElement("tr");
                    var td = document.createElement("td");

                    if (terms[i].parentNode.nodeName == "ygg:Synonyms") {
                        synonymString = synonymString + "\n" + terms[i].getAttribute("name");

                    }
                    else {
                        ++countNonSynonym;
                        td.className = "TermCell";

                        var div = document.createElement("div");
                        div.className = "TextminedTermRef";
                        div.style.verticalAlign = "middle";

                        var currentTermId = terms[i].getAttribute("id");
                        var description = terms[i].getAttribute("desc");
                        var currentLabel = terms[i].getAttribute("name");
                        var txtNode = document.createTextNode(currentLabel);

                        var imgId = documentId + currentTermId + ":Proposed";
                        var imgNodePos = document.createElement("img");
                        imgNodePos.id = "pos:" + imgId;
                        imgNodePos.src = "../Curators/curationIconPositiveInactive.png";
                        imgNodePos.title = "Highly relevant here."; //"Activate this to indicate that this term is missing in the list above.";
                        imgNodePos.style.border = "none";
                        imgNodePos.style.verticalAlign = "middle";
                        imgNodePos.setAttribute("onclick", "Javascript:storeCuratedTerm('" + documentId + "','" + currentTermId + "','" + curator + "','1','" + imgId + "', 0,0,0)");

                        var imgNodeNotRel = document.createElement("img");
                        imgNodeNotRel.id = "irr:" + imgId;
                        imgNodeNotRel.src = "../Curators/curationIconNeutralInactive.png";
                        imgNodeNotRel.title = "Less relevant here."; //"Activate this to indicate that this term is missing in the list above.";
                        imgNodeNotRel.style.border = "none";
                        imgNodeNotRel.style.verticalAlign = "middle";
                        imgNodeNotRel.setAttribute("onclick", "Javascript:storeCuratedTerm('" + documentId + "','" + currentTermId + "','" + curator + "','0','" + imgId + "', 0,0,0)");

                        var imgNodeNeg = document.createElement("img");
                        imgNodeNeg.id = "neg:" + imgId;
                        imgNodeNeg.src = "../Curators/curationIconNegativeInactive.png";
                        imgNodeNeg.title = "NOT correct here."; // "Activate this to indicate that this term is missing in the list above.";
                        imgNodeNeg.style.border = "none";
                        imgNodeNeg.style.verticalAlign = "middle";
                        imgNodeNeg.setAttribute("onclick", "Javascript:storeCuratedTerm('" + documentId + "','" + currentTermId + "','" + curator + "','-1','" + imgId + "', 0,0,0)");

						var localname = currentTermId.substring(0,currentTermId.indexOf("#"));
						var imgNodeOntology = document.createElement("img");
                        imgNodeOntology.width="11";
                        imgNodeOntology.height="11";
                        imgNodeOntology.style.border = "medium none";
						imgNodeOntology.style.margin = "0px 3px 0px 5px";
                        imgNodeOntology.style.verticalAlign = "middle";
                        imgNodeOntology.alt=" (" + localname + ") ";
						imgNodeOntology.src="../Ontology/"+localname+".gif";

                        var discImg = document.createElement("img");
                        discImg.id = "discuss:" + imgId;
                        discImg.src = "../Curators/discussion.png";
                        discImg.style.border = "none"
                        discImg.style.verticalAlign = "middle"
                        discImg.style.display = "none";
                        discImg.setAttribute("onclick", "Javascript:storeDiscussion('" + documentId + "', '" + currentTermId + "', '" + curator + "','',this)");


                        div.appendChild(imgNodePos);
                        div.appendChild(imgNodeNotRel);
                        div.appendChild(imgNodeNeg);
						div.appendChild(document.createTextNode(" "));
						div.appendChild(imgNodeOntology);
                        div.appendChild(txtNode);
                        div.appendChild(document.createTextNode(" "));
                        div.appendChild(discImg);
                        //                        div.appendChild(document.createTextNode(" "));
                        //                        div.appendChild(remvImg);

                        var title = "";
                        if (description) {
                            title = title + description;
                        }
                        if (synonymString) {
                            title = title + "\nSynonyms:\n" + synonymString;
                        }
                        if (currentTermId) {
                            title = title + " (" + currentTermId + ")";
                        }
                        if (title) {
                            div.title = title;
                        }
                        td.appendChild(div);
                        tr.appendChild(td);
                        tbody.appendChild(tr);

                        synonymString = "";
                    }
                }

                var theadText = document.createTextNode("" + countNonSynonym + " found term" + (terms.length == 1 ? "" : "s"));
                theadCol.appendChild(theadText);
                table.appendChild(tbody);
                //formular.appendChild(table);

                node.appendChild(table);
                node.style.display = "";

            }
            else {
                alert("No terms found!");
            }
            makeNiceTitles();
        }
    }
    catch (e) {
        whenFailed();
    }
}

function storeDiscussion(documentId, termId, curator, previousDiscussion, node){
    curatorEmail = readSetting(applicationSettings, 'curatorEmail', null);
    curatorCode = readSetting(applicationSettings, 'curatorCode', null);

    var discussion = prompt("Your discussion please:", previousDiscussion);
    if (discussion) {
        var url = baseUrl + "discussTerm" +
        "?documentId=" +
        encodeURIComponent(documentId) +
        "&term=" +
        encodeURIComponent(termId) +
        "&curator=" +
        encodeURIComponent(curatorEmail) +
        "&code=" +
        encodeURIComponent(curatorCode) +
        "&value=" +
        encodeURIComponent(discussion);

        var connection = new Connection(url);
        connection.on_finish = checkResult;
        connection.on_fail = whenFailed;
        connection.establish(true);

        if (connection.success) {
            node.setAttribute("onclick", "Javascript:storeDiscussion('" + documentId + "', '" + termId + "', '" + curator + "','" + discussion + "',this)");
            makeNiceTitle(node, discussion);
        }
    }
}

function modifyCurationCounts(modify){
    var nodes = document.getElementsByName("TermCurationCount");
    for (var i = 0, l = nodes.length; i < l; ++i) {
        var textnode = nodes[i].firstChild;
        var count = modify(textnode.nodeValue);
        textnode.nodeValue = count;
    }
}

function showCurationSaved(documentId){
    var node = document.getElementById("CurationCountInfoSaved:" + documentId);
    node.style.display = "block";
}

function hideCurationsSaved(documentId){
    var node = document.getElementById("CurationCountInfoSaved:" + documentId);
    node.style.display = "none";
}
