crmApp.controller("AdminController", AdminController);

function AdminController($scope, $window) {
    var vm = this;

    vm.navMenuClicked = function ($event) {
        var elem = $event.currentTarget || $event.srcElement;
        var activeMenu = document.querySelector('.sidebar-menu > .treeview.active');

        if (activeMenu)
            angular.element(activeMenu).removeClass("active");

        angular.element(elem).addClass("active");
    };

    vm.navSubMenuClicked = function ($event) {
        var elem = $event.currentTarget || $event.srcElement;
        var activeSubMenu = document.querySelector('.treeview-menu > li.active');

        if (activeSubMenu)
            angular.element(activeSubMenu).removeClass("active");

        angular.element(elem).addClass("active");
    };
}

crmApp.controller('CfgJenisPelanggan', function ($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                          { Text: 'Tidak', Value: false }];
    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        var model = { LookupCode: "JenisPelanggan" };
        AdminSI.getLookupParam(model).then(function (r) {
            if (r.status === 200) {
                vm.list = r.data;
            }
        });
    };

    vm.addNew = function () {
        vm.editTitle = "Tambah Jenis Pelanggan";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsDefault = false;
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Jenis Pelanggan";
        var filtered = $filter('filter')(vm.list, {"LookupParamID": id}, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.IsDefault == null)
        {
            vm.editing.IsDefault = false;
        }
  
        vm.editMode = true;
    };

    vm.save = function (myForm) {
        var isDirty = myForm.$dirty;
        if (myForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(myForm);
                    if (vm.editing.IsDefault == true) { //if IsDefault = true
                        for (i = 0; i < vm.list.length ; i++) {
                            if (vm.list[i].LookupParamID == vm.editing.LookupParamID)
                                vm.list[i].IsDefault = false; //set IsDefault = false for current LookupParamID 
                        };

                        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
                        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
                        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Jenis Pelanggan ini telah digunakan. Cuba guna jenis pelanggan lain", "error");
                            vm.changesHistory = [];
                        }
                        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Pelanggan Kod ini telah digunakan. Cuba buat pelanggan kod baru", "error");
                            vm.changesHistory = [];
                        }
                        else
                        {
                            var filtered = $filter('filter')(vm.list, { "IsDefault": true }, true);

                            if (filtered.length >= 1) { //if more than 1 default value 
                                swal({
                                    title: "Default value has been set for other value. Are you sure you want to set this as Default value?",
                                    text: "",
                                    type: "warning",
                                    showCancelButton: true,
                                    confirmButtonText: "Yes",
                                    cancelButtonText: "No",
                                    closeOnConfirm: false,
                                    closeOnCancel: false
                                }, function (isConfirm) {
                                    if (isConfirm) {
                                        var model = [];
                                        model.push(filtered[0]);
                                        vm.editing.IsDefault = false;
                                        vm.editing.LookupCode = "JenisPelanggan";
                                        vm.editing.ChangeHistory = vm.changesHistory;
                                        model.push(vm.editing);
                                        AdminSI.addDefaultLookupParam(model).then(function (r) {
                                            if (r.status === 200) {
                                                if (r.data) {
                                                    swal({
                                                        title: "Berjaya Kemaskini!",
                                                        type: "success",
                                                        timer: 2500,
                                                        showConfirmButton: false
                                                    }, function () {
                                                        location.reload();
                                                    });
                                                }
                                                else
                                                    swal("Gagal", r.data, "error");
                                            } else
                                                swal("Gagal", r.data, "error");
                                        })
                                    } else {
                                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                                    }
                                });
                            }
                            else { // If IsDefault = true & length = 0
                                vm.editing.IsDefault = true;
                                AddLookupParam();
                            };
                        }                   
                    } else { //if false, Save only
                        AddLookupParam();
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.deleteJenisPelanggan = function (lookupParamID,IsAktive) {
        vm.editMode = false;
        if (IsAktive) {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: false,
                LookupCode: "JenisPelanggan"
            };

            swal({
                title: "Adakah anda pasti mahu deactivate Jenis Pelanggan ini?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


                        }
                    });
                }
                else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        }
        else
        {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: true,
                LookupCode: "JenisPelanggan"
            };

            swal({
                title: "Adakah anda pasti mahu activate Jenis Pelanggan ini?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


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

    }

    function AddLookupParam() {
        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Jenis Pelanggan ini telah digunakan. Cuba guna jenis pelanggan lain", "error");
            vm.changesHistory = [];
        }
        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Pelanggan Kod ini telah digunakan. Cuba buat pelanggan kod baru", "error");
            vm.changesHistory = [];
        }
        else
        {
            model = vm.editing;
            model.LookupCode = "JenisPelanggan";
            model.ChangeHistory = vm.changesHistory
            AdminSI.addLookupParam(model).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });
                    }
                    else
                        swal("Gagal", r.data, "error");
                } else
                    swal("Gagal", r.data, "error");
            })
        }
    };
    
    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

});

crmApp.controller('CfgFileType', function ($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = 0;
    vm.showValidationMsg = false;
    var constChangeFileType = 2;
    var constAddNewFileTypePrefix = 3;
    var constChangeFileTypePrefix = 4;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('order', [[0, 'asc']])
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                  { Text: 'Tidak', Value: false }];

    vm.init = function () {
        AdminSI.getTPFileType().then(function (r) {
            if (r.status === 200) {
                vm.list = r.data;
                console.log(vm.list);
            }
        });
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Jenis Fail";
        var filtered = $filter('filter')(vm.list, { "TPFileTypeID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];

        if (vm.editing.TPFileTypePrefix.length > 0)
        {
            var m = $filter('orderBy')(vm.editing.TPFileTypePrefix, 'TPFileTypePrefix');
            if (m && m.length > 0) {
                vm.editing.TPFileTypePrefix = m;
            }
        }

        vm.editMode = 2;
    };

    vm.addNewSubType = function () {
        vm.editTitle = "Tambah Jenis Fail Prefix";
        angular.extend(vm.editing, {
            EditingSub: {
                TPFileTypePrefixID: 0,
                TPFileTypePrefix: "",
                IsActive : true
            }
        });
        vm.editMode = 3;
    };

    vm.openEditSubType = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var subid = angular.element(elem).data("subid");

        vm.editTitle = "Kemaskini Jenis Fail Prefix";
        var filtered = $filter('filter')(vm.editing.TPFileTypePrefix, { "TPFileTypePrefixID": subid }, true);

        if (filtered.length > 0) {
            angular.extend(vm.editing, {
                EditingSub: filtered[0]
            });
            vm.editing.EditingSub.TPFileTypePrefix = filtered[0].TPFileTypePrefix;
        }

        //resetSubClsBene();
        vm.editMode = 4;
    };

    vm.removeFileTypePrefix = function (e) {
        vm.editMode = 3;
        //TODO: remove

    }

    vm.save = function (myForm) {
        //TODO: save
        var isDirty = myForm.$dirty;
        if (myForm.$valid)
        {
            if (isDirty) {

                var model = {};
                if (vm.editMode == constChangeFileType)  //Change Parent File Type
                {
                    getChangeHistory(myForm);
                    model = {
                                TPFileTypeID: vm.editing.TPFileTypeID,
                                TPFileTypeName: vm.editing.TPFileTypeName,
                                EditMenuMode: vm.editMode,
                                ChangeHistory: vm.changesHistory
                    }
                      
                            AdminSI.updatedFileType(model).then(function (r) {
                                if (r.status == 200) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    });

                                    vm.list = r.data;
                                    vm.editTitle = "Kemaskini File Type";
                                    var filtered = $filter('filter')(vm.list, {
                                        "TPFileTypeID": vm.editing.TPFileTypeID
                                    }, true);

                                    if (filtered.length > 0) vm.editing = filtered[0];
                                    vm.editMode = 2;
                                    vm.changesHistory = [];
                                }
                            });
                }
                else
                {
                    getChangeHistory(myForm);
                     model = {
                                TPFileTypeID: vm.editing.TPFileTypeID,
                                TPFileTypePrefix: vm.editing.EditingSub.TPFileTypePrefix,
                                TPFileTypePrefixID: vm.editing.EditingSub.TPFileTypePrefixID,
                                IsActive: vm.editing.EditingSub.IsActive,
                                EditMenuMode: vm.editMode,
                                ChangeHistory: vm.changesHistory
                     }

                     if (vm.editMode == constAddNewFileTypePrefix)  //Edit File Type Prefix
                     {
                         swal({
                             title: " Andakah anda pasti mahu Tambah File Type Prefix?",
                             text: "",
                             type: "warning",
                             showCancelButton: true,
                             confirmButtonText: "Yes",
                             cancelButtonText: "No",
                             closeOnConfirm: false,
                             closeOnCancel: false
                         }, function (isConfirm) {
                             if (isConfirm) {
                                 AdminSI.updatedFileType(model).then(function (r) {
                                     if (r.status == 200) {
                                         swal({
                                             title: "Berjaya Kemaskini!",
                                             type: "success",
                                             timer: 2500,
                                             showConfirmButton: false
                                         });

                                         vm.list = r.data;
                                         vm.editTitle = "Kemaskini File Type";
                                         var filtered = $filter('filter')(vm.list, { "TPFileTypeID": vm.editing.TPFileTypeID }, true);

                                         if (filtered.length > 0) vm.editing = filtered[0];
                                         vm.editMode = 2;
                                         vm.changesHistory = [];
                                     }
                                 });
                             }
                             else {
                                 swal("Batal!", "Permohonan telah dibatalkan.", "error");
                             }

                         });
                     }
                     else
                     {
                                 AdminSI.updatedFileType(model).then(function (r) {
                                     if (r.status == 200) {
                                         swal({
                                             title: "Berjaya Kemaskini!",
                                             type: "success",
                                             timer: 2500,
                                             showConfirmButton: false
                                         });

                                         vm.list = r.data;
                                         vm.editTitle = "Kemaskini File Type";
                                         var filtered = $filter('filter')(vm.list, { "TPFileTypeID": vm.editing.TPFileTypeID }, true);

                                         if (filtered.length > 0) vm.editing = filtered[0];
                                         vm.editMode = 2;
                                         vm.changesHistory = [];
                                     }
                                 });
                     }
                     
                }
                              
            }
            else
            {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        }
        else
        {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }

    }

    vm.cancel = function () {
        vm.editMode = 0;
        vm.init();
        vm.showValidationMsg = false;
    }

    vm.cancelEditSubType = function () {
        vm.editTitle = "Kemaskini Jenis Fail";
        vm.editMode = 2;
    };

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if(value.$viewValue == true)
                    {
                        newvalue = "Ya";
                    }
                    else
                    {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

});

crmApp.controller('CfgBahasa', function ($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
   
    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                      { Text: 'Tidak', Value: false }];

    vm.IsActive = true;

    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        var model = { LookupCode: "BahasaPehubungan" };
        AdminSI.getLookupParam(model).then(function (r) {
            if (r.status === 200) {
                vm.list = r.data;
            }
        });
    };

    vm.addNew = function () {
        vm.editTitle = "Tambah Bahasa Perhubungan";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsDefault = false;
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Bahasa Perhubungan";
        var filtered = $filter('filter')(vm.list, { "LookupParamID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.IsDefault == null) {
            vm.editing.IsDefault = false;
        }
        vm.editMode = true;
    };

    vm.save = function (myForm) {
        var isDirty = myForm.$dirty;
        if (myForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    //$scope.myForm["IsActive"].$pristine = false;
                    //$scope.myForm["IsDefault"].$pristine = false;
                    getChangeHistory(myForm);
                    if (vm.editing.IsDefault == true) { //if IsDefault = true
                        for (i = 0; i < vm.list.length ; i++) {
                            if (vm.list[i].LookupParamID == vm.editing.LookupParamID)
                                vm.list[i].IsDefault = false; //set IsDefault = false for current LookupParamID 
                        };

                        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
                        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
                        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Nama ini telah digunakan. Cuba guna Nama Lain", "error");
                            vm.changesHistory = [];
                        }
                        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
                            vm.changesHistory = [];
                        }
                        else
                        {
                            var filtered = $filter('filter')(vm.list, { "IsDefault": true }, true);
                            if (filtered.length >= 1) { //if more than 1 default value 
                                swal({
                                    title: "Default value has been set for other value. Are you sure you want to set this as Default value?",
                                    text: "",
                                    type: "warning",
                                    showCancelButton: true,
                                    confirmButtonText: "Yes",
                                    cancelButtonText: "No",
                                    closeOnConfirm: false,
                                    closeOnCancel: false
                                }, function (isConfirm) {
                                    if (isConfirm) {
                                        var model = [];
                                        model.push(filtered[0]);
                                        vm.editing.IsDefault = false;
                                        vm.editing.LookupCode = "BahasaPehubungan";
                                        vm.editing.ChangeHistory = vm.changesHistory;
                                        model.push(vm.editing);
                                        AdminSI.addDefaultLookupParam(model).then(function (r) {
                                            if (r.status === 200) {
                                                if (r.data) {
                                                    swal({
                                                        title: "Berjaya Kemaskini!",
                                                        type: "success",
                                                        timer: 2500,
                                                        showConfirmButton: false
                                                    }, function () {
                                                        location.reload();
                                                    });
                                                }
                                                else
                                                    swal("Gagal", r.data, "error");
                                            } else
                                                swal("Gagal", r.data, "error");
                                        })
                                    } else {
                                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                                    }
                                });
                            }
                            else { // If IsDefault = true & length = 0
                                vm.editing.IsDefault = true;
                                AddLookupParam();
                            };
                        }         
                    } else { //if false, Save only
                        AddLookupParam();
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    function AddLookupParam() {
        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Nama ini telah digunakan. Cuba guna Nama Lain", "error");
            vm.changesHistory = [];
        }
        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
            vm.changesHistory = [];
        }
        else
        {
            model = vm.editing;
            model.LookupCode = "BahasaPehubungan";
            model.ChangeHistory = vm.changesHistory
            AdminSI.addLookupParam(model).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });
                    }
                    else
                        swal("Gagal", r.data, "error");
                } else
                    swal("Gagal", r.data, "error");
            })
        }
    };

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    vm.deleteBahasa = function (lookupParamID) {
        vm.editMode = false;
        var model = {
            LookupParamID: lookupParamID,
            IsActive: false,
            LookupCode :"BahasaPehubungan"
        };

        swal({
            title: "Adakah anda pasti mahu deactivate bahasa ini  ?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                AdminSI.inactiveLookupParam(model).then(function (r) {
                    if (r.status == 200) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });


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

    }

    function getChangeHistory(myForm) {
    angular.forEach(myForm, function (value, key) {
        if (key[0] == '$') return;

        var displayName = $('#' + key).data('displayfield');
        if (key == "IsActive" || key == "IsDefault") {
            value.$pristine = false

        }

        if (value.$pristine == false) {
            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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                if (value.$viewValue == true) {
                    newvalue = "Ya";
                }
                else {
                    newvalue = "Tidak";
                }
            }
            else {
                newvalue = value.$viewValue;
            }

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

});

crmApp.controller('CfgActChannel', function ($scope, $filter, $q, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;

    vm.dtInstance = {};
    vm.actChannellist = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];
    vm.duplicateRoles = false;

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {

        getDDLOptions().then(function (data) {

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

        AdminSI.getRefActChannel().then(function (r) {
            if (r.status === 200) {
                vm.actChannellist = r.data;
            }
        });
    };

    vm.openEditActChannel = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Saluran Aktiviti";
        var filtered = $filter('filter')(vm.actChannellist, { "ActChannelID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];

        if (vm.editing.DefaultRolesID != null) {
            var objFunctionRoleID = vm.editing.DefaultRolesID.split('||');
            vm.editing.selected = [];
            angular.forEach(objFunctionRoleID, function (value, key) {

                m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: parseInt(value) }, true);
                if (m.length > 0) {
                    vm.editing.selected.push(m[0].FunctionalRoleID);
                }
                else {
                    vm.editing.selected = "";
                }
            })
        }
        else {
            vm.editing.selected = "";
        }

        vm.editMode = true;
    };

    vm.save = function (myActChannelForm) {
        var isDirty = myActChannelForm.$dirty;
        if (myActChannelForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(myActChannelForm);
                    var model = {};

                    if (vm.editing.selected.length == 0) {
                        vm.editing.DefaultRoles = "";
                    }
                    else {

                        for (i = 0; i < vm.actChannellist.length ; i++) {
                            if (vm.actChannellist[i].DefaultRolesID != null && vm.actChannellist[i].DefaultRolesID != "" && vm.actChannellist[i].ActChannelID != vm.editing.ActChannelID) {
                                var oriFunctionRoleID = vm.actChannellist[i].DefaultRolesID.split('||');
                                var newFunctionRoleID = vm.editing.selected;
                                for (j = 0 ; j < oriFunctionRoleID.length; j++)
                                {
                                    for (k = 0 ; k < newFunctionRoleID.length; k++)
                                    {
                                        if (parseInt(oriFunctionRoleID[j]) == newFunctionRoleID[k] ) {
                                            vm.duplicateRoles = true;
                                            var m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: parseInt(oriFunctionRoleID[j]) }, true);
                                            if (m.length > 0) {
                                                vm.duplicateValue = m[0].RoleName;
                                                break;
                                            }
                                        }
                                    }
                                    //vm.duplicateValue = vm.duplicateValue.join(" , ");
                                }                       
                            }
                        };

                        vm.editing.DefaultRoles = vm.editing.selected.join(" || ");
                    }
                    
                    if (!vm.duplicateRoles) {
                        model = {
                            ActChannel: vm.editing,
                            ChangeHistory: vm.changesHistory
                        }
                        AdminSI.updateRefActChannel(model).then(function (r) {
                            if (r.status === 200) {
                                if (r.data) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    }, function () {
                                        location.reload();
                                    });
                                }
                                else
                                    swal("Gagal", r.data, "error");
                            } else
                                swal("Gagal", r.data, "error");
                        });
                    }
                    else
                    {
                        swal("Gagal", "Roles ini( " + vm.duplicateValue + " ) sudah default to other aktiviti.Sila guna role lain", "error");
                        vm.duplicateRoles = false;
                        vm.changesHistory = [];
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

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

            if (value.$pristine == false) {
                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' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if ($(document.getElementById(key))[0].type == 'radio') {
                        if (value.$viewValue == true) {
                            newvalue = "Ya";
                        }
                        else {
                            newvalue = "Tidak";
                        }
                    }
                    else if ($(document.getElementById(key))[0].type == 'checkbox')
                    {
                        if (value.$viewValue == true) {
                            newvalue = "Ya";
                        }
                        else {
                            newvalue = "Tidak";
                        }
                    }
                    else {
                        newvalue = value.$viewValue;
                    }

                }
                else if ($(document.getElementById(key))[0].tagName = 'DIV' && ((value.$viewValue !== '' || value.$viewValue !== null) !== '' || value.$viewValue !== null)) {
                    angular.forEach(value.$viewValue, function (kemValue, kemKey) {
                        if (newvalue != "") {
                            newvalue = newvalue + "," + kemValue.RoleName;
                        }
                        else {
                            newvalue = kemValue.RoleName;
                        }
                    })
                }
                else {
                    newvalue = value.$viewValue;
                }

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

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

});

