productWinForm.getForm().on("actioncomplete",function(){
   tabs.add({
        title:'Addons',
        items:[addonsPanel]
    });
    addonLovComboStore.load({params:{group:selectedProductGroup}});
});

addonStyleStore = new Ext.data.ArrayStore({
  idIndex:0,
  fields:['style','stylename'],
  data:[
        [0,lang("Drop-down menus")],
        [1,lang("Radio buttons")]
       ]
});

cboProductAddonStyle = new Ext.form.ComboBox({
    anchor: "90%",
    height: 20,
    x:80,
    y:9,
    xtype: "combo",
    lazyRender: false,
    validationEvent:  false,
    triggerAction: "all",
    mode: 'local',
    store:    addonStyleStore,
    valueField:       'style',
    displayField:     'stylename',
    value:            addonStyle,
    hiddenId:         'style',
    hiddenName:       'addonStyle',
    forceSelection:   true,
    editable:         false
});


// Store for the addons
addonLovComboStore = new Ext.data.JsonStore({
    fields: [{name: 'id'}, {name: 'name'},{name: 'description'},{name: 'plugin_var'},{name: 'order',type:'int'},{name: 'taxable',type:'bool'}],
    root:           'addons',
    totalProperty:  'totalcount',
    idProperty:     'id',
    sortInfo: {field: "order", direction: "ASC"},
    url: "index.php?fuse=admin&action=adminGetAddons&productType="+productType
});

// Dropdown of existing addons
lovComboAddons = new Ext.form.ComboBox({ //new Ext.ux.form.LovCombo({
    id:'lovComboAddons',
    beforeBlur : Ext.emptyFn,
    width: 200,
    x: 70,
    y: 9,
    editable:false,
    hideOnSelect:false,
    fieldLabel: "Select Addons:",
    maxHeight:200,
    store: addonLovComboStore,
    tpl: '<tpl for="."><div qtip="<b>Name</b>: {name}<br/><b>Description</b>: {description}<br/>" class="x-combo-list-item">{name}</div></tpl>',
    triggerAction: 'all',
    lazyRender: false,
    mode: 'local',
    validationEvent: false,
    valueField: 'id',
    displayField: 'name',
    listeners: {
        select : function( combo, record, index ) {

            var row = record.data;
            if (row.checked) {
                var temp = new addon({
                id: row.id,
                name: row.name,
                description: row.description,
                plugin_var: row.plugin_var,
                order: row.order,
                taxable: row.taxable
                });
                addonStore.insert(addonStore.getCount(), temp);
            
            } else {

                for(var i=0;i<addonStore.data.length;i++){
                    var thisRow = addonStore.data.items[i].data;
                    if (row.id == thisRow.id){
                        addonStore.remove(addonStore.data.items[i]);
                    }
                }
            }
            addonGrid.getView().refresh(true);
        }
    }
});

// Renter the Yes No Text
function renderYesNo(value,p,record){
    if (value == 1) return lang("Yes");
    return lang("No");
}

// View config for the grid
addonGridView = new Ext.grid.GridView({
    forceFit: true
});

// Store for the addons tied to this product. Loaded with the grid render
addonStore = new Ext.data.JsonStore({
    fields: [{name: 'id'}, {name: 'package_id'},{name: 'name'},{name: 'description'},{name: 'plugin_var'},{name: 'order',type:'int'},{name: 'taxable',type:'bool'}],
    root:           'addons',
    totalProperty:  'totalcount',
    idProperty:     'id',
    baseParams: {packageid: productId},
    sortInfo: {field: "order", direction: "ASC"}
});

// Cell actions definitions, to delete addons from the grid!
addonGridCellActions = new Ext.ux.grid.CellActions({
    listeners:{
        action:function(grid, record, action, value) {
            if (action=="icon-edit"){
                btnAddonEdit_Click(grid,record,action,value);
            } else if (action=="icon-delete") {
                btnAddonDelete_Click(grid,record,action,value);
            }

        }
    },
    align:'left'
});

