var currenciesInDataBase;


Ext.Ajax.request({
   url: 'index.php?fuse=billing&action=GetCurrenciesInDataBase',
   success: function(responseObj) {
        currenciesInDataBase = responseObj.responseText;
   },
   failure: function() {
        Ext.Msg.alert("Fail");
   }
});

Ext.onReady(function(){
    var addCurrencyButton =  new Ext.Button({
        id:"addcurrency",
        renderTo:"addcurrency",
        text: lang('Add Currency'),
        iconAlign: 'left',
        disabled: true,
        handler:function(){
            CurrencyWin.CreateWindow(false,0);
            selectedCurrency = '';
            currencystore.setBaseParam('code', selectedCurrency);
            currencystore.load();
            currencyCode.setValue(selectedCurrency);
            simpleForm.getForm().reset();
        }
    });

    var gridstore = new Ext.data.JsonStore({
            id:             "gridstore",
            root:           'currencies',
            totalProperty:  'totalcount',
            idProperty:     'id',
            remoteSort:     true,
            baseParams:     {
                                filter: "",
                                customerid: "0"
                            },
            fields:         [
                                'id',
                                'name',
                                'count',
                                'symbol',
                                'abrv',
                                'alignment',
                                'precision',
                                //'rate',
                                'candelete',
                                'isdefault'
                            ],
            // 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=GetCurrencies'
                            })
    });
    gridstore.setDefaultSort('id', 'asc');

    function renderName(value,p,record){
        name = '<a href="javascript:ShowEditCurrencyWindow('+record.data.id+');" id="'+record.data.id+'" class="editcurrency" qtip="'+lang('Click to edit this currency')+'">'+record.data.name+'</a>';
        if(record.data.isdefault){
            name = name + "<font color=red> (" + lang("Default") + ")</font>";
        }
        return name;
    }
    
    var sm = new Ext.grid.CheckboxSelectionModel({
        id:'currency-sm',
        width: 30,
        listeners:{
             'rowdeselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                    toggleButtons();
              }
        }
    });

    var grid = new Ext.grid.GridPanel({
        id:'currency-grid',
        el:'currency-grid',
		autoHeight:true,
        store: gridstore,
        trackMouseOver:true,
        disableSelection:true,
        loadMask: true,

        // grid columns
        columns:[sm,{
            id: 'id', 
            header: lang("Id"),
            width: 15,	
    		dataIndex : "id",
            sortable: false,
            hidden:true
        },{
            id: 'name', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Name"),
    		dataIndex : "name",
            sortable: false,
            renderer: renderName
        },{
            id: 'count', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Count"),
            width: 40,	
    		dataIndex : "count",
            sortable: false
        },{
            id: 'symbol', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Symbol"),
            width: 30,	
    		dataIndex : "symbol",
            sortable: false
        },{
            id: 'abrv', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Code"),
            width: 45,	
    		dataIndex : "abrv",
            sortable: false
        },{
            id: 'alignment', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Alignment"),
            width: 60,	
    		dataIndex : "alignment",
            sortable: false
        },{
            id: 'precision', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Precision"),
            width: 60,	
    		dataIndex : "precision",
            sortable: false
        }
        /*
        ,{
            id: 'rate', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Rate"),
            width: 60,	
            dataIndex : "rate",
            sortable: false
        }
        */
        ],
		stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no currencies available to view at this time"),
	    scrollOffset:1
        },
        sm: sm,
        // inline buttons
        buttons:[deletebutton = new Ext.Button({
                     id:'actionbuttons',
                     autoHeight:true, 
                     xtype:'button',
                     text:'Delete',
                     disabled: true,
                     onClick: function(record){
                            if(!deletebutton.disabled){
                                requesturl = "index.php?fuse=billing&action=DeleteCurrencies";
                                ProcessAction(requesturl);
                            }
                        }
                     }),
                 setdefaultbutton = new Ext.Button({
                     id:'statusbuttons',
                     autoHeight:true, 
                     xtype:'button',
                     text:lang('Set Default'),
                     disabled: true,
                     onClick: function(record){
                            if(!setdefaultbutton.disabled){
                                requesturl = "index.php?fuse=billing&action=SetDefaultCurrency";
                                ProcessAction(requesturl);
                            }
                        }
                 })
                ],
        buttonAlign:'left'

    });

    // option button code
    function toggleButtons(count){
        if(count == undefined){
            count = sm.getCount();
        }
        if(count>0){
            deletebutton.setDisabled(false);
            if(count>1){
                setdefaultbutton.setDisabled(true);
            }else{
                setdefaultbutton.setDisabled(false);
            }
        }else{
            deletebutton.setDisabled(true);
            setdefaultbutton.setDisabled(true);
        }
    }
      
    function GetSelectedRowIds(){
        var arrayofids = new Array();
        rows = sm.getSelections();
	    for(x=0;x<rows.length;x++){
	       arrayofids[x] = rows[x].data.id;
	    }
	    return arrayofids;
    }

    function ProcessAction(requesturl){
	    grid.disable();
	    Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                //refreshgrid
                grid.enable()
                gridstore.load({params:{start:0}});   
                toggleButtons(0);
                
                var data = Ext.util.JSON.decode(xhr.responseText);
                if(data.message){
                    msg(data.message);
                }else{
                    msg(lang("Currency(ies) have been updated"));
                } 
           },
           failure: function() {
                grid.enable()
                msg(lang("There was an error performing this action"));
           },
           params: { 
            ids: Ext.util.JSON.encode(GetSelectedRowIds())
         }
       });
	    
    }

    // render it
    grid.render();
    gridstore.setBaseParam('limit', 50);
    gridstore.load({params:{start:0}});
    gridstore.on('load', function(){
                             if(gridstore.getCount() < currenciesInDataBase){
                                 addCurrencyButton.setDisabled(false);
                             }else{
                                 addCurrencyButton.setDisabled(true);
                             }
                         }
    );

});