crmApp.controller('CfgSumber', function ($scope, $filter,$q, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;

    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                      { Text: 'Tidak', Value: false }];

    vm.dtInstance = {};
    vm.sumberList = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        AdminSI.getAllSumber().then(function (r) {
            if (r.status === 200) {
                vm.sumberList = r.data;
            }
        });
    };
 
    getDDLOptions().then(function (data) {

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

    vm.addNew = function () {
        vm.editTitle = "Tambah Sumber";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
    };

    vm.openEditSumber = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Sumber";
        var filtered = $filter('filter')(vm.sumberList, { "SumberID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        vm.editMode = true;
    };

    vm.save = function (sumberForm) {
        var isDirty = sumberForm.$dirty;
        if (sumberForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(sumberForm);

                    var checkDuplicateName = $filter('filter')(vm.sumberList, { "SumberName": vm.editing.SumberName }, true);
                    if (checkDuplicateName.length > 0 && checkDuplicateName[0].SumberID != vm.editing.SumberID) {
                        swal("Gagal", "Sumber ini telah digunakan. Cuba guna sumber lain", "error");
                        vm.changesHistory = [];
                    }
                    else
                    {
                        var model = {};
                        model = {
                            Sumber: vm.editing,
                            ChangeHistory: vm.changesHistory
                        }
                        AdminSI.updateSumberDetails(model).then(function (r) {
                            if (r.status === 200) {
                                if (r.data) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    }, function () {
                                        location.reload();
                                    });
                                }
                                else
                                    swal("Gagal", r.data, "error");
                            } else
                                swal("Gagal", r.data, "error");
                        });
                    }
 
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    vm.deleteSumber = function (sumberId) {
        vm.editMode = false;
        var model = {
            SumberID: sumberId,
            IsActive: false,
        };

        swal({
            title: "Adakah anda pasti mahu deactivate Sumber ini ?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                AdminSI.removeCurrentSumberDetail(model).then(function (r) {
                    if (r.status == 200) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });


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

    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

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

crmApp.controller('CfgStatusBayaranS104S22', function ($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;

    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                      { Text: 'Tidak', Value: false }];

    vm.IsActive = true;

    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        var model = { LookupCode: "StatusBayaranS104S22" };
        AdminSI.getLookupParam(model).then(function (r) {
            if (r.status === 200) {
                vm.list = r.data;
            }
        });
    };

    vm.addNew = function () {
        vm.editTitle = "Tambah Status Bayaran S104/S22";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsDefault = false;
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Status Bayaran S104/S22";
        var filtered = $filter('filter')(vm.list, { "LookupParamID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        vm.editMode = true;
    };

    vm.save = function (myForm) {
        var isDirty = myForm.$dirty;
        if (myForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    //$scope.myForm["IsActive"].$pristine = false;
                    //$scope.myForm["IsDefault"].$pristine = false;
                    getChangeHistory(myForm);
                    if (vm.editing.IsDefault == true) { //if IsDefault = true
                        for (i = 0; i < vm.list.length ; i++) {
                            if (vm.list[i].LookupParamID == vm.editing.LookupParamID)
                                vm.list[i].IsDefault = false; //set IsDefault = false for current LookupParamID 
                        };

                        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
                        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
                        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Nama ini telah digunakan. Cuba guna nama lain", "error");
                            vm.changesHistory = [];
                        }
                        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
                            vm.changesHistory = [];
                        }
                        else
                        {
                            var filtered = $filter('filter')(vm.list, { "IsDefault": true }, true);
                            if (filtered.length >= 1) { //if more than 1 default value 
                                swal({
                                    title: "Default value has been set for other value. Are you sure you want to set this as Default value?",
                                    text: "",
                                    type: "warning",
                                    showCancelButton: true,
                                    confirmButtonText: "Yes",
                                    cancelButtonText: "No",
                                    closeOnConfirm: false,
                                    closeOnCancel: false
                                }, function (isConfirm) {
                                    if (isConfirm) {
                                        var model = [];
                                        model.push(filtered[0]);
                                        vm.editing.IsDefault = false;
                                        vm.editing.LookupCode = "StatusBayaranS104S22";
                                        vm.editing.ChangeHistory = vm.changesHistory;
                                        model.push(vm.editing);
                                        AdminSI.addDefaultLookupParam(model).then(function (r) {
                                            if (r.status === 200) {
                                                if (r.data) {
                                                    swal({
                                                        title: "Berjaya Kemaskini!",
                                                        type: "success",
                                                        timer: 2500,
                                                        showConfirmButton: false
                                                    }, function () {
                                                        location.reload();
                                                    });
                                                }
                                                else
                                                    swal("Gagal", r.data, "error");
                                            } else
                                                swal("Gagal", r.data, "error");
                                        })
                                    } else {
                                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                                    }
                                });
                            }
                            else { // If IsDefault = true & length = 0
                                vm.editing.IsDefault = true;
                                AddLookupParam();
                            };
                        }

                    } else { //if false, Save only
                        AddLookupParam();
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    function AddLookupParam() {
        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Nama ini telah digunakan. Cuba guna nama lain", "error");
            vm.changesHistory = [];
        }
        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
            vm.changesHistory = [];
        }
        else
        {
            model = vm.editing;
            model.LookupCode = "StatusBayaranS104S22";
            model.ChangeHistory = vm.changesHistory;

            AdminSI.addLookupParam(model).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });
                    }
                    else
                        swal("Gagal", r.data, "error");
                } else
                    swal("Gagal", r.data, "error");
            })
        }
    };

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    vm.deleteStatusBayaranS104 = function (lookupParamID) {
        vm.editMode = false;
        var model = {
            LookupParamID: lookupParamID,
            IsActive: false,
            LookupCode: "StatusBayaranS104S22"
        };

        swal({
            title: "Adakah anda pasti mahu deactivate StatusBayaranS104S22 ini ?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                AdminSI.inactiveLookupParam(model).then(function (r) {
                    if (r.status == 200) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });


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

    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

});

