/////////////////////////////////////////////////////////////
// DBK drug add list
/////////////////////////////////////////////////////////////
drugAddList.prototype = new _drugList;
drugAddList.prototype.constructor = drugAddList;

function drugAddList(varName, settings) {
    this.debug = false;
    if (settings) {
        if (settings.debug) this.debug = settings.debug;
        if (this.debug) alert("Set reload event: " + settings.onReload);
        if (settings.onReload) this.onReload = settings.onReload;
        if (settings.popupLeftOffset) this.popupLeftOffset = settings.popupLeftOffset;
    }
    _drugList.call(this, varName, settings);
}

// ---------------------------------------------------------------------------------------------------------------------

// clicked on drug in popup, add it to the addedDrugs list
drugAddList.prototype.addDrugToList = function (id, genericId, name, addButton) {
    _drugList.prototype.addDrugToList.call(this, id, genericId, name, addButton);
    updateDrugCnt();
};

// ---------------------------------------------------------------------------------------------------------------------

// Remove a drug from the addedDrugs field
drugAddList.prototype.removeItem = function (id) {
    _drugList.prototype.removeItem.call(this, id);
    updateDrugCnt();
};

// ---------------------------------------------------------------------------------------------------------------------

drugAddList.prototype.reloadDrugs = function () {
    _drugList.prototype.reloadDrugs.call(this);
    updateDrugCnt();
};

/////////////////////////////////////////////////////////////
// DBK symptom list
/////////////////////////////////////////////////////////////
sxAddList.prototype = new _sxList;
sxAddList.prototype.constructor = sxAddList;

// ---------------------------------------------------------------------------------------------------------------------

function sxAddList(varName, settings) {
    _sxList.call(this, varName, settings);
}

// ---------------------------------------------------------------------------------------------------------------------

sxAddList.prototype.handleKeyUp = function(event, val) {
    _sxList.prototype.handleKeyUp.call(this, event, val);
    if (this.relatedSymptomsList != null) {
        this.relatedSymptomsList.hideList();
    }
};

// ---------------------------------------------------------------------------------------------------------------------

sxAddList.prototype.onFocus = function() {
    _sxList.prototype.onFocus.call(this);
    hide('symptomsEx');
    hide('newFeature');
};

// ---------------------------------------------------------------------------------------------------------------------

// Remove a symptom from the selectedSymptoms field
sxAddList.prototype.removeSymptom = function (id) {
    _sxList.prototype.removeSymptom.call(this, id);
    updateSymptomCnt();
    var sideEffectId = id;
    sideEffectId = sideEffectId.replace("[", "");
    sideEffectId = sideEffectId.replace("]", "");
    this.saveToCookie();
    if (this.onRemove) this.onRemove(sideEffectId);
};

// ---------------------------------------------------------------------------------------------------------------------

sxAddList.prototype.addSelectedSymptom = function () {
    _sxList.prototype.addSelectedSymptom.call(this);
    updateSymptomCnt();
    hide('div_sxSearchResults');
};

// ---------------------------------------------------------------------------------------------------------------------

sxAddList.prototype.addSx = function(searchTerm, type, id, name, addButton, inputObj) {
    _sxList.prototype.addSx.call(this, searchTerm, type, id, name, addButton, inputObj);
    updateSymptomCnt();
};

// ---------------------------------------------------------------------------------------------------------------------

sxAddList.prototype.reloadSx = function() {
    _sxList.prototype.reloadSx.call(this);
    updateSymptomCnt();
    if (this.onReload) this.onReload();
};

// ---------------------------------------------------------------------------------------------------------------------

sxAddList.prototype.createRelatedPopup = function(sxName) {
    _sxList.prototype.createRelatedPopup.call(sxName);
    this.relatedSymptomsPopup = new sxRelatedList(sxName, "");
};

/////////////////////////////////////////////////////////////
// DBK search symptom list
/////////////////////////////////////////////////////////////
sxSearchList.prototype = new _sxList;
sxSearchList.prototype.constructor = sxSearchList;

function sxSearchList(varName) {
    _sxList.call(this, varName);
}

// ---------------------------------------------------------------------------------------------------------------------

