viewingWhat = 'products';
var productassigncombo;
Ext.onReady(function(){

    addProductButton = new Ext.Button(
                    {

                        id:"addProduct",
                        renderTo:"addproduct",
                        text: lang('Add Product'),
                        iconAlign: 'left',
                        tooltip: 'Select a product group from the dropdown above in order to add a product.',
                        disabled:true,
                        handler:function(){
                                addProduct(selectedProductGroupType, selectedProductGroupName);
                        }
                    }
                );

    /*
     * Functions to load the product grid
     */
    gridstore = new Ext.data.GroupingStore({
            proxy: new Ext.data.HttpProxy({
                    url: 'index.php?fuse=admin&action=getProductsGrid'
            }),
            reader: new Ext.data.JsonReader({
                root: 'results',
                id: 'productsReader',
                fields: ['id','name','price', 'price3','price6','price12','price24','taxable','onetime','signup','group', 'type']
            }),
            sortInfo:{field: 'group', direction: "ASC"},
            groupField:'group',
            id: 'productGroupStore',
            listeners : {
                 'load' : function() {
                     var cells;
                     $('.rerenderparent').parent().parent().parent().each(function(index){
                         cells = $(this).children();
                         cells.eq(4).hide();cells.eq(5).hide();cells.eq(6).hide();cells.eq(7).hide();cells.eq(8).hide();
                         cells.eq(3).html("<div class='x-grid3-cell-inner x-grid3-col-3'>Click on product for pricing details</div>");
                         cells.eq(3).attr('colspan','5');
                         cells.eq(3).css('width','');
                     });
                 }
            }
        });
        
    gridstore.load();
    
    function renderName(value, p, record){
        var name = record.data.ticketTypeName;
        //if(store.reader.jsonData.canEditTicketTypes){
            name = '&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:editProduct('+record.data.id+', '+record.data.type+');" id="'+record.data.id+'" class="editbillingtype">'+lang(record.data.name)+'</a>';
        //}

        return name;
    }

     function toggleButtons(count){

         // If 0 disable all
         if(sm.getCount() == 0) {
            deleteProductButton.setDisabled(true);
            cloneProductButton.setDisabled(true);
            productassigncombo.setDisabled(true);
            assigntolabel.setDisabled(true);
         } else if(sm.getCount() == 1) {
            deleteProductButton.setDisabled(false);
            cloneProductButton.setDisabled(false);
            productassigncombo.setDisabled(false);
            assigntolabel.setDisabled(false);
         } else {
            deleteProductButton.setDisabled(false);
            cloneProductButton.setDisabled(true);
            productassigncombo.setDisabled(false);
            assigntolabel.setDisabled(false);
         }
    }

    if(admin_edit_packagetypes){
        var sm = new Ext.grid.CheckboxSelectionModel({
            listeners:{
                 'rowdeselect': function(model, rowIndex, record){
                        toggleButtons();
                  },
                  'rowselect': function(model, rowIndex, record){
                        toggleButtons();
                  }
            }
        });

        var productsGridButtons = [
            deleteProductButton = new Ext.Button({
                 id:'deleteProductButton',
                 autoHeight:true,
                 arrowAlign:'right',
                 xtype:'button',
                 text:lang('Delete'),
                 tooltip: 'Click to delete the selected products.',
                 disabled: true,
                 listeners:{
                     'click' : function(cb,record){
                         Ext.MessageBox.confirm('Confirm', lang('Are you sure you want to delete the selected product(s)?'), function(btn, text){
                            if (btn == 'yes'){
                                ButtonActionHandler('delete', false);
                            }
                        });
                     }
                 }
             }),
             cloneProductButton = new Ext.Button({
                 id:'cloneProductButton',
                 autoHeight:true,
                 arrowAlign:'right',
                 xtype:'button',
                 text:lang('Clone Product'),
                 tooltip: 'Click to clone the selected product. <br>Note: You can only clone 1 product at once.',
                 disabled: true,
                 listeners:{
                     'click' : function(cb,record){
                         Ext.MessageBox.confirm('Confirm', lang('Are you sure you want to clone the selected product?'), function(btn, text){
                            if (btn == 'yes'){
                                ButtonActionHandler('clone', false);
                            }
                        });
                     }
                 }
             }),
             assigntolabel = new Ext.form.Label({
                disabled: true,
                style:'paddingLeft:10px;font:12px/18px "Lucida Grande","Lucida Sans Unicode",Verdana,Arial,sans-serif;',
                text:'Move To: '
             }),
             productassigncombo = new Ext.form.ComboBox({
                triggerAction: 'all',
                lazyRender:false,
                editable:false,
                disabled: true,
                value:"          - Select Product Group -",
                mode: 'local',
                store: new Ext.data.ArrayStore({
                    idIndex: 0,
                    fields: [
                        'myId',
                        'displayText',
                        'productCount',
                        'typeid'
                    ]
                }),
                valueField: 'myId',
                width: 220,
                displayField: 'displayText',
                tpl: '<tpl for=".">' +
                     '<div class="x-combo-list-item">'  +
                     '{prename}{displayText}' +
                     '</div></tpl>'
                ,
                // all of your config options
                listeners:{
                     'select': function(cb,record){
                         Ext.MessageBox.confirm('Confirm', lang('Are you sure you want to move the selected product(s)?'), function(btn, text){
                            if (btn == 'yes'){
                                ButtonActionHandler('move', record.data.myId);
                            }
                         });
                     }
                }
            })
        ];
    }else{
        var sm = new Ext.grid.CheckboxSelectionModel({});
        var productsGridButtons = '';
    }

    renderProductPrice1 = function(value, p, record){
        //get first parent table if type is
        var div = record.data.price ;
        if((record.data.type==3) || (record.data.type==2)){
            div = "<span class='rerenderparent'>"+div+"</span>";
        }
        return div;
    }

    productsGrid = new Ext.grid.GridPanel({ // xg.GridPanel({
        store: gridstore,
        columns: [sm,
            {id: 'id',header: "ID", width: 10, hidden:true, dataIndex: 'id'},
            {header: lang("Name"), renderer : renderName, width: 80, dataIndex: 'name'},
            {header: lang("Monthly"), width: 15, align:'center', dataIndex: 'price', renderer: renderProductPrice1},
            {header: lang("Quarterly"), width: 15, align:'center', dataIndex: 'price3'},
            {header: lang("Semiannual"), width: 15, align:'center', dataIndex: 'price6'},
            {header: lang("Annual"), width: 15, align:'center', dataIndex: 'price12'},
            {header: lang("2 Year"), width: 15, align:'center', dataIndex: 'price24'},
            {header: lang("One-Time"), width: 15, align:'center', dataIndex: 'onetime'},
            {header: lang("Taxable"), width: 12, align:'center',dataIndex: 'taxable', renderer: renderYesNo},
            {header: lang("In Signup?"), width: 15, align:'center',dataIndex: 'signup', renderer: renderSignup},
            {header: lang("Product Group"), width: 20, align:'center',dataIndex: 'group', hidden: true}
        ],

        view: new Ext.grid.GroupingView({
            scrollOffset:1,
            forceFit:true,
            groupFit:true,
            emptyText: lang("There are no products available in this group."),
            emptyGroupText: "blah",
            enableGroupingMenu: false,
            enableNoGroups:false,
            groupTextTpl: '{text}'
        }),
        collapsible: false,
        animCollapse: false,
        iconCls: 'icon-grid',
        renderTo: 'products-list',        
        disableSelection:true,
        trackMouseOver:false,
        loadMask: true,
        stripeRows: true,
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no products available."),
            scrollOffset:1
        },   
        columnLines: true,
        autoHeight:true,
        title: '',
        sm:sm,
        buttons: productsGridButtons,
        buttonAlign:'left'
    });
    
    function renderSignup(value,p,record){
        if (value == 1) return lang("Yes");
        if (value == 0) return lang("Hidden");
        return lang("No");
    }
    
    function renderYesNo(value,p,record){
        if (value == 1) return lang("Yes");
        return lang("No");
    }

    function getProductItems(){
        //var arrayofids = new Array();
        var productItems = "";
        rows = sm.getSelections();
        //var i = 0;
        for(x=0;x<rows.length;x++){
            var commavar = ";";
            if(x !=0){
               productItems += commavar;
            }
            productItems += rows[x].data.id;
        }
        return productItems;
    }

    ButtonActionHandler = function(action, groupId){
        productsGrid.disable();
        requesturl = "index.php?fuse=admin&action=actOnProductsGrid";

        Ext.Ajax.request({
            url:      requesturl,
            params:   {
                items:          Ext.util.JSON.encode(getProductItems()),
                actionbutton:   action,
                groupid:        groupId
            },
            success:  function(xhr){
                productsGrid.enable();
                gridstore.load();
                var json = ce.parseAjaxResponse(xhr);
                deleteProductButton.setDisabled(true);
                cloneProductButton.setDisabled(true);
                productassigncombo.setDisabled(true);
                assigntolabel.setDisabled(true);

            },
            failure:  function(){
                //Unmask the grid
                productsGrid.enable();
                alert("Fatal Error. ExtJS did not properly catch an exception so I have no idea what happened. Sorry.");
           }
        });
    }
});