Ext.BLANK_IMAGE_URL = 'templates/images/ext/default/s.gif';

var selectedCat = -1;
var selectedArticleId = 0;
var deletedCatParentId = -1;
var addCatWin;
var addArticleWin;
var articleAuthor="";
var returnedtickettype =0;

var gridstore = new Ext.data.JsonStore({
        id: "gridstore",
        root: 'topics',
        totalProperty: 'totalCount',
        idProperty: 'threadid',
        remoteSort: true,
        baseParams:{catid: "-1"},
        fields: [
            'title', 'forumtitle', 'articleid', 'author','type','created','modified','excerpt','totalvisitors','rating'
        ],

        // 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=KB_GetArticles_Async'
        })
});
gridstore.setDefaultSort('modified', 'desc');



function _GetTreeNodeCount(nodeNameWithCount){
    var pos = strrpos(nodeNameWithCount,"(");
    var nodeCount = substr(nodeNameWithCount,pos);
    nodeCount = (nodeCount.split("(")[1].split(")")[0]);
    return nodeCount;
}

function _GetTreeNodeName(nodeNameWithCount){
    var pos = strrpos(nodeNameWithCount,"(");
    var nodeName = substr(nodeNameWithCount,0, (pos-nodeNameWithCount.length));
    return nodeName;
}

function UpdateTreeNodeCount(node,subtract){
    var nodeCount = _GetTreeNodeCount(node.text);
    if(subtract){
        nodeCount--;
    }else{
        nodeCount++;
    }
    node.setText(_GetTreeNodeName(node.text) + "("+nodeCount+")");
}

function GetNodePathToAdd(newNode){
    //only return node path of the categories that are not in the parent list
    //so it will add to the count of a sibling node, but not its parent.  In
    //event we are adding to nodes within our own tree structure

    newPath = newNode.getPath();
    var tree = Ext.getCmp('categoryTree');
    var pnode = tree.getNodeById(selectedCat);
    var tnode;

    //loop through new path
    arr = newPath.split("/");
    returnStr = "";
    for ( x=0;x<=arr.length;x++)
    {
        if((arr[x]!="-1")&&(arr[x]!=="")&&(arr[x]!==null)&&(arr[x]!==undefined)){
            tnode = tree.getNodeById(arr[x]);
            //if((!pnode.isAncestor(tnode)) && (pnode.id != arr[x])){
            if((!pnode.isAncestor(tnode)) && (!tnode.contains(pnode)) && (pnode.id != tnode.id)){
                UpdateTreeNodeCount(tnode,false);
                returnStr += "/"+arr[x];
            }
        }
    }
    return returnStr;
}

function GetNodePathToSubtract(pnode){
    //only return node path of the categories that are not in the parent list
    //so it will add to the count of a sibling node, but not its parent.  In
    //event we are adding to nodes within our own tree structure

    var tree = Ext.getCmp('categoryTree');
    oldPath = tree.getNodeById(selectedCat).getPath();

    var tnode;
    //loop through old path
    arr = oldPath.split("/");
    returnStr = "";
    for ( x=0;x<=arr.length;x++)
    {
        if((arr[x]!="-1")&&(arr[x]!=="")&&(arr[x]!==null)&&(arr[x]!==undefined)){
            tnode = tree.getNodeById(arr[x]);
            if((!pnode.isAncestor(tnode)) && (pnode.id != arr[x])){
                UpdateTreeNodeCount(tnode,true);
                returnStr += "/"+arr[x];
            }
        }
    }
    return returnStr;
}




