$(document).ready(function () {
    var menulist = JSON.parse(localStorage.getItem("menulist"));
    if (menulist == null) {
        MsgBox("Session Close Please Login !!!.");
        window.location.href = "/Login/Index";
        return;
    }
    //  NotificationSuccess(tempsession);
    var menudata = menulist.filter(obj => obj.PageName == "Transaction Password");
    if (menudata != null && menudata.length != 0) {
    var pageview = menudata[0].View;
    var pageadd = menudata[0].Add;
    var pageedit = menudata[0].Edit;
        var pagedelete = menudata[0].Delete;
    }
    else {
        MsgBox("Page Access Permission Denied !!!.");
        setTimeout(function () {
            window.location.href = "/Login/Home";
        }, 3000);

        return;
    }
    if (menudata[0].View == 0) {
        MsgBox("Page Access Permission Denied !!!.");
        setTimeout(function () {
            window.location.href = "/Login/Home";
        }, 3000);

        return;
    }

    $("#jqxLoader").jqxLoader({ width: 100, height: 60, imagePosition: 'top' });


    $("#txtEditpassword").jqxPasswordInput({ width: 70, height: 15 });
    $("#txtEditpassword").bind('keydown', function (event) {
        var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
        if (key == '13') {
            if ($("#txtEditpassword").val() != "" && $("#txtEditpassword").val() != null) {
                var type = "";
                if (PasswordType == 1) {
                    type = "EditPassword";
                }
                else if (PasswordType == 0) {
                    type = "FormConfig";
                }
                else if (PasswordType == 2) {
                    type = "AdminPower";
                }
                $.ajax({
                    async: false,
                    url: "/Master/EditPassword",
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    data: '{"password":"' + $("#txtEditpassword").val() + '","type":"' + type + '"}',
                    //data: datavalue,
                    success: function (data) {
                        if (data.ok == true) {
                            $('#LockEditWindow').jqxWindow('Close');
                        }
                        else {
                            alert("Invaild Password !!!.");
                        }
                    },
                    error: function (error) {
                        MsgBox('Technical Fault Contact Software Vendor  !!!.');
                    }
                });
            }
        }
    });
    var PasswordType = 0;
    function EditPasswordWindow(type) {
        var titlenew = "";
        if (type == 1) {
            titlenew = "Edit Pwd";
        }
        else if (type == 0) {
            titlenew = "Form Pwd";
        }
        else if (type == 2) {
            titlenew = "Admin Pwd";
        }
        let centerX = (screen.width - 450) / 2;
        let centerY = (screen.height - 450) / 2;

        $('#LockEditWindow').jqxWindow({
            position: { x: centerX, y: centerY },
            showCollapseButton: false,
            showCloseButton: false, 
            height: 150,
            width: 120,
            title: titlenew,
            isModal: true,
            keyboardCloseKey: 0,
            resizable: false,
            initContent: function () {
            }
        });
        $('#LockEditWindow').jqxWindow('Open');
        setTimeout(function () {
            $('#txtEditpassword').val('');
            $("#txtEditpassword").focus();
        }, 250);

    }
    $('#LockEditWindow').on('close', function (event) {

        setTimeout(function () {
            methods.loadTransactionpassword();
        }, 250);

    }); 

    var gridTransactionpw = $("#grid");

    var Widthdatacolumns = []; //Array for widthdatacolumns

    //region gridcolumnname
    var grdUserName = "UserName";
    var grdPassword = "Password";
    var grdId = "Id";
    var grdEditMode = "EditMode";
    //endregion

    //TotalWidthSetting
    var totalwidth = 10;
    var WindowWidthFull = screen.width - percentage(screen.width, 15);
    var WindowHeightFull = screen.height - percentage(screen.height, 15);
    var WindowWidth = screen.width - percentage(screen.width, 15);
    var WindowHeight = $(this).height() - 200;
    var gridHeight = WindowHeight - 65;
    //End
    var gridcolumns = [
                               {
                                   text: 'S.No', sortable: false, filterable: false, editable: false,
                                   groupable: false, draggable: false, resizable: false, hidden: false, pinned: true,
                                   datafield: '', columntype: 'number', width: 50,
                                   cellsrenderer: function (row, column, value) {
                                       return "<div style='margin:4px;'>" + (value + 1) + "</div>";
                                   }
                               },
                             { text: 'Transaction Name', datafield: grdUserName, width: 150, hidden: false, pinned: true, editable: false },
                             { text: 'Password', datafield: grdPassword, width: 100},
                             { text: 'Id', datafield: grdId, width: 100, hidden: true },
    ]

    //Window Width Calculation for F10 Disabled Options
    for (var i = 0; i < gridcolumns.length; i++) {
        if (gridcolumns[i].text != "Id") {
            totalwidth = totalwidth + gridcolumns[i].width;
        }
    }
    gridTransactionpw.bind('keypress', function (event) {
        var e = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
        if (e == '13') {
            return;
        }
        var cell = gridTransactionpw.jqxGrid('getselectedcell');
        var rowindex = cell.rowindex;
        var columnname = cell.datafield;
        if ( columnname == grdPassword) {
            GridKeyPressValidation(gridTransactionpw, event, 50, "string", 2);
        }
    });
    gridTransactionpw.on("celldoubleclick", function (event) {
        var cell = gridTransactionpw.jqxGrid('getselectedcell');
        var rowindex = cell.rowindex;
        var columnname = cell.datafield;
        if (columnname == grdPassword) {
            gridTransactionpw.jqxGrid({ editmode: 'selectedcell' });
        }

    });

    gridTransactionpw.on('cellselect', function (event) {
        var cell = gridTransactionpw.jqxGrid('getselectedcell');
        var rowindex = cell.rowindex;
        var columnname = cell.datafield;
        

    });

    gridTransactionpw.on('cellendedit', function (event) {
        gridTransactionpw.jqxGrid({ editmode: 'programmatic' });
    });



    gridTransactionpw.bind('keydown', function (event) {
        var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
        if (key == '8') {
            gridTransactionpw.trigger('keypress');
        }

    });


    gridTransactionpw.bind('keydown', function (event) {
        var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
        if (key == '8') {
            gridArea.trigger('keypress');
        }
        if (key == '13') {
            var cell = gridTransactionpw.jqxGrid('getselectedcell');
            var gridcount = gridTransactionpw.jqxGrid('getrows');
            var rowcount = gridcount.length;
            rowindexc = cell.rowindex;
            var columnname = cell.datafield;
            var columnindex = gridTransactionpw.jqxGrid('getcolumnindex', cell.datafield);

            var editable = gridTransactionpw.jqxGrid('endcelledit', rowindexc, cell.datafield, false);
            var value = gridTransactionpw.jqxGrid('getcellvalue', rowindexc, cell.datafield);
          
            gridTransactionpw.jqxGrid('selectcell', rowindexc + 1, grdPassword);
            gridTransactionpw.jqxGrid('focus');
        }
    });

    $(document).on('keydown', function (e) {
        //F1 Press
            if (e.keyCode === 112) {
                e.preventDefault();
                var flag = 1;
                if (methods.gridemptycheck() == false)
                    return;

                if (pageadd == 0 &&  pageedit == 0) {
                    MsgBox("Page Add & Update Permission Denied !!!.");
                    flag = 0;
                }
                if (methods.gridemptycheck() == false)
                    return;
                var griddata = gridTransactionpw.jqxGrid('getrows');
                var getdata;
                if (pageadd == 1 && pageedit == 1) {
                    getdata = griddata.filter(obj => obj.EditMode == 1);
                    if (getdata.length == 0) {
                      
                    }
                }
                else if (pageadd == 1 && pageedit == 0) {
                    getdata = griddata.filter(obj => obj.EditMode == 1 && obj.Id == null);
                    if (getdata.length == 0) {
                        var tempdata = griddata.filter(obj => obj.EditMode == 1);
                        if (tempdata.length == 0) {
                          
                        }
                        else {
                            MsgBox("Page Edit Permission Denied !!!.");
                            flag = 0;
                        }
                    }
                }
                else if (pageedit == 1 && pageadd ==0) {
                    getdata = griddata.filter(obj => obj.EditMode == 1 && obj.Id != null);
                    if (getdata.length == 0) {
                        var tempdata = griddata.filter(obj => obj.EditMode == 1);
                        if (tempdata.length == 0) {
                          
                        }
                        else {
                            MsgBox("Page Add Permission Denied !!!.");
                            flag = 0;
                        }
                    }
                }
                if (flag == 0)
                {
                  //  methods.Addrowfunc();
                }

                if (flag == 0)
                    return;

            var griddata = gridTransactionpw.jqxGrid('getrows');

            var str = 'Do you Want to Save the Transaction Password Details?'
            MsgBoxYesNo(str).then(function (reply) { if (reply == "Yes") {
                $('#jqxLoader').jqxLoader('open');
                $.ajax({
                    url: "/Master/UpdateTransactionPassword",
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(griddata),
                    success: function (data) {
                        if (data.ok) {
                            $('#jqxLoader').jqxLoader('close');
                            NotificationSuccess(data.message);
                            methods.loadTransactionpassword();
                        }
                        else {
                            $('#jqxLoader').jqxLoader('close');
                            MsgBox(data.message);
                        }
                    },
                    error: function (error) {
                        $('#jqxLoader').jqxLoader('close');
                        var str = data.errors;
                        MsgBox('Technical Fault Contact Software Vendor  !!!.');
                    }
                }).done(function () {
                });
            }
            else {
                methods.Addrowfunc();
            }
            });
        }
        //Esc Press
        if (e.keyCode === 27) {
            e.preventDefault();
            if ($("#LockEditWindow").jqxWindow('isOpen') == false) {
                var str = 'Do You Want To Quit Page?'
                MsgBoxYesNo(str).then(function (reply) {
                    if (reply == "Yes") {
                        window.location.href = "/Login/Home";
                    }
                });
            }
        }
    });

    methods = (function () {
        return {
            init: function () {
                methods.createElements();
                PasswordType = 1;
                EditPasswordWindow(1);
            },

            createElements: function () {
                if (totalwidth > WindowWidth) {
                    totalwidth = WindowWidth;
                }

                var jqxWidget = $('#jqxWidget');
                var offset = jqxWidget.offset();
                $('#windowmain').jqxWindow({
                    resizable: false,
                    minWidth: 200,
                    minHeight: 200,
                    width: totalwidth,
                    keyboardCloseKey: 0,
                    maxWidth: WindowWidthFull,
                    maxHeight: WindowHeightFull,
                    height: WindowHeight,
                    zIndex: 50
                });
                $('#windowmain').jqxWindow('focus');
                //$("#jqxWidget").css('visibility', 'visible');
            },
            Escape: function () {
                window.open("/Login/Home", "_self");
            },

            //Grid Empty Check
            gridemptycheck: function () {
                var griddata = gridTransactionpw.jqxGrid('getrows');
                var rowcount = griddata.length;
                if (gridTransactionpw.jqxGrid('getcellvalue', rowcount - 1, grdUserName) == "" || gridTransactionpw.jqxGrid('getcellvalue', rowcount - 1, grdUserName == null)) {
                    if (rowcount > 1) {
                        var id = gridTransactionpw.jqxGrid('getrowid', rowcount - 1);
                        gridTransactionpw.jqxGrid('deleterow', id);
                    }
                }
                griddata = gridTransactionpw.jqxGrid('getrows');
                rowcount = griddata.length;
                for (var i = 0; i <= griddata.length - 1; i++) {
                    if (griddata[i].EditMode == 1) {
                        if (griddata[i].Password == "" || griddata[i].Password == null) {
                            MsgBox("Enter All Password in the Grid !!!.");
                            gridTransactionpw.jqxGrid('selectcell', i, grdPassword);
                            gridTransactionpw.jqxGrid('focus');
                            return false;
                        }
                    }
                }
                return true;
            },

            Addrowfunc: function () {
                //addrow(gridTransactionpw);
                //var rowscount = gridTransactionpw.jqxGrid('getdatainformation').rowscount;
                //gridTransactionpw.jqxGrid('selectcell', rowscount - 1, grdPassword);
                //gridTransactionpw.jqxGrid('focus');
            },

            loadTransactionpassword: function () {
                $('#jqxLoader').jqxLoader('open');
                var objcounter = {};
                $.ajax({
                    url: "/Master/SelectTransactionPasswordList",
                    type: "POST",
                    dataType: "json",
                    cache :false,
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(objcounter),
                    success: function (data) {
      var source =
          {
              localdata: data,
              datatype: "local",
              datafields:
              [
                  { name: grdId, type: 'number' },
                  { name: grdUserName, type: 'string' },
                  { name: grdPassword, type: 'string' },
                  { name: grdEditMode, type: 'number' },
              ],
              addrow: function (rowid, rowdata, position, commit) {
                  commit(true);
                  AutoScroll(gridTransactionpw, rowid);
              },
              deleterow: function (rowid, commit) {
                  commit(true);
              },
              updaterow: function (rowid, newdata, commit) {
                  newdata.EditMode = 1;
                  commit(true);
              }
          };
                        var dataAdapter = new $.jqx.dataAdapter(source);
                        //WidthDataColumns
                        Widthdatacolumns = gridcolumns.filter(obj => obj.pinned == false);
                        Widthdatacolumns = Widthdatacolumns.filter(obj => obj.hidden == false);

                        gridTransactionpw.jqxGrid(
                        {
                                width: '100%',
                                height: gridHeight,
                            editable: true,
                            theme: 'classic',
                            showaggregates: true,
                            editmode: 'programmatic',
                            keyboardnavigation: true,
                            selectionmode: 'singlecell',
                            source: dataAdapter,
                            columnsresize: true,
                            enablekeyboarddelete: false,
                            columns: [
                                {
                                    text: 'S.No', sortable: false, filterable: false, editable: false,
                                    groupable: false, draggable: false, resizable: false,
                                    datafield: '', columntype: 'number', width: 50,
                                    cellsrenderer: function (row, column, value) {
                                        return "<div style='margin:4px;'>" + (value + 1) + "</div>";
                                    }
                                }

                            ]
                        });
                        $('#jqxLoader').jqxLoader('close');
                        gridTransactionpw.jqxGrid("render");
                        gridTransactionpw.jqxGrid({ columns: gridcolumns });
                     //   addrow(gridTransactionpw);
                        var objlistnew = gridTransactionpw.jqxGrid('getrows');
                        gridTransactionpw.jqxGrid('selectcell', 0, grdPassword);
                        gridTransactionpw.jqxGrid('focus');
                    },
                    error: function (msg, url, line) {
                        MsgBox('Technical Fault Contact Software Vendor  !!!.');
                    }
                }).done(function () {
                    $('#ajax_load').css('display', 'none');
                    $('body,html').animate({ scrollTop: 10 }, 1000);
                });
            },
        };

    })();
    window.methods = methods;
    methods.init();
});