sxSearchList.prototype.getList = function(val) {
    this.postUrl("pages/popups/SxSearch.jsp", "name=" + val + "&varName=" + this.varName);
};

/////////////////////////////////////////////////////////////
// Condition list
/////////////////////////////////////////////////////////////
_conditionList.prototype = new _popupList;
_conditionList.prototype.constructor = _conditionList;

// need for support delete from list
var conditionsRegister = new Object();

function _conditionList(varName, settings) {
    this.settings = settings;
    if (!this.settings) this.settings = new Object();
    if (this.settings.persistanceOnlyRead == undefined) {
        this.settings.persistanceOnlyRead = true;
    }
    _popupList.call(this, varName);
    conditionsRegister[varName] = this;
    this.debug = false;
    // in up this property select in popup condition use event onAdd
    this.useAdd = false;
    this.inputId = (this.settings.custom ? varName : "") + "searchCondition";
    this.picklistDiv = (this.settings.custom ? varName : "") + "popupListBox";
    if (this.debug) alert(this.picklistDiv);
    this.itemsId = (this.settings.custom ? varName : "") + "conditionItems";
    this.itemIdPrefix = (this.settings.custom ? varName : "") + "conditionItem";
    this.trashGif = "./images/glythe/trash.gif";
    this.containerDiv = (this.settings.custom ? varName : "") + "condition_popup_container";
    this.rowDivName = "condition_row";
    this.restoreFromCookie();
}

// ---------------------------------------------------------------------------------------------------------------------

_conditionList.prototype.saveToCookie = function () {
    if (!this.settings.persistanceCookieName) return;
    if (this.settings.persistanceOnlyRead) return;
    if (this.debug) alert("Start save to cookie!");
    var cookieValue = "";
    var idAndNames = this.getConditionIdAndNames();
    for (var i = 0; i < idAndNames.length; i++) {
        cookieValue += idAndNames[i].conditionId + ":" + idAndNames[i].conditionName + ";";
    }
    setPopupItems(this.settings.persistanceCookieName, cookieValue);
    if (this.debug) alert("Setted cookie value: " + cookieValue);
};

// ---------------------------------------------------------------------------------------------------------------------

_conditionList.prototype.restoreFromCookie = function () {
    if (!this.settings.persistanceCookieName) return;
    if (this.debug) alert("Start restore to cookie!");
    var cookieValue = getPopupItems(this.settings.persistanceCookieName);
    if (this.debug) alert("Restore cookie value: " + cookieValue);
    if (cookieValue && cookieValue.length > 0) {
        var idAndNames = cookieValue.split(";");
        for (var i = 0; i < idAndNames.length; i++) {
            var idAndName = idAndNames[i].split(":");
            if (idAndName[0] > 0) {
                this.addCondition(idAndName[0], idAndName[1]);
            }
        }
    }
};

// ---------------------------------------------------------------------------------------------------------------------

_conditionList.prototype.popupType = function () {
    return 'condition';
};

// ---------------------------------------------------------------------------------------------------------------------

_conditionList.prototype.hidePopup = function () {
    hide(this.containerDiv);
};

// ---------------------------------------------------------------------------------------------------------------------

_conditionList.prototype.getConditionIds = function () {
    var conditionItems = document.getElementById(this.itemsId);
    var conditionIds = new Array();
    for (var i = 0; i < conditionItems.childNodes.length; i++) {
        var conditionItem = conditionItems.childNodes[i];
        if (conditionItem.conditionId > 0) {
            conditionIds.push(conditionItem.conditionId);
        }
    }
    return conditionIds;
};

// ---------------------------------------------------------------------------------------------------------------------

_conditionList.prototype.getConditionIdAndNames = function () {
    var conditionItems = document.getElementById(this.itemsId);
    var conditionIdAndNames = new Array();
    for (var i = 0; i < conditionItems.childNodes.length; i++) {
        var conditionItem = conditionItems.childNodes[i];
        if (conditionItem.conditionId > 0) {
            var conditionIdAndName = new Object();
            conditionIdAndName.conditionId = conditionItem.conditionId;
            conditionIdAndName.conditionName = conditionItem.conditionName;
            if (this.debug) alert(conditionItem.conditionId + " " + conditionItem.conditionName);
            conditionIdAndNames.push(conditionIdAndName);
        }
    }
    return conditionIdAndNames;
};

