var defaultEmptyOK = false;

var whitespace = " \t\n\r";

var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 9

var digitsInUSPhoneNumber = 10;

var currentDivQ;
var mousex = 0 ;
var mousey = 0;

var firstClick = false;

var contextPath;

function isEmpty(s)
{
    return ((s == null) || (s.length == 0))
}


function isWhitespaceThere(s)

{
    var i;

    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);

        if (c == ' ') return true;
    }

    return false;
}


function isWhitespace(s)

{
    var i;

    if (isEmpty(s)) return true;

    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    return true;
}

function stripWhitespace(s)

{
    return stripCharsInBag(s, whitespace)
}

function stripCharsInBag(s, bag)

{
    var i;
    var returnString = "";

    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

function isEmail(s)
{

    if (isEmpty(s))
        if (isEmail.arguments.length == 1) return defaultEmptyOK;
        else return (isEmail.arguments[1] == true);

    if (isWhitespace(s)) return false;

    var i = 1;
    var sLength = s.length;

    while ((i < sLength) && (s.charAt(i) != "@"))
    {
        i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    while ((i < sLength) && (s.charAt(i) != "."))
    {
        i++
    }

    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}


function checkEmail(theField, emptyOK)
{
    if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isEmail(theField.value, false)) {

        return false;
    }
    else return true;
}

function isYear(s)
{
    if (isEmpty(s))
        if (isYear.arguments.length == 1) return defaultEmptyOK;
        else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}

function isNonnegativeInteger(s)
{
    var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];
    return (isSignedInteger(s, secondArg)
            && ( (isEmpty(s) && secondArg) || (parseInt(s) >= 0) ) );
}

function isSignedInteger(s)

{
    if (isEmpty(s))
        if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
        else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        // skip leading + or -
        if ((s.charAt(0) == "-") || (s.charAt(0) == "+"))
            startPos = 1;
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}

function isLetter(c)
{
    return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}


function isDigit(c)
{
    return ((c >= "0") && (c <= "9"))
}


function isLetterOrDigit(c)
{
    return (isLetter(c) || isDigit(c))
}


function isInteger(s)

{
    var i;

    if (isEmpty(s))
        if (isInteger.arguments.length == 1) return defaultEmptyOK;
        else return (isInteger.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }

    return true;
}

function isZIPCode(s)
{
    if (isEmpty(s))
        if (isZIPCode.arguments.length == 1) return defaultEmptyOK;
        else return (isZIPCode.arguments[1] == true);
    return (isInteger(s) &&
            ((s.length == digitsInZIPCode1) ||
             (s.length == digitsInZIPCode2)))
}

function isUSPhoneNumber(s)
{
    if (isEmpty(s))
        if (isUSPhoneNumber.arguments.length == 1) return defaultEmptyOK;
        else return (isUSPhoneNumber.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInUSPhoneNumber)
}

function isIntegerInRange(s, a, b)
{
    if (isEmpty(s))
        if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
        else return (isIntegerInRange.arguments[1] == true);

    if (!isInteger(s, false)) return false;

    var num = parseInt(s);
    return ((num >= a) && (num <= b));
}


function isMonth(s)
{
    if (isEmpty(s))
        if (isMonth.arguments.length == 1) return defaultEmptyOK;
        else return (isMonth.arguments[1] == true);
    return isIntegerInRange(s, 1, 12);
}


function isDay(s)
{
    if (isEmpty(s))
        if (isDay.arguments.length == 1) return defaultEmptyOK;
        else return (isDay.arguments[1] == true);
    return isIntegerInRange(s, 1, 31);
}


function doAnchorClick(domID)
{
    var elem = document.getElementById(domID) ;
    if (elem) {
        if (elem.click) {
            elem.click();          // for IE
        }
        else {
            location = elem.href;  // for FFox
        }
    }

    return;
}


function showDialog(divToShow) {
    var showthis = document.getElementById(divToShow);
    if (showthis.style.visibility == 'visible') {
        //
        showthis.style.visibility = "hidden";
        showthis.style.display = "none";
    } else {
        showthis.style.borderStyle = "double";
        showthis.style.zIndex = 100;
        showthis.style.display = "block";

        var top = document.body.clientHeight / 2 + showthis.offsetHeight / 2 ;
        var left = document.body.clientWidth / 2 + showthis.offsetWidth / 2;

        showthis.style.pixelLeft = 100;
        showthis.style.pixelTop = 100;

        showthis.style.visibility = "visible";
        showthis.style.display = "block";
    }

}

function isAlphabetic(s)

{
    var i;

    if (isEmpty(s))
        if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
        else return (isAlphabetic.arguments[1] == true);

    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);

        if (!isLetter(c))
            return false;
    }

    return true;
}

function isAlphanumeric(s)

{
    var i;

    if (isEmpty(s))
        if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
        else return (isAlphanumeric.arguments[1] == true);

    var isNumeric = false;
    var isAlpha = false;
    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);

        if (isLetter(c))
            isNumeric = true;
        else if (isDigit(c))
            isAlpha = true;
    }

    if (isNumeric && isAlpha)
        return true;
    else
        return false;
}

function getAge(mm, dd, yyyy) {

    var now = new Date();
    var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

    var yearNow = now.getFullYear();
    var monthNow = now.getMonth();
    var dateNow = now.getDate();

    var dob = new Date(yyyy, mm, dd);
    var yearDob = dob.getFullYear();
    var monthDob = dob.getMonth();
    var dateDob = dob.getDate();

    yearAge = yearNow - yearDob;

    if (monthNow < monthDob) {
        yearAge--;
        var monthAge = 12 + monthNow - monthDob;
    }

    if (dateNow < dateDob)
    {
        monthAge--;
        var dateAge = 31 + dateNow - dateDob;

        if (monthAge < 0) {
            monthAge = 11;
            yearAge--;
        }
    }

    return yearAge;

}

