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

    var gridCardMaster = $("#grid");
    var Widthdatacolumns = []; //Array for widthdatacolumns

    //TotalWidthSetting
    var totalwidth = 100;
    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() - 180;
    var gridHeight = WindowHeight - 65;
    //End
    //region gridcolumnname
    var grdMahalName = "MahalName";

    var grdActive = "Active";
    var grdId = "Id";
    var grdEditMode = "EditMode";
    var cellclass = function (row, datafield, value, rowdata) {
        if (rowdata.Active == 0) {
            return "editedRow";
        }

    }
    var gridcolumns = [
        {
            text: 'S.No', sortable: false, filterable: false, editable: false, cellclassname: cellclass,
            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: 'Mahal Name', datafield: grdMahalName, width: 270, hidden: false, pinned: true, cellsalign: 'left', cellclassname: cellclass },
        { text: 'Active', datafield: grdActive, width: 90, threestatecheckbox: false, cellclassname: cellclass, columntype: 'checkbox', pinned: true, hidden: true, },
        { text: 'Id', datafield: grdId, width: 100, hidden: true, pinned: false, cellclassname: cellclass },

    ]
    //endregion

    gridCardMaster.bind('keypress', function (event) {
        var e = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
        if (e == '13') {
            return;
        }
        var cell = gridCardMaster.jqxGrid('getselectedcell');
        var rowindex = cell.rowindex;
        var columnname = cell.datafield;
        if (columnname == grdMahalName) {
            GridKeyPressValidation(gridCardMaster, event, 50, "string", 2);
        }


    });





    gridCardMaster.on('cellendedit', function (event) {
        gridCardMaster.jqxGrid({ editmode: 'programmatic' });
    });
    gridCardMaster.bind('keydown', function (event) {
        var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
        if (key == '8') {
            gridCardMaster.trigger('keypress');
        }
        if (key == '13') {
            var cell = gridCardMaster.jqxGrid('getselectedcell');
            var gridcount = gridCardMaster.jqxGrid('getrows');
            var rowcount = gridcount.length;
            var rowindex = cell.rowindex;
            var columnname = cell.datafield;
            var columnindex = gridCardMaster.jqxGrid('getcolumnindex', cell.datafield);
            var rowscount = gridCardMaster.jqxGrid('getdatainformation').rowscount;
            var editable = gridCardMaster.jqxGrid('endcelledit', rowindex, cell.datafield, false);
            var value = gridCardMaster.jqxGrid('getcellvalue', rowindex, cell.datafield);
            if (columnname == grdMahalName) {
                if (value == null || value == "") {
                    MsgBox("Enter Card Name !!!.");

                    return;
                }
                if (CheckDuplicate(gridCardMaster, grdMahalName, "Mahal Name") == true) {
                    if (rowscount - 1 == rowindex) {
                        addrow(gridCardMaster);
                        gridCardMaster.jqxGrid('selectcell', rowscount, grdMahalName);
                        gridCardMaster.jqxGrid('focus');
                    }
                    else {

                        gridCardMaster.jqxGrid('selectcell', rowscount - 1, grdMahalName);
                        gridCardMaster.jqxGrid('focus');

                    }
                }
            }
            else if (columnname == grdActive) {

                if (rowscount - 1 == rowindex) {
                    addrow(gridCardMaster);
                    gridCardMaster.jqxGrid('selectcell', rowscount, grdMahalName);
                    gridCardMaster.jqxGrid('focus');
                }
                else {

                    gridCardMaster.jqxGrid('selectcell', rowscount - 1, grdMahalName);
                    gridCardMaster.jqxGrid('focus');

                }

            }

            else {

            }
        }
        else if (key === 46) {
            var cell = gridCardMaster.jqxGrid('getselectedcell');
            var gridcount = gridCardMaster.jqxGrid('getrows');
            var rowcount = gridcount.length;
            var rowindex = cell.rowindex;
            var columnname = cell.datafield;
            var columnindex = gridCardMaster.jqxGrid('getcolumnindex', cell.datafield);
            var value = gridCardMaster.jqxGrid('getcellvalue', rowindex, grdId);
            if (value != 0 && value != null) {
                document.getElementById("windowmain").style.zIndex = "50";
                var str = "Wish to Delete the Record " + gridCardMaster.jqxGrid('getcellvalue', rowindex, grdMahalName) + "?";
                MsgBoxYesNo(str).then(function (reply) {
                    if (reply == "Yes") {
                        $('#jqxLoader').jqxLoader('open');
                        $.ajax({
                            url: "/Master/DeleteMahalMaster",
                            type: "POST",
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",
                            data: '{"Id":' + value + '}',
                            success: function (data) {
                                if (data.ok) {
                                    $('#jqxLoader').jqxLoader('close');
                                    NotificationSuccess(data.message);
                                    DeleteRow(gridCardMaster, rowindex, columnindex, grdId, rowcount, 0);
                                    setTimeout(function () {
                                        var rowscount = gridCardMaster.jqxGrid('getdatainformation').rowscount;
                                        gridCardMaster.jqxGrid('selectcell', rowscount - 1, grdMahalName);
                                        gridCardMaster.jqxGrid('focus');
                                    }, 50);
                                }
                                else {
                                    $('#jqxLoader').jqxLoader('close');
                                    MsgBox(data.message);
                                }

                            },
                            error: function (error) {
                                $('#jqxLoader').jqxLoader('close');
                                MsgBox('Technical Fault Contact Software Vendor  !!!.');
                            }
                        });


                    }
                });


            }
            else {

                DeleteRow(gridCardMaster, rowindex, columnindex, grdMahalName, rowcount, 1);
                var rowscount = gridCardMaster.jqxGrid('getdatainformation').rowscount;
                gridCardMaster.jqxGrid('selectcell', rowscount - 1, grdMahalName);
                gridCardMaster.jqxGrid('focus');
            }
        }

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


            var griddata = gridCardMaster.jqxGrid('getrows');
            var getdata;
            getdata = griddata.filter(obj => obj.EditMode == 1);
            document.getElementById("windowmain").style.zIndex = "50";
            var str = 'Do you Want to Save the MahalName Details?'
            MsgBoxYesNo(str).then(function (reply) {
                if (reply == "Yes") {
                    $('#jqxLoader').jqxLoader('open');
                    $.ajax({
                        url: "/Master/InsertMahalMaster",
                        type: "POST",
                        dataType: "json",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify(getdata),
                        success: function (data) {
                            if (data.ok) {
                                $('#jqxLoader').jqxLoader('close');
                                NotificationSuccess(data.message);
                                methods.loadCustomer();

                            }
                            else {
                                $('#jqxLoader').jqxLoader('close');

                                MsgBox(data.message);
                            }

                        },
                        error: function (error) {
                            $('#jqxLoader').jqxLoader('close');
                            MsgBox('Technical Fault Contact Software Vendor  !!!.');
                        }
                    }).done(function () {
                    });
                }
            });
        }
        //F2 Press
        if (e.keyCode === 113) {
            e.preventDefault();

        }
        //Esc Press
        if (e.keyCode === 27) {
            e.preventDefault();
            document.getElementById("windowmain").style.zIndex = "50";
            var str = 'Do You Want To Quit Page?'
            MsgBoxYesNo(str).then(function (reply) {
                if (reply == "Yes") {

                    window.location.href = "/Login/Home";

                }
            });
        }
        //F12
        if (e.keyCode === 123) {

        }
    });
    methods = (function () {
        return {
            init: function () {
                methods.addEventListeners();
                methods.createElements();
                $("#jqxWidget").css('visibility', 'visible');
                methods.loadCustomer();
            },
            addEventListeners: function () {
                $('#showWindowButton').mousedown(function () {
                    $('#windowmain').jqxWindow('open');
                    $('#windowmain').jqxWindow('focus');
                });
            },
            createElements: function () {
                if (totalwidth > WindowWidth) {
                    totalwidth = WindowWidth;
                }

                var jqxWidget = $('#jqxWidget');
                var offset = jqxWidget.offset();
                $('#windowmain').jqxWindow({

                    resizable: false,
                    minWidth: 200,
                    minHeight: 200,
                    width: 350,
                    keyboardCloseKey: 0,
                    maxWidth: WindowWidthFull,
                    maxHeight: WindowHeightFull,
                    height: WindowHeight,
                    zIndex: 50

                });
                $('#windowmain').jqxWindow('focus');

                $("#jqxWidget").css('visibility', 'visible');
            },

            Addrowfunc: function () {
                addrow(gridCardMaster);
                var rowscount = gridCardMaster.jqxGrid('getdatainformation').rowscount;
                gridCardMaster.jqxGrid('selectcell', rowscount - 1, grdMahalName);
                gridCardMaster.jqxGrid('focus');
            },
            gridemptycheck: function () {
                var griddata = gridCardMaster.jqxGrid('getrows');
                var rowcount = griddata.length;
                if (gridCardMaster.jqxGrid('getcellvalue', rowcount - 1, grdMahalName) == "" || gridCardMaster.jqxGrid('getcellvalue', rowcount - 1, grdMahalName) == null) {
                    if (rowcount > 1) {
                        var id = gridCardMaster.jqxGrid('getrowid', rowcount - 1);
                        gridCardMaster.jqxGrid('deleterow', id);
                    }
                }
                griddata = gridCardMaster.jqxGrid('getrows');
                rowcount = griddata.length;
                for (var i = 0; i <= griddata.length - 1; i++) {
                    if (griddata[i].EditMode == 1) {

                        if (griddata[i].MahalName == "" || griddata[i].MahalName == null) {
                            MsgBox("Enter All AccountName in the Grid !!!.");
                            gridCardMaster.jqxGrid('selectcell', i, grdMahalName);
                            gridCardMaster.jqxGrid('focus');
                            return false;
                        }
                        
                    }
                }
                return true;
            },
            loadCustomer: function () {
                $('#jqxLoader').jqxLoader('open');
                var objcounter = {};
                var getdata = {};
                $.ajax({
                    async: false,
                    url: "/Master/SelectMahalMaster",
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(objcounter),
                    success: function (data) {

                        getdata = data;


                    },
                    error: function (error) {
                        $('#jqxLoader').jqxLoader('close');
                        MsgBox('Technical Fault Contact Software Vendor  !!!.');
                    }

                }).done(function () {
                    $('#ajax_load').css('display', 'none');
                    $('body,html').animate({ scrollTop: 10 }, 1000);
                });

                var source =
                {
                    localdata: getdata,
                    datatype: "local",
                    datafields:
                        [
                            { name: grdId, type: 'number' },
                            { name: grdMahalName, type: 'string' },
                            { name: grdActive, type: 'bool' },
                            { name: grdEditMode, type: 'string' },


                        ],
                    addrow: function (rowid, rowdata, position, commit) {

                        commit(true);

                        gridCardMaster.jqxGrid('setcellvalue', rowdata.boundindex, grdActive, true);
                        rowidnew = rowid;
                        AutoScroll(gridBrand, rowid);

                    },
                    deleterow: function (rowid, commit) {
                        commit(true);
                        AutoScroll(gridBrand, rowid);
                    },
                    updaterow: function (rowid, newdata, commit) {
                        newdata.EditMode = 1;
                        commit(true);
                    }
                };
                //WidthDataColumns

                var dataAdapter = new $.jqx.dataAdapter(source);

                gridCardMaster.jqxGrid(
                    {
                        width: '100%',
                        height: gridHeight,
                        editable: true,
                        theme: 'classic',
                        showaggregates: true,
                        editmode: 'programmatic',
                        keyboardnavigation: true,
                        enablekeyboarddelete: false,
                        rowsheight: 25,
                        columnsheight: 25,
                        selectionmode: 'singlecell',
                        source: dataAdapter,
                        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');
                gridCardMaster.jqxGrid("render");
                gridCardMaster.jqxGrid({ columns: gridcolumns });
                addrow(gridCardMaster);
                var rowscount = gridCardMaster.jqxGrid('getdatainformation').rowscount;
                gridCardMaster.jqxGrid('selectcell', rowscount - 1, grdMahalName);
                gridCardMaster.jqxGrid('focus');
            },
        }
    })();
    window.methods = methods;
    methods.init();
});