var CONST_SLIDESHOW_DLG_WIDTH = 980;
var CONST_SLIDESHOW_DLG_HEIGHT = 650;
var isNav = (navigator.appName.indexOf("Netscape") != -1) ? true : false;
var isIE = false;//(getInternetExplorerVersion() > -1) ? true : false;
var screenW = 1024, screenH = 768;
var maxScreenWidthForSmallDevices = 991; //Also has reference in ppwebCommon.js
var gbShowTextEditor = "";
var isShowTextEditor = "";

gscomingfromcancel = '' ; 
// Do not Remove Below Code.
var gsRetVal;       			// Added by Vishal W. on 10 Feb 2021 for Preferred Pharmacy on Web Patient Portal Enhancement(#341583).
var gsOperation4PP	= '';		// Added by Vishal W. on 10 Feb 2021 for Preferred Pharmacy on Web Patient Portal Enhancement(#341583).

// Manoj S. on 18 FEB 2019 - Legal Document Signing Issue (Open the document using Zoom Icon and submit it from Parent screen)
var gsPortalZoomWinObj ;

if (parseInt(navigator.appVersion)>3) 
{
 	screenW = screen.width;
 	screenH = screen.height;
}
else if (navigator.appName == "Netscape" && parseInt(navigator.appVersion)==3 && navigator.javaEnabled()) 
{
 	var jToolkit = java.awt.Toolkit.getDefaultToolkit();
 	var jScreenSize = jToolkit.getScreenSize();
 	screenW = jScreenSize.width;
 	screenH = jScreenSize.height;
}

if(navigator.userAgent.indexOf("iPad")>0 )
{	
	var temp 	= screenW;
	screenW		= screenH;
	screenH		= temp;
}

function setIdIfNotExists()
{
    for (var i = 0, length = document.all.length; i < length; i++)
	{
	    if (((typeof (document.all[i].id) == 'undefined') || (document.all[i].id == "")) && (typeof (document.all[i].name) !='undefined') && (document.all[i].name != ""))
	    	document.all[i].id = document.all[i].name;
	}
}

//15 APR 2015 call from scrLabReportRHS.jsp and scrRadReportRHS.jsp
function callLargePopup4Groups(asFormField, asType, asEncStatus, asCode, asPoolName, asCssName, asTitle, asMaxSize, asIfPhraseSearch, asIfGroupSearch, callback)
{
	callBackFun	= callback;
	var paramObject = new Object();
	paramObject.textVal = document.getElementsByName(asFormField)[0].value;
	paramObject.typeVal	= asType;
	paramObject.title = "Edit - Notes";
	if(asTitle == null || asTitle == '' )
	{
		title = document.Form.msScreenTitle.value ;
		paramObject.title = document.Form.msScreenTitle.value ;
	}
	else
	{
		title = asTitle;
		paramObject.title = asTitle ;
	}
	url = "scrNotes.jsp?encStatus="+asEncStatus+"&type="+asType+"&title="+title+"&code="+asCode+"&poolname="+asPoolName+"&cssname="+asCssName+"&maxsize="+asMaxSize+"&phrasesearch="+asIfPhraseSearch+"&groupsearch=" + asIfGroupSearch ;
	
	var newurl	= packWhereParam2(url);
	newurl 		= "scrPopUpFrame.jsp?mainurl="+newurl;
	newurl 		= packWhereParam(newurl);
	
	asFormField1	= asFormField;
	retVal			= showGlobalModalPopup("scrModal.jsp?url="+newurl, paramObject, 'dialogHeight: 550px; dialogWidth: 900px; dialogTop: 30px; dialogLeft: 50px; edge: raised; center: Yes; help: No; resizable: No; scroll: Auto; status: No;', 100, 100, callBack4GroupSearch);
	if (isIE) callBack4GroupSearch();
}

function callBack4GroupSearch()
{
	if (!isIE) retVal = top.$('#modalWindow1')[0].globalReturnObject;
	
	if(retVal!=null)
	{
		textVal = retVal.textVal;
		document.getElementsByName(asFormField1)[0].value = textVal;
		document.getElementsByName(asFormField1)[0].focus();
		valueChanged();
	}
	if(!isIE && callBackFun != null && callBackFun != '')
		eval(callBackFun+'()');
}


//11 APR 2015 call from scrReports.jsp
function callLargePopup4Sql(asFormField, asType, asEncStatus, asCode, asPoolName, asCssName, asTitle, asMaxSize, asIfPhraseSearch, asCalledFrom, callback)
{	
	callBackFun	= callback;
	var paramObject = new Object();
	//paramObject.textVal = document.getElementById(asFormField).value;
	paramObject.textVal = document.getElementsByName(asFormField)[0].value;
	paramObject.typeVal	= asType;
	paramObject.title="Edit SQL";
	if(asTitle == null || asTitle == '' )
		title = document.Form.msScreenTitle.value;
	else
		title = asTitle;
	url = "scrNotes.jsp?encStatus="+asEncStatus+"&type="+asType+
		  "&title="+title+"&code="+asCode+"&poolname="+asPoolName+"&cssname="+asCssName+"&maxsize="+asMaxSize+
		  "&phrasesearch="+asIfPhraseSearch+"&textarearows=25&iscallfrom="+asCalledFrom;
	
	var newurl	= packWhereParam2(url);
	newurl 		= "scrPopUpFrame.jsp?mainurl="+newurl;
	newurl 		= packWhereParam(newurl);
	
	asFormField1	= asFormField;
	retVal			= showGlobalModalPopup("scrModal.jsp?url="+newurl, paramObject, 'dialogHeight: 550px; dialogWidth: 900px; dialogTop: 30px; dialogLeft: 50px; edge: raised; center: Yes; help: No; resizable: No; scroll: Auto; status: No;', 100, 100, generatedCallback_MDjs_Common4Sql_1);
	if (isIE) generatedCallback_MDjs_Common4Sql_1();
}
function generatedCallback_MDjs_Common4Sql_1()
{
    if (!isIE) retVal = top.$('#modalWindow1')[0].globalReturnObject;
	if(retVal!=null)
	{	
		textVal = retVal.textVal;
		document.getElementsByName(asFormField1)[0].value = textVal;
		document.getElementsByName(asFormField1)[0].focus();
		valueChanged();
	}
	if(!isIE && callBackFun != null && callBackFun != '')
		eval(callBackFun+'()');
}
function callLargePopup(asFormField, asType, asEncStatus, asCode, asPoolName, asCssName, asTitle, asMaxSize, asIfPhraseSearch, callback, readOnly,ShowTextEditor)
{	
	callBackFun		= callback;
	var paramObject = new Object();
	isShowTextEditor = ShowTextEditor;
	//paramObject.textVal = document.getElementById(asFormField).value;
	paramObject.textVal = document.getElementsByName(asFormField)[0].value;
	paramObject.typeVal	= asType;
	paramObject.title="Edit - Notes";
	if(asTitle == null || asTitle == '' )
	{
		title = document.Form.msScreenTitle.value;
		paramObject.title = document.Form.msScreenTitle.value;
	}
	else
	{
		title = asTitle;
		paramObject.title = asTitle;
	}
	url = "scrNotes.jsp?encStatus="+asEncStatus+"&type="+asType+"&title="+title+"&code="+asCode+"&poolname="+asPoolName+"&cssname="+asCssName+"&maxsize="+asMaxSize+"&phrasesearch="+asIfPhraseSearch+"&readonly="+readOnly+"&isShowTextEditor="+isShowTextEditor ;
	
	var newurl	= packWhereParam2(url);
	newurl 		= "scrPopUpFrame.jsp?mainurl="+newurl;
	newurl 		= packWhereParam(newurl);
	
	asFormField1	= asFormField;
	retVal			= showGlobalModalPopup("scrModal.jsp?url="+newurl, paramObject, 'dialogHeight: 540px; dialogWidth: 1000px; dialogTop: 50px; dialogLeft: 250px; edge: raised; center: Yes; help: No; resizable: No; scroll: Auto; status: No;', 100, 100, generatedCallback_MDjs_Common_1);//Skumar 14 April 2016 Increase Height For Safari 1024*768
	if (isIE) generatedCallback_MDjs_Common_1();
}
function generatedCallback_MDjs_Common_1()
{
	if (!isIE) retVal = top.$('#modalWindow1')[0].globalReturnObject;
	if(retVal!=null)
	{	
		if(retVal.textVal == undefined || retVal.textVal == null || retVal.textVal == "undefined" ) // 17 DEC 2019 retVal.textVal-> Giving undefined text
		{
			; // Do Nothing
		}
		else
		{
			textVal = retVal.textVal;
			document.getElementsByName(asFormField1)[0].value = textVal;
			document.getElementsByName(asFormField1)[0].focus();
			if(gbShowTextEditor && isShowTextEditor == 'true')
			{
				$('#notesText').html(document.getElementsByName(asFormField1)[0].value);
			}
			valueChanged();
		}
	}
	if(!isIE && callBackFun != null && callBackFun != '')
		eval(callBackFun+'()');
}
//for disabling the right click	in application 
//we can right clickon text box and text area for basic copy,paste functions
//****if we want to use right click in development enviormnet just commnt the alert line.***
function right(e)
{
   if (navigator.appName == 'Netscape' && (e.which == 3 || e.which == 2))
		return false;
   else if (navigator.appName == 'Microsoft Internet Explorer' && 
    (event.button == 2 || event.button == 3)) 
	{
	   	var evt = document.event;
		var eventTarget = evt ? evt.target : event.srcElement;
		if(eventTarget.type == 'textarea' || eventTarget.type == 'text'){
				return true;
		}else
		{
		 //   alert("Sorry, Right Click is Disabled");
		   return false;
		}
   }
   return true;						  
}
document.onmousedown=right;
if (document.layers) window.captureEvents(Event.MOUSEDOWN);
window.onmousedown=right;
//End of rigth click
function logout()
{
	returnValue ="logout" ;		
	return window.close();
}
//This call only meant for the Lock Screen
function showPopupAsModalLock(url,title,height,width,top,left)
{	
	lsinputhref = window.location.href; 
	lsPrefix = "";
	var newurl =packWhereParam(url);
	var myObject = new Object();
	myObject.title = title;		
	features = 'dialogHeight: '+height+'px; dialogWidth: '+width+'px; edge: raised; help: No; resizable: No; scroll: No; status: No; fullscreen:Yes;'
	if(top != '0')
		 features += 'dialogTop: '+top+'px; ';
	if(left != '0')
		 features += 'dialogLeft: '+left+'px; ';
	retval  = showGlobalModalPopup(lsPrefix+"scrModal.jsp?url="+newurl, myObject,  features , 100, 100, generatedCallback_MDjs_Common_2);
	if (isIE) generatedCallback_MDjs_Common_2();
}
function generatedCallback_MDjs_Common_2()
{
    if (!isIE) retval  = top.$('#modalWindow1')[0].globalReturnObject;
	if(retval == null )
		return  'closing';
	else
		return  retval;
}
function closeWin( ) 
{ 
		return window.close() ; 
}
// To open the Medline site along with the key word passed
function showMedLine(keyword)
{
	lsUrl="http://search.nlm.nih.gov/medlineplus/query?DISAMBIGUATION=true&FUNCTION=search&PARAMETER=" +keyword;
	// Old URL
	//	lsUrl = "http://www.nlm.nih.gov/cgi/medlineplus/search2.pl?words=" + document.Form.msDr_keyword.value;
	open_popup(lsUrl,"prognoKeyWord","width=750,height=525,resizable=yes,scrollbars=yes,left=20,top =20");
}
function showGlobalModalPopup(url,object,features,height,width,callback)
{    
    if(!isIE)
	url = unpackWhereParam(url);

    url = encodeURI(url);
    if(features != null && features != "") {
	var lsdialogHeightArg 	= '500';
	var lsdialogWidthArg 	= '500';
	var lsdialogTopArg		= '0';
	var lsdialogLeftArg		= '0';
	var lsResizeable		= 'No';
		
	lsdialogHeightArg = extractDimension(features,'dialogHeight',';');
	if(lsdialogHeightArg == '')
	    lsdialogHeightArg = extractDimension(features,'height',',');
			
	lsdialogWidthArg = extractDimension(features,'dialogWidth',';');
	if(lsdialogWidthArg == '')			
	    lsdialogWidthArg = extractDimension(features,'width',',');
	    
	lsdialogTopArg 	= extractDimension(features,'PopUpTop',';');
	lsdialogLeftArg = extractDimension(features,'PopUpLeft',';');
	lsResizeable    = extractDimension(features,'resizable',';');
    }
    if (isIE) {
	return(window.showModalDialog(url,object,features));
    } else {
	var hideIframeModal = function(hash){
	    var $modal = $(hash.w);
	    var $modalContent = $("iframe[name=jqmContent]", $modal);
		$modalContent.html("").attr("src", "");
	    //$modal.fadeOut('2000',function(){ hash.o.remove(); });
	    $modal.hide();
	    hash.o.remove();
	    if (callback != null && callback != false)
		callback();
	}
	var onShowIframeModal = function(hash)
	{
	    var trigger = hash.c.trigger;
	    var $modal = $(hash.w);
	    var $moverlay = $(hash.o);
	    //$modal.style.visibility = visible;
	    var $modalContent = $("iframe[name=jqmContent]", $modal);
	    $modalContent.html("").attr("src", trigger.href);	
	    var newTop	= '';
	    var newLeft	= '';
	    var windowHeight	= window.outerHeight;
	    var windowWidth		= window.outerWidth;
	   
	    if(navigator.userAgent.indexOf("iPad") > -1)
	    {   
	    	windowHeight	= 760;	//$(window).height();
	    	windowWidth		= 1020;	//$(window).width();
	    }
	    if(lsdialogTopArg != '')
	    	newTop	= lsdialogTopArg;
	    else
	    {
	    	//newTop	= Math.max(Math.floor(((parseInt(screenH) - 50) - parseInt(lsdialogHeightArg))/2), 0);
	    	newTop	= (parseInt(windowHeight)/2)-(parseInt(lsdialogHeightArg)/2);
	    	if(newTop < 8) newTop=8;
	    }
	    
	    if(lsdialogLeftArg != '')
	    	newLeft	= lsdialogLeftArg;
	    else
	    {
	    	//newLeft = Math.max(Math.floor((parseInt(screenW) - parseInt(lsdialogWidthArg))/2), 0);
	    	newLeft = (parseInt(windowWidth)/2) - (parseInt(lsdialogWidthArg)/2);
	    	if(newLeft < 0) newLeft=0;
	    }
	    $modal.css({width: 0, height: 0, opacity: 0}).show().animate({height: lsdialogHeightArg, width: lsdialogWidthArg, top: newTop, left: newLeft, marginLeft: 0, opacity: 1});
	    $moverlay.css({height:'100%',width:'100%',position:'fixed'}).animate({height:'100%',width:'100%'});
	}
	top.$('#modalWindow1')[0].dialogArguments = object;
	var trigger = new Object();
	trigger.href = url;
	var i;
	for (i = 1; i <= 4; i++) {
	    try {
	    	if ((typeof (top.$.jqm.hash) != 'undefined'))
	    	{
			    if ((typeof (top.$.jqm.hash[i]) == 'undefined') || (top.$.jqm.hash[i].a != true)) 
			    {
					top.$('#modalWindow'+i).jqm({trigger: trigger, onHide: hideIframeModal, onShow: onShowIframeModal, modal: true});
					//top.$('#modalWindow'+i).w.css({'z-index': i*3000});
					top.$('#modalWindow'+i).jqmShow();
					if(lsResizeable == 'Yes')
					{
						top.$('#modalWindow'+i).resizable({
								      handles: "n, e, s, w, ne, se, sw, nw", // Enable resizing from all sides and corners
								      minHeight: 100, // Minimum height
								      minWidth: 100,  // Minimum width
								    });
						top.$('#modalWindow'+i).draggable();
					}
					return;
			    }
	    	}
	    } catch (e) {}
	}
	alert("More than four popups not supported");
    }
}
function globalClosePopup(retval)
{
    if (isIE) 
    {
	    if(typeof(gscomingfromcancel) != 'undefined')
	    	gscomingfromcancel = 'y' ;
		return top.close();
    } 
    else 
    {
		var obj = top;
		try 
		{
		    var i = 4;
		    for (i = 4; i>0; i--) 
		    {
				try 
				{
				    if (top.$.jqm.hash[i].a) 
				    {
				    	top.$('#modalWindow1')[0].globalReturnObject = retval;
						try 
						{
					    	top.$('#modalWindow'+i).jqmHide();
					    	top.$('#modalWindow'+i)[0].globalReturnObject = null;
						} 
						catch(e) 
						{
						}
						return;
				    }
				} 
				catch(e) 
				{
				};
		    }
		} 
		catch (e) 
		{
			top.close();
		}
    }
    return;
}

function closeJqmPopup(retval)
{
	//Verified By : Navin
	//Changes done by Priya on 8-Oct-2014
	//Changes done so that Multiselect option in IE browser behaves like non-IE
	var obj = top;
	try
	{
		var i = 4;
	    for (i = 4; i>0; i--)
	    {
	    	try
	    	{
	    		if (obj.$.jqm.hash[i].a)
	    		{
	    			obj.$('#modalWindow1')[0].globalReturnObject = retval;
	    			try
	    			{
	    				obj.$('#modalWindow'+i).jqmHide();
	    			}
	    			catch(e) {}
	    			return;
	    		}
	    	}
	    	catch(e) {};
	    }
	}
	catch (e) {top.close();}
    return;
}

function extractDimension(aFeatures,aDimensionType,aDimensionSeparator)
{
	var lsDimensionValue = '';
	var liIndOfdialogDimension	= aFeatures.indexOf(aDimensionType);
	var lsSeparatorIndOfdialogDimension = aFeatures.indexOf(aDimensionSeparator,liIndOfdialogDimension);
	
	var lsdialogDimensionArg = '';
	if(liIndOfdialogDimension > -1 && lsSeparatorIndOfdialogDimension > -1)
	{
		lsdialogDimensionArg = aFeatures.substring(liIndOfdialogDimension,lsSeparatorIndOfdialogDimension);
	}
	
	lsdialogDimensionArg = lsdialogDimensionArg.replace(aDimensionType,'');
	lsdialogDimensionArg = lsdialogDimensionArg.replace(':','');
	lsdialogDimensionArg = lsdialogDimensionArg.replace('=','');
	lsdialogDimensionArg = lsdialogDimensionArg.replace('px','');
	lsdialogDimensionArg = lsdialogDimensionArg.replace('em','');
	lsdialogDimensionArg = lsdialogDimensionArg.replace(' ','');
	if(lsdialogDimensionArg != '')
		lsDimensionValue = lsdialogDimensionArg;
	
	return lsDimensionValue;
}

var jqModalCount = 0;