function showSaveSummaryDialog(message)
{
    window.open('SaveSummaryAction.do?message=' + message, 'SaveSummary', 'top=100,left=100,width=700,height=600,toolbar=no,titlebar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,copyhistory=no,resizable=no');
}

function openPopup(page, name)
{
    window.open(page, name, 'top=400,left=400,width=600,height=500,toolbar=no,titlebar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,copyhistory=no,resizable=yes');
}

function checkEnterKey(theForm, e) {
    var keynum;
    //var keychar
    //var numcheck

    if (window.event) // IE
    {
        keynum = e.keyCode;
    } else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    //keychar = String.fromCharCode(keynum);
    //numcheck = /\d/;
    //return !numcheck.test(keychar);
    //    alert(keynum);

    if (keynum == 13)
        theForm.submit();
    else
        return;

}

function register() {
    top.location = "Register.do";

}

function toggleCheckBox(fullVer, theCheckbox) {
    var z = 0;
    if (fullVer.checked) {
        for (i = 0; i < theCheckbox.length; i++)
        {
            theCheckbox[i].checked = false;

        }
    }
}

function savesummary(pCommand) {
    if (pCommand == undefined)
        pCommand = "update";
    document.forms['saveSummaryForm'].elements['command'].value = pCommand;
    document.forms['saveSummaryForm'].submit();

}

function savesummaryas(pCommand) {
    if (pCommand == undefined)
        pCommand = "updateas";
    document.forms['saveSummaryForm'].elements['command'].value = pCommand;
    document.forms['saveSummaryForm'].elements['summaryName'].value = document.getElementById('summaryName2').value;
    document.forms['saveSummaryForm'].submit();

}


function editText(divQ, primaryKey, type, oEvent) {
    currentDivQ = divQ;
    getMouseXY(oEvent);
    document.forms['textEditForm'].elements['primaryKey'].value = primaryKey;
    document.forms['textEditForm'].elements['type'].value = type;
    document.forms['textEditForm'].submit();
}


function fetchAnswer(divQ, qId, oEvent) {
    currentDivQ = divQ;

    getMouseXY(oEvent);
    var formBody = document.forms['answerForm2'];
    formBody.elements['answerDataName'].value = qId;
    formBody.submit();
}

function fecthTellMeMore(divQ, tmId, contentKindP) {
    var divo = document.getElementById("tellMeMorePerTM");
    if (divo.style.visibility == "visible") {
        divo.innerHTML = "";
        divo.style.visibility = "hidden";
    }
    currentDivQ = divQ;

    if (contentKindP != undefined) {
        document.tellMeMoreForm.contentKind.value = contentKindP;
    } else {
        document.tellMeMoreForm.contentKind.value = "TreatmentMessage";
    }
    document.tellMeMoreForm.action = "TellMeMoreAction.do";
    document.tellMeMoreForm.contentId.value = tmId;
    document.tellMeMoreForm.target = "loadTellMeMore";
    document.tellMeMoreForm.submit();

}


function showTellMeMore(divQ, tmId, contentKindP, urlP, oEvent) {

    currentDivQ = divQ;
    if (oEvent)
        getMouseXY(oEvent);
    var divo = document.getElementById("div_container");
    if (divo.style.visibility == "visible") {
        document.getElementById("div_container_holder").innerHTML = "";
        divo.style.visibility = "hidden";
    }
    createXMLHttpRequestG();
    //alert(xmlHttp);
    var url = "TellMeMoreAction.do";
    if (urlP != undefined)
        url = urlP;
    xmlHttpGlobal.open("POST", url, true);
    xmlHttpGlobal.onreadystatechange = callbackTMM;
    xmlHttpGlobal.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
    if (contentKindP != undefined) {
        params = "contentId=" + tmId + "&requestMethod=2&contentKind=" + contentKindP;
    } else {
        params = "contentId=" + tmId + "&requestMethod=2&contentKind=TreatmentMessage";
    }
    xmlHttpGlobal.send(params);
}


function callbackTMM() {
    if (xmlHttpGlobal.readyState == 4) {
        if (xmlHttpGlobal.status == 200) {

            var responseText = xmlHttpGlobal.responseText;
            setTellMeMoreNoFrame(responseText);

        }
    }
}

function setTellMeMoreNoFrame(htmlText) {


    var divo = document.getElementById("div_container");
    mousex = calculateWindow(mousex, divo);
    divo.style.left = mousex + "px";

    divo.style.top = (mousey + 5) + "px";

    document.getElementById("div_container_holder").innerHTML = htmlText;
    document.getElementById("div_container_holder").style.display = "block";
    document.getElementById("div_container_holder").style.visibility = "visible";
    divo.style.display = "block";
    divo.style.visibility = "visible";
    firstClick = true;
}

function hideTellMeMore() {
    var divo1 = document.getElementById("div_container");

    var isVisible1 = false;
    var isVisible2 = false;
    var divo2 = document.getElementById("div_container2");
    var divHolder1 = document.getElementById("div_container_holder");

    if (divo1 && divo1.style.visibility == "visible")
        isVisible1 = true;

    if (divo2 && divo2.style.visibility == "visible")
        isVisible2 = true;

    if (firstClick)
    {
        firstClick = false;
        return;
    }


    if (firstClick == false && isVisible1 && isVisible2 == false)
    {
        if (document.activeElement != divHolder1 &&
            document.activeElement != divo1)
        {
            hideByID("div_container_holder");
            hideByID("div_container");
        }
    }
    if (firstClick == false && isVisible2)
    {
        if (document.activeElement != divo2) {
            hideByID("div_container2_holder");
            hideByID("div_container2");
        }

    }


    if (document.getElementById("emdDrugPickComp") != undefined) {
        document.getElementById("emdDrugPickComp").style.visibility = "hidden";
        document.getElementById("emdDrugPickComp").display = "none";
        document.getElementById("emdDrugPickComp").innerHTML = "";
    }
    if (document.getElementById("div_drug_container") != undefined) {
        document.getElementById("div_drug_container").style.visibility = "hidden";
        document.getElementById("div_drug_container").display = "none";
    }
    if (document.getElementById("div_sx_container") != undefined) {
        document.getElementById("div_sx_container").style.visibility = "hidden";
        document.getElementById("div_sx_container").display = "none";
    }

    // hide popups - remove above code?
    _hideAllPopups();

    firstClick = false;
}


