Ext.onReady(function(){

    // Create the add button
    var addTLD = new Ext.Button({
        id:"addTLD",
        renderTo:"addtld",
        text: lang('Add Domain Extension'),
        iconAlign: 'left',
        handler:function(){
            closing = false;
            update = false;
            addTld();
        }
    }
    );

	
    // Get and process the JSON data
    tld_store = new Ext.data.JsonStore({
        id: "tld_store",
        root: 'topleveldomains',
        idProperty: 'id',
        remoteSort: true,
        fields: [
        'name','id','plugin', 'dnsmgmt', 'autorenew', 'active','pricing', 'rowid'
        ],
        proxy: new Ext.data.HttpProxy({
            url: 'index.php?fuse=admin&action=GetTldList'
        })
    });
    tld_store.setDefaultSort('name', 'asc');
    tld_store.load();
    
    // Define the row expander template
    var expander = new Ext.ux.grid.RowExpander({
        tpl : new Ext.Template('<div id="myrow-{rowid}" ></div>')
    });
    expander.on('expand', expandedRow);
    

    // Function to load the pricing grid on row expander
    function expandedRow(obj, record, body, rowIndex){
        id = "myrow-" + rowIndex;
        id2 = "mygrid-" + rowIndex;

        // Get and process the JSON data
        theStore2 = new Ext.data.JsonStore({
            id: "theStore2",
            root: 'pricing',
            idProperty: 'period_id',
            remoteSort: true,
            fields: [
            'period_id','period','price', 'renew', 'transfer'
            ],
            proxy: new Ext.data.HttpProxy({
                url: 'index.php?fuse=admin&action=GetTldPricing&option=grid&tldId=' + record.data.id
            })
        });
        theStore2.setDefaultSort('period', 'asc');
        theStore2.load();
        
        var subGrid = new Ext.grid.GridPanel({
            store: theStore2,          
            autoExpandColumn: 'period',
            autoHeight:true,
            id: id2,
            columns: [
            {
                header: "Period",
                id: "period",
                dataIndex: 'period',
                width: 125
            },
            {
                header: "Price",
                dataIndex: 'price',
                width: 90
            },
            {
                header: "Renewal Price",
                dataIndex: 'renew',
                width: 90
            },
            {
                header: "Transfer Price",
                dataIndex: 'transfer',
                width: 90
            }
            ],
            viewConfig: {
                emptyText: "No pricing has been configured for this TLD"
            }
        });        
        subGrid.render(id);
        subGrid.getEl().swallowEvent([ 'mouseover', 'mousedown', 'click', 'dblclick' ]);
    }

    // Function to put together the link for the open window
    function renderTldName(value,p,record){
        var link = "<a href='javascript:editTld(" + record.data.id + ");'>" + record.data.name + "</a>";
        return link;
    }
    function renderPlugin(value,p,record){
        var link = "<a href='javascript:editTld(" + record.data.id + ");'>" + record.data.plugin + "</a>";
        return link;
    }
    
    var sm = new Ext.grid.CheckboxSelectionModel({
        id:'tld-sm',
        width: 30,
        listeners:{
            'rowdeselect': function(model, rowIndex, record){
                toggleButtons();
            },
            'rowselect': function(model, rowIndex, record){
                toggleButtons();
            }
        }
    });
    
    // Create the grid
    var tldgrid = new Ext.grid.GridPanel({
        id: 'tld-grid',
        store: tld_store,
        renderTo: 'tld-list',
        autoExpandColumn: 'name',
        autoHeight:true,
        plugins: [expander],
        stripeRows: true,
        columns: [expander,sm,
        {
            id: 'name',
            header: 'TLD',
            dataIndex: 'name',
            width: 99,
            renderer: renderTldName,
            menuDisabled:true
        },{
            header: 'DNS Management',
            dataIndex: 'dnsmgmt',
            align: 'center',
            menuDisabled:true,
            width: 120
        },{
            header: 'Automatic Renewal',
            dataIndex: 'autorenew',
            align: 'center',
            menuDisabled:true,
            width: 120
        },{
            header: 'Registrar Plugin',
            dataIndex: 'plugin',
            align: 'center',
            menuDisabled:true,
            renderer: renderPlugin,
            width: 120
        },{
            header: 'Active',
            dataIndex: 'active',
            align: 'center',
            menuDisabled:true,
            width: 60
        }

        ],
        sm: sm,
        viewConfig: {
            emptyText: "There are no TLDs available. <a href='javascript:addTld();'>Click here</a> to add one."
        },
        buttons:[deletebutton = new Ext.Button({
            id:'actionbuttons',
            autoHeight:true,
            xtype:'button',
            text:'Delete',
            disabled: true,
            onClick: function(record){
                if(!deletebutton.disabled){
                    Ext.Msg.show({
                        title:    "Delete TLD",
                        msg:      "Are you sure you want to delete the selected TLD(s)?",
                        buttons:  Ext.Msg.YESNO,
                        disabled: true,
                        fn:       function(btn, text){
                            if(btn == 'yes'){
                                requesturl = "index.php?fuse=admin&action=DeleteTld";
                                ProcessAction(requesturl);
                            }
                        },
                        icon:     Ext.MessageBox.QUESTION
                    });
                }
            }
        }),
        clonebutton = new Ext.Button({
            id:'clonebutton',
            autoHeight:true,
            xtype:'button',
            text:'Clone TLD',
            disabled: true,
            onClick: function(record){
                if(!clonebutton.disabled){
                    Ext.Msg.show({
                        title:    "Clone TLD",
                        msg:      "Are you sure you want to clone the selected TLD?",
                        buttons:  Ext.Msg.YESNO,
                        disabled: true,
                        fn:       function(btn, text){
                            if(btn == 'yes'){
                                requesturl = "index.php?fuse=admin&action=CloneTld";
                                ProcessAction(requesturl);
                            }
                        },
                        icon:     Ext.MessageBox.QUESTION
                    });
                }
            }
        })
        ],
        buttonAlign:'left'
    });

    // option button code
    function toggleButtons(count){
        if(count == undefined){
            count = sm.getCount();
        }

        if(count>0){
            deletebutton.setDisabled(false);
            clonebutton.setDisabled(true);
        }else{
            deletebutton.setDisabled(true);
            clonebutton.setDisabled(true);
        }

        // Now enable the clone button
        if(count == 1) {
            clonebutton.setDisabled(false);
        }
    }
      
    function GetSelectedRowIds(){
        var arrayofids = new Array();
        rows = sm.getSelections();
        for(x=0;x<rows.length;x++){
            arrayofids[x] = rows[x].data.id;
        }
        return arrayofids;
    }

    function ProcessAction(requesturl){
        tldgrid.disable();
        Ext.Ajax.request({
            url: requesturl,
            success: function(xhr) {

                // Decode the JSON
                var data = Ext.util.JSON.decode(xhr.responseText);

                // Check if we failed
                if(data.error) {
                     Ext.MessageBox.alert(lang("Errors"), data.message);
                } else {
                    msg(data.response,"");
                }

                // uncheck
                toggleButtons(0);

                //refreshgrid
                tldgrid.enable();
                tld_store.load({
                    params:{start:0}
                });
            },
            failure: function() {
                tldgrid.enable();
                Ext.MessageBox.alert(lang("Errors"), "There was an error performing this action");
            },
            params: {
                ids: Ext.util.JSON.encode(GetSelectedRowIds())
            }
        });    
    }
});