// Used to hide when click happens in window
_listOfPopups = new Array;

function _addToListOfPopups(p) {
    _listOfPopups.push(p);
}

function _hideAllPopups() {
    for (var i = 0; i < _listOfPopups.length; i++) {
        _listOfPopups[i].hidePopup();
    }
}

//
// Base popupList class
//
function _popupList(name) {
    this.varName = name;
    this.picklistDiv = "";
    this.selectedTable = "";
    this.containerDiv = "";
    this.inputId = "";
    this.rowDivName = "";
    this.plusGif = "";
    this.trashGif = "";
    this.popupLeftOffset = 0;
    this.hiRowIndex = 0;
    this.requestCount = 0;
    this.kbTimer = null;
    this.kbTimeout = 200;  // 200 ms
    this.lastCaller = null;
    this.processEnter = false;

    this.addItemListener = null;
    this.removeItemListener = null;

    var self = this;
    // callback for postUrl request
    this.onLoad = function(client) {
        // Get the last request made
        if (client.getRequestId() == this.requestCount) {
            var text = trim(client.xmlhttp.responseText);
            if (text.length > 0) this.showPopup(text);
            self.hiRowIndex = 0;
            self.lastCaller = null;
            //            alert(self.processEnter);
            if (self.processEnter) {
                self.selectCurrentRow(0);
                self.processEnter = false;
            }
        }
    };

    this.onError = function(status, statusText) {
        self.lastCaller = null;
        self.processEnter = false;
        alert("Error: " + status + ": " + statusText + "<br>");
    };

    _addToListOfPopups(this);
}

// Invoke the client
_popupList.prototype.postUrl = function(url, params, postbuf) {
    if (this.lastCaller) {
        this.lastCaller.cancelRequest();
    }

    this.lastCaller = new AsyncAjax();
    this.lastCaller.init(url, params, postbuf);

    try {
        this.lastCaller.setRequestId(++this.requestCount);
        this.lastCaller.asyncGET(this);
    } catch (e) {
        alert(e);
    }
};

//
// General keyboard and scrolling functions
//
_popupList.prototype.getKey = function(e) {
    var keynum = null;
    if (e) {
        if (e.keyCode != undefined) // IE
        {
            keynum = e.keyCode;
        } else if (e.which) // Netscape/Firefox/Opera
        {
            keynum = e.which;
        }
    }
    return keynum;
};

_popupList.prototype.handleUpDownArrows = function(event) {
    var keynum;
    if ((keynum = this.getKey(event)) != null) {
        if (keynum == 38) {
            this.scrollVisibleList('up');
        } else if (keynum == 40) {
            this.scrollVisibleList('down');
        } else if (keynum == 9) {
            this.hidePopup();
        }
    }
};

_popupList.prototype.handleKeyPress = function(event) {
    if (!window.event)
        this.handleUpDownArrows(event);
};

_popupList.prototype.handleKeyDown = function(event) {
    if (window.event)
        this.handleUpDownArrows(event);
};

_popupList.prototype.onClick = function(event, value)
{
    this.handleKeyUp(event, value);
};

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

_popupList.prototype.onFocus = function() {
};

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

_popupList.prototype.hidePopup = function() {
    alert('override hidePopup');
};

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

_popupList.prototype.showPopup = function(text) {
    alert('override showPopup ' + text);
};

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

_popupList.prototype.getList = function(val) {
    alert('override getList' + val);
};

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

_popupList.prototype.handleKeyUp = function(event, val) {
    var keynum;
    var result = true;

    if ((keynum = this.getKey(event)) != null)
    {
        if (keynum == 38 || keynum == 40)
        {
            // drop it
        }
        else if (keynum == 13) {
            if (this.lastCaller || this.kbTimer != null) this.processEnter = true;
            re = this.selectCurrentRow(this.hiRowIndex);
            if (re) result = false;
        } else if (keynum == 27 || (keynum == 9) || (keynum == 9 && event.shiftKey)) {
            this.hidePopup();
            result = false;
        } else {
            this.hidePopup();
            this.hiRowIndex = -1;
            if (val.length >= 3) {
                // cancel timer if there is one, then short timeout before getList
                if (this.kbTimer != null) {
                    clearTimeout(this.kbTimer);
                }
                var self = this;
                this.kbTimer = setTimeout(function() {

                    self.getList(val);
                    self.kbTimer = null;
                }, this.kbTimeout);
            }
        }

    }
    return result;
};

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

