helpFile = "Chart_Identification.htm";
var numAcctOptions = 1;
var newWnd = null;
var isBodyLoaded = false;
var PatientUid = iMedica.Patient.PatientUid;

function init1()
{
	initDesktop();

	var GetPatientURL = "../GetPatient.aspx" + window.location.search;

	//This is debug code, it can be thrown away.
	//try {
//		if(AGetPatient != null) {
//			AGetPatient.href = GetPatientURL + "&IE_WORKAROUND=.xml";
//			AGetPatient.innerText = GetPatientURL;
//		}
	//catch(ex) {}

	personDemographicsXML.loadXML(iMedica.Patient.PatientDemographicXML);
    accountXML.loadXML(iMedica.Patient.PatientAccountXML);
    contactXML.loadXML(iMedica.Patient.PatientContactXML);
    employmentXML.loadXML(iMedica.Patient.PatientEmploymentXML);
    pharmacyXML.loadXML(iMedica.Patient.PatientPharmacyXML);
    //notesXML.loadXML(iMedica.Patient.PatientNotesXML);
    surveyXML.loadXML(iMedica.Patient.PatientSurveyXML);

    /// Adding for PATIENTPROGRAMS /////////////
    programsXML.loadXML(iMedica.Patient.PatientProgramsXML);
    practiceFormXML.loadXML(iMedica.Patient.PatientPracticeFormXML);

	// unhide all hidden tabs
	for (var i=1; i<document.all.tabsTable.rows(0).cells.length; i++)
			document.all.tabsTable.rows(0).cells(i).style.display = "";
					
	demographicDataDiv.innerHTML = personDemographicsXML.transformNode(personDemographicData.XMLDocument);
	contactDataDiv.innerHTML = contactXML.transformNode(contactData.XMLDocument);
	employmentDataDiv.innerHTML = employmentXML.transformNode(employmentData.XMLDocument);
	accountHeaderDataDiv.innerHTML = accountXML.transformNode(accountData.XMLDocument);
	pharmacyDataDiv.innerHTML = pharmacyXML.transformNode(pharmacyData.XMLDocument);
	surveyDataDiv.innerHTML = surveyXML.transformNode(surveyData.XMLDocument);

	notesDataDiv.innerHTML = fnGetNotesList();
    /// Adding for PATIENTPROGRAMS /////////////
    programsDataDiv.innerHTML = programsXML.transformNode(programsData.XMLDocument);
    practiceFormDataDiv.innerHTML = practiceFormXML.transformNode(practiceFormData.XMLDocument);
	
	PersonUid = personDemographicsXML.documentElement.selectSingleNode("Person/@PersonUid").text;
	
	//AccountDataDiv.innerHTML = accountDataXML.transformNode(accountData.XMLDocument);
	//alert(DemographicDataDiv.innerHTML);
	//document.title = personDemographicsXML.documentElement.selectSingleNode("PERSONDEMOGRAPHICS/PERSONNAME").text + " Identification";

	//fnTabClick(nStartTab);
	fnTabClick(getCurrentTab());

	isBodyLoaded = true;
	// Hide notes oDiv
	refreshNotesoDiv1();

    document.all.printButtons.style.visibility = "visible";
    document.all.patientBarcode.style.visibility = iMedica.Patient.PatientBarcode ? "visible" : "hidden";

	//Load everything that's not on the first page Asynchronously:
	//loadPharmacyData();
}
var PersonUid = null;

//var pharmacyDataXML = null;
function loadPharmacyData()
{
    var pharmacyDataXML = new ActiveXObject("MSXML2.DOMDocument.3.0");
	str = iMedica.Patient.PatientPharmacyXML;
	if(!pharmacyDataXML.loadXML(str))
		pharmacyDataXML.loadXML("<root/>");
	pharmacyDataDiv.innerHTML = pharmacyDataXML.transformNode(pharmacyData.XMLDocument);
}

var outsideProviderDataXML = null;

