
// selected items
var writers = {};
var IsShowActive = true;
var agIsShowActive = true;
var uwdataSource;
var agentDataSource;

$(document).ready(function () {

  
   
    BuildGrid();

    $("#multiselect").kendoMultiSelect({
        dataTextField: "text",
        dataValueField: "value",
        change: function (e) {
            var previous = this._savedOld;
            // These are current values.
            var current = this.value();
            // Let's save it for the next time
            saveCurrent(this);

            // The difference between previous and current are removed elements
            var diff = $(previous).not(current).get();
            // get currently applied filters from the Grid.

            var uwdatasourceFilters = $("#writergrid").data("kendoGrid").dataSource;
            var uwfilters = uwdatasourceFilters.filter();

            // get current set of filters, which is supposed to be array.
            // if the object uwfilterswe obtained above is null/undefined, set this to an empty array
            var currentFilters = uwfilters ? uwfilters.filters : [];

            if (uwfilters == null) {
                // finally, the currentFilters array is applied back to the Grid, using "and" logic.
                $("#writergrid").data("kendoGrid").dataSource.filter({
                    logic: "and",
                    filters: currentFilters
                });

                uwfilters = $("#writergrid").data("kendoGrid").dataSource.filter();
            }

            //To Show Inactive


            for (i = 0; i < uwdatasourceFilters.filter().filters.slice().length; i++) {
                if (uwdatasourceFilters.filter().filters[i].field == diff) {
                    uwfilters.filters.splice(i, 1); //Remove IsActive Filter from its Position in Filters List
                }
            }
            uwdatasourceFilters.filter(uwfilters)

            if (diff == "IsActive") {
                IsShowActive = false;
                var isActiveButton = $("#writergrid .k-grid-ShowInactive")[0];
                isActiveButton.textContent = "Hide Inactive";
            }

        } //end of change Event


    });
});

function saveCurrent(multi) {
    multi._savedOld = multi.value().slice(0);
    }