_popupList.prototype.popupType = function() {
    alert('override popupType');
};

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

_popupList.prototype.scrollVisibleList = function(arrowdirection) {
    if (this.hiRowIndex > -1)
        this.unhighliterow(this.hiRowIndex);

    if (arrowdirection == 'down') {
        this.highliterow(this.hiRowIndex + 1);
    } else if (arrowdirection == 'up') {
        if (this.hiRowIndex > 0) {
            this.highliterow(this.hiRowIndex - 1);
        } else
            this.hiRowIndex = -1;
    }

    /* Make sure item is visible */
    var type = this.popupType();
    if (document.getElementById(type + "Pickrow" + this.hiRowIndex))
        document.getElementById(type + "Scroller").scrollTop =
        document.getElementById(type + "Pickrow" + this.hiRowIndex).offsetTop - 20;
};

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

_popupList.prototype.clearInput = function(inputName) {
    if (document.getElementById(inputName))
        document.getElementById(inputName).value = "";
};

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

// Synthesize enter key event
_popupList.prototype.synthEnterKey = function() {
    if (window.KeyEvent) {
        var evObj = document.createEvent('KeyEvents');
        evObj.initKeyEvent('keyup', true, true, window, false, false, false, false, 13, 0);
    } else {
        var evObj = document.createEventObject();
        evObj.type = "keyup";
        evObj.keyCode = 13;
    }
    return evObj;
};

// ---------------------------------------------------------------------------------------------------------------------
// Update struts form when drugs or symptoms change
//
function DummyHandler() {
}

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

// Highlight functions
_popupList.prototype.highliterow = function(rownum) {
    var name = this.popupType();
    if (document.getElementById(name + '_row_left' + rownum)) {
        document.getElementById(name + '_row_left' + rownum).className = "inputLeftRound_h";
        document.getElementById(name + '_row_right' + rownum).className = "inputRightRound_h";
        document.getElementById(name + '_row_middle' + rownum).className = "highlighted";
        this.hiRowIndex = rownum;
    } else
        this.hiRowIndex = -1;
};

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

_popupList.prototype.unhighliterow = function(rownum) {
    var name = this.popupType();
    if (document.getElementById(name + '_row_left' + rownum)) {
        document.getElementById(name + '_row_left' + rownum).className = "inputLeftRound";
        document.getElementById(name + '_row_right' + rownum).className = "inputRightRound";
        document.getElementById(name + '_row_middle' + rownum).className = "unhighlighted";
        this.hiRowIndex = rownum;
    } else
        this.hiRowIndex = -1;
};

// ---------------------------------------------------------------------------------------------------------------------
// Adds the currently selected symptom in the popup to the symptom list
_popupList.prototype.selectCurrentRow = function (curIndex) {
    if (this.lastCaller) return false;
    if (curIndex == -1) return false;
    var currentTR = document.getElementById(this.rowDivName + curIndex);
    if (currentTR) {
        if (this.useAdd) {
            currentTR.onclick();
            this.hidePopup();
        } else {
            eval(currentTR.attributes['onclick'].value);
        }
        return true;
    }
    return false;
};

/////////////////////////////////////////////////////////////
// Base drug list
/////////////////////////////////////////////////////////////
_drugList.prototype = new _popupList;
_drugList.prototype.constructor = _drugList;

function _drugList(varName, settings) {
    _popupList.call(this, varName);
    this.containerDiv = "div_drug_container";
    this.inputId = "drugField";
    this.picklistDiv = "emdDrugPickComp";
    this.rowDivName = "drug_row";
    this.selectedTable = "selectedDrugs";
    this.infoGif = "./images/glythe/info.gif";
    this.plusGif = "skins/base/images/v2/plusIconOn.gif";
    this.trashGif = "./images/glythe/trash.gif";
    this.popupLeftOffset = 0;
    this.dbkPath = "";
    this.drugPage = "DrugDetail.do";
    this.settings = settings;
    if (!this.settings) this.settings = new Object();
    if (!this.settings.persistanceCookieName) this.settings.persistanceCookieName = "dbkDrugs";
}

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

