/*!
 * Ardeo JavaScript Library 
 * This file makes ajax call to display series instances.
 */
 
 jQuery(document).ready(function ($) {  
		 // Click out event!
		  $("#backgroundPopup").click(function(){  
		  }); 	
		  $("#dateSearchType").change(function(){
	        processDate(this.value);
          });
         
   	});
 
 // SETTING UP OUR POPUP
  	 // 0 means disabled; 1 means enabled;
 	 var popupStatus = 0;  

	 function loadPopup(divName){  
	 // loads popup only if it is disabled
	 if(popupStatus==0){  
		 $("#backgroundPopup").css({  
		 	"opacity": "0.3" 
 	 	 });  
	 	 $("#backgroundPopup").fadeIn("fast");  
	     $("#"+divName).fadeIn("fast");  
	     popupStatus = 1;  
 		}  
 	}  
	 // disabling popup with jQuery magic!
	 function disablePopup(divName, tableName){  
		 // disables popup only if it is enabled
		 if(popupStatus==1){ 
	      var myTable = document.getElementById(tableName); 
		     // or use : var table = document.all.tableid;
		     if (myTable != null)	{
			     for(var i = myTable.rows.length-1 ; i > 1; i--){
				      	myTable.deleteRow(i);
				      }	    	 
		     }
		 $("#backgroundPopup").fadeOut("fast");  
		 $("#"+divName).fadeOut("fast");  
	 	 popupStatus = 0;  
		 }  
	 } 
	 
	 function removeRow(tableName){
		 var myTable = document.getElementById(tableName); 
		     // or use : var table = document.all.tableid;
		     if (myTable != null)	{
			     for(var i = myTable.rows.length-1 ; i > 0; i--){
				      	myTable.deleteRow(i);
				      }	    	 
		     }
	 }

	 // centering popup
	 function centerPopup(divName){  
		 var elementSelecter = '#' + divName;
		 $(elementSelecter).css({
	        'position' : 'fixed',
	        'left' : '50%',
	        'top' : '50%',
	        'margin-left' : -$(elementSelecter).outerWidth()/2,
	        'margin-top' : -$(elementSelecter).outerHeight()/2
	    });
	
	 }

	 // Call PACS request but with default parameters and no dialog box
	 function callPacsRequestDirect(formName, startDate, patientHospitalNumber, accessionNumber, seriesOrStudy){
			var endDate = null;	
			// startDate= 'null';
			// patientHospitalNumber='BU001015';
			// accessionNumber='BU001015';
			if (seriesOrStudy != true)	{			
				removeRow("imgStatusTrackingTable");
				document.getElementById('studyDetails').style.display = 'none';
			}
			removeRow("seriesTable");
			document.getElementById('seriesDetails').style.display = 'none';
			var searchType = 'is'; 
			var modalityValue = '';
		    if(((startDate == '' && patientHospitalNumber == '')||(startDate == 'null' && patientHospitalNumber == 'null'))){
		    	alert("Performing this search will take a very long time. Please check image form has a study date and patient has a hospital number, and try again.");
		    	return false;
		    }
		    openProgressPopupWindow();
		    sendPacsRequest(formName, accessionNumber,searchType, startDate, endDate, patientHospitalNumber, modalityValue,'direct', '', seriesOrStudy);		 
		    return false;
	    		
		 }

	 // Call PACS request but with dialog box
	 function callPacsRequestFormPopup(formName){
		var endDate = null;	
		removeRow("imgStatusTrackingTable");
		document.getElementById('studyDetails').style.display = 'none';
		removeRow("seriesTable");
		document.getElementById('seriesDetails').style.display = 'none';
		var accessionNumber = document.getElementById('accessionNumberID').value;
		var searchType = document.getElementById('dateSearchType').value; 
		var modalityValue = document.getElementById('modalitySelect').value;
		var startDate = document.getElementById('StudyDate1').value;
		var patientDob = document.getElementById('patientDob').value;
		/*
		 * if(startDate ==''){ alert("Please select the start date.");
		 * document.getElementById('StudyDate1').focus(); return false; }
		 */    
	    var patientHospitalNumber = document.getElementById('patientHospitalNumber').value;
	    if(searchType == 'between'){	
	    	if(startDate ==''){
	    	alert("Please select the start date.");
	    	document.getElementById('StudyDate1').focus();
	    	return false;
	    	}	     
  	        endDate = document.getElementById('StudyDate2').value;
	    	if(endDate==''){
	    	alert("Please select the end date.");
	    	document.getElementById('StudyDate2').focus();
	    	return false;
	    	}
	    }
	   /*
		 * if(modalityValue == 'select'){ alert("Please select modality");
		 * return false; }
		 */
	    if(modalityValue != 'select' && (startDate == '' && patientHospitalNumber == '' && accessionNumber == '' && patientDob == '')){
	    	alert("Performing a search with modality alone is not permitted. Please select some search criteria and try again");
	    	return false;
	    }
	    if(modalityValue == 'select' && startDate == '' && patientHospitalNumber == '' && accessionNumber == '' && patientDob == ''){
	    	alert("Performing an open search of PACS is not permitted. Please select some search criteria and try again");
	    	return false;
	    }
	    
	    document.getElementById('pacsParameterTable').style.display = 'block';
	    disablePopup('pacsParameterID','pacsParameterTable');
		openProgressPopupWindow();
	    sendPacsRequest(formName, accessionNumber,searchType, startDate, endDate, patientHospitalNumber, modalityValue, 'criteriaWindow', patientDob, 'study');		      
	    return false;
    		
	 }
	 
	
	 function sendPacsRequest(formName, accessionNumber, searchType, startDate, endDate, patientHospitalNumber, modality, requestedFrom, patientDob, seriesOrStudy){
		var unmatchedDcmQrDTOListSize = null;
		var matchedFilesListSize = null;
		var csrfdata=document.getElementById("csrfparameterName").value;
		csrfdata=csrfdata+"="+document.getElementById("csrfparametervalue").value;
		var	url = "../referrals/pacsSearch.form";	
		var userParameterData = "searchType="+searchType+"&accessionNumber="+accessionNumber+"&startDate="+startDate+"&endDate="+endDate+"&patientHospitalNumber="+patientHospitalNumber+"&modality="+modality+"&requestedFrom="+requestedFrom+"&patientDob="+patientDob+"&series="+seriesOrStudy+"&" + csrfdata;
		$.ajax({
		   type: "POST",
		   url: url,
		   data: "searchType="+searchType+"&accessionNumber="+accessionNumber+"&startDate="+startDate+"&endDate="+endDate+"&patientHospitalNumber="+patientHospitalNumber+"&modality="+modality+"&requestedFrom="+requestedFrom+"&patientDob="+patientDob+"&series="+seriesOrStudy+"&" + csrfdata,		   
		   success: function(msg){   
				 showSeriesTable(msg, formName, userParameterData);		      			
				 disablePopup('progressPopupID','progressPopupTable');
			}
 		});
	 }		
	 	
	 function showSeriesTable(msg, formName, userParameterData){
		   var listSize = msg.dcmQrDTOListSize;			       
		   if(listSize>0){	
			   if (formName == "imgStatusTracking")
				   $('#studyDetails').show("fast");
			   else
				   $('#seriesDetails').show("fast");
			   	document.getElementById('noDataFoundID').style.display = 'none';
			   	processRequest(formName, msg, userParameterData);
		   }else{
			   noDataFound(formName, msg.errorMsg);	      	
		   }	
		 
	 }
	 
	 function sendRequest(formName, accessionNumber){
			var url = null;
			var listSize = null;
			var csrfdata=document.getElementById("csrfparameterName").value;
			csrfdata=csrfdata+"="+document.getElementById("csrfparametervalue").value;
			if(formName == "imgStatusTracking" || formName == "preTreatmentCTScanPopup"){
				url = "../referrals/applet/loadImage.form?accessionNumber="+accessionNumber;		// FIXME looks obsolete
			}else if(formName == "printPopup"){
				url = "../referrals/printPatientDetails.form";	
			}else if(formName == "seniorStaff"){
				url = "../referrals/chooseSeniorStaffs.form";	
			}
			$.ajax({
			   type: "POST",
			   url: url,
			   data:csrfdata,
			   success: function(msg){
			   if(formName == "imgStatusTracking"){
			      stopProcessImage();   
			      listSize = msg.dcmQrDTOListSize;
			   }else if(formName == "preTreatmentCTScanPopup"){
			      listSize = msg.dcmQrDTOListSize;  
			   }else if(formName == "printPopup"){		  
			      listSize = msg.filePathListSize ;  
			   }else if(formName == "seniorStaff"){		  
			      listSize = msg.seniorStaffListSize ;  
			   }
			   if(listSize>0){	
				   if((listSize == 1) && (formName == "seniorStaff")){
				   		document.getElementById('primaryClinician').value = msg.seniorStaffList[0].name;
				   		document.getElementById("actionRequired").value = "save";
						preSubmit();
						document.getElementById("consultationNote").submit();
				   }else{
				   	processRequest(formName, msg,''); 
				   }
			   	 
			   }else{
			     noDataFound(formName, msg.errorMsg);
			     if(formName == "printPopup"){	
			       centerPopup(formName); 
			       loadPopup(formName); 
			     } 	
			   }		   	  
	  		 }
	 		});
		 }
		 
	 
	/*
	 * function processRequest(formName, msg){ var i = 0; var rowCount = null;
	 * if(formName == "imgStatusTracking" || formName ==
	 * "preTreatmentCTScanPopup"){ rowCount = msg.dcmQrDTOListSize ; for (i=0;i<rowCount;i++){
	 * addRowToImgTable(formName, msg.dcmQrDTOList[i]); } }else if(formName ==
	 * "printPopup"){ centerPopup(formName); loadPopup(formName);
	 * rowCount=msg.filePathListSize ; for (i=0;i<rowCount;i++){
	 * addRowToPrintTable(msg.filePathList[i]); } } }
	 */
	
	function dicomDateToStandard (d)	{
		var r = "";
	
		if (d.length == 8)	{
			// YYYYMMDD
			r = d.substr(6,2) + "/" + d.substr(4,2) + "/" + d.substr(0,4);
			// DD/MM/YYYY
		}
		return r;
	}
	
	function addRowToImgTable(formName, resultRow, userParameterData){			
	  var tbl = null;	
	  var lastRow = null;
	  var iteration = null;
 	  var accessionNumber = resultRow.accessionNumber;
 	  var modality=resultRow.modality;
 	  var viewDownload = resultRow.viewDownload;
 	  var seriesDescription = resultRow.seriesDescription;
 	  var studyDescription = resultRow.studyDescription;
 	  var set_seriesDescription;
 	  var numberOfSeriesInstances = resultRow.numberOfSeriesRelatedInstances;
 	  var seriesNumber = resultRow.seriesNumber;
	  var seriesInstanceUID =  resultRow.seriesInstanceUID;
 	  if(formName == "imgStatusTracking"){
 	  	tbl = document.getElementById('imgStatusTrackingTable');
 	  }else if(formName == "preTreatmentCTScanPopup"){
 	  	tbl = document.getElementById('preTreatmentCTScanTable');
 	  }else if(formName == "seriesTable"){
 	  	tbl = document.getElementById('seriesTable');
 	  }
 	  lastRow = tbl.rows.length;
 	  // if there's no header row in the table, then iteration = lastRow + 1
	  iteration = lastRow;
	  var row = tbl.insertRow(lastRow);
	  
	 /*
		 * // patient Id TD var patientIdContent =
		 * document.createTextNode(resultRow.patientID); var patientIdTD =
		 * document.createElement("TD");
		 * patientIdTD.appendChild(patientIdContent);
		 * row.appendChild(patientIdTD);
		 */
	  
	  // patient name TD
	  var patientNameContentTD = document.createTextNode(resultRow.patientName);
	  var patientNameTD = document.createElement("TD");
	  patientNameTD.appendChild(patientNameContentTD);
	  patientNameTD.setAttribute('class','seriesDescriptionTD');
	  row.appendChild(patientNameTD);
	  
	  // Date of Birth TD
	  var dobFormatted = dicomDateToStandard(resultRow.dateOfBirth);
	  var dateOfBirthContent = document.createTextNode(dobFormatted);
	  var dateOfBirthTD = document.createElement("TD");
	  dateOfBirthTD.appendChild(dateOfBirthContent);
	  dateOfBirthTD.setAttribute('class','seriesDescriptionTD');
	  row.appendChild(dateOfBirthTD);
	  
	  // study date TD
	  var studyDateFormatted = dicomDateToStandard(resultRow.studyDate);
	  var studyDateContent = document.createTextNode(studyDateFormatted);
	  var studyDateTD = document.createElement("TD");
	  studyDateTD.appendChild(studyDateContent);
	  studyDateTD.setAttribute('class','seriesDescriptionTD');
	  row.appendChild(studyDateTD);	  

	  // Accession number
	  var accNumberContent = document.createTextNode(resultRow.accessionNumber);
	  var accNumberTD = document.createElement("TD");
	  accNumberTD.appendChild(accNumberContent);
	  accNumberTD.setAttribute('class','seriesDescriptionTD');
	  row.appendChild(accNumberTD);	  
	  

	  // Modality TD
	  var modalityContent = document.createTextNode(resultRow.modality);
	  var modalityTD = document.createElement("TD");
	  modalityTD.appendChild(modalityContent);
	  modalityTD.setAttribute('class','seriesDescriptionTD');
	  row.appendChild(modalityTD);
	  
	  // series description TD
	  if(resultRow.queryLevel == "STUDY"){
		  set_seriesDescription = resultRow.studyDescription;
	  }
	  else	{
		  set_seriesDescription = resultRow.seriesDescription;
	  }

	  var seriesDescriptionContent = document.createTextNode(set_seriesDescription);
	  var seriesDescriptionTD = document.createElement("TD");
	  seriesDescriptionTD.appendChild(seriesDescriptionContent);
	  seriesDescriptionTD.setAttribute('class','seriesDescriptionTD');
	  row.appendChild(seriesDescriptionTD);
	  
	   // no. of images TD
	  var numberOfSeries;
	  if(resultRow.queryLevel == "STUDY"){
		  numberOfSeries = resultRow.numberOfStudyRelatedInstances;
	  }
	  else	{
		  numberOfSeries = resultRow.numberOfSeriesRelatedInstances;
	  }
	  var noOfImagesContent = document.createTextNode(numberOfSeries);
	  var noOfImagesTD = document.createElement("TD");
	  noOfImagesTD.appendChild(noOfImagesContent);
	  row.appendChild(noOfImagesTD);
	 
	  // Fourth TD
	  if(resultRow.queryLevel == "STUDY"){
		  var newlink = document.createElement('a');
		  newlink.appendChild(document.createTextNode ("Show"));
		  var link = "javascript:callPacsRequestDirect('seriesTable','" +studyDateFormatted + "','" + resultRow.patientID+ "','" + accessionNumber + "',true);";
		  newlink.setAttribute('href', link );  
		  var TD4 = document.createElement("TD");
		  TD4.appendChild(newlink);
		  row.appendChild(TD4);
	  } 
//	  else{
//		  newlink.setAttribute('href', "javascript:downloadImages('"+viewDownload+"','"+seriesInstanceUID+"','"+userParameterData+"');");
//  	  }
	 }
	
	function downloadImages(viewDownload,seriesInstanceUID,userParameterData){			
		openProgressPopupWindow();
		var searchType = null;
		var accessionNumber = null;
		var startDate = null;
		var endDate = null;
		var patientHospitalNumber = null;
		var modality = null;		
		var mainSplitResult = userParameterData.split("&");
		for(i = 0; i < mainSplitResult.length; i++){
			var subSplitResult = mainSplitResult[i].split("=");
			if(subSplitResult[0] == 'searchType' && subSplitResult[1] != ''&& subSplitResult[1] != null){					
				searchType = subSplitResult[1];
			}else if(subSplitResult[0] == 'accessionNumber' && subSplitResult[1] != ''&& subSplitResult[1] != null){					
				accessionNumber = subSplitResult[1];
			}else if(subSplitResult[0] == 'startDate' && subSplitResult[1] != ''&& subSplitResult[1] != null){					
				startDate = subSplitResult[1];
			}else if(subSplitResult[0] == 'endDate' && subSplitResult[1] != ''&& subSplitResult[1] != null){					
				endDate = subSplitResult[1];
			}else if(subSplitResult[0] == 'patientHospitalNumber' && subSplitResult[1] != ''&& subSplitResult[1] != null){					
				patientHospitalNumber = subSplitResult[1];
			}else if(subSplitResult[0] == 'modality' && subSplitResult[1] != ''&& subSplitResult[1] != null){					
				modality = subSplitResult[1];
			}
		}
		var	url = "../referrals/applet/loadImage.form";	
		var csrfdata=document.getElementById("csrfparameterName").value;
		csrfdata=csrfdata+"="+document.getElementById("csrfparametervalue").value;
		 $.ajax({
			   type: "POST",
			   url: url,
			   data: "accessionNumber="+accessionNumber+"&viewDownload="+viewDownload+"&patientHospitalNumber="+patientHospitalNumber+"&seriesInstanceUID="+seriesInstanceUID+"&"+csrfdata,		   
			   success: function(result){	
			        removeRow("imgStatusTrackingTable");
				    document.getElementById('studyDetails').style.display = 'none';
			 		sendPacsRequest('imgStatusTracking', accessionNumber,searchType, startDate, endDate, patientHospitalNumber, modality,'afterUpdate');
		  		 }
	 		});		 
			
	}
	 
	function addRowToPrintTable(msg){
		  var filePath = msg.filePath;
	 	  var fileName = msg.fileName;
	 	  var lastmodifiedDate=msg.lastmodifiedDate;
	 	  var tbl = document.getElementById('ajaxFilePathTable'); 	  
	 	  var lastRow = tbl.rows.length;
	 	  // if there's no header row in the table, then iteration = lastRow + 1
		  var iteration = lastRow;
		  var row = tbl.insertRow(lastRow);
		  
		  var element = document.createElement("input");
		  element.setAttribute("type", "checkbox");
		  element.setAttribute("id", filePath);
		  element.setAttribute("class","allNonInvert");
		  var TD0 = document.createElement("TD");	  
		  TD0.appendChild(element);
		  var contentTD0 = document.createTextNode (fileName);
		  TD0.appendChild(contentTD0);
		  row.appendChild(TD0);
		  
		  var contentTD3 = document.createTextNode(lastmodifiedDate);
		  var TD3 = document.createElement("TD");
		  TD3.appendChild(contentTD3);
		  row.appendChild(TD3);
	 
	 }	
	
	 function addRowToSeniorStaffTable(msg){

	 	  var seniorStaffName = msg.fullName; 	  
	 	  var tbl = document.getElementById('seniorStaffTable'); 	  
	 	  var lastRow = tbl.rows.length;
	 	  // if there's no header row in the table, then iteration = lastRow +
			// 1
		  var iteration = lastRow;
		  var row = tbl.insertRow(lastRow);
		  
		   // First TD
		  var username = msg.name;
		  var radioBtn = createRadioElement(username, false);
		 
		  var TD1 = document.createElement("TD");	  
		  TD1.appendChild(radioBtn);
		  row.appendChild(TD1);
		  
		  var contentTD2 = document.createTextNode(seniorStaffName);
		  var TD2 = document.createElement("TD");
		  TD2.appendChild(contentTD2);
		  row.appendChild(TD2);
	 
	 }
	 
	 
	 function createRadioElement( seniorStaffName, checked) {
		    var radioInput;
		    try {
		        var radioHtml = '<input type="radio" name="radio" id="'+seniorStaffName+'"';
		        if ( checked ) {
		            radioHtml += ' checked="checked"';
		        }
		        radioHtml += ' value="'+ seniorStaffName +'"/>';
		        radioInput = document.createElement(radioHtml);
		    } catch( err ) {
		        radioInput = document.createElement('input');
		        radioInput.setAttribute('type', 'radio');
		        radioInput.setAttribute('name', 'radio');
		         radioInput.setAttribute('id', seniorStaffName);
		        if ( checked ) {
		            radioInput.setAttribute('checked', 'checked');
		        }
		         radioInput.setAttribute('value', seniorStaffName);
		    }
		    return radioInput;
	}
	 
	 
	 
	function startProcessImage(){
		document.getElementById('processImageID').style.display = 'block';
	
	}
	
	function stopProcessImage(){
		document.getElementById('processImageID').style.display = 'none';
		$('#studyDetails').show("fast");
	}
	
	function noDataFound(formName, errorMsg){	
		if(formName == "printPopup"){
			document.getElementById('noPrintDataFoundID').style.display = 'block';
		}else{
				if(errorMsg != null && errorMsg != ''){
					document.getElementById('noDataFoundID').innerHTML = errorMsg;
				}
				document.getElementById('noDataFoundID').style.display = 'block';
		}
	}
	
	function disableLoadImage(accessionNumber){	
		document.getElementById('Div'+accessionNumber+'ID1').style.display = 'none';
		document.getElementById('Div'+accessionNumber+'ID2').style.display = 'block';
	}
	
	function openPacsParameterWindow(formName, studyDate){
	
	 document.getElementById('noDataFoundID').style.display = 'none';
	 document.getElementById('pacsParameterTable').style.display = 'block';
	 document.getElementById('processImageID').style.display = 'none';
	 document.getElementById(formName).style.display = 'block';
	 document.getElementById('StudyDate1').value = studyDate; 
	 centerPopup(formName); 
	 loadPopup(formName);	 
	}
	
	function processDate(selectedType){
		if(selectedType=='between'){
			document.getElementById('imageSpanFirst').style.display = 'block';
			document.getElementById('imageSpanSecond').style.display = 'none';
		}else{
			document.getElementById('imageSpanFirst').style.display = 'none';
			document.getElementById('imageSpanSecond').style.display = 'block';
		}	
	}
	
	function openProgressPopupWindow(){
	 document.getElementById('progressPopupID').style.display = 'block';
	 centerPopup('progressPopupID'); 
	 loadPopup('progressPopupID');	
	
	}
	function openPacsParameterWindow(){
		 document.getElementById('pacsParameterID').style.display = 'block';
		 centerPopup('pacsParameterID'); 
		 loadPopup('pacsParameterID');	
		
		}
	function chooseSeniors(){
	 	sendRequest('seniorStaff', 'null');
	}
	
	function processRequest(formName, msg, userParameterData){
		var i = 0;
		var rowCount = null;
		if(formName == "imgStatusTracking" || formName == "preTreatmentCTScanPopup" || formName == "seriesTable"){
		    rowCount = msg.dcmQrDTOListSize ;		
			for (i=0;i<rowCount;i++){		
			  addRowToImgTable(formName, msg.dcmQrDTOList[i], userParameterData);
			}
		}else if(formName == "printPopup"){
			centerPopup(formName); 
		    loadPopup(formName);		
		    rowCount=msg.filePathListSize ;   
		    for (i=0;i<rowCount;i++){
			  addRowToPrintTable(msg.filePathList[i]);
			 }
		}else if(formName == "seniorStaff"){
			centerPopup('seniorStaffID'); 
	 		loadPopup('seniorStaffID');	 	
		    rowCount=msg.seniorStaffListSize ;   
		    for (i=0;i<rowCount;i++){
			  addRowToSeniorStaffTable(msg.seniorStaffList[i]);
			}
		}	 	 
	
	}
	
	function hidePwdExpiryWarning(divName){
		var csrfdata=document.getElementById("csrfparameterName").value;
		csrfdata=csrfdata+"="+document.getElementById("csrfparametervalue").value;
		$.ajax({
		  url: "../admin/hidePwdExpiryWarning.form",
		  data:csrfdata,
		  success: function(){
		    document.getElementById(divName).style.display = 'none';
		  }
		});
	}
	
	
	function callAjaxRequest(formName){ 
		var accessionNumber = document.getElementById('AccessionNumber').value
		if(accessionNumber==""){
		return false;
		}else{
		  // calling action
		  sendRequest(formName, accessionNumber);
		} 
	 }
	 
	function printPatient(formName){  
	  if(confirm('Please confirm that you want to send this patient details to the printer')){	    
	 	 sendRequest(formName, 'null');
	  } 
	}
	
	// Requirement #336(New Images don't get automatically fetched)
	function sendRereferingPatientMsg(selectedValue,formName,informBasingstoke){
		var consultationNoteFormId ;
		var imageTransferMethod;
		var isPrefered;
		if(informBasingstoke == 'null'){
			disablePopup('alreadyReferedId','alreadyReferedIdTable');
		}else{
			if(selectedValue=='YES'){
				if (document.getElementById('imageTransferMethodId').value == 'Select') {
					alert("Please select image transfer method");
					return false;
				}else {
					imageTransferMethod = document.getElementById('imageTransferMethodId').value;					
				}	
			}
			consultationNoteFormId = document.getElementById('consultationNoteFormId').value;
			disablePopup('alreadyReferedImagingFormId','alreadyReferedImagingFormTable');
		}
		var	url = "../referrals/amendedPatientInformation.form";
		var data=document.getElementById("csrfparameterName").value;
		data=data+"="+document.getElementById("csrfparametervalue").value;
		$.ajax({
			   type: "POST",
			   url: url,
			   data: "selectedValue="+selectedValue+"&formName="+formName+"&informBasingstoke="+informBasingstoke+"&consultationNoteFormId="+consultationNoteFormId+"&imageTransferMethod="+imageTransferMethod+"&"+data,		   
			   success: function(msg){
				  if(informBasingstoke== 'null'){
						if(selectedValue =='YES'){
							openMessagesSentWindow();
						}	
						if(formName =='PreTreatmentCTScan' || formName =='PreTreatmentMRIScan' || formName=='PreTreatmentPETCTScan' || formName=='PostChemoCTScan' || formName=='PostChemoMRIScan' || formName=='OtherScan'){
							if(selectedValue =='YES'){
								setTimeout("openAlreadyReferedImagingFormWindow()",4000);							
							}else{
								openAlreadyReferedImagingFormWindow();
							}
						}
				  }else{
					  if(selectedValue =='YES'){
							openAlreadyReferedRespMsgWindow();
						}
				  }
			   }
	 	});
	}
	
	// Requirement #336(New Images don't get automatically fetched)
	function openAlreadyReferedfWindow(){
		 document.getElementById('alreadyReferedId').style.display = '';
		 centerPopup('alreadyReferedId'); 
		 loadPopup('alreadyReferedId');			
	}
	// Requirement #336(New Images don't get automatically fetched)
	function openAlreadyReferedRespMsgWindow(){
		 document.getElementById('alreadyReferdRespMsgId').style.display = '';
		 centerPopup('alreadyReferdRespMsgId'); 
		 loadPopup('alreadyReferdRespMsgId');
		 setTimeout("disablePopup('alreadyReferdRespMsgId','alreadyReferdRespMsgTable')",3000);
	}		
	function openMessagesSentWindow(){
		 document.getElementById('messagesSentDivId').style.display = '';
		 centerPopup('messagesSentDivId'); 
		 loadPopup('messagesSentDivId');
		 setTimeout("disablePopup('messagesSentDivId','messagesSentMsgTable')",3000);
	}		
	
	// Requirement #336(New Images don't get automatically fetched)
	function openAlreadyReferedImagingFormWindow(){
		 document.getElementById('alreadyReferedImagingFormId').style.display = '';
		 centerPopup('alreadyReferedImagingFormId'); 
		 loadPopup('alreadyReferedImagingFormId');			
	}
	// Requirement #336(New Images don't get automatically fetched)
	function openSendRereferingPatientFm(){		
		document.getElementById('alreadyReferedImagingFormId').style.height = '165px';
		document.getElementById('alreadyReferedImagingY&NId').style.display = 'none';
		document.getElementById('alreadyReferedImagingSubId').style.display = '';
	}
	// Requirement #336(New Images don't get automatically fetched)
	function closeSendRereferingPatientFm(){
		document.getElementById('alreadyReferedImagingFormId').style.height = '75px';
		document.getElementById('alreadyReferedImagingY&NId').style.display = '';
		document.getElementById('alreadyReferedImagingSubId').style.display = 'none';
	}
	
	function GetURLParameter(sParam){
	    var sPageURL = window.location.search.substring(1);
	    var sURLVariables = sPageURL.split('&');
   		for (var i = 0; i < sURLVariables.length; i++)
	    {
	      var sParameterName = sURLVariables[i].split('=');
	      if (sParameterName[0] == sParam)
	       {
            return sParameterName[1];
	       }
	    }
	}
	//Finds y value of given object
	function findPos(obj) {
	    var curtop = 0;
	    if (obj.offsetParent) {
	        do {
	            curtop += obj.offsetTop;
	        } while (obj = obj.offsetParent);
	    return [curtop];
	    }
	}
	function confirmLockMeeting(){
		 document.getElementById('lockMeetingId').style.display = '';
		 window.scroll(0,findPos(document.getElementById("lockMeetingId")));
		 centerPopup('lockMeetingId'); 
		 loadPopup('lockMeetingId');			
	}
	function selectSpecialityForNewReferral(){
		 document.getElementById('selectSpecialityId').style.display = '';
		 centerPopup('selectSpecialityId'); 
		 loadPopup('selectSpecialityId');			
	}
	function openSaveReferralsDefinitionAs(){
		 document.getElementById('saveReferralsDefinitionAsId').style.display = '';
		 centerPopup('saveReferralsDefinitionAsId'); 
		 loadPopup('saveReferralsDefinitionAsId');			
	}
	function printSelectedForms(){
		var location="../referrals/openPdfController.form?fileName="
		var tbl = document.getElementById('ajaxFilePathTable'); 	  
	    var elems = tbl.getElementsByTagName ( "input" );
	    var len = elems.length;
	    var fileChecked=false;
	    for ( var i = 0; i < len; i++ ){
	     	if ( elems[i].type == "checkbox" ){
	     		if(elems[i].checked){
	     			fileChecked=true;
	     			location=location+elems[i].id
	     			if(i<len-1){
	     				location=location+"&fileName="
	     			}
	     		}
	     	}
	     }
	    if(fileChecked){
	    	window.open(location);
	    	disablePopup('printPopup','ajaxFilePathTable');
	    }else{
	    	alert("At least one file should be selected for printing.");
	    }
	}
	function selectReferralDetails(){
		document.getElementById('selectReferralDetailsId').style.display = '';
		 centerPopup('selectReferralDetailsId'); 
		 loadPopup('selectReferralDetailsId');	
	}
	function openAttachFilePopup(){
		 document.getElementById('attachFilePopupId').style.display = '';
		 centerPopup('attachFilePopupId'); 
		 loadPopup('attachFilePopupId');			
	}
	function openNoteModificationPopup(){
		 document.getElementById('noteModifiedPopupId').style.display = '';
		 centerPopup('noteModifiedPopupId'); 
		 loadPopup('noteModifiedPopupId');			
	}
	function openColorPickerPopup(inputId){
		document.getElementById('color-picker-container').setAttribute("onclick", "updateInput('"+inputId+"')");
		centerPopup('colorPickerPopupId'); 
		loadPopup('colorPickerPopupId');			
	}