function showAdvBillingElements(bShow)
{
	// Show or hide pymt tables, statement print icons, and sendstatement spans
	// with accountID suffixes
	var oAcctIDNodes = accountDataXML.selectNodes("IDENTIFICATIONRECORD/ACCOUNTS/ACCOUNT/ACCOUNTID");
	for (var i=0; i<oAcctIDNodes.length; i++){
		eval('document.all.pymtTable' + oAcctIDNodes[i].text + '.style.display = (bShow ? "" : "none")');
		eval('document.all.statamentPrintIcon' + oAcctIDNodes[i].text + '.style.display = (bShow ? "" : "none")');
		eval('document.all.sendStatementSpan' + oAcctIDNodes[i].text + '.style.display = (bShow ? "" : "none")');
	}
}

function refreshNotesoDiv1(obj)
{
	// keep other tabs from using the notes key handling routine by hiding
	// its oDiv1 object when not on the notes tab
	if(typeof(oDiv1) == "object")
		try {
			oDiv1.style.display = (obj == null || obj.style.display == "none" ? "none" : "");
		} catch (e) {};
}

function getNotes(type)	// fetch notes; type is 1 for Resp. types notes
{
	var oRPRP = document.all["rpRP"];
	var sRespParty="";
	if(oRPRP != null)
		sRespParty=oRPRP.checked ? "&respparty=yes" : "";
	var oChkClosed = document.all["chkClosed"];
	var sChkClosed="";
	if(oChkClosed != null)
		sChkClosed=oChkClosed.checked ? "&chkclosed=yes" : "";
	XMLHTTPGet("API/Patients/getNotes.aspx?chartPersonID=" + theChartPersonID + "&chartID=" + theChartID + sRespParty + sChkClosed, notesData, true);
	if (!XMLHTTPResponseOK(notesData, " error finding notes: identification.js, getNotes()"))
		return false;
	lenNotesRec = notesData.selectNodes("//notes").length;	// set the length
	return true;
}

function setDemographicDisplayValues()
{
	addDisplayNode("GENDER","gender",0);
	addDisplayNode("MARITALSTATUS","maritalStatus",0);
	addDisplayNode("ETHNICITY","ethnicity",parseInt(personDemographicsXML.documentElement.selectSingleNode("PERSONDEMOGRAPHICS/HISPANIC").text,10));
	addDisplayNode("EMPLOYMENTSTATUS","employmentStatus",0);
	addDisplayNode("PATIENTSTATUS","status",0);
}

function addDisplayNode(strNodeName,strSelectName,iHispanic)
{
	var strDisplayValue, strDisplayNode;
	var oNode = createMSXMLDOMObject();
	var theNodeValue = personDemographicsXML.documentElement.selectSingleNode("PERSONDEMOGRAPHICS/" + strNodeName).text;
	if ((strNodeName == "GENDER") && (theNodeValue == "indeterminate"))
		theNodeValue = "";
	if (theNodeValue != "")
		{
		var nodeDV = parent.selectOptionsXML.documentElement.selectSingleNode("SELECT[SELECTNAME='" + strSelectName + "']/OPTIONS/OPTION[VALUE='" + theNodeValue + "']/DISPLAYNAME");
		if (nodeDV == null) nodeDV = parent.selectOptionsXML.documentElement.selectSingleNode("SELECT[SELECTNAME='" + strSelectName + "']/OPTIONS/OPTION[VALUE='" + theNodeValue.toLowerCase() + "']/DISPLAYNAME");
		strDisplayValue = nodeDV.text;
		}
	else
		if (strNodeName == "GENDER")
			strDisplayValue = "Indeterminate";
		else
			strDisplayValue = "";
	if (iHispanic == 1)
		strDisplayValue = strDisplayValue + "/Hispanic";
	strDisplayNode = "<display" + strNodeName + ">" + strDisplayValue + "</display" + strNodeName + ">";
	oNode.loadXML(strDisplayNode);
	personDemographicsXML.documentElement.selectSingleNode("PERSONDEMOGRAPHICS").appendChild(oNode.selectSingleNode("display" + strNodeName));
}

