function checkNumLines(elem, max, fld){
	val = elem.value;
	lines = val.split("\n");
	if(lines.length > max){
		alert(fld + " contains more than "+max+" lines which will not display correctly in the generated document.  Please revise");
		elem.focus();
	}
}

entry = false;
function toggleEntry(){
	entry = !entry;
	if(entry){
		Element.show('entry');
		$('resident-id').disabled = true;
	} else {
		Element.hide('entry');
		$('resident-id').disabled = false;
	}
}



function enableFieldsOnSubmit(form){

	for(var i =0; i < form.elements.length; i++){
		form.elements[i].disabled = false;

	}
}

function setSelectValue(selectObj, val){
	for(var i = 0; i < selectObj.options.length; i++){
		if(selectObj.options[i].value == val){
			selectObj.options[i].selected = true;
			break;
		}
	}
}

function checkAll(form){
	for(var i = 0; i < form.elements.length; i++){
		if(form.elements[i].type == "checkbox")
			form.elements[i].checked = true;
	}
}

function uncheckAll(form){
	for(var i = 0; i < form.elements.length; i++){
		if(form.elements[i].type == "checkbox")
			form.elements[i].checked = false;
	}
}

function toggleChecks(el, form){
	for(var i = 0; i < form.elements.length; i++){
		if(form.elements[i].type == "checkbox")
			form.elements[i].checked = el.checked;
	}
}

function id2elem(id) {
	if (typeof(id) != 'string') {
		return id;
	}
	if (document.getElementById) {
		id = document.getElementById(id);
	} else if (document.all) {
		id=document.all[id];
	} else {
		id = null;
	}
	return id;
}

function setButtonWidths(cell_list, button_list)
{
    var w, c, b;
    for(i=0; i<cell_list.length; i++)
    {
	c = document.getElementById(cell_list[i]);
	b = document.getElementById(button_list[i]);
	b.style.width = c.offsetWidth;
	c.style.width = b.offsetWidth;
    }
}

function gotoNopayAdd(){
	opener.location = 'programs.php?p=nopay&atn=add';
	window.close();
}

function closeWindow()
{
	opener.location.reload(true);
	//window.opener.navigate(window.opener.document.location.href);
	window.close();

}

function verify_dx_code(dx){
	var regex = /^\d{3,5}$/;
	return dx.match(regex);
}

function verify_stateid(stateid)
{
	if (stateid.length > 12)
	{
		alert(stateid + "is not a valid state id.");
		return false;
	}
	return true;
}

function verify_npi(npi)
{
    var regex = /^\d{10}$/;     //NPI is a 10-digit number
	return (npi.match(regex) ? true : false);
}

function verify_socialid(ssno)
{
	//SSM must be 9 digits
	var regex = /^\d{3}-\d{2}-\d{4}$/;
	return regex.test(ssno);
}

function verify_medicalid(medicalid)
{
	var regex = /^\w{9,14}$/;
	return medicalid.match(regex);
}

function verify_federalid(federalid)
{
	if (federalid.length > 10 )
		return false;

	return true;
}

function verify_upin(upin)
{
	if (upin.length > 12 || upin.length < 5)
		return false;

	return true;
}

function verify_firstname(firstname)
{
	if (firstname.length == 0)
	{
		alert("You must input a value in the 'First Name' field.");
		return false;
	}
	return true;
}

function verify_lastname(lastname)
{
	if (lastname.length == 0)
	{
		alert("You must input a value in the 'Last Name' field.");
		return false;
	}
	return true;
}

function verify_gender(gender)
{
	if(gender.length == 0)
		return false;
	if(gender != "F" && gender != "M" && gender != "f" && gender != "m")
		return false;

	return true;
}

function verify_name(facname)
{
	if (facname.length == 0)
		return false;

	return true;
}

function isYear (year)
{
    return ((year > 1800) && (year <= 2100))
}

function isMonth (month)
{
    return ((month >= "01") && (month <= "12"))
}

function isDay (day, month, isLeapYear)
{
	if(month == 2 && !isLeapYear)
		return ((day >= "01") && (day <= "28"));

	if(month == 2 && isLeapYear)
		return ((day >= "01") && (day <= "29"));

	if(month == 1 || month == 3 || month ==5 || month == 7 || month == 8
		|| month == 10 || month ==12)
		return ((day >= "01") && (day <= "31"));
	else
		return ((day >= "01") && (day <= "30"));
}

