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

function PreAddArticle(articleId){

    selectedArticleId = articleId;

    var params = "";
    if(articleId!==0){
        params = { articleId: articleId};
    }

    Ext.Ajax.request({
        url: 'index.php?fuse=knowledgebase&action=KB_GetArticle_Async',
        params: params,
        success: 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',
            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,
            format: gDateFormat,
            id: 'artCreated'
        });

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


        var excerptTip = lang('Any text included here will be added as a summary of your article.  If left blank the first couple hundred characters will be used as an excerpt.');
        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',
                        fieldLabel: lang("Title"),
                        width: 270,
                        name: 'artTitle',
                        id:'artTitle'
                    }, {
                        xtype:'textfield',
                        fieldLabel: lang("Category"),
                        width: 270,
                        id:'artCategory',
                        disabled:true,
                        name: 'artCategory'
                    },{
                        xtype:"checkbox",
                        fieldLabel: lang("Is Draft"),
                        boxLabel: '',
                        name: 'artDraft',
                        id: 'artDraft'
                    }
                    ]
                },{
                    columnWidth:0.4,
                    layout: 'form',
                    items: [
                    {
                        xtype:'textfield',
                        id: 'artAuthor',
                        fieldLabel: lang("Author"),
                        name: 'artAuthor'
                    },new Ext.form.ComboBox({
                        id: 'cbAccess',
                        store: accessStore,
                        displayField:'type',
                        valueField: 'type',
                        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:  "<span style='border-bottom: 1px solid rgb(223, 223, 223); top: 0px;' class='tip-target' qtip='" + excerptTip.replace(/'/g, "&#39;") + "'>" + lang("Excerpt") + "</span>",
                anchor:'98%',
                height:60,
                name: 'artExcerpt'
            }),
            {
                xtype:'htmleditor',
                id:'artContent',
                name: 'artContent',
                fieldLabel:lang("Content"),
                height:220,
                anchor:'98%'
            },{
                layout:'column',
                items:[{
                    columnWidth:0.5,
                    layout: 'form',
                    items: [{
                        xtype:'textfield',
                        fieldLabel: lang("Related To"),
                        name: 'artRelatedArticles',
                        id:'artRelatedArticles'
                    }]
                },{
                    columnWidth:0.5,
                    layout: 'form',
                    items: [tickettypecombo]
                }]
            }, new Ext.form.FileUploadField({
                id: 'artAttachment',
                name: 'artAttachment',
                labelStyle: 'height:27px;',
                fieldLabel: lang("Attachment"),
                width: 500,
                buttonOnly: false,
                anchor: '98%',
                border: false
            }), new Ext.form.DisplayField({
                html: '<div id="AttachmentList"></div>'
            })
            ]
        });

        //document.getElementById('artAttachment').value = "";
        addArticleWin = new Ext.Window({
            id: "articleWindow",
            x: 230,
            y: 25,
            width       : 800,
            height      : 600,
            autoHeight: true,
            modal:true,
            shadow: false,
            plain:      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();

    document.getElementById('AttachmentList').innerHTML = '';
    AttachmentTpl = new Ext.Template(
        '<div style="font-size:10px !important;padding:2px;">',
            '<span>',
                '<input type="checkbox" name="attachments" value="{ATTACHMENT_ID}" /> &nbsp;',
                '<span class="ticket-attachment">{ATTACHMENT_DATEADDED}</span> &nbsp;by:{ATTACHMENT_ADDEDBY} &nbsp;',
                '<a qtip="Submitted by: {ATTACHMENT_ADDEDBY}<br/>On: {ATTACHMENT_DATEADDED}" href="index.php?fuse=knowledgebase&action=KB_GetAttachment&articleId='+selectedArticleId+'&file_id={ATTACHMENT_ID}" >{ATTACHMENT_FILE_NAME}</a>',
            '</span>',
        '</div>'
    );

    if ( json.attachments ) {
        if(json.attachments.length > 0){
            document.getElementById('AttachmentList').innerHTML = '<span style="font-weight:bold;">Attachments</span>:<br/>';
            for(j = 0; j < json.attachments.length; j++){
                AttachmentTpl.append("AttachmentList", json.attachments[j]);
            }
            document.getElementById('AttachmentList').innerHTML += '<span style="font-size:10px>(Select checkboxes of the files you want to delete)</span>';
        }
    }

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

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

        _clearAddArticleForm();

        document.getElementById('artTitle').value = json.title;
        document.getElementById('artExcerpt').value = json.excerpt;
        document.getElementById('artCreated').value = json.datecreated.split(" ")[0];

        document.getElementById('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");
        }

        document.getElementById('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();

        //document.getElementById('artCategory').value = selectedCat;
        document.getElementById('artCategory').value = document.getElementById('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)
{
    var deleteAttachments = '';
    for(j = 0; j < document.getElementsByName("attachments").length; j++){
        if(document.getElementsByName("attachments")[j].checked){
            if(deleteAttachments != ''){
                deleteAttachments += ',';
            }
            deleteAttachments += document.getElementsByName("attachments")[j].value;
        }
    }

    if(document.getElementById('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:              document.getElementById('artTitle').value,
                      articleId:          selectedArticleId,
                      relatedTicketTypes: tickettype.getValue(),
                      content:            content.getValue(),
                      author:             document.getElementById('artAuthor').value,
                      datecreated:        document.getElementById('artCreated').value,
                      relatedTopics:      document.getElementById('artRelatedArticles').value,
                      articleIsDraft:     artIsDraft,
                      excerpt:            document.getElementById('artExcerpt').value,
                      articleAccess:      access,
                      deleteAttachments:  deleteAttachments
                      //,
                      //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);
            document.getElementById("artAttachment").value = "";
        }else{
            Ext.MessageBox.alert(lang("Errors"), "There was an error performing this action");
        }
    }*/

    addArticleWin.hide();
    if (typeof(gridstore) != 'undefined') {
       gridstore.reload();
    }
    // Remove any value from the attachment field.
    $("artAttachment").value = "";
}

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
    document.getElementById('artTitle').value = "";
    document.getElementById('artExcerpt').value = "";
    document.getElementById('artRelatedArticles').value = "";

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