function BuildGrid() {

    var crudServiceBaseUrl = "http://localhost:63213/api/WebApi",
                        uwdataSource = new kendo.data.DataSource({
                            transport: {
                                read: {
                                    url: crudServiceBaseUrl + "/GetwriterData"//,
                                },
                                create: {
                                    url: crudServiceBaseUrl + "/POSTAddWriterData",
                                    type: "POST",
                                    contentType: "application/json"
                                },
                                update: {
                                    url: crudServiceBaseUrl + "/UpdateWriterData",
                                    type: "POST",
                                    contentType: "application/json"
                                },                                
                                parameterMap: function (options, operation) {                                    
                                    if (operation != "read") {
                                        return kendo.stringify(options);
                                    }
                                }
                            },
                            batch: false,
                            pageSize: 15,
                            serverPaging: false,
                            serverFiltering: false,
                            serverSorting: false,
                            schema: {
                                model: {
                                    id: "writerID",
                                    code: "code",
                                    Name: "Name",
                                    Agents: "Agents",
                                    fields: {
                                        writerID: { type: "string" },
                                        Code: { type: "string", validation: { required: true} },
                                        Name: { type: "string", validation: { required: true} },
                                        IsActive: { type: "boolean" },
                                        Agents: { type: "list"}
                                    }
                                }
                            },
                            filter: {
                                "field": "IsActive",
                                "operator": "IsEqualTo",
                                "value": true
                            }
                        });

                        $("#writergrid").kendoGrid({
                            dataSource: uwdataSource,
                            pageable: true,
                            height: 685,
                            filterable: { extra: false },
                            sortable: true,
                            pageable: {
                                refresh: true,
                                pageSizes: [5, 10, 15, 20],
                                buttonCount: 5
                            },
                            resizable: true,
                            toolbar: [{ name: "create", text: "" },
                                        {name: "ShowInactive", text: "Show Inactive" },
                                        { template: $("#template").html() }
                                    ],
                            dataBound: function () {
                             
                                var multiselect = $("#multiselect").data("kendoMultiSelect");
                                var jsonObj = [];
                                var selectedVal = [];
                                var datasource1 = $("#writergrid").data("kendoGrid").dataSource;
                                var presentfilters = datasource1.filter();

                                // get current set of filters, which is supposed to be array.
                                // if the object uwfilterswe obtained above is null/undefined, set this to an empty array
                                var currentFilters = presentfilters ? presentfilters.filters : [];

                                if (presentfilters == null) {
                                    // finally, the currentFilters array is applied back to the Grid, using "and" logic.
                                    $("#writergrid").data("kendoGrid").dataSource.filter({
                                        logic: "and",
                                        filters: currentFilters
                                    });

                                    datasource1 = $("#writergrid").data("kendoGrid").dataSource;
                                }

                                for (i = 0; i < datasource1.filter().filters.slice().length; i++) {
                                    if (datasource1.filter().filters[i].field != "IsActive") {
                                        jsonObj.push({
                                            text: datasource1.filter().filters[i].field,
                                            value: datasource1.filter().filters[i].field

                                        });
                                        selectedVal.push(datasource1.filter().filters[i].field);
                                    }
                                }

                                var localDataSource = new kendo.data.DataSource({ data: jsonObj });
                                localDataSource.read();
                                multiselect.dataSource = localDataSource;
                                multiselect.refresh();
                                multiselect.value(selectedVal);

                                saveCurrent(multiselect);

                            },
                            columns: [
                      
                            {
                            width: 25,
                            template: "# if (IsActive == false){# <img class= 'icon' src = '../images/InActive.png' />#} #"
                     
                        },
                            { field: "Code", title: "Code", filterable: {
                                ui: function (element) {
                                    element.kendoAutoComplete({
                                        dataSource: uwdataSource,
                                        dataTextField: "Code"
                                    })
                                }
                            }
                            },
                            { field: "Name", title: "Name", filterable: {
                                ui: function (element) {
                                    element.kendoAutoComplete({
                                        dataSource: uwdataSource,
                                        dataTextField: "Name"
                                    })
                                }
                            }
                            },
                          {field: "IsActive", title: "Status", hidden: true },
                       
                            {
                            command: [
                                        {
                                            name: "edit",
                                            text: {
                                                edit: "Edit",      // This is the localization for Edit button
                                                update: "Save",    // This is the localization for Update button
                                                cancel: "Cancel"   // This is the localization for Cancel button
                                            }
                                        }
                                       ], width: "140px", title: "&nbsp;"
                            }
                           ],

                        editable: {
                            mode: "popup",
                            window: { title: "Edit" },
                            template: kendo.template($("#popup_editor").html())
                        },
                        edit: function (e) {
                            $("#tabstrip").kendoTabStrip({
                                animation: {
                                    open: {
                                        effects: "fadeIn"
                                    }
                                }
                            });
                            $(".k-edit-form-container").parent().width(900).height(620).data("kendoWindow").center();
                            $(".k-edit-form-container").width(880);
                          
                                        
                             agentDataSource = new kendo.data.DataSource({
                                data: e.model.Agents,
                                pageSize: 10,
                                serverPaging: false,
                                serverFiltering: false,
                                serverSorting: false,
                                schema: {
                                    model: {
                                        AgentID: "AgentID",
                                        Name: "Name",
                                        IsActive: "IsActive",
                                        fields: {
                                            AgentID: { type: "string" },
                                            Name: { type: "string", validation: { required: true} },
                                            IsActive: { type: "boolean" }
                                        }
                                    }
                                },
                                filter: {
                                    "field": "IsActive",
                                    "operator": "IsEqualTo",
                                    "value": true
                                }

                            });
                        
                            BuildAgentGrid();

                            buildMultiSelect();

                        } // end of Edit 

                    }); //End of writergrid 

                } // End of build grid 


