function toggleFilters (el) { 
	var req = getXMLHttpRequest();
	if(req) {
		//window.alert(el.checked);
		
		req.open("GET", "../admin/toggleFilters.form?ignoreFilters=" + el.checked, true);
		req.send(null);
	}
}

function getXMLHttpRequest() {
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest) {
	    return new XMLHttpRequest();
	// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
	   return new ActiveXObject("Microsoft.XMLHTTP");
	}
}

function editList(domain, listName) {
	if(!domain || domain.length == 0) {
		domain = "EMDT";
	}
	if(listName) {
		if (domain == "DATABASE")
			window.open("../admin/editDBList.form?domain=" + domain + "&name=" + listName+ "&method=list",'editList','scrollbars=1,toolbar=1,status=1,menubar=1,resizable=1,location=0,directories=0,width=800,height=400,left=0,top=0');
		else
			window.open("../admin/editList.form?domain=" + domain + "&name=" + listName, 'editList','scrollbars=1,toolbar=1,status=1,menubar=1,resizable=1,location=0,directories=0,width=800,height=400,left=0,top=0');
	} else {
		window.alert("List domain/name missing");
	}
}

var cursorPointer = "pointer";
if(document.all) { 
	//Define IE specific vars in here..
	cursorPointer = "hand"; //For IE versions less then 6
}

function popup(url, id, width, height) {
	return window.open(url, id,'scrollbars=1,toolbar=1,status=1,menubar=1,resizable=1,location=1,directories=1,width=' + width + ',height=' + height + ',left=0,top=0');
}

function dataGuard() {
	var saveButton = document.getElementById('saveDataButton');
	if(saveButton && unsavedData) {
		return window.confirm("You have unsaved data. Are you sure?");
	}
	return true;
}

function buttonOver(button) {
	button.className = "buttonOver";
}

function buttonOut(button) {
	button.className = "button";
}

function confirmAndDispatch(methodName, message) {
	if(window.confirm(message)) {
		return dispatch(methodName);
	}
	return false;
}

var formSubmitted = false;
function submitTheForm(){
if(formSubmitted == true){
	return false;
}else{
	formSubmitted = true;
	return true;
}
}

function getConsNote(filterId) {
	fullScreenPleaseWait();
	document.location = "consultationNote.form?filterFormId="+filterId;
}

function dispatch(methodName) {
    fullScreenPleaseWait();
	if(methodName) {
		var target = document.getElementById("dispatchMethod");
		if(target) {
			target.value = methodName;
			return true;
		} else {
			window.alert("Cannot find dispatchMethod Element");
		}
	} else {
		window.alert("No method name to dispatch to!");
	}
	return false;
}

function moveSelection(sourceId, targetId) {
	var source = document.getElementById(sourceId);
	var target = document.getElementById(targetId);
	if(!source) {
		window.alert("Could not find source selection field with id '" + sourceId + "'");
	}
	if(!target) {
		window.alert("Could not find target selection field with id '" + targetId + "'");
	}
	//@todo check source and target are selection fields
	for(var i = 0; i < source.options.length;) {
		if(source.options[i].selected) {
			var option = source.options[i];
			if(source.options[i].value != "emptyPlaceHolder") {
				target.insertBefore(option, target.options[0]);
				continue;
			}
		}
		++i;
	}
}

function updateParent() {
	
	if(window.opener) {
		if(window.opener.update) {
			window.opener.update();
		}
	}
}

function select(mode) {
	var els = document.getElementsByTagName("input");
	for(var i = 0; i < els.length; i++) {
		if(els.item(i).type == "checkbox" && hasClassName(els.item(i), "allNonInvert")) {
			if(mode == "all") {
				els.item(i).checked = true;
			} else if(mode == "none") {
				els.item(i).checked = false;
			} else if(mode == "invert") {
				els.item(i).checked = !els.item(i).checked;
			}		
		}
	}
}

function getClassNames(el) {
	return el.className.split(/\s+/);
}

function hasClassName(el, className) {
	var classNames = getClassNames(el);
	for(var i = 0; i < classNames.length; i++) {
		if(classNames[i] == className) return true;
	}
	return false;
}