function verify_date(formDate)
{
    //now test to see if its a real date
	var isLeapYear = false;
    var dateArray = new Array();
    dateArray[0] = formDate.substring(0,2);	// month
    dateArray[1] = formDate.substring(3,5);	// day
    dateArray[2] = formDate.substring(6,10);	// year

	//see if its a leap year
	if(dateArray[2].substring(2,4) % 4 == 0)
		isLeapYear = true;

    if (!isYear(dateArray[2]))
	return false;

    if (!isMonth(dateArray[0]))
	return false;

    if (!isDay(dateArray[1], dateArray[0], isLeapYear))
	return false;

    return true;

}

function verify_time(ftime){
	if(ftime.length == 0)
		return false;
	parts = ftime.split(":");
	h = parseInt(parts[0]);
	if(isNaN(h) || h > 23 || h < 0)
		return false;
	m = parseInt(parts[1]);
	if(isNaN(m) || m < 0 || m > 59)
		return false;
	return true;
}

function compareDates(fromDate, toDate)
{
    var fromdateArray = new Array();
    fromdateArray[0] = fromDate.substring(0,2);	// month
    fromdateArray[1] = fromDate.substring(3,5);	// day
    fromdateArray[2] = fromDate.substring(6,10);	// year

    var todateArray = new Array();
    todateArray[0] = toDate.substring(0,2);	// month
    todateArray[1] = toDate.substring(3,5);	// day
    todateArray[2] = toDate.substring(6,10);	// year

    if(fromdateArray[2] <= todateArray[2])
      if(fromdateArray[0] <= todateArray[0])
        if(fromdateArray[1] <= todateArray[1])
	  return true;

	return false;
}

function verify_alphanumeric(n)
{
	var regex = /\w+/;
	return regex.test(n);
}

function verify_numeric(n)
{
    var regex = /^-?(\d+(\.\d{1,2})?|\.\d{1,2})?$/;
    return regex.test(n);
}

function get_element_ref(id)
{
    if(document.all)
	return eval(id);
    else
	return document.getElementById(id);
}

function update_date_text(form_name, id, e)
{
    var DELETE = 8;
    var form = document.forms[form_name];
    var d = form.elements[id];
    dt = d.value.replace(/[^\d]/g, '');
/*    if(id == 'nopay_start' && dt.length > 4)
    	dt.replace(/^(\d\d)\d\d(\d{0,4})$/, "$1"+"01"+"$2"); */
    d.value = "";
    if(dt.length > 0)
    	d.value = dt.substr(0,2);
    if(dt.length > 2)
    	d.value += '/' + dt.substr(2, 2);
    if(dt.length > 4)
    	d.value += '/' + dt.substr(4,4);

}

function update_time_text(form_name, id, e)
{
    var DELETE = 8;
    var form = document.forms[form_name];
    var d = form.elements[id];
    if(d.value.length == 2 && e.keyCode != DELETE)
	d.value += ":";
}

function update_phone_text(form_name, id, e)
{
    var DELETE = 8;
    var form = document.forms[form_name];
    var d = form.elements[id];

    var ph = d.value.replace(/[\D]/g, '');
    d.value = "";
    if(ph.length > 0)
    	d.value = '(' + ph.substr(0,3);
    if(ph.length > 3)
    	d.value += ') ' + ph.substr(3,3);
    if(ph.length > 6)
    	d.value += '-' + ph.substr(6,4);
    if(ph.length > 10)
    	d.value += ' x' + ph.substr(10);

}

function update_ss_text(form_name, id, e){
	var DELETE = 8;
    var form = document.forms[form_name];
    var d = form.elements[id];


    var ph = d.value.replace(/[\D]/g, '');
    d.value = "";
    if(ph.length > 0)
    	d.value = ph.substr(0,3);
    if(ph.length > 3)
    	d.value += '-' + ph.substr(3,2);
    if(ph.length > 5)
    	d.value += '-' + ph.substr(5,4);
}

function validate_login(f){

	if(id2elem('login').value == "") {
		id2elem('login_msg').style.display = 'block';
		id2elem('login_msg').innerHTML = "<font color='red'><b>Please provide a username</b></font>";
		id2elem('login').focus();
		return false;
	}

	if(id2elem('password').value == "") {
		id2elem('login_msg').style.display = 'block';
		id2elem('login_msg').innerHTML = "<font color='red'><b>Please provide a password</b></font>";
		id2elem('password').focus();
		return false;
	}

	id2elem('login_msg').style.display = 'none';
	//f.submit();
	return true;
}


// AJAX FUNCTIONS
function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

