/**
 * 
 * nExtPanel.js
 * Author: Hendrik Daldrup
 * email : hendrik@osbutler.com
 * 
 * CONFIG OPTIONS:
 *   - how to change default pagination size:
 *       edit this files initGrid() function and change the pageSize: 25 value 
 *       edit the get-overview.php file and change the default $_POST['limit'] = 25 value
 *       BOTH values have to match, otherwise the pagination will break! 
 * 
 */

// global vars
var win;  // login window
var cp;   // Ext CookieProvider
var tabs; // Main window TabPanel
var tree; // Domain TreePanel

// initialize features
function init()
{
	cp = new Ext.state.CookieProvider();
    Ext.state.Manager.setProvider(cp);
    
    Ext.QuickTips.init();
    
    // render basic UI
    initViewport();
    initLoginWindow();
    
    //initMainToolbar();
    //initGrid();
    //initTreePanel();
}

function initLoginWindow()
{
    var login = new Ext.FormPanel({
    	    	    	 
      	labelWidth: 130,
      	url: 'login.php', 
      	frame: true, 
      	title: 'Please Login', 
      	width: 250, 
      	padding: 200, 
      	defaultType: 'textfield',
      	monitorValid: true,
    	items:[{
            fieldLabel: 'WHM Domain',
            id: 'whmDomain', 
            name: 'whmDomain', 
            value: cp.get('whmDomain'),
            allowBlank: false 
        },{ 
            fieldLabel: 'WHM Username', 
            id: 'whmUsername', 
            name: 'whmUsername', 
            value: cp.get('whmUsername'),
            allowBlank: false 
        },{ 
            fieldLabel: 'WHM Password', 
            id: 'whmPassword', 
            name: 'whmPassword', 
            inputType: 'password' 
        },{ 
            fieldLabel: 'WHM Access Key', 
            id: 'whmKey', 
            name: 'whmKey', 
            inputType: 'password',
            maxLength: 980
        }],
    	buttons:[{
            text: 'Login',
            formBind: true,	 
            handler: function(){ 
                login.getForm().submit({ 
                    method: 'POST', 
                    waitTitle: 'Connecting', 
                    waitMsg: 'Sending data...',
                    success: function(){
			   					cp.set('whmDomain', Ext.get('whmDomain').getValue());
			   					cp.set('whmUsername', Ext.get('whmUsername').getValue());
			   					win.hide();
			   					// render dynamic UIs
			   					initTreePanel();
		   						initDomainSearch();
								initGrid();
								initServerGrid();
								initMainToolbar();
                    },
                    failure: function(form, action){
                        if(action.failureType == 'server'){
                            obj = Ext.util.JSON.decode(action.response.responseText); 
                            Ext.Msg.alert('Login Failed!', obj.errors.reason); 
                        } else { 
                            Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText + "abcd"); 
                        } 
                        login.getForm().reset(); 
                    } 
                }); 
            } 
        }] 
	});

 	win = new Ext.Window({
    	layout: 'fit',
    	width: 300,
    	height: 200,
    	closable: false,
    	resizable: false,
    	plain: true,
    	items: [login],
    	draggable: false,
    	modal: true
	});
	win.show();
}

function initViewport()
{
	tabs = new Ext.TabPanel({
		region: 'center',
        deferredRender: false,
        enableTabScroll: true,
        activeTab: 0,
        items:[{
        	contentEl: 'center1',
            title: 'My Domains - Overview',
            autoScroll: true
        }],
        plugins: new Ext.ux.TabCloseMenu()
    });

    viewport = new Ext.Viewport({
    	layout: 'border',
        items:[
        	new Ext.BoxComponent({
        		region: 'north',
                el: 'north',
                height: 50
            }),{
                region: 'south',
                contentEl: 'south',
                split: false,
                height: 50,
                minSize: 50,
                maxSize: 200,
                title: 'nExtPanel Information',
                margins: '0 0 0 0'
            },{
                region: 'east',
                id: 'east-panel',
                title: 'Server Environment',
                collapsible: true,
                split: true,
                width: 225,
                minSize: 175,
                maxSize: 400,
                layout: 'fit',
                margins: '0 5 0 0',
                items:
                    new Ext.TabPanel({
                        border: false,
                        activeTab: 0,
                        tabPosition: 'bottom',
                        items:[{
                        	contentEl: 'serverTab',
                            //autoLoad: { url: 'get-information.php', params: ''},
                            title: 'Server Information',
                            autoScroll: true
                        }]
                    })
            },{
                region: 'west',
                id: 'west-panel',
                title: 'Account Management',
                split: true,
                width: 200,
                minSize: 250,
                maxSize: 400,
                collapsible: true,
                margins: '0 0 0 5',
                layout: 'accordion',
                layoutConfig:{
                    animate: true
                },
                items: [{
                    contentEl: 'west',
                    title: 'Domain List',
                    border: false,
                    iconCls: 'nav'
                },{
                    title: 'Settings',
                    html: '<p>*BETA*</p>',
                    border: false,
                    iconCls: 'settings'
                }]
            },
            tabs
         ]
    });
}