_drugList.prototype.popupType = function() {
    return 'drug';
};

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

_drugList.prototype.saveToString = function(delimiter) {
    var string = "";
    var items = this.getItems();
    for (var i = 0; i < items.length; i++) {
        string += items[i].id + "=" + items[i].genericId + ":" + items[i].name + delimiter;
    }
    return string;
};

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

_drugList.prototype.restoreFromString = function(string) {
    jQuery("#" + this.selectedTable + " > [tagName='TBODY']").html("");
    if (string && string.length > 0) {
        var idAndNames = string.split(",");
        for (var i = 0; i < idAndNames.length; i++) {
            if (idAndNames[i].length < 1) continue;
            var idsAndName = idAndNames[i].split(":");
            var nameIdAndId = idsAndName[0].split("=");
            this.displayDrugs(nameIdAndId[0], nameIdAndId[1], idsAndName[1]);
        }
    }
};

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

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

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

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

// ---------------------------------------------------------------------------------------------------------------------
// display the drug popup
_drugList.prototype.showPopup = function(responseText) {
    document.getElementById(this.picklistDiv).innerHTML = responseText;

    var searchInput = document.getElementById(this.inputId);
    var drugListDiv = document.getElementById(this.containerDiv);
    var drugListWidth = 630 ;

    drugListDiv.style.width = drugListWidth + "px";

    var obj1BottomX = _getLeft(searchInput) + this.popupLeftOffset; //+searchInput.offsetWidth;
    obj1BottomX = calculateWindowX(obj1BottomX, drugListWidth);
    var obj1BottomY = _getTop(searchInput) + searchInput.offsetHeight + 6;
    drugListDiv.style.left = obj1BottomX + "px";
    drugListDiv.style.top = obj1BottomY + "px";

    show(this.picklistDiv);
    show(this.containerDiv);
    this.highliterow(0);
};

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

_drugList.prototype.reloadDrugs = function() {
    this.restoreFromCookie();
    if (this.debug) alert("Reload drugs list.");
    if (this.debug) alert("Reload fire onReload event: " + this.onReload);
    if (this.onReload) this.onReload();
};

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

_popupList.prototype.getItems = function() {
    var items = new Array();
    $("#" + this.selectedTable + " > [tagName='TBODY'] > [tagName='TR'][itemId]").each(function () {
        items.push({id: this.itemId, name: this.itemName});
    });
    return items;
};

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

_drugList.prototype.getItems = function() {
    var items = new Array();
    $("#" + this.selectedTable + " > [tagName='TBODY'] > [tagName='TR'][itemId]").each(function () {
        items.push({id: this.itemId, genericId: this.itemGenericId, name: this.itemName});
    });
    return items;
};

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

// displays the drug in list after it's added.
_drugList.prototype.displayDrugs = function (id, genericId, name) {
    var myNewRow = document.getElementById(this.selectedTable).insertRow(0);
    myNewRow.itemId = id;
    myNewRow.itemGenericId = genericId;
    myNewRow.itemName = name;

    var myCell3 = myNewRow.insertCell(0);
    myCell3.style.verticalAlign = "top";

    var tip = document.createElement("span");
    $(tip).bind("mouseover", function () {
        Tip("Remove " + name, BALLOON, true);
    });
    $(tip).bind("click mouseout", function () {
        UnTip();
    });
    $(myCell3).append(tip);

    var items = this;
    var image = document.createElement("img");
    image.className = "cursorhand";
    image.src = this.trashGif;
    $(image).bind("click", function () {
        items.removeItem(id);
        UnTip();
    });
    $(tip).append(image);

    var drugDetail = this.dbkPath + "/" + this.drugPage;
    var myCell = myNewRow.insertCell(1);

    myCell.className = "body";
    myCell.innerHTML = "<span onmouseover=\"Tip('Information on " + name +
                       "', BALLOON, true)\" onmouseout=\"UnTip()\"><a href='" + drugDetail +
                       "?dname=" + name + "&sid=" + id + "'>" +
                       "<img src='" + this.infoGif + "'> " + name + "</a></span>";
};


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

