



function showProgress() {
    //document.getElementById("progress").style.visibility = 'visible';
    document.getElementById("submit").disabled = true;
}

isLoad = false;
var cRoundClassName = "round";
var RootUrl = "";
var test = 1200;
var timerID = null;
var loadActiveXError = "";

function findObj(theObj, theDoc) {
    var p, i, foundObj;
    if (!theDoc) theDoc = document;
    if ((p = theObj.indexOf("?")) > 0 && parent.frames.length) {
        theDoc = parent.frames[theObj.substring(p + 1)].document;
        theObj = theObj.substring(0, p);
    }
    if (!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
    if (theDoc[theObj] && typeof (theDoc[theObj]) == "string" && theDoc.all) foundObj = theDoc.all[theObj]; // fix for same class and id name
    for (i = 0; !foundObj && i < theDoc.forms.length; i++)
        foundObj = theDoc.forms[i][theObj];
    for (i = 0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)
        foundObj = findObj(theObj, theDoc.layers[i].document);
    if (!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
    return foundObj;
}
//check if element has specific class name
function haveClassName(element, classname) {
    var pattern = new RegExp("\\b" + classname + "\\b");
    if (!element || !element.className) return;
    return pattern.test(element.className) ? true : false;
}
//set css class cssClassName to the object with id objectId
function SetCssClass(objectId, cssClassName) {
    var object = $get(objectId);
    if (!object) return;
    object.className = cssClassName;
}

// Retrieve a specific element by it's class
function getElementsByClass(node, searchClass, tag) {
    var classElements = new Array(); var elements = node.getElementsByTagName(tag); // use "*" for all elements
    var pattern = new RegExp("\\b" + searchClass + "\\b");
    for (i = 0, j = 0; i < elements.length; i++) if (pattern.test(elements[i].className)) classElements[j++] = elements[i];
    return classElements;
}

function showHideLayers() {
    var i, visStr, obj, args = showHideLayers.arguments;
    for (i = 0; i < (args.length - 2); i += 3) {
        if ((obj = findObj(args[i])) != null) {
            visStr = args[i + 2];
            if (obj.style) {
                obj = obj.style;
                if (visStr == 'show') visStr = 'visible';
                else if (visStr == 'hide') visStr = 'hidden';
            }
            obj.visibility = visStr;
        }
    }
}

function switchImage(imgName) {
    var objFooter = $get('footer');
    var tblTemp = $get('tblList');
    var window = getPageSize();
    var windowHeight = window[3];
    var tableHeight = tblTemp.clientHeight + 190;
    var objFooter = $get('footer');
    //get footer y position
    var footeryPosition = findPosY(objFooter);
    if (document.images) {
        if (document.images[imgName].src.indexOf("VisualStyles/ThemeC/Images/Buttons/Icons/imgExpand.png") > 0) {
            //document.images[imgName].src.replace = "Image/collapse.gif";	  
            document.images[imgName].src = document.images[imgName].src.replace('imgExpand.png', 'imgCollapse.png');
            if (footeryPosition < tableHeight + 78) {
                objFooter.style.marginTop = (parseFloat(objFooter.style.marginTop.replace('px', '')) + 52) + 'px';
            } else {
                objFooter.style.marginTop = (objFooter.style.marginTop.replace('px', '') - 52) + 'px';
            }
        }
        else {
            document.images[imgName].src = document.images[imgName].src.replace('imgCollapse.png', 'imgExpand.png');
            if (footeryPosition < windowHeight) {
                objFooter.style.marginTop = windowHeight - tableHeight - 60 + 'px';
            } else {
                objFooter.style.marginTop = (parseFloat(objFooter.style.marginTop.replace('px', '')) - 30) + 'px';
            }

        }
    }
}

function switchLayers() {
    var i, obj, args = switchLayers.arguments;
    for (i = 0; i < args.length; i += 1) {
        obj = $get(args[i]);
        if (!obj || !obj.style || !obj.tagName) continue;
        if (obj.tagName == 'TR') {
            // switching table rows
            if (obj.style.display == 'none') {
                try { obj.style.display = 'table-row'; } // for all regular browsers (IE causes error) 
                catch (e) { obj.style.display = 'block'; } // for IE6 and lower, IE7 will probably support table-row
            } else obj.style.display = 'none';
        }
        else if (obj.style.display == 'none') obj.style.display = 'block'; else obj.style.display = 'none'; // everything else should be layer
    }
}

function showLayer() {
    var i, objLayer, args = showLayer.arguments;
    for (i = 0; i < (args.length); i += 1) {
        objLayer = $get(args[i]);
        if (objLayer) {
            if (objLayer.style.display != 'block') {
                objLayer.style.display = 'block';
                //if (shouldRound(objLayer)) roundCorner(objLayer);
            }
        }
    }
}

function switchRow(imageID, rowID) {
    switchImage(imageID);
    switchLayers(rowID);
}

function switchRow2(rowID) {
    //switchImage(imageID);
    switchLayers(rowID);
}

//function setFocus(theObj, theDoc) {
//    
//	var theEl = findObj(theObj, theDoc);
//	if (theEl != null) {
//		try  { theEl.focus(); }
//		catch(e) { } //do nothing in case control is not visible or enabled
//	}
//}

/* Peter-Paul Koch BrowserDetect object. */
// http://www.quirksmode.org/js/detect.html
// BrowserDetect.init() needed in code for using this script;

var BrowserDetect = {
    init: function() {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function(data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function(dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
		{ string: navigator.userAgent,
		    subString: "OmniWeb",
		    versionSearch: "OmniWeb/",
		    identity: "OmniWeb"
		},
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari"
		},
		{
		    prop: window.opera,
		    identity: "Opera"
		},
		{
		    string: navigator.vendor,
		    subString: "iCab",
		    identity: "iCab"
		},
		{
		    string: navigator.vendor,
		    subString: "KDE",
		    identity: "Konqueror"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{
		    string: navigator.vendor,
		    subString: "Camino",
		    identity: "Camino"
		},
		{		// for newer Netscapes (6+)
		    string: navigator.userAgent,
		    subString: "Netscape",
		    identity: "Netscape"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Gecko",
		    identity: "Mozilla",
		    versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
		    string: navigator.userAgent,
		    subString: "Mozilla",
		    identity: "Netscape",
		    versionSearch: "Mozilla"
		}
	],
    dataOS: [
		{
		    string: navigator.platform,
		    subString: "Win",
		    identity: "Windows"
		},
		{
		    string: navigator.platform,
		    subString: "Mac",
		    identity: "Mac"
		},
		{
		    string: navigator.platform,
		    subString: "Linux",
		    identity: "Linux"
		}
	]

};

function onPageLoad() {
    BrowserDetect.init();
    setTextBoxes();
    setFocus();
    setFooter();

}
function setFooter() {
    var objFooter = $get('ctl00_cphBlank_ucFooter_footer');
    if (!objFooter) return;
    //get footer y position
    var footeryPosition = findPosY(objFooter);
    //alert(footeryPosition);
    //get window dimensions
    var window = getPageSize();
    //alert(window);

    if (footeryPosition < window[3] - 60) {
        objFooter.style.marginTop = window[3] - footeryPosition - 60 + 'px';
    } else {
        objFooter.style.marginTop = 0 + 'px';
    } if (footeryPosition < window[3] - 60) {
        objFooter.style.marginTop = window[3] - footeryPosition - 60 + 'px';
    } else {
        objFooter.style.marginTop = 0 + 'px';
    }


}
function setFooterForList() {
    var objFooter = $get('footer');
    if (!objFooter) return;
    var tblTemp = $get('tblList');
    var footeryPosition = findPosY(objFooter);
    var window = getPageSize();
    //we should increase or decrease footer top margin         
    //if footeryPosition + marginTop 
    //    if (window[3] < 90 + tblTemp.clientHeight ){
    //         objFooter.style.marginTop = 90 + tblTemp.clientHeight + 'px';
    //    } else {
    //        objFooter.style.marginTop = window[3] - objFooter.clientHeight - tblTemp.clientHeight - 60 + 'px';
    //    }   
}

// Set focus on specified ClientId.
function setFocus(focusControlId) {
    if (!focusControlId || focusControlId == "") return;
    var objFocusControl = $get(focusControlId);
    if (!objFocusControl) return;
    try {
        objFocusControl.focus();
    }
    catch (e) {
        // for now JS exceptions are not handled.
    }
}

function setTextBoxes() {
    /*
    var doc = document;
    var elements = doc.getElementsByTagName("*");
    for (i=0; i < elements.length; i++) {
    element = elements[i];
    if (element.tagName == "INPUT" && (element.type == "text" || element.type == "password")) {
    if (!element.onfocus) element.onfocus = function() { onTextBoxFocus(this); }
    if (!element.onblur) element.onblur = function() { onTextBoxBlur(this) };
    }
    }*/
}

function onResize() {
    if (isLoad) window.location.reload(false);
}

// setting onTextBoxFocus style
function onTextBoxFocus(element) {
    if (element && element.style) element.style.backgroundColor = '#467c87';
}

// setting onTextBoxBlur style
function onTextBoxBlur(element) {
    if (element && element.style) element.style.backgroundColor = '#2c5d72';
}

function ShowSelected(selectObjectId) {
    var objSelect = $get(selectObjectId);
    if (!objSelect) return;
    if (objSelect.options[objSelect.selectedIndex].text == 'Practice') {
        divTitle.style.display = 'block';
        //ValidatorEnable(findObj('ctl00_cphLogin_ucRegister_rfvTitle'), true);
    }
    else {
        divTitle.style.display = 'none';
        //ValidatorEnable(findObj('ctl00_cphLogin_ucRegister_rfvTitle'), false);
    }
}


//move selected doctors from select-multiple to another select-multiple control
function moveDoctors(fromControlID, toControlID) {
    var fromControl = $get(fromControlID), toControl = $get(toControlID);
    //if (toControl.type == "select-multiple") {
    var fromSelectedItems = getSelectedListItems(fromControl);
    if (fromSelectedItems.length == 0) {
        alert('Please, select contact first.');
        return;
    }
    for (var i = 0; i < fromSelectedItems.length; i++) {
        var fromSelectedItem = fromSelectedItems[i];
        if (findListItemByValue(toControl, fromSelectedItem.value)) alert(fromSelectedItem.text + " can't be moved because it is already in the list.");
        else toControl.appendChild(fromSelectedItem); // only selectable and new should be moved
    }
}

function findListItemByValue(ctrl, value) {
    var resListItem = null;
    for (var i = 0; i < ctrl.length; i++) {
        473
        var listItem = ctrl[i];
        if (listItem.value == value) {
            resListItem = listItem;
            break;
        }
    }
    return resListItem;
}

function getSelectedListItems(ctrl) {
    var selectedItems = new Array(), selectedIndex = -1;
    for (var i = 0; i < ctrl.length; i++) {
        var listItem = ctrl[i];
        if (listItem.selected) selectedItems[++selectedIndex] = listItem;
    }
    return selectedItems;
}
function CheckUserFromList(listFrom, listTo) {
    lstFrom = document.getElementById(listFrom);
    lstTo = document.getElementById(listTo);
    var booltest = false;
    var fromSelectedItems = getSelectedListItems(lstFrom);
    if (fromSelectedItems.length == 0) {
        alert('Please select at least one preferred doctor.')
        return false;
    }
    for (var i = 0; i < fromSelectedItems.length; i++) {
        var fromSelectedItem = fromSelectedItems[i];
        if (findListItemByValue(lstTo, fromSelectedItem.value)) {
            alert(fromSelectedItem.text + " can't be moved because it is already in the list.");
            booltest = false;
            break;
        } else {
            booltest = true;
        }
    }
    return booltest
}
function findListItemByValue(ctrl, value) {
    var resListItem = null;
    for (var i = 0; i < ctrl.length; i++) {
        var listItem = ctrl[i];
        if (listItem.value == value) {
            resListItem = listItem;
            break;
        }
    }
    return resListItem;
}
//determines if multiselect list item is selectable
// "quirk" solution for not removing item from multiselect (unselectable attribute doesn't work by self)
function isListItemSelectable(listItem) {
    var bSelectable = false;
    if (listItem.attributes["style"]) {
        bSelectable = true;
    }
    return bSelectable;
}
function CheckSelection(list, source) {
    lstTo = document.getElementById(list);
    var fromSelectedItems = getSelectedListItems(lstTo);
    if (fromSelectedItems.length == 0) {
        alert('Please select at least one ' + source + ' doctor.');
        return false;
    } else {
        return true;
    }
}
function showNotification(notificationMessage) {
    var objNotification = $get('notification'); var objNotificationArea = $get('notificationArea');
    if (objNotification && objNotificationArea) {
        if (objNotification.style.display == 'block') return; // just a minor design fix
        objNotification.style.display = 'block';
        objNotificationArea.innerHTML = notificationMessage;
        roundCorner(objNotification.className);
    }
}

function openReferCasePopUp() {
    document.location = 'refer_case.aspx'; // for now no popup
}

function checkSearchForm(btnObject) {
    var txtFirstName = $get('txtFirstName');
    var txtLastName = $get('txtLastName');
    var txtEmail = $get('txtEmail');
    var btnSendReferral = $get(btnObject);
    if (txtFirstName.value != '' && txtLastName.value != '' && txtEmail.value != '') {
        btnSendReferral.disabled = false;
        btnSendReferral.className = "submitLiquid";
    }
    else {
        btnSendReferral.disabled = true;
        btnSendReferral.className = "submitLiquidDisable";
    }
}

function hasAttribute(attributes, attributeName, attributeIndex) {
    var bRes = false; attributeIndex = -1;
    for (var i = 0; i < attributes.length; i++) {
        var attribute = attributes[i];
        if (attribute.name == attributeName) {
            bRes = true;
            attributeIndex = i;
            break;
        }
    }
    return bRes;
}

function moveChildren(src, dest) {
    var moveCount = 0;
    while (src.hasChildNodes()) {
        var child = src.childNodes[0];
        child = src.removeChild(child);
        dest.appendChild(child);
        moveCount++;
    }
    return moveCount;
}

function disableControl(controlId) {
    var objControl = $get(controlId);
    if (objControl) objControl.disabled = true;
    setTimeout("enableControl('" + controlId + "')", 500);
}
function enableControl(controlId) {
    var objControl = $get(controlId);
    if (objControl) objControl.disabled = false;
}

/// Disable control in specified interval
function disableControlSetTimeout(controlId, interval) {
    setTimeout("disableControl('" + controlId + "')", interval);
}

/// When button is clicked disable it (prevents double click problems).
function onSubmitClick(control) {
    disableControlSetTimeout(control.id, 100);
}

var popUpWin = 0;

function popUpWindow(URLStr, left, top, width, height) {
    if (popUpWin) {
        if (!popUpWin.closed) popUpWin.close();
    }
    if (left == 0) left = (window.screen.width - width) / 2;
    if (top == 0) top = (window.screen.height - height) / 2;
    popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=yes,width=' + width + ',height=' + height + ',left=' + left + ', top=' + top + ',screenX=' + left + ',screenY=' + top + '');
}
function ShowHidePreferredDoctors() {
    var hiddenDiv = $get('divPreferred');
    hiddenDiv.style.display = 'block';
}
function ShowModalPopUp(location, vArgument, left, top, width, height) {
    if (left == 0) left = (window.screen.width - width) / 2;
    if (top == 0) top = (window.screen.height - height) / 2;

    window.showModalDialog(location, vArgument, 'resizable:yes;dialogHeight:' + height + 'px;dialogLeft:' + left + 'px;dialogTop:' + top + 'px;dialogWidth:' + width + 'px;status:no');
}

// populate hidden field from listbox values
function SaveListBoxValues(listboxId, hiddenFieldId) {
    var listbox = $get(listboxId);
    var hiddenField = $get(hiddenFieldId);

    if (listbox == null || hiddenField == null)
        return;
    hiddenField.value = "";
    for (i = 0; i < listbox.length; i++) {
        if (hiddenField.value == "") {
            hiddenField.value = listbox.options[i].value;
        }
        else {
            hiddenField.value += ";" + listbox.options[i].value;
        }
    }
}


function RefreshPage() {
    history.go(0);
}

// removes options from first select control which values are contained in followed controls 
function ClearExistingContacts() {
    if (arguments.length < 2) {
        alert("Must select at least two lists");
        return;
    }
    var clearingList = $get(arguments[0]);
    for (var i = 1; i < arguments.length; i++) {
        var listbox = $get(arguments[i]);
        for (var j = 0; j < listbox.length; j++) {
            for (var k = clearingList.length - 1; k >= 0; k--) {
                if (listbox.options[j].value == clearingList.options[k].value) {
                    clearingList.remove(k);
                    continue;
                }
            }
        }
    }
}

function showReferCase(divReferCaseID) {

    switchLayers(divReferCaseID);
}
function HideObject(selectObjectId) {
    var objSelect = $get(selectObjectId);
    if (!objSelect) return;
    objSelect.style.display = 'none';
}
function ShowObject(selectObjectId) {
    var objSelect = $get(selectObjectId);
    if (!objSelect) return;
    objSelect.style.display = 'block';
}

function MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; } 
    }
}
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}
function getPageSize() {

    var xScroll, yScroll;

    if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;
    if (self.innerHeight) {	// all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if (yScroll < windowHeight) {
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if (xScroll < windowWidth) {
        pageWidth = windowWidth;
    } else {
        pageWidth = xScroll;
    }


    arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight)
    return arrayPageSize;
}
//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll() {

    var yScroll;

    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
        yScroll = document.documentElement.scrollTop;
    } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
    }

    arrayPageScroll = new Array('', yScroll)
    return arrayPageScroll;
}

