﻿//========Global Variables===============
//var iframeID="";
 var version;
 var browser;
 var ajaxMethod; //Used to determine GET or POST.  Mozilla likes GET, IE likes POST.
     ajaxMethod = "GET";
//----For autocomplete, height weight, etc-------     
var keynum;
document.onkeydown = getkeynum;
//=======================================

//======Loop to get the x, y position of an element
var curleft = 0;
var curtop = 0;
function getXYPos(objID)
{
    var obj = document.getElementById(objID);
     curleft = 0;
     curtop = 0;
     while(obj.offsetParent) 
        {
              curleft += obj.offsetLeft;
              curtop += obj.offsetTop;
              if(!obj.offsetParent)
                break;
              obj = obj.offsetParent;
          
        }
}

function parseXML(xml) {
    if (window.ActiveXObject && window.GetObject) {
        var dom = new ActiveXObject('Microsoft.XMLDOM');
        dom.loadXML(xml);
        return dom;
    }
    if (window.DOMParser)
        return new DOMParser().parseFromString(xml, 'text/xml');
    throw new Error('No XML parser available');
}
//==================================================

function getbrowser()
{
       /* browser = navigator.appName;
         switch (browser)
        {
            case "Netscape":
                ajaxMethod = "GET";
            break;
            case "Microsoft Internet Explorer":
                ajaxMethod = "POST";
            break;
            default:
                ajaxMethod = "POST";
        }*/
        
}
//Object used to call ajax.  You will not need to call this directly.
function getXmlHttpRequestObject(FieldID)
            {	
                if (window.XMLHttpRequest) {
	                    return new XMLHttpRequest();	
	                    } 
                else if(window.ActiveXObject) {		
                        return new ActiveXObject("Microsoft.XMLHTTP");	
                        } 
                else {		
                        alert("Browser Incompatible with AJAX.");
                     }
             }
var objajax = getXmlHttpRequestObject();
 
 
/* This function sends the request and returns a string via ajax
 *
 * Required Params:
 *  url (string) - the url with the query variables you want to use
 *  divID (string) - id attribute of the div you will populate the returned html with
 *
 * Optional Params:
 *  async (bool) - whether or not to make ajax call asynchronously. If not passed as a
 *      parameter to the function it will default to true, thus providing expected 
 *      default ajax behavior
*/
function ajaxRequest(url, divID, async) {
    async = (async == null) ? true : async;
    var div = document.getElementById(divID);
    div.innerHTML = '<div style="text-align:center; width:100%" ><img src="https://www.patientally.com/GFX/ajaxloading_blue.gif"/></div>';
    var objajax = new getXmlHttpRequestObject();
    if (objajax.readyState == 4 || objajax.readyState == 0) {
        var thisdate = new Date();
        objajax.open(ajaxMethod, url, true);
        objajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        objajax.setRequestHeader("If-Modified-Since", thisdate);
        objajax.onreadystatechange = function() {
        //alert(objajax.readyState);
            if (objajax.readyState == 4) {
                if (objajax.status == 200) {
                    var arr = objajax.responseText.split("&&&");
                   // alert(objajax.responseText);
                    //alert(arr[1]);
                    div.innerHTML = arr[1];
                    // iFrameAutoResize('iframe1', "open"); //autocomplete stuff
                }
            }
        }

        objajax.send(null);
    }
}
//var workit = 0;
 //Variation of the function above - this one is used specifically for gridviews
 //gridDT is the variable you declare in your page to hold the grid's datatable
 function ajaxRequestGrid(url, divID, xmlfile) {

                //workit +=1
               var thisdate = new Date();
                var div = document.getElementById(divID);
                div.innerHTML = '<div style="text-align:center; width:100%" ><img src="https://www.patientally.com/GFX/ajaxloading_blue.gif"/></div>';
                //document.getElementById("gridResults").innerHTML = '<div style="text-align:center; width:100%" ><img src="https://www.patientally.com/GFX/ajaxloading_blue.gif"/></div>';
               
                var objajax = new getXmlHttpRequestObject();
                // alert(url);
                var arr, arr2, arrDiv, arrDiv2, arrDiv3;
                setCMD = 'document.getElementById("' + divID + '")';
                 if (objajax.readyState == 4 || objajax.readyState == 0) 
                        {
	                        objajax.open("POST", url, true);
	                        objajax.setRequestHeader("If-Modified-Since", thisdate);
	                        objajax.onreadystatechange = function() {
	                            if (objajax.readyState==4)
                                {         
                                    if (objajax.status==200)
                                    { 
                                        arr = objajax.responseText.split("&&&"); 
                                        //arr[1] contains the grid(s) and the div
                                        arr2 = arr[1].split("+++");
                                        //div.innerHTML = '';
                                        div.innerHTML = arr2[0];
                                        //this contains the div that holds the datatable strign
                                        arrDiv = arr2[1].split('divDs">'); //take out header
                                        arrDiv2 = arrDiv[1].split('</div>'); //take out footer;
                                        arrDiv3 = arrDiv2[0].split('***'); //split between the dataset and sortdirection
										// alert(arrDiv3.innerHTML);
                                        gridDT = arrDiv3[0];
                                        //alert(gridDT);
                                        gvsortDir = arrDiv3[1];
                                        
                                        //iFrameAutoResize('iframe1', "open");
                                        //alert(objajax.responseText);                                       
	                                 }
	                             }    
	                        }// close readyState check
                            
	                        objajax.send(xmlfile); 
                       }    
            }

            function ajaxRequestReport(url, divID, xmlfile) {
                var thisdate = new Date();
                var div = document.getElementById(divID);
                div.innerHTML = '<div style="text-align:center; width:100%" ><img src="/PatientAlly/GFX/ajaxloading_blue.gif"/></div>';
                var objajax = new getXmlHttpRequestObject();
                if (objajax.readyState == 4 || objajax.readyState == 0) {

                    objajax.open("POST", url, true);
                    //objajax.setRequestHeader("If-Modified-Since", thisdate);
                    objajax.onreadystatechange = function() {
                        if (objajax.readyState == 4) {
                            if (objajax.status == 200) {
                                var arr = objajax.responseText.split("&&&");
                                var arr2 = arr[1].split("+++");

                                div.innerHTML = arr2[0];
                                var arrDiv = arr2[1].split('divDs">'); //take out header
                                var arrDiv2 = arrDiv[1].split('</div>'); //take out footer;
                                var arrDiv3 = arrDiv2[0].split('***'); //split between the dataset and sortdirection
                                //gridDT = arrDiv3[0];

                                rptGridDT[divID] = arrDiv3[0]; // for a multiform display
                                gvsortDir[divID] = arrDiv3[1];
                            }
                        }
                    }
                    objajax.send(xmlfile);
                }
            }