function displayAcctDetail()
{
	if (document.all.AcctID.value == "AID0")
		{
		var d = new Date();
		var n = d.getMilliseconds();
		document.all.hiddenAnchor.href = "../Account/account.asp?mode=new&accountID=0&chartID=" + theChartID + "&detailID=0&instanceID=" + n + "&ProviderUserID=" + theProviderUserID;
		document.all.hiddenAnchor.target = "";
		try	{document.all.hiddenAnchor.click();} catch (e) {}
		}
	else
		{
		var numOptions, optionValue, displayDiv;
		numOptions = document.all.AcctID.children.length;
		for (var i=0; i<numOptions; i++)
			{
			optionValue = document.all.AcctID.children[i].value;
			obj = document.all[optionValue];
			obj.style.display = "none";
			}
		displayDiv = document.all.AcctID.value;
		obj = document.all[displayDiv];
		obj.style.display = "";
		var selectedOption = document.all.AcctID.selectedIndex + 1;
		AcctsOptions.innerHTML = "<font size='0'>" + selectedOption + " of " + (numAcctOptions) + "</font>";
		}
}

function formatForPrinting(theURL,theTitle,theWidth,theHeight)
{
	//if another print window is already open, close it first
	if (newWnd)
		newWnd.close();
	//open a new window and transform masterIdentificationData to display data in printable format
	if ((theURL == "identificationPrint.htm") && (theChartID > 0))
		theHeight = "520px";
	var windowSettings = "directories=yes, location=yes, toolbar=yes, menubar=yes, resizable=yes, width=" + theWidth + ", height=" + theHeight + ", scrollbars=yes";
	newWnd = window.open("../Person/" + theURL, theTitle, windowSettings);
}

function edit_Demographics()
{
	var d = new Date();
	var n = d.getMilliseconds();
	document.all.hiddenAnchor.href = "../Person/person_new.asp?chartID=" + theChartID + "&chartPersonID=" + theChartPersonID + "&instanceID=" + n + "&updateContext=patient&ProviderUserID=" + theProviderUserID;
	document.all.hiddenAnchor.target = "";
	try	{document.all.hiddenAnchor.click();} catch (e) {}
}

//new account is handled in displayDetails() onChange event for the Select
function edit_Account(theAccountID)
{
	var d = new Date();
	var n = d.getMilliseconds();
	theAccountID = theAccountID.substr(theAccountID.indexOf("AID")+3);
	if (theAccountID == 0)
		document.all.hiddenAnchor.href = "../Account/account.asp?mode=edit&chartID=" + theChartID + "&chartPersonID=" + theChartPersonID + "&accountID=0&detailID=0&instanceID=" + n + "&ProviderUserID=" + theProviderUserID;
	else
		{
		var theNode = "IDENTIFICATIONRECORD/ACCOUNTS/ACCOUNT[ACCOUNTID='" + theAccountID + "']/ACCOUNTDETAIL/DETAILID";
		var theAcctDtlID = accountDataXML.selectSingleNode(theNode).text;
		document.all.hiddenAnchor.href = "../Account/account.asp?mode=edit&chartID=" + theChartID + "&chartPersonID=" + theChartPersonID + "&accountID=" + theAccountID + "&detailID=" + theAcctDtlID + "&instanceID=" + n + "&ProviderUserID=" + theProviderUserID;
		}
	document.all.hiddenAnchor.target = "";
	try	{document.all.hiddenAnchor.click();} catch (e) {}
}

function select_Pharmacy()
{
	var parms = new Array();
	parms[0] = AppStyleSheet.href;
	parms[1] = parent.isAllowedRole;
	parms[2] = parent;
	var retArray = window.showModalDialog(getASPNetURL() + "pharmacy/search_pharmacies.htm", parms, "dialogHeight:580px;dialogWidth:700px;center:yes;resizable:no; help: no; status: no;");
	delete parms;
	if (retArray[0])
		// user closed the modal dialog without selecting a patient
		return false;
	else
		{
		var theOrigUID = null;
		if (pharmacyDataXML.documentElement.selectSingleNode("row") != null)
			theOrigUID = pharmacyDataXML.documentElement.selectSingleNode("row").getAttribute("uid");
		pharmacyDataXML.loadXML("<data>" + retArray[1].xml + "</data>");
		var theNewUID = pharmacyDataXML.documentElement.selectSingleNode("row").getAttribute("uid");
		// update pharmacy patient pharmacy if changed
		var retXml = createMSXMLDOMObject();
		if (theNewUID != theOrigUID)
			XMLHTTPGet("API/Patients/setPatientPharmacy.aspx?chartID=" + theChartID + "&pharmacyUID=" + theNewUID, retXml, true);
		delete retXml;
		pharmacyDataDiv.innerHTML = pharmacyDataXML.transformNode(pharmacyData.XMLDocument);
		}
}