function hideByID(divToHide)
{
    if (divToHide)
    {
        var hidethis = document.getElementById(divToHide);
        if (hidethis) {
            hidethis.style.visibility = "hidden";
            hidethis.style.display = "none";
        }
    }
}

function toggleDiv(divContainer, divClicked, divToShow, additionalCaption) {

    var showthis = document.getElementById(divToShow);


    if (showthis.style.visibility == 'visible') {
        //
        showthis.style.visibility = "hidden";
        showthis.style.display = "none";

        if (additionalCaption != undefined) {
            divClicked.innerHTML = additionalCaption;
        }
        else {
            divClicked.innerHTML = "<b>Show</b>";
        }
        //text.style.height = text.scrollHeight - 100;

    }
    else {

        //text.style.height = text.scrollHeight + 100;
        showthis.style.visibility = "visible";
        showthis.style.display = "block";

        if (additionalCaption != undefined) {
            divClicked.innerHTML = "Hide " + additionalCaption;
        }
        else {
            divClicked.innerHTML = "<b>Hide</b>";
        }


    }
    firstClick = true;
}

function showBubble(meaning, divClickedObj)
{
    var obj1TopX = getLeft(divClickedObj) ;
    var obj1TopY = getTop(divClickedObj);
    var obj1BottomX = obj1TopX - (divClickedObj.offsetWidth * 3 - 100);
    var obj1BottomY = obj1TopY + divClickedObj.offsetHeight + 3;

    divContainerObj = document.getElementById("bubble_container");
    divContainerObj.innerHTML = meaning;
    divContainerObj.style.left = obj1BottomX + "px";
    divContainerObj.style.top = obj1BottomY + "px";

    divContainerObj.style.visibility = "visible";
    divContainerObj.style.display = "block";
}


function showDiv2(oEvent, divToShow, divClicked) {

    getMouseXY(oEvent);
    var divo = document.getElementById(divToShow);
    mousex = calculateWindow(mousex, divClicked);
    divo.style.left = mousex + "px";

    divo.style.top = (mousey + 5) + "px";
    divo.style.visibility = "visible";
    divo.style.display = "block";

}

function showDiv(divClicked, divToShow) {

    var showOrHide = divClicked.innerHTML;
    var showthis = document.getElementById(divToShow);
    if (showOrHide == "Hide...") {
        divClicked.innerHTML = "More...";
        showthis.style.visibility = "hidden";
        showthis.style.display = "none";
    } else {
        divClicked.innerHTML = "Hide...";
        showthis.style.visibility = "visible";
        showthis.style.display = "block";
    }

}

function showInfoURL(divClicked, urlToShow, frameToLoad) {

    var frameToLoadObj = document.getElementById(frameToLoad);
    frameToLoadObj.src = urlToShow;

    var divContainerObj = document.getElementById("div_" + frameToLoad);

    if (divContainerObj != undefined && divContainerObj.style.visibility == "visible") {
        divContainerObj.style.visibility = "hidden";

    }
    //calculate where this divClicked
    var parent = divClicked.offsetParent;
    var top = 0;
    var left = 0;
    if (parent) {
        top = parent.offsetTop;
        left = parent.offsetLeft;

    }
    for (var i = 0; i < 10; i++) {
        parent = parent.offsetParent;
        if (parent) {
            top += parent.offsetTop;
            left += parent.offsetLeft;
        } else {
            break;
        }
    }
    divContainerObj.style.pixelLeft = divClicked.offsetLeft + left;
    divContainerObj.style.pixelTop = divClicked.offsetTop + divClicked.clientHeight + top + divClicked.offsetHeight;
    divContainerObj.style.visibility = "visible";
    divContainerObj.style.display = "block";

}

function showInfoInline(divToShow)
{
    var divContainerObj = document.getElementById(divToShow);
    //divContainerObj.style.height = "400px";
    //divContainerObj.style.overflow = "auto";
    divContainerObj.style.visibility = "visible";
    divContainerObj.style.display = "block";
}

function showInfo(divClicked, divToShow, divContainer, oEvent) {


    var divClickedObj = divClicked;
    var showthis = document.getElementById(divToShow);
    var divContainerObj = document.getElementById(divContainer);
    var divContainerHolder = document.getElementById(divContainer + "_holder");

    if (oEvent)
        getMouseXY(oEvent);

    if (divContainerObj != undefined && divContainerObj.style.visibility == "visible") {
        divContainerObj.style.visibility = "hidden";
    }


    if (divContainerObj != undefined) {

        //alert(mousex+ ":"+ mousey + "="+ divContainerHolder+":"+divToShow);
        if (showthis != undefined)
            divContainerHolder.innerHTML = showthis.innerHTML;


        divContainerHolder.style.visibility = "visible";
        divContainerHolder.style.display = "block";
        divContainerObj.style.visibility = "visible";
        divContainerObj.style.display = "block";

        mousex = calculateWindow(mousex, divContainerObj);


        divContainerObj.style.left = mousex + "px";
        divContainerObj.style.top = mousey + "px";
        firstClick = true;

    } else {
        //alert(divContainerHolder);

        if (showthis != undefined)
            divContainerHolder.innerHTML = showthis.innerHTML;
        divContainerHolder.style.visibility = "visible";
        divContainerHolder.style.display = "block";
        mousex = calculateWindow(mousex, divContainerHolder);
        divContainerHolder.style.left = mousex + "px";
        divContainerHolder.style.top = mousey + "px";
        firstClick = true;
    }

}


