﻿/// <reference path="jQuery-vsdoc.js"/> //jQuery intellisense
//array removeitems prototype function (http://webdevel.blogspot.com/2003/07/javascript-remove-items-from-array.html)
Array.prototype.removeItems = function(itemsToRemove) {

    if (!/Array/.test(itemsToRemove.constructor)) {
        itemsToRemove = [itemsToRemove];
    }

    var j;
    for (var i = 0; i < itemsToRemove.length; i++) {
        j = 0;
        while (j < this.length) {
            if (this[j] == itemsToRemove[i]) {
                this.splice(j, 1);
            } else {
                j++;
            }
        }
    }
}
///////////////input extension to create update button //////////////////////////
//Object.prototype.makeToggleButton = function() {
//debugger;
//}
//stringbuilder class///////////////////////
function StringBuilder() {
    this.buffer = [];
    this.length = 0;
}
StringBuilder.prototype.append = function(text) {
    if (text) {
        this.buffer.push(text);
        this.length += text.length;
    }
}
StringBuilder.prototype.toString = function() {
    return this.buffer.join("");
}
StringBuilder.prototype.clear = function() {
    this.buffer.clear();
    this.length = 0;
}
////////////////////////////////////////////

function updateVersionCheck() {

    mostUpdateVersion = $("#mostUpdateVersions")[0].content.split(";");
    version = versionCheck();
    $(mostUpdateVersion).each(function() {
        var cookie = readCookie('staywithcurrentversion');
        if (this == version && !cookie) {
            html = "<div>A new version of the application is available. Would you like to upgrade the application now?<br/>";
            html += "<input type='checkbox' id='chk_cookie'/>Don't remind me for 30 days.";
            html += "<div class='modalAction'><a onclick='updateVersion();'>YES</a><a onclick='dontUpdateVersion();'>NO</a></div></div>";
            showModal(html, "Version update");
        }
        else if (cookie) {
            return "dontUpdate";
        }
    });
}

function GetAddresse() {
    document.forms("frmProfile").cbStatust.value = 0;
    document.forms("frmProfile").submit();
}

function updateAdminSetting(setting) {
    showModal(setting);
}

function footerVersionCheck(showUpdate) {
    version = versionCheck();

    if ($("#clientVersionSpan").length > 0) {
        if (version == $("#LastVersion")[0].content) {
            //hack for situations where .html() appends from some reason
            if (showUpdate) {
                $("#clientVersionSpan")[0].innerHTML = "<img id='ajaxloaderline'/>";
                setTimeout('$("#clientVersionSpan")[0].innerHTML = "<a onclick=footerVersionCheck(true);> Client version: " + version</a>', 1250);
            }
            else {
                $("#clientVersionSpan")[0].innerHTML = "Client version: " + version;
            }
        }
        else {
            switch ($("#LastVersion")[0].content) {
                case '3.02.00':
                    $("#clientVersionSpan").html("<a href='downloads/eMedconClient_NT.exe'>Download latest version</a>");
                    break;
                case '3.03.00':
                    $("#clientVersionSpan").html("<a href='downloads/emedconmsi.msi'>Download latest version</a>");
                    break;
				  case '3.04.00':
                    $("#clientVersionSpan").html("<a href='downloads/emedconmsi3.04.00.msi'>Download latest version</a>");
                    break;
                default:
                    break;
            }
        }
    }
}
//insert logging for each time odp is viewed
function LogOdpViewing(OdpID) {
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=LogOdpViewing &ODPID=" + OdpID,
        async: true,
        //success: function(information) {showModal(information);},
        failure: function(error) { showModal(error); }
    });
}
//insert logging for each time odp is viewed
function Log(module, level, action, text) {
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=LogEvent&module=" + module + "&level=" + level + "&logAction=" + action + "&text=" + text,
        async: true,
        //success: function(information) {showModal(information);},
        failure: function(error) { showModal(error); }
    });
}
//was the odp viewed??
function wasTheOdpViewed(OdpID) {
    var wasViewed;
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=wasTheOdpViewed&ODPID=" + OdpID,
        async: true,
        success: function(LogID) {
            wasViewed = LogID > 0;
        },
        failure: function(error) { showModal(error); }
    });
    return wasViewed;
}
function dontUpdateVersion() {
    if (chk_cookie.checked) {
        createCookie('staywithcurrentversion', 'true', 30);
    }
    document.location.href = 'inbox.asp';
}
function updateVersion() {
    $.modal.close();
    var cookie = readCookie('staywithcurrentversion');

    if (!cookie) {
        timerID = setTimeout("OpenDownloadDlg()", 3000);
    }
}
function checkSessionVar(sessionVar) {
    var returnValue;
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=checkSessionVar&Var=" + sessionVar,
        async: false,
        success: function(sessionValue) {
            returnValue = sessionValue;
        },
        failure: function(error) { showModal(error); }
    });
    return returnValue;
}

function versionCheck() {

    //alert("versionCheck:call checkSessionVar");
    var agentVersion = checkSessionVar("AgentVersion");
    //alert("versionCheck:" + agentVersion);
    if (agentVersion == "") {
        try {
            var agent = new ActiveXObject("MDAgent.Agent");
            var version = agent.GetVersion;
            //insert into session
            insertSessionVar("AgentVersion", version);
            agent = null;
            return version;
        }
        catch (err) {
            //alert(err);
            return 0;
        }
    }
    else {
        return agentVersion;
    }

}
//toggle faq inner divs display (show/hide)
function toggleFaqInnerDiv(sender, divNumber) {
    if ($("#faqInnerDiv_" + divNumber + " :visible").length > 0) {
        $("#faqInnerDiv_" + divNumber).slideUp("slow");
        sender.innerHTML = "+";
    }
    else {
        $("#faqInnerDiv_" + divNumber).slideDown("slow");
        sender.innerHTML = "-";
    }
}
function getUrlToCall(path) {
    return path;
}

function assignValueToAddresseeInput(clickedItem) {
    $("#text_addressee")[0].value = clickedItem.innerText;
    //make the auto complete disappear
    $("#addressee_autocomplete").html(" ");
}
//get autocomplition for addressees in profile page
function autoCompleteAddresses() {
    if ($("#text_addressee")[0].value.length > 0) {
        //make ajax call and grab data
        $.ajax({
            type: "POST",
            url: getUrlToCall("Services.asp"),
            dataType: "application/x-www-form-urlencoded",
            data: "Action=getAutoCompleteInfo&Q=" + $("#text_addressee")[0].value,
            async: true,
            success: function(information) {
                if (information.length > 0) {
                    var autoComplitionInfoObj = eval('(' + information + ')');
                    var autoComplitionInf = autoComplitionInfoObj.Experts
                }
                var data = new Array();
                for (i = 0; i < autoComplitionInf.length; i++) {
                    if (autoComplitionInf[i].Name != undefined) {
                        data[i] = new expert(autoComplitionInf[i].Name, autoComplitionInf[i].ID);
                    }
                }
                //assmble the autocomplete box
                var html = "";

                $(data).each(function() {
                    html += "<a style='text-decoration:underline;color:blue;' onclick='assignValueToAddresseeInput(this)'>" + this._name + "</a><br/>";
                });
                $("#addressee_autocomplete").html(html);

            },
            failure: function(error) { showModal(error); }
        });
    }


}

//class expert for autocomplition
function expert(name, id) {
    this._name = name;
    this._id = id;
}
expert.prototype._name;
expert.prototype._id;
//end expert class
function getDomainContent(content) {
    var returnValue;
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=getdomaininformation",
        async: false,
        success: function(information) {
            if (information.length > 0) {
                var domainInfo;
                var domainInformation = eval('(' + information + ')');
                if (domainInformation.domainInfo) {
                    domainInfo = domainInformation.domainInfo;
                }
                if (eval("domainInfo." + content != "")) {
                    returnValue = eval("domainInfo." + content);

                }
            }
        },
        failure: function(error) { showModal(error); }
    });
    return returnValue;
}
function getDomainInformation(page) {
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=getdomaininformation",
        async: false,
        success: function(information) {
            if (information.length > 0) {
                var domainInformation = eval('(' + information + ')');
                //if the returning information contains a domain info element
                if (domainInformation.domainInfo) {
                    domainInfo = domainInformation.domainInfo;
                }
                else {
                    showModal("Wrong URL");
                }

                //change the logo source
                switch (page) {
                    case "index":
                        if (domainInfo.Logo != "") {
                            $("#DomainLogo").attr("src", domainInfo.Logo);
                            if (domainInfo.HospitalURL != "") {
                                $("#DomainSiteLink").attr("href", domainInfo.HospitalURL);
                                $("#FooterHospitalLink").attr("href", domainInfo.HospitalURL);
                            }
                        }
                        else {
                            $("#DomainLogo").hide();
                        }
                        if (domainInfo.LastVersion != "") {
                            $("#LastVersion").attr("content", domainInfo.LastVersion);
                        }
                        if (domainInfo.HospitalName != "") {
                            $("#HospitalName").html(domainInfo.HospitalName); //FooterHospitalName
                            $("#FooterHospitalName").html("<small>" + domainInfo.HospitalName + "</small>");
                        }
                        if (domainInfo.Banner != "") {
                            var lastIndexOfPeriod = domainInfo.Banner.lastIndexOf('.');
                            if ($("#HospitalBanner").length > 0) {
                                if (domainInfo.Banner.slice(lastIndexOfPeriod + 1) == "swf") {
                                    var html = "<object type='application/x-shockwave-flash' style='width:728px; height:90px;' data='" + domainInfo.Banner + "'>";
                                    html += "<param name='movie' value='" + domainInfo.Banner + "' /><param name='wmode' value='transparent' /></object>";
                                    $("#HospitalBanner")[0].innerHTML = html;
                                } else {
                                    $("#HospitalBanner")[0].innerHTML = "<img src='" + domainInfo.Banner + "' style='width:728px;'/>";
                                }
                            }

                        }
                        else {
                            $("#DomainLogo").css("display", "none");
                        }
                        break;
                    case 'servervars':
                        domainInfo.ShowSessionPrompt == 1 ? chk_sessionPrompt.checked = 'checked' : null;
                        domainInfo.DeleteInDir == 1 ? chk_deleteInFolder.checked = 'checked' : null;
                        txt_passwordExpiration.value = domainInfo.PasswordExpirationDuration;
                        break;

                }
            }
            else {
                // instaead of welcome message, show explanation about the wrong address
                $("#WelcomeMsgDiv").html("<h2>The inserted URL does not point to a domain</h2>");
                $("#IndexTextDiv").html("If you are familiar with the correct URL, please type it in the address bar and refresh the website<br/>" +
                                           "Otherwise, please contact support. ");
                disableContent();
                location.reload();

            }
        },
        failure: function(error) { showModal(error); }
    });
}

