/*
 * 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();

    //create the combo for type of user
    new Ext.form.ComboBox({
        transform: 'view',
        typeAhead: true,
        triggerAction: 'all',
        editable: false,
        width:135,
        forceSelection:true
    });

    //create the combo by field
    new Ext.form.ComboBox({
        transform: 'searchbyfield',
        typeAhead: true,
        triggerAction: 'all',
        width:154,
        editable: false,
        forceSelection:true,
        listeners: {
            'select' : function(cb, record) {
                ToggleCustomFields(cb.getValue(), 'div');
            }
        }
    });

    //create the combo for profile
    new Ext.form.ComboBox({
        transform: 'searchbycustomprofilefield',
        typeAhead: true,
        triggerAction: 'all',
        editable: false,
        width:135,
        forceSelection:true
    });

    //create the combo for package
    new Ext.form.ComboBox({
        transform: 'searchbycustompackagefield',
        typeAhead: true,
        editable: false,
        triggerAction: 'all',
        width:135,
        forceSelection:true
    });

/*
 * Class for saving grid state. Modeled on LayoutStateManager
 */

Ext.grid.GridStateManager = function(){
     // default empty state
     this.state = {
        hidden: { },
        locked: { },
        widths: { }
    };
};

Ext.grid.GridStateManager.prototype = {
    init : function(grid, provider){
        this.provider = provider;
        this.grid = grid;
        var state = columnsavedstate;

        if(state) {
            state.hidden = state.hidden || { };
            for (var colId in state.hidden) {
              var colIndex = this.grid.getColumnModel().getIndexById(colId);
              if (!isNaN(colIndex) && colIndex >= 0) {
                this.grid.getColumnModel().setHidden(colIndex, state.hidden[colId]);
              }
            }
            state.locked = state.locked || { };
            for (var colId in state.locked) {
              var colIndex = this.grid.getColumnModel().getIndexById(colId);
              if (!isNaN(colIndex) && colIndex >= 0) {
                this.grid.getColumnModel().setLocked(colIndex, state.locked[colId]);
              }
            }
            state.widths = state.widths || { };
            for (var colId in state.widths) {
              var colIndex = this.grid.getColumnModel().getIndexById(colId);
              if (!isNaN(colIndex) && colIndex >= 0) {
                this.grid.getColumnModel().setColumnWidth(colIndex, state.widths[colId]);
              }
            }
            if (state.sortInfo) {
              //this.grid.getDataSource().setDefaultSort(state.sortInfo.field, state.sortInfo.direction);
            }
            if (state.colIds) {
              for (var i = 0; i < state.colIds.length; i++) {
                var savedColId = state.colIds[i];
                var initialColIndex = this.grid.getColumnModel().getIndexById(savedColId);
                if (!isNaN(initialColIndex) && initialColIndex > 0 && initialColIndex != i) {
                  this.grid.getColumnModel().moveColumn(initialColIndex, i);
                }
              }
            }
            this.state = state;
        }
        grid.getColumnModel().on("hiddenchange", this.onHiddenChange, this);
        // for some reason the widthchange event on ColumnModel always gives width = undefined
        // so have to list to the event on the grid directly
        grid.on("columnresize", this.onColumnResize, this);
        grid.getColumnModel().on("columnlockchange", this.onLockChange, this);
        grid.getColumnModel().on("columnmoved", this.onColumnMove, this);
        //grid.getDataSource().on("datachanged", this.onSort, this);
    },

    getStateKey : function() {
      return this.grid.id + "-grid-state";
    },

    storeState : function(){

        // Upadat the local var
        columnsavedstate = this.state;

        // Post it
        Ext.Ajax.request({
           url: 'index.php?fuse=admin&action=updateGridSavedState',
           success: function(xhr) {
                    },
           failure: function() {
                NE_log(1,"Failed from saving gridstate");
           },
           params: { gridcustomfield: 'ClientListGridState',
                     gridsavedstate: Ext.encode(gridsavedstate),
                     columnsavedstate: Ext.util.JSON.encode(this.state)
                     },
           method:'post'
        });
    },

    onHiddenChange : function(cm, colIndex, hidden){
        var colId = cm.getColumnId(colIndex);
        this.state.hidden[colId] = hidden;
        this.storeState();
    },

    onColumnResize : function(colIndex, width){
        var colId = this.grid.getColumnModel().getColumnId(colIndex);
        this.state.widths[colId] = width;
        this.storeState();
    },

    onLockChange : function(cm, colIndex, lockState){
        var colId = cm.getColumnId(colIndex);
        this.state.locked[colId] = lockState;
        this.storeState();
    },

    onColumnMove : function(cm, oldIndex, newIndex){
        // we do this one by saving array of current order of column ids
        var colIds = [];
        for(var i = 0; i < cm.getColumnCount(); i++){
            colIds.push(cm.getColumnId(i));
        }
        this.state.colIds = colIds;
        this.storeState();
    },

    onSort : function(dataSource){
        if (dataSource.sortInfo) {
          this.state.sortInfo = { field: dataSource.sortInfo.field, direction: dataSource.sortInfo.direction }
          this.storeState();
        }
    }
};