function buildMultiSelect() {

    var select = $("#agMultiselectfilter");

    if (!select.data("kendoMultiSelect")) {
        $("#agMultiselectfilter").kendoMultiSelect({
            dataTextField: "text",
            dataValueField: "value",
            change: function (e) {
                debugger;
                var previous = this._savedOld;
                // These are current values.
                var current = this.value();
                // Let's save it for the next time
                saveCurrent(this);

                // The difference between previous and current are removed elements
                var diff = $(previous).not(current).get();
                // get currently applied filters from the Grid.

                var agdatasourceFilters = $("#agentGrid").data("kendoGrid").dataSource;
                var agfilters = agdatasourceFilters.filter();

                // get current set of filters, which is supposed to be array.
                // if the object uwfilterswe obtained above is null/undefined, set this to an empty array
                var currentFilters = agfilters ? agfilters.filters : [];

                if (agfilters == null) {
                    // finally, the currentFilters array is applied back to the Grid, using "and" logic.
                    $("#agentGrid").data("kendoGrid").dataSource.filter({
                        logic: "and",
                        filters: currentFilters
                    });

                    agfilters = $("#agentGrid").data("kendoGrid").dataSource.filter();
                }


                //To Show Inactive
                for (i = 0; i < agdatasourceFilters.filter().filters.slice().length; i++) {
                    if ($.inArray(agdatasourceFilters.filter().filters[i].field, diff) !== -1) {
                        agfilters.filters.splice(i, 1); //Remove IsActive Filter from its Position in Filters List
                    }
                }
                agdatasourceFilters.filter(agfilters)

                if (diff == "IsActive") {
                    agIsShowActive = false;

                    agInactivebutton.textContent = "Hide Inactive";
                }

            } //end of change Event

        });
    }
}

function BuildAgentGrid() {

     $("#agentGrid").kendoGrid({
        dataSource: agentDataSource,
        pageable: true,
        height: 425,
        filterable: { extra: false },
        sortable: true,
        pageable: {
            refresh: true,
            pageSizes: [5, 10, 15, 20],
            buttonCount: 5
        },
        resizable: true,
        toolbar: [
        //{ name: "ShowInactiveAgents", text: "Show Inactive" }
                       {template: kendo.template($("#agInactivetemplate").html()) },
                       {template: $("#agFiltertemplate").html() }
                 ],

        dataBound: function () {
            buildMultiSelect();
            var agmultiselect = $("#agMultiselectfilter").data("kendoMultiSelect");

            var jsonagObj = [];
            var agselectedVal = [];
            var agdatasource = $("#agentGrid").data("kendoGrid").dataSource;
            var agpresentfilters = agdatasource.filter();

            // get current set of filters, which is supposed to be array.
            // if the object uwfilterswe obtained above is null/undefined, set this to an empty array
            var agcurrentFilters = agpresentfilters ? agpresentfilters.filters : [];

            if (agpresentfilters == null) {
                // finally, the currentFilters array is applied back to the Grid, using "and" logic.
                $("#agentGrid").data("kendoGrid").dataSource.filter({
                    logic: "and",
                    filters: agcurrentFilters
                });

                agdatasource = $("#agentGrid").data("kendoGrid").dataSource;
            }

            for (i = 0; i < agdatasource.filter().filters.slice().length; i++) {
                //if (agdatasource.filter().filters[i].field != "IsActive") {
                jsonagObj.push({
                    text: agdatasource.filter().filters[i].field,
                    value: agdatasource.filter().filters[i].field

                });
                agselectedVal.push(agdatasource.filter().filters[i].field);
                //}
            }

//            var agmultiselect = $("#agMultiselectfilter").data("kendoMultiSelect");
//            var aglocalDataSource = new kendo.data.DataSource({ data: jsonagObj });
//            aglocalDataSource.read();
//            agmultiselect.dataSource = aglocalDataSource;
//            agmultiselect.refresh();
//            agmultiselect.value(agselectedVal);


            var agmultiselect = $("#agMultiselectfilter").data("kendoMultiSelect");
            agmultiselect.setDataSource(jsonagObj);
            agmultiselect.refresh();
            agmultiselect.value(agselectedVal);


            saveCurrent(agmultiselect);

        },
        columns: [
                       {
                           width: 25,
                           template: "# if (IsActive == false){# <img class= 'icon' src = '../images/InActive.png' />#} #"
                          
                       },
                       { field: "AgentID", title: "Agency ID", filterable: {
                           ui: function (element) {
                               element.kendoAutoComplete({
                                   dataSource: agentDataSource,
                                   dataTextField: "AgentID"
                               })
                           }
                       }
                       },
                       { field: "Name", title: "Agent Name", filterable: {
                           ui: function (element) {
                               element.kendoAutoComplete({
                                   dataSource: agentDataSource,
                                   dataTextField: "Name"
                               })
                           }
                       }
                       },
                       { field: "IsActive", title: "Status", hidden:true }
                 ]
    });
}


