/**
 * Created by adekker on 05/12/14.
 */

// ========================
// ADVANCED SEARCH
//
// developer: adekker
//========================

function removePreviousPlusButton(block, counter) {

    counter--;
    if (counter > -1)
        document.getElementById(block + "PlusButton" + counter).style.display="none";
}


// Remove this row if it's not the last one! also add previous plus button.
function removeThisRow(block, counter) {

    var blockId = block + counter;
    var node = document.getElementById(blockId);

    var parentBlock = block.substr(0, block.length - 1) + "ies";
    var parentNode = document.getElementById(parentBlock);
    var divNodes = parentNode.getElementsByTagName("div");
    var divNodesQuantity = divNodes.length;

    // Not the last one!
    if (divNodesQuantity == 1) {
        addAnotherRow(block, counter);
    }

    // Get the last row
    var lastRow = 0;
    var beforeLastRow = 0;
    for (i = 0; i < divNodesQuantity; i++) {
        var id = divNodes[i].getAttributeNode("id").value;
        var row = id.substr(block.length);

        if (row > lastRow) {
            beforeLastRow = lastRow;
            lastRow = row;
        }
    }

    // Delete the row!
    document.getElementById(parentBlock).removeChild(node);

    // If it's the only row, add a plus button to the next row, or...
    // If it's the last row, add a plus button to the previous row
    if (divNodesQuantity == 1)
        document.getElementById(block + "PlusButton" + (counter + 1)).style.display = "inline";
    else if (counter == lastRow) {
        document.getElementById(block + "PlusButton" + (beforeLastRow)).style.display = "inline";
    }
}

// Add another row of the same block! also remove plus button.
function addAnotherRow(block, counter) {

    var blockId = block+counter;
    var modelNode = document.getElementById(blockId);
    var newNode = modelNode.cloneNode(true);
    var children = newNode.childNodes;
    var newCounter = counter+1;

    //var msg = blockId+"\n";
    newNode.setAttribute('id',blockId.replace(counter,newCounter));

    for(i=0;i<children.length;i++) {
        if (children[i].nodeType == 1) {
            //msg += children[i].nodeName + "\n";

            nameValue = children[i].getAttribute("name");
            typeValue = children[i].getAttribute("type");
            idValue = children[i].getAttribute("id");
            onclickValue = children[i].getAttribute("onclick");
            onkeyupValue = children[i].getAttribute("onkeyup");
            onblurValue = children[i].getAttribute("onblur");
            onmouseoutValue = children[i].getAttribute("onmouseout");

            if (nameValue != null)
                children[i].setAttribute("name", nameValue.replace(counter,newCounter));
            nameValue = children[i].getAttribute("name");

            if (idValue != null)
                children[i].setAttribute("id", idValue.replace(counter,newCounter));
            idValue = children[i].getAttribute("id");

            if (onclickValue != null)
                children[i].setAttribute("onclick", onclickValue.replace(counter,newCounter));

            if (onkeyupValue != null)
                children[i].setAttribute("onkeyup", onkeyupValue.replace(counter,newCounter));

            if (onblurValue != null)
                children[i].setAttribute("onblur", onblurValue.replace(counter,newCounter));

            if (onmouseoutValue != null)
                children[i].setAttribute("onmouseout", onmouseoutValue.replace(counter,newCounter));

            if (children[i].nodeName == "INPUT" && idValue != null && typeValue != null && typeValue == "text")
                children[i].value = "";

            if(children[i].nodeName == "SELECT" && children[i].name.indexOf("operator") > 1)
                children[i].value = "AND";

            if (children[i].nodeName == "SELECT" && idValue == "incomingOntologyQueryRelationship" + newCounter)
                children[i].value = "";

            if (children[i].nodeName == "SELECT" && (children[i].name == "chargeQuery[" + newCounter + "].startRange" ||
                children[i].name == "chargeQuery[" + newCounter + "].endRange"))
                children[i].value = "1000";

            if (children[i].nodeName == "SELECT" && children[i].name == "datasourceQuery[" + newCounter + "].value")
                children[i].value = " All databases ";

            if (children[i].nodeName == "SELECT" && children[i].name == "textQuery[" + newCounter + "].category")
                children[i].value = "All_fields";
        }
    }
    //alert(msg);

    // Get the parent block!
    parentBlock = block.substr(0, block.length-1) + "ies";
    document.getElementById(parentBlock).appendChild(newNode);

    // Fix the buttons!
    document.getElementById(block+"PlusButton"+counter).style.display = "none";
    document.getElementById(block+"PlusButton"+newCounter).style.display = "inline";
}

