crmApp.controller("ActivityController", ActivityController);

function ActivityController($scope, $window, ActivitySI, TaxPayerSI, TaxPayerService, $mdDialog, CaseSI, $q,
    DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $filter, $compile,
    QRCodeSI, AntiForgeryService, Upload, GeneralService, MenuBarService, $timeout, TaskSI,
    localStorageService, ActivitySessionService, OutboundService, $sce, UserSI, $http, OutboundSI) {

    var vm = this;
    var TabID = "01";
    var TabType = "Profile";
    var skillsetURL = "";
    vm.IsUnitChoose = true;
    vm.showdetail = false;

    //used to identify <textarea> elements to be replaced by CKEditor instance
    editor = CKEDITOR.replace('TextArea_EmailContent',
        {
            //customConfig:'custom/ckeditor_activity_config.js'  
            extraPlugins: 'emailtemplates,font,colorbutton',//,signaturetemplates
            //on: {
            //    pluginsLoaded: function () {
            //        //var editor = this;
            //        //editor.ui.addToolbarGroup('emailtemplates', 'colors', ['others']);

            //    } 
            //}
            on: {
                pluginsLoaded: function () {
                    var editor = this;
                    editor.addCommand("onClickPreview", {
                        exec: function (edt) {
                            $('#btnEmailPreview').click();
                        }
                    });

                    editor.ui.addButton('Preview2', {
                        label: "Preview",
                        command: 'onClickPreview',
                        toolbar: 'others',
                        hidpi: true,
                        icon: 'custom/icons/preview/preview-rtl.png'
                    });
                },
                instanceReady: function (evt) {
                    //var editor = this;
                    //editor.ui.addToolbarGroup('emailtemplates', 'colors', ['others']);
                    $(".cke_combo__emailtemplatesa").closest(".cke_toolbar").addClass("pull-right");//.addClass("pull-right"); //.css({ "float": "right" });
                    $(".cke_combo__emailtemplatesb").closest(".cke_toolbar").addClass("pull-right");// //.css({ "float": "right" });
                    //$(".cke_combo__signaturetemplates").closest(".cke_toolbar").addClass("pull-right"); //.css({ "float": "right" });

                    $(".cke_top").append('<span class="cke_toolbar_break"></span><span class="cke_toolbar pull-right textRed" style="color:#EF5049!important;font-size:0.9em;font-family:Poppins, sans-serif;">*Note: [[Bookmarks]] in the templates will be replaced with data when sending email</span>');
                    //$(".cke_combo__signaturetemplates").closest(".cke_toolbar").css({ "float": "right" });

                }
            }
        }
    );

    /**From $window **/
    vm.activityid = $window.activityid;
    var userInfo = $scope.UserInfo;
    /*From add activity button*/
    vm.SessionKey = $window.sessionkey == '' ? null : $window.sessionkey;
    var tpID = $window.tpid; // From TP profile 
    var caseID = $window.caseid; // From Case Profile
    var tpName = $window.tpname; //From orphan TP in CASE or Activty 
    var idType = $window.idtype;
    var outBoundID = $window.outboundid;
    var reMSDataID = $window.reMSDataID;
    var jenisKempenID = $window.jenisKempenID;
    var prevActivityID = $window.prevactivityid;
    var isReplyToTPCFF = $window.isreplytotpcff == '' ? false : ($window.isreplytotpcff.toUpperCase() == 'TRUE' ? true : false);
    var isResendEmail = $window.isresendemail == '' ? false : ($window.isresendemail.toUpperCase() == 'TRUE' ? true : false);
    var isFrCRM = $window.isFrCRM == '' ? false : ($window.isFrCRM.toUpperCase() == 'TRUE' ? true : false);
    var kategori1ID = $window.kategori1id;
    var kategori2ID = $window.kategori2id;
    var kategori3ID = $window.kategori3id;

    /*From Screen Pop*/
    var idNo = decodeEntities($window.idno);
    var idTypeCode = $window.idtypecode;
    var cukaiNo = $window.cukaiNo;
    var fbTwDisplayName = decodeEntities($window.fbtwdisplayname);
    var telNo = decodeEntities($window.telno);
    var callAttempts = $window.callattempts == '' ? null : $window.callattempts;
    var actChannelID = $window.actchannelid; // this is from screen pop/ email 
    var aliranCode = $window.aliranCode; //Aliran Code
    vm.IsInboundMissCall = $window.isinboundmisscall.toUpperCase() == 'TRUE' ? true : false;
    var languageCode = $window.languagecode;
    var skillSet = decodeEntities($window.skillset);
    var isOrphanTP = $window.IsOrphanTP;

    //test chew
    //vm.Isdelete = false;

    vm.outlookSubject = $window.outlooksubject;
    vm.outlookSender = $window.outlooksender;
    vm.outlookTo = $window.outlookto;
    vm.outlookCC = $window.outlookcc;
    vm.outlookContent = $window.outlookcontent;
    vm.outlookReceivedDate = $window.outlookreceiveddate;
    vm.interactionId = $window.interactionId;
    vm.isselfselectoutbound = $window.isselfselectoutbound;
    vm.CCCampaignName = $window.cccampaignName;
    var email = $window.email;


    var idTypeDesc = $window.idTypeDesc;
    var uuid = $window.uuid;
    /**From $window End **/

    /**Initialise**/
    vm.IsSearchPelanggan = false;
    vm.IsActivityClose = false;//Indicate if activity is closed in db
    vm.IsPelangganNamaCukaiDisable = true;
    vm.IsChannelDDLDisable = false;
    vm.IsAliranRBDisable = false;
    vm.IsJenisKempenDDLDisable = false;
    vm.hdrTempl = 'loading';
    vm.TPID = 0;
    vm.case = {};
    //vm.SelectedAliran = "";
    vm.lstCase = [];
    vm.VeriFailedCount = 0;
    vm.VeriPassCount = 0;
    vm.VeriCountMessage = "0 Butiran disemak";
    vm.IsShowVerificationTab = false;
    vm.IsShowPenerimaanDocTab = false;
    vm.ChangesHistory = [];
    vm.SearchTP = {};
    //vm.ActVerificationEjens = [];
    //vm.ActShareholderVerification = [];
    //vm.ActSpouseVerification = [];
    //vm.ShowSearchTP = true;
    TaxPayerService.PopupID = "#searchModal";
    vm.dtInstanceOpenCase = {};
    vm.dtInstanceOutbound = {};
    vm.tempEmail = {}; //Store Email and CFF email
    vm.isEditTPData = false;
    vm.isEditAnsuranActData = false;
    vm.DefaultManager = [];

    var initEvent;
    var isFirstLoad = true;
    var isFirstLoadOutbound = true;
    var isNewActFirstLoad = false;
    var isEmptyOpenCase = false;
    var constClosedActStatusID = 0;
    var constOpenActStatusID = 0;
    var constNoReplyEmail = '';
    var isDDLOptionsLoaded = false;
    var isEmailTmplatesLoaded = false;
    var tempTP = null;
    var tempPelanggan = null;
    var isHasLinkCaseAction = false;
    var defaultLanguageID = null;
    var blnIsSaveDraft = false;
    var blnIsPelangganSearched = true;
    var blnIsTPSearched = true;
    /**Initialise End **/

    /***Constants*/
    var constSumberReMS = 9;
    var constSumberTelefon = 8;
    var constSumberKaunter = 5;
    var constSumberFB = 11;
    var constSumberTW = 12;
    var constSumberEmelPC = 3;
    var constSumberChat = 1;
    //Ref_CCIDType
    var constFBIDTypeCode = '6';
    var constTWIDTypeCode = '7';
    var constCukaiTypeCode = '8';
    var constStatus2Normal = 6;
    var constNoReplyEmailID = 5;
    var constAttachmentSizeID = 14;
    var constAttachmentAcceptedFileTypeID = 15;
    var constDummyProfileName = 19;
    var constDummyProfileIDTypeID = 20;
    var constDummyProfileIDNumber = 21;
    var constBelumSelesaiLookUpValue = '2';
    var constSelesaiLookUpValue = '1';
    var constTranskripPerbualanID = 13;
    var constIDTypeNRIC = {};
    var constOutboundKategoriID = 8;
    var constAssignToTypeUnit = 20;
    var constAssignToTypeUser = 21;
    var constBelumSelesai = 'belum selesai';
    var constOutboundStatusInQueue = 30;

    vm.constActChannelChat = 1;
    vm.constActChannelEmail = 2;
    vm.constActChannelKaunter = 3;
    vm.constActChannelLetter = 4;
    vm.constActChannelPhone = 5;
    vm.constActChannelSMS = 6;
    vm.constActChannelSocialMedia = 7;
    vm.constActChannelCFF = 8;
    vm.constAliranIN = 'IN';
    vm.constAliranOUT = 'OUT';
    vm.constMaklumatAnsuran = 23;
    vm.constMaklumatTunggakan = 24;
    vm.constMaklumatCTL = 25;


    /***Constants End */


    vm.SeksyenEnabledDocUnit = true;
    vm.JabatanEnabledDocUnit = true;
    $scope.number = 0;

    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;

    /*On page load functions */
    vm.init = function (e) {
        //query string to track which tab to be in
        var querystring = location.search;
        if (querystring) {
            //TabID = querystring.substring(querystring.indexOf("=") + 1, querystring.indexOf("&"));
            //TabType = querystring.substring(querystring.lastIndexOf("=") + 1, querystring.length);
            TabID = $.urlParam('t') || "01";
            TabType = $.urlParam('ty') || "Profile";
            skillsetURL = decodeEntities($.urlParam('ss'));
        }


        tabAction(TabID, TabType);


        // datepicker
        //Change history
        vm.dateFromMinDate = null;
        vm.dateFromMaxDate = null;
        vm.buttonBarObj = $scope.ButtonBar;
        vm.dateFromOptions = {
            minDate: null, // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            dateDisabled: false,
            startingDay: 1
        };

        vm.dateToMinDate = null;
        vm.dateToMaxDate = null;
        vm.dateToOptions = {
            minDate: null, // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            dateDisabled: false,
            startingDay: 1,
            closed: function (args) {
                vm.closedArgs = args;
                alert('datepicker closed');
            }
        };
        // END Change History

        // Letter received date        
        vm.letterReceivedDateOptions = {
            minDate: null, // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            startingDay: 1
        };

        // Email received date        
        vm.emailReceivedDateOptions = {
            minDate: null, // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            startingDay: 1
        };

        // Promised to pay date        
        vm.ptpDateOptions = {
            minDate: (new Date()).setHours(0, 0, 0, 0), // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            startingDay: 1
        };

        // Nota temuduga tarikh terima      
        vm.NTTarikhTerimaOptions = {
            minDate: null, // Use this property to enable a min selected date
            maxDate: null, // Use this property to enable a max selected date
            showWeeks: $scope.ShowWeeks,
            startingDay: 1
        };

        initEvent = e;
        isOrphanTP = (isOrphanTP != undefined && isOrphanTP != null) ? (isOrphanTP.toLowerCase() == 'true') : false;
        if ($window.opener && isFrCRM) {
            sessionStorage.removeItem('draftID');
        }
        //If Screen Pop saved as draft, and user refresh page , get back the saved draftID to load
        if (!vm.activityid && sessionStorage.draftID && parseInt(JSON.parse(sessionStorage.draftID)) > 0) {
            vm.activityid = parseInt(JSON.parse(sessionStorage.draftID)); 
        }
        ActivitySessionService.bind($scope);

        if (vm.activityid > 0) {
            // Load Activity data
            ActivitySI.getActivity(vm.activityid).then(function (r) {
                if (r.status === 200) {
                    //$scope.activity = r.data;
                    vm.activity = r.data;

                    //test chew
                    vm.IsDelete = r.data.IsDelete;

                    if (skillsetURL)//skillset
                    {
                        vm.activity.Skillset = skillsetURL;
                    }

                    formatDatePickerDates();

                    bindActivityData(); //bind Outbound here as well
                    if (vm.activity.TP != null && vm.activity.TP != undefined)
                        vm.ViewVerificationTab = vm.activity.TP.ViewVerificationTab;
                    else
                        vm.ViewVerificationTab = true;

                    var objTP = {
                        TPID: vm.activity.TP ? vm.activity.TP.TPID : 0,
                        TPName: vm.activity.TP ? vm.activity.TP.TPName : vm.activity.TPName,
                        TPJenisPengenalan: vm.activity.TP ? vm.activity.TP.JenisPengenalan : vm.activity.TPJenisPengenalan,
                        TPIDNumber: vm.activity.TP ? vm.activity.TP.IdentityNo : vm.activity.TPIDNumber,
                        TPNoCukai: vm.activity.TP ? vm.activity.TP.NoCukaiCode + ' ' + vm.activity.TP.NoCukai : vm.activity.TPNoCukai
                    };

                    bindHeader(objTP, vm.activity.TP);

                    //Show Profile Header
                    vm.hdrTempl = 'tp.profile.header';

                    //Kategori Dokumen
                    if (vm.activity.KategoriDocReceived) {
                        for (i = 0; i < vm.activity.KategoriDocReceived.length; i++) {
                            for (j = 0; j < vm.activity.KategoriDocReceived[i].ActDocReceived.length; j++) {
                                if (!vm.activity.KategoriDocReceived[i].ActDocReceived[j].Checked)
                                    vm.activity.KategoriDocReceived[i].ActDocReceived[j].Copy = null;
                            }
                        }
                    }
                     

                    bindActProfileOnSuccess();

                    if (!vm.activity.IsDraft && vm.activity.TPID)
                        getOutboundCount();

                    $timeout(delayedSetEditorReadOnly, 50); //rely on isActivityClose

                    if (vm.activity.ActWorkflow != null) {
                        vm.AssignBy = vm.activity.ActWorkflow.AssignByName;
                        vm.AssignTo = vm.activity.ActWorkflow.AssignTo;
                        vm.UserType = vm.activity.ActWorkflow.AssignToTypeID;
                        vm.WorkFlowId = vm.activity.ActWorkflow.WorkflowID;

                        vm.HideCreatedBy = false;
                        if (vm.activity.ActWorkflow.IsCurrentLogin) {   //AssignToLogin Match
                            if (vm.activity.ActWorkflow.AssignToLogin.toLowerCase() == vm.activity.ActWorkflow.AssignBy.toLowerCase()) {
                                vm.IsRecall = false;
                                vm.IsReturn = false;
                                vm.IsAssign = true;
                                vm.IsOtherLogin = false;
                                vm.HideCreatedBy = true;
                            }
                            else {
                                vm.IsRecall = false;
                                vm.IsReturn = true;
                                vm.IsAssign = true;
                                vm.IsOtherLogin = false;
                            }

                        }
                        else {
                            if (vm.activity.ActWorkflow.IsOtherLogin) {   //Other than AssignTo and Assign By
                                vm.IsRecall = false;
                                vm.IsReturn = false;
                                vm.IsAssign = false;
                                vm.IsOtherLogin = true;
                            }
                            else {
                                vm.IsRecall = true;        //AssignBy
                                vm.IsReturn = false;
                                vm.IsAssign = false;
                                vm.IsOtherLogin = false;
                            }

                        }

                        // if Assign To People didnot have manager
                        if (vm.activity.ActWorkflow.AssignToTypeID == 0) {
                            vm.AssignOther = true;
                            vm.Other = constAssignToTypeUser;
                        }
                        else  //If Assign To People have manager ,Disable for it.
                        {
                            vm.AssignToDisable = true;
                        }
                    }
                    else {
                        vm.HideCreatedBy = true;
                        vm.IsRecall = false;
                        vm.IsReturn = false;
                        vm.IsAssign = true;
                        vm.IsOtherLogin = false;
                        vm.TP = r.data.TP ? r.data.TP.TPID : null;

                        //By Unit
                        var Kategory = {
                            Kategori1: vm.activity.Kategori1ID,
                            Kategori2: vm.activity.Kategori2ID,
                            Kategori3: vm.activity.Kategori3ID,
                            AssignToType: constAssignToTypeUnit,
                            TPID: vm.activity.TP ? vm.activity.TP.TPID : null
                        }

                        ActivitySI.getActWorkFlowAssignToByKategoryId(Kategory).then(function (s) {
                            if (s.data.ID != null && s.data.ID > 0) {
                                vm.Users = [s.data];
                                vm.AssignTo = vm.Users[0];
                                vm.UserType = constAssignToTypeUnit;
                                vm.AssignToDisable = true;
                            }
                            else {

                                //By Manager
                                var data = {
                                    keyword: "",
                                    AssignToType: constAssignToTypeUser
                                }

                                if (vm.DefaultManager != null && vm.DefaultManager.length > 0) {
                                    vm.Users = vm.DefaultManager;
                                    vm.AssignTo = vm.DefaultManager;

                                    vm.UserType = constAssignToTypeUser;
                                    vm.AssignToDisable = true;
                                    vm.AssignOther = false;
                                    vm.showdetail = false;
                                }
                                else {
                                    vm.AssignTo = null;
                                    vm.UserType = 0;
                                    vm.AssignToDisable = false;
                                    vm.AssignOther = true;
                                }

                                //ActivitySI.getActWorkFlowSearchUserOrUnit(data).then(function (u) {
                                //    if (u.data.length > 0 && u.data[0].ID != null) {
                                //        var m = u.data;
                                //        if (m.length != 0) {
                                //            vm.Users = m;
                                //            vm.AssignTo = vm.Users[0];
                                //            vm.AssignTo.DisplayName = vm.Users[0].DisplayName;
                                //            vm.UserType = constAssignToTypeUser;
                                //            vm.AssignToDisable = true;
                                //        }
                                //    }
                                //    else {
                                //        vm.AssignTo = null;
                                //        vm.UserType = 0;
                                //        vm.AssignToDisable = false;
                                //        vm.AssignOther = true;
                                //    }
                                //});
                            }
                        });
                    }
                    if (vm.activity.NotaTemuduga != null && vm.activity.NotaTemuduga.QRCode != null)
                        addQRCodeGeneratedCSS();
                }
            });

            //TODO don't call if isDraft?
            getTaskList();

            //TODO don't call if isDraft
            getChangeHistory();

            //getSaveSession(); 
            vm.SessionKey = ActivitySessionService.getActSessionKey(vm.activityid);
           
        }
        else { //New Activity 

            var model = {
                TPID: tpID,
                CaseID: caseID,
                OutboundID: outBoundID,
                ReMSDataID: reMSDataID,
                JenisKempenID: jenisKempenID,
                IDType: idType,
                IDTypeCode: idTypeCode,
                IDNo: idNo,
                NoCukai: idTypeCode == constCukaiTypeCode ? idNo : cukaiNo,
                FBID: idTypeCode == constFBIDTypeCode ? idNo : null,
                TWID: idTypeCode == constTWIDTypeCode ? idNo : null,
                TPName: tpName,
                PrevActivityID: prevActivityID,
                IsReplyToTPCFF: isReplyToTPCFF,
                IsResendEmail: isResendEmail,
                IsOrphanTP: isOrphanTP
            };
            ActivitySI.getNewActivity(model).then(function (r) {
                vm.activity = r.data;

                //vm.outbound = angular.copy(vm.activity.Outbound);
                //vm.activity.ActVerification = {};
                if (vm.activity.TP != null && vm.activity.TP != undefined) {
                    vm.ViewVerificationTab = vm.activity.TP.ViewVerificationTab;
                    vm.SearchTProfileAccess = vm.activity.TP.SearchTPProfile;
                }
                else
                    vm.ViewVerificationTab = true;

                vm.tempEmail = {};
                vm.tempEmail.EmailReceivedDate = new Date();//$filter('date')(new Date(), $scope.DateFormat);
                vm.activity.LetterFaxReceived = new Date();//$filter('date')(new Date(), $scope.DateFormat);
                /**********init with screen pop up************/

                //If idTypeCode has value , means it is screen pop 
                //vm.isSaveToDraft = idTypeCode && !vm.IsInboundMissCall ? true : false; //TODO temp
                vm.activity.IsDraft = !isFrCRM && !vm.IsInboundMissCall ? true : false;

                if (telNo)
                    vm.activity.TelefonInteraksi = telNo;

				// Chew 2020-09-28 to avoid inbound phone have email interaksi
				if (email && actChannelID != vm.constActChannelPhone)
					vm.activity.EmailInteraksi = email;
					//TODO : ADD FOR OUTLOOK EMAIL
				
                if (callAttempts > 0)
                    vm.activity.CallAttempts = callAttempts;

                if (skillSet)
                    vm.activity.Skillset = skillSet;

                if (idTypeCode == constFBIDTypeCode) {
                    vm.activity.TPFBDisplayName = fbTwDisplayName;
                    vm.activity.TPFBID = idNo;
                    vm.activity.SocialMediaInteraksiID = idNo;
                    vm.activity.SocialMediaInteraksiName = fbTwDisplayName;
                    vm.isEditTPData = true;
                }

                if (idTypeCode == constTWIDTypeCode) {
                    vm.activity.TPTWDisplayName = fbTwDisplayName;
                    vm.activity.TPTWID = idNo;
                    vm.activity.SocialMediaInteraksiID = idNo;
                    vm.activity.SocialMediaInteraksiName = fbTwDisplayName;
                    vm.isEditTPData = true;
                }

                //init with convert to activity additional kategori's data
                if (kategori1ID > 0) {
                    vm.activity.Kategori1ID = kategori1ID;
                    if (kategori2ID > 0) {
                        vm.activity.Kategori2ID = kategori2ID;
                        if (kategori3ID > 0) {
                            vm.activity.Kategori3ID = kategori3ID;
                        }
                    }
                }

                if (actChannelID > 0) {
                    vm.activity.ActChannelID = actChannelID;
                    //If ActChannel exists , disable field  
                } 

                vm.activity.InteractionID = vm.interactionId || null;
                vm.activity.UUID = uuid;
                 
                /*******init with screen pop up END **********/

                //init from Case Profile reply_to_TP button 
                if (isReplyToTPCFF && vm.activity.ActCFF) {
                    if (vm.activity.ActCFF.To)
                        vm.activity.EmailInteraksi = vm.activity.ActCFF.To.trim();
                }

                bindActivityData();

                bindActProfileOnSuccess();

                $timeout(delayedSetEditorReadOnly, 50); 
                //Show Profile Header
                vm.hdrTempl = 'tp.profile.header';
            });

        }

        //Init Open Case Dtbl
        displayOpenCaseDataTable();

        displayOutboundDataTable();

        angular.element($window).on('beforeunload', onbeforeunload);
        angular.element($window).on('unload', onUnload);
    }

    $.urlParam = function (name) {
        var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
        if (results == null) {
            return null;
        }
        else {
            return decodeURI(results[1]) || 0;
        }
    }
    function setIsTPPelangganSearched() {

        vm.IsNotFromSearchTP = !blnIsTPSearched;
        if (vm.activity.TPIDNumber)
            $scope.makAmForm["TPIDNumber"].$setValidity("isSearched", blnIsTPSearched);

        if (vm.activity.TPIDType)
            $scope.makAmForm["TPJenisPengenalan"].$setValidity("isSearched", blnIsTPSearched);

        if (vm.activity.PelangganIDNumber)
            $scope.makAmForm["PelangganIDNumber"].$setValidity("isSearched", blnIsPelangganSearched);

        if (vm.activity.PelangganIDType)
            $scope.makAmForm["PelangganJenisPengenalan"].$setValidity("isSearched", blnIsPelangganSearched);
    }

    getDDLOptions().then(function (data) {

        for (var key in data) {
            vm[key] = data[key];
        }

        vm.WorkflowAssignToSeksyenOptionDocUnit = data["WorkflowAssignToSeksyenOption"];
        vm.WorkflowAssignToJabatanOptionDocUnit = data["WorkflowAssignToJabatanOption"];
        vm.WorkflowAssignToCawanganOptionDocUnit = data["WorkflowAssignToCawanganOption"];
        vm.WorkflowAssignToUnitOptionDocUnit = data["WorkflowAssignToUnitOption"];
         
        isDDLOptionsLoaded = true;
        bindActProfileOnSuccess();
    });

    //getSessionKeyByAID();
    /*On page load functions END */

    function getChangeHistory() {
        var ajaxCallbackCH = function (data, callback, settings) {

            data.ActivityID = vm.activityid;
            data.FieldName = vm.FieldName;
            data.DateFrom = vm.DateFrom == undefined ? null : $filter('date')(vm.DateFrom, $scope.DateTimeFormat);
            data.DateTo = vm.DateTo == undefined ? null : $filter('date')(vm.DateTo, $scope.DateTimeFormat);
            data.LastUpdatedBy = vm.LastUpdatedBy;


            TaxPayerSI.getPagedChangeHistory(data).then(function (r) {
                if (r.status == 200) {
                    if (r.data.data) {
                        for (i = 0; i < r.data.data.length; i++) {
                            if (r.data.data[i].OldValue)
                                r.data.data[i].OldValue = r.data.data[i].OldValue.replace(/\n/g, '<br/>');
                            if (r.data.data[i].NewValue)
                                r.data.data[i].NewValue = r.data.data[i].NewValue.replace(/\n/g, '<br/>');
                        }
                    }
                    callback(r.data); 
                }
            });
        }


        //Bind table - start 
        vm.dtColumnsActChangesHistory = [
            //DTColumnBuilder.newColumn('ID').withTitle('ID'),
            DTColumnBuilder.newColumn('FieldName').withTitle('Nama Medan').withOption('width', '16%'),
            DTColumnBuilder.newColumn('OldValue').withTitle('Maklumat Asal').withOption('width', '27%'),
            DTColumnBuilder.newColumn('NewValue').withTitle('Maklumat Dipinda').withOption('width', '27%'),
            DTColumnBuilder.newColumn('CreatedByName').withTitle('Dikemaskini Oleh').withOption('width', '15%'),
            DTColumnBuilder.newColumn('CreatedDateTime').withTitle('Tarikh Dikemaskini').withOption('width', '15%').renderWith(function (data, type) {
                return $filter('date')(data, $scope.DateTimeFormat);
            }),

        ];

        vm.dtOptionsActChangesHistory = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallbackCH)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('searching', true)
            .withOption('serverSide', true)
            .withOption('autoWidth', false)
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
        //Bind Table - end
    }

    function getDDLOptions() {
        var deferred = $q.defer();
        ActivitySI.getActivityDDLOptions().then(function (r) {
            if (r.status === 200) {
                deferred.resolve(r.data);
            }
        });
        return deferred.promise;
    }


    //function GetUserGroupHierarcyOptions() {

    //    UserSI.getUserGroupHierarcyOptions().then(function (r) {
    //        if (r.status === 200) {
    //            if (r.data) {
    //                vm.WorkflowAssignToSeksyenOption = r.data["WorkflowAssignToSeksyenOption"];
    //                vm.WorkflowAssignToJabatanOption = r.data["WorkflowAssignToJabatanOption"];
    //                vm.WorkflowAssignToCawanganOption = r.data["WorkflowAssignToCawanganOption"];
    //                vm.WorkflowAssignToUnitOption = r.data["WorkflowAssignToUnitOption"];
    //            }
    //        }
    //    });


    //}


    function GetDefaultManager() {
        UserSI.getDefaultManager().then(function (r) {
            if (r.status === 200) {
                if (r.data) {
                    vm.DefaultManager = r.data;
                }
            }
        });
    }

    function SearchUserByUnitID(selectedUnitID) {
        vm.NoUserMessage = false;
        vm.UserResultOption = [];
        vm.AssignTo = "";
        UserSI.searchUserByUnitID(selectedUnitID).then(function (r) {
            if (r.status === 200) {
                if (r.data) {
                    vm.UserResultOption = r.data;


                    if (vm.UserResultOption.length == 0) {
                        vm.NoUserMessage = true;
                    }

                }
            }
        });


    }

    function decodeEntities(encodedString) {
        var textArea = document.createElement('textarea');
        textArea.innerHTML = encodedString;
        return textArea.value;
    }


    function bindActProfileOnSuccess() {
        if (isDDLOptionsLoaded && vm.activity) { 
             
            //**Bind Constants**//
            var m = $filter('filter')(vm.ActStatusOptions, { Code: constSelesaiLookUpValue }, true);
            if (m && (m.length > 0)) {
                constClosedActStatusID = m[0].Value;
            }

            m = $filter('filter')(vm.ActStatusOptions, { Code: constBelumSelesaiLookUpValue }, true);
            if (m && (m.length > 0)) {
                constOpenActStatusID = m[0].Value;
            }

            //ParameterSettings : No-Reply Email value for CFF and Email OUTBOUND From field
            m = $filter('filter')(vm.ParameterSettings, { ParameterID: constNoReplyEmailID }, true);
            if (m && (m.length != 0)) {
                constNoReplyEmail = m[0].ParameterValue;
            }

            // ParameterSettings : Transkrip Perbualan URL
            m = $filter('filter')(vm.ParameterSettings, { ParameterID: constTranskripPerbualanID }, true);
            if (m && (m.length != 0)) {
                vm.activity.TranskripPerbualanURL = m[0].ParameterValue;
            }


            m = $filter('filter')(vm.ParameterSettings, { ParameterID: constAttachmentSizeID }, true);
            if (m && (m.length != 0)) {
                vm.constAttachmentSize = m[0].ParameterValue;
            }
            m = $filter('filter')(vm.ParameterSettings, { ParameterID: constAttachmentAcceptedFileTypeID }, true);
            if (m && (m.length != 0)) {
                vm.constAcceptedFileType = m[0].ParameterValue;
            }

            m = $filter('filter')(vm.ParameterSettings, { ParameterID: constDummyProfileName }, true);
            if (m && (m.length != 0)) {
                vm.constDummyTPName = m[0].ParameterValue;
            }
            m = $filter('filter')(vm.ParameterSettings, { ParameterID: constDummyProfileIDTypeID }, true);
            if (m && (m.length != 0)) {
                vm.constDummyTPIDType = m[0].ParameterValue;
            }
            m = $filter('filter')(vm.ParameterSettings, { ParameterID: constDummyProfileIDNumber }, true);
            if (m && (m.length != 0)) {
                vm.constDummyTPIDNumber = m[0].ParameterValue;
            }
            //**Bind Constants End**//

            //Mandatory fields start 
            //**init with screen pop up after get ddloptions**/// 
            if (languageCode) {
                var m = $filter('filter')(vm.LanguageOptions, { Code: languageCode }, true);
                if (m && (m.length > 0)) {
                    vm.activity.LanguageID = m[0].Value;
                }
            }

            //init with screen pop up after get ddloptions
            if (aliranCode) {
                var m = $filter('filter')(vm.AliranOptions, { Code: aliranCode.toUpperCase() }, true);
                if (m && (m.length != 0)) {
                    vm.activity.AliranID = m[0].Value;
                }
            }

            //populate outlook content
            if (vm.outlookContent) {
                vm.activity.ActChannelID = vm.constActChannelEmail;
                vm.activity.SumberID = constSumberEmelPC;

                var m = $filter('filter')(vm.AliranOptions, { Code: vm.constAliranIN.toUpperCase() }, true);
                if (m && (m.length != 0)) {
                    vm.SelectedAliran = m[0].Code;
                    vm.activity.AliranID = m[0].Value;
                }

                if (vm.tempEmail == null) {
                    vm.tempEmail = {};
                }

                vm.tempEmail.To = vm.outlookTo;
                vm.tempEmail.CC = vm.outlookCC;
                vm.tempEmail.EmailSubject = decodeEntities(vm.outlookSubject);
                vm.tempEmail.From = vm.outlookSender;
                vm.tempEmail.EmailReceivedDate = new Date(vm.outlookReceivedDate);
                vm.outlookContent = vm.outlookContent ? vm.outlookContent.replace(/�/g, "") : vm.outlookContent

                editor.setData(decodeEntities(vm.outlookContent));
            }

            if (vm.activity.ActCFF != null)
                vm.CFFMainKategoriChanged(vm.activity.ActCFF.CFFMainKategori);

            
            //**Mandatory fields end**//

            //Save Draft before actChannelChange, channel and aliran defaults
            if (vm.activity.IsDraft && !vm.activity.ActivityID)
                UpdateActivity(1);




            //**** Set conditional defaults and disable fields ****//
            vm.outbound && (vm.IsJenisKempenDDLDisable = true);
            vm.outbound && !vm.activity.Kategori1ID && (vm.activity.Kategori1ID = constOutboundKategoriID); //Soft default to outbound if no kategoriID

            //Set soft defaults channel and aliran for new outbound activity 
            //disable channel and aliran 
            //if saved from db or from screen pop, disable channel select 
            if ((vm.activity.ActChannelID && vm.activity.ActivityID) || actChannelID) {
                //if (!(vm.outbound && (!vm.activity.ActivityID || vm.activity.IsDraft)))
                vm.IsChannelDDLDisable = true;
            }
            else if (!vm.activity.ActChannelID) {
                if (vm.outbound) { //default to phone for new outbound when none 
                    vm.activity.ActChannelID = vm.constActChannelPhone;
                }
                else {
                    var intUserDefaultCnannelID = 0;
                    var strUsrRoles = "";
                    for (var i = 0; i < userInfo.RoleGroups.length; i++) {
                        if (i == 0) {
                            strUsrRoles = strUsrRoles + userInfo.RoleGroups[i].FunctionalRoleID;
                        }
                        else {
                            strUsrRoles = strUsrRoles + "|" + userInfo.RoleGroups[i].FunctionalRoleID;
                        }
                    }
                    if (strUsrRoles != "") {
                        for (i = vm.ActChannelOptions.length - 1; i >= 0; i--) {
                            if (vm.ActChannelOptions[i].DefaultRoles) {
                                var regex = new RegExp("(\\D|\\b|\\s)(" + strUsrRoles + ")(\\D|\\b|\\s)");
                              
                                if (regex.test(vm.ActChannelOptions[i].DefaultRoles)) {
                                    intUserDefaultCnannelID = vm.ActChannelOptions[i].ActChannelID;
                                }
                            }
                        }
                    }

                    vm.activity.ActChannelID = intUserDefaultCnannelID == 0 ? vm.constActChannelPhone : intUserDefaultCnannelID;

                }
            }


            if ((vm.activity.AliranID && vm.activity.ActivityID) || aliranCode) {
                vm.IsAliranRBDisable = true;
            }
            else if (!vm.activity.AliranID) {
                if (vm.outbound) {
                    m = $filter('filter')(vm.AliranOptions, { Code: vm.constAliranOUT }, true);
                    if (m && (m.length > 0)) {
                        vm.activity.AliranID = m[0].Value;
                    }
                }
            }
            //**** END Set conditional defaults and disable fields ****//


            //****Set Defaults from System here if they have not been populated by now****//

            if (!vm.activity.ActivityID || vm.activity.IsDraft) {
                if (!vm.activity.LanguageID) {
                    var m = $filter('filter')(vm.LanguageOptions, { IsDefault: true }, true);
                    if (m && (m.length > 0)) {
                        defaultLanguageID = m[0].Value; //Assign to temp variable as may populate from TP profile
                    }
                }

                //m = $filter('filter')(vm.JenisPengenalanOptions, { IsDefault: true }, true);
                //if (m && (m.length > 0)) {
                //    constIDTypeNRIC = m[0];
                //    vm.SearchTP.IDType = constIDTypeNRIC;
                //}

                if (!vm.activity.AliranID) {
                    m = $filter('filter')(vm.AliranOptions, { IsDefault: true }, true);
                    if (m && (m.length > 0)) {
                        vm.activity.AliranID = m[0].Value;
                    }
                }

                if (!vm.activity.JenisPelangganID) {
                    m = $filter('filter')(vm.JenisPelangganOptions, { IsDefault: true }, true);
                    if (m && (m.length > 0)) {
                        vm.activity.JenisPelangganID = m[0].Value;
                    }
                }

                if (!vm.activity.PelangganLokasiID) {
                    m = $filter('filter')(vm.LokasiOptions, { IsDefault: true }, true);
                    if (m && (m.length > 0)) {
                        vm.activity.PelangganLokasiID = m[0].Value;
                    }
                }

                if (!vm.activity.ActStatus1ID) {
                    var m = $filter('filter')(vm.ActStatusOptions, { IsDefault: true }, true);
                    if (m && (m.length > 0)) {
                        vm.activity.ActStatusID = m[0].Value;

                        if (parseInt(m[0].Code)) {
                            vm.activity.ActStatus1ID = parseInt(m[0].Code);
                            vm.activity.ActStatus2ID = constStatus2Normal;
                        }
                    }
                }
            }


            var m = $filter('filter')(vm.WorkflowAssignToTypeOption, { IsDefault: true }, true);
            if (m && (m.length > 0)) {
                vm.Other = m[0].Value;
            }

             
            //****END Set Defaults from System here****//

            //*** Set controller variables used for functions***//
            var a = $filter('filter')(vm.AliranOptions, { Value: vm.activity.AliranID }, true);
            if (a.length != 0) {
                vm.SelectedAliran = a[0].Code;
            }
            //Saved Activity : Check Is Closed?
            if (vm.activity.ActStatusID == constClosedActStatusID) {
                vm.IsActivityClose = true;
            }

            vm.kategori1Change(vm.activity.Kategori1ID);
            vm.kategori2Change(vm.activity.Kategori2ID);
            vm.kategori3Change(vm.activity.Kategori3ID);

            //init with prev activity details or existing Act
            vm.jenisPelangganChange();

            vm.actStatus1Change(vm.activity.ActStatus1ID, true);
            vm.actStatus2Change(vm.activity.ActStatus2ID);

            vm.actChannelChange(); //bindMenuBar is here as well

            //bind the cascading TINDAKAN SUSULAN
            vm.kempenAndKodChange(vm.activity.KodSelesaiID, vm.outbound ? vm.outbound.JenisKempenID : vm.activity.JenisKempenID, 'Agent'); //TODO Temp hardcode 'Agent'

            //*** END Set controller variables used for functions***//


            if (vm.activity.Case != null) { //bind case summary tab
                bindCaseSummary(vm.activity.Case, true);
            }

            checkIsTPAllowEdit();
            //if (vm.activity.ActivityID > 0) { //&& vm.activity.IsDraft) {

            //    //PY: iframe removed IN CFF PDF
            //    if (vm.SelectedAliran == vm.constAliranIN && vm.activity.ActChannelID == vm.constActChannelCFF) {

            //        ActivitySI.getCFFSummaryAttachment(vm.activityid).then(function (r) {
            //            if (r.status === 200) {
            //                if (r.data) {
            //                    vm.CFFFileSource = r.config.url + "#zoom=120,0,0&page=1&wmode=transparent";
            //                }
            //            }
            //        });
            //    }

            //    //TODO : Bind for New IN ActCFF activity(Temp)
            //    //if (!vm.activity.EmailInteraksi && vm.activity.ActChannelID == vm.constActChannelCFF && vm.SelectedAliran == vm.constAliranIN) {
            //    //    if (vm.activity.ActCFF && vm.activity.ActCFF.Email) {
            //    //        vm.activity.EmailInteraksi = vm.activity.ActCFF.Email.trim();
            //    //        if (vm.activity.IsPelangganPembayarSama) {
            //    //            vm.activity.TPEmailMB = vm.activity.EmailInteraksi;
            //    //            //$scope.makAmForm["TPEmailMB"].$pristine = false;
            //    //            vm.isEditTPData = true;
            //    //        }
            //    //    }
            //    //}
            //}
             

            bindTempPelangganDetails();

            if (!vm.activity.ActivityID || vm.activity.IsDraft) {
                if (!isResendEmail && !vm.outlookContent)
                    setDefaultEmail();//After  vm.SelectedAliran                 

                //setDefaultSumberbyChannel(); //Do after saveDraft , so that default sumber woudn't save into draft recordivit
                if (vm.outbound) {
                   
                    vm.activity.JenisKempenID = vm.outbound.JenisKempenID;
                    vm.activity.TahunTaksiran = vm.outbound.ASSESSMENT_YEAR;
                }

                blnIsPelangganSearched = false;
                blnIsTPSearched = false;
                if (!vm.activity.SumberID)
                    setDefaultSumberbyChannel();

                if (vm.activity.TP != null) { 
                    blnIsTPSearched = true;
                    isNewActFirstLoad = true;
                    vm.lstTP = [];
                    vm.lstTP.push(vm.activity.TP);
                    vm.selectTaxPayer(vm.activity.TP.TPID);
                }
                else {
                    bindTempTPDetails();
                    if (vm.activity.IsOrphanActivity) { //Orphan TP from Case or Activity    //Orphan TP from search TP
                        
                        blnIsTPSearched = true; 
                        isNewActFirstLoad = true;
                        vm.selectTaxPayer(0);

                    }
                    else if (vm.activity.TPList) {

                        vm.lstTP = [];
                        vm.lstTP = vm.activity.TPList;
                        if (idTypeCode) {
                            var a = $filter('filter')(vm.JenisPengenalanOptions, { Code: idTypeCode }, true);

                            if (a && a.length != 0)
                                vm.SearchTP.IDType = a[0];

                            vm.SearchTP.IDNo = idNo;
                        }

                        isNewActFirstLoad = true;
                        vm.ShowSearchTPResult = true;
                        vm.ShowNoneSearchTPResult = false;
                        vm.openDialogV2(initEvent, "#searchModal");


                    }
                    else if (!vm.activity.TPIDType && (vm.activity.TPFBID || vm.activity.TPTWID)) { //Integration with FB or TW

                        isNewActFirstLoad = true;
                        vm.ShowSearchTPResult = false;
                        vm.ShowNoneSearchTPResult = false;
                        vm.socialMediaID = idNo;
                        vm.socialMediaMsg = vm.activity.TPFBID ? "ID Facebook" : "ID Twitter";
                        vm.isSocialMediaNotFound = true;
                        vm.openDialogV2(initEvent, "#searchModal");

                    }
                    else if (!vm.activity.TPName) { //Orphan from integration or New Activity 
                        vm.ShowSearchTP = true;

                        vm.SearchTP.IDType == null
                        if (vm.activity.TPIDType) { //Orphan from integration
                            var a = $filter('filter')(vm.JenisPengenalanOptions, {
                                Value: vm.activity.TPIDType
                            }, true);

                            if (a && a.length != 0)
                                vm.SearchTP.IDType = a[0];
                        }

                        vm.SearchTP.NoCukai = vm.activity.TPNoCukai;
                        vm.SearchTP.IDNo = vm.activity.TPIDNumber;
                        vm.ShowSearchTPResult = false;

                        if (checkSearchTPCriteria())
                            vm.ShowNoneSearchTPResult = true;

                        vm.SearchTP.InvalidSearch = false;
                        isNewActFirstLoad = true;
                        vm.openDialogV2(initEvent, "#searchModal");

                    }
                }
                 
                vm.isEditTPData = true;
                $scope["makAmForm"].$dirty = true;
                 
            }
            //If TP is orphan , here is not executed
            constructDefaultEmailEndPart();
        }
    }

    function bindActivityData() {

        //FB or TW from integration
        if (vm.activity.IsDraft) {
            if (vm.activity.TPFBID) {
                idTypeCode = constFBIDTypeCode
            }
            if (vm.activity.TPTWID) {
                idTypeCode = constTWIDTypeCode
            }
        }

        if (vm.activity.Outbound) {
            vm.outbound = angular.copy(vm.activity.Outbound); 
            vm.activity.Outbound = null;
            OutboundService.init(vm.outbound);
            vm.outbound.UsiaData = OutboundService.Tunggakan.UsiaData;
            vm.outbound.UsiaDebit = OutboundService.Tunggakan.UsiaDebit;
            //vm.outbound.TarikhKenaBayar = OutboundService.Ansuran.TarikhKenaBayar;
            vm.outbound.AnsuranList = OutboundService.Ansuran.AnsuranList;
        }

        if (vm.activity.EmailBlast) {
            vm.emailblast = angular.copy(vm.activity.EmailBlast); 
            vm.activity.EmailBlast = null;
            OutboundService.init(vm.outbound);
        }

        if (vm.activity.NilaiKes)
            vm.activity.NilaiKes = $filter('number')(vm.activity.NilaiKes, 2);

        if (vm.activity.AnggaranAnsuranPC)
            vm.activity.AnggaranAnsuranPC = $filter('number')(vm.activity.AnggaranAnsuranPC, 2);

        //Set Data in CKEEditor
        if (vm.activity.ActEmail != null) {
            vm.tempEmail = angular.copy(vm.activity.ActEmail);
            editor.selTemplateID = vm.activity.ActEmail.TemplateID;
            editor.selSignatureTplID = vm.activity.ActEmail.SignatureTemplateID;
            editor.setData(decodeEntities(vm.activity.ActEmail.EmailContent));
        }

        if (vm.activity.ActCFF != null) {
            vm.tempEmail = {
            };
            vm.tempEmail.From = vm.activity.ActCFF.From;
            vm.tempEmail.To = vm.activity.ActCFF.To;
            vm.tempEmail.CC = vm.activity.ActCFF.CC;
            vm.tempEmail.BCC = vm.activity.ActCFF.BCC;
            vm.tempEmail.EmailSubject = vm.activity.ActCFF.EmailSubject;
            vm.tempEmail.EmailContent = vm.activity.ActCFF.EmailContent;
            vm.tempEmail.TemplateID = editor.selTemplateID = vm.activity.ActCFF.TemplateID;
            vm.tempEmail.SignatureTemplateID = editor.selSignatureTplID = vm.activity.ActCFF.SignatureTemplateID;
            editor.setData(decodeEntities(vm.activity.ActCFF.EmailContent));
        }

        if (vm.activity.ActCatatans) {
            for (i = 0; i < vm.activity.ActCatatans.length; i++)
                vm.activity.ActCatatans[i].Catatan = vm.activity.ActCatatans[i].Catatan.replace(/\n/g, '<br/>');
        }

        if (vm.activity.ActVerification != null && vm.activity.TP) {
            vm.VeriCountMessage = (vm.activity.ActVerification.TotalWrong + vm.activity.ActVerification.TotalCorrect) + " Butiran disemak";

            if (vm.activity.ActVerification.SpouseID && vm.activity.TP.TPSpouseList) {
                for (i = 0; i < vm.activity.TP.TPSpouseList.length; i++) {
                    if (vm.activity.TP.TPSpouseList[i].SpouseID == vm.activity.ActVerification.SpouseID) {
                        vm.activity.TP.TPSpouseList[i].Result = vm.activity.ActVerification.PasanganResult;
                        vm.activity.TP.TPSpouseList[i].Remarks = vm.activity.ActVerification.PasanganRemarks;
                    }
                }
            }


            if (vm.activity.ActVerification.EjenCukaiID && vm.activity.TP.TPEjenCukais) {
                for (i = 0; i < vm.activity.TP.TPEjenCukais.length; i++) {
                    if (vm.activity.TP.TPEjenCukais[i].EjenCukaiID == vm.activity.ActVerification.EjenCukaiID) {
                        vm.activity.TP.TPEjenCukais[i].Result = vm.activity.ActVerification.EjenCukaiResult;
                        vm.activity.TP.TPEjenCukais[i].Remarks = vm.activity.ActVerification.EjenCukaiRemarks;
                    }
                }
            }
            if (vm.activity.ActVerification.ShareholderID && vm.activity.TP.TPShareholder) {
                for (i = 0; i < vm.activity.TP.TPShareholder.length; i++) {
                    if (vm.activity.TP.TPShareholder[i].ShareholderID == vm.activity.ActVerification.ShareholderID) {
                        vm.activity.TP.TPShareholder[i].Result = vm.activity.ActVerification.ShareholderResult;
                        vm.activity.TP.TPShareholder[i].Remarks = vm.activity.ActVerification.ShareholderRemarks;
                    }
                }
            }

            if (vm.activity.ActVerification.MajikanID && vm.activity.TP.TPMajikanList) {
                for (i = 0; i < vm.activity.TP.TPMajikanList.length; i++) {
                    if (vm.activity.TP.TPMajikanList[i].NoCukaiSTSMajikanID == vm.activity.ActVerification.MajikanID) {
                        vm.activity.TP.TPMajikanList[i].Result = vm.activity.ActVerification.NamaMajikanResult;
                        vm.activity.TP.TPMajikanList[i].Remarks = vm.activity.ActVerification.NamaMajikanRemarks;
                    }
                }
            }
        }
    }

    var retryCount = 0;
    function delayedSetEditorReadOnly() {
        if (editor.editable() == undefined && retryCount++ < 10) {
            $timeout(delayedSetEditorReadOnly, retryCount * 100); //Wait a while longer each iteration
        } else {
            setEditorIsReadOnly();

        }
    };


    function setEditorIsReadOnly() {
        if (!vm.activity.AliranID || !vm.activity.ActChannelID || vm.IsActivityClose) {

            editor.setReadOnly(true);
        }
        else if (vm.activity.ActChannelID == vm.constActChannelEmail || vm.activity.ActChannelID == vm.constActChannelCFF) {
            editor.setReadOnly(false);
            if (!isEmailTmplatesLoaded)
                getEmailTemplateDDLOptions();
        }
    }

    var intDefaultEmailTemplateID = 11;
    function getEmailTemplateDDLOptions() {
        var comboEmailTmplsA = editor.ui.get("emailtemplatesA");
        var comboEmailTmplsB = editor.ui.get("emailtemplatesB");
        comboEmailTmplsA.createPanel(editor);
        comboEmailTmplsB.createPanel(editor);
        //var comboSignatureTmpls = editor.ui.get("signaturetemplates");
        //comboSignatureTmpls.createPanel(editor);
        editor.listTemplates = [];
        ActivitySI.getActEmailTemplateDDLOptions().then(function (r) {
            if (r.status == 200) {
                var data = r.data || {};
                lstGroupedTmplsA = data.lstEmailTemplateA;
                lstGroupedTmplsB = data.lstEmailTemplateB;
                lstSignatureTmpls = data.lstSignatureTemplate;
                var delimiter = '|^~^|';

                //editor.Templates = lstTmpls;  
                for (i = 0; i < lstGroupedTmplsA.length; i++) {
                    //add(value,name,label)

                    var lstTmpls = lstGroupedTmplsA[i];
                    editor.listTemplates.push.apply(editor.listTemplates, lstTmpls)
                    comboEmailTmplsA.startGroup(lstTmpls[0].Language);
                    for (j = 0; j < lstTmpls.length; j++) {
                        //if (lstTmpls[j].TemplateHTML != null) { 
                        //    lstTmpls[j].TemplateHTML = lstTmpls[j].TemplateHTML.replace(/\n/g, '<br/>')
                        //}
                        comboEmailTmplsA.add(lstTmpls[j].TemplateID, lstTmpls[j].Subject, lstTmpls[j].Subject);
                        if (lstTmpls[j].TemplateID == editor.selTemplateID) {
                            editor.IsEmailTemplateASelected = 1;
                            editor.IsEmailTemplateBSelected = 0;
                            editor.selEmailSubject = lstTmpls[j].Subject;
                        }
                        if (j == 0) {
                            intDefaultEmailTemplateID = lstTmpls[j].TemplateID; // assign any first activity template
                        }
                    }
                }

                for (i = 0; i < lstGroupedTmplsB.length; i++) {
                    //add(value,name,label)
                    var lstTmpls = lstGroupedTmplsB[i];
                    editor.listTemplates.push.apply(editor.listTemplates, lstTmpls)
                    comboEmailTmplsB.startGroup(lstTmpls[0].Language);
                    for (j = 0; j < lstTmpls.length; j++) {
                        comboEmailTmplsB.add(lstTmpls[j].TemplateID, lstTmpls[j].Subject, lstTmpls[j].Subject);
                        if (lstTmpls[j].TemplateID == editor.selTemplateID) {
                            editor.IsEmailTemplateASelected = 0;
                            editor.IsEmailTemplateBSelected = 1;
                            editor.selEmailSubject = lstTmpls[j].Subject;
                        }
                        if (j == 0) {
                            intDefaultEmailTemplateID = lstTmpls[j].TemplateID; // assign any first activity template
                        }
                    }
                }

                //for (i = 0; i < lstSignatureTmpls.length; i++) {
                //    //add(value,name,label)
                //    comboSignatureTmpls.add(lstSignatureTmpls[i].TemplateSignatureID + delimiter + lstSignatureTmpls[i].TemplateSignatureHTML, lstSignatureTmpls[i].TemplateSignatureName, lstSignatureTmpls[i].TemplateSignatureName);

                //    if (lstSignatureTmpls[i].TemplateSignatureID == editor.selSignatureTplID)
                //        editor.selSignatureName = lstSignatureTmpls[i].TemplateSignatureName;
                //}

                isEmailTmplatesLoaded = true;
                editor.isTemplateLoaded = true;
            }
        });
    }

    //function getOutBoundDetails() {
    //    vm.outbound = {};
    //   // vm.outbound = r.data
    //    var dtAnsuran = [];
    //    vm.AnsuranRecords = [];
    //    var i = 0;
    //    for (var key in vm.outbound) {
    //        var matches = key.match(/^DATE(\d+)/);
    //        if (matches && matches.length > 1)
    //            if (vm.outbound[key]) { 
    //                i++;
    //                dtAnsuran.push(new Datvm.WindowUnloadEventEnable)e(vm.outbound[key]));
    //                vm.AnsuranRecords.push({ Key: key,  Bil: i, Date: vm.outbound[key], AMT: vm.outbound['AMT' + matches[1]], Status: (vm.outbound['AMT' + matches[1]]?'Bayar' : 'Gagal')});

    //            } 
    //    }

    //    vm.outbound.TarikhKenaBayar = new Date(Math.max.apply(null, dtAnsuran));
    //}

    var WindowUnloadEventEnable = true;
    function onbeforeunload(e) {

        if (!$window.beforeUnloadCanceled && WindowUnloadEventEnable) {

            return e.returnValue = "Unsaved changes";
        }
        //if false , set back to true ( false when user click attachment)
        WindowUnloadEventEnable = true;

    }

    function onUnload(e) {

        if ($window.location.pathname == '/Activity/Profile/New') {
            if (vm.activity.IsDraft && vm.activity.ActivityID > 0) {
                vm.redirectTo('/activity/profile/detail/' + vm.activity.ActivityID);
            }
        }
    }
    vm.redirectTo = function (url) {

        $window.beforeUnloadCanceled = true;
        $window.location.href = url;
    }
     

    //Bind Open Case - Start
    function displayOpenCaseDataTable() {
        vm.dtColumnsOpenCase = [
            DTColumnBuilder.newColumn('CaseRefNo').withTitle('No. Kes').renderWith(function (data, type, full) {
                return '<a target="_blank" href="/case/profile/detail/' + full.CaseID + '">' + data + '</a>';
            }).withOption('width', '20%'),
            DTColumnBuilder.newColumn('Kategori').withTitle('Kategori').renderWith(renderKategori).withOption('width', '25%'),
            DTColumnBuilder.newColumn('CaseStatusLevel2Name').withTitle('Status').renderWith(renderStatusLevel).withOption('width', '25%'),
            DTColumnBuilder.newColumn('CreatedDateTime').withTitle('Tarikh Dihasilkan').renderWith(function (data, type) {
                return $filter('date')(data, $scope.DateTimeFormat);
            }).withOption('width', '15%'),
            DTColumnBuilder.newColumn('CaseID').withTitle('').renderWith(function (data) {
                var link;
                link = '<button type="button" ng-click="act.selectCase(\'' + data + '\')" class="btn btn-primary" ><span class="fa fa-check-square"></span> Pilih</button>';
                return link;
            }).withOption('width', '15%').withOption('bSortable', false)
        ];
        vm.dtOptionsOpenCase = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallback)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('serverSide', true)
            .withOption('autoWidth', false)
            .withOption('filter', false)
            .withOption('createdRow', function (row, data, dataIndex) {
                $compile(angular.element(row).contents())($scope);
            })
            .withOption('order', [])
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
    }

    var ajaxCallback = function (data, callback, settings) {
        if (!isFirstLoad) {
            data.TPID = vm.activity.TP ? vm.activity.TP.TPID : 0;
            if (data.TPID == 0) {
                vm.transferToCase();
            }
            else { 
                CaseSI.getOpenCase(data).then(function (r) {
                    if (r.status === 200) {
                        vm.lstCase = r.data.data;
                        callback(r.data);
                        isEmptyOpenCase = vm.lstCase.length > 0 ? false : true;

                        if (isEmptyOpenCase) {
                            vm.transferToCase();
                        } else {
                            if (!angular.element(document.body).hasClass('md-dialog-is-showing'))
                                vm.openDialog(vm.linkCaseEvent, '#myModal');
                        }
                    }
                });
            }
        }
        isFirstLoad = false;
    };

    function renderKategori(data, type, row, meta) {
        var kategoriDesc = '';
        if (row.Kategori1Name != '' && row.Kategori1Name != undefined)
            kategoriDesc += '<ul class="list-inline"><li><b>' + row.Kategori1Name + ' </b></li>';
        if (row.Kategori2Name != '' && row.Kategori2Name != undefined)
            kategoriDesc += '<li class="arrow-separator" style="font-size:0.785em;"><b> ' + row.Kategori2Name + ' </b></li>';
        if (row.Kategori3Name != '' && row.Kategori3Name != undefined)
            kategoriDesc += '<li class="arrow-separator" style="font-size:0.785em;"><span> ' + row.Kategori3Name + '</span></li>';

        if (kategoriDesc != '')
            kategoriDesc = kategoriDesc + '</ul >';

        var label = '<span>' + kategoriDesc + '</span>';

        return label
    }

    function renderStatusLevel(data, type, row, meta) {
        var statusDesc = '';
        if (row.CaseStatusLevel2Name != '' && row.CaseStatusLevel2Name != undefined)
            statusDesc += '<ul class="list-inline"><li class="arrow-separator" style="font-size:0.785em;"><b>' + row.CaseStatusLevel2Name + ' </b></li>';
        if (row.CaseStatusLevel3Name != '' && row.CaseStatusLevel3Name != undefined)
            statusDesc += '<li class="arrow-separator" style="font-size:0.785em;"><span> ' + row.CaseStatusLevel3Name + ' </span></li>';

        if (statusDesc != '')
            statusDesc = statusDesc + '</ul >';

        var label = '<span>' + statusDesc + '</span>';

        return label
    }
    //Bind Open Case - End

    //Bind Outbound table - Start

    function displayOutboundDataTable() {
        vm.dtColumnsOutbound = [

            DTColumnBuilder.newColumn('StatusID').withTitle(' ').renderWith(function (data, type) {
                if (data != '27' && data != '29' && data != '30') {
                    return '';
                }
                else {
                    return '<i class="case fa fa-exclamation-circle" style="color:red;" ></i >';

                }
            }),
            DTColumnBuilder.newColumn('JenisKempen').withTitle('Jenis Kempen').renderWith(function (data, type, full) {
                if (data == '-') {
                    return data
                }
                else {
                    return '<a target="_blank" href="/Outbound/profile/detail/' + full.JenisKempenID + '/' + full.ReMSDataID + '">' + data + '</a>';
                }

            }).withOption('width', '20%'),
            DTColumnBuilder.newColumn('CampaignName').withTitle('Nama Kempen'),
            DTColumnBuilder.newColumn('JenisCukai').withTitle('Jenis Cukai'),
            DTColumnBuilder.newColumn('TarikhJanjiBayar').withTitle('Tarikh Janji Bayar').renderWith(function (data, type) {
                if (data == null)
                    return '-'
                return $filter('date')(data, $scope.DateFormat);
            }),
            DTColumnBuilder.newColumn('TahunTaksiran').withTitle('Tahun Taksiran'),
            //DTColumnBuilder.newColumn('TarikhREMSHantar').withTitle('Tarikh REMS Hantar').renderWith(function (data, type) {
            //    if (data == null)
            //        return '-'

            //    return $filter('date')(data, 'dd MMM yyyy');
            //}),
            //DTColumnBuilder.newColumn('REMSDate').withTitle('Tarikh ReMS').renderWith(function (data, type) {
            //    if (data == null)
            //        return '-'

            //    return $filter('date')(data, 'dd MMM yyyy');
            //}),
            DTColumnBuilder.newColumn('OutboundStatus').withTitle('Status'),
            DTColumnBuilder.newColumn('JenisKempenID').withTitle('').renderWith(function (data, type, full) {
                var link;
                if (vm.outbound != null && vm.outbound.JenisKempenID != null)
                    link = '<button type="button" ng-click="act.addOutboundActivity(\'' + full.OutboundID + '\', \'' + full.ReMSDataID + '\', \'' + full.JenisKempenID + '\', \'' + full.CCCampaignName + '\')" class="btn btn-primary" ><span class="fa fa-plus"></span> Tambah Aktiviti</button>';
                else
                    link = '<button type="button" ng-click="act.selectOutbound(\'' + full.OutboundID + '\', \'' + full.ReMSDataID + '\', \'' + full.JenisKempenID + '\', \'' + full.CCCampaignName + '\')" class="btn btn-primary" ><span class="fa fa-check-square"></span> Pilih</button>';
                return link;
            }).withOption('width', '15%').withOption('bSortable', false)
        ];
        vm.dtOptionsOutbound = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallback2)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('serverSide', true)
            .withOption('autoWidth', false)
            .withOption('filter', false)
            .withOption('createdRow', function (row, data, dataIndex) {
                $compile(angular.element(row).contents())($scope);
            })
            .withOption('order', [])
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
    }

    var ajaxCallback2 = function (data, callback, settings) {
        if (!isFirstLoadOutbound) {
            data.TPID = vm.activity.TP ? vm.activity.TP.TPID : 0;
            TaxPayerSI.getOutboundListByTaxPayer(data).then(function (r) {
                if (r.status == 200) {
                    callback(r.data);

                    if (!angular.element(document.body).hasClass('md-dialog-is-showing'))
                        vm.openDialog(vm.linkOutbondEvent, '#myModalOutbound');
                    //console.log(r.data);
                }
            });
 
        }
        isFirstLoadOutbound = false;
    };
     

    //Bind Outbound table - Close

    /*Tab functions*/
    vm.tabAction = tabAction;
    function tabAction(cls, type, init) {
        TabID = cls;
        TabType = type;
        reset();
        if (init) {
            getLatestTab();
        }
        else {
            switch (cls) {
                case '01':
                    type == "Profile" ? tabProfile01Click() : tabServices01Click();
                    break;
                case '02':
                    type == "Profile" ? tabProfile02Click() : tabServices02Click();
                    break;
                case '03':
                    type == "Profile" ? tabProfile03Click() : tabServices03Click();
                    break;
                case '04':
                    type == "Profile" ? tabProfile04Click() : tabServices04Click();
                    break;
                case '05':
                    type == "Profile" ? tabProfile05Click() : tabServices05Click();
                    break;
                case '06':
                    type == "Profile" ? tabProfile06Click() : tabServices06Click();
                    break;
                case '07':
                    type == "Profile" ? tabProfile07Click() : tabServices07Click();
                    break;
            }
        }
    }

    function getLatestTab() {
        $("li[class^='Services_']").each(function () {
            var myClassName = this.className;
            if (myClassName.indexOf("Services_01") >= 0) {
                vm.tabServices01Click();
                //console.log("Services_01");
                return false;
            }
            else if (myClassName.indexOf("Services_02") >= 0) {
                vm.tabServices02Click();
                //console.log("Services_02");
                return false;
            }

        });
    }

    //Profile Tab 01
    vm.tabProfile01Click = tabProfile01Click;
    function tabProfile01Click() {
        vm.IsProfileTab = vm.tabProfile01Active = true;
        $("html, body").animate({
            scrollTop: 0
        }, 400);
    }

    //Profile Tab 02
    vm.tabProfile02Click = tabProfile02Click;
    function tabProfile02Click() {
        vm.IsProfileTab = vm.tabProfile02Active = true;
        $("html, body").animate({
            scrollTop: 0
        }, 400);
    }

    //Profile Tab 03
    vm.tabProfile03Click = tabProfile03Click;
    function tabProfile03Click() {
        vm.IsProfileTab = vm.tabProfile03Active = true;
        $("html, body").animate({
            scrollTop: 0
        }, 400);
    }

    //Profile Tab 04
    vm.tabProfile04Click = tabProfile04Click;
    function tabProfile04Click() {
        vm.IsProfileTab = vm.tabProfile04Active = true;
        $("html, body").animate({
            scrollTop: 0
        }, 400);
    }

    //Profile Tab 05
    vm.tabProfile05Click = tabProfile05Click;
    function tabProfile05Click() {
        vm.IsProfileTab = vm.tabProfile05Active = true;
        //$("html, body").animate({
        //    scrollTop: 0
        //}, 500);

        if (vm.activity.OutboundID > 0 && vm.activityid > 0 && $scope.number == 0)
        {
            ActivitySI.getActOutboundDetails(vm.activity.OutboundID).then(function (r) {
                if (r.status === 200) {
                    //$scope.activity = r.data;
                    if(r.data.Outbound)
                    {
                        vm.Actoutbound = r.data.Outbound;
                        if (vm.Actoutbound) {
                            vm.outbound = angular.copy(vm.Actoutbound);
                            vm.activity.Outbound = null;
                            OutboundService.init(vm.outbound);
                            vm.outbound.UsiaData = OutboundService.Tunggakan.UsiaData;
                            vm.outbound.UsiaDebit = OutboundService.Tunggakan.UsiaDebit;
                            //vm.outbound.TarikhKenaBayar = OutboundService.Ansuran.TarikhKenaBayar;
                            vm.outbound.AnsuranList = OutboundService.Ansuran.AnsuranList;
                        }
                    }

                    $scope.number = 0;
                    
                }
            })
        }
        
        $scope.number = 1;

        $("html, body").animate({
            scrollTop: 0
        }, 500);

    }

    //Profile Tab 06
    vm.tabProfile06Click = tabProfile06Click;
    function tabProfile06Click() {
        vm.IsProfileTab = vm.tabProfile06Active = true;
        $("html, body").animate({
            scrollTop: 0
        }, 400);
    }

    //Profile Tab 06
    vm.tabProfile07Click = tabProfile07Click;
    function tabProfile07Click() {
        vm.IsProfileTab = vm.tabProfile07Active = true;
        $("html, body").animate({
            scrollTop: 0
        }, 400);
    }

    //Services Tab 01
    vm.tabServices01Click = tabServices01Click;
    function tabServices01Click() {
        vm.IsServicesTab = vm.tabServices01Active = true;
        $("html, body").animate({
            scrollTop: 0
        }, 400);
    }

    //Services Tab 02
    vm.tabServices02Click = tabServices02Click;
    function tabServices02Click() {
        vm.IsServicesTab = vm.tabServices02Active = true;
        $("html, body").animate({
            scrollTop: 0
        }, 400);
    }

    function reset() {
        vm.IsProfileTab = false;
        vm.IsServicesTab = false;

        // Set Table visibility
        vm.tabProfile01Active = false;
        vm.tabProfile02Active = false;
        vm.tabProfile03Active = false;
        vm.tabProfile04Active = false;
        vm.tabProfile05Active = false;
        vm.tabProfile06Active = false;
        vm.tabProfile07Active = false;

        vm.tabServices01Active = false;
        vm.tabServices02Active = false;
        vm.tabServices03Active = false;
    }

    /*Tab functions END*/

    vm.verifiedTP = function () {
         
        vm.activity.ActVerification.TotalCorrect = $('.verification:checkbox:checked').length;

        vm.activity.ActVerification.TotalWrong = $('.verificationFailed:checkbox:checked').length;

        vm.VeriCountMessage = (vm.activity.ActVerification.TotalCorrect + vm.activity.ActVerification.TotalWrong) + " Butiran disemak";
    }

    vm.verificationFailedTP = function () {
         
        vm.activity.ActVerification.TotalWrong = $('.verificationFailed:checkbox:checked').length;

        vm.activity.ActVerification.TotalCorrect = $('.verification:checkbox:checked').length;

        vm.VeriCountMessage = (vm.activity.ActVerification.TotalCorrect + vm.activity.ActVerification.TotalWrong) + " Butiran disemak";
    }

    vm.toggleVerifyList = function (lstVerify, i, type) {
        for (var j = 0; j < lstVerify.length; j++) {
            if (j != i) {
                lstVerify[j].Result = null;
                lstVerify[j].Remarks = null;

                $('.' + type + '-' + j + ":checkbox").each(function () {
                    $(this).prop("checked", false);
                });
            }
        }

        vm.activity.ActVerification = vm.activity.ActVerification || {
        };

        if (type == 'spouse-checkbox-lst') {
            vm.activity.ActVerification.SpouseID = lstVerify[i].SpouseID;
            vm.activity.ActVerification.PasanganResult = lstVerify[i].Result;
            vm.activity.ActVerification.PasanganRemarks = lstVerify[i].Remarks;
            vm.SpouseVerificationChangeHistory = lstVerify[i].SpouseName + (lstVerify[i].IdentityNo ? '(' + lstVerify[i].JenisPengenalan + ' : '
                + lstVerify[i].IdentityNo + ')' : '') + '<br/> Keputusan Pengesahan : ' + (lstVerify[i].Result == null || lstVerify[i].Result == undefined ? '-' : lstVerify[i].Result && 'Ya' || 'Tidak') + ';<br/> Catatan Pengesahan : ' + (lstVerify[i].Remarks || '-') + ';';

            $scope.verificationForm.$dirty = true;
            $scope.verificationForm["ActVerification_Spouse"].$pristine = false;
            $scope.verificationForm["ActVerification_Spouse"].$dirty = true;
        }

        else if (type == 'ejen-checkbox-lst') {
            vm.activity.ActVerification.EjenCukaiID = lstVerify[i].EjenCukaiID;
            vm.activity.ActVerification.EjenCukaiResult = lstVerify[i].Result;
            vm.activity.ActVerification.EjenCukaiRemarks = lstVerify[i].Remarks;
            vm.EjenVerificationChangeHistory = lstVerify[i].EjenCukaiName + '<br/> Keputusan Pengesahan : ' + (lstVerify[i].Result == null || lstVerify[i].Result == undefined ? '-' : lstVerify[i].Result && 'Ya' || 'Tidak') + ';<br/> Catatan Pengesahan : ' + (lstVerify[i].Remarks || '-') + ';';
            $scope.verificationForm.$dirty = true;
            $scope.verificationForm["ActVerification_EjenCukai"].$pristine = false;
            $scope.verificationForm["ActVerification_EjenCukai"].$dirty = true;
        }

        else if (type == 'shareholder-checkbox-lst') {
            vm.activity.ActVerification.ShareholderID = lstVerify[i].ShareholderID;
            vm.activity.ActVerification.ShareholderResult = lstVerify[i].Result;
            vm.activity.ActVerification.ShareholderRemarks = lstVerify[i].Remarks;
            vm.ShareholderVerificationChangeHistory = lstVerify[i].ShareholderName + ' (No. Pengenalan : ' + (lstVerify[i].ShareholderIdentityNo || '-') + ')<br/> Keputusan Pengesahan : ' + (lstVerify[i].Result == null || lstVerify[i].Result == undefined ? '-' : lstVerify[i].Result && 'Ya' || 'Tidak') + ';<br/> Catatan Pengesahan : ' + (lstVerify[i].Remarks || '-') + ';';
            $scope.verificationForm.$dirty = true;
            $scope.verificationForm["ActVerification_Shareholder"].$pristine = false;
            $scope.verificationForm["ActVerification_Shareholder"].$dirty = true;
        }
        else if (type == 'majikan-checkbox-lst') {
            vm.activity.ActVerification.MajikanID = lstVerify[i].NoCukaiSTSMajikanID;
            vm.activity.ActVerification.NamaMajikanResult = lstVerify[i].Result;
            vm.activity.ActVerification.NamaMajikanRemarks = lstVerify[i].Remarks;
            vm.MajikanVerificationChangeHistory = lstVerify[i].NamaMajikan + '<br/> Keputusan Pengesahan : ' + (lstVerify[i].Result == null || lstVerify[i].Result == undefined ? '-' : lstVerify[i].Result && 'Ya' || 'Tidak') + ';<br/> Catatan Pengesahan : ' + (lstVerify[i].Remarks || '-') + ';';
            $scope.verificationForm.$dirty = true;
            $scope.verificationForm["ActVerification_Majikan"].$pristine = false;
            $scope.verificationForm["ActVerification_Majikan"].$dirty = true;
        }
    }
    /*Verification Tab End */
    vm.openPreviewDialog = function (e, id) {
		
		if(vm.activity.AssignedOfficerName != null)
		{
			 vm.activity.AssignedOfficerName = vm.activity.AssignedOfficerName.substring(0, vm.activity.AssignedOfficerName.indexOf(","));
		}
		      
        var arr = [['No Rujukan Cukai', vm.activity.TPNoCukai], ['Tax Payer Name', vm.activity.TPName]
        , ['Tax Payer IDNumber', vm.activity.TPIDNumber]
        , ['Tahun Taksiran', vm.activity.TahunTaksiran]
        , ['Pegawai Bertugas', vm.activity.AssignedOfficerName || userInfo.DisplayName]
        , ['Kategori', (vm.case.Kategori1Name ? vm.case.Kategori1Name : vm.Kategori1Name)]
        , ['Sub Kategori', (vm.case.hasOwnProperty('Kategori2Name') ? vm.case.Kategori2Name : vm.Kategori2Name)]
        , ['No Telefon', (vm.activity.TP ? vm.activity.TP.TelNo : null)], ['Case Number', vm.case.CaseRefNo]
        , ['Pelanggan Nama', vm.activity.PelangganNama], ['Pelanggan IDNumber', vm.activity.PelangganIDNumber]
        , ['Pelanggan Telefon', (tempPelanggan ? tempPelanggan.TelNo : null)]
        , ['Dihasilkan Oleh', vm.activity.CreatedByName], ['Dihasilkan Pada', (vm.activity.CreatedDateTime ? moment(vm.activity.CreatedDateTime).format('DD MMM YYYY') : null)]
        , ['Cawangan', (vm.activity.TP ? vm.activity.TP.CWPungutanCP : '')]];

        var strTemp = editor.getData();
        //var reg = new RegExp(/(\[)(\[)(.*?)(\])(\])/, 'mgi');
        //var match;
        //var strContent = '';
        strTemp += strTemp != '' ? editor.defaultEmailEndPart : '';

        for (var i = 0; i < arr.length; i++) {
            var regex = new RegExp('\\[\\[' + arr[i][0] + '\\]\\]', "g");
            strTemp = strTemp.replace(regex, arr[i][1] || '-');

        }
         
        vm.openDialog(e, id);
        vm.EmailTempPreview = strTemp;
    }

    vm.setIframeBody = function (strId, strContent) {
        $timeout(function () {
            var iframe = document.getElementById(strId);
            var iframedoc = iframe.contentDocument || iframe.contentWindow.document;
            iframedoc.open('text/html', 'replace');
            //iframedoc.body.innerHTML = strContent;
            iframedoc.write(strContent);
            iframedoc.close();
            ifrmBody = iframedoc.getElementsByTagName("body")[0];
            ifrmBody.style.wordBreak = "break-all";
            ifrmBody.style.overflowX = "hidden";
        }, 100);
    }

    //Dialog
    vm.openDialog = function (e, id) {
        $mdDialog.show({
            contentElement: id,
            parent: angular.element(document.body),
            targetEvent: e,
            clickOutsideToClose: true
        });
    }

    vm.openDialogV2 = function (e, id) {
        $mdDialog.show({
            contentElement: id,
            parent: angular.element(document.body),
            targetEvent: e,
            clickOutsideToClose: false
        });
    }

    vm.close = function () {
        $mdDialog.hide();
    }

    vm.CloseActAssignCase = function () {
        $mdDialog.hide();
    }



    /*Link Unlink Case*/
    vm.selectCase = function (CaseID) {
        //TODO Need to Combine?
        CaseSI.getCaseSummary(CaseID).then(
            function (r) {
                if (r.status == 200) {
                    var objOpenCase = r.data;
                    if (objOpenCase) {
                        var model = {
                            ActivityID: vm.activity.ActivityID,
                            CaseID: CaseID,
                            CaseRefNo: objOpenCase.CaseRefNo,
                            ChangeStamp: vm.activity.ChangeStamp,
                            IsLinkCase: true
                        };
                        // New activity
                        if (!vm.activity.ActivityID || vm.activity.IsDraft) {
                            bindCaseSummary(objOpenCase);
                        }
                        else {
                            ActivitySI.linkUnlinkActivity(model).then(
                                function (r) {
                                    if (r.status == 200) {
                                        if (!r.data.IsSuccess) {
                                            swal("Failed", "Unable to link case to the activity. Please check if case has been closed.", "error");
                                            return;
                                        }

                                        vm.activity.ChangeStamp = r.data.ChangeStamp;
                                        bindCaseSummary(objOpenCase);
                                        checkIsTPAllowEdit();

                                        vm.dtInstanceActChangesHistory.reloadData();
                                        if (r.data.data) {
                                            var data = r.data.data;
                                            vm.activity.Kategori1ID = data.Kategori1ID;
                                            vm.kategori1Change(vm.activity.Kategori1ID);
                                            vm.activity.Kategori2ID = data.Kategori2ID;
                                            vm.kategori2Change(vm.activity.Kategori2ID);
                                            vm.activity.Kategori3ID = data.Kategori3ID;
                                            vm.kategori3Change(vm.activity.Kategori3ID);

                                            vm.activity.ActStatus1ID = data.ActStatus1ID;
                                            vm.actStatus1Change(vm.activity.ActStatus1ID, true); //ActStatusID will be change ?? isLoadFromDB=true
                                            vm.activity.ActStatus2ID = data.ActStatus2ID;
                                            vm.actStatus2Change(vm.activity.ActStatus2ID);
                                            vm.activity.ActStatus3ID = data.ActStatus3ID;

                                            //vm.activity.JenisKempenID = data.JenisKempenID;
                                            vm.activity.TahunTaksiran = data.TahunTaksiran;
                                            //vm.activity.StatusBayaranS104S22ID = data.StatusBayaranS104S22ID;
                                            vm.activity.NilaiKes = data.NilaiKes;
                                            vm.activity.TahapID = data.TahapID;
                                            vm.activity.NoBaucer = data.NoBaucer;
                                            //vm.activity.KodSelesaiID = data.KodSelesaiID;
                                            //vm.kempenAndKodChange(vm.activity.KodSelesaiID, vm.outbound ? vm.outbound.JenisKempenID : vm.activity.JenisKempenID, 'Agent')
                                            //vm.activity.TindakanSusulanID = data.TindakanSusulanID;
                                            vm.activity.LastUpdatedBy = data.LastUpdatedBy;
                                            vm.activity.LastUpdatedByName = data.LastUpdatedByName;
                                            vm.activity.LastUpdatedDateTime = data.LastUpdatedDateTime;
                                            //vm.isEditAnsuranActData = true;
                                            //Format
                                            if (vm.activity.NilaiKes) {
                                                vm.activity.NilaiKes = $filter('number')(vm.activity.NilaiKes, 2);
                                            }

                                        }
                                    }
                                });
                        }

                    }
                    else swal("Failed", "Unable to link case to the activity. Please check if case has been deleted.", "error");
                }
            });

        //vm.ShowRedBanner = false;
        //vm.ShowSekatanBanner = false;
        $mdDialog.hide();
    };

    vm.linkToCase = function ($event) {
        vm.linkCaseEvent = $event;
        vm.dtInstanceOpenCase.reloadData();
    };

    vm.openCaseProfile = function ($event) {
        $event.preventDefault();
        // if new activity then prompt:
        if (!vm.activity.ActivityID || vm.activity.IsDraft) {
            swal({
                title: "Please note that the Profil Aktiviti is not saved and link case is not completed.",
                text: "",
                type: "warning",
                showCancelButton: false,
                confirmButtonText: "Ok",
                closeOnConfirm: true,
                closeOnCancel: true
            }, function (isConfirm) {
                $window.open("/case/profile/detail/" + vm.case.CaseID, "_blank")
            });
        }
        else
            $window.open("/case/profile/detail/" + vm.case.CaseID, "_blank")

        return;
    };

    vm.resetCaseID = function () {
        //New Activity
        if (!vm.activity.ActivityID || (vm.activity.IsDraft && !vm.activity.IsCFFDraft)) {
            vm.case.CaseRefNo = "";
            vm.case = {
            };
            vm.activity.CaseID = null;
            vm.showcase = false;
            vm.ShowCaseSummaryTab = false;
            tabAction("01", "Profile"); //focus in MaklumatAm tab 
            return;
        }

        //Existing Activity
        swal({
            title: "Anda telah memilih untuk melepaskan pautan Kes daripada Aktiviti ini. Adakah anda pasti?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (!isConfirm) {

                swal("Batal!", "Permohonan telah dibatalkan.", "error");

                return;
            }

            var model = {
                ActivityID: vm.activity.ActivityID,
                CaseID: vm.activity.CaseID,
                CaseRefNo: vm.case.CaseRefNo,
                ChangeStamp: vm.activity.ChangeStamp,
                IsLinkCase: false
            };

            ActivitySI.linkUnlinkActivity(model).then(
                function (r) {
                    if (r.status == 200) {
                        if (!r.data.IsSuccess) {
                            swal("Batal!", "Permohonan telah dibatalkan.", "error"); swal("Failed", "Unable to unlink activity from case. Please delete the existing case to unlink.", "error");
                            return;
                        }
                        vm.case.CaseRefNo = "";
                        vm.case = {
                        };
                        isHasLinkCaseAction = false;
                        vm.activity.CaseID = null;
                        vm.activity.ChangeStamp = r.data.ChangeStamp;
                        checkIsTPAllowEdit();

                        if (r.data.data) {
                            var data = r.data.data;
                             
                            vm.activity.LastUpdatedBy = data.LastUpdatedBy;
                            vm.activity.LastUpdatedByName = data.LastUpdatedByName;
                            vm.activity.LastUpdatedDateTime = data.LastUpdatedDateTime;
                             

                        }

                        vm.showcase = false;
                        vm.ShowCaseSummaryTab = false;
                        tabAction("01", "Profile"); //focus in MaklumatAm tab 

                        swal({
                            title: "Case Unlinked!",
                            text: "Your activity is unlinked from case successfully.",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: true
                        }, function () {
                            vm.dtInstanceActChangesHistory.reloadData();
                        });
                    }

                });
        })

    };

    function bindCaseSummary(objCase, isLoadProfile) {

        vm.case = objCase;
        vm.activity.CaseID = vm.case.CaseID;
        isHasLinkCaseAction = true;
        vm.activity.Case = {
        }; //Clear case object tied to activity , no use anymore
        //bind the cascading KATEGORI
        if (vm.case.NilaiKes) {
            vm.case.NilaiKes = $filter('number')(vm.case.NilaiKes, 2);

        }

        if (vm.case && vm.case.TarikhStatus)
            vm.case.TarikhStatus = new Date(vm.case.TarikhStatus);
        vm.kategori1Change(objCase.Kategori1ID);
        vm.kategori2Change(objCase.Kategori2ID);

        //bind the cascading STATUS
        vm.caseStatus1Change(objCase.CaseStatusLevel1ID);
        vm.caseStatus2Change(objCase.CaseStatusLevel2ID);

        //bind the cascading TindakanSusulan
        //vm.kempenAndKodChange(objCase.KodSelesaiID, objCase.JenisKempenID, 'Agent');
        vm.ShowCaseSummaryTab = true;
        vm.showcase = true;

        if (!isLoadProfile) {
            tabAction("06", "Profile"); //focus in CaseSummaryTab
        }

        //Cater when add activity from case
        if (!vm.activity.ActivityID || vm.activity.IsDraft) {
            vm.activity.Kategori1ID = objCase.Kategori1ID;
            vm.activity.Kategori2ID = objCase.Kategori2ID;
            vm.activity.Kategori3ID = objCase.Kategori3ID;

            vm.activity.ActStatus1ID = objCase.CaseStatusLevel1ID;
            vm.actStatus1Change(vm.activity.ActStatus1ID, true); //ActStatusID will be change ?? isLoadFromDB=true
            vm.activity.ActStatus2ID = objCase.CaseStatusLevel2ID;
            vm.actStatus2Change(vm.activity.ActStatus2ID);
            vm.activity.ActStatus3ID = objCase.CaseStatusLevel3ID;

            //vm.activity.JenisKempenID = data.JenisKempenID;
            vm.activity.TahunTaksiran = objCase.TahunTaksiran;
            vm.activity.NilaiKes = objCase.NilaiKes;
            vm.activity.TahapID = objCase.TahapID;
            vm.activity.NoBaucer = objCase.NoBaucer;

        }

    };

    vm.caseStatus1Change = function (selectedStatus1ID) {
        vm.caseStatus2Options = [];

        var m = $filter('filter')(vm.Status1Options, {
            StatusLevel1ID: selectedStatus1ID
        }, true);
        if (m && (m.length > 0)) {
            vm.caseStatus2Options = m[0].StatusLevel2;
        }
    }

    vm.caseStatus2Change = function (selectedStatus2ID) {
        vm.caseStatus3Options = [];

        var m = $filter('filter')(vm.caseStatus2Options, {
            StatusLevel2ID: selectedStatus2ID
        }, true);
        if (m && (m.length > 0)) {
            vm.caseStatus3Options = m[0].StatusLevel3;
            vm.case.status3Disabled = m[0].StatusLevel3.length > 0 ? false : true;
        }
    }
    /*Link Unlink Case END*/

    /*Select Outbound - Start*/
    vm.linkToOutbound = function ($event) {
        vm.linkOutbondEvent = $event;
        vm.dtInstanceOutbound.reloadData();

    };

    vm.selectOutbound = function (OutboundID, ReMSDataID, JenisKempenID, CCCampaignName) {
        //TODO Need to Combine?
        vm.outbound = {
        };

        var model = {
            DataID: ReMSDataID,
            JenisKempenID: JenisKempenID
        };

        OutboundSI.getOutboundDetails(model).then(
            function (r) {
                if (r.status == 200) {
                    vm.outbound = r.data;
                    vm.isselfselectoutbound = true;
                    vm.CCCampaignName = CCCampaignName;
                }
            }

        );

        //vm.ShowRedBanner = false;
        //vm.ShowSekatanBanner = false;
        $mdDialog.hide();
    };


    vm.addOutboundActivity = function (OutboundID, ReMSDataID, JenisKempenID, CCCampaignName) {
        if (!vm.activity.ActivityID || vm.activity.IsDraft) {
            swal("Amaran!", "Profil aktiviti perlu disimpan dahulu.", "warning");
            return;
        }
        vm.SessionKey = ActivitySessionService.getActSessionKey(vm.activity.ActivityID);
        angular.element('#addOutboundActRemsDataID').val(ReMSDataID);
        angular.element('#addOutboundActJenisKempenID').val(JenisKempenID);
        angular.element('#addOutboundActSessionKey').val(vm.SessionKey);
        angular.element('#addOutboundActCCCampaignName').val(CCCampaignName);
        var btn = angular.element('#btn-addOutboundActivity');
        btn.click();

    }


    vm.resetOutbound = function () {
        vm.outbound = null;
        vm.isselfselectoutbound = false;
        vm.CCCampaignName = "";
        vm.activity.OutboundID = "";
        tabAction("01", "Profile"); //focus in MaklumatAm tab    
        //swal({
        //    title: "Adakah anda pasti untuk menghapuskan pautan outbound ini dari aktiviti?",
        //    text: "",
        //    type: "warning",
        //    showCancelButton: true,
        //    confirmButtonText: "Ya",
        //    cancelButtonText: "Tidak",
        //    closeOnConfirm: true,
        //    closeOnCancel: true
        //}, function (isConfirm) {
        //    if (isConfirm) {
        //        vm.outbound = null;
        //        vm.activity.OutboundID = "";        
        //        tabAction("01", "Profile"); //focus in MaklumatAm tab            
        //    }
        //    else {
        //        return;
        //    }
        //});
          
    }
    /*Select Outbound - End*/

    /*Change events - Start */

    vm.jenisPelangganChange = function () {
        var m = $filter('filter')(vm.JenisPelangganOptions, {
            Value: vm.activity.JenisPelangganID
        }, true);
        if (m && (m.length > 0)) {
            vm.JenisPelangganDesc = m[0].Text;
            vm.JenisPelangganCode = m[0].Code;
        }
    }

    vm.actChannelChange = function () {

        vm.SumberOptions = [];
        vm.activity.ActChannelID = vm.activity.ActChannelID == undefined ? null : vm.activity.ActChannelID;
        var m = $filter('filter')(vm.ActChannelOptions, {
            ActChannelID: vm.activity.ActChannelID
        }, true);
        if (m && (m.length > 0)) {
            vm.IsShowVerificationTab = m[0].IsShowVerificationTab;
            vm.IsShowPenerimaanDocTab = m[0].IsShowPenerimaanDocTab;
            vm.SumberOptions = m[0].Sumber;
            vm.selectActChannelName = m[0].ActChannelName;
            vm.sumberDisabled = m[0].Sumber.length > 0 ? false : true;//TODO?
        }
        else {
            vm.selectActChannelName = "";
        }
        bindMenuBar();
        if (!vm.activity.ActivityID || vm.activity.IsDraft) {
            //bindMenuBar()

            vm.activity.NotaTemuduga = null;
            vm.activity.ActDocReceived = null;
            vm.activity.KategoriDocReceived = null;

            if (vm.IsShowPenerimaanDocTab) {
                vm.activity.NotaTemuduga = {
                };
                vm.activity.NotaTemuduga.NTTarikhTerima = new Date();//$filter('date')(new Date(), $scope.DateFormat);
            }
        }

        if (!vm.IsChannelDDLDisable) {

            //Kaunter default to IN aliran
            if (vm.activity.ActChannelID == vm.constActChannelKaunter) {

                var a = $filter('filter')(vm.AliranOptions, {
                    Code: vm.constAliranIN
                }, true);
                if (a.length != 0) {
                    //vm.SelectedAliran = a[0].Code;
                    vm.activity.AliranID = a[0].Value;
                    vm.aliranChange(a[0].Code);
                }
            }

            //Disable user select CFF Inbound if not loaded from DB 
            if (vm.activity.ActChannelID == vm.constActChannelCFF) {
                var a = $filter('filter')(vm.AliranOptions, {
                    Code: vm.constAliranOUT
                }, true);
                if (a.length != 0) {
                    //vm.SelectedAliran = a[0].Code;
                    vm.activity.AliranID = a[0].Value;
                    vm.aliranChange(a[0].Code);
                }
            }

        }

    }

    vm.kategori1Change = function (selectedKategori1ID) {
        vm.SubKategoriOptions = [];
        //vm.kategori3Disabled = false;
        selectedKategori1ID = selectedKategori1ID == undefined ? null : selectedKategori1ID;
        var m = $filter('filter')(vm.MainKategoriOptions, {
            Kategori1ID: selectedKategori1ID
        }, true);
        if (m && (m.length > 0)) {
            vm.SubKategoriOptions = m[0].SubKategori;
            vm.Kategori1Name = m[0].Kategori1Name;
            vm.kategori2Disabled = m[0].SubKategori.length > 0 ? false : true;
            if (vm.kategori2Disabled) {
                vm.kategori3Disabled = true;
                vm.InnerSubKategoriOptions = {
                };
            }
        }
        else {
            vm.Kategori1Name = "";
        }

    }

    vm.kategori2Change = function (selectedKategori1ID) {
        vm.InnerSubKategoriOptions = [];

        var m = $filter('filter')(vm.SubKategoriOptions, {
            Kategori2ID: selectedKategori1ID
        }, true);
        if (m && (m.length > 0)) {
            vm.InnerSubKategoriOptions = m[0].InnerSubKategori;
            vm.Kategori2Name = m[0].Kategori2Name;
            vm.kategori3Disabled = m[0].InnerSubKategori.length > 0 ? false : true;
        }
        else {
            vm.Kategori2Name = "";
        }

    }

    vm.kategori3Change = function (selectedKategori3ID) {
        selectedKategori3ID = selectedKategori3ID == undefined ? null : selectedKategori3ID;
        var m = $filter('filter')(vm.InnerSubKategoriOptions, {
            Kategori3ID: selectedKategori3ID
        }, true);
        if (m && (m.length > 0)) {
            vm.Kategori3Name = m[0].Kategori3Name;
        }
        else {
            vm.Kategori3Name = "";
        }
    }

    vm.addkategori1Change = function (selectedKategori1ID) {
        vm.AddSubKategoriOptions = [];
        //vm.addKategori3Disabled = false;
        selectedKategori1ID = selectedKategori1ID == undefined ? null : selectedKategori1ID;
        var m = $filter('filter')(vm.MainKategoriOptions, {
            Kategori1ID: selectedKategori1ID
        }, true);
        if (m && (m.length > 0)) {
            vm.AddSubKategoriOptions = m[0].SubKategori;
            vm.addKategori2Disabled = m[0].SubKategori.length > 0 ? false : true;
            if (vm.addKategori2Disabled) {
                vm.addKategori3Disabled = true;
                vm.AddInnerSubKategoriOptions = {
                };
            }
        }

    }

    vm.addkategori2Change = function (selectedKategori2ID) {
        vm.AddInnerSubKategoriOptions = [];
        selectedKategori2ID = selectedKategori2ID == undefined ? null : selectedKategori2ID;
        var m = $filter('filter')(vm.AddSubKategoriOptions, {
            Kategori2ID: selectedKategori2ID
        }, true);
        if (m && (m.length > 0)) {
            vm.AddInnerSubKategoriOptions = m[0].InnerSubKategori;
            vm.addKategori3Disabled = m[0].InnerSubKategori.length > 0 ? false : true;
        }

    }

    //TODO dun pass in the actstatus1ID
    vm.actStatus1Change = function (selectedActStatus1ID, isNotActStatusIDChg) {
        vm.Status2Options = [];
        //vm.status3Disabled = false;
        selectedActStatus1ID = selectedActStatus1ID == undefined ? null : selectedActStatus1ID;
        var m = $filter('filter')(vm.Status1Options, {
            StatusLevel1ID: selectedActStatus1ID
        }, true);
        if (m && (m.length > 0)) {
            vm.Status2Options = m[0].StatusLevel2;
        }

        if (selectedActStatus1ID && !isNotActStatusIDChg) {
            //Bind with Main actstatus 
            m = $filter('filter')(vm.ActStatusOptions, {
                Code: selectedActStatus1ID.toString()
            }, true);
            if (m && (m.length > 0)) {
                vm.activity.ActStatusID = m[0].Value;
                $scope.makPerinciForm.ActStatus.$pristine = false;
            }
        }
    }

    vm.actStatus2Change = function (selectedActStatus2ID) {
        vm.Status3Options = [];
        selectedActStatus2ID = selectedActStatus2ID == undefined ? null : selectedActStatus2ID;
        if (selectedActStatus2ID) {
            var m = $filter('filter')(vm.Status2Options, {
                StatusLevel2ID: selectedActStatus2ID
            }, true);
            if (m && (m.length > 0)) {
                vm.Status3Options = m[0].StatusLevel3;
                vm.status3Disabled = m[0].StatusLevel3.length > 0 ? false : true;
            }
        }
    }

    vm.onChannelAliranChange = function (isFirstLoadNew) {
        //*Don't do this if on first load new activity , as the CKEDITOR takes some time to initialise
        if (!isFirstLoadNew) {
            //Ckeditor is shown when actchannel is CFF or Email, set readonly if Aliran is not selected yet
            if (editor && CKEDITOR.status == 'loaded')
                setEditorIsReadOnly();
        }

        if (!vm.activity.ActivityID || vm.activity.IsDraft) {
            setDefaultSumberbyChannel();

            if (!isResendEmail && !vm.outlookContent) //if not from outlook only reset content
                setDefaultEmail();
        }

    }

    function constructDefaultEmailEndPart() {
         
        var strCFFdetails = vm.activity.ActCFF && vm.activity.ActCFF.CFFDetails ? "<br/>Butiran: " + vm.activity.ActCFF.CFFDetails : '';
        var strDefEndPart = '<p style="overflow: hidden;  width: 100 %; height: 1em; ">===================================================================================================================================================</p>'
            + "<p>"
            + "<b>Maklumat Pelanggan</b>"
            + "<br/>"
            + "Nama Pelanggan: [[Pelanggan Nama]]"
            //+ PelangganNama
            + "<br/>"
            + "No. Pengenalan: [[Pelanggan IDNumber]]"
            //+ PelangganIDNumber
            + "<br/>"
            + "No. Telefon: [[Pelanggan Telefon]]"
            + "<br/>"
             + "<br/>"
            + "<b>Maklumat Pembayar Cukai</b>"
            + "<br/>"
            + "Nama: [[Tax Payer Name]]"
            + "<br/>"
            + "No. Pengenalan: [[Tax Payer IDNumber]]"
            + "<br/>"
           /* + "No. Rujukan Cukai: [[No Rujukan Cukai]]"
             + "<br/>"*/
            + "No. Telefon: [[No Telefon]]"
            + "<br/>"
            + strCFFdetails
            + "</p>";

        editor && (editor.defaultEmailEndPart = strDefEndPart);
        return strDefEndPart;
    }

    function setDefaultEmail() {
         

        //Repopulate the default values if CFF and Email Outbound for New Activity
        if (vm.SelectedAliran == vm.constAliranOUT && (vm.activity.ActChannelID == vm.constActChannelEmail || vm.activity.ActChannelID == vm.constActChannelCFF)) {
             
            //When NOT reply to CFF and vm.activity.ActEmail.To got value
            if (!isReplyToTPCFF && vm.activity.TPEmail) {
                vm.tempEmail.To = vm.activity.TPEmail; //TODO Email is Pelanggan's or TP
            }
            else if (isReplyToTPCFF == true && vm.activity.ActCFF) {
                vm.tempEmail.To = vm.activity.ActCFF.To;
                vm.tempEmail.EmailSubject = vm.activity.ActCFF.EmailSubject;
            }
             
            
            if (!vm.tempEmail.BCC) {
                vm.tempEmail.BCC = userInfo.Manager != null && userInfo.Manager.Email ? userInfo.Manager.Email : vm.tempEmail.BCC; //Auto set to current user's manager
                if (vm.tempEmail.BCC) {
                    vm.tempEmail.BCC += ';' + (userInfo.Email || '');
                }
                else {
                     vm.tempEmail.BCC  = (userInfo.Email || '');
                } 
            }

            //ParameterSettings : No-Reply Email value for CFF and Email OUTBOUND From field 
            if (!vm.tempEmail.From)
                vm.tempEmail.From = constNoReplyEmail;
        }

        vm.tempEmail.EmailReceivedDate = new Date();// $filter('date')(new Date(), $scope.DateFormat);
         
    }

    function setDefaultSumberbyChannel() {
        if (vm.SelectedAliran == vm.constAliranOUT && vm.activity.ActChannelID == vm.constActChannelPhone) { //Phone
            vm.activity.SumberID = constSumberReMS; //TODO set constant
        }
        else if (vm.activity.ActChannelID == vm.constActChannelPhone) { //Phone
            vm.activity.SumberID = constSumberTelefon;
        }

        if (vm.activity.ActChannelID == vm.constActChannelKaunter) { //Kaunter
            vm.activity.SumberID = constSumberKaunter;
        }

        if (vm.activity.ActChannelID == vm.constActChannelSocialMedia) { //Social Media
            if (idTypeCode == constFBIDTypeCode) {
                vm.activity.SumberID = constSumberFB;
            }

            if (idTypeCode == constTWIDTypeCode) {
                vm.activity.SumberID = constSumberTW;
            }
        }

        if (vm.activity.ActChannelID == vm.constActChannelChat) { //Chat
            vm.activity.SumberID = constSumberChat;
        }
    }

    vm.aliranChange = function (selectedAliran) {

        oldSelectedAliran = vm.SelectedAliran;
        vm.SelectedAliran = selectedAliran;
        MenuBarService.MB.Aliran = vm.SelectedAliran;
        //Don't change if oldSelectedAliran is empty and SelectedAliran is INBound as default is Inbound values
        if (vm.activity.TP && !(!oldSelectedAliran && vm.SelectedAliran == vm.constAliranIN) && oldSelectedAliran != vm.SelectedAliran) {
            vm.activity.TPEmailMB = vm.activity.TP.TPID > 0 ? (vm.SelectedAliran == vm.constAliranOUT ? vm.activity.TP.OutEmailMB : vm.activity.TP.InEmailMB) : null;
            vm.activity.TPTelefonMB = vm.activity.TP.TPID > 0 ? (vm.SelectedAliran == vm.constAliranOUT ? vm.activity.TP.OutTelefonBimbit : vm.activity.TP.InTelefonMB) : null;
            vm.activity.TPTelefonPejabat = vm.activity.TP.TPID > 0 ? (vm.SelectedAliran == vm.constAliranOUT ? vm.activity.TP.OutTelefonPejabat : null) : null;
             
        }

    }

    vm.kempenAndKodChange = function (selectedKodSelesai, selectedJenisKempen, selectedUnit) {

        vm.actTindakanSusulanOptions = [];

        vm.IsEditAnsuranActData = true;
        if (selectedKodSelesai != null && selectedJenisKempen != null && selectedUnit != null) {
            var m = $filter('filter')(vm.TindakanSusulanOptions, {
                KodSelesaiID: selectedKodSelesai, JenisKempenID: selectedJenisKempen, Unit: selectedUnit
            }, true);

            if (m != undefined && m.length != 0) {

                vm.actTindakanSusulanOptions = m;
            }
        }

    };

    vm.isPelangganPembayarSamaChange = function (e, IsPelangganPembayarSama, IsPopSearchDialog) {
        if (IsPelangganPembayarSama == false) {
            bindTempTPDetails();
            clearActivityTPDetails();
            //Clear Header
            var objTP = {
                TPID: null,
                TPName: vm.activity.TPName,
                TPJenisPengenalan: vm.activity.TPJenisPengenalan,
                TPIDNumber: vm.activity.TPIDNumber,
                TPNoCukai: vm.activity.TPNoCukai
            };
            bindHeader(objTP, null);

            vm.openDialogV2(e, "#searchModal");
        }
        else if (IsPelangganPembayarSama == true) { //Repopulate the Pembayar Cukai from Pelanggan
            
            clearActivityTPDetails();

            if (vm.activity.PelangganTPID) {
                vm.activity.IsOrphanActivity = false;
                if (tempPelanggan) {
                    vm.activity.TP = tempPelanggan;
                }
                bindActivityTPDetailsByTP();
            }
            else {
                vm.activity.IsOrphanActivity = true;
                vm.activity.TP = null;
                vm.activity.TPName = vm.activity.PelangganNama;
                vm.activity.TPIDType = vm.activity.PelangganIDType;
                vm.activity.TPIDNumber = vm.activity.PelangganIDNumber;
                vm.activity.TPNoCukai = vm.activity.PelangganNoCukai;
                //vm.activity.TPTelefonMB = vm.activity.PelangganTelefon;
                //vm.activity.TPEmailMB = vm.activity.PelangganEmail;

                var m = $filter('filter')(vm.JenisPengenalanOptions, {
                    Value: vm.activity.PelangganIDType
                }, true);

                if (m && (m.length > 0)) {
                    vm.activity.TPJenisPengenalan = m[0].Text;
                }

            }
             
            var objTP = {
                TPID: vm.activity.IsOrphanActivity == false ? vm.activity.TP.TPID : null,
                TPName: vm.activity.TPName,
                TPJenisPengenalan: vm.activity.TPJenisPengenalan,
                TPIDNumber: vm.activity.TPIDNumber,
                TPNoCukai: vm.activity.TPNoCukai
            };
            bindHeader(objTP, vm.activity.TP);
            vm.isEditTPData = true;
            if (vm.activity.TelefonInteraksi) { 
                vm.activity.TPTelefonMB = vm.activity.TelefonInteraksi; 
            }
            //Requested by user (Nazil), not populate to EmailMB for chat
            //if (vm.activity.EmailInteraksi && vm.activity.ActChannelID != vm.constActChannelChat) {
				
			//Requested by user (Nazil), populate to EmailMB for chat as well
			if (vm.activity.EmailInteraksi && vm.activity.ActChannelID != vm.constActChannelPhone) {
                 
                vm.activity.TPEmailMB = vm.activity.EmailInteraksi; 
            }

            if (vm.activity.SocialMediaInteraksiID && vm.activity.SumberID == constSumberFB) {
                vm.activity.TPFBDisplayName = vm.activity.SocialMediaInteraksiName;
                vm.activity.TPFBID = vm.activity.SocialMediaInteraksiID;
            }
            else if (vm.activity.SocialMediaInteraksiID && vm.activity.SumberID == constSumberTW) {
                vm.activity.TPTWDisplayName = vm.activity.SocialMediaInteraksiName;
                vm.activity.TPTWID = vm.activity.SocialMediaInteraksiID;
            }

            blnIsTPSearched = blnIsPelangganSearched;
        }

        //if Pelanggan is Orphan but not sama with Pembayar then false
        if (!vm.activity.PelangganTPID && vm.activity.IsPelangganPembayarSama == false)
            vm.IsPelangganNamaCukaiDisable = false;
        else
            vm.IsPelangganNamaCukaiDisable = true;//if Pelanggan is Orphan but not sama with Pembayar then false

        if (!isResendEmail && !vm.outlookContent) //if not from outlook only reset content
            setDefaultEmail();

        setIsTPPelangganSearched();
    };

    vm.replaceNonCharacter = function (strValue, idType) {
        if (strValue)
            if (idType && idType.Code == constIDTypeNRIC.Code)
                strValue = strValue.replace(/[-\s]/g, '');
            else
                strValue = strValue.replace(/\s/g, '');

        return strValue
    }


    vm.tpNameChange = function () {
        TaxPayerService.TP.Name = vm.activity.TPName;
        if (vm.activity.IsPelangganPembayarSama == true) {
            if (vm.activity.IsOrphanActivity == true) {
                vm.activity.PelangganNama = vm.activity.TPName;
            }
        }
    }

    vm.tpCukaiNoChange = function () {
        TaxPayerService.TP.TaxNo = vm.activity.TPNoCukai;
        if (vm.activity.IsPelangganPembayarSama == true) {
            if (vm.activity.IsOrphanActivity == true) {
                vm.activity.PelangganNoCukai = vm.activity.TPNoCukai;
            }
        }
    }


    vm.seksyenChange = function (selectedTimbalan) {

        vm.actWorkflowAssignToJabatanOption = [];

        if (selectedTimbalan != null) {
            var m = $filter('filter')(vm.WorkflowAssignToJabatanOption, {
                ParentUnitID: parseInt(selectedTimbalan)
            }, true);

            if (m != undefined && m.length != 0) {

                vm.actWorkflowAssignToJabatanOption = m;
            }


            if (vm.Other == constAssignToTypeUser) {
                SearchUserByUnitID(selectedTimbalan);
            }
        }

    };

    vm.seksyenChangeDocUnit = function (selectedTimbalanDocUnit) {

        vm.actWorkflowAssignToJabatanOptionDocUnit = [];

        if (selectedTimbalanDocUnit != null) {
            var m = $filter('filter')(vm.WorkflowAssignToJabatanOptionDocUnit, {
                ParentUnitID: parseInt(selectedTimbalanDocUnit)
            }, true);
            if (m != undefined && m.length != 0) {
                vm.actWorkflowAssignToJabatanOptionDocUnit = m;
            }
        }

    };


    vm.jabatanChange = function (SelectedJabatan) {
        //enable upper hierarchy
        vm.SeksyenEnabled = true;

        vm.actWorkflowAssignToCawanganOption = [];

        if (SelectedJabatan != null) {
            //disable upper hierarchy
            vm.SeksyenEnabled = false;
            var m = $filter('filter')(vm.WorkflowAssignToCawanganOption, {
                ParentUnitID: parseInt(SelectedJabatan)
            }, true);

            if (m != undefined && m.length != 0) {

                vm.actWorkflowAssignToCawanganOption = m;
            }

            if (vm.Other == constAssignToTypeUser) {
                SearchUserByUnitID(SelectedJabatan);
            }
        }

    };

    vm.jabatanChangeDocUnit = function (SelectedJabatanDocUnit) {
        //enable upper hierarchy
        vm.SeksyenEnabledDocUnit = true;
        vm.actWorkflowAssignToCawanganOptionDocUnit = [];

        if (SelectedJabatanDocUnit != null) {
            //disable upper hierarchy
            vm.SeksyenEnabledDocUnit = false;
            var m = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, {
                ParentUnitID: parseInt(SelectedJabatanDocUnit)
            }, true);

            if (m != undefined && m.length != 0) {
                vm.actWorkflowAssignToCawanganOptionDocUnit = m;
            }
        }

    };


    vm.cawanganChange = function (SelectedCawangan) {

        //enable upper hierarchy
        vm.SeksyenEnabled = true;
        vm.JabatanEnabled = true;

        vm.actWorkflowAssignToUnitOption = [];

        if (SelectedCawangan != null) {
            //disable upper hierarchy
            vm.SeksyenEnabled = false;
            vm.JabatanEnabled = false;

            var m = $filter('filter')(vm.WorkflowAssignToUnitOption, {
                ParentUnitID: parseInt(SelectedCawangan)
            }, true);

            if (m != undefined && m.length != 0) {

                vm.actWorkflowAssignToUnitOption = m;
            }

            if (vm.Other == constAssignToTypeUser) {
                SearchUserByUnitID(SelectedCawangan);
            }

        }

    };
    vm.cawanganChangeDocUnit = function (SelectedCawanganDocUnit) {

        //enable upper hierarchy
        vm.SeksyenEnabledDocUnit = true;
        vm.JabatanEnabledDocUnit = true;

        vm.actWorkflowAssignToUnitOptionDocUnit = [];

        if (SelectedCawanganDocUnit != null) {
            //disable upper hierarchy
            vm.SeksyenEnabledDocUnit = false;
            vm.JabatanEnabledDocUnit = false;

            var m = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, {
                ParentUnitID: parseInt(SelectedCawanganDocUnit)
            }, true);

            if (m != undefined && m.length != 0) {
                vm.actWorkflowAssignToUnitOptionDocUnit = m;
            }
        }

    };

    vm.unitChange = function (SelectedUnits) {

        if (vm.Other == constAssignToTypeUser) {
            SearchUserByUnitID(SelectedUnits);
        }


    };

    //Change events  - End

    /*Button Events*/

    vm.onAddActClick = function () {
        if (!vm.activity.ActivityID || vm.activity.IsDraft) {
            swal("Amaran!", "Profil aktiviti perlu disimpan dahulu.", "warning");
            return;
        }

        //ActivitySessionService.refresh();
        vm.SessionKey = ActivitySessionService.getActSessionKey(vm.activity.ActivityID);
        angular.element('#addActSessionKey').val(vm.SessionKey);
        angular.element('#addActPrevActivityID').val(vm.activity.ActivityID);
        angular.element('#addActInteractionID').val(vm.activity.InteractionID);
        var intSession = localStorageService.get("Int_ID" + vm.activity.InteractionID);
        if (intSession != null) {
            var popupwindow = 'Int_ID' + vm.activity.InteractionID + '_' + intSession.WindowNames.length;
            intSession.WindowNames.push(popupwindow);
            localStorageService.set("Int_ID" + vm.activity.InteractionID, intSession);
        }
        var form = angular.element('#addActivityForm');
        form.attr('target', popupwindow);
        form.submit();
    }


    vm.onReplyToTPClick = function () {
        if (!vm.activity.ActivityID || vm.activity.IsDraft) {
            swal("Amaran!", "Profil aktiviti perlu disimpan dahulu.", "warning");
            return;
        }
        vm.SessionKey = ActivitySessionService.getActSessionKey(vm.activity.ActivityID);
        angular.element('#addOutCFFSessionKey').val(vm.SessionKey);
        angular.element('#addOutCFFPrevActivityID').val(vm.activity.ActivityID);
        angular.element('#addOutCFFCaseID').val(vm.activity.CaseID);
        angular.element('#addOutCFFActChannelID').val(vm.constActChannelCFF);
        angular.element('#addOutCFFAliran').val('OUT');
        var form = angular.element('#replyCFFActivityForm');
        form.submit();

        if (vm.activity.ActivityID > 0)
        {
            UpdateActivity(2, false, false, false)
        }
    }

    vm.onClickResendEmail = function () { //TODO need to add interaction ID??
        if (!vm.activity.ActivityID || vm.activity.IsDraft) {
            swal("Amaran!", "Profil aktiviti perlu disimpan dahulu.", "warning");
            return;
        }

        //ActivitySessionService.refresh();
        vm.SessionKey = ActivitySessionService.getActSessionKey(vm.activity.ActivityID);
        angular.element('#resendEmailSessionKey').val(vm.SessionKey);
        angular.element('#resendEmailPrevActivityID').val(vm.activity.ActivityID);
        var form = angular.element('#resendEmailForm');
        form.submit();

    }
    vm.onConvertToActClick = function (k1, k2, k3) { //TODO need to add interaction ID??
        if (!vm.activity.ActivityID || vm.activity.IsDraft) {
            swal("Amaran!", "Profil aktiviti perlu disimpan dahulu.", "warning");
            return;
        }
        //ActivitySessionService.refresh();
        vm.SessionKey = ActivitySessionService.getActSessionKey(vm.activity.ActivityID);
        angular.element('#convertToActKategori1ID').val(k1);
        angular.element('#convertToActKategori2ID').val(k2);
        angular.element('#convertToActKategori3ID').val(k3);
        angular.element('#convertToActSessionKey').val(vm.SessionKey);
        angular.element('#convertToActPrevActivityID').val(vm.activity.ActivityID);
        var btn = angular.element('#btn-submit');
        btn.click();

    }

    vm.getTranscript = function (TranskripPerbualanURL, ActChannelID) {
        if (ActChannelID == vm.constActChannelPhone) {
            var url = TranskripPerbualanURL
            window.open(url);
        }
        else if (ActChannelID == vm.constActChannelChat ||
            ActChannelID == vm.constActChannelSocialMedia) {
            if (vm.activity.InteractionID) {
                $http.get("http://172.20.229.59:7080/genesys/1/cs/interactions/" + vm.activity.InteractionID + "/structured_text").then(function (r) {
                    if (r.status === 200) {
                        var xml = r.data;
                        var msg = $(xml).find('msgText').text();
                        msg = msg.replace(/(?:\r\n|\r|\n)/g, '<br>');
                        //console.log('hey - ' + msg);
                        //vm.activity.Transcript = msg;
                        //todo: bind this msg to div element
                    }
                });
            }


        }
    }

    function returnResult() {
        var result = null;
        var deferred = $q.defer();
        deferred.reject('');
        result = deferred.promise;
        //$scope.$apply();
        return result;
    }

    /*Button Events END*/

    /*Activity Functions*/
    //Save
    vm.saveActivity = function (arrIsDirty, genQRCodeFlag, isTambahCatatan, isSendEmail, isExit, interactionId) {// 5 = GenQRCode
        vm.isNeedConfirmClose = (vm.activity.ActStatusID == constClosedActStatusID);//if activity status is Closed, set as need confirm(true); if not Closed status , set as false.
        vm.showValidationMsgPopup = false;
        var result = null;
        indicator = 1;//Insert --> Can mean it is New or IsDraft but Not Saved As Draft yet
        if (vm.activity.ActivityID > 0) indicator = 2;  //Update 
        if (vm.IsActivityClose == true) {
            vm.isNeedConfirmClose = false; indicator = 3;
        }  //Closed
        interactionId = interactionId || vm.activity.InteractionID;

        //$scope.terimDocForm.Timbalan.$dirty = false;
        //$scope.terimDocForm.Timbalan.$pristine = true;
        //$scope.terimDocForm.Jabatan.$dirty = false;
        //$scope.terimDocForm.Jabatan.$pristine = true;
        //$scope.terimDocForm.Cawangan.$dirty = false;
        //$scope.terimDocForm.Cawangan.$pristine = true;
        //$scope.terimDocForm.Units.$dirty = false;
        //$scope.terimDocForm.Units.$pristine = true;

        //Populate tempEmail before check form valid
        if (vm.tempEmail && (vm.activity.ActChannelID == vm.constActChannelEmail || vm.activity.ActChannelID == vm.constActChannelCFF)) {

            vm.tempEmail.EmailContent = editor.getData();// editor.getData() != '' ? editor.getData() + (editor.selSignature || '') + constructDefaultEmailEndPart() : '';
            vm.tempEmail.EmailSubject = $('#TempEmail_EmailSubject').val();
            vm.tempEmail.TemplateID = editor.selTemplateID;
            vm.tempEmail.SignatureTemplateID = editor.selSignatureTplID;
            if (editor.checkDirty()) {
                arrIsDirty[2] = true;
                $scope.makPerinciForm.$dirty = true;
                $scope.makPerinciForm["TempEmail_EmailContent"].$pristine = false;
                vm.ActEmailContent_ChangeHistoryDesc = vm.tempEmail.EmailContent;
                $scope.makPerinciForm["TempEmail_EmailContent"].$setViewValue(vm.ActEmailContent_ChangeHistoryDesc);
                ///$scope.makPerinciForm["ActEmail_EmailContent"].$viewValue=vm.ActEmailContent_ChangeHistoryDesc; 
            }

            if (vm.activity.ActChannelID == vm.constActChannelEmail) {
                if (vm.SelectedAliran == vm.constAliranIN) {
                    vm.activity.ActEmail = angular.copy(vm.tempEmail);
                    vm.activity.ActEmail.BCC = null;
                    $scope.makPerinciForm.TempEmail_BCC.$pristine = false;
                    $scope.makPerinciForm["TempEmail_BCC"].$setViewValue('');
                }
                else if (vm.SelectedAliran == vm.constAliranOUT) {
                    vm.activity.ActEmail = angular.copy(vm.tempEmail);
                    vm.activity.ActEmail.EmailReceivedDate = null;
                    $scope.makPerinciForm.ActEmail_EmailReceivedDate.$pristine = false;
                    $scope.makPerinciForm["ActEmail_EmailReceivedDate"].$setViewValue('');
                }
                vm.activity.ActCFF = null;
            }
            else if (vm.activity.ActChannelID == vm.constActChannelCFF) {
                if (vm.SelectedAliran == vm.constAliranOUT) {
                    if (!vm.activity.ActCFF) vm.activity.ActCFF = {
                    };
                    for (var k in vm.tempEmail) vm.activity.ActCFF[k] = vm.tempEmail[k];
                }
                vm.activity.ActEmail = null;
            }
        }
        else {
            vm.activity.ActEmail = null;
            vm.activity.ActCFF = null;
        }

        if (!checkIsFormValid()) {
            vm.showValidationMsgPopup = true;
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            $scope.$apply();
            return returnResult();
        } 


        if (vm.activity.KategoriDocReceived) {
            for (var i = 0; i < vm.activity.KategoriDocReceived.length; i++) {
                var a = $filter('filter')(vm.activity.KategoriDocReceived[i].ActDocReceived, {
                    Checked: true
                }, true);
                if (!a.length) {
                    swal("Gagal", "Sila pilih sekurang-kurangnya satu dokumen bagi setiap kategori dokumen!", "error");
                    return returnResult();
                }
            }
        }

        //if (!isSendEmail && vm.isNeedConfirmClose && vm.SelectedAliran == vm.constAliranOUT && (vm.activity.ActChannelID == vm.constActChannelEmail || vm.activity.ActChannelID == vm.constActChannelCFF)) {
        //    swal({
        //        title: "Closing activity will send email. Are you sure you would like to proceed?",
        //        text: "",
        //        type: "warning",
        //        showCancelButton: true,
        //        confirmButtonText: "Ya",
        //        cancelButtonText: "Tidak",
        //        closeOnConfirm: false,
        //        closeOnCancel: true
        //    }, function (isConfirm) {
        //        if (isConfirm) {
        //            isSendEmail = true;
        //            vm.isNeedConfirmClose = false;
        //            if (genQRCodeFlag) { // if Generate & Print, Generate and Save Activity
        //                vm.genQRCode(arrIsDirty, true, isSendEmail, isExit);
        //                return;
        //            }

        //            if (!(arrIsDirty[0] || arrIsDirty[1] || arrIsDirty[2] || arrIsDirty[3] || vm.GenQRCode)) {
        //                if (!isSendEmail) {
        //                    swal("Gagal", "Tiada perubahan maklumat dilakukan!", "error");
        //                    return returnResult();
        //                }

        //                if (vm.activity.ActivityID > 0 && !vm.activity.IsDraft) {
        //                    sendEmail(isExit);
        //                    return returnResult();
        //                }
        //            }

        //            if (vm.activity.ActivityID > 0 && !vm.activity.IsDraft)
        //                getAllChangeHistory(arrIsDirty);
        //            result = UpdateActivity(indicator, isTambahCatatan, isSendEmail, isExit); //Catatan is in Form as well, if got tambah catatan Form is Dirty
        //            //return result;

        //        } else {
        //            //swal("Batal!", "Permohonan telah dibatalkan.", "error");
        //            result = returnResult();
        //        }
        //    });
        //    console.log('Return Result :  ' + result);
        //    return result == null ? returnResult() : result;
        //}

        var isFormDirty = true;
        //If no change (GenQRCode does not make form dirty ) And Not draft
        if (!(arrIsDirty[0] || arrIsDirty[1] || arrIsDirty[2] || arrIsDirty[3] || vm.GenQRCode || isExit || isHasLinkCaseAction || vm.isselfselectoutbound) && !vm.activity.IsDraft) {

            isFormDirty = false;
            if (!isSendEmail) {
                swal("Gagal", "Tiada perubahan maklumat dilakukan!", "error");
                return returnResult();
            }

            //if (vm.activity.ActivityID > 0 && !vm.activity.IsDraft) {
            //    sendEmail();
            //    return returnResult();
            //}
        }

        if (genQRCodeFlag) { // if Generate & Print, Generate and Save Activity
            vm.genQRCode(arrIsDirty, true);
        }
        else if (isSendEmail) {
            if (isSendEmail) {
                swal({
                    title: 'Hantar emel akan menukar status Aktiviti ini kepada "Selesai". Adakah anda pasti?',
                    text: "",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonText: "Ya",
                    cancelButtonText: "Tidak",
                    closeOnConfirm: false,
                    closeOnCancel: true,
                    showLoaderOnConfirm: true
                }, function (isConfirm) {
                    if (isConfirm) {
                        vm.isNeedConfirmClose = false;
                        if (!isFormDirty && vm.activity.ActivityID > 0 && !vm.activity.IsDraft) {
                            sendEmail();
                            return returnResult();
                        }
                        else {
                            if (vm.activity.ActivityID > 0 && !vm.activity.IsDraft)
                                getAllChangeHistory(arrIsDirty);
                            result = UpdateActivity(indicator, isTambahCatatan, isSendEmail, isExit); //Catatan is in Form as well, if isTambahCatatan == true ,Form is Dirty
                            return result;
                        }
                    }
                    else {
                        return returnResult();
                    }
                });
            }

        }
        else {

            if (vm.activity.ActivityID > 0 && !vm.activity.IsDraft)
                getAllChangeHistory(arrIsDirty);

            if (typeof InteractionHelper !== "undefined") {
                var dispCode = null;

                if (vm.outbound != null && vm.outbound.JenisKempenID != null) {
                    //HRCC - send tindakan susulan
                    if (vm.activity.TindakanSusulanID != null) {
                        var tindakan = $filter('filter')(vm.actTindakanSusulanOptions, {
                            TindakanSusulanID: vm.activity.TindakanSusulanID
                        }, true);

                        if (tindakan.length > 0) {
                            vm.activity.TindakanSusulanDesc = tindakan[0].TindakanSusulanDesc;
                        }
                    }

                    dispCode = vm.activity.TindakanSusulanDesc || '00 Not Applicable';
                }
                else {
                    //HCL - send kategori 123
                    if (vm.activity.Kategori3ID != null) {
                        var kat3 = $filter('filter')(vm.InnerSubKategoriOptions, {
                            Kategori3ID: vm.activity.Kategori3ID
                        }, true);

                        if (kat3.length > 0) {
                            dispCode = kat3[0].DispositionCode3;
                        }
                    }
                    else if (vm.activity.Kategori2ID != null) {
                        var kat2 = $filter('filter')(vm.SubKategoriOptions, {
                            Kategori2ID: vm.activity.Kategori2ID
                        }, true);

                        if (kat2.length > 0) {
                            dispCode = kat2[0].DispositionCode2;
                        }
                    }
                    else if (vm.activity.Kategori1ID != null) {
                        var kat1 = $filter('filter')(vm.MainKategoriOptions, {
                            Kategori1ID: vm.activity.Kategori1ID
                        }, true);

                        if (kat1.length > 0) {
                            dispCode = kat1[0].DispositionCode1;
                        }
                    }

                }
                if (vm.activity.KodSelesaiID) {
                    var kodselesai = $filter('filter')(vm.KodSelesaiOptions, {
                        KodSelesaiID: vm.activity.KodSelesaiID
                    }, true);

                    if (kodselesai.length > 0) {
                        vm.activity.CCCallResultID = kodselesai[0].CCCallResultCode ? kodselesai[0].CCCallResultCode.trim() : null;
                    }


                }

                InteractionHelper.UpdateDisposition(interactionId, dispCode);

                InteractionHelper.UpdateAttachData(interactionId, (vm.activity.CCCallResultID || "") + "|" + (vm.activity.ActivityID || 0));

            }

            result = UpdateActivity(indicator, isTambahCatatan, isSendEmail, isExit); //Catatan is in Form as well, if isTambahCatatan == true ,Form is Dirty
            //return result;
        }
        return result;
    }



    var sendEmail = function (isExit) {
        vm.activity.ActStatusID = constClosedActStatusID;
        // construct model
        var model = {
            EmailFromList: !vm.tempEmail.From ? [] : vm.tempEmail.From.split(';').clean(''),
            EmailToList: !vm.tempEmail.To ? [] : vm.tempEmail.To.split(';').clean(''),
            EmailCCList: !vm.tempEmail.CC ? [] : vm.tempEmail.CC.split(';').clean(''),
            EmailBCCList: !vm.tempEmail.BCC ? [] : vm.tempEmail.BCC.split(';').clean(''),
            EmailBCCList: !vm.tempEmail.BCC ? [] : vm.tempEmail.BCC.split(';').clean(''),
            Content: vm.tempEmail.EmailContent + editor.defaultEmailEndPart,
            Subject: vm.tempEmail.EmailSubject,
            TemplateId: editor.selTemplateID || vm.tempEmail.TemplateID || intDefaultEmailTemplateID,
            ReftableId: vm.activity.ActivityID,
            ActStatusUpdateModel: {
                ActivityID: vm.activity.ActivityID, 
                ActChannelID: vm.activity.ActChannelID,
                ChangeStamp: vm.activity.ChangeStamp
            }
        };

        ActivitySI.closeActivityEmail(model).then(function (r) {
            swal({
                title: "Email is sent successfully", //TODO change message 
                text: GeneralService.SaveMessage.Text,
                type: "success",
                timer: 2500,
                showConfirmButton: true
            }, function () {
                if (isExit) {
                    WindowUnloadEventEnable = false;
                    $window.close();
                } else
                    vm.redirectTo('/activity/profile/detail/' + vm.activity.ActivityID + '?t=' + TabID + '&ty=' + TabType);
            });
        });

    }

    vm.reopenActivity = function () {
        var confirmText = 'Anda telah memilih untuk menukar Status Aktiviti ini dari "Selesai" kepada "Belum Selesai". Adakah anda pasti?';
        swal({
            title: confirmText,
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: true,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {

                var model = {
                    ActivityID: vm.activity.ActivityID,
                    //ActStatusID: constOpenActStatusID,
                    // ActStatus1ID: 2,
                    // ActStatus2ID: 6,
                    ChangeStamp: vm.activity.ChangeStamp
                };
                ActivitySI.reopenActivity(model).then(
                    function (r) {
                        if (r.status == 200) {

                            vm.IsActivityClose = false;
                            checkIsTPAllowEdit();
                            vm.activity.ChangeStamp = r.data.ChangeStamp;
                            vm.activity.ActStatusID = r.data.ActStatusID;
                            vm.activity.ActStatus1ID = r.data.ActStatus1ID;
                            vm.actStatus1Change(vm.activity.ActStatus1ID, true);
                            vm.activity.ActStatus2ID = r.data.ActStatus2ID;
                            vm.actStatus2Change(vm.activity.ActStatus2ID);
                            vm.activity.ActStatus3ID = r.data.ActStatus3ID;
                            setEditorIsReadOnly()
                            vm.dtInstanceActChangesHistory.reloadData();
                            //TODO last updated date
                            swal({
                                title: GeneralService.SaveMessage.Title,
                                text: GeneralService.SaveMessage.Text,
                                type: "success",
                                timer: 2500,
                                showConfirmButton: true
                            });
                        }
                        else swal("Gagal", r.data, "error", 3000, false);
                    });

            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });
    }

    //Delete Activity
    vm.deleteActivity = function () {

        swal({
            title: "Adakah anda pasti untuk menghapuskan aktiviti ini?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: true,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {
                var model = {
                    ActivityID: vm.activity.ActivityID,
                    ActRefNo: vm.activity.ActRefNo,
                    ChangeStamp: vm.activity.ChangeStamp
                };
                ActivitySI.deleteActivity(model).then(function (r) {
                    if (r.status === 200) {
                        if (r.data.IsSuccess == true) {
                            swal({
                                title: "Aktiviti Dihapuskan!",
                                text: "Aktiviti anda telah berjaya dihapuskan!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: true
                            }, function () {
                                vm.redirectTo('/');
                            });
                        } else {
                            swal("Gagal", "Tidak dapat menghapuskan aktiviti ini. Sila semak adakah ia terikat kepada Kes, Tugas atau statusnya selesai.", "error");
                        }
                    }
                });
            }
        });
    };

    //Route to Agent
    vm.routeToAgent = function (arrIsDirty) {
         
        if (arrIsDirty[0] || arrIsDirty[1]) {
            return swal("Gagal!", "Sila simpan aktiviti terlebih dahulu sebelum route to agent.", "error");
        }

        swal({
            title: "Are you sure you want to route to agent?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm: true
        }, function (isConfirm) {
            if (isConfirm) {

                ActivitySI.routeToAgent(vm.activityid).then(function (r) {
                    if (r.status === 200) { 
                        if (r.data) { //true
                            swal({
                                title: "This activity is routed.",
                                text: "",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: true
                            }, function () { //back to home page
                                vm.redirectTo('/');
                            });
                        } else {
                            swal("Gagal!", "This activity is failed to route to agent.", "error");
                        }

                        //if (r.data.StatusCode == 0 && r.data.InteractionID) { //success
                        //    swal({
                        //        title: "This activity is routed.",
                        //        text: "",
                        //        type: "success",
                        //        timer: 2500,
                        //        showConfirmButton: true
                        //    }, function () { //back to home page
                        //        vm.redirectTo('/');
                        //    });
                        //} else { //fail
                        //    swal("Gagal!", "This activity is failed to route to agent.", "error");
                        //}
                    }
                });

            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });
    };

    vm.CFFMainKategoriChanged = function (cffMainKategori) {
        vm.CFFSubKategoriFiltered = [];
        if (cffMainKategori) {
            var m = $filter('filter')(vm.CFFSubKategoriOption, {
                CFFMainKategoriID: cffMainKategori
            }, true);
            if (m && (m.length > 0)) {
                vm.CFFSubKategoriFiltered = m;
            }
        }
    };

    vm.CFFSubKategoriChanged = function (cffSubKategori) {
        if (cffSubKategori) {
             
            var m = $filter('filter')(vm.CFFSubKategoriOption, {
                CFFKategoriID: cffSubKategori
            }, true);
            if (m && (m.length > 0)) {
                vm.activity.Kategori1ID = m[0].Kategori1ID;
                if (vm.activity.Kategori2ID) {
                    vm.activity.Kategori2ID = null;
                }
                if (vm.activity.Kategori3ID) {
                    vm.activity.Kategori3ID = null;
                }

                vm.activity.Kategori1ID.$dirty = true;
                vm.activity.Kategori1ID.$pristine = false;
                var kategori1Name = "";
                var n = $filter('filter')(vm.MainKategoriOptions, {
                    Kategori1ID: vm.activity.Kategori1ID
                }, true);
                if (n && (n.length > 0)) {
                    kategori1Name = n[0].Kategori1Name;
                }
                vm.ChangesHistory.push({
                    ID: vm.activity.ActivityID,
                    FieldName: "Kategori1Name",
                    DisplayName: "Kategori",
                    OldValue: '',
                    NewValue: vm.activity.Kategori1ID == null ? "" : kategori1Name,
                    IsChanged: !vm.activity.Kategori1ID.$pristine
                });

            }
        }
    };

    //Gen QR Code
    vm.genQRCode = function (arrIsDirty, isSave, isSendEmail, isPreview, e, isExit) {
        vm.GenQRCode = true; //Don't have to check form is dirty when save as gen QR Code means there is changes

        var modelKategoriDocReceived = [];
        var modelDocumentDetailsByID = [];
        var arrDocumentDetails = [];

        if (vm.activity.KategoriDocReceived) {
            modelKategoriDocReceived = angular.copy(vm.activity.KategoriDocReceived);

            for (var i = 0; i < modelKategoriDocReceived.length; i++) {
                for (var j = 0; j < modelKategoriDocReceived[i].ActDocReceived.length; j++) {
                    if (modelKategoriDocReceived[i].ActDocReceived[j].Checked) {
                        //modelKategoriDocReceived[i].ActDocReceived[j].DocCategory = modelKategoriDocReceived[i].KategoriDocName;
                        modelKategoriDocReceived[i].ActDocReceived[j].DocCatCode = modelKategoriDocReceived[i].KategoriDocCode;
                        modelKategoriDocReceived[i].ActDocReceived[j].DocDate = new Date(modelKategoriDocReceived[i].ActDocReceived[j].TarikhDokumen);//$filter('date')(new Date(modelKategoriDocReceived[i].ActDocReceived[j].TarikhDokumen), $scope.DateFormat);
                        modelKategoriDocReceived[i].ActDocReceived[j].TT = modelKategoriDocReceived[i].ActDocReceived[j].TahunTaksiran;
                        modelDocumentDetailsByID.push(modelKategoriDocReceived[i].ActDocReceived[j]);
                    }
                }
            }

            if (modelDocumentDetailsByID.length > 0) {
                var modelDocumentDetails = {
                    ActRefID: vm.activity.ActRefNo || "",
                    DocDtlsByID: modelDocumentDetailsByID
                }
                arrDocumentDetails.push(modelDocumentDetails);
            }

        }

        if (vm.activity.NotaTemuduga != null)
            var model = {
                RefID: vm.activity.ActRefNo || "",
                TaxRefNo: vm.activity.TPNoCukai ? vm.activity.TPNoCukai.substring(vm.activity.TPNoCukai.indexOf(" ") + 1) : "",
                FileType: vm.activity.TPNoCukai ? vm.activity.TPNoCukai.substring(0, vm.activity.TPNoCukai.indexOf(" ")) : "",
                ReceiveDate: vm.activity.NotaTemuduga.NTTarikhTerima ? vm.activity.NotaTemuduga.NTTarikhTerima : "",
                ActionBranch: $('#NotaTemuduga_NTCawTindakanName')[0].selectedIndex == 0 ? "" : $('#NotaTemuduga_NTCawTindakanName')[0].options[$('#NotaTemuduga_NTCawTindakanName')[0].selectedIndex].text,
                Unit: vm.activity.NotaTemuduga.NTUnit != null ? vm.activity.NotaTemuduga.NTUnit.DisplayName : "",
                IsSuratKeluar: vm.activity.NotaTemuduga.NTStatusSuratKeluar ? "true" : "false",
                IsSegera: vm.activity.NotaTemuduga.NTStatusSegera ? "true" : "false",
                IsNoTindakan: vm.activity.NotaTemuduga.NTStatusTidakPerluTindakan ? "true" : "false",
                IsCetakSurat: vm.activity.NotaTemuduga.NTStatusCetakSurat ? "true" : "false",
                DocDtls: arrDocumentDetails
            };


        QRCodeSI.genQRcode(model).then(function (r) {
            if (r.status === 200) {
                if (vm.activity.NotaTemuduga == null) vm.activity.NotaTemuduga = {
                };
                vm.activity.NotaTemuduga.QRCode = r.data;
                vm.activity.NotaTemuduga.QRCodeDate = moment(new Date()).format('DD MMM YYYY hh:mm:ss A');

                addQRCodeGeneratedCSS();
                if (isPreview) {
                    PrintPenerimaanDocument(r.data, e);
                }

                indicator = 1;//Insert
                if (vm.activity.ActivityID > 0) indicator = 2; //Update  
                if (vm.IsActivityClose == true) indicator = 3; //Closed

                if (isSave) { // If Save
                    if (checkIsFormValid()) {
                        //save case or insert case 
                        if (vm.activity.ActivityID > 0 && !vm.activity.IsDraft)
                            getAllChangeHistory(arrIsDirty);
                        UpdateActivity(indicator, false, isSendEmail, isExit);
                    }
                    else {
                        vm.showValidationMsgPopup = true;
                        swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
                    }
                }
            }
        });
    };

    function SaveDraft() {
    }

    function addQRCodeGeneratedCSS() {
        $('.tblGeneralPenerimaanDoc').toggleClass('qrCode-generated', true);
    }

    //Call API

    function UpdateActivity(indicator, isTambahCatatan, isSendEmail, isExit) {
        var result = null;
        blnIsSaveDraft = false;

        var activityModel = angular.copy(vm.activity);

        if (activityModel.ActivityID > 0) {
            blnIsSaveDraft = activityModel.IsDraft ? true : false;
            activityModel.IsDraft = false
        }
        activityModel.ActCatatans = null;
        if (vm.activity.ActCatatans) {
            for (var i = 0; i < vm.activity.ActCatatans.length; i++) {
                if (vm.activity.ActCatatans[i].CatatanID < 0) {

                    if (!activityModel.ActCatatans)
                        activityModel.ActCatatans = [];

                    activityModel.ActCatatans.push(vm.activity.ActCatatans[i]);
                } 
            }
        }

        if (vm.IsShowVerificationTab == false)
            activityModel.ActVerification = null;

        var actUpdate = {
            Activity: activityModel,
            ChangeHistory: vm.ChangesHistory,
            IsEditTPData: vm.isEditTPData,
            IsEditAnsuranActData: vm.isEditAnsuranActData,
            IsSelfSelectOutbound: vm.isselfselectoutbound,
            IsSaveDraft: blnIsSaveDraft
        };

        actUpdate = consolidateBeforeSave(actUpdate);

        !activityModel.IsDraft && constructOutboundModel(actUpdate);

        //if ActStatus == Completed, prompt confirm msg.
        if (actUpdate.Activity.ActStatusID == constClosedActStatusID && vm.isNeedConfirmClose) {
            swal({
                title: 'Anda telah memilih untuk menukar Status Aktiviti ini dari "Belum Selesai" kepada "Selesai". Adakah anda pasti?',
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Ya",
                cancelButtonText: "Tidak",
                closeOnConfirm: false,
                closeOnCancel: true//,
                //showLoaderOnConfirm: !blnIsSaveDraft
            }, function (isConfirm) {
                if (isConfirm) {
                    $(".confirm").attr('disabled', 'disabled'); //Prevent Double Click by user.
                    result = SaveActivity(actUpdate, indicator, isTambahCatatan, isSendEmail, isExit);
                } else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                    return returnResult();
                }
            });
        } else {
            result = SaveActivity(actUpdate, indicator, isTambahCatatan, isSendEmail, isExit);
        }

        return result == null ? returnResult() : result;
    }

    function SaveActivity(actUpdate, indicator, isTambahCatatan, isSendEmail, isExit) {
        var result = null;
        var data = ActivitySI.saveActivity(actUpdate);
        result = data;
        data.then(function (r) {
            if (r.status === 200) {
                vm.activity.ActivityID = r.data.ActivityID;
                vm.activity.ChangeStamp = r.data.ChangeStamp;
                //to cater for draft only
                vm.activity.AssignedOfficerName = r.data.Activity.AssignedOfficerName;
                vm.activity.AssignedOfficerLogin = r.data.Activity.AssignedOfficerLogin;
                vm.activity.AssignedOfficerEmail = r.data.Activity.AssignedOfficerEmail;
                vm.activity.AssignedDateTime = r.data.Activity.AssignedDateTime;
                vm.activity.CreatedBy = r.data.Activity.CreatedBy;
                vm.activity.CreatedByName = r.data.Activity.CreatedByName;
                vm.activity.CreatedDateTime = r.data.Activity.CreatedDateTime;

                if (vm.SessionKey && indicator == 1) { //For new activity and has session key  //TODO! 
                    ActivitySessionService.setActSession(vm.SessionKey, vm.activity.ActivityID);
                }

                sessionStorage.removeItem('draftID'); //Clear draftid
                if (vm.activity.IsDraft && !blnIsSaveDraft) {
                    sessionStorage.draftID = JSON.stringify(vm.activity.ActivityID);
                    
                    InteractionHelper.UpdateAttachData(interactionId, (vm.activity.CCCallResultID || "") + "|" + (vm.activity.ActivityID || 0));

                    return;
                }
              
                if (isTambahCatatan || (vm.ActCatatan && vm.ActCatatan.Catatan)) {
                    vm.ActCatatan.ActivityID = vm.activity.ActivityID;
                    AddNewActCatatan(true, isSendEmail); //If got TambahCatatan in save, it is new activity
                    return;
                }

                if (isSendEmail) {
                    sendEmail(isExit);
                    return;
                }

                swal({
                    title: GeneralService.SaveMessage.Title,
                    text: GeneralService.SaveMessage.Text,
                    type: "success",
                    timer: 2500,
                    showConfirmButton: true
                }, function () {
                    if (isExit) {
                        WindowUnloadEventEnable = false;
                        window.opener = "";
                        window.close();
                    } else
                        vm.redirectTo('/activity/profile/detail/' + r.data.ActivityID + '?t=' + TabID + '&ty=' + TabType);
                });

            }
        });
        return result;
    }

    function constructOutboundModel(actUpdate) {

        if (vm.outbound) {
            actUpdate.Outbound = {
                OutboundID: vm.activity.OutboundID, //Only integration or those that exists in db
                JenisKempenId: vm.outbound.JenisKempenID,
                ReMSDataID: vm.outbound.DataID,
                Kategori1ID: vm.activity.Kategori1ID,
                Kategori2ID: vm.activity.Kategori2ID,
                Kategori3ID: vm.activity.Kategori3ID,
                EmailTemplateID: vm.tempEmail ? vm.tempEmail.TemplateID : null
            };

            actUpdate.OutboundInfo = {
                ReMSTableName: vm.outbound.JenisKempenDetails.ReMSTableName,
                JenisKempenKategoriSysID: vm.outbound.JenisKempenDetails.JenisKempenKategoriSysID,
                IsCancelVoiceQueue: vm.outbound.StatusID == constOutboundStatusInQueue && vm.isselfselectoutbound && (!vm.activity.ActivityID || vm.activity.IsDraft) ? true : false,
                CCCampaignName: vm.CCCampaignName,
                OutboundPhone: vm.outbound.PHONE1 || vm.outbound.PHONE2 || vm.outbound.PHONE3
            }
        }
    }

    function checkIsFormValid() {

        if (vm.ActCatatan.CatatanAttachmentList && vm.ActCatatan.CatatanAttachmentList.length > 0 && !vm.ActCatatan.Catatan) {
            vm.showRequiredMsg = true;
            isCatatanComplete=false;
        }
        else {
            vm.showRequiredMsg = false;
            isCatatanComplete = true;
        }

        return $scope.makAmForm.$valid && $scope.verificationForm.$valid && $scope.makPerinciForm.$valid && $scope.terimDocForm.$valid && isCatatanComplete;
    }

    function getAllChangeHistory(arrIsDirty) {
        // isForm1Dirty, isForm2Dirty, isForm3Dirty, isForm4Dirty
        var form = {
        };
        for (i = 0; i < arrIsDirty.length; i++) {
            if (arrIsDirty[i] == true) { //IfDirty , only loop form to get change history
                switch (i + 1) {
                    case 1:
                        form = $scope.makAmForm;
                        getChangeHistorybyForm(form, "makAmForm");
                        break;
                    case 2:
                        form = $scope.verificationForm;
                        getChangeHistorybyForm(form, "verificationForm");
                        break;
                    case 3:
                        for (j = 0; j < vm.DeletedAddKategoris.length; j++) {
                            $scope.makPerinciForm["AdditionalKategoris_" + vm.DeletedAddKategoris[j].ActAddKategoriID.toString()].$pristine = false;
                        }

                        if (vm.activity.AdditionalKategoris) {
                            for (j = 0; j < vm.activity.AdditionalKategoris.length; j++) {
                                if (vm.activity.AdditionalKategoris[j].ActAddKategoriID == 0) {
                                    $scope.makPerinciForm["AdditionalKategoris_0:" + j.toString()].$pristine = false;
                                }
                            }
                        }
                        form = $scope.makPerinciForm;
                        getChangeHistorybyForm(form, "makPerinciForm");
                        break;
                    case 4:
                        if (vm.deletedKategoriDoc) {
                            for (k = 0; k < vm.deletedKategoriDoc.length; k++) {
                                $scope.terimDocForm["ActDocReceived_" + vm.deletedKategoriDoc[k].DocListID.toString()].$pristine = false;
                            }
                        }
                        form = $scope.terimDocForm;
                        getChangeHistorybyForm(form, "terimDocForm");
                        break;

                }
            }
        }

    }

    function getChangeHistorybyForm(form, formName) {
        angular.forEach(form, function (value, key) {
            if (key.indexOf("KategoriDoc") < 0) //field name added for field validation, to skip kategori doc change history
            {
                if (key[0] == '$') return;

                var displayName = $(document.getElementById(key)).data('displayfield');
                var takeLabelText = $(document.getElementById(key)).data('takelabeltext');
                var i = key.toString().indexOf(':');
                var key2 = null;
                if (i != -1) {
                    key2 = key.substring(0, i);
                }
                if (value.$pristine == false || value.$dirty == true) {

                    //get new value
                    var newvalue = "";
                    if ($(document.getElementById(key))[0].tagName == 'SELECT' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                        if ($(document.getElementById(key))[0].selectedIndex && $(document.getElementById(key))[0].selectedIndex >= 0) {
                            newvalue = $(document.getElementById(key))[0].options[$(document.getElementById(key))[0].selectedIndex].text;
                        }
                    }
                    else if ($(document.getElementById(key))[0].tagName == 'INPUT' && $(document.getElementById(key))[0].type == 'radio' && $(document.getElementById(key))[0].parentElement.nodeName == "LABEL" && takeLabelText && (value.$viewValue !== '' || value.$viewValue !== null)) {
                        newvalue = $(document.getElementById(key))[0].parentElement.innerText.trim();
                    }
                    else if ($(document.getElementById(key))[0].tagName == 'INPUT' && $(document.getElementById(key))[0].type == 'checkbox') {
                        //newvalue= value.$modelValue == true ? 'Ya' : 'Tidak';
                        if (value.$modelValue) {
                            newvalue = 'Ya';
                        }
                        else if (value.$modelValue == false) {
                            newvalue = 'Tidak';
                        }
                        else
                            newvalue = '';
                    }
                    else if ($(document.getElementById(key))[0].tagName == 'DIV' && value.$viewValue != null) //ui-select
                    {
                        var strInnerText = $(document.getElementById(key))[0].innerText.trim();
                        var intLineBreak = strInnerText.search(/\n/);
                        if (intLineBreak > 0)
                            newvalue = strInnerText.substring(0, strInnerText.search(/\n/));
                        else
                            newvalue = strInnerText;
                    }
                    else {
                        newvalue = value.$viewValue;
                    }

                    //if (displayName && formName == "makAmForm" && vm.isEditTPData == false)
                    //    vm.isEditTPData = displayName.indexOf("Pembayar Cukai") != -1 ? true : false;

                    if (vm.activity.ActEmail) {
                        if (key && formName == "makPerinciForm") {
                            key = key.toString().replace("TempEmail", "ActEmail");
                        }
                    }
                    else if (vm.activity.ActCFF) {
                        if (key && formName == "makPerinciForm") {
                            key = key.toString().replace("TempEmail", "ActCFF");
                        }
                    }

                    vm.ChangesHistory.push({
                        ID: vm.activity.ActivityID,
                        FieldName: key2 || key,
                        DisplayName: displayName,
                        OldValue: '',
                        NewValue: newvalue == null ? "" : newvalue,
                        IsChanged: !value.$pristine
                    });
                }
            }
        });
    }
    /*Activity Functions END*/

    //Additional Kategori - Start
    var addKategoriForEdit = null;
    vm.DeletedAddKategoris = [];

    vm.openAddKategori = function (e) {
        angular.element("#EditAddKategoriButton").text("Tambah");
        vm.openDialogV2(e, '#AddKategoriDialog');
    }

    vm.closeAddKategori = function () {
        //Reset selectedAddKategori
        //vm.selectedAddKategoriIndex = null;
        //vm.selectedEditKategoriID = null;
        vm.AddSubKategoriOptions = [];
        vm.AddInnerSubKategoriOptions = [];
        vm.selectedAddKategori1 = null;
        vm.selectedAddKategori2 = null;
        vm.selectedAddKategori3 = null;
        vm.AddKategoriDesc = "";
        vm.showAddKategori1RequiredMsg = false;
        addKategoriForEdit = null;
        vm.close();
    }

    vm.addKategori = function () {

        vm.showAddKategori1RequiredMsg = false;
        if (!vm.selectedAddKategori1) {
            vm.showAddKategori1RequiredMsg = true;
            return;
        }

        vm.activity = vm.activity == null ? {
        } : vm.activity;
        vm.activity.AdditionalKategoris = vm.activity.AdditionalKategoris == null ? [] : vm.activity.AdditionalKategoris;
        var selectedActAddKategoriID = addKategoriForEdit ? addKategoriForEdit.ActAddKategoriID : 0;

        var kategoriToAdd = {
            //AddKategoriIndex: vm.selectedAddKategoriIndex,
            ActAddKategoriID: selectedActAddKategoriID,
            Kategori1ID: vm.selectedAddKategori1.Kategori1ID,
            Kategori1Name: vm.selectedAddKategori1.Kategori1Name,
            Kategori2ID: vm.selectedAddKategori2 ? vm.selectedAddKategori2.Kategori2ID : null,
            Kategori2Name: vm.selectedAddKategori2 ? vm.selectedAddKategori2.Kategori2Name : null,
            Kategori3ID: vm.selectedAddKategori3 ? vm.selectedAddKategori3.Kategori3ID : null,
            Kategori3Name: vm.selectedAddKategori3 ? vm.selectedAddKategori3.Kategori3Name : null,
            Description: vm.AddKategoriDesc
        };
        kategoriToAdd.ChangeHistoryDesc = "Kategori : " + (kategoriToAdd.Kategori1Name || "-") + " ;<br/> Sub Kategori : " + (kategoriToAdd.Kategori2Name || "-") + " ;<br/> Sub-sub Kategori : " + (kategoriToAdd.Kategori3Name || "-") + " ;<br/> Catatan : " + (kategoriToAdd.Description || "-");

        if (!addKategoriForEdit) {
            //Add
            vm.activity.AdditionalKategoris.push(angular.copy(kategoriToAdd));
        }
        else {
            //Edit  
            var index = vm.activity.AdditionalKategoris.indexOf(addKategoriForEdit);
            if (index != -1) {
                vm.activity.AdditionalKategoris[index] = kategoriToAdd; //Replace  
                $scope.makPerinciForm.$dirty = true;
                $scope.makPerinciForm["AdditionalKategoris_" + selectedActAddKategoriID.toString() + ":" + index.toString()].$pristine = false;
            }
        }

        vm.AddSubKategoriOptions = [];
        vm.AddInnerSubKategoriOptions = [];
        vm.selectedAddKategori1 = null;
        vm.selectedAddKategori2 = null;
        vm.selectedAddKategori3 = null;
        addKategoriForEdit = null;
        vm.AddKategoriDesc = "";

        vm.close();
    }
     
    vm.showEditKategoriPopup = function (e, objAddKategoriForEdit) {

        angular.element("#EditAddKategoriButton").text("Kemaskini");
        addKategoriForEdit = objAddKategoriForEdit;

        vm.AddSubKategoriOptions = [];
        vm.AddInnerSubKategoriOptions = [];

        vm.AddKategoriDesc = addKategoriForEdit.Description;
        var m = $filter('filter')(vm.MainKategoriOptions, {
            Kategori1ID: addKategoriForEdit.Kategori1ID
        }, true);
        if (m && (m.length > 0)) {
            vm.AddSubKategoriOptions = m[0].SubKategori;
            vm.selectedAddKategori1 = m[0];

            if (vm.AddSubKategoriOptions && vm.AddSubKategoriOptions.length != 0) {
                var n = $filter('filter')(vm.AddSubKategoriOptions, {
                    Kategori2ID: addKategoriForEdit.Kategori2ID
                }, true);
                if (n && n.length != 0) {
                    vm.AddInnerSubKategoriOptions = n[0].InnerSubKategori;
                    vm.selectedAddKategori2 = n[0];
                }
            }

            if (vm.AddInnerSubKategoriOptions && vm.AddInnerSubKategoriOptions.length != 0) {
                var q = $filter('filter')(vm.AddInnerSubKategoriOptions, {
                    Kategori3ID: addKategoriForEdit.Kategori3ID
                }, true);
                if (q && q.length != 0) {
                    vm.selectedAddKategori3 = q[0];
                }
            }
        }
        vm.openDialog(e, '#AddKategoriDialog')
    }

    vm.deleteAdditionalKategori = function (item) {
        swal({
            title: "Adakah anda pasti untuk menghapuskan tambahan kategori pertanyaan ini?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: true,
            closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                var index = vm.activity.AdditionalKategoris.indexOf(item);
                if (index != -1) {
                    vm.activity.AdditionalKategoris.splice(index, 1);

                    //Do history
                    if (item.ActAddKategoriID) {
                        $scope.makPerinciForm.$dirty = true;
                        vm.DeletedAddKategoris.push({
                            ActAddKategoriID: item.ActAddKategoriID, ChangeHistoryDesc: ""
                        });
                    }

                    $scope.$apply();
                }
            }
        });
    }

    //Additional Kategori - End

    //Kategori Dokumen- Start
    vm.actDocReceivedCheckboxToggled = function (event, idxDoc, katDoc) {
        var idxKategoriDoc = vm.activity.KategoriDocReceived.indexOf(katDoc);

        if (!event.target.checked) {
            vm.activity.KategoriDocReceived[idxKategoriDoc].ActDocReceived[idxDoc].Copy = null;
            vm.activity.KategoriDocReceived[idxKategoriDoc].ActDocReceived[idxDoc].TarikhDokumen = null;
            vm.activity.KategoriDocReceived[idxKategoriDoc].ActDocReceived[idxDoc].TahunTaksiran = null;
            vm.activity.KategoriDocReceived[idxKategoriDoc].ActDocReceived[idxDoc].Remarks = null;
        }
        else {
            vm.activity.KategoriDocReceived[idxKategoriDoc].ActDocReceived[idxDoc].Copy = '1';
            vm.activity.KategoriDocReceived[idxKategoriDoc].ActDocReceived[idxDoc].TarikhDokumen = new Date();// moment().format($scope.DateFormat);
            vm.activity.KategoriDocReceived[idxKategoriDoc].ActDocReceived[idxDoc].TahunTaksiran = new Date().getFullYear();//moment().format('YYYY');
        }

        genKategoriDocChangeHistory(idxKategoriDoc);
        $scope.terimDocForm["ActDocReceived_" + vm.activity.KategoriDocReceived[idxKategoriDoc].DocListID].$pristine = false;

    }

    vm.validateFieldChanged = function (katDoc) {
        form = $scope.terimDocForm;
        //console.log('gen doc history');
        //console.log(katDoc);
        var idxKategoriDoc = vm.activity.KategoriDocReceived.indexOf(katDoc);
        if (vm.activity.KategoriDocReceived[idxKategoriDoc].DocListID) //if existing doc and field has been changed
        {
            for (i = 0; i < vm.activity.KategoriDocReceived[idxKategoriDoc].ActDocReceived.length; i++) {
                if (!vm.activity.KategoriDocReceived[idxKategoriDoc].ActDocReceived[i].Copy && vm.activity.KategoriDocReceived[idxKategoriDoc].ActDocReceived[i].Checked) //set 0 for copy if empty
                    vm.activity.KategoriDocReceived[idxKategoriDoc].ActDocReceived[i].Copy = 0;
                //var id = vm.activity.KategoriDocReceived[idxKategoriDoc].ActDocReceived[i].ActDocReceivedID;
                //if (id) {
                //    {
                genKategoriDocChangeHistory(idxKategoriDoc);
                $scope.terimDocForm["ActDocReceived_" + vm.activity.KategoriDocReceived[idxKategoriDoc].DocListID].$pristine = false;
                //    }
                //} 
            }
        }
    }

    function genKategoriDocChangeHistory(idxKategoriDoc) {
        var changedKategoriDoc = vm.activity.KategoriDocReceived[idxKategoriDoc];
        var i;
        var desc = "";

        for (i = 0; i < changedKategoriDoc.ActDocReceived.length; i++) {
            if (changedKategoriDoc.ActDocReceived[i].Checked) {
                var remarks = changedKategoriDoc.ActDocReceived[i].Remarks ? changedKategoriDoc.ActDocReceived[i].Remarks : "-";
                var copy = changedKategoriDoc.ActDocReceived[i].Copy ? changedKategoriDoc.ActDocReceived[i].Copy : "0";
                var tarikh = changedKategoriDoc.ActDocReceived[i].TarikhDokumen ? moment(changedKategoriDoc.ActDocReceived[i].TarikhDokumen).format('DD MMM YYYY') : "-";
                var tahun = changedKategoriDoc.ActDocReceived[i].TahunTaksiran ? changedKategoriDoc.ActDocReceived[i].TahunTaksiran : "-";

                desc += "Nama Dokumen: " + changedKategoriDoc.ActDocReceived[i].DocName + ";<br/> Salinan: " + copy + ";<br/> Tarikh Dokumen: " + tarikh + ";<br/> Tahun Taksiran: " + tahun + ";<br/> Catatan: " + remarks + "<br/><br/>";
            }
        }

        if (desc)
            vm.activity.KategoriDocReceived[idxKategoriDoc].ChangeHistoryDesc = vm.activity.KategoriDocReceived[idxKategoriDoc].KategoriDocName + "<br/>" + desc;
        else
            vm.activity.KategoriDocReceived[idxKategoriDoc].ChangeHistoryDesc = "";
    }

    vm.openKategoriDocDialog = function (e) {
        vm.openDialogV2(e, '#KategoriDocDialog');
    }

    vm.closeKategoriDocDialog = function () {
        vm.close();
    }

    vm.addKategoriDoc = function () {
        if (vm.kategoriDocSelected) {
            vm.kategoriDokumenExist = false;

            if (!vm.activity.KategoriDocReceived)
                vm.activity.KategoriDocReceived = [];

            //check if kategori dokumen exists
            if ($filter('filter')(vm.activity.KategoriDocReceived, {
                DocListID: vm.kategoriDocSelected
            }, true).length > 0) {
                vm.kategoriDokumenExist = true;
                vm.close();
                return;
            }
            else {

                var a = $filter('filter')(vm.RefDocList, {
                    DocListID: vm.kategoriDocSelected
                }, true);
                if (a.length > 0) {
                    //insert kategori doc
                    vm.activity.KategoriDocReceived.push(a[0]);

                    //add documents to kategori
                    var idx = vm.activity.KategoriDocReceived.length - 1;
                    //if (!vm.activity.KategoriDocReceived[idx].ActDocReceived)
                    vm.activity.KategoriDocReceived[idx].ActDocReceived = [];

                    var b = $filter('filter')(vm.RefDocList, {
                        DocListID: vm.kategoriDocSelected
                    }, true);
                    if (b.length > 0)
                        b[0].DocListDetail.sort(function compare(a, b) {
                            return a.DocName.localeCompare(b.DocName)
                        });
                    for (i = 0; i < b[0].DocListDetail.length; i++) {
                        var obj = b[0].DocListDetail[i];
                        obj.Checked = false;
                        obj.Copy = '';
                        obj.TahunTaksiran = '';
                        obj.TarikhDokumen = '';
                        obj.Remarks = '';

                        vm.activity.KategoriDocReceived[idx].ActDocReceived.push(obj);
                    }
                    //console.log(vm);
                }
                vm.close();
            }
        }
        return;
    }

    vm.deletedKategoriDoc = [];

    vm.deleteKategoriDoc = function (item) {
        swal({
            title: "Are you sure you want to delete this Kategori Dokumen?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: true,
            closeOnCancel: true
        }, function (isConfirm) {
            if (isConfirm) {
                vm.kategoriDokumenExist = false;

                $scope.terimDocForm.$dirty = true;
                vm.deletedKategoriDoc.push({
                    DocListID: item.DocListID, ChangeHistoryDesc: ""
                });
                vm.activity.KategoriDocReceived.splice(vm.activity.KategoriDocReceived.indexOf(item), 1);
                $scope.$apply();
            }
        });

    };
    //Kategori Dokumen - End

    /*Search TP*/
    function checkSearchTPCriteria() {
        vm.showRequireSearchIDType = false;
        vm.showRequireSearchIDNo = false;
        vm.invalidSearchRujukanNo = false;
        vm.SearchTP.InvalidSearch = false;
        vm.ShowNoneSearchTPResult = false;
        if (!vm.SearchTP.NoCukai && !vm.SearchTP.IDType && !vm.SearchTP.IDNo) {
            vm.SearchTP.InvalidSearch = true;
            return false;
        }

        if (vm.SearchTP.IDType && !vm.SearchTP.IDNo && !vm.SearchTP.NoCukai) {
            vm.showRequireSearchIDNo = true;
            return false;
        }

        if (vm.SearchTP.IDNo && !vm.SearchTP.IDType) {
            vm.showRequireSearchIDType = true;
            return false;
        }

        if (vm.SearchTP.NoCukai && vm.SearchTP.NoCukai.length < 6) {
            vm.invalidSearchRujukanNo = true;
            return false;
        }

        return true;
    }


    function checkIsTPAllowEdit() {
        
        vm.TPAllowEdit = TaxPayerService.TP.AllowEdit = !(vm.activity.ActivityID && !vm.activity.IsDraft && vm.activity.CaseID || vm.IsActivityClose);
        // Only overide with Search tp profile access if Allow Edit is true
        if (TaxPayerService.TP.AllowEdit) {
            TaxPayerService.TP.AllowEdit = (vm.SearchTProfileAccess == undefined || vm.SearchTProfileAccess == null) ? TaxPayerService.TP.AllowEdit : vm.SearchTProfileAccess;
        }
    }

    vm.searchTaxPayer = function () {

        if (!checkSearchTPCriteria()) {
            return;
        }

        vm.IsSearchTPLoading = true;
        var model = {
            IDTypeID: vm.SearchTP.IDType ? vm.SearchTP.IDType.Value : null,
            IDNo: vm.SearchTP.IDNo,
            NoCukai: vm.SearchTP.NoCukai
            //IsCukaiExact: vm.SearchTP.IsExact
        };
        TaxPayerSI.searchTP(model).then(function (r) {
            vm.IsSearchTPLoading = false;
            if (r.status === 200) {
                vm.lstTP = r.data || [];
                if (vm.lstTP.length != 0) {
                    vm.ShowSearchTPResult = true;
                    vm.ShowNoneSearchTPResult = false;
                }
                else {
                    vm.ShowNoneSearchTPResult = true;
                    vm.ShowSearchTPResult = false;
                }
            }
        });

    }

    var isDummyTP = false;
    vm.selectDummyTP = function () {

        vm.SearchTP.IDType = null;

        var a = $filter('filter')(vm.JenisPengenalanOptions, {
            Code: vm.constDummyTPIDType
        }, true);

        if (a && a.length != 0)
            vm.SearchTP.IDType = a[0];

        isDummyTP = true;

        vm.SearchTP.IDNo = vm.constDummyTPIDNumber;

        if (vm.SearchTP.IDType && vm.SearchTP.IDNo) {

            vm.selectTaxPayer(0);
        }
        else
            return;
    }

    vm.selectTaxPayer = function (TPID) {
        if (vm.IsSearchPelanggan == false) { // Search for TP

            vm.activity.TP = null;
            vm.activity.ActVerification = null;

            if (!isNewActFirstLoad)
                clearActivityTPDetails();

            if (TPID > 0) { //TP exists in system

                vm.activity.IsOrphanActivity = false;
                var m = $filter('filter')(vm.lstTP, {
                    TPID: TPID
                }, true);

                //Bind TP details
                vm.activity.TP = m[0];
                // get view verification tab access
                if (vm.activity.TP != null && vm.activity.TP != undefined)
                    vm.ViewVerificationTab = vm.activity.TP.ViewVerificationTab;
                else
                    vm.ViewVerificationTab = false;

                bindActivityTPDetailsByTP();

                //clear search result list
                vm.lstTP = [];
            }
            else { //Orphan TP search result 
                vm.ViewVerificationTab = true;
                vm.activity.IsOrphanActivity = true;
                // CT Change Orphan here
                if (vm.SearchTP.IDNo && vm.SearchTP.IDType) {//Done in code for orphan TP  - changed as bug when orphan for Resend Email
                    vm.activity.TPIDType = vm.SearchTP.IDType.Value;
                    vm.activity.TPIDNumber = vm.SearchTP.IDNo;
                    vm.activity.TPJenisPengenalan = vm.SearchTP.IDType.Text;

                    if (isDummyTP)
                        vm.activity.TPName = vm.constDummyTPName;
                }
            }

            var objTP = {
                TPID: vm.activity.TP ? vm.activity.TP.TPID : null,
                TPName: vm.activity.TPName,
                TPJenisPengenalan: vm.activity.TPJenisPengenalan,
                TPIDNumber: vm.activity.TPIDNumber,
                TPNoCukai: vm.activity.TPNoCukai
            };
            bindHeader(objTP, vm.activity.TP);
            blnIsTPSearched = true;
            bindPelangganOnNewActFirstLoad();

            $scope.makAmForm.$dirty = true;
            $scope.makAmForm["TPName"].$pristine = false;
            $scope.makAmForm["TPNoCukai"].$pristine = false;
            $scope.makAmForm["TPIDNumber"].$pristine = false;
            $scope.makAmForm["TPJenisPengenalan"].$pristine = false;
            $scope.makAmForm["TPTelefon"].$pristine = false;
            $scope.makAmForm["TPEmail"].$pristine = false;
            $scope.makAmForm["TPEmailMB"].$pristine = false;
            $scope.makAmForm["TPTelefonMB"].$pristine = false;
            $scope.makAmForm["TPTelefonPejabat"].$pristine = false;
            $scope.makAmForm["TPFBDisplayName"] && ($scope.makAmForm["TPFBDisplayName"].$pristine = false);
            $scope.makAmForm["TPFBID"] && ($scope.makAmForm["TPFBID"].$pristine = false);
            $scope.makAmForm["TPTWDisplayName"] && ($scope.makAmForm["TPTWDisplayName"].$pristine = false);
            $scope.makAmForm["TPTWID"] && ($scope.makAmForm["TPTWID"].$pristine = false);

            //clear Case linked
            if (!isNewActFirstLoad) {
                vm.case.CaseRefNo = "";
                vm.case = {
                };
                vm.activity.CaseID = null;
                vm.showcase = false;
                vm.ShowCaseSummaryTab = false;
                tabAction("01", "Profile"); //focus in MaklumatAm tab 
            }
        }
        else { //Search for Pelanggan

            if (TPID > 0) {
                //filter TPID from lstTP
                var m = $filter('filter')(vm.lstTP, {
                    TPID: TPID
                }, true);
                //Bind Pelanggan details
                vm.activity.PelangganTPID = m[0].TPID;
                vm.activity.PelangganNama = m[0].TPName;
                vm.activity.PelangganIDType = m[0].IdentityTypeID;
                vm.activity.PelangganIDNumber = m[0].IdentityNo;
                vm.activity.PelangganNoCukai = m[0].NoCukaiCode + m[0].NoCukai;
                vm.activity.PelangganTelefon = m[0].InTelefonMB;
                vm.activity.PelangganEmail = m[0].InEmailMB;
                tempPelanggan = m[0];
                //vm.IsPelangganNamaCukaiDisable = true; 
            }
            else {
                vm.activity.PelangganTPID = null;
                vm.activity.PelangganNama = null;
                vm.activity.PelangganIDType = vm.SearchTP.IDType.Value;
                vm.activity.PelangganIDNumber = vm.SearchTP.IDNo;
                vm.activity.PelangganNoCukai = null;
                vm.activity.PelangganTelefon = null;
                vm.activity.PelangganEmail = null;
                //vm.IsPelangganNamaCukaiDisable = false;
                if (isDummyTP)
                    vm.activity.PelangganNama = vm.constDummyTPName;
            }
            $scope.makAmForm.$dirty = true;
            $scope.makAmForm["PelangganNama"].$pristine = false;
            $scope.makAmForm["PelangganJenisPengenalan"].$pristine = false;
            $scope.makAmForm["PelangganIDNumber"].$pristine = false;
            $scope.makAmForm["PelangganNoCukai"].$pristine = false;
            $scope.makAmForm["PelangganTelefon"].$pristine = false;
            $scope.makAmForm["PelangganEmail"].$pristine = false;

            blnIsPelangganSearched = true;
        }

        vm.isEditTPData = true;
        if (vm.activity.PelangganIDType == vm.activity.TPIDType) {
            vm.activity.IsPelangganPembayarSama = vm.activity.PelangganIDNumber.toUpperCase() == vm.activity.TPIDNumber.toUpperCase();
        }
        else {
            vm.activity.IsPelangganPembayarSama = false;
        }
        //bindTempPelangganDetails();

        if (vm.activity.IsPelangganPembayarSama) {

            if (!vm.activity.LanguageID) {
                if (vm.activity.TP && vm.activity.TP.LanguageID)
                    vm.activity.LanguageID = vm.activity.TP.LanguageID;

                else
                    vm.activity.LanguageID = defaultLanguageID;

            }

            if (vm.activity.TelefonInteraksi) {
              
                vm.activity.TPTelefonMB = vm.activity.TelefonInteraksi;
            }
            //Requested by user (Nazil), not populate to EmailMB for chat
            //if (vm.activity.EmailInteraksi && vm.activity.ActChannelID != vm.constActChannelChat) {
				
			//Requested by user (Nazil), populate to EmailMB for chat as well
			if (vm.activity.EmailInteraksi && vm.activity.ActChannelID != vm.constActChannelPhone) {
                 
                vm.activity.TPEmailMB = vm.activity.EmailInteraksi; 
            }
			
            if (vm.activity.SocialMediaInteraksiID) {
                 
                if ((vm.activity.SocialMediaInteraksiID && vm.activity.SumberID == constSumberFB) || idTypeCode == constFBIDTypeCode) {
                    vm.activity.TPFBDisplayName = vm.activity.SocialMediaInteraksiName;
                    vm.activity.TPFBID = vm.activity.SocialMediaInteraksiID;
                }
                else if ((vm.activity.SocialMediaInteraksiID && vm.activity.SumberID == constSumberTW) || idTypeCode == constTWIDTypeCode) {
                    vm.activity.TPTWDisplayName = vm.activity.SocialMediaInteraksiName;
                    vm.activity.TPTWID = vm.activity.SocialMediaInteraksiID;
                }
            }
        }
        else {
            if (!vm.activity.LanguageID) {
                if (tempPelanggan && tempPelanggan.LanguageID)
                    vm.activity.LanguageID = tempPelanggan.LanguageID;

                else
                    vm.activity.LanguageID = defaultLanguageID;

            }
            //Use when search for pelanggan. As the Taxpayer interaksi info not cleared . -- so that previous activity don't go here
            if (vm.IsSearchPelanggan == true) {
                if (vm.activity.TPTelefonMB == vm.activity.TelefonInteraksi) {
                    vm.activity.TPTelefonMB = null;
                    $scope.makAmForm["TPTelefonMB"].$pristine = false;

                    if (vm.activity.TP) {
                        vm.activity.TPTelefonMB = vm.SelectedAliran == vm.constAliranOUT ? vm.activity.TP.OutTelefonBimbit : vm.activity.TP.InTelefonMB;
                        vm.activity.TPTelefonMB = vm.activity.TPTelefonMB == vm.activity.TelefonInteraksi ? null : vm.activity.TPTelefonMB;
                    }
                }
                if (vm.activity.EmailInteraksi == vm.activity.TPEmailMB) {
                    vm.activity.TPEmailMB = null;
                    $scope.makAmForm["TPEmailMB"].$pristine = false;
                    if (vm.activity.TP) {
                        vm.activity.TPEmailMB = vm.SelectedAliran == vm.constAliranOUT ? vm.activity.TP.OutEmailMB : vm.activity.TP.InEmailMB;
                        vm.activity.TPEmailMB = vm.activity.EmailInteraksi == vm.activity.TPEmailMB ? null : vm.activity.TPEmailMB;
                    }
                }
                if ((vm.activity.SocialMediaInteraksiID == vm.activity.TPFBID && vm.activity.SumberID == constSumberFB) || idTypeCode == constFBIDTypeCode) {
                    vm.activity.TPFBID = null
                    vm.activity.TPFBDisplayName = null
                    $scope.makAmForm["TPFBDisplayName"].$pristine = false;
                    $scope.makAmForm["TPFBID"].$pristine = false;
                    if (vm.activity.TP) {
                        vm.activity.TPFBID = vm.activity.TP.FBID;
                        vm.activity.TPFBDisplayName = vm.activity.TP.FBDisplayName;
                        if (vm.activity.SocialMediaInteraksiID == vm.activity.TPFBID) {
                            vm.activity.TPFBID = null
                            vm.activity.TPFBDisplayName = null
                        }
                    }
                }

                if ((vm.activity.SocialMediaInteraksiID == vm.activity.TWID && vm.activity.SumberID == constSumberTW) || idTypeCode == constTWIDTypeCode) {
                    vm.activity.TPTWID = null
                    vm.activity.TPTWDisplayName = null
                    $scope.makAmForm["TPTWDisplayName"].$pristine = false;
                    $scope.makAmForm["TPTWID"].$pristine = false;
                    if (vm.activity.TP) {
                        vm.activity.TPTWDisplayName = vm.activity.TP.TWDisplayName;
                        vm.activity.TPTWID = vm.activity.TP.TWID;
                        if (vm.activity.SocialMediaInteraksiID == vm.activity.TPTWID) {
                            vm.activity.TPTWID = null
                            vm.activity.TPTWDisplayName = null
                        }
                    }
                }
            }
        }

        if ((!vm.activity.PelangganTPID || vm.activity.PelangganTPID == vm.constDummyTPID) && vm.activity.IsPelangganPembayarSama == false)
            vm.IsPelangganNamaCukaiDisable = false; //if Pelanggan is Orphan but not sama with Pembayar then false
        else
            vm.IsPelangganNamaCukaiDisable = true;

        //Reinitialise 
        isDummyTP = false;
        isNewActFirstLoad = false;
        vm.IsSearchPelanggan = false;
        vm.ShowNoneSearchTPResult = false;
        vm.ShowSearchTPResult = false;
        tempTP = null;
        if (!isResendEmail && !vm.outlookContent) //if not from outlook only reset content
            setDefaultEmail();
        vm.isSocialMediaNotFound = false;
        vm.SearchTP = {
        };
        setIsTPPelangganSearched();
        vm.close();
    }


    function bindPelangganOnNewActFirstLoad() {
        //New Activity First Load Pelanggan is Sama with TP ( is SelectTP To Create New Activity From screen pop up) :
        if (isNewActFirstLoad && vm.activity.IsPelangganPembayarSama) {
            //Bind Pelanggan details 
            vm.activity.PelangganTPID = vm.activity.TPID;
            vm.activity.PelangganNama = vm.activity.TPName;
            vm.activity.PelangganIDType = vm.activity.TPIDType;
            vm.activity.PelangganIDNumber = vm.activity.TPIDNumber;
            vm.activity.PelangganNoCukai = vm.activity.TPNoCukai;
            vm.activity.PelangganTelefon = vm.activity.TP && vm.activity.TP.TPID > 0 ? vm.activity.TP.InTelefonMB : vm.activity.TPTelefonMB; //Pelanggan MB always uses the Inbound
            vm.activity.PelangganEmail = vm.activity.TP && vm.activity.TP.TPID > 0 ? vm.activity.TP.InEmailMB : vm.activity.TPEmailMB;
            if (vm.activity.PelangganTPID) {
                tempPelanggan = vm.activity.TP;
            }
        }
        else if (isNewActFirstLoad && !vm.activity.IsPelangganPembayarSama) {
            if (tempPelanggan && tempPelanggan.hasOwnProperty('TPID')) { 
                vm.activity.PelangganTPID = tempPelanggan.TPID;
                vm.activity.PelangganNama = tempPelanggan.TPName;
                vm.activity.PelangganIDType = tempPelanggan.IdentityTypeID;
                vm.activity.PelangganIDNumber = tempPelanggan.IdentityNo;
                vm.activity.PelangganNoCukai = tempPelanggan.NoCukaiCode + tempPelanggan.NoCukai;
                vm.activity.PelangganTelefon = tempPelanggan.InTelefonMB;
                vm.activity.PelangganEmail = tempPelanggan.InEmailMB;
            }
        }

        if (isNewActFirstLoad)
            blnIsPelangganSearched = blnIsTPSearched;

    }


    vm.clearSearchTPCriteria = function () {
        vm.lstTP = [];
        vm.SearchTP = {
        };
        vm.showRequireSearchIDType = false;
        vm.showRequireSearchIDNo = false;
        vm.invalidSearchRujukanNo = false;
        vm.SearchTP.InvalidSearch = false;
        vm.ShowNoneSearchTPResult = false;
        vm.ShowSearchTPResult = false;
    }

    vm.closeSearchTP = function () {
        vm.lstTP = [];
        vm.SearchTP = {
        };
        vm.showRequireSearchIDType = false;
        vm.showRequireSearchIDNo = false;
        vm.invalidSearchRujukanNo = false;
        vm.SearchTP.InvalidSearch = false;
        //vm.SearchTP.IDType = constIDTypeNRIC;
        vm.IsSearchPelanggan = false;
        vm.ShowNoneSearchTPResult = false;
        //vm.isPelangganPembayarNotSama = false;
        vm.isSocialMediaNotFound = false;
        vm.ShowSearchTPResult = false;
        if (tempTP) {
            //if got tempTP(populated when select IsPelangganPembayarSama=false) Revert back to true
            vm.activity.IsPelangganPembayarSama = true;

            if (tempTP.TPID) {
                vm.activity.TP = tempTP;
                bindActivityTPDetailsByTP();
                vm.activity.TPTelefonPejabat = tempTP.TelefonPejabat;
                //vm.activity.IsOrphanActivity = false; 
            }
            else {
                vm.activity.TPName = tempTP.TPName;
                vm.activity.TPIDType = tempTP.IdentityTypeID;
                vm.activity.TPIDNumber = tempTP.IdentityNo;
                vm.activity.TPNoCukai = tempTP.TPNoCukai;
                vm.activity.TPEmailMB = vm.SelectedAliran == vm.constAliranOUT ? tempTP.OutEmailMB : tempTP.InEmailMB;
                vm.activity.TPTelefonMB = vm.SelectedAliran == vm.constAliranOUT ? tempTP.OutTelefonBimbit : tempTP.InTelefonMB;
                vm.activity.TPTelefonPejabat = tempTP.TelefonPejabat;
                //vm.activity.IsOrphanActivity = true;  
            }
            vm.activity.TPFBDisplayName = tempTP.FBDisplayName;
            vm.activity.TPFBID = tempTP.FBID;
            vm.activity.TPTWDisplayName = tempTP.TWDisplayName;
            vm.activity.TPTWID = tempTP.TWID;
            vm.activity.IsOrphanActivity = tempTP.IsOrphanActivity;
            //Bind Header
            var objTP = {
                TPID: vm.activity.TP ? vm.activity.TP.TPID : null,
                TPName: vm.activity.TPName,
                TPJenisPengenalan: vm.activity.TPJenisPengenalan,
                TPIDNumber: vm.activity.TPIDNumber,
                TPNoCukai: vm.activity.TPNoCukai
            };
            bindHeader(objTP, vm.activity.TP);
            tempTP = null;

        }
        vm.close();
        bindPelangganOnNewActFirstLoad();
        setIsTPPelangganSearched();
        if (vm.IsNotFromSearchTP) {
            swal("Perhatian!", "Sila buat carian pembayar cukai terlebih dahulu untuk teruskan aktiviti.", "warning");
            return;
        }
    }

    /*Search TP END */

    vm.transferToCase = function () {
        if (!vm.activity.ActivityID || vm.activity.IsDraft) {
            swal("Amaran", "Profil Aktiviti perlu disimpan dahulu", "warning");
            return;
        }
        else {
            //prompt information msg if Status == Selesai
            if (vm.activity.ActStatus1ID == constSelesaiLookUpValue) {
                swal({
                    title: "Informasi",
                    text: "Status kes akan menjadi selesai setelah dipautkan ke kes.",
                    type: "info",
                    showCancelButton: false,
                    confirmButtonText: "OK",
                    closeOnConfirm: true
                }, function (isConfirm) {
                    if (isConfirm) {
                        TransferToCase();
                    }
                });
            } else {
                TransferToCase();
            }

        }
    };

    function TransferToCase() {
        ActivitySI.getChangeStampbyID(vm.activity.ActivityID).then(function (r) {
            if (r.status === 200) {
                if (vm.activity.ChangeStamp == r.data.data) {
                    var form = angular.element('#transferToCaseForm');
                    form.submit();
                    isHasLinkCaseAction = true;
                }
                else {
                    swal("Gagal", GeneralService.ErrorHandling.RefreshPageMsg, "error");
                    return;
                }
            }
        });
    }

    function bindMenuBar() {
        MenuBarService.MB.ActChannelID = vm.activity.ActChannelID;
        //MenuBarService.MB.Aliran = vm.SelectedAliran;
        MenuBarService.MB.InteractionID = vm.interactionId || vm.activity.InteractionID;
        //MenuBarService.MB.TelNoInteraksi = telNo;
        MenuBarService.setInteractionChannel(MenuBarService.MB.InteractionID, vm.activity.TPName);
    }


    function bindTempPelangganDetails() {
        if (vm.activity.TempPelanggan) {
            tempPelanggan = vm.activity.TempPelanggan;
            vm.activity.TempPelanggan = null;
        }
        else if (vm.activity.PelangganTPID > 0 && vm.activity.IsPelangganPembayarSama) { //Orphan
            tempPelanggan = vm.activity.TP;
        }
         
    }
    function bindTempTPDetails() {
        if (vm.activity.TP && vm.activity.TP.TPID)
            tempTP = angular.copy(vm.activity.TP);
        else { //Orphan
            tempTP = {
            };
            tempTP.TPName = vm.activity.TPName;
            tempTP.IdentityTypeID = vm.activity.TPIDType;
            tempTP.IdentityNo = vm.activity.TPIDNumber;
            tempTP.JenisPengenalan = vm.activity.TPJenisPengenalan;
            tempTP.TPNoCukai = vm.activity.TPNoCukai;

        }

        tempTP.IsOrphanActivity = vm.activity.IsOrphanActivity;
        tempTP.TelefonPejabat = vm.activity.TPTelefonPejabat; //TelefonPejabat self created
        if (vm.SelectedAliran == vm.constAliranOUT) {
            tempTP.OutEmailMB = vm.activity.TPEmailMB;
            tempTP.OutTelefonBimbit = vm.activity.TPTelefonMB;
        }
        else {
            tempTP.InEmailMB = vm.activity.TPEmailMB;
            tempTP.InTelefonMB = vm.activity.TPTelefonMB;
            //tempTP.InTelefonPejabat = vm.activity.TPTelefonPejabat;
        }

        tempTP.FBDisplayName = vm.activity.TPFBDisplayName;
        tempTP.FBID = vm.activity.TPFBID;
        tempTP.TWDisplayName = vm.activity.TPTWDisplayName;
        tempTP.TWID = vm.activity.TPTWID;

    }

    function bindActivityTPDetailsByTP() {
        //Call when new or draft activity

        vm.activity.TPID = vm.activity.TP.TPID;

        vm.activity.TPName = vm.activity.TP.TPName;

        vm.activity.TPNoCukai = vm.activity.TP.NoCukaiCode + vm.activity.TP.NoCukai;

        vm.activity.TPIDType = vm.activity.TP.IdentityTypeID;

        vm.activity.TPIDNumber = vm.activity.TP.IdentityNo;

        vm.activity.TPJenisPengenalan = vm.activity.TP.JenisPengenalan;

        vm.activity.TPTelefon = vm.activity.TP.TelNo;

        vm.activity.TPEmail = vm.activity.TP.Email;

        vm.activity.TPEmailMB = vm.SelectedAliran == vm.constAliranOUT ? vm.activity.TP.OutEmailMB : vm.activity.TP.InEmailMB;

        vm.activity.TPTelefonMB = vm.SelectedAliran == vm.constAliranOUT ? vm.activity.TP.OutTelefonBimbit : vm.activity.TP.InTelefonMB;

        vm.activity.TPTelefonPejabat = vm.SelectedAliran == vm.constAliranOUT ? vm.activity.TP.OutTelefonPejabat : null;

        vm.activity.TPFBDisplayName = vm.activity.TP.FBDisplayName;

        vm.activity.TPFBID = vm.activity.TP.FBID;

        vm.activity.TPTWDisplayName = vm.activity.TP.TWDisplayName;

        vm.activity.TPTWID = vm.activity.TP.TWID;
         
        getOutboundCount();
    }


    function getOutboundCount() {

        model = {
            TPID: vm.activity.TPID,
            ReMSTableName: vm.outbound ? vm.outbound.ReMSTableName : '',
            ReMSDataID: vm.outbound ? vm.outbound.DataID : 0
        }

        ActivitySI.getOutboundCountByTP(model).then(function (r) {
            vm.activity.TP.IsOwnOpenOutbound = false;
            var intCount = r.data;
            console.log(intCount);
            if (intCount > 0) {
                vm.activity.TP.IsOwnOpenOutbound = true;
            }
        });
    }

    function clearActivityTPDetails() {

        vm.activity.TPID = null;
        vm.activity.TPName = null;
        vm.activity.TPNoCukai = null
        vm.activity.TPJenisPengenalan = null;
        vm.activity.TPIDType = null
        vm.activity.TPIDNumber = null
        vm.activity.TPTelefon = null;
        vm.activity.TPEmail = null;
        vm.activity.TPTelefonMB = null;
        vm.activity.TPEmailMB = null;
        vm.activity.TPTelefonPejabat = null;


        vm.activity.TPFBDisplayName = null;
        vm.activity.TPFBID = null;
        vm.activity.TPTWDisplayName = null;
        vm.activity.TPTWID = null;
         
    }

    function bindHeader(objTP, objTPOtherDetails) {

        //TaxPayerService.TP.AllowEdit = true;  
        TaxPayerService.TP.TPID = objTP.TPID;
        TaxPayerService.TP.Name = objTP.TPName;
        TaxPayerService.TP.TPType = objTP.TPJenisPengenalan;
        TaxPayerService.TP.IDNo = objTP.TPIDNumber;

        if (objTPOtherDetails != null) {
            TaxPayerService.TP.FileType = objTPOtherDetails.FileType;
            TaxPayerService.TP.TaxNo = objTPOtherDetails.NoCukai;
            TaxPayerService.TP.NoCukaiCode = objTPOtherDetails.NoCukaiCode;
            TaxPayerService.TP.StatusFail = objTPOtherDetails.StatusFail;
            TaxPayerService.TP.StatusFailPendua = objTPOtherDetails.StatusFailPendua;
            TaxPayerService.CWNG.PungutanCP = objTPOtherDetails.CWPungutanCP;
            TaxPayerService.CWNG.PungutanCKHT = objTPOtherDetails.CWPungutanCKHT;
            TaxPayerService.CWNG.PenaksiranCP = objTPOtherDetails.CWPenaksiranCP;
            TaxPayerService.CWNG.PenaksiranCKHT = objTPOtherDetails.CWPenaksiranCKHT;
            TaxPayerService.CWNG.GuamanSivil = objTPOtherDetails.CWGuamanSivil;
            TaxPayerService.TP.GelaranName = objTPOtherDetails.GelaranName;
            TaxPayerService.TP.HonorificName = objTPOtherDetails.HonorificName;
            vm.SearchTProfileAccess = objTPOtherDetails.SearchTPProfile;
        }
        else {
            TaxPayerService.TP.TaxNo = objTP.TPNoCukai; //Cater for Orphan TP
            TaxPayerService.TP.FileType = null;
            TaxPayerService.TP.NoCukaiCode = null;
            TaxPayerService.TP.StatusFail = null;
            TaxPayerService.TP.StatusFailPendua = null;
            TaxPayerService.CWNG.PungutanCP = '-';
            TaxPayerService.CWNG.PungutanCKHT = '-';
            TaxPayerService.CWNG.PenaksiranCP = '-';
            TaxPayerService.CWNG.PenaksiranCKHT = '-';
            TaxPayerService.CWNG.GuamanSivil = '-';
            TaxPayerService.TP.GelaranName = null;
            TaxPayerService.TP.HonorificName = null;
            vm.SearchTProfileAccess = true;
        }
    }

    vm.dtInstanceActChangesHistory = {
    };
    //Search Activity
    vm.searchAct = function () {

        vm.blnValid = true;
        vm.showErrCreatedDate = false;
        vm.ErrMsgCreatedDate = "";
        var d = new Date(vm.DateFrom);
        var dt = new Date(vm.DateTo);

        if ((!vm.DateFrom && vm.DateTo) ||
            (vm.DateFrom && !vm.DateTo)) {
            vm.ErrMsgCreatedDate = "Banjaran tarikh tidak sah.";
            vm.showErrCreatedDate = true;
            vm.blnValid = false;
        }
        if (d > dt) {
            //console.log("1")
            vm.ErrMsgCreatedDate = "Date To must be greater than Date From.  ";
            //console.log(vm.ErrMsgCreatedDate)
            vm.showErrCreatedDate = true;
            vm.blnValid = false;
        }

        if (vm.blnValid) {
            vm.showErrCreatedDate = false;
            vm.ErrMsgCreatedDate = "";
            vm.dtInstanceActChangesHistory.reloadData();
        }
    }
    vm.clear = function () {
        vm.DateFrom = null;
        vm.DateTo = null;
        vm.FieldName = '';
        vm.showErrCreatedDate = false;
        vm.ErrMsgCreatedDate = "";
        vm.blnValid = true;
        vm.LastUpdatedBy = '';
    }

    /*Attachment*/
    vm.getAttachment = function (AttachID, Type, $event) {
        //act.WindowUnloadEventEnable=false; 
        $event.preventDefault();
        WindowUnloadEventEnable = false;
        $window.open((ActivitySI.getAttachment(Type) + AttachID), '_self');
    }

    vm.deleteAttachment = function (AttachID, objfile, indicator, type) {
        //type : 1 - Activity ,  2 - Catatan, 3 - CatatanEdit
        //indicator : 1 - New Temp Attach, 2 - Saved Attachments
        if (indicator == 1)//delete from new temp attachment  
        {
            var update = ActivitySI.deleteAttachment(AttachID);

            var result = update.then(function (r) {
                if (r.status === 200) {
                    $scope.makPerinciForm.$dirty = true;
                    switch (type) {
                        case 1:
                            if (vm.activity.ActAttachmentList) {
                                var index = vm.activity.ActAttachmentList.indexOf(objfile);
                                if (index != -1) {
                                    vm.activity.ActAttachmentList.splice(index, 1);
                                }
                            }
                            break;
                        case 2:
                            if (vm.ActCatatan.CatatanAttachmentList) {
                                var index = vm.ActCatatan.CatatanAttachmentList.indexOf(objfile);
                                if (index != -1) {
                                    vm.ActCatatan.CatatanAttachmentList.splice(index, 1);
                                }
                            }
                            break;
                        case 3:
                            if (vm.ActCatatanEdit.CatatanAttachmentList) {
                                var index = vm.ActCatatanEdit.CatatanAttachmentList.indexOf(objfile);
                                if (index != -1) {
                                    vm.ActCatatanEdit.CatatanAttachmentList.splice(index, 1);
                                }
                            }
                            break;
                    }
                }

            });
        } else {  //delete from saved attachments
            $scope.makPerinciForm.$dirty = true;
            switch (type) {
                case 1:
                    if (vm.activity.ActAttachmentList) {
                        var index = vm.activity.ActAttachmentList.indexOf(objfile);
                        if (index != -1) {
                            vm.activity.ActAttachmentList.splice(index, 1);
                        }
                    }
                    break;
                case 2:
                    if (vm.ActCatatan.CatatanAttachmentList) {
                        var index = vm.ActCatatan.CatatanAttachmentList.indexOf(objfile);
                        if (index != -1) {
                            vm.ActCatatan.CatatanAttachmentList.splice(index, 1);
                        }
                    }
                    break;
                case 3:
                    if (vm.ActCatatanEdit.CatatanAttachmentList) {
                        var index = vm.ActCatatanEdit.CatatanAttachmentList.indexOf(objfile);
                        if (index != -1) {
                            vm.ActCatatanEdit.CatatanAttachmentList.splice(index, 1);
                        }
                    }
                    break;
            }
        }
    }

    function getFileType(strFileName, strFileContentType) {
        if (strFileContentType.match(/^image\/.+/)) {
            return 'image';
        }

        return (strFileName.substring(strFileName.lastIndexOf('.'), strFileName.length) || "").toLowerCase();
    }

    function returnPromise() {
        var result = null;
        var deferred = $q.defer();
        result = deferred.promise;
        return result;
    }

    vm.uploadFiles = function (files, errFiles, type) {
        //type : 1 - Activity ,  2 - Catatan, 3 - CatatanEdit
        //$error: "maxSize"
        //$errorMessages: { maxSize: true }
        //$errorParam: "30MB"
        var result = returnPromise();
        var promises = [];
        var promiseUpload = returnPromise(); //return a promise;
        vm.f = files;
        vm.uploadFileType = type;
        //vm.errFile = errFiles != null && errFiles.length > 0 ? errFiles[0] : null;
        //file = 'a'; TODO Error Response not caught 
        var isUploaded = false;

        if (files && files.length) {
            for (var i = 0; i < files.length; i++) {
                file = files[i];
                if (!file.$error) {
                    file.progress = 0;
                    file.FileType = getFileType(file.name, file.type); 
                    file.upload = Upload.upload(ActivitySI.uploadAttachment(file));
                    promises.push(file.upload);
                    file.upload.then(function (r) {
                        //console.log("Upload step 1");
                        $timeout(function () {
                            //vm.Files.push({ TempAttachID: r.data, Name: file.name });
                            $scope.makPerinciForm.$dirty = true;
                            r.data.AttachmentID = null;
                            isUploaded = true;
                            switch (type) {
                                case 1:
                                    if (!vm.activity.ActAttachmentList) {
                                        vm.activity.ActAttachmentList = [];
                                    }
                                    r.data.FileType = getFileType(r.data.FileName, r.data.FileContentType);
                                    vm.activity.ActAttachmentList.push(r.data);
                                    break;
                                case 2:
                                    if (!vm.ActCatatan.CatatanAttachmentList) {
                                        vm.ActCatatan.CatatanAttachmentList = [];
                                    }
                                    r.data.FileType = getFileType(r.data.FileName, r.data.FileContentType);
                                    vm.ActCatatan.CatatanAttachmentList.push(r.data);
                                    break;
                                case 3:
                                    if (!vm.ActCatatanEdit.CatatanAttachmentList) {
                                        vm.ActCatatanEdit.CatatanAttachmentList = [];
                                    }
                                    r.data.FileType = getFileType(r.data.FileName, r.data.FileContentType);
                                    vm.ActCatatanEdit.CatatanAttachmentList.push(r.data);
                                    vm.IsEditCatatanFile = true;
                                    break;
                            }

                            //console.log("Upload step 1.1");

                            //vm.errFile = null;
                        });
                    }, function (r) {
                        file.$error = r.status + ': ' + r.data;
                        errFiles || (errFiles = []);
                        errFiles.push(file);
                    }, function (evt) {
                        //console.log("Upload step 3");
                        // Math.min is to fix IE which reports 200% sometimes
                        var progress = Math.min(100, parseInt(100.0 *
                            evt.loaded / evt.total));
                        if (isUploaded == false)
                            progress = parseInt(progress * 0.7);
                        else progress = 100;
                        file.progress = progress;
                    }).finally(function () {

                    });

                }
            }
            promiseUpload = $q.all(promises);
        }
        else {
            promiseUpload = returnResult();
        }

        result = promiseUpload.then().finally(function () {
            vm.f = null;
            angular.element("input[type='file']").val(null);
            var patternErrorCount = 0;
            if (errFiles && errFiles.length) {
                var strErrorMsg = "";
                for (var i = 0; i < errFiles.length; i++) {
                    if (errFiles[i].$error == "maxSize") {
                        strErrorMsg = strErrorMsg + "\n" + errFiles[i].name + " fail saiz " + (parseInt(errFiles[i].size / 1000000) || "0").toString() + "MB melebihi saiz muat naik maksimum(" + errFiles[i].$errorParam + ") yang dibenarkan.";
                        //File too large    { { errorFile.size / 1000000 | number: 1 } } MB: max 2M
                    }
                    else if (errFiles[i].$error == "pattern") {
                        if (patternErrorCount == 0)
                            strErrorMsg = strErrorMsg + "\n" + "Format fail yang dibenarkan untuk dimuat naik adalah : imeg,.pdf,.xls,.xlsx,.doc,.docx dan .txt.";

                        strErrorMsg = strErrorMsg + "\n" + errFiles[i].name + " jenis fail tidak diterima." + "\n";
                        patternErrorCount++;
                    }
                    else {
                        strErrorMsg = strErrorMsg + "\n" + errFiles[i].name + " " + errFiles[i].$error + " " + errFiles[i].$errorParam;
                    }
                }
                swal("Gagal", strErrorMsg, "error");
            }
        });

        return result;
    }
    /*Attachment End*/

    /*Catatan tab*/
    vm.ActCatatan = {
    }; //Obj used for New Catatan
    vm.ActCatatanEdit = {
    }; //Obj used for Edit Catatan 
    function returnResultPromise() {
        var result = null;
        var deferred = $q.defer();
        deferred.resolve('');
        result = deferred.promise;
        return result;
    }



    vm.addCatatan = function () {
        var result = null;
        if (vm.ActCatatan.Catatan) {
            vm.showRequiredMsg = false;
        }
        else {
            vm.showRequiredMsg = true;
        }

        if (!vm.showRequiredMsg) {

            vm.ActCatatan.ActivityID = vm.activity.ActivityID;

            if (!vm.activity.ActivityID || vm.activity.IsDraft) {

                //result = vm.saveActivity([$scope.makAmForm.$dirty, $scope.verificationForm.$dirty, $scope.makPerinciForm.$dirty, $scope.terimDocForm.$dirty], false, true)

                //Rose - bug619 - prompt when add catatan
                swal({
                    title: "Tambah catatan memerlukan aktiviti disimpan. Adakah anda pasti untuk simpan aktiviti ini ?",
                    text: "",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonText: "Ya",
                    cancelButtonText: "Tidak",
                    closeOnConfirm: false,
                    closeOnCancel: false//,
                    //showLoaderOnConfirm: true
                }, function (isConfirm) {
                    if (isConfirm) {
                        //vm.activity.ActCatatan = model;  
                        //objActCatatan = model;
                        result = vm.saveActivity([$scope.makAmForm.$dirty, $scope.verificationForm.$dirty, $scope.makPerinciForm.$dirty, $scope.terimDocForm.$dirty], false, true)
                        return result;
                    } else {
                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                    }
                });
            }
            else {
                result = AddNewActCatatan(false);
            }
        } else {
            //todo : y put here ?
            var deferred = $q.defer();
            deferred.reject('');
            result = deferred.promise;
        }

        return result == null ? returnResultPromise() : result;
    };

    vm.showEditCatatanDialog = function (e, catatanID, catatan, catatanAttachmentList, changeStamp) {
        vm.OriCatatan = catatan;
        vm.ActCatatanEdit = {
        };
        vm.ActCatatanEdit.Catatan = catatan.replace(/<br\/>/g, '\n');
        vm.ActCatatanEdit.CatatanID = catatanID;
        vm.ActCatatanEdit.ChangeStamp = changeStamp;
        vm.ActCatatanEdit.CatatanAttachmentList = angular.copy(catatanAttachmentList);
        vm.showEditRequiredMsg = false;
        vm.openDialog(e, '#myCatatanModal');
    }

    vm.editCatatan = function () {
        if (vm.ActCatatanEdit.Catatan) {
            vm.showEditRequiredMsg = false;
        }
        else vm.showEditRequiredMsg = true;

        if (vm.ActCatatanEdit.Catatan == vm.OriCatatan && !vm.IsEditCatatanFile) //check if no change - update
        {
            swal("Gagal", "Tiada perubahan maklumat dilakukan!", "error");
            return;
        }

        if (!vm.showEditRequiredMsg) {

            //var model = {}; 
            vm.ActCatatanEdit.ActivityID = vm.activity.ActivityID;
            //AddNewActCatatan(isNewActivity, isSendEmail)
            if (vm.ActCatatanEdit.CatatanID < 0) { 
                for (var i = 0 ; i < vm.activity.ActCatatans.length; i++) {
                    if (vm.activity.ActCatatans[i].CatatanID == vm.ActCatatanEdit.CatatanID) {
                        vm.activity.ActCatatans[i].Catatan = vm.ActCatatanEdit.Catatan;
                        vm.activity.ActCatatans[i].CatatanAttachmentList = vm.ActCatatanEdit.CatatanAttachmentList;
                       
                        break;
                    } 
                } 
                 $mdDialog.hide();
            }
            else {
                ActivitySI.updateActCatatan(vm.ActCatatanEdit).then(function (r) {
                    if (r.status === 200) {

                        vm.ActCatatanEdit = {
                        };
                        vm.IsEditCatatanFile = false;

                        vm.activity.ActCatatans = r.data;
                        if (vm.activity.ActCatatans) {
                            for (i = 0; i < vm.activity.ActCatatans.length; i++)
                                vm.activity.ActCatatans[i].Catatan = vm.activity.ActCatatans[i].Catatan.replace(/\n/g, '<br/>');
                        }

                        $mdDialog.hide();
                        swal({
                            title: GeneralService.SaveMessage.Title,
                            text: GeneralService.SaveMessage.Text,
                            type: "success",
                            timer: 2500,
                            showConfirmButton: true
                        }, function () {
                            vm.dtInstanceActChangesHistory.reloadData();

                        });

                    }
                });
            }
        }
    }

    vm.deleteCatatan = function (catatanID, changeStamp) {
        swal({
            title: "Adakah anda pasti untuk menghapuskan catatan ini?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false,
            showLoaderOnConfirm:true
        }, function (isConfirm) {
            if (isConfirm) {

                if (catatanID < 0) { 
                    for (var i = 0 ; i < vm.activity.ActCatatans.length; i++) {
                        if (vm.activity.ActCatatans[i].CatatanID == catatanID) {
                            vm.activity.ActCatatans.splice(i, 1);
                            break;
                        }
                    }
                    $scope.$apply(); 
                    swal.close();
                } else {
                    var model = {
                    };
                    model.ActivityID = vm.activity.ActivityID;
                    model.CatatanID = catatanID;
                    model.ChangeStamp = changeStamp;
                    ActivitySI.deleteActCatatan(model).then(function (r) {
                        if (r.status === 200) {
                            vm.activity.ActCatatans = r.data;
                            if (vm.activity.ActCatatans) {
                                for (i = 0; i < vm.activity.ActCatatans.length; i++)
                                    vm.activity.ActCatatans[i].Catatan = vm.activity.ActCatatans[i].Catatan.replace(/\n/g, '<br/>');
                            }
                            swal({
                                title: GeneralService.SaveMessage.Title,
                                text: GeneralService.SaveMessage.Text,
                                type: "success",
                                timer: 2500,
                                showConfirmButton: true
                            }, function () {
                                vm.dtInstanceActChangesHistory.reloadData();
                            });
                        }
                    });
                }
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });
    }

    function AddNewActCatatan(isNewActivity, isSendEmail) {
        var result = null;
        result = ActivitySI.addActCatatan(vm.ActCatatan).then(function (r) {
            if (r.status === 200) {

                vm.ActCatatan = {
                };

                vm.activity.ActCatatans = r.data;
                if (vm.activity.ActCatatans) {
                    for (i = 0; i < vm.activity.ActCatatans.length; i++)
                        vm.activity.ActCatatans[i].Catatan = vm.activity.ActCatatans[i].Catatan.replace(/\n/g, '<br/>');
                }

                $mdDialog.hide();
                if (isNewActivity) {
                    if (isSendEmail) {
                        sendEmail();
                        return;
                    }
                    vm.redirectTo('/activity/profile/detail/' + vm.activity.ActivityID + '?t=' + TabID + '&ty=' + TabType);
                }
                else {
                    vm.dtInstanceActChangesHistory.reloadData();
                }
                 
            }
        });

        return result;
    }

    /*  END catatan tab*/

    /*import activity catatan in Penerimaan Dokumen tab*/
    vm.importCatatan = function () {
        ActivitySI.getAllCatatanInString(vm.activity.ActivityID).then(function (r) {
            if (r.data) {
                if (!vm.activity.NotaTemuduga)
                    vm.activity.NotaTemuduga = {
                    };
                var catatan = r.data.replace(/<br>/g, "\n");
                vm.activity.NotaTemuduga.NTCatatanTambahan = catatan + (!vm.activity.NotaTemuduga.NTCatatanTambahan ? '' : vm.activity.NotaTemuduga.NTCatatanTambahan);
                $scope.terimDocForm.$dirty = true;
                $scope.terimDocForm.NotaTemuduga_NTCatatanTambahan.$pristine = false;
            }
            else {
                swal("Gagal", "Tiada catatan untuk diimport.", "error");
            }
        });
    };

    /*validation and format functions*/
    function commaSeparateNumber(val) {
        while (/(\d+)(\d{3})/.test(val.toString())) {
            val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
        }
        return val;
    };

    vm.formatNumber = function (name) {
        vm.activity[name] = GeneralService.getFormattedNumber(vm.activity[name]);
    };

    vm.formatLineBreaksToHTML = function (str) {
        str = str.replace(/\n/g, '<br/>');
        return str;
    };

    vm.Validation = {
    };
    vm.Validation.Email = GeneralService.Validation.Email;
    vm.Validation.EmailMsg = GeneralService.Validation.EmailMsg;

    vm.Validation.MultipleEmail = GeneralService.Validation.MultipleEmail;
    vm.Validation.MultipleEmailMsg = GeneralService.Validation.MultipleEmailMsg;

    vm.Validation.Phone = GeneralService.Validation.Phone;
    vm.Validation.PhoneMsg = GeneralService.Validation.PhoneMsg;
     
    vm.Validation.Year = GeneralService.Validation.Year;
    vm.Validation.YearMsg = GeneralService.Validation.YearMsg;

    vm.Validation.Money = GeneralService.Validation.Money;
    vm.Validation.MoneyMsg = GeneralService.Validation.MoneyMsg; 
    /*validation and format functions END */


    /*Task Start*/
    //AddTask
    vm.addTask = function () {
        var form = angular.element('#addtaskForm');
        form.submit();
    };

    //Task Expand And Collapse Filter
    vm.ExpandTaskFilter = function () {
        vm.Taskshow = true;
    }

    vm.CollapseTaskFilter = function () {
        vm.Taskshow = false;
    }
    // Task Expand And Collapse Filter

    function getTaskList() {
        vm.TaskStatus = {
        };
        var ajaxCallbackTL = function (data, callback, settings) {
            data.ActivityID = $window.activityid;
            data.StatusID = vm.TaskStatus == null ? 0 : vm.TaskStatus.Value; //if TaskStatus = ALL = null = 0 
            TaskSI.getPagedTaskListByID(data).then(function (r) {
                if (r.status == 200) { 
                    callback(r.data);
                }
            });
        }
        //Bind table - start 
        vm.dtColumnsTaskList = [
            DTColumnBuilder.newColumn('Status').notSortable().withTitle(' ').renderWith(function (data, type) {
                var input = data.toLowerCase() == constBelumSelesai ? '<i class="case fa fa-exclamation-circle" style="color:red;" title="Belum Selesai"></i>' : '';
                return input;
            }).withOption('width', '2%'),
            DTColumnBuilder.newColumn('TaskID').withTitle('No. Tugasan').renderWith(renderTasklink).withOption('width', '13%'),
            //DTColumnBuilder.newColumn('CaseID').withTitle('Case No.').renderWith(renderCaselink).withOption('width', '11%'),
            // DTColumnBuilder.newColumn('ActivityID').withTitle('Activity No.').renderWith(renderActlink).withOption('width', '13%'),
            DTColumnBuilder.newColumn('AssignToName').withTitle('Pegawai Petugas').withOption('width', '15%'),
            DTColumnBuilder.newColumn('AssignByName').withTitle('Diagihkan Oleh').withOption('width', '15%'),
            DTColumnBuilder.newColumn('DueDate').withTitle('Tarikh Susulan').renderWith(function (data, type) {
                return $filter('date')(data, $scope.DateFormat);
            }).withOption('width', '8%'),
            DTColumnBuilder.newColumn('title').withTitle('Perkara').withOption('width', '16%'),
            //DTColumnBuilder.newColumn('Description').withTitle('Description').withOption('width', '11%'),
            DTColumnBuilder.newColumn('Status').withTitle('Status').withOption('width', '8%'),
            DTColumnBuilder.newColumn('LastUpdatedDateTime').withTitle('Tarikh Dikemaskini').renderWith(function (data, type) {
                return $filter('date')(data, $scope.DateTimeFormat);
            }).withOption('width', '10%'),

        ];

        function renderTasklink(data, type, row, meta) {
            return '<a href="/Task/detail/' + row.TaskID + '" target="_blank">' + row.TaskRefNo + '</a>';
        }

        function renderActlink(data, type, row, meta) {
            var link = '<a href="/Activity/Profile/detail/' + row.ActivityID + '" target="_blank">' + row.ActRefNo + '</a>';
            if (row.ActRefNo == undefined || row.ActRefNo == '0')
                link = '-';
            return link
        }

        function renderCaselink(data, type, row, meta) {

            var link = '<a href="/Case/Profile/detail/' + row.CaseID + '" target="_blank">' + row.CaseRefNo + '</a>';
            if (row.CaseRefNo == undefined || row.CaseRefNo == '0')
                link = '-';
            return link
        }

        vm.dtOptionsTaskList = DTOptionsBuilder.newOptions()
            .withOption('ajax', ajaxCallbackTL)
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('autoWidth', false)
            .withOption('searching', true)
            .withOption('serverSide', true)
            .withPaginationType('full_numbers')
            .withDisplayLength(10);
        //Bind Table - end

    }

    //Search Task List
    vm.dtInstanceTaskList = {
    };

    vm.searchTL = function () {

        vm.blnValid = true;

        if (vm.blnValid) {
            vm.dtInstanceTaskList.reloadData();
        };


    }
    vm.clearTL = function () {

        vm.TaskStatus = '';

    }
    /*Task END*/

    vm.printSlipKedatangan = function (e) {
        var model = {
            ActID: vm.activity.ActivityID
        };
        ActivitySI.printSlipKedatangan(model).then(function (r) {

            //var screen = window.open("data:text/json," +encodeURIComponent(r.data),
            //           "_blank");
            //screen.focus();
            vm.openDialog(e, '#myModalSlipKedatangan');
            document.getElementById("divPrintSlipKedatangan").innerHTML = r.data;
        });
    }

    vm.btnPrintSlipKedatanganClicked = function () {
        printElem("divPrintSlipKedatangan");

        //insert print record here
        var model = {
            TPID: vm.activity.TP == null ? null : vm.activity.TP.TPID,
            ActID: vm.activity.ActivityID
        };
        ActivitySI.insertSlipKedatanganAction(model).then(function (r) {
            if (r.data) {
                return true;
            }
        });
    }

    /*Private Other functions*/
    function printElem(elem) {
        var mywindow = window.open('', 'PRINT', 'height=400,width=600');

        mywindow.document.write(document.getElementById(elem).innerHTML);
        mywindow.document.close(); // necessary for IE >= 10
        mywindow.focus(); // necessary for IE >= 10*/

        mywindow.print();
        mywindow.close();

    }

    function consolidateBeforeSave(actUpdate) {
        if (actUpdate.Activity.NotaTemuduga) {
            if (actUpdate.Activity.NotaTemuduga.NTTarikhTerima) {
                actUpdate.Activity.NotaTemuduga.NTTarikhTerima = $filter('date')(actUpdate.Activity.LetterFaxReceived, $scope.DateTimeFormat); //actUpdate.Activity.NotaTemuduga.NTTarikhTerima;//// moment(actUpdate.Activity.NotaTemuduga.NTTarikhTerima, $scope.DateFormat).toDate();
            }

            if (actUpdate.Activity.NotaTemuduga.NTUnit) {
                actUpdate.Activity.NotaTemuduga.NTUnitID = actUpdate.Activity.NotaTemuduga.NTUnit.ID;
                actUpdate.Activity.NotaTemuduga.NTUnitName = actUpdate.Activity.NotaTemuduga.NTUnit.DisplayName;
            }
            else {
                actUpdate.Activity.NotaTemuduga.NTUnitID = null;
                actUpdate.Activity.NotaTemuduga.NTUnitName = null;
            }

        }
        if (actUpdate.Activity.LetterFaxReceived)
            actUpdate.Activity.LetterFaxReceived = $filter('date')(actUpdate.Activity.LetterFaxReceived, $scope.DateTimeFormat);
         

        if (actUpdate.Activity.PromiseToPayDate)
            actUpdate.Activity.PromiseToPayDate = $filter('date')(actUpdate.Activity.PromiseToPayDate, $scope.DateTimeFormat);
        

        if (actUpdate.Activity.ActEmail && actUpdate.Activity.ActEmail.EmailReceivedDate)
            actUpdate.Activity.ActEmail.EmailReceivedDate = $filter('date')(actUpdate.Activity.ActEmail.EmailReceivedDate, $scope.DateTimeFormat);
          

        if (actUpdate.Activity.KategoriDocReceived) {
            actUpdate.Activity.ActDocReceived = [];
            for (i = 0; i < actUpdate.Activity.KategoriDocReceived.length; i++) {
                for (j = 0; j < actUpdate.Activity.KategoriDocReceived[i].ActDocReceived.length; j++) {
                    model = {
                        ActDocReceivedID: actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].ActDocReceivedID,
                        ActivityID: actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].ActDocReceivedID,
                        DocListID: actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].DocListID,
                        KategoriDocName: actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].KategoriDocName,
                        KategoriDocCode: actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].KategoriDocCode,
                        DocListDetailID: actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].DocListDetailID,
                        DocName: actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].DocName,
                        Copy: actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].Copy,
                        TahunTaksiran: actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].TahunTaksiran,
                        TarikhDokumen: actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].TarikhDokumen,//moment(actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].TarikhDokumen, $scope.DateFormat).toDate(),
                        Remarks: actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].Remarks,
                        Checked: actUpdate.Activity.KategoriDocReceived[i].ActDocReceived[j].Checked
                    }
                    actUpdate.Activity.ActDocReceived.push(model);
                }
            }
        }

        if (actUpdate.Activity.TarikhMulaAnsuran)
            actUpdate.Activity.TarikhMulaAnsuran = actUpdate.Activity.TarikhMulaAnsuran;//actUpdate.Activity.TarikhMulaAnsuran = moment(actUpdate.Activity.TarikhMulaAnsuran, $scope.DateFormat).toDate();

        return actUpdate;
    }

    function formatDatePickerDates() {
        if (vm.activity.NotaTemuduga)
            if (vm.activity.NotaTemuduga.NTTarikhTerima)
                vm.activity.NotaTemuduga.NTTarikhTerima = new Date(vm.activity.NotaTemuduga.NTTarikhTerima);//$filter('date')(new Date(vm.activity.NotaTemuduga.NTTarikhTerima), $scope.DateFormat);

        if (vm.case && vm.case.TarikhStatus)
            vm.case.TarikhStatus = new Date(vm.case.TarikhStatus);

        if (vm.activity.LetterFaxReceived)
            vm.activity.LetterFaxReceived = new Date(vm.activity.LetterFaxReceived);
        //vm.activity.LetterFaxReceived = $filter('date')(new Date(vm.activity.LetterFaxReceived), $scope.DateFormat);

        if (vm.activity.ActEmail && vm.activity.ActEmail.EmailReceivedDate)
            vm.activity.ActEmail.EmailReceivedDate = new Date(vm.activity.ActEmail.EmailReceivedDate);//$filter('date')(new Date(vm.activity.ActEmail.EmailReceivedDate), $scope.DateFormat);

        if (vm.activity.PromiseToPayDate) {
            vm.activity.PromiseToPayDate = new Date(vm.activity.PromiseToPayDate);
            makPerinciForm.$pristine = true;
            makPerinciForm.$dirty = false;
            makPerinciForm.PromiseToPayDate.valid = true;
            makPerinciForm.PromiseToPayDate.invalid = true;
        } //vm.activity.PromiseToPayDate = $filter('date')(new Date(vm.activity.PromiseToPayDate), $scope.DateFormat);

        if (vm.activity.KategoriDocReceived) {
            for (i = 0; i < vm.activity.KategoriDocReceived.length; i++) {
                for (j = 0; j < vm.activity.KategoriDocReceived[i].ActDocReceived.length; j++) {
                    if (vm.activity.KategoriDocReceived[i].ActDocReceived[j].Checked)
                        if (vm.activity.KategoriDocReceived[i].ActDocReceived[j].TarikhDokumen)
                            vm.activity.KategoriDocReceived[i].ActDocReceived[j].TarikhDokumen = new Date(vm.activity.KategoriDocReceived[i].ActDocReceived[j].TarikhDokumen);//$filter('date')(new Date(vm.activity.KategoriDocReceived[i].ActDocReceived[j].TarikhDokumen), $scope.DateFormat);
                }
            }
        }

        if (vm.activity.TarikhMulaAnsuran)
            vm.activity.TarikhMulaAnsuran = new Date(actUpdate.Activity.TarikhMulaAnsuran);//$filter('date')(new Date(vm.activity.TarikhMulaAnsuran), $scope.DateFormat);
    }
    /*Private Other Functions END*/


    vm.workflowAction = function (e) {

        vm.SelectedTimbalan = "";
        vm.SelectedJabatan = "";
        vm.SelectedCawangan = "";
        vm.SelectedUnits = "";

        vm.SeksyenEnabled = true;
        vm.JabatanEnabled = true;
        vm.NoUserMessage = false;

        //if (vm.WorkflowAssignToSeksyenOption == undefined)
        //    GetUserGroupHierarcyOptions();

        if (vm.DefaultManager == null)
            GetDefaultManager();

        vm.openDialog(e, '#WorkflowActionDialog');
    }

    // Search Default Unit for Activity
    vm.searchActForUnit = function () {
        var Kategory = {
            Kategori1: vm.activity.Kategori1ID,
            Kategori2: vm.activity.Kategori2ID,
            Kategori3: vm.activity.Kategori3ID,
            TPID: vm.activity.TP.TPID
        }

        ActivitySI.getActWorkFlowAssignToByKategoryId(Kategory).then(function (r) {
            if (r.data.ID != null && r.data.ID > 0) {
                vm.Users = [r.data];
                vm.AssignTo = vm.Users[0];
                vm.UserType = constAssignToTypeUnit;
                vm.AssignToDisable = true;
                vm.AssignOther = false;
                vm.showdetail = false;

            }
            else {
                vm.AssignTo = [r.data][0];
                vm.UserType = constAssignToTypeUnit;
                vm.AssignToDisable = true;
                vm.AssignOther = false;
                vm.showdetail = false;
            }
        });
    }
    // Search Default Unit for Activity

    // Search Manger for Login People 
    vm.searchActForUser = function () {
        //21-->Get default people value for Submit To
        var data = {
            keyword: "",
            AssignToType: constAssignToTypeUser

        }

        if (vm.DefaultManager != null) {
            vm.Users = vm.DefaultManager;
            vm.AssignTo = vm.DefaultManager;
            vm.UserType = constAssignToTypeUser;
            vm.AssignToDisable = true;
            vm.AssignOther = false;
            vm.showdetail = false;
        }
        else {

            vm.AssignTo = null;
            vm.UserType = constAssignToTypeUser;
            vm.AssignToDisable = false;
            vm.AssignOther = false;
            vm.showdetail = false;
        }

        //ActivitySI.getActWorkFlowSearchUserOrUnit(data).then(function (u) {
        //    if (u.data.length > 0) {
        //        var m = u.data;
        //        if (m.length != 0) {
        //            vm.Users = m;
        //            vm.AssignTo = vm.Users[0];
        //            vm.UserType = constAssignToTypeUser;
        //            vm.AssignToDisable = true;
        //            vm.AssignOther = false;
        //            vm.showdetail = false;

        //        }
        //    }
        //    else {
        //        vm.AssignTo = null;
        //        vm.UserType = constAssignToTypeUser;
        //        vm.AssignToDisable = false;
        //        vm.AssignOther = false;
        //        vm.showdetail = false;
        //    }
        //});
    }

    // Search Manger for Login People 

    // Search For Other
    vm.searchActForOther = function () {
        vm.AssignTo = null;
        vm.UserType = 0;
        vm.AssignToDisable = false;
        vm.AssignOther = true;
    }
    // Search For Other

    //Search All Unit-->For More Option Purpose

    vm.SearchJabatan = function (query) {
        vm.JabatanOption = [];
        if (query.length > 1) {
            vm.JabatanOption = vm.WorkflowAssignToJabatanOption;
        }

    }

    vm.SearchJabatanDocUnit = function (query) {
        vm.JabatanOptionDocUnit = [];
        if (query.length > 1) {
            vm.JabatanOptionDocUnit = vm.WorkflowAssignToJabatanOptionDocUnit;
        }

    }

    vm.SearchCawangan = function (query) {

        vm.CawanganOption = [];
        if (query.length > 1) {
            vm.CawanganOption = vm.WorkflowAssignToCawanganOption;
        }

    }

    vm.SearchCawanganDocUnit = function (query) {

        vm.CawanganOptionDocUnit = [];
        if (query.length > 1) {
            vm.CawanganOptionDocUnit = vm.WorkflowAssignToCawanganOptionDocUnit;
        }

    }

    //vm.SearchNTUnit = function (query) {

    //    vm.UnitPenerimaanDocFilteredOption = [];
    //    if (query.length > 1) {
    //        vm.UnitPenerimaanDocFilteredOption = vm.UnitPenerimaanDocOption;
    //    }

    //}
    //Search All Unit-->For More Option Purpose

    vm.CloseSearchHierary = function () {
        if (vm.SelectedUnits != "") {
            vm.SelectedUnits = "";
        }

        if (vm.SelectedCawangan != "") {
            vm.SelectedCawangan = "";
        }

        if (vm.SelectedJabatan != "") {
            vm.SelectedJabatan = "";
        }

        if (vm.SelectedTimbalan != "") {
            vm.SelectedTimbalan = "";
        }
    }

    vm.CancelSearchHierary = function (e) {
        $mdDialog.hide();
        vm.openDialog(e, '#WorkflowActionDialog');
    }



    vm.SearchUser = function (query, click) {
        vm.UsersOption = [];
        vm.loading = true;
        var UserType = vm.UserType;
        var data = {
            keyword: query,
            AssignToType: UserType

        }

        if (query.length > 2) {
            // TODO : To search users from DB or AD
            CaseSI.getWorkFlowSearchUserOrUnit(data).then(function (r) {
                if (r.data != null) {
                    var m = r.data;
                    if (m.length != 0) {
                        vm.UsersOption = m;


                    }
                } vm.loading = false;
            });

        }

    }

    //Selected Submit To User
    vm.SelectUser = function (selectedItem) {
        vm.AssignTo = selectedItem;
    }

    vm.SearchUserByName = function (query) {
        vm.UserResultOption = [];
        vm.loading = true;

        if (vm.Other == constAssignToTypeUser && query.length > 2) {
            UserSI.searchUserByName(query).then(function (r) {
                if (r.data != null) {
                    var m = r.data;
                    if (m.length != 0) {
                        vm.UserResultOption = m;
                    }
                } vm.loading = false;
            });
        }


        //if (query.length == 0 && UnitNames != "" && CawanganNames != "") {
        //    ActivitySI.getActSearchResultOptionByHierarchy(data).then(function (r) {
        //        if (r.data != null) {
        //            var m = r.data;
        //            if (m.length != 0) {
        //                vm.UserResultOption = m;
        //            }
        //        } vm.loading = false;
        //    });
        //}
        //else {
        //    if (query.length > 2) {
        //        // TODO : To search users from DB or AD
        //        ActivitySI.getActSearchResultOptionByHierarchy(data).then(function (r) {
        //            if (r.data != null) {
        //                var m = r.data;
        //                if (m.length != 0) {
        //                    vm.UserResultOption = m;
        //                }
        //            } vm.loading = false;
        //        });

        //    }
        //}

    }


    vm.SearchUnitByName = function (query) {
        vm.UserResultOption = [];
        vm.loading = true;

        if (query.length > 2) {
            UserSI.searchUnitByName(query).then(function (r) {
                if (r.data != null) {
                    var m = r.data;
                    if (m.length != 0) {
                        vm.UserResultOption = m;
                    }
                } vm.loading = false;
            });
        }
    }

    vm.SearchUnitByNameDocUnit = function (query) {
        vm.UnitPenerimaanDocOption = [];
        vm.UnitDocloading = true;

        if (query.length > 2) {
            UserSI.searchUnitByName(query).then(function (r) {
                if (r.data != null) {
                    var m = r.data;
                    if (m.length != 0) {
                        vm.UnitPenerimaanDocOption = m;
                    }
                } vm.UnitDocloading = false;
            });
        }
    }


    //Selected Submit To User
    vm.SelectUserHierarchy = function (selectedItem) {
        vm.AssignTo = selectedItem;
    }


    // Drop Down List for Other Option(Group,User OR All)

    vm.chooseOtherGroupOrUser = function () {

        vm.ResetHierarchy();
    }
    // Drop Down List for Other Option (Group,User OR All)

    //Open and Hide More Option for Other
    vm.ShowFilterOption = function () {
        if (!vm.showdetail) {
            vm.showdetail = true;
        }
        else {
            vm.ResetHierarchy();
            vm.showdetail = false;
        }
    }

    vm.ShowFilterOptionDocUnit = function () {

        vm.showdetailDocUnit = !vm.showdetailDocUnit;
    }

    //Open and Hide More Option for Other

    //Activity Workflow
    vm.ActWorkflowButton = function (isDirty, workflowForm, buttonID) {
        vm.showValidationMsgPopup = false;

        workflowForm.Timbalan.$dirty = false;
        workflowForm.Timbalan.$pristine = true;
        workflowForm.Jabatan.$dirty = false;
        workflowForm.Jabatan.$pristine = true;
        workflowForm.Cawangan.$dirty = false;
        workflowForm.Cawangan.$pristine = true;
        workflowForm.Units.$dirty = false;
        workflowForm.Units.$pristine = true;

        var result = null;
        if (vm.activity.ActivityID == "") {
            //Please save activity first before adding workflow for this activity.
            swal("Gagal", "Sila simpan aktiviti terlebih dahulu sebelum menambah alur kerja untuk aktiviti ini.", "error");
            $mdDialog.hide();
        }
        else {

            if (vm.AssignTo == null) {
                swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");

                var deferred = $q.defer(); // required for click and disabled
                deferred.reject('');
                result = deferred.promise;
                vm.showValidationMsgPopup = true;
                vm.showValidationMsg = true;
            }
            else if (vm.AssignTo.ManagerFunctionRoleID == null && buttonID != 7 && buttonID != 8 && vm.AssignTo.AssignToType == 20) {
                swal("Failed", "No manager assigned for this unit. Please assign to a unit that has manager.", "error");
                var deferred = $q.defer(); // required for click and disabled
                deferred.reject('');
                result = deferred.promise;
                vm.showValidationMsgPopup = true;
                vm.showValidationMsg = true;
            }
            else if (buttonID == 6 && vm.AssignTo.ID == null) {
                swal("Failed", "No assigned manager for it. Please Used Other Option to choose user.", "error");
                var deferred = $q.defer(); // required for click and disabled
                deferred.reject('');
                result = deferred.promise;
                vm.showValidationMsgPopup = true;
                vm.showValidationMsg = true;
            }
            else if (buttonID == 6 && vm.AssignTo.ID == -1) {
                swal("Failed", "No Default Unit Found.Please Used Other Option to choose Unit", "error");
                var deferred = $q.defer(); // required for click and disabled
                deferred.reject('');
                result = deferred.promise;
                vm.showValidationMsgPopup = true;
                vm.showValidationMsg = true;
            }
            else if(vm.AssignTo.AssignToType == 20) 
            {
                var ManagerFunctionRoleID = vm.AssignTo.ManagerFunctionRoleID.split("||");
                var HasManagerFucntionalRoleValue = 0;
                // Check the Unit and unit manager functional role exist or not
                angular.forEach(ManagerFunctionRoleID, function (value, key) {
                    var m = $filter('filter')(vm.FunctionRoleMemberOption, { UnitID: parseInt(vm.AssignTo.ID), FunctionalRoleID: parseInt(value) }, true);
                    if (m.length == 0) {
                        HasManagerFucntionalRoleValue = 0 + HasManagerFucntionalRoleValue;
                    }
                    else {
                        HasManagerFucntionalRoleValue = HasManagerFucntionalRoleValue + m.length;
                    }
                });

                // If No exist
                if (HasManagerFucntionalRoleValue == 0) {
                    swal("Failed", "No manager assigned for this unit. Please assign to a unit that has manager.", "error");
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                    vm.showValidationMsgPopup = true;
                    vm.showValidationMsg = true;
                }
                else {
                    if (workflowForm.$valid) {

                        if (isDirty) {
                            angular.forEach($scope.workflowForm, function (value, key) {
                                if (key[0] == '$') return;

                                var displayName = $('#' + key).data('displayfield');

                                if (value.$pristine == false) {

                                    var newvalue = "";
                                    if (key == 'SubmitTo') {
                                        newvalue = value.$viewValue.DisplayName;
                                    }
                                    else if (key == 'AssignTo') {
                                        newvalue = value.$viewValue.DisplayName;
                                    }
                                    else {
                                        newvalue = value.$viewValue;
                                    }

                                    vm.ChangesHistory.push({
                                        ID: vm.CaseId,
                                        FieldName: key,
                                        DisplayName: displayName,
                                        OldValue: '',
                                        NewValue: newvalue,
                                        IsChanged: !value.$pristine
                                    });
                                }

                            });

                        }
                        else {
                            var deferred = $q.defer(); // required for click and disabled
                            deferred.reject('');
                            result = deferred.promise;
                        }
                         
                        ActivityWorkFlowAction(buttonID)

                    }
                    else {
                        swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");

                        var deferred = $q.defer(); // required for click and disabled
                        deferred.reject('');
                        result = deferred.promise;
                        vm.showValidationMsgPopup = true;
                        vm.showValidationMsg = true;

                    }
                }
            }
            else
            {
               if (workflowForm.$valid) {

                if (isDirty) {
                    angular.forEach($scope.workflowForm, function (value, key) {
                        if (key[0] == '$') return;

                        var displayName = $('#' + key).data('displayfield');

                        if (value.$pristine == false) {

                            var newvalue = "";
                            if (key == 'SubmitTo') {
                                newvalue = value.$viewValue.DisplayName;
                            }
                            else if (key == 'AssignTo') {
                                newvalue = value.$viewValue.DisplayName;
                            }
                            else {
                                newvalue = value.$viewValue;
                            }

                            vm.ChangesHistory.push({
                                ID: vm.CaseId,
                                FieldName: key,
                                DisplayName: displayName,
                                OldValue: '',
                                NewValue: newvalue,
                                IsChanged: !value.$pristine
                            });
                        }

                    });

                }
                else {
                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                }
                    
                ActivityWorkFlowAction(buttonID)

            }
                else {
                            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");

                    var deferred = $q.defer(); // required for click and disabled
                    deferred.reject('');
                    result = deferred.promise;
                    vm.showValidationMsgPopup = true;
                    vm.showValidationMsg = true;

                }
            }



            return result;
        }

    }

    function ActivityWorkFlowAction(buttonid) {

        var workflowAction = {
            ActivityID: vm.activity.ActivityID,
            UserType: vm.UserType,
            AssignTo: vm.AssignTo,
            Remarks: "",
            DecisionID: buttonid,
            WorkflowID: vm.WorkFlowId

        }

        var WorkflowUpdate = {
            Workflow: workflowAction,
            WorkflowChangeHistory: vm.ChangesHistory
        }

        if (buttonid == 7) {
            swal({
                title: "Are you sure you want to recall this case workflow?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Ya",
                cancelButtonText: "Tidak",
                closeOnConfirm: false,
                closeOnCancel: false,
                showLoaderOnConfirm: true
            }, function (isConfirm) {
                if (isConfirm) {
                    result = ActivitySI.insertActWorkflowAction(WorkflowUpdate);
                    result.then(function (r) {
                        if (r.status === 200) {
                            swal({
                                title: "Recalled Succesfully",
                                type: "success",
                                showConfirmButton: true
                            }, function () {
                                vm.redirectTo('/activity/profile/detail/' + vm.activity.ActivityID + '?t=' + TabID + '&ty=' + TabType);

                            });
                        }
                        else {
                            swal("Gagal", r.data, "error");
                        }
                    });

                } else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        }
        else {
            result = ActivitySI.insertActWorkflowAction(WorkflowUpdate);
            result.then(function (r) {
                if (r.status === 200) {
                    swal({
                        title: "Proses agihan aktiviti berjaya dikemaskini.",
                        type: "success",
                        showConfirmButton: true
                    }, function () {
                        vm.redirectTo('/activity/profile/detail/' + vm.activity.ActivityID);

                    });
                }
                else {
                    swal("Gagal", r.data, "error");
                }
            });
        }
    }

    //Activity WorkFlow

    //Print Activity Penerimaan Document Tab
    vm.printPenerimaanDoc = function (isDirty, e) {
        if (vm.activityid > 0) {
            if (isDirty[0] || isDirty[1] || isDirty[2]) {
                swal("Gagal", "Perubahan telah dibuat! Sila simpan aktiviti ini sebelum mencetak nota temuduga", "error");
            }
            else {
                vm.genQRCode(isDirty, false, false, true, e);
            }
        }
        else {
            swal("Gagal", "Sila simpan aktiviti ini sebelum mencetak nota temuduga", "error");
        }
    }

    vm.btnPrintClicked = function () {
        printElem("divPrintNoteTemuduga");
    }

    function PrintPenerimaanDocument(qrcode, e) {
        //swal({
        //    title: 'Loading Data...',
        //    imageUrl: "/Content/images/ajax-loader-gif-5.gif",
        //    showConfirmButton: false,
        //    allowOutsideClick: false,
        //    timer: 1000
        //});

        var model = {
            ActID: vm.activityid,
            QRCode: qrcode,
            QRCodeDate: moment(new Date()).format('DD MMM YYYY hh:mm:ss A')
        };
        ActivitySI.printActPenerimaanDoc(model).then(function (r) {
            vm.openDialog(e, '#myModalNoteTemuduga');
            document.getElementById("divPrintNoteTemuduga").innerHTML = r.data;
        });
    }

    //Print Activity Penerimaan Document Tab


    vm.ResetHierarchy = function () {
        vm.SeksyenEnabled = true;
        vm.JabatanEnabled = true;
        vm.NoUserMessage = false;

        vm.SelectedTimbalan = "";
        vm.SelectedJabatan = "";
        vm.SelectedCawangan = "";
        vm.SelectedUnits = "";
        vm.AssignTo = "";

        vm.actWorkflowAssignToJabatanOption = [];
        vm.actWorkflowAssignToCawanganOption = [];
        vm.actWorkflowAssignToUnitOption = [];
        vm.UserResultOption = [];

        vm.JabatanOption = [];
        vm.CawanganOption = [];
        vm.UnitOption = [];


    }

    vm.ResetHierarchyDocUnit = function () {
        vm.SeksyenEnabledDocUnit = true;
        vm.JabatanEnabledDocUnit = true;

        vm.SelectedTimbalanDocUnit = "";
        vm.SelectedJabatanDocUnit = "";
        vm.SelectedCawanganDocUnit = "";
        vm.SelectedUnitsDocUnit = "";
        // vm.AssignTo = "";

        vm.actWorkflowAssignToJabatanOptionDocUnit = [];
        vm.actWorkflowAssignToCawanganOptionDocUnit = [];
        vm.actWorkflowAssignToUnitOptionDocUnit = [];
        //vm.UserResultOption = [];

        vm.JabatanOptionDocUnit = [];
        vm.CawanganOptionDocUnit = [];
        vm.UnitOptionDocUnit = [];
    }



    vm.SelectHierarchy = function () {
        vm.UserResultOption = [];
        m = [];

        if (vm.SelectedUnits != "" && vm.SelectedUnits != null) {
            m = $filter('filter')(vm.WorkflowAssignToUnitOption, {
                ID: vm.SelectedUnits
            }, true);
        }
        else if (vm.SelectedCawangan != "" && vm.SelectedCawangan != null) {
            m = $filter('filter')(vm.WorkflowAssignToCawanganOption, {
                ID: vm.SelectedCawangan
            }, true);
        }
        else if (vm.SelectedJabatan != "" && vm.SelectedJabatan != null) {
            m = $filter('filter')(vm.WorkflowAssignToJabatanOption, {
                ID: vm.SelectedJabatan
            }, true);
        }

        else if (vm.SelectedTimbalan != "" && vm.SelectedTimbalan != null) {
            m = $filter('filter')(vm.WorkflowAssignToSeksyenOption, {
                ID: vm.SelectedTimbalan
            }, true);
        }

        if (m && (m.length != 0)) {

            vm.UserResultOption = m;
            vm.AssignTo = m[0];
        }

    }


    vm.SelectHierarchyDocUnit = function () {
        vm.UnitPenerimaanDocOption = [];
        m = [];

        if (vm.SelectedUnitsDocUnit != "" && vm.SelectedUnitsDocUnit != null) {
            m = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, {
                ID: vm.SelectedUnitsDocUnit
            }, true);
        }
        else if (vm.SelectedCawanganDocUnit != "" && vm.SelectedCawanganDocUnit != null) {
            m = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, {
                ID: vm.SelectedCawanganDocUnit
            }, true);
        }
        else if (vm.SelectedJabatanDocUnit != "" && vm.SelectedJabatanDocUnit != null) {
            m = $filter('filter')(vm.WorkflowAssignToJabatanOptionDocUnit, {
                ID: vm.SelectedJabatanDocUnit
            }, true);
        }

        else if (vm.SelectedTimbalanDocUnit != "" && vm.SelectedTimbalanDocUnit != null) {
            m = $filter('filter')(vm.WorkflowAssignToSeksyenOptionDocUnit, {
                ID: vm.SelectedTimbalanDocUnit
            }, true);
        }
        if (m && (m.length != 0)) {
            vm.UnitPenerimaanDocOption = m;
            //if (vm.activity.NotaTemuduga != null && vm.activity.NotaTemuduga.NTUnitID) {
            vm.activity.NotaTemuduga.NTUnit = m[0];

            $scope.terimDocForm.$dirty = true;
            $scope.terimDocForm.$pristine = false;
            $scope.terimDocForm.NotaTemuduga_NTUnitName.$dirty = true;
            $scope.terimDocForm.NotaTemuduga_NTUnitName.$pristine = false;
            //}

        }
    }

    // datepicker
    vm.openDateFrom = function () {
        vm.dateFromOpened = true;
    };

    vm.openDateTo = function () {
        vm.dateToOpened = true;
    };

    vm.clearDateFrom = function () {
        vm.DateFrom = null;
        vm.DateFrom.$dirty = true;
        vm.DateFrom.$pristine = false;
    };
    vm.clearDateTo = function () {
        vm.DateTo = null;
        vm.DateTo.$dirty = true;
        vm.DateTo.$pristine = false;
    };

    vm.clearLetterReceiveddate = function (makPerinciForm) {
        vm.activity.LetterFaxReceived = '';
        vm.activity.LetterFaxReceived.$setViewValue = '';
        makPerinciForm.$pristine = false;
        makPerinciForm.$dirty = true;
        makPerinciForm.LetterFaxReceived.$dirty = true;
    };

    vm.clearEmailReceiveddate = function (makPerinciForm) {
        vm.tempEmail.EmailReceivedDate = '';
        vm.tempEmail.EmailReceivedDate.$setViewValue = '';
        makPerinciForm.$pristine = false;
        makPerinciForm.$dirty = true;
        makPerinciForm.ActEmail_EmailReceivedDate.$dirty = true;
    };

    vm.clearPTPDate = function (makPerinciForm) {
        vm.activity.PromiseToPayDate = '';
        vm.activity.PromiseToPayDate.$setViewValue = '';
        makPerinciForm.$pristine = false;
        makPerinciForm.$dirty = true;
        makPerinciForm.PromiseToPayDate.$dirty = true;
        vm.isEditAnsuranActData = true;
    };

    vm.clearTarikhMulaAnsuran = function (makPerinciForm) {
        vm.activity.TarikhMulaAnsuran = '';
        vm.activity.TarikhMulaAnsuran.$setViewValue = '';
        makPerinciForm.$pristine = false;
        makPerinciForm.$dirty = true;
        makPerinciForm.TarikhMulaAnsuran.$dirty = true;
        vm.isEditAnsuranActData = true;
    };

    vm.clearNTTarikhTerima = function (terimDocForm) {
        vm.activity.NotaTemuduga.NTTarikhTerima = '';
        vm.activity.NotaTemuduga.NTTarikhTerima.$setViewValue = '';
        terimDocForm.$pristine = false;
        terimDocForm.$dirty = true;
        terimDocForm.NotaTemuduga_NTTarikhTerima.$dirty = true;
    };

    vm.clearTarikhDokumenItem = function (terimDocForm, item, katDoc) {
        item.TarikhDokumen = '';
        terimDocForm.$pristine = false;
        terimDocForm.$dirty = true;
        vm.validateFieldChanged(katDoc);
    };


    vm.UploadTranskrip = function () {
        $('#fileUploadTranskripHidden').click();
    };

    vm.triggerClickHiddenFileUpload = function (id) {
        $('#' + id).click();
    };


}