function save(formId, actionId) {
	if(setVal(actionId, "save")) {
		document.getElementById(formId).submit();
	}
}

function cancel(formId, actionId) {
	if(setVal(actionId, "cancel")) {
		document.getElementById(formId).submit();
	}
}

function setVal(elId, val) {
	var target = document.getElementById(elId);
	if(target) {
		target.value=val;
		return true;
	} else {
		alert("Could not set element value. Element id = " + elId + ", value = " + val);
		return false;
	}
}

function changePage(formId, actionId, pageNum) {
	var formEl = document.getElementById(formId);
	if(!formEl) {
		alert("Could not find form element with " + formId + " id");
		return false;
	}
	
	if(setVal(actionId, "changePage") && setVal("_page", pageNum)) {
		formEl.submit();
		return true;
	}
	return false;
}

//send browser to a url and display progress indicator
function dispatchAndShowPleaseWait (url)	{
	fullScreenPleaseWait();
	window.location = url;
}
//show 'please wait' message
function showPleaseWait(){
	fullScreenPleaseWait();
}

function isChecked(aCheckbox){
		if(aCheckbox){	
			if(aCheckbox.length){
				var checkboxLength = aCheckbox.length;		
				for(var i = 0; i<checkboxLength ; i=i+1){
				 	if(aCheckbox[i].checked == true ){
				 		return true;
				 	}
				}
				return false;
			}else{
				if(aCheckbox.checked == true ){
				 		return true;
				}else{
						return false;
				}
			}
		}else{
			return false;
		}
	}


function deselectCheckBox(aCheckbox){
		if(aCheckbox){	
			if(aCheckbox.length){
				var checkboxLength = aCheckbox.length;		
				for(var i = 0; i<checkboxLength ; i=i+1){
				 	aCheckbox[i].checked = false;				 		
				}
				return false;
			}else{
				aCheckbox.checked = false;
			}
		}
	}
function fnMoveItems(lstbxFrom,lstbxTo)
{
	 var varFromBox = document.all(lstbxFrom);
	 var varToBox = document.all(lstbxTo); 
	 if ((varFromBox != null) && (varToBox != null)) 
	 { 
		  if(varFromBox.length < 1) 
		  {
			   alert('Please select atleast one user.');
			   return false;
		  }
		  if(varFromBox.options.selectedIndex == -1) // when no Item is selected the index will be -1		
		  {
			   alert('Please select a user to Add/Remove');
			   return false;
		  }
		  while ( varFromBox.options.selectedIndex >= 0 ) 
		  { 			  
			   var newOption = new Option(); // Create a new instance of ListItem 
			
			   newOption.text = varFromBox.options[varFromBox.options.selectedIndex].text; 
			   newOption.value = varFromBox.options[varFromBox.options.selectedIndex].value; 
			   varToBox.options[varToBox.length] = newOption; //Append the item in Target Listbox
			
			   varFromBox.remove(varFromBox.options.selectedIndex); //Remove the item from Source Listbox 
		
		  } 
	 }
	 sortOptions(varFromBox);
	 sortOptions(varToBox);
	 
	 return false; 
}


function compareOptionText(a,b) {
  return a.text!=b.text ? a.text<b.text ? -1 : 1 : 0;
}
function sortOptions(list) {
	var items = list.options.length;
	// create array and make copies of options in list
	var tmpArray = new Array(items);
	for ( i=0; i<items; i++ ){
		tmpArray[i] = new Option(list.options[i].text,list.options[i].value);
	}
	// sort options using given function
	tmpArray.sort(compareOptionText);
	// make copies of sorted options back to list
	for ( i=0; i<items; i++ ){
		list.options[i] = new Option(tmpArray[i].text,tmpArray[i].value);
	}
  }
  
