var navAppName = navigator.appName.toLowerCase();
var isMoz = false;
var isMs = false;
var jsonurl = "/vco/JSON-RPC";
var jsonrpc = null;
var page=0;
var edit=1;
var task=2;
var mail=3;
var im=4;
var oWin=new Array();

if(navAppName.indexOf('netscape')>-1){
  isMoz = true;
} else if(navAppName.indexOf('microsoft')>-1){
  isMs = true; 
}

function makeDropdownContent(initContent, initCodeType, initChildScope, initChildId, initBehavior) {
  var obj = new Object();
  obj['content'] = initContent;
  obj['ICD9Code'] = initCodeType;
  obj['childDropdownScope'] = initChildScope;
  obj['childDropdownId'] = initChildId;
  obj['behavior'] = initBehavior;
  return obj;
}

var ddLocalCache = new Array();
function renderOptions(ddScope, ddId) {
  var dropdowns = getDropdown(true, ddScope, ddId);
  if (dropdowns == null) {
    return;
  }
  for (var i = 0; i < dropdowns.length; i++) {
    document.write('<option value="'+dropdowns[i].behavior+'">'+dropdowns[i].content+'</option>');
  }
}



function getDropdown(globalCached, ddScope, ddId) {
  var dropdowns;
  var ddName = ddScope+"-"+ddId;
  if (ddLocalCache != null) {
    dropdowns = ddLocalCache[ddName];
    if (globalCached && dropdowns != null) {
      if (moveToCache(ddName,dropdowns)) {
        noteDropdownGlobalCached(ddScope, ddId);
      }
    }
  }
  if (dropdowns == null) {
    dropdowns = retrieveFromCache(ddName);
  }
  if (dropdowns == null) {
    // RPC
    dropdowns = retrieveDropdownViaJSON(ddScope, ddId);
    // GLOBAL CACHE
    if (globalCached) {
      if (moveToCache(ddName,dropdowns)) {
	noteDropdownGlobalCached(ddScope, ddId);
      }
    } else {
      ddLocalCache[ddName] = dropdowns;
    }
  }
  return dropdowns;
}

function retrieveFromCache(ddScopeId) {
  if (top.ddCache) {
    return top.ddCache[ddScopeId];
  }
  else if (parent.parent.ddCache) {
    return parent.parent.ddCache[ddScopeId];
  } else if (parent.parent.parent.ddCache) {
    return parent.parent.parent.ddCache[ddScopeId];
  } else if (parent.parent.parent.parent.ddCache) {
    return parent.parent.parent.parent.ddCache[ddScopeId];
  }
  return null;
}

function moveToCache(ddScopeId, list) {
  if (top.ddCache) {
    top.ddCache[ddScopeId] = list;
  }
  else if (parent.ddCache) {
    parent.ddCache[ddScopeId] = list;
  } else if (parent.parent.ddCache) {
    parent.parent.ddCache[ddScopeId] = list;
  } else if (parent.parent.parent.ddCache) {
    parent.parent.parent.ddCache[ddScopeId] = list;
  } else if (parent.parent.parent.parent.ddCache) {
    parent.parent.parent.parent.ddCache[ddScopeId] = list;
  } else if (parent.parent.parent.parent.parent.ddCache) {
    parent.parent.parent.parent.parent.ddCache[ddScopeId] = list;
  } else {
    return false;
  }
  return true;
}

function noteDropdownGlobalCached(ddScope, ddId) {
  var jsonrpc = parent.parent.jsonrpc;
  if (jsonrpc == null) {
    jsonrpc = new JSONRpcClient(jsonurl);
  }
  jsonrpc.rpcUtil.noteDropdownGlobalCached(ddScope, ddId);
}

function retrieveDropdownViaJSON(ddScope, ddId) {
  var jsonrpc = parent.parent.jsonrpc;
  if (jsonrpc == null) {
    jsonrpc = new JSONRpcClient(jsonurl);
  }
  var temp = null;
  temp = jsonrpc.rpcUtil.getDropdownContent(ddScope, ddId);
  if (temp == null) { return new Array(); }
  return temp;
}

function makeOptions(dropdowns) {
   var options = new Array(dropdowns.length);
   for (var i = 0; i < dropdowns.length; i++) {
     var optionText = dropdowns[i].content;
     var behavior = dropdowns[i].behavior;
     options[i] = new Option(optionText, ''+behavior);
   }
   return options;
}

function doPatientLabPopupConfirm(){
  if (document.patientMenuForm.doConfirm.value=='true'){
    if (!confirm("Are you sure you want to leave this page without saving?")){
      return;
    }
  }
  doPatientLabPopup();
}


function doPatientLabPopup(){
  var pid = (document.patientMenuForm.pid.value);
  
  if(pid>10){
//oWin[page].open("EDI Labs", "/vco/lab/labReports.jsp?popup=1&pid="+pid,900, 570, 10, document.body.scrollTop+60);
    oWin[page].open("EDI Labs", "",900, 570, 10, document.body.scrollTop+60);
     document.patientMenuForm.targetAction.value = 33;
     document.patientMenuForm.target = "iframe0";
     document.patientMenuForm.submit();
     document.patientMenuForm.target = "_self";
  }
  else{
    alert('Please select a patient before selecting one of these patient functions.');
  }
}

function doPatientLabPopupFrame(){
  var pid = (parent.parent.document.patientMenuForm.pid.value);

  if(pid>10){
   oWin[page].open("EDI Labs", "/vco/lab/labReports.jsp?popup=1&pid="+pid,900, 570, 10, document.body.scrollTop+60);
  }
  else{
    alert('Please select a patient before selecting one of these patient functions.');
  }
}

function doManualLabResult() {
  var pid=(document.patientMenuForm.pid.value);
  if(pid>10){
   oWin[page].open("Manual Lab Results", "/vco/lab/manualLabResults.jsp?pid="+pid,900, 570, 10, document.body.scrollTop+60);
  }
  else{
    alert('Please select a patient before selecting one of these patient functions.');
  }
}
function doRxHubPopup(){
  var pid = (document.patientMenuForm.pid.value);
  if(pid>10){
     oWin[page].open("Medication History", "/vco/rxHub/rxHubEligibility.jsp?pid="+pid,900, 640, 10, document.body.scrollTop+60);
     
  }
  else{
    alert('Please select a patient before selecting one of these patient functions.');
  }
}


function isMozilla(){
  return isMoz;
}

function isIE(){
  return isMs;
}

// check if netscape
NS4 = (document.layers) ? true : false;
var amAtCal=false;
function openPopup(url, setting){
  var newWin = window.open(url, "popup", setting, false);
  void('');
  newWin.focus();
  return newWin;
}

function openRandPopup(url, setting){
  var num=Math.floor(Math.random()*10000);
  eval("var newWin"+num+" = window.open(url, \"popup"+num+"\", setting, false)");
  void('');
  eval("newWin"+num+".focus()");
  return;
}
function getSpecHelp(loc){
  oWin[page].open("Help Pages", "/vco/help/doHelp.jsp?loc="+loc, 900, 570, 10, document.body.scrollTop+60);
  return;
}
function getWinSpecHelp(loc) {
  var win=openRandPopup("/vco/help/doHelp.jsp?loc="+loc, "width=900, height=570, location=no, menubar=no, scrollbars=yes, status=yes, resizable=yes, toolbar=yes");
  return;
}
function getWinMainHelp() {
  openRandPopup("/vco/help/index.html", "width=900, height=570, location=no, menubar=no, scrollbars=yes, status=yes, resizable=yes, toolbar=yes");
  return;
}
function openWinTutorial(name){
  openRandPopup(getTutorialUrl(name), "width=900, height=570, location=no, menubar=no, scrollbars=yes, status=yes, resizable=yes, toolbar=yes");
  return;
}
function openTutorial(name){
  oWin[im].open(name+" Tutorial", getTutorialUrl(name), 900, 570, 10, document.body.scrollTop+60);
  return;
}
function getTutorialUrl(name){
	var bu="/vco/help/";
	if (name=="EMR") return bu+"EMR_Training.htm";
	else if (name=="Billing") return bu+"Billing_Process.htm";
	else if (name=="HPI") return bu+"SynaTutorial_HPI.htm";
        else if (name=="Scheduling Templates") return bu+"SynaTutorial_SchedTemplates.htm";
        else if (name=="eRx") return bu+"SynaTutorial_eRxTraining.htm";
        else if (name=="Global Note Settings") return bu+"SynaTutorial_GlobalNoteSettings.htm";
	return bu+"index.html";
}
function getMainHelp() {
  oWin[page].open("Help Pages", "/vco/help/index.html", 900, 570, 10, document.body.scrollTop+60);
  return;
}
function funcname(f) {
 var s = f.toString().match(/function (\w*)/)[1];
 if ((s == null) || (s.length==0)) return "anonymous";
 return s;
}
function stacktrace() {
 var s = "";
 for (var a = arguments.caller; a !=null; a = a.caller) {
   s += "->"+funcname(a.callee) + "\n";
   if (a.caller == a) {s+="*"; break;}
 }
 return s;
}
function isBlank(s){
	for (var i =0; i<s.length; i++){
		var c = s.charAt(i);
		if( (c!=' ') && (c != '\n') && (c  != '\t')) 
			return false;
	}
	return true;
}

function validateSelected(selection, errmsg){
	if (selection.selectedIndex<0 )	{
		alert (errmsg);
		return false;
	} 
	return true;
}
function trim(str) {
  str = str.replace( /^\s+/g, "");
  return str.replace( /\s+$/g, "");
}
function y2k(number) {
  number = new Number(number); 
 if(number < 1000){
  if(number >= 100){
    number += 1000;
  } else {
    number += 1900;
  }
 }
 return number;
}  

var reason = '';

