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

/*
 * Start preparing the fields
 */
var previousSelection = 0;
var store = new Ext.data.ArrayStore({
    fields: ['period','price','transfer', 'renew', 'period_id']
});

var dropdownstore = new Ext.data.ArrayStore({
    fields: ['period']
});
var dropdownArray = [['1 Year'], ['2 Years'], ['3 Years'], ['4 Years'], ['5 Years'], ['6 Years'], ['7 Years'], ['8 Years'], ['9 Years'], ['10 Years']]
dropdownstore.loadData(dropdownArray);

// Create the pricing grid
var tldpricinggrid = new Ext.grid.EditorGridPanel({
    store: store,
    anchor: "100%",
    height: 323,
    id: 'tldpricinggrid',
    region:'center',
    selModel: new Ext.grid.RowSelectionModel(),
    margins: '0 5 5 5',
    clicksToEdit:1,
    columns: [{
        id: 'period',
        header: 'Registration Period',
        dataIndex: 'period',
        width: 225,
        menuDisabled:true,
        editor: new Ext.form.ComboBox({
            store: dropdownstore,
            typeAhead: true,
            triggerAction: 'all',
            displayField: 'period',
            mode: 'local',
            editable:false,
            valueField: 'period'
        })
    },{
        id: 'price',
        header: 'Registration Price',
        dataIndex: 'price',
        width: 125,
        menuDisabled:true,
        editor:new Ext.form.TextField({})
    },{
        id: 'renew',
        header: 'Renewal Price',
        dataIndex: 'renew',
        width: 125,
        menuDisabled:true,
        editor:new Ext.form.TextField({})
    },{
        id: 'transfer',
        header: 'Transfer Price',
        dataIndex: 'transfer',
        width: 125,
        menuDisabled:true,
        editor:new Ext.form.TextField({})
    }],
    tbar: [{
        text: 'Add Pricing',
        disabled: true,
        id:'gridAddPricing',
        handler : function(){
            var Record = tldpricinggrid.getStore().recordType;
            var p = new Record({
                period: 'Choose One...',
                price: '0.00',
                renew: '0.00',
                transfer: '0.00'
            });

            // Code to insert a new row
            tldpricinggrid.stopEditing();
            var rownum = store.getCount();
            store.insert(rownum,p);
            tldpricinggrid.startEditing(rownum, 1);
        }
    }, '-', {
        text: 'Delete Pricing',
        disabled: true,
        id:'gridDeletePricing',
        handler:  function () {
            var rec = tldpricinggrid.getSelectionModel().getSelected();
            if (!rec) {
                return false;
            }
            tldpricinggrid.store.remove(rec);
        }
    }]
});


// Re-purpose these for the pricing clicked option
billingCyclesRowForceUpdate = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    hidden:true,
    y: 210,
    border: false,
    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"
    },
    new Ext.form.NumberField({
        id:'pricingClicked',
        width: 10,
        value:'1',
        x: 7,
        y: 4
    })]
});


// Store for the list of TLD's
tld_store = new Ext.data.JsonStore({
    id: "tld_store",
    root: 'data',
    idProperty: 'tld',
    remoteSort: true,
    fields: [
    'tld','pricing', 'registrar', 'isDefault'
    ],
    proxy: new Ext.data.HttpProxy({
        url: "index.php?fuse=admin&action=getTldAndPricing&productId="+productId
    })
});

// Don't bother loading the store if we are adding a product
if(productId != -1) {
    tld_store.load();
}

// Dropdown of existing addons
lovComboTLD = new Ext.form.ComboBox({ //new Ext.ux.form.LovCombo({
    id:'lovComboTLD',
    beforeBlur : Ext.emptyFn,
    width: 200,
    x: 108,
    y: 8,
    hideOnSelect:false,
    fieldLabel: "Select TLD:",
    maxHeight:200,
    store: tld_store,
    triggerAction: 'all',
    lazyRender: false,
    mode: 'local',
    value: '-- Select a TLD --',
    validationEvent: false,
    valueField: 'tld',
    displayField: 'tld',
    editable:false,
    listeners: {
        select : function( combo, record, index ) {

            // Work out if we need to save the current grid back to the store or not
            if(previousSelection != 0) {

                saveGridPricing(previousSelection);
            }

            // Save the selected index
            previousSelection = index;

            // Check if we have selected an actual TLD or not
            if(record.data.tld == '-- Select a TLD --') {

                // Clear the grid
                clearResetGrid(true);

                // Reload the period dropdown store
                dropdownstore.loadData(dropdownArray);

            } else {
                
                // reload the period dropdown store to avoid additional period entries being erased
                dropdownstore.loadData(dropdownArray);

                // Enable the grid buttons
                clearResetGrid(false);
                
                // Populate the grid with the pricing data
                var pricingArray = record.data.pricing;
                var finalArray = [];
                
                // Check if we have any pricing data
                if(pricingArray != null) {
                    for (i=0;i<pricingArray.length;i++) {
                        if(pricingArray[i].period == 1) {var yearsText = ' Year';} else {var yearsText = ' Years';}
                        finalArray[i] = [pricingArray[i].period + yearsText, pricingArray[i].price, pricingArray[i].transfer, pricingArray[i].renew, pricingArray[i].period];
                    }
                }

                // Load the array to the store
                store.loadData(finalArray);
            }
        }
    }
});