/*
 * @enhancements
 * Add method to Grid to restore state.
 */
Ext.apply(Ext.grid.GridPanel.prototype, {
  restoreState: function (provider) {
    if (!provider) {
      provider = Ext.state.Manager;
    }
    var sm = new Ext.grid.GridStateManager();
    sm.init(this, provider);
  }
});

    if(document.getElementById('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', 'isOrganization', 'fullname', '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&comma=yes'
        })
    });
    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){
        //var name = record.data.firstname + " " + record.data.lastname;
        var name = record.data.fullname;
        if (record.data.isOrganization==1) {
            name = name + "&nbsp;&nbsp;<span class='clientlist-org-contact'>"+record.data.firstname+" "+record.data.lastname+"</span>";
        }
        name = "<span ext:qtip='id:"+record.data.id+"<br/>e-mail:"+record.data.email+"<br/>contact:"+record.data.firstname+" "+record.data.lastname+"'>"+name+"</span>";
        //var name = <div ext:qtip="id: {id}<br/>e-mail: {email}<br/>status: {statusname}<br/>type: {clienttypename}" class="x-combo-list-item"><span style="text-transform:capitalize;">{fullname}</span></div></tpl>""
        if(record.data.clienttypebgcolor==""){
            url = String.format(
                '<a href="index.php?fuse=clients&amp;view=Admin_Profile_Contact&amp;frmClientID={1}">{0}</a>',
                name, 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>',
                name, 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;

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

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

    function toggleButtons(count){
        if(count == undefined){
            count = sm.getCount();
        }
        if(count>0){
            deletebutton.setDisabled(false);
        }else{
            deletebutton.setDisabled(true);
        }
    }

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

        // grid columns
        columns:[sm, {
            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,
        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");
            }
        },
	sm: sm,
	buttons:[deletebutton = new Ext.Button({
	    id:'actionbuttons',
	    autoHeight:true,
	    xtype:'button',
	    text:'Delete',
	    disabled: true,
	    onClick: function(record){
		response = Ext.MessageBox.show({
		    title: lang('Delete Users?'),
		    msg: lang('Do you want to use the respective server plugins to delete all these users?'),
		    buttons: Ext.MessageBox.YESNOCANCEL,		    
		    icon: Ext.MessageBox.QUESTION,
		    fn: processDeleteResult
		});
	    }
	})],
	buttonAlign:'left'
    });

    function processDeleteResult(result)
    {
	if ( result == 'cancel' )
	    return;
	
	// DeleteClient expects 1/0
	if ( result == 'yes' )
	    result = 1;
	else
	   result = 0;

	
	if ( !deletebutton.disabled )
	{
	    requestURL = "index.php?fuse=clients&action=DeleteClient&deletewithplugin=" + result;
	    processAction(requestURL);
	}
    }

    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) {
		grid.enable();
		gridstore.load({params:{start:0}});
		toggleButtons(0);
		var data = Ext.util.JSON.decode(xhr.responseText);
		if(data.message){
		    msg(data.message);
		}else{
		    msg(lang("The selected users have been removed."));
		}
	    },
	    failure: function() {
		grid.enable();
		msg(lang("There was an error performing this action"));
	    },
	    params: {
		deleteid: Ext.util.JSON.encode(GetSelectedRowIds()),
		isjson: 1,
		nextaction: 'ViewUsers'
	    }
	});
    }


grid.restoreState();


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

    // render it
    grid.render();
    
    // trigger the data store load
    gridstore.load({params:{start:0}});
    
    // create the combo instance
    new Ext.form.ComboBox({
        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");
           }
        });
    }
    PopulateUserFilters();
});