// clicked on drug in popup, add it to the _addedDrugs list
_drugList.prototype.addDrugToList = function(id, genericId, name, addButton) {
    if (addButton) {
        addButton.onclick = "";
        addButton.childNodes.item(0).src = this.plusGif;
    }

    this.clearInput(this.inputId);
    hide(this.containerDiv);

    if (this.addItemListener != null) {
        this.addItemListener();
    }

    this.addItem(id, genericId, name);
    return false;
};

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

_popupList.prototype.findItemById = function(id) {
    var items = this.getItems();
    for (var i = 0; i < items.length; i++) {
        if (items[i].id == id) {
            return items[i];
        }
    }
    return null;
};

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

_popupList.prototype.findItemByName = function(name) {
    var items = this.getItems();
    for (var i = 0; i < items.length; i++) {
        if (items[i].name == name) {
            return items[i];
        }
    }
    return null;
};

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

_drugList.prototype.addItem = function(id, genericId, name) {
    if (!this.findItemById(id)) {
        this.displayDrugs(id, genericId, name);
        this.saveToCookie();
        addDrugToAddReview(id, genericId, name);

        // throw event about remove
        if (this.debug) alert("Remove drug with id: " + id + " from list.");
        if (this.onAdd) this.onAdd(id, name);
    }

    return false;
};

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

_drugList.prototype.restoreFromCookie = function () {
    if (!this.settings.persistanceCookieName) return;
    if (this.debug) alert("Start restore to cookie!");
    $("#" + this.selectedTable + " > [tagName='TBODY']").html("");
    var self = this;
    loadDrugs(this.settings.persistanceCookieName, function (id, genericId, name) {
        self.displayDrugs(id, genericId, name);
        addDrugToAddReview(id, genericId, name);
    });
};

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

function loadDrugs(variable, callback) {
    var value = getPopupItems(variable);
    if (value && value.length > 0) {
        var idAndNames = value.split(";");
        for (var i = 0; i < idAndNames.length; i++) {
            if (idAndNames[i].length < 1) continue;
            var idsAndName = idAndNames[i].split(":");
            var nameIdAndId = idsAndName[0].replace(",", "").split("=");
            callback(nameIdAndId[0], nameIdAndId[1], idsAndName[1]);
        }
    }
};

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

_drugList.prototype.saveToCookie = function () {
    if (!this.settings.persistanceCookieName) return;
    if (this.settings.persistanceOnlyRead) return;
    if (this.debug) alert("Start save to cookie!");
    var cookieValue = "";
    var items = this.getItems();
    for (var i = 0; i < items.length; i++) {
        cookieValue += items[i].id + "=" + items[i].genericId + ":" + items[i].name + ";";
    }
    setPopupItems(this.settings.persistanceCookieName, cookieValue);
    if (this.debug) alert("Setted cookie value: " + cookieValue);
};

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

function addDrugToAddReview(id, genericId, name) {
    try {
        addReviewDrugs.addItem(id, genericId, name);
    } catch (e) {
        // error when page not containts add reviewWithOther section
    }
}

_drugList.prototype.addSelectedDrug = function() {
    var val = document.getElementById(this.inputId).value;
    this.handleKeyUp(this.synthEnterKey(), val);
};

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

_drugList.prototype.removeItem = function(id) {
    _popupList.prototype.removeItem.call(this, id);

    if (this.removeItemListener != null) {
        this.removeItemListener();
    }
};

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

_popupList.prototype.removeItem = function(id) {
    var drugFinded = false;
    var items = document.getElementById(this.selectedTable);
    for (var i = 0; i < items.rows.length; i++) {
        if (items.rows[i].itemId == id) {
            drugFinded = true;
            items.deleteRow(i);
        }
    }

    if (drugFinded) {
        this.saveToCookie();
        if (this.debug) alert("Remove drug with id: " + id + " from list.");
        if (this.onRemove) this.onRemove(id);
    }
};

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

// clear drug list
_drugList.prototype.clear = function() {
    _popupList.prototype.clear.call(this);

    if (this.removeItemListener != null) {
        this.removeItemListener();
    }
};