crmApp.controller('CfgJenisKempen', function ($scope, $filter, $q, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.isHRCC = $window.isHRCC;

    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                      { Text: 'Tidak', Value: false }];

    vm.dtInstance = {};
    vm.sumberList = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
       
        var model = {};
        if (vm.isHRCC == "True")
        {
            var model = {
                IsHRCC: true
            }
        }
        else
        {
            var model = {
                IsHRCC: false
            }
        }
  
        AdminSI.getAllJenisKempen(model).then(function (r) {
            if (r.status === 200) {
                vm.JenisKempenList = r.data;
            }
        });
    };
 
    getDDLOptions().then(function (data) {

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

    vm.addNew = function () {
        vm.editTitle = "Tambah Jenis Kempen";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
    };

    vm.openEditJenisKempen = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Jenis Kempen";
        var filtered = $filter('filter')(vm.JenisKempenList, { "JenisKempenID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        vm.editMode = true;
    };

    vm.save = function (JenisKempenForm) {
        var isDirty = JenisKempenForm.$dirty;
        if (JenisKempenForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(JenisKempenForm);                    
                    var model = {};
                    var JenisKempenModel = {}

                    if (vm.isHRCC == "True") {
                       JenisKempenModel = {
                            JenisKempenID: vm.editing.JenisKempenID,
                            JenisKempenKategoriSysID: vm.editing.JenisKempenKategoriSysID,
                            JenisKempenName: vm.editing.JenisKempenName,
                            CreatedDatetime: vm.editing.CreatedDatetime,
                            CreatedBy: vm.editing.CreatedBy,
                            IsActive: vm.editing.IsActive,
                            IsHRCC: true
                        }
                    }
                    else
                    {
                      JenisKempenModel = {
                            JenisKempenID: vm.editing.JenisKempenID,
                            JenisKempenKategoriSysID: vm.editing.JenisKempenKategoriSysID,
                            JenisKempenName: vm.editing.JenisKempenName,
                            CreatedDatetime: vm.editing.CreatedDatetime,
                            CreatedBy: vm.editing.CreatedBy,
                            IsActive: vm.editing.IsActive,
                            IsHRCC: false
                        }
                    }
                  

                    model = {
                        JenisKempen: JenisKempenModel,
                        ChangeHistory: vm.changesHistory
                    }
                    AdminSI.updateJenisKempen(model).then(function (r) {
                        if (r.status === 200) {
                            if (r.data) {
                                swal({
                                    title: "Berjaya Kemaskini!",
                                    type: "success",
                                    timer: 2500,
                                    showConfirmButton: false
                                }, function () {
                                    location.reload();
                                });
                            }
                            else
                                swal("Gagal", r.data, "error");
                        } else
                            swal("Gagal", r.data, "error");
                    });
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    vm.deleteJenisKempen = function (JenisKempenId) {
        vm.editMode = false;
        var model = {};
        if (vm.isHRCC == "True") {
            model = {
                JenisKempenID: JenisKempenId,
                IsActive: false,
                IsHRCC : true
            };
        }
        else
        {
            model = {
                JenisKempenID: JenisKempenId,
                IsActive: false,
                IsHRCC: false
            };
        }
    
        swal({
            title: "Adakah anda pasti mahu deactivate Kempen ini ?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                AdminSI.removeCurrentKempenDetail(model).then(function (r) {
                    if (r.status == 200) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });


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

    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

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

crmApp.controller('CfgKategori', function ($scope, $filter, $q, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;

    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                      { Text: 'Tidak', Value: false }];

    vm.dtInstance = {};
    vm.kategoriList = {};
    vm.editing = {};
    vm.editing.EditingSub = {};
    vm.MainKategoriList = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];
    var constAddNewKategori1 = 1;
    var constChangeKategori1 = 2;
    var constAddNewKategori2 = 3;
    var constChangeKategori2 = 4;
    var constAddKategori3 = 5;
    var constEditStatusLevel3 = 6;

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        AdminSI.getAllKategori().then(function (r) {
            if (r.status === 200) {
                vm.MainKategoriList = r.data;
            }
        });
    };

    getDDLOptions().then(function (data) {

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

    vm.addNew = function () {
        vm.editTitle = "Tambah Kategori";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editMode = 1;
    };

    vm.addNewKategoriLevel2 = function () {
        vm.editTitle = "Tambah Sub Kategori";
        angular.extend(vm.editing, {
            EditingSub: {
                StatusLevel2ID: 0,
                StatusLevel2Name: ""
            }
        });
        vm.editing.EditingSub.IsActive = true;
        vm.editMode = 3;
    }

    vm.addNewKategoriLevel3 = function () {
        vm.editTitle = "Tambah Sub-Sub Kategori";
        angular.extend(vm.editing.EditingSub, {
            EditingSubLevel3: {
                StatusLevel3ID: 0,
                StatusLevel3Name: ""
            }
        });
        vm.editing.EditingSub.EditingSubLevel3.IsActive = true;
        vm.editMode = 5;
    }
    vm.openEditKategoriLevel = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Kategori";
        var filtered = $filter('filter')(vm.MainKategoriList, { "Kategori1ID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];

        vm.editMode = true;
        vm.editMode = 2;
    };

    vm.openEditKategoriLevel2 = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var subid = angular.element(elem).data("subid");

        vm.editTitle = "Kemaskini Sub Kategori";
        var filtered = $filter('filter')(vm.editing.SubKategori, { "Kategori2ID": subid }, true);

        if (filtered.length > 0) {
            angular.extend(vm.editing, {
                EditingSub: filtered[0]
            });
            vm.editing.EditingSub.SubKategori = filtered[0].SubKategori;
        }

        vm.editMode = 4;
    };

    vm.openEditKategoriLevel3 = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var subid = angular.element(elem).data("subid");

        vm.editTitle = "Kemaskini Sub-sub Kategori";
        var filtered = $filter('filter')(vm.editing.EditingSub.InnerSubKategori, { "Kategori3ID": subid }, true);

        if (filtered.length > 0) {
            angular.extend(vm.editing.EditingSub, {
                EditingSubLevel3: filtered[0]
            });
            vm.editing.EditingSub.EditingSubLevel3.InnerSubKategori = filtered[0];
        }

        vm.editMode = 6;
    }

    vm.save = function (myStatusForm) {
        //TODO: save
        var isDirty = myStatusForm.$dirty;
        if (myStatusForm.$valid) {
            if (isDirty) {

                var kategoriModel = {};
                var model = {};
                if (vm.editMode == constChangeKategori1 || vm.editMode == constAddNewKategori1)  //Add or Change Kategori 1
                {
                    getChangeHistory(myStatusForm);
                    var checkDuplicateName = $filter('filter')(vm.MainKategoriList, { "Kategori1Name": vm.editing.Kategori1Name }, true);
                    if (checkDuplicateName.length > 0 && checkDuplicateName[0].Kategori1ID != vm.editing.Kategori1ID) {
                        swal("Gagal", "Kategori  ini telah digunakan. Cuba guna Kategori lain", "error");
                        vm.changesHistory = [];
                    }
                    else
                    {
                        kategoriModel = {
                            Kategori1ID: vm.editing.Kategori1ID,
                            Kategori1Name: vm.editing.Kategori1Name,
                            DispositionCode1: vm.editing.DispositionCode1,
                            IsActive: vm.editing.IsActive,
                            EditMenuMode: constChangeKategori1,
                        }

                        model = {
                            MainKategori: kategoriModel,
                            ChangeHistory: vm.changesHistory
                        }

                        AdminSI.updateKategoriLevel(model).then(function (r) {
                            if (r.status == 200) {
                                swal({
                                    title: "Berjaya Kemaskini!",
                                    type: "success",
                                    timer: 2500,
                                    showConfirmButton: false
                                });

                                if (vm.editing.Kategori1ID == undefined) {
                                    vm.editMode = false;
                                    vm.init();
                                }
                                else {
                                    vm.editing1 = r.data;
                                    vm.editTitle = "Kemaskini Kategori";
                                    var filtered = $filter('filter')(vm.editing1, {
                                        "Kategori1ID": vm.editing.Kategori1ID
                                    }, true);

                                    if (filtered.length > 0) vm.editing = filtered[0];
                                    vm.editMode = 2;
                                    vm.changesHistory = [];
                                }

                            }
                        });
                    }
                   
                }
                else if (vm.editMode == constAddNewKategori2 || vm.editMode == constChangeKategori2)  // Add or Change Kategori 2
                {
                    getChangeHistory(myStatusForm);
                        kategoriModel = {
                            Kategori1ID: vm.editing.Kategori1ID,
                            Kategori2Name: vm.editing.EditingSub.Kategori2Name,
                            Kategori2ID: vm.editing.EditingSub.Kategori2ID,
                            DispositionCode2: vm.editing.EditingSub.DispositionCode2,
                            IsActiveSubKategori: vm.editing.EditingSub.IsActive,
                            EditMenuMode: vm.editMode,

                        }

                        model = {
                            MainKategori: kategoriModel,
                            ChangeHistory: vm.changesHistory
                        }

                        if (vm.editMode == constAddNewKategori2)  //Add Kategori 2
                        {
                            AdminSI.updateKategoriLevel(model).then(function (r) {
                                if (r.status == 200) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    });

                                    vm.list = r.data;
                                    vm.editTitle = "Kemaskini Kategori ";
                                    var filtered = $filter('filter')(vm.list, { "Kategori1ID": vm.editing.Kategori1ID }, true);

                                    if (filtered.length > 0) vm.editing = filtered[0];
                                    vm.editMode = 2;
                                    vm.changesHistory = [];
                                }
                            });
                        }
                        else {
                            AdminSI.updateKategoriLevel(model).then(function (r) {
                                if (r.status == 200) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    });

                                    vm.list = r.data;
                                    vm.editTitle = "Kemaskini Sub Kategori ";
                                    var filtered = $filter('filter')(vm.list, { "Kategori1ID": vm.editing.Kategori1ID }, true);

                                    if (filtered.length > 0) vm.editing = filtered[0];
                                    vm.editMode = 2;
                                    vm.changesHistory = [];
                                }
                            });
                        }
          

                }
                else {                                                                    // Change Status Level 3
                    getChangeHistory(myStatusForm);
                    kategoriModel = {
                        Kategori1ID: vm.editing.Kategori1ID,
                        Kategori2Name: vm.editing.EditingSub.Kategori2Name,
                        Kategori2ID: vm.editing.EditingSub.Kategori2ID,
                        IsActiveSubKategori: vm.editing.EditingSub.IsActive,
                        Kategori3ID: vm.editing.EditingSub.EditingSubLevel3.Kategori3ID,
                        Kategori3Name: vm.editing.EditingSub.EditingSubLevel3.Kategori3Name,
                        DispositionCode3: vm.editing.EditingSub.EditingSubLevel3.DispositionCode3,
                        IsActiveInnerSubKategori: vm.editing.EditingSub.EditingSubLevel3.IsActive,
                        EditMenuMode: vm.editMode,

                    }

                    model = {
                        MainKategori: kategoriModel,
                        ChangeHistory: vm.changesHistory
                    }

                    if (vm.editMode == constAddKategori3)  // Add Status Level 3 
                    {
                        AdminSI.updateKategoriLevel(model).then(function (r) {
                            if (r.status == 200) {
                                swal({
                                    title: "Berjaya Kemaskini!",
                                    type: "success",
                                    timer: 2500,
                                    showConfirmButton: false
                                });

                                vm.list = r.data;
                                vm.editTitle = "Kemaskini Sub Kategori";

                                var filtered = $filter('filter')(vm.list, { "Kategori1ID": vm.editing.Kategori1ID }, true);
                                filtered = $filter('filter')(filtered[0].SubKategori, { "Kategori2ID": vm.editing.EditingSub.Kategori2ID }, true);


                                if (filtered.length > 0) {
                                    angular.extend(vm.editing, {
                                        EditingSub: filtered[0]
                                    });
                                    vm.editing.EditingSub.SubKategori = filtered[0].SubKategori;
                                }

                                vm.editMode = 4;
                                vm.changesHistory = [];
                            }
                        });
                    }
                    else {   // Edit Status Level 3 
                        AdminSI.updateKategoriLevel(model).then(function (r) {
                            if (r.status == 200) {
                                swal({
                                    title: "Berjaya Kemaskini!",
                                    type: "success",
                                    timer: 2500,
                                    showConfirmButton: false
                                });

                                vm.list = r.data;
                                vm.editTitle = "Kemaskini Sub Kategori";

                                var filtered = $filter('filter')(vm.list, { "Kategori1ID": vm.editing.Kategori1ID }, true);
                                filtered = $filter('filter')(filtered[0].SubKategori, { "Kategori2ID": vm.editing.EditingSub.Kategori2ID }, true);

                                if (filtered.length > 0) {
                                    angular.extend(vm.editing, {
                                        EditingSub: filtered[0]
                                    });
                                    vm.editing.EditingSub.SubKategori = filtered[0].SubKategori;
                                }

                                vm.editMode = 4;
                                vm.changesHistory = [];
                                vm.editMode = 4;
                                vm.changesHistory = [];
                            }
                        });
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        }
        else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    vm.cancelKategoriLevel2 = function () {
        vm.editTitle = "Kemaskini Kategori";
        vm.editMode = 2;
    }

    vm.cancelKategoriLevel3 = function () {
        vm.init();
        vm.editTitle = "Kemaskini Sub Kategori";
        vm.editMode = 4;
    }

    vm.BackMainPage = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }
    vm.deleteKategoriLevel = function (Kategori1ID) {
        vm.editMode = false;

            var model = {
                Kategori1ID: Kategori1ID,
                IsActive: false,
                EditMenuMode: constChangeStatusLvl1,
            };

            swal({
                title: "Adakah anda pasti mahu deactivate Kategori ini ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.deleteKategoriLevel(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


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

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

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

});

crmApp.controller('CfgKodSelesai', function ($scope, $filter, $q, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;

    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                      { Text: 'Tidak', Value: false }];

    vm.dtInstance = {};
    vm.kategoriList = {};
    vm.editing = {};
    vm.kodSelesaiList = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];
    var constAddKodSelesai = 1;
    var constChangeKodSelesai = 2;
    var constAddNewTindakanSusulan = 3;
    var constChangeTindakanSusulan = 4;
    vm.TindakanSusulanKempenOptions = {};

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('order', [[1, 'asc']])
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        AdminSI.getAllKodSelesai().then(function (r) {
            if (r.status === 200) {
                vm.kodSelesaiList = r.data;
            }
        });
    };

    getDDLOptions().then(function (data) {

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

    vm.addNew = function () {
        vm.editTitle = "Tambah Kod Selesai";
        vm.editing = {};
        vm.editMode = 1;
        vm.editing.IsActive = true;
        vm.editing.IsAgentOption = true;
        
    };

    vm.addNewTindakanSusulan = function () {
        vm.editTitle = "Tambah Tindakan Susulan";
        vm.editing.selected = "";
        angular.extend(vm.editing, {
            EditingSub: {
                TindakanSusulanID: 0,
                TindakanSusulanDesc: "",
                IsActive: true,
                TSKempenID: 0,
                TSRoleID : 0
            }
        });
        vm.editMode = 3;
    };

    vm.openEditKodSelesai = function (e, KategoriPenyelesaianID) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Kod Selesai";
        var filtered = $filter('filter')(vm.kodSelesaiList, { "KodSelesaiID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];

        var m = $filter('filter')(vm.KategoriPenyelesaianOption, { Value: KategoriPenyelesaianID }, true);
        if (m && (m.length > 0)) {
            vm.editing.KategoriPenyelesaianID = m[0].Value;
        }
        else {
            vm.editing.KategoriPenyelesaianID = "";
        }

        var m = $filter('filter')(vm.TindakanSusulanOnlyOptions, { KodSelesaiID: vm.editing.KodSelesaiID }, true);
        if (m && (m.length > 0)) {
            vm.editing.TindakanSusulanOptions = m;
        }
        else {
            vm.editing.TindakanSusulanOptions = "";
        }
     
        //vm.editMode = true;
        vm.editMode = 2;
    };

    vm.openEditTindakanSusulan = function(e)
    {
        var elem = e.currentTarget || e.srcElement;
        var subid = angular.element(elem).data("subid");

        vm.editTitle = "Kemaskini Tindakan Susulan";
        var filtered = $filter('filter')(vm.editing.TindakanSusulanOptions, { "TindakanSusulanID": subid }, true);

        if (filtered.length > 0) {
            angular.extend(vm.editing, {
                EditingSub: filtered[0]
            });

            var filteredRole = $filter('filter')(vm.FunctionalRoleOptions, { "FunctionalRoleID": filtered[0].FunctionalRoleID }, true);
         if (filteredRole.length > 0) {
             vm.editing.EditingSub.FunctionalRoleID = filteredRole[0];
            }
            else {
             vm.editing.EditingSub.FunctionalRoleID.FunctionalRoleID = "";
            }

         vm.editing.EditingSub.IsActive = filtered[0].IsActive;

            //Get Jenis Kempen
            var filteredKempen = $filter('filter')(vm.TindakanSusulanKempenOptions, { "TindakanSusulanID": subid }, true);
            if (filteredKempen.length > 0)
            {
                vm.editing.selected = [];
                //vm.Tindakansusu = filteredKempen;
                angular.forEach(filteredKempen, function (value, key) {
                   // m = $filter('filter')(vm.JenisKempenOptions, { JenisKempenID: value.JenisKempenID }, true);
                    m = $filter('filter')(vm.JenisKempenAdminOptions, { JenisKempenID: value.JenisKempenID }, true);
                    if (m.length > 0) {

                        vm.editing.selected.push(m[0].JenisKempenID);

                    }
                    else {
                        vm.editing.selected = "";
                    }
                })
                //angular.forEach(vm.JenisKempenOptions, function (value, key) {
                //    m = $filter('filter')(filteredKempen, { JenisKempenID: value.JenisKempenID }, true);
                //    if (m.length > 0) {

                //        vm.editing.selected.push(m[0].JenisKempenID);

                //    }
                //    else {
                //        vm.editing.selected = "";
                //    }
                //})

            }
   
        }

        vm.editMode = 4;
    }

    vm.save = function (kategoriForm) {
        var isDirty = kategoriForm.$dirty;
        if (kategoriForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(kategoriForm);
                    var model = {};
                    var TindakanSusulanModel = {};
                    
                    if (vm.editMode == constChangeKodSelesai || vm.editMode == constAddKodSelesai)  //Change Kod Selesai
                    {
                        var checkDuplicateName = $filter('filter')(vm.kodSelesaiList, { "KodSelesaiDesc": vm.editing.KodSelesaiDesc }, true);
                        var checkDuplicateCode = $filter('filter')(vm.kodSelesaiList, { "KodSelesaiCode": vm.editing.KodSelesaiCode }, true);

                        if (checkDuplicateName.length > 0 && checkDuplicateName[0].KodSelesaiID != vm.editing.KodSelesaiID) {
                            swal("Gagal", "Description ini telah digunakan. Cuba guna Description lain", "error");
                            vm.changesHistory = [];
                        }
                        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].KodSelesaiID != vm.editing.KodSelesaiID) {
                            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
                            vm.changesHistory = [];
                        }
                        else {
                                    if (vm.editing.KategoriPenyelesaianID <= 0 || vm.editing.KategoriPenyelesaianID == undefined) {
                                        vm.editing.KategoriPenyelesaianID = 0
                                    }

                                    if (vm.editing.CCCallResultID <= 0 || vm.editing.CCCallResultID == undefined) {
                                        vm.editing.CCCallResultID = 0
                                    }

                                    model = {
                                        AdminKodSelesai: vm.editing,
                                        EditMenuMode: vm.editMode,
                                        ChangeHistory: vm.changesHistory
                                    }
                                    AdminSI.updateKodSelesai(model).then(function (r) {
                                        if (r.status === 200) {
                                            if (r.data.AdminKodSelesai.KodSelesaiID > 0) {
                                                swal({
                                                    title: "Berjaya Kemaskini!",
                                                    type: "success",
                                                    timer: 2500,
                                                    showConfirmButton: false
                                                }, function () {
                                                    location.reload();
                                                });
                                            }
                                            else {
                                                if (r.data.AdminKodSelesai.KodSelesaiID == -1) {
                                                    swal("Gagal", "The kod selesai call result is in used.Cant deactive for it.", "error");
                                                }
                                                else {
                                                    swal("Gagal", r.data, "error");
                                                }

                                            }

                                        } else
                                            swal("Gagal", r.data, "error");
                                    });
                        }              
                    }
                    else
                    {
                        //for (i = 0; i < vm.editing.TindakanSusulanOptions.length ; i++) {
                        //    if (vm.editing.TindakanSusulanOptions[i].TindakanSusulanCode == vm.editing.EditingSub.TindakanSusulanCode && vm.editing.TindakanSusulanOptions[i].TindakanSusulanID != vm.editing.EditingSub.TindakanSusulanID) {
                        //        vm.duplicateCode = true;
                        //    }
                        //};

                        var checkDuplicateName = $filter('filter')(vm.editing.TindakanSusulanOptions, { "KodSelesaiDesc": vm.editing.KodSelesaiDesc }, true);
                        var checkDuplicateCode = $filter('filter')(vm.editing.TindakanSusulanOptions, { "KodSelesaiCode": vm.editing.EditingSub.TindakanSusulanCode }, true);

                        if (checkDuplicateName.length > 0 && checkDuplicateName[0].TindakanSusulanID != vm.editing.EditingSub.TindakanSusulanID) {
                            swal("Gagal", "Tindakan Susulan ini telah digunakan. Cuba guna tindakan susulan lain", "error");
                            vm.changesHistory = [];
                        }
                        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].TindakanSusulanID != vm.editing.EditingSub.TindakanSusulanID) {
                            swal("Gagal", "Tindakan Susulan Kod ini telah digunakan. Cuba buat tindakan susulan kod baru", "error");
                            vm.changesHistory = [];
                        }
                        else {
                            if (vm.editMode == constAddNewTindakanSusulan) {

                                if (vm.editing.selected.length == 0) {
                                    vm.editing.selected = "";
                                }
                                else {
                                    vm.editing.selected = vm.editing.selected.join(" , ");
                                }

                                var AdminTindakanSusulan = {
                                    TindakanSusulanID: vm.editing.EditingSub.TindakanSusulanID,
                                    KodSelesaiID: vm.editing.KodSelesaiID,
                                    TindakanSusulanDesc: vm.editing.EditingSub.TindakanSusulanDesc,
                                    TindakanSusulanCode: vm.editing.EditingSub.TindakanSusulanCode,
                                    FunctionalRoleID: vm.editing.EditingSub.FunctionalRoleID.FunctionalRoleID,
                                    JenisKempenID: vm.editing.selected,
                                    JenisKempenIDMultiple: vm.editing.selected,
                                    IsActive: vm.editing.EditingSub.IsActive,
                                    EditMenuMode: vm.editMode,
                                }

                                model = {
                                    AdminTindakanSusulan: AdminTindakanSusulan,
                                    ChangeHistory: vm.changesHistory
                                }

                                AdminSI.updateTindakanSusulan(model).then(function (r) {
                                    if (r.status === 200) {
                                        if (r.data) {
                                            swal({
                                                title: "Berjaya Kemaskini!",
                                                type: "success",
                                                timer: 2500,
                                                showConfirmButton: false
                                            });

                                            //vm.kodSelesaiList = r.data
                                            vm.editTitle = "Kemaskini Kod Selesai";
                                            var filtered = $filter('filter')(vm.kodSelesaiList, { "KodSelesaiID": vm.editing.KodSelesaiID }, true);

                                            if (filtered.length > 0) vm.editing = filtered[0];

                                            var m = $filter('filter')(vm.KategoriPenyelesaianOption, { Value: vm.editing.KategoriPenyelesaianID }, true);
                                            if (m && (m.length > 0)) {
                                                vm.editing.KategoriPenyelesaianID = m[0].Value;
                                            }
                                            else {
                                                vm.editing.KategoriPenyelesaianID = "";
                                            }

                                            var m = $filter('filter')(r.data.LstTindakanSusulan, { KodSelesaiID: vm.editing.KodSelesaiID }, true);
                                            if (m && (m.length > 0)) {
                                                vm.editing.TindakanSusulanOptions = m;
                                            }
                                            else {
                                                vm.editing.TindakanSusulanOptions = "";
                                            }

                                            vm.TindakanSusulanKempenOptions = r.data.LstTindakanSusulanKempen;

                                            vm.editMode = 2;
                                            vm.changesHistory = [];

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

                                if (vm.editing.selected.length == 0) {
                                    vm.editing.selected = "";
                                }
                                else {
                                    vm.editing.selected = vm.editing.selected.join(" , ");
                                }

                                var AdminTindakanSusulan = {
                                    TindakanSusulanID: vm.editing.EditingSub.TindakanSusulanID,
                                    KodSelesaiID: vm.editing.KodSelesaiID,
                                    TindakanSusulanDesc: vm.editing.EditingSub.TindakanSusulanDesc,
                                    TindakanSusulanCode: vm.editing.EditingSub.TindakanSusulanCode,
                                    FunctionalRoleID: vm.editing.EditingSub.FunctionalRoleID.FunctionalRoleID,
                                    JenisKempenID: vm.editing.selected,
                                    JenisKempenIDMultiple: vm.editing.selected,
                                    IsActive: vm.editing.EditingSub.IsActive,
                                    EditMenuMode: vm.editMode,
                                }

                                model = {
                                    AdminTindakanSusulan: AdminTindakanSusulan,
                                    ChangeHistory: vm.changesHistory
                                }

                                AdminSI.updateTindakanSusulan(model).then(function (r) {
                                    if (r.status === 200) {
                                        if (r.data) {
                                            swal({
                                                title: "Berjaya Kemaskini!",
                                                type: "success",
                                                timer: 2500,
                                                showConfirmButton: false
                                            });

                                            vm.editTitle = "Kemaskini Kod Selesai";
                                            var filtered = $filter('filter')(vm.kodSelesaiList, { "KodSelesaiID": vm.editing.KodSelesaiID }, true);

                                            if (filtered.length > 0) vm.editing = filtered[0];

                                            var m = $filter('filter')(vm.KategoriPenyelesaianOption, { Value: vm.editing.KategoriPenyelesaianID }, true);
                                            if (m && (m.length > 0)) {
                                                vm.editing.KategoriPenyelesaianID = m[0].Value;
                                            }
                                            else {
                                                vm.editing.KategoriPenyelesaianID = "";
                                            }

                                            var m = $filter('filter')(r.data.LstTindakanSusulan, { KodSelesaiID: vm.editing.KodSelesaiID }, true);
                                            if (m && (m.length > 0)) {
                                                vm.editing.TindakanSusulanOptions = m;
                                            }
                                            else {
                                                vm.editing.TindakanSusulanOptions = "";
                                            }

                                            vm.TindakanSusulanKempenOptions = r.data.LstTindakanSusulanKempen;


                                            vm.editMode = 2;
                                            vm.changesHistory = [];
                                        }
                                        else
                                            swal("Gagal", r.data, "error");
                                    } else
                                        swal("Gagal", r.data, "error");
                                });

                            }
                        }                
                    }
              }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
             swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    vm.cancelEditTindakanSusulan = function () {
        vm.editTitle = "Kemaskini Kod Selesai";
        vm.editMode = 2;
    };

    vm.deleteKodSelesai = function (KodSelesaiID) {
        vm.editMode = false;
        var model = {
            KodSelesaiID: KodSelesaiID,
            IsActive: false,
        };
       
        swal({
            title: " Adakah anda pasti mahu deactivate Kod Selesai ini  ?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                AdminSI.removeCurrentAdminKodSelesai(model).then(function (r) {
                    if (r.status == 200) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });


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

    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsAgentOption") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                var newvalue = "";
                var newkempenName = "";
                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' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if ($(document.getElementById(key))[0].type == 'radio')
                    {
                        if (value.$viewValue == true) {
                            newvalue = "Ya";
                        }
                        else {
                            newvalue = "Tidak";
                        }
                    }
                    else
                    {
                        newvalue = value.$viewValue;
                    }

                }
                else if ($(document.getElementById(key))[0].tagName = 'DIV' && ((value.$viewValue !== '' || value.$viewValue !== null) !== '' || value.$viewValue !== null)) {
                    angular.forEach(value.$viewValue, function (kemValue, kemKey) {
                            if (newvalue != "")
                            {
                                newvalue = newvalue + "," + kemValue.JenisKempenName;
                            }
                            else
                            {
                                newvalue = kemValue.JenisKempenName;
                            }  
                    })
                }
                else {
                    newvalue = value.$viewValue;
                }

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

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

crmApp.controller('CfgStatus', function ($scope, $filter, $q, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;

    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                      { Text: 'Tidak', Value: false }];

    vm.dtInstance = {};
    vm.kategoriList = {};
    vm.editing = {};
    vm.editing.EditingSub = {};
    vm.StatusLevelList = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];
    var constAddNewStatusLvl1 = 1;
    var constChangeStatusLvl1 = 2;
    var constAddNewStatusLevel2 = 3;
    var constChangeStatusLevel2 = 4;
    var constAddStatusLevel3 = 5;
    var constEditStatusLevel3 = 6;

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        AdminSI.getAllStatusLevel().then(function (r) {
            if (r.status === 200) {
                vm.StatusLevelList = r.data;
            }
        });
    };

    getDDLOptions().then(function (data) {

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

    vm.addNew = function () {
        vm.editTitle = "Tambah Status Level 1";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editMode = 1;
    };

    vm.addNewStatusLevel2 = function()
    {
        vm.editTitle = "Tambah Status Level 2";
        angular.extend(vm.editing, {
            EditingSub: {
                StatusLevel2ID: 0,
                StatusLevel2Name: "",
                IsActive: true
            }
        });
        vm.editing.EditingSub.IsActive = true;
        vm.editMode = 3;
    }

    vm.addNewStatusLevel3 = function()
    {
        vm.editTitle = "Tambah Status Level 3";
        angular.extend(vm.editing.EditingSub, {
            EditingSubLevel3: {
                StatusLevel3ID: 0,
                StatusLevel3Name: "",
                IsActive : true
            }
        });
        vm.editing.EditingSub.IsActive = true;
        vm.editMode = 5;
    }
    vm.openEditStatusLevel = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Status Tahap 1";
        var filtered = $filter('filter')(vm.StatusLevelList, { "StatusLevel1ID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];

        if (vm.editing.StatusLevel2.length > 0) {
            var m = $filter('orderBy')(vm.editing.StatusLevel2, 'StatusLevel2Name');
            if (m && m.length > 0) {
                vm.editing.StatusLevel2 = m;
            }
        }

        vm.editMode = true;
        vm.editMode = 2;
    };

    vm.openEditStatusLevel2 = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var subid = angular.element(elem).data("subid");

        vm.editTitle = "Kemaskini Status Tahap 2";
        var filtered = $filter('filter')(vm.editing.StatusLevel2, { "StatusLevel2ID": subid }, true);

        if (filtered.length > 0) {
            angular.extend(vm.editing, {
                EditingSub: filtered[0]
            });
            vm.editing.EditingSub.StatusLevel2 = filtered[0].StatusLevel2;

            if (vm.editing.StatusLevel2.length > 0) {
                var m = $filter('orderBy')(vm.editing.EditingSub.StatusLevel3, 'StatusLevel3Name');
                if (m && m.length > 0) {
                    vm.editing.EditingSub.StatusLevel3 = m;
                }
            }
        }

        vm.editMode = 4;
    };

    vm.openEditStatusLevel3 = function(e)
    {
        var elem = e.currentTarget || e.srcElement;
        var subid = angular.element(elem).data("subid");

        vm.editTitle = "Kemaskini Status Tahap 3";
        var filtered = $filter('filter')(vm.editing.EditingSub.StatusLevel3, { "StatusLevel3ID": subid }, true);

        if (filtered.length > 0) {
            angular.extend(vm.editing.EditingSub, {
                EditingSubLevel3: filtered[0]
            });
            vm.editing.EditingSub.EditingSubLevel3.StatusLevel3 = filtered[0];
        }

        vm.editMode = 6;
    }

    vm.save = function (myStatusForm) {
        //TODO: save
        var isDirty = myStatusForm.$dirty;
        if (myStatusForm.$valid) {
            if (isDirty) {

                var Statusmodel = {};
                var model = {};
                if (vm.editMode == constChangeStatusLvl1 || vm.editMode == constAddNewStatusLvl1)  //Change Status Level1
                {
                    getChangeHistory(myStatusForm);
                    Statusmodel = {
                        StatusLevel1ID: vm.editing.StatusLevel1ID,
                        StatusLevel1Name: vm.editing.StatusLevel1Name,
                        IsActive: vm.editing.IsActive,
                        EditMenuMode: constChangeStatusLvl1,
                    }

                    model = {
                        Statuslevel1: Statusmodel,
                        ChangeHistory: vm.changesHistory
                    }

                    AdminSI.updatedStatusLevel(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            });

                            if (vm.editing.StatusLevel1ID == undefined)
                            {
                                vm.editMode = false;
                                vm.init();
                            }
                            else
                            {
                                vm.editing1 = r.data;
                                vm.editTitle = "Kemaskini Status Level 1";
                                var filtered = $filter('filter')(vm.editing1, {
                                    "StatusLevel1ID": vm.editing.StatusLevel1ID
                                }, true);

                                if (filtered.length > 0) vm.editing = filtered[0];
                                vm.editMode = 2;
                                vm.changesHistory = [];
                            }
                   
                        }
                    });
                }
                else if (vm.editMode == constAddNewStatusLevel2 || vm.editMode == constChangeStatusLevel2)  // Change Status Level 2
                {
                    getChangeHistory(myStatusForm);

                        Statusmodel = {
                            StatusLevel1ID: vm.editing.StatusLevel1ID,
                            StatusLevel2Name: vm.editing.EditingSub.StatusLevel2Name,
                            StatusLevel2ID: vm.editing.EditingSub.StatusLevel2ID,
                            IsActiveLevel2: vm.editing.EditingSub.IsActive,
                            EditMenuMode: vm.editMode,

                        }

                        model = {
                            Statuslevel1: Statusmodel,
                            ChangeHistory: vm.changesHistory
                        }

                        if (vm.editMode == constAddNewStatusLevel2)  //Add New Status Level 2
                        {
                            AdminSI.updatedStatusLevel(model).then(function (r) {
                                if (r.status == 200) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    });

                                    vm.list = r.data;
                                    vm.editTitle = "Kemaskini Status Level 2";
                                    var filtered = $filter('filter')(vm.list, { "StatusLevel1ID": vm.editing.StatusLevel1ID }, true);

                                    if (filtered.length > 0) vm.editing = filtered[0];
                                    vm.editMode = 2;
                                    vm.changesHistory = [];
                                }
                            });
                        }
                        else {
                            AdminSI.updatedStatusLevel(model).then(function (r) {
                                if (r.status == 200) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    });

                                    vm.list = r.data;
                                    vm.editTitle = "Kemaskini Status Level 2";
                                    var filtered = $filter('filter')(vm.list, { "StatusLevel1ID": vm.editing.StatusLevel1ID }, true);

                                    if (filtered.length > 0) vm.editing = filtered[0];
                                    vm.editMode = 2;
                                    vm.changesHistory = [];
                                }
                            });
                        }
                 
                }
                else  
                {                                                                    // Change Status Level 3
                    getChangeHistory(myStatusForm);
                   
                    var checkDuplicateName = $filter('filter')(vm.editing.EditingSub.StatusLevel3, { "StatusLevel3Name": vm.editing.EditingSub.EditingSubLevel3.StatusLevel3Name }, true);
                    if (checkDuplicateName.length > 0 && checkDuplicateName[0].StatusLevel3ID != vm.editing.StatusLevel3ID) {
                        swal("Gagal", "Status Tahap 3 ini telah digunakan. Cuba guna status tahap 3 Lain", "error");
                        vm.changesHistory = [];
                    }
                    else
                    {
                        Statusmodel = {
                            StatusLevel1ID: vm.editing.StatusLevel1ID,
                            StatusLevel2Name: vm.editing.EditingSub.StatusLevel2Name,
                            StatusLevel2ID: vm.editing.EditingSub.StatusLevel2ID,
                            IsActiveLevel2: vm.editing.EditingSub.IsActive,
                            StatusLevel3ID: vm.editing.EditingSub.EditingSubLevel3.StatusLevel3ID,
                            StatusLevel3Name: vm.editing.EditingSub.EditingSubLevel3.StatusLevel3Name,
                            IsActiveLevel3: vm.editing.EditingSub.EditingSubLevel3.IsActive,
                            EditMenuMode: vm.editMode,

                        }

                        model = {
                            Statuslevel1: Statusmodel,
                            ChangeHistory: vm.changesHistory
                        }

                        if (vm.editMode == constAddStatusLevel3)  // Add Status Level 3 
                        {
                            AdminSI.updatedStatusLevel(model).then(function (r) {
                                if (r.status == 200) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    });

                                    vm.list = r.data;
                                    vm.editTitle = "Kemaskini Status Level 2";

                                    var filtered = $filter('filter')(vm.list, { "StatusLevel1ID": vm.editing.StatusLevel1ID }, true);
                                    filtered = $filter('filter')(filtered[0].StatusLevel2, { "StatusLevel2ID": vm.editing.EditingSub.StatusLevel2ID }, true);


                                    if (filtered.length > 0) {
                                        angular.extend(vm.editing, {
                                            EditingSub: filtered[0]
                                        });
                                        vm.editing.EditingSub.StatusLevel2 = filtered[0].StatusLevel2;
                                    }

                                    vm.editMode = 4;
                                    vm.changesHistory = [];
                                }
                            });
                        }
                        else {   // Edit Status Level 3 
                            AdminSI.updatedStatusLevel(model).then(function (r) {
                                if (r.status == 200) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    });

                                    vm.list = r.data;
                                    vm.editTitle = "Kemaskini Status Level 2";

                                    var filtered = $filter('filter')(vm.list, { "StatusLevel1ID": vm.editing.StatusLevel1ID }, true);
                                    filtered = $filter('filter')(filtered[0].StatusLevel2, { "StatusLevel2ID": vm.editing.EditingSub.StatusLevel2ID }, true);

                                    if (filtered.length > 0) {
                                        angular.extend(vm.editing, {
                                            EditingSub: filtered[0]
                                        });
                                        vm.editing.EditingSub.StatusLevel2 = filtered[0].StatusLevel2;
                                    }

                                    vm.editMode = 4;
                                    vm.changesHistory = [];
                                    vm.editMode = 4;
                                    vm.changesHistory = [];
                                }
                            });
                        }
                    }
         
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        }
        else {
            sswal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    vm.cancelStatusLevel2 = function()
    {
        vm.editTitle = "Kemaskini Status Tahap 1";
        vm.editMode = 2;
    }

    vm.cancelStatusLevel3 = function()
    {
        vm.init();
        vm.editTitle = "Kemaskini Status Tahap 2";
        vm.editMode = 4;
    }

    vm.BackMainPage = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }
    vm.deleteStatusLevel = function (StatusLevel1) {
        vm.editMode = false;

        var filtered = $filter('filter')(vm.StatusLevelList, { "StatusLevel1ID": StatusLevel1 }, true);
        if (filtered.length > 0)
        {
            swal("Gagal!", "Status ini ada status level 2.Buang tidak dibenarkan", "error");
        }
        else
        {
            var model = {
                StatusLevel1ID: StatusLevel1,
                IsActive: false,
                EditMenuMode: constChangeStatusLvl1,
            };
    
            swal({
                title: "Adakah anda pasti mahu deactivate Status Level  ini  ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.removeAdminStatusLevel(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


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

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

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

crmApp.controller('CfgSenaraiPenerimaanDoc', function ($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.SenaraiPenerimaanDoclist = {}
    vm.editMode = 0;
    vm.showValidationMsg = false;
    var constAddNewKategoriDoc = 1;
    var constChangeFileType = 2;
    var constAddNewFileTypePrefix = 3;
    var constChangeFileTypePrefix = 4;
    vm.changesHistory = [];


    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                  { Text: 'Tidak', Value: false }];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        AdminSI.getSenaraiPenerimaanDoc().then(function (r) {
            if (r.status === 200) {
                vm.SenaraiPenerimaanDoclist = r.data;
                
            }
        });
    };

    vm.addNewKategoriDoc = function()
    {
        vm.editTitle = "Tambah Kategori Dokumen";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editMode = 1;
    }

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Kategori Dokumen";
        var filtered = $filter('filter')(vm.SenaraiPenerimaanDoclist, { "DocListID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        vm.editMode = 2;
    };

    vm.addNewSubType = function () {
        vm.editTitle = "Tambah Maklumat Dokumen";
        angular.extend(vm.editing, {
            EditingSub: {
                DocListDetailID: 0,
                DocName: "",
                DocCode: "",
                IsActive : true
            }
        });
        vm.editMode = 3;
    };

    vm.openEditSubType = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var subid = angular.element(elem).data("subid");

        vm.editTitle = "Kemaskini Maklumat Dokumen";
        var filtered = $filter('filter')(vm.editing.DocListDetail, { "DocListDetailID": subid }, true);

        if (filtered.length > 0) {
            angular.extend(vm.editing, {
                EditingSub: filtered[0]
            });
            vm.editing.EditingSub.DocListDetail = filtered[0].DocListDetail;
        }

        //resetSubClsBene();
        vm.editMode = 4;
    };

    vm.removeChildDocList = function (myDocForm) {
        var model = {
            DocListID: vm.editing.DocListID,
            DocName: vm.editing.EditingSub.DocName,
            DocListDetailID: vm.editing.EditingSub.DocListDetailID,
            DocCode: vm.editing.EditingSub.DocCode,
            EditMenuMode: vm.editMode,
            IsActiveDocument: false,
            EditMenuMode: 4
        };
 
        swal({
            title: "Adakah anda pasti mahu deactivate Document Detail ini   ?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                AdminSI.removeCurrentAdminKategoriDocument(model).then(function (r) {
                    if (r.status == 200) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        });

                           //vm.list = r.data;
                        vm.editTitle = "Kemaskini DOCUMENT LIST DETAIL";
                          var filtered = $filter('filter')(vm.SenaraiPenerimaanDoclist, { "DocListID": vm.editing.DocListID}, true);

                           if (filtered.length > 0) vm.editing = filtered[0];
                            vm.editMode = 2;
                            vm.changesHistory = [];
                    }
                });
            }
            else {
                swal("Batal!", "Permohonan telah dibatalkan.", "error");
            }
        });

    }

    vm.save = function (myDocForm) {
        //TODO: save
        var isDirty = myDocForm.$dirty;
        if (myDocForm.$valid) {
            if (isDirty) {

                var DocListmodel = {};
                var model = {};
                if (vm.editMode == constChangeFileType || vm.editMode == constAddNewKategoriDoc)  //Change Parent File Type
                {
                    //for (i = 0; i < vm.SenaraiPenerimaanDoclist.length ; i++) {
                    //    if (vm.SenaraiPenerimaanDoclist[i].KategoriDocCode == vm.editing.KategoriDocCode && vm.SenaraiPenerimaanDoclist[i].DocListID != vm.editing.DocListID) {
                    //        vm.duplicateCode = true;
                    //    }
                    //};

                    var checkDuplicateName = $filter('filter')(vm.SenaraiPenerimaanDoclist, { "KategoriDocName": vm.editing.KategoriDocName }, true);
                    var checkDuplicateCode = $filter('filter')(vm.SenaraiPenerimaanDoclist, { "KategoriDocCode": vm.editing.KategoriDocCode }, true);
                    if (checkDuplicateName.length > 0 && checkDuplicateName[0].DocListID != vm.editing.DocListID) {
                        swal("Gagal", "Nama Kategori Dokumen ini telah digunakan. Cuba guna nama kategori dokumen Lain", "error");
                        vm.changesHistory = [];
                    }
                    else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].DocListID != vm.editing.DocListID) {
                        swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
                        vm.changesHistory = [];
                    }
                    else
                    {
                        getChangeHistory(myDocForm);
                        DocListmodel = {
                            DocListID: vm.editing.DocListID,
                            KategoriDocName: vm.editing.KategoriDocName,
                            KategoriDocCode: vm.editing.KategoriDocCode,
                            IsActiveKategoryDoc: vm.editing.IsActive,
                            EditMenuMode: vm.editMode,

                        }

                        model = {
                            DocList: DocListmodel,
                            ChangeHistory: vm.changesHistory
                        }

                        AdminSI.updatedDocumentName(model).then(function (r) {
                            if (r.status == 200) {
                                swal({
                                    title: "Berjaya Kemaskini!",
                                    type: "success",
                                    timer: 2500,
                                    showConfirmButton: false
                                });

                                vm.list = r.data;
                                vm.editTitle = "Kemaskini Kategori Dokumen";
                                if (vm.editing.DocListID != undefined) {
                                    var filtered = $filter('filter')(vm.list, {
                                        "DocListID": vm.editing.DocListID
                                    }, true);
                                    if (filtered.length > 0) vm.editing = filtered[0];
                                }
                                else {
                                    var filtered = $filter('filter')(vm.list, {
                                        "KategoriDocCode": vm.editing.KategoriDocCode
                                    }, true);
                                    if (filtered.length > 0) vm.editing = filtered[0];
                                    //vm.editing.DocListID = filtered[0].DocListID
                                }

                                vm.editMode = 2;
                                vm.changesHistory = [];
                            }
                        });
                    }  
                }
                else {
                    vm.changesHistory = [];
                    for (i = 0; i < vm.editing.DocListDetail.length; i++) {
                        if (vm.editing.DocListDetail[i].DocName == vm.editing.EditingSub.DocName && vm.editing.DocListDetail[i].DocListDetailID != vm.editing.EditingSub.DocListDetailID)
                        {
                            vm.duplicateName = true;
                        }
                        else
                        if (vm.editing.DocListDetail[i].DocCode == vm.editing.EditingSub.DocCode && vm.editing.DocListDetail[i].DocListDetailID != vm.editing.EditingSub.DocListDetailID) {
                            vm.duplicateCode = true;
                        }     
                    }

                    if (vm.duplicateName) {
                        swal("Gagal", "Nama Dokumen ini telah digunakan. Cuba guna nama dokumen Lain", "error");
                        vm.changesHistory = [];
                        vm.duplicateName = false;
                        vm.duplicateCode = false;
                    }
                    else if (vm.duplicateCode) {
                        swal("Gagal", "Kod Dokumen ini telah digunakan. Cuba buat kod dokumen baru", "error");
                        vm.changesHistory = [];
                        vm.duplicateCode = false;
                        vm.duplicateName = false;
                    }
                    else {
                        getChangeHistory(myDocForm);
                        DocListmodel = {
                            DocListID: vm.editing.DocListID,
                            DocName: vm.editing.EditingSub.DocName,
                            DocListDetailID: vm.editing.EditingSub.DocListDetailID,
                            DocCode: vm.editing.EditingSub.DocCode,
                            IsActiveDocument: vm.editing.EditingSub.IsActive,
                            EditMenuMode: vm.editMode,

                        }

                        model = {
                            DocList: DocListmodel,
                            ChangeHistory: vm.changesHistory
                        }

                        if (vm.editMode == constAddNewFileTypePrefix)  //Edit Document Name
                        {
                            AdminSI.updatedDocumentName(model).then(function (r) {
                                if (r.status == 200) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    });

                                    vm.list = r.data;
                                    vm.editTitle = "Kemaskini Kategori Dokumen ";
                                    var filtered = $filter('filter')(vm.list, { "DocListID": vm.editing.DocListID }, true);

                                    if (filtered.length > 0) vm.editing = filtered[0];
                                    vm.editMode = 2;
                                    vm.changesHistory = [];
                                }
                            });
                        }
                        else {
                            AdminSI.updatedDocumentName(model).then(function (r) {
                                if (r.status == 200) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    });

                                    vm.list = r.data;
                                    vm.editTitle = "Kemaskini Kategori Dokumen";
                                    var filtered = $filter('filter')(vm.list, { "DocListID": vm.editing.DocListID }, true);

                                    if (filtered.length > 0) vm.editing = filtered[0];
                                    vm.editMode = 2;
                                    vm.changesHistory = [];
                                }
                            });
                        }
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        }
        else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.cancel = function () {
        vm.editMode = 0;
        vm.init();
        vm.showValidationMsg = false;
    }

    vm.cancelEditSubType = function () {
        vm.editTitle = "Kemaskini Kategori Dokumen";
        vm.editMode = 2;
    };

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

    vm.deleteSenaraiPenerimaanDoclist = function (DocListID) {
        vm.editMode = false;
        var model = {
            DocListID: DocListID,
            IsActiveKategoryDoc: false,
            EditMenuMode: 2
        };

        swal({
            title: "Adakah anda pasti mahu deactivate Kategori Document ini  ?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                AdminSI.removeCurrentAdminKategoriDocument (model).then(function (r) {
                    if (r.status == 200) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });


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

    }

});