function isValidDate (myDate,sep) {
// checks if date passed is in valid mm/dd/yyyy or mm/dd/yy format

    if (myDate.length <= 10  && myDate.length >= 8) {
        if (myDate.substring(2,3) == sep && myDate.substring(5,6) == sep) {
            var month  = myDate.substring(0,2);
            var date = myDate.substring(3,5);
            var year  = myDate.substring(6, myDate.length);
			
			month = new Number(month);
			date = new Number(date);
			year = new Number(year);
			
			var test = new Date(year,month-1,date);
//			alert(y2k(year) + " " + y2k(test.getYear()));
//            if (new Number(y2k(year)) != new Number(y2k(test.getYear()))){
//			  alert("Invalid year.");
//			  return false;
//			}
			if((month-1) != test.getMonth()){
			  alert("Invalid month.");
			  return false;
			}
			if(date != test.getDate()) {
			  alert("Invalid date.");
			  return false;
			}
            return true;
            
        }
        else {
            reason = 'invalid spearators';
            return false;
        }
    }
    else {
        reason = 'invalid length';
        return false;
    }
	return true;
}

function makeCascadeDdd(propName, ddId, formName, refreshTa, value, options, size, onenter){
        var sb="";
	var divName = "comboDiv" + propName;
	var selectName = "comboSelect" + propName;
	var idName = "comboId" + propName;
        sb+="<input type=\"text\" name=\""+propName+"\" size=\""+size+"\" value=\""+value+"\"";
        if (onenter==null || onenter==""){
        sb+=" onKeyDown=\"return checkEnter(event, this, this.form['"+selectName+"'],'text');\" ";
        } else {
        sb+=" onKeyDown=\"return checkEnter(event, this, this.form['"+selectName+"'],'text','"+onenter+"');\" ";
        }
        sb+="onfocus=\"initDropdown('"+divName+"');\" onBlur=\"notifyBlur('"+divName+"');\">";
	sb+="<span id=\""+divName+"\" class=\"absolute\" style=\"position:absolute\">";
	sb+="<select size=\"0\" name=\""+selectName+"\" id=\""+idName+"\" class=\"absolute\"";
        sb+=" onfocus=\"hideChildDropdown(this, '"+divName+"')\" onblur=\"notifyBlur('"+divName+"'this)\"";
        sb+=" onChange=\"doSelect(event, this, '"+formName+"', 'options', '1', '"+ddId+"', '"+refreshTa+"',";
        sb+=" 'false', '0', 'false');\">";
        for (var i=0; i<options.length; i++){
                sb+="<option>"+options[i]+"</option>";
        }
        sb+="<option value=\""+ddId+"\">Edit...</option></select>";
	sb+="</span>";
        return sb;
}

function makeEditDdd(propName, ddId, formName, refreshTa, value, options, size, onenter){
	var sb="";
	sb+="<input type=\"text\" name=\""+propName+"\" size=\""+size+"\" value=\""+value+"\"";
	if (onenter==null || onenter==""){
	sb+=" onKeyDown=\"return checkEnter(event, this, this.form['comboSelect"+propName+"'],'text');\" ";
	} else {
	sb+=" onKeyDown=\"return checkEnterExec(event, this, this.form['comboSelect"+propName+"'],'text','"+onenter+"');\" ";
	}
	sb+="onfocus=\"showByLink('comboId"+propName+"',this);\" onBlur=\"hide('comboId"+propName+"');\"";
	sb+="><select size=\"0\" name=\"comboSelect"+propName+"\" id=\"comboId"+propName+"\" class=\"absolute\"";
	sb+=" onfocus=\"noteOnOpts(this)\" onblur=\"noteOutOpts(this)\" onmouseup=\"\" onmousedown=\"\"";
	sb+=" onChange=\"doSelect(this, '"+formName+"', 'options', '1', '"+ddId+"', '"+refreshTa+"',";
	sb+=" 'false', '0', 'false');\">";
	for (var i=0; i<options.length; i++){
		sb+="<option>"+options[i]+"</option>";
	}
	sb+="<option value=\""+ddId+"\">Edit...</option></select>";
	return sb;
}
function gebi(name){
  return document.getElementById(name);
}
function isValidDateStrict (myDate,sep,yearDigits) {
// checks if date passed is in valid with number of digits in year yearDigits
    if (myDate.length == (6+yearDigits) ) {
        if (myDate.substring(2,3) == sep && myDate.substring(5,6) == sep) {
            var month  = myDate.substring(0,2);
            var date = myDate.substring(3,5);
            var year  = myDate.substring(6, myDate.length);

                        month = new Number(month);
                        date = new Number(date);
                        year = new Number(year);

                        var test = new Date(year,month-1,date);
//                      alert(y2k(year) + " " + y2k(test.getYear()));
//            if (new Number(y2k(year)) != new Number(y2k(test.getYear()))){
//                        alert("Invalid year.");
//                        return false;
//                      }
                        if((month-1) != test.getMonth()){
                          alert("Invalid month.");
                          return false;
                        }
                        if(date != test.getDate()) {
                          alert("Invalid date.");
                          return false;
                        }
            return true;

        }
        else {
            reason = 'invalid spearators';
            return false;
        }
    }
    else {
        reason = 'invalid length';
        return false;
    }
        return true;
}

function checkKeyEnter(event, form) { // checks if user clicked enter, if so, then submit form object
	if (event != null && form != null) {
		var code = 0;
		if (NS4) {
			code = event.which;
		} else {
			code = event.keyCode;
		}
		if (code==13) {
			form.submit();
		}
	}
}

function figureDays(month, year){
  var isLeapYear=(year%4==0);
  var numdays=new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  if (isLeapYear){
    numdays[1]=29;
  }
  return numdays[month];
}

function enforceDaysBlank(dayElement, monthElement, yearElement, dayValueOffset, optOffset){
    var days=figureDays(monthElement.options[monthElement.selectedIndex].value, yearElement.options[yearElement.selectedIndex].value);
    var selectedDay=dayElement.selectedIndex;
    for (i=31; i>27; i--){
      dayElement.options[i+optOffset]=null;
    }
    for (j=28; j<days+1; j++){
      dayElement.options[j-1+optOffset] = new Option(j, j+dayValueOffset);
    }
    if (selectedDay<days){
        dayElement.selectedIndex=selectedDay;
    } else {
        dayElement.selectedIndex=days-1;
    }
}

function enforceDays(dayElement, monthElement, yearElement, dayValueOffset){
    var days=figureDays(monthElement.options[monthElement.selectedIndex].value, yearElement.options[yearElement.selectedIndex].value);
    var selectedDay=dayElement.selectedIndex;
    for (i=31; i>27; i--){
      dayElement.options[i]=null;
    }
    for (j=28; j<days+1; j++){
      dayElement.options[j-1] = new Option(j, j+dayValueOffset);
    }
    if (selectedDay<days){
        dayElement.selectedIndex=selectedDay;
    } else {
        dayElement.selectedIndex=days-1;
    }
}

function pubMed() {
  window.open("http://www.ncbi.nlm.nih.gov/entrez/query.fcgi");
}

function parseBool(boolStr){
  return (boolStr=="true" || boolStr=="yes" || boolStr=="on");
}

function enforceChecked(field, checked){
  field.checked=checked;
}

function openIM() {

    window.open("/vco/insideImSupport.jsp","_blank","toolbar=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, width=450, height=400, location=no, titlebar=no");
}

function openInventory(){
	if(top.SynaTabConst.USE_TAB){
    	top.SynaTab.doShow("h_inventory");
    	return;
	}
}

function openPatientPortal(){
	if(top.SynaTabConst.USE_TAB){
    	top.SynaTab.doShow("h_patientPortal");
    	return;
	}
}

function openMailClient() {
	
   if(top.tutorialEnabled){ top.showNextStepTutorial(); }
   
    if(top.SynaTabConst.USE_TAB){
    	top.SynaTab.doShow("h_email2");
    	return;
	}
   
   
   //window.open("/vco/message/mainMenu.jsp", "Messaging", "width=750, height=475, location=no, menubar=no, scrollbars=yes, status=yes, resizable=yes");
   if(window.frames['mainFrame']){
     top.oWin[mail].open(" Email", "/vco/message/mainMenu.jsp?c=1", 880, 570, 50, document.body.scrollTop+67);
     top.oWin[mail].focus();
   } else {
     oWin[mail].open(" Email", "/vco/message/mainMenu.jsp?c=1", 880, 570, 50, document.body.scrollTop+67);
     oWin[mail].focus();
   }
   return;
}

function openComposeMail(){	
	oWin[mail].open("New Phone Message", "/vco/message/mainMenu.do?targetAction=3", 880, 570, 50, document.body.scrollTop+67);
	oWin[mail].focus();
	return;
}

function openSupportMail(){
        oWin[mail].open("Send Message To SynaMed Support", "/vco/message/mainMenu.do?targetAction=3&preTo=support", 880, 570, 50, document.body.scrollTop+67);
        oWin[mail].focus();
        return;
}

function newPhoneMessage(targetAction){
 if (document.patientMenuForm.doctorId.value!="" || !amAtCal){
        oWin[mail].open("New Phone Message", "", 880, 570, 50, document.body.scrollTop+67);
	document.messageForm.targetAction.value=17;
        document.messageForm.inDhtml.value=true;
        document.messageForm.pid.value = document.patientMenuForm.pid.value;
        document.messageForm.target="iframe3";
        document.messageForm.submit();
        document.messageForm.target="_self";
	return;
        } else {
       		alert('Please select a patient before selecting one of these patient functions.');
        }
        return;

}