function disableContent() {
    //hide the logo placeholder
    $("#DomainLogo").css("display", "none");
    //disable the buttons and inputs
    $("input").attr("disabled", "disabled");

}
function addAttachmentToDB(file, path) {
    //filename = file.name.replace(/\s/g, "%20");
    filename = file.replace(/\s/g, "%20");
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=addAttachmentToDB&PATH=" + path + "&NAME=" + filename,
        async: true,
        success: function(attachmentID) {
            //add the attachmentID to the list of attachments in the procedure
            //MDHTML.attachmentIDs += attachmentID + ";";
            //showModal(MDHTML.attachmentIDs);
        },
        failure: function(error) { showModal(error); }
    });

}
function GetCategoriesForDomain() {
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=GetCategoriesForDomain",
        async: true,
        success: function(information) {
            if (information.length > 0) {

                var domainCategories = eval('(' + information + ')');
                var categories = domainCategories.Categories;
                var htmlToAssign = new StringBuilder();
                htmlToAssign.append("<div style='text-align:center;'>");

                $(categories).each(function() {
                    if (this.Name != undefined) {
                        htmlToAssign.append("<input id='catBtn_" + this.ID + "' type='button' class='verylongbutton' value='" + this.Name + "' onclick=\"getDoctorsByCat(" + this.ID + ",'" + this.Name + "',1);\"   /><br/> ");
                    }
                }
                );
                htmlToAssign.append("</div>");
                $("#ProfTable").html(htmlToAssign.toString());
            }
        },
        failure: function(error) { showModal(error); }
    });
}
function GetHospitalsForDomain() {
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=GetHospitalsForDomain",
        async: true,
        success: function(information) {
            if (information.length > 0) {
                var hospitals = eval('(' + information + ')').Hospitals;
                var htmlToAssign = new Array();
                htmlToAssign.push("<div style='text-align:center;height:250px;width:230px;overflow-y:scroll'>");
                $(hospitals).each(function() {
                    if (this.hospitalname != undefined) {
                        htmlToAssign.push("<input  type='button' style='font-size:0.9em' class='verylongbutton' value='" + this.hospitalname + "' onclick='getDoctorsByHospitalName(this);' /><br/> ");
                    }
                }
                );
                htmlToAssign.push("</div>");
                document.getElementById("ProfTable").innerHTML = htmlToAssign.join('');
            }
        },
        failure: function(error) { showModal(error); }
    });
}
function updateDomainContent(domainContentName, newValue) {

    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=updateDomainContent&dc=" + domainContentName + "&v=" + newValue,
        async: true,
        success: function(information) {
            showModal("updated");
        },
        failure: function(error) { showModal(error); }
    });
}

function getDoctorsByHospitalName(sender) {
    Level = 2;
    hospitalName = sender.value.replace(/\s/g, "%20");
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=getDoctorsByHospitalName&hn=" + hospitalName,
        async: true,
        success: function(information) {
            if (information.length > 0) {
                var informationObj = eval('(' + information + ')');
                var experts = informationObj.Experts;
                //var htmlToAssign = new StringBuilder();
                var htmlToAssign = new Array();
                htmlToAssign.push("<table id='doctorsTbl'>");

                var userID = $("#userID")[0].content;
                var DefaultAddresseeID = getProfileFields(userID, 'DefaultAddresseeID');
                if (DefaultAddresseeID != undefined) {
                    DefaultAddresseeID = $(DefaultAddresseeID.split(";"));
                    $(experts).each(function(index, element) {
                        if (element.Name != undefined) {
                            //htmlToAssign.append(GetExpertHTML(element, index, DefaultAddresseeID, Level));
                            htmlToAssign.push(GetExpertHTML(element, index, DefaultAddresseeID, Level));
                        }
                    });
                }

                //htmlToAssign.append("</table>");
                htmlToAssign.push("</table>");


                //$("#doctorsTblDiv").html(htmlToAssign.toString());
                var doctors = htmlToAssign.join('');
                document.getElementById("doctorsTblDiv").innerHTML = doctors;


                //show the criteria
                $("#search-doctors-criteria").html("Search results for: " + hospitalName.replace(/%20/gi, ' ')).show();

            }
            $("#progress-bar").hide();
        },
        failure: function(error) { showModal(error); }
    });

}

function getDoctorsByCat(catID, catName, Level) {
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=getDoctorsByCat&level=" + Level + "&cat=" + catID,
        async: true,
        success: function(information) {
            if (information.length > 0) {
                var informationObj = eval('(' + information + ')');
                var experts = informationObj.Experts;

                var htmlToAssign = new StringBuilder();
                htmlToAssign.append("<table id='doctorsTbl'>");

                $(experts).each(function(index, element) {
                    if (element.Name != undefined) {
                        htmlToAssign.append(GetExpertHTML(element, index, undefined, Level));
                    }
                }
                                );
                htmlToAssign.append("</table>");
                $("#doctorsTblDiv").html(htmlToAssign.toString());
                //show the criteria
                $("#search-doctors-criteria").html("Search results for: " + catName).show();
            }
            //rebind
            //bindExpertHoverEvent();
            bindExpertDocumentHoverEvent();
        },
        failure: function(error) { showModal(error); }
    });
}
//select all experts
function checkAllExperts() {
    //get all expert nodes
    expertChkBoxes = $(".expertChk")
    //check all
    expertChkBoxes.attr("checked", "checked");
    //add to addressees list
    var htmlToAppend = '';
    $(expertChkBoxes).each(function() {
        htmlToAppend += this.expertID + ",";
    });
    $("#addressees")[0].value += htmlToAppend;
}
function uncheckAllExperts() {
    expertChkBoxes = $(".expertChk:checked")
    //check all
    expertChkBoxes.attr("checked", "");
    //remove from addressee list
    $(expertChkBoxes).each(function() {
        removeItemFromList('addressees', this.expertID);
    });
}

//get experts by first letter of last name
//this is a global var to hold the last query
var lastDoctorsQuery;
var lastDoctorsLevelQuery;
///////////////////////////////////////////
function getDoctorsByLetter(startsWith, Level, skip, take, append) {
    lastDoctorsQuery = startsWith;
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=getDoctorsByLetter&level=" + Level + "&sw=" + startsWith + "&skip=" + skip + "&take=" + take,
        async: true,
        success: function(information) {
            if (information.length > 0) {
                var informationObj = eval('(' + information + ')');
                var experts = informationObj.Experts;
                //var htmlToAssign = new StringBuilder();
                var htmlToAssign = new Array();
                // htmlToAssign.append("<table id='doctorsTbl'>");
                htmlToAssign.push("<table id='doctorsTbl'>");
                var userID = $("#userID")[0].content;
                var DefaultAddresseeID = getProfileFields(userID, 'DefaultAddresseeID');
                if (DefaultAddresseeID != undefined) {
                    DefaultAddresseeID = $(DefaultAddresseeID.split(";"));
                    $(experts).each(function(index, element) {
                        if (element.Name != undefined) {
                            //htmlToAssign.append(GetExpertHTML(element, index, DefaultAddresseeID, Level));
                            htmlToAssign.push(GetExpertHTML(element, index, DefaultAddresseeID, Level));
                        }
                    });
                }

                // htmlToAssign.append("</table>");
                htmlToAssign.push("</table>");
                // var finalHtml = htmlToAssign.toString();
                var finalHtml = htmlToAssign.join('');

                if (append) {
                    var tableHTML = finalHtml;
                    $("tr", tableHTML).appendTo("#doctorsTbl");
                } else {
                    //$("#doctorsTblDiv").html(finalHtml);
                    document.getElementById('doctorsTblDiv').innerHTML = finalHtml;
                }

                //show the criteria
                if (startsWith != '%') {
                    $("#search-doctors-criteria").html("Search results for: " + startsWith).show();
                }
                else {
                    $("#search-doctors-criteria").hide();
                }

            }
            //rebind
            if (Level == 1) {
                bindExpertDocumentHoverEvent();
            }

            $("#progress-bar").hide();
        },
        failure: function(error) { showModal(error); }
    });
}