/////////////////////////////////////////////////////////////
// Base symptom list
/////////////////////////////////////////////////////////////
_sxList.prototype = new _popupList;
_sxList.prototype.constructor = _sxList;

function _sxList(varName, settings) {
    _popupList.call(this, varName);
    this.settings = new Object();
    if (settings) this.settings = settings;
    if (!this.settings.persistanceCookieName) this.settings.persistanceCookieName = "dbkSymptoms";
    this.containerDiv = "div_sx_container";
    this.inputId = "searchSymptom";
    this.picklistDiv = "quicksymptom_results";
    this.rowDivName = "sx_row";
    this.selectedTable = "selectedSymptoms";
    this.trashGif = "./images/glythe/trash.gif";
    this.popupLeftOffset = 0;
    this.searchGif = "./skins/base/images/search.gif";
    this.showRelatedSymptoms = true;      // true if displaying related symptoms popup
    this.relatedSymptomsList = null; // related sx popup obj
    this.relatedSymptomsLeftOffset = null; // related sx popup obj left
}

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

_sxList.prototype.restoreFromCookie = function () {
    if (!this.settings.persistanceCookieName) return;
    this.removeItemsWithoutEvent();
    var self = this;
    loadSideEffects(this.settings.persistanceCookieName, function (id, name) {
        self.displaySymptom(id, name);
    });
};

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

_sxList.prototype.saveToString = function() {
    var string = "";
    var items = this.getItems();
    for (var i = 0; i < items.length; i++) {
        string += ",," + items[i].id + "=" + items[i].name + ":" + items[i].name;
    }
    return string;
};

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

_sxList.prototype.restoreFromString = function(string) {
    jQuery("#" + this.selectedTable + " > [tagName='TBODY']").html("");
    if (string && string.length > 0) {
        var idAndNames = string.split(",,");
        for (var i = 0; i < idAndNames.length; i++) {
            var idAndName = idAndNames[i].split("=");
            if (idAndName[0] > 0) {
                this.displaySymptom(idAndName[0], idAndName[1].split(":")[0]);
            }
        }
    }
};

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

function loadSideEffects(variable, callback) {
    var value = getPopupItems(variable);
    if (value && value.length > 0) {
        var idAndNames = value.split(";;");
        for (var i = 0; i < idAndNames.length; i++) {
            var idAndName = idAndNames[i].split(":");
            if (idAndName[0] > 0) {
                callback(idAndName[0], idAndName[1]);
            }
        }
    }
};

// ---------------------------------------------------------------------------------------------------------------------
/**
 * This function used for get some data on server in user session.
 * We use it as very long cookie.
 * @param popupName - name popup
 */
function getPopupItems(popupName) {
    return $.ajax({
        type: "GET",
        dataType: "text",
        url: "/getSessionAttribute.do?name=popupItems" + popupName,
        cache: false,
        async: false
    }).responseText;
}

// ---------------------------------------------------------------------------------------------------------------------
/**
 * Store data in user session.
 * @param popupName - name
 * @param popupItems - value
 */
function setPopupItems(popupName, popupItems) {
    $.ajax({
        type: "POST",
        url: "/setSessionAttribute.do",
        data: "name=popupItems" + popupName
                + "&value=" + popupItems,
        cache: false,
        async: false
    });
}

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

_sxList.prototype.saveToCookie = function () {
    if (!this.settings.persistanceCookieName) return;
    if (this.settings.persistanceOnlyRead) return;
    var cookieValue = "";
    var idAndNames = this.getItems();
    for (var i = 0; i < idAndNames.length; i++) {
        cookieValue += idAndNames[i].id + ":" + idAndNames[i].name + ";;";
    }
    setPopupItems(this.settings.persistanceCookieName, cookieValue);
};

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

_sxList.prototype.popupType = function() {
    return 'sx';
};

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

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

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

// display list of added symptoms on page reload
_sxList.prototype.reloadSx = function() {
    this.restoreFromCookie();
};

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

_sxList.prototype.addSxTip = function(sxNode) {
    var name = sxNode.getAttribute("_name");
    var tip = unescape(name).replace(/([^()]+?) *\(([^)]+?)\)/g, "$1");
    if (getClassName(sxNode) == "clickable") Tip("Add " + tip, BALLOON, true)
    else Tip("Already added", BALLOON, true);
};

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