function do_upd(updtype, id, fieldname, fieldvalue) {

	var parms = 't='+updtype+'&id='+id+'&f='+fieldname+'&v='+fieldvalue;
	showLoading(id);
	http = createRequestObject();
	http.open('get','update_rec.php?'+parms);
	http.onreadystatechange = handleUpdResponse;
	http.send(null);
}

function handleUpdResponse(responseCode) {
	if(http.readyState == 4){
		//alert("response was: " + http.responseText);
        showUpdResponse(http.responseText);
    }
}

function showUpdResponse(responseCode) {
	var retvals = responseCode.split("|"); // create array
	if (retvals[1] == 1) {
		// Success...
		//alert("Good News - UPDATED");
		showSuccess(retvals[0]);
	} else {
		// Failure...
		//alert("Bad News - There was an error!");
		showError(retvals[0]);
	}
}

function showLoading(id) {
	//alert('msg_'+id+' status_'+id);
	$('msg_'+id).style.display = 'block';
	$('status_'+id).style.display = 'block';
	$('status_'+id).innerHTML = '<img src="images/loading.gif" width="18" height="18" border="0" align="absmiddle">';
	//$('status_'+id).style.background = "url('images/loading.gif') top left no-repeat";
}

function showError(id) {
	//alert('msg_'+id+' status_'+id);
	$('msg_'+id).style.display = 'block';
	$('status_'+id).style.display = 'block';
	$('status_'+id).innerHTML = '<img src="images/alert.gif" width="18" height="18" border="0" align="absmiddle">';
	//$('status_'+id).style.background = "url('images/alert.gif') top left no-repeat";
}

function showSuccess(id) {
	//alert('msg_'+id+' status_'+id);
	$('msg_'+id).style.display = 'block';
	$('status_'+id).style.display = 'block';
	$('status_'+id).innerHTML = '<img src="images/checkmark.gif" width="18" height="18" border="0" align="absmiddle">';
	//$('status_'+id).style.background = "url('images/checkmark.gif') top left no-repeat";
}

// No-Pay Bills :: Functions

function reactivateNoPays(){
	var form = id2elem("nopay_activate");

    var chk_count = 0;

    for(var i=0; i < form.elements.length;  i++){
		if(form.elements[i].type == "checkbox" && form.elements[i].checked){
		    chk_count++;
		}
    }
	if(chk_count > 0)
		form.submit();
	else
		alert('No records selected for reactivation');
}

function update_nopay(type) {
    var form = id2elem("form_nopay");

    var resident_list = new Array();
    var chk_count = 0;
    var j = 0;


    for(var i=0; i < form.elements.length;  i++){
		if(form.elements[i].name != 'chk_all' && form.elements[i].type == "checkbox" && form.elements[i].checked){
		    chk_count++;
		    resident_list[j++] = form.elements[i].value;
		}
    }

    var w_attr = "titlebar=false,menubar=false,scrollbars=false,toolbar=false,width=550,height=250,resizable=yes,status=no";

    switch(type){
	case "new":
	    if(w_update) w_update.close();
	    w_update = window.open("NopayAdd.php","main", w_attr);
	    break;

	case "delete":
		var msg = "";
		if(chk_count > 0){
			if(chk_count > 1)
					msg = "Delete these " + chk_count + " no pay claims?";
			    else
					msg = "Delete this no pay claim?";
			    if(window.confirm(msg)){
					var s = "";
					for(var i=0; i < j; i++)
					    s += resident_list[i] + "_";
					//window.location.href="programs.php?p=nopay&atn=list&action=delete&dlist="+s;
					form.submit();
			    }
		    } else {
		    	alert("No No Pays selected to delete.");
		    }
		break;

	case 'modify':
	    if(chk_count == 1){
			if(w_update) { w_update.close() }
			w_update = window.open("NopayModify.php?nopay_id="+resident_list[0],"main", w_attr);
	    } else {
			if(chk_count > 1)
			    alert("Can't modify more than one record at a time");
			else
			    alert("Nothing selected to modify");
	    }
	    break;
    }
}

