public override void ViewDidLoad ()
		{
			base.ViewDidLoad();
			AppDelegate.pb.Stop();
			try
			{

			//uvDynamicSurgeonview.Add (uvMainSurgeon);
			//svBillingInfo.Add (uvDynamicSurgeonview);
			svBillingInfo.Add(uvProviderView);
			uvBillingProcedureInfo = new UIView (new CGRect (0, Anesheight + 150, 1008, 800));
			uvBillingProcedureInfo.Add (uvProcedureInfo);
			svBillingInfo.Add (uvBillingProcedureInfo);
			
			UITapGestureRecognizer uvpatinetinfoTap = new UITapGestureRecognizer(() => {
				txtpmrn.ResignFirstResponder();
				txtpFirstName.ResignFirstResponder();
				txtpLastName.ResignFirstResponder();
			});
			uvPatientInfo.UserInteractionEnabled = true;
			uvPatientInfo.AddGestureRecognizer(uvpatinetinfoTap);

			txtNotes.Layer.BorderColor = UIColor.Gray.CGColor;
			txtNotes.Layer.BorderWidth = 1;
			txtpmrn.ShouldChangeCharacters = (textField, range, replacement) =>
			{
				int number;
				return replacement.Length == 0 || int.TryParse(replacement, out number);
			};
				this.txtpmrn.ShouldReturn += (textField) => {
					textField.ResignFirstResponder();
					return true;
				};

			
			txtFacility.Enabled = false;
			txtpAge.Enabled = false;

			if (this.procedureDetails != null) {
				if (this.procedureDetails.StatusID == "1" || this.procedureDetails.StatusID == "2")
					btnSubmit.SetTitle (" Finalize", UIControlState.Normal);
					//btnSubmit.text

				if (this.procedureDetails.StatusID == "3") {
					btnSubmit.SetTitle ("Unlock", UIControlState.Normal);
					uvPatientInfo.UserInteractionEnabled = false;
					uvBillingInfo.UserInteractionEnabled = false;
					uvQualityMetrics.UserInteractionEnabled = false;
				}
			}


			InvokeOnMainThread (async () => {	
				ReceiveContext surgeons = await AppDelegate.Current.pqrsMgr.GetSurgeons();
				if (surgeons != null && surgeons.result != null && surgeons.status !=null && surgeons.status.ToUpper() =="OK") {
					lstOfSurgeons = (List<SurgeonDetails>)JsonConvert.DeserializeObject (surgeons.result.ToString (), typeof(List<SurgeonDetails>));
				 }
				 else
					NavigationController.PopToRootViewController(true);

				if (this.procedureDetails != null) {
					ReceiveContext selectedSurgeonOfProcedure = await AppDelegate.Current.pqrsMgr.GetSelectedSurgeonOfProcedure(this.procedureDetails.ID);
						if (selectedSurgeonOfProcedure != null && selectedSurgeonOfProcedure.result != null && surgeons.status !=null && surgeons.status.ToUpper() =="OK") {
						selectedSurgeon = (List<ProcedureSurgeonDetails>)JsonConvert.DeserializeObject (selectedSurgeonOfProcedure.result.ToString (), typeof(List<ProcedureSurgeonDetails>));
						if(selectedSurgeon.Count > 0)
						{
							lblSurgeon.Text = selectedSurgeon[0].Name;
							SurgeonID=selectedSurgeon[0].SurgeonID;
						}
					}
					else if (selectedSurgeonOfProcedure != null && selectedSurgeonOfProcedure.result != null && surgeons.status !=null && surgeons.status.ToUpper() =="ERROR")
						NavigationController.PopToRootViewController(true);						
					else
					   selectedSurgeon[0].ProcSurgeonID = 0;
				}
				BindSurgeon(lstOfSurgeons);

			});
				AddBasicProviderView ();
//			InvokeOnMainThread (async () => {	
//				ReceiveContext users = await AppDelegate.Current.pqrsMgr.GetUsers();
//				List<UserDetails> lstOfUsers = new List<UserDetails>();
//				if(users != null && users.result != null) {
//					lstOfUsers = (List<UserDetails>)JsonConvert.DeserializeObject (users.result.ToString (), typeof(List<UserDetails>));
//					listOfAnestheologists = lstOfUsers.FindAll(x => x.Role == "Anesthesiologist");
//					listOfCRNAs = lstOfUsers.FindAll(x => x.Role == "CRNA");
//						AddBasicProviderView ();
//
//				}
//			});

//			btnCamera.TouchUpInside += async delegate {
//				Camera.TakePicture (this, (obj) =>{
//					var photo = obj.ValueForKey(new NSString("UIImagePickerControllerOriginalImage")) as UIImage;
//					var documentsDirectory = Environment.GetFolderPath
//						(Environment.SpecialFolder.Personal);
//					string jpgFilename = System.IO.Path.Combine (documentsDirectory, DateTime.Now.Millisecond+".jpg"); // hardcoded filename, overwritten each time
//					NSData imgData = photo.AsJPEG();
//					NSError err = null;
//					if (imgData.Save(jpgFilename, false, out err)) {
//						Console.WriteLine("saved as " + jpgFilename);
//					} else {
//						Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
//					}
//				});					
//			};

//				btnViewCam.TouchUpInside += async delegate {
//					try
//					{
//						var documentsDirectory = Environment.GetFolderPath
//							(Environment.SpecialFolder.Personal);
//
//						string jpgFilename = System.IO.Path.Combine (documentsDirectory, "PQRS.jpg");
//						List<UIImageView> currentImagelist=new List<UIImageView>(); 
//						UIImageView viewi = null;
//
//						UIImage imageToAdd = UIImage.FromFile(jpgFilename);
//						viewi= new UIImageView ();
//						if(imageToAdd == null)
//							return;
//
//						viewi.Image=imageToAdd;
//						currentImagelist.Add(viewi);
//
//						//				foreach (string eachImage in Directory.GetFiles(documentsDirectory, "*jpg"))
//						//				{
//						//					viewi= new UIImageView ();
//						//
//						//
//						//					using (UIImage imageToAdd = UIImage.FromFile(eachImage))
//						//					{
//						//						viewi.Image=imageToAdd;
//						//						currentImagelist.Add(viewi);
//						//					}
//						//
//						//				}
//
//						viewimg=new ImagesGalleryView();
//						if(currentImagelist.Count>0)
//							viewimg.currentImagelist.Add(currentImagelist[currentImagelist.Count-1]);
//
//						viewimg.PresentFromPopover(btnViewCam,10,10,480);
//						viewimg.Dispose();
//					}
//					catch (Exception ex)
//					{
//						string str=ex.Message;
//					}					
//				};

//				btnFaceShtViewCam.TouchUpInside += async delegate {
//					try
//					{
//						var documentsDirectory = Environment.GetFolderPath
//							(Environment.SpecialFolder.Personal);
//
//						string jpgFilename = System.IO.Path.Combine (documentsDirectory, "PQRS.jpg");
//						List<UIImageView> currentImagelist=new List<UIImageView>(); 
//						UIImageView viewi = null;
//
//						UIImage imageToAdd = UIImage.FromFile(jpgFilename);
//						viewi= new UIImageView ();
//						if(imageToAdd == null)
//							return;
//
//						viewi.Image=imageToAdd;
//						currentImagelist.Add(viewi);
//
//						//				foreach (string eachImage in Directory.GetFiles(documentsDirectory, "*jpg"))
//						//				{
//						//					viewi= new UIImageView ();
//						//
//						//
//						//					using (UIImage imageToAdd = UIImage.FromFile(eachImage))
//						//					{
//						//						viewi.Image=imageToAdd;
//						//						currentImagelist.Add(viewi);
//						//					}
//						//
//						//				}
//
//						viewimg=new ImagesGalleryView();
//						if(currentImagelist.Count>0)
//							viewimg.currentImagelist.Add(currentImagelist[currentImagelist.Count-1]);
//
//						viewimg.PresentFromPopover(btnFaceShtViewCam,10,10,480);
//						viewimg.Dispose();
//					}
//					catch (Exception ex)
//					{
//						string str=ex.Message;
//					}					
//				};
//			btnFaceShtCam.TouchUpInside += async delegate {
//				Camera.TakePicture (this, (obj) =>{
//					var photo = obj.ValueForKey(new NSString("UIImagePickerControllerOriginalImage")) as UIImage;
//					var documentsDirectory = Environment.GetFolderPath
//						(Environment.SpecialFolder.Personal);
//					string jpgFilename = System.IO.Path.Combine (documentsDirectory, DateTime.Now.Millisecond+".jpg"); // hardcoded filename, overwritten each time
//					NSData imgData = photo.AsJPEG();
//					NSError err = null;
//					if (imgData.Save(jpgFilename, false, out err)) {
//						Console.WriteLine("saved as " + jpgFilename);
//					} else {
//						Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
//					}
//				});					
//			};


			ProcAttribTypes();

			ViewQualityMetrics (pqrsTypes, pqrsTypeOptions, "PQRS");	
			ViewQualityMetrics (nonPqrsTypes, nonPqrsTypeOptions, "NON PQRS");	
			svQualityMetrics.SizeToFit ();
			svQualityMetrics.ContentSize = new SizeF (float.Parse (svQualityMetrics.Frame.Width.ToString ()), float.Parse (svQualityMetrics.Frame.Height.ToString ())+hUV-250);
			BindAllTypes();
			BindAllControlWithText();

				if (patientProfile != null && patientProfile.ID != 0) {
					if (this.procedureDetails.StatusID == "2" || this.procedureDetails.StatusID == "1")
					{
						//uvQualityMetrics.UserInteractionEnabled = true;
						Setenableanddiablelbl(true);
					}
					else if (this.procedureDetails.StatusID == "3")
					{
						//uvDynamicQualityMetrics.UserInteractionEnabled = false;
						//svQualityMetrics.UserInteractionEnabled = false;
						Setenableanddiablelbl(false);
					}
					btnSubmit.Hidden=false;
				}
				else
					btnSubmit.Hidden=true;
			if (this.procedureDetails == null) {
				if (iProPQRSPortableLib.Consts.Role == "Anesthesiologist") {
					//btnAnes1.SetTitle (iProPQRSPortableLib.Consts.LoginUserFullName, UIControlState.Normal);
				}
			} else {
				if (this.procedureDetails.Anesthesiologist1 != null && this.procedureDetails.Anesthesiologist1.Trim () == string.Empty) {
					if (iProPQRSPortableLib.Consts.Role == "Anesthesiologist") {
						//btnAnes1.SetTitle (iProPQRSPortableLib.Consts.LoginUserFullName, UIControlState.Normal);
					}
				}

				InvokeOnMainThread (async () => {	
					ReceiveContext procParticipants = await AppDelegate.Current.pqrsMgr.GetProcedureParticipants(this.procedureDetails.ID);
						if(procParticipants != null && procParticipants.result != null && procParticipants.status !=null && procParticipants.status.ToUpper() =="OK" ) {
						listOfProcParticiPants = (List<ProcedureParticipantDetails>)JsonConvert.DeserializeObject (procParticipants.result.ToString (), typeof(List<ProcedureParticipantDetails>));
						selectedAnestheologistList = listOfProcParticiPants.FindAll(x => x.RoleID == 2);
						selectedAnestheologistList = selectedAnestheologistList.OrderBy( x => x.ProcParticipantID).ToList();

						selectedCRNAList = listOfProcParticiPants.FindAll(x => x.RoleID == 6);
						selectedCRNAList = selectedCRNAList.OrderBy( x => x.ProcParticipantID).ToList();

						int i = 0;
						foreach (var item in selectedAnestheologistList) {
							AddAnesView(selectedAnestheologistList[i]);
							i++;
						}

						int j = 0;
						foreach (var item in selectedCRNAList) {
							AddCRNAView(selectedCRNAList[j]);
							j++;
						}

						if(selectedAnestheologistList.Count == 0)
							AddAnesView(null);

						if(selectedCRNAList.Count == 0)
							AddCRNAView(null);		
					}
					else
						NavigationController.PopToRootViewController(true);
				});


			}

			if (this.procedureDetails != null) {
				if (this.procedureDetails.StatusID == "0" || this.procedureDetails.StatusID == "1")
						tctSurgeryDate.Enabled = false;
				
				if (this.procedureDetails.StatusID == "2" || this.procedureDetails.StatusID == "3")
					tctSurgeryDate.Enabled = false;
			}

			tctSurgeryDate.Text = DateTime.Now.ToString("MM/dd/yyyy");
			uSEmergency.SetState (false, false);

			FacilityDetails fac = iProPQRSPortableLib.Consts.Facilities.result.Find (u => u.FMID.ToString() == iProPQRSPortableLib.Consts.SelectedFacilityID);
			txtFacility.Text = fac.FacilityName;

			NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.DidShowNotification, KeyBoardUpNotification);
			NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification, KeyBoardDownNotification);


			PatientsBackBtn.TouchUpInside+= (object sender, EventArgs e) => {
				this.NavigationController.PopViewController(true);
			};
			//start patient infromation
		
			SetViewBorderColor ();

			BindDropDown ();
			if (procedureDetails == null) {
				sCtab.SetEnabled (false, 1);
				sCtab.SetEnabled (false, 2);
			} else {
				sCtab.SetEnabled (true, 1);
				sCtab.SetEnabled (true, 2);
			}
			svuvBillingInfo.Frame=uvBillingInfo.Frame;
				svuvBillingInfo.SizeToFit ();
				svuvBillingInfo.ContentSize = new SizeF (float.Parse (svuvBillingInfo.Frame.Width.ToString ()), float.Parse (svuvBillingInfo.Frame.Height.ToString ())+430);
			svuvBillingInfo.Add(uvBillingInfo);

			sCtab.ValueChanged += (object sender, EventArgs e) => {
				uvMainPatientinfo.RemoveFromSuperview ();
				uvDynamicQualityMetrics.RemoveFromSuperview ();
					svuvBillingInfo.RemoveFromSuperview ();
				if (sCtab.SelectedSegment == 0){
					uvMain.AddSubview (uvPatientInfo);
				}else if (sCtab.SelectedSegment == 1){
						if(!anesadded){
							AddAnesView(null);
						}
						if(!crnaadded){
							AddCRNAView(null);
						}
						uvMain.AddSubview (svuvBillingInfo);
				}else if (sCtab.SelectedSegment == 2) {
					uvMain.AddSubview (uvDynamicQualityMetrics);
				} 

			};
				lblProcID.Hidden = true;
			///End patient infromation
			// Perform any additional setup after loading the view, typically from a nib.

			// start Quality metrics
			DropReason.Hidden=true;
			uSwitchCaseCanceled.ValueChanged+= (object sender, EventArgs e) => {
				if(uSwitchCaseCanceled.On)
				{
					uvPreIntraOp.Hidden=true;
					DropReason.Hidden=false;
				}
				else
				{
					uvPreIntraOp.Hidden=false;
					DropReason.Hidden=true;
				}
			};

			SliderPreopPainScore.ValueChanged+= (object sender, EventArgs e) => {				
				LblPreopPainScoreValue.Text=((int)Math.Round(SliderPreopPainScore.Value,0)).ToString();
			};

			uvScrollview.ContentSize = new CoreGraphics.CGSize (0, 1350);
			dropPotoc.Hidden = true;
			scPotoc.ValueChanged+= (object sender, EventArgs e) => {
				dropPotoc.Hidden=false;
			};
			scAnyUnwanted.ValueChanged+= (object sender, EventArgs e) => {

				if(scAnyUnwanted.SelectedSegment==0)
					dropAnyUnwanted.Hidden=false;
				else
					dropAnyUnwanted.Hidden=true;
			};
			// End Quality metrics