// The addons grid itself
addonGrid = new Ext.grid.GridPanel({
    ds: addonStore,
    defaults: {
        sortable: true
    },
    columns:
        [{id: 'id', width:10, header: 'Id', hidden:true, sortable: true, dataIndex: 'id'},
         {header:'Name', width: 100,hidden:false, sortable: true, locked:false, dataIndex: 'name',
            cellActions:[{
                          iconCls:'icon-delete',
                          qtip:'Click to Delete'
                        }]
           },
           {header: "Description", hidden:false, width: 100, sortable: true,locked:false,  dataIndex: 'description'},
           {header: "Plugin", width: 55, sortable: true, dataIndex: 'plugin_var'}
        ],
    enableDragDrop: true,
    ddGroup: 'myGridDD',
    dragConfig: {
        containerScroll : true
    },
    stripeRows: true,
    listeners: {
        render: function(){
               Ext.Ajax.request({
                url: 'index.php?fuse=admin&action=Admin_GetProductAddons&productType='+productType,
                params: {
                    product_id: productId
                },
                success: function(respObj){
                    if (respObj.status==200){
                       var data = Ext.util.JSON.decode(respObj.responseText);
                       if (data){

                            var addonids = "";
                            for(var i=0;i<data.addon.length;i++){
                                var row = data.addon[i];

                                if (i<data.addon.length-1) {
                                    addonids += row.id + ",";
                                }
                                else {
                                    addonids += row.id
                                }
                                var temp = new addon({
                                    id: row.id,
                                    name: row.name,
                                    description: row.description,
                                    plugin_var: row.plugin_var,
                                    order: row.order,
                                    taxable: row.taxable
                                });

                                // remove item from combo
                                for(var x=0;x<addonLovComboStore.data.length;x++){
                                    var lovItem = addonLovComboStore.data.items[x];
                                    var lovRow = lovItem.data;
                                    if (lovRow.id==row.id){
                                        addonLovComboStore.remove(lovItem);
                                        lovComboAddons.setValue('');
                                    }
                                }
                                addonStore.insert(addonStore.getCount(), temp);
                            }
                            addonStore.commitChanges();
                            addonGrid.getView().refresh(true);
                            addonsRendered = true;
                       }
                    }
                }
            });
        }
    },
    plugins:[addonGridCellActions],
    view: addonGridView,
    autoExpandColumn: 'name',
    height: 250,
    title:'',
    border: 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;
        } 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);
        
        return true;
    }
};

addonGrid.on('viewready',function(grid){
    var leftGridDropTarget   = new Ext.dd.DropZone(addonGrid.el, dropTargetCfg);
});

// Addon row definition
addon = Ext.data.Record.create([
    {name: 'id', type: 'int'},
    {name: 'package_id', type: 'int'},
    {name: 'name', type: 'string'},
    {name: 'description', type: 'string'},
    {name: 'plugin_var', type: 'string'},
    {name: 'order', type: 'int'},
    {name: 'taxable', type: 'int'}
]);

// On click handler
function btnAddonDelete_Click(grid,record,action,value){

    moveAddonFromGridToCombo(record);
}

// FUnctuon to move the addon from the dropdown to the grid
function moveAddonFromComboToGrid(){

    var curVal = lovComboAddons.getValue();
    if(curVal == ''){
        Ext.MessageBox.alert(lang("Notice"), lang("You must first select an addon from the list.<br>If your list is empty or you need to create more addons, you can do it in System Setup > Products > Addons"));
        return;
    }
    for(var i =0;i<addonLovComboStore.data.length;i++){
        var item = addonLovComboStore.data.items[i];
        var row = item.data;
        if (row.id==curVal){
                var temp = new addon({
                                id: row.id,
                                name: row.name,
                                description: row.description,
                                plugin_var: row.plugin_var,
                                order: row.order,
                                taxable: row.taxable

                                });
               // remove item from Combo
               addonLovComboStore.remove(item);
               lovComboAddons.setValue('');

               // add item to grid
               addonStore.insert(addonStore.getCount(), temp);
               addonGrid.getView().refresh(true);
        }
    }
}