//writer Inactive Button Click Action
$("#writergrid").on("click", ".k-grid-ShowInactive", function (e) {

        var datasourceInactive = $("#writergrid").data("kendoGrid").dataSource;

        // get currently applied filters from the Grid.
        var uwfilters = datasourceInactive.filter();

        // get current set of filters, which is supposed to be array.
        // if the object uwfilterswe obtained above is null/undefined, set this to an empty array
        var currentFilters = uwfilters ? uwfilters.filters : [];

        if(uwfilters == null){
                   // finally, the currentFilters array is applied back to the Grid, using "and" logic.
                     $("#writergrid").data("kendoGrid").dataSource.filter({
                       logic: "and",
                       filters: currentFilters
                       });

                       uwfilters=$("#writergrid").data("kendoGrid").dataSource.filter();
        }

        //To Show Inactive
        if (IsShowActive) {

                    for (i = 0; i < datasourceInactive.filter().filters.slice().length; i++) {
                        if (datasourceInactive.filter().filters[i].field == "IsActive") {
                            uwfilters.filters.splice(i, 1); //Remove IsActive Filter from its Position in Filters List
                        }
                    }

                    datasourceInactive.filter(uwfilters);
                    IsShowActive = false;
                    this.textContent = "Hide Inactive";

                    //$("#writergrid").data("kendoGrid").showColumn(0);

        } else { //To Hide Inactive
           
                    uwfilters.filters.push({ "field": "IsActive", //Add Active Filter
                        "operator": "IsEqualTo",
                        "value": true
                    });
                    datasourceInactive.filter(uwfilters);
                    IsShowActive = true;
                    this.textContent = "Show Inactive";

                    //$("#writergrid").data("kendoGrid").hideColumn(0);
        }

            });

 //Agents Inactive Button Click Action
 //$("#agentGrid").on("click", ".k-grid-ShowInactiveAgents", function (e) {
 //$(".k-agentGrid-ShowInactiveAgents").click(function(e){
 //$(".k-button.k-button-icontext.k-agentGrid-ShowInactiveAgents").on("click", function () {

            function agInactive_click() {
             
                var agdatasourceInactive = $("#agentGrid").data("kendoGrid").dataSource;

                // get currently applied filters from the Grid.
                var agfilters = agdatasourceInactive.filter();

                // get current set of filters, which is supposed to be array.
                // if the object uwfilterswe obtained above is null/undefined, set this to an empty array
                var currentFilters = agfilters ? agfilters.filters : [];

                if (agfilters == null || agfilters.filters == null ) {
                    // finally, the currentFilters array is applied back to the Grid, using "and" logic.
                    $("#agentGrid").data("kendoGrid").dataSource.filter({
                        logic: "and",
                        filters: currentFilters
                    });

                    agfilters = $("#agentGrid").data("kendoGrid").dataSource.filter();
                }

                //To Show Inactive
                if (agIsShowActive) {

                    for (i = 0; i < agdatasourceInactive.filter().filters.slice().length; i++) {
                        if (agdatasourceInactive.filter().filters[i].field == "IsActive") {
                            agfilters.filters.splice(i, 1); //Remove IsActive Filter from its Position in Filters List
                        }
                    }

                    agdatasourceInactive.filter(agfilters);
                    agIsShowActive = false;
                    agInactivebutton.textContent = "Hide Inactive";

                    //$("#agfilters").data("kendoGrid").showColumn(0);

                } else { //To Hide Inactive

                    agfilters.filters.push({ "field": "IsActive", //Add Active Filter
                        "operator": "IsEqualTo",
                        "value": true
                    });
                    agdatasourceInactive.filter(agfilters);
                    agIsShowActive = true;
                    agInactivebutton.textContent = "Show Inactive";

                    //$("#agfilters").data("kendoGrid").hideColumn(0);
                }

                // });
            }
            