var portalColumn1;
var portalColumn2;
var portalColumn3;
var viewport;
var viewportTop;

Ext.onReady(function(){
    
    /////////////////////////////////
    // DYNAMIC DASHBOARD PANELS
    /////////////////////////////////

    // create some portlet tools using built in Ext tool ids
    var tools = [{
        id:'close',
        handler: function(e, target, panel){
            panel.fireEvent('close', panel);
            panel.ownerCt.remove(panel, true);
        }
    }];
    
    var columnwidth = (0.98 / numColumns);
    
    portalColumn1 = new Ext.ux.PortalColumn({
        id: 'portalColumn1',
        columnWidth: col1width,
        style: 'padding:0px 0 10px 10px'
    });
    
    portalColumn2 = new Ext.ux.PortalColumn({
        id: 'portalColumn2',
        columnWidth: col2width,
        style: 'padding:0px 0 10px 10px'
    });
    
    portalColumn3 = new Ext.ux.PortalColumn({
        id: 'portalColumn3',
        columnWidth: col3width,
        style: 'padding:0px 0 10px 10px'
    });
    
    var items;
    
    if (numColumns == 1)
        items = [portalColumn1];
    else if (numColumns == 2)
        items = [portalColumn1, portalColumn2];
    else if (numColumns == 3)
        items = [portalColumn1, portalColumn2, portalColumn3];
    
    

    viewport = new Ext.Container({
        id: 'myContainer',
        applyTo: 'dashboard-plugins',
        hideBorders: true,
        items:[{
            xtype:'portal',
            region:'center',
            margins:'35 5 5 0',
            autoScroll : false,
            items: items,
            listeners: {
                'drop': function(e){
                     movePanel(e, e.columnIndex);
                }
            }
        }]
    });

    portalColumnTop = new Ext.ux.PortalColumn({
        id: 'portalColumnTop',
        columnWidth: 1,
        style: 'padding:10px 10px 0px 10px'
    });

    var itemsTop = [portalColumnTop];

    viewportTop = new Ext.Container({
        id: 'myContainer2',
        applyTo: 'dashboard-plugins-top',
        hideBorders: true,
        items:[{
            xtype:'portal',
            region:'center',
            margins:'35 5 5 0',
            autoScroll : false,
            items: itemsTop,
            listeners: {
                'drop': function(e){
                     movePanel(e, "top");
                }
            }
        }]
    });

    // loop through all the columns
    for (i = 0; i < dashboardPanels.columns.length; i++) {

        // loop through the plugins in each column
        for (j = 0; j < dashboardPanels.columns[i].length; j++) {

            // now find the plugin data
            for (k = 0; k < dashboardPlugins.plugins.length; k++) {
                if (dashboardPlugins.plugins[k].plugin == dashboardPanels.columns[i][j]) {
                    var isCollapsed = false;
                    for (l = 0; l < dashboardPanels.collapsed.length; l++) {
                        if (dashboardPlugins.plugins[k].plugin == dashboardPanels.collapsed[l]) isCollapsed = true;
                    }

                    addPanel(dashboardPlugins.plugins[k].plugin, dashboardPlugins.plugins[k].title, i, isCollapsed,dashboardPlugins.plugins[k].configFunction,dashboardPlugins.plugins[k].configJSFile);
                    break;
                }
            }
        }
    }

    // loop through the plugins in the top column
    for (i = 0; i < dashboardPanels.topColumn.length; i++) {
        // now find the plugin data
        for (j = 0; j < dashboardPlugins.plugins.length; j++) {
            if (dashboardPlugins.plugins[j].plugin == dashboardPanels.topColumn[i]) {
                var isCollapsed = false;
                for (k = 0; k < dashboardPanels.collapsed.length; k++) {
                    if (dashboardPlugins.plugins[j].plugin == dashboardPanels.collapsed[k]) isCollapsed = true;
                }

                addPanel(dashboardPlugins.plugins[j].plugin, dashboardPlugins.plugins[j].title, "top", isCollapsed,dashboardPlugins.plugins[j].configFunction,dashboardPlugins.plugins[j].configJSFile);
                break;
            }
        }
    }

    viewport.doLayout();
    viewportTop.doLayout();
});

function customizeDashboard()
{
    var panel = new Ext.Panel({
        region: 'center',
        autoLoad: {url: 'index.php?fuse=home&view=CustomizeDashboard', scripts: true},
        autoScroll: true
    });
    
    var win = new Ext.Window({
        id          : 'customizeDashboard',
        title       : lang('Customize your dashboard'),
        layout      : 'border',
        width       : 450,
        height      : 400,
        closeable   : true,
        minimizable : false,
        plain       : true,
        items       : panel
    });
    
    win.show();
    
}