function update_eligibility2(type) {
    var form = id2elem("form_eligibility");

    var resident_list = new Array();
    var chk_count = 0;
    var j = 0;


    for(var i=0; i < form.elements.length;  i++){
		if(form.elements[i].name != 'chk_all' && form.elements[i].type == "checkbox" && form.elements[i].checked){
		    chk_count++;
		    ar = form.elements[i].id.split('_');
		    resident_list[j++] = ar[1];
		}
    }

    var w_attr = "titlebar=false,menubar=false,scrollbars=false,toolbar=false,width=550,height=250,resizable=yes,status=no";

    switch(type){
	case "new":
	    if(w_update) w_update.close();
	    w_update = window.open("ModifyMediCalEligibility2.php","main", w_attr);
	    break;

	case "delete":
		var msg = "";
		if(chk_count > 0){
			if(chk_count > 1)
					msg = "Remove these " + chk_count + " Medi Cal Eligibility Checks?";
			    else
					msg = "Remove this Medi Cal Eligibility Check?";
			    if(window.confirm(msg)){
					var s = "";
					for(var i=0; i < j; i++)
					    s += resident_list[i] + "_";
					//window.location.href="programs.php?p=nopay&atn=list&action=delete&dlist="+s;
					form.submit();
			    }
		    } else {
		    	alert("No Medi Cal Eligibility Checks selected to remove.");
		    }
		break;

	case 'modify':
	    if(chk_count == 1){
			if(w_update) { w_update.close() }
			w_update = window.open("ModifyMediCalEligibility2.php?resident_id="+resident_list[0],"main", w_attr);
	    } else {
			if(chk_count > 1)
			    alert("Can't modify more than one record at a time");
			else
			    alert("Nothing selected to modify");
	    }
	    break;
    }
}


function checkmenp(id){
	id2elem(id).checked = true;
}

function clearForm(form){
	for(i = 0; i < form.elements.length; i++){
		if(form.elements[i].type == "text")
			form.elements[i].value = "";
	}

}

function getResidentEligibilityRecord2(res_id){
	form = document.forms[0];
	dis = new Array('dob', 'medcal_card_date', 'medi_cal_id');
	disableFormFields(dis, form);
	httpd = createRequestObject();
	httpd.open("get", "rpc/getResidentEligibilityRecord2.php?resident_id="+res_id);
	httpd.onreadystatechange = handleEligRecResponse;
	httpd.send(null);
}

function handleEligRecResponse(){
	if(httpd.readyState == 4){
		var vals = new Array();
		var retpairs = httpd.responseText.split('&');
		for(var i = 0; i < retpairs.length; i++){
			ar = retpairs[i].split('=');
			vals[ar[0]] = ar[1];
		}
		form = document.forms[0];
		for(ind in vals){
			form.elements[ind].value = vals[ind];
		}
	}
	enableFormFields(dis, document.forms[0]);
}

function disableFormFields(ar, form){
	for( var i = 0; i < ar.length; i++){
		form.elements[ar[i]].disabled = true;
	}
}

function enableFormFields(ar, form){
	for( var i = 0; i < ar.length; i++){
		form.elements[ar[i]].disabled = false;
	}
}

function checkNopayStartDate(from_dt){
	if(facility_nopay_start_date != '')
		return compareDates(facility_nopay_start_date, from_dt);
	return true;
}

function checkRequiredFields(form, fields){
	for(fld in fields){
		if(fld == 'resident_id'){
			if(form[fld].disabled){
				if(form['first_name'].value.length == 0){
					alert('Please enter First Name');
					return false;
				}
				if(form['last_name'].value.length == 0){
					alert('Please enter Last Name');
					return false;
				}
				if(form['medicare_hic'].value.length == 0){
					alert('Please enter Medicare HIC');
					return false;
				}
			} else {
				if(form.resident_id.value.length == 0){
					alert('Please Choose a patient');
					return false;
				}
			}
		} else {
			if(form[fld].value.length == 0){
				alert("Please enter a value for "+fields[fld]);
				return false;
			}
		}
	}
	return true;
}

function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function URLDecode(encoded )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef";
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2)
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
};

function getDollarValue(n){
	if(parseInt(n) == n && n.indexOf(".") < 0)
		return n + ".00";
	if(n.indexOf(".") >= 0){
		var a = n.split(".");
		if(a[1].length == 1) a[1] += "0";
		return a[0] + "." + a[1];
	}

	return n;
}

/* 
 * =============================================================================
 * Element position size functions
 * =============================================================================
 */
var POS_WINDOW_CENTER	= 1;
var POS_PARENT_CENTER	= 2;
var POS_OBJ_OFFSET		= 3;
/*
  positionPopupDiv()
  -positions obj in the center of the parent object's area
*/
function positionPopupDiv(obj, width, height, parent){
    var windowheight;
    if(parent == null) {
	windowheight = getWindowHeight();
	parent = document.body;
    }
    else
	windowheight = parent.clientHeight;

    var left = getElementLeft(parent) + (parent.clientWidth - width) / 2;
    var top = (document.all ? parent.scrollTop : window.pageYOffset) + (windowheight - height) / 2;

    if(width) obj.style.left = left + 'px';
    if(height) obj.style.top = top + 'px';
}

