var giCurrentRowID;
var giCurrentRowFullID;
var giRecordID=0;
var bypassDirty = false;
var bypassGridClick = false;
var floatStart = 0;
var bugOffset = 0;
var gFlashTimer = null;
var FlashColor =  '#FFCF00'; //'#A4CE8A';
var gFlashCount = 0
var OrigColor = null;
var PrevColor = null;
var RowHighlightColor = '#e8e8e8';
var GridClickTarget = '';
var QueryModule = '';
var QueryKey = '';
var QueryReturn = '';
var gHelpMapID = 0;
var gWebCombos = new Array();
var gPosting=false;
var PageLoaded=false;
var bypassLoader=false;
var globalPCSLoader=null;
var globalTimer=null;

window.onscroll= doOnScroll;
window.onerror = handleError;

addEvent(window,'load',doOnLoad);
window.onbeforeunload = doBeforeUnload;
window.onunload=doUnload;

function editImage(path){
	mnuToolbar.HideAll();
    popToolbar.Show('winStandardScroll','../shared/imageeditor.aspx?path=' + path,600,500,'Image Editor');
}

function DrillUp(){
	window.location=PageProperties.DrillUpPath;
}

//This runs for every page and allows pages to reference the querystring
//using familiar notation ex: alert(QueryString['id'])
var QueryString = new Array();
var qs = location.search.substring(1).split("&");
for(i=0;i<qs.length;i++)
{
    t = qs[i].split("=")
	if(t[0] && t[1])
	{
		QueryString[t[0].toLowerCase()] = unescape(t[1]);
	}
}

function PageProperties(){
	this.RecordID=0;
	this.HelpMapID=0;
}
PageProperties.prototype.Init=function (props){
    for (var prop in props){
        this[prop]=props[prop];   
    }
}

function doOnLoad() 
{
	if(PageLoaded) return;
	PageLoaded=true;
	if (document.getElementById('divFloatToolbar')) floatStart = document.getElementById('divFloatToolbar').offsetTop;
	if (floatStart >= 150){
		floatStart -= 100;
		bugOffset = 100;
	}
	if (typeof(JSFX_FloatDiv) != 'undefined' && dgi('divFloatToolbar')) JSFX_FloatDiv('divFloatToolbar', 0,0).floatIt();
	if (dgi(PageProperties.ToolbarClientID + '_hdnScrollTop')) document.body.scrollTop = dgi(PageProperties.ToolbarClientID + '_hdnScrollTop').value;
	if (typeof(refreshNav) != 'undefined') refreshNav();
	
}
function doBeforeUnload(){
	try{
		if(bypassLoader) return;
		if(!typeof(PCSLoader)=='function') return;
		if(!PageProperties) return;
		if(PageProperties.PublicPage) return;
		if(PCSLoadersVisible()) return;
		globalPCSLoader = new PCSLoader('body','Loading...',null,null,true);
		globalPCSLoader.Show();
		//this will hide any global loaders that shouldn't have been shown and could be blocking
		//globalTimer = setTimeout(function(){globalPCSLoader.Hide();},5000);
	} catch(e){}
}
function doUnload(){
	// if this is a true window unload and not a download or local link, then cancel the auto hide of the loader
	//clearTimeout(globalTimer);
}
function dgi(objid){return document.getElementById(objid);}
function doOnScroll(){if (dgi(PageProperties.ToolbarClientID + '_hdnScrollTop')) dgi(PageProperties.ToolbarClientID + '_hdnScrollTop').value = document.body.scrollTop;}

function setDirty(){
	if(!dgi(PageProperties.ToolbarClientID + '_hdnIsDirty')) return;
	dgi(PageProperties.ToolbarClientID + '_hdnIsDirty').value = '1';
}