billingCyclesRowPackageIsTaxable = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    y: 210,
    border: false,
    items: [{
        xtype: "label",
        name:  "lblallowinsignup",
        width: 150,
        x: 60,
        y: 14,
        text: "Tax Domain orders?",
        style : "font-weight:bold"
    },
    new Ext.form.Checkbox({
        id:'taxable',
        width: 10,
        x: 40,
        y: 10
    })]
});

// Function to add a new TLD to the store
function addTld(registrar,text, isDefault){

    if(text != ''){
        
        // Strip the . from TLD
        if(text.charAt(0) == '.') {
            text = text.substring(1,text.length);
        }

        // Make the record
        var TldEntry = Ext.data.Record.create([
            {name: 'tld'},
            {name: 'pricing'},
            {name: 'registrar'},
            {name: 'isDefault'}
        ]);

        // Add to the store
        tld_store.add(new TldEntry({
            tld: text,
            pricing: '',
            registrar: registrar,
            isDefault: isDefault
        }));

        // Save any changes to the grid before moving the data
        saveGridPricing(previousSelection);

        // Select the record in the dropdown
        lovComboTLD.setValue(text);

        // Clear the grid
        clearResetGrid(false);

        // Set the selection
        previousSelection = tld_store.findExact('tld', lovComboTLD.getValue());
    }
}

// Function to save updates to a TLD to the store
function editTld(registrar,text,isDefault){

    // Strip . from TLD
    if(text.charAt(0) == '.') {
        text = text.substring(1,text.length);
    }

    // Check the result
    if(text != ''){

        // Save the tld
        var rec = tld_store.getAt(previousSelection);
        rec.set('tld', text);
        rec.set('registrar', registrar);
        rec.set('isDefault', isDefault);
        rec.commit();
        lovComboTLD.setValue(text);
    } 
}

// Function Delete TLD
function deleteTld(btn) {

    if(btn == 'yes') {
        // Delete the record
        var rec = tld_store.getAt(previousSelection);
        tld_store.remove(rec);

        // Clear the grid and move to the placeholder in the dropdown
        lovComboTLD.setValue('-- Select a TLD --');
        clearResetGrid(true);
        previousSelection = 0; // Reset the previous selection so we don't erase another entries data

        addEditTld.hide();
    }
}

// Fieldset for the addons
domainsPricingPanel = new Ext.form.FieldSet({
    id: "domainpricingpanel",
    style: 'padding:0px;background-color:#F5F5F5 ',
    collapsible: false,
    height: 357,
    layout: "border",
    border: false,
    autoscroll:true,
    defaults: {border:false},
    items: [{
        region: "north",
        height: 40,
        items: [{
            layout: "column",
            border: false,
            defaults: {border:false},
            items: [{
                columnWidth: .7,
                border: false,
                layout: "anchor",
                defaults: {border:false},
                items : [{
                    layout: "absolute",
                    width: 420,
                    height: 40,
                    items: [{
                        xtype: "label",
                        text: "Top Level Domain:",
                        x: 2,
                        y: 11
                    },
                    lovComboTLD,
                    {
                        id: "domainAddButton",
                        xtype: "button",
                        text: lang('+'),
                        style: "float:left;padding-left:3px",
                        x: 316,
                        y: 6,
                        listeners:{
                            click: function(){
                                createAddEditTld('add');
                            }
                        }
                    },{
                        id: "domainEditButton",
                        xtype: "button",
                        text: lang('Edit TLD'),
                        style: "float:left;padding-left:3px",
                        x: 352,
                        y: 6,
                        hidden:true,
                        listeners:{
                            click: function(){
                                createAddEditTld('edit');
                            }
                        }
                    }]
                }]
            },{
                columnWidth: .3,
                border: false,
                layout: "anchor",
                defaults: {border:false},
                items : [billingCyclesRowPackageIsTaxable,billingCyclesRowForceUpdate]
            }]
        }]
    },
    {
        region: "center",
        height: 400,
        layout: "fit",
        autoscroll:true,
        items: [tldpricinggrid]
    }]
});


/*
 * Advanced tab
 */