function deletePharmacyFromChart()
{
	var theUID;
	theUID = pharmacyDataXML.documentElement.selectSingleNode("row").getAttribute("uid");
	if (theUID == "")
		{
		alert("No pharmacy selected for deletion.  To select a pharmacy for the patient, click the binoculars icon.");
		return;
		}
	if (confirm("This action will remove the selected pharmacy from the patient's identification.  Click OK to continue."))
		{
		pharmacyDataXML.documentElement.selectSingleNode("row").setAttribute("uid","");
		var retXml = createMSXMLDOMObject();
		XMLHTTPGet("API/Patients/setPatientPharmacy.aspx?chartID=" + theChartID + "&pharmacyUID=", retXml, true);
		delete retXml;
		pharmacyDataXML.documentElement.selectSingleNode("row").setAttribute("name","");
		pharmacyDataXML.documentElement.selectSingleNode("row").setAttribute("address","");
		pharmacyDataXML.documentElement.selectSingleNode("row").setAttribute("city","");
		pharmacyDataXML.documentElement.selectSingleNode("row").setAttribute("state","");
		pharmacyDataXML.documentElement.selectSingleNode("row").setAttribute("zip","");
		pharmacyDataXML.documentElement.selectSingleNode("row").setAttribute("phone","");
		pharmacyDataXML.documentElement.selectSingleNode("row").setAttribute("fax","");
		pharmacyDataDiv.innerHTML = pharmacyDataXML.transformNode(pharmacyData.XMLDocument);
		}
}

function add_Contact ()
{
	document.all.hiddenAnchor.href = getASPNetURL() + "Contacts/contactInfo.aspx?chartID=" + theChartID + "&chartPersonID=" + theChartPersonID;
	document.all.hiddenAnchor.target = "";
	try	{document.all.hiddenAnchor.click();} catch (e) {}
}

function edit_Contact (theSelectedContact)
{
	var theContactUUID = theSelectedContact.lastChild.firstChild.value;
	var theContactPersonID = contactDataXML.documentElement.selectSingleNode("CONTACT[UUID='" + theContactUUID + "']/CONTACTPERSONID").text;
	parent.tempXML.loadXML(contactDataXML.documentElement.selectSingleNode("CONTACT[UUID='" + theContactUUID + "']").xml);
	document.all.hiddenAnchor.href = getASPNetURL() + "Contacts/contactInfo.aspx?uuid=" + theContactUUID + "&contactPersonID=" + theContactPersonID + "&chartID=" + theChartID + "&chartPersonID=" + theChartPersonID;
	document.all.hiddenAnchor.target = "";
	try	{document.all.hiddenAnchor.click();} catch (e) {}
}

function window_onunload()
{
	if (newWnd)
		newWnd.close();
}

function printLabel()
{
	var parms = new Array();
	parms[0] = parent;
	parms[1] = personDemographicsXML.documentElement.firstChild.xml;
	window.showModalDialog("../printPDF/printLabel.htm", parms, "dialogHeight: 475px; dialogWidth: 400px; help: no; status: no;");
	delete parms;
}

function printLabelClinical()
{
	var parms = new Array();
	parms[0] = parent;
	parms[1] = theChartID;
	window.showModalDialog("../printPDF/printLabelClinical.htm", parms, "dialogHeight: 360px; dialogWidth: 410px; help: no; status: no;");
	delete parms;
}

function openWnd()
{
	try{
		if (newWnd!=null)
			newWnd.close()
		newWnd=null;
		newWnd=window.open(rptPath+'/Reports/reports.htm','Reports','top=0,left=0,,width='+(window.screen.width-10)+',height='+(window.screen.height-10));
	}catch(e)
		{
		alert("An internal error has occurred(openWnd, " + e.description+ ").\n\nIf the problem persists, please contact technical support.");
		return false;
		}
}

