// Generic Function to prepare the view. Any ExtJS loading stuff can go here, I think.
function prepareHostingView() {
    tabs.add(productPricingTab);
    //loadAddonData();
    tabs.add(productPluginTab);
}

/*
 * Start preparing the fields
*/
billingCyclePanelsBorder = false;
billingRowTopText = new Ext.Panel({
    layout: "absolute",
    name: "billingRowTopText",
    anchor: "100%",
    height: 15,
    border: billingCyclePanelsBorder,
    items: [
    {
        xtype: "label",
        name: "lblmonthlybilling",
        width: 80,
        x: 105,
        y: 1,
        text: "Price",
        style : "font-weight:bold"

    },
    {
        xtype: "label",
        name: "lblckallowmonthlybillinginsignup",
        width: 125,
        x: 173,
        y: 1,
        text: "Setup",
        style : "font-weight:bold"
    }]
});

// Monthly
txtBillingCyclesMonthlyAmount = new Ext.form.NumberField({
    xtype: "textfield",
    id: "priceMonthly",
    width: 60,
    x: 85,
    y: 2,
    value:"0.00",
    validationEvent: false,
    allowBlank: false
});

txtBillingCyclesMonthlySetup = new Ext.form.NumberField({
    xtype: "textfield",
    id: "setupMonthly",
    width: 60,
    x: 153,
    y: 2,
    value:"0.00",
    validationEvent: false,
    allowBlank: false
});

ckBillingCyclesMonthlyAmountAllowInSignup = new Ext.form.Checkbox({
    xtype: "checkbox",
    id: "priceMonthly_checked",
    width: 40,
    fieldLabel: "Allow in signup",
    x: 219,
    y: 2,
    checked: false
});

billingCyclesRowMonthlySignup = new Ext.Panel({
    layout: "absolute",
    name: "billingRowMonthlySignup",
    anchor: "100%",
    height: 35,
    border: billingCyclePanelsBorder,
    items: [
    {
        xtype: "label",
        name: "lblmonthlybilling",
        width: 80,
        x: 2,
        y: 6,
        text: "Monthly",
        style : "font-weight:bold"

    },
    txtBillingCyclesMonthlyAmount,
    txtBillingCyclesMonthlySetup,
    ckBillingCyclesMonthlyAmountAllowInSignup,
    {
        xtype: "label",
        name: "lblckallowmonthlybillinginsignup",
        width: 129,
        x: 238,
        y: 6,
        text: "Allow in signup",
        style : "font-weight:bold"
    }]
});

// Quarterly
txtBillingCyclesQuarterlyAmount = new Ext.form.NumberField({
    xtype: "textfield",
    id: "priceQuarterly",
    width: 60,
    x: 85,
    y: 2,
    value:"0.00",
    validationEvent: false,
    allowBlank: false
});

txtBillingCyclesQuarterlySetup = new Ext.form.NumberField({
    xtype: "textfield",
    id: "setupQuarterly",
    width: 60,
    x: 153,
    y: 2,
    value:"0.00",
    validationEvent: false,
    allowBlank: false
});

ckBillingCyclesQuarterlyAmountAllowInSignup = new Ext.form.Checkbox({
    id:'priceQuarterly_checked',
    xtype: "checkbox",
    width: 40,
    x: 219,
    y: 2,
    checked: false
});

billingCyclesRowQuarterlySignup = new Ext.Panel({

    layout: "absolute",
    name: "billingRowMonthlySignup",
    anchor: "100%",
    height:35,
    y: 35,
    border: billingCyclePanelsBorder,
    items: [
          {
            xtype: "label",
            name: "lblquarterlybilling",
            width: 80,
            x: 2,
            y: 6,
            text: "Quarterly",
            style : "font-weight:bold"
         },
         txtBillingCyclesQuarterlyAmount,
         txtBillingCyclesQuarterlySetup,
         ckBillingCyclesQuarterlyAmountAllowInSignup,
        {
            xtype: "label",
            name: "lblckallowquarterlybillinginsignup",
            width: 129,
            x: 238,
            y: 6,
            text: "Allow in signup",
            style : "font-weight:bold"
         }
    ]

});