//			SignatureView vns=new SignatureView(new System.Drawing.RectangleF(0f,0f,(float)uvNurseSignaturevalue.Bounds.Width,(float)uvNurseSignaturevalue.Bounds.Height));
//			uvNurseSignaturevalue.AddSubview(vns);
//			SignatureView vps=new SignatureView(new System.Drawing.RectangleF(0f,0f,(float)uvPatientSignature.Bounds.Width,(float)uvPatientSignature.Bounds.Height));
//			uvPatientSignature.AddSubview (vps);

			if (patientProfile != null && patientProfile.ID != 0) {
				lblFullName.Text = patientProfile.LastName.Trim () + ", " + patientProfile.FirstName.Trim ();
				mrnLbl.Text = "MRN: " + patientProfile.MRN.Trim ();
				txtpmrn.Text = patientProfile.MRN;
				txtpmrn.Enabled = false;
				txtpFirstName.Text = patientProfile.FirstName;
				txtpLastName.Text = patientProfile.LastName;

				if (txtpmrn.Text.Trim () != string.Empty) {
//					lblMRN.Text = "MRN";
					txtpmrn.Layer.BorderColor = UIColor.Gray.CGColor;
				} else {
//					lblMRN.Text = "*MRN";
					txtpmrn.Layer.BorderColor = UIColor.Red.CGColor;
					txtpmrn.Layer.BorderWidth = 1f;
					txtpmrn.Layer.CornerRadius = (nfloat)8.0; 
				}

				if (txtpFirstName.Text.Trim () != string.Empty) {
//					lblFirstName.Text = "First Name";
					txtpFirstName.Layer.BorderColor = UIColor.Gray.CGColor;
				} else {
//					lblFirstName.Text = "*First Name";
					txtpFirstName.Layer.BorderColor = UIColor.Red.CGColor;
					txtpFirstName.Layer.BorderWidth = 1f;
					txtpFirstName.Layer.CornerRadius = (nfloat)8.0; 
				}

				if (txtpLastName.Text.Trim () != string.Empty) {
//					lblLastName.Text = "Last Name";
					txtpLastName.Layer.BorderColor = UIColor.Gray.CGColor;
				} else {
//					lblLastName.Text = "*Last Name";
					txtpLastName.Layer.BorderColor = UIColor.Red.CGColor;
					txtpLastName.Layer.BorderWidth = 1f;
					txtpLastName.Layer.CornerRadius = (nfloat)8.0; 
				}

				string patientGender = string.Empty;
				if (!string.IsNullOrEmpty (patientProfile.Sex)) {
					switch (patientProfile.Sex.Trim ().ToLower ()) {
					case	"m":
						patientGender = "Male";
							patientGenderID=1;
						break;
					case "f":
						patientGender = "Female";
							patientGenderID=2;
						break;
					//case "u":
					//	patientGender = "Unknown";
						//	patientGenderID=3;
					//	break;
					default:
						break;
					} 
				}

				btnPatientGender.SetTitle (patientGender, UIControlState.Normal);
				string tempDOB;
					//patientGenderID

				if (!string.IsNullOrEmpty (patientProfile.DOB)) {
					tempDOB = Convert.ToDateTime (patientProfile.DOB).ToString ("MM/dd/yyyy");
					txtpDOB.Text = tempDOB;

					int age = DateTime.Now.Year - Convert.ToDateTime (patientProfile.DOB).Year;
					txtpAge.Text = age.ToString ();
				}

				string surgeryDate;
				if (!string.IsNullOrEmpty (procedureDetails.OperationDate)) {
					surgeryDate = Convert.ToDateTime (procedureDetails.OperationDate).ToString ("MM/dd/yyyy");
					tctSurgeryDate.Text = surgeryDate;
				}

				if (patientProfile.DiagnosticList != null && patientProfile.DiagnosticList.Count > 0) {
					foreach (var item in patientProfile.DiagnosticList) {
						NewDiagnosis (item.Code, item.Name);
						selectedDiagnosisCodeid.Add (item.ProcCodeID);
					}
				} else 
					NewDiagnosis (string.Empty, string.Empty);

				if(patientProfile.ProcedureList != null && patientProfile.ProcedureList.Count > 0){
					foreach (var item in patientProfile.ProcedureList) {
						AddProcedure (item.Code, item.Name);
						selectedprocedureCodeid.Add (item.ProcCodeID);
					}
				}else
					AddProcedure (string.Empty, string.Empty);
			} else {
//				lblMRN.Text = "*MRN";
//				lblFirstName.Text = "*First Name";
//				lblLastName.Text = "*Last Name";
				txtpmrn.Layer.BorderColor = UIColor.Red.CGColor;
				txtpFirstName.Layer.BorderColor = UIColor.Red.CGColor;
				txtpLastName.Layer.BorderColor = UIColor.Red.CGColor;
				txtpmrn.Layer.BorderWidth = 1f;
				txtpFirstName.Layer.BorderWidth = 1f;
				txtpLastName.Layer.BorderWidth = 1f;
				txtpmrn.Layer.CornerRadius = (nfloat)8.0; 
				txtpFirstName.Layer.CornerRadius = (nfloat)8.0; 
				txtpLastName.Layer.CornerRadius = (nfloat)8.0; 
			}

			//Kumar start
			if (procedureDetails == null ) {
				EncounterBtn.Enabled = false;
				PhysicalStatusBtn.Enabled = false;
				uSEmergency.Enabled = false;
				addNewDiagnosis.Enabled = false;
				deleteDiagnosis.Enabled = false;
				removeProc.Enabled = false;
				addNewProc.Enabled = false;
				NewDiagnosis (string.Empty, string.Empty);
				AddProcedure (string.Empty, string.Empty);
			}else
					lblProcID.Text = "Proc ID: "+procedureDetails.ID.ToString ();
			
			if (procedureDetails != null &&  !string.IsNullOrEmpty(procedureDetails.ddlEncounterType)) {
				EncounterBtn.SetTitle (procedureDetails.ddlEncounterType, UIControlState.Normal);
				if(dEncounterTypelist != null && dEncounterTypelist.Count > 0)
					encounterTypeid = dEncounterTypelist.Where (w => w.DropDownText.ToUpper().Trim() == procedureDetails.ddlEncounterType.ToUpper().Trim()).Select (s => s.DropDownID).SingleOrDefault ();
			}
			if (procedureDetails != null &&  !string.IsNullOrEmpty(procedureDetails.ddlASAType)) {
				string btntxt;
				if (dlPhyStatusList != null && dlPhyStatusList.Count > 0)
					physicalStatus = Convert.ToInt16 (procedureDetails.ddlASAType);
				btntxt = dlPhyStatusList.Where (w => w.DropDownID ==Convert.ToInt16(procedureDetails.ddlASAType)).Select (s => s.DropDownText).SingleOrDefault ();
				PhysicalStatusBtn .SetTitle (btntxt, UIControlState.Normal);

			}
			if (procedureDetails != null && !string.IsNullOrEmpty (procedureDetails.cbEmergency)) {
				Emergency = procedureDetails.cbEmergency;
				if (procedureDetails.cbEmergency == "1")
					uSEmergency.On = true;
				else
					uSEmergency.On = false;
			}
			//Kumar end
			
				tctSurgeryDate.ShouldBeginEditing += delegate {
					DatePicker  dp=new DatePicker();

					CoreGraphics.CGRect f=tctSurgeryDate.Frame;
					dp.PresentFromPopover(this.View,float.Parse(f.X.ToString()),float.Parse(f.Y.ToString())+100);
					dp._ValueChanged += delegate {	
						tctSurgeryDate.Text=dp.SelectedDate;
						string format = "MM/dd/yyyy"; 
						DateTime surgeryDate = DateTime.ParseExact(tctSurgeryDate.Text, format,System.Globalization.CultureInfo.CurrentCulture);

						if(DateTime.Now.Date < surgeryDate){
							sCtab.SetEnabled (false, 1);
							sCtab.SetEnabled (false, 2);
						}
					};
					return false;
				};

			//tctSurgeryDate.EditingDidBegin+= (object sender, EventArgs e) => {
					
			//};

			txtpDOB.ShouldBeginEditing += delegate {
					txtpmrn.ResignFirstResponder();
					txtpFirstName.ResignFirstResponder();
					txtpLastName.ResignFirstResponder();
			 	DatePicker  dp = new DatePicker();
					dp.MaximumDate=DateTime.Now;
				if(!string.IsNullOrEmpty(txtpDOB.Text))
					{
						//DateTime dtval=DateTime.ParseExact(txtpDOB.Text,"MM/dd/yyyy",System.Globalization.CultureInfo.InvariantCulture);
						string format = "MM/dd/yyyy"; 
						DateTime dt = DateTime.ParseExact(txtpDOB.Text, format,System.Globalization.CultureInfo.CurrentCulture);
						dp.SelectedDateValue=dt;
					}

				CoreGraphics.CGRect f = txtpDOB.Frame;
				dp.PresentFromPopover(this.View,float.Parse(f.X.ToString()),float.Parse(f.Y.ToString())+100);
				dp._ValueChanged += delegate {	
					if(dp.SelectedDateValue != DateTime.MinValue){	
						int age = DateTime.Now.Year - dp.SelectedDateValue.Year;
						if((dp.SelectedDateValue.Month > DateTime.Now.Month) || (dp.SelectedDateValue.Month == DateTime.Now.Month && dp.SelectedDateValue.Day > DateTime.Now.Day))
							age--;
						//this.mPatient.DOB = dp.SelectedDate;
								
							txtpDOB.Text=dp.SelectedDateValue.ToString ("MM/dd/yyyy");
						txtpAge.Text=age.ToString();
					}else{
						txtpDOB.Text = string.Empty;
						txtpAge.Text = string.Empty;
					}
					SavePatientInfo();
				};

				return false;
			};


			txtpFirstName.EditingDidEnd += async (object sender, EventArgs e) => {
					showKeyBoard = false;
					txtpmrn.ResignFirstResponder();
					txtpFirstName.ResignFirstResponder();
					txtpLastName.ResignFirstResponder();

				SavePatientInfo();
				if (txtpFirstName.Text.Trim () != string.Empty){
//					lblFirstName.Text = "First Name";
					txtpFirstName.Layer.BorderColor = UIColor.Gray.CGColor;
				}else{
//					lblFirstName.Text = "*First Name";
					txtpFirstName.Layer.BorderColor = UIColor.Red.CGColor;
					txtpFirstName.Layer.CornerRadius = (nfloat)8.0; 
				}
			};

			txtpLastName.EditingDidEnd += async (object sender, EventArgs e) => {
					showKeyBoard = false;
					txtpmrn.ResignFirstResponder();
					txtpFirstName.ResignFirstResponder();
					txtpLastName.ResignFirstResponder();

				SavePatientInfo();
				if (txtpLastName.Text.Trim () != string.Empty){
//					lblLastName.Text = "Last Name";
					txtpLastName.Layer.BorderColor = UIColor.Gray.CGColor;
				}else{
//					lblLastName.Text = "*Last Name";
					txtpLastName.Layer.BorderColor = UIColor.Red.CGColor;
					txtpLastName.Layer.CornerRadius = (nfloat)8.0; 
				}
			};	
				this.View.EndEditing(true);
			//	txtpmrn.Delegate= new KeyBoardHideTextFieldDelegate();
			txtpmrn.EditingDidEnd+= async (object sender, EventArgs e) => {
					showKeyBoard = false;
					txtpmrn.ResignFirstResponder();
					txtpFirstName.ResignFirstResponder();
					txtpLastName.ResignFirstResponder();

				if(!string.IsNullOrEmpty(txtpmrn.Text))
				{
					AppDelegate.pb.Start(this.View,"Please wait...");
					ReceiveContext context = new ReceiveContext();
					context = await serv.CheckExistingPatintInfo(txtpmrn.Text,iProPQRSPortableLib.Consts.SelectedFacilityID);				
					if(context.result!=null && context.status !=null && context.status.ToUpper() =="OK")
					{
						Patient patientDetails = (Patient)JsonConvert.DeserializeObject(context.result.ToString() , typeof(Patient));
						EncounterBtn.Enabled = true;
						PhysicalStatusBtn.Enabled = true;
						uSEmergency.Enabled = true;
						addNewDiagnosis.Enabled = true;
						deleteDiagnosis.Enabled = true;
						removeProc.Enabled = true;
						addNewProc.Enabled = true;

						if(patientDetails!=null){						
							patientProfile = patientDetails;
								lblFullName.Text = patientDetails.LastName.Trim() + ", " + patientDetails.FirstName.Trim();
							mrnLbl.Text = "MRN: " + patientDetails.MRN.Trim();

							txtpmrn.Text = patientDetails.MRN;
							txtpFirstName.Text = patientDetails.FirstName;
							txtpLastName.Text = patientDetails.LastName;
							if (txtpmrn.Text.Trim () != string.Empty) {
//								lblMRN.Text = "MRN";
								txtpmrn.Layer.BorderColor = UIColor.Gray.CGColor;
							} else {
//								lblMRN.Text = "*MRN";
								txtpmrn.Layer.BorderColor = UIColor.Red.CGColor;
								txtpmrn.Layer.BorderWidth = 1f;
							}

							if (txtpFirstName.Text.Trim () != string.Empty) {
//								lblFirstName.Text = "First Name";
								txtpFirstName.Layer.BorderColor = UIColor.Gray.CGColor;
							} else {
//								lblFirstName.Text = "*First Name";
								txtpFirstName.Layer.BorderColor = UIColor.Red.CGColor;
								txtpFirstName.Layer.BorderWidth = 1f;
							}

							if (txtpLastName.Text.Trim () != string.Empty) {
//								lblLastName.Text = "Last Name";
								txtpLastName.Layer.BorderColor = UIColor.Gray.CGColor;
							} else {
//								lblLastName.Text = "*Last Name";
								txtpLastName.Layer.BorderColor = UIColor.Red.CGColor;
								txtpLastName.Layer.BorderWidth = 1f;
							}
								DateTime tDOB=Convert.ToDateTime (patientDetails.DOB);
								txtpDOB.Text = tDOB.ToString ("MM/dd/yyyy");

							int age = DateTime.Now.Year - Convert.ToDateTime (patientDetails.DOB).Year;
								if((tDOB.Month > DateTime.Now.Month) || (tDOB.Month == DateTime.Now.Month && tDOB.Day > DateTime.Now.Day))
									age--;
							txtpAge.Text = age.ToString ();
								//btnSubmit.Hidden=false
							//Nahid Ahmed Aug 4, 2015
							//As per Raj, dont populate Physical Status, Encounter and Emergency from Patient Details
							//as these items belong to procedures.
							/* DropDownModel pitem = dlPhyStatusList.Find (u => u.DropDownText == patientDetails.ddlASAType);
							if (pitem != null) {
								PhysicalStatusBtn.SetTitle (pitem.DropDownText, UIControlState.Normal);
								physicalStatus = pitem.DropDownID;
							} else {
								PhysicalStatusBtn.SetTitle ("Select", UIControlState.Normal);
								physicalStatus = 0;
							}

							DropDownModel eitem = dEncounterTypelist.Find (u => u.DropDownText == patientDetails.ddlEncounterType);
							if (eitem != null) {
								EncounterBtn.SetTitle (eitem.DropDownText, UIControlState.Normal);
								encounterTypeid = eitem.DropDownID;
							} else {
								EncounterBtn.SetTitle ("Select", UIControlState.Normal);
								encounterTypeid = 0;
							}

							if (patientDetails.cbEmergency != null && patientDetails.cbEmergency.Trim().ToLower () == "on")
								uSEmergency.SetState (true, false);
							else
								uSEmergency.SetState (false, false); */

						}
							else if(context.result!=null && context.status !=null && context.status.ToUpper() =="ERROR")
								NavigationController.PopToRootViewController(true);
							else{
							//	txtpmrn.Text = "";
							lblMRN.Text = "MRN";
							txtpmrn.Layer.BorderColor = UIColor.Gray.CGColor;
							txtpmrn.Layer.BorderWidth = 1f;

//							lblFirstName.Text = "*First Name";
//							lblLastName.Text = "*Last Name";
							txtpFirstName.Layer.BorderColor = UIColor.Red.CGColor;
							txtpLastName.Layer.BorderColor = UIColor.Red.CGColor;

							txtpFirstName.Layer.BorderWidth = 1f;
							txtpLastName.Layer.BorderWidth = 1f;
							txtpmrn.Layer.CornerRadius = (nfloat)8.0; 
							txtpFirstName.Layer.CornerRadius = (nfloat)8.0; 
							txtpLastName.Layer.CornerRadius = (nfloat)8.0; 


							txtpFirstName.Text = "";
							txtpLastName.Text = "";
							txtpDOB.Text = "";
							mrnLbl.Text = "";
							lblFullName.Text = "";
						}
						AppDelegate.pb.Stop();
					}
						else if(context.result!=null && context.status !=null && context.status.ToUpper() =="ERROR")
						NavigationController.PopToRootViewController(true);
					else{
						//	txtpmrn.Text = "";
							//	txtpmrn.Text = "";
							if (txtpmrn.Text.Trim () != string.Empty) {
//								lblMRN.Text = "MRN";
								txtpmrn.Layer.BorderColor = UIColor.Gray.CGColor;
							} else {
//								lblMRN.Text = "*MRN";
								txtpmrn.Layer.BorderColor = UIColor.Red.CGColor;
								txtpmrn.Layer.BorderWidth = 1f;
								txtpmrn.Layer.CornerRadius = (nfloat)8.0; 
							}
//							lblFirstName.Text = "*First Name";
//							lblLastName.Text = "*Last Name";						
							txtpFirstName.Layer.BorderColor = UIColor.Red.CGColor;
							txtpLastName.Layer.BorderColor = UIColor.Red.CGColor;						
							txtpFirstName.Layer.BorderWidth = 1f;
							txtpLastName.Layer.BorderWidth = 1f;

							txtpFirstName.Layer.CornerRadius = (nfloat)8.0; 
							txtpLastName.Layer.CornerRadius = (nfloat)8.0; 

							txtpFirstName.Text = "";
							txtpLastName.Text = "";
							txtpDOB.Text = "";
							mrnLbl.Text="";
							lblFullName.Text="";
							EncounterBtn.Enabled = false;
							PhysicalStatusBtn.Enabled = false;
							uSEmergency.Enabled = false;
							addNewDiagnosis.Enabled = false;
							deleteDiagnosis.Enabled = false;
							removeProc.Enabled = false;
							addNewProc.Enabled = false;

					}
				}else{
//					lblMRN.Text = "*MRN";
					txtpmrn.Layer.BorderColor = UIColor.Red.CGColor;
					txtpmrn.Layer.CornerRadius = (nfloat)8.0; 
				}
				
				AppDelegate.pb.Stop();
			};
			
				this.txtpmrn.ShouldReturn += (textField) => { 
					txtpmrn.ResignFirstResponder();
					txtpFirstName.ResignFirstResponder();
					txtpLastName.ResignFirstResponder();
					textField.ResignFirstResponder();
					return true; 
				};
				txtpFirstName.ShouldReturn += (textField) => { 
					txtpmrn.ResignFirstResponder();
					txtpFirstName.ResignFirstResponder();
					txtpLastName.ResignFirstResponder();

					textField.ResignFirstResponder();
					return true; 
				};
				txtpLastName.ShouldReturn += (textField) => { 
					txtpmrn.ResignFirstResponder();
					txtpFirstName.ResignFirstResponder();
					txtpLastName.ResignFirstResponder();
					textField.ResignFirstResponder();
					return true; 
				};
				txtpDOB.ShouldReturn += (textField) => { 
					txtpmrn.ResignFirstResponder();
					txtpFirstName.ResignFirstResponder();
					txtpLastName.ResignFirstResponder();
					textField.ResignFirstResponder();
					return true; 
				};
			btnSubmit.TouchUpInside+= async (object sender, EventArgs e) => {
//				SavePatientInfo();
				if(this.procedureDetails != null){

					
						
						bool chechvalidation=await submitFinalizecase();

						
					//ValidateAndUpdateProcedure(string.Empty,string.Empty);
				}
			};

			addNewDiagnosis.TouchUpInside += (object sender, EventArgs e) => {
				NewDiagnosis (string.Empty,string.Empty);
			};
			deleteDiagnosis.TouchUpInside += async (object sender, EventArgs e) => {
				//RemoveDiagnosis();
				DeleteDiagnosis();
			};


		




			addNewProc.TouchUpInside += (object sender, EventArgs e) => {
				AddProcedure(string.Empty,string.Empty);
			};
			removeProc.TouchUpInside += async (object sender, EventArgs e) => {
				//RemoveProcedures();
				DeleteProcedures();
			};
			 
			//billing info start
			svBillingInfo.SizeToFit ();
			svBillingInfo.ContentSize = new SizeF (float.Parse (svBillingInfo.Frame.Width.ToString ()), float.Parse (svBillingInfo.Frame.Height.ToString ())+500);
			//billing info End


				int mw=MeasureTextLine(lblNerveBlock.Text);
				int maxheight=30;
				if(mw>500)
				{
					maxheight=55;
					lblNerveBlock.Lines=2;
				}
				else if(mw> 1000)
				{
					maxheight=80;
					lblNerveBlock.Lines=2;
				}
				CoreGraphics.CGRect fram=lblNerveBlock.Frame;
				fram.Height=maxheight;
				lblNerveBlock.Frame=fram;


			}
			catch (Exception ex) {
				NavigationController.PopToRootViewController(true);
				//new UIAlertView("Procedure Info", "Successfully Saved."	, null, "ok", null).Show();
			}
		}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			ProcAttribTypes ();
			txtAnesthesiaTechs.EditingDidBegin += (object sender, EventArgs e) => {
				BindAnesthesiaTechniques(anesTechItems);
			};
			tctSurgeryDate.Enabled = false;
			tctSurgeryDate.Text = DateTime.Now.ToString("MM/dd/yyyy");
			uSEmergency.SetState (false, false);

			FacilityDetails fac = iProPQRSPortableLib.Consts.Facilities.result.Find (u => u.FMID.ToString() == iProPQRSPortableLib.Consts.SelectedFacilityID);
			txtFacility.Text = fac.FacilityName;


			NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.DidShowNotification, KeyBoardUpNotification);
			NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification, KeyBoardDownNotification);


			PatientsBackBtn.TouchUpInside+= (object sender, EventArgs e) => {
				this.NavigationController.PopViewController(true);
			};
			//start patient infromation
		
			SetViewBorderColor ();

			BindDropDown ();
			sCtab.ValueChanged += (object sender, EventArgs e) =>  {
				uvMainPatientinfo.RemoveFromSuperview ();
				uvQualityMetrics.RemoveFromSuperview ();
				uvBillingInfo.RemoveFromSuperview ();
				if (sCtab.SelectedSegment == 0)
					uvMain.AddSubview (uvPatientInfo);
				else
					if (sCtab.SelectedSegment == 2)
						uvMain.AddSubview (uvQualityMetrics);
					else
						if (sCtab.SelectedSegment == 1)
							uvMain.AddSubview (uvBillingInfo);
			};
			///End patient infromation
			// Perform any additional setup after loading the view, typically from a nib.

			// start Quality metrics
			DropReason.Hidden=true;
			uSwitchCaseCanceled.ValueChanged+= (object sender, EventArgs e) => {
				if(uSwitchCaseCanceled.On)
				{
					uvPreIntraOp.Hidden=true;
					DropReason.Hidden=false;
				}
				else
				{
					uvPreIntraOp.Hidden=false;
					DropReason.Hidden=true;
				}
			};

			SliderPreopPainScore.ValueChanged+= (object sender, EventArgs e) => {				
				LblPreopPainScoreValue.Text=((int)Math.Round(SliderPreopPainScore.Value,0)).ToString();
			};

			uvScrollview.ContentSize = new CoreGraphics.CGSize (0, 1450);
			dropPotoc.Hidden = true;
			scPotoc.ValueChanged+= (object sender, EventArgs e) => {
				dropPotoc.Hidden=false;
			};
			scAnyUnwanted.ValueChanged+= (object sender, EventArgs e) => {

				if(scAnyUnwanted.SelectedSegment==0)
					dropAnyUnwanted.Hidden=false;
				else
					dropAnyUnwanted.Hidden=true;
			};
			// End Quality metrics