//Similar to sql function isnull.
//t is the string to check for null
//ret is the value to replace the string with.
function isnull(str, ret) 
            { 
                if (str.length > 0 )
                {
                    return str;
                }
                else
                {
                    return ret;
                }
                 
            }           

//Similar to VB function contains.
//t is the value to check for in the string.
//example usage: var x = "hi";  x.contains("hi");
String.prototype.contains = function(t) { return this.indexOf(t) >= 0 ? true : false }      

//============Functions used to grab values in gridview from client side========== 
    var gridViewCtl = null;
    var curSelRow = null;
    var curRowIdx = -1;
    function getGridViewControl()
    {
            //$get is an ajax way of getting an element.  Won't always work.
            gridViewCtl = $get(gridViewCtlId);
            if (gridViewCtl == undefined)
            {
                gridViewCtl = document.getElementById(gridViewCtlId);
            }
    }
    function getSelectedRow(rowIdx)
    {
        return getGridRow(rowIdx);
    }
    
    function getGridRow(rowIdx)
    {
        getGridViewControl();
        if (null != gridViewCtl)
        {
            return gridViewCtl.rows[rowIdx];
        }
        return null;
    }
    
    function getGridColumn(rowIdx, colIdx)
    {
        var gridRow = getGridRow(rowIdx);
        if (null != gridRow)
        {
            return gridRow.cells[colIdx];
        }
        return null;
    }
    
    function getCellValue(rowIdx, colIdx)
    {
        var gridCell = getGridColumn(rowIdx, colIdx);
        if (null != gridCell)
        {
            if (gridCell.innerText == undefined)
            {
                return gridCell.textContent;
            }
            else
            {
                return gridCell.innerText;
            }
        }
        return null;
    }
    
    //Microsoft AJAX Calendar functions
   /* function hidecalendar(sender,args)
    {
        sender.hide();
    }*/
    
    //Custom Modal Popup functions
    function showmodpop(frameID, frameurl, popID)
    {
       iframeID = frameID;
       var iframe = document.getElementById(frameID);
       iframe.src = frameurl;
       var pop = $find(popID); 
       pop.show();
    }
    function showmodpop2(frameID, frameurl, popID, frameWidth, frameHeight)
    {
       iframeID = frameID;
       var iframe = document.getElementById(frameID);
       iframe.src = frameurl;
       iframe.style.width = frameWidth;
       iframe.style.height = frameHeight;
       var header = document.getElementsByClassName("ModPopHeader");
       header[0].style.width = frameWidth;
       var pop = $find(popID); 
       pop.show();
    }
    function hidemodpop(popID)
    {
         iframeID = "";
        var pop = $find(popID); 
        pop.hide();
    }
    
    //This cleans out spaces inside a table element - used so that code in firefox can work correctly also
    function cleanTable(tableElement)
    {
        var numTextElementsRemoved = 0;
        if (tableElement.nodeName != 'TD' && tableElement.nodeName != 'TH')
        {
            numTextElementsRemoved += cleanElement(tableElement);
            var node = tableElement.firstChild;
            while (node != null)
            {
	            numTextElementsRemoved += cleanTable(node);
	            node = node.nextSibling;
            }
        }
        return tableElement;
    }

    // removes all #text elements directly attached to the node.
    function cleanElement(element)
    {		
        if (element == null) return 0;
        var numTextElementsRemoved = 0;
        var node = element.firstChild;
        while (node != null)
        {
            var tmp = node.nextSibling;
            if (node.nodeName == '#text')
            {	
	            element.removeChild(node);
	            numTextElementsRemoved++;
            }
            node = tmp;
        }
        return numTextElementsRemoved;
    }
    
    function hidecalendar(sender,args)
    {
        sender.hide();
    }
    //================Ajax Functions for AutoComplete========================
    var keynum;
    document.onkeydown = getkeynum;
    document.onclick = hideautocomp;
    var autocompActiveID ="";
    //----This code checks whenever autocomplete is on.  If it's on,-----
    //----look for up, down, and enter key strokes.--------------------------
    function setautocompSel()
    {
       if (autocompActiveID.length > 0)
        {
            // alert("keynum " + keynum);
            //we're only interested in picking up up, down and enter keys.  Any other key we bypass.
            if (keynum == 40 || keynum == 38 || keynum == 13) 
            {
                var arrpnl = document.getElementsByClassNames("pnlautocomp", "autocomphigh");
                var arrhlink = document.getElementsByClassName("hlink");
                //40 is down arrow; 38 is up arrow; 13 is enter
               
               // alert(acSelIndex);
                //alert("arr length is " + arrpnl.length);
                switch (keynum)
                {
                    case 40:
                    if (acSelIndex < arrpnl.length-1)
                    {
                             if (acSelIndex >= 0)
                             {
                                arrpnl[acSelIndex].className = 'pnlautocomp';
                             }
                            acSelIndex++;
                            arrpnl[acSelIndex].className = 'autocomphigh';
                         
                        
                    }
                    break;
                    case 38:
                    if (acSelIndex >= 0)
                    {
                        arrpnl[acSelIndex].className = 'pnlautocomp';
                        if (acSelIndex > 0)
                         {
                            acSelIndex--;
                            arrpnl[acSelIndex].className = 'autocomphigh';
                         }
                         else if (acSelIndex ==0)
                         {
                            acSelIndex--;
                         }    
                    }
                    
                    break;
                case 13:
                    var href = document.getElementById("btnACEnter");
                    href.focus();
                    //alert(arrpnl[acSelIndex].focus());
                    //arrhlink[acSelIndex].focus()
                    if (document.getElementById("fldDescriptiontxt") != null) {
                        if (acSelIndex == -1) {
                            href.blur();
                            //document.getElementById("fldDescriptiontxt").value = "";
                            document.getElementById("fldDescriptiontxt").style.display = "";
                            document.getElementById("fldDescriptiontxt").blur();
                            document.getElementById("btnAddMedication").blur();
                        } else {
                            href.blur();
                            arrhlink[acSelIndex].click();
                        }
                    } else {
                        arrhlink[acSelIndex].click();
                    }
                    break;
                }
            }
        }
    }
    function getkeynumValue(e) {
        if (window.event) // IE
        {
            //alert("keycode " + event.keyCode);
            return event.keyCode;
        }
        else if (e.which) // Netscape/Firefox/Opera
        {
            return e.which;
        }

        //Set Autocomplete
        setautocompSel();
    }
    
    function getkeynum(e)
    {
          if(window.event) // IE
          {
          //alert("keycode " + event.keyCode);
          keynum = event.keyCode;
          }
          else if(e.which) // Netscape/Firefox/Opera
          {
          keynum = e.which;
          }
          
          //Set Autocomplete
          setautocompSel();
    }
    
    var ACparamnames = ""; //additional name of parameters for autocomplete
    var ACparamvalues = ""; //additional parameter values for autocomplete
    function getautocomp(txt, pnlID, divID, hdnID, typeofauto)
    {
        //only alphanumeric and stuff
        if ((keynum >= 48 && keynum <= 105) || keynum == 8 || keynum ==46 || keynum ==32)
        {
            //alert(keynum);
            //Reset hidden value on every keyup
           
            var hdn = document.getElementById(hdnID);
           // alert("hi");
         
//            alert(hdn.value);
//            hdn.value = '';
           
            
            var pnl = document.getElementById(pnlID);
            //alert(pnl.value);
            if ( txt.value.length > 2)
            {
                pnl.style.display = "";
                //This part's kind strange - we want the ability for autocomplete to accept additional parameters
                //That the AC stored proc may need.  So, we declare a global variable that saves the parameters
                //we send the required parameters along with the str of additional parameters to the web service.
                //var wsURL = 'https://www.patientally.com/common/AjaxRequests/AutoComplete.aspx?text=';
                var wsURL = '../AjaxRequests/AutoComplete.aspx?text=';
               // alert(ACparamvalues);
                ajaxRequest(wsURL + txt.value + '&textid=' + txt.id + '&hdnid=' + hdnID + '&pnlid=' + pnlID + '&type=' + typeofauto + "&acparamnames=" + ACparamnames + "&acparamvalues=" + ACparamvalues, divID);
             //   alert(wsURL + txt.value + '&textid=' + txt.id + '&hdnid=' + hdnID + '&pnlid=' + pnlID + '&type=' + typeofauto + "&acparamnames=" + ACparamnames + &acparamvalues=" + ACparamvalues);          
                autocompActiveID = pnlID;
            }
            else
            {
                pnl.style.display = "none";
            }
        }
    }

    function selectText(txtid, hdnid, txtvalue, targetid, pnlID, description) {
        iFrameAutoResize('iframe1', 'close');
        var txt = document.getElementById(txtid);
        var hdn = document.getElementById(hdnid);
        txt.value = txtvalue;
        hdn.value = targetid;
        var pnl = document.getElementById(pnlID);
        pnl.style.display = "none";
        var hdnDescr = document.getElementById("fldSelectiontxt");
        if (hdnDescr != "undefined") {
            //txt.value = txtvalue + ' - ' + description;
            hdnDescr.value = txtvalue;
			var div = document.getElementById("ctl00_cphPopup_ctl00_SearchAdvisor1_divAddMedication");
			if (div != "undefined") {
				div.style.display = "";
			}
			var div2 = document.getElementById("ctl00_cphPopup_ctl00_SearchAdvisor1_divSearchResults");
			if (div2 != "undefined") {
				div2.style.display = "none";
			}
        }
        
    }

    //this function is used to populate additional fields when an autocomplete value is selected
    //this is a default function in case normally you don't use it.  You may override it in your own page.
    function populateFields(txtID, fields)
    {
        //alert("i am only called when i am not overridden");
    }
    function hideautocomp()
    {
        //Inefficient way, but may have its uses
       /* var divs = document.getElementsByTagName("div");
        for (i=0; i< divs.length; i++)
        {
            if (divs[i].id.contains("autocomppnl"))
            {
                divs[i].style.display = "none";
            }
        }*/
        if (autocompActiveID.length > 0)
        {
            var pnl = document.getElementById(autocompActiveID);
            pnl.style.display = "none";
        }
        iFrameAutoResize('iframe1', 'close');
    }
    
    
    
    function iFrameAutoResize(frameID, mode) 
    {
      
      var iFrame = parent.document.getElementById ? parent.document.getElementById(frameID) : parent.document.all[frameID];
      if (iFrame != null && iFrame != "undefined")
      {
          switch (mode)
          {
            case "open":
                  var iFrameContent = iFrame.contentDocument ? iFrame.contentDocument : document.frames(frameID).contentWindow.document;
                  var autocomp = iFrameContent.getElementsByClassName("autocompbox");
                  //alert(autocomp[0].offsetHeight);
                  if (autocomp[0] != null && autocomp[0] != "undefined")
                  {
                    //iFrame.height = iFrame.height + autocomp[0].offsetHeight;//iFrameContent.body.offsetHeight + 10;
                    if (autocomp[0].offsetHeight > 700)//Don't make it bigger than the screen
                    {
                        iFrame.height = 700;
                    }
                    else
                    {
                        iFrame.height = autocomp[0].offsetHeight + 100;
                    }
                  }
              
            break;
            case "close":
             iFrame.height = 300;
             break;
          } 
      }
    }
    //This is already supported in Firefox 3.  But I don't think it's supported in any other versions.  So this is the function.
    document.getElementsByClassName = function(v){
                                        e=document.getElementsByTagName("*"),f=[];
                                        if (e.length > 0)
                                        {
                                            for(i in e)if(e[i].className==v)f.push(e[i]);return f;
                                        }
                                        else
                                        {
                                            return null;
                                        }
                                        }
                                        
    //My own javascript function.  Use this to get elements inside autocomplete box.
     document.getElementsByClassNames = function(v, w){
                                        e=document.getElementsByTagName("*"),f=[];
                                        if (e.length > 0)
                                        {
                                            for(i=0; i<= e.length-1; i++)
                                            {
                                                if(e[i].className==v||e[i].className==w)
                                                    f.push(e[i]);
                                            }
                                            return f;
                                        }
                                        
                                        else
                                        {
                                            return null;
                                        }
                                        }
                                        

    function setFocus(txtname)
    {
       var txt = document.getElementById(txtname);
       txt.focus();
    }
    //=====================Third Party Functions that fix IE/Mozilla Crap=================
    //fixes the hlink.click() problem in mozilla (you suck btw)
    if("HTMLElement" in window) // IE
    {
        HTMLElement.prototype.click = function() {
            var evt = this.ownerDocument.createEvent('MouseEvents');
            evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
            this.dispatchEvent(evt);
    
            }
    } 
    //===========Functions for UserControl Search Filter ===========================
     var searchcontent = new Array();
     function getsearchFields(ddlID, txt, divID, SPName, searchtype, mode)
    {
        if (txt.value.length > 1 || mode == "viewall")
        {
             var ddl = document.getElementById(ddlID);
            var colName = ddl.options[ddl.selectedIndex].value;
            var searchtext = convertsearchcontent();
			
             ajaxRequestGrid('/pm/Common/ajaxRequests/ajaxSearch.aspx?searchcontent=' + searchtext + '&colname=' + colName + '&searchtext=' + txt.value + '&searchtype=' + searchtype + '&spname=' + SPName, divID, gridDT);
        }
         
    }
    
    //This function is used specifically for the Inbox
    //btnsel is the type of mail (inbox, drafts, sent, archived)
    function getsearchFieldsInbox(ddlID, txt, divID, SPName, searchtype, btnsel)
    {
        if (txt.value.length > 1)
        {
             var ddl = document.getElementById(ddlID);
            var colName = ddl.options[ddl.selectedIndex].value;
            var searchtext = convertsearchcontent();
            ajaxRequest('/pm/Common/ajaxRequests/ajaxSearch.aspx?spname=' + SPName  + '&searchcontent=' + searchtext + '&colname=' + colName + '&searchtext=' + txt.value + '&searchtype=' + searchtype + '&btnsel=' + btnsel, divID);
        }
         
    }
    
    function convertsearchcontent()
    {
            var searchtext="";
			
			//alert(searchcontent.length);
		
            if (searchcontent.length > 0)
            {
                var a;
                for(a=0; a<=searchcontent.length; a++)
                {
				   
                    if (searchtext.length > 0)
                    {
                        searchtext += "|" + searchcontent[a]; 
                    }
                    else
                    {
                        searchtext = searchcontent[a];
                    }
                    
                }
            }
            return searchtext;
    }
    
    function loadCriteria(divID)
    {
       var div = document.getElementById(divID);
       var a;
       var strfilter="";
       var fieldname;
       var strtext;
       var arr;
       for (a=0; a<=searchcontent.length -1; a++)
       {
            if (searchcontent[a])
            {
                arr = searchcontent[a].split("*");
                fieldname = arr[2];
                strtext = arr[1] ;
                if (strfilter.length > 0)
                {
                    strfilter += "<br /> ";
                }
                strfilter +=  fieldname + " contains <b>'" + strtext + "'</b>";
            }
       } 
       if (strfilter.length > 0)
       {
            strfilter += "<br /><div onclick='javascript:clearfilter()' class='filterbtn'>click to clear</div>";
       }
       div.innerHTML = strfilter;
    }
    //This is already supported in Firefox 3.  But I don't think it's supported in any other versions.  So this is the function.
    document.getElementsByClassName = function(v){
                                        e=document.getElementsByTagName("*"),f=[];
                                        if (e.length > 0)
                                        {
                                            for(i in e)if(e[i].className==v)f.push(e[i]);return f;
                                        }
                                        else
                                        {
                                            return null;
                                        }
                                        }
                                        
    //My own javascript function.  Use this to get elements inside autocomplete box.
     document.getElementsByClassNames = function(v, w){
                                        e=document.getElementsByTagName("*"),f=[];
                                        if (e.length > 0)
                                        {
                                            for(i=0; i<= e.length-1; i++)
                                            {
                                                if(e[i].className==v||e[i].className==w)
                                                    f.push(e[i]);
                                            }
                                            return f;
                                        }
                                        
                                        else
                                        {
                                            return null;
                                        }
                                        }
                                        
                 
    //=================Functions for submenu tabs (forms)=================================
    function grdtabminimize(grdID)
    {
        var grd = document.getElementById(grdID);
        grd.style.display = "none";
    }
    
    function grdtabmaximize(grdID)
    {
        var grd = document.getElementById(grdID);
        grd.style.display = "";
    }
    //=================Code For Rounded Corners===========================================
    function NiftyCheck()
    {
    if(!document.getElementById || !document.createElement)
        return(false);
    var b=navigator.userAgent.toLowerCase();
    if(b.indexOf("msie 5")>0 && b.indexOf("opera")==-1)
        return(false);
    return(true);
    }

    function Rounded(selector,bk,color,size){
    var i;
    var v=getElementsBySelector(selector);
    var l=v.length;
    for(i=0;i<l;i++){
        AddTop(v[i],bk,color,size);
        AddBottom(v[i],bk,color,size);
        }
    }

    function RoundedTop(selector,bk,color,size){
    var i;
    var v=getElementsBySelector(selector);
    for(i=0;i<v.length;i++)
        AddTop(v[i],bk,color,size);
    }

    function RoundedBottom(selector,bk,color,size){
    var i;
    var v=getElementsBySelector(selector);
    for(i=0;i<v.length;i++)
        AddBottom(v[i],bk,color,size);
    }

    function AddTop(el,bk,color,size){
    var i;
    var d=document.createElement("b");
    var cn="r";
    var lim=4;
    if(size && size=="small"){ cn="rs"; lim=2}
    d.className="rtop";
    d.style.backgroundColor=bk;
    for(i=1;i<=lim;i++){
        var x=document.createElement("b");
        x.className=cn + i;
        x.style.backgroundColor=color;
        d.appendChild(x);
        }
    el.insertBefore(d,el.firstChild);
    }

    function AddBottom(el,bk,color,size){
    var i;
    var d=document.createElement("b");
    var cn="r";
    var lim=4;
    if(size && size=="small"){ cn="rs"; lim=2}
    d.className="rbottom";
    d.style.backgroundColor=bk;
    for(i=lim;i>0;i--){
        var x=document.createElement("b");
        x.className=cn + i;
        x.style.backgroundColor=color;
        d.appendChild(x);
        }
    el.appendChild(d,el.firstChild);
    }

    function getElementsBySelector(selector){
    var i;
    var s=[];
    var selid="";
    var selclass="";
    var tag=selector;
    var objlist=[];
    if(selector.indexOf(" ")>0){  //descendant selector like "tag#id tag"
        s=selector.split(" ");
        var fs=s[0].split("#");
        if(fs.length==1) return(objlist);
        return(document.getElementById(fs[1]).getElementsByTagName(s[1]));
        }
    if(selector.indexOf("#")>0){ //id selector like "tag#id"
        s=selector.split("#");
        tag=s[0];
        selid=s[1];
        }
    if(selid!=""){
        objlist.push(document.getElementById(selid));
        return(objlist);
        }
    if(selector.indexOf(".")>0){  //class selector like "tag.class"
        s=selector.split(".");
        tag=s[0];
        selclass=s[1];
        }
    var v=document.getElementsByTagName(tag);  // tag selector like "tag"
    if(selclass=="")
        return(v);
    for(i=0;i<v.length;i++){
        if(v[i].className==selclass){
            objlist.push(v[i]);
            }
        }
    return(objlist);
    }