function initDetectChanges() {
	for(var i=0;i<document.all.length; i++)
	{
		if (! document.all[i].type) continue;
		if(document.all[i].changes || 
			(document.all[i].type == 'text' || document.all[i].type == 'select-one' || document.all[i].type == 'select-multiple' ||
			document.all[i].type == 'textarea' || document.all[i].type == 'select' ||
			document.all[i].type == 'checkbox' || document.all[i].type == 'radio'))
		{
			if(document.all[i].type == 'checkbox'){
				var ev = document.all[i].onclick;
				if (typeof(ev) == "function" ) {            
					ev = ev.toString();
					ev = ev.substring(ev.indexOf("{") + 1, ev.lastIndexOf("}"));
				}
				else {
					ev = "";
				}
				if(ev.substr(ev.length-2,1) != ';') ev = ev + ';'
				var func = new Function(ev + " setDirty();");
				document.all[i].onclick = func;
			}else{
				var ev = document.all[i].onchange;
				if (typeof(ev) == "function" ) {            
					ev = ev.toString();
					ev = ev.substring(ev.indexOf("{") + 1, ev.lastIndexOf("}"));
				}
				else {
					ev = "";
				}
				if(document.all[i].id!='txtSSN'){
				var func = new Function("setDirty(); " + ev);
				document.all[i].onchange = func;
				//if(document.all[i].id=='txtSSN'){
				//	alert(document.all[i].onchange);
				//}
				}
			}
		}	
	}
}

function handleError(description,page,line) {
	if (description == 'Unspecified error.') return true;
}
function doOnBeforeUnload()
{
	var isDirty = (dgi(PageProperties.ToolbarClientID + '_hdnIsDirty').value == '1' ? true : false);
	if (isDirty==true && bypassDirty == false){
		window.event.returnValue = 'Changes were detected on this page. All changes will be lost if you continue.'
	}
}
function callbackError(arg,callbackid)
{
	if(dgi('lblErrorMessage')){
		dgi('lblErrorMessage').innerHTML = arg;
	}else if (dgi(PageProperties.NavigatorClientID + '_lblErrorMessage')){
		dgi(PageProperties.NavigatorClientID + '_lblErrorMessage').innerHTML = arg;
	}else if (dgi(PageProperties.ToolbarClientID + '_lblErrorMessage')){
		dgi(PageProperties.ToolbarClientID + '_lblErrorMessage').innerHTML = arg;
	}else{
		if (dgi('lblErrorMessage')) dgi('lblErrorMessage').innerHTML = arg;
	}
		var cb = window[callbackid];
	if(cb.Loaders){
		for(var i=0;i<cb.Loaders.Controls.length;i++){
			cb.Loaders.Controls[i].Reposition();
		}
	}
	if(arg.toLowerCase().left(6) == 'error:' || arg.toLowerCase().left(8) == 'warning:' || arg.toLowerCase().left(12) == 'concurrency:'){
		alert(replaceAll(arg,'<BR>','\n'));
	}
}

