function nullifyId() {
	document.getElementById("task").value = null;
	document.getElementById("pathwayorder").value = null;
}
function processEditDelete(task, id) {
	var isProceed = true;
	if (task == "4") {
		if (!confirm("Are you sure you want to delete this Referral Pathway?")) {
			isProceed = false;
		}
	}
	if (isProceed) {
		document.getElementById("referralsDefinitionId").value = id;
		createNewReferralsDefinitionForm(task);
	}
}
function deleteGroup(task, id) {
	var isProceed = true;
	if (task == "10") {
		if (!confirm("Are you sure you want to delete this group?")) {
			isProceed = false;
		}
	}
	if (isProceed) {
		document.getElementById("groupFormId").value = id;
		createNewReferralsDefinitionForm(task);
	}
}
function createNewReferralsDefinitionForm(passedVal) {
	document.getElementById("task").value = passedVal;
	var fsForm = document.getElementById("referralsDefinitionForm");
	// fullScreenPleaseWait();
	fsForm.submit();
}

function valdtDplctSpeciality(speciality) {
	$
			.ajax( {
				type : "POST",
				url : "../emdt/validateReferralsDefinition.form",
				data : "speciality=" + speciality,
				success : function(msg) {
					var isRefrlDefExists = msg.isSpecialistExists;
					if ("Yes" == isRefrlDefExists) {
						document.getElementById('validateCodeMsg').style.display = "block";
						document.getElementById('codeAlreadyExists').value = "Yes";
					} else {
						document.getElementById('validateCodeMsg').style.display = "none";
						document.getElementById('codeAlreadyExists').value = "No";
					}
				}
			});
}
function processReferralsDefinitionForm(arg) {
	var result = validateField();
	if (result == true) {
		fullScreenPleaseWait();
	    setClinicians();
		setFormsAndSummaries();
		setGroups();
		sentReq(arg);
	}
}

function validateField() {
	var table = document.getElementById("clinicianTblId");
	var rowCount = table.rows.length;
	var table1 = document.getElementById("formsTblId");
	var rowCount1 = table1.rows.length;
	var title = document.getElementById("title").value;
	var speciality = document.getElementById("speciality").value;
	var formAdded=false;
	if (rowCount1 >= 1){
		for ( var i = 1; i < rowCount1; i++){
			if(table1.rows[i].cells[8].innerHTML=='Form'){
				formAdded=true;
				break;
			}
		}
	}
	document.getElementById("speciality").value = speciality;
	if (title == "") {
		alert("Please enter Pathway Title");
		document.getElementById("title").focus();
		return false;
	} else if (speciality == "") {
		alert("Please enter Speciality");
		document.getElementById("speciality").focus();
		return false;
	} else if (document.getElementById('selectedHospital').value  == "") {
		alert("Please select a hospital.");
		document.getElementById("selectedHospital").focus();
		return false;
	} else if (rowCount <= 0) {
		alert("At least one clinician has to be added");
		document.getElementById("clinician").focus();
		return false;
	} else if (!formAdded) {
		alert("At least one form has to be added");
		document.getElementById("forms").focus();
		return false;
	}
	return true;
}

function sentReq(arg) {
	if(arg==1){  
		setClinicians();
		setFormsAndSummaries();
		setGroups();
	}
	document.getElementById("task").value = arg;
	var fsForm = document.getElementById("referralsDefinitionForm");
	fsForm.method = "POST";
	fsForm.action = "../emdt/referralsDefinition.form";
	fsForm.submit();
}
function addClinician() {
	var table = document.getElementById("clinicianTblId");
	var rowCount = table.rows.length;
	if (document.getElementById('clinician') == null)
		return;
	var userName = document.getElementById('clinician').value;
	var fullname = document.getElementById(userName).value;
	if (rowCount > 0) {
		for ( var i = 0; i < rowCount; i++)
			if (table.rows[i].cells[1].innerHTML == userName) {
				alert("Clinician '" + fullname + "' is already present");
				return false;
			}
	}
	var row = table.insertRow(rowCount);
	row.setAttribute("id", "cliniciantable" + userName);

	var column = row.insertCell(0);
	column.setAttribute("class", "grabable");

	column = row.insertCell(1);
	column.setAttribute("width", "70%");
	column.setAttribute("class", "grabableTitle");
	var element = document.createTextNode(fullname);
	column.appendChild(element);

	column = row.insertCell(2);
	column.setAttribute('align','center');	// TODO better put into css
	element = document.createElement("img");	
	element.setAttribute("src", "../images/delete.png");
	element.setAttribute("id", "removecomment");
	var newlink = document.createElement('a');
	newlink.appendChild(element);
	var value1="cliniciantable"+fullname;
	
	newlink.setAttribute("onclick", "deleteRow('"+value1+"','clinicianTblId');");
	newlink.setAttribute("onmouseover", "this.style.cursor = cursorPointer");
	column.appendChild(newlink);
	var column = row.insertCell(3);
	column.style.display = 'none';
	var element = document.createTextNode(fullname);
	column.appendChild(element);
}

