/*
 * Ext JS Library 3.0 RC1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

var gridstore;

Ext.onReady(function(){
    var customfilterwin;
    Ext.QuickTips.init();

    if($('adduserbutton') != null){
        new Ext.Button({
            id:"adduser",
            renderTo:"adduserbutton",
            text: lang('Add User'),
            iconAlign: 'left',
            handler:function(){
                addClient();
            }
        });
    }

    gridstore = new Ext.data.JsonStore({
        id: "gridstore",
        root: 'clients',
        totalProperty: 'totalcount',
        idProperty: 'id',
        remoteSort: true,
        fields: [
                'id','firstname','lastname', 'email','dateactivated','status','statusname','clienttype','clienttypename','clienttypebgcolor'
        ],

        // 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=clients&action=GetClientList'
        })
    });
    gridstore.setDefaultSort(gridsavedstate.sortinfo.field, gridsavedstate.sortinfo.dir);
    gridstore.setBaseParam('limit', gridsavedstate.displaysize);
	
    //check to see if my template file has set some additional search variables
    //from the post of the advanced search.  If so then add to the params so the
    //action can filter using these properties.
    if (typeof(customsearchtype) != "undefined") {
        //these are set in the viewusers.tpl
        gridstore.setBaseParam('customsearchtype', customsearchtype);
        gridstore.setBaseParam('customsearchfield', customsearchfield);
        gridstore.setBaseParam('customsearchstring', customsearchstring);
    }

    // pluggable renders
    function renderName(value, p, record){
        if(record.data.clienttypebgcolor==""){
            url = String.format(
                '<a href="index.php?fuse=clients&amp;view=Admin_Profile_Contact&amp;frmClientID={1}">{0}</a>',
                record.data.firstname + " " + record.data.lastname, record.data.id);
        }else{
            url= String.format(
                '<span class="customergroupstyle"><a style="background:{2} !important;" href="index.php?fuse=clients&amp;view=Admin_Profile_Contact&amp;frmClientID={1}">{0}</a></span>',
                record.data.firstname + " " + record.data.lastname, record.data.id, record.data.clienttypebgcolor);
        }
        return url;
    }
	
    function renderClientType(value,p,record){
        return String.format("{0}",record.data.clienttypename);
    }

    // pluggable renders
    function renderStatus(value, p, record){
        return String.format("{0}",record.data.statusname);
    }

    function showCol(value,p,record){
        return false;
    }

    var clientgridbb = new Ext.PagingToolbar({
        id:'clientgridpagingbar',
        store: gridstore,
        pageSize: gridsavedstate.displaysize,
        listeners:{
           'change': function(bb,data){
                    if(data.total == 0) { var addBy = 0;} else { var addBy = 1;}
                    from = (data.activePage * bb.pageSize) - bb.pageSize + addBy;
                    to = from+ bb.pageSize - 1;
                    if(to>data.total) to = data.total;

				$('clientgridpagingbar').style.display = ( data.pages > 1 ) ? '' : 'none';
				$('clientlistlabel').innerHTML = String.format(lang('Displaying users') +' {0} - {1}' + ' of ' + '{2}',from,to,data.total);
          }
        }
    })

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

        // grid columns
        columns:[{
            id: 'id', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Id"),
            width: 50,
            dataIndex : "id",
            hidden:true,
            sortable: true,
            align:"left"
        },{
            id: 'clientname', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Name"),
            width: 320,
            renderer: renderName,
            dataIndex : "lastname",
            sortable: true,
            hidden:  false
        },{
            id: 'clienttype',
            header: lang("Client Type"),
            dataIndex : "clienttype",
            renderer: renderClientType,
            width: 120,
            hidden: true,
            sortable: true
        },{
            id: 'clientemail',
            header: lang("E-mail"),
            dataIndex : "email",
            width: 220,
            hidden: false,
            sortable: true,
            align:"right"
        },{
            id: 'dateactivated',
            header: lang("Activated"),
            dataIndex : "dateactivated",
            width: 100,
            hidden: false,
            sortable: true,
            align:"center"
        },{
            id: 'status',
            header: lang("Status"),
            dataIndex : "status",
            renderer: renderStatus,
            width: 100,
            hidden: false,
            sortable: true,
            align:"center"
        }],
        stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are currently no customers to view"),
            scrollOffset:1
        },
        // paging bar on the bottom
        bbar: clientgridbb,
        plugins: [new Ext.ux.grid.Search({
            searchText: lang('Filter'),
            mode: 'remote',
            disableIndexes:['clienttype','dateactivated','status'],
            minChars:2,
            autoFocus:false,
            align:'right',
            dateFormat: 'm d Y H:i'
        })],
        listeners:{
           'columnmove': function(oldIndex,newIndex){
               //alert(oldIndex);
               //alert(newIndex);
            },
            'sortchange' : function (grid,sortInfo){
                gridsavedstate.sortinfo.field = sortInfo.field;
                gridsavedstate.sortinfo.dir = sortInfo.direction;
                updateGridSavedState("ClientListGridState");
            }
        }
    });

    function updateGridSavedState(customfield){
        Ext.Ajax.request({
           url: 'index.php?fuse=admin&action=updateGridSavedState',
           success: function(xhr) {
                    //msg('Settings Update Successfully','');
                    },
           failure: function() {
                ce.log(1,"Failed from saving gridstate");
           },
           params: { gridcustomfield: customfield,
                     gridsavedstate: Ext.encode(gridsavedstate)
                     },
           method:'post'
        });
    }

    // render it
    grid.render();
    
    // trigger the data store load
    gridstore.load({params:{start:0}});
    
    // create the combo instance
    new Ext.form.ComboBox({
        tpl: '<tpl for="."><div ext:qtip="Display {displayText} items" class="x-combo-list-item">{displayText}</div></tpl>',
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value: gridsavedstate.displaysize,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 0,
            fields: [
                'myId',
                'displayText'
            ],
            data: [[10, '10'], [25, '25'] ,[50, '50'], [150,'150'],[300,'300']]
        }),
        valueField: 'myId',
        width: 50,
        displayField: 'displayText',
        applyTo: 'local-states-with-qtip',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                gridstore.setBaseParam('limit', record.data.myId);
                clientgridbb.pageSize = record.data.myId;
                gridstore.load({params:{start:0}});
                gridsavedstate.displaysize = record.data.myId;
                updateGridSavedState("ClientListGridState");
             }
        }
    });
 
    //check to see if my template file has set some additional search variables
    //from the post of the advanced search.  If so then add to the params so the
    //action can filter using these properties.
    if (typeof(searchcustomerid) != "undefined") {
        //searchfilter is set in tpl from view if search filter is passed in url
        FilterGrid(searchfilter,searchcustomerid);
    }

    //called to standardize the default filters and dropdown filter
    function FilterGrid(filter,customerid){
        //these are set in the viewusers.tpl
        if(filter!=null) gridstore.setBaseParam('filter', filter);
        gridstore.load({params:{start:0}});
    }   

    function PopulateCustomQueryNoticeBox(text,isprivate,id){
        //customquerynoticebox
        Ext.get("customquerynoticebox").setStyle("display","");
        Ext.get("deletecustomfilter").setStyle("display","inline");
        searchfilter = id; //used by update and delete custom query buttons
        document.getElementById("filtername").value = text;
        document.getElementById("filterprivate").checked = (isprivate==0) ? false : true;
    }

    var storeItem = Ext.data.Record.create([{name:'myId',type:'string'},{name:'displayText',type:'string'}]);
    var filtertypecombo = new Ext.form.ComboBox({
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value:"All Clients",
        mode: 'local',
        store: new Ext.data.ArrayStore({
            idIndex: 0,
            fields: [
                'myId',
                'displayText',
                'type',
                'private'
            ]
        }),
        valueField: 'myId',
        width: 220,
        displayField: 'displayText',
        applyTo: 'usertype',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                FilterGrid(record.data.myId,0);
                return true;
             }
        }
    });
    
    function updateButtonsWithContent(data){
        if(data.type == "filter")
        {
            if(data.private == undefined){
                data.private = 0;
            }
            var comboitem = new storeItem({myId:data.id,displayText:data.name,type:data.type, private:data.private});
            filtertypecombo.getStore().insert(
                filtertypecombo.getStore().getCount(),
                comboitem
            );
        }
    }

   function PopulateUserFilters(){
        Ext.Ajax.request({
           url: 'index.php?fuse=clients&action=getClientFilters',
           success: function(xhr) {
                //clear the items from our combobox
                filtertypecombo.getStore().removeAll();
                //go through our options and add to the UI
                var data = Ext.util.JSON.decode(xhr.responseText);
                //data.options.forEach(updateButtonsWithContent);
                for ( var i in data.options )
                {
                    updateButtonsWithContent( data.options[i] );
                }
            },
           failure: function() {
                Ext.Msg.alert("Fail");
           },
           params: { foo: 'bar' }
        });
    }
    PopulateUserFilters();
});