allowSelfManage = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    y: 210,
    border: false,
    items: [{
        xtype: "label",
        name:  "lblallowselfmanage",
        width: 300,
        x: 20,
        y: 14,
        text: "Allow 'Self-Manage' Domain Orders?",
        style : "font-weight:bold"
    },
    new Ext.form.Checkbox({
        id:'adv_allowSelfManage',
        width: 10,
        x: 2,
        y: 10
    })]
});

allowTransfer = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    y: 210,
    border: false,
    items: [{
        xtype: "label",
        name:  "lblallowtransfer",
        width: 300,
        x: 20,
        y: 14,
        text: "Allow 'Transfer' Domain Orders?",
        style : "font-weight:bold"
    },
    new Ext.form.Checkbox({
        id:'adv_allowTransfer',
        width: 10,
        x: 2,
        y: 10
    })]
});

enableNamesuggest = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    y: 210,
    items: [{
        xtype: "label",
        name:  "lblenableNamesuggest",
        width: 300,
        x: 20,
        y: 14,
        html:"<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='NameSuggest is only supported on certain plugins, check this box if you wish to enable it. <br><b>NameSuggest is used to cross-sell additional configured TLDs to your customers.</b>'>" + lang("Enable NameSuggest?") + "</span>",
        style : "font-weight:bold"
    },
    new Ext.form.Checkbox({
        id:'adv_enableNamesuggest',
        width: 10,
        x: 2,
        y: 10
    })]
});

maxNamesuggestRow = new Ext.Panel({
    layout: "absolute",
    anchor: "100%",
    height: 35,
    y: 210,
    items: [new Ext.form.TextField({
        anchor: "40%",
        x:165,
        y:5,
        id:'adv_maxNamesuggest',
        allowBlank: false,
        value: '5'
    }),
    {
        xtype: "label",
        name:  "lblMaxNamesuggest",
        width: 170,
        y: 7,
        html:"<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='The NameSuggest feature will return the WHOIS results of the entered domain using additional TLDs. Enter the maximum amount of results you wish to display to the customer.'>" + lang("Max NameSuggest Results") + "</span>",
        style : "font-weight:bold"
    }]
});

advancedPanel = new Ext.form.FieldSet({
    layout: "absolute",
    id: 'advancedPanel',
    border:false,
    width: 257,
    height: 450,
    anchor: "100%",
    x: 0,
    style: 'padding:0px;background-color:#F5F5F5 ',
    items: [{
        layout: 'column',
        border: false,
        items:  [{
            columnWidth:  1,
            layout:'form',
            bodyStyle:'padding:0 5px 0 5px',
            border:       false,
            items:[allowSelfManage, allowTransfer, enableNamesuggest,maxNamesuggestRow]
        },new Ext.form.NumberField({
            id:'advancedClicked',
            hidden: true,
            width: 10,
            value:'1',
            x: 7,
            y: 4
        })]
    }]
});



/*
 * Functions to handle Domain Pricing grid updates
 */
// Save the pricing grid back to the main store
function saveGridPricing(recordId) {

    // Save the grid
    var arraydata = new Array();
    // Update the tld_store
    var rec = tld_store.getAt(recordId);
    rec.set('pricing', arraydata);
    rec.commit();
    for(x=0;x<store.getCount();x++){
        var workingArray = [];
        var workingPeriod = store.getAt(x).get('period');

        if(workingPeriod.charAt(workingPeriod.length) == 's') {
            workingPeriod = workingPeriod.substring(0,workingPeriod.length-6);
        } else {
            workingPeriod = workingPeriod.substring(0,workingPeriod.length-5);
        }

        workingArray['period'] = workingPeriod;
        workingArray['period_id'] = workingPeriod;
        workingArray['price'] = store.getAt(x).get('price');
        workingArray['transfer'] = store.getAt(x).get('transfer');
        workingArray['renew'] = store.getAt(x).get('renew');

        arraydata[x] = workingArray;
    }

    // Update the tld_store
    //var rec = tld_store.getAt(recordId);
    rec.set('pricing', arraydata);
    rec.commit();
}

// Clear and reset the grid
function clearResetGrid(disable) {

    if(disable == true) {
        // Disable the grid buttons
        Ext.getCmp('gridAddPricing').setDisabled(true);
        Ext.getCmp('gridDeletePricing').setDisabled(true);
        Ext.getCmp('domainEditButton').hide();
    } else {
        Ext.getCmp('gridAddPricing').setDisabled(false);
        Ext.getCmp('gridDeletePricing').setDisabled(false);
        Ext.getCmp('domainEditButton').show();
    }

    // Clear the grid
    store.loadData([]);
}


/*
 * Functions for handing the add / edit TLD popup
 */