/**
 * Deletes a specific row from a table and performs validations based on the table ID before deletion.
 *
 * @param {string} row - The ID of the table row to be deleted.
 * @param {string} tableId - The ID of the table from which the row will be removed.
 * @return {boolean} Returns `false` if the deletion is prevented due to validation checks, otherwise no value is returned.
 */
function deleteRow(row, tableId) {
	var isProceed = true;
	if (tableId === "formsTblId") {
		var tableRow = document.getElementById(row);
		var type= tableRow.cells[8].innerHTML;
		if (!confirm("Are you sure you want to remove this "+ type+" from the referral pathway?")) {
			isProceed = false;
		}
	}else if(tableId === "grpTblId"){
	  	if (!confirm("Are you sure you want to remove this group?")) {
			isProceed = false;
		}
	}else {
		if (!confirm("Are you sure you want to remove this clinician?")) {
			isProceed = false;
		}
	}
	if (isProceed) {
		var table = document.getElementById(tableId);
		var tableRow = document.getElementById(row);
		var deleteOption;

		if (tableId === 'grpTblId') {
			// Flow for deleting a Group e.g. Images and Reports
			deleteOption = tableRow.cells[1].innerHTML;
			console.log("group name to delete " + deleteOption);
			var formTable = document.getElementById('formsTblId');
			var formTableRowCount = formTable.rows.length;
			// Check if the group is present and selected for any form in the forms table
			if (formTableRowCount > 1) {
				for ( var i = 1; i < formTableRowCount; i++) {
					var groupDropdown = document.getElementById("groupName" + i);
					if (groupDropdown) {
						for (var j = groupDropdown.length - 1; j >= 0; j--) {
							if (groupDropdown.options[j].innerHTML === deleteOption) {
								if (groupDropdown.options[j].selected) {
									alert('Group ' + deleteOption + ' cannot be deleted because it is in use: please check if any forms are present under this group and remove them first.');
									return false;
								}

							}
						}
					}
				}
				for ( var i = 1; i < formTableRowCount; i++) {
					var groupSelectList = document.getElementById("groupName" + i);
					if (groupSelectList) {
						for (var j = groupSelectList.length - 1; j >= 0; j--) {
							if (groupSelectList.options[j].innerHTML === deleteOption) {
								groupSelectList.remove(j);
							}
						}
					}

				}
			}
		}
		tableRow.parentNode.removeChild(tableRow);

		if (tableId === 'formsTblId') {
			var rowCount = table.rows.length;
			if (rowCount === 1) {
				document.getElementById('formsTblId').style.display = 'none';
			}
		}
	}
}
function exchange(oRowI, oRowJ, amount, tableId) {
	var table = document.getElementById(tableId);
	if (oRowI.rowIndex == oRowJ.rowIndex + 1) {
		oRowI.parentNode.insertBefore(oRowI, oRowJ);
	} else if (oRowJ.rowIndex == oRowI.rowIndex + 1) {
		oRowJ.parentNode.insertBefore(oRowJ, oRowI);
	} else {
		var tmpNode = oRowI.parentNode.replaceChild(oRowI, oRowJ);
		if (typeof (oRowI) != "undefined" && amount == -1) {
			oRowI.parentNode.insertBefore(tmpNode, oRowI);
		} else {
			oRowI.parentNode.appendChild(tmpNode);
		}
	}
}
function addGroups() {
	var table = document.getElementById("grpTblId");
	var rowCount = table.rows.length;
	var groupName = document.getElementById('selectedGroup').value;
	if (rowCount > 1) {
		for ( var i = 0; i < rowCount; i++)
			if (table.rows[i].cells[1].innerHTML == groupName) {
				alert("Group '" + groupName + "' is already added");
				return false;
			}
	}
	if (rowCount == 0) {
		var row = table.insertRow(rowCount);
		var column = row.insertCell(0);
		column.setAttribute("width", "10%");

		column = row.insertCell(1);
		column.setAttribute("width", "50%");
		element = document.createTextNode('Name');
		column.appendChild(element);

		column = row.insertCell(2);
		element = document.createTextNode("Can't Be Empty");
		column.appendChild(element);
		
		column = row.insertCell(3);
		element = document.createTextNode("Delete");
		column.appendChild(element);
		rowCount = table.rows.length;
	}
	
	var row = table.insertRow(rowCount);
	row.setAttribute("id", "grptable"+groupName);

	var column = row.insertCell(0);
	column.style.display = 'none';
	element = document.createTextNode(" ");
	column.appendChild(element);

	var column = row.insertCell(1);
	var element = document.createTextNode(groupName);
	column.appendChild(element);

	column = row.insertCell(2);
	column.setAttribute('align','center');	// TODO better put into css
	element = document.createElement("input");
	element.setAttribute("type", "checkbox");
	element.setAttribute("id", "group" + groupName);
	column.appendChild(element);
	
	column = row.insertCell(3);
	column.setAttribute('align','center');	// TODO better put into css
	element = document.createElement("img");
	element.setAttribute("src", "../images/delete.png");
	element.setAttribute("id", "removecomment");
	var newlink = document.createElement('a');
	newlink.appendChild(element);
	newlink.setAttribute("onclick", " deleteRow('grptable" + groupName
			+ "','grpTblId');");
	newlink.setAttribute("onmouseover", "this.style.cursor = cursorPointer");
	column.appendChild(newlink);
	

	var formTable = document.getElementById('formsTblId');
	var formTableRowCount = formTable.rows.length;
	if (formTableRowCount > 1) {
		for ( var i = 1; i < formTableRowCount; i++) {
			var element = document.getElementById("groupName" + i);
			if (element) {
				var option = document.createElement("option");
				var textNode = document.createTextNode(groupName);
				option.appendChild(textNode);
				element.appendChild(option);
			}
		}
	}
}
function editSummary(rowId){
	var row= document.getElementById(rowId);
	var rowIndex= row.rowIndex;
	var rowContent = row.cells[2].innerHTML;
	if(rowContent.indexOf('<textarea')>=0){
		rowContent=document.getElementById('editedContent'+rowIndex).value;
	}
	rowContent= rowContent.replace(/<br\s*\/?>/ig, "\r\n");
	row.cells[2].innerHTML="";
    var element=document.createElement("textarea");
    element.setAttribute("cols","40");
    element.setAttribute("rows","4");
    element.setAttribute("id","editedContent"+rowIndex);
    var txt = document.createTextNode(rowContent);
    element.appendChild(txt);
    element.setAttribute("onkeypress","setEditSummary(event,'"+rowId+"');")
    row.cells[2].appendChild(element);
    document.getElementById('editimgId'+row.cells[7].innerHTML).style.display='none';
    document.getElementById('saveimgId'+row.cells[7].innerHTML).style.display='block';
  }