function addToDashboard(pluginId, pluginTitle, column, isCollapsed,hasConfigWindow,hasConfigJSFile)
{
    document.getElementById('addpanel_'+pluginId).style.display = 'none';
    addPanel(pluginId, pluginTitle, column, isCollapsed,hasConfigWindow,hasConfigJSFile);
    Ext.Ajax.request({
        url: 'index.php?fuse=home&action=SaveDashboardState&type=panel&task=add&plugin='+pluginId
    });
}

function addPanel(pluginId, pluginTitle, column, isCollapsed, hasConfigWindow,hasConfigJSFile)
{
    var tools;
    if( (hasConfigWindow!=undefined) && (hasConfigWindow!=false) ){
        tools = [{
            id:'gear',
            handler: function(){
                if (hasConfigJSFile) {
                    LazyLoad.js('../plugins/dashboard/'+pluginId+"/"+hasConfigJSFile, function () {
                        eval((hasConfigWindow+"()"));
                    });
                } else {
                    eval((hasConfigWindow+"()"));
                }
                
                //do lazy load
            }
        },{
            id:'close',
            handler: function(e, target, panel){
                panel.fireEvent('close', panel);
                panel.ownerCt.remove(panel, true);
            }
        }];
    }else{
        tools = [{
            id:'close',
            handler: function(e, target, panel){
                panel.fireEvent('close', panel);
                panel.ownerCt.remove(panel, true);
            }
        }];
    }

    var autoloadurlwidth = calculatePanelWidth(column);
    var fullwidth = (column ==  "top" || numColumns == 1)? true : false;

    var portlet = new Ext.ux.Portlet({
        id: 'panel_' + pluginId,
        title: pluginTitle,
        layout: 'fit',
        tools: tools,
        collapsed: isCollapsed,
        autoLoad: {url: 'index.php?nolog=1&fuse=home&view=ViewDashboardPlugin&plugin='+pluginId+'&width='+autoloadurlwidth+'&fullwidth='+fullwidth, scripts: true},
        listeners: {
            'collapse': function(e){
                Ext.Ajax.request({
                    url: 'index.php?fuse=home&action=SaveDashboardState&type=panel&task=collapse&plugin='+pluginId
                });
            },
            'expand': function(e){
                Ext.Ajax.request({
                    url: 'index.php?fuse=home&action=SaveDashboardState&type=panel&task=expand&plugin='+pluginId
                });
            },
            'close': function(e){
                Ext.Ajax.request({
                    url: 'index.php?fuse=home&action=SaveDashboardState&type=panel&task=close&plugin='+pluginId
                });
            }
        }
    });

    if (column == "top") {
        viewportTop.findById('portalColumnTop').add(portlet);
    } else if (column == 0) {
        viewport.findById('portalColumn1').add(portlet);
    } else if (column == 1) {
        viewport.findById('portalColumn2').add(portlet);
    } else if (column == 2) {
        viewport.findById('portalColumn3').add(portlet);
    }
    viewport.doLayout();
    viewportTop.doLayout();
}

function changeNumColumnsAndPercentages(values){
    options = values.split("_");
    columns = options[0];
    if(options.length > 1)
    {
        percentages = options[1];
    }else{
        percentages = "100";
    }
    
    Ext.Ajax.request({
        url: 'index.php?fuse=home&action=SaveDashboardState&type=panel&task=columns&number=' + columns + '&percentages=' + percentages
    });
}

function calculatePanelWidth(column)
{
    var width = 100;
    if (column == "top") {
        width = portalColumnTop.getWidth();
    } else if (column == 0) {
        width = portalColumn1.getWidth();
    } else if (column == 1) {
        width = portalColumn2.getWidth();
    } else if (column == 2) {
        width = portalColumn3.getWidth();
    }
    return width;
}

function movePanel(e, column)
{
    // Tell CE about the moved panel.
    Ext.Ajax.request({
        url: 'index.php?fuse=home&action=SaveDashboardState&type=panel&task=move&plugin='+e.panel.id+'&column='+column+'&row='+e.position
    });
    // Reload the panel so the width is correct.
    var autoloadurlwidth = calculatePanelWidth(column);
    var fullwidth = (column ==  "top" || numColumns == 1)? true : false;
    var plugin = e.panel.id.substr("panel_".length);
    e.panel.load({
        url: 'index.php?nolog=1&fuse=home&view=ViewDashboardPlugin&plugin='+plugin+'&width='+autoloadurlwidth+'&fullwidth='+fullwidth,
        scripts: true
    });
}