function MoveArticleToCategorySuccess(t){
    unsetStatus('', 2);
    gridstore.reload();

}
function MoveArticleToCategory(catId,articleId,node){

    //do not do anything if moving to the open node
    if(catId == selectedCat){ return;}
    if(catId == -1){ return;}

    setStatus(lang("Moving Article"));

    var post;
    post = "articleid="+articleId;
    post += "&newCategories="+catId;
    post += "&newnodepath="+GetNodePathToAdd(node);
    post += "&oldnodepath="+GetNodePathToSubtract(node);

    new Ajax.Request(   'index.php?fuse=knowledgebase&action=KB_MoveArticles_Async',
        {
            postBody    : post,
            onSuccess   : MoveArticleToCategorySuccess
        }
    );
}



function SaveArticleSuccess(t){
    unsetStatus('', 1);

    addArticleWin.hide();
    gridstore.reload();
}
function SaveArticle(isUpdate){

    var tree = Ext.getCmp('categoryTree');
    var cbIsArtDraft = Ext.getCmp('artDraft');
    var cbAccess = Ext.getCmp('cbAccess');
    var content = Ext.getCmp('artContent');
    var tickettype = Ext.getCmp('artTicketType');


    setStatus(lang("Saving Article"));

    var post;
    post = "category="+selectedCat;
    post += "&catPath="+ tree.getNodeById(selectedCat).getPath();
    post += "&title="+encodeURIComponent($('artTitle').value);

    if( $('artTitle').value === ""){
        Ext.MessageBox.alert(lang("Errors"), lang("Please add a title."));
        return;
    }

    post += "&articleId="+selectedArticleId;
    post += "&relatedTicketTypes="+tickettype.getValue();
    post += "&content="+encodeURIComponent(content.getValue());
    post += "&author="+encodeURIComponent($('artAuthor').value);
    post += "&datecreated="+$('artCreated').value;
    post += "&relatedTopics="+$('artRelatedArticles').value;
    if(cbIsArtDraft.getValue()){
        post += "&articleIsDraft=1";
    }else{
        post += "&articleIsDraft=0";
    }

    post += "&excerpt="+encodeURIComponent($('artExcerpt').value);

    //set the correct id
    var access =0;
    if(cbAccess.getValue()=="Members"){
        access = 0;
    }else if(cbAccess.getValue()=="Internal"){
        access = 1;
    }else if(cbAccess.getValue()=="Public"){
        access = 2;
    }

    post += "&articleAccess="+access;
    //post += "&relateToTicketType"=+

    if(!isUpdate){
        arr = tree.getNodeById(selectedCat).getPath().split("/");
        for ( x=0;x<=arr.length;x++)
        {
            if((arr[x]!="-1")&&(arr[x]!=="")&&(arr[x]!==null)&&(arr[x]!==undefined)){
                tnode = tree.getNodeById(arr[x]);
                UpdateTreeNodeCount(tnode,false);
            }
        }
    }

    new Ajax.Request(   'index.php?fuse=knowledgebase&action=KB_SaveArticle_Async',
        {
            postBody    : post,
            onSuccess   : SaveArticleSuccess
        }
    );



}

function DeleteArticleSuccess(t){
    unsetStatus('', 1);

    var tree = Ext.getCmp('categoryTree');
    arr = tree.getNodeById(selectedCat).getPath().split("/");
    for ( x=0;x<=arr.length;x++)
    {
        if((arr[x]!="-1")&&(arr[x]!=="")&&(arr[x]!==null)&&(arr[x]!==undefined)){
            tnode = tree.getNodeById(arr[x]);
            UpdateTreeNodeCount(tnode,true);
        }
    }
    gridstore.reload();
}

function DeleteArticle(){
    setStatus(lang("Saving Article"));
    var tree = Ext.getCmp('categoryTree');

    var post;
    post += "&articleId="+selectedArticleId;
    post += "&catPath="+ tree.getNodeById(selectedCat).getPath();

    new Ajax.Request(   'index.php?fuse=knowledgebase&action=KB_DeleteArticle_Async',
        {
            postBody    : post,
            onSuccess   : DeleteArticleSuccess
        }
    );
    
}