function calculateWindow(mousex, objContainer)
{
    return calculateWindowX(mousex, objContainer.offsetWidth);
}

function calculateWindowX(mousex, offsetWidth)
{
    var x,y;
    if (self.innerHeight) // all except Explorer
    {
        x = self.innerWidth;
        y = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight)
    // Explorer 6 Strict Mode
    {
        x = document.documentElement.clientWidth;
        y = document.documentElement.clientHeight;
    }
    else if (document.body) // other Explorers
        {
            x = document.body.clientWidth;
            y = document.body.clientHeight;
        }

    if ((mousex + offsetWidth) > x) {
        mousex = x - offsetWidth - 50;
    }

    return mousex;
}


function setTellMeMore(divChild) {
    var divo = document.getElementById("tellMeMorePerTM");
    var parent = currentDivQ.offsetParent;


    var top = 0;
    var left = 0;
    if (parent) {
        top = parent.offsetTop;
        left = parent.offsetLeft;

    }
    for (var i = 0; i < 20; i++) {
        parent = parent.offsetParent;
        if (parent) {
            top += parent.offsetTop;
            left += parent.offsetLeft;
        } else {
            break;
        }
    }
    divo.innerHTML = divChild.innerHTML;
    divo.style.pixelLeft = currentDivQ.offsetLeft + left;


    divo.style.pixelTop = currentDivQ.offsetTop + currentDivQ.clientHeight + top + currentDivQ.offsetHeight;


    divo.style.visibility = "visible";
    divo.style.display = "block";
}


function getMouseXY(e) // works on IE6,FF,Moz,Opera7
{
    if (!e) e = window.event; // works on IE, but not NS (we rely on NS passing us the event)

    if (e)
    {
        if (e.pageX || e.pageY)
        { // this doesn't work on IE6!! (works on FF,Moz,Opera7)
            mousex = e.pageX;
            mousey = e.pageY;
            algor = '[e.pageX]';
            if (e.clientX || e.clientY) algor += ' [e.clientX] '
        }
        else if (e.clientX || e.clientY)
        { // works on IE6,FF,Moz,Opera7
            // Note: I am adding together both the "body" and "documentElement" scroll positions
            //       this lets me cover for the quirks that happen based on the "doctype" of the html page.
            //         (example: IE6 in compatibility mode or strict)
            //       Based on the different ways that IE,FF,Moz,Opera use these ScrollValues for body and documentElement
            //       it looks like they will fill EITHER ONE SCROLL VALUE OR THE OTHER, NOT BOTH
            //         (from info at http://www.quirksmode.org/js/doctypes.html)
            mousex = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
            mousey = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
            algor = '[e.clientX]';
            if (e.pageX || e.pageY) algor += ' [e.pageX] '
        }
    }
}


function setAnswerList(divChild, qId, drugName, sxName) {

    var divo = document.getElementById("div_answer_container");
    //alert(mousex + ":"+ mousey );


    //position under it
    divo.style.visibility = "visible";
    divo.style.display = "block";


    divo.style.width = 550 + "px";
    mousex = calculateWindow(mousex, divo);
    divo.style.left = mousex + "px";
    divo.style.top = (mousey + 5) + "px";
    divo.style.zIndex = 100;
    document.getElementById("div_answer_container_holder").innerHTML =
    "<form action='EditAnswer.do' name='answerForm' method='post' target='_top'>" +
    divChild.innerHTML + "</form>";

    divChild.innerHTML = "";
    firstClick = true;
    if (drugName != null && drugName.length > 0) {
        //reloadDrugs(drugName);
        parent.drugAdd.reloadDrugs();
    }
    if (sxName != null && sxName.length > 0) {
        // reloadSx(sxName);
        parent.sxAdd.reloadSx();
    }

}

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

function setAnswerDrugsList(divChild, drugName, sxName) {
    var formToSubmit = document.forms['answerFormDrug'] ;
    formToSubmit.innerHTML = "";

    var divo = document.getElementById("div_answer_container");

    //position under it
    divo.style.visibility = "visible";
    divo.style.display = "block";

    divo.style.width = 550 + "px";
    mousex = calculateWindow(mousex, divo);
    divo.style.left = mousex + "px";
    divo.style.top = (mousey + 5) + "px";
    divo.style.zIndex = 100;
    document.getElementById("div_answer_container_holder").innerHTML = divChild.innerHTML;

    divChild.innerHTML = "";

    firstClick = true;
    if (drugName != null && drugName.length > 0) {
        parent.drugAdd.restoreFromString(document.getElementById(drugName).value);
    }
    if (sxName != null && sxName.length > 0) {
        parent.sxAdd.restoreFromString(document.getElementById(sxName).value);
    }
}

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

function submitAnswerDrugsList(drugName, sxName) {
    hideByID("div_answer_container");
    if (drugName && document.getElementById(drugName)) {
        document.getElementById(drugName).value = parent.drugAdd.saveToString(",");
    }
    if (sxName && document.getElementById(sxName)) {
        document.getElementById(sxName).value = parent.sxAdd.saveToString(",");
    }
    var formToSubmit = document.forms["answerFormDrug"];
    var divSrc = "div_answer_container_holder";
    var domSrc = document.getElementById(divSrc);
    var formBody = domSrc.innerHTML;
    domSrc.innerHTML = "";
    formToSubmit.innerHTML = formBody;
    formToSubmit.name = "answerForm";
    formToSubmit.submit();
    formToSubmit.name = "answerFormDrug";
    return true;
}