//=====================Code for the Custom GridView Control===============================
function loadcustomsummary(formID)//Note: you may have to adjust the parameters passed in (like iframe1)
{
    if (formID > 0 && formID < 8) //Patient forms
    {
        showmodpop2('iframe1', 'popups/popup.aspx?page=poppatientforms.ascx&mode=view&formid=' + formID, "pop1", "600px", "400px");
    }
    else if ( formID == 8)
    {
        showmodpop2('iframe1', 'popups/popup.aspx?page=manageextpro', "pop1", "1200px", "600px")
    } 
    else //EHR Forms
    {
        showmodpop2('iframe1', 'popups/popup.aspx?page=poppatientsummary.ascx&formid=' + formID, "pop1", "600px", "400px");
    }
}
//=====================Functions for Report===============================================
function printdiv(divID)
{
    var div = document.getElementById(divID);
    
    var newwin = window.open('','','left=0,top=0,width=1,height=1, toolbar=0,scrollbars=0,status=0');
    newwin.document.open();
    newwin.document.write("<html><head>");
    newwin.document.write('<link rel="stylesheet" href="/CMAlly2/css/PatientChannel.css" type="text/css" />');
    newwin.document.write('<link rel="stylesheet" href="/CMAlly2/css/formfield.css" type="text/css" />');
    newwin.document.write("</head><body>");
    newwin.document.write(div.innerHTML);
    newwin.document.write("</body></html>");
    newwin.document.close();
    newwin.focus();
    newwin.print();
    newwin.close();
}
//======================Functions for Height and Weight FormField=========================
       //convert pound to kg (weight) 
       function kgconv(txtID)
        {
            var kg =  document.getElementById(txtID);
            if (kg.value.contains("lb"))
            {
                var mysplit = "lb";
                var mySplitResult = kg.value.split(mysplit, 1);   
                var weightconv = mySplitResult.toString();
                kg.value =(Math.round(weightconv / 2.2)).toFixed(1);    
            }
        }
                
        function setautocompConvKg(txtID)
        {
            var autocompConvKg = document.getElementById(txtID);
            if (autocompConvKg.value.length > 0 && autocompConvKg.value.contains("lb") == false )
            {
               if (keynum == 32)
               {
                 autocompConvKg.value = autocompConvKg.value + "lb ";
                
               }             
            } 
        }
           //convert feet to cm (height)      
        function inchconv(txtID)
        {
            var feet =  document.getElementById(txtID);
            var inch =  document.getElementById(txtID);
            var feetconv =  document.getElementById(txtID);
            if (feet.value.contains("ft") && feet.value.contains("inch") )
            {
                var mysplit = "ft";   
                var mySplitResult = feet.value.split(mysplit, 2);
                var myarray = mySplitResult.toString();        
                var mySplitResultinch= myarray.split("inch", 1);
                var replpd = mySplitResultinch.toString();
                var replperiod = replpd.replace(/\,/g,".");
                var replspace = replperiod.toString();       
                var repl = replspace.replace(/ /g,"");         
             
                var floatconv = repl.toString();
                floatconv=(Math.round(floatconv * 12)).toFixed(1);
                feet.value =(Math.round(floatconv* 2.54)).toFixed(1);
	        } 
	        	       
	        if (inch.value.contains("inch"))
	        {
	           var mysplit = "inch";
	           var myinch = inch.value.split(mysplit, 2);
	           var convstr = myinch.toString();
	           var splitcomma = convstr.split(",", 1);
	           inch.value = (Math.round(splitcomma * 2.54)).toFixed(1);
	        }
	        
	        if (feetconv.value.contains("ft"))
	        {
	            var myfeetspl = "ft";
	            var feetConvRe = feetconv.value.split(myfeetspl, 2);
	            var feetconvstr = feetConvRe.toString();
	            var feetsplitcomma = feetconvstr.split(",", 1);
	            feetconv.value = (Math.round(feetsplitcomma* 30.48)).toFixed(1);
	            
	        }
        }
        		
        function setautocompConv(txtID, pnlID, pnlshow)
        {
             var autocompConv = document.getElementById(txtID);

              var x;
              x = autocompConv.value.length - 1;
              var anum=/(^\d+$)|(^\d+\.\d+$)/; 
            
            
              if (keynum == 32 || keynum == 38 || keynum == 40)
               {
                           
                   switch (keynum)
                  { 
                         case 32:

                        //alert(anum.test(autocompConv.value.substring(0, x)));
                            
                        if(anum.test(autocompConv.value.substring(0, x)) == true)//if it's a number
                        {
                            autocompConv.value = autocompConv.value + "ft ";
                        }
                        
                        else if (anum.test(autocompConv.value.substring(x-1, x)) == true && autocompConv.value.contains("inch") == false)
                        {
                            autocompConv.value = autocompConv.value + "inch ";
                            hideToolTip(pnlID, pnlshow);
                        } 
                      
                               
                        else 
                        {
                          // do nothing
                        }              
                   
                     break;
                  
                     case 38:
                        
                       if (autocompConv.value.length > 0 && autocompConv.value.contains("ft") == true && autocompConv.value.contains("inch") == false  )
                       {
                             autocompConv.value = autocompConv.value.replace("ft", "inch");
                               
                       }
                                           
                        hideToolTip(pnlID, pnlshow);
                     break;
                     case 40:
                    
                        if (autocompConv.value.length > 0 && autocompConv.value.contains("inch") == true && autocompConv.value.contains("ft") == false )
                             {
                             autocompConv.value = autocompConv.value.replace("inch", "ft");
                             }
                       hideToolTip(pnlID, pnlshow);
                     break; 
                    
                }
                       
          }  
                 
           
        }
  
 
      function showToolTip(txtID, pnlheight, plnshow)
      {
                var obj = document.getElementById(pnlheight);
                var plnbtn = document.getElementById(plnshow);
                if (obj.style.display != 'block')
                {
                    getXYPos(txtID);		        
    		
                    obj.style.display = 'block';
                    var left = 0;
                    left = curleft + 40;
                    obj.style.left =  left + 'px';
                    var top = 0;
                    top = curtop - 120;
                    obj.style.top = top  + 'px';
                    plnbtn.style.display = 'none';
                           
                }
               
               
        }
      function hideToolTip(pnlID, pnltxt)
        {
               var obj = document.getElementById(pnlID);
               var pnlshow = document.getElementById( pnltxt);
              
               
                   obj.style.display = 'none';
                   pnlshow.style.display = 'block';
                   
                   
                
        }
