/******************************************************************************/
/*                                                                            */
/* Copyright Avaya LLC.                                                       */
/*                                                                            */
/******************************************************************************/
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Reflection;
using System.ComponentModel;
using Microsoft.Win32;
using System.IO;
using System.Collections.Generic;
using System.Windows.Media;
using CommunicationSampleApp.Classes;
using Avaya.ClientServices.Media;
using Avaya.ClientServices;


namespace CommunicationSampleApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public static char Dtmf = ' ';
        public static String OldDtmfString = " ";
        public event PropertyChangedEventHandler PropertyChanged;

        private bool callServiceBtnEnabled;
        private bool contactServiceBtnEnabled;
        private bool callLogsBtnEnabled;
        private bool messagingServiceBtnEnabled;
        private bool isAvayaClientSDKGridVisible;
        private bool isSettingsGridVisible;
        private bool isCallServiceSettingsGridVisible;
        private bool isMessagingServiceSettingsGridVisible;
        private bool isDeviceServiceSettingsGridVisible;
        private bool isCallLogGridVisible;
        private bool isContactsGridVisible;
        private bool isViewContactGridVisible;
        private bool isContactSearchGridVisible;
        private bool isCallServiceGridVisible;
        private bool isActiveCallGridVisible;
        private bool isVideoGridVisible;
        private bool isConversationListGridVisible;
        private bool isCreateNewChatGridVisible;
        private bool isViewConversationGridVisible;
        private bool isAttachmentListGridVisible;
        private bool isAboutScreenGridVisible;
        private bool isDeleteContactBtnVisible;
        private bool isUpdateContactBtnVisible;
        private bool isEditContactBtnVisible;
        private bool isaddNewContactBtnVisible;

        private bool sendAllCallsBtnEnabled;
        private bool isDesktopSharingBtnVisible;
        private bool isConferenceControlsBtnVisible;
        private bool isCollaborationBtnVisible;

        private String sipServerAddressText;
        private String sipDomainText;
        private String sipPortText;
        private String sipUsernameText;
        private String sipLoginStatusContent;
        private String messagingServerAddressText;
        private String messagingPortText;
        private String messagingUsernameText;
        private String acsUrlText;
        private String acsPortText;
        private String acsUsernameText;
        private String acsIsSecureContent;
        private String acsStatusContent;

        private String muteBtnContent;
        private String desktopSharingBtnContent;
        private String sipTransportBtnContent;
        private String sendAllCallsBtnContent;
        private String messagingTLSContent;
        private String messagingLoginStatusContent;
        private String callDurationContent;
        private String callStateContent;
        private String searchingContactLabelContent;

        private bool firstNameIsReadOnly;
        private bool lastNameIsReadOnly;
        private bool numberIsReadOnly;
        private bool emailIsReadOnly;

        private String firstNameText;
        private String lastNameText;
        private String numberText;
        private String emailText;

        DispatcherTimer timer = new DispatcherTimer();
        Stopwatch stopWatch = new Stopwatch();

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }

        public bool CallServiceBtnEnabled
        {
            get { return callServiceBtnEnabled; }
            set
            {
                if (callServiceBtnEnabled != value)
                {
                    callServiceBtnEnabled = value;
                    OnPropertyChanged("CallServiceBtnEnabled");  // To notify when the property is changed
                }
            }
        }

        public bool ContactServiceBtnEnabled
        {
            get { return contactServiceBtnEnabled; }
            set
            {
                if (contactServiceBtnEnabled != value)
                {
                    contactServiceBtnEnabled = value;
                    OnPropertyChanged("ContactServiceBtnEnabled");  // To notify when the property is changed
                }
            }
        }

        public bool CallLogsBtnEnabled
        {
            get { return callLogsBtnEnabled; }
            set
            {
                if (callLogsBtnEnabled != value)
                {
                    callLogsBtnEnabled = value;
                    OnPropertyChanged("CallLogsBtnEnabled");  // To notify when the property is changed
                }
            }
        }

        public bool MessagingServiceBtnEnabled
        {
            get { return messagingServiceBtnEnabled; }
            set
            {
                if (messagingServiceBtnEnabled != value)
                {
                    messagingServiceBtnEnabled = value;
                    OnPropertyChanged("MessagingServiceBtnEnabled");  // To notify when the property is changed
                }
            }
        }

        public bool FirstNameIsReadOnly
        {
            get { return firstNameIsReadOnly; }
            set
            {
                if (firstNameIsReadOnly != value)
                {
                    firstNameIsReadOnly = value;
                    OnPropertyChanged("FirstNameIsReadOnly");  // To notify when the property is changed
                }
            }
        }
        public bool LastNameIsReadOnly
        {
            get { return lastNameIsReadOnly; }
            set
            {
                if (lastNameIsReadOnly != value)
                {
                    lastNameIsReadOnly = value;
                    OnPropertyChanged("LastNameIsReadOnly");  // To notify when the property is changed
                }
            }
        }
        public bool NumberIsReadOnly
        {
            get { return numberIsReadOnly; }
            set
            {
                if (numberIsReadOnly != value)
                {
                    numberIsReadOnly = value;
                    OnPropertyChanged("NumberIsReadOnly");  // To notify when the property is changed
                }
            }
        }
        public bool EmailIsReadOnly
        {
            get { return emailIsReadOnly; }
            set
            {
                if (emailIsReadOnly != value)
                {
                    emailIsReadOnly = value;
                    OnPropertyChanged("EmailIsReadOnly");  // To notify when the property is changed
                }
            }
        }
        public String FirstNameText
        {
            get { return firstNameText; }
            set
            {
                if (firstNameText != value)
                {
                    firstNameText = value;
                    OnPropertyChanged("FirstNameText");  // To notify when the property is changed
                }
            }
        }
        public String LastNameText
        {
            get { return lastNameText; }
            set
            {
                if (lastNameText != value)
                {
                    lastNameText = value;
                    OnPropertyChanged("LastNameText");  // To notify when the property is changed
                }
            }
        }
        public String NumberText
        {
            get { return numberText; }
            set
            {
                if (numberText != value)
                {
                    numberText = value;
                    OnPropertyChanged("NumberText");  // To notify when the property is changed
                }
            }
        }
        public String EmailText
        {
            get { return emailText; }
            set
            {
                if (emailText != value)
                {
                    emailText = value;
                    OnPropertyChanged("EmailText");  // To notify when the property is changed
                }
            }
        }
        public String MessagingTLSContent
        {
            get { return messagingTLSContent; }
            set
            {
                if (messagingTLSContent != value)
                {
                    messagingTLSContent = value;
                    OnPropertyChanged("MessagingTLSContent");  // To notify when the property is changed
                }
            }
        }
        public String MessagingLoginStatusContent
        {
            get { return messagingLoginStatusContent; }
            set
            {
                if (messagingLoginStatusContent != value)
                {
                    messagingLoginStatusContent = value;
                    OnPropertyChanged("MessagingLoginStatusContent");  // To notify when the property is changed
                }
            }
        }
        public String SearchingContactLabelContent
        {
            get { return searchingContactLabelContent; }
            set
            {
                if (searchingContactLabelContent != value)
                {
                    searchingContactLabelContent = value;
                    OnPropertyChanged("SearchingContactLabelContent");  // To notify when the property is changed
                }
            }
        }
        public String SendAllCallsBtnContent
        {
            get { return sendAllCallsBtnContent; }
            set
            {
                if (sendAllCallsBtnContent != value)
                {
                    sendAllCallsBtnContent = value;
                    OnPropertyChanged("SendAllCallsBtnContent");  // To notify when the property is changed
                }
            }
        }
        public String SipTransportBtnContent
        {
            get { return sipTransportBtnContent; }
            set
            {
                if (sipTransportBtnContent != value)
                {
                    sipTransportBtnContent = value;
                    OnPropertyChanged("SipTransportBtnContent");  // To notify when the property is changed
                }
            }
        }
        public String DesktopSharingBtnContent
        {
            get { return desktopSharingBtnContent; }
            set
            {
                if (desktopSharingBtnContent != value)
                {
                    desktopSharingBtnContent = value;
                    OnPropertyChanged("DesktopSharingBtnContent");  // To notify when the property is changed
                }
            }
        }
        public String MuteBtnContent
        {
            get { return muteBtnContent; }
            set
            {
                if (muteBtnContent != value)
                {
                    muteBtnContent = value;
                    OnPropertyChanged("MuteBtnContent");  // To notify when the property is changed
                }
            }
        }
        public String CallStateContent
        {
            get { return callStateContent; }
            set
            {
                if (callStateContent != value)
                {
                    callStateContent = value;
                    OnPropertyChanged("CallStateContent");  // To notify when the property is changed
                }
            }
        }
        public String CallDurationContent
        {
            get { return callDurationContent; }
            set
            {
                if (callDurationContent != value)
                {
                    callDurationContent = value;
                    OnPropertyChanged("CallDurationContent");  // To notify when the property is changed
                }
            }
        }
        public String SipServerAddressText
        {
            get { return sipServerAddressText; }
            set
            {
                if (sipServerAddressText != value)
                {
                    sipServerAddressText = value;
                    OnPropertyChanged("SipServerAddressText");  // To notify when the property is changed
                }
            }
        }
        public String SipDomainText
        {
            get { return sipDomainText; }
            set
            {
                if (sipDomainText != value)
                {
                    sipDomainText = value;
                    OnPropertyChanged("SipDomainText");  // To notify when the property is changed
                }
            }
        }
        public String SipUsernameText
        {
            get { return sipUsernameText; }
            set
            {
                if (sipUsernameText != value)
                {
                    sipUsernameText = value;
                    OnPropertyChanged("SipUsernameText");  // To notify when the property is changed
                }
            }
        }
        public String SipPortText
        {
            get { return sipPortText; }
            set
            {
                if (sipPortText != value)
                {
                    sipPortText = value;
                    OnPropertyChanged("SipPortText");  // To notify when the property is changed
                }
            }
        }
        public String SipLoginStatusContent
        {
            get { return sipLoginStatusContent; }
            set
            {
                if (sipLoginStatusContent != value)
                {
                    sipLoginStatusContent = value;
                    OnPropertyChanged("SipLoginStatusContent");  // To notify when the property is changed
                }
            }
        }
        public String MessagingServerAddressText
        {
            get { return messagingServerAddressText; }
            set
            {
                if (messagingServerAddressText != value)
                {
                    messagingServerAddressText = value;
                    OnPropertyChanged("MessagingServerAddressText");  // To notify when the property is changed
                }
            }
        }
        public String MessagingPortText
        {
            get { return messagingPortText; }
            set
            {
                if (messagingPortText != value)
                {
                    messagingPortText = value;
                    OnPropertyChanged("MessagingPortText");  // To notify when the property is changed
                }
            }
        }
        public String MessagingUsernameText
        {
            get { return messagingUsernameText; }
            set
            {
                if (messagingUsernameText != value)
                {
                    messagingUsernameText = value;
                    OnPropertyChanged("MessagingUsernameText");  // To notify when the property is changed
                }
            }
        }
        public String AcsUrlText
        {
            get { return acsUrlText; }
            set
            {
                if (acsUrlText != value)
                {
                    acsUrlText = value;
                    OnPropertyChanged("AcsUrlText");  // To notify when the property is changed
                }
            }
        }
        public String AcsPortText
        {
            get { return acsPortText; }
            set
            {
                if (acsPortText != value)
                {
                    acsPortText = value;
                    OnPropertyChanged("AcsPortText");  // To notify when the property is changed
                }
            }
        }
        public String AcsUsernameText
        {
            get { return acsUsernameText; }
            set
            {
                if (acsUsernameText != value)
                {
                    acsUsernameText = value;
                    OnPropertyChanged("AcsUsernameText");  // To notify when the property is changed
                }
            }
        }
        public String AcsIsSecureContent
        {
            get { return acsIsSecureContent; }
            set
            {
                if (acsIsSecureContent != value)
                {
                    acsIsSecureContent = value;
                    OnPropertyChanged("AcsIsSecureContent");  // To notify when the property is changed
                }
            }
        }

        public String AcsStatusContent
        {
            get { return acsStatusContent; }
            set
            {
                if (acsStatusContent != value)
                {
                    acsStatusContent = value;
                    OnPropertyChanged("AcsStatusContent");  // To notify when the property is changed
                }
            }
        }

        public bool SendAllCallsBtnEnabled
        {
            get { return sendAllCallsBtnEnabled; }
            set
            {
                if (sendAllCallsBtnEnabled != value)
                {
                    sendAllCallsBtnEnabled = value;
                    OnPropertyChanged("SendAllCallsBtnEnabled");  // To notify when the property is changed
                }
            }
        }

        public bool IsAvayaClientSDKGridVisible
        {
            get { return isAvayaClientSDKGridVisible; }
            set
            {
                if (isAvayaClientSDKGridVisible != value)
                {
                    isAvayaClientSDKGridVisible = value;
                    OnPropertyChanged("IsAvayaClientSDKGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsDesktopSharingBtnVisible
        {
            get { return isDesktopSharingBtnVisible; }
            set
            {
                if (isDesktopSharingBtnVisible != value)
                {
                    isDesktopSharingBtnVisible = value;
                    OnPropertyChanged("IsDesktopSharingBtnVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsConferenceControlsBtnVisible
        {
            get { return isConferenceControlsBtnVisible; }
            set
            {
                if (isConferenceControlsBtnVisible != value)
                {
                    isConferenceControlsBtnVisible = value;
                    OnPropertyChanged("IsConferenceControlsBtnVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsCollaborationBtnVisible
        {
            get { return isCollaborationBtnVisible; }
            set
            {
                if (isCollaborationBtnVisible != value)
                {
                    isCollaborationBtnVisible = value;
                    OnPropertyChanged("IsCollaborationBtnVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsAboutScreenGridVisible
        {
            get { return isAboutScreenGridVisible; }
            set
            {
                if (isAboutScreenGridVisible != value)
                {
                    isAboutScreenGridVisible = value;
                    OnPropertyChanged("IsAboutScreenGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsAttachmentListGridVisible
        {
            get { return isAttachmentListGridVisible; }
            set
            {
                if (isAttachmentListGridVisible != value)
                {
                    isAttachmentListGridVisible = value;
                    OnPropertyChanged("IsAttachmentListGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsViewConversationGridVisible
        {
            get { return isViewConversationGridVisible; }
            set
            {
                if (isViewConversationGridVisible != value)
                {
                    isViewConversationGridVisible = value;
                    OnPropertyChanged("IsViewConversationGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsCreateNewChatGridVisible
        {
            get { return isCreateNewChatGridVisible; }
            set
            {
                if (isCreateNewChatGridVisible != value)
                {
                    isCreateNewChatGridVisible = value;
                    OnPropertyChanged("IsCreateNewChatGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsConversationListGridVisible
        {
            get { return isConversationListGridVisible; }
            set
            {
                if (isConversationListGridVisible != value)
                {
                    isConversationListGridVisible = value;
                    OnPropertyChanged("IsConversationListGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsVideoGridVisible
        {
            get { return isVideoGridVisible; }
            set
            {
                if (isVideoGridVisible != value)
                {
                    isVideoGridVisible = value;
                    OnPropertyChanged("IsVideoGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsActiveCallGridVisible
        {
            get { return isActiveCallGridVisible; }
            set
            {
                if (isActiveCallGridVisible != value)
                {
                    isActiveCallGridVisible = value;
                    OnPropertyChanged("IsActiveCallGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsCallServiceGridVisible
        {
            get { return isCallServiceGridVisible; }
            set
            {
                if (isCallServiceGridVisible != value)
                {
                    isCallServiceGridVisible = value;
                    OnPropertyChanged("IsCallServiceGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsCallLogGridVisible
        {
            get { return isCallLogGridVisible; }
            set
            {
                if (isCallLogGridVisible != value)
                {
                    isCallLogGridVisible = value;
                    OnPropertyChanged("IsCallLogGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsContactSearchGridVisible
        {
            get { return isContactSearchGridVisible; }
            set
            {
                if (isContactSearchGridVisible != value)
                {
                    isContactSearchGridVisible = value;
                    OnPropertyChanged("IsContactSearchGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsViewContactGridVisible
        {
            get { return isViewContactGridVisible; }
            set
            {
                if (isViewContactGridVisible != value)
                {
                    isViewContactGridVisible = value;
                    OnPropertyChanged("IsViewContactGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsContactsGridVisible
        {
            get { return isContactsGridVisible; }
            set
            {
                if (isContactsGridVisible != value)
                {
                    isContactsGridVisible = value;
                    OnPropertyChanged("IsContactsGridVisible");  // To notify when the property is changed
                }
            }
        }
        public bool IsDeviceServiceSettingsGridVisible
        {
            get { return isDeviceServiceSettingsGridVisible; }
            set
            {
                if (isDeviceServiceSettingsGridVisible != value)
                {
                    isDeviceServiceSettingsGridVisible = value;
                    OnPropertyChanged("IsDeviceServiceSettingsGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsMessagingServiceSettingsGridVisible
        {
            get { return isMessagingServiceSettingsGridVisible; }
            set
            {
                if (isMessagingServiceSettingsGridVisible != value)
                {
                    isMessagingServiceSettingsGridVisible = value;
                    OnPropertyChanged("IsMessagingServiceSettingsGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsSettingsGridVisible
        {
            get { return isSettingsGridVisible; }
            set
            {
                if (isSettingsGridVisible != value)
                {
                    isSettingsGridVisible = value;
                    OnPropertyChanged("IsSettingsGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsCallServiceSettingsGridVisible
        {
            get { return isCallServiceSettingsGridVisible; }
            set
            {
                if (isCallServiceSettingsGridVisible != value)
                {
                    isCallServiceSettingsGridVisible = value;
                    OnPropertyChanged("IsCallServiceSettingsGridVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsDeleteContactBtnVisible
        {
            get { return isDeleteContactBtnVisible; }
            set
            {
                if (isDeleteContactBtnVisible != value)
                {
                    isDeleteContactBtnVisible = value;
                    OnPropertyChanged("IsDeleteContactBtnVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsUpdateContactBtnVisible
        {
            get { return isUpdateContactBtnVisible; }
            set
            {
                if (isUpdateContactBtnVisible != value)
                {
                    isUpdateContactBtnVisible = value;
                    OnPropertyChanged("IsUpdateContactBtnVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsEditContactBtnVisible
        {
            get { return isEditContactBtnVisible; }
            set
            {
                if (isEditContactBtnVisible != value)
                {
                    isEditContactBtnVisible = value;
                    OnPropertyChanged("IsEditContactBtnVisible");  // To notify when the property is changed
                }
            }
        }

        public bool IsaddNewContactBtnVisible
        {
            get { return isaddNewContactBtnVisible; }
            set
            {
                if (isaddNewContactBtnVisible != value)
                {
                    isaddNewContactBtnVisible = value;
                    OnPropertyChanged("IsaddNewContactBtnVisible");  // To notify when the property is changed
                }
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            CallLogsBtnEnabled = false;
            ContactServiceBtnEnabled = false;
            CallServiceBtnEnabled = false;
            MessagingServiceBtnEnabled = false;
            SendAllCallsBtnEnabled = false;
            IsDesktopSharingBtnVisible = false;
            IsAvayaClientSDKGridVisible = true;
            IsSettingsGridVisible = false;
            IsCallServiceSettingsGridVisible = false;
            IsCollaborationBtnVisible = false;
            IsaddNewContactBtnVisible = false;
            SipPortText = "5061";
            MessagingPortText = "8443";
            DesktopSharingBtnContent = "Start Sharing";
            SipTransportBtnContent = "ON";
            SendAllCallsBtnContent = "OFF";
            MessagingTLSContent = "ON";
            MessagingLoginStatusContent = "Not Logged In";
            SipLoginStatusContent = "Not Logged In";
            CallStateContent = String.Empty;
            CallDurationContent = String.Empty;
            AcsIsSecureContent = "Yes";
            AcsStatusContent = "Not Logged In";
            FirstNameIsReadOnly = true;
            LastNameIsReadOnly = true;
            NumberIsReadOnly = true;
            EmailIsReadOnly = true;

            DataContext = this;

            SDKManager sdkmanager = SDKManager.GetInstance();
            sdkmanager.UserRegistrationSuccessfulEvent += HandleUserRegistration;
            sdkmanager.UserRegistrationInProgressEvent += HandleUserRegistrationInProgress;
            sdkmanager.UserUnRegistrationSuccessfulEvent += HandleUserUnRegistration;
            sdkmanager.ClientShutdownCompletedEvent += HandleClientShutdown;

            CallFeatureManager callFeatureManager = CallFeatureManager.GetInstance();
            callFeatureManager.UpdateSACUIEvent += HandleUpdateSACUIEvent;

            CallManager callmanager = CallManager.GetInstance();
            callmanager.IncomingCallEvent += HandleIncomingCallEvent;
            callmanager.CallStateChangedEvent += HandleCallStateChangedEvent;
            callmanager.CallStartedEvent += HandleCallStartedEvent;
            callmanager.CallEstablishedEvent += HandleCallEstablishedEvent;
            callmanager.MuteEvent += HandleMuteEvent;
            callmanager.UpdateVideoUIEvent += HandleUpdateVideoUIEvent;
            callmanager.RemoteAddressChangedEvent += HandleRemoteAddressChangedEvent;
            callmanager.ParticipantsChangedEvent += HandleParticipantsChangedEvent;
            callmanager.ConferenceStartedEvent += HandleConferenceStartedEvent;
            callmanager.ConferenceCapabilitiesChangedEvent += HandleConferenceCapabilitiesChangedEvent;

            timer.Tick += new EventHandler(HandleTimerTickEvent);
            timer.Interval = new TimeSpan(0, 0, 0, 0, 1);

            ContactManager contactManager = ContactManager.GetInstance();
            contactManager.ContactServiceAvailableEvent += HandleContactServiceAvailableEvent;
            contactManager.ContactServicesCapabilitiesChangedEvent += HandleContactServicesCapabilitiesChangedEvent;
            contactManager.GetContactDoneEvent += HandleGetContactDoneEvent;
            contactManager.UpdateContactUIEvent += HandleUpdateContactUIEvent;
            contactManager.SearchContactDoneEvent += HandleSearchContactDoneEvent;
            contactManager.SearchContactFailedEvent += HandleSearchContactFailedEvent;

            MessagingServiceManager.MessagingServiceAvailableEvent += HandleMessagingServiceAvailableEvent;
            MessagingServiceManager.UpdateConversationUIEvent += HandelUpdateConversationUIEvent;
            MessagingServiceManager.UpdateViewConversationUIEvent += HandleUpdateViewConversationUIEvent;
            MessagingServiceManager.ViewConversationUIEvent += HandleViewConversationUIEvent;
            MessagingServiceManager.ParicipantAddedSuccessEvent += HandleParicipantAddedSuccessEvent;
            MessagingServiceManager.ComposingParticipantsChangedEvent += HandleComposingParticipantsChangedEvent;
            MessagingServiceManager.StartConversationSuccessEvent += HandleStartConversationSuccessEvent;

            CollaborationManager collaborationManager = CollaborationManager.GetInstance();
            collaborationManager.UpdateSharingControlUIEvent += HandleUpdateSharingControlUIEvent;
            CollaborationWindow.CollaborationWindowClosingEvent += HandleCollaborationWindowClosingEvent;
        }
        #region Event handlers to handle UI       

        public void HandleUserRegistration(object sender, EventArgs e)
        {
            SipLoginStatusContent = "Logged In";
            CallLogsBtnEnabled = true;
            ContactServiceBtnEnabled = true;
            CallServiceBtnEnabled = true;
        }

        public void HandleUserRegistrationInProgress(object sender, EventArgs e)
        {
            SipLoginStatusContent = "Logging In";
        }

        public void HandleUserUnRegistration(object sender, EventArgs e)
        {
            SipLoginStatusContent = "Not Logged In";
            MessagingLoginStatusContent = "Not Logged In";
        }

        public void HandleClientShutdown(object sender, EventArgs e)
        {
            StartClient();  // restart
        }

        public void HandleFinalClientShutdown(object sender, EventArgs e)
        {
            App.Current.Shutdown();
        }

        public void HandleIncomingCallEvent(object sender, EventArgs e)
        {
            AcceptPopup dialog = new AcceptPopup();
            dialog.Owner = this;
            dialog.ShowDialog();
        }

        public void HandleUpdateSACUIEvent(object sender, EventArgs e)
        {
            //Enable sendAllCallsButton if SendAllCallsCapability is allowed
            //Default sendAllCallButton is disabled
            if (CallFeatureManager.CallFeatureServiceInstance.SendAllCallsCapability.Allowed)
            {
                SendAllCallsBtnEnabled = true;
                //Set sendAllCallsBtn to "ON" if SendAllCalls is enabled
                if (CallFeatureManager.CallFeatureServiceInstance.SendAllCallsEnabled)
                {
                    SendAllCallsBtnContent = "ON";
                }
                else
                {
                    SendAllCallsBtnContent = "OFF";
                }
            }
        }

        public void HandleCallStateChangedEvent(object sender, EventArgs e)
        {
            if (CallManager.CurrentCall != null)
            {
                CallStateContent = CallManager.CurrentCall.State.ToString();
                if (CallManager.CurrentCall.State == CallState.Established)
                {
                    stopWatch.Start();
                    timer.Start();
                    DisplayParticipantList();
                    if (CallManager.CurrentCall.AudioMuted)
                    {
                        MuteBtnContent = "ON";
                    }
                    else
                    {
                        MuteBtnContent = "OFF";
                    }
                }

                if (CallManager.CurrentCall.State == CallState.Ended || CallManager.CurrentCall.State == CallState.Ignored)
                {
                    if (stopWatch.IsRunning)
                    {
                        stopWatch.Stop();
                        stopWatch.Reset();
                    }
                    CallManager.GetInstance().StopLocalVideo();
                    CallManager.GetInstance().StopVideoWindow();
                    IsCallServiceGridVisible = true;
                    IsActiveCallGridVisible = false;
                    IsVideoGridVisible = false;
                }
            }
        }

        public void HandleCallStartedEvent(object sender, EventArgs e)
        {
            IsCallServiceGridVisible = false;
            IsActiveCallGridVisible = true;
        }

        public void HandleCallEstablishedEvent(object sender, EventArgs e)
        {
            IsAvayaClientSDKGridVisible = false;
            IsSettingsGridVisible = false;
            IsCallServiceSettingsGridVisible = false;
            IsCallServiceGridVisible = false;
            IsCallLogGridVisible = false;
            IsContactsGridVisible = false;
            IsActiveCallGridVisible = true;
        }

        public void HandleMuteEvent(object sender, EventArgs e)
        {
            Call call = SDKManager.GetUser().CallService.ActiveCall;
            if (call != null)
            {
                if (call.AudioMuted)
                {
                    MuteBtnContent = "ON";
                }
                else
                {
                    MuteBtnContent = "OFF";
                }
            }
        }

        public void HandleParticipantsChangedEvent(object sender, EventArgs e)
        {
            DisplayParticipantList();
        }

        public void HandleConferenceStartedEvent(object sender, EventArgs e)
        {
        }

        public void HandleConferenceCapabilitiesChangedEvent(object sender, EventArgs e)
        {
            if (CallManager.ConferenceInstance != null && CallManager.ConferenceInstance.ModerateConferenceCapability.Allowed)
            {
                IsConferenceControlsBtnVisible = true;
            }
            else
            {
                Console.WriteLine("Moderator capability not allowed");
            }
            if (CollaborationManager.CollaborationInstance != null)
            {
                if (CollaborationManager.CollaborationInstance.ContentSharing.ShareFullScreenCapability.Allowed)
                {
                    IsDesktopSharingBtnVisible = true;
                }
            }
        }

        /// <summary>
        /// Event handler to handle timer tick event
        /// </summary>
        void HandleTimerTickEvent(object sender, EventArgs e)
        {
            if (stopWatch.IsRunning)
            {
                TimeSpan ts = stopWatch.Elapsed;
                CallDurationContent = String.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);
            }
        }
        public void HandleUpdateVideoUIEvent(object sender, EventArgs e)
        {
            IsVideoGridVisible = true;
        }


        public void HandleContactServiceAvailableEvent(object sender, EventArgs e)
        {
            if (SDKManager.UserInstance.ContactService.NetworkSearchContactCapability.Allowed)
            {
                AcsStatusContent = "Logged In";
            }
        }

        public void HandleContactServicesCapabilitiesChangedEvent(object sender, EventArgs e)
        {
            if (!SDKManager.UserInstance.ContactService.NetworkSearchContactCapability.Allowed)
            {
                AcsStatusContent = "Not Logged In";
            }
            else
            {
                AcsStatusContent = "Logged In";
            }
        }

        public void HandleGetContactDoneEvent(object sender, EventArgs e)
        {
            DisplayContact();
        }

        public void HandleUpdateContactUIEvent(object sender, EventArgs e)
        {
            ContactManager contactManager = ContactManager.GetInstance();
            contactManager.GetContacts();
            IsContactsGridVisible = true;
            IsViewContactGridVisible = false;
            FirstNameIsReadOnly = true;
            LastNameIsReadOnly = true;
            NumberIsReadOnly = true;
            EmailIsReadOnly = true;
        }
        public void HandleSearchContactDoneEvent(object sender, EventArgs e)
        {
            SearchingContactLabelContent = "";
            DisplayContactSearchResult();
        }

        public void HandleSearchContactFailedEvent(object sender, EventArgs e)
        {
            SearchingContactLabelContent = "";
            NotificationHelper.ShowNotification("Contact Search Failed");
        }

        public void HandleRemoteAddressChangedEvent(object sender, EventArgs e)
        {
            DisplayParticipantList();
        }

        public void HandleMessagingServiceAvailableEvent(object sender, EventArgs e)
        {
            if (SDKManager.UserInstance.MessagingService.IsServiceAvailable)
            {
                MessagingLoginStatusContent = "Logged In";
                MessagingServiceBtnEnabled = true;
            }
        }

        public void HandelUpdateConversationUIEvent(object sender, EventArgs e)
        {
            DisplayConversationList();
        }

        public void HandleUpdateViewConversationUIEvent(object sender, EventArgs e)
        {
            DisplayMessage();
        }
        public void HandleViewConversationUIEvent(object sender, EventArgs e)
        {
            DisplayMessageList();
        }

        public void HandleParicipantAddedSuccessEvent(object sender, EventArgs e)
        {
            String conversationWithParticipant = "";
            foreach (Participant participant in MessagingServiceManager.ActiveConversation.Participants)
            {
                if (participant.Address == SDKManager.UserInstance.MessagingService.SelfAddress)
                {
                    continue;
                }
                conversationWithParticipant = conversationWithParticipant + participant.DisplayName;
            }
            conversationWithLabel.Content = "Conversation with " + conversationWithParticipant;
        }

        public void HandleStartConversationSuccessEvent(object sender, EventArgs e)
        {
            IsCreateNewChatGridVisible = false;
            IsViewConversationGridVisible = true;
        }

        public void HandleComposingParticipantsChangedEvent(object sender, EventArgs e)
        {
            composingParticipant.Content = MessagingServiceManager.ComposingParticipants;
        }

        public void HandleUpdateSharingControlUIEvent(object sender, EventArgs e)
        {
            if (CollaborationManager.CollaborationInstance != null)
            {
                if (CollaborationManager.CollaborationInstance.ContentSharing.ShareFullScreenCapability.Allowed)
                {
                    IsDesktopSharingBtnVisible = true;
                }
            }
            if (CollaborationManager.IsContentSharingActive)
            {
                IsCollaborationBtnVisible = true;
            }
            else
            {
                IsCollaborationBtnVisible = false;
            }
            if (CollaborationManager.IsDesktopSharingActive)
            {
                DesktopSharingBtnContent = "Stop Sharing";
            }
            else
            {
                DesktopSharingBtnContent = "Start Sharing";
            }
        }

        public void HandleCollaborationWindowClosingEvent(object sender, EventArgs e)
        {
            IsCollaborationBtnVisible = true;
        }

        #endregion

        #region Call service settings , Messaging service settings , Device service settings and about screen 

        private void settingsBtn_Click(object sender, RoutedEventArgs e)
        {
            IsAvayaClientSDKGridVisible = false;
            IsSettingsGridVisible = true;
        }

        private void callServiceSettingsBtn_Click(object sender, RoutedEventArgs e)
        {
            SipServerAddressText = Configuration.SipServerAddress;
            SipPortText = Configuration.SipPort.ToString();
            SipDomainText = Configuration.SipDomain;
            SipUsernameText = Configuration.SipUserName;
            sipPassword.Password = Configuration.SipPassword;
            if (Configuration.IsSecure == true)
            {
                SipTransportBtnContent = "ON";
            }
            else
            {
                SipTransportBtnContent = "OFF";
            }
            IsSettingsGridVisible = false;
            IsCallServiceSettingsGridVisible = true;
        }

        private void settingsBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsAvayaClientSDKGridVisible = true;
            IsSettingsGridVisible = false;
        }

        private void applyBtn_Click(object sender, RoutedEventArgs e)
        {
            CallLogsBtnEnabled = false;
            ContactServiceBtnEnabled = false;
            CallServiceBtnEnabled = false;
            MessagingServiceBtnEnabled = false;
            conversationList.Items.Clear();
            MessagingServiceManager.ConversationList.Clear();
            ContactManager.ContactList.Clear();
            Configuration.SipServerAddress = SipServerAddressText;
            int.TryParse(SipPortText, out Configuration.SipPort);
            Configuration.SipDomain = sipDomainText;
            Configuration.SipUserName = SipUsernameText;
            Configuration.SipPassword = sipPassword.Password;
            if (SipTransportBtnContent.ToString().Equals("ON"))
            {
                Configuration.IsSecure = true;
            }
            else
            {
                Configuration.IsSecure = false;
            }
            CommunicationSampleApp.Properties.Settings.Default.SipServerAddress = Configuration.SipServerAddress;
            CommunicationSampleApp.Properties.Settings.Default.SipDomain = Configuration.SipDomain;
            CommunicationSampleApp.Properties.Settings.Default.SipUserName = Configuration.SipUserName;
            CommunicationSampleApp.Properties.Settings.Default.SipPassword = Configuration.SipPassword;
            CommunicationSampleApp.Properties.Settings.Default.SipPort = Configuration.SipPort;
            CommunicationSampleApp.Properties.Settings.Default.IsSecure = Configuration.IsSecure;
            CommunicationSampleApp.Properties.Settings.Default.Save();

            SipLoginStatusContent = "Logging In";
            RestartClient();
        }

        private void RestartClient()
        {
            if (SDKManager.ClientInstance != null)
            {
                if (SDKManager.UserInstance != null)
                {
                    SDKManager.GetInstance().RemoveUser(SDKManager.UserInstance);
                }
                SDKManager.ClientInstance.Shutdown(true);  // restart client on ShutdownCompleted event
            }
            else
                StartClient();
        }

        private void StartClient()
        {
            SDKManager.GetInstance().StartClient();
            SDKManager.GetInstance().SetUserConfiguration();
        }

        private void callServiceSettingsBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsCallServiceSettingsGridVisible = false;
            IsSettingsGridVisible = true;
        }

        private void sipTransportBtn_Click(object sender, RoutedEventArgs e)
        {
            if (SipTransportBtnContent.Equals("OFF"))
            {
                SipTransportBtnContent = "ON";
                Configuration.IsSecure = true;
            }
            else if (sipTransportBtn.Content.Equals("ON"))
            {
                SipTransportBtnContent = "OFF";
                Configuration.IsSecure = false;
            }
        }

        private void messagingServiceSettingsBtn_Click(object sender, RoutedEventArgs e)
        {
            MessagingUsernameText = Configuration.MessagingServiceUserName;
            messagingPassword.Password = Configuration.MessagingServicePassword;
            MessagingServerAddressText = Configuration.MessagingServiceServerAddress;
            MessagingPortText = Configuration.MessagingServiceServerPort.ToString();
            if (Configuration.MessagingServiceServerIsSecure == true)
            {
                MessagingTLSContent = "ON";
            }
            else
            {
                MessagingTLSContent = "OFF";
            }
            switch (Configuration.PollIntervalInMinutes)
            {
                case 0:
                    messagingPollInterval.SelectedIndex = 0;
                    break;
                case 1:
                    messagingPollInterval.SelectedIndex = 1;
                    break;
                case 2:
                    messagingPollInterval.SelectedIndex = 2;
                    break;
                case 5:
                    messagingPollInterval.SelectedIndex = 3;
                    break;
                case 15:
                    messagingPollInterval.SelectedIndex = 4;
                    break;
                case 60:
                    messagingPollInterval.SelectedIndex = 5;
                    break;
                case 1000:
                    messagingPollInterval.SelectedIndex = 6;
                    break;

            }
            IsSettingsGridVisible = false;
            IsMessagingServiceSettingsGridVisible = true;
        }

        private void messagingServiceSettingsBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsSettingsGridVisible = true;
            IsMessagingServiceSettingsGridVisible = false;
        }

        private void messagingTLS_Click(object sender, RoutedEventArgs e)
        {
            if (MessagingTLSContent.Equals("OFF"))
            {
                MessagingTLSContent = "ON";
                Configuration.MessagingServiceServerIsSecure = true;
            }
            else if (MessagingTLSContent.Equals("ON"))
            {
                MessagingTLSContent = "OFF";
                Configuration.MessagingServiceServerIsSecure = false;
            }
        }

        private void messagingApplyBtn_Click(object sender, RoutedEventArgs e)
        {
            CallLogsBtnEnabled = false;
            ContactServiceBtnEnabled = false;
            CallServiceBtnEnabled = false;
            MessagingServiceBtnEnabled = false;
            conversationList.Items.Clear();
            MessagingServiceManager.ConversationList.Clear();
            ContactManager.ContactList.Clear();
            Configuration.SipServerAddress = SipServerAddressText;
            int.TryParse(SipPortText, out Configuration.SipPort);
            Configuration.SipDomain = sipDomainText;
            Configuration.SipUserName = SipUsernameText;
            Configuration.SipPassword = sipPassword.Password;
            if (SipTransportBtnContent.Equals("ON"))
            {
                Configuration.IsSecure = true;
            }
            else
            {
                Configuration.IsSecure = false;
            }

            Configuration.MessagingServiceUserName = MessagingUsernameText;
            Configuration.MessagingServicePassword = messagingPassword.Password;
            Configuration.MessagingServiceServerAddress = MessagingServerAddressText;
            if (MessagingTLSContent.ToString().Equals("ON"))
            {
                Configuration.MessagingServiceServerIsSecure = true;
            }
            else
            {
                Configuration.MessagingServiceServerIsSecure = false;
            }

            int.TryParse(MessagingPortText, out Configuration.MessagingServiceServerPort);
            switch (messagingPollInterval.SelectedIndex)
            {
                case 0:
                    Configuration.PollIntervalInMinutes = (uint)RefreshType.PushMode;
                    break;
                case 1:
                    Configuration.PollIntervalInMinutes = (uint)RefreshType.OneMinute;
                    break;
                case 2:
                    Configuration.PollIntervalInMinutes = (uint)RefreshType.TwoMinutes;
                    break;
                case 3:
                    Configuration.PollIntervalInMinutes = (uint)RefreshType.FiveMinutes;
                    break;
                case 4:
                    Configuration.PollIntervalInMinutes = (uint)RefreshType.FifteenMinutes;
                    break;
                case 5:
                    Configuration.PollIntervalInMinutes = (uint)RefreshType.SixtyMinutes;
                    break;
                case 6:
                    Configuration.PollIntervalInMinutes = (uint)RefreshType.ManualMode;
                    break;
            }
            CommunicationSampleApp.Properties.Settings.Default.SipServerAddress = Configuration.SipServerAddress;
            CommunicationSampleApp.Properties.Settings.Default.SipDomain = Configuration.SipDomain;
            CommunicationSampleApp.Properties.Settings.Default.SipUserName = Configuration.SipUserName;
            CommunicationSampleApp.Properties.Settings.Default.SipPassword = Configuration.SipPassword;
            CommunicationSampleApp.Properties.Settings.Default.SipPort = Configuration.SipPort;
            CommunicationSampleApp.Properties.Settings.Default.IsSecure = Configuration.IsSecure;
            CommunicationSampleApp.Properties.Settings.Default.MessagingServiceServerAddress = Configuration.MessagingServiceServerAddress;
            CommunicationSampleApp.Properties.Settings.Default.MessagingServiceUserName = Configuration.MessagingServiceUserName;
            CommunicationSampleApp.Properties.Settings.Default.MessagingServicePassword = Configuration.MessagingServicePassword;
            CommunicationSampleApp.Properties.Settings.Default.PollIntervalInMinutes = Configuration.PollIntervalInMinutes;
            CommunicationSampleApp.Properties.Settings.Default.MessagingServiceServerPort = Configuration.MessagingServiceServerPort;
            CommunicationSampleApp.Properties.Settings.Default.MessagingServiceTLS = Configuration.MessagingServiceServerIsSecure;
            CommunicationSampleApp.Properties.Settings.Default.Save();

            MessagingLoginStatusContent = "Logging In";
            RestartClient();
        }

        private void deviceServiceSettingsBtn_Click(object sender, RoutedEventArgs e)
        {
            IsSettingsGridVisible = false;
            IsDeviceServiceSettingsGridVisible = true;
            AcsUrlText = Configuration.ACSUrl;
            AcsPortText = Configuration.ACSPort.ToString();
            if (Configuration.ACSIsSecure == true)
            {
                AcsIsSecureContent = "Yes";
            }
            else
            {
                AcsIsSecureContent = "No";
            }
            AcsUsernameText = Configuration.ACSUserName;
            acsPassword.Password = Configuration.ACSPassword;
        }

        private void deviceServiceSettingsBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsSettingsGridVisible = true;
            IsDeviceServiceSettingsGridVisible = false;
        }

        private void acsApply_Click(object sender, RoutedEventArgs e)
        {
            CallLogsBtnEnabled = false;
            ContactServiceBtnEnabled = false;
            CallServiceBtnEnabled = false;
            MessagingServiceBtnEnabled = false;
            conversationList.Items.Clear();
            MessagingServiceManager.ConversationList.Clear();
            ContactManager.ContactList.Clear();
            Configuration.ACSUrl = AcsUrlText;
            int.TryParse(AcsPortText, out Configuration.ACSPort);
            if (AcsIsSecureContent.ToString().Equals("Yes"))
            {
                Configuration.ACSIsSecure = true;
            }
            else
            {
                Configuration.ACSIsSecure = false;
            }
            Configuration.ACSUserName = AcsUsernameText;
            Configuration.ACSPassword = acsPassword.Password;
            CommunicationSampleApp.Properties.Settings.Default.ACSUrl = Configuration.ACSUrl;
            CommunicationSampleApp.Properties.Settings.Default.ACSPort = Configuration.ACSPort;
            CommunicationSampleApp.Properties.Settings.Default.ACSIsSecure = Configuration.ACSIsSecure;
            CommunicationSampleApp.Properties.Settings.Default.ACSUserName = Configuration.ACSUserName;
            CommunicationSampleApp.Properties.Settings.Default.ACSPassword = Configuration.ACSPassword;
            CommunicationSampleApp.Properties.Settings.Default.Save();

            AcsStatusContent = "Logging In";
            RestartClient();
        }

        private void acsIsSecure_Click(object sender, RoutedEventArgs e)
        {
            if (AcsIsSecureContent.ToString() == "Yes")
            {
                AcsIsSecureContent = "No";

            }
            else
            {
                AcsIsSecureContent = "Yes";
            }
        }

        private void aboutBtn_Click(object sender, RoutedEventArgs e)
        {
            sdkVersion.Content = Client.Version;
            appVersion.Content = Configuration.ProductVersion + " Build " + Configuration.BuildNumber;
            DateTime buildDate = new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
            appBuildDate.Content = buildDate.ToString();
            IsAboutScreenGridVisible = true;
            IsSettingsGridVisible = false;
        }

        private void aboutBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsAboutScreenGridVisible = false;
            IsSettingsGridVisible = true;
        }

        #endregion Call service settings , Messaging service settings , Device service settings and about screen 

        #region Call Service
        private void callServiceBtn_Click(object sender, RoutedEventArgs e)
        {
            IsAvayaClientSDKGridVisible = false;
            IsCallServiceGridVisible = true;
        }

        private void endCallBtn_Click(object sender, RoutedEventArgs e)
        {
            CallManager callManager = CallManager.GetInstance();
            Call call = CallManager.CurrentCall;
            if (call != null)
            {
                CallManager.GetInstance().StopRinging();
                if (call.IsVideoActive)
                {
                    callManager.StopVideoWindow();
                }
                callManager.EndCall(call);
                if (stopWatch.IsRunning)
                {
                    stopWatch.Stop();
                    stopWatch.Reset();
                }
            }
            IsVideoGridVisible = false;
            IsCallServiceGridVisible = true;
            IsActiveCallGridVisible = false;
        }

        private void audioCallBtn_Click(object sender, RoutedEventArgs e)
        {
            if (numberToCall.Text != String.Empty)
            {
                IsConferenceControlsBtnVisible = false;
                IsDesktopSharingBtnVisible = false;
                participantList.Items.Clear();
                dtmfString.Text = string.Empty;
                CallDurationContent = string.Empty;
                MuteBtnContent = "OFF";
                CallManager callManager = CallManager.GetInstance();
                callManager.CreateAudioCall(numberToCall.Text);
                callManager.StartCall(CallManager.OutgoingCall);
                IsCallServiceGridVisible = false;
                IsActiveCallGridVisible = true;
            }
            else
            {
                NotificationHelper.ShowNotification("Enter number to call");
            }
        }

        private void callServiceBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsCallServiceGridVisible = false;
            IsAvayaClientSDKGridVisible = true;
        }

        private void videoCallBtn_Click(object sender, RoutedEventArgs e)
        {
            if (numberToCall.Text != String.Empty)
            {
                CallManager callManager = CallManager.GetInstance();
                IsConferenceControlsBtnVisible = false;
                IsDesktopSharingBtnVisible = false;
                dtmfString.Text = string.Empty;
                participantList.Items.Clear();
                CallDurationContent = string.Empty;
                MuteBtnContent = "OFF";
                callManager.CreateAudioCall(numberToCall.Text);
                callManager.AddVideo(CallManager.OutgoingCall);
                callManager.StartCall(CallManager.OutgoingCall);
            }
            else
            {
                NotificationHelper.ShowNotification("Enter number to call");
            }
        }

        private void muteBtn_Click(object sender, RoutedEventArgs e)
        {
            CallManager callManager = CallManager.GetInstance();
            callManager.MuteCall();
        }

        /// <summary>
        /// Event handler occurs when DTMF textbox text changes
        /// </summary>
        private void dtmfStringTextChanged(object sender, TextChangedEventArgs e)
        {
            if (dtmfString.Text != OldDtmfString)
            {
                if (dtmfString.Text.Length > 0)
                {
                    Dtmf = dtmfString.Text.Last();
                    CallManager callManager = CallManager.GetInstance();
                    callManager.SendDTMF(Dtmf);
                }
                OldDtmfString = dtmfString.Text;
            }
        }

        /// <summary>
        /// Validate input dtmf string with valid characters
        /// </summary>
        private void dtmfStringInputValidation(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9 # * A B C D]+");
            e.Handled = regex.IsMatch(e.Text);
        }

        /// <summary>
        /// Open moderator controls list window
        /// </summary>
        private void conferenceControlsBtn_Click(object sender, RoutedEventArgs e)
        {
            ConferenceControlsWindow conferenceControlsWindow = new ConferenceControlsWindow();
            conferenceControlsWindow.Owner = this;
            conferenceControlsWindow.Show();
        }

        /// <summary>
        /// Start/Stop sharing desktop full screen
        /// </summary>
        private void desktopSharingBtn_Click(object sender, RoutedEventArgs e)
        {
            if (CollaborationManager.IsDesktopSharingActive)
            {
                CollaborationManager.GetInstance().StopSharingFullScreen();
            }
            else
            {
                CollaborationManager.GetInstance().StartSharingFullScreen();
            }
        }

        /// <summary>
        /// If content sharing is active open collaboration window
        /// </summary>
        private void collaborationBtn_Click(object sender, RoutedEventArgs e)
        {
            CollaborationWindow.collaborationWindow = new CollaborationWindow(CollaborationManager.ContentSharingInstance);
            CollaborationWindow.collaborationWindow.Show();
            IsCollaborationBtnVisible = false;
        }

        /// <summary>
        /// Display active call participant list on UI
        /// </summary>
        public void DisplayParticipantList()
        {
            participantList.Items.Clear();
            Call call = SDKManager.GetUser().CallService.ActiveCall;
            if (call != null)
            {
                //For conference call display list of all participant
                if (call.IsConference && CallManager.ConferenceInstance != null)
                {
                    List<ActiveParticipant> participants = CallManager.ConferenceInstance.Participants;
                    foreach (ActiveParticipant activeparticipant in participants)
                    {
                        participantList.Items.Add(new
                        {
                            participantName = activeparticipant.DisplayName
                        });
                    }
                }
                //For Two party call Display remote participant name
                else
                {
                    Participant participant = call.RemoteParticipant;

                    participantList.Items.Add(new
                    {
                        participantName = participant.DisplayName
                    });
                }
            }
        }
        #endregion Call Service

        #region Contact Service
        private void contactServiceBtn_Click(object sender, RoutedEventArgs e)
        {
            IsAvayaClientSDKGridVisible = false;
            IsContactsGridVisible = true;
            ContactManager contactManager = ContactManager.GetInstance();
            contactManager.GetContacts();
        }

        private void contactsServiceBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsContactsGridVisible = false;
            IsAvayaClientSDKGridVisible = true;
        }

        /// <summary>
        /// View contact details
        /// </summary>
        private void ContactView_Click(object sender, RoutedEventArgs e)
        {
            var item = (sender as ListView).SelectedItem;
            if (item != null)
            {
                try
                { 
                ContactManager.SelectedContact = ContactManager.ContactList.ElementAt(contactList.SelectedIndex);
                IsViewContactGridVisible = true;
                IsContactsGridVisible = false;
                IsEditContactBtnVisible = true;
                IsUpdateContactBtnVisible = false;
                IsaddNewContactBtnVisible = false;
                if (ContactManager.ContactList.ElementAt(contactList.SelectedIndex).DeleteContactCapability.Allowed)
                {
                    IsDeleteContactBtnVisible = true;
                }
                else
                {
                    IsDeleteContactBtnVisible = false;
                }
                FirstNameText = ContactManager.ContactList.ElementAt(contactList.SelectedIndex).FirstName.Value;
                LastNameText = ContactManager.ContactList.ElementAt(contactList.SelectedIndex).LastName.Value;
                if (! ContactManager.ContactList.ElementAt(contactList.SelectedIndex).PhoneNumbers.IsEmpty)
                {
                    NumberText = ContactManager.ContactList.ElementAt(contactList.SelectedIndex).PhoneNumbers.Values[0].PhoneNumber;
                }
                if (! ContactManager.ContactList.ElementAt(contactList.SelectedIndex).EmailAddresses.IsEmpty)
                {
                    EmailText = ContactManager.ContactList.ElementAt(contactList.SelectedIndex).EmailAddresses.Values[0].Address;
                }
                FirstNameIsReadOnly = true;
                LastNameIsReadOnly = true;
                NumberIsReadOnly = true;
                EmailIsReadOnly = true;
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    NotificationHelper.ShowNotification("Wait : Select contact again");
                }
            }
        }

        /// <summary>
        /// Display screen to add new contact
        /// </summary>
        private void addContactBtn_Click(object sender, RoutedEventArgs e)
        {
            IsViewContactGridVisible = true;
            IsContactsGridVisible = false;
            IsUpdateContactBtnVisible = false;
            IsEditContactBtnVisible = false;
            IsDeleteContactBtnVisible = false;
            IsaddNewContactBtnVisible = true;
            FirstNameIsReadOnly = false;
            LastNameIsReadOnly = false;
            NumberIsReadOnly = false;
            EmailIsReadOnly = false;
            FirstNameText = "";
            LastNameText = "";
            NumberText = "";
            EmailText = "";
        }

        /// <summary>
        /// Create contact deatils textviews editable if contact have editable capability
        /// </summary>
        private void editContactBtn_Click(object sender, RoutedEventArgs e)
        {
            Contact selectedContact = ContactManager.ContactList.ElementAt(contactList.SelectedIndex);
            if (selectedContact.UpdateContactCapability.Allowed)
            {
                FirstNameIsReadOnly = false;
                LastNameIsReadOnly = false;
                NumberIsReadOnly = false;
                EmailIsReadOnly = false;
                IsDeleteContactBtnVisible = false;
                IsUpdateContactBtnVisible = true;
            }
        }

        private void addNewContactBtn_Click(object sender, RoutedEventArgs e)
        {
            ContactManager.GetInstance().AddContact(FirstNameText, LastNameText, NumberText, EmailText);
        }

        private void deleteContactBtn_Click(object sender, RoutedEventArgs e)
        {
            ContactManager.GetInstance().DeleteContact();
        }

        private void updateContactBtn_Click(object sender, RoutedEventArgs e)
        {
            ContactManager.GetInstance().UpdateContact(FirstNameText, LastNameText, NumberText, EmailText);
        }

        private void contactDetailsBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsViewContactGridVisible = false;
            IsContactsGridVisible = true;
            FirstNameIsReadOnly = true;
            LastNameIsReadOnly = true;
            NumberIsReadOnly = true;
            EmailIsReadOnly = true;
        }

        private void searchBtn_Click(object sender, RoutedEventArgs e)
        {
            IsContactsGridVisible = false;
            IsContactSearchGridVisible = true;
            ContactManager.GetInstance().StopSearchContact();
            contactSearchList.Items.Clear();
            contactToSearch.Text = string.Empty;
            if (!ContactManager.ContactServiceInstance.NetworkSearchContactCapability.Allowed)
            {
                NotificationHelper.ShowNotification("ACS contact search not available");
            }
        }

        private void contactSearchBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsContactsGridVisible = true;
            IsContactSearchGridVisible = false;
            ContactManager.GetInstance().StopSearchContact();
            ContactManager.GetInstance().StopContactSearchPresence();
            ContactManager.GetInstance().StartContactPresence();
            ContactManager.ContactSearchList.Clear();
        }

        private void searchContactBtn_Click(object sender, RoutedEventArgs e)
        {
            SearchingContactLabelContent = "Searching...";
            ContactManager.GetInstance().SearchContactWithSearchString(contactToSearch.Text);
        }

        /// <summary>
        /// Display contacts on UI
        /// </summary>
        public void DisplayContact()
        {
            contactList.Items.Clear();
            if (ContactManager.ContactList != null)
            {
                string contactName = "";
                string conatctPresence = "";
                foreach (Contact contact in ContactManager.ContactList)
                {

                    if (contact.Presence != null)
                    {
                        switch (contact.Presence.OverallState)
                        {
                            case PresenceState.Available:
                                conatctPresence = @".\Resources\Images\available.png";
                                break;
                            case PresenceState.Away:
                                conatctPresence = @".\Resources\Images\away.png";
                                break;
                            case PresenceState.Busy:
                                conatctPresence = @".\Resources\Images\busy.png";
                                break;
                            case PresenceState.DoNotDisturb:
                                conatctPresence = @".\Resources\Images\dnd.png";
                                break;
                            case PresenceState.Offline:
                                conatctPresence = @".\Resources\Images\offline.png";
                                break;
                            case PresenceState.OnACall:
                                conatctPresence = @".\Resources\Images\onacall.png";
                                break;
                            case PresenceState.OutOfOffice:
                                conatctPresence = @".\Resources\Images\outofoffice.png";
                                break;
                            case PresenceState.Unspecified:
                                conatctPresence = @".\Resources\Images\unspecified.png";
                                break;
                            case PresenceState.Unknown:
                                conatctPresence = @".\Resources\Images\unknown.png";
                                break;
                            default:
                                conatctPresence = @".\Resources\Images\default.png";
                                break;
                        }
                    }
                    else
                    {
                        conatctPresence = @".\Resources\Images\Default.png";
                    }
                    contactName = contact.FirstName.Value + "  " + contact.LastName.Value;
                    contactList.Items.Add(new
                    {
                        presence = conatctPresence,
                        name = contactName
                    });
                }
            }
        }

        /// <summary>
        /// Display contacts on UI
        /// </summary>
        public void DisplayContactSearchResult()
        {
            contactSearchList.Items.Clear();
            if (ContactManager.ContactSearchList != null)
            {
                string contactName = "";
                string contactPresence = "";
                foreach (Contact contact in ContactManager.ContactSearchList)
                {
                    if (contact.Presence != null)
                    {
                        switch (contact.Presence.OverallState)
                        {
                            case PresenceState.Available:
                                contactPresence = @".\Resources\Images\available.png";
                                break;
                            case PresenceState.Away:
                                contactPresence = @".\Resources\Images\away.png";
                                break;
                            case PresenceState.Busy:
                                contactPresence = @".\Resources\Images\busy.png";
                                break;
                            case PresenceState.DoNotDisturb:
                                contactPresence = @".\Resources\Images\dnd.png";
                                break;
                            case PresenceState.Offline:
                                contactPresence = @".\Resources\Images\offline.png";
                                break;
                            case PresenceState.OnACall:
                                contactPresence = @".\Resources\Images\onacall.png";
                                break;
                            case PresenceState.OutOfOffice:
                                contactPresence = @".\Resources\Images\outofoffice.png";
                                break;
                            case PresenceState.Unspecified:
                                contactPresence = @".\Resources\Images\unavailable.png";
                                break;
                            case PresenceState.Unknown:
                                contactPresence = @".\Resources\Images\unavailable.png";
                                break;
                            default:
                                contactPresence = @".\Resources\Images\default.png";
                                break;
                        }
                    }
                    else
                    {
                        contactPresence = @".\Resources\Images\Default.png";
                    }
                    contactName = contact.FirstName.Value + "  " + contact.LastName.Value;
                    contactSearchList.Items.Add(new
                    {
                        presence = contactPresence,
                        contactName
                    });
                }
            }
        }

        #endregion Contact Service

        #region CallLog Service
        private void callLogsBtn_Click(object sender, RoutedEventArgs e)
        {
            IsAvayaClientSDKGridVisible = false;
            IsCallLogGridVisible = true;
            DisplayCallLog();
        }

        private void callLogsBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsCallLogGridVisible = false;
            IsAvayaClientSDKGridVisible = true;
        }

        /// <summary>
        /// Display call log iteams on UI
        /// </summary>
        public void DisplayCallLog()
        {
            callLogsList.Items.Clear();
            if (CallLogManager.CallLogStatus != null)
            {
                foreach (CallLogItem calllogitem in CallLogManager.CallLogItem)
                {
                    if (calllogitem.RemoteParticipants.ElementAt(0).DisplayName != null)
                    {
                        String date;
                        int day = DateTime.Now.Date.Day;
                        int month = DateTime.Now.Date.Month;
                        int year = DateTime.Now.Date.Year;
                        if (calllogitem.StartTime.Date == DateTime.Now.Date)
                        {
                            date = "Today  " + calllogitem.StartTime.ToString("hh:mm:tt");
                        }
                        else if ((day - 1) == calllogitem.StartTime.Date.Day && month == calllogitem.StartTime.Date.Month && year == calllogitem.StartTime.Date.Year)
                        {
                            date = "Yesterday  " + calllogitem.StartTime.ToString("hh:mm:tt");
                        }
                        else
                        {
                            date = calllogitem.StartTime.ToString();
                        }
                        int hrs = calllogitem.TotalCallDurationInSeconds / 3600;
                        int min = (calllogitem.TotalCallDurationInSeconds - (hrs * 3600)) / 60;
                        int sec = calllogitem.TotalCallDurationInSeconds - ((hrs * 3600) + (min * 60));
                        String Name;
                        if (calllogitem.IsCallerIdPrivate)
                        {
                            Name = "Restricted";
                        }
                        else if (calllogitem.IsConference)
                        {
                            Name = "Conference";
                        }
                        else
                        {
                            Name = calllogitem.RemoteParticipants.ElementAt(0).DisplayName;
                        }
                        callLogsList.Items.Add(new
                        {
                            time = date,
                            action = calllogitem.ActionType,
                            name = Name,
                            number = calllogitem.RemoteParticipants.ElementAt(0).RemoteNumber,
                            duration = hrs.ToString("00") + min.ToString(":00") + sec.ToString(":00")

                        });
                    }
                }
            }
        }

        #endregion CallLog Service

        #region Call Feature Service
        private void sendAllCallsBtn_Click(object sender, RoutedEventArgs e)
        {
            CallFeatureManager callFeatureManager = CallFeatureManager.GetInstance();
            callFeatureManager.SendAllCalls();
        }

        #endregion Call Feature Service

        #region Messaging Service
        private void messagingServiceBtn_Click(object sender, RoutedEventArgs e)
        {
            IsAvayaClientSDKGridVisible = false;
            IsConversationListGridVisible = true;
            DisplayConversationList();
        }

        private void conversationListBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsAvayaClientSDKGridVisible = true;
            IsConversationListGridVisible = false;
        }

        private void ConversationView_Click(object sender, RoutedEventArgs e)
        {
            var item = (sender as ListView).SelectedItem;
            if (item != null)
            {
                conversationWithLabel.Content = string.Empty;
                MessagingServiceManager.SelectedConversation = MessagingServiceManager.ConversationList[conversationList.SelectedIndex];
                IsConversationListGridVisible = false;
                IsViewConversationGridVisible = true;
                MessagingServiceManager messagingServiceManager = MessagingServiceManager.GetInstance();
                messagingServiceManager.DisplayConversation();
                MessagingServiceManager.CurrentConversation = MessagingServiceManager.ConversationList[conversationList.SelectedIndex];
                String participantsInConversation = "";
                foreach (Participant participant in MessagingServiceManager.SelectedConversation.Participants)
                {
                    if (participant.Address == SDKManager.UserInstance.MessagingService.SelfAddress)
                    {
                        continue;
                    }
                    participantsInConversation = participantsInConversation + " " + participant.DisplayName;
                }
                conversationWithLabel.Content = "Conversation with " + participantsInConversation;
            }
        }

        private void newChatBtn_Click(object sender, RoutedEventArgs e)
        {
            IsConversationListGridVisible = false;
            IsCreateNewChatGridVisible = true;
        }

        private void createNewChatBtn_Click(object sender, RoutedEventArgs e)
        {
            MessagingServiceManager messagingServiceManager = MessagingServiceManager.GetInstance();
            if (MessagingServiceManager.MessagingServiceInstance != null && MessagingServiceManager.MessagingServiceInstance.CreateConversationCapability.Allowed)
            {
                messagingServiceManager.CreateConversation(addressToChatTxt.Text);
            }
            else
            {
                NotificationHelper.ShowNotification("CreateConversationCapability : Not Allowed");
            }
            messageList.Items.Clear();
        }

        private void createNewChatBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsConversationListGridVisible = true;
            IsCreateNewChatGridVisible = false;
            DisplayConversationList();
        }

        private void sendMessageBtn_Click(object sender, RoutedEventArgs e)
        {
            MessagingServiceManager messagingServiceManager = MessagingServiceManager.GetInstance();
            if (MessagingServiceManager.CurrentConversation.CreateMessageCapability.Allowed)
            {
                messagingServiceManager.CreateAndSendMessage(messageText.Text);
            }
            else
            {
                NotificationHelper.ShowNotification("CreateMessageCapability : Not Allowed");
            }
            messageText.Text = String.Empty;
        }

        private void ViewConversationBackBtn_Click(object sender, RoutedEventArgs e)
        {
            if (MessagingServiceManager.SelectedConversation != null)
            {

                if (MessagingServiceManager.SelectedConversation.MarkAllContentAsReadCapability.Allowed)
                {
                    MessagingServiceManager.SelectedConversation.MarkAllContentAsRead((MessagingFailureEventArgs error) => { });
                }
            }
            DisplayConversationList();
            IsViewConversationGridVisible = false;
            IsConversationListGridVisible = true;
        }

        private void leaveConversationBtn_Click(object sender, RoutedEventArgs e)
        {
            if (MessagingServiceManager.SelectedConversation.LeaveCapability.Allowed)
            {
                MessagingServiceManager.GetInstance().LeaveConversation();
                IsViewConversationGridVisible = false;
                IsConversationListGridVisible = true;
                DisplayConversationList();
            }
            else
            {
                NotificationHelper.ShowNotification("LeaveCapability : Not Allowed");
            }
        }

        private void attachFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog() == true)
            {
                MessagingServiceManager.IsAttachment = true;
                MessagingServiceManager.AttachedFileLocation = openFileDialog.FileName;
                MessagingServiceManager.AttachedFileName = Path.GetFileName(openFileDialog.FileName);
            }
        }

        private void attachmentListBtn_Click(object sender, RoutedEventArgs e)
        {
            IsAttachmentListGridVisible = true;
            IsViewConversationGridVisible = false;
        }

        private void attachmentListBackBtn_Click(object sender, RoutedEventArgs e)
        {
            IsAttachmentListGridVisible = false;
            IsViewConversationGridVisible = true;
        }

        /// <summary>
        /// On attachment click open popup for download attachment option
        /// </summary>
        private void Attachment_Click(object sender, RoutedEventArgs e)
        {
            var item = (sender as ListView).SelectedItem;
            if (item != null)
            {
                try
                {
                    MessagingServiceManager.SelectedAttachment = MessagingServiceManager.SelectedConversationAttachmentList.ElementAt(attachmentList.SelectedIndex);
                    DownloadAttachmentPopup downloadAttachmentPopup = new DownloadAttachmentPopup();
                    downloadAttachmentPopup.Owner = this;
                    downloadAttachmentPopup.ShowDialog();
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    NotificationHelper.ShowNotification("Wait : An attachment is being sent");
                }
            }
        }

        /// <summary>
        /// Display conversation list
        /// </summary>
        public void DisplayConversationList()
        {
            conversationList.Items.Clear();
            if (MessagingServiceManager.ConversationList != null)
            {
                foreach (Conversation conversation in MessagingServiceManager.ConversationList)
                {

                    String participantsInConversation = "";
                    foreach (Participant participant in conversation.Participants)
                    {
                        //Do not add self address in participantsInConversation

                        if (participant.Address == SDKManager.UserInstance.MessagingService.SelfAddress)
                        {
                            continue;
                        }
                        participantsInConversation = participantsInConversation + " " + participant.DisplayName;
                    }
                    participantsInConversation = participantsInConversation + "\n";
                    if (conversation.UnreadMessageCount > 0)
                    {
                        participantsInConversation = participantsInConversation + "[" + conversation.UnreadMessageCount + " unread text]";
                    }
                    if (conversation.UnreadAttachmentCount > 0)
                    {
                        participantsInConversation = participantsInConversation + "[" + conversation.UnreadAttachmentCount + " unread media]";
                    }
                    conversationList.Items.Add(new
                    {
                        participantsInConversation = participantsInConversation
                    });

                }
            }
        }

        /// <summary>
        /// Display selected conversation message list
        /// </summary>
        public void DisplayMessageList()
        {
            messageList.Items.Clear();
            attachmentList.Items.Clear();
            MessagingServiceManager.SelectedConversationAttachmentList.Clear();
            foreach (Message m in MessagingServiceManager.MessageList.Reverse())
            {
                if (m.Body != string.Empty)
                {
                    if (m.IsFromMe)
                    {
                        messageList.Items.Add(new
                        {
                            Message = "Me : " + m.Body
                        });
                    }
                    else
                    {
                        messageList.Items.Add(new
                        {
                            Message = m.FromParticipant.DisplayName + " : " + m.Body
                        });
                    }
                }
                if (m.Attachments.Count > 0)
                {
                    foreach (Attachment attachment in m.Attachments)
                    {
                        if (!attachment.IsThumbnail)
                        {
                            MessagingServiceManager.SelectedConversationAttachmentList.Add(attachment);
                            if (m.IsFromMe)
                            {
                                attachmentList.Items.Add(new
                                {
                                    FileName = "Me" + " : " + attachment.Name,
                                    DownloadStatus = attachment.Status.ToString()
                                });
                            }
                            else
                            {
                                attachmentList.Items.Add(new
                                {
                                    FileName = m.FromParticipant.DisplayName + " : " + attachment.Name,
                                    DownloadStatus = attachment.Status.ToString()
                                });
                            }
                        }
                    }
                }
            }
            MessagingServiceManager.MessageList.Clear();
        }

        /// <summary>
        /// Display single messgae (sent/received)
        /// </summary>
        public void DisplayMessage()
        {
            if (!MessagingServiceManager.NewMessage.IsFromMe)
            {
                if (MessagingServiceManager.NewMessage.Body != string.Empty)
                {
                    messageList.Items.Add(new
                    {
                        Message = MessagingServiceManager.NewMessage.FromParticipant.DisplayName + " : " + MessagingServiceManager.NewMessage.Body
                    });
                }
                if (MessagingServiceManager.NewMessage.Attachments.Count > 0)
                {
                    foreach (Attachment attachment in MessagingServiceManager.NewMessage.Attachments)
                    {
                        if (!attachment.IsThumbnail)
                        {
                            MessagingServiceManager.SelectedConversationAttachmentList.Add(attachment);
                            attachmentList.Items.Add(new
                            {
                                FileName = MessagingServiceManager.NewMessage.FromParticipant.DisplayName + " : " + attachment.Name,
                                DownloadStatus = attachment.Status.ToString()
                            });
                        }
                    }
                }
            }
            else
            {
                if (MessagingServiceManager.NewMessage.Body != string.Empty)
                {
                    messageList.Items.Add(new
                    {
                        Message = Configuration.MessagingServiceUserName + " : " + MessagingServiceManager.NewMessage.Body
                    });
                }
                if (MessagingServiceManager.NewMessage.Attachments.Count > 0)
                {
                    foreach (Attachment attachment in MessagingServiceManager.NewMessage.Attachments)
                    {
                        if (!attachment.IsThumbnail)
                        {
                            attachmentList.Items.Add(new
                            {
                                FileName = Configuration.MessagingServiceUserName + " : " + attachment.Name,
                                DownloadStatus = attachment.Status.ToString()
                            });
                        }
                    }
                }
            }
        }

        #endregion Messaging Service

        /// <summary>
        /// Event occurs when window is closing
        /// </summary>    
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            SDKManager csdkManager = SDKManager.GetInstance();
            if (SDKManager.UserInstance != null)
            {
                csdkManager.RemoveUser(SDKManager.UserInstance);
            }
            csdkManager.UserRegistrationSuccessfulEvent -= HandleUserRegistration;
            csdkManager.UserRegistrationInProgressEvent -= HandleUserRegistrationInProgress;
            csdkManager.UserUnRegistrationSuccessfulEvent -= HandleUserUnRegistration;

            CallManager callManager = CallManager.GetInstance();
            callManager.CallStateChangedEvent -= HandleCallStateChangedEvent;
            callManager.CallStartedEvent -= HandleCallStartedEvent;
            callManager.CallEstablishedEvent -= HandleCallEstablishedEvent;
            callManager.MuteEvent -= HandleMuteEvent;
            callManager.UpdateVideoUIEvent -= HandleUpdateVideoUIEvent;
            callManager.RemoteAddressChangedEvent -= HandleRemoteAddressChangedEvent;
            callManager.ParticipantsChangedEvent -= HandleParticipantsChangedEvent;
            callManager.ConferenceStartedEvent -= HandleConferenceStartedEvent;
            callManager.ConferenceCapabilitiesChangedEvent -= HandleConferenceCapabilitiesChangedEvent;
            CompositionTarget.Rendering -= (LocalVideo.Source as VideoRenderer2).onRendering;
            CompositionTarget.Rendering -= (RemoteVideo.Source as VideoRenderer2).onRendering;
            timer.Tick -= HandleTimerTickEvent;

            CallFeatureManager callFeatureManager = CallFeatureManager.GetInstance();
            callFeatureManager.UpdateSACUIEvent -= HandleUpdateSACUIEvent;

            ContactManager contactManager = ContactManager.GetInstance();
            contactManager.GetContactDoneEvent -= HandleGetContactDoneEvent;

            MessagingServiceManager.MessagingServiceAvailableEvent -= HandleMessagingServiceAvailableEvent;
            MessagingServiceManager.UpdateConversationUIEvent -= HandelUpdateConversationUIEvent;
            MessagingServiceManager.UpdateViewConversationUIEvent -= HandleUpdateViewConversationUIEvent;
            MessagingServiceManager.ViewConversationUIEvent -= HandleViewConversationUIEvent;
            MessagingServiceManager.ParicipantAddedSuccessEvent -= HandleParicipantAddedSuccessEvent;
            MessagingServiceManager.ComposingParticipantsChangedEvent -= HandleComposingParticipantsChangedEvent;
            MessagingServiceManager.StartConversationSuccessEvent -= HandleStartConversationSuccessEvent;

            CollaborationManager collaborationManager = CollaborationManager.GetInstance();
            collaborationManager.UpdateSharingControlUIEvent -= HandleUpdateSharingControlUIEvent;
            CollaborationWindow.CollaborationWindowClosingEvent -= HandleCollaborationWindowClosingEvent;

            if (SDKManager.ClientInstance != null)
            {
                e.Cancel = true;  // wait for client shutdown
                csdkManager.ClientShutdownCompletedEvent -= HandleClientShutdown;
                csdkManager.ClientShutdownCompletedEvent += HandleFinalClientShutdown;
                csdkManager.ShutdownClient();
            }
        }

        /// <summary>
        /// Auto login function - Get stored configuration values
        /// </summary>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if ((Properties.Settings.Default.SipUserName != string.Empty && Properties.Settings.Default.SipPassword != string.Empty) 
                || (Properties.Settings.Default.MessagingServiceUserName != string.Empty && Properties.Settings.Default.MessagingServicePassword != string.Empty) 
                || (Properties.Settings.Default.ACSUserName != string.Empty && Properties.Settings.Default.ACSPassword != string.Empty))
            {
                Configuration.SipServerAddress = Properties.Settings.Default.SipServerAddress;
                Configuration.SipDomain = Properties.Settings.Default.SipDomain;
                Configuration.SipUserName = Properties.Settings.Default.SipUserName;
                Configuration.SipPassword = Properties.Settings.Default.SipPassword;
                Configuration.SipPort = Properties.Settings.Default.SipPort;
                Configuration.IsSecure = Properties.Settings.Default.IsSecure;

                Configuration.MessagingServiceServerAddress = Properties.Settings.Default.MessagingServiceServerAddress;
                Configuration.MessagingServiceServerPort = Properties.Settings.Default.MessagingServiceServerPort;
                Configuration.MessagingServiceUserName = Properties.Settings.Default.MessagingServiceUserName;
                Configuration.MessagingServicePassword = Properties.Settings.Default.MessagingServicePassword;
                Configuration.PollIntervalInMinutes = Properties.Settings.Default.PollIntervalInMinutes;
                Configuration.MessagingServiceServerIsSecure = Properties.Settings.Default.MessagingServiceTLS;

                Configuration.ACSUrl = Properties.Settings.Default.ACSUrl;
                Configuration.ACSPort = Properties.Settings.Default.ACSPort;
                Configuration.ACSIsSecure = Properties.Settings.Default.ACSIsSecure;
                Configuration.ACSUserName = Properties.Settings.Default.ACSUserName;
                Configuration.ACSPassword = Properties.Settings.Default.ACSPassword;

                Configuration.UserAgentInstanceId = Properties.Settings.Default.UserAgentInstanceId;

                StartClient();
            }
            CallManager.GetInstance().localVideo.Clear();
            CallManager.GetInstance().remoteVideo.Clear();
            CompositionTarget.Rendering += (LocalVideo.Source as VideoRenderer2).onRendering;
            CompositionTarget.Rendering += (RemoteVideo.Source as VideoRenderer2).onRendering;
            CallManager.GetInstance().AddLocalVideoRenderer(LocalVideo.Source as VideoRenderer2);
            CallManager.GetInstance().AddRemoteVideoRenderer(RemoteVideo.Source as VideoRenderer2);
        }
    }
}