function SaveCategorySuccess(t){
    unsetStatus('', 1);

    var tree = Ext.getCmp('categoryTree');
    var pnode = tree.getNodeById(selectedCat);

    //only expand if it was a new node
    if(t.responseText.split("|")[2]=="1"){
        var path = pnode.getPath();
        pnode.reload();
        tree.expandPath(path);
    }else{
        //only update text of selected cat if it was an update
        //var tmp = pnode.text.split("(");
        var count = _GetTreeNodeCount(pnode.text);
        pnode.setText(t.responseText.split("|")[1] + " (" + count + ")");
    }

}

function SaveCategory(isUpdate){

    var title = $("catTitle").value;
    var description = $("catDescription").value;
    var staffOnly = 0;
    if($('catStaffOnly').checked){
       staffOnly =1;
    }

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

    //KB_SaveCategory_Async
    setStatus(lang("Saving Category"));

    var post;
    post = "category="+selectedCat;
    post += "&title="+encodeURIComponent(title);
    post += "&description="+ encodeURIComponent(description);
    post += "&staffOnly="+ staffOnly;
    if(isUpdate){
        post += "&categoryId="+selectedCat;
    }

    new Ajax.Request(   'index.php?fuse=knowledgebase&action=KB_SaveCategory_Async',
        {
            postBody    : post,
            onSuccess   : SaveCategorySuccess
        }
    );

    addCatWin.hide();


}


function SelectNode(id,text){
    gridstore.baseParams = {catid: id};
    gridstore.load({params:{start:0, limit:10}});

    selectedCat = id;

    var grid = Ext.getCmp('articleGrid');
    var title = lang("Article for category: ") + text.split("(")[0];
    grid.setTitle(title);
    if(id!=-1){
        $('btnEditCategory').disabled=false;
    }else{
        $('btnEditCategory').disabled=true;
    }
}

function DeleteCategorySucess(t){
    unsetStatus('', 1);

    var delCatParentId = t.responseText.split("||")[0];
    var error = t.responseText.split("||")[1];

    if(error!==""){
        Ext.MessageBox.alert('Errors', t.responseText);
        return;
    }

    //get parentid for the node we are deleting
    //so that we can reload it
    var tree = Ext.getCmp('categoryTree');
    var pnode = tree.getNodeById(delCatParentId);
    pnode.reload();
    pnode.select();
    SelectNode(pnode.id,pnode.text);

    addCatWin.hide();
}

function DeleteCategory(){
    //calls the ajax action that returns the fields
    //then call category with edit

    //KB_SaveCategory_Async
    setStatus(lang("Loading Category"));

    //get parentid for the node we are deleting
    //so that we can reload it
    var tree = Ext.getCmp('categoryTree');
    var pnode = tree.getNodeById(selectedCat);
    var selectedCatParentId = pnode.parentNode.id;

    var post;
    post = "categoriesId="+selectedCat;
    post += "&parentId="+selectedCatParentId;

    new Ajax.Request(   'index.php?fuse=knowledgebase&action=KB_DeleteCategory_Async',
        {
            postBody    : post,
            onSuccess   : DeleteCategorySucess
        }
    );
    
}


function AddCategory(edit){
        var btnAddCategory = Ext.get("btnAddCategory");
        if(!addCatWin){
            addCatWin = new Ext.Window({
                id: "catWindow",
                x: 400,
                y: 200,
                applyTo     : 'category-win',
                labelAlign: 'right',
                layout      : 'form',
                width       : 400,
                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'){
                                        DeleteCategory();
                                        addCatWin.hide();
                                    }
                                });
                            }
                        },
                        {
                            id       : 'btnUpdate',
                            text     : lang("Update"),
                            disabled : false,
                            hidden :true,
                            handler  : function(){
                                SaveCategory(true);
                            }
                        },
                        {
                            id       : 'btnSave',
                            text     : lang("Save"),
                            disabled : false,
                            handler  : function(){
                                SaveCategory(false);
                            }
                        },{
                            id       : 'btnCancel',
                            text     : lang("Cancel"),
                            disabled : false,
                            handler  : function(){
                                addCatWin.hide();
                            }
                        }
                    ]

            });
        }

        //reset values
        $('catTitle').value="";
        $('catDescription').value="";
        //$('catTitle').focus();

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