//Function to add NRL event:
function addNRLEvent(dateFieldId, title) {
	var dateField = document.getElementById(dateFieldId);
	if(dateField) {
		if(!title) title = "";
		var date = dateField.value;
		window.open("../calendar/editEventPopup.jsp?forward=closeWindow&id=new&type=event&date=" + date + "&title=" + title,'editEvent','scrollbars=1,toolbar=0,status=1,menubar=1,resizable=1,location=0,directories=0,width=700,height=500,left=0,top=0');
	}
}	
	function fileUploader(id) {
		document.getElementById('usedInSave').value="attached"
		document.getElementById("actionRequired").value = "fileUpload";
		document.getElementById("actionButton").value = id;
		preSubmit();
		document.getElementById("consultationNote").submit();
	}
	
	
	function fileDeleteAction(id, fileNameSel) {
		if(confirm("Are you sure that you want to delete the file?")){
			document.getElementById("actionRequired").value = "fileDelete";
			document.getElementById("actionButton").value = id;
			document.getElementById("fileName").value=fileNameSel;
			preSubmit();
			document.getElementById("consultationNote").submit();
		}
	}
	
	function showPatient(patientId, parentScreen, careSpellId){
		document.getElementById('id').value = patientId;
		if(parentScreen != null && parentScreen == 'InCompleteReferrals'){
			document.location.href = '../referrals/viewPatient.form?patientId='+patientId+'&csId='+careSpellId;
		}else{
			document.location.href = '../referrals/viewPatient.form?patientId='+patientId+'&csId='+careSpellId;
		}
		
	}
	
	function showPatientResponse(patientId, careSpellId, isAcknowledged){
		document.getElementById('id').value = patientId;
		document.getElementById('csId').value = careSpellId;
		document.getElementById('isAcknowledged').value = isAcknowledged;
		document.forms[0].actionRequired.value = 'SHOW_PATIENT';
		document.forms[0].submit();
	}
	
	
	function setAction(val){
		document.getElementById('actionRequired').value = val;
	}
	
	function setReferralCompleted(){
		if(confirm('Please confirm')){
			var data=document.getElementById("csrfparameterName").value;
			data=data+"="+document.getElementById("csrfparametervalue").value;
			document.forms[0].action = "completeReferral.form?"+data;
			document.forms[0].submit();
		}else{
			document.getElementById('isCompleted').checked = false;
		}
	}
	
	function lookUpPatient(){
		document.forms[0].actionRequired.value='SEARCH'; 
		document.forms[0].action='../referrals/referralsPatient.form';
		document.forms[0].submit();
	}

	function savePatient(parentScreen){
		var reslt=true;
		if('ReferAPatient' == parentScreen){
			reslt = nhsNumberValidation();
		}
	    if(reslt){
		document.forms[0].actionRequired.value='SAVE'; 
		if('ReferAPatient' == parentScreen){
			document.forms[0].action='../referrals/referralsPatient.form';
		}else{
			document.forms[0].action='../referrals/viewPatient.form';
		}
		setClinicians();
		fullScreenPleaseWait();
		document.forms[0].submit();
		}else{
			return false;
		}
	}
	
	
	function saveNMDMPatient(parentScreen){
		var reslt=true;
		
		if('ReferAPatient' == parentScreen){
			reslt = nhsNumberValidation();
		}
	    if(reslt){
			document.forms[0].actionRequired.value='SAVE';
			document.forms[0].action='../nationalMDT/nmdmPatientController.form';

			setClinicians();
            fullScreenPleaseWait();
			document.forms[0].submit();
		}else{
			return false;
		}
	}
	
	
	function nhsNumberValidation(){
		var NhsNumber=document.getElementById('nhsNumberId').value;
		NhsNumber=NhsNumber.split(' ').join('');
		var notAlphabet= true;
		for(var i=0;i<NhsNumber.length;i++){
			if(NhsNumber.charAt(i).match(/^[a-zA-Z]+$/)){
				notAlphabet=false;
				break;
			}
		}
		if (NhsNumber.length == 0)
			return true;
		
		 if(NhsNumber.length!=10 || notAlphabet==false){
		     var r = confirm('Please note: this NHS number is not valid (should be 10 digits):\n\nChoose OK to proceed with Save, choose Cancel to resume editing');
			   if(r){
				   return true;
			   }else{
				   return false;
			   }
		 }else{
		     var check=0,j=0;
		   for(var i=10;i>=2;i--){
			   var k=NhsNumber.charAt(j)
			   check = check+(i*k);
			   j++;
		   }
		   check=check%11;
		   check=11-check;
		   if(check!= NhsNumber.charAt(9)){
		     var r = confirm('Please note: this NHS number is not valid (incorrect check digit):\n\nChoose OK to proceed with Save, choose Cancel to resume editing');
			   if(r){
				   return true;
			   }else{
				   return false;
			   }
		   }else{
			   return true;
		   }
		}
	}

