
var ServerWin;
var pgWin;


Ext.onReady(function(){

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


    // 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 Server');
            var serverId = id;

        } else {

            buttonText = lang('Save');
            titleText = '&nbsp;&nbsp;'+lang('Add Server');
            var serverId = id;
        }

        /* Functions related to creating the general properties tab */


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

        // Create the dropdown of Registrar plugins
        plugindropdown = new Ext.form.ComboBox({
           anchor:'100%',
           fieldLabel: lang('Plugin'),
           hideOnSelect:false,
           editable:false,
           maxHeight:200,
           store:pluginsstore,
           displayField:'name',
           hiddenName: 'plugin',
           valueField:'value',
           triggerAction:'all',
           mode:'local',
           beforeBlur : Ext.emptyFn,
           value: 'None',
           listeners:        {
                select: productFieldProductGroup_OnSelect
            }
       });

    function productFieldProductGroup_OnSelect(combo, record, index)
    {
        var row = record.data;

        if(row.value == 'None') {
            tabs.hideTabStripItem('pluginTab');
        } else {
            tabs.unhideTabStripItem('pluginTab');
            productFieldProductGroupActions(row.value);
        }
    }

    function productFieldProductGroupActions(productgroup_id)
    {
        getGroupProducts(productgroup_id);
    }

    function getGroupProducts(productgroup_id)
    {
        pluginOptions_store.removeAll();
        pluginOptions_store.load({
            params: {
                plugin:  productgroup_id,
                serverId: serverId
            }
        });
        //tabs.showTabStripItem('pluginTab');
    }


        var helpViewable = lang('Checking this box will allow customers to view this servers stats from their dashboard.');
        var helpUrl = lang('<b>Optional phpSysInfo Integration</b> <br><br> This field will allow CE plugins to use the xml data exposed by the open source project phpSysInfo.  <br><br>To use, you will need to download the script and install on each server. Place the URL to the script in this field (append ?template=xml for version 2.5 or xml.php for upper phpSysInfo versions) <br><br> phpSysInfo URL <br> http://sourceforge.net/projects/phpsysinfo');
        var helpQuota = lang('Maximum number of domains that this server allows. Leave empty or enter 0 for an unlimited number.');
        // Make the Group of fields
        detailsFieldSet = [{
            fieldLabel: lang('Server Name'),
            id:'servername',
            name: 'servername',
            xtype: "textfield",
            allowBlank:false,
            anchor:'80%'
        },{
            fieldLabel: lang('Hostname'),
            id:'hostname',
            name: 'hostname',
            xtype: "textfield",
            allowBlank:false,
            anchor:'100%'
        },{
            fieldLabel: lang('Shared IP'),
            id:'sharedip',
            name: 'sharedip',
            xtype: "textfield",
            allowBlank:false,
            anchor:'60%'
        },plugindropdown,{
            fieldLabel: lang('Domains Quota'),
            id:'quota',
            name: 'quota',
            xtype: "textfield",
            fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpQuota.replace(/'/g, "&#39;") + "'>" + lang("Domains Quota") + "</span>",
            allowBlank:true,
            anchor:'50%'
        },{
            fieldLabel: lang('Stats URL'),
            id:'stats',
            name: 'stats',
            xtype: "textfield",
            fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpUrl.replace(/'/g, "&#39;") + "'>" + lang("Stats URL") + "</span>",
            allowBlank:true,
            anchor:'100%'
        },{
            fieldLabel: lang('Viewable by Customers?'),
            id:'statsviewable',
            name: 'statsviewable',
            xtype: "checkbox",
            fieldLabel:       "<span style='text-decoration: underline; top: 0px;' class='tip-target' qtip='" + helpViewable.replace(/'/g, "&#39;") + "'>" + lang("Viewable by Customers?") + "</span>",
            allowBlank:true,
            anchor:'100%'
        }]; // ADD MORE FIELDS HERE












        /* FUnctions relating to the Name Servers tab */


        // Get the nameservers
        var getNSUrl = 'index.php?fuse=admin&action=GetNameServers&serverId=' + serverId;
        ns_store = new Ext.data.JsonStore({
            id: "ns_store",
            root: 'data',
            idProperty: 'id',
            remoteSort: true,
            fields: [
                'id','ip','hostname'
            ],
            proxy: new Ext.data.HttpProxy({
                url: getNSUrl
            })
        });
        ns_store.setDefaultSort('id', 'asc');
        ns_store.load();




        // Create the pricing grid
        var nsgrid = new Ext.grid.EditorGridPanel({
                store: ns_store,
                width: 600,
                height: 365,
                id: 'nsgrid',
                region:'center',
                selModel: new Ext.grid.RowSelectionModel(),
                margins: '0 5 5 5',
                clicksToEdit:1,
                columns: [
                    {
                        id: 'id',
                        header: 'ID',
                        dataIndex: 'id',
                        hidden:true
                    },{
                        id: 'hostname',
                        header: 'Hostname',
                        dataIndex: 'hostname',
                        width: 200,
                        menuDisabled:true,
                        editor:new Ext.form.TextField({})
                    },{
                        id: 'ip',
                        header: 'IP Address',
                        dataIndex: 'ip',
                        width: 200,
                        menuDisabled:true,
                        editor:new Ext.form.TextField({})
                    }
                ],
                tbar: [{
                    text: 'Add Nameserver',
                    handler : function(){
                        var Record = nsgrid.getStore().recordType;
                        var p = new Record({
                            hostname: 'ns1.yourserver.com',
                            ip: '00.00.00.00'
                        });

                        // Re-trigger the dropdown load
                        //dropdown_store.load();

                        // Code to insert a new row
                        nsgrid.stopEditing();
                        var rownum = ns_store.getCount();
                        ns_store.insert(rownum,p);
                        nsgrid.startEditing(rownum, 0);
                    }
                }, '-', {
                    text: 'Delete Nameserver',
                    handler:  function () {
                        var rec = nsgrid.getSelectionModel().getSelected();
                        if (!rec) {
                            return false;
                        }
                        nsgrid.store.remove(rec);
                    }
                }]
            });




    /* FUnctions relating to the IP tab */


        // Get the nameservers
        var getIPUrl = 'index.php?fuse=admin&action=GetIPAddresses&serverId=' + serverId;
        ip_store = new Ext.data.JsonStore({
            id: "ip_store",
            root: 'data',
            idProperty: 'id',
            remoteSort: true,
            fields: [
                'serverid','ip'
            ],
            proxy: new Ext.data.HttpProxy({
                url: getIPUrl
            })
        });
        ip_store.setDefaultSort('ip', 'asc');
        ip_store.load();

        // Create the pricing grid
        var ipgrid = new Ext.grid.EditorGridPanel({
                store: ip_store,
                width: 600,
                height: 365,
                id: 'ipgrid',
                region:'center',
                selModel: new Ext.grid.RowSelectionModel(),
                margins: '0 5 5 5',
                clicksToEdit:1,
                columns: [
                    {
                        id: 'ip',
                        header: 'IP Address',
                        dataIndex: 'ip',
                        width: 400,
                        menuDisabled:true,
                        editor:new Ext.form.TextField({})
                    }
                ],
                tbar: [{
                    text: 'Add IP Address',
                    handler : function(){
                        var Record = ipgrid.getStore().recordType;
                        var p = new Record({
                            ip: '00.00.00.00'
                        });

                        // Re-trigger the dropdown load
                        //dropdown_store.load();

                        // Code to insert a new row
                        ipgrid.stopEditing();
                        var rownum = ip_store.getCount();
                        ip_store.insert(rownum,p);
                        ipgrid.startEditing(rownum, 0);
                    }
                }, '-', {
                    text: 'Delete IP Address',
                    handler:  function () {
                        var rec = ipgrid.getSelectionModel().getSelected();
                        if (!rec) {
                            return false;
                        }
                        ipgrid.store.remove(rec);
                    }
                }]
            });




      /* Functions related to the Plugin grid.*/

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


                    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;
                            }
                            // Adding a text field
                            if(o.type == 'text') {

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

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

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

                                // Add the fields to the container
                                pluginOptions_container.add({
                                    fieldLabel: fieldLabel,
                                    id: o.name,
                                    name: o.name,
                                    value: o.value,
                                    xtype: "textarea",
                                    anchor:'100%'
                                });
                            } else if(o.type == 'check') {

                                // Add the fields to the container
                                pluginOptions_container.add({
                                    fieldLabel: fieldLabel,
                                    id: o.name,
                                    name: o.name,
                                    checked: o.value,
                                    xtype: "checkbox",
                                    anchor:'100%'
                                });
                            } else if(o.type == 'yesno') {


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

                                // Dropdown box to allow DNS records
                                var combobox = new Ext.form.ComboBox({
                                    fieldLabel: fieldLabel,
                                    anchor:'50%',
                                    hiddenName: o.name,
                                    store: new Ext.data.SimpleStore({
                                        fields: ['fieldname'],
                                        data : yesno
                                    }),
                                    displayField: 'fieldname',
                                    mode: 'local',
                                    triggerAction: 'all',
                                    editable: false,
                                    value: o.value
                                });

                                // Add the fields to the container
                                pluginOptions_container.add(combobox);
                            }
                    }

                    // Add a secret value
                                pluginOptions_container.add({
                                    id: 'pluginClicked',
                                    name: 'pluginClicked',
                                    value: '1',
                                    fieldLabel: '',
                                    xtype: "textfield",
                                    hidden: true,
                                    anchor:'90%'
                                });
                    // Show the container
                    pluginOptions_container.show();
                    tabs.unhideTabStripItem('pluginTab');
            }
        }
            });

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



        /*
         * Functions relating to setting up the tabs & window
         */

        tabs = new Ext.TabPanel({
        	id:'tabpanel',
                layoutOnTabChange: true,
			 xtype:'tabpanel'
 				,activeItem:0
 				,border:false
 				,anchor:'100% 100%'
 				,deferredRender:false
 				,defaults:{
 					 layout:'form'
 					,defaultType:'textfield'
 				}
 				,items:[
 				{
 					 title:'General',
 					 labelAlign: 'right',
					 labelWidth: 125,
 					 bodyStyle:'padding:5px',
 					 items:[detailsFieldSet]
 				},{
					title:'Name Servers',
					layout:'fit',
					id: 'nsTab',
  					items:[nsgrid]
  				},{
  					title:'IP Management',
                                        layout:'fit',
  					id: 'ipTab',
  					items:[ipgrid]
  				},{
  					title:'Plugin Configuration',
 					 labelAlign: 'right',
					 labelWidth: 125,
 					 bodyStyle:'padding:5px;overflow-y:auto',
   					id: 'pluginTab',
                                        autoScroll:true,
                                        items:[pluginOptions_container]
                                }]
 			} );


        // Create the form layout
        ServerWinform = new Ext.FormPanel({
            frame:true,
            hideBorders:true,
            shadow:false,
            floating:false,
            height:400,
            title: '',
            //width: 550,
                     items:[tabs]
        });







        // Create the window
        win = new Ext.Window({
            layout:'fit',
            title:titleText,
            width:450,
            y:25,
            shadow:false,
            height:400,
            modal:true,
            closeAction:'hide',
            plain: true,
            items: [ServerWinform],
            fbar: [
                    {
                        text: lang('Cancel'),
                        handler: function(){
                            win.hide();
                        }
                    },
                   {
                        text: buttonText,
                        handler: function(){
                           ServerWinform.getForm().submit({
                                clientValidation: true,
                                url: 'index.php?fuse=admin&action=SaveServer',
                                params: {
                                    id : serverId,
                                    nsHostname: Ext.util.JSON.encode(getNSHostnames()),
                                    nsIP: Ext.util.JSON.encode(getNSIPs()),
                                    ips: Ext.util.JSON.encode(getIPs())
                                },
                                success: function(form, action) {
                                   win.hide();
                                   servers_store.load();
                                },
                                failure: function(form, action) {
                                    if(typeof (action.result.message) != "undefined"){
                                        Ext.Msg.alert('Failure', action.result.message);
                                        return;
                                    }
                                    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() {ServerWinform.destroy();}
            }
        });

        win.show(this);

    } // End CreateWindow function




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

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

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


    function loadFields(id){
        tabs.hideTabStripItem('pluginTab');
        ServerWinform.getForm().load({
            url: 'index.php?fuse=admin&action=GetServer&serverId=' + id,
            waitMsg:lang('Loading'),
            params: {tld: id},
            success: function(form, action) {
                // special loading rules
                var response = Ext.util.JSON.decode(action.response.responseText);
                ServerWinform.findById("servername").setValue(response.data.name);
                ServerWinform.findById("hostname").setValue(response.data.hostname);
                ServerWinform.findById("sharedip").setValue(response.data.sharedip);
                ServerWinform.findById("stats").setValue(response.data.statsurl);
                ServerWinform.findById("quota").setValue(response.data.domains_quota);


                if(response.data.plugin == 'None') {
                    tabs.hideTabStripItem('pluginTab');
                } else {

                    pluginOptions_store.load({
                        params: {
                            plugin:  response.data.plugin,
                            serverId: response.data.id
                        }
                    });
                }
            },
            failure: function(form, action) {alert('failure');}

        });

    }

    // Not sure what this does yet
    function setForNewEntry(){
        tabs.hideTabStripItem('pluginTab');
    }


});

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

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

}