function bindExpertDocumentHoverEvent() {
    var timeoutID;
    //bind hover the document icon in the sendcase.asp page
    $(".documentImage").hover(
    function() {
        window.clearTimeout(timeoutID);
        expertID = $(".expertChk", $(this)[0].parentElement.parentElement)[0].expertID;
        timeoutID = window.setTimeout("getUserProfile(expertID," + (window.event.x - 280) + "," + window.event.y + ");", 1000);
    },
    function() {
        //windows will auto hide after 10 seconds if leaving the icon
        window.clearTimeout(timeoutID);
        timeoutID = window.setTimeout('hideTooltip();', 1500);

    });
}

function GetExpertHTML(expert, index, DefaultAddresseeID, Level) {

    var DefaultAddressee = "";
    var ifDefaultShowIt = function() {
        if (this == expert.ID) {
            DefaultAddressee = "<b style='color:gray;padding-left:10px;'>Default addressee</b>";
        };
    }
    if (DefaultAddresseeID != undefined) {
        DefaultAddresseeID.each(ifDefaultShowIt);
    }
    var htmlToAppend;
    if (index % 2 == 0) {
        htmlToAppend = "<tr class='evenTr'>";
    }
    else {
        htmlToAppend = "<tr class='oddTr'>";
    }
    htmlToAppend = GetExpertTRHtml(expert, htmlToAppend, DefaultAddressee, Level);
    return htmlToAppend.toString();
}
function GetUsersHTML(user, index) {
    var htmlToAppend = new StringBuilder();
    if (index % 2 == 0) {
        htmlToAppend.append("<tr onclick='editUser(" + user.UserID + ",this);' id='user_" + user.UserID + "' class='evenTr'>");
    }
    else {
        htmlToAppend.append("<tr onclick='editUser(" + user.UserID + ",this);' id='user_" + user.UserID + "' class='oddTr'>");
    }
    htmlToAppend.append(GetUsersTRHtml(user, htmlToAppend));
    return htmlToAppend.toString();
}
function GetUsersTRHtml(user, htmlToAppend) {
    htmlToAppend += "<td style='width:210px;'>" + user.Name + "</td>";
    htmlToAppend += "<td style='width:210px;'>" + user.Login + "</td>";
    htmlToAppend += "<td style='width:212px;'>" + user.Category + "</td>";
    htmlToAppend += "</tr>";
    return htmlToAppend;
}

function editUser(userID, sender) {
    if ($("#userDetails").length > 0) {

        if ($("#userDetails")[0].previousSibling == sender) {
            $("#userDetails").remove();
            return false;
        }
        else {
            $("#userDetails").remove();
        }
    }

    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=getUserProfile&UID=" + userID,
        async: true,
        success: function(information) {
            if (information.length > 0) {
                //showModal(information);
                var informationObj = eval('(' + information + ')');
                var profile = informationObj.Profile;
                newTr = "<tr id='userDetails' style='height:100px;'>";
                newTr += "<td>" + profile.Name + ", " + profile.Title + "</td>";
                newTr += "<td>" + profile.HospitalName + "</td>";
                if (profile.Mail.length > 0) {
                    newTr += "<td>E-mail: <a title='Click to send mail' href='mailto:" + profile.Mail + "'>" + profile.Mail + "</a></td>";
                }
                newTr += "</tr>";

                $(newTr).insertAfter(sender);
            }
        },
        failure: function(error) { showModal(error); }
    });


}
function GetExpertTRHtml(expert, htmlToAppend, DefaultAddressee, Level) {
    htmlToAppend += "<td style='padding-left:5px;width:20px;'><input class='expertChk' id='expertChk_" + expert.ID + "' expertID=" + expert.ID + " type='checkbox' " + eval(itemInList('addressees', expert.ID) ? '"checked"' : '') + " onclick='addRemoveAddressee(" + expert.ID + ");' /></td>";
    if (Level == 1) {
        htmlToAppend += "<td id='expertNameTD_" + expert.ID + "' class='expertName' style='padding-left:5px;width:385px;' expertID='" + expert.ID + "'>" + expert.Name + ", " + expert.Title + DefaultAddressee + "</td>";
        htmlToAppend += "<td style='padding-left:5px;width:120px;text-align:center;'><div class='documentImage' style='text-decoration:underline;color:blue;' onclick='ShowCv(" + expert.ID + ")'/></td>";
    }
    else {
        htmlToAppend += "<td id='expertNameTD_" + expert.ID + "' class='expertName' style='padding-left:5px;width:510px;' expertID='" + expert.ID + "'>" + expert.Name + ", " + expert.Title + DefaultAddressee + "</td>";
    }
    htmlToAppend += "</tr>";
    return htmlToAppend;
}
function sortMsgsBy(EntityID, FieldName, page, sender) {
    if ($(sender).parent().hasClass("sortedColumn")) {
        $("#msgsDiv").hide();
        //This next section is all about reversing the order of the list
        var rows = $("tr", "#msgsTable");
        var newRows = new Array();

        //position withing the newRows array
        j = 0;
        for (i = rows.length - 1; i >= 0; i--) {
            newRows[j] = rows[i];
            j++;
        }
        var html = "<table id='msgsTable'>";
        for (i = 0; i < newRows.length; i++) {
            if (newRows[i]) {
                if (newRows[i].outerHTML != "") {
                    html += newRows[i].outerHTML;
                }
            }
        }
        html += "</table>";
        $("#msgsDiv").html(html).slideDown("fast");

        if ($("img", $(sender).parent()).attr("src") == "images/sortingArrow_Asc.gif") {
            $("img", $(sender).parent()).attr("src", "images/sortingArrow_Desc.gif")
        }
        else {
            $("img", $(sender).parent()).attr("src", "images/sortingArrow_Asc.gif");
        }

    }
    else {
        img = "<img style='padding-left:3px;' src='images/sortingarrow_desc.gif' />";
        //reset classes for all headers
        $sorted = $("th.sortedColumn", "#tableHeadersTable");
        $sorted.removeClass('sortedColumn');
        if ($sorted.length > 0) {
            //debugger;
            html = $sorted.html();
            htmlArray = html.split($(html)[0].firstChild.data)
            if (htmlArray.length > 2) {
                html = htmlArray[0] + htmlArray[1] + $(html)[0].firstChild.data + "</A>";
                html = html.replace(/,'',/, ",'" + $(html)[0].firstChild.data + "',");
            }
            else {
                html = htmlArray[0] + $(html)[0].firstChild.data + "</A>"
            }

            $sorted.html(html);
        }

        html = $(sender).html();
        $(sender).parent().addClass("sortedColumn").end().html(html + img);
        $("#msgsDiv").hide();
        switch (page) {
            case 'inbox':
                GetInboxForUser(EntityID, FieldName);
                break;
            case 'outbox':
                GetOutboxForUser(EntityID, FieldName);
                break;
            case 'ReceivedOdps':
                getDomainReceivedOdps(EntityID, FieldName);
                break;
        }
        $("#msgsDiv").slideDown("fast");
    }
}
//Get the odps for specific domain
function getDomainReceivedOdps(DomainID, OrderBy) {
    beginDate = $("#begin-date").val();
    finishDate = $("#finish-date").val();
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=getDomainReceivedOdps&DID=" + DomainID + "&OrderBy=" + OrderBy + "&BD=" + beginDate + "&FD=" + finishDate,
        async: true,
        success: function(information) {
            if (information.length > 0) {
                var informationObj = eval('(' + information + ')');
                var msgs = informationObj.Msgs;
                //var for total size
                var totalSize = 0;
                //generate html
                var htmlToAssign = "<table id='msgsTable'>";
                $(msgs).each(function(index, element) {
                    if (element.User != undefined) {
                        htmlToAssign += GetMsgHTML(element, index);
                        totalSize += Math.round(element.Size / 1024);
                    }
                }
                );
                htmlToAssign += "</table>";

                $("#msgsDiv").html(htmlToAssign);
                var numTransactions = $("tr", "#msgsTable").length;
                $("#numTransactions").html(numTransactions);
                var avgSize = Math.round(totalSize / numTransactions);
                $("#avgSize").html(avgSize + "Kb");
                //show details div

                $("#Admin-SubPanel-Procedures").show();
            }
        },
        failure: function(error) { showModal(error); }
    });
}

//get inbox by userid
function GetInboxForUser(UserID, OrderBy) {
	$.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=getInboxByUserID&ID=" + UserID + "&OrderBy=" + OrderBy,
        async: true,
        success: function(information) {
            if (information.length > 0) {
                var informationObj = eval('(' + information + ')');
                var msgs = informationObj.Msgs;
                //generate html
                var htmlToAssign = "<table id='msgsTable'>";
                $(msgs).each(function(index, element) {
                    if (element.User != undefined) {
                        htmlToAssign += GetMsgHTML(element, index);
                    }
                }
                );
                htmlToAssign += "</table>";

                $("#msgsDiv").html(htmlToAssign);
            }
			
        },
        failure: function(error) { showModal(error); }
    });
	
}
//get outbox by userid
function GetOutboxForUser(UserID, OrderBy) {
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=getOutboxByUserID&ID=" + UserID + "&OrderBy=" + OrderBy,
        async: true,
        success: function(information) {
            if (information.length > 0) {
                var informationObj = eval('(' + information + ')');
                var msgs = informationObj.Msgs;
                //generate html
                var htmlToAssign = "<table id='msgsTable'>";
                $(msgs).each(function(index, element) {
                    if (element.User != undefined) {
                        htmlToAssign += GetMsgHTML(element, index);
                    }
                }
                );
                htmlToAssign += "</table>";

                $("#msgsDiv").html(htmlToAssign);
            }
        },
        failure: function(error) { showModal(error); }
    });
}

