/*
 * Ext JS Library 3.0 RC1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */

/*
DO NOT CREATE VARIABLES OR FUNCTIONS WITH THE FOLLOWING NAMES, IN ORDER TO AVOID CONFLICTS:
    pendingMask
    showPendingItems
    PluginPendingItems
    showMask
    hideMask
    cleanjsfiles
    removejscssfile
*/

var ViewPendingOrdersInvoked = false;
var waitingMask;

function ViewPendingOrders(){
    // Prevent this from being called twice
    if($('pendingitems') == null || ViewPendingOrdersInvoked){
        return;
    }
    
    Ext.QuickTips.init();
    var gridstore = new Ext.data.JsonStore({
        id:             "gridstore",
        root:           'data',
        totalProperty:  'totalcount',
        idProperty:     'pendingpackageid',
        remoteSort:     true,
        fields:         [
            'pendingcustomerurl',
            'pendingpackageid',
            'pendingpackagereference',
            'pendingpackagedate',
            'pendingpackagetype',
            'pendingpackagename',
            'packagepaidstatus',
            'pendingpackagecustomername',
            'pendingpackageuserid'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=clients&action=GetPendingOrdersList'
        })
    });
    
    var sm = new Ext.grid.CheckboxSelectionModel({
        id:         'po-sm',
        width:      30,
        listeners:  {
            'rowdeselect':    function(model, rowIndex, record){
                toggleButtons();
            },
            'rowselect':      function(model, rowIndex, record){
                toggleButtons();
            }
        }
    });
    
    function renderPackageUrl(value, p, record){
        return String.format('<a href="{0}" style="font-size:9px;">{1}</a>', record.data.pendingcustomerurl, record.data.pendingpackagereference);
    }

    function renderCustomerName(value,p,record){
        return String.format('<a href="index.php?fuse=clients&view=Admin_Profile_Contact&frmClientID={0}" style="font-size:9px;">{1}</a>', record.data.pendingpackageuserid, record.data.pendingpackagecustomername);
    }
    
    function renderDateUrl(value,p,record){
        return String.format('<a href="{0}" style="font-size:9px;">{1}</a>', record.data.pendingcustomerurl, record.data.pendingpackagedate);
    }
    function renderPackageType(value,p,record){
        return String.format('<a href="{0}" style="font-size:9px;">{1}</a>', record.data.pendingcustomerurl, record.data.pendingpackagetype);
    }
    function renderPackageName(value,p,record){
        return String.format('<a href="{0}" style="font-size:9px;">{1}</a>', record.data.pendingcustomerurl, record.data.pendingpackagename);
    }
    function renderPackageStatus(value,p,record){
        return String.format('<a href="{0}" style="font-size:9px;">{1}</a>', record.data.pendingcustomerurl, record.data.packagepaidstatus);
    }
    
    var grid = new Ext.grid.GridPanel({
        el:               'pendingitems',
        autoHeight:       true,
        store:            gridstore,
        trackMouseOver:   true,
        disableSelection: true,
        loadMask:         true,
        
        
        // grid columns
        columns:          [
            sm,
            {
                id:         'package', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header:     "Pkg",
                width:      150,
                renderer:   renderPackageUrl,
                hidden:     true,
                dataIndex:  "pendingpackagereference"
                //sortable:   true
            },
            {
                id:         'customername', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header:     "Name",
                width:      150,
                renderer:   renderCustomerName,
                hidden:     false,
                dataIndex:  "pendingpackagecustomername"
                //sortable:   true
            }
            ,
            {
                id:         'date', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header:     "Date",
                width:      170,
                renderer:   renderDateUrl,
                dataIndex:  "pendingpackagedate",
                hidden: true,
                //sortable:   true,
                align:      "center"
            },
            {
                id:         'type', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header:     "Type",
                width:      150,
                hidden:     true,
                renderer:   renderPackageType,
                dataIndex:  "pendingpackagetype",
                //sortable:   true,
                align:      "center"
            },
            {
                id:         'name', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header:     "Pkg Name",
                width:      150,
                dataIndex:  "pendingpackagename",
                renderer:   renderPackageName,
                align:      "center"
            },
            {
                id:         'status',
                header:     "Status",
                dataIndex:  "packagepaidstatus",
                renderer:   renderPackageStatus,
                width:      130,
                align:      "center"
                //sortable:   true
            }
        ],
        stripeRows:       true,
        // customize view config
        viewConfig:       {
            forceFit:       true,
            enableRowBody:  true,
            emptyText:         lang("There are currently no oustanding orders"),
            scrollOffset:   1
        },
        sm:               sm,
        buttons:          [
            activatebutton = new Ext.Button({
                id:         'activatebutton',
                autoHeight: true,
                arrowAlign: 'right',
                xtype:      'splitbutton',
                text:       "&nbsp;&nbsp;"+lang('Activate')+ "&nbsp;&nbsp;",
                disabled:   true
            }),
            deletebutton = new Ext.Button({
                id:         'deletebutton',
                autoHeight: true,
                arrowAlign: 'right',
                xtype:      'splitbutton',
                text:       "&nbsp;&nbsp;"+lang('Delete')+ "&nbsp;&nbsp;",
                disabled:   true
            })
        ],
        buttonAlign:      'left'
    });
    
    function GetSelectedRowIds(){
        var arrayofids = new Array();
        rows = sm.getSelections();
        
        for(x = 0; x < rows.length; x++){
           arrayofids[x] = rows[x].data.pendingpackageid;
        }
        
        return arrayofids;
    }
    
    var btnButtonActionHandler = function(button, event){
        grid.disable();
        
        var usepackageplugin = 0;
        var useregistrarplugin = 0;
        var usedeletecustomer = 0;
        
        switch(button.id){
            case "activatebutton":
                requesturl = "index.php?fuse=clients&action=ActivateClientPackages";
                
                var packageplugin = confirm("Do you want to activate the packages using their respective server plugins?");
                
                if(packageplugin == true){
                    usepackageplugin = 1;
                }
                
                var registrarplugin = confirm("Do you want to activate the packages using their respective registrar plugins?");
                
                if(registrarplugin == true){
                    useregistrarplugin = 1;
                }
                
                break;
            case "deletebutton":
                requesturl = "index.php?fuse=clients&action=DeleteClientPackages";
                var confirmmsg = "Are you sure you want to delete the package(s) ?";
                
                var deleteClientPacks = confirm(confirmmsg);
                
                if(deleteClientPacks == false){
                    grid.enable();
                    return false;
                }
                
                var deletecustomer = confirm("Do you want to delete the customers of the selected packages if they don't have more packages?");
                
                if(deletecustomer == true){
                    usedeletecustomer = 1;
                }
                
                break;
        }
        
        showWaitingMask();
        
        Ext.Ajax.request({
            url:      requesturl,
            success:  function(xhr){
                hideWaitingMask();
                
                //refreshgrid
                toggleButtons(0);
                
                grid.enable();
                
                gridstore.load({
                    params: {
                        start:  0
                    }
                });
                
                var data = Ext.util.JSON.decode(xhr.responseText);
                
                if(data.error){
                    //we do not need to repopulate the filters if there was a validation error
                    msg(lang("There was an error performing this action"),"");
                }else if(data.message){
                    msg(data.message,"");
                }else{
                    msg(lang("The action has been performed"),"");
                }
            },
            failure:  function(){
                hideWaitingMask();
                grid.enable();
                Ext.Msg.alert("Fail");
            },
            params:   {
                domainids:          Ext.util.JSON.encode(GetSelectedRowIds()),
                usepackageplugin:   usepackageplugin,
                useregistrarplugin: useregistrarplugin,
                usedeletecustomer:  usedeletecustomer
            }
        });
    }
    
    function showWaitingMask(){
        if(!waitingMask){
            waitingMask = new Ext.LoadMask('pendingitems', {msg:"Please wait..."});
        }
        
        waitingMask.show();
    }
    
    function hideWaitingMask(){
        waitingMask.hide();
    }
    
    // option button code
    function toggleButtons(count){
        if(count == undefined){
            count = sm.getCount();
        }
        
        if(count > 0){
            activatebutton.setDisabled(false);
            deletebutton.setDisabled(false);
        }else{
            activatebutton.setDisabled(true);
            deletebutton.setDisabled(true);
        }
    }
    
    function addButtonListeners(){
        activatebutton.addListener("click",btnButtonActionHandler);
        deletebutton.addListener("click",btnButtonActionHandler);
    }
    
    addButtonListeners();
    
    // render it
    grid.render();
    
    // trigger the data store load
    gridstore.load({params:{start:0, limit:0}});
    
    ViewPendingOrdersInvoked = true;
}

function removeObjects(){
    // Set to NULL all the GLOBAL variables
    ViewPendingOrdersInvoked = null;
    waitingMask = null;
    
    // Set to NULL all the GLOBAL functions
    ViewPendingOrders = null;
}