// Reference local blank image to prevent link back to extjs.com

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

ClientExec.AddonSettings = function(){

        /* Private Variables */
        var myMask;
        var addonId=0;
        var addonWin;
        var update = false;
        var windowWidth = 760;
        var windowHeight = 490;
        var win;

        var frmAddon;
        var addonPrice;
        var addonPricesStore;
        var addonPricesRowSelectionModel;
        var addonPricesGrid;
        var addonPricesRowEditor;
        var addonPluginVariableStore;

        /* Private Methods */
        function validateFields(fld,msg,allmsgs){
            var newline = "<br/>";
            if (!fld.validate()){
                if (allmsgs.str!=''){

                    allmsgs.str += newline + lang(msg);
                }
                else allmsgs.str = lang(msg);
            }
        }

        function addonGetNextAddonPricesOrder(){

            //debugger;
            var data = addonPricesStore.data;
            var highestorder = 0;
            for(var i=0;i<data.length;i++){

                var row = data.items[i].data;
                if (row.sortkey > highestorder){
                        highestorder = row.sortkey;
                }
            }
            //debugger;
            return highestorder + 1;

        }

        function btnAddonPricesAdd_Click(doEdit){

            if(selectedProductGroupType == 3){
                priceforce = 1;
            }else{
                priceforce = 0;
            }

            var e = new addonPrice({
            //deleteOk: doEdit?'1':'No',
            deleteOk: '1',
            id: '',
            packageaddon_id: addonId,
            sortkey: addonGetNextAddonPricesOrder(),
            detail: doEdit?'':'None',
            plugin_var_value: '',
            price0: '',
            price1: '',
            price1_force: priceforce,
            price3: '',
            price3_force: priceforce,
            price6: '',
            price6_force: priceforce,
            price12: '',
            price12_force: priceforce,
            price24: '',
            price24_force: priceforce

            });
            addonPricesRowEditor.stopEditing();
            addonPricesStore.insert(addonPricesStore.data.length, e);
            addonPricesGrid.getView().refresh();
            addonPricesGrid.getSelectionModel().selectRow(0);
            if (doEdit){
                addonPricesRowEditor.startEditing(addonPricesStore.data.length-1);
            }

       }

        function btnAddonPricesDelete_Click(){

            addonPricesGrid.stopEditing();
            addonPricesRowEditor.stopEditing();
            var s = addonPricesGrid.getSelectionModel().getSelections();

            if(s.length >= addonPricesStore.data.length){
                Ext.MessageBox.alert("Option Mandatory","You can not delete all the options from an addon. You must have at least one option.");
            }else{
                for(var i = 0, r; r = s[i]; i++){
                    var index = addonPricesStore.indexOf(r);

                    if(r.data.deleteOk == "1"){
                        addonPricesStore.remove(r);
                    }else{
                        Ext.MessageBox.alert("Addon Price In Use","This price is in use. You can not delete this addon price until you first<br>change the following domain\\package to use another option: <br>" + r.data.deleteOk);
                    }
                }

                addonPricesGrid.getView().refresh();
            }
        }

        function addonPricesHTMLEncode(row){

            row.detail = encodeURIComponent(row.detail);
            row.plugin_var_value = encodeURIComponent(row.plugin_var_value);
            return row;

        }

        function saveUpdateAddon(type,url,waitMessage){

            var message = {str:''};

            validateFields(Ext.getCmp('txtaddonname'),"Addon Name",message);
            validateFields(lovComboProductGroups,"Product Groups",message);

            if(message.str != ''){

                Ext.MessageBox.alert(lang("Errors"), lang("The following form field(s) were incomplete or incorrect") + ":<br><br>" + message.str + "<br><br>" + lang("Please complete or correct the form and submit again."));
                return;

            }else { // valid - submit


                addonPricesStore.commitChanges();

                if (addonPricesStore.data.length>0){
                    var addonPricesArray = new Array(addonPricesStore.data.length);
                    for(var i=0;i<addonPricesStore.data.length;i++){

                        var row = addonPricesStore.data.items[i].data;
                        row.sortkey = i;
                        addonPricesStore.commitChanges();
                        addonPricesArray[i] = addonPricesHTMLEncode(row);
                    }
                }

                myMask.show();
                var pluginvar = "";
                if (Ext.getCmp('txtpluginvariableavcustom').hidden){
                    pluginvar = Ext.getCmp('cbopluginvar').getValue();
                }else{
                    pluginvar = Ext.getCmp('txtpluginvariableavcustom').getValue();
                }

                Ext.Ajax.request({
                    url: url,
                    params: {
                        name: encodeURIComponent(Ext.getCmp('txtaddonname').getValue()),
                        description:  encodeURIComponent(Ext.getCmp('txtaddondescription').getValue()),
                        //taxable: encodeURIComponent(Ext.getCmp('ckaddontaxable').getValue()),
                        plugin_var: encodeURIComponent(pluginvar),

                        productgroup_ids: encodeURIComponent(Ext.getCmp('lovcboproductgroups').getValue()),
                        addonid: addonId,
                        addonprices: Ext.util.JSON.encode(addonPricesArray)
                    },
                    success: function(respObj){
                        //if (!Ext.isIE) console.log(respObj);
                        if (respObj.status==200){

                            grid = Ext.getCmp("addonsGrid");
                            if(grid!=null){
                                grid.getStore().load({params:{start:0}});

                            }
                            win.close();
                        }
                        myMask.hide();

                    }
                });
            }

        }

        function createAddonUI(){

            Ext.override(Ext.ux.grid.RowEditor,{
                 verifyLayout: function(force){
                    if(this.el && (this.isVisible() || force === true)){
                        var row = this.grid.getView().getRow(this.rowIndex);
                        this.setSize(Ext.fly(row).getWidth(), Ext.isIE ? Ext.fly(row).getHeight() + 9 : undefined);
                        var cm = this.grid.colModel, fields = this.items.items;
                        for(var i = 0, len = cm.getColumnCount(); i < len; i++){
                            if(!cm.isHidden(i)){
                                var adjust = 0;
                                if(i === (len - 1)){
                                    adjust += 3; // outer padding
                                } else{
                                    adjust += 2; /* MJL -  adjusted value from 1 to 2 which fixed issue with missaligned fields and with last field (Setup) being partially hidden*/
                                }
                                fields[i].show();
                                fields[i].setWidth(cm.getColumnWidth(i) - adjust);
                            } else{
                                fields[i].hide();
                            }
                        }
                        this.doLayout();
                        this.positionButtons();
                    }
                },
                onGridKey: function(e){
                    if(e.getKey() === e.ENTER && !this.isVisible()){
                        var r = this.grid.getSelectionModel().getSelected();
                        if(r){
                            var index = this.grid.store.indexOf(r);
                            //if (index>0){
                                this.startEditing(index);
                                e.stopPropagation();
                            //}else{
                                //Ext.MessageBox.alert("Editing Disabled", "You may not edit the default option for an addon.")
                            //}

                        }
                    }
                },
                onRowClick: function(g, rowIndex, e){
                    if(this.clicksToEdit == 'auto'){
                        var li = this.lastClickIndex;
                        this.lastClickIndex = rowIndex;
                        if(li != rowIndex && !this.isVisible()){
                            return;
                        }
                    }
                    //if (rowIndex>0){
                        this.startEditing(rowIndex, false);
                        this.doFocus.defer(this.focusDelay, this, [e.getPoint()]);
                    //}else{
                        //Ext.MessageBox.alert("Editing Disabled", "You may not edit the default option for an addon.")
                    //}
                },
                onRowDblClick: function(g, rowIndex, e){
                    //if (rowIndex>0){
                        this.startEditing(rowIndex, false);
                        this.doFocus.defer(this.focusDelay, this, [e.getPoint()]);
                    //}else{
                        //Ext.MessageBox.alert("Editing Disabled", "You may not edit the default option for an addon.")
                    //}

                }

            });

            //addon store
            addonPluginVariableStore = new Ext.data.JsonStore({
                id: "addonPluginVariableStore",
                root: 'addons',
                totalProperty: 'totalcount',
                idProperty: 'plugin_var',
                remoteSort: true,
                fields: [
                        'plugin_var','name','description','available_in'
                ],
                // 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=getAddonVariables&productType='+selectedProductGroupType
                })
            });
            
            addonPluginVariableStore.on("load",function(){
                var isCustom =true;
                pluginvar = Ext.getCmp('cbopluginvar').getValue();
                for (var i=0;i<addonPluginVariableStore.data.length;i++) {
                    var item =addonPluginVariableStore.data.items[i];
                    var tempRow = item.data;
                    if (tempRow.plugin_var==pluginvar){
                        isCustom = false;
                        Ext.getCmp('cbopluginvar').fireEvent('select',null,item,null);
                    }
                }
                if (isCustom) {
                    Ext.getCmp('cbopluginvar').setValue('CUSTOM');
                    Ext.getCmp('txtpluginvariableavcustom').setValue(pluginvar);
                    Ext.getCmp('txtpluginvariableavcustom').setVisible(true);
                    Ext.getCmp('lblpluginvariableavcustom').setVisible(true);
                } else {
                    pluginvar = Ext.getCmp('cbopluginvar').getValue();
                    Ext.getCmp('cbopluginvar').setValue(pluginvar);
                }
            });
            //end addon store

            addonPricesRowEditor = new Ext.ux.grid.RowEditor({
                id: "addonRowEditor",
                saveText: 'Update'
            });

            addonPrice = Ext.data.Record.create([
                {
                    name: "deleteOk",
                    type: "string"

                },
                {
                    name: "id",
                    type: "int"

                },
                {
                    name: "packageaddon_id",
                    type: "int"
                },
                {
                    name: "sortkey",
                    type: "int"

                },
                {
                    name: "detail",
                    type: "string"

                },
                {
                    name: "plugin_var_value",
                    type: "string"

                },
                {
                    name: "price0",
                    type: "string"
                },
                {
                    name: "price1",
                    type: "string"
                },
                {
                    name: "price1_force",
                    type: "bool"
                },
                {
                    name: "price3",
                    type: "string"
                },
                {
                    name: "price3_force",
                    type: "bool"
                },
                {
                    name: "price6",
                    type: "string"
                },
                {
                    name: "price6_force",
                    type: "bool"
                },
                {
                    name: "price12",
                    type: "string"
                },
                {
                    name: "price12_force",
                    type: "bool"
                },
                {
                    name: "price24",
                    type: "string"
                },
                {
                    name: "price24_force",
                    type: "bool"
                }


            ]);

            addonPricesStore = new Ext.data.JsonStore({
                successProperty: "success",
                idProperty: "id",
                fields: addonPrice,
                root: "theAddonPrices",
                totalProperty: "totalcount",
                autoSave: false,
                batch: true,
                sortInfo: {field: 'sortkey', direction: 'ASC'},
                url: 'index.php?fuse=admin&action=Admin_GetAddonPrices',
                baseParams: {addonid:addonId},
                listeners: {
                    load: function(store,records,options){
                        //if (!Ext.isIE) console.log(records);
                    }
                }
            });


           addonPricesRowSelectionModel = new Ext.grid.RowSelectionModel({
                    singleSelect: false

           });

           productGroupsStore = new Ext.data.JsonStore({

                root:           'productGroups', //'staff',
                totalProperty:  'totalcount',
                idProperty:     'id',
                remoteSort:     true,
                baseParams:     {
                                    groupsonly:1
                                },
                fields:         [
                                    'id',
                                    'name'
                                ],
                proxy:          new Ext.data.HttpProxy({
                                    url:  'index.php?fuse=admin&action=Admin_GetProductGroups&groupsonly=1&groupType=' + selectedProductGroupType
                                })
            });

            productGroupsStore.setDefaultSort('id', 'asc');

            productGroupsStore.load();

            productGroupsStore.on('load',function(){
                    

            });

            lovComboProductGroups = new Ext.ux.form.LovCombo({
                id:'lovcboproductgroups'
                ,beforeBlur : Ext.emptyFn
                ,width: 200
                ,x: 5
                ,y: 68
                ,anchor: "100%"
                ,hideOnSelect:false
                ,maxHeight:200
                ,store: productGroupsStore
                ,triggerAction:    'all'
                ,lazyRender:       false
                ,mode:             'local'
                ,validationEvent:  false
                ,allowBlank: false
                ,forceSelection: true
                ,valueField:       'id'
                ,displayField:     'name'

            });

            lovComboProductGroups.on('select',function(combo,record,index){
                if (record.data.name=="All Product Groups"){
                    if (record.data.checked){
                        lovComboProductGroups.deselectAll();
                        lovComboProductGroups.setValue(-1);
                    }
                }
                else {
                    if (record.data.checked){
                        var allIsChecked = false;
                        var checkedItems = "";
                        for(var i=0;i<lovComboProductGroups.getStore().data.length;i++){
                            var row = lovComboProductGroups.getStore().data.items[i].data;
                            if (row.checked){
                                if (row.name == "All Product Groups"){
                                    allIsChecked = true;
                                }else {
                                      if (i==1) checkedItems += row.id;
                                      else checkedItems += "," + row.id;
                                }
                            }
                        }
                        if (allIsChecked){
                            lovComboProductGroups.deselectAll();
                            lovComboProductGroups.setValue(checkedItems);

                        }
                    }
                }

            });

            addonPricesGrid = new Ext.grid.GridPanel({
                id: "productaddongrid",
                sm: addonPricesRowSelectionModel,
                store: addonPricesStore,
                mode: 'local',
                width: 600,
                region:'center',
                anchor: "100%,100%",
                clicksToEdit: 1,
                plugins: [addonPricesRowEditor],
                tbar: [{
                    text: 'Add Addon Details',
                    handler: function(){
                        btnAddonPricesAdd_Click(true);
                    }
                },{
                    ref: '../removeBtn',
                    text: 'Remove Addon Details',
                    disabled: true,
                    handler: function(){
                        btnAddonPricesDelete_Click();
                    }
                }],
                columns: [
                {
                    header: 'Price Detail',
                    dataIndex: 'detail',
                    width: 90,
                    sortable: true,
                    editor: {
                        xtype: 'textfield',
                        allowBlank: false
                    }
                },{
                    header: 'Monthly',
                    dataIndex: 'price1',
                    width: 65,
                    sortable: true,
                    editor: {
                        xtype: 'numberfield'
                    }
                },{
                    xtype: 'booleancolumn',
                    header: '...',
                    dataIndex: 'price1_force',
                    align: 'center',
                    width: 28,
                    trueText: 'Yes',
                    falseText: 'No',
                    editor: {
                        xtype: 'checkbox'
                    }
                },{
                    header: 'Quarterly',
                    dataIndex: 'price3',
                    width: 70,
                    sortable: true,
                    editor: {
                        xtype: 'numberfield'
                    }
                },{
                    xtype: 'booleancolumn',
                    header: '...',
                    dataIndex: 'price3_force',
                    align: 'center',
                    width: 28,
                    trueText: 'Yes',
                    falseText: 'No',
                    editor: {
                        xtype: 'checkbox'
                    }
                },{
                    header: 'Semiannual',
                    dataIndex: 'price6',
                    width: 85,
                    sortable: true,
                    editor: {
                        xtype: 'numberfield'
                    }
                },{
                    xtype: 'booleancolumn',
                    header: '...',
                    dataIndex: 'price6_force',
                    align: 'center',
                    width: 28,
                    trueText: 'Yes',
                    falseText: 'No',
                    editor: {
                        xtype: 'checkbox'
                    }
                },{
                    header: 'Annual',
                    dataIndex: 'price12',
                    width: 60,
                    sortable: true,
                    editor: {
                        xtype: 'numberfield'
                    }
                },{
                    xtype: 'booleancolumn',
                    header: '...',
                    dataIndex: 'price12_force',
                    align: 'center',
                    width: 28,
                    trueText: 'Yes',
                    falseText: 'No',
                    editor: {
                        xtype: 'checkbox'
                    }
                },{
                    header: '2 Year',
                    dataIndex: 'price24',
                    width: 55,
                    sortable: true,
                    editor: {
                        xtype: 'numberfield'
                    }
                },{
                    xtype: 'booleancolumn',
                    header: '...',
                    dataIndex: 'price24_force',
                    align: 'center',
                    width: 28,
                    trueText: 'Yes',
                    falseText: 'No',
                    editor: {
                        xtype: 'checkbox'
                    }
                },{
                    header: 'Setup',
                    dataIndex: 'price0',
                    width: 60,
                    sortable: true,
                    editor: {
                        xtype: 'numberfield'
                    }
                },{
                    header: 'Plugin Value',
                    dataIndex: 'plugin_var_value',
                    width: 115,
                    id: 'plugin_var_value',
                    hidden: false,
                    sortable: true,
                    editor: {
                        xtype: 'textfield',
                        allowBlank: true

                    }
                }],
                enableDragDrop    : true,
                ddGroup     : 'myGridDD',
                dragConfig : {
                    containerScroll : true

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

                if (targetIndex == 0){
                    return;
                }
                // 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();
                }

                if (origIndex==0) targetIndex=0;
                store.insert(targetIndex, records);

                this.clearDDStyles(ddSrc);
                //addonsSetOrder();
//                Ext.Ajax.request({
//                    url: 'index.php?fuse=support&action=UpdateTicketTypesOrder',
//                    method: 'POST',
//                    success: function(xhr) {
//                    },
//                    failure: function() {
//                         alert("fail");
//                    },
//                    params: { ids: Ext.util.JSON.encode(getRowIds())
//                    }
//
//                });

                return true;
            }
        };

            addonPricesGrid.getSelectionModel().on('selectionchange', function(sm){
                addonPricesGrid.removeBtn.setDisabled(sm.getCount() < 1);
            });

           addonPricesGrid.on({
               render:{
                  scope: this,
                  fn: function() {
                     //load store after the grid is done rendering
                    //addonStore.load({waitMsg:"Loading Addons"});
                    if (!update) {
                        btnAddonPricesAdd_Click(false);
                        Ext.getCmp('cbopluginvar').setValue('NONE');
                        Ext.getCmp('txtaddonname').focus('',300);
                    }


                  }
               }
            })

            addonPricesGrid.on('viewready',function(grid){

                var leftGridDropTarget   = new Ext.dd.DropZone(addonPricesGrid.el, dropTargetCfg);
            });

            addonPricesStore.on('load',function(){



            });

        }

        function createFormUI() {

            if(selectedProductGroupType == 3){
                txtaddondescript = '*Tick checkboxs to show a price in signup. Prices left empty won\'t be shown, 0 will';
            }else{
                txtaddondescript = '*Prices left empty won\'t be shown, 0 will. Tick checkboxs to always show a price in signup regardless of the billing cycle';
            }

            frmAddon = new Ext.FormPanel({

                items: [
                         {
                            id: "productaddontabbordersouth",
                            region: "top",
                            layout: "border",
                            height: 400,
                            border: false,
                            defaults: {border: false},
                            items : [
                                {
                                 region: "north",
                                 height: 110 ,
                                 border: false,
                                 defaults: {border: false},
                                 items: [
                                            {
                                                layout: "column",
                                                border: false,
                                                defaults: {border: false},
                                                items: [
                                                        {
                                                            width: 360,
                                                            border: false,
                                                            labelAlign:     'top',
                                                            style: "padding-right: 5px",
                                                            items : [
                                                                    {
                                                                        xtype: "panel",
                                                                        height: 120,
                                                                        layout: "absolute",
                                                                        anchor: "100%,100%",
                                                                        style: "padding: 5px",
                                                                        border: false,
                                                                        items: [
                                                                            {
                                                                                xtype: "label",
                                                                                text: "Name",
                                                                                height: 20,
                                                                                width: 50,
                                                                                x: 5,
                                                                                y: 5
                                                                            },
                                                                           {
                                                                                id: "txtaddonname",
                                                                                xtype: "textfield",
                                                                                height: 20,
                                                                                x: 5,
                                                                                y: 23,
                                                                                name: "addonName",
                                                                                fieldLabel: "Name",
                                                                                anchor: "100%",
                                                                                validationEvent: false,
                                                                                allowBlank: false
                                                                            },
                                                                            {
                                                                                xtype: "label",
                                                                                x: 5,
                                                                                y: 51,
                                                                                width: 140,
                                                                                height: 20,
                                                                                text: "Product Groups",
                                                                                style: "padding-right: 5px"
                                                                                /*style: "font-weight: bold"*/
                                                                            },
                                                                            lovComboProductGroups
                                                                        ]
                                                                    }

                                                                    ]
                                                        },
                                                        {
                                                            width: 375,
                                                            items : [
                                                                    {
                                                                        xtype: "panel",
                                                                        height: 120,
                                                                        layout: "absolute",
                                                                        anchor: "100%,100%",
                                                                        style: "padding: 5px",
                                                                        border: false,
                                                                        items: [
                                                                            {
                                                                                xtype: "label",
                                                                                text: "Plugin Variable",
                                                                                height: 20,
                                                                                width: 100,
                                                                                x: 5,
                                                                                y: 3
                                                                            },
                                                                           {
                                                                                id: "cbopluginvar",
                                                                                xtype: "combo",
                                                                                height: 20,
                                                                                x: 5,
                                                                                y: 23,
                                                                                anchor: "100%",
                                                                                lazyRender: true,
                                                                                validationEvent:  false,
                                                                                triggerAction: "all",
                                                                                mode: 'remote',
                                                                                store:    addonPluginVariableStore,
                                                                                valueField:       'plugin_var',
                                                                                displayField:     'name',
                                                                                value:            'NONE',
                                                                                hiddenId:         'plugin_var',
                                                                                hiddenName:       'name',
                                                                                forceSelection:   true,
                                                                                editable:         false,
                                                                                listeners: {
                                                                                    select: function(combo,record,index){
                                                                                        //debugger;
                                                                                        var addon_ColumnModel = Ext.getCmp('productaddongrid').getColumnModel();
                                                                                        /*
                                                                                        var plugin_var_value_index = addon_ColumnModel.findColumnIndex('plugin_var_value');
                                                                                        if(record.data.plugin_var == "NONE"){
                                                                                            addon_ColumnModel.setHidden(plugin_var_value_index, true);
                                                                                        }else{
                                                                                            addon_ColumnModel.setHidden(plugin_var_value_index, false);
                                                                                        }*/

                                                                                        Ext.getCmp('pluginvariabledescription').setText(record.data.description);
                                                                                        if (record.data.available_in!=""){
                                                                                            Ext.getCmp('pluginvariableavailablein').setText('Available In: ' + record.data.available_in);
                                                                                        }
                                                                                        else {
                                                                                            Ext.getCmp('pluginvariableavailablein').setText('');
                                                                                        }
                                                                                        if (record.data.plugin_var=="CUSTOM") {
                                                                                            Ext.getCmp('txtpluginvariableavcustom').setVisible(true);
                                                                                            Ext.getCmp('lblpluginvariableavcustom').setVisible(true);
                                                                                        } else {
                                                                                            Ext.getCmp('txtpluginvariableavcustom').setVisible(false);
                                                                                            Ext.getCmp('lblpluginvariableavcustom').setVisible(false);
                                                                                        }
                                                                                    }
                                                                                }
                                                                            },
                                                                            {
                                                                                id: "pluginvariabledescription",
                                                                                xtype: "label",
                                                                                height: 40,
                                                                                x: 5,
                                                                                y: 50,
                                                                                anchor: "100%",
                                                                                text: '',
                                                                                style: 'text-align:center',
                                                                                border: true
                                                                            },
                                                                            {
                                                                                id: "pluginvariableavailablein",
                                                                                xtype: "label",
                                                                                height: 40,
                                                                                x: 5,
                                                                                y: 66,
                                                                                anchor: "100%",
                                                                                style: 'text-align:center',
                                                                                text: '',
                                                                                border: true
                                                                            },
                                                                            {
                                                                                id: "lblpluginvariableavcustom",
                                                                                xtype: "label",
                                                                                height: 20,
                                                                                hidden: false,
                                                                                x: 5,
                                                                                y: 51,
                                                                                anchor: "100%",
                                                                                text: 'Custom Plugin Variable Name',
                                                                                border: true
                                                                            },
                                                                            {
                                                                                id: "txtpluginvariableavcustom",
                                                                                xtype: "textfield",
                                                                                fieldLabel: "Custom Plugin Variable Name",
                                                                                hidden: false,
                                                                                height: 20,
                                                                                x: 5,
                                                                                y: 68,
                                                                                anchor: "100%",
                                                                                text: '',
                                                                                border: true
                                                                            }
                                                                        ]

                                                                    }
                                                                ]
                                                        }

                                                        ]

                                            }
                                        ]
                                },
                                {
                                 region: "center",
                                 bodyStyle: 'padding-left:8px;padding-right:8px;padding-bottom:6px;',
                                 layout: "form",
                                 items: [

                                    {
                                        id: "lbtxtaddondescription",
                                        xtype: "label",
                                        x: 0,
                                        y: 3,
                                        anchor: "100%",
                                        text: 'Description',
                                        border: false
                                    },
                                    {
                                        id: "txtaddondescription",
                                        xtype: "textarea",
                                        anchor: "100%",
                                        hideLabel: true,
                                        style: "padding-bottom:3px;",
                                        x: 0,
                                        y: 30,
                                        height: 80
                                    }
                                 ]
                                },
                                {
                                 region: "south",
                                 height: 180,
                                 layout: "fit",
                                 items: [
                                    addonPricesGrid
                                 ]
                                }
//
                                ]
                        },{
                            id: "lbtxtaddondescription",
                            xtype: "label",
                            y: 4,
                            anchor: "100%",
                            style : 'padding-left:5px;font-size:10px;position:relative;top:3px;',
                            text: txtaddondescript,
                            border: false
                        }
                        ]
            });
        }