function positionObject(obj, width, height, parent, positionType, offset_x, offset_y){
    var windowheight;
    if(parent == null) {
		windowheight = getWindowHeight();
		parent = document.body;
    }
    else
		windowheight = parent.clientHeight;

    var top, left;
    switch(positionType){
	case POS_WINDOW_CENTER:
	    left = getElementLeft(parent) + (parent.offsetWidth - width) / 2;
	    top = (document.all ? parent.scrollTop : window.pageYOffset) + (windowheight - height) / 2;
	    break;
	case POS_PARENT_CENTER:
	    left = getElementLeft(parent) + (parent.offsetWidth - width) / 2;
	    top = getElementTop(parent) + (windowheight - height) / 2;
	    break;
	case POS_OBJ_OFFSET:
		left = getElementLeft(parent) + offset_x;
		top  = getElementTop(parent) + getElementHeight(parent) + offset_y;
		break;
    }

    if(width) obj.style.left = left + 'px';
    if(height) obj.style.top = top + 'px';
	obj.style.display = "block";
}

function getElementWidth(p_elm){
  var elm;
  if (p_elm)
  {
	 if(typeof(p_elm) == "object"){
		elm = p_elm;
	 } else {
		elm = document.getElementById(p_elm);
	 }
	 return parseInt(elm.offsetWidth);
  }
  return 0;
}

function getElementRight(p_elm){
    return getElementLeft(p_elm) + getElementWidth(p_elm);
}

function getElementTop(p_elm) {
    var y = 0;
    var elm;
    if(typeof(p_elm) == "object"){
	elm = p_elm;
    } else {
	elm = document.getElementById(p_elm);
    }
    while (elm != null) {
	y+= elm.offsetTop;
	elm = elm.offsetParent;
    }
    return parseInt(y);
}

function getElementLeft(p_elm) {
    var x = 0;
    var elm;
    if(typeof(p_elm) == "object"){
	elm = p_elm;
    } else {
	elm = document.getElementById(p_elm);
    }
    while (elm != null) {
	x+= elm.offsetLeft;
	elm = elm.offsetParent;
    }
    return parseInt(x);
}
function getElementHeight(p_elm){
    var elm;
    if(typeof(p_elm) == "object"){
	elm = p_elm;
    } else {
	elm = document.getElementById(p_elm);
    }
    return parseInt(elm.offsetHeight);
}

function getElementBottom(p_elm){
    return getElementTop(p_elm) + getElementHeight(p_elm);
}

function getElementsByClassName(oElm, strTagName, strClassName){
  var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
  var arrReturnElements = new Array();
  strClassName = strClassName.replace(/\-/g, "\\-");
  var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
  var oElement;
  for(var i=0; i<arrElements.length; i++){
	 oElement = arrElements[i];
	 if(oRegExp.test(oElement.className)){
		arrReturnElements.push(oElement);
	 }
  }
  return (arrReturnElements)
}


function isInside(p_elm, x, y){
    var elm;
	 if (p_elm)
	 {
		if(typeof(p_elm) == "object"){
		  elm = p_elm;
		} else {
		  elm = document.getElementById(p_elm);
		}

		return (
			 x >= getElementLeft(elm) && 
			 x <= getElementRight(elm) &&
			 y >= getElementTop(elm) && 
			 y <= getElementBottom(elm)
			 );
	 }
	return false;
}

function getWindowHeight()
{
  if (parseInt(navigator.appVersion)>3) {
	 if (navigator.appName=="Netscape") {
		return window.innerHeight;
	 }
	 if (navigator.appName.indexOf("Microsoft")!=-1) {
		return document.body.offsetHeight;
	 }
  }

}

function getWindowWidth()
{
  if (parseInt(navigator.appVersion)>3) {
	 if (navigator.appName=="Netscape") {
		return window.innerWidth;
	 }
	 if (navigator.appName.indexOf("Microsoft")!=-1) {
		return document.body.offsetWidth;
	 }
  }

}

function getDateStr(d){
    var y = d.getYear() + (d.getYear() < 1900 ? 1900 : 0);
    var m = d.getMonth() + 1;
    var d = d.getDate();

    if(m < 10) m = "0" + m;
    if(d < 10) d = "0" + d;

    return m + "/" + d + "/" + y;
}

w_update = null;
