/**
 * $LastChangedDate$
 * $LastChangedRevision$
 */

Ext.ux.Tags = Ext.extend(Ext.Window, {

    _itemid : 0,
    _itemtype : 0,

    _itemtags: [],

    initComponent : function(){

        this.addEvents({
            'beforesave': true, 'save': true, 'cancel': true
        });

        this._buildSelectBox();

        Ext.apply(this, {
            width: 400,
            title: 'Modify Tags',
            resizable: false,
            modal: true,

            items: [this._selectBox],
            buttons: [{
                text: 'Save Tags',
                handler: function(e) {
                    if(this.fireEvent("beforesave", this) === false){
                        return this;
                    }

                    var p = {
                        typeid : this.getTypeId(),
                        itemid : this.getItemId()
                    };
                    p['tags[]'] = [];

                    var tags = this._selectBox.getValue();
                    tags = tags.split(',');
                    for (var t in tags) {
                        if(typeof tags[t] != 'function') {
                            p['tags[]'].push(tags[t]);
                        }
                    }

                    Ext.Ajax.request({
                        url: '/tags/modify/save',
                        params: p,
                        scope: this,
                        callback: function(opt, success, resp) {
                            this.fireEvent('save', this, Ext.decode(resp.responseText));
                            this.close();
                        }
                    })
                },
                scope: this
            },{
                text: 'Cancel',
                handler : function(e) {
                    this.fireEvent('cancel', this);
                    this._selectBox.destroy();
                    this.close();
                },
                scope: this
            }]
        });

        this.on('beforeshow', function(cmp){
            if(this._itemid == 0 || this._itemtype == 0) {
                Ext.Msg.alert("Error!", "You Must use setItem() before you can modify the tags");
                return false;
            }
        }, this);

        Ext.ux.Tags.superclass.initComponent.call(this);
    },

    _buildSelectBox : function() {
        this._selectBox = new Ext.ux.BoxSelect({
                name: location + '[]',
                store: new Ext.data.JsonStore({url: '/tags/lookup/query', root: 'tags', fields: ['tag_id', 'tag_name']}),
                mode: 'remote',
                minChars: '2',
                queryDelay: 150,
                width: 390,
                cls: 'tagSelectBox',
                displayField: 'tag_name',
                displayFieldTpl: '{tag_name}',
                valueField: 'tag_id',
                addUniqueValues: false
            })

        this._selectBox.on('render', function(cmp) {
                    Ext.Ajax.request({
                        url: '/tags/lookup/item',
                        params: { itemid: this._itemid, typeid: this._itemtype },
                        scope: this,
                        callback: function(opt, success, resp) {
                            this._itemtags = Ext.decode(resp.responseText);

                            (function(){
                                if(this._itemtags.length > 0) {
                                    this._selectBox.setValues(new Ext.data.ArrayReader({
                                                id: 0
                                            }, Ext.data.Record.create([
                                            {name: 'tag_id'},
                                            {name: 'tag_name'}
                                        ])).readRecords(this._itemtags).records);
                                }
                            }).createDelegate(this).defer(50);
                        }
                    });
                }, this);

    },

    setItem : function(itemid, typeid) {
        this._itemid = itemid;
        this._itemtype = typeid;

        return this;
    },

    getItemId : function() {
        return this._itemid;
    },

    getTypeId : function() {
        return this._itemtype;
    }
});

