/**
<span style="font-size:60px;color:red;font-weight:bold;">DOCUMENT ME PLEASE!</span>
@class ViewAnchorDialog
@namespace ProspectDirector.Modules.Views
**/
ProspectDirector.Modules.Views.ViewAnchorDialog = (function (options) {

    var 

    //===========================
    // MEMBERS
    //===========================

    PRIVATE = {

        /**
        @method init
        @private
        **/
        init: function (options) {

            this.options = $.extend({
                selector: null,
                data: {
                    viewStateId: null,
                    targets: [],
                    linkedViewCount: 0,
                    documentTypes: [],
                    canEditDocTypeTargets: true,
                    canEditEntTypeTargets: true
                }
            }, options);

            this._init_menu();

            this._init_tabStrip();

            this._init_grid();

            this._init_documentGrid();

            this._populate(this.options.data.anchors);

            this._init_dialog();

        },

        //===========================
        // PROPERTIES
        //===========================

        get_dialog: function () {
            return $(PRIVATE.options.selector);
        },

        get_menu: function () {
            return PRIVATE.get_dialog().find("[data-role=menu]");
        },

        get_documentTypesMenu: function () {
            return PRIVATE.get_dialog().find("[data-role=document-types-menu]");
        },

        get_grid: function () {
            return PRIVATE.get_dialog().find("[data-role=grid]");
        },

        get_documentGrid: function () {
            return PRIVATE.get_dialog().find("[data-role=document-grid]");
        },

        get_okButton: function () {
            return PRIVATE.get_dialog().find("[data-role=dialog-button][data-command=ok]");
        },

        get_cancelButton: function () {
            return PRIVATE.get_dialog().find("[data-role=dialog-button][data-command=cancel]");
        },
        
        get_tabStrip: function () {
            return PRIVATE.get_dialog().find("[data-role=tabstrip]");
        },
        
        //===========================
        // EVENT HANDLERS
        //===========================

        _okButton_onClick: function (sender, e) {

            var grid = this.get_documentGrid().data("kendoGrid"),
                data = null,
                docs = [];

            if (grid) {

                data = grid.dataSource.data();

                $(data).each(function (index, item) {
                    docs[docs.length] = item.id;
                });

            }

            PD.ajax({

                type: "POST",

                url: ProspectDirector.RUNTIME.resolveUrl("~/viewanchor/update?viewStateId=" + this.options.data.viewStateId),

                data: {
                    data: JSON.stringify({
                        anchor: this._packageData(),
                        documentTypes: docs
                    })
                },

                success: $.proxy(this._okButton_onClick_success, this)

            });

        },

        _okButton_onClick_success: function () {

            PRIVATE.get_dialog().data("dialog").hide({
                command: "ok"
            });

        },

        _cancelButton_onClick: function (sender, e) {
            PRIVATE.get_dialog().data("dialog").hide();
        },
        
        _menu_onSelect: function (e) {

            var command = $(e.item).data("command"),
                grid = PRIVATE.get_grid().data("kendoGrid");

            switch (command) {

                case "add":
                    ProspectDirector.Types.Core.Dialogs.FindAnchorTarget.show({
                        params: {
                            viewStateId: this.options.data.viewStateId
                        },
                        callbacks: {
                            ok: $.proxy(function (sender, e) {
                                this._populate(e, true);
                            }, this)
                        }
                    });

                    break;

                case "clear":

                    grid.dataSource.data([]);
                    break;

            }

        },

        _documentTypeMenu_onSelect: function (e) {

            var command = $(e.item).data("command");
            var grid = PRIVATE.get_documentGrid().data("kendoGrid");
            var selections = null;

            switch (command) {

                case "add":
                    
                    PDJS.Shared.DocumentTypes.DocumentTypeBrowserDialog.open({
                        viewCustomId: PDJS.Services.Views.BuiltInViews.DOCUMENT_TYPE_ASSIGNMENT,
                        selectionMode: PD.Web.UI.Controls.GridSelectionMode.multiple,
                        callbacks: {
                            ok: function (sender, e) {
                                
                                _.each(e, function (item) {
                                    if (!grid.dataSource.get(item.id)) {
                                        grid.dataSource.add({
                                            id: item.id,
                                            name: item.name,
                                            category: item.category
                                        });
                                    }
                                });
                                
                                grid.refresh();
                                
                            }
                        }
                    });

                    
                    break;

                case "remove":

                    selections = grid.select();

                    $(selections).each(function (index, item) {
                        grid.removeRow(item);
                    });

                    break;

                case "clear":

                    selections = this.get_documentGrid().find("TR[data-uid]");

                    $(selections).each(function (index, item) {
                        grid.removeRow(item);
                    });

                    break;

            }
            
        },

        _tabStrip_onSelect: function (e) {

            var grid = this.get_documentGrid().data("kendoGrid");

            setTimeout(function () {
                grid.refresh();
            }, 50);

        },

        _documentGrid_onDataBound: function () {

            var grid = this.get_documentGrid().data("kendoGrid"),
                data = grid.dataSource.data();

            if (data.length === 0) {

                ProspectDirector.Types.KendoExtensions.Grid.addMessage(this.get_documentGrid(),
                        "No document types selected.");

            }
            else {

                ProspectDirector.Types.KendoExtensions.Grid.removeMessage(this.get_documentGrid());

            }
            
        },

        _grid_onDataBound: function () {

            var grid = this.get_grid().data("kendoGrid"),
                data = grid.dataSource.data();

            if (data.length === 0) {

                ProspectDirector.Types.KendoExtensions.Grid.addMessage(this.get_grid(),
                        "No anchor targets selected.");

            }
            else {

                ProspectDirector.Types.KendoExtensions.Grid.removeMessage(this.get_grid());

            }

        },

        //===========================
        // PRIVATE METHODS
        //===========================

        _init_tabStrip: function () {

            var tabStrip = PRIVATE.get_tabStrip().kendoTabStrip({
                animation: false,
                select: $.proxy(this._tabStrip_onSelect, this)
            }).data("kendoTabStrip");

            if (!this.options.data.canEditDocTypeTargets) {
                $(tabStrip.items()[1]).attr("style", "display:none");
            }

            if (!this.options.data.canEditEntTypeTargets) {
                $(tabStrip.items()[0]).attr("style", "display:none");
                setTimeout(function () {
                    tabStrip.select(1);
                }, 50);
            }

        },

        _init_menu: function () {

            PRIVATE.get_menu().kendoMenu({
            });

            if (this.get_documentTypesMenu().length > 0) {
                this.get_documentTypesMenu().kendoMenu({});
            }

        },

        _init_documentGrid: function () {

            var grid = PRIVATE.get_documentGrid().kendoGrid({
                dataSource: {
                    data: this.options.data.documentTypes
                },
                resizable: true,
                height: "366px",
                selectable: "multiple",
                columns: [
                    {
                        field: "name",
                        title: "Document Type",
                        width: "250px"
                    },
                    {
                        field: "category",
                        title: "Document Category"
                    }
                ],
                dataBound: $.proxy(this._documentGrid_onDataBound, this)
            });

            this.get_grid().disableTextSelection();

        },

        _init_grid: function () {

            var grid = PRIVATE.get_grid().kendoGrid({
                dataSource: {
                    data: []
                },
                resizable: true,
                height: "366px",
                columns: [
                    {
                        field: "depth",
                        title: "Anchor",
                        width: "60px",
                        template: function (e) {
                            return e.depth > 0 ? "Ancestor " + e.depth : "Target";
                        }
                    },
                    {
                        field: "nodes",
                        title: "Group",
                        width: "200px",
                        encode: false,
                        template: function (e) {

                            var result = "",
                                index = 0,
                                nodes = null;

                            nodes = e.nodes.slice(0).sort(function (a, b) {
                                return (a.name < b.name) ? -1 : 1;
                            });

                            for (index; index < nodes.length; index++) {
                                result += (result.length > 0 ? ", " : "") + nodes[index].name;
                            }

                            return result === "" ? "<i>Any</i>" : result;

                        }
                    }
                ],
                dataBound: $.proxy(this._grid_onDataBound, this)
            });

        },

        _init_dialog: function () {

            PRIVATE.get_okButton().on("click", $.proxy(this._okButton_onClick, PRIVATE));
            PRIVATE.get_cancelButton().on("click", $.proxy(this._cancelButton_onClick, PRIVATE));
            PRIVATE.get_menu().data("kendoMenu").bind("select", $.proxy(this._menu_onSelect, PRIVATE));
            PRIVATE.get_documentTypesMenu().data("kendoMenu").bind("select", $.proxy(this._documentTypeMenu_onSelect, PRIVATE));

        },

        _packageData: function () {

            var result = [],
                grid = this.get_grid().data("kendoGrid"),
                data = grid.dataSource.data(),
                index = 0;

            for (index; index < data.length; index++) {

                result[result.length] = {
                    targets: (function () {

                        var result = [],
                            i = 0,
                            nodes = data[index].nodes;

                        for (i = 0; i < nodes.length; i++) {
                            result[result.length] = nodes[i].id;
                        }

                        return result;

                    })()
                };
            }

            return result;

        },

        _populate: function (data, merge) {

            var i = 0,
                grid = this.get_grid().data("kendoGrid"),
                dataSource = grid.dataSource;

            if (!merge) {
                dataSource.data([]);
            }

            for (i = 0; i < data.length; i++) {

                if (dataSource.total() < i + 1) {
                    dataSource.add({ depth: i, nodes: data[i] })
                }
                else {
                    this.mergeRecord(dataSource.at(i), data[i]);
                }

            }

            grid.refresh();

        },

        mergeRecord: function (item, nodes) {

            var data = item.nodes.slice(0),
                index = 0,
                contains = function (array, value) {
                    return $(array).filter(function () {
                        return this.id == value;
                    }).length > 0;
                };

            for (index; index < nodes.length; index++) {
                if (!contains(data.nodes, nodes[index].id)) {
                    data[data.length] = nodes[index];
                }
            }

            item.set("nodes", data);

        }

    }

    //===========================
    // PUBLIC MEMBERS
    //===========================

    PUBLIC = {
    };

    PRIVATE.init(options);

    return PUBLIC;

});