function setEditText(divChild) {

    var divo = document.getElementById("div_answer_container");
    //alert(mousex + ":"+ mousey );


    //position under it
    divo.style.visibility = "visible";
    divo.style.display = "block";


    // divo.style.width = 550 + "px";
    divo.style.width = "90ex";
    //divo.style.hight = "300ex";
    mousex = calculateWindow(mousex, divo);
    divo.style.left = mousex + "px";
    divo.style.top = (mousey + 5) + "px";
    divo.style.zIndex = 100;

    holder = document.getElementById("div_answer_container_holder");

    var str = divChild.innerHTML ;
    divChild.innerHTML = "";

    holder.innerHTML = str;

    firstClick = true;
    return;
}


function setLocation(loc) {
    window.top.location = loc;
}

function submitToForm(formObj, targetName, actionName, openAttr) {

    if (openAttr != undefined) {
        window.open("blank.jsp", targetName, openAttr);
    }

    if (targetName != undefined)
        formObj.target = targetName;

    if (actionName != undefined)
        formObj.action = actionName;
    //alert(formObj);
    formObj.submit();
}

function submitFaqForm(formObj, opName, idValue)
{

    formObj.action = 'FAQEntryAction.do';
    formObj.target = '_top';


    if (opName != undefined) {
        formObj.elements['opName'].value = opName;
    }

    if (idValue != undefined) {
        formObj.elements['idValue'].value = idValue;
    }

    formObj.submit();
}

function deleteFaqEntry(formObj, idValue, shortText)
{
    if (idValue != undefined) {
        var doIt = window.confirm("Your are about delete entry [" + idValue + "]:\n" +
                                  "Q: '" + shortText + "'\n\n\n" +
                                  "Deleting is not revertable action.\n Please select Ok to confirm") ;

        if (doIt) {
            formObj.action = 'FAQEntryAction.do';
            formObj.target = '_top';

            formObj.elements['opName'].value = 'delete';
            formObj.elements['idValue'].value = idValue;

            formObj.submit();
        }
    }

    return false;
}

function deleteQLEntry(formObj, idValue, shortText)
{
    if (idValue != undefined) {
        var doIt = window.confirm("Your are about delete entry [" + idValue + "]:\n" +
                                  "'" + shortText + "'\n\n\n" +
                                  "Deleting is not revertable action.\n Please select Ok to confirm") ;

        if (doIt) {
            formObj.action = 'QLEntryAction.do';
            formObj.target = '_top';

            formObj.elements['opName'].value = 'delete';
            formObj.elements['idValue'].value = idValue;

            formObj.submit();
        }
    }

    return false;
}


function submitToFAQForm(formObj, targetName, actionName, attributes, faqIdP) {

    if (faqIdP != undefined)
        formObj.faqID.value = faqIdP;
    else
        formObj.faqID.value = '0';
    submitToForm(formObj, targetName, actionName, attributes);
}

function submitToSaveForm(formObj, targetName, actionName, attributes, actionValue, summaryIdValue) {

    window.name = "icdmainwindow";
    formObj.command.value = actionValue;
    formObj.summaryId.value = summaryIdValue;

    submitToForm(formObj, targetName, actionName, attributes);

}

function showSavedEval(summaryIdValue, summaryName, curDatasetName, curDatasetId) {
    if (curDatasetName && (summaryName != curDatasetName))
    {
        var yesFunc = function() {
            saveAndShow(curDatasetName, curDatasetId, summaryIdValue);
        };
        var noFunc = function() {
            showSavedReport(summaryIdValue);
        };
        var msg = "Changes to '" + curDatasetName + "' will be ";
        msg += "lost unless you save your answers. ";
        msg += "Clicking NO will lose your answers and display '" + summaryName + "'. ";
        msg += "<br/><br/>Do you want to save '" + curDatasetName + "' before continuing?";
        showYesNoBox(msg, yesFunc, noFunc);
    }
    else
    {
        showSavedReport(summaryIdValue);
    }
}

function showSavedReport(summaryIdValue)
{
    var formObj = document.myTreatmentForm;
    formObj.surveyDataSetId.value = summaryIdValue;
    submitToForm(formObj);
}

function warnDeleteSummary(summaryId, summaryName)
{
    var msg = "Are you sure you want to delete '" + summaryName + "' ?";
    var okFunc = function() {
        deleteSummary(summaryId);
    };
    showOkCancelBox(msg, okFunc);
}

function deleteSummary(summaryId)
{
    createXMLHttpRequest();
    var url = "SaveSummaryAction.do";
    xmlHttpRequest.onreadystatechange = callbackDeleteSummary;
    xmlHttpRequest.open("POST", url, true);
    xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var params = "command=delete&summaryId=" + summaryId;
    xmlHttpRequest.send(params);
}

function callbackDeleteSummary()
{
    if (xmlHttpRequest)
    {
        if (xmlHttpRequest.readyState == 4) {
            if (xmlHttpRequest.status == 200) {
                window.location.reload();
            }
        }
    }
}

// Params to SaveSummaryAction.do dependent on id. If id < 0, updateas to create new eval
//
function getUpdateParams(id)
{
    if (id > 0)
        return ("command=update&summaryId=" + id);
    else
        return ("command=updateas&summaryId=0");
}

function saveAndShow(summaryName, summaryId, showIdValue)
{
    createXMLHttpRequest();
    var url = "SaveSummaryAction.do";
    var callbackFunc = function() {
        callbackSaveAndShow(showIdValue)
    };
    xmlHttpRequest.onreadystatechange = callbackFunc;
    xmlHttpRequest.open("POST", url, true);
    xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var params = getUpdateParams(summaryId) + "&summaryName=" + summaryName;
    xmlHttpRequest.send(params);
}

function callbackSaveAndShow(id)
{
    if (xmlHttpRequest)
    {
        if (xmlHttpRequest.readyState == 4) {
            if (xmlHttpRequest.status == 200) {
                var okFunc = function() {
                    showSavedReport(id);
                };
                showMessageBox("Your changes have been saved.", okFunc);
            }
        }
    }
}