// calculate client window width and height and put it in the global values
function getClientWidthAndHeight() {
    clientWindowWidth = 0, clientWindowHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        clientWindowWidth = window.innerWidth;
        clientWindowHeight = window.innerHeight;
    } else if (document.documentElement &&
      (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        clientWindowWidth = document.documentElement.clientWidth;
        clientWindowHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        clientWindowWidth = document.body.clientWidth;
        clientWindowHeight = document.body.clientHeight;
    }
}
function MoveInfPanel(objectId) {
    obj = $get(objectId);
    if (!obj) return;
    getClientWidthAndHeight();
    //obj.style.left = 1250;

}

var cUpdateProgressTextID = 'updateProgressText';
var cUpdateProgress = 'divUpdateProgress';

// Set custom update progress text
function SetUpdateProgressText(updateProgressID, text) {
    var objUpdateProgress = $get(updateProgressID);
    if (objUpdateProgress) objUpdateProgress.innerHTML = text;
}

// Set default update progress text
function SetDefaultUpdateProgressText() {
    SetUpdateProgressText(cUpdateProgressTextID, "Please wait...");
}

// Hide update progress if refresh timer on case page is causing Ajax Postback. Otherwise, show update progress.
function SetUpdateProgressVisibility(sender, Args) {
    var objUpdateProgress = $get(cUpdateProgress);
    if (!objUpdateProgress || !objUpdateProgress.style || !timerID) return;
    objUpdateProgress.style.display = 'block';
    if (Args && Args._postBackElement && Args._postBackElement.id == timerID) {
        objUpdateProgress.style.display = 'none';
    }
}

