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

Ext.onReady(function(){

    Ext.QuickTips.init();
	var gridstore = new Ext.data.JsonStore({
            id: "gridstore",
			root: 'data',
			totalProperty: 'totalcount',
            idProperty: 'customerid',
			remoteSort: true,
			fields: [
				'customerid','customername','cclast4'
			],

			// load using script tags for cross domain, if the data in on the same domain as
			// this page, an HttpProxy would be better
			proxy: new Ext.data.HttpProxy({
				url: 'index.php?fuse=billing&action=getPendingCCList'
			})
	});
	gridstore.setDefaultSort('customerid', 'asc');
	var sm = new Ext.grid.CheckboxSelectionModel({
        listeners:{
             'rowdeselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                    toggleButtons();
              }
        }
    });
    var validatebutton = new Ext.Button({
                     id:'validatebutton',
                     autoHeight:true,
                     arrowAlign:'right',
                     xtype:'button',
                     text:'Validate',
                     disabled: true
                     //style : "background-color:red"
                     
                     

    });

    var passPhrase = new Ext.form.TextField({
                        text:'TextField',
                        id : 'passphrasetext'
                        
                        });

    var label = new Ext.form.Label({
                        text:'PassPhrase'
    });

    var spacebar = new Ext.Spacer({
                        width : 80
    });
    var spacebar1 = new Ext.Spacer({
                        width : 10
    });
    var spacebar2 = new Ext.Spacer({
                        width : 20
    });
    var vItems = new Array();
    vItems.push(spacebar);
    vItems.push(label);
    vItems.push(spacebar1);
    vItems.push(passPhrase);
    vItems.push(spacebar2);
    vItems.push(validatebutton);

    var grid = new Ext.grid.GridPanel({
        el:'pendingcc-grid',
		autoHeight:true,
        title:'Pending CC List',
        store: gridstore,
        trackMouseOver:true,
        disableSelection:true,
        loadMask: true,
        

        // grid columns
        columns:[
            sm,
        {
            id: 'customerid',
            header: "Customer Id",
            hidden : true,
            width: 50,
			dataIndex : "customerid",
            align:"left"
        },{
            id: 'customername',
            header: "Customer Name",
            width: 150,
			dataIndex : "customername"
        },{
			id: 'cclast4',
            header: "Last 4",
			dataIndex : "cclast4",
            width: 120
        }],
        sm: sm
		,stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            emptyText: lang("There are currently no pending cc validations to view"),
            enableRowBody:true,
            scrollOffset:1
        },
        editor: new Ext.form.TextField({
		inputType: 'password',
		allowBlank: false
        }),
        //buttons:[validatebutton],
        // paging bar on the bottom
        bbar: new Ext.PagingToolbar({
            pageSize: 15,
            store: gridstore,
            height : 30,
            displayInfo: true,
            displayMsg: 'Displaying users {0} - {1} of {2}',
            emptyMsg: "",
            items : vItems
        })

    });

    function getUserIds(){
        var arrayofids = new Array();
        rows = sm.getSelections();
        for(x=0;x<rows.length;x++){
            arrayofids[i] = rows[x].data.customerid;
        }
        return arrayofids;
    }

    function getPassPhraseValue(){
        return passPhrase.getValue();
    }

    var btnButtonActionHandler = function(button, event){
        //grid.disable();
        //delete

	    switch(button.id){
           case "validatebutton":
               if(getPassPhraseValue()==""){
                   Ext.Msg.alert("A passphrase is required to validate these credit cards.");
                   return;
               }
               requesturl = "index.php?fuse=billing&action=ValidatePendingCC";
	           break;
           default:
	           return false;
	    }

        Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                        //refreshgrid
                        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
                           Ext.Msg.alert(data.message);
                        }

                        validatebutton.setDisabled(true);
                        passPhrase.setValue("");
                    },
           failure: function() {
               
                grid.enable();
                validatebutton.setDisabled(true);
                Ext.Msg.alert("Fail");
           },
           params: { userids: Ext.util.JSON.encode(getUserIds()),
                     passphrase: Ext.util.JSON.encode(getPassPhraseValue())
                     


           }
        });
    }
    
    function toggleButtons(){
        if(sm.getCount()>0){
            validatebutton.setDisabled(false);

        }else{
            validatebutton.setDisabled(true);
        }
    }
    validatebutton.addListener("click",btnButtonActionHandler);
    grid.render();

    // trigger the data store load
    gridstore.load({params:{start:0 , limit:10}});
});