function logoffPrompt(saved, datasetName, surveyId)
{
    if (saved == 'false')
    {
        var yesFunc = function() {
            saveAndLogoff(datasetName, surveyId);
        };
        var noFunc = function() {
            logoff('LogoffAction.do');
        };
        var msg = "There are unsaved changes to '<a href='MyTreatmentAction.do'>" + datasetName;
        msg += "</a>'.  Clicking NO will lose changes and logoff. ";
        msg += "<br/><br/>Do you want to save before logging off?";
        showYesNoBox(msg, yesFunc, noFunc);
    }
    else
    {
        logoff('LogoffAction.do');
    }
}

function saveAndLogoff(summaryName, summaryId)
{
    createXMLHttpRequest();
    var url = "SaveSummaryAction.do";
    var callbackFunc = function() {
        callbackSaveAndLogoff()
    };
    xmlHttpRequest.onreadystatechange = callbackFunc;
    xmlHttpRequest.open("POST", url, true);
    xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var params = getUpdateParams(summaryId) + "&summaryName=" + summaryName;
    xmlHttpRequest.send(params);
}

function callbackSaveAndLogoff()
{
    if (xmlHttpRequest)
    {
        if (xmlHttpRequest.readyState == 4) {
            if (xmlHttpRequest.status == 200) {
                var okFunc = function() {
                    logoff('LogoffAction.do');
                };
                showMessageBox("Your changes have been saved.", okFunc);
            }
        }
    }
}

function saveEval(summaryName, summaryId)
{
    createXMLHttpRequest();
    var url = "SaveSummaryAction.do";
    var callbackFunc = function() {
        callbackSaveEval()
    };
    xmlHttpRequest.onreadystatechange = callbackFunc;
    xmlHttpRequest.open("POST", url, true);
    xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    var params = getUpdateParams(summaryId) + "&summaryName=" + summaryName;
    xmlHttpRequest.send(params);
}

function callbackSaveEval()
{
    if (xmlHttpRequest)
    {
        if (xmlHttpRequest.readyState == 4) {
            if (xmlHttpRequest.status == 200) {
                var okFunc = function() {
                    showSurvey();
                };
                showMessageBox("Your changes have been saved.", okFunc);
            }
        }
    }
}

function saveWarning(prompt, datasetName, surveyId, loggedIn)
{
    if (surveyId < 0) surveyId = 0;

    if (!prompt)
    {
        showSurvey();
    }
    else if (!loggedIn)
    {
        var yesFunc = function() {
            showLogon();
        };
        var noFunc = function() {
            showSurvey();
        };
        var msg = "Changes to '<a href='MyTreatmentAction.do'>" + datasetName + "</a>' will be ";
        msg += "lost unless you logon and ";
        msg += "save your answers. Clicking NO will lose your answers and begin a new evaluation. ";
        msg += "<br/><br/>Do you want to <a href='javascript:showLogon()'>logon</a> now?";
        showYesNoBox(msg, yesFunc, noFunc);
    }
    else
    {
        var yesFunc = function() {
            saveEval(datasetName, surveyId);
        };
        var noFunc = function() {
            showSurvey();
        };
        var msg = "Changes to '<a href='MyTreatmentAction.do'>" + datasetName + "</a>' will be ";
        msg += "lost unless you save your answers. ";
        msg += "Clicking NO will lose your answers and begin a new evaluation. ";
        msg += "<br/><br/>Do you want to save your answers before continuing?";
        showYesNoBox(msg, yesFunc, noFunc);
    }
}

function showSurvey()
{
    document.forms['conditionForm'].action = "SurveyAction.do";
    document.forms['conditionForm'].target = "_top";
    document.forms['conditionForm'].takingForSelf.value = "false";
    document.forms['conditionForm'].submit();
}

function isForSelf(conditionName) {
    if (conditionName == 'false') {
        show('div_forSelf');
    } else {
        document.forms['conditionForm'].action = "SurveyAction.do";
        document.forms['conditionForm'].target = "_top";
        document.forms['conditionForm'].takingForSelf.value = "false";
        document.forms['conditionForm'].submit();
    }
}

function goToSurvey(forSelfQ, thisform) {
    var chosen = "";

    if (forSelfQ != undefined) {
        for (i = 0; i < forSelfQ.length; i++)
        {
            if (forSelfQ[i].checked == true)
            {
                chosen = forSelfQ[i].value;
                break;
            }
        }
        thisform.takingForSelf.value = chosen;
    } else {
        thisform.takingForSelf.value = "false";
    }
    thisform.target = "_top";
    thisform.action = "SurveyAction.do";
    thisform.submit();
}

function goToSurveyList(forSelfQ, thisform) {
    var chosen = "";

    if (forSelfQ != undefined) {
        for (i = 0; i < forSelfQ.length; i++)
        {
            if (forSelfQ[i].checked == true)
            {
                chosen = forSelfQ[i].value;
                break;
            }
        }
        thisform.takingForSelf.value = chosen;
    } else {
        thisform.takingForSelf.value = "false";
    }
    thisform.target = "_top";
    thisform.action = "SurveyListAction.do";
    thisform.submit();
}


function showMoreMessage(divQ, tmId) {
    var divo = document.getElementById("d_showMoreMessage");
    if (divo.style.visibility == "visible") {
        divo.innerHTML = "";
        divo.style.visibility = "hidden";
    }

    currentDivQ = divQ;
    document.tellMeMoreForm.action = "MyConditionSummary.do";
    document.tellMeMoreForm.target = "i_showMoreMessage";
    document.tellMeMoreForm.contentId.value = tmId;
    document.tellMeMoreForm.submit();
}