function showJqmPopup(url,object,features,height,width,callback)
{
	//Verified By : Navin
	//Changes done by Priya on 8-Oct-2014
	//Changes done so that Multiselect option in IE browser behaves like non-IE
    if(features != null && features != "")
    {
		var lsdialogHeightArg 	= '500';
		var lsdialogWidthArg 	= '500';
		var lsdialogTopArg		= '0';
		var lsdialogLeftArg		= '0';
			
		lsdialogHeightArg = extractDimension(features,'dialogHeight',';');
		if(lsdialogHeightArg == '')
		    lsdialogHeightArg = extractDimension(features,'height',',');
				
		lsdialogWidthArg = extractDimension(features,'dialogWidth',';');
		if(lsdialogWidthArg == '')			
		    lsdialogWidthArg = extractDimension(features,'width',',');
		    
		lsdialogTopArg 	= extractDimension(features,'PopUpTop',';');
		lsdialogLeftArg = extractDimension(features,'PopUpLeft',';');
		
    }
	var hideIframeModal = function(hash)
	{
	    var $modal = $(hash.w);
	    var $modalContent = $("iframe[name=jqmContent]", $modal);
		$modalContent.html("").attr("src", "blank.html"); //19 NOV 2015 Amey Sawant - setting blank source to iframe causes problem in MS Edge browser.
	    $modal.hide();
	    hash.o.remove();
	    if (callback != null && callback != false)
		callback();
	}
	var onShowIframeModal = function(hash)
	{
		var trigger = hash.c.trigger;
		var $modal = $(hash.w);
		var $moverlay = $(hash.o);
	    var $modalContent = $("iframe[name=jqmContent]", $modal);
	    $modalContent.html("").attr("src", trigger.href);	
	    var newTop	= '';
	    var newLeft	= '';
	    var windowHeight	= window.outerHeight;
	    var windowWidth		= window.outerWidth;
	    if(navigator.userAgent.indexOf("iPad") > -1)
	    {
	    	windowHeight	= 760;	//$(window).height();
	    	windowWidth		= 1020;	//$(window).width();
	    }
	    if(lsdialogTopArg != '')
	    	newTop	= lsdialogTopArg;
	    else
	    {
	    	newTop	= (parseInt(windowHeight)/2)-(parseInt(lsdialogHeightArg)/2);
	    }
		    
	    if(lsdialogLeftArg != '')
	    	newLeft	= lsdialogLeftArg;
	    else
	    {
	    	newLeft = (parseInt(windowWidth)/2) - (parseInt(lsdialogWidthArg)/2);
	    }
		    
	    $modal.css({width: 0, height: 0, opacity: 0}).show().animate({height: lsdialogHeightArg, width: lsdialogWidthArg, top: newTop, left: newLeft, marginLeft: 0, opacity: 1});
	    $moverlay.css({height:'100%',width:'100%',position:'fixed'}).animate({height:'100%',width:'100%'});
	}
	top.$('#modalWindow1')[0].dialogArguments = object;
	var trigger = new Object();
	url 		= encodeURI(url);
	trigger.href = url;
	var i;
	for (i = 1; i <= 4; i++)
	{
		try
		{
			if ((typeof (top.$.jqm.hash) != 'undefined'))
				if ((typeof (top.$.jqm.hash[i]) == 'undefined') ||	(top.$.jqm.hash[i].a != true)) 
				{
					top.$('#modalWindow'+i).jqm({trigger: trigger, onHide: hideIframeModal, onShow: onShowIframeModal, modal: true});
					top.$('#modalWindow'+i).jqmShow();
					return;
			    }
		}
		catch (e) {}
	}
	alert("More than four popups not supported");
}

// to display popups as modal windows	
function showPopupAsModal(url,title,height,width,top,left,callback)
{	
    var newurl = (isIE) ? "scrModal.jsp?url="+packWhereParam(url) : url;
	var myObject = new Object();
	myObject.title = title;	
			features = 'dialogHeight: '+height+'px; dialogWidth: '+width+'px; edge: raised; center: Yes; help: No; resizable: No; scroll: No; status: No;'
			if(top != '0')
				 features += 'dialogTop: '+top+'px; ';
			if(left != '0')
				 features += 'dialogLeft: '+left+'px; ';
    return showGlobalModalPopup(newurl,myObject,features,height,width,callback);
}
function showJqModalConfirm(message,title,height,width,callback)
{	
	var myObject = new Object();
	myObject.title = title;	
	features = 'dialogHeight: '+height+'px; dialogWidth: '+width+'px; edge: raised; center: Yes; help: No; resizable: No; scroll: No; status: No;'
	newurl = "scrConfirm.jsp?message="+message;
	//return showGlobalModalPopup(newurl,myObject,features,height,width,callback);
	showJqmPopup(newurl,myObject,features,height,width,callback);
}
//this two methodes are used  opening and closing new window
function globalClosePopupNote(retval)
{ 
	  
	
	var obj = top;
	
	top.close();
return ;
}
function showGlobalModalPopupNote(url,object,features,height,width,callback)
{
	
	
 /*   if(!isIE)
	url = unpackWhereParam(url);*/

    if(features != null && features != "") {
	var lsdialogHeightArg = '500';
	var lsdialogWidthArg = '500';
		
	lsdialogHeightArg = extractDimension(features,'dialogHeight',';');
	if(lsdialogHeightArg == '')
	    lsdialogHeightArg = extractDimension(features,'height',',');
			
	lsdialogWidthArg = extractDimension(features,'dialogWidth',';');
	if(lsdialogWidthArg == '')			
	    lsdialogWidthArg = extractDimension(features,'width',',');
    }
   var agent = navigator.userAgent.toLowerCase();
   url 		 = encodeURI(url);
    if(agent.indexOf('android') >= 0 ){
        var retval=window.open(url,'','');
    }else{
        var retval=window.open(url,object,features);
    }
   
 return;  
}


// to display popups as modal windows	
function showPopupAsModalNote(url,title,height,width,top,left,callback)
{	
	
    var newurl = "scrModal.jsp?url="+packWhereParam(url) ;
	var myObject = new Object();
	myObject.title = title;	
			features = 'dialogHeight: '+height+'px; dialogWidth: '+width+'px; edge: raised; center: Yes; help: No; resizable: No; scroll: No; status: No;'
			if(top != '0')
				 features += 'dialogTop: '+top+'px; ';
			if(left != '0')
				 features += 'dialogLeft: '+left+'px; ';
    return showGlobalModalPopupNote(newurl,myObject,features,height,width,callback);
}
function squeezeCommas(originalString)
{	
	return replaceChar(originalString,',','');
}
function currency2Float(asValue)
{
	asValue = squeezeCommas(asValue);
	asValue = parseFloat(asValue);
	return asValue;
}
function roundAmount(afNum)
{
	cents = Math.round(afNum * 100);
	amount = cents/100;
	return amount;
}
// Replaces all occurence of param2 with param3 and returns a new string
function replaceChar(originalString,findstr,replacestr)
{	
	var finalString = '';
	var findlen = findstr.length;
	cnti=0; 
	while (cnti <originalString.length) 
	{      
		// assume last will not be '&', i +1 to be taken care else
		if(originalString.substring(cnti,cnti+findlen) == findstr)
		{	
			finalString= finalString + replacestr;
			cnti+=findlen;
		}
		else
		{
			if(cnti==0)
				finalString= originalString.substring(cnti,cnti+1);
			else	
				finalString= finalString + originalString.substring(cnti,cnti+1);
			cnti++;
		}
	}
	
	return finalString;
}
// new method added.
function unpackWhereParam(asString)
{
	//Verified By Shahin
	//Changes done by Priya to replace .pt. before .sp. since if pt was added in remarks then wrong output was displayed
	if(asString == null || asString == "") 
		return "";
	var lsWhere ="";
	lsWhere = replaceChar(asString,".le.","<=");
	lsWhere = replaceChar(lsWhere,".ge.",">=");
	lsWhere = replaceChar(lsWhere,".eq.","=");
	lsWhere = replaceChar(lsWhere,".sq.","'"); 
	lsWhere	= replaceChar(lsWhere,".amp.","&"); 
	lsWhere	= replaceChar(lsWhere,".qm.","?"); 
	lsWhere	= replaceChar(lsWhere,".hs.","#"); 
	lsWhere	= replaceChar(lsWhere,".sp."," "); 
	lsWhere = replaceChar(lsWhere,".pt.","%");
	lsWhere	= replaceChar(lsWhere,".qt.","\""); 
	lsWhere = replaceChar(lsWhere,".lt.","<");
	lsWhere = replaceChar(lsWhere,".gt.",">");
	//Verified by Shahin
	//Changes done by Priya to unpack .tt. which was already done by Amey in WIP
	lsWhere = replaceChar(lsWhere,".tt.","~");
	// Changes done by Ashwini to unpack .su. to '+', verified by Deepraj
	//for Sugar case no-336185 - Symbol '+' displaying incorrectly on Output templates.
	lsWhere = replaceChar(lsWhere,".su.","+");
	lsWhere = replaceChar(lsWhere,".nl.","\r\n"); // Added by Ashwini on 7-4-22 Verified by Amod to resolve issue of new line ref case- 384364 
	return lsWhere;
}
function packWhereParam(asString)
{
	if(asString == null || asString == "") 
		return "";
	var lsWhere="";
	lsWhere = replaceChar(asString,"<=",".le.");
	lsWhere = replaceChar(lsWhere,">=",".ge.");
	lsWhere	= replaceChar(lsWhere,"=",".eq.");
	lsWhere	= replaceChar(lsWhere,"'",".sq.");
	lsWhere	= replaceChar(lsWhere,"%",".pt.");// Rk Change History 2
	lsWhere	= replaceChar(lsWhere,"&",".amp.");//prd Change History 6
	lsWhere	= replaceChar(lsWhere,"?",".qm.");//prd Change History 6
	lsWhere	= replaceChar(lsWhere,"#",".hs.");
	lsWhere	= replaceChar(lsWhere," ",".sp.");
	lsWhere	= replaceChar(lsWhere,"\"",".qt.");
	lsWhere = replaceChar(lsWhere,"<",".lt.");
	lsWhere = replaceChar(lsWhere,">",".gt.");
	lsWhere = replaceChar(lsWhere,"+",".su.");
	return lsWhere;
}
//this is explicitely used when there is url inside a url
function packWhereParam2(asString)
{
	if(asString == null || asString == "") 
		return "";
	var lsWhere="";
	lsWhere = replaceChar(asString,"<=",".le2.");
	lsWhere = replaceChar(lsWhere,">=",".ge2.");
	lsWhere	= replaceChar(lsWhere,"=",".eq2.");
	lsWhere	= replaceChar(lsWhere,"'",".sq2.");
	lsWhere	= replaceChar(lsWhere,"%",".pt2.");// Rk Change History 2
	lsWhere	= replaceChar(lsWhere,"&",".amp2.");//prd Change History 6
	lsWhere	= replaceChar(lsWhere,"?",".qm2.");//prd Change History 6
	lsWhere	= replaceChar(lsWhere,"#",".hs2.");
	lsWhere = replaceChar(lsWhere,"\^",".ct2."); 
	lsWhere = replaceChar(lsWhere,"+",".su2.");
	lsWhere = replaceChar(lsWhere,"|",".ps2."); 
	return lsWhere;
}
function std2Display(dispDateformat, asStdDate) 
{ 
	strDateArray = asStdDate.split('-');
	strMonth	= strDateArray[1];
	strDay		= strDateArray[2];
	strYear		= strDateArray[0];
	retDate = "";
	if(dispDateformat == 'MM/DD/YYYY'){
		retDate = strMonth+'/'+strDay+'/'+strYear;
	}else if(dispDateformat == 'MM-DD-YYYY'){
		retDate = strMonth+'-'+strDay+'-'+strYear;
	}else if(dispDateformat == 'DD/MM/YYYY'){
		retDate = strDay+'/'+strMonth+'/'+strYear;
	}else if(dispDateformat == 'DD-MM-YYYY'){
		retDate = strDay+'-'+strMonth+'-'+strYear;
	}else if(dispDateformat == 'YYYY/MM/DD'){
		retDate = strYear+'/'+strMonth+'/'+strDay;
	}else if(dispDateformat == 'YYYY-MM-DD'){
		retDate = strYear+'-'+strMonth+'-'+strDay;
	}
	return retDate ;
}
function display2Std(format, asDispDate) 
{ 
	strDateArray = asDispDate.split('-');
	if (strDateArray.length != 3) 
	{
		strDateArray = asDispDate.split('/');
	}
	strMonth	= '';
	strDay		= '';
	strYear		= '';
	if(format == 'MM/DD/YYYY' || format == 'MM-DD-YYYY')
	{
			strMonth	= strDateArray[0];
			strDay		= strDateArray[1];
			strYear		= strDateArray[2];
	}else if(format == 'DD/MM/YYYY' ||	format == 'DD-MM-YYYY')
	{
			strMonth	= strDateArray[1];
			strDay		= strDateArray[0];
			strYear		= strDateArray[2];
	}else if(format == 'YYYY/MM/DD' ||	format == 'YYYY-MM-DD')
	{
			strMonth	= strDateArray[1];
			strDay		= strDateArray[2];
			strYear		= strDateArray[0];
	}
	return strYear+"-"+strMonth+"-"+strDay;
}
var gDisplayFormatMMDDYYYY	= 'MM-DD-YYYY';
function display2StdDefaultFormat(asDispDate) 
{
	return display2Std(gDisplayFormatMMDDYYYY,asDispDate);
}
function std2DisplayDefaultFormat(asStdDate) 
{
	return std2Display(gDisplayFormatMMDDYYYY, asStdDate);
}
function isDateValid(format, fieldName , objName , a_yearFrom , a_yearUpto, ismandatory , fieldLabel) 
{ 
	if(ismandatory == 'true')
	{
		if(objName == '')
		{
			alert(fieldLabel+ ' is mandatory');
			return false;
		}	
	}
	else
	{
		if(objName == '')
		{
			return true;
		}		
	}
	gNow = new Date();
    p_yearFrom = gNow.getFullYear();
	if(a_yearFrom=='0'){
	    //special case , 0 has to be send as a string, otherwise it is taken as blank, and sets the default year to +20.
	}
	else if (a_yearFrom == null || a_yearFrom == "")
        p_yearFrom -= 50;
    else
        p_yearFrom += a_yearFrom;
    p_yearUpto = gNow.getFullYear();
	if(a_yearUpto=='0'){
	    //special case , 0 has to be send as a string, otherwise it is taken as blank, and sets the default year to +20.
	}
    else if (a_yearUpto == null || a_yearUpto == "")
        p_yearUpto += 20;
    else
        p_yearUpto += a_yearUpto;
 
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var booFound = false;
	var datefield = objName;
	var intElementNr;
	strDate = datefield;
	if(strDate.length > 10)
	{
		alert("This date is invalid.  Please give date in "+format+" format.");
		return false;
	}
	strDateArray = strDate.split('-');
	if (strDateArray.length != 3) 
	{
		strDateArray = strDate.split('/');
		if (strDateArray.length != 3) 
		{
			// Exact format of 10 char string
			//if (strDate.length < 10) 
			//{
			
				alert("This date is invalid.  Please give date in "+format+" format.");
				return false;
			//}		
			//strDateArray[0] = strDate.substring(0,2);
			//strDateArray[1] = strDate.substring(3,5);
			//strDateArray[2] = strDate.substring(6,10);
		}
	}
	if(format == 'MM/DD/YYYY' ||	format == 'MM-DD-YYYY')
	{
			strMonth	= strDateArray[0];
			strDay		= strDateArray[1];
			strYear		= strDateArray[2];
	}else if(format == 'DD/MM/YYYY' ||	format == 'DD-MM-YYYY')
	{
			strMonth	= strDateArray[1];
			strDay		= strDateArray[0];
			strYear		= strDateArray[2];
	}else if(format == 'YYYY/MM/DD' ||	format == 'YYYY-MM-DD')
	{
			strMonth	= strDateArray[1];
			strDay		= strDateArray[2];
			strYear		= strDateArray[0];
	}
	intday = parseIntBase10(strDay, 10);
	if (isNaN(intday)) 
	{
		alert('Day is not Valid');	
		return false;
	}
	intMonth = parseIntBase10(strMonth, 10);
	if (isNaN(intMonth)) 
	{
		alert('Month is not Valid');	
		return false;
	}
	intYear = parseIntBase10(strYear, 10);
	if (isNaN(intYear)) 
	{
		alert('Year is not Valid');	 
		return false;
	}	
	
	var tmpYear = intYear+'';
	if (tmpYear.length != 4) 
	{	
		alert('Year is not Valid');	
		return false;		
	}
	
	if(intday == 1 && intMonth == 1 && intYear == 1900)
	{
		alert('System Limitation: Date 01-01-1900 cannot be accepted.');	
		return false;
	}
	// CHECK IF THERE IS NO NON NUMERIC CHARACTER IN MONTH AND DAY.. 
	inttest = /^[0-9-]{1,}$/; 
	if(!inttest.test(strMonth))
	{	
		alert('Month is not Valid');	
		return false;		
	}
	
	if(!inttest.test(strDay))
	{	
		alert('Day is not Valid');	
		return false;		
	}
	
	if (strYear > p_yearUpto) 
	{
		alert('Year can not be more than: '+p_yearUpto+'.');	
		return false;		
	}
	if (strYear < p_yearFrom) 
	{
		alert('Year can not be earlier than: '+p_yearFrom+'.');
		return false;		
	}
		
	if (intday < 1 || intday > 31) 
	{
		alert("This date is invalid.");
		return false;
	}
	
	if (intMonth>12 || intMonth<1) 
	{
		alert("This date is invalid.  Please give date in "+format+" format.");
		return false;
	}
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) 
	{
		alert("This date is invalid.");
		return false;
	}
	if (intMonth == 2) 
	{
		if (intday > 28) 
		{
			if (LeapYear(intYear) == true) 
			{
				if (intday > 29) 
				{
					alert("This date is invalid.");
					return false;
				}
			}
			else 
			{
				alert("This date is invalid.");
				return false;
			}
		}
	}
	// pad o's Prijesh - check for "checkdate"  and add one parameter which is Name of text
	// pad o's
	if(strMonth.length > 2)
	{
		alert("This date is invalid.");
				return false;
	}
	if(strDay.length > 2)
	{
		alert("This date is invalid.");
				return false;
	}
	if(strMonth.length == 1)
	{
		strMonth = "0" + strMonth;
	}
	if(strDay.length == 1)
	{
		strDay = "0" + strDay;
	}
	retDate = '';
	if(format == 'MM/DD/YYYY'){
		retDate = strMonth+'/'+strDay+'/'+strYear;
	}else if(format == 'MM-DD-YYYY'){
		retDate = strMonth+'-'+strDay+'-'+strYear;
	}else if(format == 'DD/MM/YYYY'){
		retDate = strDay+'/'+strMonth+'/'+strYear;
	}else if(format == 'DD-MM-YYYY'){
		retDate = strDay+'-'+strMonth+'-'+strYear;
	}else if(format == 'YYYY/MM/DD'){
		retDate = strYear+'/'+strMonth+'/'+strDay;
	}else if(format == 'YYYY-MM-DD'){
		retDate = strYear+'-'+strMonth+'-'+strDay;
	}
	setBackDate(fieldName, retDate);
	return true;
}