// Executes on begin ajax request handle.
function beginAjaxRequestHandle(sender, Args) {
    //alert("begin request handle");
    SetUpdateProgressVisibility(sender, Args);

}

// Executes on endAjaxRequestHandle.
// Set default update progress text. Check if there is need for generating reports.
function endAjaxRequestHandle(sender, Args) {
    //alert("end request handle");
    SetDefaultUpdateProgressText();
}

//Create message for adding doctor(s) to the case group
function ConfirmAddToCaseGroup(prefferredlistboxid) {
    var numbSelected;
    var bReturnValue = false;
    var listBox = $get(prefferredlistboxid);
    var messageText = '';
    if (listBox == null) {
        return bReturnValue;
    }
    //get selected doctors from  list of prefferred doctors
    var selectedDoctors = getSelectedListItems(listBox);
    if (selectedDoctors.length == 0) {
        alert('Please, select at least one doctor form prefferred list.');
        return bReturnValue;
    }
    //count number of selected doctors
    numbSelected = selectedDoctors.length;
    for (var i = 0; i < selectedDoctors.length; i++) {
        //if doctor is colored in grey, it is already in casegroup
        if (selectedDoctors[i].style.color != '') {
            selectedDoctors[i].selected = false;
        } else {
            messageText += selectedDoctors[i].text + ',';
        }

    }
    if (messageText == '' && numbSelected > 0) {
        //user choose only users which are already in casegroup
        alert('Please, select at least one preferred doctor that is not in case group list.');
        bReturnValue = false;
    } else {
        //delete last characheter [,] from message
        messageText = messageText.substring(0, messageText.length - 1);
        messageText = 'Are you sure you want to add ' + messageText + ' to the case group?';
        if (confirm(messageText) == true) {
            bReturnValue = true;
        } else {
            bReturnValue = false;
        }
    }
    return bReturnValue;
}
//Change header icon on onmouseover event
function OnHeaderIconOver(img, name) {
    var currentImg;
    var imageName;
    //imageName = 
    currentImg = $get(img);
    if (currentImg == null) return;
    currentImg.firstChild.src = currentImg.firstChild.src.replace(name + '_up.gif', name + '_over.gif');
}

//Change header icon on onmouseover event
function OnHeaderIconOut(img, name) {
    var currentImg;
    var imageName;
    //imageName = 
    currentImg = $get(img);
    if (currentImg == null) return;
    currentImg.firstChild.src = currentImg.firstChild.src.replace(name + '_over.gif', name + '_up.gif');
}
//Change message header icon on onmouseover event
function OnMessageIcon(divId, classname) {

    var currentDiv;
    var imageName;
    //imageName = 
    divId = $get(divId);
    if (divId == null) return;
    divId.className = classname;
}
//Set pop up text on inbox pop up
function SetInboxPopUpText(message, hdnMessageNumberId, messageNumber) {
    var messageLabel = $get('lblMessage');
    messageLabel.innerHTML = message;
    var popMessageNumber = $get(hdnMessageNumberId);
    if (popMessageNumber == null) return;
    popMessageNumber.value = messageNumber;
}
function ExpireSession(location) {
    window.location = location;
}
//Populate patient detail 
function PopulatePatientDetail(mrn, firstname, lastname, dob, sex) {

    var lblMrn = $get('lblMrn');
    var lblFirstName = $get('lblFirstName');
    var lblLastName = $get('lblLastName');
    var lblDob = $get('lblDob');
    var lblSex = $get('lblSex');
    //alert(lblMrn.innerText);
    lblMrn.innerHTML = mrn;

    //alert(lblMrn.innerText);
    lblFirstName.innerHTML = firstname;
    lblLastName.innerHTML = lastname;
    lblDob.innerHTML = dob;
    lblSex.innerHTML = sex;

}