//			SignatureView vns=new SignatureView(new System.Drawing.RectangleF(0f,0f,(float)uvNurseSignaturevalue.Bounds.Width,(float)uvNurseSignaturevalue.Bounds.Height));
//			uvNurseSignaturevalue.AddSubview(vns);
//			SignatureView vps=new SignatureView(new System.Drawing.RectangleF(0f,0f,(float)uvPatientSignature.Bounds.Width,(float)uvPatientSignature.Bounds.Height));
//			uvPatientSignature.AddSubview (vps);
		
			if (patientProfile != null && patientProfile.ID != 0) {
				lblFullName.Text = patientProfile.FirstName.Trim() + ", " + patientProfile.LastName.Trim();
				mrnLbl.Text = "MRN: " + patientProfile.MRN.Trim();
				txtpmrn.Text = patientProfile.MRN;
				txtpFirstName.Text = patientProfile.FirstName;
				txtpLastName.Text = patientProfile.LastName;
				string tempDOB;

				if (!string.IsNullOrEmpty (patientProfile.DOB)) {
					tempDOB = Convert.ToDateTime (patientProfile.DOB).ToString ("MM/dd/yyyy");
					txtpDOB.Text = tempDOB;

					int age = DateTime.Now.Year - Convert.ToDateTime (patientProfile.DOB).Year;
					txtpAge.Text = age.ToString ();
				}

				string surgeryDate;
				if (!string.IsNullOrEmpty (patientProcedureDetails.OperationDate))
					surgeryDate = Convert.ToDateTime (patientProcedureDetails.OperationDate).ToString ("MM/dd/yyyy");
				tctSurgeryDate.Text = surgeryDate;

				if(patientProfile.DiagnosticList!=null && patientProfile.DiagnosticList.Count>0){
					foreach (var item in patientProfile.DiagnosticList) {
						NewDiagnosis (item.Code, item.Name);
					}
				}

				if(patientProfile.ProcedureList != null && patientProfile.ProcedureList.Count > 0){
					foreach (var item in patientProfile.ProcedureList) {
						AddProcedure (item.Code, item.Name);
					}
				}
			}

			tctSurgeryDate.EditingDidBegin+= (object sender, EventArgs e) => {
				DatePicker  dp=new DatePicker();
				CoreGraphics.CGRect f=tctSurgeryDate.Frame;
				dp.PresentFromPopover(this.View,float.Parse(f.X.ToString()),float.Parse(f.Y.ToString())+100);
				dp._ValueChanged += delegate {	
					int age = DateTime.Now.Year - dp.SelectedDateValue.Year;
					//this.mPatient.DOB = dp.SelectedDate;
					tctSurgeryDate.Text=dp.SelectedDate;
				};
			};
			txtpDOB.EditingDidBegin+= (object sender, EventArgs e) => {
				DatePicker  dp=new DatePicker();
				CoreGraphics.CGRect f=txtpDOB.Frame;
				dp.PresentFromPopover(this.View,float.Parse(f.X.ToString()),float.Parse(f.Y.ToString())+100);
				dp._ValueChanged += delegate {	
					int age = DateTime.Now.Year - dp.SelectedDateValue.Year;
					//this.mPatient.DOB = dp.SelectedDate;
					txtpDOB.Text=dp.SelectedDate;
					txtpAge.Text=age.ToString();
				};
			};
			txtpmrn.EditingDidEnd+= async (object sender, EventArgs e) => {
				if(!string.IsNullOrEmpty(txtpmrn.Text))
				{
					AppDelegate.pb.Start(this.View,"Please wait...");
					ReceiveContext context = new ReceiveContext();
					context = await serv.CheckExistingPatintInfo(txtpmrn.Text,iProPQRSPortableLib.Consts.SelectedFacilityID);				
					if(context.result!=null)
					{
						Patient patientDetails = (Patient)JsonConvert.DeserializeObject(context.result.ToString() , typeof(Patient));

						if(patientDetails!=null){						

							lblFullName.Text = patientDetails.FirstName.Trim() + ", " + patientDetails.LastName.Trim();
							mrnLbl.Text = "MRN: " + patientDetails.MRN.Trim();

							txtpmrn.Text = patientDetails.MRN;
							txtpFirstName.Text = patientDetails.FirstName;
							txtpLastName.Text = patientDetails.LastName;

							txtpDOB.Text = Convert.ToDateTime (patientDetails.DOB).ToString ("MM/dd/yyyy");

							int age = DateTime.Now.Year - Convert.ToDateTime (patientDetails.DOB).Year;
							txtpAge.Text = age.ToString ();

							//Nahid Ahmed Aug 4, 2015
							//As per Raj, dont populate Physical Status, Encounter and Emergency from Patient Details
							//as these items belong to procedures.
							/* DropDownModel pitem = dlPhyStatusList.Find (u => u.DropDownText == patientDetails.ddlASAType);
							if (pitem != null) {
								PhysicalStatusBtn.SetTitle (pitem.DropDownText, UIControlState.Normal);
								physicalStatus = pitem.DropDownID;
							} else {
								PhysicalStatusBtn.SetTitle ("Select", UIControlState.Normal);
								physicalStatus = 0;
							}

							DropDownModel eitem = dEncounterTypelist.Find (u => u.DropDownText == patientDetails.ddlEncounterType);
							if (eitem != null) {
								EncounterBtn.SetTitle (eitem.DropDownText, UIControlState.Normal);
								encounterTypeid = eitem.DropDownID;
							} else {
								EncounterBtn.SetTitle ("Select", UIControlState.Normal);
								encounterTypeid = 0;
							}

							if (patientDetails.cbEmergency != null && patientDetails.cbEmergency.Trim().ToLower () == "on")
								uSEmergency.SetState (true, false);
							else
								uSEmergency.SetState (false, false); */

						}else{
							//	txtpmrn.Text = "";
							txtpFirstName.Text = "";
							txtpLastName.Text = "";
							txtpDOB.Text = "";
							mrnLbl.Text="";
							lblFullName.Text="";
						}
						AppDelegate.pb.Stop();
					}
					else{
						//	txtpmrn.Text = "";
						txtpFirstName.Text = "";
						txtpLastName.Text = "";
						txtpDOB.Text = "";
						mrnLbl.Text="";
						lblFullName.Text="";
					}
				}
				AppDelegate.pb.Stop();
			};

			btnSubmit.TouchUpInside+= async (object sender, EventArgs e) => {
				if(validatedata())
				{
				AppDelegate.pb.Start(this.View,"Please wait...");
				Patient profile=new Patient();

				if(patientProfile!=null)
					profile.ID=patientProfile.ID;
				else
					profile.ID=0;		


				if(uSEmergency.On)
					profile.cbEmergency = "on";
				else
					profile.cbEmergency = string.Empty;

				profile.CreatedOn=DateTime.Now.ToShortDateString();
				profile.ddlEncounterType=EncounterBtn.TitleLabel.Text;
				profile.LastModifiedDate=DateTime.Now.ToShortDateString();
				profile.FacilityID=iProPQRSPortableLib.Consts.SelectedFacilityID;
				profile.FirstName=txtpFirstName.Text;
				profile.LastName=txtpLastName.Text;
				profile.DOB=txtpDOB.Text;	
				profile.MRN=txtpmrn.Text;

					switch (PhysicalStatusBtn.TitleLabel.Text) {
					case "ASA 1":
						profile.ddlASAType = "1";
						break;
					case "ASA 2":
						profile.ddlASAType = "2";
						break;
					case "ASA 3":
						profile.ddlASAType = "3";
						break;
					case "ASA 4":
						profile.ddlASAType = "4";
						break;
					case "ASA 5":
						profile.ddlASAType = "5";
						break;
					case "ASA 6":
						profile.ddlASAType = "6";
						break;
					}
				ReceiveContext result1=await serv.SavePatintInfo(profile);
				Patient piResult=null;
				if(string.IsNullOrEmpty(result1.message))
				{
					new UIAlertView("Patient Info", "Successfully Saved."
						, null, "ok", null).Show();
				}
				else
				{
					new UIAlertView("Patient eroor", result1.message
						, null, "ok", null).Show();
				}
				AppDelegate.pb.Stop();
			}
			};

			addNewDiagnosis.TouchUpInside += (object sender, EventArgs e) => {
				NewDiagnosis (string.Empty,string.Empty);
			};
			deleteDiagnosis.TouchUpInside += (object sender, EventArgs e) => {
				RemoveDiagnosis();
			};


			addNewProc.TouchUpInside += (object sender, EventArgs e) => {
				AddProcedure(string.Empty,string.Empty);
			};
			removeProc.TouchUpInside += (object sender, EventArgs e) => {
				RemoveProcedures();
			};

			svBillingInfo.SizeToFit ();
			svBillingInfo.ContentSize = new SizeF (float.Parse (svBillingInfo.Frame.Width.ToString ()), float.Parse (svBillingInfo.Frame.Height.ToString ())+150);
		}
		public void ShowPatientEditor(PatientProcedureDetails patientProcedureDetails)
		{
			AppDelegate.pb.Start(this.View,"");
			isViewPushed = false;
			InvokeOnMainThread (async () => {				
				ReceiveContext context = new ReceiveContext ();

				PatientProcedureFullDetails  procedureDetails = null;
				ReceiveContext procdetailsontext = await AppDelegate.Current.pqrsMgr.GetPatientProcFullDetails(patientProcedureDetails.ProcID);
				if(procdetailsontext != null && procdetailsontext.result != null && procdetailsontext.status !=null && procdetailsontext.status.ToUpper() =="OK" ) 
				{
					procedureDetails= (PatientProcedureFullDetails)JsonConvert.DeserializeObject (procdetailsontext.result.ToString (), typeof(PatientProcedureFullDetails));
					

					context = await serv.GetPatientDetails (patientProcedureDetails.PatientID);
					Patient selectedPatientDetails=null;
					if(context != null && context.result != null && context.status !=null && context.status.ToUpper() =="OK" ) 
						 selectedPatientDetails = (Patient)JsonConvert.DeserializeObject (context.result.ToString (), typeof(Patient));
					else
						NavigationController.PopToRootViewController(true);
					

					var rootobject = await AppDelegate.Current.pqrsMgr.GetProcedureDiagnosticMaster(patientProcedureDetails.ProcID);
					List<DataResults> DiagnosticList = rootobject.result.FindAll(u=>u.ProcCodeTypeID == 2);
					selectedPatientDetails.DiagnosticList = DiagnosticList;
					List<DataResults> ProcedureList = rootobject.result.FindAll(u=> u.ProcCodeTypeID == 1);
					selectedPatientDetails.ProcedureList = ProcedureList;
					selectedPatientDetails.MACCodesList = rootobject.result.FindAll(u=> u.ProcCodeTypeID == 418);

					iProPQRSPortableLib.Consts.SelectedProcAttribtslist  = await AppDelegate.Current.pqrsMgr.GetAllAttribTypesOfAProcedure(patientProcedureDetails.ProcID);		


					AddPatientViewController addpatient = new AddPatientViewController (selectedPatientDetails,procedureDetails);
					//ReceiveContext users = await AppDelegate.Current.pqrsMgr.GetUsers();
				//	List<UserDetails> lstOfUsers = new List<UserDetails>();
					//if(users != null && users.result != null) {
						//lstOfUsers = (List<UserDetails>)JsonConvert.DeserializeObject (users.result.ToString (), typeof(List<UserDetails>));

				//	}
					if(iProPQRSPortableLib.Consts.lstOfUsers != null)
					{
					addpatient.listOfAnestheologists = iProPQRSPortableLib.Consts.lstOfUsers .FindAll(x => x.Role == "Anesthesiologist");
					addpatient.listOfCRNAs = iProPQRSPortableLib.Consts.lstOfUsers .FindAll(x => x.Role == "CRNA");
					}
					this.NavigationController.PushViewController(addpatient,true);
			   }
				else
					NavigationController.PopToRootViewController(true);

			});		
		}
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad();
			AppDelegate.pb.Stop();
			AddBasicProviderView ();
			//uvDynamicSurgeonview.Add (uvMainSurgeon);
			//svBillingInfo.Add (uvDynamicSurgeonview);
			svBillingInfo.Add(uvProviderView);
			uvBillingProcedureInfo = new UIView (new CGRect (0, Anesheight + 150, 1008, 520));
			uvBillingProcedureInfo.Add (uvProcedureInfo);
			svBillingInfo.Add (uvBillingProcedureInfo);
		

			txtpmrn.ShouldChangeCharacters = (textField, range, replacement) =>
			{
				int number;
				return replacement.Length == 0 || int.TryParse(replacement, out number);
			};

			txtFacility.Enabled = false;
			txtpAge.Enabled = false;

			if (this.procedureDetails != null) {
				if (this.procedureDetails.StatusID == "1" || this.procedureDetails.StatusID == "2")
					btnSubmit.SetTitle ("Submit", UIControlState.Normal);

				if (this.procedureDetails.StatusID == "3") {
					btnSubmit.SetTitle ("UnSubmit", UIControlState.Normal);
					uvPatientInfo.UserInteractionEnabled = false;
					uvBillingInfo.UserInteractionEnabled = false;
					uvQualityMetrics.UserInteractionEnabled = false;
				}
			}


			InvokeOnMainThread (async () => {	
				ReceiveContext surgeons = await AppDelegate.Current.pqrsMgr.GetSurgeons();
				if (surgeons != null && surgeons.result != null) {
					lstOfSurgeons = (List<SurgeonDetails>)JsonConvert.DeserializeObject (surgeons.result.ToString (), typeof(List<SurgeonDetails>));
				}

				if (this.procedureDetails != null) {
					ReceiveContext selectedSurgeonOfProcedure = await AppDelegate.Current.pqrsMgr.GetSelectedSurgeonOfProcedure(this.procedureDetails.ID);
					if (selectedSurgeonOfProcedure != null && selectedSurgeonOfProcedure.result != null) {
						selectedSurgeon = (List<ProcedureSurgeonDetails>)JsonConvert.DeserializeObject (selectedSurgeonOfProcedure.result.ToString (), typeof(List<ProcedureSurgeonDetails>));
						if(selectedSurgeon.Count > 0)
							lblSurgeon.Text = selectedSurgeon[0].Name;
					}else
						selectedSurgeon[0].ProcSurgeonID = 0;
				}


				BindSurgeon(lstOfSurgeons);
			});

			InvokeOnMainThread (async () => {	
				ReceiveContext users = await AppDelegate.Current.pqrsMgr.GetUsers();
				List<UserDetails> lstOfUsers = new List<UserDetails>();
				if(users != null && users.result != null) {
					lstOfUsers = (List<UserDetails>)JsonConvert.DeserializeObject (users.result.ToString (), typeof(List<UserDetails>));
					listOfAnestheologists = lstOfUsers.FindAll(x => x.Role == "Anesthesiologist");
					listOfCRNAs = lstOfUsers.FindAll(x => x.Role == "CRNA");




				}
			});





			ProcAttribTypes();
			ViewQualityMetrics (pqrsTypes, pqrsTypeOptions, "PQRS");	
			ViewQualityMetrics (nonPqrsTypes, nonPqrsTypeOptions, "NON PQRS");	
			svQualityMetrics.SizeToFit ();
			svQualityMetrics.ContentSize = new SizeF (float.Parse (svQualityMetrics.Frame.Width.ToString ()), float.Parse (svQualityMetrics.Frame.Height.ToString ())+hUV-100);
			BindAllTypes();
			BindAllControlWithText();

			if (this.procedureDetails == null) {
				if (iProPQRSPortableLib.Consts.Role == "Anesthesiologist") {
					//btnAnes1.SetTitle (iProPQRSPortableLib.Consts.LoginUserFullName, UIControlState.Normal);
				}
			} else {
				if (this.procedureDetails.Anesthesiologist1 != null && this.procedureDetails.Anesthesiologist1.Trim () == string.Empty) {
					if (iProPQRSPortableLib.Consts.Role == "Anesthesiologist") {
						//btnAnes1.SetTitle (iProPQRSPortableLib.Consts.LoginUserFullName, UIControlState.Normal);
					}
				}

				InvokeOnMainThread (async () => {	
					ReceiveContext procParticipants = await AppDelegate.Current.pqrsMgr.GetProcedureParticipants(this.procedureDetails.ID);
					if(procParticipants != null && procParticipants.result != null) {
						listOfProcParticiPants = (List<ProcedureParticipantDetails>)JsonConvert.DeserializeObject (procParticipants.result.ToString (), typeof(List<ProcedureParticipantDetails>));
						selectedAnestheologistList = listOfProcParticiPants.FindAll(x => x.RoleID == 2);
						selectedAnestheologistList = selectedAnestheologistList.OrderBy( x => x.ProcParticipantID).ToList();

						selectedCRNAList = listOfProcParticiPants.FindAll(x => x.RoleID == 6);
						selectedCRNAList = selectedCRNAList.OrderBy( x => x.ProcParticipantID).ToList();

						int i = 0;
						foreach (var item in selectedAnestheologistList) {
							AddProviderView(selectedAnestheologistList[i]);
							i++;
						}

						int j = 0;
						foreach (var item in selectedCRNAList) {
							
							AddCRNAView(selectedCRNAList[j]);
							j++;
						}
					}
				});
			}

			if (this.procedureDetails != null) {
				if (this.procedureDetails.StatusID == "0" || this.procedureDetails.StatusID == "1")
					tctSurgeryDate.Enabled = true;
				
				if (this.procedureDetails.StatusID == "2" || this.procedureDetails.StatusID == "3")
					tctSurgeryDate.Enabled = false;
			}

			tctSurgeryDate.Text = DateTime.Now.ToString("MM/dd/yyyy");
			uSEmergency.SetState (false, false);

			FacilityDetails fac = iProPQRSPortableLib.Consts.Facilities.result.Find (u => u.FMID.ToString() == iProPQRSPortableLib.Consts.SelectedFacilityID);
			txtFacility.Text = fac.FacilityName;

			NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.DidShowNotification, KeyBoardUpNotification);
			NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification, KeyBoardDownNotification);


			PatientsBackBtn.TouchUpInside+= (object sender, EventArgs e) => {
				this.NavigationController.PopViewController(true);
			};
			//start patient infromation
		
			SetViewBorderColor ();

			BindDropDown ();
			sCtab.ValueChanged += (object sender, EventArgs e) => {
				uvMainPatientinfo.RemoveFromSuperview ();
				uvDynamicQualityMetrics.RemoveFromSuperview ();
				uvBillingInfo.RemoveFromSuperview ();
				if (sCtab.SelectedSegment == 0){
					lblProcID.Hidden = false;
					uvMain.AddSubview (uvPatientInfo);
				}
				else if (sCtab.SelectedSegment == 1)
				{
					lblProcID.Hidden = true;
				if (procedureDetails != null) {
					uvMain.AddSubview (uvBillingInfo);
					}
				}
				else if (sCtab.SelectedSegment == 2) {
					lblProcID.Hidden = true;
					if (procedureDetails != null) {
						uvMain.AddSubview (uvDynamicQualityMetrics);
//						uvMain.AddSubview (uvQualityMetrics);
					}
				} 

			};

			///End patient infromation
			// Perform any additional setup after loading the view, typically from a nib.

			// start Quality metrics
			DropReason.Hidden=true;
			uSwitchCaseCanceled.ValueChanged+= (object sender, EventArgs e) => {
				if(uSwitchCaseCanceled.On)
				{
					uvPreIntraOp.Hidden=true;
					DropReason.Hidden=false;
				}
				else
				{
					uvPreIntraOp.Hidden=false;
					DropReason.Hidden=true;
				}
			};

			SliderPreopPainScore.ValueChanged+= (object sender, EventArgs e) => {				
				LblPreopPainScoreValue.Text=((int)Math.Round(SliderPreopPainScore.Value,0)).ToString();
			};

			uvScrollview.ContentSize = new CoreGraphics.CGSize (0, 1450);
			dropPotoc.Hidden = true;
			scPotoc.ValueChanged+= (object sender, EventArgs e) => {
				dropPotoc.Hidden=false;
			};
			scAnyUnwanted.ValueChanged+= (object sender, EventArgs e) => {

				if(scAnyUnwanted.SelectedSegment==0)
					dropAnyUnwanted.Hidden=false;
				else
					dropAnyUnwanted.Hidden=true;
			};
			// End Quality metrics