_sxList.prototype.addSxEvent = function(sxNode) {
    if (getClassName(sxNode) == "clickable") {
        var sxJSName = sxNode.getAttribute("_name"), sxJSId = sxNode.getAttribute("_id");
        this.addSx("", sxJSName, sxJSId, sxJSName, sxNode);
        UnTip();
    }
};

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

// displays symptom in list after it's added
_sxList.prototype.displaySymptom = function(id, name) {
    var myNewRow = document.getElementById(this.selectedTable).insertRow(0);
    myNewRow.itemId = id;
    myNewRow.itemName = name;

    var sxName = unescape(name).replace(/([^()]+?) *\(([^)]+?)\)/g, "$1");

    var curCell = 0;
    var myCell = myNewRow.insertCell(curCell++);
    myCell.style.verticalAlign = "top";
    myCell.style.align = "left";
    myCell.style.width = "20px";
    myCell.innerHTML = "<span onmouseover=\"Tip('Remove " +
                       sxName + "', BALLOON, true)\" onmouseout=\"UnTip()\">" +
                       "<img class='cursorhand'  src='" + this.trashGif + "' " +
                       "onClick='UnTip();" + this.varName + ".removeSymptom(\"" + id + "\")'/></span>";

    if (this.showRelatedSymptoms) {
        myCell = myNewRow.insertCell(curCell++);
        myCell.style.verticalAlign = "top";
        myCell.style.align = "left";
        myCell.style.width = "20px";
        myCell.innerHTML = "<span onmouseover=\"Tip('Search symptoms related to " +
                           sxName + "', BALLOON, true)\" onmouseout=\"UnTip()\">" +
                           "<img class='cursorhand' src='" + this.searchGif + "' " +
                           "onClick='UnTip();" + this.varName + ".showRelatedSx(\"" + sxName + "\")'/>" +
                           "</span>";
    }

    myCell = myNewRow.insertCell(curCell++);
    myCell.style.align = "left";
    myCell.className = "body";
    myCell.innerHTML = name;

    // Good place to create related symptom list
    if (this.showRelatedSymptoms) {
        this.relatedSymptomsList = new _sxRelatedList(sxName, "");
    }
};

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

_sxList.prototype.addSx = function(searchTerm, type, id, name, addButton, inputObj) {
    if (!this.findItemById(id)) {
        this.displaySymptom(id, name);
        if (this.relatedSymptomsList != null) {
            this.relatedSymptomsList.updateRelatedSymptoms("");
        }
        this.saveToCookie();
        if (this.onAdd) this.onAdd(id, name);
    }

    if (inputObj) document.getElementById(inputObj).value = "";
    this.clearInput(this.inputId);
    this.hidePopup();
};

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

_sxList.prototype.addItem = function(id, name) {
    if (!this.findItemById(id)) {
        this.displaySymptom(id, name);
        if (this.relatedSymptomsList != null) {
            this.relatedSymptomsList.updateRelatedSymptoms("");
        }
        this.saveToCookie();
        if (this.onAdd) this.onAdd(id, name);
    }

    this.hidePopup();
};

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

_popupList.prototype.clear = function() {
    this.removeItemsWithoutEvent();
};

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

_popupList.prototype.removeItemsWithoutEvent = function() {
    $("#" + this.selectedTable + " > [tagName='TBODY'] > [tagName='TR'][itemId]").remove();
};

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

_sxList.prototype.showRelatedSx = function(name) {
    if (this.showRelatedSymptoms) {
        if (this.relatedSymptomsLeftOffset != null) {
            this.relatedSymptomsList.leftOffset = _getLeft(document.getElementById(this.inputId)) +
                                                  this.relatedSymptomsLeftOffset;
        }
        this.relatedSymptomsList.showRelatedSx(name);
    }
};

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

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

