var addArticleWin;
var addArticlePanel;
var selectedArticleId = 0;
var returnedtickettype =0;

function PreAddArticle(articleId){

    selectedArticleId = articleId;

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

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

}


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

    if(json.hasdata =="0" && 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({
            id: 'addArticlePanel',
            name: 'addArticlePanel',
            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;height:27px;',
                fieldLabel: lang("Attachment"),
                width: 500,

                buttonOnly: false,
                anchor: '98%',
                border: false
            })
            ]
        });

        //$('artAttachment').value = "";
        addArticleWin = new Ext.Window({
            id: "articleWindow",
            x: 230,
            y: 25,
            applyTo     : 'article-win',
            width       : 800,
            height      : 600,
            autoHeight: true,
            modal:true,
            title : lang("Article Window"),
            defaultType: 'textfield',
            closeAction :'hide',
            items : addArticlePanel,
            buttons: [{
                id  : 'btnArtDelete',
                text: lang("Delete"),
                handler  : function(){
                    Ext.MessageBox.confirm('Confirm', lang('Are you sure you want to delete this article?'), 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();


    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 = lang("Article Window") + " Id:"+ selectedArticleId;
        addArticleWin.title = addArticleWin.setTitle(newtitle);

    }else{

        _clearAddArticleForm();

        //$('artCategory').value = selectedCat;
        $('artCategory').value = $('categoryfilter').value;

        ctrlAccess.setValue("Public");

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

        newtitle = lang("Article Window");
        addArticleWin.title = addArticleWin.setTitle(newtitle);
    }

}

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

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

    var artIsDraft = 0;

    if(cbIsArtDraft.getValue()){
        artIsDraft = 1
    }

    //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;
    }

    Ext.Ajax.request({
        form:     addArticlePanel.getForm().id,
        url:      'index.php?fuse=knowledgebase&action=KB_SaveArticle_Async',
        isUpload: true,
        method:   'POST',
        params:   {
                      category:           selectedCat,
                      title:              $('artTitle').value,
                      articleId:          selectedArticleId,
                      relatedTicketTypes: tickettype.getValue(),
                      content:            content.getValue(),
                      author:             $('artAuthor').value,
                      datecreated:        $('artCreated').value,
                      relatedTopics:      $('artRelatedArticles').value,
                      articleIsDraft:     artIsDraft,
                      excerpt:            $('artExcerpt').value,
                      articleAccess:      access
                      //,
                      //relateToTicketType:
                  },
        success:  onCompleteSaveArticle,
        failure:  onCompleteSaveArticle
    });
}

function onCompleteSaveArticle(responseObj)
{
    var json = ce.parseAjaxResponse(responseObj);

    /*
    var data = Ext.util.JSON.decode(responseObj.responseText);
    if(data.issue){
        if(data.details){
            Ext.MessageBox.alert(lang("Errors"), data.details);
            $("artAttachment").value = "";
        }else{
            Ext.MessageBox.alert(lang("Errors"), "There was an error performing this action");
        }
    }*/

    addArticleWin.hide();
    if (typeof(gridstore) != 'undefined') {
       gridstore.reload();
    }


}

function DeleteArticle(){
    var arrayofids = new Array();
    arrayofids[0] = selectedArticleId;
    Ext.Ajax.request({
       url: 'index.php?fuse=knowledgebase&action=deleteArticles',
       success: function(xhr) {
                if (typeof(gridstore) != "undefined") {
                    gridstore.reload();
                }
       },
       failure: function() {
            Ext.Msg.alert("Fail");
       },
       params: {articleId: Ext.util.JSON.encode(arrayofids)}
    });
}

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

    var content = Ext.getCmp('artContent');
    content.setValue("");
}