// Semi Annual
txtBillingCyclesSemiAnnualAmount = new Ext.form.NumberField({
    id:'priceSemiannual',
    xtype: "textfield",
    width: 60,
    x: 85,
    y: 2,
    value:"0.00",
    validationEvent: false,
    allowBlank: false
});

txtBillingCyclesSemiAnnualSetup = new Ext.form.NumberField({
    xtype: "textfield",
    id: "setupSemiannual",
    width: 60,
    x: 153,
    y: 2,
    value:"0.00",
    validationEvent: false,
    allowBlank: false
});

ckBillingCyclesSemiAnnualAmountAllowInSignup = new Ext.form.Checkbox({
    id:'priceSemiannual_checked',
    xtype: "checkbox",
    width: 40,
    fieldLabel: "Allow in signup",
    x: 219,
    y: 2,
    checked: false
});

billingCyclesRowSemiAnnualSignup = new Ext.Panel({

    layout: "absolute",
    name: "billingRowSemiAnnualSignup",
    anchor: "100%",
    height:35,
    y: 35,
    border: billingCyclePanelsBorder,
    items: [
          {
            xtype: "label",
            name: "lblsemiannualbilling",
            width: 80,
            x: 2,
            y: 6,
            text: "Semi-Annual",
            style : "font-weight:bold"

         },
          txtBillingCyclesSemiAnnualAmount,
          txtBillingCyclesSemiAnnualSetup,
          ckBillingCyclesSemiAnnualAmountAllowInSignup,
        {
            xtype: "label",
            name: "lblckallowsemiannualbillinginsignup",
            width: 129,
            x: 238,
            y: 6,
            text: "Allow in signup",
            style : "font-weight:bold"

         }
    ]

});

// Annual
txtBillingCyclesAnnualAmount = new Ext.form.NumberField({
    id:'priceYearly',
    xtype: "textfield",
    width: 60,
    x: 85,
    y: 2,
    value:"0.00",
    validationEvent: false,
    allowBlank: false
});

txtBillingCyclesAnnualSetup = new Ext.form.NumberField({
    xtype: "textfield",
    id: "setupAnnual",
    width: 60,
    x: 153,
    y: 2,
    value:"0.00",
    validationEvent: false,
    allowBlank: false
});

ckBillingCyclesAnnualAmountAllowInSignup = new Ext.form.Checkbox({
    id:'priceYearly_checked',
    xtype: "checkbox",
    width: 40,
    fieldLabel: "Allow in signup",
    x: 219,
    y: 2,
    checked: false
});

billingCyclesRowAnnualSignup = new Ext.Panel({

    layout: "absolute",
    name: "billingRowAnnualSignup",
    anchor: "100%",
    height:35,
    y: 35,
    border: billingCyclePanelsBorder,
    items: [
          {
            xtype: "label",
            name: "lblannualbilling",
            width: 80,
            x: 2,
            y: 6,
            text: "Annual",
            style : "font-weight:bold"

         },
          txtBillingCyclesAnnualAmount,
          txtBillingCyclesAnnualSetup,
          ckBillingCyclesAnnualAmountAllowInSignup,
        {
            xtype: "label",
            name: "lblckallowannualbillinginsignup",
            width: 129,
            x: 238,
            y: 6,
            text: "Allow in signup",
            style : "font-weight:bold"

         }
    ]

});

// Biennial
txtBillingCyclesBiennialAmount = new Ext.form.NumberField({
    id:'price2Years',
    xtype: "textfield",
    width: 60,
    x: 85,
    y: 2,
    value:"0.00",
    validationEvent: false,
    allowBlank: false
});

txtBillingCyclesBiennialSetup = new Ext.form.NumberField({
    xtype: "textfield",
    id: "setupBiennial",
    width: 60,
    x: 153,
    y: 2,
    value:"0.00",
    validationEvent: false,
    allowBlank: false
});

ckBillingCyclesBiennialAmountAllowInSignup = new Ext.form.Checkbox({
    id:'price2Years_checked',
    xtype: "checkbox",
    width: 40,
    fieldLabel: "Allow in signup",
    x: 219,
    y: 2,
    checked: false
});