//Sumit S. 25 JAN 2019 ProCheckIn - will be used for Alerts change on ProCheckIn
function isDateValidWithReturnMsg(format, fieldName , objName , a_yearFrom , a_yearUpto, ismandatory , fieldLabel) 
{ 
	var lsMessage = '';
	if(ismandatory == 'true')
	{
		if(objName == '')
		{
			lsMessage = fieldLabel+ ' is mandatory';
			return lsMessage;
		}	
	}
	else
	{
		if(objName == '')
		{
			return true;
		}		
	}
	gNow = new Date();
    p_yearFrom = gNow.getFullYear();
	if(a_yearFrom=='0'){
	    //special case , 0 has to be send as a string, otherwise it is taken as blank, and sets the default year to +20.
	}
	else if (a_yearFrom == null || a_yearFrom == "")
        p_yearFrom -= 50;
    else
        p_yearFrom += a_yearFrom;
    p_yearUpto = gNow.getFullYear();
	if(a_yearUpto=='0'){
	    //special case , 0 has to be send as a string, otherwise it is taken as blank, and sets the default year to +20.
	}
    else if (a_yearUpto == null || a_yearUpto == "")
        p_yearUpto += 20;
    else
        p_yearUpto += a_yearUpto;
 
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var booFound = false;
	var datefield = objName;
	var intElementNr;
	strDate = datefield;
	if(strDate.length > 10)
	{
		lsMessage = "This date is invalid.  Please give date in "+format+" format.";
		return lsMessage;
	}
	strDateArray = strDate.split('-');
	if (strDateArray.length != 3) 
	{
		strDateArray = strDate.split('/');
		if (strDateArray.length != 3) 
		{
			// Exact format of 10 char string
			//if (strDate.length < 10) 
			//{
			
			lsMessage = "This date is invalid.  Please give date in "+format+" format.";
				return lsMessage;
			//}		
			//strDateArray[0] = strDate.substring(0,2);
			//strDateArray[1] = strDate.substring(3,5);
			//strDateArray[2] = strDate.substring(6,10);
		}
	}
	if(format == 'MM/DD/YYYY' ||	format == 'MM-DD-YYYY')
	{
			strMonth	= strDateArray[0];
			strDay		= strDateArray[1];
			strYear		= strDateArray[2];
	}else if(format == 'DD/MM/YYYY' ||	format == 'DD-MM-YYYY')
	{
			strMonth	= strDateArray[1];
			strDay		= strDateArray[0];
			strYear		= strDateArray[2];
	}else if(format == 'YYYY/MM/DD' ||	format == 'YYYY-MM-DD')
	{
			strMonth	= strDateArray[1];
			strDay		= strDateArray[2];
			strYear		= strDateArray[0];
	}
	intday = parseIntBase10(strDay, 10);
	if (isNaN(intday)) 
	{
		lsMessage = 'Day is not Valid';	
		return lsMessage;
	}
	intMonth = parseIntBase10(strMonth, 10);
	if (isNaN(intMonth)) 
	{
		lsMessage = 'Month is not Valid';	
		return lsMessage;
	}
	intYear = parseIntBase10(strYear, 10);
	if (isNaN(intYear)) 
	{
		lsMessage = 'Year is not Valid';	 
		return lsMessage;
	}	
	
	var tmpYear = intYear+'';
	if (tmpYear.length != 4) 
	{	
		lsMessage = 'Year is not Valid';	
		return lsMessage;		
	}
	
	if(intday == 1 && intMonth == 1 && intYear == 1900)
	{
		lsMessage = 'System Limitation: Date 01-01-1900 cannot be accepted.';	
		return lsMessage;
	}
	// CHECK IF THERE IS NO NON NUMERIC CHARACTER IN MONTH AND DAY.. 
	inttest = /^[0-9-]{1,}$/; 
	if(!inttest.test(strMonth))
	{	
		lsMessage = 'Month is not Valid';	
		return lsMessage;		
	}
	
	if(!inttest.test(strDay))
	{	
		lsMessage = 'Day is not Valid';	
		return lsMessage;		
	}
	
	if (strYear > p_yearUpto) 
	{
		lsMessage = 'Year can not be more than: '+p_yearUpto+'.';	
		return lsMessage;		
	}
	if (strYear < p_yearFrom) 
	{
		lsMessage = 'Year can not be earlier than: '+p_yearFrom+'.';
		return lsMessage;		
	}
		
	if (intday < 1 || intday > 31) 
	{
		lsMessage = "This date is invalid.";
		return lsMessage;
	}
	
	if (intMonth>12 || intMonth<1) 
	{
		lsMessage = "This date is invalid.  Please give date in "+format+" format.";
		return lsMessage;
	}
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) 
	{
		lsMessage = "This date is invalid.";
		return lsMessage;
	}
	if (intMonth == 2) 
	{
		if (intday > 28) 
		{
			if (LeapYear(intYear) == true) 
			{
				if (intday > 29) 
				{
					lsMessage = "This date is invalid.";
					return lsMessage;
				}
			}
			else 
			{
				lsMessage = "This date is invalid.";
				return lsMessage;
			}
		}
	}
	// pad o's Prijesh - check for "checkdate"  and add one parameter which is Name of text
	// pad o's
	if(strMonth.length > 2)
	{
		lsMessage = "This date is invalid.";
				return lsMessage;
	}
	if(strDay.length > 2)
	{
		lsMessage = "This date is invalid.";
				return lsMessage;
	}
	if(strMonth.length == 1)
	{
		strMonth = "0" + strMonth;
	}
	if(strDay.length == 1)
	{
		strDay = "0" + strDay;
	}
	retDate = '';
	if(format == 'MM/DD/YYYY'){
		retDate = strMonth+'/'+strDay+'/'+strYear;
	}else if(format == 'MM-DD-YYYY'){
		retDate = strMonth+'-'+strDay+'-'+strYear;
	}else if(format == 'DD/MM/YYYY'){
		retDate = strDay+'/'+strMonth+'/'+strYear;
	}else if(format == 'DD-MM-YYYY'){
		retDate = strDay+'-'+strMonth+'-'+strYear;
	}else if(format == 'YYYY/MM/DD'){
		retDate = strYear+'/'+strMonth+'/'+strDay;
	}else if(format == 'YYYY-MM-DD'){
		retDate = strYear+'-'+strMonth+'-'+strDay;
	}
	setBackDate(fieldName, retDate);
	return '';
}

//Project Code: SSN-ENCRYPTION
function getDigitString(str) 
{ 
    var num = str.replace(/[^0-9]/g, ''); 
    return num; 
}
function isSSNValid2(strField,mask,maxlen)
{
	var lsSsn 	= strField.value;
	lsSsn 		= getDigitString(lsSsn);
	
}
/*
  SSN Validation 
  getDigits()
if(len == 4)
	short
if(len == 9)
	New enetered
others 
	invalid
	
*/	
function isSSNValid(strField,mask,maxlen)
{
	var oLen = strField.value.length; 
	for(j=0;j<oLen;j++)
	{
		if(mask.charAt(j) == '9')
		{
			var Unicodeval = strField.value.charCodeAt(j);
			if(Unicodeval < 48 || Unicodeval > 57)
			{
				return false;
			}
		}else
		{
			if(mask.charAt(j) != '9' && mask.charAt(j) != 'X')
			{
				if(strField.value.charAt(j) != mask.charAt(j))
				{
					return false;
				}
			}
		}
	}
	return true;
}
function setBackDate(fieldName,strDate) 
{
	var agent = navigator.userAgent.toLowerCase();
	if(agent.indexOf('firefox') >= 0 )
		document.getElementsByName(fieldName).value = strDate;
	else
		document.all[fieldName].value = strDate;
	//var doc = document.getElementsByTagName('body')[0].getElementsByTagName('*');
	//doc[0].elements[fieldName].value = strDate;
}
function LeapYear(intYear) 
{
	if (intYear % 100 == 0) 
	{
		if (intYear % 400 == 0) {return true;}
	}
	else 
	{
		if ((intYear % 4) == 0) {return true;}
	} 
	return false;
}
//this is to check the textarea max limit characters allowed to punch into it 
function CheckLength(length)
{
	if(length > 0)
	{
		if (getLengthOfText(window.event.srcElement.value) >= length)
		{
			$(":button:first").focus();	//Added for iPad as sreen was getting freezed
			alert('You have reached the maximum length of characters permitted here.');
			return false;                         
		}
	}
}
function CheckLength2(length)
{
	if(length > 0)
	{
		if (getLengthOfText(window.event.srcElement.value) >= length)
		{
			$(":button:first").focus();	//Added for iPad as sreen was getting freezed
			alert('You have reached the maximum length of '+length+' characters permitted here.');
			return false;                         
		}
	}
}
//this is to check the textarea max limit characters allowed to punch into it 
function CheckLen(field, length)
{
	if(length > 0)
	{
		if (field.value.length >= length)
		{
			alert('2You have reached the maximum length of characters permitted here.');
			return length;
		}
	}
	return field.value.length;
}
//to handle the parseInt function of javascript (to make it base 10 function)
function parseIntBase10(asStr)
{
	return parseInt(asStr,10);
}
function checkifValidChars4Masters(asStr , elnname)
{
	if(asStr.indexOf("%") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('% is not a Valid Character')
		return true;
	}
	if(asStr.indexOf("\"") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('Please give Valid Characters')
		return true;
	}
	if(asStr.indexOf("^") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('^ is not a Valid Character')
		return true;
	}
	if(asStr.indexOf("<") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('< is not a Valid Character')
		return true;
	}
	if(asStr.indexOf(">") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('> is not a Valid Character')
		return true;
	}	
	return false;	
}
function checkifquotes(asStr , elnname)
{
	if(asStr.indexOf("&") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('& is not a Valid Character')
		return true;
	}
	else if(asStr.indexOf("%") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('% is not a Valid Character')
		return true;
	}
	else if(asStr.indexOf("#") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('# is not a Valid Character')
		return true;
	}
	if(asStr.indexOf("\"") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('Please give Valid Characters')
		return true;
	}
	if(asStr.indexOf("^") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('^ is not a Valid Character')
		return true;
	}
	if(asStr.indexOf("<") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('< is not a Valid Character')
		return true;
	}
	if(asStr.indexOf(">") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('> is not a Valid Character')
		return true;
	}
	
	return false;	
}
function checkifquotes2(asStr , elnname)
{
	if(asStr.indexOf("#") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('# is not a Valid Character')
		return true;
	}
	if(asStr.indexOf("^") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('^ is not a Valid Character')
		return true;
	}
	if(asStr.indexOf("<") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('< is not a Valid Character')
		return true;
	}
	if(asStr.indexOf(">") >=0  )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('> is not a Valid Character')
		return true;
	}
	
	return false;	
}
//Skumar PayPros Special Case 25 June 2015
function isSpclChar(asStr , elnname)
{
	var iChars = "!@#$%^&*()+=_[]\\\;/{}|\":<>?";	// SUGAR 234086 - REMOVED hyphen(-) CHAR FROM VALIDATION CHECK, VISHAL 05-FEB-2018 
	for (var i = 0; i < document.all[elnname].value.length; i++) 
	{
		if (iChars.indexOf(document.all[elnname].value.charAt(i)) != -1) 
		{
			document.all[elnname].select();
			document.all[elnname].focus();
			alert ("Special Characters are not allowed.");
			return false;
		}
	}
} 

function chkSpecialChar(asStr , elnname)
{
	var iChars = "#%^<>\"&";
	for (var i = 0; i < document.all[elnname].value.length; i++) 
	{
		if (iChars.indexOf(document.all[elnname].value.charAt(i)) != -1) 
		{
			document.all[elnname].select();
			document.all[elnname].focus();
			alert ("Special Characters(#%^<>\"&) are not allowed.");
			return true;
		}
	}
} 

function chkApptSMSSpecialChar(asStr , elnname)
{
	var iChars = "$^*()+=-[]\\\;/{}|:<>?";
	for (var i = 0; i < document.all[elnname].value.length; i++) 
	{
		if (iChars.indexOf(document.all[elnname].value.charAt(i)) != -1) 
		{
			document.all[elnname].select();
			document.all[elnname].focus();
			return true;
		}
	}
} 											   
function validateSplChar(asStr , elnname)
{
	var iChars = "^%&#<>";
	for (var i = 0; i < document.all[elnname].value.length; i++) 
	{
		if (iChars.indexOf(document.all[elnname].value.charAt(i)) != -1) 
		{
			document.all[elnname].select();
			document.all[elnname].focus();
			alert ("Special Characters are not allowed.");
			return false;
		}
	}
} 
//Skumar invalid decimal Value. 30 July 2015
function isNumericAmt(input)
{
    return (input - 0) == input && (''+input).trim().length > 0;
}
function trim(str) 
{ 
	if(str == null)
		return str;
	str = str.replace(/^\s*/, '').replace(/\s*$/, ''); 
	return str;
} 
function isInt(str)
{
	var i = parseInt (str);
	if (isNaN (i))
		return false;
	i = i . toString ();
	if (i != str)
		return false;
	return true;
}
// both the dates must be in yyyy-mm-dd format only.
//eg getDateDiff("2000-01-22","2000-01-30") => 8
//	* @param asDate1 		String Date1, YYYY-MM-DD  format
//	* @param asDate2 		String Date2, YYYY-MM-DD  format
//	* @return 				if Date1 < Date2 = returns positive no. of days
//	*						if Date1 > Date2 = returns negative no. of days
function compareTwoDates(date1, date2)
{
	var jsdate1 = new Date(date1.substring(0,4), parseInt(date1.substring(5,7), 10)-1 , date1.substring(8,date1.length)); 
	var jsdate2 = new Date(date2.substring(0,4), parseInt(date2.substring(5,7), 10)-1 , date2.substring(8,date2.length)); 
	
	//Set 1 day in milliseconds
	var one_day=1000*60*60*24;
	//Calculate difference btw the two dates, and convert to days
	return Math.ceil((jsdate2.getTime()-jsdate1.getTime())/(one_day));
	
	
}
//To get date in perticular format
function getDateInFormat(date,format)
{
    var yyyy = date.getFullYear().toString();
    	format = format.replace(/yyyy/g, yyyy);
    var mm = (date.getMonth()+1).toString(); 
    	format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
    var dd  = date.getDate().toString();
    	format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
  return format;
}
//function to handle the names (make first letter uppercase and others lower case 
//Condition if it contents special cahaters like "'" or " " (space) or "-" then dont convert
function convert2NameFormat(asStr)
{
	var	lsSpecialChars	= new Array(2);
	lsSpecialChars[0] = " ";
	lsSpecialChars[1] = "'";
	lsSpecialChars[2] = "-";
	if(asStr == null || asStr == '' )
		return '';
	var lsStr = trim(asStr);
	liLen = lsStr.length;
	if(liLen == 0)
		return '';
	for(var i=0;i<lsSpecialChars.length;i++)
	{
		if(lsStr.indexOf(lsSpecialChars[i]) >= 0) 
			return lsStr;
	}
	lsStr = lsStr.toLowerCase();
	var lsFirst	= lsStr.substring(0,1);
	lsFirst	= lsFirst.toUpperCase();
	if(liLen == 1)
		lsStr = lsFirst;
	else
		lsStr = lsFirst + lsStr.substring(1);
	return lsStr;
}
function validateAmount(cntl , left , right , displayText)
{
	str_amount = cntl.value;
	if(!checkNum(cntl))
		return false;
	if(!checkForDecimalInAmount(cntl, left, right, displayText))
		return false;
	if (parseFloat(str_amount) == 0)
	{
		alert("Please Enter Amount.");
		return false;
	}
	else if (str_amount.substr(0,1) == '0' && str_amount.substr(0,2) != '0.')
	{
		alert("Please Enter valid Amount.");
		return false;
	}
	return true;
}
function parseAmt(e) // Krishna : 5-31-2016 Sugar#173041 To allow only Numbers
{
	var chCode = ('charCode' in e) ? e.charCode : e.keyCode;
	if(chCode == 46) // Delete
		return true;
	else if(chCode >= 48 && chCode <= 57)
		return true;
	else
		return false;
}
function formatAmt(lfAmt) // Added By Krishna on 8-2-2016 to Format the Amount 
{
	lsAmt = lfAmt+'';
	if(lsAmt.indexOf('.') > 0)
	{
		if(lsAmt.indexOf('.') == lsAmt.length-2)
			lsAmt = lfAmt+'0';
		else if(lsAmt.length > lsAmt.indexOf('.') + 2)
			lsAmt = lsAmt.substring(0,lsAmt.indexOf('.') + 3);
	}else
	{
		lsAmt = lfAmt+'.00';
	}
	return lsAmt; 
}
function checkNum(newObj)
{
	var flag = true;
	
	var v_value = newObj.value;
	
	if(flag==true)
	{
		for (var i=0;i<v_value.length;i++)
		{
			var v_part = v_value.substring(i,i+1);
			if (v_part == "e" || v_part == "E")
			{
				alert("Please enter numeric values.");
				newObj.focus();
				newObj.select();
				flag =  false;
				break;
			}	
		}
	}
	if(flag==true)
	{
		if (v_value == "" )
		{
			alert("Please enter positive numeric values.");		
			newObj.focus();
			newObj.select();		
			return false ;
		}
		else if( isNaN(v_value) || v_value <= 0 ) 
		{
			alert("Please enter positive numeric values.");
			newObj.focus();
			newObj.select();
			flag =  false;	
		}
	}
	return flag;
}
function checkForDecimalInAmount(newObj , left , right, displayText)
{
	var leftPart;
	var rightPart;
	var idOfDecimal;
	var val = newObj.value;
	var len = val.length;
	if (val.indexOf('.') == -1)
	{
		if (len > parseInt(left))
		{
			alert(displayText+' too large');
			newObj.focus();
			newObj.select();
			
			return false;
		}
		
	}
	else
	{
		idOfDecimal = val.indexOf('.');
		leftPart = val.substring(0,idOfDecimal);
		
		rightPart = val.substring(idOfDecimal+1,val.length);		
		if (leftPart.length > parseInt(left))
		{
			alert(displayText+' too large');
			newObj.focus();
			newObj.select();			
			return false;
		}
		
		if (rightPart.length > parseInt(right))
		{
			alert('Only '+right+' digits after decimal is allowed');
			newObj.focus();
			newObj.select();
			
			return false;
		}
		
	}	
	return true;
}
function isCalcPopupDateValid(format, asDate) 
{ 
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var booFound = false;
	var intElementNr;
	var lsError = "";
	strDate = asDate;
	if(strDate.length != 10)
		return false;
	strDateArray = strDate.split('-');
	if (strDateArray.length != 3) 
	{
		strDateArray = strDate.split('/');
		if (strDateArray.length != 3) 
			return false;
	}
	if(format == 'MM/DD/YYYY' ||	format == 'MM-DD-YYYY')
	{
			strMonth	= strDateArray[0];
			strDay		= strDateArray[1];
			strYear		= strDateArray[2];
	}else if(format == 'DD/MM/YYYY' ||	format == 'DD-MM-YYYY')
	{
			strMonth	= strDateArray[1];
			strDay		= strDateArray[0];
			strYear		= strDateArray[2];
	}else if(format == 'YYYY/MM/DD' ||	format == 'YYYY-MM-DD')
	{
			strMonth	= strDateArray[1];
			strDay		= strDateArray[2];
			strYear		= strDateArray[0];
	}
	intday = parseIntBase10(strDay, 10);
	if (isNaN(intday)) 
		return false;
	intMonth = parseIntBase10(strMonth, 10);
	if (isNaN(intMonth)) 
		return false;
	intYear = parseIntBase10(strYear, 10);
	if (isNaN(intYear)) 
		return false;
	
	var tmpYear = intYear+'';
	if (tmpYear.length != 4) 
		return false;		
	if (intday < 1 || intday > 31) 
		return false;
	
	if (intMonth>12 || intMonth<1) 
		return false;
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) 
		return false;
	if (intMonth == 2) 
	{
		if (intday > 28) 
		{
			if (LeapYear(intYear) == true) 
			{
				if (intday > 29) 
					return false;
			}
			else 
				return false;
		}
	}
	return true;
}
function showExpressionMessage(ExpressionIds)
{	
	/*var paramObject = new Object();
	paramObject.title="Expression";
	newurl = "scrShowExpression.jsp?ExpressionIds="+ExpressionIds;
	//newurl = packWhereParam(newurl); //removed by kedar 
	retVal  = showGlobalModalPopup(newurl, paramObject,  'dialogHeight: 290px; dialogWidth: 440px; dialogTop: 214px; dialogLeft: 360px; edge: raised; center: Yes; help: No; resizable: yes; status: No;', 100, 100, false);
	*/
	// Added by Priyanka for PROG_397
	var paramObject = new Object();
	paramObject.title="Expression";
	newurl = "showExpression.action2?operation=DISPLAY&ExpressionIds="+ExpressionIds;
	
	showGlobalModalPopup(newurl, paramObject,  'dialogHeight: 290px; dialogWidth: 440px; dialogTop: 214px; dialogLeft: 360px; edge: raised; center: Yes; help: No; resizable: yes; status: No;', 100, 100, false);
}
function showExpressionAndGuideLines()
{
	//Event display
	if(document.Form.msExpressionMessage.value != '')
	{
		if(document.Form.msExpressionMessage.value != '')
			showExpressionMessage(document.Form.msExpressionMessage.value);
		document.Form.msExpressionMessage.value = '';
	}
	//Guideline display
	if(document.Form.msIsGuidelinePresent.value != 'NO')
	{
		var windowFeatures = 'width=440px,height=290px,toolbar=0,location=no,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,titlebar=0,visible=0,left=580px,top=10px'
		window_handle = window.open('', '', 'width=1,height=1,toolbar=0,location=no,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,titlebar=0,visible=0,left=1500,top=1000');
		if(this != window_handle)
		{
			window_handle.close();
		}
		window_handle = window.open('scrGuidelinePopUp.jsp', '', windowFeatures);
		document.Form.msIsGuidelinePresent.value = 'NO';
	}
}
function getCursorPos(textEl) 
{
	/*var iCaretPos = 0;

	// IE Support
	if (document.selection && navigator.appVersion.indexOf('MSIE 10') == -1) 
	{ 
		textEl.focus ();
		var oSel = document.selection.createRange();
		var SelLength = oSel.text.length;
		oSel.moveStart ('character', -textEl.value.length);
		iCaretPos = oSel.text.length - SelLength;
	}
	else if (textEl.selectionStart || textEl.selectionStart == '0')
	{
		if(trim(textEl.value) != '' && parseInt(textEl.selectionStart) < 0)
			iCaretPos = textEl.value.length;
		else 
			iCaretPos = textEl.selectionStart;
	}

	return iCaretPos;*/
	//Verified By Shahin/Navin
	//Changes done by Priya on 10-Aug-15
	//Changes done to place phrase at correct location
	
	var pos = 0;
	if("selectionStart" in textEl) {
		if(trim(textEl.value) != '' && parseInt(textEl.selectionStart) < 0)
			pos = textEl.value.length;
		else 
			pos = textEl.selectionStart;
	} else if("selection" in document) {
		textEl.focus();
	   var Sel = document.selection.createRange();
	   var SelLength = document.selection.createRange().text.length;
	   Sel.moveStart("character", -textEl.value.length);
	   pos = Sel.text.length - SelLength;
	}
	
	return pos;
}
 
