var TldWin;
var pgWin;


Ext.onReady(function(){

	// Function to process the window request
    function TldWindow(update){
        if(this instanceof TldWindow){
            //this.update = update;
            this.CreateWindow = createWindow;
            this.LoadFields = loadFields;
            this.SetForNewEntry = setForNewEntry;
        }else{
            return new TableTypeWindow();
        }
    }
    TldWin = new TldWindow();


    // Set the window options & decide if we are adding or editing
    function createWindow(update, id) {
        if (update) {
            buttonText = lang('Update');
            titleText = '&nbsp;&nbsp;'+lang('Edit Domain Extension (TLD)');
            var deleteButtonTF = false;
            var TldId = id;

        } else {
            buttonText = lang('Save');
            titleText = '&nbsp;&nbsp;'+lang('Add Domain Extension (TLD)');
            var deleteButtonTF = true;
            var TldId = id;
        }
        
        
        // 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: '----'
       });
        
        // Yes / No options for dropdowns
        var yesno = [
                     ['Yes'],
                     ['No']
                    ];            
            
        // Dropdown box to allow DNS records
        var allowdns = new Ext.form.ComboBox({
        	fieldLabel: lang('Allow User DNS Management?'),
        	anchor:'100%',
            hiddenName: 'dnsmgmt',
            store: new Ext.data.SimpleStore({
            	fields: ['dns'],
            	data : yesno 
            }),
            displayField: 'dns',
            mode: 'local',
            triggerAction: 'all',
            editable: false,
            value: "No"
        });

        // Dropdown box for auto renew
        var autorenew = new Ext.form.ComboBox({
        	fieldLabel: lang('Enable Automatic Domain Renewal?'),
        	anchor:'100%',
            hiddenName: 'autorenew',
            store: new Ext.data.SimpleStore({
            	fields: ['renew'],
            	data : yesno 
            }),
            displayField: 'renew',
            mode: 'local',
            triggerAction: 'all',
            editable: false,
            value: "No"
        });
        
        // Dropdown box for auto renew
        var active = new Ext.form.ComboBox({
        	fieldLabel: lang('TLD Active?'),
        	anchor:'100%',
            hiddenName: 'active',
            store: new Ext.data.SimpleStore({
            	fields: ['active'],
            	data : yesno 
            }),
            displayField: 'active',
            mode: 'local',
            triggerAction: 'all',
            editable: false,
            value: "Yes"
        });
        
        // Make the Group of fields
        detailsFieldSet = [{
            fieldLabel: lang('Domain Extension (TLD)'),
            id:'name',
            name: 'name',
            xtype: "textfield",
            allowBlank:false,
            anchor:'100%'
        },registrardropdown,allowdns,autorenew,active]; // ADD MORE FIELDS HERE
        
        
        // Get the pricing structure
        var getPricingUrl = 'index.php?fuse=admin&action=GetTldPricing&option=grid&tldId=' + TldId;
        tldpricing_store = new Ext.data.JsonStore({
            id: "tldpricing_store",
            root: 'pricing',
            idProperty: 'period_id',
            remoteSort: true,
            fields: [
                'period','price','transfer', 'renew', 'period_id'
            ],
            proxy: new Ext.data.HttpProxy({
                url: getPricingUrl
            })
        });
        tldpricing_store.setDefaultSort('period_id', 'asc');
        tldpricing_store.load();

        
        
        
        // Get the pricing structure
        var getDropdownUrl = 'index.php?fuse=admin&action=GetTldPricing&option=dropdown&tldId=' + TldId;
        dropdown_store = new Ext.data.JsonStore({
            id: "dropdown_store",
            root: 'pricing',
            idProperty: 'period_id',
            remoteSort: true,
            fields: [
                'period', 'period_id'
            ],
            proxy: new Ext.data.HttpProxy({
                url: getDropdownUrl
            })
        });
        dropdown_store.setDefaultSort('period_id', 'asc');
        dropdown_store.load();

        
        // Create the pricing grid
        var tldpricinggrid = new Ext.grid.EditorGridPanel({
                store: tldpricing_store,
                width: 600,
                height: 365,
                id: 'tldpricinggrid',
                region:'center',
                selModel: new Ext.grid.RowSelectionModel(),
                margins: '0 5 5 5',
                clicksToEdit:1,
                columns: [
                    {
                        id: 'period',
                        header: 'Period',
                        dataIndex: 'period',
                        width: 125,
                        menuDisabled:true,
                        editor: new Ext.form.ComboBox({
                            store: dropdown_store,
                            typeAhead: true,
                            triggerAction: 'all',
                            displayField: 'period',
                            valueField: 'period'
                          })
                    },{
                        id: 'price',
                        header: 'Price',
                        dataIndex: 'price',
                        width: 70,
                        menuDisabled:true,
                        editor:new Ext.form.TextField({})
                    },{
                        id: 'renew',
                        header: 'Renew',
                        dataIndex: 'renew',
                        width: 70,
                        menuDisabled:true,
                        editor:new Ext.form.TextField({})
                    },{
                        id: 'transfer',
                        header: 'Transfer',
                        dataIndex: 'transfer',
                        width: 70,
                        menuDisabled:true,
                        editor:new Ext.form.TextField({})
                    }
                ],
                tbar: [{
                    text: 'Add Pricing',
                    handler : function(){
                        var Record = tldpricinggrid.getStore().recordType;
                        var p = new Record({
                            period: 'Choose One...',
                            price: '0.00',
                            renew: '0.00',
                            transfer: '0.00'
                        });
                        
                        // Re-trigger the dropdown load
                        //dropdown_store.load();
                        
                        // Code to insert a new row
                        tldpricinggrid.stopEditing();
                        var rownum = tldpricing_store.getCount();
                        tldpricing_store.insert(rownum,p);
                        tldpricinggrid.startEditing(rownum, 1);
                    }
                }, '-', {
                    text: 'Delete Pricing',
                    handler:  function () {
                        var rec = tldpricinggrid.getSelectionModel().getSelected();
                        if (!rec) {
                            return false;
                        }
                        tldpricinggrid.store.remove(rec);
                    }
                }]
            });

        
        // Create the form layout
        tldwinform = new Ext.FormPanel({
            labelAlign: 'top',
            frame:true,
            hideBorders:true,
            shadow:false,
            floating:false,
            height:400,
            title: '',
            width: 350,
                     items:[{
        				 xtype:'tabpanel'
        				,activeItem:0
        				,border:false
        				,anchor:'100% 100%'
        				,deferredRender:false
        				,defaults:{
        					 layout:'form'
        					,labelWidth:80
        					,defaultType:'textfield'
        					,hideMode:'offsets'
        				}
        				,items:[{
        					 title:'Settings'
        					,bodyStyle:'padding:5px'
        					,items:[detailsFieldSet]
        				},{
        					 title:'Pricing'
        					,items:[tldpricinggrid]
        				}]
        			}]
        });

        // Create the window
        win = new Ext.Window({
            layout:'fit',
            title:titleText,
            width:375,
            y:25,
            shadow:false,
            autoHeight:true,
            modal:true,
            closeAction:'hide',
            plain: true,
            items: [tldwinform],
            fbar: [
                    {
                        text: lang('Cancel'),
                        handler: function(){
                            win.hide();
                        }
                    },
                   {
                        text: buttonText,
                        handler: function(){
                                tldwinform.getForm().submit({
                                clientValidation: true,
                                url: 'index.php?fuse=admin&action=SaveTld',
                                params: {
                                    id : TldId,
                                    period: Ext.util.JSON.encode(getPeriods()),
                                    price: Ext.util.JSON.encode(getPrices()),
                                    renew: Ext.util.JSON.encode(getRenew()),
                                    transfer: Ext.util.JSON.encode(getTransfer())
                                },
                                success: function(form, action) {
                                   win.hide();
                                   tld_store.load();
                                },
                                failure: function(form, action) {
                                    switch (action.failureType) {
                                        case Ext.form.Action.CLIENT_INVALID:
                                            Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
                                            break;
                                        case Ext.form.Action.CONNECT_FAILURE:
                                            Ext.Msg.alert('Failure', 'Ajax communication failed');
                                            break;
                                        case Ext.form.Action.SERVER_INVALID:
                                            Ext.Msg.alert('Failure', action.result.msg);
                                   }
                                }
                            });
                        }
                    }
            ],
            listeners: {
                hide: function() { tldwinform.destroy(); }
            }
        });

        win.show(this);
    
    } // End CreateWindow function

    
   

    function getPeriods(){
        var arrayofids = new Array();
        for(x=0;x<tldpricing_store.getCount();x++){
                arrayofids[x] = tldpricing_store.getAt(x).get('period');
        }
	    return arrayofids;
    }

    function getPrices(){
        var arrayofids = new Array();
        for(x=0;x<tldpricing_store.getCount();x++){
                arrayofids[x] = tldpricing_store.getAt(x).get('price');
        }
	    return arrayofids;
    }
    
    function getRenew(){
        var arrayofids = new Array();
        for(x=0;x<tldpricing_store.getCount();x++){
                arrayofids[x] = tldpricing_store.getAt(x).get('renew');
        }
	    return arrayofids;
    }
    
    function getTransfer(){
        var arrayofids = new Array();
        for(x=0;x<tldpricing_store.getCount();x++){
                arrayofids[x] = tldpricing_store.getAt(x).get('transfer');
        }
	    return arrayofids;
    }

    function loadFields(id){
        tldwinform.getForm().load({
            url: 'index.php?fuse=admin&action=GetTld&tld=' + id,
            waitMsg:lang('Loading'),
            params: {tld: id},
            success: function(form, action) {
                // special loading rules
                var response = Ext.util.JSON.decode(action.response.responseText);
                tldwinform.findById("name").setValue(response.data.name);
                
            },
            failure: function(form, action) {alert('failure');}
            
        });

    }

    // Not sure what this does yet
    function setForNewEntry(){
        
    }
});

// Function to load the Edit TLD window
function editTld(id)
{
    TldWin.CreateWindow(true,id);
    TldWin.LoadFields(id);
}

// Function to load the Add TLD window
function addTld()
{
	TldWin.CreateWindow(false, '-1');
    TldWin.SetForNewEntry();

}