Ext.define("Portfolio.pd.manager.view.Main", {

    extend: "Ext.panel.Panel",

    alias: [
        "widget.pd-manager-main"
    ],

    requires: [
        "Portfolio.pd.manager.component.panel.view.Property",
        "Portfolio.pd.manager.component.panel.view.Collection",
        "Portfolio.pd.manager.component.panel.view.Form",
        "Portfolio.ux.file.view.Explorer"
    ],

    config: {
        propertyData: [],
        collectionData: [],
        formData: [],
        properties: null,
        collections: null,
        forms: null,
        tabArea: null,
        file: "",
        service: "",
        toolbar: null,
        definitions: []
    },

    layout: "fit",

    listeners: {
        afterrender: {
            fn: function() {
                var i_self = this;
                
                if (i_self.getService()) {

                    i_self.setLoading(true);

                    i_self.loadService(i_self.getService());
                }
                else if (i_self.getFile()) {
                    i_self.setLoading(true);
                    i_self.loadFile(i_self.getFile());
                }
            }
        }, 
        editproperty: {
            fn: function(s_property, s_type) {

                var i_self = this;
                var i_properties = i_self.getProperties();

                i_properties.fireEvent("editproperty", s_property, s_type);
            }
        },
        editcollection: {
            fn: function(s_property, s_type) {

                var i_self = this;
                var i_collections = i_self.getCollections();

                i_collections.fireEvent("editcollection", s_property, s_type);
            }
        },
        editcomplete: {
            fn: function(s_property, s_type) {

                var i_self = this;

                switch(s_type) {
                    case "collection":
                        var i_collection = i_self.getCollections();
                        i_collection.fireEvent("editcomplete", s_property);
                        break;
                    case "form":
                        var i_forms = i_self.getForms();
                        i_forms.fireEvent("editcomplete", s_property);
                        break;
                }
            }
        },
        checkProperty: {
            fn: function(s_name) {

                var i_self = this;
                i_self.checkProperty(s_name);
            }
        },
        checkCollection: {
            fn: function(s_name) {

                var i_self = this;
                i_self.checkCollection(s_name);
            }
        }
    },

    initComponent: function() {

        var i_self = this;
        i_self.callParent(arguments);

        i_self.add([
            i_self.createLayout(),
        ]);

        i_self.addDocked(i_self.createToolbar());

    },

    createLayout: function() {

        var i_self = this;

        var i_properties = Ext.widget("pd-manager-panel-property", {
            title: ip2.i18n({
                da: "Property",
                en: "Property"
            }),
            values: i_self.getPropertyData() 
        });

        var i_collections = Ext.widget("pd-manager-panel-collection", {
            title:  ip2.i18n({
                da: "Collection",
                en: "Collection"
            }),
            values: i_self.getCollectionData()
        });

        var i_forms = Ext.widget("pd-manager-panel-form", {
            title:  ip2.i18n({
                da: "Form collection",
                en: "Form collection"
            }),
            values: i_self.getFormData()
        });

        var i_panel = Ext.widget("tabpanel", {
            hidden: true,
            items: [
                i_forms,
                i_collections,
                i_properties
            ]
        });

        i_self.setProperties(i_properties);
        i_self.setCollections(i_collections);
        i_self.setForms(i_forms);

        i_self.setTabArea(i_panel);

        return  i_panel;
    },

    createToolbar: function() {
        
        var i_self = this;

        var i_toolbar = Ext.widget("toolbar", {
            dock: "top",
            items:[
                {
                    xtype: "button",
                    text: "File",
                    ui: "function",
                    itemId: "file-menu",
                    menu: {
                        plain: true,
                        items: [
                            {
                                xtype: "menuitem",
                                text: ip2.i18n({
                                    da: "Ny",
                                    en: "New"
                                }),
                                handler: function() {
                                    i_self.createNew();
                                }
                            },
                            {
                                xtype: "menuitem",
                                text: ip2.i18n({
                                    da: "Åben",
                                    en: "Open"
                                }),
                                menu: {
                                    plain: true,
                                    items: [
                                        {
                                            xtype: "menuitem",
                                            text: ip2.i18n({
                                                da: "Fil",
                                                en: "File"
                                            }),
                                            handler: function() {

                                                i_self.setLoading(true);

                                                i_self.openFile();
                                            }
                                        },
                                        {
                                            xtype: "menuitem",
                                            text: ip2.i18n({
                                                da: "Service",
                                                en: "Service"
                                            }),
                                            handler: function() {
                                                i_self.createServiceWindow();
                                            }
                                        }
                                    ]
                                },
                            },
                            {
                                xtype: "menuitem",
                                text: ip2.i18n({
                                    da: "Gem",
                                    en: "Save"
                                }),
                                itemId: "save-menu",
                                disabled: true,
                                handler: function() {
                                    i_self.doSave();
                                }
                            },
                            {
                                xtype: "menuitem",
                                text: ip2.i18n({
                                    da: "Gem som",
                                    en: "Save as"
                                }),
                                itemId: "save-as-menu",
                                disabled: true,
                                menu: {
                                    plain: true,
                                    items: [
                                        {
                                            xtype: "menuitem",
                                            text: ip2.i18n({
                                                da: "Fil",
                                                en: "File"
                                            }),
                                            handler: function() {
                                                i_self.doSaveAs();
                                            }
                                        },
                                        {
                                            xtype: "menuitem",
                                            text: ip2.i18n({
                                                da: "Service",
                                                en: "Service"
                                            }),
                                            handler: function() {
                                                i_self.saveServiceAs();
                                            }
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            ]
        });

        i_self.setToolbar(i_toolbar);

        return i_toolbar;
    },

    createNew: function() {
        
        var i_self = this;

        var s_file = i_self.getFile();
        var s_service = i_self.getService();

        if (s_file || s_service) {

            ip2.messageBox({
                title: ip2.i18n({
                    da: "Advarsel",
                    en: "Warning"
                }),
                closable: false,
                message: ip2.i18n({
                    da: "Alt som ikke er gemt vil gå tabt\nSkal der skabes en ny...?",
                    en: "Unsaved data will be lost\nAre you sure want to create a new..?"
                }),
                yesFn: function () {
                    i_self.setLoading(true);

                    setTimeout(function() {

                        i_self.setFile(null);
                        i_self.setService(null);

                        Ext.suspendLayouts();

                        i_self.removeAll(true);

                        i_self.add([
                            i_self.createLayout(),
                        ]);

                        i_self.doUpdateTitle(ip2.i18n({
                            da: "Ny definition",
                            en: "New defnition"
                        }));

                        var i_filebar = i_self.getToolbar();

                        var i_button = i_filebar.getComponent("file-menu");
                        var i_menu = i_button.menu;
                
                        var i_save = i_menu.getComponent("save-menu");
                        var i_saveAs = i_menu.getComponent("save-as-menu");
                
                        if (i_save) {
                            i_save.disable();
                            i_saveAs.enable();
                        }

                        Ext.resumeLayouts(true);

                        i_self.setLoading(false);

                    }, 100);
                },
                yesText: ip2.i18n({
                    da: "Ja",
                    en: "Yes"
                }),
                noText: ip2.i18n({
                    da: "Nej",
                    en: "No"
                })
            });
        }
        else {
            i_self.setLoading(true);

            setTimeout(function() {

                Ext.suspendLayouts();

                i_self.removeAll(true);

                i_self.add([
                    i_self.createLayout(),
                ]);

                var i_filebar = i_self.getToolbar();

                var i_button = i_filebar.getComponent("file-menu");
                var i_menu = i_button.menu;
        
                var i_save = i_menu.getComponent("save-menu");
                var i_saveAs = i_menu.getComponent("save-as-menu");
        
                if (i_save) {
                    i_save.disable();
                    i_saveAs.enable();
                }

                Ext.resumeLayouts(true);

                i_self.setLoading(false);

            }, 100);
        }
    },

    createServiceWindow: function() {

        var i_self = this;

        // THIS CAN BE USED AS A TEST URL..
        //"/ip2-services/ip2transaction.aspx?payload={"action": "cmsCms.cmsListPD","TABLE": "CMSPRD"}

		var i_fileStore = Ext.create("Ext.data.Store", {
			fields: [
				{ name: "key" },
				{ name: "value" }
			],
			proxy: {
				type: "ajax",
				url: "ip2-services/ip2Services.aspx",
				extraParams: {
					plugin: "DB2",
					func: "getDataModels"
				},
				reader: {
					type: "json",
					rootProperty: "rows",
					totalProperty: "totalRows"
				}
			}
		});

		var i_table = Ext.widget("combobox", {
			fieldLabel: ip2.i18n({
				da: "Tabel",
				en: "Table"
			}),
			name: "file",
			allowBlank: false,
			displayField: "key",
			valueField: "value",
			store: i_fileStore,
			queryMode: "remote",
			minChars: 1,
			triggerAction: "all"
		});
        
        var i_form = Ext.widget("form",{
            layout: "anchor",
            bodyPadding: 10,
            defaults: {
                anchor: "100%",
            },
            items: [
                i_table
            ]
        });

        var i_window = Ext.widget("window", {
            title: ip2.i18n({
                da: "Hent definition",
                en: "Load definition"
            }),
            layout: "anchor",
            width: 800,
            modal: true,
            items: [
                i_form
            ]
        });

        var i_toolbar = Ext.widget("toolbar", {
            dock: "bottom",
            ui: "footer",
            items: [
                "->",
                {
                    xtype: "button",
                    text: ip2.i18n({
                        da: "Luk",
                        en: "Close"
                    }),
                    handler: function() {
                        i_window.close();
                    }
                },
                {
                    xtype: "button",
                    ui: "primary-button",
                    text: ip2.i18n({
                        da: "Åben",
                        en: "Open"
                    }),
                    handler: function() {

                        i_self.setLoading(true);

                        var o_values = i_form.getValues(false, false, true, true);

                        var a_split = o_values.file.split("/");
                        var s_table = a_split.pop();

                        i_window.close();

                        Ext.Ajax.request({
                            method: "POST",
                            url: "/ip2-services/ip2transaction.aspx",
                            jsonData: {
                                action: "cmsCms.cmsListPD",
                                TABLE: s_table
                            },
                            success: function(i_response) {

                                i_self.setLoading(false);

                                var a_definitions = Ext.decode(i_response.responseText);
                    
                                i_self.afterload(a_definitions, o_values.file, "service");
                            },
                            failure: function(i_error) {
                                i_self.setLoading(false);

                                ip2.messageBox({
                                    title: ip2.i18n({
                                        da: "Fejl",
                                        en: "Error"
                                    }),
                                    message: i_error.message,
                                    yesText: ip2.i18n({
                                        da: "Ok",
                                        en: "OK"
                                    })
                                });
                            }
                        });
                    }
                }
            ]
        });

        i_window.addDocked(i_toolbar);

        i_window.show();
    },

    saveServiceAs: function() {

        var i_self = this;

        var i_fileStore = Ext.create("Ext.data.Store", {
			fields: [
				{ name: "key" },
				{ name: "value" }
			],
			proxy: {
				type: "ajax",
				url: "ip2-services/ip2Services.aspx",
				extraParams: {
					plugin: "DB2",
					func: "getDataModels"
				},
				reader: {
					type: "json",
					rootProperty: "rows",
					totalProperty: "totalRows"
				}
			}
		});

		var i_table = Ext.widget("combobox", {
			fieldLabel: ip2.i18n({
				da: "Tabel",
				en: "Table"
			}),
			name: "file",
			allowBlank: false,
			displayField: "key",
			valueField: "value",
			store: i_fileStore,
			queryMode: "remote",
			minChars: 1,
			triggerAction: "all"
		});
        
        var i_form = Ext.widget("form",{
            layout: "anchor",
            bodyPadding: 10,
            defaults: {
                anchor: "100%",
            },
            items: [
                i_table
            ]
        });

        var i_window = Ext.widget("window", {
            title: ip2.i18n({
                da: "Gem definition",
                en: "Save definition"
            }),
            layout: "anchor",
            width: 600,
            modal: true,
            items: [
                i_form
            ]
        });

        var i_toolbar = Ext.widget("toolbar", {
            dock: "bottom",
            ui: "footer",
            items: [
                "->",
                {
                    xtype: "button",
                    text: ip2.i18n({
                        da: "Luk",
                        en: "Close"
                    }),
                    handler: function() {
                        i_window.close();
                    }
                },
                {
                    xtype: "button",
                    ui: "primary-button",
                    text: ip2.i18n({
                        da: "Gem",
                        en: "Save"
                    }),
                    handler: function() {

                        i_self.setLoading(ip2.i18n({
                            da: "Gemmer...",
                            en: "Saving..."
                        }));

                        var o_values = i_form.getValues(false, false, true, true);

                        var a_split = o_values.file.split("/");
                        var s_table = a_split.pop();

                        var a_saved = i_self.getSaveValues(false);

                        Ext.Ajax.request({
                            method: "POST",
                            url: "/ip2-services/ip2transaction.aspx",
                            jsonData: {
                                action: "cmsCms.cmsSavePD",
                                TABLE: s_table,
                                PD: a_saved
                            },
                            success: function(i_response) {

                                i_self.setLoading(false);
                                i_window.close();
                                i_self.setService(o_values.file);
                                i_self.setFile(null);
                                i_self.doUpdateTitle(o_values.file);
                                
                            },
                            failure: function(i_error) {
                                i_self.setLoading(false);

                                ip2.messageBox({
                                    title: ip2.i18n({
                                        da: "Fejl",
                                        en: "Error"
                                    }),
                                    message: i_error.message,
                                    yesText: ip2.i18n({
                                        da: "Ok",
                                        en: "OK"
                                    })
                                });
                            }
                        });
                    }
                }
            ]
        });

        i_window.addDocked(i_toolbar);

        i_window.show();
    },

    saveService: function() {

        var i_self = this;

        var s_service = i_self.getService();

        if (!s_service) {
            i_self.saveServiceAs();
        }
        else {
            i_self.setLoading(ip2.i18n({
                da: "Gemmer...",
                en: "Saving..."
            }));

            var a_split = s_service.split("/");
            var s_table = a_split.pop();

            var a_saved = i_self.getSaveValues(false);

            Ext.Ajax.request({
                method: "POST",
                url: "/ip2-services/ip2transaction.aspx",
                jsonData: {
                    action: "cmsCms.cmsSavePD",
                    TABLE: s_table,
                    PD: a_saved
                },
                success: function(i_response) {
                    i_self.setLoading(false);
                },
                failure: function(i_error) {
                    i_self.setLoading(false);

                    ip2.messageBox({
                        title: ip2.i18n({
                            da: "Fejl",
                            en: "Error"
                        }),
                        message: i_error.message,
                        yesText: ip2.i18n({
                            da: "Ok",
                            en: "OK"
                        })
                    });
                }
            });
        }
    },

    getSaveValues: function(b_encode) {

        var i_self = this;
        var i_properties = i_self.getProperties();
        var i_collections = i_self.getCollections();
        var i_forms = i_self.getForms();
        
        var a_properties = i_properties.save();
        var a_collections = i_collections.save();
        var a_forms = i_forms.save();

        var a_result = [];

        a_result = a_result.concat(a_properties).concat(a_collections).concat(a_forms);

        return b_encode ? Ext.encode(a_result, true) || false : a_result;

    },

    doSave: function() {

        var i_self = this;

        var s_file = i_self.getFile();
        var s_service = i_self.getService();

        if (s_file) {

            i_self.setLoading(ip2.i18n({
                da: "Gemmer...",
                en: "Saving..."
            }));

            var s_value = i_self.getSaveValues(true);
    
            i_self.saveFileToPath(s_file, s_value, function(b_success, i_error) {
                
                i_self.setLoading(false);
    
                if(!b_success) {
    
                    ip2.messageBox({
                        title: ip2.i18n({
                            da: "Fejl",
                            en: "Error"
                        }),
                        message: i_error.message,
                        yesText: ip2.i18n({
                            da: "Ok",
                            en: "OK"
                        })
                    });
                }
                else {
                    i_self.setFile(s_file);
                    i_self.doUpdateTitle(s_file);
                }
            });
        }
        else if (s_service) {
            i_self.saveService();
        }
    },

    doSaveAs: function() {

        var i_self = this;

		var i_explorer = Ext.widget("file.explorer", {
			path: ip2.baseconfig.session.preset.root || "/",
			saveAction: true,
			fileExtension: [
                {
                    ext: "pd",
                    desc: ip2.i18n({
                        da: "PD Filer",
                        en: "PD Files"
                    }) + " (*.pd)"
                }
            ],
			listeners: {
				filesave: {
					fn: function(i_explorer, s_file) {

                        i_self.setLoading(ip2.i18n({
                            da: "Gemmer...",
                            en: "Saving..."
                        }));

                        var s_value = i_self.getSaveValues(true);

                        i_self.saveFileToPath(s_file, s_value, function(b_success, i_error) {
                            
                            i_self.setLoading(false);

                            if(!b_success) {

                                ip2.messageBox({
                                    title: ip2.i18n({
                                        da: "Fejl",
                                        en: "Error"
                                    }),
                                    message: i_error.message,
                                    yesText: ip2.i18n({
                                        da: "Ok",
                                        en: "OK"
                                    })
                                });
                            }
                            else {
                                i_self.setFile(s_file);
						        i_self.doUpdateTitle(s_file);
                            }
                        });
					}
				}
			}
		});

		i_explorer.show();
    },

    saveFileToPath: function(s_file, s_data, f_callback) {

        var i_self = this;

        f_callback = f_callback || Ext.emptyFn;

		Ext.Ajax.request({
			url: "/ip2-services/webBios.aspx",
			params: {
				func: "writestmf",
				data: s_data,
				file: s_file,
				ignoreStaticDir: true
            },
            success: function() {
                f_callback.call(i_self, true);
            },
            failure: function(i_error) {
                f_callback.call(i_self, false, i_error);
            }
		});
    },
    
    openFile: function() {

        var i_self = this;

        var i_explorer = Ext.widget("file.explorer", {
			path: ip2.baseconfig.session.preset.root || "/",
			saveAction: false,
			fileExtension: [
                {
                    ext: "pd",
                    desc: ip2.i18n({
                        da: "PD Filer",
                        en: "PD Files"
                    }) + " (*.pd)"
                }
            ],
			listeners: {
				fileopen: {
					fn: function(i_explorer, s_file) {
                        
						i_self.loadFile(s_file);
					}
				}
			}
		});

		i_explorer.show();
    },

    getFileFromPath: function(s_path, f_callback) {

		Ext.Ajax.request({
			url: "/ip2-services/webBios.aspx",
			params: {
				func: "readstmf",
				file: s_path
			},
			success: function (o_response) {

				var s_result = o_response.responseText;

				f_callback(s_result);
			}
		});
    },
    
    doUpdateTitle: function(s_title) {

        var i_self = this;

        var i_window = i_self.up("window");

        if (i_window) {
            i_window.setTitle(s_title);
        }
        else {
            i_self.setTitle(s_title);
        }
    },

    loadFile: function(s_file) {

        var i_self = this;

        i_self.getFileFromPath(s_file, function(s_data) {

            var a_definitions = Ext.decode(s_data, true) || false;

            i_self.afterload(a_definitions, s_file, "file");
        });
    },

    loadService: function(s_table) {

        var i_self = this;

        var a_split = s_table.split("/");
        var s_result = a_split.pop();

        Ext.Ajax.request({
            method: "POST",
            url: "/ip2-services/ip2transaction.aspx",
            jsonData: {
                action: "cmsCms.cmsListPD",
                TABLE: s_result
            },
            success: function(i_response) {
                
                i_self.setLoading(false);

                var a_definitions = Ext.decode(i_response.responseText);

                i_self.afterload(a_definitions, s_table, "table");
            },
            failure: function(i_error) {
                i_self.setLoading(false);

                ip2.messageBox({
                    title: ip2.i18n({
                        da: "Fejl",
                        en: "Error"
                    }),
                    message: i_error.message,
                    yesText: ip2.i18n({
                        da: "Ok",
                        en: "OK"
                    })
                });
            }
        });
    },

    afterload: function(a_definitions, s_value, s_type) {

        var i_self = this;

        var a_properties = Ext.Array.filter(a_definitions, function(o_def) {
            return o_def.type == "property";
        });
        var a_collections = Ext.Array.filter(a_definitions, function(o_def) {
            return o_def.type == "collection" || o_def.type == "group";
        });

        var a_forms = Ext.Array.filter(a_definitions, function(o_def) {
            return o_def.type == "formCollection";
        });

        var i_properties = i_self.getProperties();
        var i_collections = i_self.getCollections();
        var i_forms = i_self.getForms();
        var i_tabArea = i_self.getTabArea();

        i_tabArea.show();

        i_properties.loadData(a_properties);
        i_collections.loadData(a_collections);
        i_forms.loadData(a_forms);

        i_self.doUpdateTitle(s_value);

        i_self[s_type == "file" ? "setFile" : "setService"](s_value);

        var i_filebar = i_self.getToolbar();

        var i_button = i_filebar.getComponent("file-menu");
        var i_menu = i_button.menu;

        var i_save = i_menu.getComponent("save-menu");
        var i_saveAs = i_menu.getComponent("save-as-menu");

        if (i_save) {
            i_save.enable();
            i_saveAs.enable();
        }

        i_self.setDefinitions(a_definitions);

        i_self.setLoading(false);
    },

    checkProperty: function(s_name) {

        var i_self = this;
        var a_definitions = i_self.getDefinitions();

        i_self.setLoading(true);

        Portfolio.pd.util.Handler.checkPropertyUsages(s_name, function(o_result, b_success) {

            i_self.setLoading(false);

            var o_def = Ext.Array.findBy(a_definitions, function(o_search) {
                return o_search.name == s_name && o_search.type == "property";
            });

            if (b_success) {

                var s_title = s_name;

                var a_collections = Ext.Array.from(o_result.collections);

                var i_collection = Ext.widget("grid", {
                    title: ip2.i18n({
                        da: "Collection",
                        en: "Collection"
                    }),
                    flex: 1,
                    split: true,
                    hidden: a_collections.length === 0,
                    plugins: [
                        {
                            ptype: "gridexporter",
                            id: "exporter"
                        }
                    ],
                    header: {
                        itemPosition: 1,
                        items: [
                            {
                                xtype: "button",
                                ui: "function-action",
                                iconCls: "pf-cloud_download",
                                arrowVisible: false,
                                tooltip: ip2.i18n({
                                    da: "Export til",
                                    en: "Export to"
                                }),
                                menu: {
                                    plain: true,
                                    items: [{
                                        text: "Excel",
                                        cfg: {
                                            ext: "xlsx",
                                            type: "excel07",
                                            fileName: "collection",
                                            exportType: ip2.i18n({
                                                da: "Collection",
                                                en: "Collection"
                                            })
                                        },
                                        handler: function(i_item) {

                                            var o_export = {
                                                title:  ip2.i18n({
                                                    da: "Collection",
                                                    en: "Collection"
                                                }),
                                                fileName: [
                                                    "collection",
                                                    s_name
                                                ].join("_") + ".xlsx",
                                                ext: "xlsx",
                                                type: "excel07",
                                            };
                                    
                                            var i_exporter = i_collection.getPlugin("exporter");
                                    
                                            i_exporter.saveDocumentAs(o_export);
                                        }
                                    }]
                                }
                            }
                        ]
                    },
                    columns: [
                        {
                            dataIndex: "name",
                            header: "Name",
                            flex: 1
                        },
                        {
                            dataIndex: "label",
                            header: "Label",
                            flex: 2
                        }
                    ],
                    store: Ext.create("Ext.data.Store", {
                        fields: [
                            {
                                name: "name",
                                type: "auto"
                            },
                            {
                                name: "label",
                                type: "auto"
                            }
                        ],
                        data: o_result.collections || []
                    })
                });

                var a_columns =[
                    {
                        dataIndex: "productnumber",
                        header: "Productnumber",
                        flex: 1
                    },
                    {
                        dataIndex: "title",
                        header: "Title",
                        flex: 2
                    }
                ];

                if (o_def) {

                    s_title = ip2.i18n(o_def.fieldLabel || o_def.label || s_name);

                    a_columns.push({
                        dataIndex: "value",
                        header: ip2.i18n(o_def.fieldLabel || o_def.label || s_name),
                        flex: 1
                    });
                }

                var a_products = Ext.Array.from(o_result.products.rows);

                a_columns.push({
                    dataIndex: "total",
                    header: o_result.products.totalRows,
                    width: 80
                });

                var i_products = Ext.widget("grid", {
                    title: ip2.i18n({
                        da: "Produkter",
                        en: "Products"
                    }),
                    split: true,
                    flex: 1,
                    hidden: a_products.length === 0,
                    plugins: [
                        {
                            ptype: "gridexporter",
                            id: "exporter"
                        }
                    ],
                    header: {
                        itemPosition: 1,
                        items: [
                            {
                                xtype: "button",
                                ui: "function-action",
                                iconCls: "pf-cloud_download",
                                arrowVisible: false,
                                tooltip: ip2.i18n({
                                    da: "Export til",
                                    en: "Export to"
                                }),
                                menu: {
                                    plain: true,
                                    items: [{
                                        text: "Excel",
                                        handler: function(i_item) {

                                            var o_export = {
                                                title: ip2.i18n({
                                                    da: "Produkter",
                                                    en: "Products"
                                                }),
                                                fileName: [
                                                    "products",
                                                    s_name
                                                ].join("_") + ".xlsx",
                                                ext: "xlsx",
                                                type: "excel07",
                                            };
                                    
                                            var i_exporter = i_products.getPlugin("exporter");
                                    
                                            i_exporter.saveDocumentAs(o_export);
                                        }
                                    }]
                                }
                            }
                        ]
                    },
                    columns: a_columns,
                    store: Ext.create("Ext.data.Store", {
                        fields: [
                            {
                                name: "productnumber",
                                type: "auto"
                            },
                            {
                                name: "title",
                                type: "auto"
                            }
                        ],
                        data: o_result.products.rows || []
                    })
                });

                var o_size = Portfolio.util.Handler.getWindowSize();
				var n_height =  o_size.height * 0.6;
                var n_width = o_size.width * 0.6;

                var o_config = {
                    title: [
                        ip2.i18n({
                            da: "Anvendelse",
                            en: "Usages"
                        }),
                        s_title
                    ].join(" - "),
                    layout: {
                        type: "hbox",
                        align: "stretch"
                    },
                    height: n_height,
                    width: n_width,
                    modal: false,
                    items: [
                        i_collection,
                        i_products
                    ]
                };
                
                Portfolio.app.fireEvent("beforedetached", o_config);

                var i_window = Ext.widget("window", o_config);

                i_window.show();
            }
            else {
                ip2.messageBox({
                    title: ip2.i18n({
                        da: "Fejl",
                        en: "Error"
                    }),
                    message: o_result.message,
                    yesText: ip2.i18n({
                        da: "OK",
                        en: "OK"
                    })
                });
            }
        });
    },

    checkCollection: function(s_name) {

        var i_self = this;
        var a_definitions = i_self.getDefinitions();

        i_self.setLoading(true);
        
        Portfolio.pd.util.Handler.checkCollectionUsages(s_name, function(o_result, b_success) {

            i_self.setLoading(false);

            var o_def = Ext.Array.findBy(a_definitions, function(o_search) {
                return o_search.name == s_name && (o_search.type == "collection" ||  o_search.type == "group");
            });

            if (b_success) {

                var s_title = s_name;

                var a_collections = Ext.Array.from(o_result.collections);

                var i_collection = Ext.widget("grid", {
                    title: ip2.i18n({
                        da: "Collection",
                        en: "Collection"
                    }),
                    flex: 1,
                    split: true,
                    hidden: a_collections.length === 0,
                    plugins: [
                        {
                            ptype: "gridexporter",
                            id: "exporter"
                        }
                    ],
                    header: {
                        itemPosition: 1,
                        items: [
                            {
                                xtype: "button",
                                ui: "function-action",
                                iconCls: "pf-cloud_download",
                                arrowVisible: false,
                                tooltip: ip2.i18n({
                                    da: "Export til",
                                    en: "Export to"
                                }),
                                menu: {
                                    plain: true,
                                    items: [{
                                        text: "Excel",
                                        handler: function(i_item) {

                                            var o_export = {
                                                title: ip2.i18n({
                                                    da: "Collection",
                                                    en: "Collection"
                                                }),
                                                fileName: [
                                                    "collection",
                                                    s_name
                                                ].join("_") + ".xlsx",
                                                ext: "xlsx",
                                                type: "excel07",
                                            };

                                            var i_exporter = i_collection.getPlugin("exporter");
                                    
                                            i_exporter.saveDocumentAs(o_export);
                                        }
                                    }]
                                }
                            }
                        ]
                    },
                    columns: [
                        {
                            dataIndex: "name",
                            header: "Name",
                            flex: 1
                        },
                        {
                            dataIndex: "label",
                            header: "Label",
                            flex: 2
                        }
                    ],
                    store: Ext.create("Ext.data.Store", {
                        fields: [
                            {
                                name: "name",
                                type: "auto"
                            },
                            {
                                name: "label",
                                type: "auto"
                            }
                        ],
                        data: o_result.collections || []
                    })
                });

                var a_columns =[
                    {
                        dataIndex: "productnumber",
                        header: "Productnumber",
                        flex: 1
                    },
                    {
                        dataIndex: "title",
                        header: "Title",
                        flex: 2
                    }
                ];

                if (o_def) {

                    s_title = ip2.i18n(o_def.label || o_def.fieldLabel || s_name);

                    a_columns.push({
                        dataIndex: "value",
                        header: s_title,
                        flex: 1
                    });
                }

                var a_products = Ext.Array.from(o_result.products.rows);

                var i_products = Ext.widget("grid", {
                    title: ip2.i18n({
                        da: "Produkter",
                        en: "Products"
                    }),
                    flex: 1,
                    split: true,
                    hidden: a_products.length === 0,
                    plugins: [
                        {
                            ptype: "gridexporter",
                            id: "exporter"
                        }
                    ],
                    header: {
                        itemPosition: 1,
                        items: [
                            {
                                xtype: "button",
                                ui: "function-action",
                                iconCls: "pf-cloud_download",
                                arrowVisible: false,
                                tooltip: ip2.i18n({
                                    da: "Export til",
                                    en: "Export to"
                                }),
                                menu: {
                                    plain: true,
                                    items: [{
                                        text: "Excel",
                                        handler: function(i_item) {

                                            var o_export = {
                                                title: ip2.i18n({
                                                    da: "Produkter",
                                                    en: "Products"
                                                }),
                                                fileName: [
                                                    "products",
                                                    s_name
                                                ].join("_") + ".xlsx",
                                                ext: "xlsx",
                                                type: "excel07",
                                            };

                                            var i_exporter = i_products.getPlugin("exporter");
                                    
                                            i_exporter.saveDocumentAs(o_export);
                                        }
                                    }]
                                }
                            }
                        ]
                    },
                    columns: a_columns,
                    store: Ext.create("Ext.data.Store", {
                        fields: [
                            {
                                name: "productnumber",
                                type: "auto"
                            },
                            {
                                name: "title",
                                type: "auto"
                            }
                        ],
                        data: o_result.products.rows || []
                    })
                });

                var o_size = Portfolio.util.Handler.getWindowSize();
				var n_height =  o_size.height * 0.6;
                var n_width = o_size.width * 0.6;

                var o_config = {
                    title: [
                        ip2.i18n({
                            da: "Anvendelse",
                            en: "Usages"
                        }),
                        s_title
                    ].join(" - "),
                    layout: {
                        type: "hbox",
                        align: "stretch"
                    },
                    height: n_height,
                    width: n_width,
                    modal: false,
                    items: [
                        i_collection,
                        i_products
                    ]
                };

                Portfolio.app.fireEvent("beforedetached", o_config);

                var i_window = Ext.widget("window", o_config);

                i_window.show();
            }
            else {
                ip2.messageBox({
                    title: ip2.i18n({
                        da: "Fejl",
                        en: "Error"
                    }),
                    message: o_result.message,
                    yesText: ip2.i18n({
                        da: "OK",
                        en: "OK"
                    })
                });
            }
        });
    }
});

