var getSelectedItemButtons;
var selectedProductId;
var selectedProductHasPlugin = false;

Ext.onReady(function(){


        filterstore = new Ext.data.JsonStore({
            id:             "filterstore",
            root:           'options',
            idProperty:     'value',
            remoteSort:     true,
            fields:         [
                                'id',
                                'name',
                                'type'
                            ],
            proxy:          new Ext.data.HttpProxy({
                                url:  'index.php?fuse=clients&action=Admin_GetFilters'
                            })
        });
        filterstore.load();


        filterstoresecond = new Ext.data.JsonStore({
            id:             "filterstoresecond",
            root:           'options',
            idProperty:     'value',
            remoteSort:     true,
            fields:         [
                                'id',
                                'name',
                                'value'
                            ],
            proxy:          new Ext.data.HttpProxy({
                                url:  'index.php?fuse=clients&action=Admin_GetFilters'
                            })
        });

 

            // Create the dropdown of Registrar plugins
        var productfiltercombo = new Ext.form.ComboBox({
            triggerAction: 'all',
            lazyRender:true,
           editable:false,
           value:'All',
           width: 120,
           store:filterstore,
           displayField:'name',
           hiddenName: 'plugin',
           valueField:'id',
           mode:'local',
           beforeBlur : Ext.emptyFn,
           applyTo: 'productfilter',
           listeners:{
             'select': function(cb,record){
                getGroupProducts(record.data.id);
             }
        }
       });

        productfiltercombo.wrap.addClass("x-form-field-float-left");




       var productfiltersecondcombo = new Ext.form.ComboBox({
            triggerAction: 'all',
            id: 'productfiltersecondcombo',
            lazyRender:true,
           editable:false,
           value:'',
           width: 180,
           store:filterstoresecond,
           displayField:'name',
           hiddenName: 'plugin',
           valueField:'id',
           mode:'local',
           beforeBlur : Ext.emptyFn,
           applyTo: 'invoicetype',
           listeners:{
             'select': function(cb,record){
                domainsFilterGrid(record.data.id);
             }
        }
       });

        productfiltersecondcombo.wrap.addClass("x-form-field-float-left");


        function getGroupProducts(type)
        {
                filterstoresecond.removeAll();
                filterstoresecond.load({
                    params: {
                        type: type
                    }
                });

                // Update the initial value
                if(type == 'products') {
                    productfiltersecondcombo.setValue("All Products");
                    domainsFilterGrid('products_all');
                } else if(type == 'domains') {
                    productfiltersecondcombo.setValue("All Domains");
                    domainsFilterGrid('domains_all');
                } else if(type == 'other') {
                    productfiltersecondcombo.setValue("Other Products");
                    domainsFilterGrid('other_all');
                } else if(type == 'all') {
                    productfiltersecondcombo.setValue("All");
                    domainsFilterGrid('all_all');
                }

        }

        function domainsFilterGrid(type) {
            entries_store.setBaseParam('filter', type);
            entries_store.load({params:{start:0,limit:15}});
        }


    // Functions to populate the filter dropdown
    var storeItem = Ext.data.Record.create([{name:'myId',type:'string'},{name:'displayText',type:'string'}]);
    function updateButtonsWithContent(data){
        
        if(data.type == "products"){
            if(data.private == undefined){
                data.private = 0;
            }
            var comboitem = new storeItem({myId:data.id,displayText:data.name,type:data.type, private:data.private});
            productfiltercombo.getStore().insert(
            		productfiltercombo.getStore().getCount(),
                comboitem
            );
        }
    }


    getSelectedItemButtons = function(id){
        selectedProductId = id;
        selectedProductHasPlugin = false;
        var currentProduct = new Ext.data.JsonStore({
            root:           'productinfo',
            totalProperty:  'totalcount',
            idProperty:     'domainid',
            remoteSort:     true,
            baseParams:     {
                id: id
            },
            fields:         [
                'Boxes',
                'Buttons'
            ],
            proxy:          new Ext.data.HttpProxy({
                url: 'index.php?fuse=clients&action=Admin_GetClientDomain'
            })
        });

        currentProduct.on('load',function(){
            productData = null;
            if (currentProduct.data.length > 0) {
                productData = currentProduct.getAt(0).data;
            }

            if (productData != undefined) {
                if(validProductData(productData.Buttons)){

                    var canChangeStatus = false;

                    if(productData.Buttons.activatepackage == true){
                        canChangeStatus = true;
                        Ext.getCmp('btnGridActivateProduct').show();
                    }else{
                        Ext.getCmp('btnGridActivateProduct').hide();
                    }

                    if(productData.Buttons.cancelpackage == true){
                        canChangeStatus = true;
                        Ext.getCmp('btnGridCancelProduct').show();
                    }else{
                        Ext.getCmp('btnGridCancelProduct').hide();
                    }

                    if(productData.Buttons.suspendpackage == true){
                        canChangeStatus = true;
                        Ext.getCmp('btnGridSuspendProduct').show();
                    }else{
                        Ext.getCmp('btnGridSuspendProduct').hide();
                    }

                    if(productData.Buttons.unsuspendpackage == true){
                        canChangeStatus = true;
                        Ext.getCmp('btnGridUnsuspendProduct').show();
                    }else{
                        Ext.getCmp('btnGridUnsuspendProduct').hide();
                    }

                    if(canChangeStatus == true){
                        Ext.getCmp('statusbuttons').setDisabled(false);
                    }else{
                        Ext.getCmp('statusbuttons').setDisabled(true);
                    }

                    if(productData.Buttons.deletepackage == true){
                        Ext.getCmp('deleteproduct').setDisabled(false);
                    }else{
                        Ext.getCmp('deleteproduct').setDisabled(true);
                    }
                }

                if(validProductData(productData.Boxes)){
                    selectedProductHasPlugin = productData.Boxes.serverplugin;
                }

            }

        });

        currentProduct.load();


    }

    function validProductData(fieldData)
    {
        if(fieldData != undefined
          && fieldData != null
          && fieldData != ''){
            return true;
        }else{
            return false;
        }
    }

    /**
     * Lets get the status buttons back dynamically
     */
    function toggleButtons(count){

        count = sm.getCount();
        if(count == 0) {

            // Hide everything
            Ext.getCmp('deleteproduct').setDisabled(true);
            Ext.getCmp('statusbuttons').setDisabled(true);
            Ext.getCmp('sendbuttons').setDisabled(true);

        } else if(count > 1) {

            // Hide status and show delete
            Ext.getCmp('statusbuttons').setDisabled(true);
            Ext.getCmp('deleteproduct').setDisabled(true);

            // Work out if we have a domain selected, if we do, hide delete
            selectedItemId = containsDomain();

            if (selectedItemId==0) {
                        Ext.getCmp('deleteproduct').setDisabled(false);
                    }
             

            // Show Send
            Ext.getCmp('sendbuttons').setDisabled(false);
        
        } else {

            // Show Send
            Ext.getCmp('sendbuttons').setDisabled(false);

            //get product type and id from stored item
                //currently doing d,2134 or p,2134 to differntiate between
                //domain or product
                selectedItemId = getProductItems();
                selectedItemType = selectedItemId.split(",")[0];
                selectedItemId = selectedItemId.split(",")[1];

                //only do these actions for products
                if (selectedItemType=="p") {
                    getSelectedItemButtons(selectedItemId);
                    //Ext.getCmp('statusbuttons').setDisabled(false);
                }
        }
    }

var btnButtonActionHandler = function(button){

        recurringgrid.disable();
        requesturl = "index.php?fuse=clients&action=ActOnClientProducts";

        Ext.Ajax.request({
            url:      requesturl,
            params:   {
                items:          Ext.util.JSON.encode(getProductItems()),
                actionbutton:   Ext.util.JSON.encode(button.id)
            },
            success:  function(xhr){
                recurringgrid.enable();
                entries_store.load({params:{start:0}});
                var json = ce.parseAjaxResponse(xhr);
            },
            failure:  function(){
                //Unmask the grid
                recurringgrid.enable();
           }
        });
    }

    var deleteGridProduct = function(usePlugin){
        Ext.Ajax.request({
           url: 'index.php?fuse=clients&action=Admin_DeletePackages',
           success: function(xhr) {
                onCompleteGridUpdate();
                var json = ce.parseAjaxResponse(xhr);
           },
           params: {domainid: encodeURIComponent(selectedProductId),
                    serverplugin : encodeURIComponent(usePlugin)
                    }
        });
    }

    var cancelGridProduct = function(usePlugin){
        
        Ext.Ajax.request({
           url: 'index.php?fuse=clients&action=Admin_CancelPackages',
           success: function(xhr) {
                onCompleteGridUpdate();
                var json = ce.parseAjaxResponse(xhr);
           },
           params: {domainid: encodeURIComponent(selectedProductId),
                    serverplugin : encodeURIComponent(usePlugin)
                    }
        });
        
    }

    var activateGridProduct = function(usePlugin){
        Ext.Ajax.request({
           url: 'index.php?fuse=clients&action=Admin_ActivatePackages',
           success: function(xhr) {
                onCompleteGridUpdate();
                var json = ce.parseAjaxResponse(xhr);
           },
           params: {domainid: encodeURIComponent(selectedProductId),
                    serverplugin : encodeURIComponent(usePlugin),
                    sendwelcomeemail :encodeURIComponent(false),
                    registrarplugin : encodeURIComponent(false)
                    }
        });
    }

    var suspendGridProduct = function(usePlugin){
        Ext.Ajax.request({
           url: 'index.php?fuse=clients&action=Admin_SuspendPackages',
           success: function(xhr) {
                onCompleteGridUpdate();
                var json = ce.parseAjaxResponse(xhr);
           },
           params: {domainid: encodeURIComponent(selectedProductId),
                    serverplugin : encodeURIComponent(usePlugin)
                    }
        });
    }

    var unsuspendGridProduct = function(usePlugin){
        Ext.Ajax.request({
           url: 'index.php?fuse=clients&action=Admin_UnSuspendPackages',
           success: function(xhr) {
                onCompleteGridUpdate();
                var json = ce.parseAjaxResponse(xhr);
           },
           params: {domainid: encodeURIComponent(selectedProductId),
                    serverplugin : encodeURIComponent(usePlugin)
                    }
        });
    }

    /**
     * Used on completion of grid action to reload the grid and reenable it
     */
    function onCompleteGridUpdate(){
        recurringgrid.enable();
        entries_store.load({params:{start:0}});
    }
    

    function containsDomain() {
        rows = sm.getSelections();
        //var i = 0;
        for(x=0;x<rows.length;x++){

            // WOrk out the product type
            if(rows[x].data.producttype != 'Product') {
                return 1;
            }
        }

        return 0;
    }

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

            // WOrk out the product type
            if(rows[x].data.producttype == 'Product') {
                invoiceItems += "p," + rows[x].data.productid;
            } else {
                invoiceItems += "d," + rows[x].data.productid;
            }
          //  i++;
        }
        return invoiceItems;
    }

    /*
     * Fucntions to load the gridstore
     */

    var expander = new Ext.ux.grid.RowExpander({
        enableCaching: false,
        listeners:{
            'expand': function(re,response,body,index){
                Ext.Ajax.request({
                    url: 'index.php?fuse=clients&action=GetProductInformation',
                    success: function(response){
                        var data = ce.parseAjaxResponse(response);
                        body.innerHTML = data.productinfo;
                    },
                    params: {
                        productid: response.data.productid,
                        producttype: response.data.producttype
                        }
                });
            }
        }
    });
    
    // Define the fields
    var RecurringCharge = Ext.data.Record.create([
                                                  {name: 'id'},
                                                  {name: 'producttype'},
                                                  {name: 'productid'},
                                                  {name: 'renewal'},
                                                  {name: 'status'},
                                                  {name: 'desc'},
                                                  {name: 'group'},
                                                  {name: 'signup'},
                                                  {name: 'status_class'},
                                                  {name: 'name'}
                                               ]);

    // Start a reader
	var myReader = new Ext.data.JsonReader({
		totalProperty: "totalcount",
		root: "results",
		id: "id"}, 
        RecurringCharge  
    );

    // Load the data                                         
    entries_store = new Ext.data.GroupingStore({
        id:       "entries_store",
        url:      'index.php?fuse=clients&action=Admin_GetClientProducts&fullversion=true',
        reader:   myReader,
        sortInfo: {
            field:      'renewal',
            direction:  "asc"
        },
        groupField: 'group',
        fields:     [
            'id',
            'producttype',
            'productid',
            'name',
            'group',
            'desc',
            'renewal',
            'signup',
            'status',
            'status_class'
        ]
    });
	
    /*
     * Fucntions to load the grid
     */
    var sm = new Ext.grid.CheckboxSelectionModel({
        listeners:{
             'rowdeselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                    toggleButtons();
              }
        }
    });

	// Define the rendered of the name, to provide a link
	function renderName(value,p,record){
        if(record.data.producttype == lang("Product")){
            name = '<a  href="javascript:editProduct(' + record.data.productid + ');" id="' + record.data.id + '">' + record.data.name + '</a>';
            
        }else{
            name = '<a href="javascript:editDomain(' +record.data.productid+ ', 2);" id="'+record.data.id+'">'+record.data.name+'</a> ';
        }
        return name;
    }
	
    function renderStatus(value,p,record){
            p.css = record.data.status_class;
            
            return record.data.status;
    }

	function askIfUsePlugin(usepluginmsg, fnc) {
        recurringgrid.disable();
        if (selectedProductHasPlugin) {
            //check to see if we want to use plugin
            Ext.Msg.show({
                title:    "Use Plugin?",
                msg:      usepluginmsg,
                buttons:  Ext.Msg.YESNO,
                fn:       function(btn, text){
                    if(btn == 'yes'){
                        fnc(true);
                    }else{
                        fnc(false);
                    }
                },
                icon:     Ext.MessageBox.QUESTION
            });
            
        } else {
            fnc(false);
        }
    }

	// Make the grid
	var recurringgrid = new Ext.grid.GridPanel({
	       store:entries_store,
	        columns: [
                    expander, sm,
	            {header: lang("Item"), width: 20, sortable: true, align:'center', dataIndex: 'producttype'},
	            {header: lang("Description"), sortable: true, renderer: renderName},
	            {header: lang("Next Bill Date"), width: 20, sortable: true,  align:'center',dataIndex: 'renewal'},
	            {header: lang("Status"), width: 20, sortable: true,  align:'center',renderer: renderStatus},
	            {header: lang("Order"), width: 20, sortable: true, hidden:true, dataIndex: 'group'}
	        ],
	        view: new Ext.grid.GroupingView({
                    scrollOffset:1,
                    forceFit:true,
	            groupFit:true,
                    emptyText: lang("There are no products available"),
	            groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
	        }),
	        frame:false,
	        loadMask: true,
	        columnLines: true,
	        autoHeight:true,
                plugins:          expander,
                sm:               sm,
                stripeRows: true,
	        collapsible: false,
	        buttonAlign:'left',
                viewConfig: {
                    forceFit:true,
                    enableRowBody:true,
                    emptyText: lang("There are no products available"),
                    scrollOffset:1
                },
	        animCollapse: false,
	        title: '',
	        iconCls: 'icon-grid',
	        id:       'domains-grid',
	        el:       'domains-grid',
                buttons:[
                    {
                        id:         'statusbuttons',
                        autoHeight: true,
                        disabled: true,
                        arrowAlign: 'right',
                        text:       lang('Status'),
                        menu:       new Ext.menu.Menu({
                            enableScrolling:  false,
                            shadow:false,
                            items:            [
                                {
                                    id:       'btnGridActivateProduct',
                                    text:     lang("Activate"),
                                    handler:  function(){
                                       askIfUsePlugin("Do you want to use the server plugin's Activate action?",activateGridProduct);
                                    }
                                },
                                {
                                    id:       'btnGridCancelProduct',
                                    text:     lang("Cancel"),
                                    onClick:  function(){
                                        askIfUsePlugin("Do you want to use the server plugin's Cancel action?",cancelGridProduct);
                                    }
                                },
                                {
                                    id:       'btnGridSuspendProduct',
                                    text:     lang("Suspend"),
                                    onClick:  function(){
                                        askIfUsePlugin("Do you want to use the server plugin's Suspend action?",suspendGridProduct);
                                    }
                                },
                                {
                                    id:       'btnGridUnsuspendProduct',
                                    text:     lang("Unsuspend"),
                                    handler:  function(){
                                        askIfUsePlugin("Do you want to use the server plugin's Unsuspend action?",unsuspendGridProduct);
                                    }
                                }
                            ]
                        })
                    },
                    {
                        id:       'deleteproduct',
                        text:     lang("Delete"),
                        disabled: true,
                        onClick:  function(record){
                            if(!Ext.getCmp('deleteproduct').disabled) {
                                Ext.Msg.show({
                                    title:    "Delete?",
                                    msg:      "Are you sure you want to delete the selected product(s)?",
                                    buttons:  Ext.Msg.YESNO,
                                    disabled: true,
                                    fn:       function(btn, text){
                                        if(btn == 'yes'){
                                            askIfUsePlugin("Do you want to use the server plugin's Delete action?",deleteGridProduct);
                                        }
                                    },
                                    icon:     Ext.MessageBox.QUESTION
                                });
                            }
                        }
                    },
                    {
                        id:         'sendbuttons',
                        autoHeight: true,
                        arrowAlign: 'right',
                        //xtype:      'splitbutton',
                        text:       lang('Send Welcome E-Mail')+'&nbsp;',
                        disabled: true,
                        onClick:  function(record){
                            if(!Ext.getCmp('sendbuttons').disabled) {
                                btnButtonActionHandler(this);
                            }
                        }
                    }
             ]
        });
    // render it
    recurringgrid.render();
	  
	// Load the grid
	entries_store.load({params:{start:0}});
	
    getGroupProducts('all');
});