crmApp.controller('CfgCCTemplateName', function ($scope, $filter, $q, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.isEmailCCTemplate = $window.isEmailCCTemplate;

    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                      { Text: 'Tidak', Value: false }];

    vm.dtInstance = {};
    vm.kategoriList = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];
    vm.duplicateCode = false;

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        var model = {};
        if (vm.isEmailCCTemplate == "True") {

            $scope.IsEmailCCTemplate = "E"
            AdminSI.getAllCCTemplateName($scope.IsEmailCCTemplate).then(function (r) {
                if (r.status === 200) {
                    vm.CCTemplateName = r.data;
                }
            });
        }
        else {

            $scope.IsEmailCCTemplate = "S"
            AdminSI.getAllCCTemplateName($scope.IsEmailCCTemplate).then(function (r) {
                if (r.status === 200) {
                    vm.CCTemplateName = r.data;
                }
            });
        }
       
    };

    getDDLOptions().then(function (data) {

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

    vm.addNew = function () {
        if (vm.isEmailCCTemplate == "True") {
            vm.editTitle = "Tambah Email Contact Center Template";
        }
        else
        {
            vm.editTitle = "Tambah Contact Center Template";
        }
      
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsAgentOption = true;
    };

    vm.openEditCCTemplateName = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        if (vm.isEmailCCTemplate == "True") {
            vm.editTitle = "Kemaskini Email Contact Center Template";
        }
        else
        {
            vm.editTitle = "Kemaskini Contact Center Template";
        }
      
        var filtered = $filter('filter')(vm.CCTemplateName, { "CCTemplateNameID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];

        vm.editMode = true;
    };

    vm.save = function (templateForm) {
        var isDirty = templateForm.$dirty;
        if (templateForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    var checkDuplicateName = $filter('filter')(vm.CCTemplateName, { "CCTemplateName": vm.editing.CCTemplateName }, true);
                    var checkDuplicateCode = $filter('filter')(vm.CCTemplateName, { "CCTemplateCode": vm.editing.CCTemplateCode }, true);
                    if (checkDuplicateName.length > 0 && checkDuplicateName[0].CCTemplateNameID != vm.editing.CCTemplateNameID) {
                        swal("Gagal", "CC Template Name ini telah digunakan. Cuba guna CC template name Lain", "error");
                        vm.changesHistory = [];
                    }
                    else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].CCTemplateNameID != vm.editing.CCTemplateNameID) {
                        swal("Gagal", "CC Template Code ini telah digunakan. Cuba buat CC template code  baru", "error");
                        vm.changesHistory = [];
                    }
                    else
                    {
                        getChangeHistory(templateForm);
                        var model = {};
                        if (vm.isEmailCCTemplate == "True") {
                            vm.editing.CCTemplateType = 'E';
                            model = {
                                CCTemplateName: vm.editing,
                                ChangeHistory: vm.changesHistory
                            }
                        }
                        else {
                            vm.editing.CCTemplateType = 'S';
                            model = {
                                CCTemplateName: vm.editing,
                                ChangeHistory: vm.changesHistory
                            }
                        }

                        AdminSI.updateCCTemplateName(model).then(function (r) {
                            if (r.status === 200) {
                                if (r.data) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    }, function () {
                                        location.reload();
                                    });
                                }
                                else
                                    swal("Gagal", r.data, "error");
                            } else
                                swal("Gagal", r.data, "error");
                        });
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    vm.deleteCCTemplateName = function (CCTemplateNameID) {
        vm.editMode = false;
        var model = {
            CCTemplateNameID: CCTemplateNameID,
            IsActive: false,
        };
 
        swal({
            title: "Adakah anda pasti mahu deactivate Nama Template ini  ?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                AdminSI.removeCurrentAdminCCTemplateName(model).then(function (r) {
                    if (r.status == 200) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });


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

    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

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

crmApp.controller('CfgKategoriPenyelesaian', function ($scope, $filter, $q, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                          { Text: 'Tidak', Value: false }];
    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        var model = { LookupCode: "KategoriPenyelesaian" };
        AdminSI.getLookupParam(model).then(function (r) {
            if (r.status === 200) {
                vm.list = r.data;
            }
        });
    };

    vm.addNew = function () {
        vm.editTitle = "Tambah Kategori Penyelesaian";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsDefault = false;
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Kategori Penerimaan ";
        var filtered = $filter('filter')(vm.list, { "LookupParamID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.IsDefault == null) {
            vm.editing.IsDefault = false;
        }
        vm.editMode = true;
    };

    vm.save = function (myForm) {
        var isDirty = myForm.$dirty;
        if (myForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(myForm);
                    if (vm.editing.IsDefault == true) { //if IsDefault = true
                        for (i = 0; i < vm.list.length ; i++) {
                            if (vm.list[i].LookupParamID == vm.editing.LookupParamID)
                                vm.list[i].IsDefault = false; //set IsDefault = false for current LookupParamID 
                        };

                        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
                        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
                        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Nama ini telah digunakan. Cuba guna jenis nama lain", "error");
                            vm.changesHistory = [];
                        }
                        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
                            vm.changesHistory = [];
                        }
                        else {
                            var filtered = $filter('filter')(vm.list, { "IsDefault": true }, true);

                            if (filtered.length >= 1) { //if more than 1 default value 
                                swal({
                                    title: "Default value has been set for other value. Are you sure you want to set this as Default value?",
                                    text: "",
                                    type: "warning",
                                    showCancelButton: true,
                                    confirmButtonText: "Yes",
                                    cancelButtonText: "No",
                                    closeOnConfirm: false,
                                    closeOnCancel: false
                                }, function (isConfirm) {
                                    if (isConfirm) {
                                        var model = [];
                                        model.push(filtered[0]);
                                        vm.editing.IsDefault = false;
                                        vm.editing.LookupCode = "KategoriPenyelesaian";
                                        model.push(vm.editing);
                                        AdminSI.addDefaultLookupParam(model).then(function (r) {
                                            if (r.status === 200) {
                                                if (r.data) {
                                                    swal({
                                                        title: "Berjaya Kemaskini!",
                                                        type: "success",
                                                        timer: 2500,
                                                        showConfirmButton: false
                                                    }, function () {
                                                        location.reload();
                                                    });
                                                }
                                                else
                                                    swal("Gagal", r.data, "error");
                                            } else
                                                swal("Gagal", r.data, "error");
                                        })
                                    } else {
                                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                                    }
                                });
                            }
                            else { // If IsDefault = true & length = 0
                                vm.editing.IsDefault = true;
                                AddLookupParam();
                            };
                        }
                     
                    } else { //if false, Save only
                        AddLookupParam();
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.deleteKategoriPenyelesaian = function (lookupParamID) {
        vm.editMode = false;
        var model = {
            LookupParamID: lookupParamID,
            IsActive: false,
            LookupCode: "KategoriPenyelesaian"
        };

        swal({
            title: "Adakah anda pasti mahu deactivate kategori document? ?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                AdminSI.inactiveLookupParam(model).then(function (r) {
                    if (r.status == 200) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });


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

    }

    function AddLookupParam()
    {
        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Nama ini telah digunakan. Cuba guna nama lain", "error");
            vm.changesHistory = [];
        }
        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
            vm.changesHistory = [];
        }
        else {
            model = vm.editing;
            model.LookupCode = "KategoriPenyelesaian";
            model.ChangeHistory = vm.changesHistory
            AdminSI.addLookupParam(model).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });
                    }
                    else
                        swal("Gagal", r.data, "error");
                } else
                    swal("Gagal", r.data, "error");
            })
        }
    };

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

});