function CreateABCPager() {
    var lettersString = 'ABCDEFGHIJKLM';
    var lettersArray = lettersString.split('');
    var rowsHtmlArray = new Array();
    rowsHtmlArray.push("<tr>");
    $(lettersArray).each(function() {
        rowsHtmlArray.push("<td><a>" + this + "</a></td>");
    });
    rowsHtmlArray.push("</tr>");
    var lettersString = 'NOPQRSTUVWXYZ';
    var lettersArray = lettersString.split('');
    rowsHtmlArray.push("<tr>");
    $(lettersArray).each(function() {
        rowsHtmlArray.push("<td><a>" + this + "</a></td>");
    });
    rowsHtmlArray.push("</tr>");
    var rowsHtml = rowsHtmlArray.join('');
    //document.getElementById("ABCTable").innerHTML = rowsHtml;
    $("#ABCTable").html(rowsHtml);
}
function GetMsgHTML(msg, index) {
    var htmlToAppend = "";
    if (index % 2 == 0) {
        htmlToAppend += "<tr title='Double-click to view a procedure.' ondblclick='showOdp(" + msg.ID + "," + msg.UserID + "," + msg.PurposeID + ");' class='evenTr' style='cursor:pointer;font-weight:" + (msg.Viewed > 0 ? '' : 'bold') + "'>";
    }
    else {
        htmlToAppend += "<tr title='Double-click to view a procedure.' ondblclick='showOdp(" + msg.ID + "," + msg.UserID + "," + msg.PurposeID + ");' class='oddTr' style='cursor:pointer;font-weight:" + (msg.Viewed > 0 ? '' : 'bold') + "'>";
    }
    htmlToAppend += "<td id='checkboxTD'><input type='checkbox' odpid='" + msg.ID + "' id='chkbox_msg_" + msg.ID + "'/> </td>";
    htmlToAppend += "<td id='nameTD'><a expertID='" + msg.UserID + "' class='mailPersonLink'>" + msg.User + "</a></td>";
    htmlToAppend += "<td id='HospitalTD'>" + msg.Hospital + "</td>";

    if (msg.PurposeID == 3) {
        htmlToAppend += "<td id='descriptionTD'>Fwd: " + msg.Description + "</td>";
    }
    else {
        htmlToAppend += "<td id='descriptionTD'>" + msg.Description + "</td>";
    }
    htmlToAppend += "<td id='UploadedTD'>" + msg.Uploaded + "</td>";
    htmlToAppend += "<td id='SizeTD'>" + Math.round(msg.Size / 1024) + "Kb</td>"; //devide by 1024 to get the size in kb
    htmlToAppend += "</tr>";


    return htmlToAppend;
}

//add addressee to procedure
function addRemoveAddressee(addresseeID) {
    if (!itemInList('addressees', addresseeID)) {
        htmlToAppend = addresseeID + ",";
        $("#addressees")[0].value += htmlToAppend;
    }
    else {
        removeItemFromList('addressees', addresseeID);
    }
}
//get user profile to show in tooltip
function getUserProfile(userID, x, y) {
    //only IE!!!
    if (!x) {
        x = window.event.x;
        y = window.event.y;
    }

    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=getUserProfile&UID=" + userID,
        async: true,
        success: function(information) {
            if (information.length > 0) {
                //showModal(information);
                var informationObj = eval('(' + information + ')');
                var profile = informationObj.Profile;
                htmlToAssign = "<div>";
                htmlToAssign += "<h1>" + profile.Name + ", " + profile.Title + "</h1>";
                htmlToAssign += "<h2>" + profile.HospitalName + "</h2>";
                htmlToAssign += "<h4>Tel: " + profile.MobilePhone + "</h4>";
                htmlToAssign += "<h4>Tel2: " + profile.WorkPhone + "</h4>";
                if (profile.Mail.length > 0) {
                    htmlToAssign += "<h4>E-mail: <a title='Click to send mail' href='mailto:" + profile.Mail + "'>" + profile.Mail + "</a></h4>";
                }
                htmlToAssign += "<span onclick='hideTooltip();' class='right' style='cursor:pointer'>Close</span>";
                htmlToAssign += "</div>";
                $("#tooltip").html(htmlToAssign).css({ left: x, top: y }).fadeIn();
            }
        },
        failure: function(error) { showModal(error); }
    });
}
function hideTooltip() {
    $("#tooltip").fadeOut();
}
function clearAddresseesDiv() {
    $("#text_addressee")[0].innerHTML = "";
}
//get profile fields for the profile page (technical profile)
function getProfileFields(userID, property) {
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=getUserTechincalProfile&UID=" + userID,
        async: true,
        success: function(information) {
            if (information.length > 0) {
                //showModal(information);
                var informationObj = eval('(' + information + ')');
                var profile = informationObj.Profile;
                if (property) {
                    property = eval("profile." + property);
                }
                else {
                    //assign profile properties to page
                    $("#chkbox_autosend").attr('checked', eval(profile.AutoSend == 0 ? false : true));
                    $("#chkbox_additionalinfo").attr('checked', eval(profile.AdditionalInfo == 0 ? false : true));
                    //parse profile.DefaultAddresseeID
                    addressees = profile.DefaultAddressees.split(";");
                    addresseesIDs = profile.DefaultAddresseeID.split(";");

                    if (addressees.length > 1) {
                        //removeDefaultAddressee
                        //$(addressees).each(function(index) {
                        //   if (this != "") {
                        //        $("#text_addressee")[0].innerHTML += "<a class='defaultAddressees' title='Click to view details' onclick='getUserProfile(" + addresseesIDs[index] + ")'>" + this + "</a>";
                        //        $("#text_addressee")[0].innerHTML += "<a onclick='removeDefaultAddressee(" + addresseesIDs[index] + ");clearAddresseesDiv();getProfileFields(" + userID + ")'><small>  Remove</small></a><br/>";
                        //    }
                        //});

                    }
                    //else {
                    //   $("#text_addressee")[0].innerHTML = "<a href='sendcase.asp'>Set default addressees</a>";
                    //}
                    $("#chkbox_dod").attr('checked', eval(profile.DownLoadID == 0 ? false : true));

                    if (jQuery.trim(profile.DICOMSource).length > 0) {
                        $("#text_DICOMSource").val(profile.DICOMSource);
                    }
                    else {
                        $("#text_DICOMSource").val("No source selected");
                    }

                    $("#chkbox_halfspeed").attr('checked', eval(profile.HalfSpeed == 0 ? false : true));
                    $("#chkbox_preview").attr('checked', eval(profile.Preview == 0 ? false : true));
                    $("input[name='First screen'][value='" + profile.FirstScreenID + "']").attr('checked', 'true');
                    $("input[name='Compression'][value='" + profile.CompressionID + "']").attr('checked', 'true');
                }
            }
        },
        failure: function(error) { showModal(error); }
    });
    return property;
}
//update profile
function UpdateProfile(UserID) {
    //get info from page
    autosend = $("#chkbox_autosend")[0].status == false ? 0 : 1;
    additionalinfo = $("#chkbox_additionalinfo")[0].status == false ? 0 : 1;
    //addressees = $("#text_addressee")[0].value.replace(" ", ";");
    dod = $("#chkbox_dod")[0].status == false ? 0 : 1;
    DICOMSource = $("#text_DICOMSource")[0].value == "No source selected" ? " " : $("#text_DICOMSource")[0].value;
    halfspeed = $("#chkbox_halfspeed")[0].status == false ? 0 : 1;
    preview = $("#chkbox_preview")[0].status == false ? 0 : 1;
    firstScreen = $("input[name='First screen']:checked").val();
    compressionID = $("input[name='Compression']:checked").val();

    data = "Action=UpdateProfile&UID=" + UserID + "&AS=" + autosend;
    data += "&P=" + preview + "&AI=" + additionalinfo + "&HS=" + halfspeed;
    data += "&FS=" + firstScreen + "&DS=" + DICOMSource + "&DOD=" + dod + "&CID=" + compressionID;
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: data,
        async: true,
        success: function(information) {
            if (information == "OK") {
                html = "<div>To see your changes, we recommend that you log off and log in again.</div>";
                showModal(html, 'Update Details');
            }

        },
        failure: function(error) { showModal(error); }
    });
}
//forward odp (inbox / outbox pages)
function forwardOdps(userID, page, ex) {
    checkedOdps = $("input[id^='chkbox_msg_']:checked");
    if (checkedOdps.length > 0) {
        //reset forward list
        $("#odpsToForward")[0].value = '';
        //get all checked Items
        checkedOdps.each(function() {
            addRemoveItem('forward', this.odpid);
        });
        //display prompt
        if (ex) {
            promptBeforeDeleteForward('exForward', userID);
        }
        else {
            promptBeforeDeleteForward('forward', userID);
        }

        //get msgs again
        /*switch (page) {
        case 'inbox':
        GetInboxForUser(userID, 'Date');
        break;
        case 'outbox':
        GetOutboxForUser(userID, 'Date');
        break;

        }*/
    }
    else {
        showModal("Please select procedure to forward.");
        return false;
    }
}
//delete odp (inbox / outbox pages)
function deleteOdps(userID, page) {
    checkedOdps = $("input[id^='chkbox_msg_']:checked");
    if (checkedOdps.length > 0) {
        //reset deletion list
        $("#odpsToDelete")[0].value = '';
        //get all checked Items
        checkedOdps.each(function() {
            addRemoveItem('delete', this.odpid);
        });
        //display prompt
        promptBeforeDeleteForward('delete', userID, page);
    }
    else {
        showModal("Please select procedure to delete.");
        return false;
    }
}
function promptBeforeDeleteForward(actionType, userID, page) {
    //make ajax call to delete
    switch (actionType) { //if actionType = delete then prompt before deletion, else prompt before forward
        case 'delete':
            //remove comma
            msgsIDs = $("#odpsToDelete")[0].value.slice(0, -1);
            strToShow = "<div>Are you sure you want to delete the selected procedure(s)?<div><div  class='modalAction'><a onclick='deleteOdp(" + userID + ",\"" + msgsIDs + "\",\"" + page + "\")'>Yes</a><a class='modalAction' onclick='$.modal.close();'>No</a></div></div></div>";
            showModal(strToShow, "Confirmation");
            break;
        case 'forward':
            //message removed by FA request
            /*
            strToShow = "<div>You are about to forward the selected procedures<div style='margin-top:10px;'><div  class='modalAction'><a class='modalAction' onclick='forwardOdpAction(false)'>Continue</a><a class='modalAction' onclick='$.modal.close();'>Cancel</a></div></div></div>";
            showModal(strToShow, "Confirmation");*/
            forwardOdpAction(false);
            break;
        case 'exForward':
            strToShow = "<div style='margin-top:10px;'><small>Send the procedure to an external addressee</small><br/>E-mail: <input id='ExternalAddresseeEmail' type='text' /></div><div class='modalAction'><a onclick='forwardOdpAction(true)'>Continue</a><a class='modalAction' onclick='$.modal.close();'>Cancel</a></div>";
            showModal(strToShow, "Confirmation", 'nothing');
            break;
    }
}
//support page msg after sending
function supportMsg() {
    str = "Thank you for your comments. Our Support team will contact you. If you encountered any inconvenience while using eMedcon, please accept our apologies.";
    showModal(str, null, "document.MailForm.submit()");
}
function forwardOdpAction(toExternal) {
    var emailAddress = $("#ExternalAddresseeEmail").val();
    if (toExternal) {
        if (isEmail(emailAddress) && jQuery.trim(emailAddress).length > 0) {
            //check if the user already exists. if so, just forward
            //doesDetailExist with FN for FieldName and FV for FieldValue
            $.ajax({
                type: "POST",
                url: getUrlToCall("Services.asp"),
                dataType: "application/x-www-form-urlencoded",
                data: "Action=doesDetailExist&FN=EmailAddress&FV=" + emailAddress,
                async: false,
                success: function(information) {
                    var Users = eval('(' + information + ')');
                    if (Users.Users.length > 1) {
                        showModal("Cannot forward to this email address, contact system administrator");
                        return false;
                    }
                    else {


                        if (Users.Users.length > 0) {
                            var userid = Users.Users[0].userid;
                            if (userid != "") {
                                //if the user already exists, then forward to the userid
                                $.ajax({
                                    type: "POST",
                                    url: getUrlToCall("Services.asp"),
                                    dataType: "application/x-www-form-urlencoded",
                                    data: "Action=ForwardOdpToUser&UID=" + userid + "&OdpID=" + $("#odpsToForward")[0].value,
                                    async: false,
                                    success: function(information) {
                                        showModal(information);
                                    },
                                    //all forwarding mechanism is on the server-side for security 
                                    failure: function(error) { showModal(error); }
                                });
                            }
                        }
                        else {
                            //create new user
                            $.ajax({
                                type: "POST",
                                url: getUrlToCall("Services.asp"),
                                dataType: "application/x-www-form-urlencoded",
                                data: "Action=CreateUserWithEmail&EMAIL=" + emailAddress,
                                async: false,
                                success: function(userid) {
                                    //all forwarding mechanism is on the server-side for security
                                    $.ajax({
                                        type: "POST",
                                        url: getUrlToCall("Services.asp"),
                                        dataType: "application/x-www-form-urlencoded",
                                        data: "Action=ForwardOdpToUser&UID=" + userid + "&OdpID=" + $("#odpsToForward")[0].value,
                                        async: false,
                                        success: function(information) {
                                            showModal(information);
                                        },
                                        //all forwarding mechanism is on the server-side for security 
                                        failure: function(error) { showModal(error); }
                                    });

                                },
                                failure: function(error) { showModal(error); }
                            });
                        }
                    }

                },
                //all forwarding mechanism is on the server-side for security 
                failure: function(error) { showModal(error); }
            });
        }
        else {
            showModal("The email address must be valid<div class='modalAction'><a onclick=promptBeforeDeleteForward('exForward')>Return</a></div>");
        }
    }
    else {
        document.forms['forward_form'].OdpToForward.value = $("#odpsToForward")[0].value;
        document.forms['forward_form'].submit();
    }
}