function setCookie(cookieName,cookieValue,nDays)
{
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName + "=" + escape(cookieValue) + ";expires="+expire.toGMTString();
}
function readCookie(cookieName)
{
	var theCookie=""+document.cookie;
	var ind=theCookie.indexOf(cookieName);
	if (ind==-1 || cookieName=="") return ""; 
	var ind1=theCookie.indexOf(';',ind);
	if (ind1==-1) ind1=theCookie.length;
	return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

function getDateTime()
{
	var now = new Date()
	var Month = now.getMonth() + 1
	var Day = now.getDate()
	var Year = now.getFullYear()
	var Hours = now.getHours()
	var Minutes = now.getMinutes()
	var Seconds = now.getSeconds()
	var theDate = Month + "/" + Day + "/" + Year;
	var theTime = theDate + " " +
		((Hours > 12) ? Hours - 12 : Hours) + 
		((Minutes < 10) ? ":0" : ":") + Minutes + ((Seconds < 10) ? ":0" : ":") + Seconds + 
		((Hours > 12) ? " PM" : " AM")
	return theTime;	
}
function getTodaysDate()
{
	var now = new Date()
	var Month = now.getMonth() + 1
	var Day = now.getDate()
	var Year = now.getFullYear()
	var theDate = Month + "/" + Day + "/" + Year;	
	return theDate;
}
function convertDate(dDate)
{
	var Month = dDate.getMonth() + 1
	var Day = dDate.getDate()
	var Year = dDate.getFullYear()
	var theDate = Month + "/" + Day + "/" + Year;	
	return theDate;
}
function convertDate2(theDate)
{
	var Month = theDate.getMonth() + 1
	if(Month.toString().length == 1) Month = '0' + Month.toString();	
	var Day = theDate.getDate()
	if(Day.toString().length == 1) Day = '0' + Day.toString();
	var Year = theDate.getFullYear()
	return Month + "/" + Day + "/" + Year;
}

function daysInMonth(dDate){
	var aNumDays = Array (31,0,31,30,31,30,31,31,30,31,30,31);
	var monthSelected = dDate.getMonth();
	var yearSelected = dDate.getFullYear();
	var startDate = new Date(yearSelected,monthSelected,1);
	var endDate;
	if (monthSelected==1) {
		endDate = new Date (yearSelected,monthSelected+1,1);
		endDate = new Date (endDate - (24*60*60*1000));
		numDaysInMonth = endDate.getDate();
	} else {
		numDaysInMonth = aNumDays[monthSelected];
	}
	return numDaysInMonth;
}
function openNewScrollableWindow(newWindow, w, h)
{
	var popUp;
	popUp = window.open(newWindow, 'popupwindow', 'width=' + w + ',height=' + h + ', left=' + getLeftCoord(w) + ', top=' + getTopCoord(h) +
		', ' + 'scrollbars=yes, status=yes, sizable=yes, resizable');
	popUp.focus();
}
function getLeftCoord(w)
{
	return (screen.availWidth - w - 10) * .5
}
function getTopCoord(h)
{
	return (screen.availHeight - h - 30) * .5
}
function regular(string, regExp){
	return (string.search(regExp) != -1 ? true : false);
}
function replaceAll( str, from, to ) {
	var idx = str.indexOf( from );
	while ( idx > -1 ) {
		str = str.replace( from, to ); 
		idx = str.indexOf( from );
	}
	return str;
}
function sf(ctrl)
{
	if (!dgi(ctrl)) return;
	try
	{
		bypassFocus=true;
		dgi(ctrl).focus();
	}catch (e){}
	
}
// Pass in any select based control (listbox, dropdown) and a value and
// this will look thru it and select the item based on the value
function setSelectedValue(lst,value)
{
	if(value=='')
	{
		lst.selectedIndex = -1;
		return;
	}
	for(i=0;i<lst.options.length;i++)
	{
		if(lst.options[i].value == value)
		{
			lst.selectedIndex = i;
			return
		}
	}
}
function showReport(path)
{
	var strOptions = "menubar=yes,status=yes,resizable=yes,scrollbars=yes,toolbar=no";
	var popup = window.open(path, 'reportwindow', strOptions);
	popup.focus();
}
function fnTrapKD(btnName)
{
	if (document.all)
	{
		var btn = document.getElementById(btnName);
		
		if (event.keyCode == 13)
		{
			event.returnValue=false;
			event.cancel = true;
			btn.click();
		}
	}
}
function showHelp(mapid){
	if(mapid==null) mapid=0;
	if (PageProperties.IsAgency){
		RH_ShowHelp(0,'../help/agency/credentiallink_help.htm',(mapid > 0 ? HH_HELP_CONTEXT : HH_DISPLAY_TOC),mapid);
	}else if (PageProperties.IsFacility){
		RH_ShowHelp(0,'../help/facility/credentiallink_facility_help.htm',(mapid > 0 ? HH_HELP_CONTEXT : HH_DISPLAY_TOC),mapid);
	}else{
		alert('Not Available');
	}
}
function showTutorials(){
	if (PageProperties.IsAgency){
		showReport('../tutorials/agency/mainmenu.htm');
	}else if (PageProperties.IsFacility){
		alert('Not Available');
	}else{
		alert('Not Available');
	}
}
function doAddCode(cboid, codeKey){
	
	var strOptions = "dialogHeight: 450px; dialogWidth: 500px; edge: Raised; center: Yes; help: No; resizable: Yes; status: Yes;";
	var myArgs = window.showModalDialog("../Setup/CodesQuickAdd.aspx?codekey=" + codeKey + "&id=0", null, strOptions);
	if (myArgs == null) return;
	setTimeout("doPostback('RefreshCode','" + cboid + "," + codeKey + "')", 100);
}

function doPostback(eventTarget, eventArgument, formname, action) {
	var theform;
	if(gPosting) return;
	if(formname != null){
		theform = document.forms[formname];
	}else{
		theform = document.forms[0];
	}
	if(action){
		theform.action = action;
		theform.__VIEWSTATE.name = 'NOVIEWSTATE';
	}
    if (!dgi('__EVENTTARGET')){
		theform.insertAdjacentHTML("afterBegin","<INPUT type='hidden' name='__EVENTTARGET'><INPUT type='hidden' name='__EVENTARGUMENT'>");	
	}
	if (eventArgument == null) eventArgument = '';
	theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
    theform.__EVENTARGUMENT.value = eventArgument;
    gPosting=true;
    theform.submit();
}

function Pause(millis) 
{
	date = new Date();
	var curDate = null;

	do { var curDate = new Date(); } 
	while(curDate-date < millis);
} 

function flashRow(rowid)
{	
	var row = dgi(rowid)
	if (!row) return;
	if (!OrigColor)
		if (OrigColor != '') OrigColor = row.style.backgroundColor
		
	if (gFlashTimer == null)
	{
		row.style.backgroundColor = FlashColor;
		gFlashTimer = setInterval('flashRow(\'' + rowid + '\')',200);
	}else
	{
		if (gFlashCount > 2)
		{
			window.clearInterval(gFlashTimer);
			gFlashTimer=null;
			gFlashCount=0;
			row.style.backgroundColor = OrigColor;
		}else
		{
			row.style.backgroundColor = (gFlashCount % 2 == 0 ? OrigColor : FlashColor);
			gFlashCount ++;
		}
	}
}

function scannerSettings(ScannerPrefix, allowsingle, allowmultisingle, allowmultipdf){
	var strCustom = readCookie(ScannerPrefix + 'Custom');
	var strResolution = readCookie(ScannerPrefix + 'Resolution');
	var strColor = readCookie(ScannerPrefix + 'Color');
	var strWidth = readCookie(ScannerPrefix + 'Width');
	var strHeight = readCookie(ScannerPrefix + 'Height');
	var strMultiPage = readCookie(ScannerPrefix + 'MultiPage');
	var strFileFormat = readCookie(ScannerPrefix + 'FileFormat');
	var myArgs = new Array();
	myArgs[0] = strCustom;
	myArgs[1] = strMultiPage;
	myArgs[2] = strWidth;
	myArgs[3] = strHeight;
	myArgs[4] = strResolution;
	myArgs[5] = strColor;
	myArgs[6] = strFileFormat;
	var strQueryString = 'allowsingle=' + (allowsingle ? '1' : '0') + '&allowmultisingle=' + (allowmultisingle ? '1' : '0') + '&allowmultipdf=' + (allowmultipdf ? '1' : '0')
	var strOptions = "dialogHeight: 400px; dialogWidth: 500px; edge: Raised; center: Yes; help: No; resizable: Yes; status: Yes;";
	var myArgs = window.showModalDialog("../shared/ScannerSettings.aspx?" + strQueryString, myArgs, strOptions);
	if(myArgs==null) return;
	setCookie(ScannerPrefix + 'Custom',myArgs[0],999);
	setCookie(ScannerPrefix + 'MultiPage',myArgs[1],999);
	setCookie(ScannerPrefix + 'Width',myArgs[2],999);
	setCookie(ScannerPrefix + 'Height',myArgs[3],999);
	setCookie(ScannerPrefix + 'Resolution',myArgs[4],999);
	setCookie(ScannerPrefix + 'Color',myArgs[5],999);
	setCookie(ScannerPrefix + 'FileFormat',myArgs[6],999);
}

function toggleEnabled(id,val,grayborders)
{
	var elem;
	if(typeof(id)=='string'){
		elem = dgi(id);
	}else{
		elem = id;
	}
		
	if(grayborders==null || grayborders=='undefined') grayborders = false;
	if (elem != null){
		switch(elem.tagName.toUpperCase()){
			case 'INPUT':
				if(elem.type.toUpperCase() == 'CHECKBOX'){
					elem.disabled=!val;
				}else if(elem.type.toUpperCase() == 'RADIO'){
					elem.disabled=!val;
				}else{
					if (val){
						//elem.onfocus = null;
						removeEvent(elem,'focus',function(){this.blur()});
						elem.style.color = '';
						elem.style.borderColor='';
						elem.style.borderStyle='';
						elem.style.borderWidth='';
						elem.tabIndex = elem.prevTabIndex;
						if(grayborders){
							elem.style.marginTop='';
							elem.style.marginBottom='';
						}
						elem.disabled=!val;
					}
					else{
						addEvent(elem,'focus',function(){this.blur()});
						//elem.onfocus = function preventFocus(e) { this.blur(); };
						if(elem.tabIndex > -1) elem.prevTabIndex = elem.tabIndex;
						elem.tabIndex = -1;
						elem.style.color = 'gray';
						if(grayborders){
							elem.style.borderColor='#D0D0BF';
							elem.style.borderStyle='solid';
							elem.style.borderWidth='1px';
							elem.style.marginTop='1px';
							elem.style.marginBottom='1px';
						}
					}
				}
				break;
			case 'WEBCOMBO':
				elem.enabled=(val ? 'True' : 'False');
				break;
			case 'TEXTAREA':
				elem.disabled=!val;
				break;
		}
	}
}

function strltrim() {return this.replace(/^\s+/,'');}
function strrtrim() {return this.replace(/\s+$/,'');}
function strtrim() {return this.replace(/^\s+/,'').replace(/\s+$/,'');}
function strLeft(n){
	if(!this || this=='') return '';
	if (n <= 0)
	    return "";
	else if (n > String(this).length)
	    return str;
	else
	    return String(this).substring(0,n);
}
function strRight(n){
	if(!this || this=='') return '';
    if (n <= 0)
       return "";
    else if (n > String(this).length)
       return this;
    else {
       var iLen = String(this).length;
       return String(this).substring(iLen, iLen - n);
    }
}
function isNumeric(RegExp){
	if(!RegExp) RegExp = /^(\d*)(\.?)(\d*)$/;
	return String(this).match(RegExp) != null
}
function formatCurrency(num) {
	if(!num) num=String(this);
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

String.prototype.ltrim = strltrim;
String.prototype.rtrim = strrtrim;
String.prototype.trim = strtrim;
String.prototype.left = strLeft;
String.prototype.right = strRight;
String.prototype.isNumeric = isNumeric;
String.prototype.formatCurrency = formatCurrency;
String.prototype.replaceAll=strReplaceAll;

function strReplaceAll(from,to){
	return replaceAll(String(this),from,to);
}
function convertToMinutes(sec){
	min = Math.floor(sec/60);
	sec = sec % 60;
	if(sec < 10) sec='0'+sec;
	if(min < 10) min = '0' + min;
	return min + ':' + sec;
}
function addEvent(obj, evType, fn)
{
	var evTypeRef = '__' + evType;
	if (obj[evTypeRef]){
		if (this.array_search(fn, obj[evTypeRef]) > -1) return;
	}else{
		obj[evTypeRef] = [];
		if (obj['on'+evType]) obj[evTypeRef][0] = obj['on'+evType];
		obj['on'+evType] = this.handleEvent;
		//if (obj[evType]) obj[evTypeRef][0] = obj[evType];
		//obj[evType] = this.handleEvent;
	}
	obj[evTypeRef][obj[evTypeRef].length] = fn;
}

function removeEvent(obj, evType, fn)
{
	var evTypeRef = '__' + evType;
	if (obj[evTypeRef]){
		var i = this.array_search(fn, obj[evTypeRef]);
		if (i > -1) delete obj[evTypeRef][i];
	}
}

function handleEvent(e)
{
	e = e || window.event;
	var evTypeRef = '__' + e.type, retValue = true;

	for (var i = 0, j = this[evTypeRef].length; i < j; i++){
		if (this[evTypeRef][i]){
			this.__fn = this[evTypeRef][i];
			retValue = this.__fn(e) && retValue;
		}
	}

	if (this.__fn) try { delete this.__fn; } catch(e) { this.__fn = null; }

	return retValue;
}

function array_search(val, arr)
{
	var i = arr.length;
	while (i--){
		if (arr[i] && arr[i].toString() == val.toString()){
			break;
		}
	}
	return i;
}

function setHTML(args,context,outer) { 
	if(typeof(context) != 'object') context = document.getElementById(context);
	if(context.tagName == 'INPUT'){
		context.value=args;
	}else{
		if(outer){
			context.outerHTML=args;
		}else{
			context.innerHTML=args;
		}
	}
    var search = args; 
    var script; 
    var is_singleq = 0; var singleq = "'"; 
    var is_doubleq = 0; var doubleq = '"'; 
    var is_escaped = 0; var escap = "\\"; 
    var layer = 0; 
    while( script = search.match(/(<script>|<script type='javascript'>|<script type=javascript>\s*(<!--)?)/)) { 
		search = search.substr(search.indexOf(RegExp.$1) + RegExp.$1.length); 
		if (!(endscript = search.match(/((-->)?\s*<\/script>)/))) break; 
    
		block = search.substr(0, search.indexOf(RegExp.$1)); 
    
		search = search.substring(block.length + RegExp.$1.length); 
        
		while(func = block.match(/(function(.+?)\((.*?)\)\s*\{)/)) { 
			eval(block.substr(0,block.indexOf(RegExp.$1))); 
			// for evaluating non functions 
        
			block = block.substr(block.indexOf(RegExp.$1) + RegExp.$1.length); 
			name = RegExp.$2; 
			param = RegExp.$3; 
	        
			is_singleq = 0; 
			is_doubleq = 0; 
			is_escaped = 0; 
			layer = 0; 
        
			for(i=0;i<block.length;i++) { 
				c = block.substr(i,1); 
	            
				if ((is_singleq || is_doubleq) && is_escaped) { 
					is_escaped = 0; 
				} else if (!is_doubleq && (c==singleq)) { 
					is_singleq = !is_singleq; 
				} else if (!is_singleq && (c==doubleq)) { 
					is_doubleq = !is_doubleq; 
				} else if ((is_singleq || is_doubleq) && (c==escap)) { 
					is_escaped = 1; 
				} else if ( c=="{") { 
					layer++; 
				} else if ( c=="}") { 
					if ( layer==0 ) { 
					break; 
					} 
					layer--; 
				} 
			} 
	        
			code = block.substr(0,i-1); 
			block = block.substr(i+1); 
	        
			code = code.replace(/\n/g, '\\n'); 
			code = code.replace(/\r/g, '\\r'); 
			code = code.replace(/'/g,"\\'"); 
	        
			eval(name + " = new Function('"+param+"','"+code+"');"); 
		} 
		eval(block); // for evaluating non functions 
	}
} 

function SL_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=SL_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function SL_swapImgRestore() { //v3.0
  var i,x,a=document.SL_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function SL_swapImage() { //v3.0
  var i,j=0,x,a=SL_swapImage.arguments; document.SL_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	if ((x=SL_findObj(a[i]))!=null){
		document.SL_sr[j++]=x;
		if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];
	}
}