// ---------------------------------------------------------------------------------------------------------------------

function removeConditionInternal(varName, conditionId) {
    conditionsRegister[varName].removeCondition(conditionId);
}

// ---------------------------------------------------------------------------------------------------------------------

_conditionList.prototype.addCondition = function (conditionId, conditionName) {
    if (!conditionId || conditionId < 1) return;
    var conditionIds = this.getConditionIds();
    for (var i = 0; i < conditionIds.length; i++) {
        if (conditionId == conditionIds[i]) return;
    }
    var conditionItems = document.getElementById(this.itemsId);
    var conditionItem = document.createElement("div");
    conditionItem.conditionId = conditionId;
    conditionItem.id = this.itemIdPrefix + conditionId;
    conditionItem.conditionName = conditionName;
    conditionItem.innerHTML = "<span  onmouseover=\"Tip('Remove " + conditionName +
                              "', BALLOON, true)\" onmouseout=\"UnTip()\"><img class='cursorhand' src='"
            + this.trashGif + "' " + "onclick='UnTip(); removeConditionInternal(\"" + this.varName + "\", " + conditionId + ")'/></span>" + conditionName;
    conditionItems.appendChild(conditionItem);
    this.saveToCookie();
    if (this.onAdd) this.onAdd(conditionId, conditionName);
};

// ---------------------------------------------------------------------------------------------------------------------

_conditionList.prototype.removeCondition = function (conditionId) {
    if (!conditionId || conditionId < 1) return;
    var conditionItem = document.getElementById(this.itemIdPrefix + conditionId);
    if (!conditionItem) return;
    //    alert("delete " + conditionId);
    conditionItem.parentNode.removeChild(conditionItem);
    this.saveToCookie();
    if (this.onRemove) this.onRemove(conditionId);
};

// ---------------------------------------------------------------------------------------------------------------------

_conditionList.prototype.showPopup = function (text) {
    if (this.debug) alert("Start show condition popup " + text);
    document.getElementById(this.picklistDiv).innerHTML = text;

    if (this.useAdd) {
        for (var i = 0; ; i++) {
            var conditionItem = document.getElementById(this.rowDivName + i);
            if (!conditionItem) break;
            if (this.debug) alert("Start find condition in popup!");
            conditionItem.conditionId = document.getElementById("conditionItemId" + i).value;
            conditionItem.conditionName = document.getElementById("conditionItemName" + i).value;
            if (this.debug) alert("Аdd condition " + conditionItem.conditionId + " in popup!");
            var conditions = this;
            conditionItem.onclick = function () {
                conditions.addCondition(this.conditionId, this.conditionName);
            };
        }
    }

    var searchInput = document.getElementById(this.inputId);
    var drugListDiv = document.getElementById(this.containerDiv);
    drugListDiv.style.width = 430 + "px";
    var obj1BottomX = _getLeft(searchInput) + this.popupLeftOffset; //+searchInput.offsetWidth;
    obj1BottomX = calculateWindow(obj1BottomX, searchInput);
    var obj1BottomY = _getTop(searchInput) + searchInput.offsetHeight + 6;
    drugListDiv.style.left = obj1BottomX + "px";
    drugListDiv.style.top = obj1BottomY + "px";

    if (this.debug) alert("Start show " + this.picklistDiv);
    show(this.picklistDiv);
    if (this.debug) alert("Show " + this.picklistDiv);
    if (this.debug) alert("Start show " + this.containerDiv);
    show(this.containerDiv);
    if (this.debug) alert("Show " + this.containerDiv);
    this.highliterow(0);
};

// ---------------------------------------------------------------------------------------------------------------------

_conditionList.prototype.getList = function (val) {
    if (this.debug) alert("Start get condition list!");
    var parameters = "name=" + val + "&varName=" + this.varName;
    this.postUrl("pages/popups/ConditionPick.jsp", parameters);
};

// ---------------------------------------------------------------------------------------------------------------------