function deleteOdp(userID, msgsIDs, page) {

    switch (page) {
        case 'outbox':
            $.ajax({
                type: "POST",
                url: getUrlToCall("Services.asp"),
                dataType: "application/x-www-form-urlencoded",
                data: "Action=deleteMsgFromOutbox&MSGID=" + msgsIDs.toString() + "&UID=" + userID,
                async: false,
                failure: function(error) { showModal(error); }
            });
            //clear delete string
            $("#odpsToDelete")[0].value = '';
            //get msgs again
            //GetOutboxForUser(userID, 'Date');
            $(msgsIDs.split(',')).each(function() {
                $($("[id$='msg_" + this + "']")[0].parentNode.parentNode).slideUp("slow").remove();
            });
            break;
        case 'inbox':
            $.ajax({
                type: "POST",
                url: getUrlToCall("Services.asp"),
                dataType: "application/x-www-form-urlencoded",
                data: "Action=deleteMsgFromInbox&MSGID=" + msgsIDs.toString() + "&UID=" + userID,
                async: true,
                failure: function(error) { showModal(error); }
            });
            //clear delete string
            $("#odpsToDelete")[0].value = '';
            //get msgs again
            //GetInboxForUser(userID, 'Date');
            $(msgsIDs.split(',')).each(function() {
            $($("[id$='msg_" + this + "']")[0].parentNode.parentNode).slideUp("slow").remove();
            });
            break;
    };

    $.modal.close();
}
//validates email address for correct structure
function isEmail(Mail) {
    Mail = Mail.toLowerCase();
    return (Mail.search(/^([a-z]+)([a-z0-9\-\_\.]{1,100})([a-z0-9]+)\@([a-z0-9]+)([a-z0-9\-\.]*)([a-z0-9]+)\.([a-z]{2,6})$/) != -1);
}
//show odp from inbox/outbox
function showOdp(OdpId, ReffID, PurposeID) {
    //log
    LogOdpViewing(OdpId);
    if (PurposeID == 3) { //if it's forward
        //get the parentID recursively. ** note that this method has a flaw as it dosn't tell beween odp and a re: **
        $.ajax({
            type: "POST",
            url: getUrlToCall("Services.asp"),
            dataType: "application/x-www-form-urlencoded",
            data: "Action=getOdpParentID&odpid=" + OdpId,
            async: false,
            success: function(parentID) {
                OdpId = parentID;
            },
            failure: function(error) { showModal(error); }
        });
    }
    
    //fill-in fields and submit the form
    document.viewodp["OdpId"].value = OdpId;
    document.viewodp["Des"].value = $("td#descriptionTD")[0].innerText;
    document.viewodp["Addressees"].value = '1 ' + ReffID;
    document.viewodp["ReffID"].value = ReffID;
    document.viewodp["RP"].value = $("#userID")[0].content;
    document.viewodp["PurposeID"].value = PurposeID;
    if (PurposeID == 2) {
        document.viewodp.action = "ViewReply.asp";
    }
    document.viewodp.submit();
}
//add odp to to list (inbox / outbox pages)
function addRemoveItem(listType, itemID) {
    switch (listType) {
        case 'addressees':
            if (!itemInList('addressees', itemID)) {
                htmlToAppend = addresseeID + ",";
                $("#addressees")[0].value += htmlToAppend;
            }
            else {
                removeItemFromList('addressees', itemID);
            }
            break;
        case 'delete':
            //debugger;
            if (!itemInList('deleteOdp', itemID)) {
                htmlToAppend = itemID + ",";
                $("#odpsToDelete")[0].value += htmlToAppend;
            }
            else {
                removeItemFromList('deleteOdp', itemID);
            }
            break;
        case 'forward':
            if (!itemInList('forwardOdp', itemID)) {
                htmlToAppend = itemID + ";";
                $("#odpsToForward")[0].value += htmlToAppend;
            }
            else {
                removeItemFromList('forwardOdp', itemID);
            }
            break;
    }
}
function removeItemFromList(listType, itemID) {
    switch (listType) {
        case 'addressees':
            List = $("#addressees")[0].value.split(",");
            List.removeItems([itemID]);
            $("#addressees")[0].value = List.toString();
            break;
        case 'deleteOdp':
            List = $("#odpsToDelete")[0].value.split(",");
            List.removeItems([itemID]);
            $("#odpsToDelete")[0].value = List.toString();
            break;
        case 'forwardOdp':
            List = $("#odpsToForward")[0].value.split(",");
            List.removeItems([itemID]);
            $("#odpsToForward")[0].value = List.toString();
            break;
    }
}