function createAddEditTld(what) {

   if(what == 'add') {
       pageTitle = 'Add TLD';
       buttonTitle = 'Save';
   } else {
       pageTitle = 'Edit TLD';
       buttonTitle = 'Update';
   }

    // Get a list of registrar plugin's and save them in a store for the dropdown
    registrarstore = new Ext.data.JsonStore({
        id:             "registrarstore",
        root:           'pluginlist',
        idProperty:     'internalname',
        remoteSort:     true,
        fields:         [
                            'internalname',
                            'name'
                        ],
        proxy:          new Ext.data.HttpProxy({
                            url:  'index.php?fuse=admin&action=GetRegistrarList'
                        })
    });
    registrarstore.setDefaultSort('internalname', 'asc');
    registrarstore.load();

    // Create the dropdown of Registrar plugins
    registrardropdown = new Ext.form.ComboBox({
        anchor:'100%'
       ,fieldLabel: lang('Registrar Plugin (Automatic Registration)')
       ,hideOnSelect:false
       ,editable:false
       ,maxHeight:200
       ,store:registrarstore
       ,displayField:'name'
       ,hiddenName: 'registrar'
       ,valueField:'internalname'
       ,triggerAction:'all'
       ,mode:'local'
       ,beforeBlur : Ext.emptyFn,
       value: '----'
    });

    // Dropdown box for auto renew
    tldName = new Ext.form.TextField({
        fieldLabel: lang('Domain Extension (TLD)'),
        id:'name',
        name: 'name',
        xtype: "textfield",
        allowBlank:false,
        anchor:'100%'
    });

    ckDomainsDefaultTLD = new Ext.form.Checkbox({
        id:'isDefault',
        width: 10,
        x: 3,
        y: 1
    });

    domainsDefaultTLD = new Ext.Panel({
        layout: "absolute",
        anchor: "100%",
        height: 35,
        y: 210,
        border: false,
        items: [
              {
                xtype: "label",
                name:  "lbldomainsDefaultTLD",
                width: 150,
                x: 20,
                y: 4,
                html: lang("<span class='tip-target' qtip='Check this box to make this TLD the default (It will always appear first in any dropdown). Note: You can only have 1 default TLD.' style='top: 0px;border-bottom: 1px solid #DFDFDF;'>Make Default?</span>"),
                style : "font-weight:bold"
             },
             ckDomainsDefaultTLD
        ]
    });

    // Create the form layout
    addEditTldForm = new Ext.FormPanel({
        labelAlign: 'top',
        frame:true,
        hideBorders:true,
        shadow:false,
        floating:false,
        height:140,
        width: 270,
        items:[tldName,registrardropdown, domainsDefaultTLD]
    });

   // Build the window
   addEditTld = new Ext.Window({
        layout:'fit',
        title:pageTitle,
        width: 270,
        shadow:false,
        forceLayout:true,
        autoHeight:true,
        modal:true,
        closeAction:'hide',
        plain: true,
        items: [addEditTldForm],
        fbar: [{
            text: lang('Cancel'),
            handler: function(){
                addEditTld.hide();
            }
        },{
            id: "tldDeleteButton",
            xtype: "button",
            text: lang('Delete TLD'),
            //style: "float:left;padding-left:3px",
            hidden:true,
            listeners:{
                click: function() {
                    // Ask to delete
                    Ext.Msg.show({
                        title:'Delete TLD?',
                        msg: "You are sure that you wish to delete the TLD '."+tldName.getValue()+"' and its associated pricing data?",
                        buttons: Ext.Msg.YESNO,
                        fn: deleteTld,
                        //animEl: 'elId',
                        icon: Ext.MessageBox.WARNING
                    });
                }
            }
        },
        {
            text: buttonTitle,
            handler: function() {
                if(tldName.getValue() != '') {
                    // Decide what function to call
                    if(what == 'add') {
                        // Add the TLD to the array
                        addTld(registrardropdown.getValue(), tldName.getValue(), ckDomainsDefaultTLD.getValue());
                    } else {
                        editTld(registrardropdown.getValue(), tldName.getValue(), ckDomainsDefaultTLD.getValue());
                    }

                    // Hide the window
                    addEditTld.hide();
                }
            }
        }],
        listeners: {
            hide: function() {
                addEditTldForm.destroy();
            }
        }
    });

    // Show the window
    addEditTld.show();

    if(what == 'edit') {
        // Update the fields
        var rec = tld_store.getAt(previousSelection);
        tldName.setValue(rec.get('tld'));
        ckDomainsDefaultTLD.setValue(rec.get('isDefault'));
        registrardropdown.setValue(rec.get('registrar'));

        // Show delete
        Ext.getCmp('tldDeleteButton').show();
    }
}


/*
 * Make the tab to load
 */
productPluginTab = {
    title:'Advanced',
    id:'productPluginTab',
    items:[advancedPanel]
}
productPricingTab = {
    title:'Domain Pricing',
    id:'productPricingTab',
    items:[domainsPricingPanel]
}