// ========================
// ADVANCED SEARCH
// AJAX part
//
// developer: adekker
//========================
function quickDWRSearch(value, block, counter) {

    var menu = block + "DWRMenu" + counter;
    if (value.length > 6 && value.toLowerCase().indexOf("chebi:") != -1) {
        // no auto-complete list for search using chebi ids.
        insertValue(block,counter,value.toUpperCase(),value);
    }
    else if (value.length > 2) {
        value = value+'*';
        QuickSearchDWR.search(value.toLowerCase(), 100, {
            callback:function(resultList) { parseResult(resultList, block, counter); }
        });

    } else {
        document.getElementById(menu).style.display = "none";
    }
}

function quickDWROntologyNameSearch(value, block, counter) {

    if (value == '')
        return;

    QuickSearchDWR.search(value, 1, {
        callback:function(resultList) { parseOntologyNameResult(resultList, block, counter); }
    });
}

function parseOntologyNameResult(results, block, counter) {
    var label = results[0].chebiName;

    var labelField = block + "LabelField" + counter;
    document.getElementById(labelField).value = label;
}

var ajaxAdvSearchResults;
function parseResult(results, block, counter) {
    if (results != null && results.length > 0) {
        ajaxAdvSearchResults = results.sort(compare);
        var page = 1;
        drawPage(block, counter, page);
    }
}

function drawPage(block, counter, page) {

    var results = ajaxAdvSearchResults;
    var maxPerPage = 10;
    var init = (page - 1) * maxPerPage;
    var max = page * maxPerPage;
    if (max > results.length) max = results.length;

    var content = "<ul>";
    for (i=init;i<max;i++) {
        if (results[i].definition != null)
            var title = results[i].definition;
        content += "<li><a " + (title?"title='"+title+"'":"") + " href=\"javascript: insertValue('"+block+"', '"+counter+"', '"+results[i].chebiId+"', '"+results[i].chebiAsciiName+"')\">"+results[i].chebiName+"</a></li>";
    }

    if (results.length > maxPerPage*page)
        content += "<li><a href=\"javascript: drawPage('"+block+"','"+counter+"',"+(++page)+")\">Next Page >></a></li>";
    content += "</ul>";

    var menu = block + "DWRMenu" + counter;
    var menuNode = document.getElementById(menu);
    menuNode.innerHTML = content;
    menuNode.style.display = "inline";
}

function insertValue(block, counter, value, label) {

    var textField = block + "TextField" + counter;
    var menu = block + "DWRMenu" + counter;
    var labelField = block + "LabelField" + counter;

    document.getElementById(textField).value = value;
    document.getElementById(labelField).value = label;
//	document.getElementById(labelField).innerHTML = label;
//	document.getElementById(labelField).title = label;
    document.getElementById(menu).style.display = "none";

    // incomingOntology expected. Add an "if" in case you need it.
    var relationship = block + "Relationship" + counter;
    var relationNode = document.getElementById(relationship);
    if (relationNode.selectedIndex == 0)
        relationNode.selectedIndex = 1;
}

var damnMenuToBeHidden;
var alive;
function dismissDWRMenu(block, counter) {
    var menu = block + "DWRMenu" + counter;
    damnMenuToBeHidden = menu;
    alive = false;
    setTimeout("hideDamnMenu()", 3000);
}

function keepAlive(val) {
    alive = val;
}
function hideDamnMenu() {
    if (damnMenuToBeHidden != null && !alive)
        document.getElementById(damnMenuToBeHidden).style.display = "none";
}

//========================
//ADVANCED SEARCH
// Submit/Search/Reset part
//
//developer: adekker
//========================

function checkForStructures() {
    var structure =  document.getElementById('ketcherFrame');
    if(structure != null ){
        var mol = window.frames['ketcherFrame'].ketcher.getMolfile();
        var structureForm = document.getElementById('advancedSearchFT_structure');
        structureForm.value = mol;
    } else {
        var str = document.getElementById('advancedSearchFT_structure');
        var edt = document.getElementById('Editor');
        str.value = edt.getMolFile();
    }
}

function checkStructureChanges(searchMethod) {

//    if (searchMethod == null)
//        searchMethod = 'substructure';

    if (searchMethod == 'substructure') { //substructure
        document.getElementById("strictlyStereoDiv").style.display = "inline";
        document.getElementById("similarityLevel").style.display = "none";
    } else if (searchMethod == 'similarity') { //similarity
        document.getElementById("strictlyStereoDiv").style.display = "none";
        document.getElementById("similarityLevel").style.display = "inline";
    } else { //exact
        document.getElementById("strictlyStereoDiv").style.display = "none";
        document.getElementById("similarityLevel").style.display = "none";
    }

}