//			SignatureView vns=new SignatureView(new System.Drawing.RectangleF(0f,0f,(float)uvNurseSignaturevalue.Bounds.Width,(float)uvNurseSignaturevalue.Bounds.Height));
//			uvNurseSignaturevalue.AddSubview(vns);
//			SignatureView vps=new SignatureView(new System.Drawing.RectangleF(0f,0f,(float)uvPatientSignature.Bounds.Width,(float)uvPatientSignature.Bounds.Height));
//			uvPatientSignature.AddSubview (vps);

			if (patientProfile != null && patientProfile.ID != 0) {
				lblFullName.Text = patientProfile.FirstName.Trim() + ", " + patientProfile.LastName.Trim();
				mrnLbl.Text = "MRN: " + patientProfile.MRN.Trim();
				txtpmrn.Text = patientProfile.MRN;
				txtpFirstName.Text = patientProfile.FirstName;
				txtpLastName.Text = patientProfile.LastName;
				string patientGender = string.Empty;
				if (!string.IsNullOrEmpty (patientProfile.Sex)) {
					switch (patientProfile.Sex.Trim ().ToLower ()) {
					case	"m":
						patientGender = "Male";
						break;
					case "f":
						patientGender = "Female";
						break;
					case "u":
						patientGender = "Unknown";
						break;
					default:
						break;
					} 
				}
				btnPatientGender.SetTitle (patientGender, UIControlState.Normal);
				string tempDOB;

				if (!string.IsNullOrEmpty (patientProfile.DOB)) {
					tempDOB = Convert.ToDateTime (patientProfile.DOB).ToString ("MM/dd/yyyy");
					txtpDOB.Text = tempDOB;

					int age = DateTime.Now.Year - Convert.ToDateTime (patientProfile.DOB).Year;
					txtpAge.Text = age.ToString ();
				}

				string surgeryDate;
				if (!string.IsNullOrEmpty (procedureDetails.OperationDate)) {
					surgeryDate = Convert.ToDateTime (procedureDetails.OperationDate).ToString ("MM/dd/yyyy");
					tctSurgeryDate.Text = surgeryDate;
				}

				if (patientProfile.DiagnosticList != null && patientProfile.DiagnosticList.Count > 0) {
					foreach (var item in patientProfile.DiagnosticList) {
						NewDiagnosis (item.Code, item.Name);
						selectedDiagnosisCodeid.Add (item.ProcCodeID);
					}
				} else 
					NewDiagnosis (string.Empty, string.Empty);

				if(patientProfile.ProcedureList != null && patientProfile.ProcedureList.Count > 0){
					foreach (var item in patientProfile.ProcedureList) {
						AddProcedure (item.Code, item.Name);
						selectedprocedureCodeid.Add (item.ProcCodeID);
					}
				}else
					AddProcedure (string.Empty, string.Empty);
			}

			//Kumar start
			if (procedureDetails == null ) {
				EncounterBtn.Enabled = false;
				PhysicalStatusBtn.Enabled = false;
				uSEmergency.Enabled = false;
				addNewDiagnosis.Enabled = false;
				deleteDiagnosis.Enabled = false;
				removeProc.Enabled = false;
				addNewProc.Enabled = false;
				NewDiagnosis (string.Empty, string.Empty);
				AddProcedure (string.Empty, string.Empty);
			}else
				lblProcID.Text = procedureDetails.ID.ToString ();
			
			if (procedureDetails != null &&  !string.IsNullOrEmpty(procedureDetails.ddlEncounterType)) {
				EncounterBtn.SetTitle (procedureDetails.ddlEncounterType, UIControlState.Normal);
				if(dEncounterTypelist != null && dEncounterTypelist.Count > 0)
					encounterTypeid = dEncounterTypelist.Where (w => w.DropDownText.ToUpper().Trim() == procedureDetails.ddlEncounterType.ToUpper().Trim()).Select (s => s.DropDownID).SingleOrDefault ();
			}
			if (procedureDetails != null &&  !string.IsNullOrEmpty(procedureDetails.ddlASAType)) {
				string btntxt;
				if (dlPhyStatusList != null && dlPhyStatusList.Count > 0)
					physicalStatus = Convert.ToInt16 (procedureDetails.ddlASAType);
				btntxt = dlPhyStatusList.Where (w => w.DropDownID ==Convert.ToInt16(procedureDetails.ddlASAType)).Select (s => s.DropDownText).SingleOrDefault ();
				PhysicalStatusBtn .SetTitle (btntxt, UIControlState.Normal);

			}
			if (procedureDetails != null && !string.IsNullOrEmpty (procedureDetails.cbEmergency)) {
				Emergency = procedureDetails.cbEmergency;
				if (procedureDetails.cbEmergency == "1")
					uSEmergency.On = true;
				else
					uSEmergency.On = false;
			}
			//Kumar end

			tctSurgeryDate.EditingDidBegin+= (object sender, EventArgs e) => {
				DatePicker  dp=new DatePicker();
				CoreGraphics.CGRect f=tctSurgeryDate.Frame;
				dp.PresentFromPopover(this.View,float.Parse(f.X.ToString()),float.Parse(f.Y.ToString())+100);
				dp._ValueChanged += delegate {	
					tctSurgeryDate.Text=dp.SelectedDate;
				};
			};

			txtpDOB.ShouldBeginEditing += delegate {
				DatePicker  dp = new DatePicker();

				if(!string.IsNullOrEmpty(txtpDOB.Text))
					dp.SelectedDateValue=Convert.ToDateTime(txtpDOB.Text);

				CoreGraphics.CGRect f = txtpDOB.Frame;
				dp.PresentFromPopover(this.View,float.Parse(f.X.ToString()),float.Parse(f.Y.ToString())+100);
				dp._ValueChanged += delegate {	
					if(dp.SelectedDateValue != DateTime.MinValue){	
						int age = DateTime.Now.Year - dp.SelectedDateValue.Year;
						//this.mPatient.DOB = dp.SelectedDate;
						txtpDOB.Text=dp.SelectedDate;
						txtpAge.Text=age.ToString();
					}else{
						txtpDOB.Text = string.Empty;
						txtpAge.Text = string.Empty;
					}
					SavePatientInfo();
				};

				return false;
			};


			txtpFirstName.EditingDidEnd += async (object sender, EventArgs e) => {
				SavePatientInfo();
			};

			txtpLastName.EditingDidEnd += async (object sender, EventArgs e) => {
				SavePatientInfo();
			};

			txtpmrn.EditingDidEnd+= async (object sender, EventArgs e) => {
				if(!string.IsNullOrEmpty(txtpmrn.Text))
				{
					AppDelegate.pb.Start(this.View,"Please wait...");
					ReceiveContext context = new ReceiveContext();
					context = await serv.CheckExistingPatintInfo(txtpmrn.Text,iProPQRSPortableLib.Consts.SelectedFacilityID);				
					if(context.result!=null)
					{
						Patient patientDetails = (Patient)JsonConvert.DeserializeObject(context.result.ToString() , typeof(Patient));
						EncounterBtn.Enabled = true;
						PhysicalStatusBtn.Enabled = true;
						uSEmergency.Enabled = true;
						addNewDiagnosis.Enabled = true;
						deleteDiagnosis.Enabled = true;
						removeProc.Enabled = true;
						addNewProc.Enabled = true;

						if(patientDetails!=null){						
							patientProfile = patientDetails;
							lblFullName.Text = patientDetails.FirstName.Trim() + ", " + patientDetails.LastName.Trim();
							mrnLbl.Text = "MRN: " + patientDetails.MRN.Trim();

							txtpmrn.Text = patientDetails.MRN;
							txtpFirstName.Text = patientDetails.FirstName;
							txtpLastName.Text = patientDetails.LastName;

							txtpDOB.Text = Convert.ToDateTime (patientDetails.DOB).ToString ("MM/dd/yyyy");

							int age = DateTime.Now.Year - Convert.ToDateTime (patientDetails.DOB).Year;
							txtpAge.Text = age.ToString ();

							//Nahid Ahmed Aug 4, 2015
							//As per Raj, dont populate Physical Status, Encounter and Emergency from Patient Details
							//as these items belong to procedures.
							/* DropDownModel pitem = dlPhyStatusList.Find (u => u.DropDownText == patientDetails.ddlASAType);
							if (pitem != null) {
								PhysicalStatusBtn.SetTitle (pitem.DropDownText, UIControlState.Normal);
								physicalStatus = pitem.DropDownID;
							} else {
								PhysicalStatusBtn.SetTitle ("Select", UIControlState.Normal);
								physicalStatus = 0;
							}

							DropDownModel eitem = dEncounterTypelist.Find (u => u.DropDownText == patientDetails.ddlEncounterType);
							if (eitem != null) {
								EncounterBtn.SetTitle (eitem.DropDownText, UIControlState.Normal);
								encounterTypeid = eitem.DropDownID;
							} else {
								EncounterBtn.SetTitle ("Select", UIControlState.Normal);
								encounterTypeid = 0;
							}

							if (patientDetails.cbEmergency != null && patientDetails.cbEmergency.Trim().ToLower () == "on")
								uSEmergency.SetState (true, false);
							else
								uSEmergency.SetState (false, false); */

						}else{
							//	txtpmrn.Text = "";
							txtpFirstName.Text = "";
							txtpLastName.Text = "";
							txtpDOB.Text = "";
							mrnLbl.Text = "";
							lblFullName.Text = "";
						}
						AppDelegate.pb.Stop();
					}
					else{
						//	txtpmrn.Text = "";
						txtpFirstName.Text = "";
						txtpLastName.Text = "";
						txtpDOB.Text = "";
						mrnLbl.Text="";
						lblFullName.Text="";
						EncounterBtn.Enabled = false;
						PhysicalStatusBtn.Enabled = false;
						uSEmergency.Enabled = false;
						addNewDiagnosis.Enabled = false;
						deleteDiagnosis.Enabled = false;
						removeProc.Enabled = false;
						addNewProc.Enabled = false;
					}
				}
				AppDelegate.pb.Stop();
			};

			btnSubmit.TouchUpInside+= async (object sender, EventArgs e) => {
//				SavePatientInfo();
				if(this.procedureDetails != null){
					if(btnSubmit.CurrentTitle == "Submit")
						this.procedureDetails.StatusID = "3";

					if(btnSubmit.CurrentTitle == "UnSubmit")
						this.procedureDetails.StatusID = "2";

					ValidateAndUpdateProcedure(string.Empty,string.Empty);
				}
			};

			addNewDiagnosis.TouchUpInside += (object sender, EventArgs e) => {
				NewDiagnosis (string.Empty,string.Empty);
			};
			deleteDiagnosis.TouchUpInside += async (object sender, EventArgs e) => {
				//RemoveDiagnosis();
				DeleteDiagnosis();
			};


		




			addNewProc.TouchUpInside += (object sender, EventArgs e) => {
				AddProcedure(string.Empty,string.Empty);
			};
			removeProc.TouchUpInside += async (object sender, EventArgs e) => {
				//RemoveProcedures();
				DeleteProcedures();
			};
			 
			//billing info start
			svBillingInfo.SizeToFit ();
			svBillingInfo.ContentSize = new SizeF (float.Parse (svBillingInfo.Frame.Width.ToString ()), float.Parse (svBillingInfo.Frame.Height.ToString ())+500);
			//billing info End
		}
		public override void ViewDidLoad ()
		{
			
			base.ViewDidLoad ();
			wvpatient.EndEditing (true);
			BackBtn.TouchUpInside+= (object sender, EventArgs e) => {
				this.NavigationController.PopViewController(true);
			};
			mMenu.ValueChanged+= (object sender, EventArgs e) => {

				wvpatient.EvaluateJavascript("bindPanel("+mMenu.SelectedSegment+")");
			};
			BtnSubmit.TouchUpInside+=async (object sender, EventArgs e) => {
				AppDelegate.pb.Start(this.View,"Please wait...");
				string str=wvpatient.EvaluateJavascript("GetTextboxValue()");
				XmlSerializer xs = new XmlSerializer(typeof(ProfileInfo));
				ProfileInfo objpi = (ProfileInfo)xs.Deserialize(new StringReader(str));

				PQRSServices services=new PQRSServices();
				Patient Profile=new Patient();

				if(patientProcedureDetails!=null)
					Profile.ID=patientProcedureDetails.PatientID;
				else
					Profile.ID=0;				
				Profile.cbEmergency=objpi.cbEmergency;

				if(mPatient!=null)
					Profile.CreatedOn = mPatient.OperationDate;
				else
					Profile.CreatedOn = DateTime.Now.ToShortDateString();
			
				Profile.ddlASAType=objpi.ddlASAType;
				Profile.ddlEncounterType=objpi.ddlEncounterType;
				Profile.LastModifiedDate=DateTime.Now.ToShortDateString();
				Profile.FacilityID=iProPQRSPortableLib.Consts.SelectedFacilityID;
				Profile.FirstName=objpi.Firstname;
				Profile.LastName=objpi.Lastname;
				Profile.DOB=objpi.DOB;	
				Profile.MRN=objpi.MRN;
				ReceiveContext result1 = await AppDelegate.Current.pqrsMgr.AddUpdatePatintInfo (Profile);
				Patient piResult=null;
				if(string.IsNullOrEmpty(result1.message))
				{
					piResult = (Patient)JsonConvert.DeserializeObject(result1.result.ToString() , typeof(Patient));
					//new UIAlertView("Patient Info", "Successfully Saved."
					//	, null, "ok", null).Show();
				}
				else
				{
					new UIAlertView("Patient eroor", result1.message
						, null, "ok", null).Show();
				}
				PatientProcedureFullDetails PDetails=new PatientProcedureFullDetails();
				if(patientProcedureDetails!=null)
				{
					PDetails.ID=patientProcedureDetails.ProcID;
					PDetails.PatientID=patientProcedureDetails.PatientID.ToString();
					PDetails.StatusID=patientProcedureDetails.StatusID.ToString();
				}
				else
				{
					if(piResult==null)
					{
						PDetails.ID=0;
						PDetails.PatientID="0";
					}
					else
					{

						PDetails.ID=0;
						PDetails.PatientID=piResult.ID.ToString();
					}	
				}


				PDetails.Mrn=objpi.MRN;
				PDetails.OperationDate=objpi.OperationDate;
				//PDetails.PatientID=objpi.PatientID;
				//PDetails.Location=objpi.Location;
				//PDetails.ORNumber=objpi.;
				PDetails.Anesthesiologist=objpi.Anesthesiologist1_label;
				PDetails.Anesthesiologist1=objpi.Anesthesiologist2_label;
				PDetails.Anesthesiologist2=objpi.Anesthesiologist2_label;
				PDetails.Anesthesiologist3=objpi.Anesthesiologist2_label;
				PDetails.Crna=objpi.CRNA1_label;
				PDetails.Crna1=objpi.CRNA1_label;
				PDetails.Crna2=objpi.CRNA2_label;
				PDetails.Crna3=objpi.CRNA3_label;
				//PDetails.RlfTime1=objpi.tim;
				//PDetails.RlfTime2
				//PDetails.RlfTime3
				//PDetails.RlfTime4
				PDetails.CrnaRlfTime1=objpi.CrnaStrtTime1;
				PDetails.CrnaRlfTime2=objpi.CrnaStrtTime2;
				PDetails.Surgeon=objpi.Surgeon;
				PDetails.Surgeon2=objpi.Surgeon2;

				PDetails.Surgeon3=objpi.Surgeon3;
			    //PDetails.Procedures=objpi.Procedures1;
				//PDetails.Diagnosis=objpi.CRNA4_label;
				//PDetails.ScheduleStartTime=objpi.;
				//PDetails.StatusID=objpi.CRNA4_label;
				//PDetails.RoomIn=objpi.CRNA4_label;
				PDetails.AnesStart=objpi.AnesStrtTime1;
				//PDetails.SurgeryStart=objpi.OperationDate;
				//PDetails.IncisionTime=objpi.time;
				//PDetails.SurgeryEnd=objpi.CRNA4_label;
				PDetails.AnesEnd=objpi.AnesEndTime1;
				PDetails.LastUpdatedTime=DateTime.Now.ToString();
				//PDetails.tbPreIndBP=objpi.CRNA4_label;
				//PDetails.tbPreIndP=objpi.CRNA4_label;
				//PDetails.tbPreIndSPO2=objpi.CRNA4_label;
				//PDetails.tbPreIndResp=objpi.CRNA4_label;
				PDetails.Procedure1=objpi.Procedures1;
				PDetails.Procedure2=objpi.Procedures2;
				PDetails.Procedure3=objpi.Procedures3;
				PDetails.Procedure4=objpi.Procedures4;
				PDetails.ProcedureCode1=objpi.ProcedureCode1;
				PDetails.ProcedureCode2=objpi.ProcedureCode2;
				PDetails.ProcedureCode3=objpi.ProcedureCode3;
				PDetails.ProcedureCode4=objpi.ProcedureCode4;
				//PDetails.ProcedureUnit1
				//PDetails.ProcedureUnit2
				//PDetails.ProcedureUnit3
				//PDetails.ProcedureUnit4
				PDetails.Diagnosis1=objpi.Diagnosis1;
				PDetails.Diagnosis2=objpi.Diagnosis2;
				PDetails.Diagnosis3=objpi.Diagnosis3;
				PDetails.Diagnosis4=objpi.Diagnosis4;

				PDetails.DiagnosisCode1=objpi.DiagnosisCode1;
				PDetails.DiagnosisCode2=objpi.DiagnosisCode2;
				PDetails.DiagnosisCode3=objpi.DiagnosisCode3;
				PDetails.DiagnosisCode4=objpi.DiagnosisCode4;
				//DiagnosisUnit1
				//DiagnosisUnit2
				//DiagnosisUnit3
				//DiagnosisUnit4
				//Modifier1
				//Modifier2
				//Modifier3
				//Modifier4
				PDetails.Duration=objpi.delayedDuration;
				//SurveyComplete
				//BillingInfo
				//PDFStatus
				//PatientClass
				//CancellationReason
				PDetails.CancellationReasonID=objpi.ddlCancellationReasons;
				//OrderNumber
				PDetails.ddlEncounterType=objpi.ddlEncounterType;
				PDetails.ddlASAType=objpi.ddlASAType;
				PDetails.cbEmergency=objpi.cbEmergency;
				PDetails.Anesthesiologist4=objpi.Anesthesiologist4;
				//RlfTime3
				PDetails.Crna4=objpi.CRNA4_label;
				//CrnaRlfTime3
				//Srna1
				//Srna2
				//SrnaRlfTime1
				//Source
				//Induction
				PDetails.AnesStrtTime1=objpi.AnesStrtTime1;
				PDetails.AnesEndTime1=objpi.AnesEndTime1;
				PDetails.AnesStrtTime2=objpi.AnesStrtTime2;
				PDetails.AnesEndTime2=objpi.AnesEndTime2;
				PDetails.AnesStrtTime3=objpi.AnesStrtTime3;
				PDetails.AnesEndTime3=objpi.AnesEndTime3;
				PDetails.AnesStrtTime4=objpi.AnesStrtTime4;
				PDetails.AnesEndTime4=objpi.AnesEndTime4;
				PDetails.CrnaStrtTime1=objpi.CrnaStrtTime1;
				PDetails.CrnaEndTime1=objpi.CrnaEndTime1;
				PDetails.CrnaStrtTime2=objpi.CrnaStrtTime2;
				PDetails.CrnaEndTime2=objpi.CrnaEndTime2;
				PDetails.CrnaStrtTime3=objpi.CrnaStrtTime3;
				PDetails.CrnaEndTime3=objpi.CrnaEndTime3;
				PDetails.CrnaStrtTime4=objpi.CrnaStrtTime4;
				PDetails.CrnaEndTime4=objpi.CrnaEndTime4;
				//SrnaStrtTime1
				//SrnaEndTime1
				//ListType
				ReceiveContext result2=await services.UpdatePatintProcedureInfo(PDetails);
				if(string.IsNullOrEmpty(result2.message))
				{
					BtnSubmit.Enabled=false;
					AppDelegate.pb.Stop();
					new UIAlertView("Patient Procedure Info", "Successfully Saved."
						, null, "ok", null).Show();
				}
				else
				{
					AppDelegate.pb.Stop();
					new UIAlertView("Patient eroor", result2.message
						, null, "ok", null).Show();
				}


				//Nahid Ahmed Testing patient upload
//				Patient pat = new Patient();
//				pat.ID = 17517;
//				pat.MRN = "54576576876";
//				pat.FirstName = "John6";
//				pat.LastName = "DoelMansuri";
//				pat.Sex = "M";
//				pat.Height = "5)6";
//				pat.Weight = "67";
//				pat.Allergies = "Tablet";
//				pat.PersonProvidingInfo = "Patient";
//				pat.DOB = "1962-02-02T00:00:00";
//				pat.AccountNo = "3564546466";
//				AppDelegate.Current.pqrsMgr.UploadPatientData(pat);

			};
			this.NavigationController.NavigationBarHidden = true;		
			if (mPatient != null && mPatient.PatientID != null) {
				lblPatientName.Text = mPatient.PatientName;
				lblhmrn.Text = "MRN :" + mPatient.MRN;
				lblAccount.Text = "ACCT :" + mPatient.AccountNo;
			} else {
				lblPatientName.Text = "";
				lblhmrn.Text = "";
				lblAccount.Text = "";
			}
			LoadWevView ();
			wvpatient.LoadFinished+= WvPatientProcedure_LoadFinished;
			#region ShouldStartLoad
			wvpatient.ShouldStartLoad = (webView, request, navType) => {
				string requestString=request.Url.Description;
				string param=string.Empty;
				if(requestString.Contains("pro://showAlert/"))
				{
					string message=requestString.Remove(0,15);
					AlertMsg(message);
				}
				else if(requestString.Contains("pro://openDatePicker/"))
				{
					param=requestString.Remove(0,22);
					string[] pary=param.Split(',');
					string mCurrentTextBoxID=pary[0];
					float x=float.Parse(pary[1]);
					float y=float.Parse(pary[2]);
					if(mCurrentTextBoxID=="OperationDate" || mCurrentTextBoxID=="DOB")
					{
						DatePicker  dp=new DatePicker();
						dp.PresentFromPopover(wvpatient,x,y);
						dp._ValueChanged += delegate {	
							int age = DateTime.Now.Year - dp.SelectedDateValue.Year;
							//this.mPatient.DOB = dp.SelectedDate;
							SetTextboxValue(mCurrentTextBoxID,dp.SelectedDate);
							SetTextboxValue("Age",age.ToString());
						};
					}
					else
					{
						TimePicker  tp=new TimePicker();
						tp.PresentFromPopover(wvpatient,x,y);
						tp._ValueChanged += delegate {						
							SetTextboxValue(mCurrentTextBoxID,tp.SelectedTime);
						};
					}

				}
				else if(requestString.Contains("pro://openCodePicker/Diagnosis"))
				{
					param=requestString.Remove(0,22);
					string[] pary=param.Split(',');
					string currentDiagnosticCodeTextID = string.Empty;

					if(requestString.Contains("Diagnosis1"))
						currentDiagnosticCodeTextID = "DiagnosisCode1";
					else if(requestString.Contains("Diagnosis2"))
						currentDiagnosticCodeTextID = "DiagnosisCode2";
					else if(requestString.Contains("Diagnosis3"))
						currentDiagnosticCodeTextID = "DiagnosisCode3";
					else if(requestString.Contains("Diagnosis4"))
						currentDiagnosticCodeTextID = "DiagnosisCode4";

					bool itemPreviouslySearched = false;

					string lastSelectedProcedures = ReadFile("lastSelectedDiagnosis.txt");
					if(lastSelectedProcedures != string.Empty){
						lastSelectedProceduresObj = (ProcedureDiagnosticMaster)JsonConvert.DeserializeObject(lastSelectedProcedures,typeof(ProcedureDiagnosticMaster));
						foreach (DataResults item in lastSelectedProceduresObj.results) {
							if(item.Name != null){
								if(item.Name.ToLower().Contains(pary[4].ToLower())){
									itemPreviouslySearched = true;
									break;
								}
							}
						}
					}

					if(cp != null){
						if(cp.popover != null)
							cp.popover.Dismiss(false);
					}


					if(itemPreviouslySearched){
						int uvWidth=280;
						List<CodePickerModel> list=SetDataSource(out uvWidth);
						string mCurrentTextBoxID=pary[0];
						float x=float.Parse(pary[1]);
						float y=float.Parse(pary[2]);
						cp	=new CodePicker(this,uvWidth);
						cp.PresentFromPopover(wvpatient,x,y,uvWidth);
						cp.DataSource=list;
						cp._ValueChanged += delegate {						
							SetTextboxValue(mCurrentTextBoxID,cp.SelectedText);
							SetTextboxValue(currentDiagnosticCodeTextID,cp.SelectedCodeValue);
						}; 
					}else{
						if(pary[4].Replace("%20"," ").Trim().Length > 0)
							DownloadData("ICD9",pary,currentDiagnosticCodeTextID);
					}
				}
				else if(requestString.Contains("pro://openCodePicker/Procedures"))
				{
					param=requestString.Remove(0,22);
					string[] pary=param.Split(',');

					string currentProceduresCodeTextID = string.Empty;

					if(requestString.Contains("Procedures1"))
						currentProceduresCodeTextID = "ProcedureCode1";
					else if(requestString.Contains("Procedures2"))
						currentProceduresCodeTextID = "ProcedureCode2";
					else if(requestString.Contains("Procedures3"))
						currentProceduresCodeTextID = "ProcedureCode3";
					else if(requestString.Contains("Procedures4"))
						currentProceduresCodeTextID = "ProcedureCode4";
					
					bool itemPreviouslySearched = false;

					string lastSelectedProcedures = ReadFile("lastSelectedProcedures.txt");
					if(lastSelectedProcedures != string.Empty){
						lastSelectedProceduresObj = (ProcedureDiagnosticMaster)JsonConvert.DeserializeObject(lastSelectedProcedures,typeof(ProcedureDiagnosticMaster));
						foreach (DataResults item in lastSelectedProceduresObj.results) {
							if(item.Name != null){
								if(item.Name.ToLower().Contains(pary[4].ToLower())){
									itemPreviouslySearched = true;
									break;
								}
							}
						}
					}
						
 					if(cp != null){
						if(cp.popover != null)
							cp.popover.Dismiss(false);
					}
					
					if(itemPreviouslySearched){
						int uvWidth=280;
						List<CodePickerModel> list=SetDataSource(out uvWidth);
						string mCurrentTextBoxID=pary[0];
						float x=float.Parse(pary[1]);
						float y=float.Parse(pary[2]);
						cp	=new CodePicker(this,uvWidth);

						if(pary[4].Trim().Length > 0)
							cp.PresentFromPopover(wvpatient,x,y,uvWidth);
						
						cp.DataSource=list;
						cp._ValueChanged += delegate {	
							SetTextboxValue(mCurrentTextBoxID,cp.SelectedText);
							SetTextboxValue(currentProceduresCodeTextID,cp.SelectedCodeValue);
						}; 
					}else{
						if(pary[4].Replace("%20"," ").Trim().Length > 0)
							DownloadData("CPT",pary,currentProceduresCodeTextID);
					}
				}
				else if(requestString.Contains("ipro://Checkmrncode/"))
				{

					param = requestString.Remove(0, 23);
					string[] pary = param.Split(',');
					string mCurrentTextBoxID = pary[3];
					float x = float.Parse(pary[1]);
					float y = float.Parse(pary[2]);
					string mrn=wvpatient.EvaluateJavascript("GetVal('"+mCurrentTextBoxID+"')");
					PQRSServices serv=new PQRSServices();
					ReceiveContext context=new ReceiveContext();
					if(!string.IsNullOrEmpty(mrn))
					{
						AppDelegate.pb.Start(this.View,"Checking MRN number");

						InvokeOnMainThread ( async () =>  {
							context=await serv.CheckExistingPatintInfo(mrn,"1");
							string strtemp=context.result.ToString();
							List<Patient> objpi = (List<Patient>)JsonConvert.DeserializeObject(context.result.ToString() , typeof(List<Patient>));
							//"MRN", "Firstname", "Lastname","DOB","Age","ddlEncounterType","ddlASAType","cbEmergency"
							Patient tempProfil;
							if(objpi.Count>0)
							{
								if(objpi.Count>1)
								{

									int maxval=FindMaxID(objpi);
									tempProfil=objpi.Find(u=>u.ID==maxval);
								}
								else
								{								
									tempProfil=objpi[0];
								}
								SetTextboxValue("Firstname",tempProfil.FirstName);
								SetTextboxValue("Lastname",tempProfil.LastName);
								if(!string.IsNullOrEmpty(tempProfil.DOB))
								{
									SetTextboxValue("DOB",tempProfil.DOB);
									var now = float.Parse(DateTime.Now.ToString("yyyy.MMdd"));
									var dob = float.Parse(Convert.ToDateTime(tempProfil.DOB).ToString("yyyy.MMdd"));
									var age = (int)(now - dob);
									SetTextboxValue("Age", age.ToString());
								}							
								lblhmrn.Text = "MRN :" + tempProfil.MRN;
								lblAccount.Text = "ACCT :" + tempProfil.AccountNo;
								lblPatientName.Text = tempProfil.FirstName+" , "+tempProfil.LastName;
								SetTextboxValue("ddlEncounterType",tempProfil.ddlEncounterType);
								SetTextboxValue("ddlASAType",tempProfil.ddlASAType);
								SetTextboxValue("cbEmergency",tempProfil.cbEmergency);
								AppDelegate.pb.Stop();
							}
							else
							{
								SetTextboxValue("Firstname","");
								SetTextboxValue("Lastname","");
								SetTextboxValue("DOB","");
								SetTextboxValue("Age", "");
								lblhmrn.Text = "";
								lblAccount.Text = "";
								lblPatientName.Text = "";
								SetTextboxValue("ddlEncounterType","");
								SetTextboxValue("ddlASAType","");
								SetTextboxValue("cbEmergency","");
								AppDelegate.pb.Stop();
							}

						});
					}


				}
                else if (requestString.Contains("ipro://mopenCodePicker/"))
                {
					wvpatient.KeyboardDisplayRequiresUserAction = false;
					UIView ruv=wvpatient.InputAccessoryView;
					if(ruv!=null)
						ruv.Hidden=true;
					
                    mCodePicker mcp;

                    param = requestString.Remove(0, 23);
                    string[] pary = param.Split(',');
                    string mCurrentTextBoxID = pary[0];
                    float x = float.Parse(pary[1]);
                    float y = float.Parse(pary[2]);
                    if (mCurrentTextBoxID == "AnesthesiaTech")
                    {
						int uvwidth;
						List<CodePickerModel> alist=mSetDataSource(AnesthesiaTech.Split(','), out  uvwidth);
						mcp = new mCodePicker(this,uvwidth);
                        // need to set Selected Items
                        if (ATlist.Count > 0)
                            mcp.SelectedItems = ATlist;
                        //
						mcp.PresentFromPopover(wvpatient, x, y,uvwidth);
						mcp.mDataSource(alist);
                        mcp._ValueChanged += delegate
                        {
                            ATlist = mcp.SelectedItems;
                            string finalText = string.Empty;
                            foreach (var item in ATlist)
                            {
                                finalText = finalText + ", " + item.ItemText;
                            }
                            SetTextboxValue(mCurrentTextBoxID, finalText.TrimStart(','));
                        };
                    }
                    else if (mCurrentTextBoxID == "Lines")
                    {
						int uvwidth;
						List<CodePickerModel> list=mSetDataSource(Lines.Split(','), out  uvwidth);
                        mcp = new mCodePicker(this);
                        // need to set Selected Items
                        if (Linelist.Count > 0)
                            mcp.SelectedItems = Linelist;
                        //
						mcp.PresentFromPopover(wvpatient, x, y,uvwidth);
						mcp.mDataSource(list);
                        mcp._ValueChanged += delegate
                        {
                            Linelist = mcp.SelectedItems;
                            string finalText = string.Empty;
                            foreach (var item in Linelist)
                            {
                                finalText = finalText + ", " + item.ItemText;
                            }
                            SetTextboxValue(mCurrentTextBoxID, finalText.TrimStart(','));
                        };
                    }
                    else if (mCurrentTextBoxID == "CVCSterileTec")
                    {
						int uvwidth;
						List<CodePickerModel> list=mSetDataSource(CVCSterileTec.Split(','), out  uvwidth);
						mcp = new mCodePicker(this,uvwidth);
                        mcp.Setwidth();
                        // need to set Selected Items
                        if (CVCTlist.Count > 0)
                            mcp.SelectedItems = CVCTlist;
                        //
						mcp.PresentFromPopover(wvpatient, x, y,uvwidth);

						mcp.mDataSource(list);
                        mcp._ValueChanged += delegate
                        {
                            CVCTlist = mcp.SelectedItems;
                            string finalText = string.Empty;
                            foreach (var item in CVCTlist)
                            {
                                finalText = finalText + ", " + item.ItemText;
                            }
                            SetTextboxValue(mCurrentTextBoxID, finalText.TrimStart(','));
                        };
                    }
                    else if (mCurrentTextBoxID == "NerveBlack")
                    {
						int uvwidth;
						List<CodePickerModel> list=mSetDataSource(NerveBlack.Split(','), out uvwidth);
						mcp = new mCodePicker(this,uvwidth);
                        // need to set Selected Items
                        if (NBlist.Count > 0)
                            mcp.SelectedItems = NBlist;
                        //
						mcp.PresentFromPopover(wvpatient, x, y,uvwidth);
						mcp.mDataSource(list);
                        mcp._ValueChanged += delegate
                        {
                            NBlist = mcp.SelectedItems;
                            string finalText = string.Empty;
                            foreach (var item in NBlist)
                            {
                                finalText = finalText + ", " + item.ItemText;
                            }
                            SetTextboxValue(mCurrentTextBoxID, finalText.TrimStart(','));
                        };
                    }
                    else if (mCurrentTextBoxID == "SterileTec")
                    {
						int uvwidth;
						List<CodePickerModel> list=mSetDataSource(SterileTec.Split(','), out uvwidth);
						mcp = new mCodePicker(this,uvwidth);
                        // need to set Selected Items
                        if (STlist.Count > 0)
                            mcp.SelectedItems = STlist;
                        //
						mcp.PresentFromPopover(wvpatient, x, y,uvwidth);
						mcp.mDataSource(list);
                        mcp._ValueChanged += delegate
                        {
                            STlist = mcp.SelectedItems;
                            string finalText = string.Empty;
                            foreach (var item in STlist)
                            {
                                finalText = finalText + ", " + item.ItemText;
                            }
                            SetTextboxValue(mCurrentTextBoxID, finalText.TrimStart(','));
                        };
                    }
                    else if (mCurrentTextBoxID == "SpecialTech")
                    {
						int uvwidth;
						List<CodePickerModel> list=mSetDataSource(SpecialTech.Split(','), out uvwidth);
						mcp = new mCodePicker(this,uvwidth);
                        // need to set Selected Items
                        if (SPTlist.Count > 0)
                            mcp.SelectedItems = SPTlist;
                        //
						mcp.PresentFromPopover(wvpatient, x, y,uvwidth);
						mcp.mDataSource(list);
                        mcp._ValueChanged += delegate
                        {
                            SPTlist = mcp.SelectedItems;
                            string finalText = string.Empty;
                            foreach (var item in SPTlist)
                            {
                                finalText = finalText + ", " + item.ItemText;
                            }
                            SetTextboxValue(mCurrentTextBoxID, finalText.TrimStart(','));
                        };
                    }
                    wvpatient.ResignFirstResponder();
                }
				return true;
			};
			#endregion
			// Perform any additional setup after loading the view, typically from a nib.
		}