function newPhone(pid){
  	oWin[mail].open("New Phone Message", "", 880, 570, 50, document.body.scrollTop+67);
	document.messageForm.targetAction.value=8;
        document.messageForm.inDhtml.value=true;
        document.messageForm.pid.value = pid;
        document.messageForm.target="iframe3";
        document.messageForm.submit();
        document.messageForm.target="_self";	
	return;
}

    function doPatientAddTaskConfirm(target){
      doPatientAddTask(target);
    }

    function doPatientAddTask(target, targetId){
      if (document.patientMenuForm.doctorId.value!="" || !amAtCal){
        document.todoForm.targetAction.value = target;
        document.todoForm.pid.value = document.patientMenuForm.pid.value;
	if (targetId == null) {
          oWin[task].open("Add Task", "/vco/blank.html", 750, 600, 10, document.body.scrollTop+40);
          document.todoForm.target="iframe2";
	} else {
	  document.todoForm.target=targetId;
	}
        document.todoForm.submit();
        document.todoForm.target="_self";
	if(!top.SynaTabConst.USE_TAB &&top.tutorialEnabled){
          top.showNextStepTutorial();
        }
	top.resetAllFrame();
      } else {
        alert('Please select a patient before selecting one of these patient functions.');
      }
      return;
    }
    function doPatientAddTaskTab(ta){
      if (document.patientMenuForm.doctorId.value!="" || !amAtCal){
	popupAssignTask(document.patientMenuForm, ta, "New Task");
      } else {
        alert('Please select a patient before selecting one of these patient functions.');
      }
      return;
    }

    function doPatientAddTaskFrame(target){
      if (parent.parent.document.patientMenuForm.doctorId.value!="" || !amAtCal){
        parent.parent.document.todoForm.targetAction.value = target;
        parent.parent.document.todoForm.pid.value = parent.parent.document.patientMenuForm.pid.value;
        parent.parent.oWin[task].open("Add Task", "/vco/blank.html", 750, 600, 10, document.body.scrollTop+40);
        parent.parent.document.todoForm.target="iframe2";
        parent.parent.document.todoForm.submit();
        parent.parent.document.todoForm.target="_self";
      } else {
        alert('Please select a patient before selecting one of these patient functions.');
      }
      return;
    }

function comingSoon(){
  alert("Your practice does not currently have access to this feature. Please contact SynaMed at 1-866-SynaMed to enable this feature.");
}

function soon(){
  alert("Coming soon!");
}
function unformatAsMoney(mnt){
  if(mnt.charAt(0)=='('){
    mnt = parseFloat(mnt.substring(1,mnt.length));
    return -1*mnt;
  }
  return parseFloat(mnt);
}
function formatAsMoney(mnt) {
  mnt -= 0;
  var tmp="";
  var neg=false;
  mnt = (Math.round(mnt*100))/100;
  if (mnt<0){
    //neg=true;
    //mnt*=-1;
    //tmp+="(";
  }
//  mnt = (Math.round(mnt*100))/100;
  var ret=(mnt == Math.floor(mnt)) ? mnt + '.00' : ( (mnt*10 == Math.floor(mnt*10)) ? mnt + '0' : mnt);
  tmp+=ret;
  if (neg){
    tmp+=")";
  }
  return tmp;
}
function ddValue(dd){
	return dd.options[dd.selectedIndex].value;
}

function getSelectDropdownText(dropdown){
	 var selectedIndex=dropdown.selectedIndex;
	 return dropdown.options[selectedIndex].text;
}


function ddValues(dd){
	var sel = new Array();
	for (var i=0; i<dd.options.length; i++) {
		var co = dd.options[i];
		if (co.selected) sel[sel.length]=co.value;
	}
	return sel;
}
function ddIdx(dd, val){
        for (var i=0; i<dd.options.length; i++) {
                var co = dd.options[i].value;
                if (co==val) return i;
        }
        return -1;
}
function setDdValue(dd, val){
	for (var i=0; i<dd.options.length; i++){
		if (dd.options[i].value==val){
			dd.selectedIndex=i;
			return;
		}
	}
}

function appendDiv(divId, divClass){
	var divElement=document.createElement("div");
	divElement.id=divId;
	if(divClass){
		divElement.className=divClass;
	}
	document.body.appendChild(divElement);
	return divElement;
}

function parseFloata(fs){
  if (typeof(fs)=="number") return fs;
  if (fs=="" || fs==null) return parseFloat("0");
  fs=fs.replace(",", "");
  if (typeof(fs)==typeof("")){
    if ("("==fs.substring(0, 1)){
      return -1*parseFloat(fs.substring(1, fs.length-1));
    }
  }
  return parseFloat(fs);
}