function insertAtCursorPos(textEl, nameList,newline) 
{ 
   var newLineChar = ' ';
   if(newline=="Y")
   {
		newLineChar = '\n';
   }
   var caretPos = getCursorPos(textEl);
   var substringFromStart = '';
   var substringAfterNewPhrase = '';
   if(parseInt(caretPos) >= 0)
   {
	   if(parseInt(caretPos) != 0)
		   substringFromStart = textEl.value.substring(0, caretPos);
	   substringAfterNewPhrase = textEl.value.substring(caretPos);
   }
   var finalValue	= '';
   var substringForNewPhrase = nameList[0];
   for(i=1; i<(nameList.length-1);i++)
	   substringForNewPhrase = substringForNewPhrase + ' ' + newLineChar + nameList[i];
   if(substringFromStart == '' && substringAfterNewPhrase == '')
	   finalValue = substringForNewPhrase;
	   //textEl.value = substringForNewPhrase;
   else if(substringFromStart == '' && substringAfterNewPhrase != '')
	   finalValue = substringForNewPhrase + ' ' + newLineChar + substringAfterNewPhrase;
	   //textEl.value = substringForNewPhrase + ' ' + newLineChar + substringAfterNewPhrase;
   else if(substringFromStart != '' && substringAfterNewPhrase == '')
	   finalValue = substringFromStart + ' ' + newLineChar + substringForNewPhrase;
	   //textEl.value = substringFromStart + ' ' + newLineChar + substringForNewPhrase;
   else
	   finalValue = substringFromStart + ' ' + newLineChar + substringForNewPhrase + ' ' + newLineChar + substringAfterNewPhrase; 
	   //textEl.value = substringFromStart + ' ' + newLineChar + substringForNewPhrase + ' ' + newLineChar + substringAfterNewPhrase; 
	   /*if(substringAfterNewPhrase == '')
		   textEl.value = substringFromStart + ' ' + newLineChar + substringForNewPhrase;
	   else
		   textEl.value = substringFromStart + ' ' + newLineChar + substringForNewPhrase + ' ' + newLineChar + substringAfterNewPhrase;*/
	
	//$(textEl).val($(textEl).html(finalValue).text());		//This is the correct syntax. But it will fail if JQuery file is not included on the JSP. As such written below javaScript equivalent code
	var dummyTextArea 		= document.createElement("textarea");
	dummyTextArea.innerHTML	= finalValue;
	textEl.value 			= dummyTextArea.innerText; 
}

function nextWorkFlowEvent()
{
	//parent.calcFrame.location.href = cleanAndEncodeURL("scrCalc.jsp?type=38&direction=1");
	var calcURL = "scrCalcAjaxCalls.jsp";
	var urlParams = "type=38&direction=1";
	xHttp=GetXmlHttpObject(calcCallback);
	xHttp.open("POST", calcURL , true);
	xHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xHttp.send(urlParams);
}
function prevWorkFlowEvent()
{
	//parent.calcFrame.location.href = cleanAndEncodeURL("scrCalc.jsp?type=38&direction=-1");
	var calcURL = "scrCalcAjaxCalls.jsp";
	var urlParams = "type=38&direction=-1";
	xHttp=GetXmlHttpObject(calcCallback);
	xHttp.open("POST", calcURL , true);
	xHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xHttp.send(urlParams);
}
function changeClassOfCheckbox(componentname)
{
	if(document.all[componentname].className == 'checkboxbut checkboxbutnor')
		document.all[componentname].className = 'checkboxbut checkboxbutdel';
	else 
		document.all[componentname].className = 'checkboxbut checkboxbutnor';
	valueChanged();
}
function changeClassOfCheckboxUpdateFlag(componentname,updateflag)
{
	if(document.all[componentname].className == 'checkboxbut checkboxbutnor')
	{
		document.all[componentname].className = 'checkboxbut checkboxbutdel';
		document.all[updateflag].value		  = true;		
	}	
	else 
	{
		document.all[componentname].className = 'checkboxbut checkboxbutnor';
		document.all[updateflag].value		  = false;
	}
	valueChanged();
}
//Required for AJAX
function GetXmlHttpObject(handler)
{ 
	//alert('GetXmlHttpObject');
	var objXmlHttp=null;
	if (navigator.userAgent.indexOf("Opera")>=0)
	{
		alert("This example doesn't work in Opera") ;
		return ;
	}
	if (navigator.userAgent.indexOf("MSIE")>=0)
	{ 
		var strName="Msxml2.XMLHTTP";
		if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
		{
			strName="Microsoft.XMLHTTP";
		} 
		try
		{ 
			objXmlHttp=new ActiveXObject(strName);
			objXmlHttp.onreadystatechange=handler ;
			return objXmlHttp;
		} 
		catch(e)
		{ 
			alert("Error. Scripting for ActiveX might be disabled") 
			return 
		} 
	} 
	if (navigator.userAgent.indexOf("Mozilla")>=0)
	{
		objXmlHttp=new XMLHttpRequest();
		objXmlHttp.onload=handler;
		objXmlHttp.onerror=handler ;
		return objXmlHttp;
	}
} 
function printDirect(url)
{
	// Added by Manoj S. on 17 DEC 2019 - Capture the object of opened window which is used in proCheckIn to ensure that ALL opened window must be closed.
	var lsPrintWinObj = '';
	var lsUrl = url.trim();
	lsUrl 	  = encodeURI(lsUrl);
	if(navigator.userAgent.indexOf("Chrome") > 0)
		lsPrintWinObj = window.open(lsUrl,'',"width=780,height=650,toolbar=no,location=no,menubar=yes,resizable=yes,scrollbars=yes,left = 50 , top =0");
	else
		lsPrintWinObj = window.open(lsUrl,'',"width=0,height=0,toolbar=no,location=no,menubar=yes,resizable=yes,scrollbars=yes,left = 2000 , top =2000");
	if(window.top.openedWinObj != null && window.top.openedWinObj != '')
		window.top.openedWinObj.printForm = lsPrintWinObj;
}
function debugAlert(asMsg)
{
	alert(asMsg);
}
function debugMsg(asMsg)
{
	console.log('%c '+asMsg+'', 'background: cyan;olor: black; display: block;');
}
function debugMsg1(asMsg)
{
	console.log('%c '+asMsg+'', 'background: green; color: white; display: block;');
}
function debugMsg2(asMsg)
{
	console.log('%c '+asMsg+'', 'background: blue; color: white; display: block;');
}
function debugMsg3(asMsg)
{
	console.log('%c '+asMsg+'', 'background: orange; color: white; display: block;');
}
function debugError(asMsg)
{
	console.log('%c '+asMsg+'', 'background: red; color: white; display: block;');
}
function verifyIP (IPvalue)
{
	errorString = "";
	theName = "IP address";
	//var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
	var ipPattern = /^(\d{1,3}\.){3}\d{1,3}(\/(\d{1,2}))?$/; // To suppport CIDR notation Ip Address
	var ipArray = IPvalue.match(ipPattern);
	if (IPvalue == "0.0.0.0")
		errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
	else if (IPvalue == "255.255.255.255")
		errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
	if (ipArray == null)
		errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';
	else 
	{
		for (i = 0; i < 4; i++)
		{
			thisSegment = ipArray[i];
			if (thisSegment > 255) 
			{
				errorString = errorString + theName + ': '+IPvalue+' is not a valid IP address.';
				i = 4;
			}
			if ((i == 0) && (thisSegment > 255)) 
			{
				errorString = errorString + theName + ': '+IPvalue+' is a special IP address and cannot be used here.';
				i = 4;
			}
	   }
	}
	extensionLength = 3;
	return errorString;
}
/******Sameer
 * Set an HTML Select Element to Read-only 
 * 	<select id="mySelect">
		<option value="1">Option 1</option>
		<option value="2" selected>Option 2</option>
	</select>
	 Usage: makeSelectReadonly(document.Form.mySelect);
	 Changes Done in scrOrderSet.jsp
 * ****/
function makeSelectReadonly( selectElementId )
{
	var selectElement = selectElementId;
	if (selectElement){		
		var parent = selectElement.parentElement;
		var textValue = selectElement.options[selectElement.options.selectedIndex].innerText;
		if (!parent){
			parent=selectElement.parentNode;
			textValue = selectElement.options[selectElement.options.selectedIndex].text;
		}
		var input = document.createElement("input");
		input.setAttribute("id",selectElement.id);
		input.setAttribute("type","text");
		input.setAttribute("value",textValue);
		input.style.background="#cccccc";
		input.readOnly = true;
		parent.appendChild(input);
	}
	selectElement.style.display="none";
}
/** Sameer Parab  
 * 	findDuplicateValuesInArray(array) here arr is array Object
 * 		if more than 1 duplicate Record found in array then comma sep. string return.
 * 		if no duplicate record found in array then empty string is return.
 * Changes Done in editCharge.js File    
 * */
function findDuplicateValuesInArray(array)
{
	var sorted_arr = array.sort(); 
	var results = [];
	for (var i = 0; i < array.length - 1; i += 1) 
	{
	    if (sorted_arr[i + 1] == sorted_arr[i]) 
	            results.push(sorted_arr[i]);
	}
	return results;
}
/** Sameer Parab.
 * On OnLoad event Set Database value to Select Control.Here Option 3 and 4 is selected.  
   <select id="mySelect" multiple="multiple" >
		<option value="OP1">Option 1</option>
		<option value="OP2">Option 2</option>
		<option value="OP3">Option 3</option>
		<option value="OP4">Option 4</option>
	</select>
	
 *	 Usage: setValueInSelectTag(document.Form.mySelect,OP3,PO4);
 *	 Changes Done in scrAssignedPaperFormFlag.jsp
 * ****/
function setValueInSelectTag(selectElementId, Value) 
{
	// Sumit S. 13 NOV 2018
	if(selectElementId == undefined || selectElementId == null || selectElementId == "undefined" )
	{
		return;
	}
	var SelectObject 	= selectElementId;
	var valueArray 		= Value.split(',');
	var valueArrLen		= valueArray.length;
	if(valueArrLen == 1)
  	{
  		Value = valueArray.toString(); 
		for(index = 0; index < SelectObject.length; index++) 
	  	{
			if(SelectObject[index].value == Value)
		    	SelectObject.selectedIndex = index;
	   	}
  	}	
  	else if(valueArrLen >= 2)
  	{
  		for(i = 0 ; i < valueArrLen; i++)
		{
	  		Value = valueArray[i]; 
	  		for(index = 0; index < SelectObject.length; index++) 
		  	{
				if(SelectObject[index].value == Value)
			    	SelectObject.options[index].selected= true;
				
		   	}
		}
  	}
}
/** Sameer Parab.
 * On SaveClick() get Selected Values ( comma sperated if 2 or more options are selected).  
   <select id="mySelect" multiple="multiple" >
		<option value="OP1">Option 1</option>
		<option value="OP2">Option 2</option>
		<option value="OP3">Option 3</option>
		<option value="OP4">Option 4</option>
	</select>
	
 *	 Usage: getMultipleSelectedValues(document.Form.mySelect,OP3);
 *	 Changes Done in scrAssignedPaperFormFlag.jsp
 * ****/
function  getMultipleSelectedValues(selectElementId)
{
	var retValue  	= '';
	var list 		= selectElementId;
	var selected 	= new Array(); 
	for (i = 0; i < list.options.length; i++) 
	{
		if (list.options[i].selected) 
			selected.push(list.options[i].value);
	}
	if(selected.length >= 2)
		retValue = selected;
	else
		retValue = selected.toString();			
	return retValue;
}
function getWindowHeight() 
{
	  var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) 
	  {
	    //Non-IE
	    myHeight = window.innerHeight;
	  }
	  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) 
	  {
	    //IE 6+ in 'standards compliant mode'
	    myHeight = document.documentElement.clientHeight;
	  } 
	  else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) 
	  {
	    //IE 4 compatible
	    myHeight = document.body.clientHeight;
	  }
	return myHeight;
}
/********* Chetan
*  	validates the textbox allow only A-Z, a-z and 0-9 to enter
*  	usage of function : just call the function on the keypress event of textbox which
   	you want to validate.
*	ex:  onkeypress="return alphaNumericWithoutSplChar(event,document.Form.msAdd_Bool_Non_USA.checked);"
*********/
function alphaNumericWithoutSplChar(e,abValidate)
{
	if(abValidate) // For Non US 
	{  	
		if(window.event) // IE
		{
			keyEntry = e.keyCode
		}
		else if(e.which) // Netscape/Firefox/Opera
		{	
			keyEntry = e.which
		}
		
		//65-90 (A-Z)
		//97-122 (a-z)
		//48-57 (0-9)
		//8 => Backspace, 32 => Spacebar, 39 => Single Quote, 127 => delete key
		if( (keyEntry >=65 && keyEntry <=90) || 
			(keyEntry >=97 && keyEntry <=122) || 
			(keyEntry >= 48 && keyEntry <= 57) || 
			keyEntry == 8 || 
			keyEntry == 32 ||
			keyEntry == 39 ||
			keyEntry == 127
		  ) 
		{
			return true;
		}
	  	else
	  	{
	  		alert("Special Characters are not allowed.");
			return false;
	  	}
	}
}
//Since earlier method was excluding single quote so introduced this method for including the same.
//Changes done by Akshay K and verified by Sangram Gughe on 09th Jan 2024
function alphaNumericWithoutSplCharNSingleQuote(e,abValidate)
{
	if(abValidate) // For Non US 
	{  	
		if(window.event) // IE
		{
			keyEntry = e.keyCode
		}
		else if(e.which) // Netscape/Firefox/Opera
		{	
			keyEntry = e.which
		}
		
		//65-90 (A-Z)
		//97-122 (a-z)
		//48-57 (0-9)
		//8 => Backspace, 32 => Spacebar, 127 => delete key
		if( (keyEntry >=65 && keyEntry <=90) || 
			(keyEntry >=97 && keyEntry <=122) || 
			(keyEntry >= 48 && keyEntry <= 57) || 
			keyEntry == 8 || 
			keyEntry == 32 ||
			keyEntry == 127
		  ) 
		{
			return true;
		}
	  	else
	  	{
	  		alert("Special Characters are not allowed.");
			return false;
	  	}
	}
}

/********* Chetan
*  	validates the textbox allow only A-Z, a-z , 0-9 and ',' to enter.no spaces allowed
*  	usage of function : just call the function on the keypress event of textbox which
   	you want to validate.
*	ex:  onkeypress="return onlyAlphaNumericWithComma(event);"
*********/
function onlyAlphabetsChars(event)
{
	if(window.event) // IE
	{
		keyEntry = event.keyCode
	}
	else if(event.which) // Netscape/Firefox/Opera
	{	
		keyEntry = event.which
	}
	
	//65-90 (A-Z)
	//97-122 (a-z)
	//8 (Backspace)
	//127 (delete key)	
	if( (keyEntry >=65 && keyEntry <=90) || 
		(keyEntry >=97 && keyEntry <=122) || 
		keyEntry == 8 	|| 
		keyEntry == 127 
	  ) 
	{
		return true;
	}
  	else if(keyEntry >= 48 && keyEntry <= 57) 
  	{
  		alert("Enter alphabets among A to L.");
		return false;
  	}
	else
	{
		alert("Special characters are not allowed.");
		return false;
	}
}
function onlyAlphaNumericWithComma(event)
{
	if(window.event) // IE
	{
		keyEntry = event.keyCode
	}
	else if(event.which) // Netscape/Firefox/Opera
	{	
		keyEntry = event.which
	}
	
	//65-90 (A-Z)
	//97-122 (a-z)
	//48-57 (0-9)
	//8 (Backspace)
	//127 (delete key)	
	//44 (comma)
	//32 (Space)	
	//46 (Period)
	if( (keyEntry >=65 && keyEntry <=90) || 
			(keyEntry >=97 && keyEntry <=122) || 
			(keyEntry >= 48 && keyEntry <= 57) || 
			keyEntry == 8 	|| 
			keyEntry == 44	||
			keyEntry == 127 ||
			keyEntry == 32  ||
			keyEntry == 46
	) 
	{
		return true;
	}
	else
	{
		alert("special characters are not allowed.");
		return false;
	}
}
function onlyAlphaNumeric(event)
{
	if(window.event) // IE
	{
		keyEntry = event.keyCode
	}
	else if(event.which) // Netscape/Firefox/Opera
	{	
		keyEntry = event.which
	}
	
	//65-90 (A-Z)
	//97-122 (a-z)
	//48-57 (0-9)
	//8 (Backspace)
	//127 (delete key)	
	//32 (Space)	
	if( (keyEntry >=65 && keyEntry <=90) || 
			(keyEntry >=97 && keyEntry <=122) || 
			(keyEntry >= 48 && keyEntry <= 57) || 
			keyEntry == 8 	|| 
			keyEntry == 127 ||
			keyEntry == 32  
	) 
	{
		return true;
	}
	else
	{
		alert("special characters are not allowed.");
		return false;
	}
}