/// CodeAnalysis: When third party code is ended, add comments in code. Now, it is not possible to distinguish baloon tooltip code from other code.
//Rich HTML Balloon Tooltip: http://www.dynamicdrive.com/dynamicindex5/balloontooltip.htm
//Created: September 10th, 2006

var disappeardelay = 250;  //tooltip disappear delay (in miliseconds)
var verticaloffset = 0; //vertical offset of tooltip from anchor link, if any
var enablearrowhead = 0; //0 or 1, to disable or enable the arrow image
var arrowheadimg = ["arrowdown.gif", "arrowup.gif"]; //path to down and up arrow images
var arrowheadheight = 11; //height of arrow image (amount to reveal)

/////No further editting needed

var ie = document.all;
var ns6 = document.getElementById && !document.all;
verticaloffset = (enablearrowhead) ? verticaloffset + arrowheadheight : verticaloffset;

function getposOffset(what, offsettype) {
    var totaloffset = (offsettype == "left") ? what.offsetLeft : what.offsetTop;
    var parentEl = what.offsetParent;
    while (parentEl != null) {
        totaloffset = (offsettype == "left") ? totaloffset + parentEl.offsetLeft : totaloffset + parentEl.offsetTop;
        parentEl = parentEl.offsetParent;
    }
    return totaloffset;
}

function showhide(obj) {
    dropmenuobj.style.left = dropmenuobj.style.top = "-500px";
    obj.visibility = "visible";
}