//======================Code to detect scrolling==========================================
function hookEvent(element, eventName, callback)
{
  if(typeof(element) == "string")
    element = document.getElementById(element);
  if(element == null)
    return;
  if(element.addEventListener)
  {
    if(eventName == 'mousewheel')
      element.addEventListener('DOMMouseScroll', callback, false);  
    element.addEventListener(eventName, callback, false);
  }
  else if(element.attachEvent)
    element.attachEvent("on" + eventName, callback);
}

function unhookEvent(element, eventName, callback)
{
  if(typeof(element) == "string")
    element = document.getElementById(element);
  if(element == null)
    return;
  if(element.removeEventListener)
  {
    if(eventName == 'mousewheel')
      element.removeEventListener('DOMMouseScroll', callback, false);  
    element.removeEventListener(eventName, callback, false);
  }
  else if(element.detachEvent)
    element.detachEvent("on" + eventName, callback);
}        
  
function MouseWheel(e)
{
  e = e ? e : window.event;
  var wheelData = e.detail ? e.detail * -1 : e.wheelDelta / 40;
  //do something
  
 return cancelEvent(e);
}

function cancelEvent(e)
{
  e = e ? e : window.event;
  if(e.stopPropagation)
    e.stopPropagation();
  if(e.preventDefault)
    e.preventDefault();
  e.cancelBubble = true;
  e.cancel = true;
  e.returnValue = false;
  return false;
} 