crmApp.controller('CfgCFFKategori', function ($scope, $filter, $q, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                          { Text: 'Tidak', Value: false }];
    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];
    vm.SeksyenEnabledDocUnit = true;
    vm.JabatanEnabledDocUnit = true;

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {

        AdminSI.getAllCFFKategori().then(function (r) {
            if (r.status === 200) {
                vm.cffKategoriList = r.data;
            }
        });
    };

    getDDLOptions().then(function (data) {

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

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

    vm.addNew = function () {
        vm.editTitle = "Tambah CFF Kategori";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsDefault = false;
        vm.GetABC = function () {
                return false;
        }
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");
        vm.DefaultUnitID = "";

        vm.editTitle = "Kemaskini CFF Kategori";
        var filtered = $filter('filter')(vm.cffKategoriList, { "CFFKategoriID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.IsDefault == null) {
            vm.editing.IsDefault = false;
        }

        var m = $filter('filter')(vm.MainKategoriOptions, { Kategori1ID: vm.editing.Kategori1ID }, true);
        if (m.length > 0 && m != undefined) {
            vm.editing.Kategori1ID = m[0].Kategori1ID;
        }
        else
        {
            vm.editing.Kategori1ID = "";
        }

        m = $filter('filter')(vm.JenisCawanganOptions, { Value: vm.editing.JenisCawanganID }, true);
        if (m.length > 0) {
            vm.editing.JenisCawanganID = m[0].Value;
        }
        else {
            vm.editing.JenisCawanganID = "";
        }

        var DefaultUnitID = "";
        if (vm.editing.DefaultUnitID != null && vm.editing.DefaultUnitID > 0)
        {
            DefaultUnitID = vm.editing.DefaultUnitID.toString();
        }
        else
        {
            DefaultUnitID = "";
        }

        if (DefaultUnitID != "")
        {
            m = $filter('filter')(vm.WorkflowAssignToUnitOptionDocUnit, { ID: DefaultUnitID }, true);
            if (m.length > 0) {
                //vm.editing.DefaultUnitID = m[0].Value;
                vm.DefaultUnitID = m[0];
            }
            else {
                m = $filter('filter')(vm.WorkflowAssignToCawanganOptionDocUnit, { ID: DefaultUnitID }, true);
                if (m.length > 0) {
                    vm.DefaultUnitID = m[0];
                }
                else {
                    m = $filter('filter')(vm.WorkflowAssignToJabatanOptionDocUnit, { ID: DefaultUnitID }, true);
                    if (m.length > 0) {
                        vm.DefaultUnitID = m[0];
                    }
                    else {
                        m = $filter('filter')(vm.WorkflowAssignToSeksyenOptionDocUnit, { ID: DefaultUnitID }, true);
                        if (m.length > 0) {
                            vm.DefaultUnitID = m[0];
                        }
                        else {
                            vm.editing.DefaultUnitID = "";
                        }

                    }

                }

            }
        }
        else
        {
            vm.editing.DefaultUnitID = "";
        }
     
        if (vm.editing.FunctionalRoleID != null)
        {
            var objFunctionRoleID = vm.editing.FunctionalRoleID.split('||');
            vm.editing.selected = [];
            angular.forEach(objFunctionRoleID, function (value, key) {

                m = $filter('filter')(vm.FunctionalRoleOptions, { FunctionalRoleID: parseInt(value) }, true);
                if (m.length > 0) {

                    vm.editing.selected.push(m[0].FunctionalRoleID);

                }
                else {
                    vm.editing.selected = "";
                }
            })
        }
        else
        {
            vm.editing.selected = "";
        }

        vm.GetABC =function()
        {
            if (vm.editing.selected != "" || vm.editing.DefaultUnitID != "" || vm.editing.JenisCawanganID != "") {
                return true;
            }
            else
            {
                    return false; 
            }
        }
        
        vm.editMode = true;
    };


    vm.SetGeneral = function ()
    {
        if ($('#Pengagihan').is(':checked')) {
            return true;
        }
        else
        {
            return false;
        }

    }
    vm.save = function (myForm) {

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

        var isDirty = myForm.$dirty;
        if (myForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(myForm);
                    var model = {};
                    var CFFModel = {};
                    var checkDuplicateName = $filter('filter')(vm.cffKategoriList, { "SubKategoriName": vm.editing.SubKategoriName }, true);
                    if (checkDuplicateName.length > 0 && checkDuplicateName[0].CFFKategoriID != vm.editing.CFFKategoriID) {
                        swal("Gagal", "CFF Kategori ini telah digunakan. Cuba guna CFF Kategori  Lain", "error");
                        vm.changesHistory = [];
                    }
                    else
                    {
                        if (vm.editing.selected != undefined) {
                            if (vm.editing.selected.length == 0) {
                                vm.editing.FunctionalRoleID = 0;
                            }
                            else {
                                vm.editing.FunctionalRoleID = vm.editing.selected.join(" || ");
                            }
                        }
                        else {
                            vm.editing.FunctionalRoleID = 0;
                        }

                        if (vm.DefaultUnitID != undefined) {
                            if (vm.DefaultUnitID.ID > 0) {
                                vm.editing.DefaultUnitID = vm.DefaultUnitID.ID
                            }
                            else {
                                vm.editing.DefaultUnitID = 0;
                            }
                        }
                        else {
                            vm.editing.DefaultUnitID = 0;
                        }

                        CFFModel = {
                            CFFKategoriID: vm.editing.CFFKategoriID,
                            SubKategoriName: vm.editing.SubKategoriName,
                            Kategori1ID: (vm.editing.Kategori1ID == undefined || vm.editing.Kategori1ID == "") ? '' : vm.editing.Kategori1ID,
                            SkillSet: (vm.editing.SkillSet == undefined || vm.editing.SkillSet == "") ? '' : vm.editing.SkillSet,
                            IsActive: vm.editing.IsActive,
                            FunctionalRoleID: vm.editing.FunctionalRoleID,
                            DefaultUnitID: vm.editing.DefaultUnitID,
                            JenisCawanganID: (vm.editing.JenisCawanganID == undefined || vm.editing.JenisCawanganID == "") ? 0 : vm.editing.JenisCawanganID
                        }
                        model = {
                            CFFKategori: CFFModel,
                            ChangeHistory: vm.changesHistory
                        }
                        AdminSI.updateCFFKategori(model).then(function (r) {
                            if (r.status === 200) {
                                if (r.data) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    }, function () {
                                        location.reload();
                                    });
                                }
                                else
                                    swal("Gagal", r.data, "error");
                            } else
                                swal("Gagal", r.data, "error");
                        });
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.deleteCFFKategori = function (cffKatId,IsActive) {
        vm.editMode = false;

        if (IsActive)
        {
            var model = {
                CFFKategoriID: cffKatId,
                IsActive: false,
            };

            swal({
                title: "Adakah anda pasti mahu deactivate CFF Kategori? ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.deleteCFFKategori(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


                        }
                    });
                }
                else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        }
        else
        {
            var model = {
                CFFKategoriID: cffKatId,
                IsActive: true,
            };

            swal({
                title: "Adakah anda pasti mahu activate CFF Kategori? ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.deleteCFFKategori(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


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

    }

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    vm.ShowFilterOptionDocUnit = function () {

        vm.showdetailDocUnit = !vm.showdetailDocUnit;
    }

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

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

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

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


    }

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

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

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

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

    vm.seksyenChange = function (selectedTimbalan) {

        vm.actWorkflowAssignToJabatanOption = [];

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

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

                vm.actWorkflowAssignToJabatanOption = m;
            }


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

    };

    vm.seksyenChangeDocUnit = function (selectedTimbalanDocUnit) {

        vm.actWorkflowAssignToJabatanOptionDocUnit = [];

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

    };


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

        vm.actWorkflowAssignToCawanganOption = [];

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

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

                vm.actWorkflowAssignToCawanganOption = m;
            }

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

    };

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

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

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

    };


    vm.cawanganChange = function (SelectedCawangan) {

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

        vm.actWorkflowAssignToUnitOption = [];

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

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

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

                vm.actWorkflowAssignToUnitOption = m;
            }

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

        }

    };
    vm.cawanganChangeDocUnit = function (SelectedCawanganDocUnit) {

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

        vm.actWorkflowAssignToUnitOptionDocUnit = [];

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

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

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

    };

    vm.unitChange = function (SelectedUnits) {

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


    };

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

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

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

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

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

    }

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

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

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

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

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


    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else if($(document.getElementById(key))[0].tagName ='DIV')
                {
                    if (value.$viewValue == undefined)
                    {
                        newvalue = "";
                    }
                    else
                    {
                        if (value.$viewValue.length > 0) {

                            newvalue = value.$viewValue[0].RoleName

                        }
                        else {
                            newvalue = value.$viewValue.DisplayName + ' ( ' + value.$viewValue.AdditionalInfo + ' )';
                        }
                    }
              
                }     
                else {
                    newvalue = value.$viewValue;
                }

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

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

});

