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

pendingccs = {};
pendingccs.ViewPendingCCInvoked = false;

pendingccs.ViewPendingCC = function(){
    // Prevent this from being called twice
    if(document.getElementById('pendingitems') == null || pendingccs.ViewPendingCCInvoked){
        return;
    }
    
    pendingccs.gridstore = new Ext.data.JsonStore({
        id:             "ccgridstore",
        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'
        })
    });
    
    pendingccs.sm = new Ext.grid.CheckboxSelectionModel({
        id:         'cc-sm',
        width:      30,
        listeners:  {
            'rowdeselect':    function(model, rowIndex, record){
                pendingccs.toggleButtons();
            },
            'rowselect':      function(model, rowIndex, record){
                pendingccs.toggleButtons();
            }
        }
    });
    
    pendingccs.renderName = function(value, p, record){
        return String.format('<a href="{0}">{1}</a>', record.data.userURL, record.data.fullname);
    }
    
    pendingccs.grid = new Ext.grid.GridPanel({
        el:               'pendingitems',
        autoHeight:       true,
        store:            pendingccs.gridstore,
        trackMouseOver:   true,
        disableSelection: true,
        loadMask:         true,
        
        // grid columns
        columns:          [
            pendingccs.sm,
            {
                id:         'customerid',
                header:     "Customer ID",
                width:      50,
                dataIndex:  "customerid",
                align:      "right",
                hidden:     true
            },
            {
                id:         'customername',
                header:     "Customer Name",
                width:      150,
                renderer:   pendingccs.renderName,
                dataIndex:  "fullname"
            },
            {
                id:         'cclastfour',
                header:     "Last 4",
                width:      50,
                dataIndex:  "cclastfour",
                align:      "right"
            }
        ],
        stripeRows:       true,
        viewConfig:       {
            forceFit:       true,
            enableRowBody:  true,
            emptyText:      lang("There are currently no CC awaiting validation"),
            scrollOffset:   1
        },
        sm:               pendingccs.sm,
        buttons:          [
            pendingccs.validatebutton = new Ext.Button({
                id:         'validateccsbutton',
                autoHeight: true,
                arrowAlign: 'right',
                xtype:      'splitbutton',
                text:       "&nbsp;&nbsp;"+lang('Validate CC')+ "&nbsp;&nbsp;",
                disabled:   true
            }),
            pendingccs.deletebutton = new Ext.Button({
                id:         'deleteccsbutton',
                autoHeight: true,
                arrowAlign: 'right',
                xtype:      'splitbutton',
                text:       "&nbsp;&nbsp;"+lang('Delete CC')+"&nbsp;&nbsp;",
                disabled:   true
            })
        ],
        buttonAlign:      'left'
    });
    
    pendingccs.GetSelectedRowIds = function(){
        var arrayofids = new Array();
        rows = pendingccs.sm.getSelections();
        
        for(x = 0; x < rows.length; x++){
           arrayofids[x] = rows[x].data.customerid;
        }
        
        return arrayofids;
    }
    
    pendingccs.btnButtonActionHandler = function(button, event){
        pendingccs.grid.disable();
        
        switch(button.id){
            case "validateccsbutton":
                //The line inside does not work in Internet Explorer
                if(/*@cc_on!@*/true){
                    Ext.MessageBox.getDialog().body.child('input').dom.type='password';
                }
                Ext.MessageBox.prompt('Validate Credit Card', 'Enter your passphrase:', ValidateCC);
                break;
            case "deleteccsbutton":
				Ext.Msg.show({
					title:    "Delete Credit Card?",
					msg:      lang("Are you sure you want to delete the credit card on file?"),
					buttons:  Ext.Msg.YESNOCANCEL,
					fn: function(btn, text){
						if(btn == "yes"){
							var requesturl = "index.php?fuse=clients&action=deleteCCNumber";
							pendingitems.showMask();
							Ext.Ajax.request({
								url:      requesturl,
								success:  function(xhr){
									pendingitems.hideMask();
									pendingccs.grid.enable();
									pendingccs.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(){
									pendingitems.hideMask();
									pendingccs.grid.enable();
								},
								params: { customerids:  Ext.util.JSON.encode(GetSelectedRowIds()) }
							});
						} else {
							pendingccs.grid.enable();
						}
					},
					icon:     Ext.MessageBox.WARNING
				});
				break;
        }
    }
    
    function ValidateCC(btn,text){
        if(btn == "ok"){
            var requesturl = "index.php?fuse=clients&action=adminValidateCCNumber";
            pendingitems.showMask();
            Ext.Ajax.request({
                url:  requesturl,
                success:  function(xhr){
                    pendingitems.hideMask();
                    pendingccs.toggleButtons(0);
                    pendingccs.grid.enable();
                    pendingccs.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(){
                    pendingitems.hideMask();
                    pendingccs.grid.enable();
                },
                params:   {
                    passphrase:   text,
                    customerids:  Ext.util.JSON.encode(pendingccs.GetSelectedRowIds())
                }
            });
        }else{
            pendingccs.grid.enable();
        }
    }
    
    // option button code
    pendingccs.toggleButtons = function(count){
        if(count == undefined){
            count = pendingccs.sm.getCount();
        }
        if(count > 0){
            pendingccs.validatebutton.setDisabled(false);
            pendingccs.deletebutton.setDisabled(false);
        }else{
            pendingccs.validatebutton.setDisabled(true);
            pendingccs.deletebutton.setDisabled(true);
        }
    }
    
    pendingccs.addButtonListeners = function(){
        pendingccs.validatebutton.addListener("click",pendingccs.btnButtonActionHandler);
        pendingccs.deletebutton.addListener("click",pendingccs.btnButtonActionHandler);
    }
    
    pendingccs.addButtonListeners();
    // render it
    pendingccs.grid.render();
    // trigger the data store load
    pendingccs.gridstore.load({params:{start:0, limit:0}});
    pendingccs.ViewPendingCCInvoked = true;
}