//checks if the addressee is already on the list
function itemInList(listType, itemID) {
    switch (listType) {
        case 'addressees':
            return $.inArray(eval("'" + itemID + "'"), $("#addressees")[0].value.split(",")) != -1;
            break;
        case 'deleteOdp':
            return $.inArray(eval("'" + itemID + "'"), $("#odpsToDelete")[0].value.split(",")) != -1;
            break;
        case 'forwardOdp':
            return $.inArray(eval("'" + itemID + "'"), $("#odpsToForward")[0].value.split(",")) != -1;
            break;
    }
}



function bindExpertHoverEvent() {
    $(".expertName").hover(function() {
        $(this).addClass('expertHovered');
        //var baseHtml = $(this).html();
        //if (baseHtml.indexOf("Default addressee") == -1) {
        //   baseHtml += "</><a title='Click here to add this expert to your default addressees' onclick='makeDefaultAddressee(" + $(this)[0].expertID + "," + $(this)[0].id + ");'><small>Make default addressee</small></a>";
        //}
        //else {
        //    baseHtml += "</><a onclick='removeDefaultAddressee(" + $(this)[0].expertID + "," + $(this)[0].id + ");'><small> remove</small></a>";
        //}
        //$(this)[0].innerHTML = baseHtml;
    }, function() {
        $(this).removeClass('expertHovered');
        //var baseHtml = $(this).html();
        //$(this).html(baseHtml.split("</>")[0]);
    });
}
/**********************************************************
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
/**********************************************************/
//identify browser
var isIE6 = navigator.appVersion.indexOf('MSIE 6.0') == -1 ? false : true;
$(document).ready(function() {

    //for admin page
    $("[id^='Admin-SubPanel']").hide();
    $("input[id$='-date']", "#admin-content-procedures").css("background-color", "transparent");



    //registration fields
    $("[id^='Registration_'][showLength='true']").each(function() {
        this.parentElement.innerHTML += "<small class='fieldLength' style='font-weight:bold;'>(" + this.maxLength + ")</small>";
    });
    $("[id^='Registration_']").addClass("RegistrationField");

    $("[id^='Registration_'][showLength='true']").keyup(function(event) {
        if (event.target.value != undefined) {
            $(event.target.parentElement.children)[1].innerHTML = "(" + (event.target.maxLength - event.target.value.length) + ")";
        }
    });
    //commentsLength
    $("#commentsLength").html("<b><small>(" + $("#reportComments").attr("maxLength") + ")</small></b>");
    $("#reportComments").keyup(function(event) {
        if (event.target.value != undefined) {
            //debugger;
            html = "<b><small>(" + ($(this).attr("maxLength") - event.target.value.length) + ")</small></b>";
            $("#commentsLength").html(html);
        }
    });

    //bind abc filters to events
    $("a", "#ABCTable").click(function() {
        getDoctorsByLetter(this.innerHTML, lastDoctorsLevelQuery, 0, 0, 0);
    });
    //show menu scripts
    $("li", "#mainNavbar").hover(function() {
        //grab the location of the hovered li
        left = $(this)[0].offsetLeft;
        $('div[id^="secNavbar_"]').hide();
        //remove class Selected from all top tabs
        $('li[id^="li_"]').removeAttr("class");
        //add the css class to the li that was hover
        $(this).addClass("Selected");
        var secMenu = $(this)[0].secmenu;
        //FF fix
        if (secMenu == undefined) {
            secMenu = $(this).attr("secmenu");
        }
        secMenu = $('div[id$="secNavbar_' + secMenu + '"]');
        if ($("li:visible", "#mainNavbar").length != 1) {
            if (trim($(this)[0].innerText) == "Help") {
                secMenu.css({ 'left': left - 50, 'position': 'relative' });
            }
            else {
                secMenu.css({ 'left': left, 'position': 'relative' });
            }

        }
        else {
            secMenu.css({ 'left': left, 'position': 'relative' });
        }

        secMenu.show();
    });
    //check if the page is index page and load domain information
    //debugger;
    if ($("#isIndex[value='true']").length > 0) {
        //get domain specific information
        getDomainInformation('index');
    }

    //check for the session var on the server to activate this feature
    var showSessionPrompt = checkSessionVar("ShowSessionPrompt");
    if (showSessionPrompt == 1) {
        //Session timer to show alert 5 min before it ends
        sessionQtr = $("#SessionTimeout").attr('content') / 4;
        setTimeout("promptBeforeSessionTimeout('" + sessionQtr + "');", ($("#SessionTimeout").attr('content') - sessionQtr) * 60000);
    }

    //get version
    footerVersionCheck(false);

    //login creds
    $("#btnLogin").click(Login);
    //check username in the db
    $("#Registration_Username").keyup(function() {
        var username = Url.encode($("#Registration_Username").val());
        if (username.length > 0) {
            $("#UsernameAjaxLoader").show();
            setTimeout('checkUserName(\'' + username + '\')', 50);
        }
    })
    var timeoutID; //for hiding the user profile tooltip window
    $(".mailPersonLink").hover(function() {
        clearTimeout(timeoutID);
        timeoutID = setTimeout("getUserProfile(" + $(this)[0].expertID + "," + window.event.x + "," + window.event.y + ")", 1000);
    },
    function() {
        clearTimeout(timeoutID);
        timeoutID = window.setTimeout('hideTooltip();', 1500);
    });
});

function insertSessionVar(sessionVar, value) {
    //alert("insert value");
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=insertSessionVar&Var=" + sessionVar + "&value=" + value,
        async: false,
        failure: function(error) { showModal(error); }
    });
}
function Login(fromPasswordChange, newPassword) {
    //if came from password change, put the new password in the password input
    if (fromPasswordChange) {
        $("#Password").val(newPassword);
    }
    var qs = new Querystring();
    var username = Url.encode($("#Username").val());
    var password = $("#Password").val();
    //sql injection check
    if (username.indexOf("'") != -1 || username.indexOf("\"") != -1 || password.indexOf("'") != -1 || password.indexOf("\"") != -1) {
        return showModal("Invalid characters. Check your credentials.");
    }
    if (username && password) {
        $.ajax({
            type: "POST",
            url: getUrlToCall("Services.asp"),
            dataType: "application/x-www-form-urlencoded",
            //verifyUser also returns whether the password need to be changed
            data: "Action=verifyUser&U=" + username + "&P=" + password, //domain is already stored in the session
            async: true,
            success: function(information) {
                var expiration;
                var userID;
                if (information.indexOf(',') != -1) {
                    msg = information.split(',')[0];
                    expiration = information.split(',')[1];
                    userID = information.split(',')[2];
                }
                else {
                    msg = information;
                }

                switch (msg) {
                    case "credsWrong":
                        showModal("The user name or password is incorrect. Please try again.", "Incorrect Details");
                        break;
                    case "credsGood":
                        var agent;
                        var version;
                        try {
                            agent = new ActiveXObject("MDAgent.Agent");
                        }
                        catch (Err) {
                            showModal("<div class='Caption'>No client detected</div><div><a href='download.asp' style='color:blue;text-decoration:underline;'>Click here</a> to download the latest version of the MCIR client</div>");
                            return false;
                            version = "0";
                        }
                        if (agent) {
                            version = agent.GetVersion;
                            agent = null;
                            //check if a cookie has been set to stay with an inupdated version of the client
                            var cookie = readCookie('staywithcurrentversion');
                            if (cookie) {

                                document.Index["DoNotUpdate"].value = 'true';
                            }
                            else {
                                document.Index["DoNotUpdate"].value = 'false';
                            }
                        }
                        //check for password expiration date
                        if (eval(expiration.toLowerCase())) {
                            changePasswordPrompt(userID);
                            return false;
                        }
                        else {
                            document.Index.action = getUrlToCall("Login.asp");
                            document.Index["Password"].value = password;
                            document.Index["Version"].value = version;
                            document.Index.submit();
                        }
                        break;
                    case "DomainIsInvalid":
                        showModal("Either the URL is wrong or your security session has expired due to inactivity. Please check your URL and refresh you web browser.");
                        break;
                }
            },
            failure: function(error) { showModal(error); }
        });
    }
    else {
        showModal("Please enter your user name and password.", "Missing Details");
    }
}
//change password prompt
function changePasswordPrompt(UserID) {
    stringHtml = new StringBuilder();
    stringHtml.append("<div><small>You must change it for security reasons</small></div><br/>")
    stringHtml.append("<div>");
    stringHtml.append("<table class='ChangePasswordTbl'>");
    stringHtml.append("<tr>");
    stringHtml.append("<td>Old Password</td>");
    stringHtml.append("<td><input type='password' id='Expired_Old' type='text' /></td>");
    stringHtml.append("</tr>");
    stringHtml.append("<tr>");
    stringHtml.append("<td>New Password</td>");
    stringHtml.append("<td><input type='password' id='Expired_Password' type='text' /></td>");
    stringHtml.append("</tr>");
    stringHtml.append("<tr>");
    stringHtml.append("<td>Confirm Password</td>");
    stringHtml.append("<td><input type='password' id='Expired_Confirmation' type='text' /></td>");
    stringHtml.append("</tr>");
    stringHtml.append("</table>");
    stringHtml.append("</div>");
    showModal(stringHtml.toString(), "Password expired", "changePasswordContinueButtonAction(" + UserID + ")", "continue");
}
function changePasswordContinueButtonAction(UserID) {
    Log("Services.asp", 4, "PASSWORD CHANGE", escape("Trying to change password"));
    var oldPassword = $("#Expired_Old").val();
    var newPassword = $("#Expired_Password").val();
    var confirmationPassword = $("#Expired_Confirmation").val();

    if (newPassword != confirmationPassword || jQuery.trim(newPassword).length < 8) {
        var html = "";
        if (newPassword != confirmationPassword) {
            html += "<p>The password and confirmation password must be identical, please try again.</p>";
        }
        if (jQuery.trim(newPassword).length < 8) {
            html += "<p>Your password must contain at least eight digits or characters.</p>";
        }
        showModal(html, "Password expired", "nothing")
        setTimeout('changePasswordPrompt(' + UserID + ')', 1500);
    }
    else {
        changePassword(UserID, oldPassword, newPassword, false);
    }
}