function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return "";
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain)
{
//alert("should be deleting cookie name="+name+", path="+path+", domain="+domain);
    if (getCookie(name))
    {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

function openTodoEdit(url) {
   window.open(url, "Edit", "width=650, height=580, location=no, menubar=no, scrollbars=yes, status=yes, resizable=yes");
   return;
}

function openTodoAdd(url) {
   window.open(url, "Add", "width=650, height=550, location=no, menubar=no, scrollbars=yes, status=yes, resizable=yes");
   return;
}

function openTodoFull() {
   window.open("/vco/calendar/todoFullView.jsp", "Add", "width=750, height=650, location=no, menubar=no, scrollbars=yes, status=yes, resizable=yes");
   return;
}

    function doPatientMenuAddTask(targetAction){
        document.todoForm.targetAction.value=targetAction;
        document.todoForm.pid.value = document.patientMenuForm.pid.value;
        document.todoForm.submit();
        openTodoAdd("/vco/calendar/todoAdd.jsp");
      return;
    }

function loadBackground(url){
  document.frames("bgjs").document.location=url;
}

// dhtmlWindow functions
function MakeSafe(html)
{
  var returnStr = html.replace(/[\r\n\f]/g,"");
  returnStr = returnStr.replace(/'/g,"\\'");
  return returnStr;
}



function win_init(){
	//intend to be empty function
}

function win_focus(){
	
}


function lib_doc_size(){
	
}
function lib_moveIt(x,y){
	movePopup("iframe"+this.num,x,y);
}

function win_max(){
	maxPopup("iframe"+this.num);
	
}
function lib_setbody(newHtml){
	setPanelContent("iframe"+this.num, newHtml);
}


function lib_obj(num){
  this.num=num;
  this.open=win_open;
  this.close=win_close;
  this.resize=win_resize;
  this.hide=win_close;
  this.destroy=win_destroy;
  this.moveIt=lib_moveIt;
  this.focus=win_focus;
  this.changeTitle=win_changeTitle;
  this.setHtmlBody=lib_setbody;
  this.showIt=win_showIt;
  this.isClosed=win_isClosed;
  this.max=win_max;
  this.subscribeClose=win_subscribeClose;
  this.unsubscribeClose=win_unsubscribeClose;
  this.setModal=win_setModal;
  return this
}

function win_setModal(modal){
	var iframeId="iframe"+this.num;
	if(popupPanels[iframeId]){
		popupPanels[iframeId].cfg.modal=modal;
	}
}

function create_window(i){
  oWin[i]=new lib_obj(i)
  oWin[i].oWindow=new lib_obj('divWindow'+i,'divWin'+i)
}

function win_changeTitle(newTitle){
	var iframeId="iframe"+this.num;
	changePopupTitle(iframeId,newTitle);
}

function win_subscribeClose(closeEvent){
	var iframeId="iframe"+this.num;
	if(popupPanels[iframeId]){
		popupPanels[iframeId].hideEvent.subscribe(closeEvent);
	}
}

function win_unsubscribeClose(){
	var iframeId="iframe"+this.num;
	if(popupPanels[iframeId]){
		popupPanels[iframeId].hideEvent.unsubscribeAll();
	}
}


function win_open(title, url, w, h, x, y, parent,modal){
  if (!url || url==""){
    url="/vco/blank.html";
  }
  if (w!=0 && !w) w=600; if (h!=0&&!h) h=200;
  if (!x) x=200; if (!y) y=document.body.scrollTop+100;
  setYuiBodyClass();
  showResizableFrame(this.num,title,url,w, h,x,y,modal);
  if(parent){
	  this.assignedParent=parent; 
  }
  
}


function win_getDocument(){
  var doc="document.frames['iframe"+this.num+"'].document";
  return eval(doc);
}

function win_showIt(){
	this.open("popup");
}

function win_getWindow(){
	var frameObj;
	if (document.frames){
	    frameObj = document.frames[iframeId].document;
	}else{
	    frameObj = document.getElementById(iframeId).contentDocument;
	}
	return frameObj;
}

function win_getTopWindow(){
  var doc="top.document.getElementById(\"iframe"+this.num+"\").contentWindow";
  return eval(doc);
}


function win_close(){
	

	hidePopup('iframe'+this.num);
	
	
	
	
}

function win_destroy(){
	var iframeId='iframe'+this.num;
	
	if(resizeControls[iframeId]){
	
		resizeControls[iframeId].destroy();
		popupPanels[iframeId].destroy();
		popupPanels[iframeId]=null;
		resizeControls[iframeId]=null;
	}
}

function win_isClosed(i){
	return isClosed('iframe'+this.num);
	
}
function win_resize(w,h){
	setPanelSize('iframe'+this.num,w,h);
}


function addWindow(){
  var num=oWin.length; wins=num+1; 
  create_window(num);
  return num;
}



function virtWin(handle, url, title, w, h, x, y){
  oWin[handle].open(title, url, w, h, x, y);
}
function hidePleaseWait(){
  document.all['wtDiv'].style.visibility="hidden";
}
function hideProgressBar(){
  if(top.hideWaitDial) top.hideWaitDial();

}
var pgload=new Array("L", "O", "A", "D");
var pgsave=new Array("|", "S", "A", "V");
var pgwork=new Array("W", "O", "R", "K");
var pgopen=new Array("O", "P", "E", "N");
var pgfind=new Array("F", "I", "N", "D");
function progressBar(){
  doProgressBar(pgload);
}
function progressLoading(){
  doProgressBar(pgload);
}
function progressSaving(){
  doProgressBar(pgsave);
}
function progressFinding(){
  doProgressBar(pgfind);
}
function progressWorking(){
  doProgressBar(pgwork);
}
function progressOpening(){
  doProgressBar(pgopen);
}
function doProgressBar(pgword){
	var showText="Processing, please wait...";
	if(pgword && (pgword instanceof String)){
		showText=pgword;
	}
   if(top.showWaitDial) top.showWaitDial(showText, false);
}
var progressEnd = 36;		// set to number of progress <span>'s.
var progressColor = '#FFD350';	// set to progress bar color
var progressInterval = 460;	// set to time between updates (milli-seconds)
var progressAt = progressEnd;
var progressTimer;
function progress_clear() {
	for (var i = 1; i <= progressEnd; i++) document.getElementById('progress'+i).style.backgroundColor = 'transparent';
	progressAt = 0;
}
function progress_update() {
	progressAt++;
	if (progressAt > progressEnd) progress_clear();
	else document.getElementById('progress'+progressAt).style.backgroundColor = progressColor;
	progressTimer = setTimeout('progress_update()',progressInterval);
}
function progress_stop() {
	clearTimeout(progressTimer);
	progress_clear();
}
function waitAll(){
	var allLinks=document.getElementsByTagName("a");
	for (var i=0; i<allLinks.length; i++){
		allLinks[i].setAttribute("href", "javascript:pleaseWait();");
	}
}

function setIframeTransparency(){
	var iframes=null;
	if(window.iframes){
		iframes=window.iframes;
	}else{
		iframes=document.getElementsByTagName("iframe");
	}
	
	if(iframes){
		for (var i=0; i<iframes.length; i++){
			iframes[i].allowTransparency=true;
		} 
	}

}
function pleaseWait(){
  if(!document.getElementById('wtDiv')) return;
  document.getElementById('wtDiv').innerHTML="<table bgcolor='99eeee'><tr><td>Please wait.</td></tr></table>";
  document.getElementById('wtDiv').style.left=200; //document.body.clientWidth/2-100;
  document.getElementById('wtDiv').style.top=200; //document.body.scrollTop+340;
  document.getElementById('wtDiv').style.visibility="visible";
  document.getElementById('wtDiv').style.zIndex=4000;
}
function isDigit(c)
{
  return ((c>="0")&&(c<="9"));
}
function validat(str){
  return (valida(str, '/') || valida(str, '-'));
}
function valida(str, del){
  if (str.indexOf(del)==1 || str.indexOf(del)==2){
    if (str.lastIndexOf(del)>2 && str.lastIndexOf(del)<6){
	var flag=true;
        for (var i =0; i<str.length; i++){
                var c=str.charAt(i);
		if (!isDigit(c) && c!=del){
			flag=false;
		}
	}
	return flag;
    }
  }
  return false;
}
function verDate(field){
        var str=field.value;
        var flag=false;
        if (isInt(str)){
                if (str.length==6 || str.length==8){
                        flag=true;
                }
        }
        if (flag==false){
                if (validat(str)) flag=true;
        }
        if (!flag){
                this.focus();
                alert("Please enter a valid date.");
		return false;
        }
	return true;
}
function isInt(str){
        var flag=true;
        for (var i =0; i<str.length; i++){
                var c=str.charAt(i);
                if (!isDigit(c)){ flag=false; }
        }
        return flag;
}
function verInt(field){
        if (!isInt(field.value)){
                this.focus();
                alert("Please enter a valid integer.");
        }
}
function verFloat(field){
        var str=field.value;
        var numDec=0;
        var flag=true;
        for (var i =0; i<str.length; i++){
                var c=str.charAt(i);
                if (!isDigit(c) && c!='.') return false;
                if (c=='.'){
                        numDec++;
                        if (numDec>1){
                                flag=false;
                        }
                }
        }
        if (!flag){
                this.focus();
                alert("Please enter a valid number.");
        }
}

function doCustomizeNoteSettings(){
  oWin[edit].open("Customize Note Structure Settings", "", 800, 500, 5, document.body.scrollTop+10);
  oWin[edit].focus();
  document.patientMenuForm.target="iframe1";
  document.patientMenuForm.targetAction.value = 45;
  document.patientMenuForm.submit();
  document.patientMenuForm.target="_self";
}

function doPatientMenuActionPID(pid, targetAction, targetTabId) {
  document.patientMenuForm.pid.value = pid;
  doPatientMenuAction(targetAction, targetTabId);
}

function doPatientMenuAction(targetAction,targetTabId){
//  if(top.SynaTabConst.USE_TAB || targetAction==52){
//    if(top.SynaTab.checkLoadQueue(targetAction)){
//    } else {
//      setTimeout("doPatientMenuAction("+targetAction+",'"+targetTabId+"');", 2000);
//      return;
//    }
//  }
  if (document.patientMenuForm.doConfirm.value=='true'){
    if (!confirm("Are you sure you want to leave this page without saving?")){
      return;
    }
  } 
 
  document.patientMenuForm.doConfirm.value='false';
  if(false&&document.getElementById("iframe4")) {
    document.patientMenuForm.imWidth.value=oWin[im].w;
    document.patientMenuForm.imHeight.value=oWin[im].h;
    document.patientMenuForm.imX.value=oWin[im].x;
    document.patientMenuForm.imY.value=oWin[im].y;
    document.patientMenuForm.imVisibility.value=eval(oWin[im].css.visibility!='hidden');
  }
  if (document.patientMenuForm.doctorId.value!="" || !amAtCal){
    document.patientMenuForm.targetAction.value=targetAction;
    document.patientMenuForm.target="dynamic";

    if (!top.SynaTabConst.USE_TAB && targetAction==27){
      oWin[page].open("Post Copay", "", 430, 283, 200, document.body.scrollTop+100);
      document.patientMenuForm.target="iframe0";
    } else if (targetAction==25) {
      oWin[mail].open("New Phone Message", "", 880, 570, 200, document.body.scrollTop+100);
      document.patientMenuForm.target="iframe3";
    } else if (targetAction==47) {
      oWin[page].open("Critical Alert", "", 680, 370, 200, document.body.scrollTop+10);
      document.patientMenuForm.target="iframe0";
    } else if (targetAction==32 && targetTabId == null){
      oWin[page].open("Add Comment", "", 450, 300, 200, document.body.scrollTop+100);
      document.patientMenuForm.target="iframe0";
    } else if (targetAction==99 && targetTabId == null){
        oWin[page].open("Add Comment", "", 500, 350, 200, document.body.scrollTop+100);
        document.patientMenuForm.target="iframe0";
    } else if (targetAction==31 && targetTabId == null){
      oWin[page].open("View Comments", "", 650, 500, 20, document.body.scrollTop+100);
      document.patientMenuForm.target="iframe0";
    }else if (targetAction==98 && targetTabId == null){
        oWin[page].open("View Comments", "", 800, 450, 20, document.body.scrollTop+100);
        document.patientMenuForm.target="iframe0";
    }else if (targetAction==40){
      oWin[page].open("Select Note Structure Setting", "", 350, 250, 20, document.body.scrollTop+100);
      oWin[page].focus();
      document.patientMenuForm.target="iframe0";
    } else if (!top.SynaTabConst.USE_TAB && targetAction==49){
      oWin[page].open("Nurses' Comments", "", 650, 500, 20, document.body.scrollTop+100);
      document.patientMenuForm.target="iframe0";
    } else if (targetAction==53 && targetTabId == null){
      oWin[page].open("Practice Guideline", "", 500, 300, 20, document.body.scrollTop+30);
      document.patientMenuForm.target="iframe0";
    } else if (targetAction==57){
      oWin[page].open("Precert/Referral Management", "", 558, 440, 20, document.body.scrollTop+50);
      document.patientMenuForm.target="iframe0";
    } else if (targetAction==55){
      oWin[page].open("HM Rule Enforcement", "", 500, 300, 20, document.body.scrollTop+30);
      document.patientMenuForm.target="iframe0";
    } else if (targetAction==62){
      oWin[page].open("Patient's Family Account Balance", "", 800, 300, 20, document.body.scrollTop+30);
      document.patientMenuForm.target="iframe0";
    } else if (targetAction==69){
      oWin[page].open("Appointment Wizard", "", 750, 550, 5, document.body.scrollTop+10);
      document.patientMenuForm.target="iframe0";
    } else if (targetAction==159) {
      oWin[page].open("Document Manager", "", 640, 480, 5, document.body.scrollTop+10);
      document.patientMenuForm.target="iframe0";
    } else if (targetAction==111) {
      oWin[page].open("Clinical Images", "", 640, 480, 5, document.body.scrollTop+10);
      document.patientMenuForm.target="iframe0";
    } else if (targetAction==71) { 
      oWin[page].open("Lab Order", "", 640, 480, 5, document.body.scrollTop+10);
      document.patientMenuForm.target="iframe0";
    } else if(targetAction==6){
      oWin[page].open("Make New Appointment", "/vco/blank.html", 650, 600, 5, document.body.scrollTop+20);
      document.patientMenuForm.target="iframe0";
    } else if (targetAction==95){
      oWin[page].open("Cancelled/No-show Appointments", "/vco/patient/allAppointments.jsp?c=true&p="+document.patientMenuForm.pid.value, 650, 600, 5, document.body.scrollTop+20);
      return;
    } else if(targetAction==13){
      var tab = top.SynaTab.addPatientOpenedItem({pid:document.patientMenuForm.pid.value,tabId:'loadingNote',tabName:'Loading'});
      if (tab != null) {
        document.patientMenuForm.target=tab.getFrameId();
        top.SynaTab.doShow(tab.id);
        document.patientMenuForm.synaTabId.value=tab.id;
      }
/*
    } else if(targetAction==52){
      var pTab = top.SynaTab.addTab({id:"pat"+document.patientMenuForm.pid.value,name:'Loading',parentId:"patients",doSwitch:true});
      top.SynaTab.initPatientSideMenu(document.patientMenuForm.pid.value);
      var oTab = top.SynaTab.addTab({id:'p_16'+document.patientMenuForm.pid.value,name:'Opened Items',parentId:'pat'+document.patientMenuForm.pid.value});
      var tab = top.SynaTab.addTab({id:document.patientMenuForm.pid.value+"Ledger",name:'Default Ledger',preload:true,parentId:oTab.id,doSwitch:true}, true);
      top.SynaTab.doShow(oTab.id);
      top.SynaTab.doShow(tab.id);
      var target = tab.getFrameId();
      document.patientMenuForm.target=target;
      top.SynaTab.doShow(tab.id);
*/
    }else{
      var tabId = 'dynamic';
      if(targetTabId!=null && targetTabId!=''){
        tabId = targetTabId;
      } else {
        progressBar();
      }
      if (top.SynaTabConst.USE_TAB) {
	    if (targetTabId && targetTabId != null && targetTabId != '') {
	      document.patientMenuForm.target=targetTabId;
	    } else {
	    	
	      var pTab = top.SynaTab.addPatientTab({pid:document.patientMenuForm.pid.value});
	      var tab = top.SynaTab.getPatientTab(document.patientMenuForm.pid.value, targetAction);
	      if (tab != null) {
		    if (targetAction == 1) {
			  tab.alreadyLoaded = false; // enable new visit from the light blue bar
			}
		    
	        top.SynaTab.doShow(tab.id);
            //top.SynaTab.loadQueue[targetAction]=1;
	        return;
	      }
	    }
      } else {
        progressBar();
      }
    }
    if(!top.SynaTabConst.USE_TAB &&top.tutorialEnabled){  
	  top.showNextStepTutorial();
  	}
    if (top.SynaTabConst.USE_TAB && document.patientMenuForm.target == 'dynamic') {
      top.SynaTab.doShow(top.SynaTabConst.HOME);
    }
    if(top.SynaTab.USE_TAB || targetAction==52) top.SynaTab.loadQueue[targetAction]=1;
    document.patientMenuForm.submit();
    if (targetAction==27 || targetAction==25 || targetAction==32 || targetAction==31 || targetAction==98 || targetAction==99 || targetAction==40 || targetAction==49 || targetAction==57 || targetAction==62 || targetAction==69){
      //document.patientMenuForm.target="_self";
      document.patientMenuForm.target="dynamic";
    }
    oWin[page].focus();
  } else {
    alert('Please select a patient before selecting one of these patient functions.');
  }
  return;
}

function doPatientMenuActionConfirm(targetAction){
  if (targetAction==27){
    doPatientMenuAction(targetAction);
  } else {
   if (confirm("Are you sure you want to leave this page without saving?")){
    document.patientMenuForm.doConfirm.value='false';
    doPatientMenuAction(targetAction);
   }
  }
  return;
}

function doPatientMenuActionFrame(targetAction){
 
  if (parent.parent.document.patientMenuForm.doConfirm.value=='true'){
    if (!confirm("Are you sure you want to leave this page without saving?")){
      return;
    }
  }
 
  parent.parent.document.patientMenuForm.doConfirm.value='false';
  if (parent.parent.document.patientMenuForm.doctorId.value!='' || !amAtCal){
    parent.parent.document.patientMenuForm.targetAction.value=targetAction;
    if (targetAction==27){
      parent.parent.oWin[page].open("Post Copay", "", 430, 283, 200, document.body.scrollTop+100);
      parent.parent.document.patientMenuForm.target="iframe0";
    } else if (targetAction==25) {
      parent.parent.oWin[page].open("New Phone Message", "", 880, 570, 200, document.body.scrollTop+100);
      parent.parent.document.patientMenuForm.target="iframe0";
    } else if (targetAction==47) {
      parent.parent.oWin[page].open("Critical Alert", "", 880, 570, 200, document.body.scrollTop+100);
      parent.parent.document.patientMenuForm.target="iframe0";
    } else if (targetAction==32){
      parent.parent.oWin[page].open("Add Comment", "", 450, 300, 200, document.body.scrollTop+100);
      parent.parent.document.patientMenuForm.target="iframe0";
    } else if (targetAction==99){
        parent.parent.oWin[page].open("Add Comment", "", 500, 350, 200, document.body.scrollTop+100);
        parent.parent.document.patientMenuForm.target="iframe0";
    } else if (targetAction==31){
      parent.parent.oWin[page].open("View Comments", "", 650, 500, 20, document.body.scrollTop+100);
      parent.parent.document.patientMenuForm.target="iframe0";
    }else if (targetAction==98){
        parent.parent.oWin[page].open("View Comments", "", 800, 500, 20, document.body.scrollTop+100);
        parent.parent.document.patientMenuForm.target="iframe0";
    }else if(targetAction==40){
      parent.parent.oWin[page].open("Select Tab Setting", "", 350, 250, 20, document.body.scrollTop+100);
      parent.parent.document.patientMenuForm.fromPanorama.value=true;
      parent.parent.document.patientMenuForm.target="iframe0";
    } else if (targetAction==49){
      parent.parent.oWin[page].open("Nurses' Comments", "", 650, 500, 20, document.body.scrollTop+100);
      parent.parent.document.patientMenuForm.fromPanorama.value=true;
      parent.parent.document.patientMenuForm.target="iframe0";
    } else if (targetAction==53){
      parent.parent.oWin[page].open("Practice Guideline", "", 500, 300, 20, document.body.scrollTop+30);
      parent.parent.document.patientMenuForm.fromPanorama.value=true;
      parent.parent.document.patientMenuForm.target="iframe0";
    } else if(targetAction==6){
      parent.parent.oWin[page].open("Make New Appointment", "/vco/blank.html", 650, 600, 5, document.body.scrollTop+20);
      parent.parent.document.patientMenuForm.fromPanorama.value=true;
      parent.parent.document.patientMenuForm.target="iframe0";
    } else if(targetAction==97){
    	parent.parent.oWin[page].open("Patient Clinical Summary", "", 880, 570, 200, document.body.scrollTop+100);
        parent.parent.document.patientMenuForm.target="iframe0";
    }else {
      parent.parent.progressBar();
    }
    if(!top.SynaTabConst.USE_TAB && top.tutorialEnabled){
	  top.showNextStepTutorial();
  	}
    parent.parent.document.patientMenuForm.submit();
    if (targetAction==27 || targetAction==25 || targetAction==32 || targetAction==31 || targetAction==40 || targetAction==49){
      //parent.parent.document.patientMenuForm.target="_self";
    }
    parent.parent.oWin[page].focus();
  } else {
    alert('Please select a patient before selecting one of these patient functions.');
  }
  return;
}

function doPatientMenuActionConfirmFrame(targetAction){
  if (targetAction==27){
    doPatientMenuActionFrame(targetAction);
  } else {
   if (confirm("Are you sure you want to leave this page without saving?")){
    parent.parent.document.patientMenuForm.doConfirm.value='false';
    doPatientMenuActionFrame(targetAction);
   }
  }
  return;
}

function goPatientPanoramaFrame(i)
{
  if (parent.parent.document.patientMenuForm.doctorId.value!='' || !amAtCal){
    parent.parent.document.patientMenuForm.selectedPatientPanoramaSetting.value=i;
    if (i%2!=0){
      parent.parent.oWin[page].open("Patient Panorama", "", 920, 600, 2, document.body.scrollTop+50);
      parent.parent.document.patientMenuForm.target="iframe0";
    } else {
      parent.parent.progressBar();
    }
    parent.parent.document.patientMenuForm.targetAction.value=35;
    parent.parent.document.patientMenuForm.submit();
  } else {
    alert('Please select a patient before selecting one of these patient functions.');
  }
}


function goPatientPanorama(i)
{
  if (document.patientMenuForm.doctorId.value!='' || !amAtCal){
    document.patientMenuForm.selectedPatientPanoramaSetting.value=i;
    if (i%2!=0){
      oWin[page].open("Patient Panorama", "", 920, 600, 2, document.body.scrollTop+50);  
      document.patientMenuForm.target="iframe0";
    } else {
      progressBar();
    }
    if(top.SynaTabConst.USE_TAB){
      var pTab = top.SynaTab.getPatientTab(document.patientMenuForm.pid.value);
      if (pTab == null) {
	pTab = top.SynaTab.addPatientTab({pid:document.patientMenuForm.pid.value});
      }
      var tab = top.SynaTab.getPatientTab(document.patientMenuForm.pid.value, top.SynaTabConst.PATIENT_PANORAMA);
      if (tab != null) {
        document.patientMenuForm.target=tab.getFrameId();
	top.SynaTab.doShow(tab.id);
      }
    }
    document.patientMenuForm.targetAction.value=35;
    document.patientMenuForm.submit();
    document.patientMenuForm.target="_self";
  } else {
    alert('Please select a patient before selecting one of these patient functions.');
  }
}


function goPatientPanoramaConfirm(i)
{
  if (document.patientMenuForm.doConfirm.value=='true'){
    if (!confirm("Are you sure you want to leave this page without saving?")){
      return;
    }
  }
  document.patientMenuForm.doConfirm.value='false';
  if (confirm("Are you sure you want to leave this page without saving?")){
    document.patientMenuForm.doConfirm.value='false';
    goPatientPanorama(i);
   }
   return;
}

function hasChecked(elements){
	var hasCheckedElement=false;
		if(elements){
			if(elements.length){
				for(i=0; i<elements.length; i++){
					if(elements[i].checked){
						hasCheckedElement=true;
					}
				}
			}else{
				hasCheckedElement=elements.checked;
			}
		}
		
	return hasCheckedElement;

}

function ajaxSubmitPage(sUrl, formObj, callBack){
	if(!callBack){
		callBack={};
	}

	YAHOO.util.Connect.setForm(formObj); 
	
	
	var request=YAHOO.util.Connect.asyncRequest('POST', sUrl, callBack);
	
	return request;
}

function ajaxPostDataJquery(sUrl, postData, successHandler){
	jQuery.post(sUrl, postData, successHandler);

}

function ajaxPostData(sUrl, dataQuery, callBack){
	if(!callBack){
		callBack={};
	}
	var request=YAHOO.util.Connect.asyncRequest('POST', sUrl, callBack,dataQuery);
	return request;
}

function ajaxSubmitPageUrl(url, callBack){
	if(!callBack){
		callBack={};
	}
     var request=YAHOO.util.Connect.asyncRequest('GET', url, callBack);
     return request;
}

// UTF-8 ENCODE AND DECODE
var SAFECHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.!~*'()";
var HEX = "0123456789ABCDEF";
var HEXCHARS = "0123456789ABCDEFabcdef";
var UTF8 = {
        // public method for url encoding
        encode : function (plaintext) {
                var encoded = "";
                for (var i = 0; i < plaintext.length; i++ ) {
                        var ch = plaintext.charAt(i);
                        if (ch == " ") {
                                encoded += "%20";                               // x-www-urlencoded, rather than %20
                        } else if (SAFECHARS.indexOf(ch) != -1) {
                                encoded += ch;
                        } else {
                                var charCode = ch.charCodeAt(0);
                                if (charCode > 255) { // Unicode Character cannot be encoded using standard URL encoding.
                                        encoded += "+";
                                } else {
                                        encoded += "%";
                                        encoded += HEX.charAt((charCode >> 4) & 0xF);
                                        encoded += HEX.charAt(charCode & 0xF);
                                }
                        }
                } // for
                return encoded;
        },
        // public method for url decoding
        decode : function (encoded) {
                var plaintext = "";
                var i = 0;
                while (i < encoded.length) {
                        var ch = encoded.charAt(i);
                        if (ch == "+") {
                                plaintext += " ";
                                i++;
                        } else if (ch == "%") {
                                if (i < (encoded.length-2)
                                        && HEXCHARS.indexOf(encoded.charAt(i+1)) != -1
                                        && HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
                                        plaintext += unescape( encoded.substr(i,3) );
                                        i += 3;
                                } else {  // ignored
                                        i++;
                                }
                        } else {
                                plaintext += ch;
                                i++;
                        }
                } // while
                return plaintext;
        }
}

function getElementCoord(obj){
    var curleft = curtop = 0;
    if (obj.offsetParent) {
    do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
    return [curleft,curtop];
}
}

// ===== end of UTF-8 ENCODE/DECODE =======
var FormValidator = {
  isChecked : function(checkbox) {
    if (checkbox != null) {
      var checkLength = checkbox.length;
      if (checkLength != null) {
        for (var i = 0; i < checkLength; i++) {
          if (checkbox[i].checked) {
            return true;
          }
        }
      } else {
        if (checkbox.checked) {
          return true;
        }
      }
    }
    return false;
  }
}

function setYuiBodyClass(){
	if(document.body){
		if (document.body.className && document.body.className.indexOf('yui-skin-sam') >= 0) {
	      		return;
	    }
	document.body.className=document.body.className+" yui-skin-sam";
	}
}


var popupPanels=[];
var resizeControls=[];
var popupInitStatus=[];

function setPopupPanelHeader(iframeId,headerTitle){
	if(!headerTitle || headerTitle==""){
		headerTitle="popup";
	}
	var headerHtml=headerTitle+"<span id='"+iframeId+"_panelAddonAction' class='panelAddonAction'><a href='javascript:toggleIframePopup(\""+iframeId+"\")' class='toggleOpenCloseItem'>&nbsp;&nbsp;&nbsp;&nbsp;</a></span>";
	popupPanels[iframeId].setHeader(headerHtml);
}

function changePopupTitle(iframeId,titleNew){
	var panel=popupPanels[iframeId];
	if(!panel) return;
	panel.setHeader(titleNew);
}

function setPanelSize(iframeId,width,height,x,y){
	var panel=popupPanels[iframeId];
	if(!panel) return;
	panel.cfg.setProperty("width",(width)+"px");
	panel.cfg.setProperty("height",(height)+"px");

	if(!x && !y){
		panel.center();
	}else{
		panel.moveTo(x,y);
	}
	
	syncIframe(iframeId,width,height);
}

function syncIframe(iframeId, width, height,url){
	var iframeElement=document.getElementById(iframeId);
	width=width-25;
	height=height-35;
	if(width<0) width=0;
	if(height<0) height=0;
	//alert("old frame: "+iframeElement.style.width+", "+iframeElement.style.height);
	
	// don't need to sync if we use percentage.....
	//iframeElement.style.width=width;
	//iframeElement.style.height=height;
	//alert("new frame: "+iframeElement.style.width+", "+iframeElement.style.height);
	if(url){
		iframeElement.src=url;
	}
}

function toggleIframePopup(iframeId){
	var className=document.getElementById(iframeId+"_panelAddonAction").className;
	if(className.indexOf('selected')>0){
		restorePopup(iframeId);
	}else{
		maxPopup(iframeId);
	}
}

function restorePopup(iframeId){
	document.getElementById(iframeId+"_panelAddonAction").className="panelAddonAction";
	var initialConfig=popupInitStatus[iframeId];
	setPanelSize(iframeId,initialConfig.width,initialConfig.height,initialConfig.xPosition,initialConfig.yPosition);
}



function maxPopup(iframeId){
	document.getElementById(iframeId+"_panelAddonAction").className="panelAddonAction selected";
	var width=YAHOO.util.Dom.getViewportWidth()-25;
	var height=YAHOO.util.Dom.getViewportHeight()-35;
	setPanelSize(iframeId,width,height);
	
}

function movePopup(iframeId,x,y){

	var panel=popupPanels[iframeId];
	if(panel){
		panel.moveTo(x,y);
	}
}

function hidePopup(iframeId){
	var panel=popupPanels[iframeId];
	if(panel){
		panel.hide();
	}
}

function isClosed(iframeId){
	var panel=popupPanels[iframeId];
	if(panel){
		return panel.cfg.visible;
	}
	return true;
}

function focusIframe(iframeId){
	var iframeElement=document.getElementById(iframeId);
	if(iframeElement){
		iframeElement.focus();
	}
}

function setPanelContent(iframeId, html){
	
	var panel=popupPanels[iframeId];
	var iframeElement=document.getElementById(iframeId);
	iframeElement.style.display="none";
	if(panel){
		panel.setBody(html);
		panel.show();
		
	}
}

function setIFrameContent(iframeId, html){

	var frameObj;
	if (document.frames){
	    frameObj = document.frames[iframeId].document;
	}else{
	    frameObj = document.getElementById(iframeId).contentDocument;
	}
	if(frameObj){
		
		frameObj.body.innerHTML=html;
		 
	}
}




function showResizableFrame(iframeIndexNum, title, url, width, height, xPosition,yPosition,modal) {
	var iframeId="iframe"+iframeIndexNum;
	
	if(popupPanels[iframeId]){
		
		resizeControls[iframeId].destroy();
		popupPanels[iframeId].destroy();
		popupPanels[iframeId]=null;
		resizeControls[iframeId]=null;
	}
	

		
		var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event;

		var containerPanel="yuiPopupPanel_"+iframeId;
		var iframeElement=document.getElementById(iframeId);
		
		function cleanSrc(){
			
			var iframeElement=document.getElementById(iframeId);
			if(iframeElement){
				iframeElement.src="/vco/blank.html";
			}
			 
		}
		
		
		
		if(!popupPanels[iframeId] || !iframeElement){
			
			var divElement=appendDiv(containerPanel);
			divElement.style.zIndex=1000;
			var myNewContent="<iframe id='"+iframeId+"' height='100%' width='99%' name='"+iframeId+"' border='0' frameborder='0'>&nbsp;</iframe>";
	        divElement.innerHTML="<div class='hd'></div><div class='bd' style='padding:0; background-color:white' id='divWinTex"+iframeIndexNum+"' style='background-color: white'>"+myNewContent+"</div>";
	 
	        var panel = new YAHOO.widget.Panel(containerPanel, {
                draggable: true,
                close: true,
                visible:false,
                width: width+"px",
                constraintoviewport:true,
                zIndex:99999,
                modal:modal
            });
            panel.renderEvent.subscribe(function() {
                YAHOO.util.Dom.setStyle(document.getElementById(iframeId), 'overflow', 'auto');
                ifrm = document.getElementById(iframeId);
            }, panel, true);
            
           
            panel.render();
            popupPanels[iframeId]=panel;
           
    		
            // Create Resize instance, binding it to the 'resizablepanel' DIV 
            var resize = new YAHOO.util.Resize(containerPanel, {
                autoRatio: false,
                minWidth: 30,
                minHeight: 30,
                status: false,
                proxy:true,
                zindex:9999999
            });
          
            resize.on("startResize", function(args) {

    		    if (this.cfg.getProperty("constraintoviewport")) {
                    var D = YAHOO.util.Dom;

                    var clientRegion = D.getClientRegion();
                    var elRegion = D.getRegion(this.element);

                    resize.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
                    resize.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
	            } else {
                    resize.set("maxWidth", null);
                    resize.set("maxHeight", null);
	        	}

            }, panel, true);
            resizeControls[iframeId]=resize;

            // Setup resize handler to update the size of the Panel's body element
            // whenever the size of the 'resizablepanel2' DIV changes
            resize.on('resize', function(args) {
            	
                var panelHeight = args.height;
                var panelWidth = args.width;
                var maxW = panelWidth;
                var maxH = panelHeight;
                if(top.isIE()){
                  maxH = document.body.clientHeight;
                  maxW = document.body.clientWidth;
                } else {
                  maxH = this.innerHeight;
                  maxW = this.innerWidth;
                }
                setPanelSize(iframeId,Math.min(maxW, panelWidth), Math.min(panelHeight, maxH),xPosition,yPosition);
                

           }, panel, true);
		}
		cleanSrc();
		var popupPanel=popupPanels[iframeId];
		function  destroyPanel(){
			popupPanel.destroy();
		} 
		//popupPanel.hideEvent.unsubscribeAll();
//		if(top.isIE()){
//			popupPanel.hideEvent.subscribe(destroyPanel);
//		}else{
//			popupPanel.hideEvent.subscribe(cleanSrc);
//		}
//		
		

		if(width==0 && height==0){
			syncIframe(iframeId,0,0,url); 
			popupPanel.hide();
		}else{
			setPopupPanelHeader(iframeId,title);
			var docMaxW;
			var docMaxH;
			if(top.isIE()){
                docMaxW = document.body.clientWidth;
             } else {
            	
                docMaxW = this.innerWidth;
             }
			docMaxH =YAHOO.util.Dom.getViewportHeight()-35;
			width=Math.min(width, docMaxW);
			
			
			if(height<0){
				height=docMaxH;
			}else{
				height=Math.min(height,docMaxH);
			}
			
			popupPanel.cfg.setProperty("height", height+"px");
			popupPanel.cfg.setProperty("width", width+"px");
			syncIframe(iframeId,width,height,url);
			popupPanel.moveTo(xPosition,yPosition);
			popupPanel.cfg.zIndex=1000;
			popupPanel.show();
        	
		}
		var configObj={
				title:title,
				url:url,
				xPosition:xPosition,
				yPosition:yPosition,
				width:width,
				height:height
		};
		popupInitStatus[iframeId]=configObj;
        
};


function getIframeDocument(iframeId){
	if (document.frames){
		var frameObj=document.frames[iframeId];
		if(frameObj){
			return frameObj.document;
		}
	}else{
		var frameObj = document.getElementById(iframeId);
		if(frameObj){
			return frameObj.contentDocument;
		}
	}
}

function getIframeDoc(iframeObj){
	if(!iframeObj) return;
	if (top.isIE()){
		
			return iframeObj.document;
		
	}else{
		
			return iframeObj.contentDocument;
		
	}
}


var secuQuestionDialog;
var secuQuestionAlert = 'Prescribing electronically in the State of Ohio requires extra security measures. \nPlease answer the questions found in Misc > Customize > Maintain Security Questions';
function initSecurityQuestions(userId, executeJs, errorJs) {
	function handleRetrievedQuestions(o) {
          var rtObj=top.parseResponse(o);
          if (rtObj.questionIds == null || rtObj.questions == null) {
	    //alert('We are unable to retrieve any security questions, please make sure you have answered all of the security questions.');
	    alert(secuQuestionAlert);
	    return;
	  }
	  var questionIds = rtObj.questionIds;
	  var questions = rtObj.questions;
	  var text = '';
	  for (var i = 0; i < questionIds.length && i < questions.length; i++) {
	    text += questions[i] + '<br/><input type="text" id="ajaxSecuAnswer'+(i+1)+'"/>';
	    text += '<input type="hidden" id="ajaxSecuQuestionId'+(i+1)+'" value="'+questionIds[i]+'"/><br/>';
	  }
	  var handleSubmit = function() {
	    var qry = '?targetAction=4';
	    var qId1 = document.getElementById('ajaxSecuQuestionId1');
	    var qId2 = document.getElementById('ajaxSecuQuestionId2');
	    var ans1 = document.getElementById('ajaxSecuAnswer1');
	    var ans2 = document.getElementById('ajaxSecuAnswer2');
	    if (qId1 != null) { qry += '&questionIds='+qId1.value; }
	    if (qId2 != null) { qry += '&questionIds='+qId2.value; }
	    if (ans1 != null) { qry += '&answers='+ans1.value; }
	    if (ans2 != null) { qry += '&answers='+ans2.value; }
	    function handleCheckSecurityQuestionSucc(o) {
	      var rtObj=top.parseResponse(o);
              if (rtObj.verified) {
		eval(executeJs);
              } else {
		if (errorJs != null) {
		  eval(errorJs);
		} else {
		  alert('Security questions and answers does not match!');
		  initSecurityQuestions(userId, executeJs, errorJs);
		}
              }
	    }
	    function handleCheckSecurityQuestionFailure() {
              //alert('We are unable to verify the security questions and answers, please try again later!');
	      alert(secuQuestionAlert);
            }
	    ajaxSubmitPageUrl("/vco/user/maintainSecuQuestions.do"+qry, {success:handleCheckSecurityQuestionSucc, failure:handleCheckSecurityQuestionFailure, timeout:6000});
          };
          var handleCancel = function() {
	    if (secuQuestionDialog != null) {
	      secuQuestionDialog.hide();
	    }
          };
	  if (secuQuestionDialog != null) {
	    //secuQuestionDialog.destory();
	  }
	  secuQuestionDialog = new YAHOO.widget.SimpleDialog("secQuestionDialog",
            {width:"300px",fixedcenter:true,visible:true,draggable:true,close:false,text:text,constraintoviewport:true,
            buttons:[{text:"Submit",handler:handleSubmit,isDefault:true},{text:"Cancel",handler:handleCancel}]});
	  secuQuestionDialog.setHeader("Please answer the following questions.");
	  secuQuestionDialog.render(document.body);
        };
        function handleRetrieveQuestionsFailure() {
	  //alert('We are unable to retrieve any security questions, please make sure you have answered all of the security questions.');
	  alert(secuQuestionAlert);
        };
	var url="/vco/user/maintainSecuQuestions.do?userId="+userId+"&targetAction=5";
	ajaxSubmitPageUrl(url, {success:handleRetrievedQuestions,failure:handleRetrieveQuestionsFailure,timeout:6000});
}

var secuQuestionDialog;
function initSecurityQuestions(userId, executeJs, errorJs) {
        function handleRetrievedQuestions(o) {
          var rtObj=top.parseResponse(o);
          if (rtObj.questionIds == null || rtObj.questions == null) {
            //alert('We are unable to retrieve any security questions, please make sure you have answered all of the security questions.');
	    alert(secuQuestionAlert);
            return;
          }
          var questionIds = rtObj.questionIds;
          var questions = rtObj.questions;
          var text = '';
          for (var i = 0; i < questionIds.length && i < questions.length; i++) {
            text += questions[i] + '<br/><input type="text" id="ajaxSecuAnswer'+(i+1)+'"/>';
            text += '<input type="hidden" id="ajaxSecuQuestionId'+(i+1)+'" value="'+questionIds[i]+'"/><br/>';
          }
          var handleSubmit = function() {
            var qry = '?targetAction=4';
            var qId1 = document.getElementById('ajaxSecuQuestionId1');
            var qId2 = document.getElementById('ajaxSecuQuestionId2');
            var ans1 = document.getElementById('ajaxSecuAnswer1');
            var ans2 = document.getElementById('ajaxSecuAnswer2');
            if (qId1 != null) { qry += '&questionIds='+qId1.value; }
            if (qId2 != null) { qry += '&questionIds='+qId2.value; }
            if (ans1 != null) { qry += '&answers='+ans1.value; }
            if (ans2 != null) { qry += '&answers='+ans2.value; }
            function handleCheckSecurityQuestionSucc(o) {
              var rtObj=top.parseResponse(o);
              if (rtObj.verified) {
                eval(executeJs);
              } else {
                if (errorJs != null) {
                  eval(errorJs);
                } else {
                  alert('Security questions and answers does not match!');
                  initSecurityQuestions(userId, executeJs, errorJs);
                }
              }
            }
            function handleCheckSecurityQuestionFailure() {
              //alert('We are unable to verify the security questions and answers, please try again later!');
	      alert(secuQuestionAlert);
            }
            ajaxSubmitPageUrl("/vco/user/maintainSecuQuestions.do"+qry, {success:handleCheckSecurityQuestionSucc, failure:handleCheckSecurityQuestionFailure, timeout:6000});
          };
          var handleCancel = function() {
            if (secuQuestionDialog != null) {
              secuQuestionDialog.hide();
            }
          };
          if (secuQuestionDialog != null) {
            //secuQuestionDialog.destory();
          }
          secuQuestionDialog = new YAHOO.widget.SimpleDialog("secQuestionDialog",
            {width:"300px",fixedcenter:true,visible:true,draggable:true,close:false,text:text,constraintoviewport:true,
            buttons:[{text:"Submit",handler:handleSubmit,isDefault:true},{text:"Cancel",handler:handleCancel}]});
          secuQuestionDialog.setHeader("Please answer the following questions.");
          secuQuestionDialog.render(document.body);
	};
        function handleRetrieveQuestionsFailure() {
          //alert('We are unable to retrieve any security questions, please make sure you have answered all of the security questions.');
	  alert(secuQuestionAlert);
        };
        var url="/vco/user/maintainSecuQuestions.do?userId="+userId+"&targetAction=5";
        ajaxSubmitPageUrl(url, {success:handleRetrievedQuestions,failure:handleRetrieveQuestionsFailure,timeout:6000});
}

function getHeightNumber(heightPx){
	heightPx=heightPx.substring(0,heightPx.length - 2);
	return parseInt(heightPx);
}

function resizePanasize(htmlElement){
	var contentDivHeight=top.getMainContentHeight();
	var heightNum=getHeightNumber(contentDivHeight);
	htmlElement.style.height=(heightNum/2-50)+"px"; 
}

function calendarPref(){
  eval(top.SynaTab.wrapTabLink('calendar', 'goCalendarPref()'));
}

function getRadioValue(radioElement){
	var rtValue =null;
	for (var i=0; i < radioElement.length; i++){
		if (radioElement[i].checked){
			rtValue = radioElement[i].value;
		}
	}
	return rtValue;
	
}

function copyStyle(styleFrom, styleTo){
	  var baseStyle = styleFrom;
    var targStyle = styleTo;
    
    for(var prop in baseStyle)
    {
          var str = "targStyle." + prop + " = baseStyle." + prop + ";";

          try
          {
                eval(str);
          }
          catch(e)
          {
                // Do nothing
          }
    }
	  
};
function getCoord(e) {
    var posx = 0;
    var posy = 0;
                         
    if (!e) var e = window.event;
                         
    if (e.pageX || e.pageY) {
         posx = e.pageX;
         posy = e.pageY;
    } else if (e.clientX || e.clientY) {
          posx = e.clientX + document.body.scrollLeft;
          posy = e.clientY + document.body.scrollTop;
    }
                   
    return [posx,posy];
}

//selector: required
//position: optional
//width: optional
//content: optional
//maxWidth: optional

function initTooltipWithSelector(selector, positions, width, content, maxWidth){

	var elements=jQuery(selector);
	
	if(elements.length<=0) return;
	
	elements.each(function(){
		var tooltipWidth=width;
		var element=jQuery(this);
		var title=element.attr("title");
		
		if(!title && content){
			title=content;
		}
		if(!title){
			return;
		}

		var maxWord=0;
		var split=title.split(" ");
		for(var i=0; i<split.length; i++){
			var word=split[i];
			if(word.length>maxWord){
				maxWord=word.length;
			}
		}
		var defaultWidth=200;
		maxWidth = maxWidth||500;
		var calWidth =tooltipWidth||maxWord*5;
		tooltipWidth = Math.min(maxWidth, Math.max(defaultWidth, calWidth));
		

		var options={
				fill: '#F7F7F7', 
				strokeStyle: '#B7B7B7', 
				spikeLength: 10, 
				spikeGirth: 10, 
				padding: 8, 
				shrinkToFit:true,
				cornerRadius: 0, 
				cssStyles: {
					fontFamily: '"lucida grande",tahoma,verdana,arial,sans-serif', 
					fontSize: '11px',
					'word-wrap': 'break-word'
				}	
		}
	
		if(tooltipWidth){
			options.width=tooltipWidth;
		}
		if(positions){
			options.positions=positions;
		}
		if(content){
			element.bt(content,options);

		}else{
			element.bt(options);
		}
	}
	);
}
 
//elementId: required
//position: optional
//width: optional
//content: optional
function initTooltip(elementId, positions, width, content){
	initTooltipWithSelector("#"+elementId,positions,width,content);
}

function hideTooltip(){
	 var tooltipDiv=document.getElementById(tooltipdivId);
	 if(tooltipDiv){
		 tooltipDiv.style.display="none";	
	 }
}

function showHandCursor(){
	document.body.style.cursor = 'pointer';
}

function showNormalCursor(){
	document.body.style.cursor = 'default';
}
Array.prototype.remove = function(from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};


function noEnter(evt){
	var keyCode = null;

    if( evt.which ) {
       keyCode = evt.which;
    } else if( evt.keyCode ) {
       keyCode = evt.keyCode;
    }
  
	if( 13 == keyCode ) {
      return false;
    } 
    return true;

}

function enterPressed(evt){
	return !noEnter(evt);
}




var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};


function disableSelection(target){
	if (typeof target.onselectstart!="undefined") //IE route
		target.onselectstart=function(){return false}
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
		target.style.MozUserSelect="none"
	else //All other route (ie: Opera)
		target.onmousedown=function(){return false}
	target.style.cursor = "default"
}


function popupSecureEmail(form, targetAction){

	
  	oWin[3].open("Secure Email", "/vco/blank.html", 800, 600);
  	form.target="iframe3";
	form.targetAction.value=targetAction;

	form.submit();
 	form.target="_self";	
 	
}

function popupAddAlert(pid){
	oWin[3].open("Add Alert", "/vco/blank.html", 500, 350);
  	document.patientMenuForm.target="iframe3";
  	document.patientMenuForm.pid.value=pid;
  	document.patientMenuForm.targetAction.value=99;
  	document.patientMenuForm.submit();
  	//alert(top.document.patientMenuForm.target);
  	document.patientMenuForm.target="_self";
}




function sendSecureEmail(sendTo){
	oWin[3].open("Secure Email", "/vco/message/messageCompose.jsp?newCompose=true&messageTo="+sendTo, 750, 550);
}

function emailPatient(pid){
	if(pid>0){
		document.patientMenuForm.pid.value=pid;
	}
	var pid = document.patientMenuForm.pid.value;

	if(pid<=10){
		alert('Please select a patient before selecting one of these patient functions.');
		return; 
	}
	top.document.patientMenuForm.pid.value=pid;
	top.popupSecureEmail(top.document.patientMenuForm,89);

}

function emailWithAssociatedPatient(pid){
	if(pid>0){
		document.patientMenuForm.pid.value=pid;
	}
	var pid = document.patientMenuForm.pid.value;

	if(pid<=10){
		alert('Please select a patient before selecting one of these patient functions.');
		return; 
	}
	top.document.patientMenuForm.pid.value=pid;
	top.popupSecureEmail(top.document.patientMenuForm,100);
	
}

function popClinicalSummary(form, targetAction){
	oWin[3].open("Clinical Summary", "/vco/blank.html", 850, 600);
  	form.target="iframe3";
	form.targetAction.value=targetAction;
	form.submit();
 	form.target="_self";	
}

function showPatientClinicalSummary(pid){
	if(pid>0){
		top.document.patientMenuForm.pid.value=pid;
	}

	var pid = top.document.patientMenuForm.pid.value;
	if(pid<=10){
		alert('Please select a patient before selecting one of these patient functions.');
		return; 
	} 
	top.popClinicalSummary(top.document.patientMenuForm,97);
}

function popupAssignTask(form, targetAction, title) {
	if (title == null || title == '') {
	  title = 'Assign Task';
	}
    oWin[task].open(title, "/vco/blank.html", 475, 450, 10, document.body.scrollTop+40);
	form.target = 'iframe2';
	form.targetAction.value=targetAction;
	form.submit();
	form.target="_self";
}

function closeAssignTask() {
	oWin[task].close();
}

function checkemail(email){
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
    if (filter.test(email)){
            return true;
    }else{
            return false;
    }
}


// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};


function disableLink(linkId){
	var linkObj=document.getElementById(linkId);
	linkObj.style.color="silver";
	linkObj.href="javascript:void(0)";
	linkObj.innerHTML="Processing...";

}

function highLightElement(className){
	$('.'+className).hover(function(){
		$(this).children().addClass('datahighlight');
	},function(){
		$(this).children().removeClass('datahighlight');
	});

}

function printStackTrace() {
  var callstack = [];
  var isCallstackPopulated = false;
  try {
    i.dont.exist+=0; //doesn't exist- that's the point
  } catch(e) {
    if (e.stack) { //Firefox
      var lines = e.stack.split('\n');
      for (var i=0, len=lines.length; i<len; i++) {
        if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
          callstack.push(lines[i]);
        }
      }
      //Remove call to printStackTrace()
      callstack.shift();
      isCallstackPopulated = true;
    }
    else if (window.opera && e.message) { //Opera
      var lines = e.message.split('\n');
      for (var i=0, len=lines.length; i<len; i++) {
        if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
          var entry = lines[i];
          //Append next line also since it has the file info
          if (lines[i+1]) {
            entry += " at " + lines[i+1];
            i++;
          }
          callstack.push(entry);
        }
      }
      //Remove call to printStackTrace()
      callstack.shift();
      isCallstackPopulated = true;
    }
  }
  if (!isCallstackPopulated) { //IE and Safari
    var currentFunction = arguments.callee.caller;
    while (currentFunction) {
      var fn = currentFunction.toString();
      var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf('')) || 'anonymous';
      callstack.push(fname);
      currentFunction = currentFunction.caller;
    }
  }
  output(callstack);
}