function iecompattest() {
    return (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}

function clearbrowseredge(obj, whichedge) {
    if (whichedge == "rightedge") {
        edgeoffsetx = 0;
        var windowedge = ie && !window.opera ? iecompattest().scrollLeft + iecompattest().clientWidth - 15 : window.pageXOffset + window.innerWidth - 15;
        dropmenuobj.contentmeasure = dropmenuobj.offsetWidth;
        if (windowedge - dropmenuobj.x < dropmenuobj.contentmeasure)
            edgeoffsetx = dropmenuobj.contentmeasure - obj.offsetWidth;
        return edgeoffsetx;
    }
    else {
        edgeoffsety = 0;
        var topedge = ie && !window.opera ? iecompattest().scrollTop : window.pageYOffset;
        var windowedge = ie && !window.opera ? iecompattest().scrollTop + iecompattest().clientHeight - 15 : window.pageYOffset + window.innerHeight - 18;
        dropmenuobj.contentmeasure = dropmenuobj.offsetHeight;
        if (windowedge - dropmenuobj.y < dropmenuobj.contentmeasure) //move up?
            edgeoffsety = dropmenuobj.contentmeasure + obj.offsetHeight + (verticaloffset * 2);
        return edgeoffsety;
    }
}



//Display pop up menu with id menuId
function DisplayCostumPopUpMenu(obj, menuId, popUpTitle, popUpId) {
    //main ballooon tooltip function          
    if (typeof dropmenuobj != "undefined") //hide previous tooltip?
        dropmenuobj.style.visibility = "hidden";
    clearhidemenu();
    //obj.onmouseout=delayhidemenu;
    dropmenuobj = $get(menuId);

    showhide(dropmenuobj.style);
    //move postition for 15px - width of icon
    dropmenuobj.x = getposOffset(obj, "left") - 18;
    dropmenuobj.y = getposOffset(obj, "top") + verticaloffset;
    var yPos = 27;
    var xPos = 18;
    if (BrowserDetect.version == 6 && BrowserDetect.browser == 'Explorer') {
        yPos = 30;
    }
    if (BrowserDetect.browser == 'Firefox') {
        xPos = 20;
    }
    dropmenuobj.style.left = dropmenuobj.x - clearbrowseredge(obj, "rightedge") + xPos + "px";
    if (clearbrowseredge(obj, "bottomedge") > 0) {
        dropmenuobj.style.top = dropmenuobj.y - clearbrowseredge(obj, "bottomedge") + 54 + "px";
    } else {
        dropmenuobj.style.top = dropmenuobj.y - clearbrowseredge(obj, "bottomedge") + obj.offsetHeight - yPos + "px";
    }
    var popUpHeader;
    if (enablearrowhead)
        displaytiparrow();
    if (BrowserDetect.browser == 'Firefox') {
        document.getElementById(popUpId).firstChild.nodeValue = popUpTitle;
    } else {
        popUpHeader = dropmenuobj.firstChild;
        popUpHeader.innerHTML = popUpTitle;
    }
    AddDocumentEvent();
}
//Function display patient pop up menu.
function DisplayPatientBalloonTip(obj, mrn, firstname, lastname, dob, sex) { //main ballooon tooltip function 

    if (typeof dropmenuobj != "undefined") { //hide previous tooltip?            
        dropmenuobj.style.visibility = "hidden";
    }

    clearhidemenu();
    //obj.onmouseout = delayhidemenu;
    dropmenuobj = document.getElementById(obj.getAttribute("accesskey"));
    showhide(dropmenuobj.style);
    //showhide(dropmenuobj);
    //move position for 15px - width of icon
    dropmenuobj.x = getposOffset(obj, "left") - 18;
    dropmenuobj.y = getposOffset(obj, "top") + verticaloffset;

    //dropmenuobj.style.left=dropmenuobj.x - clearbrowseredge(obj, "rightedge") + "px";
    dropmenuobj.style.left = dropmenuobj.x - clearbrowseredge(obj, "rightedge") + 18 + "px";
    if (clearbrowseredge(obj, "bottomedge") > 0) {
        dropmenuobj.style.top = dropmenuobj.y - clearbrowseredge(obj, "bottomedge") + 54 + "px";
    } else {
        dropmenuobj.style.top = dropmenuobj.y - clearbrowseredge(obj, "bottomedge") + obj.offsetHeight - 27 + "px";
    }
    if (enablearrowhead)
        displaytiparrow();
    PopulatePatientDetail(mrn, firstname, lastname, dob, sex);
    AddDocumentEvent();
    //dropmenuobj.onmouseleave=delayhidemenu;     


}
////Function display pop up menu.
//function DisplayPopUpMenu(obj, addNewReportUrl, existingReportCollection, addNewMessage, headerTitle){ //main ballooon tooltip function   
//    if (typeof dropmenuobj!="undefined") //hide previous tooltip?
//        dropmenuobj.style.visibility="hidden";
//        clearhidemenu();
//        //obj.onmouseout=delayhidemenu;
//        dropmenuobj=document.getElementById(obj.getAttribute("accesskey"));
//        
//        showhide(dropmenuobj.style);
//        //move postition for 15px - width of icon
//        dropmenuobj.x=getposOffset(obj, "left") - 18;
//        dropmenuobj.y=getposOffset(obj, "top")+verticaloffset;
//        //dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+"px";
//        //dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px";
//        dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+ 20 + "px";
//        dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight - 20 +"px";
//        if (enablearrowhead)
//            displaytiparrow();
//        PopulateCostumMenu(dropmenuobj, addNewReportUrl, existingReportCollection, addNewMessage, headerTitle);
//        dropmenuobj.onmouseleave=delayhidemenu;
//}
////Write html content for pop up menu.
//function PopulateCostumMenu(dropmenuobj, addNewReportUrl, existingReportCollection, addNewMessage, headerTitle){
//        var linksArray;
//        linksArray = existingReportCollection.split('::');        
//        var str='';
//        if (addNewReportUrl == '' && linksArray.length - 1 == 1){
//            str+='<div class="popUpReport" style="padding-top:6px">';              
//        } else {
//            str+='<div class="popUpReport">';      
//        }               
//        for (var x = 0; x < linksArray.length-1; x++){
//            str += linksArray[x];
//        }
//        if (addNewReportUrl != ''){  
//            str+='<a href="'+ addNewReportUrl + '" class="titlePopup">'+ addNewMessage +'<\/a>';            
//        }         
//        
////        if (addNewReportUrl != ''){  
////            str+='<a href="'+ addNewReportUrl + '" class="titlePopup">'+ addNewMessage +'<\/a>';            
////        }
//        
//        str+='<\/div>';
////        var divCloseButton = $get('divCloseButton');
////        if (BrowserDetect.browser == "Explorer"){
////            divCloseButton.style.display = "none";
////        }
//        var divContent = $get('divContent');
//        divContent
//        divContent.innerHTML = str;  
//        var popUpHeader = $get('popUpHeader');  
//        popUpHeader.innerHTML = headerTitle;
//        
//}

//Function display pop up menu.
function DisplayPopUpMenu(obj, addNewReportUrl, existingReportCollection, addNewMessage, headerTitle) { //main ballooon tooltip function           
    DisplayPopUpMenuWithClose(obj, addNewReportUrl, existingReportCollection, addNewMessage, headerTitle, '', '', '')
}
function DisplayPopUpMenuWithClose(obj, addNewReportUrl, existingReportCollection, addNewMessage, headerTitle, readNoReportUrl, readNoReportMessage, caseId) { //main ballooon tooltip function              
    if (typeof dropmenuobj != "undefined") //hide previous tooltip?
        dropmenuobj.style.visibility = "hidden";
    clearhidemenu();
    //obj.onmouseout=delayhidemenu;
    dropmenuobj = document.getElementById(obj.getAttribute("accesskey"));
    showhide(dropmenuobj.style);
    //move postition for 15px - width of icon
    dropmenuobj.x = getposOffset(obj, "left") - 18;
    dropmenuobj.y = getposOffset(obj, "top") + verticaloffset;
    var yPos = 27;
    var xPos = 18;
    if (BrowserDetect.version == 6 && BrowserDetect.browser == 'Explorer') {
        yPos = 30;
    }
    if (BrowserDetect.browser == 'Firefox') {
        xPos = 20;
    }
    //dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+"px";
    //dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+"px";        
    dropmenuobj.style.left = dropmenuobj.x - clearbrowseredge(obj, "rightedge") + xPos + "px";
    if (clearbrowseredge(obj, "bottomedge") > 0) {
        dropmenuobj.style.top = dropmenuobj.y - clearbrowseredge(obj, "bottomedge") + 54 + "px";
    } else {
        dropmenuobj.style.top = dropmenuobj.y - clearbrowseredge(obj, "bottomedge") + obj.offsetHeight - yPos + "px";
    }
    if (enablearrowhead)
        displaytiparrow();
    PopulateCustomMenu(dropmenuobj, addNewReportUrl, existingReportCollection, addNewMessage, headerTitle, readNoReportUrl, readNoReportMessage, caseId);
    AddDocumentEvent();

}
function AddDocumentEvent() {
    if (IE) {
        document.attachEvent("onclick", DocumentClickEvent);
    } else {
        document.captureEvents(Event.MOUSECLICK);
        document.onclick = DocumentClickEvent;
    }
}
function DocumentClickEvent(e) {
    getMouseXY(e);
    if (!dropmenuobj) {
        return;
    }
    var byXAxis = (tempX > dropmenuobj.offsetLeft + dropmenuobj.offsetWidth || tempX < dropmenuobj.offsetLeft);
    var byYAxis = (tempY < dropmenuobj.offsetTop || tempY > dropmenuobj.offsetTop + dropmenuobj.offsetHeight);
    if (byXAxis || byYAxis) {
        delayhide = setTimeout("dropmenuobj.style.visibility='hidden'; dropmenuobj.style.left=0; if (enablearrowhead) tiparrow.style.visibility='hidden'", disappeardelay);
    }
}
//Write html content for pop up menu.
function PopulateCustomMenu(dropmenuobj, addNewReportUrl, existingReportCollection, addNewMessage, headerTitle, readNoReportUrl, readNoReportMessage, caseId) {
    var linksArray;
    linksArray = existingReportCollection.split('::');
    var str = '';
    if (addNewReportUrl == '' && linksArray.length - 1 == 1) {
        str += '<div class="popUpReport" style="padding-top:6px">';
    } else {
        str += '<div class="popUpReport">';
    }
    for (var x = 0; x < linksArray.length - 1; x++) {
        str += linksArray[x];
    }
    if (addNewReportUrl != '') {
        str += '<a onclick=ClosePopUp(\'divReport\') href="' + addNewReportUrl + '" class="titlePopup">' + addNewMessage + '<\/a>';
    }

    if (readNoReportUrl != '') {
        str += '<a  href="' + readNoReportUrl + '" onclick="SetReadNoReportStatus(\'' + caseId + '\'); ClosePopUp(\'divReport\')" class="titlePopup noReport">' + readNoReportMessage + '<\/a>';
    }
    str += '<\/div>';
    var divContent = $get('divContent');
    divContent.innerHTML = str;
    var popUpHeader
    if (BrowserDetect.browser == 'Firefox') {
        popUpHeader = document.getElementById("popUpTitle");
        popUpHeader.innerHTML = headerTitle;
    } else {
        popUpHeader = dropmenuobj.firstChild;
        popUpHeader.innerHTML = headerTitle;
    }

}

function SetReadNoReportStatus(caseId) {
    PageMethods.SetToReadNoReport(caseId);
}


/// CodeAnalysis: Function is not properly named.
function displaytiparrow() { //function to display optional arrow image associated with tooltip
    tiparrow = document.getElementById("arrowhead");
    tiparrow.src = (edgeoffsety != 0) ? arrowheadimg[0] : arrowheadimg[1];
    var ieshadowwidth = (dropmenuobj.filters && dropmenuobj.filters[0]) ? dropmenuobj.filters[0].Strength - 1 : 0;
    //modify "left" value depending on whether there's no room on right edge of browser to display it, respectively
    tiparrow.style.left = (edgeoffsetx != 0) ? parseInt(dropmenuobj.style.left) + dropmenuobj.offsetWidth - tiparrow.offsetWidth - 10 + "px" : parseInt(dropmenuobj.style.left) + 5 + "px";
    //modify "top" value depending on whether there's no room on right edge of browser to display it, respectively
    tiparrow.style.top = (edgeoffsety != 0) ? parseInt(dropmenuobj.style.top) + dropmenuobj.offsetHeight - tiparrow.offsetHeight - ieshadowwidth + arrowheadheight + "px" : parseInt(dropmenuobj.style.top) - arrowheadheight + "px";
    tiparrow.style.visibility = "visible";
}

/// CodeAnalysis: Function is not properly named.
function delayhidemenu() {
    //alert(dropmenuobj.style.visibility);
    delayhide = setTimeout("dropmenuobj.style.visibility='hidden'; dropmenuobj.style.left=0; if (enablearrowhead) tiparrow.style.visibility='hidden'", disappeardelay);
    //delayhide=setTimeout("dropmenuobj.style.display='none'; dropmenuobj.style.left=0; if (enablearrowhead) tiparrow.style.visibility='hidden'",disappeardelay);
}



/// CodeAnalysis: Function is not properly named.
function clearhidemenu() {
    if (typeof delayhide != "undefined")
        clearTimeout(delayhide);
}

function reltoelement(linkobj) { //tests if a link has "rel" defined and it's the ID of an element on page
    var relvalue = linkobj.getAttribute("rel");
    return (relvalue != null && relvalue != "" && document.getElementById(relvalue) != null && document.getElementById(relvalue).className == "balloonstyle") ? true : false;
}

// Check if StudyViewer is already installed. Return true if StudyViewer (ActiveX) is already installed. Otherwise, return false.
function isStudyViewerInstalled(studyViewer) {
    var res = false;
    try {
        var boolStr = studyViewer.FullScreen.toString();
        res = true;
    }
    catch (err) {
        loadActiveXError = "failed";
    }
    return res;
}

//Check fields on case report and patient history page
function CheckCaseReportTemplateFields(templateDescriptionId, templateNameId, reportContentId) {
    var templateName = $get(templateNameId);
    var templateDescription = $get(templateDescriptionId);
    var reportContent = $get(reportContentId);
    if (reportContent.value == '') {
        alert('Please insert content.');
        return false;
    } else if (templateName.value == '') {
        alert('Please insert template name.');
        return false;
    } else if (templateDescription.value == '') {
        alert('Please insert template description.');
        return false;
    } else {
        return true;
    }
}

function UnderlineText(radiologistId) {
    var currentDiv = $get(radiologistId);
    currentDiv.textDecoration = 'underline';
}

/// CodeAnalysis: Obsolute. Should use ShowHideStudy instead. Delete when switched to new function.
function ShowHideDetails(buttonId, controlId) {
    var button = document.getElementById(buttonId);
    var control = document.getElementById(controlId);

    if (control.style.display == 'none') {
        control.style.display = 'block';
        button.src = 'VisualStyles/ThemeC/Images/Buttons/Icons/imgCollapse.png';
    }
    else {
        control.style.display = 'none';
        button.src = 'VisualStyles/ThemeC/Images/Buttons/Icons/imgExpand.png';
    }
}

function ShowHideCases(rowId, buttonId, trList, rowCss) {
    var patientRow = $get(rowId);
    var button = $get(buttonId);
    var rowList, mode;
    rowList = trList.split('~');
    for (var x = 0; x < rowList.length - 1; x++) {
        var objSingleRow = $get(rowList[x]);
        if (objSingleRow == null) return;
        if (objSingleRow.style.display == 'none') {
            mode = "show";

        } else {
            mode = "hide";

        }
        switchLayers(rowList[x]);
    }
    if (mode == "show") {
        AddToShowList(rowId);
        button.src = 'VisualStyles/ThemeC/Images/Buttons/Icons/imgCollapse.png';
        patientRow.className = "patientRowOpen";
    }
    else {
        RemoveFromShowList(rowId);
        button.src = 'VisualStyles/ThemeC/Images/Buttons/Icons/imgExpand.png';
        patientRow.className = rowCss;
    }
}

// Add expanded patient row index to list of rows to show case rows
function AddToShowList(rowId) {
    if (!showList) return;
    for (var i = 0; i < showList.length - 1; i++) {
        if (showList[i] == rowId)
            return;
    }
    showList.push(rowId);
    UpdateShowListHiddenField();
}

// Remove collapsed patient row index from list of rows to be shown
function RemoveFromShowList(rowId) {
    if (!showList) return;
    for (var i = showList.length - 1; i >= 0; i--) {
        if (showList[i] == rowId)
            showList.splice(i, 1);
    }
    UpdateShowListHiddenField();
}

/// CodeAnalysis: CollapseButton should not be relative to current page. Apsolute path constant is much better, that will work on any page.
/// Show hide study list when collapse button is clicked, switch collapse image icons and switch className for patient panel.
function ShowHideStudy(collapseButtonID, pnlStudyListID, pnlPatientID) {
    var collapseButton = $get(collapseButtonID);
    var pnlStudyList = $get(pnlStudyListID);
    var pnlPatient = $get(pnlPatientID);
    if (pnlStudyList.style.display == 'none') {
        pnlStudyList.style.display = 'block';
        collapseButton.src = 'VisualStyles/ThemeC/Images/Buttons/Icons/imgCollapse.png';
        pnlPatient.className = "patientRowOpen";
    }
    else {
        pnlStudyList.style.display = 'none';
        collapseButton.src = 'VisualStyles/ThemeC/Images/Buttons/Icons/imgExpand.png';
        pnlPatient.className = "patientRow";
    }
}

// clears search controls in patient list and work list
function clearSearchFields(firstName, secondName, title, date, lastDays, defaultLastDays) {
    firstName.value = secondName.value = title.value = date.value = "";
    lastDays.value = defaultLastDays;
    return false;
}

var ToggleButtonCheckTitle = "Check";

function OnCheckBoxOver(checkBox) {
    var toggleButton = FindToogleButton(checkBox);
    if (!toggleButton) return;
    //toggleButton.style.backgroundImage = 'url(Image/butt_checkButtonLogin_over.gif)';
}

/* Toggle Button start */
// currently not used

function OnCheckBoxOut(checkBox) {
    var toggleButton = FindToogleButton(checkBox);
    if (!toggleButton) return;
    //toggleButton.style.backgroundImage = 'url(Image/butt_checkButtonLogin.gif)';
}

// Quirk way to find ToggleButton of specified CheckBox control, until ToggleButton doesn't implement OnMouseOver behavior.
function FindToogleButton(checkBox) {
    var toggleButton = null;
    if (checkBox && checkBox.parentElement && checkBox.parentElement.firstChild && checkBox.parentElement.firstChild.firstChild && checkBox.parentElement.firstChild.firstChild.firstChild) {
        var element = checkBox.parentElement.firstChild.firstChild.firstChild;
        if (element.tagName == "A") toggleButton = element;
    }
    return toggleButton;
}

/* Toggle Button end */

/* ButtonSmart start */

function OnButtonOverOrOut(button, className) {
    var divContainer = FindButtonContainerDiv(button);
    if (!divContainer) return;
    divContainer.className = className;
}

function FindButtonContainerDiv(button) {
    var divContainer = null;
    if (button && GetParent(button) && GetParent(GetParent(button))) {
        var element = GetParent(GetParent(button));
        if (element.tagName == "DIV") divContainer = element;
    }
    return divContainer;
}

/* ButtonSmart end */

// Cross browser implementation of parentNode. "parentElement" is IE and "parentNode" is FF.
function GetParent(htmlElement) {
    if (!htmlElement) return null;
    return (htmlElement.parentElement == undefined) ? htmlElement.parentNode : htmlElement.parentElement;
}

// Handles onunload event
function OnUnLoad() {
    activeX.OnUnLoad();
}

// Handle StudyViewer Universal Event - Action
function StudyViewerAction(ActionName, ActionParam) {
    // not implemented
}
function ClosePopUp(popUpId) {
    var popUp = $get(popUpId);
    if (!popUp) return;
    popUp.style.visibility = 'hidden';
    return false;
}
//Open pop up for send to radiologist process.
function SendForReviewOpenPopUp(obj, hdnPatientRowId, hdnCaseRowId,
                                    hdnCaseId, hdnHavePatientHistId, hdnCommandArgumentId,
                                    patientRow, caseRow, caseId, havePatientHist,
                                    isEnt, mainContainer, commandArgument) {
    //main ballooon tooltip function
    if (typeof dropmenuobj != "undefined") //hide previous tooltip?
        dropmenuobj.style.visibility = "hidden";
    clearhidemenu();
    dropmenuobj = $get(obj.getAttribute("accesskey"));
    showhide(dropmenuobj.style);
    dropmenuobj.x = getposOffset(obj, "left") - 18;
    dropmenuobj.y = getposOffset(obj, "top") + verticaloffset;
    dropmenuobj.style.left = dropmenuobj.x - clearbrowseredge(obj, "rightedge") + 18 + "px";
    var yPos = 27;
    if (BrowserDetect.version == 6 && BrowserDetect.browser == 'Explorer') {
        yPos = 30;
    }
    if (clearbrowseredge(obj, "bottomedge") > 0) {
        dropmenuobj.style.top = dropmenuobj.y - clearbrowseredge(obj, "bottomedge") + 54 + "px";
    } else {
        dropmenuobj.style.top = dropmenuobj.y - clearbrowseredge(obj, "bottomedge") + obj.offsetHeight - yPos + "px";
    }
    if (enablearrowhead)
        displaytiparrow();
    //dropmenuobj.onmouseleave=delayhidemenu;  
    AddDocumentEvent();
    //populate necessary information to the pop up
    var hdnPatRow = $get(hdnPatientRowId);
    var hdnCaseRow = $get(hdnCaseRowId);
    var hdnCaseId = $get(hdnCaseId);
    var hdnHavePatHist = $get(hdnHavePatientHistId);
    var mainPopUpDiv = $get(mainContainer);
    var hdnCommandArgument = $get(hdnCommandArgumentId);
    if (hdnPatRow == null || hdnCaseRow == null || hdnHavePatHist == null || mainPopUpDiv == null || hdnCommandArgument == null) {
        return;
    }
    hdnPatRow.value = patientRow;
    hdnCaseRow.value = caseRow;
    hdnCaseId.value = caseId;
    hdnHavePatHist.value = havePatientHist;
    hdnCommandArgument.value = commandArgument;
    var elements = mainPopUpDiv.getElementsByTagName("div");
    if (havePatientHist == 'False' && isEnt == 'True') {
        // hide link buttons           
        for (i = 0; i < elements.length; i++) {
            element = elements[i];
            var pattern = new RegExp("\\bdivLinkButton");
            if (pattern.test(element.id)) {
                element.style.display = 'none';
            }
            pattern = new RegExp("divDoctor");
            if (pattern.test(element.id)) {
                element.style.display = 'block';
            }
        }
    } else {
        //show only link buttons
        for (i = 0; i < elements.length; i++) {
            element = elements[i];
            pattern = new RegExp("divDoctor");
            if (pattern.test(element.id)) {
                element.style.display = 'none';
            }
            pattern = new RegExp("\\bdivLinkButton");
            if (pattern.test(element.id)) {
                element.style.display = 'block';
            }
        }
    }
}
// Send for review function.
function SendForReview(isEnt, hdnPatientRowId, hdnCaseRowId, hdnCaseId, hdnHavePatientHist, hdnComandArgumentsid, doctorId, senderId, popUpMessage) {
    var hdnPatRow = $get(hdnPatientRowId);
    var hdnCaseRow = $get(hdnCaseRowId);
    var hdnCaseId = $get(hdnCaseId);
    var hdnHavePatHist = $get(hdnHavePatientHist);
    var hdnComandArgs = $get(hdnComandArgumentsid);


    if (isEnt == 'True' && hdnHavePatHist.value == 'False') {
        alert('Please attach patient history before sending scan.');
        return false;
    } else {
        //call server side method           
        if (!confirm(popUpMessage)) {
            ClosePopUp('divSendToReview');
            return false;
        }
        ClosePopUp('divSendToReview');
        PageMethods.SendForReview(hdnComandArgs.value, doctorId, hdnCaseId.value, senderId);
        return true;
    }
}
function ClearAdvSearchFieds(list, dropDownList, ddlLastNDays, numberOfDays) {
    for (i = 0; i < list.length; i++) {
        list[i].value = "";
    }
    for (j = 0; j < dropDownList.length; j++) {
        dropDownList[j].selectedIndex = 0;
    }
    ddlLastNDays.value = numberOfDays;
}

function DisableControls(list) {
    for (i = 0; i < list.length; i++) {
        $get(list[i]).disabled = true;
    }
}

function EnableControls(list) {
    for (i = 0; i < list.length; i++) {
        $get(list[i]).disabled = false;
    }
}
function ClearShowList() {
    if (!showList) return;
    for (var i = showList.length - 1; i >= 0; i--) {
        showList.splice(i, 1);
    }
}

// Hide modal popup with specified behavior id. 
function hideModalPopup(modalPopupBehaviorId) {
    var modalPopUp = $find(modalPopupBehaviorId)
    if (!modalPopUp) return;
    modalPopUp.hide();
}

// Show modal popup with specified behavior id. 
function showModalPopup(modalPopupBehaviorId) {
    var modalPopUp = $find(modalPopupBehaviorId)
    if (!modalPopUp) return;
    modalPopUp.show();
}

// Hide specified control
function hideControl(control) {
    if (!control || !control.style) return;
    control.style.display = 'none';
}

function switchSingleImage(image) {
    var img = $get(image);
    if (img.src.indexOf("/VisualStyles/Images/Buttons/Icons/imgExpand.png") > 0)
        img.src = "../VisualStyles/Images/Buttons/Icons/imgCollapse.png";
    else
        img.src = "../VisualStyles/Images/Buttons/Icons/imgExpand.png";
}

function showHideObject(obj) {
    var o = $get(obj);
    if (o.style.display == "none")
        o.style.display = "";
    else
        o.style.display = "none";
}
function ShowModalPopUp(popUpId) {
    var modal = $find(popUpId);
    modal.show();
}
function HideModalPopUp(popUpId) {
    var modal = $find(popUpId);
    modal.hide();
}
// Temporary variables to hold mouse x-y pos.s
var tempX = 0;
var tempY = 0;
var IE = document.all ? true : false;
// Main function to retrieve mouse x-y pos.s

//Gets mouse X and Y position.
function getMouseXY(e) {
    var yScroll;
    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
        yScroll = document.documentElement.scrollTop;
    } else if (document.body) {// all other Explorers
        yScroll = document.body.scrollTop;
    }

    if (IE) { // grab the x-y pos.s if browser is IE    
        tempX = event.clientX + document.body.scrollLeft;
        tempY = event.clientY + yScroll;
    } else {  // grab the x-y pos.s if browser is NS   
        tempX = e.pageX;
        tempY = e.pageY;
    }
    // catch possible negative values in NS4
    if (tempX < 0) { tempX = 0 }
    if (tempY < 0) { tempY = 0 }
}
function ChangeSubmenuCss(obj, className) {
    alert(obj);
    if (!obj) return;
    obj.className = className;
}
function ResizeHelpArea() {
    if (BrowserDetect.version == 6 && BrowserDetect.browser == 'Explorer') {
        //help header
        var divNavBarTop = $get('divNavBarHelp');
        //help content
        var mainContainer = $get('mainHelpContainer');
        //help footer 
        var helpFooter = $get('helpFooter');
        //page header 
        var header = $get('tblHeader')
        var copyrightHeight = 35;
        var pageHeight;
        var screenHeight = document.documentElement.clientHeight;
        var screenWidth = document.documentElement.clientWidth;
        if (!divNavBarTop || !mainContainer || !helpFooter) return;

        divNavBarTop.style.width = screenWidth - 349 + "px";
        mainContainer.style.width = screenWidth - 351 + "px";
        helpFooter.style.width = screenWidth - 349 + "px";



        //if sum of header, footer, page header, grid header and grid footer is 
        //higher than screen height, set help content height to 0
        //otherwise set proper height
        //216px header height
        //68px footer height

        var avaliableHeight;
        avaliableHeight = screenHeight - 216 - 68 - 80;

        var helpMenu = $get('helpMenu');
        if (avaliableHeight <= 0) {
            mainContainer.style.height = 0 + "px";
            mainContainer.style.display = 'none';
            helpMenu.style.height = 0 + "px";
        } else {
            mainContainer.style.height = avaliableHeight + 7 + "px";
            mainContainer.style.display = 'block';
            helpMenu.style.height = avaliableHeight + 35 + "px";
        }

    }
}
//Function that is fired on practice invitation button click.
function ConfirmPracticeInvitation(emailTextBoxId, ddlSelectedPracticeId, message, rfvEmailTextBoxId) {
    var emailTxt = $get(emailTextBoxId);
    if (!emailTxt) return;
    var rfvEmailTextBox = $get(rfvEmailTextBoxId);
    if (!rfvEmailTextBox) return;
    var ddlSelectedPractice = $get(ddlSelectedPracticeId);
    if (!ddlSelectedPractice) return;

    //test email format
    var emailPattern = "^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$";
    var pattern = new RegExp(emailPattern);

    var result = pattern.test(emailTxt.value);
    if (!result) {
        //allow server side method to fire, because of notifications
        return true;
    }
    //if email field is empty return false
    if (emailTxt.value == '') {
        rfvEmailTextBox.style.visibility = 'visible';
        return false;
    } else if (ddlSelectedPractice.value == '') {
        //allow server side method to fire
        return true;
    }
    else {
        rfvEmailTextBox.style.visibility = 'hidden';
        return confirm(message);
    }
}