crmApp.controller('CfgUnitType', function ($scope, $filter, $q, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                          { Text: 'Tidak', Value: false }];
    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {

        AdminSI.getAllUnitType().then(function (r) {
            if (r.status === 200) {
                vm.unitTypeList = r.data;
            }
        });
    };

    vm.addNewUnitType = function () {
        vm.editTitle = "Tambah Jenis Unit ";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsDefault = false;
    };

    vm.openEditUnitType = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Jenis Unit";
        var filtered = $filter('filter')(vm.unitTypeList, { "UnitTypeID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.IsDefault == null) {
            vm.editing.IsDefault = false;
        }
        vm.editMode = true;
    };

    vm.save = function (unitTypeForm) {
        var isDirty = unitTypeForm.$dirty;
        if (unitTypeForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {

                    var checkUnitTypeNameDuplicate = $filter('filter')(vm.unitTypeList, { "TypeName": vm.editing.TypeName }, true);
                    if (checkUnitTypeNameDuplicate.length > 0 && checkUnitTypeNameDuplicate[0].UnitTypeID != vm.editing.UnitTypeID)
                    {
                        swal("Gagal!", "Nama Unit Type sudah digunakan!", "error");
                    }
                    else
                    {
                        getChangeHistory(unitTypeForm);
                        var model = {};
                        model = {
                            UnitType: vm.editing,
                            ChangeHistory: vm.changesHistory
                        }
                        AdminSI.updateUnitType(model).then(function (r) {
                            if (r.status === 200) {
                                if (r.data) {
                                    swal({
                                        title: "Berjaya Kemaskini!",
                                        type: "success",
                                        timer: 2500,
                                        showConfirmButton: false
                                    }, function () {
                                        location.reload();
                                    });
                                }
                                else
                                    swal("Gagal", r.data, "error");
                            } else
                                swal("Gagal", r.data, "error");
                        });
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.deleteUnitType = function (unitTypeID, IsActive) {
        vm.editMode = false;
        var model ={};
        if (IsActive)
        {
            model = {
                UnitTypeID: unitTypeID,
                IsActive: false,
            };

            swal({
                title: "Adakah anda pasti mahu deactivate Unit Type ini ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.deleteUnitType(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


                        }
                    });
                }
                else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        }
        else
        {
            model = {
                UnitTypeID: unitTypeID,
                IsActive: true,
            };

            swal({
                title: "Adakah anda pasti mahu activate Unit Type ini ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.deleteUnitType(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


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

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

});

crmApp.controller('CfgCCCampaignName', function ($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.isHCLCampaign = $window.isHCLCampaign;

    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                          { Text: 'Tidak', Value: false }];
    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];



    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        if (vm.isHCLCampaign == "True") {
            var model = { LookupCode: "CCCampaignHCL" };
            AdminSI.getLookupParam(model).then(function (r) {
                if (r.status === 200) {
                    vm.list = r.data;
                }
            });
        }
        else
        {
            var model = { LookupCode: "CCCampaign" };
            AdminSI.getLookupParam(model).then(function (r) {
                if (r.status === 200) {
                    vm.list = r.data;
                }
            });
        }
     
    };

    vm.addNew = function () {
        if (vm.isHCLCampaign == "True") {
            vm.editTitle = "Tambah CC Campaign HCL";
        }
        else
        {
            vm.editTitle = "Tambah CC Campaign HRCC";
        }
       
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsDefault = false;
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        if (vm.isHCLCampaign == "True") {
            vm.editTitle = "Kemaskini CC Campaign HCL";
        }
        else
        {
            vm.editTitle = "Kemaskini CC Campaign HRCC";
        }
       
        var filtered = $filter('filter')(vm.list, { "LookupParamID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.IsDefault == null) {
            vm.editing.IsDefault = false;
        }

        vm.editMode = true;
    };

    vm.save = function (myForm) {
        var isDirty = myForm.$dirty;
        if (myForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(myForm);
                    if (vm.editing.IsDefault == true) { //if IsDefault = true
                        for (i = 0; i < vm.list.length ; i++) {
                            if (vm.list[i].LookupParamID == vm.editing.LookupParamID)
                                vm.list[i].IsDefault = false; //set IsDefault = false for current LookupParamID 
                   
                        };

                        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
                        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
                        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Nama Campaign ini telah digunakan. Cuba guna nama campaign lain", "error");
                            vm.changesHistory = [];
                        }
                        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
                            vm.changesHistory = [];
                        }
                        else
                        {
                            var filtered = $filter('filter')(vm.list, { "IsDefault": true }, true);
                            if (filtered.length >= 1) { //if more than 1 default value 
                                swal({
                                    title: "Default value has been set for other value. Are you sure you want to set this as Default value?",
                                    text: "",
                                    type: "warning",
                                    showCancelButton: true,
                                    confirmButtonText: "Yes",
                                    cancelButtonText: "No",
                                    closeOnConfirm: false,
                                    closeOnCancel: false
                                }, function (isConfirm) {
                                    if (isConfirm) {
                                        var model = [];
                                        model.push(filtered[0]);
                                        vm.editing.IsDefault = false;
                                        if (vm.isHCLCampaign == "True") {
                                            vm.editing.LookupCode = "CCCampaignHCL";
                                        }
                                        else {
                                            vm.editing.LookupCode = "CCCampaign";
                                        }

                                        vm.editing.ChangeHistory = vm.changesHistory;
                                        model.push(vm.editing);
                                        AdminSI.addDefaultLookupParam(model).then(function (r) {
                                            if (r.status === 200) {
                                                if (r.data) {
                                                    swal({
                                                        title: "Berjaya Kemaskini!",
                                                        type: "success",
                                                        timer: 2500,
                                                        showConfirmButton: false
                                                    }, function () {
                                                        location.reload();
                                                    });
                                                }
                                                else
                                                    swal("Gagal", r.data, "error");
                                            } else
                                                swal("Gagal", r.data, "error");
                                        })
                                    } else {
                                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                                    }
                                });
                            }
                            else { // If IsDefault = true & length = 0
                                vm.editing.IsDefault = true;
                                AddLookupParam();
                            };
                        }      
                    } else { //if false, Save only
                        AddLookupParam();
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.deleteCCCampaign= function (lookupParamID,IsAktive) {
        vm.editMode = false;
        if (IsAktive)
        {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: false,
                LookupCode: "CCCampaign"
            };

            swal({
                title: "Adakah anda pasti mahu deactivate CC Campaign ini ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


                        }
                    });
                }
                else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        }
        else
        {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: true,
                LookupCode: "CCCampaign"
            };

            swal({
                title: "Adakah anda pasti mahu activate CC Campaign ini ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


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

    }

    function AddLookupParam() {
        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Nama Campaign ini telah digunakan. Cuba guna nama campaign lain", "error");
            vm.changesHistory = [];
        }
        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
            vm.changesHistory = [];
        }
        else
        {
            model = vm.editing;
            if (vm.isHCLCampaign == "True") {
                model.LookupCode = "CCCampaignHCL";
            }
            else {
                model.LookupCode = "CCCampaign";
            }

            model.ChangeHistory = vm.changesHistory
            AdminSI.addLookupParam(model).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });
                    }
                    else
                        swal("Gagal", r.data, "error");
                } else
                    swal("Gagal", r.data, "error");
            })
        }   
    };

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

});