/*
	Method to disable UI and show a 'Please wait' message,
	with the intention of preventing users from double-clicking or re-submitting forms while submit is in progress.
 */

function fullScreenPleaseWait()	{
    var pleaseWaitContainer = document.createElement("div");
    pleaseWaitContainer.setAttribute("id", "pleaseWaitContainer");
    var message = document.createElement("div");
    message.setAttribute("id", "pleaseWaitPopup");
	message.innerHTML = "Please Wait...";
    pleaseWaitContainer.appendChild(message);
    document.body.appendChild(pleaseWaitContainer);
}

function disableSaveButtonsAfterClick ()	{
		// SPIRE-238 disable both the bottom button and the big button when either are clicked
        var bottomSaveButton = document.getElementById("saveDataButton");
        var topSaveButton = document.getElementById("save");
		if (bottomSaveButton)	{
			// this is an A tag
        	bottomSaveButton.disabled=true; 
        	bottomSaveButton.innerHTML="<img src='../images/ajax-loader-bl.gif'/> Saving..."; 
        	bottomSaveButton.href='#'; 
		}
		if (topSaveButton)	{
			// this is a DIV tag
        	topSaveButton.disabled=true; 
        	topSaveButton.style.cursor = 'wait';
        	topSaveButton.style.color = 'grey';
        	topSaveButton.innerHTML="<br/><img src='../images/ajax-loader-bl.gif'/> Saving..."; 
		}
	}
	// check if save button was already disabled, in case of double-click
	function wasDoubleClick ()	{
        var bottomSaveButton = document.getElementById("saveDataButton");
        var topSaveButton = document.getElementById("save");

        if ((topSaveButton && topSaveButton.disabled) || (bottomSaveButton && bottomSaveButton.disabled))	{
        	console.log("ignore double click");
        	return true
        }
        return false;
	}
	
	function saveNote() {
	if(document.getElementById("usedInSave") && document.getElementById("usedInSave").value=="notAttachedYet"){
		var r = confirm("File selected, but not attached yet.\nProceeding will cause this to be discarded. \n\nProceed? ");
			if(r) {
				document.getElementById("actionRequired").value = "saveTemp";
				disableSaveButtonsAfterClick();
				preSubmit();
				document.getElementById("consultationNote").submit();
			 }else {
				 return false;
			}
	  }else{
		document.getElementById("actionRequired").value = "saveTemp";
        if (wasDoubleClick())
            return;
        fullScreenPleaseWait();
        preSubmit();
		document.getElementById("consultationNote").submit();
		}
	}
	function patientHistory(id1, name1){
		document.location.href = "patientHistoryActions.form?filterFormId="+id1+"&formName="+name1;
	}
	function goToReOrderScr(type, id){
		if("2" == type){
			location.href = '../emdt/formObject.form?type='+type+'&id='+id+'&action=reOrderPage';
		}else if("3" == type){
			location.href = '../emdt/formObject.form?type='+type+'&id='+id+'&action=reOrderSection';
		}else if("4" == type){
			location.href = '../emdt/formObject.form?type='+type+'&id='+id+'&action=reOrderField';
		}else{
			document.forms[0].action = '../emdt/formObject.form?type='+type+'&id='+id;
			document.getElementById("form").submit();
		}
}
function backScreen(){
	var type = document.getElementById('type').value;
	var id = document.getElementById('id').value;
	location.href  = "../emdt/formObject.form?type="+type+"&id="+id;
}


function cancelSort(){
	var type = document.getElementById('type').value;
	var id = document.getElementById('id').value;
	goToReOrderScr(type, id);
}

function trimAll(sString){
	while (sString.substring(0,1) == ' '){
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' '){
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}
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;
	}
}