function confirmAppointmentDelete() {
    if (confirm("Are you sure, you want to delete the appointment?"))
        return true;
    else
        return false;
}

function formatTelNo(telNo) {
    // If it's blank, save yourself some trouble by doing nothing.
    if (telNo.value == "") return;
    var phone = new String(telNo.value);
    phone = phone.substring(0, 14);

    /*
    "." means any character. If you try to use "(" and ")", the regular expression becomes 
    complicated sice both are reserve characters and escaping them sometimes fails. So just 
    use "." for any character and replace it later.
    */
    if (phone.match(".[0-9]{3}.[0-9]{3}-[0-9]{4}") == null) {

        if (phone.match(".[0-9]{2}.[0-9]{3}-[0-9]{4}|" + ".[0-9].[0-9]{3}-[0-9]{4}|" +
            ".[0-9]{3}.[0-9]{2}-[0-9]{4}|" + ".[0-9]{3}.[0-9]-[0-9]{4}") == null) {
            /*
            You will reach here only if the user is still typing the number or if he/she has 
            messed up already formatted number. 
            */
            var phoneNumeric = phoneChar = "", i;
            // Loop thru what user has entered.
            for (i = 0; i < phone.length; i++) {
                // Go thru what user has entered one character at a time.
                phoneChar = phone.substr(i, 1);

                // If that character is not a number or is a White space, ignore it. Only if it is a digit, 
                // concatinate it with a number string.
                if (!isNaN(phoneChar) && (phoneChar != " ")) phoneNumeric = phoneNumeric + phoneChar;
            }

            phone = "";
            // At this point, you have picked up only digits from what user has entered. Loop thru it.
            for (i = 0; i < phoneNumeric.length; i++) {
                // If it's the first digit, throw in "(" before that.
                if (i == 0) phone = phone + "(";
                // If you are on the 4th digit, put ") " before that.
                if (i == 3) phone = phone + ") ";
                // If you are on the 7th digit, insert "-" before that.
                if (i == 6) phone = phone + "-";
                // Add the digit to the phone charatcer string you are building.
                phone = phone + phoneNumeric.substr(i, 1)
            }
        }
    }
    else {
        // This means the tel no is in proper format. Make sure by replacing the 0th, 4th and 8th character.
        phone = "(" + phone.substring(1, 4) + ") " + phone.substring(5, 8) + "-" + phone.substring(9, 13);
    }
    // So far you are working internally. Refresh the screen with the re-formatted value.
    if (phone != telNo.value) telNo.value = phone;
}