crmApp.controller('CfgDMStatus', function ($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                          { Text: 'Tidak', Value: false }];
    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];
    vm.duplicateCode = false;

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        var model = { LookupCode: "DMSStatus" };
        AdminSI.getLookupParam(model).then(function (r) {
            if (r.status === 200) {
                vm.list = r.data;
            }
        });
    };

    vm.addNew = function () {
        vm.editTitle = "Tambah DMS Status";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsDefault = false;
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini DMS Status";
        var filtered = $filter('filter')(vm.list, { "LookupParamID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.IsDefault == null) {
            vm.editing.IsDefault = false;
        }

        vm.editMode = true;
    };

    vm.save = function (myForm) {
        var isDirty = myForm.$dirty;
        if (myForm.$valid) {
            if (isDirty) {
                if (vm.editMode) 
                {
                    getChangeHistory(myForm);
                    if (vm.editing.IsDefault == true) { //if IsDefault = true
                        for (i = 0; i < vm.list.length ; i++) {
                            if (vm.list[i].LookupParamID == vm.editing.LookupParamID)
                                vm.list[i].IsDefault = false; //set IsDefault = false for current LookupParamID 
                        };

                        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
                        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
                        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID)
                        {
                            swal("Gagal", "Nama Status ini telah digunakan. Cuba guna Nama Status Lain", "error");
                            vm.changesHistory = [];
                        }
                        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID)
                        {
                            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
                            vm.changesHistory = [];
                        }
                        else
                        {
                            var filtered = $filter('filter')(vm.list, { "IsDefault": true }, true);

                            if (filtered.length >= 1) { //if more than 1 default value 
                                swal({
                                    title: "Default value has been set for other value. Are you sure you want to set this as Default value?",
                                    text: "",
                                    type: "warning",
                                    showCancelButton: true,
                                    confirmButtonText: "Yes",
                                    cancelButtonText: "No",
                                    closeOnConfirm: false,
                                    closeOnCancel: false
                                }, function (isConfirm) {
                                    if (isConfirm) {
                                        var model = [];
                                        model.push(filtered[0]);
                                        vm.editing.IsDefault = false;
                                        vm.editing.LookupCode = "DMSStatus";
                                        vm.editing.ChangeHistory = vm.changesHistory;
                                        model.push(vm.editing);
                                        AdminSI.addDefaultLookupParam(model).then(function (r) {
                                            if (r.status === 200) {
                                                if (r.data) {
                                                    swal({
                                                        title: "Berjaya Kemaskini!",
                                                        type: "success",
                                                        timer: 2500,
                                                        showConfirmButton: false
                                                    }, function () {
                                                        location.reload();
                                                    });
                                                }
                                                else
                                                    swal("Gagal", r.data, "error");
                                            } else
                                                swal("Gagal", r.data, "error");
                                        })
                                    } else {
                                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                                    }
                                });
                            }
                            else { // If IsDefault = true & length = 0
                                vm.editing.IsDefault = true;
                                AddLookupParam();

                            };
                        }             
                    } else { //if false, Save only
                        AddLookupParam();
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.deleteCCCampaign = function (lookupParamID, IsAktive) {
        vm.editMode = false;
        if (IsAktive) {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: false,
                LookupCode: "DMSStatus"
            };

            swal({
                title: "Adakah anda pasti mahu deactivate DMS Status ini ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


                        }
                    });
                }
                else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        }
        else {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: true,
                LookupCode: "DMSStatus"
            };

            swal({
                title: "Adakah anda pasti mahu activate DMS Status ini ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


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


    }

    function AddLookupParam() {
        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Nama Status ini telah digunakan. Cuba guna Nama Status Lain", "error");
            vm.changesHistory = [];
        }
        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
            vm.changesHistory = [];
        }
        else
        {
            model = vm.editing;
            model.LookupCode = "DMSStatus";
            model.ChangeHistory = vm.changesHistory
            AdminSI.addLookupParam(model).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });
                    }
                    else
                        swal("Gagal", r.data, "error");
                } else
                    swal("Gagal", r.data, "error");
            })
        }
    };

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

});

crmApp.controller('CfgDMReturnedReason', function ($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                          { Text: 'Tidak', Value: false }];
    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('order', [[1, 'asc']])
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        var model = { LookupCode: "ReturnedReason" };
        AdminSI.getLookupParam(model).then(function (r) {
            if (r.status === 200) {
                vm.list = r.data;
            }
        });
    };

    vm.addNew = function () {
        vm.editTitle = "Tambah Outbound Alasan Dipulangkan";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsDefault = false;
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Outbound Alasan Dipulangkan";
        var filtered = $filter('filter')(vm.list, { "LookupParamID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.IsDefault == null) {
            vm.editing.IsDefault = false;
        }

        vm.editMode = true;
    };

    vm.save = function (myForm) {
        var isDirty = myForm.$dirty;
        if (myForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(myForm);
                    if (vm.editing.IsDefault == true) { //if IsDefault = true
                        for (i = 0; i < vm.list.length ; i++) {
                            if (vm.list[i].LookupParamID == vm.editing.LookupParamID)
                                vm.list[i].IsDefault = false; //set IsDefault = false for current LookupParamID 
                            //if (vm.list[i].LookupValue == vm.editing.LookupValue && vm.list[i].LookupParamID != vm.editing.LookupParamID) {
                            //    vm.duplicateCode = true;
                            //}
                        };

                        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
                        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
                        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Nama ini telah digunakan. Cuba guna nama lain", "error");
                            vm.changesHistory = [];
                        }
                        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
                            vm.changesHistory = [];
                        }
                        else
                        {
                            var filtered = $filter('filter')(vm.list, { "IsDefault": true }, true);

                            if (filtered.length >= 1) { //if more than 1 default value 
                                swal({
                                    title: "Default value has been set for other value. Are you sure you want to set this as Default value?",
                                    text: "",
                                    type: "warning",
                                    showCancelButton: true,
                                    confirmButtonText: "Yes",
                                    cancelButtonText: "No",
                                    closeOnConfirm: false,
                                    closeOnCancel: false
                                }, function (isConfirm) {
                                    if (isConfirm) {
                                        var model = [];
                                        model.push(filtered[0]);
                                        vm.editing.IsDefault = false;
                                        vm.editing.LookupCode = "ReturnedReason";
                                        vm.editing.ChangeHistory = vm.changesHistory;
                                        model.push(vm.editing);
                                        AdminSI.addDefaultLookupParam(model).then(function (r) {
                                            if (r.status === 200) {
                                                if (r.data) {
                                                    swal({
                                                        title: "Berjaya Kemaskini!",
                                                        type: "success",
                                                        timer: 2500,
                                                        showConfirmButton: false
                                                    }, function () {
                                                        location.reload();
                                                    });
                                                }
                                                else
                                                    swal("Failed", r.data, "error");
                                            } else
                                                swal("Failed", r.data, "error");
                                        })
                                    } else {

                                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                                    }
                                });
                            }
                            else { // If IsDefault = true & length = 0
                                vm.editing.IsDefault = true;
                                AddLookupParam();
                            };
                        }
                    } else { //if false, Save only
                        AddLookupParam();
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.deleteReturnedReason = function (lookupParamID, IsAktive) {
        vm.editMode = false;
        if (IsAktive) {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: false,
                LookupCode: "ReturnedReason"
            };

            swal({
                title: "Adakah anda pasti mahu deactivate DMS Status ini ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


                        }
                    });
                }
                else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        }
        else {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: true,
                LookupCode: "ReturnedReason"
            };

            swal({
                title: "Adakah anda pasti mahu activate DMS Status ini ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


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


    }

    function AddLookupParam() {
        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Nama ini telah digunakan. Cuba guna nama Lain", "error");
            vm.changesHistory = [];
        }
        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
            vm.changesHistory = [];
        }
        else {
            model = vm.editing;
            model.LookupCode = "ReturnedReason";
            model.ChangeHistory = vm.changesHistory
            AdminSI.addLookupParam(model).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });
                    }
                    else
                        swal("Gagal", r.data, "error");
                } else
                    swal("Gagal", r.data, "error");
            })
        }
    };

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

});

crmApp.controller('CfgTahap', function ($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                          { Text: 'Tidak', Value: false }];
    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('order', [[1, 'asc']])
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        var model = { LookupCode: "Tahap" };
        AdminSI.getLookupParam(model).then(function (r) {
            if (r.status === 200) {
                vm.list = r.data;
            }
        });
    };

    vm.addNew = function () {
        vm.editTitle = "Tambah Tahap";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsDefault = false;
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Tahap";
        var filtered = $filter('filter')(vm.list, { "LookupParamID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.IsDefault == null) {
            vm.editing.IsDefault = false;
        }

        vm.editMode = true;
    };

    vm.save = function (myForm) {
        var isDirty = myForm.$dirty;
        if (myForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(myForm);
                    if (vm.editing.IsDefault == true) { //if IsDefault = true
                        for (i = 0; i < vm.list.length ; i++) {
                            if (vm.list[i].LookupParamID == vm.editing.LookupParamID)
                                vm.list[i].IsDefault = false; //set IsDefault = false for current LookupParamID 
                  
                        };

                        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
                        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
                        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Nama Tahap ini telah digunakan. Cuba guna nama tahap Lain", "error");
                            vm.changesHistory = [];
                        }
                        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
                            vm.changesHistory = [];
                        }
                        else
                        {
                            var filtered = $filter('filter')(vm.list, { "IsDefault": true }, true);

                            if (filtered.length >= 1) { //if more than 1 default value 
                                swal({
                                    title: "Default value has been set for other value. Are you sure you want to set this as Default value?",
                                    text: "",
                                    type: "warning",
                                    showCancelButton: true,
                                    confirmButtonText: "Yes",
                                    cancelButtonText: "No",
                                    closeOnConfirm: false,
                                    closeOnCancel: false
                                }, function (isConfirm) {
                                    if (isConfirm) {
                                        var model = [];
                                        model.push(filtered[0]);
                                        vm.editing.IsDefault = false;
                                        vm.editing.LookupCode = "Tahap";
                                        vm.editing.ChangeHistory = vm.changesHistory;
                                        model.push(vm.editing);
                                        AdminSI.addDefaultLookupParam(model).then(function (r) {
                                            if (r.status === 200) {
                                                if (r.data) {
                                                    swal({
                                                        title: "Berjaya Kemaskini!",
                                                        type: "success",
                                                        timer: 2500,
                                                        showConfirmButton: false
                                                    }, function () {
                                                        location.reload();
                                                    });
                                                }
                                                else
                                                    swal("Gagal", r.data, "error");
                                            } else
                                                swal("Gagal", r.data, "error");
                                        })
                                    } else {
                                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                                    }
                                });
                            }
                            else { // If IsDefault = true & length = 0
                                vm.editing.IsDefault = true;
                                AddLookupParam();
                            };
                        }         
                    } else { //if false, Save only
                        AddLookupParam();
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.deleteTahap = function (lookupParamID, IsAktive) {
        vm.editMode = false;
        if (IsAktive) {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: false,
                LookupCode: "Tahap"
            };

            swal({
                title: "Adakah anda pasti mahu deactivate Tahap ini ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


                        }
                    });
                }
                else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        }
        else {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: true,
                LookupCode: "Tahap"
            };

            swal({
                title: "Adakah anda pasti mahu activate Tahap ini ?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


                        }
                    });
                }
                else {

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


    }

    function AddLookupParam() {
        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Nama Tahap ini telah digunakan. Cuba guna nama tahap Lain", "error");
            vm.changesHistory = [];
        }
        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
            vm.changesHistory = [];
        }
        else {
            model = vm.editing;
            model.LookupCode = "Tahap";
            model.ChangeHistory = vm.changesHistory
            AdminSI.addLookupParam(model).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });
                    }
                    else
                        swal("Gagal", r.data, "error");
                } else
                    swal("Gagal", r.data, "error");
            })
        }
    };

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

});

