Ext.onReady(function(){

	// Function to process the window request
    function productGroupWindow(update){
        if(this instanceof productGroupWindow){
            this.CreateWindow = createWindow;
            this.LoadFields = loadFields;
            this.SetForNewEntry = setForNewEntry;
        }else{
            return new productGroupWindow();
        }
    }
    productGroupWin = new productGroupWindow();

    // Set the window options & decide if we are adding or editing
    function createWindow(update, id) {
        if (update) {
            buttonText = lang('Update');
            titleText = '&nbsp;&nbsp;'+lang('Edit Product Group');
            productGroupId = 0;
            productCount = 0;

        } else {
            buttonText = lang('Save');
            titleText = '&nbsp;&nbsp;'+lang('Add Product Group');
        }

        // Yes / No options for dropdowns
        var yesno = [
                     ['Hosting'],
                     ['Domain'],
                     //['SSL'],
                     ['General']
                    ];

        // Dropdown box to allow DNS records
        groupType = new Ext.form.ComboBox({
            fieldLabel:"<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='Set the Type of this product group:<br><b>Hosting:</b> Any hosting related products that require server plugins.<br><b>Domain:</b> Any Domain related products that require registrar plugins.<br><b>SSL:</b> Any SSL related products that require SSL provisioning.<br><b>General:</b> Any generic product that does not fall under one of the above types.'>" + lang("Type") + "</span>",
            anchor:'100%',
            hiddenName: 'ProductGroupType',
            store: new Ext.data.SimpleStore({
                fields: ['ProductGroupType'],
                data : yesno
            }),
            displayField: 'ProductGroupType',
            mode: 'local',
            triggerAction: 'all',
            editable: false,
            value: "Hosting",
            id:"groupType"
        });


        testFields = [{
            id:'id',
            name: 'id',
            value: '0',
            xtype: "hidden",
            hidden:true
        },{
            fieldLabel: lang('Name'),
            id:'name',
            name: 'name',
            xtype: "textfield",
            allowBlank:false,
            anchor:'100%'
        },{
            layout:'column',
            items:[{
                columnWidth:.4,
                layout: 'form',
                items: [groupType]
            },{
                columnWidth:.4,
                layout: 'form',
                items: [{
                        xtype:'checkbox',
                        name: 'inSignup',
                        style: {
                            marginLeft: '80px',
                            marginTop: '20px'
                        },
                        id: 'inSignup',
                        hideLabel:true,
                        boxLabel: lang('Show In Signup')
                    }]
            },{
                columnWidth:.2,
                layout: 'form',
                items: [{
                    fieldLabel:"<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='Use this setting to change the order in which the Product Groups are displayed on the signup page. <br><b>Groups are displayed in ascending order e.g. 1-10.'>" + lang("Group Order") + "</span>",
                    id:'groupOrder',
                    name: 'groupOrder',
                    xtype: "textfield",
                    allowBlank:false,
                    value:1,
                    anchor:'80%'
                }]
            }]
        },{
            fieldLabel: lang('Description'),
            id:'desc',
            name: 'desc',
            xtype: "htmleditor",
            allowBlank:false,
            value: "",
            height: 200,
            anchor:'100%'
        },{
            id:'signupurl',
            name: 'signupurl',
            fieldLabel: lang('Signup URL'),
            xtype: "label",
            hideLabel: true,
            hidden:true,
            anchor:'98%',
            html: lang('Signup URL') + ": "
        }];

        simpleForm = new Ext.FormPanel({
            labelAlign: 'top',
            frame:true,
            hideBorders:true,
            shadow:false,
            floating:false,
            autoHeight:true,
            title: '',
            bodyStyle:'padding:5px 5px 0',
            width: 450,
            items: [ testFields ]
        });


        win = new Ext.Window({
            layout:'fit',
            title:titleText,
            width:625,
            y:25,
            shadow:false,
            autoHeight:true,
            modal:true,
            closeAction:'hide',
            plain: true,
            buttonAlign: 'left',
            items: [simpleForm],
            fbar: [{
                        text: lang('Delete Product Group'),
                        hidden: true,
                        id:'deleteButton',
                        handler: function(){

                             if (productCount == 0) {
                                Ext.Msg.show
                                (
                                    {
                                        title : "Delete?" ,
                                        msg: "Are you sure you want to delete this product group?",
                                        buttons: Ext.Msg.YESNO,
                                        fn: function(btn, text)
                                        {
                                            if (btn == 'yes')
                                            {
                                                Ext.Ajax.request({
                                                   url: "index.php?fuse=admin&action=deleteProductGroup&id="+productGroupId,
                                                   success: onProductGroupDeleted,
                                                   failure: onProductGroupDeleted
                                                });
                                            }
                                        },
                                        icon: Ext.MessageBox.QUESTION
                                    }
                               );
                             }
                             else {
                                 Ext.MessageBox.alert(lang("Unable to Delete Product Group"),lang("It is not possible to delete a product group until all products assigned to the group have been removed or re-assigned to another group."));
                             }
                            //win.hide();
                        }
                    }
                ,'->',
                    {
                        text: lang('Cancel'),
                        handler: function(){
                            win.hide();
                        }
                    },
                    {
                        text: buttonText,
                        handler: function(){
                            simpleForm.getForm().submit({
                                clientValidation: true,
                                url: 'index.php?fuse=admin&action=saveProductGroup',
                                params: {
                                    insignup: Ext.getCmp('inSignup').getValue()//document.getElementById('inSignup').checked
                                },
                                success: function(form, action) {
                                   win.hide();

                                   // Repopulate the category combo
                                   populateCategoryCombo();

                                   // Load the grid
                                   FilterGrid(null,null);

                                },
                                failure: function(form, action) {
                                    switch (action.failureType) {
                                        case Ext.form.Action.CLIENT_INVALID:
                                            Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                                            break;
                                        case Ext.form.Action.CONNECT_FAILURE:
                                            Ext.Msg.alert('Failure', 'Ajax communication failed');
                                            break;
                                        case Ext.form.Action.SERVER_INVALID:
                                           Ext.Msg.alert('Failure', action.result.msg);
                                   }
                                }
                            });
                        }
                    }
            ],
            listeners: {
                hide: function() {simpleForm.destroy();}
            }
        });
        win.show(this);
    }

    function onProductGroupDeleted(responseObj){

        var data = Ext.util.JSON.decode(responseObj.responseText);
        if(data.error){
            if(data.message){
                Ext.MessageBox.alert(lang("Errors"), data.message);
            }else{
                Ext.MessageBox.alert(lang("Errors"), "There was an error performing this action");
            }
            return;
        }else if(data.message){
            msg(data.message,"");
        }else{
            msg(lang("Action have been performed"),"");
        }

        // Re-filter the grid & the dropdown
        FilterGrid('group', '-1');
        populateCategoryCombo();

        // Select -All- from the dropdown so it looks like we've reset
        productfiltercombo.setValue(' - All -');
        
        // Hide the window
        win.hide();

    }


    // Load the default fields
    function loadFields(id){
        simpleForm.getForm().load({
            url: 'index.php?fuse=admin&action=getProductGroup&groupId=' + id,
            params: {
       			foo:'bar'
       		},
            waitMsg:lang('Loading'),
            success: function(form, action) {
                simpleForm.findById("signupurl").setVisible(true);
                var response = Ext.util.JSON.decode(action.response.responseText);
                document.getElementById("signupurl").innerHTML = lang('Signup URL') + ": <a href='" + response.data.signupurl + "' target='_blank'>" + response.data.signupurl + "</a>";
                Ext.getCmp("inSignup").setValue(response.data.inSignup);

                // Check if we can delete this group and set things up accordningly
                if(response.data.canDelete == 1) {
                    Ext.getCmp("deleteButton").setVisible(true);
                } else {
                    Ext.getCmp("groupType").disable();
                }
            },
            failure: function(form, action) {Ext.MessageBox.alert(lang("Errors"), "There was an error performing this action.");}

        });

    }

    // Not sure what this does yet
    function setForNewEntry(){

    }
});


function editProductGroup(id, count) {
    productGroupWin.CreateWindow(true,id);
    productGroupWin.LoadFields(id);
    productCount = count;
    productGroupId = id;
}
function addProductGroup() {
    productGroupWin.CreateWindow(false, '-1');
    productGroupWin.SetForNewEntry();
}