crmApp.controller("CaseController", CaseController);

function CaseController($scope, $window, $mdDialog, $q, CaseSI, ActivitySI, TaxPayerService, $filter, $timeout, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, QRCodeSI, TaxPayerSI, AntiForgeryService, GeneralService, Upload, TaskSI, UserSI) {
    var vm = this;
    var TabID = "01";
    var TabType = "Profile";
    var constAssignToTypeUnit = 20;
    var constAssignToTypeUser = 21;
    var constAttachmentSizeID = 14;
    var constAttachmentAcceptedFileTypeID = 15;
    var constBelumSelesai = "belum selesai";
    var constSelesaiStatus = 1;
    var constSaveAndCloseConfirmMsg = "Adakah anda pasti untuk simpan dan menutup kes ini?";
    var constCloseConfirmMsg = "Anda telah memilih untuk menutup kes ini. Adakah anda pasti?";
    var constCloseAllActDesc = 'Notis: Dengan menutup kes ini, semua aktiviti yang berstatus "Belum Selesai" dan telah dipautkan dengan kes ini akan ditutup.';
    var constCloseActDesc = 'Notis: Dengan menutup kes ini, semua aktiviti yang berstatus "Belum Selesai" dan telah dipautkan dengan kes ini akan ditutup.';
    var isKategoriChanged = false;
    vm.IsAssignedUser = false;
    vm.CaseId = $window.caseid;
    vm.ActId = $window.activityid;
    //vm.TransferToCaseFunc = $window.transfertocaseFunc;
    vm.ChangesHistory = [];
    vm.case = {};
    vm.GenQRCode = false;
    AntiForgeryService.cookieToken = $window.cookietoken;
    AntiForgeryService.formToken = $window.formtoken;
    vm.hdrTempl = 'loading';
    vm.Users = [];
    vm.Units = [];
    vm.TempUser = [];
    vm.TempUnit = [];
    vm.IsUnitChoose = true;
    vm.showdetail = false;
    vm.optionWording = 'More Option'

    vm.Validation = {};
    vm.Validation.Money = GeneralService.Validation.Money;
    vm.Validation.MoneyMsg = GeneralService.Validation.MoneyMsg;

    //Disable the Search TP edit button on header 
    TaxPayerService.TP.AllowEdit = false;
    vm.InvalidStatusSelected = false;

    vm.SeksyenEnabledDocUnit = true;
    vm.JabatanEnabledDocUnit = true;
    vm.constActChannelCFF = 8;


    vm.init = function () {
        //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);
        }
        tabAction(TabID, TabType);

        // datepicker
        vm.dateFromMinDate = null;
        vm.dateFromMaxDate = null;
        vm.buttonBarObj = $scope.ButtonBar;
        console.log(vm.buttonBarObj);
        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');
            }
        };
        // Letter received date        
        vm.tarikhStatusOptions = {
            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
        };
        // NTTarikhTerima
        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
        };

        // TODO : To be replace with data passed from DB
        vm.UsersOption = [];
        isKategoriChanged = true;
        if (parseInt(vm.CaseId)) {
            //Load Case data
            var a = CaseSI.getCase(vm.CaseId).then(function (r) {
                if (r.status === 200) {
                    vm.case = r.data;

                    vm.IsDelete = r.data.IsDelete;
                    vm.IsShowPenerimaanDocTab = vm.case.IsShowPenerimaanDocTab;
                    vm.CanCloseCase = vm.case.CanCloseCase;
                    console.log(vm.case);
                    for (var key in r.data) {
                        switch (key) {

                            //Decimal
                            case "NilaiKes":
                                vm.case[key] = $filter('number')(r.data[key], 2);
                                break;

                                //Convert to DateTime
                            case "CreatedDateTime":
                            case "LastUpdatedDateTime":
                                if (r.data[key] == "1900-01-01T00:00:00")
                                    vm.case[key] = "";
                                else
                                    vm.case[key] = $filter('date')(r.data[key], $scope.DateTimeFormat);
                                break;

                            default:
                                vm.case[key] = r.data[key];
                        }
                    }


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

                    ////bind date control
                    //if (r.data.NotaTemuduga != null) {
                    //    vm.case.NotaTemuduga.NTTarikhDokumen = r.data.NotaTemuduga.NTTarikhDokumen == null ? "" : $filter('date')(new Date(r.data.NotaTemuduga.NTTarikhDokumen), 'dd MMM yyyy');
                    //    vm.case.NotaTemuduga.NTTarikhTerima = r.data.NotaTemuduga.NTTarikhTerima == null ? "" : $filter('date')(new Date(r.data.NotaTemuduga.NTTarikhTerima), 'dd MMM yyyy');
                    //}

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

                    //bind TPHeader
                    bindHeader(objTP, vm.case.TP);

                    //drop down menu
                    CaseSI.getCaseDropdown().then(function (r) {
                        if (r.status == 200) {
                            for (var key in r.data) {
                                vm[key] = r.data[key];
                            }

                            vm.WorkflowAssignToSeksyenOptionDocUnit = r.data["WorkflowAssignToSeksyenOption"];
                            vm.WorkflowAssignToJabatanOptionDocUnit = r.data["WorkflowAssignToJabatanOption"];
                            vm.WorkflowAssignToCawanganOptionDocUnit = r.data["WorkflowAssignToCawanganOption"];
                            vm.WorkflowAssignToUnitOptionDocUnit = r.data["WorkflowAssignToUnitOption"];

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

                            //bind the cascading KATEGORI
                            vm.kategori1Changed(vm.case.Kategori1ID);
                            vm.kategori2Changed(vm.case.Kategori2ID);

                            //bind the cascading STATUS
                            vm.status1Changed(vm.case.CaseStatusLevel1ID);
                            vm.status2Changed(vm.case.CaseStatusLevel2ID);

                            //bind the cascading TINDAKAN SUSULAN
                            vm.kempenAndKodChanged(vm.case.KodSelesaiID, vm.case.JenisKempenID, 'Agent'); //Temp hardcode 'Agent'

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

                            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;
                            }


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

                            //notatemuduga
                            // Q : added not null checking
                            //if (vm.case.NotaTemuduga != null && vm.case.NotaTemuduga.NTUnitID) {
                            //    var m = $filter('filter')(vm.UnitPenerimaanDocOption, { ID: vm.case.NotaTemuduga.NTUnitID });
                            //    if (m && (m.length > 0)) {
                            //        vm.case.NotaTemuduga.NTUnit = m[0];
                            //    }
                            //}

                            if (!vm.case.NotaTemuduga.NTTarikhTerima) {
                                vm.case.NotaTemuduga.NTTarikhTerima = new Date();//$filter('date')(new Date(), 'dd MMM yyyy');
                            }
                        }
                    });




                    vm.hdrTempl = 'tp.profile.header';

                    if (vm.case.WorkflowDetail != null) {
                        vm.CreatedBy = vm.case.WorkflowDetail.AssignByName;
                        vm.AssignTo = vm.case.WorkflowDetail.AssignTo;
                        //vm.Remarks = t.data.Remarks;
                        vm.UserType = vm.case.WorkflowDetail.AssignToTypeID;
                        vm.WorkFlowId = vm.case.WorkflowDetail.WorkflowID;
                        // TODO 

                        vm.HideCreatedBy = false;
                        //  Is Assignor and Assignee
                        if (vm.case.WorkflowDetail.IsCurrentLogin && vm.case.WorkflowDetail.IsOtherLogin) {
                            vm.IsRecall = false;
                            vm.IsReturn = false;
                            vm.IsAssign = true;
                            vm.IsOtherLogin = false;
                            vm.HideCreatedBy = true;
                        }// Is Assignee only
                        else if (vm.case.WorkflowDetail.IsCurrentLogin && !vm.case.WorkflowDetail.IsOtherLogin) {
                            vm.IsRecall = false;
                            vm.IsReturn = true;
                            vm.IsAssign = true;
                            vm.IsOtherLogin = false;
                        }// Is Assignor only
                        else if (!vm.case.WorkflowDetail.IsCurrentLogin && vm.case.WorkflowDetail.IsOtherLogin) {
                            vm.IsRecall = true;
                            vm.IsReturn = false;
                            vm.IsAssign = false;
                            vm.IsOtherLogin = false;
                        }
                        else {
                            vm.IsRecall = false;
                            vm.IsReturn = false;
                            vm.IsAssign = false;
                            vm.IsOtherLogin = true;
                        }
                        //if (vm.case.WorkflowDetail.IsCurrentLogin) {   //AssignToLogin Match
                        //    if (vm.case.WorkflowDetail.AssignToLogin.toLowerCase() == vm.case.WorkflowDetail.AssignBy.toLowerCase()) {
                        //        vm.IsRecall = false;
                        //        vm.IsReturn = false;
                        //        vm.IsAssign = true;
                        //        vm.IsOtherLogin = false;
                        //        vm.HideCreatedBy = true;
                        //    }
                        //    else {
                        //        if (vm.case.WorkflowDetail.AssignToTypeID == constAssignToTypeUnit) {
                        //            vm.IsRecall = true;
                        //            vm.IsReturn = false;
                        //            vm.IsAssign = false;
                        //            vm.IsOtherLogin = false;
                        //            vm.HideCreatedBy = false;
                        //        }
                        //        else {
                        //            vm.IsRecall = false;
                        //            vm.IsReturn = true;
                        //            vm.IsAssign = true;
                        //            vm.IsOtherLogin = false;
                        //        }
                        //    }
                        //}
                        //else {
                        //    if (vm.case.WorkflowDetail.IsOtherLogin) {   //Other than AssignTo and Assign By // Is Assignor
                        //        vm.IsRecall = false;
                        //        vm.IsReturn = false;
                        //        vm.IsAssign = false;
                        //        vm.IsOtherLogin = true;
                        //    }
                        //    else if (vm.case.WorkflowDetail.IsCurrentLogin) { // Is Assigned to
                        //        vm.IsRecall = true;        //AssignBy
                        //        vm.IsReturn = false;
                        //        vm.IsAssign = false;
                        //        vm.IsOtherLogin = false;
                        //    }
                        //    else {
                        //        vm.IsRecall = false;        // Third person
                        //        vm.IsReturn = false;
                        //        vm.IsAssign = false;
                        //        vm.IsOtherLogin = false;
                        //    }

                        //}

                        // if Assign To People didnot have manager
                        if (vm.case.WorkflowDetail.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.TPID;

                        //By Unit
                        var Kategory = {
                            Kategori1: r.data.Kategori1ID,
                            Kategori2: r.data.Kategori2ID,
                            Kategori3: r.data.Kategori3ID,
                            AssignToType: 20,
                            TPID: r.data.TP.TPID
                        }

                        CaseSI.getWorkFlowAssignToByKategoryId(Kategory).then(function (s) {
                            if (s.data.ID != null && s.data.ID > 0) {
                                vm.Users = [s.data];
                                vm.TempUnit = vm.Users[0];
                                vm.AssignTo = vm.Users[0];
                                vm.UserType = constAssignToTypeUnit;
                                vm.AssignToDisable = true;

                                isKategoriChanged = false;
                            }
                            else {

                                if (vm.TempUnit.length == 0 && vm.case.NotaTemuduga != null && vm.case.NotaTemuduga.NTUnitID > 0)
                                {
                                    var UnitID = vm.case.NotaTemuduga.NTUnitID;
                                    CaseSI.getCaseAssignDefaultUnitByUnitID(UnitID).then(function (r) {
                                        if (r.data.ID != null) {
                                            vm.Users = [r.data];
                                            vm.TempUnit = vm.Users[0];
                                            vm.AssignTo = vm.Users[0];
                                            vm.UserType = constAssignToTypeUnit;
                                            vm.AssignToDisable = true;
                                            vm.AssignOther = false;
                                            vm.showdetail = false;

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

                                    CaseSI.getWorkFlowSearchUserOrUnit(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.TempUser = vm.Users[0];
                                                vm.AssignTo = vm.Users[0];
                                                vm.UserType = constAssignToTypeUser;
                                                vm.AssignToDisable = true;
                                            }
                                        }
                                        else {
                                            vm.AssignTo = null;
                                            vm.UserType = 0;
                                            vm.AssignToDisable = false;
                                            vm.AssignOther = true;
                                        }
                                    });
                                }
                            }
                        });
                    }

                    formatDatePickerDates();
                    if (vm.case.NotaTemuduga.QRCode != null) {
                        addQRCodeGeneratedCSS();
                    }
                }
            });

            getChangeHistoryAndActivity();
            if ($window.caseid > 0) {
                getTaskList();
            }

        }
        else if (parseInt(vm.ActId)) { //Transfer to Case

            var actID = parseInt(vm.ActId);
            var a = ActivitySI.getActivity(actID).then(function (r) {
                //console.log("data", r.data);
                vm.case = r.data;
                vm.CanCloseCase = r.data.CanCloseCase;
                vm.case.NilaiKes = $filter('number')(r.data.NilaiKes, 2);
                vm.case.CaseStatusLevel1ID = r.data.ActStatus1ID;
                vm.case.CaseStatusLevel2ID = r.data.ActStatus2ID;
                vm.case.CaseStatusLevel3ID = r.data.ActStatus3ID;
                vm.case.AssignedDateTime = "";
                vm.case.CreatedBy = "";
                vm.case.CreatedByName = "";
                vm.case.CreatedDateTime = "";
                vm.case.LastUpdatedBy = "";
                vm.case.LastUpdatedByName = "";
                vm.case.LastUpdatedDateTime = "";
                vm.case.TotalActBlmSelesai = 0; //default to 0 when new case created, after save only have activity
                vm.case.TotalActivity = 1;
                vm.case.CaseID = null;
                vm.case.CaseRefNo = null;
                vm.case.AllDocReceived = r.data.AllDocReceived;
                vm.case.TotalTaskBlmSelesai = 0; //default to 0 when new case created
                vm.HideCreatedBy = true;

                CaseSI.getAllCatatan(actID).then(function (resp) {
                    vm.case.CatatanLst = resp.data;
                    //console.log(resp.data);
                });

                //drop down menu
                CaseSI.getCaseDropdown().then(function (r) {
                    if (r.status == 200) {
                        for (var key in r.data) {
                            vm[key] = r.data[key];
                        }

                        vm.WorkflowAssignToSeksyenOptionDocUnit = r.data["WorkflowAssignToSeksyenOption"];
                        vm.WorkflowAssignToJabatanOptionDocUnit = r.data["WorkflowAssignToJabatanOption"];
                        vm.WorkflowAssignToCawanganOptionDocUnit = r.data["WorkflowAssignToCawanganOption"];
                        vm.WorkflowAssignToUnitOptionDocUnit = r.data["WorkflowAssignToUnitOption"];

                        var a = $filter('filter')(vm.AliranOptions, { Value: vm.case.AliranID }, true);
                        if (a.length != 0) {
                            vm.SelectedAliran = a[0].Code;
                            vm.case.TotalAliranMasuk = vm.SelectedAliran == 'IN' ? 1 : 0;
                            vm.case.TotalAliranKeluar = vm.SelectedAliran == 'OUT' ? 1 : 0;
                        }

                        //vm.activity.ActChannelID = vm.activity.ActChannelID == undefined ? null : vm.activity.ActChannelID;
                        var m = $filter('filter')(vm.ActChannelOptions, { ActChannelID: vm.case.ActChannelID }, true);
                        if (m && (m.length > 0)) {
                            vm.IsShowPenerimaanDocTab = m[0].IsShowPenerimaanDocTab;
                        }

                        //bind the cascading KATEGORI
                        vm.kategori1Changed(vm.case.Kategori1ID);
                        vm.kategori2Changed(vm.case.Kategori2ID);
                        vm.kategori3Changed(vm.case.Kategori3ID)

                        //bind the cascading STATUS
                        vm.status1Changed(vm.case.CaseStatusLevel1ID);
                        vm.status2Changed(vm.case.CaseStatusLevel2ID);

                        //bind the cascading TINDAKAN SUSULAN
                        vm.kempenAndKodChanged(vm.case.KodSelesaiID, vm.case.JenisKempenID, 'Agent'); //Temp hardcode 'Agent'

                        var objTP = {
                            TPID: vm.case.TP ? vm.case.TP.TPID : 0, //If vm.case.TP is null, orphan - set TPID to 0
                            TPName: vm.case.TPName,
                            TPJenisPengenalan: vm.case.TPJenisPengenalan,
                            TPIDNumber: vm.case.TPIDNumber,
                            TPNoCukai: vm.case.TPNoCukai
                        };

                        bindHeader(objTP, vm.case.TP);

                        if (vm.case.TP != null) {
                            vm.TPID = vm.case.TP.TPID;
                        }

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

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


                        //notatemuduga
                        // Q : added not null checking
                        //if (vm.case.NotaTemuduga != null && vm.case.NotaTemuduga.NTUnitID) {
                        //    var m = $filter('filter')(vm.UnitPenerimaanDocOption, { ID: vm.case.NotaTemuduga.NTUnitID });
                        //    //var m = $filter('filter')(vm.UserResultOption, { ID: vm.case.NotaTemuduga.NTUnitID });
                        //    if (m && (m.length > 0)) {
                        //        vm.case.NotaTemuduga.NTUnit = m[0];
                        //    }
                        //}
                    }
                });
                console.log(vm.case);

                //var objTP = {
                //    TPName: vm.case.TPName,
                //    TPJenisPengenalan: vm.case.TPJenisPengenalan,
                //    TPIDNumber: vm.case.TPIDNumber,
                //    TPNoCukai: vm.case.TPNoCukai
                //};
                //bindHeader(objTP, vm.activity.TP);
                //if (r.data.TP != null)
                //    bindHeader(r.data.TP);
                //else { //Orphan Activity
                //    TaxPayerService.TP.Name = vm.case.TPName;
                //    var a = $filter('filter')(vm.JenisPengenalanOptions, { Value: vm.case.TPIDType });
                //    if (a.length != 0) {
                //        TaxPayerService.TP.TPType = a[0].Text;
                //    }
                //    TaxPayerService.TP.IDNo = vm.case.TPIDNumber;
                //    TaxPayerService.TP.TaxNo = vm.case.TPNoCukai; //Only TaxNo, NO CukaiCode
                //}

                vm.hdrTempl = 'tp.profile.header';

                vm.HideCreatedBy = true;
                vm.IsRecall = false;
                vm.IsReturn = false;
                vm.IsAssign = true;

                // Set Assign To default value When first time load workflow
                //Unit
                var Kategory = {
                    Kategori1: vm.case.Kategori1ID,
                    Kategori2: vm.case.Kategori2ID,
                    Kategori3: vm.case.Kategori3ID,
                    AssignToType: 20

                }

                CaseSI.getWorkFlowAssignToByKategoryId(Kategory).then(function (s) {
                    if (s.data.ID != null) {
                        vm.Users = [s.data];
                        vm.TempUnit = vm.Users[0];
                        vm.AssignTo = vm.Users[0];
                        vm.UserType = constAssignToTypeUnit;
                        vm.AssignToDisable = true;
                    }
                    else {
                        //Manager 
                        var data = {
                            keyword: "",
                            AssignToType: constAssignToTypeUser

                        }

                        CaseSI.getWorkFlowSearchUserOrUnit(data).then(function (u) {
                            if (u.data.length > 0) {
                                var m = u.data;
                                if (m.length != 0) {
                                    vm.Users = m;
                                    vm.TempUser = vm.Users[0];
                                    vm.AssignTo = vm.Users[0];
                                    vm.UserType = constAssignToTypeUser;
                                    vm.AssignToDisable = true;

                                }
                            }
                            else {
                                vm.UserType = 0;
                                vm.AssignTo = null
                                vm.AssignToDisable = false;
                            }
                        });
                    }
                });

                formatDatePickerDates();

                if (vm.case.NotaTemuduga != null) {
                    vm.case.NotaTemuduga.QRCode = undefined;
                    vm.case.NotaTemuduga.QRCodeDate = undefined;
                }
            });
        }


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

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

    function formatDatePickerDates() {
        if (vm.case.NotaTemuduga)
            if (vm.case.NotaTemuduga.NTTarikhTerima)
                vm.case.NotaTemuduga.NTTarikhTerima = new Date(vm.case.NotaTemuduga.NTTarikhTerima);//$filter('date')(new Date(vm.case.NotaTemuduga.NTTarikhTerima), 'dd MMM yyyy');

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

    }

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

            data.CaseID = $window.caseid;
            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.dtColumnsCaseChangesHistory = [
            //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.dtOptionsCaseChangesHistory = 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

        //Get Activities List
        //vm.Kategori1Act = {};
        //vm.Kategori2Act = {};
        vm.ActAliran = {};
        vm.ActChn = {};
        vm.ActStatus = {};
        var ajaxCallbackAL = function (data, callback, settings) {
            data.CaseID = $window.caseid;
            //data.Kategori1ID = !vm.Kategori1Act ? "" : vm.Kategori1Act.Kategori1ID;
            //data.Kategori2ID = !vm.Kategori2Act ? "" : vm.Kategori2Act.Kategori2ID;
            //data.Kategori3ID = !vm.Kategori3Act ? "" : vm.Kategori3Act.Kategori3ID;
            data.ActChannelID = !vm.ActChn ? "" : vm.ActChn.ActChannelID;
            data.AliranID = !vm.ActAliran ? "" : vm.ActAliran.Value;
            data.ActStatusID = !vm.ActStatus ? "" : vm.ActStatus.Value;
            data.ActivityNo = vm.ActivityNo;

            ActivitySI.getPagedActivityListByID(data).then(function (r) {
                if (r.status == 200) {
                    console.log(r.data);
                    if (!vm.firstActivityID) {
                        var m = $filter('orderBy')(r.data.data, 'ActivityID');
                        if (m && m.length > 0) {
                            vm.firstActivityID = m[0].ActivityID;
                        }
                    }
                    console.log(r.data);
                    callback(r.data);
                }
            });
        }

        //Bind table - start 
        vm.dtColumnsActivityList = [
            //DTColumnBuilder.newColumn('ID').withTitle('ID'),
            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('ActivityID').withTitle('No. Aktiviti').renderWith(renderActlink).withOption('width', '14%'),
            DTColumnBuilder.newColumn('ActChannelName').withTitle('Aktiviti').withOption('width', '11%'),
            DTColumnBuilder.newColumn('Aliran').withTitle('Aliran').withOption('width', '9%'),
            DTColumnBuilder.newColumn('Kategori1Name').withTitle('Kategori').renderWith(renderKategori).withOption('width', '29%'),
            DTColumnBuilder.newColumn('Status').withTitle('Status').withOption('width', '8%'),
            DTColumnBuilder.newColumn('LastUpdatedByName').withTitle('Dikemaskini Oleh').withOption('width', '15%'),
            DTColumnBuilder.newColumn('LastUpdatedDateTime').withTitle('Tarikh Dikemaskini').renderWith(function (data, type) {
                return $filter('date')(data, $scope.DateTimeFormat);
            }).withOption('width', '12%'),

        ];

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

        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
        }

        //function renderAliran(data, type, row, meta) {
        //    //    var str = "" + row.OutboundID;
        //    //    var pad = "0000000000";
        //    //    var paddedStr = pad.substring(0, pad.length - str.length) + str;
        //    //    var outboundLink = '<a href="/Outbound/Profile/detail/' + row.OutboundID + '" target="_blank"> ' + paddedStr + '</a>';//to do after outbound page link available
        //    //    return data == 'Masuk' ? ' <span class="arrow" style="padding:5px;"><i style="transform:rotate(-45deg)" class="fa fa-arrow-down"  title="Masuk"></i></span>'
        //    //: '<span class="arrow outboundArrow" style="padding:5px;"> <i style = "transform:rotate(-45deg)" class="fa fa-arrow-up" title="Keluar"></i>' + outboundLink + '</span>';
        //    var link = '';

        //    switch (row.ActChannelID) {
        //        case (2)://email
        //            if (row.HCLEmailBlastID > 0)
        //                link = '<a title="HCL Email Blast ID" href="/Outbound/Profile/detail/' + row.HCLEmailBlastID + '" target="_blank"> ' + row.HCLEmailBlastID + '</a>' //todo when profile available
        //            break;
        //        case (5)://phone
        //            if (row.OutboundID > 0)
        //                link = '<a title="Outbound ID" href="/HCLEmailBlast/Profile/detail/' + row.OutboundID + '" target="_blank"> ' + row.OutboundID + '</a>' //todo when profile available
        //            console.log(link);
        //            break;
        //    }

        //    return data == 'Masuk' ? ' <span class="arrow" style="padding:5px;"><i style="transform:rotate(-45deg)" class="fa fa-arrow-down"  title="Masuk"></i></span>'
        //        : '<span class="arrow outboundArrow" style="padding:5px;"> <i style = "transform:rotate(-45deg)" class="fa fa-arrow-up" title="Keluar"></i>' + link + '</span>';
        //}

        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
        }

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

    function getTaskList() {
        vm.TaskStatus = {};
        var ajaxCallbackTL = function (data, callback, settings) {
            data.CaseID = $window.caseid;
            data.StatusID = vm.TaskStatus == null ? 0 : vm.TaskStatus.Value; //if TaskStatus = ALL = null = 0 
            TaskSI.getPagedTaskListByID(data).then(function (r) {
                if (r.status == 200) {
                    console.log(r.data);
                    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', '13%'),
            //DTColumnBuilder.newColumn('ActivityID').withTitle('Activity No.').renderWith(renderActlink).withOption('width', '11%'),
            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, 'dd MMM yyyy');
            }).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


    }

    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;
    }

    vm.redirectTo = function (url) {

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

    vm.toggleChangeTPProfile = toggleChangeTPProfile;
    function toggleChangeTPProfile(toggle) {
        if (toggle == true) {

        }
    }

    vm.tabAction = tabAction;
    function tabAction(cls, type, init) {
        TabID = cls;
        TabType = type;
        reset();
        if (init) { getLatestTab(); }
        switch (cls) {
            case '01':
                type == "Profile" ? tabProfile01Click() : tabServices01Click();
                break;
            case '02':
                type == "Profile" ? tabProfile02Click() : tabServices02Click();
                break;
            case '03':
                type == "Profile" ? tabProfile03Click() : tabServices03Click();
                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);
    }

    //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);
    }

    //Services Tab 03
    vm.tabServices03Click = tabServices03Click;
    function tabServices03Click() {
        vm.IsServicesTab = vm.tabServices03Active = 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.tabServices01Active = false;
        vm.tabServices02Active = false;
        vm.tabServices03Active = false;
    }

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

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

    vm.getAttachment = function (AttachID, Type, $event) {
        if (Type == 'A') Type = 'ActCatatan';
        if (Type == 'C') Type = 'CaseCatatan';
        //act.WindowUnloadEventEnable=false; 
        $event.preventDefault();
        WindowUnloadEventEnable = false;
        $window.open((CaseSI.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 = CaseSI.deleteAttachment(AttachID);
            var result = update.then(function (r) {
                if (r.status === 200) {
                    $scope.myCaseForm.$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.CaseCatatan.CatatanAttachmentList) {
                                var index = vm.CaseCatatan.CatatanAttachmentList.indexOf(objfile);
                                if (index != -1) {
                                    vm.CaseCatatan.CatatanAttachmentList.splice(index, 1);
                                }
                            }
                            break;
                        case 3:
                            if (vm.CaseCatatanEdit.CatatanAttachmentList) {
                                var index = vm.CaseCatatanEdit.CatatanAttachmentList.indexOf(objfile);
                                if (index != -1) {
                                    vm.CaseCatatanEdit.CatatanAttachmentList.splice(index, 1);
                                }
                            }
                            break;
                    }
                } else {
                    swal("Gagal!", r.data, "error");
                }

            });
        } else {  //delete from saved attachments
            $scope.myCaseForm.$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.CaseCatatan.CatatanAttachmentList) {
                        var index = vm.CaseCatatan.CatatanAttachmentList.indexOf(objfile);
                        if (index != -1) {
                            vm.CaseCatatan.CatatanAttachmentList.splice(index, 1);
                        }
                    }
                    break;
                case 3:
                    if (vm.CaseCatatanEdit.CatatanAttachmentList) {
                        var index = vm.CaseCatatanEdit.CatatanAttachmentList.indexOf(objfile);
                        if (index != -1) {
                            vm.CaseCatatanEdit.CatatanAttachmentList.splice(index, 1);
                        }
                    }
                    break;
            }
        }
    }

    vm.uploadFiles = function (files, errFiles, type) {
        //type : 1 - Activity ,  2 - Catatan, 3 - CatatanEdit
        var result = returnPromise();;
        var promises = [];
        var promiseUpload = returnPromise(); //return a promise;

        vm.f = files;
        vm.uploadFileType = type;

        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(CaseSI.uploadAttachment(file));
                    promises.push(file.upload);
                    file.upload.then(function (r) {
                        $timeout(function () {
                            $scope.myCaseForm.$dirty = true;
                            r.data.AttachmentID = null;
                            isUploaded = true;
                            switch (type) {
                                //case 1:
                                //    if (!vm.activity.ActAttachmentList) { vm.activity.ActAttachmentList = []; }
                                //    vm.activity.ActAttachmentList.push(r.data);
                                //    break;
                                case 2:
                                    if (!vm.CaseCatatan.CatatanAttachmentList) { vm.CaseCatatan.CatatanAttachmentList = []; }
                                    r.data.FileType = getFileType(r.data.FileName, r.data.FileContentType);
                                    vm.CaseCatatan.CatatanAttachmentList.push(r.data);
                                    break;
                                case 3:
                                    if (!vm.CaseCatatanEdit.CatatanAttachmentList) { vm.CaseCatatanEdit.CatatanAttachmentList = []; }
                                    r.data.FileType = getFileType(r.data.FileName, r.data.FileContentType);
                                    vm.CaseCatatanEdit.CatatanAttachmentList.push(r.data);
                                    vm.IsEditCatatanFile = true;
                                    break;
                            }

                        });
                    }, function (r) {
                        file.$error = r.status + ': ' + r.data;
                        errFiles || (errFiles = []);
                        errFiles.push(file);
                    }, function (evt) {
                        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;
                    });
                }
            }
            promiseUpload = $q.all(promises);
        }
        else {
            promiseUpload = returnResultPromise();
        }
        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*/

    vm.catatanIncludes = ['App', 'C', 'A'];

    vm.includeCatatan = function (type) {
        var i = $.inArray(type, vm.catatanIncludes);
        if (i > -1) { // if it's include in catatanIncludesList
            vm.catatanIncludes.splice(i, 1);
        } else {
            vm.catatanIncludes.push(type);
        }
    }

    var catatanList = vm.CatatanLst;
    vm.catatanFilter = function (catatanList) {
        if (vm.catatanIncludes.length > 0) {
            if ($.inArray(catatanList.CatatanType, vm.catatanIncludes) < 0)
                return;
        } else {
            return null;
        }
        return catatanList;
    }

    /*Catatan tab*/
    vm.CaseCatatan = {}; //Obj used for New Catatan
    vm.CaseCatatanEdit = {}; //Obj used for Edit Catatan 

    vm.InsertCaseCatatan = function (indicator) {
        if (indicator == 1) { //insert
            if (!vm.CaseCatatan.Catatan) {
                vm.showRequiredMsg = true;
            } else {
                vm.showRequiredMsg = false;
            }
        } else if (indicator == 2) { //update
            if (!vm.CaseCatatanEdit.Catatan) {
                vm.showRequiredMsgPopup = true;
            } else {
                vm.showRequiredMsgPopup = false;
            }
        }

        if (indicator == 2 && (vm.CaseCatatanEdit.Catatan == vm.OriCatatan) && !vm.IsEditCatatanFile) //check if no change - update
        {
            swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
        }
        else if (!vm.showRequiredMsg && !vm.showRequiredMsgPopup) {

            var model = {};
            if (vm.CaseCatatanEdit.hasOwnProperty('CatatanAttachmentList') == true) {
                vm.CaseCatatanEdit.Indicator = indicator;
                vm.CaseCatatanEdit.CaseID = vm.CaseId;
                model = vm.CaseCatatanEdit;
            }
            else {
                vm.CaseCatatan.Indicator = indicator;
                vm.CaseCatatan.CaseID = vm.CaseId;
                model = vm.CaseCatatan;
            }

            if (!vm.CaseId) {
                swal({
                    title: "Tambah catatan memerlukan kes disimpan. Adakah anda pasti untuk simpan kes ini?",
                    text: "",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonText: "Ya",
                    cancelButtonText: "Tidak",
                    closeOnConfirm: false,
                    closeOnCancel: false
                }, function (isConfirm) {
                    if (isConfirm) {
                        objCaseCatatan = model;
                        vm.saveCase($scope.myCaseForm, 1, true);
                    } else {
                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                    }
                });
            } else {
                UpdateCatatan(model);
            }
        }
    };

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

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

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

        if (!vm.showRequiredMsg) {

            vm.CaseCatatan.CaseID = vm.CaseId;

            if (!vm.CaseId) {
                swal({
                    title: "Tambah catatan memerlukan kes disimpan. Adakah anda pasti untuk simpan kes ini?",
                    text: "",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonText: "Ya",
                    cancelButtonText: "Tidak",
                    closeOnConfirm: false,
                    closeOnCancel: false
                }, function (isConfirm) {
                    if (isConfirm) {
                        result = vm.saveCase($scope.myCaseForm, 1, true);
                    } else {
                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                        result = returnResultPromise();
                    }
                });
            }
            else {
                result = AddNewCaseCatatan(false);
            }
        } else {
            result = returnResultPromise();
        }
        return result == null ? returnResultPromise() : result;
    };

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

    vm.editCatatan = function () {
        if (vm.CaseCatatanEdit.Catatan) {
            vm.showRequiredMsgPopup = false;
        }
        else vm.showRequiredMsgPopup = true;

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

        if (!vm.showRequiredMsgPopup) {

            vm.CaseCatatanEdit.CaseID = vm.CaseId;

            CaseSI.updateCaseCatatan(vm.CaseCatatanEdit).then(function (r) {
                if (r.status === 200) {

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

                    vm.case.CatatanLst = r.data;
                    if (vm.case.CatatanLst) {
                        for (i = 0; i < vm.case.CatatanLst.length; i++)
                            vm.case.CatatanLst[i].Catatan = vm.case.CatatanLst[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.dtInstanceCaseChangesHistory.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
        }, function (isConfirm) {
            if (isConfirm) {
                var model = {};
                model.CaseID = vm.CaseId;
                model.CatatanID = catatanID;
                model.ChangeStamp = changeStamp;
                CaseSI.deleteCaseCatatan(model).then(function (r) {
                    if (r.status === 200) {
                        vm.case.CatatanLst = r.data;
                        if (vm.case.CatatanLst) {
                            for (i = 0; i < vm.case.CatatanLst.length; i++)
                                vm.case.CatatanLst[i].Catatan = vm.case.CatatanLst[i].Catatan.replace(/\n/g, '<br/>');
                        }
                        swal({
                            title: GeneralService.SaveMessage.Title,
                            text: GeneralService.SaveMessage.Text,
                            type: "success",
                            timer: 2500,
                            showConfirmButton: true
                        }, function () {
                            vm.dtInstanceCaseChangesHistory.reloadData();
                        });
                    }
                });
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });
    }

    function AddNewCaseCatatan(isNewCase) {
        var result = null;
        result = CaseSI.addCaseCatatan(vm.CaseCatatan).then(function (r) {
            if (r.status === 200) {

                vm.CaseCatatan = {};

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

                $mdDialog.hide();

                if (isNewCase) {
                    vm.redirectTo('/case/profile/detail/' + vm.case.CaseID + '?t=' + TabID + '&ty=' + TabType);
                }
                else {
                    vm.dtInstanceCaseChangesHistory.reloadData();
                }
                //swal({
                //    title: GeneralService.SaveMessage.Title,
                //    text: GeneralService.SaveMessage.Text,
                //    type: "success",
                //    timer: 2500,
                //    showConfirmButton: true
                //}, function () {
                //    if (isNewCase) {
                //        vm.redirectTo('/case/profile/detail/' + vm.case.CaseID);
                //    }
                //    else {
                //        vm.dtInstanceCaseChangesHistory.reloadData();
                //    }

                //});

            }
        });

        return result;
    }
    // END catatan tab

    function UpdateCatatan(model) {
        var update = CaseSI.updateCaseCatatan(model);
        var result = update.then(function (r) {
            if (r.status === 200) {
                vm.CaseCatatan = {};
                vm.CaseCatatanEdit = {};
                vm.IsEditCatatanFile = false;

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

                $mdDialog.hide();
                swal({
                    title: GeneralService.SaveMessage.Title,
                    text: GeneralService.SaveMessage.Text,
                    type: "success",
                    timer: 2500,
                    showConfirmButton: true
                }, function () {
                    if (objCaseCatatan) {
                        objCaseCatatan = null;
                        vm.redirectTo('/case/profile/detail/' + vm.case.CaseID + '?t=' + TabID + '&ty=' + TabType);
                    } else {
                        if (model.indicator != 1) //Not Insert
                            vm.dtInstanceCaseChangesHistory.reloadData();
                    }
                });
            } else {
                swal("Gagal!", r.data, "error");
            }
        });
    }

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

    vm.kategori1Changed = function (selectedKategori1ID) {
        vm.SubKategoriOptions = [];
        vm.kategori3Disabled = true;
        if (vm.CaseId && vm.CaseId != 0) isKategoriChanged = true;
        if (selectedKategori1ID == undefined) {
            vm.case.Kategori1Name = "";
        } else {
            vm.SubKategoriOptions = [];

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

    vm.kategori2Changed = function (selectedKategori2ID) {
        vm.InnerSubKategoriOptions = [];
        if (vm.CaseId && vm.CaseId != 0) isKategoriChanged = true;
        var m = $filter('filter')(vm.SubKategoriOptions, { Kategori2ID: selectedKategori2ID }, true);
        if (m != undefined && m.length > 0) {
            vm.InnerSubKategoriOptions = m[0].InnerSubKategori;
            vm.case.Kategori2Name = m[0].Kategori2Name;
            vm.kategori3Disabled = m[0].InnerSubKategori.length > 0 ? false : true;
        } else {
            vm.case.Kategori2Name = "";
        }
    };

    vm.kategori3Changed = function (selectedKategori3ID) {
        if (vm.CaseId && vm.CaseId != 0) isKategoriChanged = true;
        var m = $filter('filter')(vm.InnerSubKategoriOptions, { Kategori3ID: selectedKategori3ID }, true);
        if (m != undefined && m.length > 0) {
            vm.case.Kategori3Name = m[0].Kategori3Name;
        } else {
            vm.case.Kategori3Name = "";
        }
    }

    vm.status1Changed = function (selectedStatus1ID) {
        vm.caseStatus2Options = [];
        vm.status3Disabled = false;
        vm.InvalidStatusSelected = false;
        selectedStatus1ID = selectedStatus1ID == undefined ? selectedStatus1ID = null : selectedStatus1ID;
        var m = $filter('filter')(vm.Status1Options, { StatusLevel1ID: selectedStatus1ID }, true);
        if (m != undefined && m.length > 0) {
            vm.caseStatus2Options = m[0].StatusLevel2;
        }

        if (!vm.case.CanCloseCase && selectedStatus1ID == constSelesaiStatus) {
            vm.InvalidStatusSelected = true;
        }
    };

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

        selectedStatus2ID = selectedStatus2ID == undefined ? selectedStatus2ID = null : selectedStatus2ID;
        var m = $filter('filter')(vm.caseStatus2Options, { StatusLevel2ID: selectedStatus2ID }, true);
        if (m != undefined && m.length > 0) {
            vm.caseStatus3Options = m[0].StatusLevel3;
            vm.status3Disabled = m[0].StatusLevel3.length > 0 ? false : true;
        }
    };

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

        vm.caseTindakanSusulanOptions = [];

        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.caseTindakanSusulanOptions = m;
            }
        }

    };


    //Gen QR Code
    vm.genQRCode = function (isDirty, isSave, isPreview, e, isExit) {
        vm.GenQRCode = true;

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

        var modelKategoriDocReceived = [];
        if (vm.case.AllDocReceived) {
            for (var i = 0; i < vm.case.AllDocReceived.length; i++) {
                if (angular.element('#chkBoxActivity_' + i)) {
                    if (angular.element('#chkBoxActivity_' + i)[0].checked) {
                        for (var j = 0; j < vm.case.AllDocReceived[i].KategoriDocReceived.length; j++) {
                            var modelDocumentDetailsByID = [];

                            modelKategoriDocReceived = angular.copy(vm.case.AllDocReceived[i].KategoriDocReceived);

                            for (var k = 0; k < modelKategoriDocReceived.length; k++) {
                                for (var l = 0; l < modelKategoriDocReceived[k].ActDocReceived.length; l++) {
                                    //modelKategoriDocReceived[k].ActDocReceived[l].DocCategory = modelKategoriDocReceived[k].KategoriDocName;
                                    modelKategoriDocReceived[k].ActDocReceived[l].DocCatCode = modelKategoriDocReceived[k].KategoriDocCode;
                                    modelKategoriDocReceived[k].ActDocReceived[l].DocDate = $filter('date')(new Date(modelKategoriDocReceived[k].ActDocReceived[l].TarikhDokumen), 'dd MMM yyyy');
                                    modelKategoriDocReceived[k].ActDocReceived[l].TT = modelKategoriDocReceived[k].ActDocReceived[l].TahunTaksiran;
                                    modelDocumentDetailsByID.push(modelKategoriDocReceived[k].ActDocReceived[l]);
                                }
                            }
                        }

                        if (modelDocumentDetailsByID.length > 0) {
                            var modelDocumentDetails = {
                                ActRefID: vm.case.AllDocReceived[i].ActRefNo,
                                DocDtlsByID: modelDocumentDetailsByID
                            }
                            arrDocumentDetails.push(modelDocumentDetails);
                        }

                    }
                }
            }
        }

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

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

                if (isSave) { // If Save

                    // check if status = selesai
                    if (!vm.case.IsCaseClosed && vm.case.CaseStatusLevel1ID == 1) // X Case Closed & Status = selesai
                    {
                        var confirmText = "";
                        var textDesc = "";
                        if (parseInt(vm.ActId) > 0) {
                            indicator = 1; //TransferToCase
                            confirmText = constSaveAndCloseConfirmMsg;
                            textDesc = constCloseActDesc;
                        }
                        else {
                            confirmText = constCloseConfirmMsg;
                            textDesc = constCloseAllActDesc;
                        }

                        swal({
                            title: confirmText,
                            text: textDesc,
                            type: "warning",
                            showCancelButton: true,
                            confirmButtonText: "Ya",
                            cancelButtonText: "Tidak",
                            closeOnConfirm: false,
                            closeOnCancel: false
                        }, function (isConfirm) {
                            if (isConfirm) {
                                vm.case.IsCaseClosed = 1;
                                indicator = 2;
                                if (parseInt(vm.ActId) > 0) indicator = 1; //IF Transfer To Case, INSERT CASE
                                GetChangeHistory(isDirty);
                                UpdateCase(indicator, false, isExit);
                            } else {
                                swal("Batal!", "Permohonan telah dibatalkan.", "error");
                                return;
                            }
                        });
                    }
                    else {
                        indicator = 2;
                        vm.case.IsCaseClosed = 0;
                        if (parseInt(vm.ActId) > 0) indicator = 1; //IF Transfer To Case, INSERT CASE
                        GetChangeHistory(isDirty);
                        //console.log(vm.ChangesHistory);
                        UpdateCase(indicator, false, isExit);

                    }
                }

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

    function AssignCaseUpdate(indicator) {
        var caseModel = angular.copy(vm.case);

        return caseUpdate = {
            Case: caseModel,
            ChangeHistory: vm.ChangesHistory,
            Indicator: indicator,
            ActivityID: parseInt(vm.ActId)
        };
    }

    //function bindHeader(objTaxPayer) {
    //    //console.log(objTaxPayer);
    //    if (objTaxPayer != null) {
    //        TaxPayerService.TP.AllowEdit = false;
    //        TaxPayerService.TP.Name = objTaxPayer.TPName;
    //        TaxPayerService.TP.TPType = objTaxPayer.JenisPengenalan;
    //        TaxPayerService.TP.IDNo = objTaxPayer.IdentityNo;
    //        TaxPayerService.TP.FileType = objTaxPayer.FileType;
    //        TaxPayerService.TP.TaxNo = objTaxPayer.NoCukai;
    //        TaxPayerService.TP.NoCukaiCode = objTaxPayer.NoCukaiCode;
    //        TaxPayerService.CWNG.PungutanCP = objTaxPayer.CWPungutanCP;
    //        TaxPayerService.CWNG.PungutanCKHT = objTaxPayer.CWPungutanCKHT;
    //        TaxPayerService.CWNG.PenaksiranCP = objTaxPayer.CWPenaksiranCP;
    //        TaxPayerService.CWNG.PenaksiranCKHT = objTaxPayer.CWPenaksiranCKHT;
    //        TaxPayerService.CWNG.GuamanSivil = objTaxPayer.CWGuamanSivil;
    //    } 
    //}

    function bindHeader(objTP, objTPOtherDetails) {
        TaxPayerService.TP.AllowEdit = false;
        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;
            TaxPayerService.TP.SearchTPProfile = 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;
        }
    }

    function consolidateBeforeSave(caseUpdate) {
        if (caseUpdate.Case.NotaTemuduga) {
            if (caseUpdate.Case.NotaTemuduga.NTTarikhTerima)
                caseUpdate.Case.NotaTemuduga.NTTarikhTerima = caseUpdate.Case.NotaTemuduga.NTTarikhTerima;//moment(caseUpdate.Case.NotaTemuduga.NTTarikhTerima, 'DD MMM YYYY').toDate();

            if (caseUpdate.Case.NotaTemuduga.NTUnit) {
                caseUpdate.Case.NotaTemuduga.NTUnitID = caseUpdate.Case.NotaTemuduga.NTUnit.ID;
                caseUpdate.Case.NotaTemuduga.NTUnitName = caseUpdate.Case.NotaTemuduga.NTUnit.DisplayName;
            }
            else {
                caseUpdate.Case.NotaTemuduga.NTUnitID = null;
                caseUpdate.Case.NotaTemuduga.NTUnitName = null;
            }
        }
        if (caseUpdate.Case.TarikhStatus) {
            if (caseUpdate.Case.TarikhStatus)
                caseUpdate.Case.TarikhStatus = $filter('date')(caseUpdate.Case.TarikhStatus, $scope.DateTimeFormat);//new Date(caseUpdate.Case.TarikhStatus);//moment(caseUpdate.Case.NotaTemuduga.NTTarikhTerima, 'DD MMM YYYY').toDate(); 
        }

        return caseUpdate;
    }

    function checkIsFormValid(myCaseForm) {

        if (vm.CaseCatatan.CatatanAttachmentList && vm.CaseCatatan.CatatanAttachmentList.length > 0 && !vm.CaseCatatan.Catatan) {
            vm.showRequiredMsg = true;
            isCatatanComplete = false;
        }
        else {
            vm.showRequiredMsg = false;
            isCatatanComplete = true;
        }
        return myCaseForm.$valid && isCatatanComplete;
    }

    //Save Case
    vm.saveCase = function (myCaseForm, indicator, isTambahCatatan, isExit) { //1 = Insert case, 2 = Save case, 3 = Reopen case, 5 = GenQRCode
        var result = null;
        myCaseForm.Timbalan.$dirty = false;
        myCaseForm.Timbalan.$pristine = true;
        myCaseForm.Jabatan.$dirty = false;
        myCaseForm.Jabatan.$pristine = true;
        myCaseForm.Cawangan.$dirty = false;
        myCaseForm.Cawangan.$pristine = true;
        myCaseForm.Units.$dirty = false;
        myCaseForm.Units.$pristine = true;

        var isDirty = myCaseForm.$dirty;

        if (!vm.CanCloseCase && vm.case.CaseStatusLevel1ID == constSelesaiStatus) {
            swal("Gagal!", "Anda tidak dibenarkan untuk menutup kes.", "error");
            return returnResultPromise();
        }

        if (checkIsFormValid(myCaseForm)) {
            if (indicator == 5) vm.GenQRCode = true;

            if (vm.GenQRCode) { // if Generate & Print, Generate and Save Case
                result = vm.genQRCode(isDirty, true, false, false, isExit);
            } else {
                var confirmText = "";
                var textDesc = "";
                //check if status = selesai
                if (!vm.case.IsCaseClosed && vm.case.CaseStatusLevel1ID == 1) {//if NOT isCaseClosed & selesai
                    if (parseInt(vm.ActId) > 0) {
                        confirmText = constSaveAndCloseConfirmMsg;
                        textDesc = constCloseActDesc;
                    }
                    else {
                        confirmText = constCloseConfirmMsg;
                        textDesc = constCloseAllActDesc;
                    }
                }

                //isExit, genQRCode not make dirty
                if (isDirty || vm.GenQRCode || parseInt(vm.ActId) > 0 || isExit) {
                    if (confirmText != "") { // if selesai status
                        swal({
                            title: confirmText,
                            text: textDesc,
                            type: "warning",
                            showCancelButton: true,
                            confirmButtonText: "Ya",
                            cancelButtonText: "Tidak",
                            closeOnConfirm: false,
                            closeOnCancel: false
                        }, function (isConfirm) {
                            if (isConfirm) {
                                vm.case.IsCaseClosed = 1;
                                if (parseInt(vm.ActId) > 0) indicator = 1; //if TransferToCaseFunc = true, then INSERT CASE

                                GetChangeHistory(isDirty);
                                result = UpdateCase(indicator, isTambahCatatan, isExit);

                            } else {
                                swal("Batal!", "Permohonan telah dibatalkan.", "error");
                                return returnResultPromise();
                            }
                        });
                    } else { //save case or insert case
                        if (parseInt(vm.ActId) > 0) indicator = 1; //if TransferToCaseFunc = true, then INSERT CASE
                        vm.case.IsCaseClosed = vm.case.CaseStatusLevel1ID == 1 ? 1 : 0;
                        GetChangeHistory(isDirty);
                        result = UpdateCase(indicator, isTambahCatatan, isExit);
                    }
                }
                else {
                    swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
                    return returnResultPromise();
                };
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            return returnResultPromise();
        }
        return result == null ? returnResultPromise() : result;
    };

    vm.closeCase = function (myCaseForm) {
        var isDirty = myCaseForm.$dirty;
        var result = null;
        if (myCaseForm.$valid) {
            indicator = 2;
            var confirmText = "";
            var textDesc = "";
            if (parseInt(vm.ActId) > 0) {
                indicator = 1; //TransferToCase
                confirmText = constSaveAndCloseConfirmMsg;
                textDesc = constCloseActDesc;
            }
            else {
                confirmText = constCloseConfirmMsg;
                textDesc = constCloseAllActDesc;
            }

            swal({
                title: confirmText,
                text: textDesc,
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Ya",
                cancelButtonText: "Tidak",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    if (vm.case.CaseStatusLevel1ID == 2) { //HARDCODE: if belum selesai, set to Selesai
                        vm.case.CaseStatusLevel1ID = 1;
                        vm.case.CaseStatusLevel2ID = 1;
                        vm.case.CaseStatusLevel3ID = null;
                    }

                    vm.case.IsCaseClosed = 1;
                    GetChangeHistory(isDirty);
                    //console.log(vm.ChangesHistory);
                    result = UpdateCase(indicator);
                } else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                    return returnResultPromise();
                }
            });
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            return returnResultPromise();
        }
        return result == null ? returnResultPromise() : result;
    }

    vm.reopenCase = function () {
        var result = null;
        indicator = 3;
        var confirmText = "Adakah anda pasti untuk membuka semula kes ini?";
        swal({
            title: confirmText,
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                var model = {
                    CaseID: vm.case.CaseID,
                    CaseRefNo: vm.case.CaseRefNo,
                    CaseStatusLevel1ID: 2,
                    CaseStatusLevel2ID: 6,
                    CaseStatusLevel3ID: null,
                    ChangeStamp: vm.case.ChangeStamp
                };
                result = CaseSI.reopenCase(model).then(function (r) {
                    if (r.status === 200) {
                        vm.case.IsCaseClosed = 0;
                        vm.case.ChangeStamp = r.data.ChangeStamp;
                        vm.case.CaseStatusLevel1ID = model.CaseStatusLevel1ID;
                        vm.status1Changed(vm.case.CaseStatusLevel1ID, true);
                        vm.case.CaseStatusLevel2ID = model.CaseStatusLevel2ID;
                        vm.status2Changed(vm.case.CaseStatusLevel2ID);
                        vm.case.CaseStatusLevel3ID = model.CaseStatusLevel3ID;
                        vm.dtInstanceCaseChangesHistory.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");
                        return returnResultPromise();
                    }
                });
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
                return returnResultPromise();
            }
        });
        return result == null ? returnResultPromise() : result;
    }

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

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

                if (value.$pristine == false) {

                    //get new value
                    var newvalue = "";
                    if ($(document.getElementById(key))[0].tagName == 'SELECT' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                        if ($(document.getElementById(key))[0]) {
                            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 == 'checkbox') {
                        newvalue = value.$viewValue == true ? 'Ya' : 'Tidak';
                    }
                    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 ($('#' + key)[0].tagName == 'SELECT' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    //    newvalue = $('#' + key)[0].selectedOptions.length > 0 ? $('#' + key)[0].selectedOptions[0].text : "";
                    //} else {
                    //    newvalue = value.$viewValue;
                    //}

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

    function UpdateCase(indicator, isTambahCatatan, isExit) {
        var caseUpdate = AssignCaseUpdate(indicator); //1 = Insert case, 2 = Save/Close case, 3 = Reopen case
        caseUpdate = consolidateBeforeSave(caseUpdate);
        //console.log(caseUpdate.Case.NotaTemuduga);
        var data = CaseSI.updateCase(caseUpdate);
        data.then(function (r) {
            if (r.status === 200) {
                vm.case.CaseID = r.data;

                if (isTambahCatatan || (vm.CaseCatatan && vm.CaseCatatan.Catatan)) {
                    vm.CaseCatatan.CaseID = vm.case.CaseID;
                    AddNewCaseCatatan(true);
                    return;
                }

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

        return data;
    };

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

    vm.workflowAction = function (e) {

        if (!vm.case.CaseID) {
            swal("Amaran!", "Profil kes perlu disimpan dahulu.", "warning");
            return;
        }

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

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

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


        // TODO : still required? no usage found
        if (vm.DefaultManager == null)
            GetDefaultManager();

        // trigger db call only if unit type is selected and kategori value has changed
        if (vm.UserType == constAssignToTypeUnit && isKategoriChanged && vm.IsAssign)
            vm.searchforUnit();

        if (vm.UserType == constAssignToTypeUnit && vm.case.WorkflowDetail == null && vm.case.WorkflowDetail == undefined) {
            vm.searchforUnit();
        }

        //        }
        //    });
        //}

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

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

    vm.WorkflowButton = 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.CaseId == "") {
            swal("Gagal!", "Sila simpan kes ini sebelum menambah aliran kerja untuk kes ini.", "error");
            $mdDialog.hide();
        }
        else {
            //if (vm.case.CatatanLst.length == 0)
            //{
            //    swal("Gagal!", "Sila isi catatan", "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 == 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");
                swal("Failed", "Default assigned manager not available. 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 available. 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 && buttonID == 6) {
                    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;
                            }

                            console.log(vm.ChangesHistory);

                            CaseWorkFlowAction(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;
                        }

                        console.log(vm.ChangesHistory);

                        CaseWorkFlowAction(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;
        }

    }

    vm.AssignToCase = function () {
        vm.isAssignCase = true;
    }

    vm.CancelAssignToCase = function () {
        vm.isAssignCase = false;
    };

    vm.CloseAssignCase = function () {
        $mdDialog.hide();

    };

    function CaseWorkFlowAction(buttonid) {

        var workflowAction = {
            CaseID: vm.CaseId,
            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
            }, function (isConfirm) {
                if (isConfirm) {
                    result = CaseSI.insertCaseWorkflowAction(WorkflowUpdate);
                    result.then(function (r) {
                        if (r.status === 200) {
                            swal({
                                title: "Recalled Succesfully",
                                type: "success",
                                showConfirmButton: true
                            }, function () {
                                vm.redirectTo('/case/profile/detail/' + vm.CaseId + '?t=' + TabID + '&ty=' + TabType);

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

                } else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        }
        else {
            result = CaseSI.insertCaseWorkflowAction(WorkflowUpdate);
            result.then(function (r) {
                if (r.status === 200) {
                    swal({
                        title: "Proses agihan kes berjaya dikemaskini.",
                        type: "success",
                        showConfirmButton: true
                    }, function () {
                        vm.redirectTo('/case/profile/detail/' + vm.CaseId + '?t=' + TabID + '&ty=' + TabType);

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

    vm.dtInstanceCaseChangesHistory = {};
    //Change history search
    vm.searchCase = 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.dtInstanceCaseChangesHistory.reloadData();
        }




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

    //Search ActivityList
    vm.dtInstanceActivityList = {};

    vm.searchAL = function () {

        vm.blnValid = true;

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


    }

    vm.clearAL = function () {
        //if (vm.Kategori1Act) vm.Kategori1Act.Kategori1ID = '';
        //if (vm.Kategori2Act) vm.Kategori2Act.Kategori2ID = '';
        //if (vm.Kategori3Act) vm.Kategori3Act.Kategori3ID = '';
        //vm.Kategori2Options = {};
        //vm.Kategori3Options = {};
        if (vm.ActChn) vm.ActChn.ActChannelID = '';
        vm.ActAliran = '';
        vm.ActStatus = '';
        vm.ActivityNo = '';

    }

    vm.actKategori1Changed = function (kategori1IDAct) {
        vm.Kategori2 = {};
        vm.Kategori3 = {};
        vm.Kategori3Options = {};

        if (!kategori1IDAct) {
            vm.Kategori2Options = {};
        }
        else {
            var m = $filter('filter')(vm.MainKategoriOptions, { Kategori1ID: kategori1IDAct }, true);
            if (m.length != 0) {
                vm.Kategori2Options = m[0].SubKategori;
            }
            else {
                vm.Kategori2Options = {};
            }
        }
    };

    vm.actKategori2Changed = function (kategori2IDAct) {
        vm.Kategori3 = {};
        vm.Kategori3Options = null;

        var m = $filter('filter')(vm.Kategori2Options, { Kategori2ID: kategori2IDAct }, true);
        if (m.length != 0) {
            vm.Kategori3Options = m[0].InnerSubKategori;
        }
        else {
            vm.Kategori3Options = {};
        }
    };
    //Search Task List
    vm.dtInstanceTaskList = {};

    vm.searchTL = function () {

        vm.blnValid = true;

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


    }
    vm.clearTL = function () {

        vm.TaskStatus = '';

    }

    vm.onAddActClick = function () {
        if (!vm.CaseId) {
            swal("Amaran!", "Profil kes perlu disimpan dahulu.", "warning");
            return;
        }
        var form = angular.element('#addActivityForm');
        form.submit();

    }

    vm.onReplyToTPClick = function () {
        if (!vm.CaseId) {
            swal("Amaran!", "Profil kes perlu disimpan dahulu.", "warning");
            return;
        }
        var form = angular.element('#replyCFFActivityForm');
        form.submit();
    }

    vm.deleteCase = function () {
        var result = null;
        swal({
            title: "Adakah anda pasti untuk menghapuskan kes ini?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Ya",
            cancelButtonText: "Tidak",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                var model = {
                    CaseID: vm.CaseId,
                    CaseRefNo: vm.case.CaseRefNo,
                    ChangeStamp: vm.case.ChangeStamp
                };
                result = CaseSI.deleteCase(model).then(function (r) {
                    if (r.status === 200) {

                        if (r.data == 1) {
                            swal({
                                title: "Kes dihapuskan!",
                                text: "Kes anda telah berjaya dihapuskan.",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: true
                            }, function () {
                                vm.redirectTo('/');
                            });
                        } else {
                            swal("Gagal!", "Tidak dapat menghapuskan kes ini, aliran kerja sedang dijalankan atau tugasan dihasilkan berkaitan dengan kes ini.", "error");
                            return returnResultPromise();
                        }
                    }
                    else {
                        swal("Gagal!", r.data, "error");
                        return returnResultPromise();
                    }
                });
            } else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
                return returnResultPromise();
            }
        });
        return result == null ? returnResultPromise() : result;
    };

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

    vm.redirectTo = function (url) {

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

    //Selected Assign To User
    //vm.SelectAssignToUser = function (selectedItem) {
    //    //vm.SelectedSubmitTo = selectedItem;
    //    //vm.SubmitTo = selectedItem;
    //    vm.AssignTo = selectedItem;
    //}

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

    //Activities Expand And Collapse Filter
    vm.ExpandActFilter = function () {
        vm.Actshow = true;
    }

    vm.CollapseActFilter = function () {
        vm.Actshow = false;
    }
    // Activities Expand And Collapse Filter

    //Chg History Expand And Collapse Filter
    vm.ExpandChgHistoryFilter = function () {
        vm.ChgHistoryshow = true;
    }

    vm.CollapseChgHistoryFilter = function () {
        vm.ChgHistoryshow = false;
    }
    //Chg History And Collapse Filter

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

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

    vm.searchforUnit = function () {
        // only call db if there is changes
        if (isKategoriChanged) {
            // If not back office unit assign,choose unit from Penerimaan Document Tab
            //if (vm.TempUnit !=null && vm.case.NotaTemuduga != null && vm.case.NotaTemuduga.NTUnitID > 0)
            //{
         
            //}
            //else
            //{
                var Kategory = {
                    Kategori1: vm.case.Kategori1ID,
                    Kategori2: vm.case.Kategori2ID,
                    Kategori3: vm.case.Kategori3ID,
                    TPID: vm.case.TP.TPID
                }

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

                    }
                    else if (vm.TempUnit != null && vm.case.NotaTemuduga != null && vm.case.NotaTemuduga.NTUnitID > 0)
                    {
                        var UnitID = vm.case.NotaTemuduga.NTUnitID;
                        CaseSI.getCaseAssignDefaultUnitByUnitID(UnitID).then(function (r) {
                            if (r.data.ID != null) {
                                vm.Users = [r.data];
                                vm.TempUnit = vm.Users[0];
                                vm.AssignTo = vm.Users[0];
                                vm.UserType = constAssignToTypeUnit;
                                vm.AssignToDisable = true;
                                vm.AssignOther = false;
                                vm.showdetail = false;

                            }
                        });
                    }
                    else
                    {
                        vm.AssignTo = NULL;
                        vm.UserType = constAssignToTypeUnit;
                        vm.AssignToDisable = true;
                        vm.AssignOther = false;
                        vm.showdetail = false;
                    }
                });



            isKategoriChanged = false;

        }
        else {

            // If not back office unit assign,choose unit from Penerimaan Document Tab
            var Kategory = {
                Kategori1: vm.case.Kategori1ID,
                Kategori2: vm.case.Kategori2ID,
                Kategori3: vm.case.Kategori3ID,
                TPID: vm.case.TP.TPID
            }

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

                }
                else
                {
                    if (vm.TempUnit !=null && vm.case.NotaTemuduga != null && vm.case.NotaTemuduga.NTUnitID > 0)
                    {
                        var UnitID = vm.case.NotaTemuduga.NTUnitID;
                        CaseSI.getCaseAssignDefaultUnitByUnitID(UnitID).then(function (r) {
                            if (r.data.ID != null) {
                                vm.Users = [r.data];
                                vm.TempUnit = vm.Users[0];
                                vm.AssignTo = vm.Users[0];
                                vm.UserType = constAssignToTypeUnit;
                                vm.AssignToDisable = true;
                                vm.AssignOther = false;
                                vm.showdetail = false;

                            }
                        });
                    }
                    else
                    {
                        //No Default Unit Found
                        if (r.data.ID == -1)
                        {
                            vm.Users = [r.data]
                            vm.TempUnit = vm.Users[0];
                            vm.AssignTo = vm.Users[0];
                            vm.UserType = constAssignToTypeUnit;
                            vm.AssignOther = false;
                            vm.showdetail = false;
                        }
                        else
                        {
                            // Assigned value stored from previous load if there is not changes
                            vm.AssignTo = vm.TempUnit;
                            vm.UserType = constAssignToTypeUnit;
                            vm.AssignOther = false;
                            vm.showdetail = false;
                        }
                  
                    }
                }
            })
        }
    }

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

        }

        CaseSI.getWorkFlowSearchUserOrUnit(data).then(function (u) {
            if (u.data.length > 0) {
                var m = u.data;
                if (m.length != 0) {
                    vm.Users = m;
                    vm.TempUser = vm.Users[0];
                    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;
            }
        });
    }

    vm.searchforOther = function () {
        vm.AssignTo = null;
        vm.UserType = 0;
        vm.AssignToDisable = false;
        vm.AssignOther = true;


    }


    vm.SelectUnit = function (selectedItem, HierarchyType) {
        if (HierarchyType == 37) {
            vm.SelectedUnits = selectedItem;
        }
        else if (HierarchyType == 36) {
            vm.SelectedCawangan = selectedItem
        }
        else if (HierarchyType == 35) {
            vm.SelectedJabatan = selectedItem
        }
        else if (HierarchyType == 34) {
            vm.SelectedTimbalan = selectedItem
        }
        else {
            vm.AssignTo = selectedItem
        }


    }
    //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;
            });
        }

    }


    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;
    }

    vm.chooseOtherGroupOrUser = function () {
        vm.ResetHierarchy();
    }

    vm.ShowFilterOption = function () {
        if (!vm.showdetail) {
            //vm.optionWording = 'Hide Option';
            vm.showdetail = true;
        }
        else {
            //vm.optionWording = 'More Option';
            vm.showdetail = false;
        }
    }

    vm.ShowFilterOptionDocUnit = function () {

        vm.showdetailDocUnit = !vm.showdetailDocUnit;

        //if (!vm.showdetailDocUnit) {
        //    vm.showdetailDocUnit = true;
        //}
        //else {           
        //    vm.showdetailDocUnit = false;
        //}
    }

    vm.printPenerimaanDoc = function (myCaseForm, e) {
        var isDirty = myCaseForm.$dirty;
        var isDirtyTarikhTerima = myCaseForm.NotaTemuduga_NTTarikhTerima.$dirty;
        var isDirtyCawTindakanName = myCaseForm.NotaTemuduga_NTCawTindakanName.$dirty;
        var isDirtyUnitName = myCaseForm.NotaTemuduga_NTUnitName.$dirty;
        var isDirtyStatusSuratKeluar = myCaseForm.NotaTemuduga_NTStatusSuratKeluar.$dirty;
        var isDirtyStatusSegera = myCaseForm.NotaTemuduga_NTStatusSegera.$dirty;
        var isDirtyStatusTidakPerluTindakan = myCaseForm.NotaTemuduga_NTStatusTidakPerluTindakan.$dirty;
        var isDirtyStatusCetakSurat = myCaseForm.NotaTemuduga_NTStatusCetakSurat.$dirty;
        var isDirtyCatatanTambahan = myCaseForm.NotaTemuduga_NTCatatanTambahan.$dirty;
        var isDirtyKategory1Name = myCaseForm.Kategori1Name.$dirty;
        var isDirtyKategory2Name = myCaseForm.Kategori2Name.$dirty;
        var isDirtyKategory3Name = myCaseForm.Kategori3Name.$dirty;

        if (isDirtyTarikhTerima || isDirtyCawTindakanName || isDirtyUnitName || isDirtyStatusSuratKeluar || isDirtyStatusSegera
             || isDirtyStatusTidakPerluTindakan || isDirtyStatusCetakSurat || isDirtyCatatanTambahan || isDirtyKategory1Name || isDirtyKategory2Name
             || isDirtyKategory3Name
            ) {
            swal("Gagal!", "Perubahan telah dibuat! Sila simpan kes ini sebelum mencetak nota temuduga", "error");
        }
        else {
            vm.genQRCode(isDirty, false, true, e);
        }

    }

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

    /*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();

        return true;
    }

    function PrintPenerimaanDocument(qrcode, e) {

        var KategoryActIDList = "";
        if (vm.case.AllDocReceived != null) {
            for (var i = 0; i < vm.case.AllDocReceived.length; i++) {
                var IsCheckKategoryDoc = $("#chkBoxActivity_" + i).prop("checked");
                if (IsCheckKategoryDoc) {
                    KategoryActIDList += vm.case.AllDocReceived[i].ActivityID + ','
                }
            }
        }

        KategoryActIDList = KategoryActIDList.replace(/(^,)|(,$)/g, "");

        var model = {
            CaseID: vm.CaseId,
            QRCode: qrcode,
            QRCodeDate: moment(new Date()).format('DD MMM YYYY hh:mm:ss A'),
            DocKategoryActID: KategoryActIDList
        };

        CaseSI.printPenerimaanDoc(model).then(function (r) {
            vm.openDialog(e, '#myModalNoteTemuduga');
            document.getElementById("divPrintNoteTemuduga").innerHTML = r.data;
        });


    }

    //Get in CaseDropdown
    //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) {

        if (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;
                        }

                    }
                }
            });
        }
    }

    vm.seksyenChange = function (selectedTimbalan) {

        vm.casesWorkflowAssignToJabatanOption = [];

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

            if (m != undefined && m.length != 0) {
                vm.casesWorkflowAssignToJabatanOption = m;
            }
            if (vm.Other == constAssignToTypeUser) {
                SearchUserByUnitID(selectedTimbalan);
            }
        }

    };
    vm.seksyenChangeDocUnit = function (selectedTimbalanDocUnit) {

        vm.casesWorkflowAssignToJabatanOptionDocUnit = [];

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

    };


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

        vm.casesWorkflowAssignToCawanganOption = [];

        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.casesWorkflowAssignToCawanganOption = m;
            }

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

    };

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

        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.casesWorkflowAssignToCawanganOptionDocUnit = m;
            }
        }

    };


    vm.cawanganChange = function (SelectedCawangan) {

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

        vm.casesWorkflowAssignToUnitOption = [];

        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.casesWorkflowAssignToUnitOption = m;
            }

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

        }

    };

    vm.cawanganChangeDocUnit = function (SelectedCawanganDocUnit) {

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

        vm.casesWorkflowAssignToUnitOptionDocUnit = [];

        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.casesWorkflowAssignToUnitOptionDocUnit = m;
            }
        }

    };



    vm.unitChange = function (SelectedUnits) {

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

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

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

        vm.casesWorkflowAssignToJabatanOption = [];
        vm.casesWorkflowAssignToCawanganOption = [];
        vm.casesWorkflowAssignToUnitOption = [];
        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.casesWorkflowAssignToJabatanOptionDocUnit = [];
        vm.casesWorkflowAssignToCawanganOptionDocUnit = [];
        vm.casesWorkflowAssignToUnitOptionDocUnit = [];
        //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.case.NotaTemuduga.NTUnit =  m[0];
            //vm.AssignToDocUnit = m[0];
            vm.UnitPenerimaanDocOption = m;
            //if (vm.case.NotaTemuduga != null && vm.case.NotaTemuduga.NTUnitID) {
            vm.case.NotaTemuduga.NTUnit = m[0];

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

        }
    }

    //vm.SearchNTUnit = function (query) {

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

    //}
    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;
    //    }

    //}

    vm.openParentCaseProfile = function ($event) {
        $event.preventDefault();
        $window.open("/case/profile/detail/" + vm.case.ParentCaseID, "_blank")

        return;
    };

    vm.openActivityProfile = function ($event) {
        $event.preventDefault();
        $window.open("/activity/profile/detail/" + (vm.firstActivityID || vm.case.CFFFirstActivityID), "_blank")

        return;
    };

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

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

    vm.clearDateFrom = function () {
        vm.DateFrom = null;
    };
    vm.clearDateTo = function () {
        vm.DateTo = null;
    };

    vm.clearNTTarikhTerima = function (myCaseForm) {
        vm.case.NotaTemuduga.NTTarikhTerima = '';
        vm.case.NotaTemuduga.NTTarikhTerima.$setViewValue = '';
        myCaseForm.$dirty = true;
        myCaseForm.$pristine = false;
        myCaseForm.NotaTemuduga.NTTarikhTerima.$dirty = true;
        myCaseForm.NotaTemuduga.NTTarikhTerima.$pristine = false;
        //terimDocForm.$pristine = false;
        //terimDocForm.$dirty = true;
        //terimDocForm.NotaTemuduga.NTTarikhTerima.$dirty = true;
    };
    vm.clearTarikhStatus = function (myCaseForm) {
        vm.case.TarikhStatus = '';
        vm.case.TarikhStatus.$setViewValue = '';
        myCaseForm.$dirty = true;
        myCaseForm.$pristine = false;
        myCaseForm.TarikhStatus.$dirty = true;
        myCaseForm.TarikhStatus.$pristine = false;
        //terimDocForm.$pristine = false;
        //terimDocForm.$dirty = true;
        //terimDocForm.NotaTemuduga.NTTarikhTerima.$dirty = true;
    };

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