function initTreePanel()
{
    var Tree = Ext.tree;
    
    tree = new Tree.TreePanel({
        el: 'domaintree',
        bodyBorder: false,
        useArrows: true,
        autoScroll: true,
        animate: true,
        enableDD: true,
        containerScroll: true,
        loader: new Tree.TreeLoader({
            dataUrl: 'get-nodes.php'
        })
    });

    tree.on('click', treeClicker);
    
    // set the root node
    var root = new Tree.AsyncTreeNode({
        text: 'My Domains',
        draggable: false,
        id: 'cpAccount'
    });
    tree.setRootNode(root);

    // render the tree
    tree.render();
    root.expand();
}

function treeClicker(e)
{
	// check the clicked TreeNode is a 'leaf' (an element, not a folder)
	if (e.leaf)
	{
		// check if selected tab already exists & set it as activeTab if it does
		if (!Ext.get(e.id))
		{
			
			if (e.id.slice(e.id.indexOf('Whm'), e.id.length) == "Whm")
			{
		    	var clickedTab = new Ext.Panel({
					id: e.id, // username is unique on server, so safe to use as element ID
					title: e.parentNode.text + " - WHM", // use the parent nodes text => accounts domain name 
					html: '<iframe src="http://' + e.parentNode.text + ':2086/" width="100%" height="100%" frameborder="0"></iframe>',
/*
					// enable for custom cPanel data support
					autoLoad: {
						//url: 'get-accountData.php', 
						//params: 'id=' + e.id + '&domain=' + e.parentNode.text, 
						//scripts: true 
					},
					autoScroll: true,
*/
					closable: true
				});
			}
			else
			{
		    	var clickedTab = new Ext.Panel({
					id: e.id, // username is unique on server, so safe to use as element ID
					title: e.parentNode.text, // use the parent nodes text => accounts domain name 
					html: '<iframe src="http://' + e.parentNode.text + ':2082/" width="100%" height="100%" frameborder="0"></iframe>',
/*
					// enable for custom cPanel data support
					autoLoad: {
						//url: 'get-accountData.php', 
						//params: 'id=' + e.id + '&domain=' + e.parentNode.text, 
						//scripts: true 
					},
					autoScroll: true,
*/
					closable: true
				});
			}
			tabs.add(clickedTab).show();

		} else {
			// make existing tab active one
			tabs.setActiveTab(e.id);
		}
	}
}

function initDomainSearch()
{
	searchField = new Ext.form.TextField({
		width: 250,
		emptyText: 'Find a Domain',
		renderTo: 'domainsearch',
		listeners: {
			render: function(f){
				f.el.on('keydown', filterTree, f, {buffer: 350});
			}
		}
	});
	
	var filter = new Ext.tree.TreeFilter(tree, {
		clearBlank: true,
		autoClear: true
	});
	var hiddenPkgs = [];
	function filterTree(e){
		var text = e.target.value;
		Ext.each(hiddenPkgs, function(n){
			n.ui.show();
		});
		if(!text){
			filter.clear();
			return;
		}
		tree.collapsed = false;
		
		var re = new RegExp('^' + Ext.escapeRe(text), 'i');

		filter.filterBy(function(n){
			if (re.test(n.text) || n.isLeaf()) return true;
			else return false;
		});
	}	
}