function onlyAlphaNumericWrapper(event){
	let keyEntry;
	if(window.event) // IE
	{
		keyEntry = event.keyCode
	}
	else if(event.which) // Netscape/Firefox/Opera
	{	
		keyEntry = event.which
	}
	//13   Enter
	if(keyEntry == 13){
		return true;
	}else{
		//$(this).focus();
		return onlyAlphaNumeric(event);
	}  
}

function onlyAlphaNumericWithCommaDollar(event)
{
	if(window.event) // IE
	{
		keyEntry = event.keyCode
	}
	else if(event.which) // Netscape/Firefox/Opera
	{	
		keyEntry = event.which
	}
	
	//65-90 (A-Z)
	//97-122 (a-z)
	//48-57 (0-9)
	//8 (Backspace)
	//127 (delete key)	
	//44 (comma)
	//32 (Space)	
	//36 ($)	
	//46 (Period)
	if( (keyEntry >=65 && keyEntry <=90) || 
			(keyEntry >=97 && keyEntry <=122) || 
			(keyEntry >= 48 && keyEntry <= 57) || 
			keyEntry == 8 	|| 
			keyEntry == 44	||
			keyEntry == 127 ||
			keyEntry == 32  ||
			keyEntry == 36  ||
			keyEntry == 46
	) 
	{
		return true;
	}
	else
	{
		alert("special characters are not allowed");
		return false;
	}
}
/********* Sameer P
 *  	validates the textbox allow only 0-9 and ',' to enter.no spaces allowed
 *  	usage of function : just call the function on the keypress event of textbox which you want to validate.
 *	ex:  onkeypress="return onlyNumericWithComma(event);"
 *********/
function onlyNumericWithComma(event)
{
	if(window.event) // IE
	{
		keyEntry = event.keyCode
	}
	else if(event.which) // Netscape/Firefox/Opera
	{	
		keyEntry = event.which
	}
	
	//48-57 (0-9)
	//8 (Backspace)
	//44 (comma)
	//127 (delete key)	
	if( (keyEntry >= 48 && keyEntry <= 57) || 
		 keyEntry == 8 	|| 
		 keyEntry == 44	||
		 keyEntry == 127 
	  ) 
	{
		return true;
	}
	else
	{
		alert("special characters are not allowed.");
		return false;
	}
}
function onlyNumericWithDot(event)
{
	if(window.event) // IE
	{
		keyEntry = event.keyCode
	}
	else if(event.which) // Netscape/Firefox/Opera
	{	
		keyEntry = event.which
	}
	
	//48-57 (0-9)
	//8 (Backspace)
	//44 (comma)
	//127 (delete key)	
	if( (keyEntry >= 48 && keyEntry <= 57) || 
		 keyEntry == 8 	|| 
		 keyEntry == 46	||
		 keyEntry == 127 
	  ) 
	{
		return true;
	}
	else
	{
		alert("Alphabets and special characters are not allowed.");
		return false;
	}
}
function onlyNumeric(event)
{
	if(window.event) // IE
	{
		keyEntry = event.keyCode
	}
	else if(event.which) // Netscape/Firefox/Opera
	{	
		keyEntry = event.which
	}
	//48-57 (0-9),	8 (Backspace),	127 (delete key)	
	if( (keyEntry >= 48 && keyEntry <= 57) || 
		 keyEntry == 8 	|| keyEntry == 127 ) 
	{
		return true;
	}
	else
	{
		alert("Alphabets and special characters are not allowed.");
		return false;
	}
}
/** Sameer Parab.
 * getWindowSize() : this Method is req. For Jquery. 
 *  Changes Done in scrClaimsCenter.jsp
 * ****/
function getWindowSize() 
{
	  var myWidth = 0, myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) 
	  {
	    //Non-IE
	    myWidth = window.innerWidth;
	    myHeight = window.innerHeight;
	  }
	  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) 
	  {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	    myHeight = document.documentElement.clientHeight;
	  } 
	  else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) 
	  {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	    myHeight = document.body.clientHeight;
	  }
	return myWidth - 100;
}

/********* Chetan

*  	validates the textbox not allowed '|', '*', ':', '~' to enter 
	specifically required for address when it is sent using EDI this characters are not allowed
*  	usage of function : just call the function on the keypress event of textbox which
   	you want to validate.

*	ex:  onkeypress="return validateAddressFields(event);"

*********/
function validateAddressFields(event)
{
	if(window.event) // IE
	{
		keyEntry = event.keyCode
	}
	else if(event.which) // Netscape/Firefox/Opera
	{	
		keyEntry = event.which
	}
	
	//65-90 (A-Z)
	//97-122 (a-z)
	//48-57 (0-9)
	//8 (Backspace)
	//127 (delete key)	
	//32 (Space)	
	//35 (#)
	//44 (comma)
	//45 (-)
	//46 (Period)
	//47 (/)
	
	if( (keyEntry >=65 && keyEntry <=90) || 
		(keyEntry >=97 && keyEntry <=122) || 
		(keyEntry >= 44 && keyEntry <= 57) || 
		keyEntry == 8 	|| 
		keyEntry == 127 ||
		keyEntry == 32  ||
		keyEntry == 35	||
		keyEntry == 46
	  ) 
	{
		return true;
	}
  	else
  	{
  		alert("special characters are not allowed.");
		return false;
  	}
}

//******  15 Jan 2018 Aditi  MISC_NPI_URL  *******//


function forcontrol(NPI_Value)
{
	var NPI_Value1=document.getElementById(NPI_Value).value;
	
	if(NPI_Value1.length < 1)
	{
		alert("Please Enter NPI");
	}
	else if(/-/.test(NPI_Value1) == true)
	 {
		alert("Invalid NPI:- Alphabets and special characters are not allowed / NPI Starting with zero.");
		
	 }
	else if(isInt(NPI_Value1) == false)
	{
		alert("Invalid NPI:- Alphabets and special characters are not allowed / NPI Starting with zero.");
		
	}

	else
	{
	if(NPI_Value1.length < 1)
	{
		alert("Please Enter NPI");
	}

else if(NPI_Value1.length < 10)
	{
	alert("NPI must be 10 digit");
	}
else
	{
	checkNPI(NPI_Value1);
	}
	}
	
	
	
}

function checkNPI(asNpiStr)
{
	var url	= "scrNPIRegistryResult.jsp?npinumber="+asNpiStr;
	url		= packWhereParam2(url)
	var paramObject = new Object();
	paramObject.title = "NPI Lookup";

	var newurl 		= "scrPopUpFrame.jsp?mainurl="+url;
	retObject 		= showGlobalModalPopup("scrModal.jsp?url="+newurl, paramObject, 'dialogHeight: 600px; dialogWidth: 1000px; PopUpTop: 40px; edge: raised; center: Yes; help: No; resizable: No; scroll: Auto; status: No;', 100, 100);
}
/********* Chetan

*  	validates the textbox not allowed '|', '*', ':', '~' to enter 
	specifically required for address when it is sent using EDI this characters are not allowed
*  	usage of function : just call the function on the keypress event of textbox which
   	you want to validate.

*	ex:  if(!validateString4SplChar(document.Form.msPtAdd_line1))"

*********/
function validateString4SplChar(objTxt)
{
	alphatest = /^[a-zA-Z0-9/. ,_#-]{1,}$/;
	var sValue = objTxt.value;
	if(alphatest.test(sValue))
		return true;
	else
		return false;
}

/** Sameer Parab.
 * isPresentInCommaSeperatedList() : 
 * 	findWhat = Single Word 
 *  findIn   = comma separated List
 *  Changes Done in era.js
 * ****/
function isPresentInCommaSeperatedList(findWhat,findIn)
{
	//findIn = squeezeCommas(findIn); // Girish [30 Nov 2012]
	var lsFindIn	= ','+findIn+',';
	var lsFindWhat	= ','+findWhat+',';
	if(lsFindIn.indexOf(lsFindWhat) >= 0)
		return true;
	else
		return false;
}
function createCookie(name,value,days)
{ 
	var expires = "";
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	
	document.cookie = name+"="+value+expires+"; path=/";
}
	

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return 'null';
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}
/******Sameer
 * get Index From Element Name 
	 How To Use This Function : 
	 	var index = getIndexFromElementName(obj.name);
	 Changes Done in era.js
 * ****/
function getIndexFromElementName(objName)
{
	var from 	= objName.indexOf("[");
	var index 	= objName.substring(from+1,objName.indexOf("]"));
	return index; 
}
/******
 * get File Extn  
	 How To Use This Function : 
	 	var fileExtn = getFileExtension(fileName);
	 	var fileExtn = getFileExtension(fileNameWithPath);
	 Changes Done in scrBillingPatientMIS.jsp
 * ****/
function getFileExtension(fileName)
{
	var fileExtn = fileName.substr(fileName.lastIndexOf('.') + 1);	
	return fileExtn; 
}

/*
	asTargetText = target textbox where date is set
	asTargetButton = target button to invoke calender
	asLowerLimit = lower year range
	asUpperLimit = upper year range
	dateFormat = date format in which date will be displayed in asTargetText
	posX = relative X coordinate from asTargetText
	posY = relative Y coordinate from asTargetText
	callBack = callback is used to call back function after selection or closing the calender
*/
function getCalendar(asTargetText, asTargetButton, asLowerLimit, asUpperLimit, dateFormat, posX, posY, callBackFunction,showMiniCal,onlyDate)
{
	if(showMiniCal == null)
		showMiniCal = false;

	if(posX == null)
		posX = 0;
	if(posY == null)
		posY = 0;
	// Added by Ashwini verified by Shahin on 17-06-22 to allow Char in Since when, ref case- 393660
	if(onlyDate == null)
		onlyDate	= true;
	if(gsDispDateFormatForCalendar != 'undefined')
		dateFormat = gsDispDateFormatForCalendar;
	
	//debugAlert("dateFormat " +dateFormat)
			
	var lsCurrentDate	= new Date();
	var lsCurrentYear	= lsCurrentDate.getFullYear();
	if (asUpperLimit == 0) 
		asUpperLimit = 0;
	else if (asLowerLimit == 0) 
		asLowerLimit = 0;
	else 
	{
		if(asLowerLimit == null || asLowerLimit == '')
			asLowerLimit = '20';
		if(asUpperLimit == null || asUpperLimit == '')
			asUpperLimit = '20';	
	}
	var lsLowerLimit	= parseInt(lsCurrentYear) - parseInt(asLowerLimit);
	var lsUpperLimit	= parseInt(lsCurrentYear) + parseInt(asUpperLimit);
		
	var iElement = document.getElementById(asTargetText);
	
	var gsFormat = "mm-dd-yy";
	if(dateFormat == '%d-%m-%Y')
		gsFormat = "dd-mm-yy";
	
	
	$('#'+asTargetText).datepicker({
	      showOn: 'button',
	      dateFormat: gsFormat,
	      changeMonth: true,
	      changeYear: true,
	      yearRange: lsLowerLimit+":"+lsUpperLimit ,
	      onSelect : callBackFunction,
	     // Added by Ashwini verified by Shahin on 17-06-22 to allow Char in Since when, ref case- 393660
	      constrainInput: onlyDate,
	      beforeShow: function(input, inst) {
	      if(showMiniCal)
	    	  $('#ui-datepicker-div').css('font-size','9px');
	      else
	    	  $('#ui-datepicker-div').css('font-size','12px');
	     
	      inst.dpDiv.css({
	          // marginTop: parseInt(input.offsetHeight+posY)+'px',
	          // marginLeft: parseInt(input.offsetWidth+posX)+'px'
	    	  marginTop: posY+'px',
	          marginLeft: posX+'px'
	      });
	   }
	});
	$('.ui-datepicker-trigger').hide();
	$('#'+asTargetButton).on('click', function(){
		if($('#'+asTargetButton).attr('class') != 'calbut calbutdis')
		{
		    $('#'+asTargetText).datepicker('show');
		}
	});
	
	/*
	var lsCurrentDate	= new Date();
	var lsCurrentYear	= lsCurrentDate.getFullYear();
	if (asUpperLimit == 0) 
		asUpperLimit = 0;
	else if (asLowerLimit == 0) 
		asLowerLimit = 0;
	else 
	{
		if(asLowerLimit == null || asLowerLimit == '')
			asLowerLimit = '20';
		if(asUpperLimit == null || asUpperLimit == '')
			asUpperLimit = '20';	
	}
	var lsLowerLimit	= parseInt(lsCurrentYear) - parseInt(asLowerLimit);
	var lsUpperLimit	= parseInt(lsCurrentYear) + parseInt(asUpperLimit);
	
	var iElement = document.getElementById(asTargetText);
	if(iElement != null){
		var gRef = JsDatePick.getCalInstanceById(iElement.getAttribute("globalNumber"));
		//Check if gRef is null then create calender
	if(gRef == null){
		if(document.getElementById(asTargetText) != null)
		{
			//debugAlert("asTargetText --" +asTargetText);
			new JsDatePick({useMode:2,target:asTargetText,targetbutton:asTargetButton,dateFormat:dateFormat,cellColorScheme:"aqua",yearsRange:[lsLowerLimit,lsUpperLimit],weekStartDay:0,forceX:posX,forceY:posY,callBack:callBackFunction});
		}
	  }
	}		
	*/
}


function getDOBCalendar(asTargetText, asTargetButton, asLowerLimit, asUpperLimit, dateFormat, posX, posY, callBackFunction,showMiniCal,asDOBValidYear)
{
	
	if(showMiniCal == null)
		showMiniCal = false;

	if(posX == null)
		posX = 0;
	if(posY == null)
		posY = 0;

	var gsFormat = "mm-dd-yy";
	if(dateFormat == '%d-%m-%Y')
		gsFormat = "dd-mm-yy";
		
	$('#'+asTargetText).datepicker({
	      showOn: 'button',
	      dateFormat: gsFormat,
	      changeMonth: true,
	      changeYear: true,
	      maxDate: '-'+asDOBValidYear+'Y',
	      yearRange: asLowerLimit+":"+asUpperLimit ,
	      onSelect : callBackFunction,
	      beforeShow: function(input, inst) {
	      if(showMiniCal)
	    	  $('#ui-datepicker-div').css('font-size','9px');
	      else
	    	  $('#ui-datepicker-div').css('font-size','12px');
	      inst.dpDiv.css({
	    	  marginTop: posY+'px',
	          marginLeft: posX+'px'
	      });
	   }
	});
	$('.ui-datepicker-trigger').hide();
	$('#'+asTargetButton).on('click', function(){
		$('#'+asTargetText).datepicker('show');
	});
}

function closeCalender(asTargetText)
{
	var iElement = document.getElementById(asTargetText);
	var gRef = JsDatePick.getCalInstanceById(iElement.getAttribute("globalNumber"));
	gRef.setTooltipText('');
	gRef.setC(this, "jsDatePickCloseButton");
	gRef.closeCalendar();
}
function nameAccordingTo5010(event)
{
	if(window.event) // IE
	{
		keyEntry = event.keyCode
	}
	else if(event.which) // Netscape/Firefox/Opera
	{	
		keyEntry = event.which
	}
	
	//65-90 (A-Z)
	//97-122 (a-z)
	//48-57 (0-9)
	//8 (Backspace)
	//127 (delete key)	
	//32 (Space)	
	//39 (')	
	if( (keyEntry >=65 && keyEntry <=90) || 
		(keyEntry >=97 && keyEntry <=122) || 
		(keyEntry >= 48 && keyEntry <= 57) || 
		keyEntry == 8 || keyEntry == 127 || 
		keyEntry == 32 || keyEntry == 39) 
	{
		return true;
	}
  	else
  	{
  		alert("special characters are not allowed.");
		return false;
  	}
}
function medicsValidateName(event)
{
	if(window.event) // IE
	{
		keyEntry = event.keyCode
	}
	else if(event.which) // Netscape/Firefox/Opera
	{	
		keyEntry = event.which
	}
	
	//65-90 (A-Z)
	//97-122 (a-z)
	//48-57 (0-9)
	//8 (Backspace)
	//127 (delete key)	
	//32 (Space)	
	//39 (')	
	if( (keyEntry >=65 && keyEntry <=90) || 
		(keyEntry >=97 && keyEntry <=122) || 
		(keyEntry >= 48 && keyEntry <= 57) || 
		keyEntry == 8 || keyEntry == 127 || 
		keyEntry == 32 || keyEntry == 45 || keyEntry == 39) 
	{
		return true;
	}
  	else
  	{
  		alert("special characters are not allowed.");
		return false;
  	}
}

function validateExtId(event)
{
	//Verified By Shahin
	//Changes done by Priya on 20-Jan-16
	//Changes done to not allow single quote.
	if(window.event) // IE
	{
		keyEntry = event.keyCode
	}
	else if(event.which) // Netscape/Firefox/Opera
	{	
		keyEntry = event.which
	}
		
	//34 ("")	
	//39 (')	
	if( keyEntry == 34 || keyEntry == 39) 
	{
		alert("special characters are not allowed.");
		return false;
	}
  	else
  	{
  		return true;
  	}
}

function connectCH(lsEdiUrl,lsEdiUserId,lsEdiPswd,lsEdiKeyword)
{
	var lsUrl = 'scrShowClearingHouseSite.jsp?ediurl='+lsEdiUrl+
				'&ediuserid='+packWhereParam2(lsEdiUserId)+
				'&edipswd='+packWhereParam2(lsEdiPswd)+
				'&edikeyword='+packWhereParam2(lsEdiKeyword);
	window.open(lsUrl,'Test','height=695,width=1015,left=0,top=0,menubar=no,status=yes,toolbar=no,scrollbars=yes,location=no,directories=no,resizable=yes');
	
}

//Added by Renuka for Waystar CH-sugar 316876-13 Aug 2020-Reviewed by Sameer Sir 
function connectWSCH(lsEdiUrl) 
{
	var lsUrl = 'scrShowClearingHouseSite.jsp?ediurl='+lsEdiUrl;
	window.open(lsUrl,'Test','height=695,width=1015,left=0,top=0,menubar=no,status=yes,toolbar=no,scrollbars=yes,location=no,directories=no,resizable=yes');

}

function getPortalTableWidth()
{
	var screenWidth		= screenW;
	var subMenuWidth	= (screenWidth*28)/100;
	var tableWidth		= parseInt(screenWidth - subMenuWidth);
	if(navigator.userAgent.indexOf("iPad") > 0)
		tableWidth		= tableWidth - 43;
	 if(navigator.userAgent.indexOf("Android") > 0 )
	 	tableWidth		= tableWidth - 230;
	return tableWidth;
}

function getPortalTableHeight()
{
	var screenHeight		= screenH;
	var menuContenerHeight	= parseInt(screenHeight) - 350;
	if(isIE == false)
		menuContenerHeight	= parseInt(menuContenerHeight) + 40;
	var tableHeight			= parseInt(menuContenerHeight) - 40;
	return tableHeight;
}