function setEditSummary(rowId){
    var row= document.getElementById(rowId);
    var rowIndex= row.rowIndex;
    var textAreaString = document.getElementById('editedContent'+rowIndex).value;
    textAreaString = textAreaString.replace(/\n\r/g,"<br />");
    textAreaString = textAreaString.replace(/\n/g,"<br />");
    row.cells[2].innerHTML="";
    row.cells[2].innerHTML=textAreaString;
    document.getElementById('saveimgId'+row.cells[7].innerHTML).style.display='none';
    document.getElementById('editimgId'+row.cells[7].innerHTML).style.display='block';
}
function setClinicians(){
	var table = document.getElementById("clinicianTblId");
	if (table == null)
		return;
	var rowCount = table.rows.length;
	var str = "";
	if (rowCount > 0) {
		for ( var i = 0; i < rowCount; i++) {
			str = str + " " + table.rows[i].cells[3].innerHTML + ",";
		}
		
		document.getElementById('clinicianList').value = str;
	}
}

function setGroups(){
	var groups = "";
	var grptable = document.getElementById("grpTblId");
	var grptableRowCount = grptable.rows.length;
	for ( var i = 1; i < grptableRowCount; i++) {
		strToAppend = grptable.rows[i].cells[1].innerHTML;
		if (document
				.getElementById('group' + grptable.rows[i].cells[1].innerHTML).checked == 1)
			document.getElementById('checkBox' + strToAppend).value = "checked";
		else
			document.getElementById('checkBox' + strToAppend).value = "notChecked";
		if (groups == '') {
			groups = strToAppend;
			;
		} else {
			groups = groups + "," + strToAppend;
		}
	}
	document.getElementById('groups').value = groups;
}
function setFormsAndSummaries(){
	var table = document.getElementById("formsTblId");
//	if (table.style.display == 'block') {
		var rowCount = table.rows.length;
		var mandatoryForms = "";
		var nonMandatoryForms = "";
		var summaries = "";
		var strToAppend = null;
		var str = null;
		if (rowCount > 1) {
			for ( var i = 1; i < rowCount; i++) {
			    str=table.rows[i].cells[7].innerHTML;
			    var displayColumnContent=table.rows[i].cells[2].innerHTML;
			    if(displayColumnContent.indexOf('<textarea')>=0 || displayColumnContent.indexOf('<TEXTAREA')>=0){
			    	displayColumnContent= document.getElementById("editedContent"+i).value;
			    }
				strToAppend = displayColumnContent+"="+str+"="+i;
				var browserName=navigator.appName;
				var grpId = table.rows[i].cells[5].children[0].id; 
			
				var group;
				if (browserName=="Microsoft Internet Explorer"){
			    	group = document.getElementById(grpId).innerHTML;
			       	group=group.substring(group.indexOf("selected"),group.length);
			    	group= group.substring(group.indexOf(">")+1,group.length);
			    	group= group.substring(0,group.indexOf("<"));
		    	}else{
		    		 group = document.getElementById(grpId).value;
		    	}
				var el = document.getElementById(group);
			   if (el)
				   document.getElementById(group).value = document.getElementById(group).value+ " " + str;
				if(table.rows[i].cells[8].innerHTML=='Form'){
					if (document.getElementById(str).checked) {
						if(mandatoryForms.length<=0){
							mandatoryForms=strToAppend;
						}else{
							mandatoryForms = mandatoryForms + "," + strToAppend;
						}
					} else {
						if(nonMandatoryForms.length<=0){
							nonMandatoryForms =  strToAppend;
						}else{
							nonMandatoryForms = nonMandatoryForms + "," + strToAppend;
						}
					}
				}else if(table.rows[i].cells[8].innerHTML=='Summary'){
						if(summaries.length<=0){
							summaries =  strToAppend;
						}else{
							summaries = summaries + "," + strToAppend;
						}
				}
			}
			document.getElementById('summariesList').value = summaries;
			document.getElementById('mandatoryForms').value = mandatoryForms;
			document.getElementById('nonMandatoryForms').value = nonMandatoryForms;
		}
//	}
}
function addFormsAndSummaries(type) {
	var table = document.getElementById('formsTblId');
	var rowCount = table.rows.length;
	var content,displayName,path;
    if(type=='Form'){
    	path = document.getElementById('forms').value
		content = document.getElementById(path).value;
		displayName=document.getElementById(path).value;
	}else if(type=='Summary'){
		content = document.getElementById('summaries').value;
		displayName=document.getElementById('summaries').value;
		path = document.getElementById(content).value;
	}
	if(content.length<1){
		alert(type+" can't be empty, please select from dropdown");
		return false;
	}
	if (rowCount > 1) {
		for ( var i = 1; i < rowCount; i++){
			if (table.rows[i].cells[7].innerHTML == path) {
				 var message="That " + type+" is already present";
				 if(type=='Summary'){
				  	message= message+" by name "+table.rows[i].cells[2].innerHTML
				  }
				 alert(message);
				 return false;
			}
		}
	}
	groupForms = new Array();
	var grptable = document.getElementById("grpTblId");
	var grptableRowCount = grptable.rows.length;
	if (grptableRowCount <= 1) {
		alert("Please Add Groups Before Adding "+type+".");
		return false;
	} else {
		for ( var i = 1; i < grptableRowCount; i++)
			groupForms[i - 1] = grptable.rows[i].cells[1].innerHTML;
	}

	if (document.getElementById('formsTblId').style.display === 'none') {
		document.getElementById('formsTblId').style.display = 'block';
	}
	
	if (rowCount === 0) {
		var row = table.insertRow(rowCount);

		column = row.insertCell(0);
		element = document.createTextNode('');
		column.appendChild(element);

		column = row.insertCell(1);
		column.setAttribute("width", "50%");
		element = document.createTextNode('Name');
		column.appendChild(element);
		
		column = row.insertCell(2);
		element = document.createTextNode('Edit');
		column.appendChild(element);
		
		column = row.insertCell(3);
		element = document.createTextNode('Mandatory');
		column.appendChild(element);

		column = row.insertCell(4);
		element = document.createTextNode('Group');
		column.appendChild(element);

		column = row.insertCell(5);
		element = document.createTextNode('Delete');
		column.appendChild(element);
		rowCount = table.rows.length;
	}
	
   	var currentTagTokens=displayName.split(' ');
	var shortWord;
	for( var i = 0; i < currentTagTokens.length; i++ ){
		 shortWord = currentTagTokens[i];
		if (shortWord.length > 13)
			displayName = displayName.replace(shortWord, shortWord
					.substring(0, 10));
	  }
	if (displayName.length > 10) {
		var tempdisplayName;
		do {
			displayName = displayName.replace(' ','\n');
			tempdisplayName = displayName.substring(displayName
					.lastIndexOf('\n') + 1, displayName.length);
			} while (tempdisplayName.length > 12);
	}

	var row = table.insertRow(rowCount);
	row.setAttribute("id", "formtable" + path);
	var column = row.insertCell(0);
	column.style.display = 'none';
	element = document.createTextNode(" ");
	column.appendChild(element);

	column = row.insertCell(1);
	column.setAttribute("class", "grabable");
	element = document.createTextNode("");
	column.appendChild(element);

	column = row.insertCell(2);
	column.setAttribute("width", "70%");
	column.setAttribute("class", "grabableTitle");
	var element = document.createTextNode(displayName);
	column.appendChild(element);

	column = row.insertCell(3);
	element = document.createElement("img");
	element.setAttribute("src", "../images/16x16/edit.png");
	var newlink = document.createElement('a');
	newlink.appendChild(element);
	newlink.setAttribute("onclick", " editSummary('formtable" + path+"');");
	newlink.setAttribute("onmouseover", "this.style.cursor = cursorPointer");
	column.appendChild(newlink);
	
	column = row.insertCell(4);	
	column.setAttribute('align','center');	// TODO better put into css
	if(type=='Form'){
		element = document.createElement("input");
		element.setAttribute("type", "checkbox");
		element.setAttribute("id", path);
		column.appendChild(element);
	}

	column = row.insertCell(5);
	element = document.createElement("select");
	for ( var i = 0; i < groupForms.length; i++) {
		var option = document.createElement("option");
		var textNode = document.createTextNode(groupForms[i]);
		option.appendChild(textNode);
		element.appendChild(option);
	}
	
	element.name="groupName" + rowCount;
	element.setAttribute("id", "groupName" + rowCount);
	column.appendChild(element);

	column = row.insertCell(6);
	element = document.createElement("img");
	element.setAttribute("src", "../images/delete.png");
	element.setAttribute("id", "removecomment");
	var newlink = document.createElement('a');
	newlink.appendChild(element);
	newlink.setAttribute("onclick", " deleteRow('formtable" + path
			+ "','formsTblId');");
	newlink.setAttribute("onmouseover", "this.style.cursor = cursorPointer");
	column.appendChild(newlink);
	column.setAttribute('align','center');	// TODO better put into css

	column = row.insertCell(7);
	column.style.display = 'none';
	element = document.createTextNode(path);
	column.appendChild(element);

	var column = row.insertCell(8);
	column.style.display = 'none';
	var element = document.createTextNode(type);
	column.appendChild(element);
}
function verifyBeforeImport(){
	var xmlfile;
	if(document.getElementById("document")!=null){
		xmlfile= document.getElementById("document").value;
	}
	if(isEmpty(xmlfile)){
		alert("Please choose a file to import.");
		return false;
	}
	if(!isEmpty(xmlfile)){
		var lPosition =xmlfile.indexOf(".");
		var lString=xmlfile.substring(lPosition,xmlfile.length);
		if('.xml'!= lString){
			alert("Please select .xml file.");
			return false;
		}
	}
	fullScreenPleaseWait();
	return true;

}
function isEmpty(str) {
    return (!str || 0 === str.length);
}

function processPathwayOrder(){
	var table = document.getElementById("referralsPathwayTblId");
	var rowCount = table.rows.length;
	var str = "";
	if (rowCount > 0) {
		for ( var i = 1; i < rowCount; i++) {
			if(str.length>0){
				str = str + "," + table.rows[i].cells[0].innerHTML+"="+i;
			}
			else{
				str= table.rows[i].cells[0].innerHTML+"="+i;
			}
		}
	}
	document.getElementById("pathwayorder").value = str;
	document.getElementById("task").value = 13;
	var fsForm = document.getElementById("referralsDefinitionForm");
	fullScreenPleaseWait();
}
