

Ext.namespace('ClientExec'); //define namespace with some 'name'


ClientExec.ProductGroupSettings = function(){
    
    var hideDelete = false;
    var productGroupId = 0;
    var productCount=0;
    var ProductGroupWin;
    var pgWin;
    var welcomeEmailFieldSet;
    var detailsFieldSet;
    var domainFieldSet;
    var simpleForm;
    var store;
    var update = false;
   

    function ProductGroupWindow(update){
        if(this instanceof ProductGroupWindow){
            //this.update = update;
            this.CreateWindow = createWindow;
            this.LoadFields = loadFields;
            this.SetForNewEntry = setForNewEntry;
        }else{
            return new TableTypeWindow();
        }
    }
    
    function renderProductGroupName(value,p,record){
        var link = "<a href='javascript:ClientExec.ProductGroupSettings.editProductGroup(" + record.data.id + "," + record.data.productCount + ");'>" + record.data.name + "</a>";
        return link;
    }

    function createProductGroupsGrid(){
        store = new Ext.data.JsonStore({
                id: "gridstore",
                root: 'productGroups',
                idProperty: 'id',
                remoteSort: true,
                fields: [
                        'id','name','activeCount', 'inactiveCount','productCount','showInSignup'
                ],
                // load using script tags for cross domain, if the data in on the same domain as
                // this page, an HttpProxy would be better
                proxy: new Ext.data.HttpProxy({
                        url: 'index.php?fuse=admin&action=Admin_GetProductGroups'
                })
            });
        
        store.load();
        
    // create the Grid
        var grid = new Ext.grid.GridPanel({
            id: "gridProductGroups",
            el: 'product-types',
            store: store,
            columns: [
                {id:'id',header: 'ID', width:20, hidden:true,sortable: false, dataIndex: 'id'},
                {id:'name',header: 'Name', width: 160, sortable: false, renderer: renderProductGroupName, dataIndex: 'name'},
                {header: '# Products', width: 45, align:'center',sortable: false, dataIndex: 'productCount'},
                {header: '# Active packages', width: 55, align:'center',sortable: false, dataIndex: 'activeCount'},
                {header: '# Inactive packages', width: 55, align:'center', sortable: false, dataIndex: 'inactiveCount'},
                {header: 'In Signup', width: 55, align:'center', sortable: false, dataIndex: 'showInSignup'}
            ],
            autoExpandColumn: 'name',
            // config options for stateful behavior
            stateful: true,
            stateId: 'grid',
            viewConfig: {
                forceFit:true,
                enableRowBody:true,
                emptyText: lang("There are no product groups available"),
                scrollOffset:1
            },
            columnLines: true,
            autoHeight:true,
            title: '',
            iconCls: 'icon-grid',
            enableDragDrop    : true,
            ddGroup     : 'myGridDD',
            dragConfig : {
                containerScroll : true
            }
        });
    
        var dropTargetCfg = {

            ddGroup         : 'myGridDD',
            onContainerOver : function(ddSrc, evtObj, ddData) {
                var grid        = ddSrc.view.grid;
                var targetDiv   = evtObj.getTarget();
                var targetIndex = grid.getView().findRowIndex(targetDiv);
                this.clearDDStyles(ddSrc);

                // is this a row?
                if (targetIndex !== false) {
                    var targetRow        = grid.getView().getRow(targetIndex);
                    var targetRowEl      = Ext.get(targetRow);
                    var targetRowHeight  = targetRowEl.getHeight();
                    var targetRowTop     = targetRowEl.getY();
                    var targetRowCtr     = targetRowTop + Math.floor(targetRowHeight / 2);
                    var mouseY           = evtObj.getXY()[1];

                    // below
                    if (mouseY >= targetRowCtr) {
                        this.point = 'below';
                        targetRowEl.addClass('gridRowInsertBottomLine');
                        targetRowEl.removeClass('gridRowInsertTopLine');
                    }
                    // above
                    else if (mouseY < targetRowCtr) {
                        this.point = 'above';
                        targetRowEl.addClass('gridRowInsertTopLine');
                        targetRowEl.removeClass('gridRowInsertBottomLine')
                    }
                    this.overRow = targetRowEl;
    //                this.targetIndex = targetIndex;
                }
                else if (targetIndex === false) {
                    targetIndex =  grid.store.getCount();
                }
                this.targetIndex = targetIndex;

                grid.body.addClass('gridBodyNotifyOver');

                return 'x-dd-drop-ok';
            },
            notifyOut : function(ddSrc) {
                var grid        = ddSrc.view.grid;
                grid.body.removeClass('gridBodyNotifyOver');
                this.clearDDStyles(ddSrc);
                delete this.point;
                delete this.targetIndex;
                return true;
            },
            clearDDStyles : function(ddSrc) {
                var grid        = ddSrc.view.grid;
                if (this.overRow) {
                    this.overRow.removeClass('gridRowInsertBottomLine');
                    this.overRow.removeClass('gridRowInsertTopLine');
                }
                grid.body.removeClass('gridBodyNotifyOver');
            },
            notifyDrop  : function(ddSrc, evtObj, ddData){
                var grid        = ddSrc.view.grid;
                var store       = grid.store;
                var records     = ddSrc.dragData.selections;
                var origIndex   = store.indexOf(records[0]);
                var targetIndex = this.targetIndex;

                if (typeof targetIndex === 'boolean' && targetIndex === false) {
                    targetIndex = store.getCount();
                }

                Ext.each(records, store.remove, store);

                if (origIndex < targetIndex && this.point == 'above') {
                    targetIndex--;
                }
                else if (origIndex > targetIndex && this.point == 'below') {
                    targetIndex++;
                }

                if (targetIndex > store.getCount()) {
                    targetIndex = store.getCount();
                }

                store.insert(targetIndex, records);

                this.clearDDStyles(ddSrc);
                getRowIds();
                Ext.Ajax.request({
                    url: 'index.php?fuse=admin&action=Admin_ReorderProductGroups',
                    method: 'POST',
                    success: function(xhr) {},
                    params: { ids: Ext.util.JSON.encode(getRowIds())}
                });

                return true;
            }
        };

        var leftGridDropTarget   = new Ext.dd.DropZone(grid.el, dropTargetCfg);
        
            // render the grid to the specified div in the page
        grid.render();

    }

    function getRowIds(){

        var arrayofids = new Array();
        for(x=0;x<store.getCount();x++){
            arrayofids[x] = store.getAt(x).get('id');

        }
	    return arrayofids;
    }

    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"),"");
        }

        //get the grid if there is one
        //if we are in the escalation rules view
        //if not then skip
        //debugger;
        grid = Ext.getCmp("gridProductGroups");
        if(grid!=null){
            grid.getStore().load({params:{start:0}});
            //toggleButtons(0);
        }
        //etStore().load({params:{start:0}});
        win.hide();

    }
    function validateFields(){
        var message = "";
        //var temp = Ext.getCmp("htmlemail").getValue().replace("<br>","").replace("​​​","");
        if (Ext.getCmp("htmlemail").getValue()=="") {

            message += "The Welcome Email HTML Field must have a value.<br>";
        }

//        if ((!Ext.getCmp("textemail").value) || Ext.getCmp("textemail").value==""){
//
//            message += "The Welcome Email Text Field must have a value.<br>";
//        }

        if (message!=""){

            Ext.MessageBox.alert("Errors",message);
            return false;
        }else{
            return true;
        }
        //if (Ext.getCmp("textemail").getValue=="")return false;


    }
    function createWindow(update) {
        if (update) {
            requesturl = 'index.php?fuse=admin&action=Admin_EditProductGroup';
            buttonText = lang('Update');
            titleText = '&nbsp;&nbsp;'+lang('Edit Product Group');
        } else {
            requesturl = 'index.php?fuse=admin&action=Admin_AddProductGroup';
            buttonText = lang('Save');
            titleText = '&nbsp;&nbsp;'+lang('Add Product Group');
        }

        Ext.override(Ext.form.HtmlEditor,{
            getValue : function() {
            this[this.sourceEditMode ? 'pushValue' : 'syncValue']();
            var value = Ext.form.HtmlEditor.superclass.getValue.call(this);
            return (Ext.isEmpty(value.replace(/<[a-zA-Z/][^>]*>/igm, ' ').trim())) ? '' : value;
        }


        });
        
        welcomeEmailFieldSet = new Ext.form.FieldSet({
            title: lang('Welcome E-mail'),
            anchor: '100%',
            items: [{
                fieldLabel: lang('E-mail Subject'),
                id:'emailsubject',
                name: 'emailsubject',
                xtype: "textfield",
                allowBlank:false,
                anchor:'98%'
            },{
                xtype: 'tabpanel',
                activeTab: 0,
                height: 150,
                anchor: '98%',
                plain: true,
                items:[{
                    cls: 'x-plain',
                    title: lang('HTML E-mail'),
                    layout:'fit',
                    items: {
                        xtype:'htmleditor',
                        id: 'htmlemail',
                        name: 'htmlemail'                        
                    }
                },{
                    cls: 'x-plain',
                    title: lang('Plain-Text E-mail'),
                    layout:'fit',
                    items: {
                        xtype: 'textarea',
                        id: 'textemail',
                        name: 'textemail',
                        allowBlank: false,
                        validationEvent: false
                    }
                }
                
                ]
            }]
        });
        
        detailsFieldSet = [{
            id:'id',
            name: 'id',
            value: '0',
            xtype: "hidden",
            hidden:true
        },{
            fieldLabel: lang('Name'),
            id:'name',
            name: 'name',
            xtype: "textfield",
            allowBlank:false,
            anchor:'98%'
        },{
            fieldLabel: lang('Description'),
            id:'desc',
            name: 'desc',
            xtype: "htmleditor",
            allowBlank:false,
            value: "",
            height: 100,
            anchor:'100%'
        },{
            id:'signupurl',
            name: 'signupurl',
            fieldLabel: lang('Signup URL'),
            xtype: "label",
            hideLabel: true,
            anchor:'98%',
            html: lang('Signup URL') + ": "
        }];
        
        domainFieldSet = new Ext.form.FieldSet({
            checkboxToggle: true,
            collapsed: false,
            id: 'domainenabled',
            name: 'domainenabled',
            title: lang('Enable Domain Options'),
            items: [{
                xtype: 'checkboxgroup',
                hideLabel: true,
                items: [
                    {
                        fieldLabel: '',
                        hideLabel:true,
                        xtype: 'checkbox',
                        boxLabel: 'Allow Registration',
                        id: 'regDomain',
                        name: 'regDomain'
                    },{
                        fieldLabel: '',
                        hideLabel:true,
                        labelSeparator: '',
                        xtype: 'checkbox',
                        boxLabel: 'Allow Self-Manage',
                        id: 'selfDomain',
                        name: 'selfDomain'
                    },{
                        fieldLabel: '',
                        hideLabel:true,
                        labelSeparator: '',
                        xtype: 'checkbox',
                        boxLabel: 'Allow Transfer',
                        id: 'transDomain',
                        name: 'transDomain'
                    },{
                        fieldLabel: '',
                        hideLabel:true,
                        labelSeparator: '',
                        xtype: 'checkbox',
                        boxLabel: 'Allow Subdomain',
                        id: 'subDomain',
                        name: 'subDomain',
                        listeners:{	
                            check: function(checkbox, checked){ 
                                var field = simpleForm.getForm().findField("subdomainbase");
                                if (checked) {
                                    field.enable();
                                } else {
                                    field.disable();
                                }
                            }	
                        }
                    }
                ]
            },{
                fieldLabel: lang('Subdomain'),
                id:'subdomainbase',
                name: 'subdomainbase',
                xtype: "textfield",
                allowBlank:false,
                anchor:'98%',
                disabled: true
            }]    
        });
        
            
        
        simpleForm = new Ext.FormPanel({
            labelAlign: 'top',
            frame:true,
            hideBorders:true,
            shadow:false,
            floating:false,
            autoHeight:true,
            title: '',
            bodyStyle:'padding:5px 5px 0',
            width: 550,
            items: [ detailsFieldSet, welcomeEmailFieldSet, domainFieldSet ]
        });
        
        win = new Ext.Window({
            layout:'fit',
            title:titleText,
            width:650,
            y:25,
            shadow:false,
            autoHeight:true,
            modal:true,
            closeAction:'hide',
            plain: true,
            items: [simpleForm],
            fbar: [
                    {
                        xtype:'checkbox',
                        name: 'inSignup',
                        id: 'inSignup',
                        hideLabel:true,
                        boxLabel: lang('Show In Signup'),
                        handler: function(cb,checked){
                            if(checked){
                                //createinvoicechecked = 1;
                            }else{
                                //createinvoicechecked = 0;
                            }
                        }
                    },{
                        text: lang('Cancel'),
                        handler: function(){
                            win.hide();
                        }
                    },
                    {
                        text: buttonText,
                        handler: function(){

                                if (validateFields()){
                                simpleForm.getForm().submit({
                                    clientValidation: true,
                                    url: requesturl,
                                    params: {
                                        insignup: Ext.getCmp('inSignup').getValue()//$('inSignup').checked
                                    },
                                    success: function(form, action) {
                                       win.hide();
                                       store.load();
                                    },
                                    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);
                                       }
                                    }
                                });
                            }
                        }
                    },{
                        text: lang('Delete'),
                        hidden: !update,
                        handler: function(){

                             if (productCount == 0) {
                                Ext.Msg.show
                                (
                                    {
                                        title : "Delete?" ,
                                        msg: "Are you sure you want to delete this product group?",
                                        buttons: Ext.Msg.YESNOCANCEL,
                                        fn: function(btn, text)
                                        {
                                            if (btn == 'yes')
                                            {
                                                new Ajax.Request("index.php?fuse=admin&action=Admin_DeleteProductGroup",
                                                    {
                                                        parameters: 'productGroupId=' + encodeURIComponent(productGroupId),
                                                        onComplete: onProductGroupDeleted

                                                    }
                                                );
                                            }
                                        },
                                        icon: Ext.MessageBox.QUESTION

                                    }
                               );
                             }
                             else {

                                 Ext.MessageBox.alert(lang("Can't Delete Product Group"),lang("You may not delete a product group until all products assigned to the group have been removed or re-assigned to another group."));

                             }
                            win.hide();
                        }
                    }
            ],
            listeners: {
                hide: function() { simpleForm.destroy(); }
            }
        });
        
        simpleForm.getForm().reset();
        win.show(this);
    }
    
    function loadFields(id){
        
        simpleForm.getForm().load({
            url: 'index.php?fuse=admin&action=Admin_GetProductGroup',
            waitMsg:lang('Loading'),
            success: function(form, action) {
                
                // special loading rules
                var response = Ext.util.JSON.decode(action.response.responseText);
                $("signupurl").innerHTML = lang('Signup URL') + ": <a href='" + response.data.signupurl + "' target='_blank'>" + response.data.signupurl + "</a>";
                //$("inSignup").checked = response.data.inSignup == "checked"?true:false;
                Ext.getCmp("inSignup").setValue(response.data.inSignup);

                if (response.data.regDomain != null){
                    Ext.getCmp("regDomain").setValue(response.data.regDomain);
                }

                Ext.getCmp("selfDomain").setValue(response.data.selfDomain);

                Ext.getCmp("transDomain").setValue(response.data.transDomain);
                
                Ext.getCmp("subDomain").setValue(response.data.subDomain);
                simpleForm.getForm().findField("subdomainbase").reset();
                if (response.data.subDomain) {
                    simpleForm.getForm().findField("subdomainbase").enable();
                    simpleForm.getForm().findField("subdomainbase").setValue(response.data.subdomainbase);
                }
                if (response.data.ProductGroupType != 2)
                    Ext.getCmp('domainenabled').collapse();
                
            },
            failure: function(form, action) {alert('failure');},
            params: {id: id}
        });
        
    }
    
    function setForNewEntry(){
        Ext.getCmp('domainenabled').collapse();
        
        
        Ext.getCmp('signupurl').setDisabled(true);
        Ext.getCmp('signupurl').setVisible(false);
        
        simpleForm.getForm().findField("subdomainbase").disable();
    }

    function  addProductGroup() {
        update = false;
        ProductGroupWin.CreateWindow(false);
        ProductGroupWin.SetForNewEntry();

    }

    return {

             init: function() {

              ProductGroupWin = new ProductGroupWindow();

                // create "add" button used above the product list grid
                 var addProdGroup = new Ext.Button(
                    {

                        id:"addProductGroup",
                        renderTo:"addproductgroup",
                        text: lang('Add Product Group'),
                        iconAlign: 'left',
                        handler: addProductGroup

                       
                    });
                    
               createProductGroupsGrid()
            },

            editProductGroup: function(id,prodCount)
            {
                update = true;
                productGroupId = id;
                productCount = prodCount;

                ProductGroupWin.CreateWindow(true);
                ProductGroupWin.LoadFields(id);
            }

    }



}();

Ext.onReady(ClientExec.ProductGroupSettings.init, ClientExec.ProductGroupSettings, true);