function setShowMoreMessage(divChild) {
    var divo = document.getElementById("d_showMoreMessage");
    var parent = currentDivQ.offsetParent;

    var top = 0;
    var left = 0;
    if (parent) {
        top = parent.offsetTop;
        left = parent.offsetLeft;

    }
    for (var i = 0; i < 20; i++) {
        parent = parent.offsetParent;
        if (parent) {
            top += parent.offsetTop;
            left += parent.offsetLeft;
        } else {
            break;
        }
    }
    divo.innerHTML = divChild.innerHTML;
    divo.style.pixelLeft = currentDivQ.offsetLeft + left;
    divo.style.pixelTop = currentDivQ.offsetTop + currentDivQ.clientHeight + top + currentDivQ.offsetHeight;

    divo.style.visibility = "visible";
    divo.style.display = "block";

}

function setAltTag(num, img) {
    switch (num) {

        case 0:

            img.alt = "Not available";
            break;
        case 1:
            img.alt = "Poor";
            break;

        case 2:
            img.alt = "Fair";
            break;

        case 3:
            img.alt = "Good";
            break;

        case 4:
            img.alt = "Very Good";
            break;
        case 5:
            img.alt = "Excellent";
            break;

    }
}

var divClosed = false;
function flagClose(divShown) {
    divClosed = true;
    hideByID(divShown);
    hideCurtain();
}
wpcFolder_LEFT = 'Left';
wpcFolder_MIDDLE = 'Middle';
wpcFolder_RIGHT = 'Right';
wpcFolder_IS_SELECTED = "isSelected";
wpcFolder_SELECTED_CLASS = "selectedClass";
wpcFolder_UNSELECTED_CLASS = "unselectedClass";

function wpcFolder_toggleTabs(selectTabs, unselectTabs) {
    var tabArr = selectTabs.split(',');

    for (var i = 0; i < tabArr.length; i++) {
        wpcFolder_selectTab(tabArr[i]);
    }
    var tabArr = unselectTabs.split(',');

    for (var i = 0; i < tabArr.length; i++) {
        wpcFolder_unselectTab(tabArr[i]);
    }
}

function toggleTabs(selectTabs, unselectTabs) {
    var tabArr = selectTabs.split(',');

    for (var i = 0; i < tabArr.length; i++) {
        selectTab(tabArr[i]);
    }
    var tabArr = unselectTabs.split(',');

    for (var i = 0; i < tabArr.length; i++) {
        unselectTab(tabArr[i]);
    }
}

function setPath(rootPath)
{

    contextPath = rootPath;
}

function selectTab(theTabId) {


    imageObj = document.getElementById("tab_" + theTabId);
    if (imageObj != null) {
        if (contextPath)
            imageObj.src = contextPath + "/skins/base/images/tab_" + theTabId + "_on.gif";
        else
            imageObj.src = "skins/base/images/tab_" + theTabId + "_on.gif";
    }
    if (document.getElementById("tab_" + theTabId + "_left"))
    {
        document.getElementById("tab_" + theTabId + "_left").className = 'tab_left_on';
        document.getElementById("tab_" + theTabId + "_middle").className = 'tab_title_on';
        document.getElementById("tab_" + theTabId + "_right").className = 'tab_right_on';
    }


}

function unselectTab(theTabId) {

    imageObj = document.getElementById("tab_" + theTabId);
    if (imageObj != null) {
        if (contextPath)
            imageObj.src = contextPath + "/skins/base/images/tab_" + theTabId + "_off.gif";
        else
            imageObj.src = "skins/base/images/tab_" + theTabId + "_off.gif";
    }

    if (document.getElementById("tab_" + theTabId + "_left"))
    {
        document.getElementById("tab_" + theTabId + "_left").className = 'tab_left_off';
        document.getElementById("tab_" + theTabId + "_middle").className = 'tab_title_off';
        document.getElementById("tab_" + theTabId + "_right").className = 'tab_right_off';
    }
}

function wpcFolder_selectTab(theTabId) {

    theCell = document.getElementById(theTabId + wpcFolder_MIDDLE);
    if (theCell != null) {
        theCell.className = theCell.getAttribute(wpcFolder_SELECTED_CLASS);
        theCell.setAttribute(wpcFolder_IS_SELECTED, "true");
    }

}

function wpcFolder_unselectTab(theTabId) {

    theCell = document.getElementById(theTabId + wpcFolder_MIDDLE);
    if (theCell != null) {
        theCell.className = theCell.getAttribute(wpcFolder_UNSELECTED_CLASS);
        theCell.setAttribute(wpcFolder_IS_SELECTED, "false");
    }
}

function wpcFolder_setTabLocation(tabId, newLocation) {
    var theDiv = document.getElementById(tabId);
    var theFrame = theDiv.firstChild;

    while (theFrame != null && theFrame.tagName != "IFRAME") {
        theFrame = theFrame.nextSibling;
    }
    theFrame.setAttribute("src", newLocation);
}

function wpcFolder_tabIsSelected(tabId) {
    var returnMe = false;
    theCell = document.getElementById(tabId + wpcFolder_LEFT);
    if (theCell != null) {
        if (theCell.getAttribute(wpcFolder_IS_SELECTED) == "true") {
            returnMe = true;
        }
    }
    return returnMe;
}

function saveDTEval(divClicked, divContainer) {
    var divClickedObj = divClicked;
    var divContainerObj = document.getElementById(divContainer);

    if (divContainerObj != undefined) {

        var obj1TopX = getLeft(divClickedObj);
        var obj1TopY = getTop(divClickedObj);
        var obj1BottomX = obj1TopX - (divClickedObj.offsetWidth * 2 - 50);
        var obj1BottomY = obj1TopY + divClickedObj.offsetHeight + 3;
        divContainerObj.style.left = obj1BottomX + "px";
        divContainerObj.style.top = obj1BottomY + "px";

        divContainerObj.style.visibility = "visible";
        divContainerObj.style.display = "block";

    }

}