billingCyclesRowBiennialSignup = new Ext.Panel({
    layout: "absolute",
    name: "billingRowBiAnnualSignup",
    anchor: "100%",
    height:35,
    y: 35,
    border: billingCyclePanelsBorder,
    items: [
          {
            xtype: "label",
            width: 80,
            x: 2,
            y: 6,
            text: "Two Years",
            style : "font-weight:bold"
         },
          txtBillingCyclesBiennialAmount,
          txtBillingCyclesBiennialSetup,
          ckBillingCyclesBiennialAmountAllowInSignup,
        {
            xtype: "label",
            width: 129,
            x: 238,
            y: 6,
            text: "Allow in signup",
            style : "font-weight:bold"
         }
    ]
});

// One-Time
txtBillingCyclesOneTimePrice = new Ext.form.NumberField({
    id:'onetime',
    width: 60,
    x: 85,
    y: 2,
    value:"0.00",
    validationEvent: false,
    allowBlank: false
});

ckBillingCyclesOneTimeAllowInSignup = new Ext.form.Checkbox({
    id:'priceOneTime_checked',
    xtype: "checkbox",
    width: 40,
    fieldLabel: "Allow in signup",
    x: 219,
    y: 2,
    checked: false
});

billingCyclesRowOneTimePrice = new Ext.Panel({
    layout: "absolute",
    name: "billingRowOneTimePrice",
    anchor: "100%",
    height:35,
    y: 35,
    border: billingCyclePanelsBorder,
    items: [
          {
            xtype: "label",
            name: "lblonetimeprice",
            width: 80,
            x: 2,
            y: 6,
            text: "One-Time",
            style : "font-weight:bold"
         },
         txtBillingCyclesOneTimePrice,
         ckBillingCyclesOneTimeAllowInSignup,
        {
            xtype: "label",
            width: 129,
            x: 238,
            y: 6,
            text: "Allow in signup",
            style : "font-weight:bold"
         }
    ]
});

ckBillingCyclesPackageIsTaxable = new Ext.form.Checkbox({
    id:'taxable',
    width: 10,
    x: 2,
    y: 2
});

billingCyclesRowPackageIsTaxable = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    y: 35,
    border: billingCyclePanelsBorder,
    items: [
          {
            xtype: "label",
            name:  "lblallowinsignup",
            width: 150,
            x: 27,
            y: 6,
            text: "Product is Taxable?",
            style : "font-weight:bold"
         },
         ckBillingCyclesPackageIsTaxable
    ]
});

// Re-purpose these for the pricing clicked option
ckBillingCyclesForceUpdate = new Ext.form.NumberField({
    id:'pricingClicked',
    width: 10,
    value:'1',
    x: 7,
    y: 4
});

billingCyclesRowForceUpdate = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    hidden:true,
    y: 210,
    border: billingCyclePanelsBorder,
    items: [
          {
            xtype: "label",
            name:  "lblforceupdate",
            width: 190,
            x: 27,
            y: 7,
            html:"<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='Select this option to push the updated pricing information for this product to any existing orders.<br><b>Any existing clients will be billed using the new pricing on their next due date.</b>'>" + lang("Update existing orders?") + "</span>",
            style : "font-weight:bold"
         },
         ckBillingCyclesForceUpdate
    ]
});


// Stock control field
txtStockAmount = new Ext.form.NumberField({
    id:'stockAmount',
    xtype: "textfield",
    width: 60,
    //y: 13,
    x:100,
    value:"0",
    validationEvent: false,
    allowBlank: false,
    allowDecimals:false,
    disabled:true
});

stockAmountRow = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    y: 210,
    border: billingCyclePanelsBorder,
    items: [txtStockAmount,
          {
            xtype: "label",
            name:  "lblstockcontrol",
            width: 190,
            y: 7,
            html:"<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='Enter the quantity of available stock for this product.<br><br><b>Note:</b> When a product is sold, the available stock quantity is automatically reduced. Stock is NOT automatically adjusted for cancelled orders.'>" + lang("Available Stock") + "</span>",
            style : "font-weight:bold"
         }
    ]
});

// stock control sold out
ckStockControlSoldOut = new Ext.form.Checkbox({
    id:'stockSoldOut',
    width: 10,
    disabled:true,
    x: 7,
    y: 4
});