// Function to move the addon from the grid to the dropdown, when deleted
function moveAddonFromGridToCombo(item){
    var row = item.data;
    var temp = new addon({
                    id: row.id,
                    name: row.name,
                    description: row.description,
                    plugin_var: row.plugin_var,
                    order: row.order,
                    taxable: row.taxable
                    });

   // remove from grid
   addonStore.remove(item);
   addonGrid.getView().refresh(true);

   // add to combo
   addonLovComboStore.insert(0, temp);
   lovComboAddons.setValue(row.id);
}

if(productType == 3){
    txtaddondescript = '*Please make sure you have ticked the checkboxs for the prices you want to show in signup, for the selected addons';
}else{
    txtaddondescript = '';
}

/*
Since tlds for domains range so many years
the addons for those tlds will require the force show checkbox ticked.
*/


// Fieldset for the addons
addonsPanel = new Ext.form.FieldSet({
    id: "productaddonsbordercenter",
    style: 'padding:0px;background-color:#F5F5F5 ',
    collapsible: false,
    height: 440,
    layout: "border",
    border: false,
    defaults: {border:false},
    items: [{
            region: "north",
            height: 40,
            items: [{
                   layout: "column",
                   border: false,
                   defaults: {border:false},
                   items: [{
                                columnWidth: .6,
                                border: false,
                                layout: "anchor",
                                defaults: {border:false},
                                items : [{
                                            layout: "absolute",
                                            width: 360,
                                            height: 40,
                                            items: [{
                                                        xtype: "label",
                                                        text: "Add Addon",
                                                        x: 5,
                                                        y: 11
                                                    },
                                                    lovComboAddons,
                                                    {
                                                        id: "addonAddButton",
                                                        xtype: "button",
                                                        text: "Add",
                                                        style: "float:left;padding-left:3px",
                                                        x: 275,
                                                        y: 6,
                                                        listeners:{
                                                            click: function(){
                                                               moveAddonFromComboToGrid();
                                                            }
                                                        }
                                                    }]
                                         }]
                            },{
                                columnWidth: .4,
                                border: false,
                                layout: "anchor",
                                defaults: {border:false},
                                items : [{
                                            layout: "absolute",
                                            width: 260,
                                            height: 40,
                                            items: [{
                                                        xtype: "label",
    													html: '<span style="cursor:pointer; border-bottom: 1px solid rgb(223, 223, 223);" qtip="The style of all addons associated with this product.">' + lang('Display Style') + '</span>',
                                                        x: 5,
                                                        y: 11
                                                    },
                                                    cboProductAddonStyle
                                                    ]
                                         }]
                            }]
                       }]
        },
        {
            region: "center",
            height: 400,
            layout: "fit",
            items: [
                {
                    id: "lbtxtaddondescription",
                    xtype: "label",
                    anchor: "100%",
                    style : 'padding-left:5px;font-size:10px;position:relative;bottom:3px;',
                    text: txtaddondescript,
                    border: false
                },
                addonGrid,
                // Re-purpose these for the pricing clicked option
                new Ext.form.NumberField({
                    id:'addonsClicked',
                    hidden: true,
                    width: 10,
                    value:'1',
                    x: 7,
                    y: 4
                })
            ]
        }
    ]
});

// HTML encoding for addon
function addonHTMLEncode(row){
    row.description = encodeURIComponent(row.description);
    row.name = encodeURIComponent(row.name);
    row.plugin_var = encodeURIComponent(row.plugin_var);
    row.value = encodeURIComponent(row.value);
    return row;
}

// Function to get the addons to post
function getAddonPostParms(){

    addonStore.commitChanges();
    if (addonStore.data.length>0){
        var addonArray = new Array(addonStore.data.length);
        for(var i=0;i<addonStore.data.length;i++){

            // order the addons according to the store order
            addonStore.data.items[i].data.order = i;
            addonStore.commitChanges();
            var row =  addonStore.data.items[i].data;
            addonArray[i] =  addonHTMLEncode(row);
        }
        return Ext.util.JSON.encode(addonArray);
    } else {
        return false;
    }
}
