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

var gridstore;
var addCatWin;
var category;
var filtertype = "public";

Ext.onReady(function(){
	gridstore = new Ext.data.JsonStore({
                id: "gridstore",
                root: 'data',
                totalProperty: 'totalcount',
                idProperty: 'articleid',
                remoteSort: true,
                fields: [
                        'articleid','articletitle','datecreated','timeelapsed', 'rating','totalvisitors', 'articlename','articleauthor','articlecomments'
                ],
                // 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=knowledgebase&action=getArticleList',
                        method: 'GET'
                }),
                listeners:
                {
                    'load' : function() {
                        toggleButtons();
                    }
                }

	});
    
    gridstore.setDefaultSort(gridsavedstate.sortinfo.field, gridsavedstate.sortinfo.dir);
    gridstore.setBaseParam('limit', gridsavedstate.displaysize);
    gridstore.setBaseParam('category', selectedCat);

    if(document.getElementById('editcategorybtn') != null){
        new Ext.Button({
            id:"editcategory",
            renderTo:"editcategorybtn",
            text: lang('edit'),
            width: '50',
            style: {paddingLeft:'7px'},
            hidden: true,
            handler:function(){
                category.ViewForEdit();
            }
        });
    }

    if(document.getElementById('addcategorybtn') != null){
        new Ext.Button({
            id:"addcategory",
            renderTo:"addcategorybtn",
            text: lang('+'),
            hidden: false,
            style: {paddingLeft:'10px'},
            handler:function(){
                category.Add();
            }
        });
    }

    function ArticleTitleRenderer(value, p, record){
        //PreAddArticle
        var name = record.data.articlename;
        if (filtertype != "summaries"){
            name = String.format(
                '<a href="javascript:PreAddArticle({3})">{0}</a>',
                value, record.data.articlename, record.id, record.data.articleid);
        }
        return name;
    }

    var kbgridbb = new Ext.PagingToolbar({
        id:'KBgridpagingbar',
        store: gridstore,
		//gridsavedstate.displaysize
        pageSize: 10,
        emptyMsg : "",
        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('KBgridpagingbar').style.display = ( data.pages > 1 ) ? '' : 'none';
                document.getElementById('articlelistlabel').innerHTML = String.format(lang('Displaying articles') +' {0} - {1}' + ' of ' + '{2}',from,to,data.total);
            }
        }
    });

    function toggleButtons(count){
        if(sm.getCount()>0){
            deletearticlebutton.setDisabled(false);
            assignarticletocombo.setDisabled(false);
            assigntolabel.setDisabled(false);
            
        }else{
            deletearticlebutton.setDisabled(true);
            assignarticletocombo.setDisabled(true);
            assigntolabel.setDisabled(true);
            
        }
    }

    function GetSelectedRowIds(){
        var arrayofids = new Array();
        rows = sm.getSelections();
	    for(x=0;x<rows.length;x++){
	       arrayofids[x] = rows[x].data.articleid;
	    }
	    return arrayofids;
    }

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

    var grid = new Ext.grid.GridPanel({
        el:'articles-grid',
        autoHeight:true,
        store: gridstore,
        trackMouseOver:true,
        disableSelection:true,
        loadMask: true,
        
        // grid columns
        columns:[sm,{
            id: 'articleid', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: "Id",
            width: 25,
			dataIndex : "articleid",
            sortable: false,
			align:"center"
        },{
            id: 'articletitle', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Title"),
            width: 150,
			dataIndex : "articlename",
            renderer : ArticleTitleRenderer,
            sortable: false
        },{
			id: 'datecreated',
            header: lang("Created"),
			dataIndex : "datecreated",
            width: 60,
            align: "center",
            sortable: false
        },{
			id: 'author',
            header: lang("Author"),
			dataIndex : "articleauthor",
            width: 100,
            sortable: false,
			align:"center"
        },{
			id: 'rating',
            header: lang("Rating"),
			dataIndex : "rating",
            width: 50,
            sortable: false,
			align:"center"
        },{
            id: 'totalvisitors', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Views"),
            width: 40,
            dataIndex : "totalvisitors",
            align:"center",
            sortable: false
        },{
            id: 'totalcomments', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Replies"),
            width: 40,
            dataIndex : "articlecomments",
            align:"center",
            sortable: false
        }
        ],
		stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no articles available for the selected category / filter"),
            scrollOffset:1
        },
        // paging bar on the bottom
        bbar: kbgridbb,
        sm:sm,
        buttons:[deletearticlebutton = new Ext.Button({
                     id:'actionbuttons',
                     autoHeight:true,
                     arrowAlign:'right',
                     xtype:'button',
                     text:lang('Delete'),
                     disabled: true,
                     listeners:{
                         'click' : function(cb,record){
                             Ext.MessageBox.confirm('Confirm', lang('Are you sure you want to delete these articles?'), function(btn, text){
                                if (btn == 'yes'){
                                    deleteArticles();
                                }
                            });
                         }
                     }
                 }),
                 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: '
                 }),
                 assignarticletocombo = new Ext.form.ComboBox({
                    triggerAction: 'all',
                    lazyRender:false,
                    editable:false,
                    disabled: true,
                    value:"          - Select Category -",
                    mode: 'local',
                    store: new Ext.data.ArrayStore({
                        idIndex: 0,
                        fields: [
                            'myId',
                            'displayText',
                            'type',
                            'prename'
                        ]
                    }),
                    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 these articles?'), function(btn, text){
                                if (btn == 'yes'){
                                    moveArticles(record.data.myId);
                                }
                             });
                         }
                    }
                 })
                ],
        buttonAlign:'left'
    });

    // render it
    grid.render();
    // trigger the data store load
    gridstore.load({params:{start:0}});
    
    var articlecombo2 = new Ext.form.ComboBox({
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value:"All",
        mode: 'local',
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'name'
            ],
            data:[
                ['Any', 'All'],
                ['Unread', 'Unread'],
                ['Read', 'Read']
            ]
        }),
        valueField: 'id',
        width: 100,
        displayField: 'name',
        applyTo: 'articlestatus',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                FilterGrid('articlestatus', record.data.id);
             }
        }
    });
    
    var storeItem = Ext.data.Record.create([{name:'myId',type:'string'},{name:'displayText',type:'string'}]);
    var articlecombo = new Ext.form.ComboBox({
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value:"Public Articles",
        mode: 'local',
        store: new Ext.data.ArrayStore({
            idIndex: 0,
            fields: [
                'myId',
                'displayText',
                'type',
                'private'
            ]
        }),
        valueField: 'myId',
        width: 220,
        displayField: 'displayText',
        applyTo: 'articlefilter',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                FilterGrid('articlefilters', record.data.myId);
                filtertype = record.data.myId;
             }
        }
    });

    var categoryfiltercombo = new Ext.form.ComboBox({
        triggerAction: 'all',
        lazyRender:false,
        editable:false,
        value:" - All -",
        mode: 'local',
        store: new Ext.data.ArrayStore({
            idIndex: 0,
            fields: [
                'myId',
                'displayText',
                'type',
                'prename'
            ]
        }),
        valueField: 'myId',
        width: 220,
        displayField: 'displayText',
        tpl: '<tpl for=".">' +
             '<div class="x-combo-list-item">'  +
             '{prename}{displayText}' +
             '</div></tpl>'
        ,
        applyTo: 'categoryfilter',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                selectedCat = record.data.myId;
                if (record.data.myId == -1) {
                   Ext.getCmp('editcategory').setVisible(false);
                   document.getElementById('editcategorybtn').style.visibility = "hidden";

                   Ext.getCmp('addArticle').setDisabled(true);
                   //document.getElementById('addArticle').style.visibility = "hidden";
                } else {
                   Ext.getCmp('editcategory').setVisible(true);
                   document.getElementById('editcategorybtn').style.visibility = "visible";
				 
                   Ext.getCmp('addArticle').setDisabled(false)
                   //document.getElementById('addArticle').style.visibility = "visible";
                }
                FilterGrid('category', record.data.myId);
             }
        }
    });

    // 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: 'numfilter',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                gridstore.setBaseParam('limit', record.data.myId);
                kbgridbb.pageSize = record.data.myId;
                gridstore.load({params:{start:0}});
                gridsavedstate.displaysize = record.data.myId;
                //updateGridSavedState("ClientListGridState");
             }
        }
    });


    if(document.getElementById('addArticleBtn') != null){
        new Ext.Button({
            id:"addArticle",
            renderTo:"addArticleBtn",
            text: lang('Add Article'),
            disabled: true,
            handler:function(){
                PreAddArticle(0);
            }
        });
    }

    function moveArticles(categoryId)
    {
        var articles = Ext.util.JSON.encode(GetSelectedRowIds());
        var categories = Ext.util.JSON.encode(new Array(categoryId));

        Ext.Ajax.request({
           url: 'index.php?fuse=knowledgebase&action=moveArticles',
           success: function(xhr) {
                var json = ce.parseAjaxResponse(xhr);
                FilterGrid();
           },
           failure: function() {
           },
           params: {articleId: articles,
                    newCategories: categories}
        });
    }

    function deleteArticles()
    {
        Ext.Ajax.request({
           url: 'index.php?fuse=knowledgebase&action=deleteArticles',
           success: function(xhr) {
                var json = ce.parseAjaxResponse(xhr);
                FilterGrid();
           },
           failure: function() {
           },
           params: {articleId: Ext.util.JSON.encode(GetSelectedRowIds())}
        });
    }

    function populateArticleFilters(){

        Ext.Ajax.request({
           url: 'index.php?fuse=knowledgebase&action=getArticleFilters',
           success: function(xhr) {
                var data = ce.parseAjaxResponse(xhr);
                if(!data.error){
                    //clear the items from our combobox
                    articlecombo.getStore().removeAll();
                    //go through our options and add to the UI
                    //data.options.forEach(updateButtonsWithContent);
                    for ( var i in data.options )
                    {
                        updateFilterWithContent( data.options[i] );
                    }
                }
            },
           failure: function() {
           },
           params: {foo: 'bar'}
        });

    }

    function populateCategoryCombo()
    {
        
        //get list of categories
        Ext.Ajax.request({
           url: 'index.php?fuse=knowledgebase&action=adminGetCategories',
           success: function(xhr) {
                var data = ce.parseAjaxResponse(xhr);
                if(!data.error){
                    //clear the items from our combobox
                    categoryfiltercombo.getStore().removeAll();
                    assignarticletocombo.getStore().removeAll(true);
                    //go through our options and add to the UI
                    var allitem= new Array()
                    allitem["id"] = -1;
                    allitem["name"] = " - All -";
                    allitem["blanks"] = 0;
                    updateCategoryCombo(allitem);
                    for (var i = 0; i < data.results.length; i++) {
                        updateCategoryCombo(data.results[i]);
                    }
                }
           },
           failure: function() {
           },
           params: {foo: 'bar'}
        });
    }

    function updateCategoryCombo(data)
    {

        var prename = "";
        for (var x=0; x < data.blanks; x++) {
            prename += "&nbsp;&nbsp;&nbsp;";
        }
        if (data.blanks > 0) {
            prename += "|-";
        }
        var comboitem = new storeItem({myId:data.id,displayText:data.name,prename:prename});
        categoryfiltercombo.getStore().insert(
           categoryfiltercombo.getStore().getCount(),
           comboitem
        );

        if (data.id !=-1 ) {
            assignarticletocombo.getStore().insert(
               assignarticletocombo.getStore().getCount(),
               comboitem
            );
        }


        if (data.id == selectedCat) {
            categoryfiltercombo.setValue(selectedCat);
        }
    }

    function updateFilterWithContent(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});
            articlecombo.getStore().insert(
               articlecombo.getStore().getCount(),
                comboitem
            );

        }
    }

    function FilterGrid(filtername, filter){
        //these are set in the viewusers.tpl
        if(filter != null){
            gridstore.setBaseParam(filtername, filter);
        }
        gridstore.load({params:{start:0}});
    }

    populateArticleFilters();
    populateCategoryCombo();


    //start defining Category Methods
    function Category ()
    {
        //category class
    }

    Category.prototype.Add = function() {
        this._showScreen(false);
    }

    Category.prototype.ViewForEdit = function(){
        //get list of categories
        Ext.Ajax.request({
           url: 'index.php?fuse=knowledgebase&action=adminGetCategory',
           success: function(xhr) {
                var t = ce.parseAjaxResponse(xhr);
                if(!t.error) {
                    category._showScreen(true);
                    var data = t.data;
                    Ext.getCmp('catTitle').setValue(data.catName);
                    Ext.getCmp('catDescription').setValue(data.catDesc);
                    var cbStaffOnly = Ext.getCmp('catStaffOnly');
                    if(data.catStaffOnly == "1"){
                        cbStaffOnly.setValue(true);
                    }else{
                        cbStaffOnly.setValue(false);
                    }
                }
           },
           failure: function() {
           },
           params: {category: selectedCat}
        });
    }

    Category.prototype._showScreen = function(edit){

        if(!addCatWin){
            addCatWin = new Ext.Window({
                id: "catWindow",
                x: 400,
                y: 200,
                labelAlign: 'right',
                layout      : 'form',
                width       : 400,
                modal       : true,
                height      : 230,
                defaultType: 'textfield',
                closeAction :'hide',
                title : lang("Category Window"),
                plain       : true,
                closable : true,
                items       : [
                        {
                            fieldLabel: lang("Title"),
                            name: 'catTitle',
                            id: 'catTitle',
                            allowBlank : false,
                            width:278,
                            labelStyle: 'font-weight:bold;font-size:11px;'
                        },
                        new Ext.form.TextArea({
                                id: "catDescription",
                                border : false,
                                hideLabel: false,
                                fieldLabel: lang("Description"),
                                labelStyle: 'font-weight:bold;font-size:11px;',
                                anchor: '99%',
                                height:100,
                                name: 'commentfield'
                        }),
                        {
                            xtype:"checkbox",
                            fieldLabel: lang("Staff Only"),
                            boxLabel: '',
                            name: 'catStaffOnly',
                            id: 'catStaffOnly',
                            labelStyle: 'font-weight:bold;font-size:11px;'
                        }
                            ],
                 buttons: [
                        {
                            id       : 'btnDelete',
                            text     : lang("Delete"),
                            disabled : false,
                            hidden:true,
                            handler  : function(){
                                Ext.MessageBox.confirm('Confirm', lang('Are you sure you want to do that?'), function(btn, text){
                                    if (btn == 'yes'){
                                        category.Delete();
                                        addCatWin.hide();
                                    }
                                });
                            }
                        },
                        {
                            id       : 'btnUpdate',
                            text     : lang("Update"),
                            disabled : false,
                            hidden :true,
                            handler  : function(){
                                category.Save(true);
                            }
                        },
                        {
                            id       : 'btnSave',
                            text     : lang("Save"),
                            disabled : false,
                            handler  : function(){
                                category.Save(false);
                            }
                        },{
                            id       : 'btnCancel',
                            text     : lang("Cancel"),
                            disabled : false,
                            handler  : function(){
                                addCatWin.hide();
                            }
                        }
                    ]

            });
        }

        //reset values
        Ext.getCmp('catTitle').setValue("");
        Ext.getCmp('catDescription').setValue("");
        Ext.getCmp('catTitle').focus('',400);

        //set buttons
        var btnSave = Ext.getCmp('btnSave');
        var btnUpdate = Ext.getCmp('btnUpdate');
        var btnDelete = Ext.getCmp('btnDelete');

        if(edit){
            btnSave.hide();
            btnDelete.show();
            btnUpdate.show();
        }else{
            btnSave.show();
            btnDelete.hide();
            btnUpdate.hide();
        }

        addCatWin.show();
        Ext.getCmp('catTitle').clearInvalid();
    }

    Category.prototype.Save = function(isUpdate){

        if (Ext.getCmp('catTitle').validate() == false) {
            Ext.MessageBox.alert(lang("Errors"), lang("Please add a title."));
            return false;
        }

        var staffOnly = 0;
        if(document.getElementById('catStaffOnly').checked){
           staffOnly =1;
        }

        Ext.Ajax.request({
           url: 'index.php?fuse=knowledgebase&action=adminSaveCategory',
           success: function(xhr) {
               var t = ce.parseAjaxResponse(xhr);
               if(!t.error)
               {
                   if (t.data.newCat) {
                       selectedCat = t.data.newselectedCat;
                   }
                   populateCategoryCombo();
                   if (t.data.newCat) {
                       FilterGrid('category', selectedCat);
                   }
               }
               
               addCatWin.hide();

           },
           failure: function() {
           },
           //parentId is only used if categoryId == 0
           params: {categoryId: selectedCat,
                    title: Ext.getCmp("catTitle").getValue(),
                    description: Ext.getCmp("catDescription").getValue(),
                    staffOnly:staffOnly,
                    isAnUpdate: isUpdate
                    }
        });

        return true;

    }

    Category.prototype.Delete = function(){
        Ext.Ajax.request({
           url: 'index.php?fuse=knowledgebase&action=adminDeleteCategory',
           success: function(xhr) {
               var t = ce.parseAjaxResponse(xhr);
               if(!t.error)
               {
                   selectedCat = t.data.parentId;
                   populateCategoryCombo();
                   FilterGrid('category', selectedCat);
               }
               addCatWin.hide();
           },
           failure: function() {
           },
           params: {categoryId: selectedCat}
        });

    }

    category = new Category();

});