stockControlSoldOutRow = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    y: 210,
    border: billingCyclePanelsBorder,
    items: [
          {
            xtype: "label",
            name:  "lblforceupdate",
            width: 190,
            x: 27,
            y: 7,
            html:"<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='Select this option show this product as being Sold Out on the order form and hide product pricing when the available stock level has been reached. <br><br><b>Note:</b> If you have enabled the Accept sold out orders option the product pricing will still be displayed.</b>'>" + lang("Set as 'Sold Out'?") + "</span>",
            style : "font-weight:bold"
         },
         ckStockControlSoldOut
    ]
});


// stock control accept orders
ckStockControlAcceptOrders = new Ext.form.Checkbox({
    id:'stockAcceptOrders',
    width: 10,
    disabled:true,
    x: 7,
    y: 4
});

stockControlAcceptOrdersRow = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    y: 210,
    border: billingCyclePanelsBorder,
    items: [
          {
            xtype: "label",
            name:  "lblacceptorders",
            width: 190,
            x: 27,
            y: 7,
            html:"<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='Select this option if you wish for customers to be able to place an order for a product that has no available stock.</b>'>" + lang("Accept Sold Out Orders?") + "</span>",
            style : "font-weight:bold"
         },
         ckStockControlAcceptOrders
    ]
});

// enable stock control
ckEnableStockControl = new Ext.form.Checkbox({
    id:'stockEnable',
    width: 10,
    x: 7,
    y: 4
});

ckEnableStockControl.on('check',function(){
    if (ckEnableStockControl.checked){
        // enable controls
        ckShowStockLevel.enable();
        ckStockControlAcceptOrders.enable();
        ckStockControlSoldOut.enable();
        txtStockAmount.enable();
    } else {
        // Disable controls
        ckShowStockLevel.disable();
        ckStockControlAcceptOrders.disable();
        ckStockControlSoldOut.disable();
        txtStockAmount.disable();
        
    }
 });
 
enableStockControlRow = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    y: 210,
    border: billingCyclePanelsBorder,
    items: [
          {
            xtype: "label",
            name:  "lblacceptorders",
            width: 190,
            x: 27,
            y: 7,
            text:"Enable stock control options?",
            style : "font-weight:bold"
         },
         ckEnableStockControl
    ]
});


// show stock level in window
ckShowStockLevel = new Ext.form.Checkbox({
    id:'stockShowLevel',
    width: 10,
    disabled:true,
    x: 7,
    y: 4
});

showStockLevelRow = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    y: 210,
    border: billingCyclePanelsBorder,
    items: [
          {
            xtype: "label",
            name:  "lblshowstocklevel",
            width: 190,
            x: 27,
            y: 7,
            html:"<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='Select this option if you wish to display the current stock level of this product in the order form.</b>'>" + lang("Show stock level in order form?") + "</span>",
            style : "font-weight:bold"
         },
         ckShowStockLevel
    ]
});



// Coupon Name
txtCouponName = new Ext.form.TextField({
    id:'automaticCoupon',
    xtype: "textfield",
    width: 200,
    //y: 13,
    x:5,
    validationEvent: false,
    allowBlank: true
});

couponNameRow = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    y: 210,
    border: billingCyclePanelsBorder,
    items: [txtCouponName]
});