function EditCategorySuccess(t){
    unsetStatus('', 1);

    AddCategory(true);

    var catReturnedId = t.responseText.split("||")[0];
    if(selectedCat == catReturnedId){

        $('catTitle').value=t.responseText.split("||")[1];
        $('catDescription').value=t.responseText.split("||")[2];

        var cbStaffOnly = Ext.getCmp('catStaffOnly');
        if(t.responseText.split("||")[3]=="1"){
            cbStaffOnly.setValue(true);
        }else{
            cbStaffOnly.setValue(false);
        }
    }
}

function EditCategory(){
    //calls the ajax action that returns the fields
    //then call category with edit

    //KB_SaveCategory_Async
    setStatus(lang("Loading Category"));

    var post;
    post = "category="+selectedCat;

    new Ajax.Request(   'index.php?fuse=knowledgebase&action=KB_GetCategory_Async',
        {
            postBody    : post,
            onSuccess   : EditCategorySuccess
        }
    );

}

function _clearAddArticleForm(){
    //clear fields
    $('artTitle').value = "";
    $('artExcerpt').value = "";
    $('artRelatedArticles').value = "";

    var content = Ext.getCmp('artContent');
    content.setValue("");
}
function AddArticle(t){

        var json = eval('(' + t.responseText + ')');

        unsetStatus('', 1);
        if(selectedCat==-1){
            Ext.MessageBox.alert(lang("Errors"), lang("Please select a category to add a new article to."));
            return;
        }

        var btnAddArticle = Ext.get("btnAddArticle");

        if(!addArticleWin){

            tickettypestore = new Ext.data.JsonStore({
                id: "tickettypestore",
                root: 'topics',
                totalProperty: 'totalCount',
                idProperty: 'typeid',
                fields: [
                    'typeid', 'typename'
                ],

                // 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=KB_GetTicketTypes_Async'
                })
            });

            tickettypestore.on({
              load: function(){
                    var ctrlticketype = Ext.getCmp('artTicketType');
                    ctrlticketype.setValue(returnedtickettype);
                    returnedtickettype=0;}
             });

            accessStore = new Ext.data.SimpleStore({
                fields: ['type'],
                data:[
                 ["Members"],["Public"],["Internal"]
                ]
            });

            tickettypecombo = new Ext.form.ComboBox({
                            id:'artTicketType',
                            store: tickettypestore,
                            displayField:'typename',
                            valueField: 'typeid',
                            labelStyle: 'font-weight:bold;font-size:11px;',
                            fieldLabel: lang("Ticket Types"),
                            mode: 'local',
                            forceSelection: true,
                            width: 210,
                            value: "None",
                            editable:false,
                            triggerAction: 'all',
                            selectOnFocus:true
                            });

            
            artDateField = new Ext.form.DateField({
                            xtype:'datefield',
                            labelStyle: 'font-weight:bold;font-size:11px;',
                            fieldLabel: lang("Date Created"),
                            name: 'artCreated',
                            width: 142,
                            id: 'artCreated'
                        });

            artDateField.on({
                  hide: function(){
                      this.getEl().up('.x-form-item').setDisplayed(false);
                  },
                  show : function(){
                      this.getEl().up('.x-form-item').setDisplayed(true);
                  }
              });



            addArticlePanel = new Ext.FormPanel({
                frame:true,
                bodyStyle:'padding:5px 5px 0',
                labelAlign: 'right',
                items :[{
                    layout:'column',
                    items:[{
                        columnWidth:0.6,
                        layout: 'form',
                        items: [{
                            xtype:'textfield',
                            labelStyle: 'font-weight:bold;font-size:11px;',
                            fieldLabel: lang("Title"),
                            width: 270,
                            name: 'artTitle',
                            id:'artTitle'
                        }, {
                            xtype:'textfield',
                            labelStyle: 'font-weight:bold;font-size:11px;',
                            fieldLabel: lang("Category"),
                            width: 270,
                            id:'artCategory',
                            disabled:true,
                            name: 'artCategory'
                        },{
                            xtype:"checkbox",
                            fieldLabel: lang("Is Draft"),
                            boxLabel: '',
                            name: 'artDraft',
                            id: 'artDraft',
                            labelStyle: 'font-weight:bold;font-size:11px;'
                        }
                        ]
                    },{
                        columnWidth:0.4,
                        layout: 'form',
                        items: [
                         {
                            xtype:'textfield',
                            id: 'artAuthor',
                            labelStyle: 'font-weight:bold;font-size:11px;',
                            fieldLabel: lang("Author"),
                            name: 'artAuthor'
                        },new Ext.form.ComboBox({
                                id: 'cbAccess',
                                store: accessStore,
                                displayField:'type',
                                valueField: 'type',
                                labelStyle: 'font-weight:bold;font-size:11px;',
                                fieldLabel: lang("Access"),
                                mode: 'local',
                                forceSelection: true,
                                width: 142,
                                editable:false,
                                value:"Public",
                                triggerAction: 'all',
                                selectOnFocus:true
                            }),artDateField
                        ]
                    }]
                },
                new Ext.form.TextArea({
                    id: "artExcerpt",
                    border : false,
                    hideLabel: false,
                    fieldLabel: lang("Excerpt"),
                    labelStyle: 'font-weight:bold;font-size:11px;',
                    anchor:'98%',
                    height:60,
                    name: 'artExcerpt'
                }),
                {
                    xtype:'htmleditor',
                    id:'artContent',
                    name: 'artContent',
                    labelStyle: 'font-weight:bold;font-size:11px;',
                    fieldLabel:lang("Content"),
                    height:320,
                    anchor:'98%'
                },{
                    layout:'column',
                    items:[{
                        columnWidth:0.5,
                        layout: 'form',
                        items: [{
                            xtype:'textfield',
                            labelStyle: 'font-weight:bold;font-size:11px;',
                            fieldLabel: lang("Related To"),
                            name: 'artRelatedArticles',
                            id:'artRelatedArticles'
                        }]
                    },{
                        columnWidth:0.5,
                        layout: 'form',
                        items: [tickettypecombo]
                    }]
                }, new Ext.form.FileUploadField({
                        id: 'artAttachment',
                        name: 'artAttachment',
                        labelStyle: 'font-weight:bold;font-size:11px;',
                        fieldLabel: lang("Attachment"),
                        width: 500,
                        buttonOnly: false
                    })
                ]
            });


            addArticleWin = new Ext.Window({
                id: "articleWindow",
                x: 230,
                y: 25,
                applyTo     : 'article-win',
                width       : 700,
                height      : 600,
                title : lang("Article Window"),
                defaultType: 'textfield',
                closeAction :'hide',
                items : addArticlePanel,
                layout : 'fit',
                buttons: [{
                            id  : 'btnArtDelete',
                            text: lang("Delete"),
                            handler  : function(){
                                Ext.MessageBox.confirm('Confirm', lang('Are you sure you want to do that?'), function(btn, text){
                                    if (btn == 'yes'){
                                        DeleteArticle();
                                        addArticleWin.hide();
                                    }
                                });

                                
                            }
                        },{
                            id  : 'btnArtUpdate',
                            text: lang("Update"),
                            handler  : function(){
                                SaveArticle(true);
                            }
                        },{
                            id  : 'btnArtSave',
                            text: lang("Save"),
                            handler  : function(){
                                SaveArticle(false);
                            }
                        },{
                            id  : 'btnArtCancel',
                            text: lang("Cancel"),
                            handler  : function(){
                                addArticleWin.hide();
                            }
                }],
                closable : true
            });
        }


        tickettypestore.load();
        addArticleWin.show(btnAddArticle);


        var btnArtSave = Ext.getCmp('btnArtSave');
        var btnArtUpdate = Ext.getCmp('btnArtUpdate');
        var btnArtDelete = Ext.getCmp('btnArtDelete');
        var ctrlAccess = Ext.getCmp('cbAccess');
        var content = Ext.getCmp('artContent');
        var artCreated = Ext.getCmp('artCreated');

        $('artAuthor').value = json.authorname;
        if(json.hasdata=="1"){

            _clearAddArticleForm();

            $('artTitle').value = json.title;
            $('artExcerpt').value = json.excerpt;
            $('artCreated').value = json.datecreated.split(" ")[0];
            $('artCategory').value = json.categoryname;
            //isdraft
            var cbIsArtDrafe = Ext.getCmp('artDraft');
            if(json.isdraft=="1"){
                cbIsArtDrafe.setValue(true);
            }else{
                cbIsArtDrafe.setValue(false);
            }

            if(json.access==1){
                ctrlAccess.setValue("Internal");
            }else if(json.access==2){
                ctrlAccess.setValue("Public");
            }else{
                ctrlAccess.setValue("Members");
            }

            $('artRelatedArticles').value = json.relatedids;
            content.setValue(json.content);

            //set associated ticket type
            if(json.tickettypeids===""){
                returnedtickettype = 0;
            }else{
                returnedtickettype = json.tickettypeids.split(",")[0];
            }


            artCreated.show();
            btnArtSave.hide();
            btnArtDelete.show();
            btnArtUpdate.show();
            newtitle = addArticleWin.title + " Id:"+ selectedArticleId;
            addArticleWin.title = addArticleWin.setTitle(newtitle);

        }else{

            _clearAddArticleForm();

            var tree = Ext.getCmp('categoryTree');
            var pnode = tree.getNodeById(selectedCat);
            $('artCategory').value = _GetTreeNodeName(pnode.text);
            ctrlAccess.setValue("Public");

            //set buttons
            artCreated.hide();
            btnArtSave.show();
            btnArtDelete.hide();
            btnArtUpdate.hide();

        }

}