function changePassword(UserID, OldPassword, NewPassword, IsRecovery) {

    if (IsRecovery) {
        if (!(jQuery.trim(OldPassword).length > 7)) {
            showModal("Your password must contain at least eight digits or characters.");
            return false;
        }
        else if (OldPassword != NewPassword) {
            showModal("The password and confirmation password must be identical.");
            return false;
        }
    }

    //update password in db
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=updatePassword&UID=" + UserID + "&NEWPASS=" + NewPassword + "&PASS=" + OldPassword,
        async: true,
        success: function(information) {
            //debugger;
            if (information == 'done') {
                if (IsRecovery) {
                    showModal("Password updated", null, "location='index.asp';", "Go to login");
                }
                else {
                    //
                    //login
                    Login(true, NewPassword);
                }
                Log("Services.asp", 4, "PASSWORD CHANGE", "Password changed");
            }
            else {
                Log("Services.asp", 4, "ERROR", "An error has occured while trying to update the password.");
                showModal("An error has occured while trying to update your password. Please check your password and try again.");
            }

        },
        failure: function(error) { $("#ajaxLoaderDiv").hide(); showModal(error); }
    });
}
//before session times out show an alert
function promptBeforeSessionTimeout(SessionQtr) {
    //if not logged in, refresh the page, else show message
    if ($("meta#userID").attr('content') != "") {
        var str = "Your session will timeout in " + SessionQtr + " minutes.<div  class='modalAction'><a onclick='location.reload();'>Refresh session</a><a href='RedirectToLogin.asp'>Log off</a></div>";
        showAltModal(str);
        setTimeout("deleteOdpOutFolder();", SessionQtr * 60000);
    }
    else {
        location.reload();
    }
}

//send password function serves as invoker for the sendpasswordaction,
//this is to show some progress during the action
function sendPassword() {
    var sendPasswordHTML = "Forgot your password?<br/> <small>Enter your username and email address and we will help you recover it.</small><br /><table style='width:100%;'><tr><td>Username:</td><td align='right'><input type='text' id='password-reminder-username' /></td></tr><tr><td>Email:</td><td align='right'><input type='text' id='password-reminder-email' /></td></table>"
    //$("#ajaxLoaderDiv").show();
    //simulate latency
    showModal(sendPasswordHTML, "Password reminder", "sendPasswordAction()", "Remind me");
}
function deleteOdpOutFolder() {
    try {
        mdhtml = new ActiveXObject("MDHTML.MDHTMLCtrl.1");
        mdhtml.DeleteDirectoryContent("c:\\program files\\medcon\\emedcon\\odp\\in\\");
        mdhtml = null;
    }
    catch (e) {
        //log here
    }

    //$.modal.close();
    $("#altModal").hide();
    //showModal("odp out folder was deleted! HA HA HA!");
    location.href = 'index.asp';
}
function sendPasswordAction() {
    var username = $("#password-reminder-username")[0].value;
    var email = $("#password-reminder-email")[0].value;
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=sendPassword&U=" + username + "&E=" + email,
        async: true,
        success: function(information) { /*$("#ajaxLoaderDiv").hide();*/showModal(information); },
        failure: function(error) { /*$("#ajaxLoaderDiv").hide();*/showModal(error); }
    });
}
function checkUserName(username) {
    username = Url.encode(username);
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=checkusername&U=" + username,
        async: true,
        //red for taken nickname, green for avaiable
        success: function(userExist) {
            $("#UsernameAjaxLoader").hide();
            cssClass = "usernameExists";
            if (userExist == "True") {
                $("#Registration_Username").addClass(cssClass);
            }
            else {
                $("#Registration_Username").removeClass(cssClass);
            }
        },
        failure: function(error) { showModal(error); }
    });
}
//make an expert default addressee for user
function makeDefaultAddressee(expertID, expertTr) {
    var DefaultAddressee = "<b style='color:gray;padding-left:10px;'>Default addressee</b>";
    var userID = $("#userID")[0].content;
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=makeDefaultAddressee&UID=" + userID + "&EI=" + expertID,
        async: true,
        success: function(information) {
            //add the "default addressee" to the td
            if (expertTr) {
                expertTr.innerHTML = expertTr.firstChild.nodeValue + DefaultAddressee;
            }
        },
        failure: function(error) { showModal(error); }
    });
}
//search mails on outbox \ inbox
function searchMails() {
    rows = $("tr", "#msgsTable").hide();
    searchterm = $("#search-mails-box").val().toLowerCase();
    if (searchterm.length > 0) {
        for (i = 0; i < rows.length; i++) {
            if (rows[i].innerText.toLowerCase().indexOf(searchterm) != -1) {
                $(rows[i]).removeHighlight().highlight(searchterm).show();
            }
        }
    }
    else {
        rows.removeHighlight().show();
    }
    //highlight searchterm
}
function showSearchDiv() {
    $("#search-mails").slideDown('fast');
    setTimeout('$("#search-mails-box").focus();', 500);


}
function hideSearchDiv() {
    $("#search-mails").slideUp('fast');
    $("tr", "#msgsTable").show();

}
function removeDefaultAddressee(expertID, expertTr) {
    var userID = $("#userID")[0].content;
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=removeDefaultAddressee&UID=" + userID + "&EI=" + expertID,
        async: true,
        success: function(information) {
            //remove the "default addressee" from the td
            if (expertTr) {
                expertTr.innerHTML = expertTr.firstChild.nodeValue;
            }
        },
        failure: function(error) { showModal(error); }
    });
    //remove expert from list of default addressees
}
//odp information
function fillOdpInformationBar(OdpID) {
    if (OdpID != undefined) {
        $.ajax({
            type: "POST",
            url: getUrlToCall("Services.asp"),
            dataType: "application/x-www-form-urlencoded",
            data: "Action=GetOdpInfo&ODPID=" + OdpID,
            async: true,
            success: function(odpinformation) {
                if (odpinformation.length > 0) {
                    var odpInfoTemp = eval('(' + odpinformation + ')');
                    var odpInfo = odpInfoTemp.OdpInformation;
                }
                $("#Description").html("<b>Description:</b> " + odpInfo.Description);
                $("#UploadDate").html("<b>Upload Date:</b> " + odpInfo.UploadDate);
                $("#HospitalName").html("<b>Hospital of origin:</b> " + odpInfo.HospitalName);
                $("#Sent-from").html("<b>Sender:</b> " + odpInfo.FullName);

            },
            failure: function(error) { showModal(error); }
        });
        //get attachments  attachments  P_GetAttachmentsByOdpID @OdpID
        $.ajax({
            type: "POST",
            url: getUrlToCall("Services.asp"),
            dataType: "application/x-www-form-urlencoded",
            data: "Action=GetAttachmentsByOdpID&ODPID=" + OdpID,
            async: true,
            success: function(attachmentsData) {
                var attachmentsRaw = eval('(' + attachmentsData + ')');
                var attachments = attachmentsRaw.attachments;
                //travarse through all the attachments and create links to download
                htmlToAppend = "<ul>";
                $(attachments).each(function() {
                    var fileName = this.path.substr(this.path.lastIndexOf("/") + 1);
                    htmlToAppend += "<li><img alt='paperclip' src='images/paperclip.png'/><a target='_blank' href='" + this.path + "'>" + fileName + "</a></li>";
                });
                htmlToAppend += "</ul>";
                $("#attachments").html(htmlToAppend);
            },
            failure: function(error) { showModal(error); }
        });
    }
    else {
        //don't even show the status bar
        $("#odpInformationDiv").hide();
    }

}

