Ext.onReady(function(){

    if($('addcouponbutton') != null){
        new Ext.Button({
            id:"addcoupon",
            renderTo:"addcouponbutton",
            text: lang('Add Coupon'),
            iconAlign: 'left',
            handler:function(){
                addCoupon();
            }
        });
    }

    var gridstore = new Ext.data.JsonStore({
            id: "gridstore",
            root: 'coupons',
            totalProperty: 'totalcount',
            idProperty: 'id',
            remoteSort: true,
            baseParams: {
            filter: "",
            customerid: "0"
        },
                    fields: [
                            'id','canedit','name','discount','duration','ineffect','description','code','recurring','billingcycles','taxable','packages'
                    ],
                    // 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=admin&action=GetCoupons'
                    })
    });
    gridstore.setDefaultSort('id', 'asc');
    gridstore.setBaseParam('active',$("couponFilter").value);

    if($("couponFilter").value == -1){
       viewingArchived = true;
    }else{
       viewingArchived=false;
    }

    function renderPackages(value,p,record){
        var packages = record.data.packages;
        if(packages.length > 20 ){
            packages = "<span qtip='"+record.data.packages+"'>"+ packages.substring(0,20)+"...</span>";
        }
        return packages;
    }

    function renderName(value,p,record){
        //make description part of the popup
        if(record.data.canedit){
            //name = '<a qtip="' + lang('Description') + ': ' + record.data.description.replace(/"/g, "&#34;") + '" href="index.php?fuse=admin&view=EditCoupon&couponid=' + record.data.id + '">' + record.data.name.replace(/"/g, "&#34;") + '</a>';
            
            name = '<a qtip="' + lang('Description') + ': ' + record.data.description.replace(/"/g, "&#34;") + '" href="javascript:editCoupon(' + record.data.id + ');" id="' + record.data.id + '">' + record.data.name.replace(/"/g, "&#34;") + '</a>';
        }else{
            name = '<div qtip="' + lang('Description') + ': ' + record.data.description.replace(/"/g, "&#34;") + '">' + record.data.name.replace(/"/g, "&#34;") + '</div>';
        }
        return name;
    }

    var sm = new Ext.grid.CheckboxSelectionModel({
        id:'coupon-sm',
        width: 30,
        listeners:{
             'rowdeselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                    toggleButtons();
              }
        }
    });

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

        // grid columns
        columns:[
        sm,{
            id: 'name', 
            header: lang("Name"),
            width: 50,	
            dataIndex : "name",
            renderer: renderName,
            sortable: false
        },{
            id: 'code',
            header: lang("Code"),
            width: 50,	
            dataIndex : "code",
            sortable: false
        },{
            id: 'discount',
            header: lang("Discount"),
            width: 20,
            align:"center",	
            dataIndex : "discount",
            sortable: false
        },{
            id: 'duration', 
            header: lang("Duration"),
            width: 25,
            align:"center",	
            dataIndex : "duration",
            sortable: false
        },{
            id: 'recurring', 
            header: lang("Recurring"),
            width: 25,	
            align:"center",
            dataIndex : "recurring",
            sortable: false
        },{
            id: 'packages', 
            header: lang("Applies To"),
            width: 40,	
            dataIndex : "packages",
            renderer: renderPackages,
            sortable: false
        },{
            id: 'billingcycles', 
            header: lang("Billing Cycles"),
            width: 40,	
            dataIndex : "billingcycles",
            sortable: false
        },{
            id: 'taxable', 
            header: lang("Taxable"),
            width: 25,	
            align:"center",
            dataIndex : "taxable",
            sortable: false
        },{
            id: 'ineffect', 
            header: lang("In Effect"),
            width: 25,	
            align:"center",
            dataIndex : "ineffect",
            sortable: false
        }

        ],
        stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no coupons 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=admin&action=DeleteCoupons";
                                ProcessAction(requesturl);
                            }
                        }
                     }),
                 archivebutton = new Ext.Button({
                    id:'statusbuttons',
                     autoHeight:true, 
                     xtype:'button',
                     text:(viewingArchived)? lang('Un-Archive'): lang('Archive'),
                     disabled: true,
                     onClick: function(record){
                            if(!archivebutton.disabled){
                                if(viewingArchived){
                                    requesturl = "index.php?fuse=admin&action=UnArchiveCoupons_Async";
                                }else{
                                    requesturl = "index.php?fuse=admin&action=ArchiveCoupons_Async";
                                }
                                ProcessAction(requesturl);
                            }
                        }
                 })
                ],
        buttonAlign:'left'


    });


    // option button code
    function toggleButtons(count){
        if(count == undefined){
            count = sm.getCount();
        }
        if(count>0){
            deletebutton.setDisabled(false);
            archivebutton.setDisabled(false);
        }else{
            deletebutton.setDisabled(true);
            archivebutton.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.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("Coupon(s) have been updated"),"");
                        }

                        
                    },
           failure: function() {
                grid.enable()
                Ext.Msg.alert("Fail");
           },
           params: { 
            ids: Ext.util.JSON.encode(GetSelectedRowIds())
            }
        });
	    
    }

    // render it
    grid.render();
    
	//check to see if I'm looking at archived or active coupons.
    gridstore.setBaseParam('limit', 50);
    gridstore.load({params:{start:0}});  

});