function PreAddArticle(articleId){

    selectedArticleId = articleId;

    //calls the ajax action that returns the fields
    //then call category with edit
    setStatus(lang("Loading Article"));

    var post;
    if(articleId!==0){
        post = "articleId="+articleId;
    }

    new Ajax.Request(   'index.php?fuse=knowledgebase&action=KB_GetArticle_Async',
        {
            postBody    : post,
            onSuccess   : AddArticle
        }
    );

}



function MoveCategorySuccess(t){
    unsetStatus('', 1);
}
function MoveCategory(oldParent,nodeid,newParent){
    setStatus(lang("Updating Ticket"));

    var post;
    post = "oldParent="+oldParent;
    post += "&newParent="+newParent;
    post += "&nodeid="+ nodeid;

    new Ajax.Request(   'index.php?fuse=knowledgebase&action=KB_MoveCategory_Async',
        {
            postBody    : post,
            onSuccess   : MoveCategorySuccess
        }
    );
}





Ext.onReady(function(){

    // shorthand
    var Tree = Ext.tree;
    //tree
    var tree = new Tree.TreePanel({
        id: "categoryTree",
        el:'tree-div',
        ddGroup     : 'gridDDGroup',
        useArrows:true,
        autoScroll:true,
        border:true,
        bodyBorder:false,
        collapseFirst:true,
        animate:true,
         hideCollapseTool:true,
        height:500,
        width:250,
        rootVisible:true,
        title:lang("Categories")+"-"+ lang("Articles"),
        enableDD:true,
        containerScroll: true,

        // auto create TreeLoader
        dataUrl: 'index.php?fuse=knowledgebase&action=KB_GetCategories_Async',

        root: {
            nodeType: 'async',
            text: 'Root',
            draggable:false,
            expanded:true,
            id:'-1'
        }
    });

    tree.on({
      click: function (node) {
        SelectNode(node.id, node.text);
      },
      movenode: function(tree,node,oldParent,newParent,index){
        //( Tree tree, Node node, Node oldParent, Node newParent, Number index )
        MoveCategory(oldParent.id,node.id,newParent.id);
      },
      load: function(node){
        //node.select();
      },
      beforenodedrop: function(dropEvent){
        catId = dropEvent.target.id;
        if(dropEvent.data.selections!=undefined){
          articleId = dropEvent.data.selections[0].data.articleid;
          MoveArticleToCategory(catId,articleId,dropEvent.target);
        }
      }

    });


    // render the tree
    tree.render();
    tree.getRootNode().expand();
    tree.getRootNode().select();
    // grid
    // create the Data Store
    // pluggable renders
    function renderTopic(value, p, record){
        return String.format(
                '<b><a href="javascript:PreAddArticle({3})">{0}</a></b>by {4}',
                value, record.data.forumtitle, record.id, record.data.articleid, record.data.author);
    }

    var pagingBar = new Ext.PagingToolbar({
        pageSize: 10,
        store: gridstore,
        displayInfo: true,
        displayMsg: lang("Displaying topics") + " {0} - {1} "+lang("of")+" {2}",
        emptyMsg: lang("No topics to display"),

        items:[
            '-', {
            pressed: false,
            enableToggle:true,
            text: lang("Show Excerpt"),
            cls: 'x-btn-text-icon details',
            toggleHandler: function(btn, pressed){
                var view = grid.getView();
                view.showPreview = pressed;
                view.refresh();
            }
        }]
    });


    var grid = new Ext.grid.GridPanel({
        id: "articleGrid",
        el:'topic-grid',
        height:500,
        width:700,
        title:lang("Root Articles"),
        store: gridstore,
        trackMouseOver:true,
        disableSelection:true,
        enableDragDrop:true,
        selModel         : new Ext.grid.RowSelectionModel({singleSelect : true}),
        ddGroup          : 'gridDDGroup',
        loadMask: true,

        // grid columns
        columns:[
        {
            header: lang("Id"),
            id: 'articleid',
            dataIndex: 'articleid',
            width: 10,
            sortable: false,
            hidden:true
        },
        {
            id: 'topic', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: lang("Title"),
            dataIndex: 'title',
            width: 420,
            renderer: renderTopic,
            sortable: true
        },{
            header: lang("Rating"),
            dataIndex: 'rating',
            width: 60,
            align:'center',
            hidden: false,
            sortable: true
        },{
            header: lang("Type"),
            dataIndex: 'type',
            width: 60,
            align: 'center',
            hidden:true,
            sortable: false
        },{
            header: lang("Views"),
            dataIndex: 'totalvisitors',
            width: 60,
            align: 'center',
            sortable: true
        },{
            header: lang("Created"),
            dataIndex: 'created',
            width: 150,
            align:'right',
            hidden: true,
            sortable: true
        },{
            id: "modified",
            header: lang("Last Modified"),
            dataIndex: 'modified',
            width: 150,
            align:'right',
            sortable: true
        }],

        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:false,
            getRowClass : function(record, rowIndex, p, store){
                if(this.showPreview){
                    p.body = '<p>'+record.data.excerpt+'</p>';
                    return 'x-grid3-row-expanded';
                }
                return 'x-grid3-row-collapsed';
            }
        },

        // paging bar on the bottom
        bbar: pagingBar
    });

    // render it
    grid.render();
    // trigger the data store load
    gridstore.load({params:{start:0, limit:10}});


});
