
var userPermission;
function UserPermission() {
    
    this.permissions = [];
    this.isAddMode = true;
    
    /* ======================= Permission Start ====================== */
    this.displayPermissionList = function displayPermissionList() {

        var maxRowNum = 0;

        for (var index in userPermission.permissions) {
            maxRowNum++;
        }

        if (maxRowNum < 51) {
            maxRowNum = 50;
        }

        $("#permission_grid").jqGrid(
            {
                datatype: "local",
                height: 200,
                colNames: ['SI', lblEmail, 'Name', lblPermission],
                colModel: [
                    {
                        name: 'SI',
                        index: 'SI',
                        width: 0,
                        sorttype: "int",
                        hidden: true
                    },
                    {
                        name: 'Email',
                        index: 'Email',
                        width: 160,
                        align: 'center',
                        editable: true
                    },
                    {
                        name: 'Name',
                        index: 'Name',
                        width: 180,
                        align: 'center',
                        hidden: true,
                        editable: true,
                        edittype: 'text',
                        editrules: { edithidden: true }
                    },
                    {
                        name: 'Permission',
                        index: 'Permission',
                        width: 160,
                        align: 'center',
                        editable: true,
                        edittype: 'select',
                        editoptions: {
                            value: permission_list
                        }
                    }

                ],
                rowNum: maxRowNum,
                rowList: [6, 10, 20, maxRowNum],
                pager: '#permission_pager',
                gridview: true,
                rownumbers: true,
                autoencode: true,
                ignoreCase: true,
                viewrecords: true,
                sortorder: 'desc',
                caption: lblPermissionList
            }
        );


        $("#permission_grid").jqGrid('navGrid', '#permission_pager', {
                add: permitted, addtitle: lblAddPermission,
                edit: permitted, edittitle: lblEditPermission,
                del: (permitted || delete_permitted), deltitle: lblDeletePermission,
                search: false,
                refresh: true
            },
            { // Edit
                recreateForm: true,
                beforeInitData: function () {
                }
            },
            { // Add
                recreateForm: true,
                beforeInitData: function () {
                }
            }

        );

        var data = [];

        $("#permission_grid").jqGrid("clearGridData", true).trigger("reloadGrid");

        for (var index in userPermission.permissions) {
            data.push([userPermission.permissions[index].id,
                userPermission.permissions[index].email,
                userPermission.permissions[index].name,
                userPermission.permissions[index].permission_name
            ]);

        }

        userPermission.setRowsToPermissionGrid(data, true);

    }

    this.setRowsToPermissionGrid = function setRowsToPermissionGrid(data, isAdd) {

        var names = ['SI', 'Email', 'Name','Permission'];
        var mydata = [];
        for (var i = 0; i < data.length; i++) {
            mydata[i] = {};
            for (var j = 0; j < data[i].length; j++) {

                mydata[i][names[j]] = data[i][j];
            }
        }
        if (isAdd == true) {
            for (var i = 0; i < mydata.length; i++) {
                $("#permission_grid").jqGrid('addRowData', data[i][0], mydata[i]);
            }
            //Set the page to the last page
        }
        else {
            $("#permission_grid").jqGrid('setRowData', data[0][0], mydata[0]);
        }
    }

    this.setPermissionGridExtension = function setPermissionGridExtension() {
        $.extend($.jgrid.edit, {
            addCaption: lblAddPermission,
            editCaption: lblEditPermission,
            bSubmit: lblSave,
            bCancel: lblCancel,
            width: 300,
            recreateForm: true,
            beforeShowForm: function (form, postData) {
                var rowId = $("#permission_grid").jqGrid('getGridParam', 'selrow');
                var isChecked = $('#restrictedMode').prop('checked');
                if(!isChecked){
                    alert(lblEnableRestrictionPermission);
                    $.jgrid.hideModal("#FrmGrid_permission_grid");
                }
                if(rowId !=null && rowId>=0 && postData == 'edit') {
                    var rowData = userPermission.permissions[rowId];
                    $('#Name', form).prop('readonly', true);
                    $('#Email', form).prop('readonly', true);
                    $('#Email', form).css('background-color', '#ccc');
                    $('#Name', form).css('background-color', '#ccc');
                    if (rowData.permission == owner) {
                        alert(lblErrorEditPermission);
                        $.jgrid.hideModal("#FrmGrid_permission_grid");
                    }
                }

            },

            beforeSubmit: function (response, postData) {
                var isEdit = response.permission_grid_id;
                var skipPartId = isEdit>0 ? isEdit : -1;
                var operation_type = skipPartId>0 ? OPERATION_TYPE.EDIT : OPERATION_TYPE.ADD;
                var name = $('#Name').val();
                var email =	$('#Email').val();
                var permission = $('#Permission').val();
                var message = userPermission.validPermissionInputForm(name,email,permission,skipPartId);

                if (message !== "") {
                    userPermission.showErrorMessage(message);
                }
                else {
                    userPermission.clearErrorMessage();
                    userPermission.savePermissionData(response.permission_grid_id,name,email,permission,operation_type);
                    $(".ui-icon-closethick").trigger('click');
                }

            }

        });

        $.extend($.jgrid.del, {

            caption: lblDeletePermission,
            msg: lblDeleteMessagePermission,
            beforeShowForm: function () {
                var rowId = $("#permission_grid").jqGrid('getGridParam', 'selrow');
                var rowData = userPermission.permissions[rowId];
                var isChecked = $('#restrictedMode').prop('checked');
                var message = lblNotDeleteMessagePermission;
                if(session_profile_id != rowData.email && delete_permitted){
                    alert(message);
                    setTimeout(function () {
                        $.jgrid.hideModal("#delmodpermission_grid");
                    }, 5);
                    return false;
                }
                else if (rowData.permission == owner || Object.keys(userPermission.permissions).length == 1) {
                    if(!isChecked){
                        message = lblEnableRestrictionPermission;
                    }
                    alert(message);
                    setTimeout(function () {
                        $.jgrid.hideModal("#delmodpermission_grid");
                    }, 5);
                    return false;
                }
                else {
                    $.jgrid.viewModal("#delmodpermission_grid");
                }

            },
            beforeSubmit: function (response, postData) {
                var id = response.permission_grid_id;
                userPermission.deletePermission(id);
            }

        });

    }

    this.validPermissionInputForm = function validPermissionInputForm(name,email,permission, skipPartId) {

        var errorMessage = "";

        errorMessage = validateEmail(email);

        if (!permission.trim()) {
            errorMessage = lblSelectPermission;
        }
        if (errorMessage === "") {
            //check the permission name already exist or not
            for (var index in userPermission.permissions) {
                if (skipPartId != userPermission.permissions[index].id) {
                    if (userPermission.permissions[index].email.toLowerCase() == email.trim().toLowerCase()) {
                        errorMessage = lblEmailExistMessage;
                        break;
                    }
                }
            }
        }

        return errorMessage;

    }

    this.savePermissionData = function savePermissionData(id,name,email,permission,operation_type) {
        var permissionObj = new Permission({
            id : id>0 ? id :userPermission.getPermissionId(),
            name : name,
            email : email,
            permission : permission,
            permission_name: permission_list[permission],
            expense_id : dashBoard.expense.id,
            operation_type : operation_type
        });

        sendToServer(permissionObj, "#permissionForm",function(success, response) {
            if (response.status) {
                dashBoard.expense.version = parseInt(dashBoard.expense.version) + 1;
                $("#ExpenseVersion").val(dashBoard.expense.version);
                userPermission.permissions[permissionObj.id] = permissionObj;
                var data = [];
                //go to the last page after adding record
                data.push([permissionObj.id, permissionObj.email, permissionObj.name, permission_list[permissionObj.permission],
                    permissionObj.expense_id,
                    permissionObj.operation_type]);
                if(id>0) {
                    userPermission.setRowsToPermissionGrid(data, false);
                }
                else {
                    userPermission.setRowsToPermissionGrid(data, true);
                }
                userPermission.setPermissionGridExtension();
                userPermission.setPageAfterAdd('#permission_grid');
            }
            else {
                alert(lblErrorSavingMessage+' '+ response.message);
            }
        });

    }

    this.deletePermission = function deletePermission(index) {
        var rowId = $("#permission_grid").jqGrid('getGridParam', 'selrow');
        var rowData = userPermission.permissions[rowId];
        //prepare delete object
        var permissionObj = new Permission({
            id : rowData.id,
            name : rowData.name,
            email : rowData.email,
            permission : rowData.permission,
            expense_id : dashBoard.expense.id,
            operation_type : OPERATION_TYPE.DELETE
        });

        sendToServer(permissionObj, "#permissionForm",function(success, response) {
            if (response.status) {
                dashBoard.expense.version = parseInt(dashBoard.expense.version) + 1;
                $("#ExpenseVersion").val(dashBoard.expense.version);
                if(rowId === session_user_id){
                    location.reload(true);
                }
                $('#permission_grid').jqGrid('delRowData', rowId);
                delete userPermission.permissions[permissionObj.id];
                userPermission.setPermissionGridExtension();
                userPermission.setPageAfterDelete('#permission_grid');
            }
            else {
                alert(lblErrorSavingMessage+' '+ response.message);
            }
            $(".ui-icon-closethick").trigger('click');
        });
    }

    this.getPermissionId = function getPermissionId() {
        var maxId = 0;

        for (var index in userPermission.permissions) {
            var idNum = index;
            if (idNum > maxId) {
                maxId = idNum;
            }
        }
        maxId++;

        return maxId;
    }

    this.showErrorMessage = function showErrorMessage(msg) {
        $("#FormError").show();
        $(".ui-state-error").html(msg);
    }

    this.clearErrorMessage = function clearErrorMessage() {
        $("#FormError").hide();
        $(".ui-state-error").html("");
    }

    this.setPageAfterAdd = function setPageAfterAdd(grid_id) {
        if (userPermission.isAddMode == true) {
            var lastPage = $(grid_id).getGridParam('lastpage');
            var totalRecords = $(grid_id).getGridParam('records');
            var rowNum = $(grid_id).getGridParam('rowNum');

            if (totalRecords > (rowNum * lastPage)) {
                lastPage++;
            }

            $(grid_id).setGridParam({ page: lastPage });
            $(grid_id).trigger("reloadGrid");
        }
    }

    this.setPageAfterDelete = function setPageAfterDelete(grid_id) {

        var currentPage = $(grid_id).getGridParam('page');
        var rowCount = $(grid_id).getGridParam('reccount');
        var rowNum = $(grid_id).getGridParam('rowNum');

        if (rowCount == 0 && currentPage > 1) {
            currentPage = currentPage - 1;
            $(grid_id).setGridParam({ page: currentPage });

        }
        $(grid_id).trigger("reloadGrid");

    }


    /* ======================= Permission End ====================== */

}