function output(arr) {
  //Optput however you want
  alert(arr.join('\n\n'));
}

function wrapPostDataWithSynaTabId(postData){
	if(window.synaTabId && window.synaTabId!=null && window.synaTabId!=undefined){
		postData.synaTabId=window.synaTabId;
	}
}

function wrapQueryWithSynaTabId(query){
	  var hadQuery=true;
	  if(action.indexOf('?')<0){
		  query=action+"?";
		  hadQuery=false;
	  }
		
	  if(window.synaTabId && window.synaTabId!=null && window.synaTabId!=undefined){
		  query+=(hadQuery?"&":"")+"synaTabId="+window.synaTabId+"&";
	   }
}

function hideProgressBarInner() {
   if (hideWaitDial) { hideWaitDial();
   } else if (hideProgressBar) { hideProgressBar(); }
}
function showProgressBarInner() {
   if (showWaitDial) {
     showWaitDial('Processing, please wait...', true);
   } else if (doProgressBar) {
     doProgressBar();
   }
}
function isWithinRange(value, upper, lower){
	return value<=upper && value >=lower;
}

function isDate(s)
{
	// make sure it is in the expected format
	if (s.search(/^\d{1,2}[\/|\-|\.|_]\d{1,2}[\/|\-|\.|_]\d{4}/g) != 0)
	return false;
	 
	// remove other separators that are not valid with the Date class
	s = s.replace(/[\-|\.|_]/g, "/");
	 
	// convert it into a date instance
	var dt = new Date(Date.parse(s));
	 
	// check the components of the date
	// since Date instance automatically rolls over each component
	var arrDateParts = s.split("/");
	return (
	dt.getMonth() == arrDateParts[0]-1 &&
	dt.getDate() == arrDateParts[1] &&
	dt.getFullYear() == arrDateParts[2]
	);
} 