/*
CheckTelNo method takes in current element of the form as input. This method should be 
fired as the user attempts to leave the current element in the form (by using onBlur method). 
It checks to see if the format of the phone is "(123) 456-7890".
Eg. <netui:textBox size="13" maxlength="13" onBlur="javascript:checkTelNo (this);" onKeyUp="javascript:formatTelNo (this);" onKeyDown="javascript:formatTelNo (this);"/>  
*/
function checkTelNo(telNo) {
    if (telNo.value == "") return;
    if (telNo.value.match(".[0-9]{3}.[0-9]{3}-[0-9]{4}") == null) {
        if (telNo.value.match("[0-9]{10}") != null)
            formatTelNo(telNo)
    }
}
/* good
*/

var zChar = new Array(' ', '(', ')', '-', '.');
var maxphonelength = 13;
var phonevalue1;
var phonevalue2;
var cursorposition;

function ParseForNumber1(object) {
    phonevalue1 = ParseChar(object.value, zChar);
}
function ParseForNumber2(object) {
    phonevalue2 = ParseChar(object.value, zChar);
}

function backspacerUP(object, e) {
    if (e) {
        e = e
    } else {
        e = window.event
    }
    if (e.which) {
        var keycode = e.which
    } else {
        var keycode = e.keyCode
    }

    ParseForNumber1(object)

    if (keycode >= 48) {
        ValidatePhone(object)
    }
}