crmApp.controller('CfgParameters', function ($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;

    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('order', [[1, 'asc']])
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        AdminSI.getAllParameterSetting().then(function (r) {
            if (r.status === 200) {
                vm.paramterList = r.data;
            }
        });
    };

    vm.openEditParam = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Parameter";
        var filtered = $filter('filter')(vm.paramterList, { "ParameterID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.IsDefault == null) {
            vm.editing.IsDefault = false;
        }

        vm.editMode = true;
    };

    vm.save = function (myForm) {
        var isDirty = myForm.$dirty;
        if (myForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(myForm);
                    var model = {};
                    model = {
                        ParameterSetting: vm.editing,
                        ChangeHistory: vm.changesHistory
                    }
                    AdminSI.updateParameterSetting(model).then(function (r) {
                        if (r.status === 200) {
                            if (r.data) {
                                swal({
                                    title: "Berjaya Kemaskini!",
                                    type: "success",
                                    timer: 2500,
                                    showConfirmButton: false
                                }, function () {
                                    location.reload();
                                });
                            }
                            else
                                swal("Gagal", r.data, "error");
                        } else
                            swal("Gagal", r.data, "error");
                    });

                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

});

crmApp.controller('CfgTindakanSusulan', function ($scope, $filter, $q, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;

    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                      { Text: 'Tidak', Value: false }];

    vm.dtInstance = {};
    vm.sumberList = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('order', [[1, 'asc']])
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        AdminSI.getAllTindakanSusulan().then(function (r) {
            if (r.status === 200) {
                vm.tindakanSusulanList = r.data;
            }
        });
    };

    getDDLOptions().then(function (data) {

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

    vm.addNew = function () {
        vm.editTitle = "Tambah Sumber";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
    };

    vm.openEditSumber = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini Sumber";
        var filtered = $filter('filter')(vm.sumberList, { "SumberID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        vm.editMode = true;
    };

    vm.save = function (sumberForm) {
        var isDirty = sumberForm.$dirty;
        if (sumberForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(sumberForm);
                    var model = {};
                    model = {
                        Sumber: vm.editing,
                        ChangeHistory: vm.changesHistory
                    }
                    AdminSI.updateSumberDetails(model).then(function (r) {
                        if (r.status === 200) {
                            if (r.data) {
                                swal({
                                    title: "Berjaya Kemaskini!",
                                    type: "success",
                                    timer: 2500,
                                    showConfirmButton: false
                                }, function () {
                                    location.reload();
                                });
                            }
                            else
                                swal("Gagal", r.data, "error");
                        } else
                            swal("Gagal", r.data, "error");
                    });
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    vm.deleteSumber = function (sumberId) {
        vm.editMode = false;
        var model = {
            SumberID: sumberId,
            IsActive: false,
        };

        swal({
            title: "Adakah anda pasti mahu deactivate Sumber ini ?",
            text: "",
            type: "warning",
            showCancelButton: true,
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            closeOnConfirm: false,
            closeOnCancel: false
        }, function (isConfirm) {
            if (isConfirm) {
                AdminSI.removeCurrentSumberDetail(model).then(function (r) {
                    if (r.status == 200) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });


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

    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

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

crmApp.controller('CfgCCFromEmail', function ($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                          { Text: 'Tidak', Value: false }];
    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('order', [[1, 'asc']])
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        var model = { LookupCode: "CCFromEmail" };
        AdminSI.getLookupParam(model).then(function (r) {
            if (r.status === 200) {
                vm.list = r.data;
            }
        });
    };

    vm.addNew = function () {
        vm.editTitle = "Tambah CC From Email ";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsDefault = false;
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini CC From Email";
        var filtered = $filter('filter')(vm.list, { "LookupParamID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.IsDefault == null) {
            vm.editing.IsDefault = false;
        }

        vm.editMode = true;
    };

    vm.save = function (myForm) {
        var isDirty = myForm.$dirty;
        if (myForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(myForm);
                    if (vm.editing.IsDefault == true) { //if IsDefault = true
                        for (i = 0; i < vm.list.length ; i++) {
                            if (vm.list[i].LookupParamID == vm.editing.LookupParamID)
                                vm.list[i].IsDefault = false; //set IsDefault = false for current LookupParamID 
                        };

                        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
                        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
                        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Nama ini telah digunakan. Cuba guna nama lain", "error");
                            vm.changesHistory = [];
                        }
                        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
                            vm.changesHistory = [];
                        }
                        else
                        {
                            var filtered = $filter('filter')(vm.list, { "IsDefault": true }, true);

                            if (filtered.length >= 1) { //if more than 1 default value 
                                swal({
                                    title: "Default value has been set for other value. Are you sure you want to set this as Default value?",
                                    text: "",
                                    type: "warning",
                                    showCancelButton: true,
                                    confirmButtonText: "Yes",
                                    cancelButtonText: "No",
                                    closeOnConfirm: false,
                                    closeOnCancel: false
                                }, function (isConfirm) {
                                    if (isConfirm) {
                                        var model = [];
                                        model.push(filtered[0]);
                                        vm.editing.IsDefault = false;
                                        vm.editing.LookupCode = "CCFromEmail";
                                        vm.editing.ChangeHistory = vm.changesHistory;
                                        model.push(vm.editing);
                                        AdminSI.addDefaultLookupParam(model).then(function (r) {
                                            if (r.status === 200) {
                                                if (r.data) {
                                                    swal({
                                                        title: "Berjaya Kemaskini!",
                                                        type: "success",
                                                        timer: 2500,
                                                        showConfirmButton: false
                                                    }, function () {
                                                        location.reload();
                                                    });
                                                }
                                                else
                                                    swal("Gagal", r.data, "error");
                                            } else
                                                swal("Gagal", r.data, "error");
                                        })
                                    } else {
                                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                                    }
                                });
                            }
                            else { // If IsDefault = true & length = 0
                                vm.editing.IsDefault = true;
                                AddLookupParam();
                            };
                        }
                    } else { //if false, Save only
                        AddLookupParam();
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.deleteJenisPelanggan = function (lookupParamID, IsAktive) {
        vm.editMode = false;
        if (IsAktive) {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: false,
                LookupCode: "CCFromEmail"
            };

            swal({
                title: "Adakah anda pasti mahu deactivate CCFromEmail ini?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


                        }
                    });
                }
                else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        }
        else {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: true,
                LookupCode: "CCFromEmail"
            };

            swal({
                title: "Adakah anda pasti mahu activate CCFromEmail ini?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


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


    }

    function AddLookupParam() {
        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Nama ini telah digunakan. Cuba guna nama lain", "error");
            vm.changesHistory = [];
        }
        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
            vm.changesHistory = [];
        }
        else
        {
            model = vm.editing;
            model.LookupCode = "CCFromEmail";
            model.ChangeHistory = vm.changesHistory
            AdminSI.addLookupParam(model).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });
                    }
                    else
                        swal("Gagal", r.data, "error");
                } else
                    swal("Gagal", r.data, "error");
            })
        }
    };

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

});

crmApp.controller('CfgCCFromSMS', function ($scope, $filter, $window, DTOptionsBuilder, DTColumnDefBuilder, AdminSI) {
    var vm = this;
    vm.isActiveOptions = [{ Text: 'Ya', Value: true },
                          { Text: 'Tidak', Value: false }];
    vm.dtInstance = {};
    vm.list = {};
    vm.editing = {};
    vm.editMode = false;
    vm.showValidationMsg = false;
    vm.changesHistory = [];

    vm.dtOptions = DTOptionsBuilder.newOptions()
        .withOption('order', [[1, 'asc']])
        .withPaginationType('full_numbers')
        .withDisplayLength(10);

    vm.init = function () {
        var model = { LookupCode: "CCFromSMS" };
        AdminSI.getLookupParam(model).then(function (r) {
            if (r.status === 200) {
                vm.list = r.data;
            }
        });
    };

    vm.addNew = function () {
        vm.editTitle = "Tambah CC From SMS";
        vm.editing = {};
        vm.editMode = true;
        vm.editing.IsActive = true;
        vm.editing.IsDefault = false;
    };

    vm.openEdit = function (e) {
        var elem = e.currentTarget || e.srcElement;
        var id = angular.element(elem).data("id");

        vm.editTitle = "Kemaskini CC From SMS";
        var filtered = $filter('filter')(vm.list, { "LookupParamID": id }, true);

        if (filtered.length > 0) vm.editing = filtered[0];
        if (vm.editing.IsDefault == null) {
            vm.editing.IsDefault = false;
        }

        vm.editMode = true;
    };

    vm.save = function (myForm) {
        var isDirty = myForm.$dirty;
        if (myForm.$valid) {
            if (isDirty) {
                if (vm.editMode) {
                    getChangeHistory(myForm);
                    if (vm.editing.IsDefault == true) { //if IsDefault = true
                        for (i = 0; i < vm.list.length ; i++) {
                            if (vm.list[i].LookupParamID == vm.editing.LookupParamID)
                                vm.list[i].IsDefault = false; //set IsDefault = false for current LookupParamID 
                            //if (vm.list[i].LookupValue == vm.editing.LookupValue && vm.list[i].LookupParamID != vm.editing.LookupParamID) {
                            //    vm.duplicateCode = true;
                            //}
                        };

                        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
                        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
                        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Nama ini telah digunakan. Cuba guna mama lain", "error");
                            vm.changesHistory = [];
                        }
                        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
                            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
                            vm.changesHistory = [];
                        }
                        else
                        {
                            var filtered = $filter('filter')(vm.list, { "IsDefault": true }, true);

                            if (filtered.length >= 1) { //if more than 1 default value 
                                swal({
                                    title: "Default value has been set for other value. Are you sure you want to set this as Default value?",
                                    text: "",
                                    type: "warning",
                                    showCancelButton: true,
                                    confirmButtonText: "Yes",
                                    cancelButtonText: "No",
                                    closeOnConfirm: false,
                                    closeOnCancel: false
                                }, function (isConfirm) {
                                    if (isConfirm) {
                                        var model = [];
                                        model.push(filtered[0]);
                                        vm.editing.IsDefault = false;
                                        vm.editing.LookupCode = "CCFromSMS";
                                        vm.editing.ChangeHistory = vm.changesHistory;
                                        model.push(vm.editing);
                                        AdminSI.addDefaultLookupParam(model).then(function (r) {
                                            if (r.status === 200) {
                                                if (r.data) {
                                                    swal({
                                                        title: "Berjaya Kemaskini!",
                                                        type: "success",
                                                        timer: 2500,
                                                        showConfirmButton: false
                                                    }, function () {
                                                        location.reload();
                                                    });
                                                }
                                                else
                                                    swal("Gagal", r.data, "error");
                                            } else
                                                swal("Gagal", r.data, "error");
                                        })
                                    } else {
                                        swal("Batal!", "Permohonan telah dibatalkan.", "error");
                                    }
                                });
                            }
                            else { // If IsDefault = true & length = 0
                                vm.editing.IsDefault = true;
                                AddLookupParam();
                            };
                        }
                    } else { //if false, Save only
                        AddLookupParam();
                    }
                }
            }
            else {
                swal("Gagal!", "Tiada perubahan maklumat dilakukan!", "error");
            }
        } else {
            swal("Gagal!", "Sila isi semua ruangan yang bertanda *", "error");
            vm.showValidationMsg = true;
        }
    }

    vm.deleteJenisPelanggan = function (lookupParamID, IsAktive) {
        vm.editMode = false;
        if (IsAktive) {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: false,
                LookupCode: "CCFromSMS"
            };

            swal({
                title: "Adakah anda pasti mahu deactivate CC From SMS ini?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


                        }
                    });
                }
                else {
                    swal("Batal!", "Permohonan telah dibatalkan.", "error");
                }
            });
        }
        else {
            var model = {
                LookupParamID: lookupParamID,
                IsActive: true,
                LookupCode: "CCFromSMS"
            };

            swal({
                title: "Adakah anda pasti mahu activate CC From SMS ini?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonText: "Yes",
                cancelButtonText: "No",
                closeOnConfirm: false,
                closeOnCancel: false
            }, function (isConfirm) {
                if (isConfirm) {
                    AdminSI.inactiveLookupParam(model).then(function (r) {
                        if (r.status == 200) {
                            swal({
                                title: "Berjaya Kemaskini!",
                                type: "success",
                                timer: 2500,
                                showConfirmButton: false
                            }, function () {
                                location.reload();
                            });


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


    }

    function AddLookupParam() {
        var checkDuplicateName = $filter('filter')(vm.list, { "ParamDesc": vm.editing.ParamDesc }, true);
        var checkDuplicateCode = $filter('filter')(vm.list, { "LookupValue": vm.editing.LookupValue }, true);
        if (checkDuplicateName.length > 0 && checkDuplicateName[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Nama ini telah digunakan. Cuba guna Nama lain", "error");
            vm.changesHistory = [];
        }
        else if (checkDuplicateCode.length > 0 && checkDuplicateCode[0].LookupParamID != vm.editing.LookupParamID) {
            swal("Gagal", "Kod ini telah digunakan. Cuba buat kod baru", "error");
            vm.changesHistory = [];
        }
        else
        {
            model = vm.editing;
            model.LookupCode = "CCFromSMS";
            model.ChangeHistory = vm.changesHistory
            AdminSI.addLookupParam(model).then(function (r) {
                if (r.status === 200) {
                    if (r.data) {
                        swal({
                            title: "Berjaya Kemaskini!",
                            type: "success",
                            timer: 2500,
                            showConfirmButton: false
                        }, function () {
                            location.reload();
                        });
                    }
                    else
                        swal("Gagal", r.data, "error");
                } else
                    swal("Gagal", r.data, "error");
            })
        }
    };

    vm.cancel = function () {
        vm.editMode = false;
        vm.init();
        vm.showValidationMsg = false;
    }

    function getChangeHistory(myForm) {
        angular.forEach(myForm, function (value, key) {
            if (key[0] == '$') return;

            var displayName = $('#' + key).data('displayfield');
            if (key == "IsActive" || key == "IsDefault") {
                value.$pristine = false

            }

            if (value.$pristine == false) {
                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 == 'radio' && (value.$viewValue !== '' || value.$viewValue !== null)) {
                    if (value.$viewValue == true) {
                        newvalue = "Ya";
                    }
                    else {
                        newvalue = "Tidak";
                    }
                }
                else {
                    newvalue = value.$viewValue;
                }

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

});


crmApp.config(function ($routeProvider) {
    $routeProvider

        .when('/JenisPelanggan', {
            templateUrl: '/Admin/Setting/ConfigureJenisPelanggan',
            controller: 'CfgJenisPelanggan'
        })
        .when('/TPFileType', {
            templateUrl: '/Admin/Setting/ConfigureFileType/',
            controller: 'CfgFileType'
        })
        .when('/Kategori', {
            templateUrl: '/Admin/Setting/ConfigureKategori/',
            controller: 'CfgKategori'
        })
        .when('/BahasaPerhubungan', {
            templateUrl: '/Admin/Setting/ConfigureBahasaPerhubungan/',
            controller: 'CfgBahasa'
        })
        .when('/ActChannel', {
            templateUrl: '/Admin/Setting/ConfigureActivitiChannel/',
            controller: 'CfgActChannel'
        })
        .when('/Sumber', {
            templateUrl: '/Admin/Setting/ConfigureSumber/',
            controller: 'CfgSumber'
        })
        .when('/StatusBayaranS104S22', {
            templateUrl: '/Admin/Setting/ConfigureStatusBayaranS104S22/',
            controller: 'CfgStatusBayaranS104S22'
        })
        .when('/JenisKempen/0', {
             templateUrl: '/Admin/Setting/ConfigureJenisKempen/0',
             controller: 'CfgJenisKempen'
        })
        .when('/JenisKempen/1', {
            templateUrl: '/Admin/Setting/ConfigureJenisKempen/1',
            controller: 'CfgJenisKempen'
         })
        .when('/KodSelesai', {
            templateUrl: '/Admin/Setting/ConfigureKodSelesai/',
            controller: 'CfgKodSelesai'
        })
        .when('/Status', {
            templateUrl: '/Admin/Setting/ConfigureStatus/',
            controller: 'CfgStatus'
        })
        .when('/DocList', {
            templateUrl: '/Admin/Setting/ConfigureSenaraiPenerimaanDoc/',
            controller: 'CfgSenaraiPenerimaanDoc'
        })
    
        .when('/CCTemplateName/E', {
            templateUrl: '/Admin/Setting/ConfigureCCTemplateName/E',
            controller: 'CfgCCTemplateName'
        })
        .when('/CCTemplateName/S', {
            templateUrl: '/Admin/Setting/ConfigureCCTemplateName/S',
            controller: 'CfgCCTemplateName'
        })
        .when('/KategoriPenyelesaian', {
            templateUrl: '/Admin/Setting/ConfigureKategoriPenyelesaian/',
            controller: 'CfgKategoriPenyelesaian'
        })
        .when('/CFFKategori', {
            templateUrl: '/Admin/Setting/ConfigureCFFKategori/',
            controller: 'CfgCFFKategori'
        })
        .when('/UnitType', {
            templateUrl: '/Admin/Setting/ConfigureUnitType/',
            controller: 'CfgUnitType'
        })
        .when('/CCCampaign', {
            templateUrl: '/Admin/Setting/ConfigureCCCampaignName/',
            controller: 'CfgCCCampaignName'
        })
        .when('/CCCampaign/HCL', {
            templateUrl: '/Admin/Setting/ConfigureCCCampaignName/HCL',
            controller: 'CfgCCCampaignName'
        })
      .when('/DMStatus', {
          templateUrl: '/Admin/Setting/ConfigureDMStatus/',
          controller: 'CfgDMStatus'
      })
        .when('/ReturnedReason', {
            templateUrl: '/Admin/Setting/ConfigureReturnedReason/',
            controller: 'CfgDMReturnedReason'
        })
        .when('/Tahap', {
            templateUrl: '/Admin/Setting/ConfigureTahap/',
            controller: 'CfgTahap'
        })
       .when('/Parameters', {
           templateUrl: '/Admin/Setting/ConfigureParameters/',
           controller: 'CfgParameters'
       })
        .when('/CCFromEmail', {
            templateUrl: '/Admin/Setting/ConfigureCCFromEmail/',
            controller: 'CfgCCFromEmail'
        })
        .when('/CCFromSMS', {
            templateUrl: '/Admin/Setting/ConfigureCCFromSMS/',
            controller: 'CfgCCFromSMS'
        })
  
});