function goDTHome() {
    document.location = "Home.do?dthome=y";
}


var _username;
var _pw;
var _email;
var _registerdata;
var _forumsid;

function registerUserForForum(username, pw, email) {
    createXMLHttpRequest();
    xmlHttpRequest.open("POST", "/forum/profile.php", false);
    xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
    _registerdata = "mode=register&agreed=true&username=" + username;
    _registerdata += "&email=" + email + "&new_password=" + pw + "&password_confirm=" + pw + "&coppa=0&submit=Submit";
    _username = username;
    _pw = pw;
    _email = email;

    if (_forumsid)
        senddataset = _registerdata + "&sid=" + _forumsid;
    else
        senddataset = "mode=register&agreed=true";

    //alert(senddataset + _forumsid);
    if (_forumsid)
        xmlHttpRequest.onreadystatechange = loginForum;
    else
        xmlHttpRequest.onreadystatechange = getSid;


    xmlHttpRequest.send(senddataset);

    //    xmlHttpRequest = null;
}
function loginForum()
{
    if (xmlHttpRequest.readyState == 4) {
        if (xmlHttpRequest.status == 200) {
            //alert(xmlHttpRequest.responseText);
            loginUserForForum(_username, _pw);

        }
    }

}

function getSid() {

    if (xmlHttpRequest.readyState == 4) {
        if (xmlHttpRequest.status == 200) {
            document.getElementById("message_head").className = "hideDiv";
            document.getElementById("message_head").innerHTML = xmlHttpRequest.responseText;
            _forumsid = document.getElementById("siddiv").innerHTML;
            //alert(_forumsid);
            if (_forumsid)
                registerUserForForum(_username, _pw, _email);
        }
    }
}


function loginUserForForum(username, pw) {
    createXMLHttpRequest();

    xmlHttpRequest.open("POST", "/forum/login.php", true);
    xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
    registerdata = "login=Log in&username=" + username + "&password=" + pw;

    xmlHttpRequest.onreadystatechange = showMessage;
    xmlHttpRequest.send(registerdata);

}

function showMessage() {

    if (xmlHttpRequest.readyState == 4) {
        if (xmlHttpRequest.status == 200) {
            //alert(xmlHttpRequest.responseText);
            //document.getElementById("message_head").innerHTML= xmlHttpRequest.responseText;
        }
    }
}

function mouseoverImage(imgObj, imgName) {
    imgObj.src = "skins/base/images/" + imgName + "_ov.gif";

}


function mouseoutImage(imgObj, imgName) {
    imgObj.src = "skins/base/images/" + imgName + ".gif";

}


//
// 
//
function showContentInfo(divClicked, oEvent, pageName) {

    createXMLHttpRequestG();

    var url = "pages/content/treatment/extrainfo/" + pageName;
    //alert(oEvent);
    if (oEvent) {
        getMouseXY(oEvent);
    }

    xmlHttpGlobal.open("GET", url, true);
    xmlHttpGlobal.onreadystatechange = callbackContent;

    xmlHttpGlobal.send(null);
}

function callbackContent() {

    var received = "";
    if (xmlHttpGlobal.readyState == 4) {
        //alert(xmlHttpGlobal.status);
        if (xmlHttpGlobal.status == 200) {
            received = xmlHttpGlobal.responseText;

            var divContainer = "div_container_content";
            var divContainerObj = document.getElementById(divContainer);
            var divContainerHolder = document.getElementById(divContainer + "_holder");

            divContainerHolder.innerHTML = received;

            divContainerObj.style.width = "500px";
            divContainerObj.style.left = mousex + "px";
            divContainerObj.style.top = "-2048px";
            divContainerObj.style.visibility = "visible";
            divContainerObj.style.display = "block";

            // nb: 50px is margin for container border
            var xwMax = calcXW(40, divContainerObj) ;
            divContainerObj.style.width = xwMax + "px";

            mousex = calculateWindow(mousex, divContainerObj);
            //alert(mousex);
            mousey = mousey + 5;
            divContainerObj.style.left = mousex + "px";
            divContainerObj.style.top = mousey + "px";
            //divContainerObj.style.width = "500px";
            divContainerHolder.style.visibility = "visible";
            divContainerHolder.style.display = "block";
            divContainerObj.style.visibility = "visible";
            divContainerObj.style.display = "block";
        }
    }
    firstClick = true;

}
function calcXW(offset, domElement)
{
    var xwMax = offset ;
    try {
        if (domElement != null && domElement.tagName) {

            // offsetLeft - Retrieves the calculated left position of the object relative to
            // the layout or coordinate parent, as specified by the offsetParent property.

            // offsetWidth - Retrieves the width of the object relative to the layout or
            // coordinate parent, as specified by the offsetParent property.

            // offset += domElement.offsetLeft ;
            var xw = offset + + domElement.offsetWidth ;
            if (xw > xwMax) {
                xwMax = xw;
            }

            var childs = domElement.childNodes ;
            var count = (childs == null) ? 0 : childs.length ;

            while (count-- > 0) {
                xw = calcXW(offset, childs[count]);
                if (xw > xwMax) {
                    xwMax = xw;
                }
            }
        }
    }
    catch(ex) {
    }

    return xwMax;
}

function getClassName(node) {
    if (node.className) return node.className;
    //	else if(node.class) return node.class;
    else return "";
}

function setClassName(node, className) {
    //	node.class = className;
    node.className = className;
}

//show & hide
function showMenu(targetId) {
    if (document.getElementById) {
        target = document.getElementById(targetId);
        if (target)  target.style.display = "block";
    }
}
function hideMenu(targetId) {
    if (document.getElementById) {
        target = document.getElementById(targetId);
        if (target)   target.style.display = "none";
    }
}