function backspacerDOWN(object, e) {
    if (e) {
        e = e
    } else {
        e = window.event
    }
    if (e.which) {
        var keycode = e.which
    } else {
        var keycode = e.keyCode
    }
    ParseForNumber2(object)
}

function GetCursorPosition() {

    var t1 = phonevalue1;
    var t2 = phonevalue2;
    var bool = false
    for (i = 0; i < t1.length; i++) {
        if (t1.substring(i, 1) != t2.substring(i, 1)) {
            if (!bool) {
                cursorposition = i
                bool = true
            }
        }
    }
}

function ValidatePhone(object) {

    var p = phonevalue1

    p = p.replace(/[^\d]*/gi, "")

    if (p.length < 3) {
        object.value = p
    } else if (p.length == 3) {
        pp = p;
        d4 = p.indexOf('(')
        d5 = p.indexOf(')')
        if (d4 == -1) {
            pp = "(" + pp;
        }
        if (d5 == -1) {
            pp = pp + ")";
        }
        object.value = pp;
    } else if (p.length > 3 && p.length < 7) {
        p = "(" + p;
        l30 = p.length;
        p30 = p.substring(0, 4);
        p30 = p30 + ")"

        p31 = p.substring(4, l30);
        pp = p30 + p31;

        object.value = pp;

    } else if (p.length >= 7) {
        p = "(" + p;
        l30 = p.length;
        p30 = p.substring(0, 4);
        p30 = p30 + ")"

        p31 = p.substring(4, l30);
        pp = p30 + p31;

        l40 = pp.length;
        p40 = pp.substring(0, 8);
        p40 = p40 + "-"

        p41 = pp.substring(8, l40);
        ppp = p40 + p41;

        object.value = ppp.substring(0, maxphonelength);
    }

    GetCursorPosition()

    if (cursorposition >= 0) {
        if (cursorposition == 0) {
            cursorposition = 2
        } else if (cursorposition <= 2) {
            cursorposition = cursorposition + 1
        } else if (cursorposition <= 5) {
            cursorposition = cursorposition + 2
        } else if (cursorposition == 6) {
            cursorposition = cursorposition + 2
        } else if (cursorposition == 7) {
            cursorposition = cursorposition + 4
            e1 = object.value.indexOf(')')
            e2 = object.value.indexOf('-')
            if (e1 > -1 && e2 > -1) {
                if (e2 - e1 == 4) {
                    cursorposition = cursorposition - 1
                }
            }
        } else if (cursorposition < 11) {
            cursorposition = cursorposition + 3
        } else if (cursorposition == 11) {
            cursorposition = cursorposition + 1
        } else if (cursorposition >= 12) {
            cursorposition = cursorposition
        }

        var txtRange = object.createTextRange();
        txtRange.moveStart("character", cursorposition);
        txtRange.moveEnd("character", cursorposition - object.value.length);
        txtRange.select();
    }

}

function ParseChar(sStr, sChar) {
    if (sChar.length == null) {
        zChar = new Array(sChar);
    }
    else zChar = sChar;

    for (i = 0; i < zChar.length; i++) {
        sNewStr = "";

        var iStart = 0;
        var iEnd = sStr.indexOf(sChar[i]);

        while (iEnd != -1) {
            sNewStr += sStr.substring(iStart, iEnd);
            iStart = iEnd + 1;
            iEnd = sStr.indexOf(sChar[i], iStart);
        }
        sNewStr += sStr.substring(sStr.lastIndexOf(sChar[i]) + 1, sStr.length);

        sStr = sNewStr;
    }

    return sNewStr;
}