function hideOdpInformationDiv() {
    //$(".pinButton").hide();
    $("#odpInformation").toggle();
    if ($(".pinButton").html() == 'Hide') {
        $(".pinButton").html('Show');
    }
    else {
        $(".pinButton").html('Hide');
    }
}
function AutoSendMethod() {
    if (document.frmAutoCD.Addressees.value != "-1" && document.frmAutoCD.Addressees.value != "") {
        document.frmAutoCD.AutoSendFlag.value = 1;
        document.frmAutoCD.submit();
    }
    else {
        //go to sendcase to 
        document.tmpAutoSend.tmpAuto.value = 1; //Fleg for SendCase page to continue AutoSend by pressing 
        //the Next button
        document.tmpAutoSend.submit();
    }
}
/**************************************************/
function SendCaseByAddresse() {
    var tmpStr;
    var tmpStrSource


    tmpStr = document.SendCase.dbAddressee.value;

    if (!tmpStr.match("-1")) {

        if (document.SendCase.ClientDicomSource.value == "")
            document.SendCase.submit();
        else {
            document.frmAutoCD.submit();
        }
    }
    else {
        document.location.href = "SendCase.asp";
    }
}
function ShowCv(ID) {
    document.frmCv.UserID.value = ID;
    document.frmCv.submit();
}
function ProfileURL(SessionFlag) {
    document.frmGoto.action = "Profile.asp";
    document.frmGoto.submit();
}
function InboxURL(SessionFlag) {
    document.frmGoto.action = "Inbox.asp";
    document.frmGoto.submit();
}
function OutboxURL(SessionFlag) {
    document.frmGoto.action = "Outbox.asp";
    document.frmGoto.submit();
}
function EditDetailsURL(SessionFlag) {
    document.frmGoto.action = "EditDetails.asp";
    document.frmGoto.submit();
}
/******************* show alerts within the jquery modal *********************/
function showModal(body, caption, closeButtonAction, closeButtonText) {
    $.modal.close();
    if (caption) {
        html = "<div class='modalCaption' style='padding:10px;'>" + caption + "</div>"
    }
    else {
        html = "<div class='modalCaption' style='padding:10px;'>System message</div>"
    }
    html += "<div class='modalContent'>" + body + "</div>";
    if (!closeButtonAction) {
        closeButtonAction = "$.modal.close();";

    }
    if (!closeButtonText) {
        closeButtonText = "close";
    }
    if (closeButtonAction != 'nothing') {
        html += "<a class='modalCloseButton' onclick=\"" + closeButtonAction + "\">" + closeButtonText + "</a>";
    }

    $(html).modal({ persist: true, close: false });
} //altModal
function showAltModal(body, caption, closeButtonAction, closeButtonText) {
    if (caption) {
        html = "<div class='modalCaption' style='padding:10px;'>" + caption + "</div>"
    }
    else {
        html = "<div class='modalCaption' style='padding:10px;'>System message</div>"
    }
    html += "<div class='modalContent'>" + body + "</div>";
    if (!closeButtonAction) {
        closeButtonAction = "$('#altModal').slideUp('slow');;";

    }
    if (!closeButtonText) {
        closeButtonText = "close";
    }
    html += "<a class='modalCloseButton' onclick=\"" + closeButtonAction + "\">" + closeButtonText + "</a>";
    $("#altModal").html(html);
    $("#altModal").slideDown('slow');
}


/****************navigation*/
function GotoRegistration() {
    document.location.href = "Registration.asp";
}


function MedconUrl() {
    document.location.href = "http://www.mckesson.com";
}
/* Client-side access to querystring name=value pairs
Version 1.3
28 May 2008
	
License (Simplified BSD):
http://adamv.com/dev/javascript/qslicense.txt
*/
function Querystring(qs) { // optionally pass a querystring to parse
    this.params = {};

    if (qs == null) qs = location.search.substring(1, location.search.length);
    if (qs.length == 0) return;

    // Turn <plus> back to <space>
    // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
    qs = qs.replace(/\+/g, ' ');
    var args = qs.split('&'); // parse out name/value pairs separated via &

    // split out each name=value pair
    for (var i = 0; i < args.length; i++) {
        var pair = args[i].split('=');
        var name = decodeURIComponent(pair[0]);

        var value = (pair.length == 2)
			? decodeURIComponent(pair[1])
			: name;

        this.params[name] = value;
    }
}

Querystring.prototype.get = function(key, default_) {
    var value = this.params[key];
    return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
    var value = this.params[key];
    return (value != null);
}

/* cookies */
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}
/* cookies */

/***************** new domain creation *****************/
function CreateNewDomain() {
    var domainName = $("#domainName").val();
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=CreateDomain&DN=" + domainName,
        async: true,
        success: function(domainID) {
            $("#insert-logo-button").click(function() {
                insertDomainInformation(1, $("#logoUrl").val(), domainID); //1 stands for logg
            });
            //and disable the prev div
            $("#domainName").attr("disabled", "true");
            $("#create-domain-button").attr("disabled", "true");

        },
        failure: function(error) { showModal(error); }
    });
}

function upgradePasswords() {
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=upgradePasswords&u=" + $("#username").val() + "&p=" + $("#password").val() + "&did=" + $("#domains-list").val(),
        async: true,
        success: function(information) {
            showModal(information);
        },
        failure: function(error) { showModal(error); }
    });
}
function insertDomainInformation(ContentType, Value, DomainID) {
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=InsertDomainInformation&CT=" + ContentType + "&V=" + Value + "&DI=" + DomainID,
        async: true,
        success: function(information) {
            //disable the prev div
            $("#logoUrl").attr("disabled", "true");
            $("#insert-logo-button").attr("disabled", "true");
            //announce
            $("#announcment").html("You are good to go!");
        },
        failure: function(error) { showModal(error); }
    });
}

function CheckForLocal(base) {
    if (MDAgent == null)
        return;

    var OdpIdStr;
    for (i = 6; i < document.forms.length; i++) {

        if (MDAgent.IsLocal(document.forms[i].OdpId.value)) {

            OdpIdStr = base + document.forms[i].OdpId.value;

            //added
            OdpIdStr = "document.images." + OdpIdStr + (i - 4);

            try {
                eval(OdpIdStr).src = "images/HD_icon.gif";
            }
            catch (err) {
                //logging here
            }
        }
    }
}

function CheckForLacal(OdpID) {
    var MDAgent;
    var RetVal;

    MDAgent = null;

    MDAgent = new ActiveXObject("MDAgent.Agent");

    RetVal = MDAgent.IsLocal(OdpID);
    MDAgent = null;
    return RetVal;
}
//from inbox.asp

function ReplyOdp() {

    var temp = "";
    var cbStr;
    var DeleteListStr;
    var confirmFlag = true;
    var Reff;
    //var Counter;

    //Counter = 0;	
    DeleteFlag = 0;
    DeleteListStr = "";

    if (document.forms.length > 1) {
        for (i = 6; i < document.forms.length; i++) {

            cbStr = "document.forms[i].cb_" + document.forms[i].OdpId.value + ".checked";

            if (eval(cbStr)) {
                temp = temp + document.forms[i].OdpId.value + ";"
                //document.forms[i].OdpId.value + ";"
                reff = document.forms[i].ReffID.value;
                Des = document.forms[i].Des.value;
            }
        }
    }

    if (temp == "") {
        showModal("Please select the case you would like to reply to");
    }
    else {
        //ex = /;/;
        temp = temp.replace(ex, "");

        document.Reply_form.Addressees.value = temp;
        document.Reply_form.ReffID.value = reff;
        document.Reply_form.Des.value = Des;
        document.Reply_form.submit();
    }
}
function LinkTo(str) {
	
	window.location.href = str;
}

function MsgBox2(str) {
    alert(str);
}
//admin page
function showPanel(sender, EntityID) {
    $("[id^='admin-content-']").hide();
    $("#admin-content-" + sender.innerHTML.toLowerCase()).show();
    $("[id='Admin-SubPanel-" + sender.innerHTML + "']").show();

    switch (sender.innerHTML.toLowerCase()) {
        case 'users':
            getUsersByDomainID(EntityID);
            break;
        case 'procedures':
            $("#Admin-SubPanel-Procedures").hide();
            break;
    }
}
function getUsersByDomainID(DomainID) {
    $.ajax({
        type: "POST",
        url: getUrlToCall("Services.asp"),
        dataType: "application/x-www-form-urlencoded",
        data: "Action=GetUsersByDomainID&DID=" + DomainID,
        async: true,
        success: function(information) {
            if (information.length > 0) {
                var usersInformation = eval('(' + information + ')');
            }
            Users = usersInformation.Users;
            var htmlToAssign = new StringBuilder();
            htmlToAssign.append("<table id='doctorsTbl'>");

            $(Users).each(function(index, element) {
                if (element.Name != undefined) {
                    htmlToAssign.append(GetUsersHTML(element, index));
                }
            });
            htmlToAssign.append("</table>");
            $("#usersTable").html(htmlToAssign.toString());
        },
        failure: function(error) { showModal(error); }
    });
}
//jquery plugin to reverse dom elements - http://lab.arc90.com/2008/05/jquery_reverse_order_plugin.php
(function($) {
    $.fn.reverseOrder = function() {
        return this.each(function() {
            $(this).prependTo($(this).parent());
        });
    };
})(jQuery);


/* Client-side access to querystring name=value pairs
Version 1.3
28 May 2008
	
License (Simplified BSD):
http://adamv.com/dev/javascript/qslicense.txt
*/
function Querystring(qs) { // optionally pass a querystring to parse
    this.params = {};

    if (qs == null) qs = location.search.substring(1, location.search.length);
    if (qs.length == 0) return;

    // Turn <plus> back to <space>
    // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
    qs = qs.replace(/\+/g, ' ');
    var args = qs.split('&'); // parse out name/value pairs separated via &

    // split out each name=value pair
    for (var i = 0; i < args.length; i++) {
        var pair = args[i].split('=');
        var name = decodeURIComponent(pair[0]);

        var value = (pair.length == 2)
			? decodeURIComponent(pair[1])
			: name;

        this.params[name] = value;
    }
}

Querystring.prototype.get = function(key, default_) {
    var value = this.params[key];
    return (value != null) ? value : default_;
}

Querystring.prototype.contains = function(key) {
    var value = this.params[key];
    return (value != null);
}

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode: function(string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function(string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}