function getNormalFixedHeaderTableHeight()
{
	var windowHeight	= $(window).height();
	var buttonHeigth	= '35';
	var tableHeight		= parseInt(windowHeight)-parseInt(buttonHeigth);
	return tableHeight;
}

function getResolutionProportionalHeight(arg)
{
	var windowHeight		= $(window).height();
	var proportionalHeight	= (arg*windowHeight)/768;
	return proportionalHeight;
}

function getResolutionProportionalWidth(arg)
{
	var screenWidth			= screen.width;
	var proportionalWidth	= (arg*screenWidth)/1024;
	return proportionalWidth;
}

function getFileExtn(asFileName)
{
	var lsExtn 	= asFileName.split('.').pop();
	lsExtn 		= lsExtn.toUpperCase();
	return lsExtn;
}
function isLabelPrinterInstalledAndConnected(lsPrinterVersion)//#295627:added for label printer  Priyanka D 
{
	try
	{
		if(lsPrinterVersion == 'null' || lsPrinterVersion == null || lsPrinterVersion == undefined)
			lsPrinterVersion = '1.2.6'; // minimum supported version
		
		if(lsPrinterVersion == '1.0'){
			lsPrinterVersion = '3.0';
			enableDisableLabelPrint(true);
			return;
		}
		
		let baseVersion = lsPrinterVersion.substring(0, lsPrinterVersion.indexOf('.'));
		if(parseInt(baseVersion) >= 3)
		{
			$.getScript('javascript/DYMO.Label.Framework.'+lsPrinterVersion+'.js', function() {
					dymo.label.framework.init(isLabelPrinterInstalledAndConnected4AsyncCall);
				});
		}
		else
			isLabelPrinterInstalledAndConnected4SyncCall(lsPrinterVersion);
		
		//return false;
	}
	catch(e)
	{
		enableDisableLabelPrint(false);
	}
}

//You should not call this function directly from your page, instead call function "isLabelPrinterInstalledAndConnected"
function isLabelPrinterInstalledAndConnected4AsyncCall()
{
	try
	{
		dymo.label.framework.getPrintersAsync().then(function(printers) {
			if (printers.length == 0)
			    enableDisableLabelPrint(false);
				
			for (var i = 0; i < printers.length; ++i)
			{
			    var printer = printers[i];
			    if (printer.printerType == "LabelWriterPrinter"
			    		&& printer.isLocal == true)
				    enableDisableLabelPrint(true);
			}
		});
		/*$.getScript('javascript/DYMO.Label.Framework.'+lsPrinterVersion+'.js', function()
			{	  
				var printers = dymo.label.framework.getPrinters();
				if (printers.length == 0)
				    enableDisableLabelPrint(false);
					
				for (var i = 0; i < printers.length; ++i)
				{
				    var printer = printers[i];
				    if (printer.printerType == "LabelWriterPrinter"
				    		&& printer.isLocal == true)
					    enableDisableLabelPrint(true);
				}	
			});*/
		
		//return false;
	}
	catch(e)
	{
		enableDisableLabelPrint(false);
	}
}

// You should not call this function directly from your page, instead call function "isLabelPrinterInstalledAndConnected"
function isLabelPrinterInstalledAndConnected4SyncCall(lsPrinterVersion)
{
	try
	{
		if(lsPrinterVersion == 'null' || lsPrinterVersion == null || lsPrinterVersion == undefined)
			lsPrinterVersion = '1.2.6'; // minimum supported version
		
		$.getScript('javascript/DYMO.Label.Framework.'+lsPrinterVersion+'.js', function()
		{	  
			var printers = dymo.label.framework.getPrinters();
			if (printers.length == 0)
			    enableDisableLabelPrint(false);
				
			for (var i = 0; i < printers.length; ++i)
			{
			    var printer = printers[i];
			    if (printer.printerType == "LabelWriterPrinter"
			    		&& printer.isLocal == true)
				    enableDisableLabelPrint(true);
			}	
		});
		
		//return false;
	}
	catch(e)
	{
		enableDisableLabelPrint(false);
	}
}
function enableDisableLabelPrint(abEnableDisable)
{
	if(abEnableDisable)		
	{
		if(document.all['labelPrint'] != null)
		{
			if(document.all['labelPrint'].className.indexOf('icnLabelPrint16') >= 0)
				document.all['labelPrint'].className = 'icon16 icnLabelPrint16 nor16';
			else
				document.all['labelPrint'].className = 'ptRegIcons24 labelbut24nor';
		}
	}
	else
	{
		if(document.all['labelPrint'] != null)
		{
			if(document.all['labelPrint'].className.indexOf('icnLabelPrint16') >= 0)
				document.all['labelPrint'].className = 'icon16 icnLabelPrint16 dis16';
			else
				document.all['labelPrint'].className = 'ptRegIcons24 labelbut24dis';
		}
	}
}

// IE & NON-IE behaves different for .length property
// IE calculate newline character as 2byte and non_IE 1byte.
// This function returns proper length, same as IE i.e. 2 bytes
function getLengthOfText(aText)
{
	// '..' are two dummy characters, used to make count perfect
	aText	= aText.replace(/(\r\n|\n|\r)/g, '``');
	return aText.length;
}

// IE & NON-IE behaves different for .length property
// IE calculate newline character as 2byte and non_IE 1byte.
// This function returns proper length, same as IE i.e. 2 bytes
function getSubStringOfText(aText, startIndex, endIndex)
{
	// '..' are two dummy characters, used to make count perfect
	aText	= aText.replace(/(\r\n|\n|\r)/g, '``');
	aText	= aText.substring(startIndex, endIndex);
	aText	= aText.replace(/(``|\n|\r)/g, '\r\n');
	return aText;
}
function goToRemittanceFromClaimLedger(asErhId,asTrnType,asBlhId,asIsRecoup) // Krishna : 4-7-2016 Sugar#166887 To fix the Recoup navigation from claim ledger
{
	var lsMenuId = '';
	if(asTrnType == 'IN') 							//Constants.ERHTYPE_INS_EOB 		-> Remittance > Edit
		lsMenuId = '282'; 							//Constants.MN_ERA_EDIT
	else if(asTrnType == 'PT')						//Constants.ERHTYPE_PAT_RECEIPT 	-> Remittance > Receipts
		lsMenuId = '287'; 							//Constants.MN_ERA_PATIENTRECEIPTS
	else if(asTrnType == 'ER')						//Constants.ERHTYPE_EMP_RECEIPT 	-> Remittance > Employer Receipt
		lsMenuId = '377';							//Constants.MN_ERA_EMPLOYER_RECEIPTS
	else if(asTrnType == 'IC')						//Constants.ERHTYPE_INS_CREDIT		-> Remittance > Ins Credit
		lsMenuId = '349';							//Constants.MN_ERA_INS_CREDIT
	else if(asTrnType == 'PC')						//Constants.ERHTYPE_PAT_CREDIT		-> Remittance > Pat Returns
		lsMenuId = '332';							//Constants.MN_ERA_PATIENTCREDIT
	else if(asTrnType == 'MC')						//Constants.ERHTYPE_MISC_CREDIT		-> Remittance > Pat Misc Credit
		lsMenuId = '360';							//Constants.MN_ERA_PAT_MISC_CREDIT
	else if(asTrnType == 'IW') 						//Constants.ERHTYPE_INS_WO,Constants.ERHTYPE_INS_DENIEDWO,Constants.ERHTYPE_INS_REBILLWO ->  Remittance > Ins Woff
		lsMenuId = '285';							//Constants.MN_ERA_INS_WO
	else if(asTrnType == 'PW')						//Constants.ERHTYPE_PAT_WO -> Remittance > Pat Woff
		lsMenuId = '288';							//Constants.MN_ERA_PAT_WO
	else if(asTrnType == 'EW')						//Constants.ERHTYPE_EMP_WO -> Remittance > Write Off > Employer Woff
		lsMenuId = '439';							//Constants.MN_ERA_EMP_WO
	else if(asTrnType == '4C')						//Constants.ERHTYPE_CA_RECEIPT -> Remittance > Other Payment  > Collection 
		lsMenuId = '418';							//Constants.MN_ERA_PAYMENT_FROM_COLLECTION_AGENCY
	else if(asTrnType == 'CR')						//Constants.ERHTYPE_CAPT_RECEIPT -> Remittance > Other Payment  > Capitation - Added by Sagar for Sugar 250500 
		lsMenuId = '357';							//Constants.MN_ERA_CAPITATION_RECEIPTS

	if(lsMenuId != '')
	{
		lsUrl ="menus.jsp?hidd_curr_tab="+lsMenuId+"&zoomid="+asErhId+"&currbillheaderid="+asBlhId+"&currecoupflag="+asIsRecoup;
		parent.location.href = cleanAndEncodeURL(lsUrl);
	}
}
function removeBlankLinesFromStr(aText)
{
	return aText.replace(/[\r\n|\n|\r]{2,}/g, '\r\n');
}

// Added by Amod on 18-Jul-2013, below method returns true, if asDEAClass = [1-5], else false
// DEA class for Controlled Substance (Narcotics) = 1,2,3,4,5
// DEA class for Non-Controlled Substance = 0,6,7,8,9
function isDEAClassControlledSub(asDEAClass)
{
	var liDEAClass = -1 ;
	var lbDEAClassContrSub = false; 
	
	if(typeof(asDEAClass) == 'undefined' || trim(asDEAClass) == '')
		return lbDEAClassContrSub ;
		
	asDEAClass = trim(asDEAClass) ;
	
	try
	{
		liDEAClass = parseInt(asDEAClass) ;
		
		if(parseInt(liDEAClass) >= 1 && parseInt(liDEAClass) <= 5)
			lbDEAClassContrSub = true;
	}
	catch(e)
	{
		lbDEAClassContrSub = false;
	}
	
	return lbDEAClassContrSub ;
}// isDEAClassControlledSub closed
function getScreenHeight()
{
	var screenHeight	= screen.height;
	if(navigator.userAgent.indexOf("iPad") > -1)
		screenHeight	= screen.width;
	return screenHeight;
}
function getScreenWidth()
{
	var screenWidth	= screen.width;
	if(navigator.userAgent.indexOf("iPad") > -1)
		screenWidth	= screen.height;
	return screenWidth;
}
function getFrameHeight()
{
	return $(window).height();
}
function getFrameWidth()
{
	return $(window).width();
}
function replaceAll(txt, replace, with_this) 
{
	  return txt.replace(new RegExp(replace, 'g'),with_this);
}
/******Sameer
 * 
	 Usage: replaceAllRecursive(txt, replace, with_this);
	 
	 Before  : FHR^12^LOB^50^^^LRB^789
	 After   : FHR^12^LOB^50^LRB^789
	 
	 Changes Done in scrLetterRefDocAttachPopUp.jsp
 * ****/

function replaceAllRecursive(txt, replace, with_this) // 11 MAY 2015   Sameer
{
	if(txt.indexOf(replace) > 0 ) 
	{
		while(true)
		{
			txt = txt.replace(replace,with_this);
			if(txt.indexOf(replace) < 0 )
				break;
		}
	}
	return txt;
}

/*
replaceAllPattern function works to replace according to pattern.
Patterns
1. g - For global match 
2. i - For case sensitive
3. d - For digit
4. w - Alphanumeric character
*/
function replaceAllPattern(txt, replace, pattern, with_this) 
{
	return txt.replace(new RegExp(replace, pattern),with_this);
}
function invokeExtrnlPatEducation(asTypeCode, asCode, aiPtId, aiEncId,aiIndex)
{
	var lsUrl = 'patEduService.action2?type='+asTypeCode+'&code='+asCode+'&ptId='+aiPtId+'&encId='+aiEncId;;
	globalRowIndex=aiIndex;
	retObject=showPopupAsModal(lsUrl, 'Patient Education', 500, 700, 100, 150, callBackInvokeExtrnlPatEducation);
}
function callBackInvokeExtrnlPatEducation(){
	if (!isIE) retObject = top.$('#modalWindow1')[0].globalReturnObject;
	if(retObject != null)
	{
		if(retObject.successFlag== true){
		 $('#edu'+globalRowIndex).addClass('eduInfoAction');
		 $('#edu'+globalRowIndex).attr('title','Education Shared');
		}
	}
	
}
/*
switchTab function to make tab enable (Shashank)
parameters-
1. Tab number to make active
2. Total number of tabs
3. Tab id prefix
4. Content div id prefix
*/
function switchTab(activeTabNum, totalTabs, tab_prefix, content_prefix)
{
	//If disabled tab is clicked then return
	if(document.getElementById(tab_prefix+activeTabNum).className == 'disabled')
		return;
	
	//Make other tabs clickable (not active) & hide div content
	for(var i=1; i<totalTabs+1; i++)
	{
		if(document.getElementById(tab_prefix+i) != null )
		{
			if(document.getElementById(tab_prefix+i).className != 'disabled') //When a tab is clicked, at that time other disabled tabs should not be enable
			{
				document.getElementById(content_prefix+i).style.display = 'none';
				document.getElementById(tab_prefix+i).className = '';
			}
		}
	}
	//Make clicked tab active & show div
	document.getElementById(content_prefix+activeTabNum).style.display = 'block';
	document.getElementById(tab_prefix+activeTabNum).className = 'active';
}
//Tab function end

function isSpacePresentInStr(asStr)
{
	if(asStr.indexOf(' ') >= 0)
		return true;
	else
		return false;
}

// Returns the version of Windows Internet Explorer or a -1
function getIEVersion()
{
   var returnVal = -1; // Return value assumes failure.
   if (navigator.appName == 'Microsoft Internet Explorer')
   {
      var userAgent = navigator.userAgent;
      var regExp  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
      if (regExp.exec(userAgent) != null)
         returnVal = parseFloat( RegExp.$1 );
   }
   return returnVal;
}

//Generic wait opertaions
function showGenericWaitDiv()
{
	if(document.getElementById('popupDivWait') != null )
		document.getElementById('popupDivWait').style.display = '';
}
function hideGenericWaitDiv()
{ 
	if(document.getElementById('popupDivWait') != null )
		document.getElementById('popupDivWait').style.display = 'none';
}
//Generic wait opertaions end
function getInternetExplorerVersion()
{
	var rv = -1;
	if (navigator.appName == 'Microsoft Internet Explorer')
	{
		var ua = navigator.userAgent;
	  	var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
	  	if (re.exec(ua) != null)
	    rv = parseFloat( RegExp.$1 );
	}
	else if (navigator.appName == 'Netscape')
	{
	  	var ua = navigator.userAgent;
	  	if(ua.toLowerCase().indexOf("windows nt") != -1 && ua.toLowerCase().indexOf("touch") != -1)	//This is for surface tablet
	  		return rv;
	  	var re  = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
	  	if (re.exec(ua) != null)
	    rv = parseFloat( RegExp.$1 );
	}
	return rv;
}
function isSafari()
{
	var ua = navigator.userAgent.toLowerCase(); 
	if(ua.indexOf('safari') != -1)
	{
		if(ua.indexOf('chrome') > -1)
	    	return false;
	   	else
	    	return true;
	}
	else
		return false;
}
function isMSEdge()
{
	var ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf('edge') != -1)
		return true;
	else
		return false;
}
function getHexCodeFromRgb(colorval)
{
	if(colorval.indexOf('rgb') == -1)
		return colorval; 
    var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    delete(parts[0]);
    for (var i = 1; i <= 3; ++i)
	{
        parts[i] = parseInt(parts[i]).toString(16);
        if (parts[i].length == 1) parts[i] = '0' + parts[i];
    }
    color = '#' + parts.join('');
    return color;
}

// 10 JUN 2015 scrNotes.jsp 
function insertTextAtCursorPosition2(myField, myValue) 
{
    //IE support
    if(document.selection) 
    {
        myField.focus();
        sel 		= document.selection.createRange();
        sel.text 	= myValue;
    }
    //MOZILLA and others
    else if(myField.selectionStart || myField.selectionStart == '0') 
    {
        var startPos	= myField.selectionStart;
        var endPos		= myField.selectionEnd;
        myField.value	= myField.value.substring(0, startPos)+
			  			  myValue+
			  			  myField.value.substring(endPos, myField.value.length);
        
        myField.selectionStart	= startPos + myValue.length;
        myField.selectionEnd	= startPos + myValue.length;
    } 
    else 
    {
        myField.value += myValue;
    }
}

function insertTextAtCursorPosition(areaId,text)
{
	var txtarea		= document.getElementById(areaId);
    var scrollPos 	= txtarea.scrollTop;
    var strPos 		= 0;
    var br 			= ((txtarea.selectionStart || txtarea.selectionStart == '0') ? "ff" : (document.selection ? "ie" : false ) );
    if (br == "ie")
	{ 
        txtarea.focus();
        var range	= document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        strPos		= range.text.length;
	}
    else if (br == "ff") 
        strPos = txtarea.selectionStart;

    var front		= (txtarea.value).substring(0,strPos);  
    var back 		= (txtarea.value).substring(strPos,txtarea.value.length); 
    txtarea.value	=front+text+back;
    strPos 			= strPos + text.length;
    if(br == "ie")
	{ 
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        range.moveStart ('character', strPos);
        range.moveEnd ('character', 0);
        range.select();
    }
    else if (br == "ff")
	{
        txtarea.selectionStart 	= strPos;
        txtarea.selectionEnd	= strPos;
        txtarea.focus();
    }
    txtarea.scrollTop = scrollPos;
}

//Added by Jinesh for ICD Cascade Search on 18-Mar-2015
//Modified by Jinesh on 14-Apr-2015, removed reading "hide.drilldown.icdsearch" property value
function invokeICDCascadeSearch(asCustType, asMaxIcdCount, asPtDtlsFlag, asPtId, asEncId, asShowOldIcd)
{
	if(asShowOldIcd == null || asShowOldIcd == 'null' || asShowOldIcd == 'undefined')
		asShowOldIcd = 'N';
	if(asPtId == null || asPtId == 'null')
		asPtId = '';
	if(asEncId == null || asEncId == 'null')
		asEncId = '';
	
	url = "ICDSearch.action2?sendPtDetails="+asPtDtlsFlag+"&ptId="+asPtId+"&encId="+asEncId+"&custType="+asCustType+"&operation=DISPLAY&maxIcdCount="+asMaxIcdCount+"&showoldcodes="+asShowOldIcd;
	var newurl =packWhereParam2(url);
	newurl = "scrPopUpFrame.jsp?mainurl="+newurl;
	newurl =packWhereParam(newurl);
	var paramObject = new Object();
	open_popup(url,"prognoListSearch","width=990,height=600,resizable=no,maximize=no,scrollbars=yes ,left = 10 , top =15");
}

