/*
 * 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 ViewPendingCCInvoked = false;
var waitingMask;

function ViewPendingCC(){
    // Prevent this from being called twice
    if($('pendingitems') == null || ViewPendingCCInvoked){
        return;
    }
    
    Ext.QuickTips.init();
    var gridstore = new Ext.data.JsonStore({
        id:             "gridstore",
        root:           'data',
        totalProperty:  'totalcount',
        idProperty:     'customerid',
        remoteSort:     true,
        fields:         [
            'customerid',
            'fullname',
            'userURL',
            'cclastfour'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=clients&action=GetPendingCCList'
        })
    });
    
    var sm = new Ext.grid.CheckboxSelectionModel({
        id:         'cc-sm',
        width:      30,
        listeners:  {
            'rowdeselect':    function(model, rowIndex, record){
                toggleButtons();
            },
            'rowselect':      function(model, rowIndex, record){
                toggleButtons();
            }
        }
    });
    
    function renderName(value, p, record){
        return String.format('<a href="{0}">{1}</a>', record.data.userURL, record.data.fullname);
    }
    
    var grid = new Ext.grid.GridPanel({
        el:               'pendingitems',
        autoHeight:       true,
        store:            gridstore,
        trackMouseOver:   true,
        disableSelection: true,
        loadMask:         true,
        
        // grid columns
        columns:          [
            sm,
            {
                id:         'customerid', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header:     "Customer ID",
                width:      50,
                dataIndex:  "customerid",
                align:      "right",
                hidden:     true
            },
            {
                id:         'customername', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header:     "Customer Name",
                width:      150,
                renderer:   renderName,
                dataIndex:  "fullname"
            },
            {
                id:         'cclastfour', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header:     "Last 4",
                width:      50,
                dataIndex:  "cclastfour",
                align:      "right"
            }
        ],
        stripeRows:       true,
        // customize view config
        viewConfig:       {
            forceFit:       true,
            enableRowBody:  true,
            emptyText:      lang("There are currently no CC awaiting validation"),
            scrollOffset:   1
        },
        sm:               sm,
        buttons:          [
            validatebutton = new Ext.Button({
                id:         'validatebutton',
                autoHeight: true,
                arrowAlign: 'right',
                xtype:      'splitbutton',
                text:       "&nbsp;&nbsp;"+lang('Validate CC')+ "&nbsp;&nbsp;",
                disabled:   true
            }),
            deletebutton = new Ext.Button({
                id:         'deletebutton',
                autoHeight: true,
                arrowAlign: 'right',
                xtype:      'splitbutton',
                text:       "&nbsp;&nbsp;"+lang('Delete CC')+"&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.customerid;
        }
        
        return arrayofids;
    }
    
    var btnButtonActionHandler = function(button, event){
        grid.disable();
        
        switch(button.id){
            case "validatebutton":
                Ext.MessageBox.prompt('Validate Credit Card', 'Enter your passphrase:', ValidateCC);
                break;
            case "deletebutton":
                Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete the credit card on file?', DeleteCC);
                break;
        }
    }
    
    function ValidateCC(btn,text){
        if(btn == "ok"){
            var requesturl = "index.php?fuse=clients&action=adminValidateCCNumber";
            
            showWaitingMask();
            
            Ext.Ajax.request({
                url:      requesturl,
                success:  function(xhr){
                    hideWaitingMask();
                    
                    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:   {
                    passphrase:   text,
                    customerids:  Ext.util.JSON.encode(GetSelectedRowIds())
                }
            });
        }else{
            grid.enable();
        }
    }
    
    function DeleteCC(btn){
        if(btn == "yes"){
            var requesturl = "index.php?fuse=clients&action=deleteCCNumber";
            
            showWaitingMask();
            
            Ext.Ajax.request({
                url:      requesturl,
                success:  function(xhr){
                    hideWaitingMask();
                    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:   {
                    customerids:  Ext.util.JSON.encode(GetSelectedRowIds())
                }
            });
        }else{
            grid.enable();
        }
    }
    
    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){
            validatebutton.setDisabled(false);
            deletebutton.setDisabled(false);
        }else{
            validatebutton.setDisabled(true);
            deletebutton.setDisabled(true);
        }
    }
    
    function addButtonListeners(){
        validatebutton.addListener("click",btnButtonActionHandler);
        deletebutton.addListener("click",btnButtonActionHandler);
    }
    
    addButtonListeners();
    
    // render it
    grid.render();
    
    // trigger the data store load
    gridstore.load({params:{start:0, limit:0}});
    
    ViewPendingCCInvoked = true;
}

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