// ---------------------------------------------------------------------------------------------------------------------
// display the symptom popup
_sxList.prototype.showPopup = function(responseText) {
    document.getElementById(this.picklistDiv).innerHTML = responseText;

    var searchInput = document.getElementById(this.inputId);
    var sxListDiv = document.getElementById(this.containerDiv);
    var sxListWidth = 430 ;

    sxListDiv.style.width = sxListWidth + "px";
    var obj1TopX = _getLeft(searchInput);
    var obj1TopY = _getTop(searchInput);
    var obj1BottomX = _getLeft(searchInput) + this.popupLeftOffset; //+searchInput.offsetWidth;
    obj1BottomX = calculateWindowX(obj1BottomX, sxListWidth);
    var obj1BottomY = _getTop(searchInput) + searchInput.offsetHeight + 6;
    sxListDiv.style.left = obj1BottomX + "px";
    sxListDiv.style.top = obj1BottomY + "px";
    show(this.picklistDiv);
    show(this.containerDiv);
    this.highliterow(0);
};

// ---------------------------------------------------------------------------------------------------------------------
// Remove a symptom from the selectedSymptoms field
_sxList.prototype.removeSymptom = function(id) {
    _popupList.prototype.removeItem.call(this, id);

    if (this.relatedSymptomsList != null) this.relatedSymptomsList.hideList();
};

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

_sxList.prototype.addSelectedSymptom = function() {
    var val = document.getElementById(this.inputId).value;
    this.handleKeyUp(this.synthEnterKey(), val);
};

// ---------------------------------------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////
// Related symptom list - this one is not quite like the others...yet
/////////////////////////////////////////////////////////////
function _sxRelatedList(sxName, addedSx) {
    this.sxName = sxName;
    this.addedSx = addedSx;
    this.relatedSxListDiv = 'div_searchedSymptoms';
    this.relatedSxContainerDiv = 'div_sxSearchResults';
    this.relatedSxTitleDiv = 'div_searchedSxText';
    this.plusGif = "skins/base/images/v2/plusIconOn.gif";
    this.leftOffset = null;

    // callback for postUrl request
    this.onLoad = function(client) {
        this.displayRelatedSymptoms(client.xmlhttp.responseText);
    };
}

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

_sxRelatedList.prototype.showRelatedSx = function(name) {
    if (name)
    {
        this.sxName = name;
    }
    // this really shouldn't be done here - need to have a better mechanism for knowing if
    // something got added
    this.setSxTextTitle(false);

    this.postUrl("pages/popups/SxRelatedList.jsp",
            "name=" + unescape(this.sxName) + "&added=" + this.addedSx);
};

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

// Invoke the client
_sxRelatedList.prototype.postUrl = function(url, params, postbuf) {
    var client = new AsyncAjax();
    client.init(url, params, postbuf);
    // optionally client.setTimeout(5000);

    try {
        client.asyncGET(this);
    } catch (e) {
        alert(e);
    }
};

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

_sxRelatedList.prototype.displayRelatedSymptoms = function(responseText) {
    document.getElementById(this.relatedSxListDiv).innerHTML = responseText;
    this.showList();
    document.getElementById(this.relatedSxListDiv).scrollTop = 0;
};

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

// Set title in secondary symptom search results
//
_sxRelatedList.prototype.setSxTextTitle = function(added) {
    var obj = document.getElementById(this.relatedSxTitleDiv);
    if (obj) {
        if (added) {
            obj.innerHTML = "Your symptom was added. Check to see if any of these related " +
                            "symptoms apply to you. " +
                            "Click the <img src='skins/base/images/v2/plusIcon.gif'> to add a symptom.";
        } else {
            obj.innerHTML = "Check to see if any of these symptoms apply to you. " +
                            "Click the <img src='skins/base/images/v2/plusIcon.gif'> to add a symptom.";
        }
    }
};

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

_sxRelatedList.prototype.hideList = function() {
    hide(this.relatedSxContainerDiv);
};

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

_sxRelatedList.prototype.showList = function() {
    if (this.leftOffset != null) {
        _setLeft(document.getElementById(this.relatedSxContainerDiv), this.leftOffset);
    }
    show(this.relatedSxContainerDiv);
};

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