billingCyclesPanel = new Ext.form.FieldSet({
    layout: "absolute",
    id: 'billingCyclesPanel',
    border:false,
    width: 257,
    height: 450,
    anchor: "100%",
    x: 0,
    style: 'padding:0px;background-color:#F5F5F5 ',
    items: [
        {
            layout: 'column',
            border: false,
            items:  [
                {
                    columnWidth:  0.61,
                    layout:'form',
                    bodyStyle:'padding:0 5px 0 5px',
                    border:       false,
                    items:[{
                            xtype:        'fieldset',
                            id:           'addonsNotice',
                            name:         'addonsNotice',
                            title:        lang('Pricing'),
                            autoHeight:   true,
                            labelAlign:   'top',
                            anchor:'98%',
                            items :[
                                billingRowTopText,
                                billingCyclesRowMonthlySignup,
                                billingCyclesRowQuarterlySignup,
                                billingCyclesRowSemiAnnualSignup,
                                billingCyclesRowAnnualSignup,
                                billingCyclesRowBiennialSignup,
                                billingCyclesRowOneTimePrice,
                                billingCyclesRowPackageIsTaxable,
                                billingCyclesRowForceUpdate,
                                {
                                    xtype:  "label",
                                    y: 25,
                                    text:   "Addon prices for billing cycles not used in this product will not be available to the customer, unless you select the force show option in the addon setup screen.",
                                    style:  "font-weight:bold"
                                }
                            ]
                        }
                    ]
                },
                {
                    columnWidth:  0.39,
                    layout:       'form',
                    border:       false,
                    items:[{
                            xtype:        'fieldset',
                            id:           'stockControl',
                            name:         'stockControl',
                            title:        lang('Stock Control'),
                            autoHeight:   true,
                            anchor:'98%',
                            labelAlign:   'top',
                            items :       [
                                enableStockControlRow,
                                stockAmountRow,
                                //stockControlSoldOutRow,
                                stockControlAcceptOrdersRow,
                                showStockLevelRow
                            ]
                        },{
                            xtype:        'fieldset',
                            id:           'automaticCoupon',
                            name:         'automaticCoupon',
                            title:        lang('Automatic Coupon'),
                            autoHeight:   true,
                            anchor:'98%',
                            labelAlign:   'top',
                            items :       [
                                couponNameRow,{
                                    xtype:  "label",
                                    y: 25,
                                    text:   "Enter an existing Coupon Code in the box above to have the coupon automatically applied during checkout. ",
                                    style:  "font-weight:bold"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
});











// Get the servers & products servers
serverStore = new Ext.data.JsonStore({
    root:           'servers',
    totalProperty:  'totalcount',
    idProperty:     'serverid',
    remoteSort:     true,
    fields:         [
                        'serverid',
                        'servername',
                        'plugin',
                        'value',
                        'servernameandplugin',
                        'checked'
                    ],
    proxy:          new Ext.data.HttpProxy({
                        url:  'index.php?fuse=admin&action=getProductServerInfo&packageId='+productId
                    })
});

serverStore.setDefaultSort('id', 'asc');
serverStore.load();


// Dropdown for servers
lovComboProductServers = new Ext.ux.form.LovCombo({
    id:'lovComboProductServers',
    beforeBlur : Ext.emptyFn,
    anchor: "100%",
    hideOnSelect:false,
    fieldLabel: 'Associated servers',
    maxHeight:200,
    store: serverStore,
    triggerAction:    'all',
    lazyRender:       false,
    mode:             'local',
    validationEvent:  false,
    valueField:       'serverid',
    displayField:     'servernameandplugin',
    listeners: {
        change : function( combo, records, option ) {

            // Reset the plugin dropdown
            dropdownstore.loadData(dropdownArray);

            // Get the checked items from the servers dropdown
            var s = lovComboProductServers.getCheckedValue();
            
            // Check it
            if (s == "") {
                
                // hide the plugin dropdown
                cboSelectServerHostManager.hide();

                // Process and fields
                handlePluginFieldCall('-1', '');

            } else {

                // Split the servers to an array
                var servers = s.split(',');

                // Loop the data store and the servers
                for(var j = 0; j < serverStore.data.length; j++){
                    for(var i = 0; i < servers.length; i++){

                        // Check if the server exists
                        if(servers[i] == serverStore.data.items[j].data.serverid) {

                            // Add it to the final array of selections
                            var finalSelections = new Array();
                            finalSelections['plugin'] = serverStore.data.items[j].data.plugin;
                            finalSelections['serverid'] = serverStore.data.items[j].data.serverid;
                            finalSelections['value'] = serverStore.data.items[j].data.value;
                            selectedPlugins.push(finalSelections);
                            
                        }
                    }
                }

                // Process the plugin list and determine what todo
                processPluginList();
                selectedPlugins = new Array();
            }
        }
    }


});

// Function to process the given plugin and return a status
// 1 =
var selectedPlugins = [];
function processPluginList() {

    var pluginStatus = 1;
    var pluginName = 0;
    var pluginServer = 0;

    // Loop the plugins we already have to work out what we need to do
    for(var j = 0; j < selectedPlugins.length; j++){

        // Loop the plugins again
        for(var i = 0; i < selectedPlugins.length; i++){

            // Check the plugin
            if(selectedPlugins[i]['plugin'] != selectedPlugins[j]['plugin'] && pluginStatus != 0) {

                // Throw an error with a mismatch
                Ext.Msg.show({
                   title:'Error',
                   msg: 'You cannot select more than 1 different type of plugin (cPanel, OnApp, Plesk, etc).',
                   buttons: Ext.Msg.OK,
                   animEl: 'elId',
                   icon: Ext.MessageBox.WARNING
                });
                handlePluginFieldCall('-1', '');
                cboSelectServerHostManager.hide();
                
                // Stop any further adding
                pluginStatus = 0;

                break;
                break;
                
            } else {

                // Change the status if the plugin is onapp
                if(selectedPlugins[j]['plugin'] == 'onapp') {
                    pluginStatus = 2;
                    pluginName = selectedPlugins[j]['plugin']
                    pluginServer = selectedPlugins[j]['serverid']
                } else {
                    pluginName = selectedPlugins[j]['plugin'];
                }
            }
        }
    }

    if(pluginStatus == 1 || selectedPlugins.length == 1) {
         cboSelectServerHostManager.hide();
         handlePluginFieldCall(pluginName, pluginServer);
        
    } else if(pluginStatus == 2) {

        // Loop the plugins and do the magic
        for(var j = 0; j < selectedPlugins.length; j++){

            // Handle the dropdown
            var pluginEntry = Ext.data.Record.create([{name: 'plugin'},{name: 'value'},{name: 'serverid'}]);

            // Add to the store
            dropdownstore.add(new pluginEntry({plugin: selectedPlugins[j]['plugin'], value: selectedPlugins[j]['value'], serverid: selectedPlugins[j]['serverid']}));

            // Shdow the dropdown
            handlePluginFieldCall('-1', '');
            cboSelectServerHostManager.show();
        }
    }

    selectedPlugins = new Array();
}


var dropdownstore = new Ext.data.ArrayStore({
    fields: ['plugin', 'value', 'serverid']
});
var dropdownArray = [['-- Select a Plugin --', '-1', '-1']]
dropdownstore.loadData(dropdownArray);


// Process the data recieved and populate the plugins dropdown
serverStore.on('load',function(store, records, option){

    serverIds = "";
    checkCount = 0;
    
    // Check if we have anything to do
    for (var i = 0; i < records.length; i++) {

        // Set the record
        o = records[i].data;

        // Check if the record should be selected
        if(o.checked == true) {


            // Add it to the final array of selections
            var finalSelections = new Array();
            finalSelections['plugin'] = o.plugin;
            finalSelections['serverid'] = o.serverid;
            finalSelections['value'] = o.value;
            selectedPlugins.push(finalSelections);
            
            // Build a list of server ID's to use as the value of the dropdown
            if(serverIds == '') {
                serverIds = o.serverid;
            } else {
                serverIds = serverIds + ',' + o.serverid;
            }
            checkCount++;
        }
    }

    if(checkCount != 0) {
        // Process the plugins
        processPluginList();
        selectedPlugins = new Array();

        // Set the initial value of the dropdown
        lovComboProductServers.setValue(serverIds);
    }
});


selectedPlugin = '';

cboSelectServerHostManager = new Ext.form.ComboBox({
    mode: 'local',
    store: dropdownstore,
    displayField: "plugin",
    valueField: "plugin",
    triggerAction: "all",
    anchor: "100%",
    
    editable: false,
    hidden:true,
    value:'-- Select a Plugin --',
    listeners: {
        select : function( combo, record, index ) {

            if(record.data.value != '-1') {
                handlePluginFieldCall(record.data.plugin, record.data.serverid);
            } else {
                handlePluginFieldCall('-1', '');
            }
        }
     }

});

function handlePluginFieldCall(plugin, serverid) {
    
    // Process any fields and their values. We need to cache the value so we don't try saving the select option
    processContainerFields(selectedPlugin);
    selectedPlugin = plugin;

    // Check what we selected
    if(plugin == '-1') {

        // Clear any plugin vars
        pluginOptions_container.removeAll();
        pluginOptions_store.removeAll();
    } else {

        // We need to get the list of plugin fields
        pluginOptions_container.removeAll();
        pluginOptions_store.removeAll();

        pluginOptions_store.load({
            params: {
                plugin:  plugin,
                packageId: productId,
                serverId: serverid
            }
        });

        //pluginOptions_container.doLayout();
    }
}

function convertToArray(obj, n) {
   if (! obj.length) {return [];} // length must be set on the object, or it is not iterable
   var a = [];

   try {
       a = Array.prototype.slice.call(obj, n);
   }
   // IE 6 and posssibly other browsers will throw an exception, so catch it and use brute force
   catch(e) {
       Core.batch(obj, function(o, i) {
           if (n <= i) {
               a[i - n] = o;
           }
       });
   }

   return a;
}

// Function to process the container fields and store their values
var pluginFieldsFinal = {};
var pluginFieldsRecieved = {};
function processContainerFields(plugin) {

    var pluginFieldsWorking = {};

    // Start looping the fields we know are in the window
    for (var i = 0; i < pluginFieldsRecieved.length; i++) {

        // Get the field
        workingField = Ext.getCmp(pluginFieldsRecieved[i]);
        // Alert if we cant get the field
        if(!workingField) {
            alert("Unable to find field: "+pluginFieldsRecieved[i]);
        } else {

            // Check that we have a field we can get the value of
            if(workingField.getXType() == 'textfield' || workingField.getXType() == 'textarea' || workingField.getXType() == 'checkbox' || workingField.getXType() == 'combo' || workingField.getXType() == 'lovcombo') {
                pluginFieldsWorking[pluginFieldsRecieved[i]] = workingField.getValue();
            }
        }
    }

    // Add the final array of fields and values.
    pluginFieldsFinal[plugin] = pluginFieldsWorking;


    // Unset the array
    pluginFieldsRecieved = {};
}

pluginOptions_store = new Ext.data.JsonStore({
    id: "pluginOptions_store",
    root: 'data',
    idProperty: 'name',
    remoteSort: true,
    baseParams:     {
        plugin:  '',
        packageId: 0,
        serverId: 0
    },
    fields: [
        'name','value', 'type', 'description', 'label', 'dropdownoptions', 'belongsto'
    ],
    proxy: new Ext.data.HttpProxy({
        url: 'index.php?fuse=admin&action=getProductPluginOptions'
    }),
    listeners: {
        load: function(store, records, option) {

            // Clear some variables
            var o = null;
            pluginOptions_container.removeAll();
            
            pluginFieldsRecieved = [];

            for (var i = 0; i < records.length; i++) {
                    o = records[i].data;

                    // Set the field label
                    if(o.description) {
                        var fieldLabel = "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + o.description.replace(/'/g, "&#39;") + "'>" + o.label + "</span>";
                    } else {
                        var fieldLabel = o.label;
                    }

                    // Store the plugin field
                    pluginFieldsRecieved.push(o.name);

                    // Work out where to add the field to 
                    if(o.belongsto) {
                        containerAdd = Ext.getCmp(o.belongsto);
                    } else {
                        containerAdd = pluginOptions_container;
                    }


                    // Work out if we have a stored value for the plugin
                    if(pluginFieldsFinal[selectedPlugin]) {
                        testingVar = pluginFieldsFinal[selectedPlugin];
                        fieldValue = testingVar[o.name];
                    } else {
                        fieldValue = o.value;
                    }

                    // Adding a text field
                    if(o.type == 'text') {

                        // Add the fields to the container
                        containerAdd.add({
                            id: o.name,
                            name: o.name,
                            value: fieldValue,
                            fieldLabel: fieldLabel,
                            xtype: "textfield",
                            labelStyle:'float:left;',
                            anchor:'90%'
                        });
                       

                    } else if(o.type == 'password') {

                        // Add the fields to the container
                        containerAdd.add({
                            id: o.name,
                            name: o.name,
                            value: fieldValue,
                            fieldLabel: fieldLabel,
                            xtype: "textfield",
                            inputType: 'password',
                            labelStyle:'float:left;',
                            anchor:'90%'
                        });
                    } else if(o.type == 'textarea') {

                        // Add the fields to the container
                        containerAdd.add({
                            fieldLabel: fieldLabel,
                            id: o.name,
                            name: o.name,
                            value: fieldValue,
                            xtype: "textarea",
                            labelStyle:'float:left;',
                            anchor:'90%'
                        });
                    } else if(o.type == 'check') {

                        // Add the fields to the container
                        containerAdd.add({
                            fieldLabel: fieldLabel,
                            id: o.name,
                            labelSeparator: "",
                            name: o.name,
                            checked: fieldValue,
                            xtype: "checkbox",
                            fieldClass: "products-hosting-fields",
                            labelStyle:'padding-left:22px;position: relative;top:12px;',
                            anchor:'100%'
                        });
                    } else if(o.type == 'yesno') {


                        // Yes / No options for dropdowns
                        var yesno = [
                                     ['Yes'],
                                     ['No']
                                    ];

                        // Dropdown box to allow DNS records
                        containerAdd.add(new Ext.form.ComboBox({
                            fieldLabel: fieldLabel,
                            anchor:'90%',
                            id: o.name,
                            //hiddenName: o.name,
                            name: o.name,
                            store: new Ext.data.SimpleStore({
                                fields: ['fieldname'],
                                data : yesno
                            }),
                            displayField: 'fieldname',
                            mode: 'local',
                            triggerAction: 'all',
                            editable: false,
                            labelStyle:'float:left;',
                            value: fieldValue,
                            validationEvent: false,
                            maxHeight: 200,
                            allowBlank: false
                        }));

                    } else if(o.type == 'dropdown') {

                        // Dropdown box to allow DNS records
                        containerAdd.add(new Ext.form.ComboBox({
                            fieldLabel: fieldLabel,
                            anchor:'90%',
                            id: o.name,
                            //hiddenName: o.name,
                            name: o.name,
                            store: o.dropdownoptions,
                            displayField: 'fieldname',
                            mode: 'local',
                            triggerAction: 'all',
                            editable: false,
                            labelStyle:'float:left;',
                            value: fieldValue,
                            validationEvent: false,
                            maxHeight: 200,
                            allowBlank: false
                        }));
                        
                    } else if(o.type == 'combo') {

                        // Dropdown box to allow DNS records
                        containerAdd.add(new Ext.ux.form.LovCombo({
                            fieldLabel: fieldLabel,
                            anchor:'90%',
                            id: o.name,
                            //hiddenName: o.name,
                            name: o.name,
                            store: new Ext.data.ArrayStore({
                                idIndex: 0,
                                fields: [
                                    'id',
                                    'fieldname'
                                ],
                                data: o.dropdownoptions
                            }),
                            displayField: 'fieldname',
                            valueField: 'id',
                            mode: 'local',
                            triggerAction: 'all',
                            editable: false,
                            labelStyle:'float:left;',
                            value: fieldValue,
                            validationEvent: false,
                            hideOnSelect: true,
                            maxHeight: 200,
                            allowBlank: false,
                            beforeBlur: Ext.emptyFn
                        }));
                        
                    } else if(o.type == 'fieldset') {

                        // Add the fields to the container
                        pluginOptions_container.add({
                            title: fieldLabel,
                            id: o.name,
                            name: o.name,
                            value: o.value,
                            xtype: "fieldset",
                            layout: 'form',
                            anchor:'100%'
                        });
                    }
            }



            pluginOptions_container.doLayout();
        }
    }
});

// Define the container for the plugin options
pluginOptions_container = new Ext.Container({
    id:     'pluginOptions_container',
    layout: 'form',
    labelAlign: 'left',
    labelWidth: 170,
    items : []
 });



productPluginTab = new Ext.form.FieldSet({
    id: 'productPluginPanel',
    //layout: "absolute",
    border:false,
    height: 370,
    autoWidth:true,
    autoScroll:true,
    bodyStyle:'overflow-y:auto;',
    style: {
            paddingRight: '0px'
        },
    items: [{
        layout:'column',
        border:false,
        width:520,
        items:[{
            columnWidth:.5,
            layout: 'form',
            border:false,
            style:'background-color:#F5F5F5 ',
            items: [lovComboProductServers]
        },
        {
            columnWidth:.5,
            style:'background-color:#F5F5F5 ',
            layout: 'form',
            border:false,
            items: [cboSelectServerHostManager]
        },
        {
            columnWidth: 1,
            style:'background-color:#F5F5F5 ',
            layout: 'form',
            border:false,
            items: [pluginOptions_container]
        }]
    }]
});

/*
 * Make the tab to load
 */
productPluginTab = {
    title:'Advanced',
    id:'productPluginTab',
    bodyStyle:'padding:0px;',
    labelWidth: 150,
    items:[productPluginTab]
}
productPricingTab = {
    title:'Pricing & Stock Control',
    id:'productPricingTab',
    items:[billingCyclesPanel]
}