//Selection of ICD10 code on click of ICD9 code - Added by Dipen on 28/04/2015
function invokeIMOSearchOnly4Icd9(asIcdCode, asIndex, asCallFromWhere,asShowOldIcd)
{ 
	if(asIcdCode == '')
		return;
	if(asShowOldIcd == null || asShowOldIcd == 'null' || asShowOldIcd == 'undefined')
		asShowOldIcd = 'N';
	sIndex				= asIndex;
	var asPtId 			= '';
	var	asEncId 		= '';
	var asPtDtlsFlag	= "";
	var asCustType 		= "";	//var asCustType 		= "Y";
	var asMaxIcdCount	= 1;

	var sCallFromWhere 	= '';
	//asCallFromWhere is used to identify that ICD coming from which tab(source) or Sett>Conf>Pref ICD of (+) button search
	if(typeof asCallFromWhere != 'undefined' && asCallFromWhere != 'null' && asCallFromWhere != '')
		sCallFromWhere = asCallFromWhere;
	else
		sCallFromWhere = '';
	
	url 		= "ICDSearch.action2?sendPtDetails="+asPtDtlsFlag+"&ptId="+asPtId+"&encId="+asEncId+"&custType="+asCustType+"&operation=DISPLAY&maxIcdCount="+asMaxIcdCount+"&icdCode="+asIcdCode+"&invokefromwhere="+sCallFromWhere+"&showoldcodes="+asShowOldIcd;
	var newurl 	= packWhereParam2(url);
	newurl 		= "scrPopUpFrame.jsp?mainurl="+newurl;
	newurl 		= packWhereParam(newurl);
	var paramObject = new Object();
	open_popup(url,"prognoListSearch","width=850,height=400,resizable=no,maximize=no,scrollbars=yes ,left = 10 , top =15");
}

//Selection of ICD9 code, SNOMED code on click of ICD10 code - Added by Amey Sawant on 27/08/2015
function invokeIMOSearchOnly4Icd10(asIcdCode, asIndex)
{ 
	if(asIcdCode == '')
		return;
	sIndex				= asIndex;
	var asPtId 			= '';
	var	asEncId 		= '';
	var asPtDtlsFlag	= "";
	var asCustType 		= "";	//var asCustType 		= "Y";
	var asMaxIcdCount	= 1;

	url 		= "ICDSearch.action2?sendPtDetails="+asPtDtlsFlag+"&ptId="+asPtId+"&encId="+asEncId+"&custType="+asCustType+"&operation=DISPLAY&maxIcdCount="+asMaxIcdCount+"&icdCode="+asIcdCode+"&sicd10call=Y";
	var newurl 	= packWhereParam2(url);
	newurl 		= "scrPopUpFrame.jsp?mainurl="+newurl;
	newurl 		= packWhereParam(newurl);
	var paramObject = new Object();
	open_popup(url,"prognoListSearch","width=850,height=400,resizable=no,maximize=no,scrollbars=yes ,left = 10 , top =15");
}

function ajaxRequest(url, params, type, callback)
{
	new makeAjaxRequest(url, params, type, callback);
}

function makeAjaxRequest(url, params, type, callback)
{
	$.ajax({async: true, type: type, url: url, cache: false, data: params,
		success: function(response, status) {
			callback(status, response);
		},
		error: function(jqXHR, status) {
			callback(status, '');
		}
	});
}

//Initilize Nice Scroll
function initNiceScroll(asCntrl, asThemeId, asScrollColor, abHorizontalScrollEnable)
{
	var lsCursorColor = "#acb4de";
	if(asScrollColor){
		lsCursorColor = asScrollColor;
	}
	var lbHorizontalScrollEnable = false;
	if(abHorizontalScrollEnable){
		lbHorizontalScrollEnable = true;
	}
	//return $(asCntrl).niceScroll({cursorcolor:lsCursorColor, horizrailenabled:lbHorizontalScrollEnable, touchbehavior:false, cursorwidth:7, autohidemode:false});	
	var scroller = $(asCntrl).niceScroll({cursorcolor:lsCursorColor, horizrailenabled:lbHorizontalScrollEnable, touchbehavior:false, cursorwidth:7, autohidemode:false});
	scroller.resize();
	return scroller;
}

// This function has been moved from mouseover.js
// As we don't use other functions from mouseover.js, it's not feasible to load mouseover.js as script
var gOldSelectionRowId = '';
var gOldSelectionRowClass = '';
function selectCurrRowOnClick(ctrl)
{ 
	if(gOldSelectionRowId != ctrl.id)
	{
		if(gOldSelectionRowId != '')
			document.all[gOldSelectionRowId].className = gOldSelectionRowClass;
		
		var oldClassName = ctrl.className;
		gOldSelectionRowClass = oldClassName;
		gOldSelectionRowId	= ctrl.id;
		
		oldClassName	= oldClassName+' selrowdet';
		ctrl.className	= oldClassName;
	}
}

// This function creates input element & returns to calling function
function createInputElement(asType, asName, asValue)
{
	var inputEle = document.createElement('input');
	inputEle.type = asType;
	inputEle.name = asName;
	inputEle.id = asName;
	if(asType != 'button' && asType != 'submit')
		inputEle.value = asValue; 
	return inputEle;
}

// This function creates dropdown element & returns to calling function
// argument to be Passed in format --> 'value1:text1|value2:text2'
function getStatusSelOptions(optionsString)
{
	var statusListStr = optionsString;
	var statusSel = document.createElement('select')
	if(statusListStr != null && statusListStr != '')
	{
		var statusList = statusListStr.split('|');
		var statusObj = '';
		var option;
		for(var i =0; i < statusList.length; i++)
		{
			statusObj = statusList[i].split(':');
			if(statusObj != null && statusObj.length == 2)
			{
				option = document.createElement('option');
				option.value = statusObj[0];
				option.text = statusObj[1];
				statusSel.appendChild(option);
			}	
		}	
	}
	return statusSel;
}

function formatNumeric(objTxt){
	intTest = /^[0-9,+-]{1,}$/;
	var sValue = objTxt.value;
	if(sValue != '')
	{
		if(intTest.test(sValue))
		{
			return true;
		}
		objTxt.value = objTxt.value.substring(0, objTxt.value.length-1);
		return formatNumeric(objTxt);
	}
}

function formatNumeric2(asValue){
	intTest = /^[0-9,+-]{1,}$/;
	var sValue = asValue;
	if(sValue != '')
	{
		if(intTest.test(sValue))
		{
			return true;
		}
		asValue = asValue.substring(0, asValue.length-1);
		return formatNumeric2(asValue);
	}
}
function formatFraction(objTxt){
	floatTest = /^[0-9.,+-]{1,}$/;
	var sValue = objTxt.value;
	if(sValue != '')
	{
		if(floatTest.test(sValue))
		{
			return true;
		}
		objTxt.value = objTxt.value.substring(0, objTxt.value.length-1);
		return formatFraction(objTxt);
	}
	
}

function removeTrailingZeros(fractionStr)
{
	// 02 MAY 2017
	// if value is 1.500 return 1.5 If value is 13 return 13
	if(fractionStr == '')
		return fractionStr;
	
	var liPos = fractionStr.indexOf('.');
	if(liPos <= 0)
		return fractionStr;
	var liLen = fractionStr.length;
	var lsLastChar = '';
	while(liLen > 0)
	{
		lsLastChar = fractionStr.substring(liLen -1,liLen)
		if(lsLastChar == '0')
		{
			fractionStr = fractionStr.substring(0,liLen -1);
			liLen = liLen -1;
		}
		else if(lsLastChar == '.')
		{
			fractionStr = fractionStr.substring(0,liLen -1);
			break;
		}
		else
			break;
	}
	return fractionStr;
}
//Added by Monika.
function checkIfBlank(asStr,elnname)
{
	if(asStr.indexOf(" ") >=0)
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		
		// 28 DEC 2018: Pritesh Gawde
		// Changes done on CR received from PM (Yogi) during Project Two-Factor Authentication
		alert('Spaces are not allowed in the \'Userid\' field.');
        return true;
	}
}
function checkValidationForSpclChar(asStr , elnname)
{
	if( asStr.indexOf("'") >=0 || asStr.indexOf("&") >=0 || asStr.indexOf("%") >=0 || asStr.indexOf("\"") >=0
			|| asStr.indexOf("^") >=0  || asStr.indexOf("<") >=0 || asStr.indexOf(">") >=0  || asStr.indexOf("?") >=0  || asStr.indexOf(":") >=0 
			|| asStr.indexOf(";") >=0 || asStr.indexOf("+") >=0 || asStr.indexOf(",") >=0 || asStr.indexOf("=") >=0  || asStr.indexOf("{") >=0 
			|| asStr.indexOf("}") >=0 )
	{
		document.all[elnname].select();
		document.all[elnname].focus();
		alert('\', %, ^, <, >, &, ", Space, :, ;, +, ?, ,, =, {, } are not  Valid UserId Characters');
		return true;
	}
	return false;	
}
function isExtnMedia(asExtn)
{
	var MEDIA_EXTENSIONS = "wav"; //This should be in synchronization with MEDIA_EXTENSIONS in Constants.java.
	if(asExtn!= "" && MEDIA_EXTENSIONS.indexOf(asExtn) >= 0 )
		return true;
	else
		return false;
}

//Added by MS on 19 DEC 2017 For Capture the Audit Trail comments for IPL Login and Logout, called from scrIplMaster.jsp
function captureAuditDetailsForIPL(asId, asPoolName, asAction, asCalledFrom, asUserSubType, asLogUserId)
{
	var lsResult 	= 'N';
	var ajaxUrl 	= 'captureAuditDetailsForIPL.action';
	var lsAuditData = {"id" :asId, "poolname":asPoolName, "action":asAction, "calledfrom":asCalledFrom, "usersubtype":asUserSubType, "loguserid":asLogUserId};
	$.ajax(
		{type:'post', async:false, cache: false, url: ajaxUrl , data: lsAuditData, dataType: "json",success: function(asAuditData)
			{
				lsResult = asAuditData;
			}
		}
	);
	return lsResult;	
}
//Added by Sumit Salunkhe 24 APR 2018 to Capture audit trail comments for emp portal print
function captureAuditDetailsForEmpPortalBill(asMenuID,asEmpUserName,asEmployerName,asSubUserType,asUserType,asPersonId,asPoolName,asDocId,asOprtn)
{
	var lsResult 	= 'N';
	var ajaxUrl 	= 'captureAuditDetailsForEmpPortalPrn.action';
	var lsAuditData = {"id" :asMenuID,"lsEmpUserName":asEmpUserName, "lsEmployerName":asEmployerName, "lsSubUserType":asSubUserType, "lsUserType":asUserType, "lsPersonId":asPersonId, "lsPoolName":asPoolName,"lsDocId":asDocId, "lsOprtn":asOprtn};
	$.ajax(
		{type:'post', async:false, cache: false, url: ajaxUrl , data: lsAuditData, dataType: "json",success: function(asAuditData)
			{
				lsResult = asAuditData;
			}
		}
	);
	return lsResult;	
}
//Added by Sumit Salunkhe 26 DEC 2018 to Capture audit trail comments for Attorney portal - ATP_AUDIT_TRAIL
function captureAuditDetailsForATPPortal(asMenuID,asAttorneyName,asSubUserType,asUserType,asPersonId,asPoolName,asObjectId,asOprtn,asExtraParam)
{
	var lsResult 	= 'N';
	var ajaxUrl 	= 'captureAuditDetailsForATPPortal.action';
	var lsAuditData = {"id" :asMenuID,"lsAttorneyName":asAttorneyName,"lsSubUserType":asSubUserType, "lsUserType":asUserType, "lsPersonId":asPersonId, "lsPoolName":asPoolName,"lsObjectId":asObjectId,"lsOprtn":asOprtn,"asExtraParam":asExtraParam};
	$.ajax(
			{type:'post', async:false, cache: false, url: ajaxUrl , data: lsAuditData, dataType: "json",success: function(asAuditData)
				{
				lsResult = asAuditData;
				}
			}
	);
	return lsResult;	
}
//Sameer 28 SEP 2022
function captureAuditDetailsForIAPPortal(asMenuID,asName,asSubUserType,asUserType,asPersonId,asPoolName,asObjectId,asOprtn,asExtraParam)
{
	var lsResult 	= 'N';
	var ajaxUrl 	= 'captureAuditDetailsForIAPPortal.action';
	var lsAuditData = {"id" :asMenuID,"lsName":asName,"lsSubUserType":asSubUserType, "lsUserType":asUserType, "lsPersonId":asPersonId, "lsPoolName":asPoolName,"lsObjectId":asObjectId,"lsOprtn":asOprtn,"asExtraParam":asExtraParam};
	$.ajax(
			{type:'post', async:false, cache: false, url: ajaxUrl , data: lsAuditData, dataType: "json",success: function(asAuditData)
				{
				lsResult = asAuditData;
				}
			}
	);
	return lsResult;	
}
//Akshay Khorgade 04 April 2024
function captureAuditDetailsForEMPPortal(asMenuID,asName,asSubUserType,asUserType,asPersonId,asPoolName,asObjectId,asOprtn,asExtraParam)
{
	var lsResult 	= 'N';
	var ajaxUrl 	= 'captureAuditDetailsForEMPPortal.action';
	var lsAuditData = {"id" :asMenuID,"lsName":asName,"lsSubUserType":asSubUserType, "lsUserType":asUserType, "lsPersonId":asPersonId, "lsPoolName":asPoolName,"lsObjectId":asObjectId,"lsOprtn":asOprtn,"asExtraParam":asExtraParam};
	$.ajax(
			{type:'post', async:false, cache: false, url: ajaxUrl , data: lsAuditData, dataType: "json",success: function(asAuditData)
				{
				lsResult = asAuditData;
				}
			}
	);
	return lsResult;	
}
// Modified by MS on 18 JAN 2018 MS
// Check version of Jquery and accordingly use .prop() or .attr() function. isJqueryAbove16() is defined in common.js
function isJqueryAbove16()
{
	var jqVersion = $.fn.jquery;
	jqVersion = jqVersion.substring(0, jqVersion.lastIndexOf('.'));
	var lsaVersionArr = jqVersion.split('.');
	if(parseInt(lsaVersionArr[0]) > 1)
		return true;
	else if(parseInt(lsaVersionArr[0]) == 1 &&  parseInt(lsaVersionArr[1]) >= 6) 
		return true;
	else
		return false;
}
//Added by- Sumit Salunkhe 6 FEB 2018
function validateDuplicatePatientOnPoral(asFname, asLname, asDob)
{
	var lsResult 	= '';
	var ajaxUrl 	= 'ajaxCntlrvalidateDuplicatePatientOnPoral.action';
	var lsValidatePatDuplicate = {
		"msPt_fname" : asFname,
		"msPt_lname" : asLname,
		"msPt_dob" : asDob
	};
	$.ajax({
		type : 'post',
		async : false,
		cache : false,
		url : ajaxUrl,
		data : lsValidatePatDuplicate,
		dataType : "json",
		success : function(asValidPat) {
			lsResult = asValidPat;
		}
	});
	return lsResult;
}

function checkTlsSupportForBrowser()
{
	// 31 JAN 2019 Amey Sawant
	// COMMENTING THIS CODE AS WE HAVE SUCCESSFULLY MIGRATED TO TLSv1.2
	/*try
	{
		var lsAjaxCallUrl 	= "https://tlstesting.prognocis.com:4433/index.html";
		
		$.ajax({async: true, type: 'post', url: lsAjaxCallUrl, cache: false,
			complete: function(jqXhr, status) {
				if(status == 'error')
				{
					if(jqXhr.status == 0 || jqXhr.status == 12157)
					{
						displayTlsAlert();
					}
				}
			}
		});
	}
	catch (e)
	{
		if(e.message.indexOf('8070000c') > -1);
		else
			displayTlsAlert();
	}*/
}

function checkTlsSupportCallback()
{
	if(xmlHttp.status == 0 || xmlHttp.status == 12157)
	{
		displayTlsAlert();
	}
}

function makeCalcAjaxCall(urlParams, url) 
{
	var calcURL = "scrCalcAjaxCalls.jsp";
	if(url != undefined && url != null && url != '')
		calcURL = url;
	
	xHttp=GetXmlHttpObject(calcCallback);
	xHttp.open("POST", calcURL , true);
	xHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xHttp.send(urlParams);
}

function calcCallback()
{
	if (xHttp.readyState==4 || xHttp.readyState=="complete")
	{
		var returnval = trim(xHttp.responseText);
		if(returnval != '')
		{
			//eval(returnval);
			if(returnval.indexOf('parent.mainFrame.TemplateCallback') > -1)
			{
				var templateStr = returnval.substring( (returnval.indexOf('(\'')+2), returnval.lastIndexOf('\')') );
				parent.mainFrame.TemplateCallback( templateStr);
			}
			if(returnval.indexOf('parent.mainFrame.orderFrame.TemplateCallback') > -1)
			{
				var templateStr = returnval.substring( (returnval.indexOf('(\'')+2), returnval.lastIndexOf('\')') );
				parent.mainFrame.orderFrame.TemplateCallback( templateStr);
			}
			else
			{
				if(returnval.indexOf('mainFrame') > -1) {
					if(parent.mainFrame != null && parent.mainFrame != undefined)
						eval(returnval);
					else {
						returnval = returnval.substring(17, returnval.length);
						eval(returnval);
					}
				} else
					eval(returnval);
			}
		}
	}
}

function resizeNicescroll(divId) {
	if(divId.indexOf('.') != 0)
		divId = '#' + divId;
	
	if($(divId).getNiceScroll().length > 0)
		$(divId).getNiceScroll().resize();
}

//Added by Sumit S. 25 SEP 2018
function removeValueFromString(asFindIn,asFindWhat)
{
   var liWholeStrLen 	= asFindIn.length;
   var liRmvStrrLen		= asFindWhat.length;
   var liStrIndex		=  asFindIn.indexOf(asFindWhat);
   var lsReturnVal		= '';
   if(liStrIndex >= 0)
	{
	   lsReturnVal = asFindIn.substring(0,liStrIndex) + asFindIn.substring((liStrIndex + liRmvStrrLen )+1 ,asFindIn.length);
	}
   return lsReturnVal;
}

//Added by Sumit S. 09 OCT 2018
function findElementStartsWith(asFindIn,asStartsWith,asSplitBy)
{
	var lsExtractedId 	= '';
	var arrName			= asFindIn.split(asSplitBy);
	for(i = 0; i < arrName.length; i++)
	{
		if(arrName[i].indexOf(asStartsWith) >= 0)
		{
			lsExtractedId 	= arrName[i].substring(arrName[i].indexOf(asStartsWith)+1,arrName[i].length);
		}
	}
	return lsExtractedId;
}

//Added by Tejas L.
function callAjax(type, async, cache, url, data, dataType){
	var lsResult = new Object();
	$.ajax(
			{type: type, async: async, cache: cache, url: url , data: data, dataType: dataType,
				success: function(response)
				{
					lsResult = response;
					lsResult.status = "success"
				},
				error: function(response) {
					lsResult = response;
					lsResult.status = "error"
				}
			}
		);
	return lsResult;
}

//Added by Tejas L.
function checkIfNullOrBlank(data){
	if(data == null || data.trim() == '')
		return true;
	return false;
}

function BizShowDialog(asMessage,asTitle,asBtnList,asTop,asLeft,asFont,asHeight)
{
	var lsButtons = { };
	$("#alert").dialog(
			{
				modal 	: true,
				title 	: asTitle,
				width 	: 360,
				height 	: 200,
				open : function(event, ui) 
				{
					$(".ui-widget-overlay").css({
						background : "rgb(0, 0, 0)",
						opacity : ".50 !important",
						filter : "Alpha(Opacity=50)",
					});
				},
				close : function(event, ui) 
				{
					// Sumit S. - If we want to perform any operation we can add here
				}
				
				// Sumit.S - dialog function required attributes
			}
	);
	
	$.each( asBtnList, function( key, value ) 
			{
		lsButtons[key] = function() 
		{
			value();
			$(this).dialog("close");
		}
			});
	//Changed default css class for this function only
	$('#alert').dialog('option', 'buttons', lsButtons);
	//(".ui-state-default").css("background","red");
	$('.ui-dialog').css({'top':'50%','left':'50%','margin-top': '-50px','margin-left': '-180px'});
//	$('.ui-widget-header').css({'background': 'rgb(56, 83, 128)','color': '#f7f5f5' ,'font-size': '12px'});
	//$('.ui-widget-header').css({'font-size': '12px'});
//	$('.ui-state-default').css({'border': '2px solid rgb(56, 83, 128)'});
	
	$('.ui-state-default').css({'border': '3px solid #aed0ea'});
	$('#alert').height(asHeight);
	$("#alert").html("<p style='color: rgb(56, 83, 128);font-size: 13px !important;' font-family: Arial, Helvetica, sans-serif;font-color: #000000;' >"
			+ asMessage
			+ "</p>");
}
/* Add by Sameer 20 JUL 2019
 * Usage: 
 *  x = create2DArray( 2 , 3,''); // 2 lines, 3 cols filled with empty string
 *	y = create2DArray( 10, 5, 0);// 10 lines, 5 cols filled with 0
 ***/