/*
    xtype:          "label",
    id:             'NoticeAddon',
    name:           'NoticeAddon',
    autoHeight:     true,
    labelAlign:     'top',
    html: lang('<br />NOTICE:<br /><br />* Prices left empty won\'t be shown (prices of 0 will).<br /><br />* Tick a checkbox to always show a price in signup regardless of the billing cycle selected by the user<br />&nbsp;&nbsp;&nbsp;(e.g. annual fees for extra IP addresses)'),
    labelStyle:     "font-weight: bold;",
    labelSeparator: '',
    style:          "font-weight: bold;"
 */

        function createUI(){
            createAddonUI();
            createFormUI();
        }

        function deleteAddon(url){

            Ext.Ajax.request({
                url: url,
                params: {
                    addonid: addonId
                },
                success: function(respObj){
                    json = ce.parseAjaxResponse(respObj);
                    grid = Ext.getCmp("addonsGrid");
                    if(grid!=null){
                        grid.getStore().load({params:{start:0}});
                    }
                    win.close();
                }
            });

        }

        function populateFields(){



        }

        function TableTypeWindow (update){
            if(this instanceof TableTypeWindow){
                //this.update = update;
                this.CreateWindow = createWindow;
                this.PopulateFields = populateFields;
            }else{
                return new TableTypeWindow();
            }
        }

        function createWindow(update,currentAddonId){
            currentAddonId = currentAddonId || "-1";
            var requesturl;
            var buttonText;
            var titleText;
            var waitMessage;

            if(update){
                requesturl = 'index.php?fuse=admin&action=Admin_SaveAddon';
                buttonText = lang('Update');
                titleText = '&nbsp;&nbsp;'+lang('Edit Addon');
                waitMessage = lang("Updating...");
            }else{
                requesturl = 'index.php?fuse=admin&action=Admin_SaveAddon';
                buttonText = lang('Save');
                titleText = '&nbsp;&nbsp;'+lang('Add Addon');
                waitMessage = lang("Adding...");
            }

            createUI();

                // create the window on the first click and reuse on subsequent clicks
            win = new Ext.Window({
                id: "myWin",
                layout:'fit',
                title:titleText,
                width:windowWidth,
                height:windowHeight,
                plain: true,
                y:25,
                modal:true,
                closeAction:'close',
                forceLayout:true, /*forces controls to render before form is displayed*/
                defaults:{bodyStyle:'padding:0px;background-color:#F5F5F5 '},
                items: [frmAddon],
                listeners: {

                    hide: function() {frmAddon.destroy();}
                },
                buttons:
                [

                    {
                        text: 'Close',
                        handler: function()
                        {
                           win.close();
                        }
                    },
                    {
                        id: 'deleteButton',
                        text: 'Delete',
                        hidden: !update,
                        onClick: function(record)
                        {

                            requesturl = "index.php?fuse=admin&action=Admin_DeleteAddon"
                            Ext.Msg.show
                            (
                                {
                                    title : "Delete?" ,
                                    msg: "Are you sure you want to delete this addon?",
                                    buttons: Ext.Msg.YESNOCANCEL,
                                    fn: function(btn, text)
                                    {
                                        if (btn == 'yes')
                                        {
                                            deleteAddon(requesturl);
                                        }
                                    },
                                    icon: Ext.MessageBox.QUESTION

                                }
                           );


                        }
                   },
                   {
                        text: buttonText,
                        handler: function (){

                            saveUpdateAddon(buttonText,requesturl,waitMessage);
                        }


                    }
                ]
            });

             // if add
             if (!update) {
                frmAddon.getForm().reset();
                win.show();
                addonPluginVariableStore.load();
             } else { // if edit
                myMask.show();
                Ext.Ajax.request({
                    url: 'index.php?fuse=admin&action=Admin_GetAddon',
                    params: { addonid: addonId },
                    success: function(respObj) {
                        //if (!Ext.isIE) console.log(respObj);
                        if (respObj.status==200) {
                           var data = Ext.util.JSON.decode(respObj.responseText);
                           if (data) {
                               var row = data.addon[0];
                               Ext.getCmp('txtaddonname').setValue(row.name);
                               Ext.getCmp('txtaddondescription').setValue(row.description);
                               //Ext.getCmp('ckaddontaxable').setValue(row.taxable);
                               Ext.getCmp('cbopluginvar').setValue(row.plugin_var);
                               myMask.hide();
                               Ext.getCmp('lovcboproductgroups').setValue(row.productgroup_ids);
                               win.show();
                               addonPluginVariableStore.load({waitMsg: "Loading Addon Variable"});
                           }
                        }
                    }
                });
                addonPricesStore.load({waitMsg: "Loading Addon Details"});
             }
        }

        /* Private Medthods End*/

        /* Public Methods and Properties*/
        return {
            init: function() {
                // create button used above the product list grid
                 addAddon = new Ext.Button(
                    {

                        id:"addAddon",
                        renderTo:"addaddon",
                        text: lang('Add Addon'),
                        iconAlign: 'left',
                        disabled:true,
                        handler:function(){
                                update = false;
                                if (!myMask){
                                    myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
                                }
                                 myMask.show();
                                 addonId = 0;
                                 addonWin =  new TableTypeWindow();
                                 addonWin.CreateWindow(false);
                                 myMask.hide();
                        }
                    }
                );
            },

            ShowEditAddonWindow: function (addId, productGroupType)
            {
                selectedProductGroupType = productGroupType;
                addonWin =  new TableTypeWindow();
                addonId = addId;
                update = true;
                if (!myMask){
                    myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
                }
                myMask.show();
                addonWin.CreateWindow(true,addonId);
            }
        };
         /* Public Methods and Properties End*/
}();


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

function addItem() {

}
function editItem() {
    
}