//==================Converts date to local (UTC) time=============================
function  parsedate(start)
{
    var dt = new Date(start);           
    
    //convert to AM/PM
    var x = dt.getUTCHours()/12;
    
    var month;
    var hour;
    var min;
    var unit;
    var VisitDate;
    if (x > 1)
    {
        hour = dt.getUTCHours() % 12;
        unit = "PM";
    }
    else if (x == 1)
    {
        hour = 12;
        unit = "PM";
    }
    else
    {
        hour = dt.getUTCHours();
        unit = "AM";
    }
    //hour = setTimeString(hour);
    min = setTimeString(dt.getUTCMinutes());
    month = dt.getUTCMonth() + 1; 

    return month + "/" + dt.getUTCDate() + "/" + dt.getUTCFullYear() + " " + hour + ":" + min + ":00 " + unit;
}   
function setTimeString(time)
{
    if (time <10)
    {
        time = "0" + time;
    }
    return time;
}
function Right(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}

//======================Cookie Functions==================================================
function setCookie(name, value, expires) {
    // no expiration date specified? use this date and it will just be deleted soon.
    if (!expires) expires = new Date();
    document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() + "; path=/";
}

function getCookie(name) {
    var cookies = document.cookie;
    if (cookies.indexOf(name) != -1) {
        var startpos = cookies.indexOf(name) + name.length + 1;
        var endpos = cookies.indexOf(";", startpos) - 1;
        if (endpos == -2) endpos = cookies.length;
        return unescape(cookies.substring(startpos, endpos));
    }
    else {
        return false; // the cookie couldn't be found! it was never set before, or it expired.
    }
}
//========================================================================================    
    //=================Code that may come useful later====================================
/*function getautocomp()
{
var txt = document.getElementById('<%=txtautocomplete.clientID %>');
var pnl = document.getElementById('<%=pnlauto.clientID %>');
if ( txt.value.length > 2)
{
pnl.style.display = "";
var pnl = document.getElementById('<%=divauto.clientID %>');
pnl.innerHTML = '<div style="text-align:center; width:100%" ><img src="../GFX/ajaxloading_blue.gif"/></div>';
ajaxRequest('AjaxRequests/AutoComplete.aspx?text=' + txt.value + '&textid=<%=txtautocomplete.clientID %>&hdnid=<%=hdnauto.clientID %>', '<%=divauto.clientID %>'); 
}
else
{
pnl.style.display = "none";
}
}*/