function checkStructureChanges2(searchMethod) {

    if (searchMethod == null)
        searchMethod = 'substructure';

    if (searchMethod == 'substructure') { //substructure
        document.getElementById("strictlyStereoDiv").style.visibility = "visible";
        document.getElementById("similarityLevel").style.visibility = "hidden";
    } else if (searchMethod == 'similarity') { //similarity
        document.getElementById("strictlyStereoDiv").style.visibility = "hidden";
        document.getElementById("similarityLevel").style.visibility = "visible";
    } else { //exact
        document.getElementById("strictlyStereoDiv").style.visibility = "hidden";
        document.getElementById("similarityLevel").style.visibility = "hidden";
    }

}

function submitSearch(form) {
    checkForStructures();
    document.getElementById("loadingSearch").style.display="block";
    form.submit();

}

function resetSearch(form) {

    if (document.getElementById('ketcherFrame') != null) $( "#ketcherFrame" ).contents().find( "#new" ).click()
    if (document.getElementById('sketch') != null) document.getElementById('sketch').contentWindow.clearStructure();
    document.getElementById("2stars").checked = true;
    resetStructure();
    resetBlock("textQueries");
    resetBlock("incomingOntologyQueries");
    resetBlock("formulaQueries");
    resetBlock("molecularWeightQueries");
    resetBlock("monoisotopicMassQueries");
    resetBlock("chargeQueries");
    resetBlock("datasourceQueries");
    resetResults();
    return false;
}

function resetBlock(parentBlock) {

    var parentNode = document.getElementById(parentBlock);
    var divNodes = parentNode.getElementsByTagName("div");

    // Get rows
    while (divNodes.length > 1) {
        document.getElementById(parentBlock).removeChild(divNodes[0]);
    }

    // Now there is only one!
    var id = divNodes[0].getAttribute("id");
    var block = parentBlock.substr(0, parentBlock.length - 3) + "y";
    var counter = id.substring(block.length, id.length);

    removeThisRow(block, parseInt(counter));
}

//========================
// Ketcher structure editor
//
//========================

function loadMol() {
    var ketcher =  window.frames['ketcherFrame'].ketcher;
    var mol = document.getElementById('advancedSearchFT_structure').value;
    mol = validatemol(mol);
    ketcher.setMolecule( mol);
}

function validatemol( mol ){
    mol = mol.trim();
    var lines = mol.split('\n');
    for(var i = 0;i < lines.length;i++){
        if(((lines[i].indexOf("V2000") > -1) || (lines[i].indexOf("V3000") > -1 )) && i==3){
            return mol;
        } else if (((lines[i].indexOf("V2000") > -1) || (lines[i].indexOf("V3000")  > -1)) && i==2) {
            return '\n'+mol;
        }else if (((lines[i].indexOf("V2000") > -1) || (lines[i].indexOf("V3000")  > -1)) && i==1) {
            return '\n\n'+mol;
        }else if (((lines[i].indexOf("V2000") > -1) || (lines[i].indexOf("V3000")  > -1)) && i==0) {
            return '\n\n\n'+mol;
        }
    }
}



function switchToAppletView(){
    document.getElementById('appletOnStructureSearch').submit();
}

function switchToJsEditorView(){
    document.getElementById('jsEditorOnStructureSearch').submit();
}

  function resetResults(){
      // var result = document.getElementById("maxResults").childNodes;
      // assignDefaultValues(result,"maxResults",1000);
      result = document.getElementById("resultsPerPage").childNodes;
      assignDefaultValues(result,"resultsPerPage",15);
  }

  function resetStructure(){
      if(document.getElementById('structureSearchOn') != null){
          checkStructureChanges('exact');
          document.getElementById('exact').checked = true;
      }
  }

  function assignDefaultValues(children,name, value){
      for(i=0;i<children.length;i++) {
          if (children[i].nodeName == "SELECT" && children[i].name == name)
              children[i].value = value;
      }
  }

//sort the list of chebi names alphabetically
// in Ontology name suggesion field
function compare(a,b) {
    if (a.chebiAsciiName < b.chebiAsciiName)
        return -1;
    if (a.chebiAsciiName > b.chebiAsciiName)
        return 1;
    return 0;
}