_sxRelatedList.prototype.updateRelatedSymptoms = function(sxAdded) {
    var sxAddedList = sxAdded.split(/,+\[.+?\]=.*?:/);
    var searchedSymptomsDiv = document.getElementById(this.relatedSxListDiv);
    var symptomNodes = this.symptomFilter(searchedSymptomsDiv), symptomNode;

    for (var i = 0; i < symptomNodes.length; i++) {
        this.updateSymptom(symptomNodes[i], sxAddedList);
    }
};

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

_sxRelatedList.prototype.updateSymptom = function(sxNode, sxAdded) {
    var name = sxNode.getAttribute("_name");
    var allAdded = 0, i;
    for (i in sxAdded) {
        if (sxAdded[i] == name) {
            allAdded = 1;
            break;
        }
    }

    if (allAdded && getClassName(sxNode) == "clickable") {
        setClassName(sxNode, "nonclickable");
        var imgNode = this.plusSignFilter(sxNode);
        if (imgNode) {
            imgNode.setAttribute("src", this.plusGif);
        }
    } else if (!allAdded && getClassName(sxNode) == "nonclickable") {
        setClassName(sxNode, "clickable");
        var sxJSName = sxNode.getAttribute("_name"), sxJSId = sxNode.getAttribute("_id");
        var imgNode = this.plusSignFilter(sxNode);
        if (imgNode) {
            imgNode.setAttribute("src", this.plusGif);
        }
    }
};

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

_sxRelatedList.prototype.plusSignFilter = function(node) {
    var children = node.getElementsByTagName("IMG"), child;
    for (var child = 0; child < children.length; child++) {
        if (getClassName(children[child]) == "plusSign") return children[child];
    }
};

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

_sxRelatedList.prototype.symptomFilter = function (node) {
    var symptomList = new Array();

    if (node.tagName == "SPAN") {
        var className = getClassName(node);
        if (className == "clickable" || className == "nonclickable") {
            symptomList.push(node);
        }
    } else {
        var children = node.getElementsByTagName("SPAN"), child;
        for (var child = 0; child < children.length; child++) {
            var className = getClassName(children[child]);
            if (className == "clickable" || className == "nonclickable") {
                symptomList.push(children[child]);
            }
        }
    }
    return symptomList;
};

/////////////////////////////////////////////////////////////
// DBK drug search list
/////////////////////////////////////////////////////////////
drugSearchList.prototype = new _drugList;
drugSearchList.prototype.constructor = drugSearchList;

function drugSearchList(varName) {
    _drugList.call(this, varName);
}

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

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

/////////////////////////////////////////////
// Utility functions
/////////////////////////////////////////////
function _getLeft(anObject)
{
    return(_getObjLeft(anObject));
}

function _getTop(anObject)
{
    return(_getObjTop(anObject));
}

function _setLeft(anObject, pos)
{
    anObject.style.left = pos + 'px';
}

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

function _setTop(anObject, pos) {
    anObject.style.top = pos + 'px';
}

//
// Positioning functions
//
function _getObjLeft(anObject) {
    if (anObject)
        return(anObject.offsetParent ?
               (_getObjLeft(anObject.offsetParent) + anObject.offsetLeft) :
               anObject.offsetLeft);
    return undefined;
}

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

function _getObjTop(anObject) {
    if (anObject)
        return(anObject.offsetParent ?
               (_getObjTop(anObject.offsetParent) + anObject.offsetTop) : anObject.offsetTop);
    return undefined;
}

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

function SetCookie(cookieName, cookieValue, nDays, domain, path) {
    var cookieString = cookieName + "=" + escape(cookieValue);
    // Session cookie is default
    if (nDays >= 1) {
        var today = new Date();
        var expire = new Date();
        expire.setTime(today.getTime() + 3600000 * 24 * nDays);
        cookieString += ";expires=" + expire.toGMTString();
    }
    if (domain) cookieString += ";domain=" + domain;
    if (path) cookieString += ";path=" + path;
    document.cookie = cookieString;
}

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

function ReadCookie(cookieName) {
    var theCookie = "" + document.cookie;
    var ind = theCookie.indexOf(cookieName);
    if (ind == -1 || cookieName == "") return "";
    var ind1 = theCookie.indexOf(';', ind);
    if (ind1 == -1) ind1 = theCookie.length;
    var val = unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
    if (val == ";") val = "";    // because of IE
    return val;
}