// evaluate button clicked
function evaluateDisclaimer() {
    document.forms["drugtoolForm"].cache.value = "";
    document.forms["drugtoolForm"].target = "_top";
    document.forms["drugtoolForm"].command.value = "disclaimer";
    document.forms["drugtoolForm"].drugName.value = "";

    loadDrugs("dbkDrugs", function (id, genericId, name) {
        document.forms["drugtoolForm"].drugName.value += "," + id + "=" + genericId + ":" + name;
    });

    document.forms["drugtoolForm"].addedSymptoms.value = "";
    loadSideEffects("dbkSymptoms", function (id, name) {
        document.forms["drugtoolForm"].addedSymptoms.value += ",,[" + id + "]=" + name + ":" + name;
    });

    document.forms["drugtoolForm"].submit();
}

// ---------------------------------------------------------------------------------------------------------------------

// update the drug counter if its on the page
function updateDrugCnt() {
    var numDrugs = document.getElementById("drugCounter");
    if (numDrugs) {
        numDrugs.innerHTML = getDrugCnt();
        updateEval();
    }
}

// ---------------------------------------------------------------------------------------------------------------------

// update the symptom counter if its on the page
function updateSymptomCnt() {
    var numSymptoms = document.getElementById("symptomCounter");
    if (numSymptoms) {
        var cnt = getSymptomCnt();
        numSymptoms.innerHTML = cnt;
        updateEval(cnt);
    }
}

// ---------------------------------------------------------------------------------------------------------------------

// get the current added drug list count
function getDrugCnt() {
    var tbl = document.getElementById("selectedDrugs");
    return tbl.rows.length;
}

// ---------------------------------------------------------------------------------------------------------------------

// get the current added symptom list count
function getSymptomCnt() {
    var tbl = document.getElementById("selectedSymptoms");
    if (!tbl) return 0;
    return tbl.rows.length;
}

// ---------------------------------------------------------------------------------------------------------------------

// set eval button available (or not)
function updateEval() {
    if (getDrugCnt() == 0) {
        hide('greenEval');
        hide('greenEvalMyDS1');
        hide('greenEvalMyDS2');
        show('greyEval');
        show('greyEvalMyDS1');
        show('greyEvalMyDS2');
    } else {
        show('greenEval');
        show('greenEvalMyDS1');
        show('greenEvalMyDS2');
        hide('greyEval');
        hide('greyEvalMyDS1');
        hide('greyEvalMyDS2');
    }
}

// ---------------------------------------------------------------------------------------------------------------------

// show initial divs' on Drugs and Symptoms page
function setupDrugSxTab() {
    if (getSymptomCnt() > 0) {
        hide('symptomsEx');
        hide('newFeature');
    } else {
        show('symptomsEx');
    }
}

// ---------------------------------------------------------------------------------------------------------------------

// Replace html when user clicks on an add link
function replacePlusIcon(obj, html) {
    obj.innerHTML = html;
    obj.onmouseover = '';
}

// ---------------------------------------------------------------------------------------------------------------------

function addMySymptom(searchTerm, type, id, name, addButton, inputObj) {
    var sxAdd = new sxAddList();
    sxAdd.addSx(searchTerm, type, id, name, addButton, inputObj);

    replacePlusIcon(document.getElementById("detailAddButton"),
            "added to My Symptoms");
}

// ---------------------------------------------------------------------------------------------------------------------

function addMyDrug(drugNameId, drugId, brand, addButton) {
    var drugAdd = new drugAddList();
    drugAdd.addDrugToList(drugNameId, drugId, brand, addButton);

    replacePlusIcon(document.getElementById("detailAddButton"), "added to My Drugs");
}

// ---------------------------------------------------------------------------------------------------------------------

// these are here, because EMDWebService.java delivers pre-made HTML
// note the hardcoded sxAdd!!! 
function addSx(searchTerm, type, id, name, addButton) {
    sxAdd.addSx(searchTerm, type, id, name, addButton);
}

// ---------------------------------------------------------------------------------------------------------------------

function addSxTip(sxNode) {
    sxAdd.addSxTip(sxNode);
}

// ---------------------------------------------------------------------------------------------------------------------

function addSxEvent(sxNode) {
    sxAdd.addSxEvent(sxNode);
}