var DomainWin;
var pgWin;
var editFrom = 1;

Ext.onReady(function(){

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


    // 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 Name');
            var deleteButtonTF = false;
            var DomainId = id;

        } else {
            buttonText = lang('Save');
            titleText = '&nbsp;&nbsp;'+lang('Add Domain Name');
            var deleteButtonTF = true;
            var DomainId = id;
        }

        
        
        
        /*
         * Functions to make the Domain Information Tab
         */
        
        // Yes / No options for dropdowns
        var yesno = [
                     ['Yes'],
                     ['No']
                    ];            
            

        // Dropdown box for auto renew
        var autorenew = new Ext.form.ComboBox({
        	fieldLabel: lang('Auto Renew'),
        	anchor:'100%',
            hiddenName: 'renew',
            store: new Ext.data.SimpleStore({
            	fields: ['renew'],
            	data : yesno 
            }),
            displayField: 'renew',
            mode: 'local',
            triggerAction: 'all',
            editable: false,
            value: "Yes"
        });
        
        var years = [
                     ['1 Year'],
                     ['2 Years'],
                     ['3 Years'],
                     ['4 Years'],
                     ['5 Years'],
                     ['6 Years'],
                     ['7 Years'],
                     ['8 Years'],
                     ['9 Years'],
                     ['10 Years']
                    ];            
            

        // Dropdown box for auto renew
        reglength = new Ext.form.ComboBox({
        	fieldLabel: lang('Registration Length'),
        	anchor:'100%',
            hiddenName: 'registrationlength',
            store: new Ext.data.SimpleStore({
            	fields: ['registrationlength'],
            	data : years 
            }),
            displayField: 'registrationlength',
            mode: 'local',
            triggerAction: 'all',
            editable: false,
            value: "1 Year"
        });
        
        
        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'),
            editable:false,
            store:registrarstore,
            displayField:'name',
            hiddenName: 'registrar',
            valueField:'internalname',
            triggerAction:'all',
            mode:'local',
            value: '----'
       });
        
        // Make the Group of fields
        detailsFieldSet = [

        {
            fieldLabel: lang('Domain Name'),
            id:'name',
            name: 'name',
            xtype: "textfield",
            allowBlank:false,
            anchor:'100%'
        },
        registrardropdown,
        reglength,
        autorenew,
        {
            fieldLabel: lang('Domain ID'),
            id:'domainid',
            name: 'domainid',
            xtype: "textfield",
            allowBlank:false,
            disabled:true,
            anchor:'100%'
        },{
            fieldLabel: lang('Expiration Date'),
            id:'expires',
            name: 'expires',
            xtype: "textfield",
            allowBlank:false,
            disabled:true,
            anchor:'100%'
        },{
            fieldLabel: lang('Registration Status'),
            id:'registration',
            name: 'registration',
            xtype: "textfield",
            allowBlank:false,
            disabled:true,
            anchor:'100%'
        },{
            fieldLabel: lang('Purchase Status'),
            id:'purchase',
            name: 'purchase',
            xtype: "textfield",
            allowBlank:false,
            disabled:true,
            anchor:'100%'
        }]; // ADD MORE FIELDS HERE


        
        
        
        
        
        /*
         * Fucntions to load contact information
         * No loger a grouping grid, as only registrant info is shown
         */
        
        // Define the fields
        var RecurringCharge = Ext.data.Record.create([
                                                      {name: 'id'},
                                                      {name: 'field'},
                                                      {name: 'group'},
                                                      {name: 'name'},
                                                      {name: 'value'}
                                                   ]);

        // Start a reader
    	var myReader = new Ext.data.JsonReader({
    		totalProperty: "totalcount",
    		root: "results",
    		id: "id" }, 
            RecurringCharge  
        );

        // Load the data   
    	var url = 'index.php?fuse=domains&action=GetContactInformation&domainid=' + DomainId;
    	contactGrid_store = new Ext.data.Store({
    		id: "entries_store",
    		url: url,
    		reader: myReader,
    		sortInfo: {field: 'id', direction: "asc"},
    		fields: ['id','field','group','name','value']
       	});

        // Check the results to see if nothing was returned
        contactGrid_store.on('load', function(store, data){


            // Disable the tab
            if(store.getCount() != '') {

                tabs.unhideTabStripItem('contactTab');
            }
        });

        // Create the pricing grid
        var contactGrid = new Ext.grid.EditorGridPanel({
                store: contactGrid_store,
                id: 'contactGrid',
                region:'center',
                //margins: '0 5 5 5',

                clicksToEdit:1,
                columns: [
                    {
                        id: 'name',
                        header: 'Name',
                        dataIndex: 'name',
                        width: 180,
                        menuDisabled:true
                    },{
                        id: 'value',
                        header: 'Value',
                        dataIndex: 'value',
                        width: 320,
                        menuDisabled:true,
                        editor:new Ext.form.TextField({})
                    },
                    {header: lang("Contact Information"), width: 20, sortable: true, hidden:true, dataIndex: 'group'}
                ]
            });

        
        
        
        
        /*
         * Function to load the DNS Settings
         */
        dnssettings_store = new Ext.data.JsonStore({
            id: "dnssettings_store",
            root: 'data',
            idProperty: 'id',
            remoteSort: true,
            fields: [
                'id','hostname','address', 'type'
            ],
            proxy: new Ext.data.HttpProxy({
                url: 'index.php?fuse=domains&action=GetDNSSettings&domainid=' + DomainId
            })
        });

        // Check the results to see if nothing was returned
        dnssettings_store.on('load', function(store, data){

            // Disable the tab
            if(store.getCount() != '') {

                tabs.unhideTabStripItem('dnsTab');
            }
        });

        dnssettings_store.setDefaultSort('period_id', 'asc');

        var records = [
                     ['A'],
                     ['MXE'],
                     ['MX'],
                     ['CNAME'],
                     ['URL'],
                     ['FRAME'],
                     ['TXT']
                    ];  
        

        
        // Create the grid
        var dnssettings = new Ext.grid.EditorGridPanel({
                store: dnssettings_store,
                id: 'dnsGrid',
                region:'center',
                selModel: new Ext.grid.RowSelectionModel(),
                margins: '0 5 5 5',
                clicksToEdit:1,
                width: 600,
                height: 365,
                columns: [
                    {
                        id: 'hostname',
                        header: 'Hostname',
                        dataIndex: 'hostname',
                        width: 240,
                        menuDisabled:true,
                        editor:new Ext.form.TextField({})
                    },{
                        id: 'type',
                        header: 'Record Type',
                        dataIndex: 'type',
                        width: 100,
                        menuDisabled:true,
                        editor: new Ext.form.ComboBox({
                        	store: new Ext.data.SimpleStore({
                            	fields: ['type'],
                            	data : records 
                            }),
                            typeAhead: true,
                            triggerAction: 'all',
                            displayField: 'type',
                            mode: 'local'
                          })
                    },{
                        id: 'address',
                        header: 'IP Address',
                        dataIndex: 'address',
                        width: 180,
                        menuDisabled:true,
                        editor:new Ext.form.TextField({})
                    }
                ],
                tbar: [{
                    text: 'Add DNS Record',
                    handler : function(){
                        var Record = dnssettings.getStore().recordType;
                        var p = new Record({
                            hostname: '',
                            type: 'A',
                            address: '',
                        });
                        
                        // Code to insert a new row
                        dnssettings.stopEditing();
                        var rownum = dnssettings_store.getCount();
                        dnssettings_store.insert(rownum,p);
                        dnssettings.startEditing(rownum, 0);
                    }
                }, '-', {
                    text: 'Delete DNS Record',
                    handler:  function () {
                        var rec = dnssettings.getSelectionModel().getSelected();
                        if (!rec) {
                            return false;
                        }
                        dnssettings.store.remove(rec);
                    }
                }]
            });

        




        /*
         * Function to load the Nameserver Settings
         */
        namesettings_store = new Ext.data.JsonStore({
            id: "namesettings_store",
            root: 'data',
            idProperty: 'id',
            remoteSort: true,
            fields: [
                'id'
            ],
            proxy: new Ext.data.HttpProxy({
                url: 'index.php?fuse=domains&action=GetNSSettings&domainid=' + DomainId
            })
        });

        // Check the results to see if nothing was returned
        namesettings_store.on('load', function(store, records, options){

            // Disable the tab
            if(store.getCount() != '') {

                tabs.unhideTabStripItem('nsTab');
            }

            alert(dump(records));
        });



        // Create the grid
        var namesettings = new Ext.grid.EditorGridPanel({
                store: namesettings_store,
                id: 'nameserversGrid',
                region:'center',
                selModel: new Ext.grid.RowSelectionModel(),
                margins: '0 5 5 5',
                clicksToEdit:1,
                width: 600,
                height: 365,
                columns: [
                    {
                        id: 'hostname',
                        header: 'Hostname',
                        dataIndex: 'hostname',
                        width: 240,
                        menuDisabled:true,
                        editor:new Ext.form.TextField({})
                    },{
                        id: 'type',
                        header: 'Record Type',
                        dataIndex: 'type',
                        width: 100,
                        menuDisabled:true,
                        editor: new Ext.form.ComboBox({
                        	store: new Ext.data.SimpleStore({
                            	fields: ['type'],
                            	data : records
                            }),
                            typeAhead: true,
                            triggerAction: 'all',
                            displayField: 'type',
                            mode: 'local'
                          })
                    },{
                        id: 'address',
                        header: 'IP Address',
                        dataIndex: 'address',
                        width: 180,
                        menuDisabled:true,
                        editor:new Ext.form.TextField({})
                    }
                ],
                tbar: [{
                    text: 'Add DNS Record',
                    handler : function(){
                        var Record = dnssettings.getStore().recordType;
                        var p = new Record({
                            hostname: '',
                            type: 'A',
                            address: '',
                        });

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


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

        tabs = new Ext.TabPanel({
        	id:'tabpanel',
			 xtype:'tabpanel'
 				,activeItem:0
 				,border:false
 				,anchor:'100% 100%'
 				,deferredRender:false
 				,defaults:{
 					 layout:'form'
 					,defaultType:'textfield'
 				}
 				,items:[
 				{
 					 title:'Domain Information',
 					 labelAlign: 'right',
					 labelWidth: 120,
 					 bodyStyle:'padding:5px',
 					 items:[detailsFieldSet]
 				},{
					title:'Registrant Information',
					layout:'fit',
					id: 'contactTab',

  					items:[contactGrid]
  				},{
  					title:'Name Servers',
  					id: 'nsTab',
  					items:[namesettings]
  				},{
  					title:'DNS Settings',
   					id: 'dnsTab',
       				items:[dnssettings]
       			},{
       				title:'Transfer',
       				id: 'transferTab',
           			items:[]
           		}]
 			} );
        
        // Create the form layout
        DomainWinform = new Ext.FormPanel({
            frame:true,
            hideBorders:true,
            shadow:false,
            floating:false,
            height:400,
            title: '',
            //width: 550,
                     items:[tabs]
        });
        
        // Button to register the current domain
        registerButton = new Ext.Button({
	                text: lang('Register / Activate Domain'),
	                id: 'registerButton',
	                hidden: true,
	                handler: function(){
		                DomainWinform.getForm().submit({
                                    waitMsg:lang('Registering Domain'),

		                clientValidation: true,
		                url: 'index.php?fuse=domains&action=SaveDomain&register=1',
		                params: {
		                	id : DomainId
		                },
		                success: function(form, action) {
		                    var response = Ext.util.JSON.decode(action.response.responseText);
		                    
		                    //Check if we have an activly registered domain or not
		                    if(response.data.success == 1) {
		                    	Ext.Msg.alert('Success', response.data.message);
			                   win.hide();
                                           if (editFrom == 1) {
                                               gridstore.load();
                                           } else {
                                               entries_store.load();
                                           }
		                    } else {
		                    	Ext.Msg.alert('Failure', response.data.message);
		                    }
		                },
		                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:
		                            var response = Ext.util.JSON.decode(action.response.responseText);
                                            Ext.Msg.alert("Errors", response.message);
		                   }
		                }
		            });
            		}
            	}); 

    addDomainTriggerRegistrar = new Ext.form.Checkbox({
        id:               'addDomainTriggerRegistrar',
        name:             'addDomainTriggerRegistrar',
        value:            false,
        validationEvent:  false,
        hideLabel:        true,
        boxLabel:         lang('Register Domain on Save'),
        hidden:           true
    });

        // Create the window
        win = new Ext.Window({
            layout:'fit',
            title:titleText,
            width:550,
            y:125,
            shadow:false,
            autoHeight:true,
            modal:true,
            closeAction:'hide',
            plain: true,
            buttonAlign: 'left',
            items: [DomainWinform],
            fbar: [addDomainTriggerRegistrar, registerButton,
            	'->',
                {
                        text: lang('Cancel'),
                        handler: function(){
                            win.hide();
                        }
                    },
                   {
                        text: buttonText,
                        handler: function(){
                                DomainWinform.getForm().submit({
                                clientValidation: true,
                                waitMsg:lang('Saving Domain'),
                                url: 'index.php?fuse=domains&action=SaveDomain',
                                params: {
                                    id : DomainId,
                                    contactNames: Ext.util.JSON.encode(getContactNames()),
                                    contactValues: Ext.util.JSON.encode(getContactValues()),
                                    dnshostnameValues: Ext.util.JSON.encode(getDnsHostnameValues()),
                                    dnstypeValues: Ext.util.JSON.encode(getDnsTypeValues()),
                                    dnsaddressValues: Ext.util.JSON.encode(getDnsAddressValues()),
                                    checkboxRegister: Ext.util.JSON.encode(addDomainTriggerRegistrar.getValue())
                                },
                                success: function(form, action) {

                                    // Check if we are registering
                                    if(addDomainTriggerRegistrar.getValue() == true) {

                                        // Show the reply
                                        var response = Ext.util.JSON.decode(action.response.responseText);

                                        //Check if we have an activly registered domain or not
                                        if(response.data.success == 1) {
                                            Ext.Msg.alert('Success', response.data.message);
                                            win.hide();
                                            if (editFrom == 1) {
                                                gridstore.load();
                                            } else {
                                                entries_store.load();
                                            }
                                        } else {
                                            Ext.Msg.alert('Failure', response.data.message);
                                        }
                                    } else {

                                        // Hide the window without showing the response
                                        win.hide();
                                        if (editFrom == 1) {
                                           gridstore.load();
                                        } else {
                                           entries_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:
                                            var response = Ext.util.JSON.decode(action.response.responseText);
                                            Ext.Msg.alert("Errors", response.message);
                                   }
                                }
                            });
                        }
                    }
            ],
            listeners: {
                hide: function() { DomainWinform.destroy(); }
            }
        });

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

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

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

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

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

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


    function loadFields(id){
    	
    	// Hide all of the tabs by default
    	tabs.hideTabStripItem('dnsTab');
        dnssettings_store.load();
    	tabs.hideTabStripItem('contactTab');
        contactGrid_store.load();
    	tabs.hideTabStripItem('nsTab');
        //namesettings_store.load();
    	tabs.hideTabStripItem('transferTab');

    	
    	// Make the on load function
        DomainWinform.getForm().load({
            waitMsg:lang('Loading Domain Data From Registrar'),
            url: 'index.php?fuse=domains&action=GetGeneralInfo&domainid=' + id,
            timeout: 60,
            success: function(form, action) {
                // special loading rules
                var response = Ext.util.JSON.decode(action.response.responseText);
                
                //Check if we have an activly registered domain or not
                if(response.data.disable == 1) {
                	
                	// Disable sone of the fields that can't be edited
                	DomainWinform.findById("name").disable();
                	registrardropdown.disable();
                	reglength.disable();
                	
                } else {
 
                	// Check if we are explicitly disabling the register button
                	if(response.data.disableRegister == 0) {

                            // Show the normal register button
                            regbutton = Ext.getCmp("registerButton");
                            regbutton.show();
                        }
                }
            },
            failure: function(form, action) {
                win.hide();
                var response = Ext.util.JSON.decode(action.response.responseText);
                Ext.Msg.alert("Errors", response.message);
            }
        });
    }

    // Not sure what this does yet
    function setForNewEntry(){
        
    }
    
    // Function to delete the TLD from the database
    function DeleteTld(requesturl){
    	DomainWinform.getForm().submit
        ({
                clientValidation: true,
                url: requesturl,
                params: {
                    newStatus: 'Deleted'
                },
                waitMsg:'Deleting',
                success: function(form, action) {
                	win.hide(); // mIGHT HAVE TO UPDATE THIS TO THE FUNCTION TO CLEAR ALL FIELDS

                   grid = Ext.getCmp("tld-grid");
                   if(grid!=null){
                        grid.getStore().load({params:{start:0}});
                   }
                },
                failure: function(form, action) {
                    switch (action.failureType) {
                        case Ext.form.Action.CLIENT_INVALID:
                            Ext.Msg.alert('Failure', 'Unable to delete the TLD.');
                            break;
                        case Ext.form.Action.CONNECT_FAILURE:
                            Ext.Msg.alert('Failure', 'Ajax communication failed');
                            break;
                        case Ext.form.Action.SERVER_INVALID:
                           var response = Ext.util.JSON.decode(action.response.responseText);
                           Ext.Msg.alert("Errors", response.message);
                   }
                }
            }
        )
    }
});

// Function to load the Edit TLD window
function editDomain(id, editFromLocation)
{
    editFrom = editFromLocation;
    DomainWin.CreateWindow(true,id);
    DomainWin.LoadFields(id);
}

// Function to load the Add TLD Window
function addDomain()
{
    editFrom = 2;
    DomainWin.CreateWindow(false,-1);

    // Hide all the tabs when adding a domain
    tabs.hideTabStripItem('dnsTab');
    tabs.hideTabStripItem('contactTab');
    tabs.hideTabStripItem('nsTab');
    tabs.hideTabStripItem('transferTab');

    // Show the check boxes
    addDomainTriggerRegistrar.show();
    addDomainTriggerRegistrar.setValue(false);
}