Ext.onReady(function(){

    if(document.getElementById('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'
        ],
        proxy: new Ext.data.HttpProxy({
                url: 'index.php?fuse=admin&action=GetCoupons'
        })
    });
    gridstore.setDefaultSort('id', 'asc');
    gridstore.setBaseParam('active',document.getElementById("couponFilter").value);

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

    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="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 expander = new Ext.ux.grid.RowExpander({
        enableCaching: false,
        listeners:{
           'expand': function(re,response,body,index){
               
               if (response.data.duration == "---") response.data.duration = "Indefinite";
               
               expanderBody = "<div class='ext-expanderframe'>";
               expanderBody += "<div class='ext-expanderframe-details'>";
               expanderBody += "<b>Code</b>: <span style='color:green'>"+ response.data.code+"</span></b>";
               expanderBody += "<br/><b>Description</b>: "+ response.data.description+"</b>";
               expanderBody += "<br/><b>Duration</b>: "+ response.data.duration+"</b>";
               expanderBody += "<br/><b>Applies To</b>: " + response.data.packages;
               expanderBody += "<br/><b>Taxable</b>: " + response.data.taxable;
               expanderBody += "</div>";
               expanderBody += "</div>";
               body.innerHTML = expanderBody;
               
            }
        }
    });


    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:[expander,
        sm,{
            id: 'name', 
            header: lang("Name"),
            dataIndex : "name",
            renderer: renderName,
            sortable: false
        },{
            id: 'discount',
            header: lang("Discount"),
            width: 20,
            align:"center",	
            dataIndex : "discount",
            sortable: false
        },{
            id: 'recurring', 
            header: lang("Recurring"),
            width: 18,	
            align:"center",
            dataIndex : "recurring",
            sortable: false
        },{
            id: 'billingcycles', 
            header: lang("Billing Cycles"),
            width: 30,	
            align: 'center',
            dataIndex : "billingcycles",
            sortable: false
        },{
            id: 'ineffect', 
            header: lang("In Effect"),
            width: 15,	
            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,
        plugins: expander,
        // 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}});  

});