function print_statement()
{
	var personWhoPaysID;
	var iAccountID = document.all.AcctID.value;
	iAccountID = iAccountID.substr(iAccountID.indexOf("AID")+3);
	personWhoPaysID = accountDataXML.documentElement.selectSingleNode("/IDENTIFICATIONRECORD/ACCOUNTS/ACCOUNT[ACCOUNTID = " + iAccountID + "]/PERSONWHOPAYSID");
	if(personWhoPaysID != null)
		{
		personWhoPaysID = personWhoPaysID.text;
		var useExcelXPViewer = (parent.oPAXCOM != null && parent.oPAXCOM.isExcelXPInstalled());
		if (event != null && event.ctrlKey == true && useExcelXPViewer)
			useExcelXPViewer = !confirm("Ctrl key detected: These statements will be shown using the Crystal Reports Viewer instead of Excel XP.");
		if (useExcelXPViewer)
			exportToExcelXP("<root><rp id='" + personWhoPaysID + "'/></root>");
		else
			printCrystalReport("<root><rp id='" + personWhoPaysID + "'/></root>", true);
		}
	else
		{
		alert("An unexpected error was encountered in print_statement(): Unable to identify the personWhoPaysID for this account.");
		return;
		}
}

function showAuditTrail()
{
	var iAccountID = document.all.AcctID.value;
	iAccountID = iAccountID.substr(iAccountID.indexOf("AID")+3);
	var target = 'viewAcctAuditTrail.asp?acctID=' + iAccountID;
	var parms = new Array();
	parms[0] = document.all.AcctID.children(document.all.AcctID.selectedIndex).text;
	parms[1] = personDemographicsXML.documentElement.selectSingleNode("PERSONDEMOGRAPHICS/PERSONNAME").text;
	parms[2] = parent;
	window.showModalDialog(target, parms, "dialogWidth:800px;dialogHeight:430px;help: no; status: no;");
	delete parms;
}

function eligibilityDetails(oSpan)
{
	var iAccountID = document.all.AcctID.value;
	iAccountID = parseInt(iAccountID.substr(iAccountID.indexOf("AID")+3),10);
	var iInsOrder = 0;
	var sDate = new Date();
	sDate = (sDate.getMonth() + 1) + "/" + sDate.getDate() + "/" + sDate.getFullYear();
	var sPhysician = personDemographicsXML.documentElement.selectSingleNode("PERSONDEMOGRAPHICS/PRACTICEPROVIDERUSERID").text;
	switch (oSpan.parentElement.parentElement.children[0].children[0].innerText)
		{
		case "Primary":
			iInsOrder = 1;
			break;
		case "Secondary":
			iInsOrder = 2;
			break;
		case "Tertiary":
			iInsOrder = 3;
			break;
		default:
			alert("Eligibility checking for this level of insurance is not currently supported");
			break;
		}
	if (iInsOrder != 0)
		{
		var sNewStatus = eligShowPopup(iAccountID, 0, iInsOrder, sDate, sDate, sPhysician, parent);
		if (sNewStatus != "")
			oSpan.innerText = sNewStatus;
		}
}

function renderAccountDetails()
{
	accountDataDiv.innerHTML = accountDataXML.transformNode(accountData.XMLDocument);
}

function editInsuranceData()
{
	document.location.href = "../insuranceOnly/insurance.asp?acctID=" + document.all.oInpMainAccountID.value + "&chartID=" + theChartID;
}

// show a dialog with the patient pin in there
function fnShowPin() {
    window.showModalDialog(getASPNetURL() + "MessagingOffice/showPtPin.aspx?personID=" + theChartPersonID, null, "dialogWidth:300px;dialogHeight:200px;help: no; status: no;");
}

function createNewNote() {
    doNewNote(parent, theChartPersonID, theChartID);
}

function fnGetNotesList() {
    return iMedica.Patient.GetNoteList(PatientUid);
}

function setPatientBarCode() {
    iMedica.Patient.SetPatientBarcode();
}