function create2DArray(asRows, asCols, asDefaultValue)
{
	  var lsaMatrix = [];
	  for(var i=0; i < asRows; i++) // Creates all lines:
	  {
		  lsaMatrix.push([]); // Creates an empty line
		  lsaMatrix[i].push( new Array(asCols));// Adds asCols to the empty line:
	      for(var j=0; j < asCols; j++)
	    	  lsaMatrix[i][j] = asDefaultValue; // Initializes:
	  }
	return lsaMatrix;
}
function closePopup()
{
	return;
}

//formatMaskDate
function formatMaskBdate(strField)
{
	valueChanged();
	formatSSN(strField,Bdatemask,Bdatemaxlen);
}

var gsMaxChequeAmnt	= Number(9999999.99);

function formatMoneyToDisplay (amountToFormat) {
	return new Intl.NumberFormat('en-US', {currency: 'USD', minimumFractionDigits: 2}).format(amountToFormat);
}


function getPPWebDateFormat(asDateValue)
{
	var gslng_label_Today	= "Today";
	var lsToCompareDate 	= asDateValue.split("-");
	lsToCompareDate 		= new Date(lsToCompareDate[0]+"/"+lsToCompareDate[1]+"/"+lsToCompareDate[2]);
	lsToCompareDate 		= lsToCompareDate.toDateString();
	var lsCurrentDate 		= new Date();
	lsCurrentDate 			= lsCurrentDate.toDateString();
 
	if (lsToCompareDate == lsCurrentDate)
		lsApptDate = gslng_label_Today+' ';
	else
		lsApptDate = lsToCompareDate+' ';

	return lsApptDate;		
}

// Added by Vishal W. on 10 Feb 2021 for Preferred Pharmacy on Web Patient Portal Enhancement(#341583).
function getPreferredPharmData(){
	var ajaxUrl	 	  	  = 'ajaxCntlrGetPrefPharmacyForPatient.action';
	var lsUserData  	  = '';
	$.ajax({type:'post', async:true, cache: false, url: ajaxUrl,data: lsUserData, dataType: "json",success: function(details){
		gsRetVal = details;
	}});
}

//SHASHANK 05-MAR-2021 Generic Method added to send email from JavaScript (Mostly for Debugging Purpose)
function sendEmail(emailIds, emailSubject, emailContents)
{
	var ajaxUrl 	= 'sendEmail.action';
	var urlParams   = 'emailIds='+emailIds+'&emailSubject='+emailSubject+'&emailContents='+emailContents;
	$.ajax({type:'post', async:true, cache:false, url:ajaxUrl, data:urlParams, success: function(response){
		console.log(response);
	}});
}

//Added by Manish on 14 Feb 2023 for editing external pdf
var lsReturn = '';
var gsselectedindex  = '';
var gsType = '';
var gsFileName = '';
var gsPtId = '';
var lsLohId = '';//EMRENH1202 
function delModifiedSelectedAttachment(asselectedAttachIndex,asType,asFileName,asPtId,asDeletedFrom)
{
	// asselectedAttachIndex is 0 indexed
	if(asType!='OT' && asType!='RFA' && asType!='LD' && asType!='CRA' && asType!='PRA')//EMRENH1202
	{
		//EMRENH1202 S
		if(asType!='LIA')
		{
			var lsExt 	= document.Form.msFileExt.value;
			lsaExt		= lsExt.split(",");
			lsReqExt	= lsaExt[asselectedAttachIndex];
		}
		if(asDeletedFrom == 'CRA')
			lsLohId	= document.Form.msCon_let_in_id.value;
		else
			lsLohId	= document.Form.msid.value;
		//EMRENH1202 E
		var lsPath 	= document.Form.msServerPath.value;	
		
	//	asPoolName 	= gsPoolName;
	//	asCssName 	= gsSessionCssName;
	}
	else
	{
		gsFileName	= asFileName;
		gsPtId		= asPtId;
	}
	asselectedAttachIndex++;
	gsselectedindex = 		asselectedAttachIndex;
	gsType	=	asType;
	lsReturn = showPopupAsModal("scrConfirm.jsp?message=Do you want to detach the modified attachment? Original File will be restored.", 'Confirm', 175, 360, 330, 230, ConfirmCallback);

}

function ConfirmCallback()
{
	if (!isIE) retObject = top.$('#modalWindow1')[0].globalReturnObject;

	if(retObject != null)
	{
		if(retObject == 'yes')
		{
			var lsAjaxCallUrl = "scrAjaxCalls.jsp";
//			var urlParams = "type=242&LohId="+document.Form.msid.value+"&Lsscrno="+gsselectedindex+"&docType="+gsType;
			var urlParams = "";
			if(gsType != 'OT' && gsType != 'RFA' && gsType != 'LD' && gsType != 'CRA' && gsType != 'PRA')//EMRENH1202
			{
				urlParams = "type=242&LohId="+lsLohId+"&Lsscrno="+gsselectedindex+"&docType="+gsType;	//EMRENH1202
			}
			else
			{
				urlParams = "type=242&LohId="+gsFileName+"&Lsscrno="+gsselectedindex+"&docType="+gsType+"&ptId="+gsPtId;
			}
			xmlHttp=GetXmlHttpObject(submitToCallback);
			xmlHttp.open("POST", lsAjaxCallUrl , true) ;
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.send(urlParams) ;
		}
	}
}

function submitToCallback()
{
	if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{
		if(gsType != 'OT' && gsType != 'RFA' && gsType != 'LD' && gsType != 'LIA')//EMRENH1202
		{
			switchTab(3,3,'tab_','content_');
			window.location.reload();
		}
		else
			window.top.location.reload();
		//EMRENH1202
		if(gsType == 'LD')
			document.getElementById("delete").style.visibility  = "hidden";
		
	}
}

function creatingWindowCookie()
{
	var domainName=window.location.hostname;
//	console.log("DomainKey::"+compress(domainName));
//	var sWindowName = asPoolName+'_'+asSessionId;
//	 if(sWindowName.indexOf('.') > 0)
//		 sWindowName =  sWindowName.substring(0, sWindowName.indexOf('.'));
	 createCookie('cookie-windowdom',domainName);
}

function compress(string) 
{
	  string = unescape(encodeURIComponent(string));
	  var newString = '',
	    char, nextChar, combinedCharCode;
	  for (var i = 0; i < string.length; i += 2) {
	    char = string.charCodeAt(i);

	    if ((i + 1) < string.length) {

	      
	      nextChar = string.charCodeAt(i + 1) - 31;

	      
	      combinedCharCode = char + "" + nextChar.toLocaleString('en', {
	        minimumIntegerDigits: 2
	      });

	      newString += String.fromCharCode(parseInt(combinedCharCode, 10));

	    } else {

	     
	      newString += string.charAt(i);
	    }
	  }
	  return newString.split("").reduce((hex,c)=>hex+=c.charCodeAt(0).toString(16).padStart(4,"0"),"");
}

function removeWindowCookie(asPoolName,asSessionId)
{
	eraseCookie('cookie-windowdom');
}

function disableFields()
{
	document.getElementById("username").disabled = true;
	document.getElementById("password").disabled = true;
	document.getElementById("username").value = "";
	document.getElementById("password").value = "";
	document.getElementById("login").disabled = true
	document.getElementById("login").className = "disbutton";
}

function isTabOpen()
{
	var cookiewindowdom = readCookie('cookie-windowdom');
	var extwindomdom = window.location.hostname;
	if(cookiewindowdom != "null")
		{
			//var existingSessionId=cookiewindowname.substring(cookiewindowname.lastIndexOf('_')+1);
			if(cookiewindowdom == extwindomdom )
			{
				return true;
			}
		}
	return false;
}
//changes by Sameer P(EMR) : Reviewed By Pratibha Mohite 	// For Project Code : EMRENH1026
function fnToSetSpecialCharFromAjax(data){
	return String.fromCharCode(data.substr(2,data.length-3))
}
//Added by Smruti on 09-May-2023 and reviewed by Suvarna: to unescape special characters.
function unEscapeHtml(val)
{
    return val.replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&');
}

//10 APR 2024 Added by Neeraj to get Exact date difference with Leap year 
function getDateDifference(asDispDate1, asDispDate2)
{
    // Parse the input date strings
	// Special handling for Ipad Devices, using replace to resolve this issue.
    var asDate1Obj = new Date(asDispDate1.replace(/-/g, '/'));
    var asDate2Obj = new Date(asDispDate2.replace(/-/g, '/'));

    // Check if the parsed dates are valid
    if (isNaN(asDate1Obj) || isNaN(asDate2Obj))
	{
        console.log("Invalid dates");
        return null;
    }

    // Calculate the time difference in milliseconds
    var lsDifferenceInMilliseconds = Math.abs(asDate2Obj.getTime() - asDate1Obj.getTime());

    // Convert milliseconds to seconds, minutes, hours, and days
    var seconds = Math.floor(lsDifferenceInMilliseconds / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours   = Math.floor(minutes / 60);
    var days    = Math.floor(hours / 24);

    // Calculate remaining hours, minutes, and seconds
    var remainingHours   = hours % 24;
    var remainingMinutes = minutes % 60;
    var remainingSeconds = seconds % 60;

    // Get the years, months, and days separately
    var years 		  = Math.floor(days / 365);
    var remainingDays = days % 365;

    // Calculate the number of leap years in the interval
    var leapYears = 0;
    for (var year = asDate1Obj.getFullYear(); year <= asDate2Obj.getFullYear(); year++)
	{
        if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0)
            leapYears++;
    }

    // Adjust for leap years
    var leapYearDays 	= leapYears * 366;
    var nonLeapYearDays = (years - leapYears) * 365;
    remainingDays 		-= leapYearDays + nonLeapYearDays;

    // Calculate the number of months and remaining days
    var months = 0;
    var remaining = remainingDays;
    for (var i = 0; i < 12; i++)
	{
        var monthDays = new Date(asDate1Obj.getFullYear(), i + 1, 0).getDate();
        if (remaining >= monthDays)
		{
            months++;
            remaining -= monthDays;
        } 
		else
            break;
    }

    return {
        years: years,
        months: months,
        days: remaining,
        hours: remainingHours,
        minutes: remainingMinutes,
        seconds: remainingSeconds
    };
}

//10 APR 2024 Added by Neeraj to download the file by passing asDrishyamEncFilePath and FileName that we have save.
//For Reference Check : scrShowGenericReportSelectionInFrame.jsp
function genericFileDownload(asDrishyamEncFilePath, asFileName)
{
	if(checkIfNullOrBlank(asDrishyamEncFilePath) == false)
	{
		if(checkIfNullOrBlank(asFileName))
			asFileName = "";
		
		lsurl 						= "scrGenDownload.jsp?key="+asDrishyamEncFilePath+"&fileName="+asFileName;
	    var element  				= document.createElement('a');
	    element.href 				= lsurl;
	    document.body.appendChild(element);
	    element.click();
	    document.body.removeChild(element);
	}
}

//6 MAY 2024 Added by Neeraj to check the device platform is Mac/iPhone/iPad
function isItMacDevice()
{
	if(navigator.platform.search("Mac") >= 0
		|| navigator.platform.search("iPhone") >= 0 
		|| navigator.platform.search("iPad") >= 0 
	)
		return true;
	else
		return false;
}

//Neeraj 11-Sept-2024
function copyToClipboard(asId) 
{
	var lsText	= document.getElementById(asId).innerHTML;
  	navigator.clipboard.writeText(lsText).then( () => {
      alert('Text copied to clipboard successfully!');
    },
    (err) => {
      console.error('Failed to copy text: ', err);
    }
  );
}

//6 MAY 2024 Added by Neeraj to check the device platform is Android
function isItAndroidDevice()
{
	if(navigator.platform.search("Linux") >= 0)
		return true;
	else
		return false;
}

//21 Aug 2024 Added by Neeraj to get Current date Timestamp
function getStdDateTimeStamp()
{
    const date = new Date();
 
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
 
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    const milliseconds = String(date.getMilliseconds()).padStart(1, '0');
 
    const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
    return formattedDateTime;
}

  
function doFunction(method, params = []) 
{
    return new Promise((resolve, reject) => 
    {
        try 
        {
            method(...params); // Call the method with the provided parameters
            resolve(); // Resolve the promise after the method is executed
        } catch (error) {
            reject(error); // Reject the promise if something goes wrong
        }
    });
}

function doPromise(lsaData) 
{
    var liLen = lsaData.length;
    if (liLen === 0) 
    {
        return; // Return if there's nothing to process
    }

    var promiseChain = doFunction(lsaData[0].method, lsaData[0].params); // Start with the first function call

    for (var j = 1; j < liLen; j++) 
    {
        promiseChain = promiseChain.then(() => {
            return doFunction(lsaData[j].method, lsaData[j].params); // Call the custom doFunction for each promise with params
        });
    }

    promiseChain.then(() => {
        console.log("All methods executed!");
    }).catch((error) => {
        console.error("A promise failed:", error);
    });
}
/************************************************************************************************************

// Example JavaScript methods with parameters
function method1(param1) {
    console.log(`Method 1 executed with parameter: ${param1}`);
}

function method2() {
    console.log("Method 2 executed without parameters");
}

function method3(param1, param2, param3, param4, param5) {
    console.log(`Method 3 executed with parameters: ${param1}, ${param2}, ${param3}, ${param4}, ${param5}`);
}

// Example usage:
var lsaData = [
    { method: method1, params: ["Parameter1"] },  // Method 1 with 1 parameter
    { method: method2, params: [] },              // Method 2 with no parameters
    { method: method3, params: ["P1", "P2", "P3", "P4", "P5"] } // Method 3 with 5 parameters
];

doPromise(lsaData);
  
************************************************************************************************************/

//6 MAY 2024 Added by Neeraj to check the device platform is Windows
function isItWindowsDevice()
{
	if(navigator.platform.search("Win") >= 0)
		return true;
	else
		return false;
}

// Added By Arjun For Sugar 474631 On 13 Sept 2024
// Note : If any changes made on below functions please do the same changes on ppWebCommon.js > getSubstringFromStart
function getSubstringFromStart(asNumChars, asText) 
{
	if(asNumChars > asText.length) 
    	return asText; 

    return asText.substring(0, asNumChars);
}

// Added By Arjun For Sugar 474631 On 23 Aug 2024 
// Note : If any changes made on below functions please do the same changes on ppWebCommon.js > packWhereParamforStax
function packWhereParamforStax(asString)
{
	if(asString == null || asString == "") 
		return "";
	var lsWhere="";
	lsWhere = replaceChar(asString,"<=",".le.");
	lsWhere = replaceChar(lsWhere,"^","_caret_");
	lsWhere = replaceChar(lsWhere,"{","_opencurlybracket_");
	lsWhere = replaceChar(lsWhere,"}","_closecurlybracket_");
	lsWhere = replaceChar(lsWhere,"|","_pipe_");
	lsWhere = replaceChar(lsWhere,"[","_openbracket_");
	lsWhere = replaceChar(lsWhere,"]","_closebracket_");
	lsWhere = replaceChar(lsWhere,":","_colon_");
	lsWhere = replaceChar(lsWhere,"<","_lessthan_");
	lsWhere = replaceChar(lsWhere,"`","_grave_");
	lsWhere = replaceChar(lsWhere,"*","_asterisk_");
	lsWhere = replaceChar(lsWhere,"\"","_DQUOTES_");
	lsWhere = replaceChar(lsWhere,"\\","_GT_");
	lsWhere = replaceChar(lsWhere,"~","_tt_");
	lsWhere	= replaceChar(lsWhere,"\'","_SQ_");
	lsWhere = replaceChar(lsWhere,">=",".ge.");
	lsWhere	= replaceChar(lsWhere,"=",".eq.");
	lsWhere	= replaceChar(lsWhere,"%",".pt.");
	lsWhere	= replaceChar(lsWhere,"&","_AMP_");
	lsWhere	= replaceChar(lsWhere,"?",".qm.");
	lsWhere = replaceChar(lsWhere,"#","_hash_");
	lsWhere	= replaceChar(lsWhere," ","_SP_");
	lsWhere = replaceChar(lsWhere,">",".gt.");
	lsWhere	= replaceChar(lsWhere,"+","_plus_");
	lsWhere = replaceChar(lsWhere, "\n", "_NL_");
	lsWhere = replaceChar(lsWhere, "\r", "_CR_");
	return lsWhere;
}

// Added By Arjun For Sugar 474631 On 23 Aug 2024 
//Note : If any changes made on below functions please do the same changes on ppWebCommon.js > unpackWhereParamForStax
function unpackWhereParamForStax(asString)
{
	if(asString == null || asString == "") 
		return "";
	var lsWhere="";
	lsWhere = replaceChar(asString,".le.","<=");
	lsWhere = replaceChar(lsWhere,"_caret_","^");
	lsWhere = replaceChar(lsWhere,"_opencurlybracket_","{");
	lsWhere = replaceChar(lsWhere,"_closecurlybracket_","}");
	lsWhere = replaceChar(lsWhere,"_pipe_","|");
	lsWhere = replaceChar(lsWhere,"_openbracket_","[");
	lsWhere = replaceChar(lsWhere,"_closebracket_","]");
	lsWhere = replaceChar(lsWhere,"_colon_",":");
	lsWhere = replaceChar(lsWhere,"_lessthan_","<");
	lsWhere = replaceChar(lsWhere,"_grave_","`");
	lsWhere = replaceChar(lsWhere,"_asterisk_","*");
	lsWhere = replaceChar(lsWhere,"_DQUOTES_","\"");
	lsWhere = replaceChar(lsWhere,"_GT_","\\");
	lsWhere = replaceChar(lsWhere,"_tt_","~");
	lsWhere	= replaceChar(lsWhere,"_SQ_","\'");
	lsWhere = replaceChar(lsWhere,".ge.",">=");
	lsWhere	= replaceChar(lsWhere,".eq.","=");
	lsWhere	= replaceChar(lsWhere,".pt.","%");
	lsWhere	= replaceChar(lsWhere,"_AMP_","&");
	lsWhere	= replaceChar(lsWhere,".qm.","?");
	lsWhere = replaceChar(lsWhere,"_hash_","#");
	lsWhere	= replaceChar(lsWhere,"_SP_"," ");
	lsWhere = replaceChar(lsWhere,".gt.",">");
	lsWhere	= replaceChar(lsWhere,"_plus_","+");
	lsWhere = replaceChar(lsWhere, "_NL_", "\n");
	lsWhere = replaceChar(lsWhere, "_CR_", "\r");
	return lsWhere;
}