function initGrid()
{
	var DataStore = new Ext.data.Store({
		id: 'DataStore',
      	proxy: new Ext.data.HttpProxy({
      		url: 'get-overview.php',
            method: 'POST'
        }),
        baseParams: { task: "LISTING" },
      reader: new Ext.data.JsonReader({
        root: 'results',
        totalProperty: 'total',
        id: 'id'
      },[  
        { name: 'Domain', type: 'string', mapping: 'domain' },
        { name: 'Diskspace', type: 'int', mapping: 'diskused' },
        { name: 'Email', type: 'string', mapping: 'email' },
        { name: 'Ip', type: 'string', mapping: 'ip' },
        { name: 'Disklimit', type: 'string', mapping: 'disklimit' },
        { name: 'Owner', type: 'string', mapping: 'owner' },
        { name: 'Partition', type: 'string', mapping: 'partition' },
        { name: 'Startdate', type: 'string', mapping: 'startdate' },
        { name: 'Suspended', type: 'string', mapping: 'suspended' },
        { name: 'Theme', type: 'string', mapping: 'theme' },
        { name: 'Plan', type: 'string', mapping: 'plan' },
        { name: 'User', type: 'string', mapping: 'user' }
      ]),
      sortInfo:{ field: 'Domain', direction: "ASC" }
    });

    function renderYesNo(val){
        if(val == 'yes'){
            return '<span style="color:red;">' + val + '</span>';
        return val;
     }};
    
	var MyColumnModel = new Ext.grid.ColumnModel(
    [{
        header: 'Domain',
        readOnly: true,
        dataIndex: 'Domain',
        width: 50,
        hidden: false
      },{
        header: 'Quota',
        dataIndex: 'Diskspace',
        width: 150,
        editor: new Ext.form.TextField({
            allowBlank: false,
            maxLength: 20,
            maskRe: /([a-zA-Z0-9\s]+)$/   // alphanumeric + spaces allowed
          })
      },{
        header: 'Email',
        dataIndex: 'Email',
        width: 150,
        editor: new Ext.form.TextField({
          allowBlank: false,
          maxLength: 20,
          maskRe: /([a-zA-Z0-9\s]+)$/
          })
      },{
        header: 'IP',
        readOnly: true,
        dataIndex: 'Ip',
        width: 50,
        hidden: true
      },{
        header: 'Disklimit',
        readOnly: true,
        dataIndex: 'Disklimit',
        width: 50,
        hidden: true
      },{
        header: 'Owner',
        readOnly: true,
        dataIndex: 'Owner',
        width: 50,
        hidden: true
      },{
        header: 'Partition',
        readOnly: true,
        dataIndex: 'Partition',
        width: 50,
        hidden: true
      },{
        header: 'Startdate',
        readOnly: true,
        dataIndex: 'Startdate',
        width: 50,
        hidden: true
      },{
        header: 'Suspended',
        readOnly: true,
        dataIndex: 'Suspended',
        renderer: renderYesNo,
        width: 50,
        hidden: true
      },{
        header: 'Theme',
        readOnly: true,
        dataIndex: 'Theme',
        width: 50,
        hidden: true
      },{
        header: 'Plan',
        dataIndex: 'Plan',
        width: 150,
        readOnly: true
      },{
        header: 'User',
        dataIndex: 'User',
        width: 150,
        readOnly: true
      }]
    );
    MyColumnModel.defaultSortable= true;

    // add grid to center2 panel
	var ListingEditorGrid =  new Ext.grid.GridPanel({
		id: 'ListingEditorGrid',
      	store: DataStore,
      	cm: MyColumnModel,
      	enableColLock: false,
      	autoHeight: true,
      	height: 350,
      	viewConfig: {
      		forceFit: true
      	},
      	frame: true,
      	stripeRows: true,
		bbar: new Ext.PagingToolbar({
            pageSize: 25,
            store: DataStore,
            displayInfo: true,
            displayMsg: 'Displaying Domains {0} - {1} of {2}',
            emptyMsg: "No topics to display"
        })
    });

    ListingEditorGrid.render('center1');

    DataStore.load();
}

function initServerGrid()
{
	var DataStore = new Ext.data.Store({
		id: 'DataStore',
      	proxy: new Ext.data.HttpProxy({
      		url: 'get-information.php',
            method: 'POST'
        }),
        baseParams: { task: "LISTING" },
        reader: new Ext.data.JsonReader({
          root: 'results',
          totalProperty: 'total',
          id: 'id'
        },[  
          { name: 'Name', type: 'string', mapping: 'item' },
          { name: 'Value', type: 'string', mapping: 'value' }
        ]),
        sortInfo:{ field: 'Name', direction: "ASC" }
    });

	var MyColumnModel = new Ext.grid.ColumnModel(
    [{
        header: 'Name',
        readOnly: true,
        dataIndex: 'Name',
        width: 50,
        hidden: false
      },{
        header: 'Value',
        dataIndex: 'Value',
        width: 50
      }]
    );
    MyColumnModel.defaultSortable= true;

    // add grid to center2 panel
	var serverGrid =  new Ext.grid.GridPanel({
		id: 'ServerGrid',
      	store: DataStore,
      	cm: MyColumnModel,
      	enableColLock: false,
      	autoHeight: true,
      	viewConfig: {
      		forceFit: true
      	},
      	frame: false,
      	stripeRows: true
    });

    serverGrid.render('serverTab');

    DataStore.load();
}

function initMainToolbar()
{
    var tb = new Ext.Toolbar();
    tb.render('center-toolbar');

    tb.add({
            text: 'Accounts',
            icon: 'icons/user.png',
            cls: 'x-btn-text-icon',
            menu: new Ext.menu.Menu({
        		id: 'accountsMenu',
        		items: [{
            		text: 'Create new Account',
            		icon: 'icons/user_add.png'
            	},{
                	text: 'Modify an Account',
            		icon: 'icons/user_edit.png'
            	},{
                	text: 'Terminate an Account',
            		icon: 'icons/user_delete.png'
        		}]
    		})
    });

    // splitter
    tb.add('-');
    
    tb.add({
            text: 'Packages',
            icon: 'icons/package.png',
            cls: 'x-btn-text-icon',
            menu: new Ext.menu.Menu({
        		id: 'packagesMenu',
        		items: [{
            		text: 'Create new Package',
            		icon: 'icons/package_add.png'
            	},{
                	text: 'Modify a Package',
            		icon: 'icons/package_go.png'
            	},{
                	text: 'Delete a Package',
            		icon: 'icons/package_delete.png'
        		}]
    		})
    });

    // splitter
    tb.add('-');

}

function logout()
{
	// reload page on logout to force UI reset
	window.location.reload();
}

// TEST: add a tab to main panel
function testAddTab()
{
	tabs.add({
		title: 'New Tab',
		autoLoad: { url: 'ext-core.js', params: '' },
		autoScroll: true,
		closable: true
	}).show();
}

Ext.onReady(function()
{
	init();
});
