/**
 * @author Jon Whitcraft
 */
Ext.namespace("Ext.ux.Windows");

var tagLinks = {
    'tpe2': '/photos/tag/',
    'tpe5': '/community/designit/view/tag/',
    'tpe6': '/community/fanphotos/view/tag/',
    'tpe8': '/audio/view/tag/'
}

Ext.ux.Windows = function(parent_el, queryfor, commentquery, firstTabTitle, postInit){
    this.parent = Ext.get(parent_el);
    this.queryfor = queryfor;
    this.commentquery = commentquery;
    this.win;
    this.tabpanel;

    this.postInit = postInit ||
    function(){
    };

    if (typeof firstTabTitle == 'undefined') {
        this.firstTabTitle = 'Design';
    } else {
        this.firstTabTitle = firstTabTitle;
    }

    this.init();
}

Ext.ux.Windows.prototype = {
    init: function(){
        var obj = this.parent.select(this.queryfor);
        obj.on('click', this.fetchData, this, {
            stopEvent: true
        });

        if (typeof this.commentquery != 'undefined') {
            var obj = this.parent.select(this.commentquery);
            obj.on('click', this.fetchData, this, {
                stopEvent: true
            });
        }

        /** Favorite Support **/
        var tagFavorite = this.parent.select('div.favoriteBox a');
        if (tagFavorite.elements.length > 0) {
            tagFavorite.on('click', this.favorite, this, {
                stopEvent: true
            });
        }

        /** Tag Support **/
        var als = Ext.select('a.tagOwner');
        als.each(function(el, list, index){
            el.on('click', function(e){
                var a = e.getTarget();
                href = a.getAttribute('href');
                var re = new RegExp('\/tags\/modify\/itemid\/([0-9]*)\/type\/([0-9]*)(\/)?');
                var m = re.exec(href);
                var t = new Ext.ux.Tags();
                t.on('save', this._reloadTagBox, this);
                t.setItem(m[1], m[2]).show();
            }, this, {
                stopEvent: true
            });
        }, this);

        var els = Ext.select('div.tagHolder');
        var ids = {};

        els.each(function(el, list, index){
            var id = el.dom.id.replace('tagHolder', '');
            id = id.split('_');

            if (typeof ids[id[1]] == "undefined") {
                ids[id[1]] = [];
            }
            ids[id[1]].push(id[0]);
        });

        for (var i in ids) {
            var p = {};
            p.typeid = i;
            p.format = 'json';
            p['items[]'] = [];
            for (var x in ids[i]) {
                if (typeof ids[i][x] != "function") p['items[]'].push(ids[i][x]);
            }

            Ext.Ajax.request({
                url: '/tags/lookup/itemlist',
                params: p,
                scope: this,
                callback: this._buildTagBoxes
            });
        }

        this.postInit();
    },

    _reloadTagBox: function(cmp, values){
        if (values.length > 0) {
            var item = cmp.getItemId();
            var type = cmp.getTypeId();
            Ext.select('div#tagHolder' + item + '_' + type + ' a.tag').remove();

            _tags = this._processTags('tagHolder' + item + '_' + type, values);
        }
    },

    _buildTagBoxes: function(opt, success, resp){
        var data = Ext.decode(resp.responseText);

        var typeid = '';
        if (typeof data.items != "undefined") {
            var typeid = '_' + data.typeid;
            data = data.items;
        }

        for (var d in data) {
            if (typeof data[d] != "function") {
                this._processTags('tagHolder' + d + typeid, data[d]);
            }
        }
    },

    _processTags : function(holder, tags)
    {
        var _tags = [];
        for (var t in tags) {
            if (typeof tags[t] != "function") {
                _tags.push({
                    tag: 'a',
                    cls: 'tag',
                    href: tagLinks['tpe' + holder.substr(holder.lastIndexOf('_')+1)] + escape(tags[t][1]),
                    html: tags[t][1]
                });
            }
        }
        if (_tags.length > 0) Ext.DomHelper.append(holder, _tags);
    },

    fetchData: function(e, obj){
        _targ = e.getTarget();

        this._processObject(_targ);

    },

    windowLoadShow: function(id){
        _targ = Ext.get(id);
        if (typeof _targ != 'undefined') {
            this._processObject(_targ);
        }
    },
    _processObject: function(item){
        if (_targ.id.substring(0, 4) != 'dic_') {
            var ids = _targ.id.substring(_targ.id.indexOf('_') + 1);
            this.design_id = ids.substring(0, ids.lastIndexOf('_'));
            this.type_id = ids.substring(ids.lastIndexOf('_') + 1);
            this._initTab = 'firstWinTab';
        } else {
            var ids = _targ.id.substring(_targ.id.indexOf('_') + 1);
            this.design_id = ids.substring(0, ids.lastIndexOf('_'));
            this.type_id = ids.substring(ids.lastIndexOf('_') + 1);
            if (Ext.fly(_targ).hasClass('addComment')) {
                this._initTab = 'thirdWinTab';
            } else {
                this._initTab = 'secondWinTab';
            }
        }

        this.doFetch();
    },
    doFetch: function(){
        Ext.Ajax.request({
            url: '/window/fetch/type/' + this.type_id + '/id/' + this.design_id,
            callback: function(opt, is_success, o){
                if (is_success) {
                    this.showWindow(o);
                } else {
                    this.showFetchError();
                }
            },
            scope: this
        })
    },
    showWindow: function(o){
        if (!this.win) {
            this.win = new Ext.Window({
                autoCreate: true,
                layout: 'fit',
                width: 680,
                height: 650,
                closeAction: 'hide',
                resizable: false,
                draggable: false,
                plain: true,

                items: new Ext.TabPanel({
                    autoCreate: true,
                    activeTab: 0,
                    deferredRender: false,
                    border: false,
                    id: 'winTabs',
                    items: [{
                        title: this.firstTabTitle,
                        id: 'firstWinTab',
                        html: o.responseText,
                        autoScroll: true
                    }, {
                        title: 'Comments',
                        id: 'secondWinTab',
                        listeners: {
                            render: function(cmp){
                                this.updateCommentsTab(cmp, '/comments/fetch/item_id/' + this.design_id + '/type_id/' + this.type_id);
                            },
                            scope: this
                        }
                    }, {
                        title: 'Add Comment',
                        id: 'thirdWinTab',
                        listeners: {
                            render: function(cmp){
                                this.updateFormTab(cmp, '/comments/index/form/item_id/' + this.design_id + '/type_id/' + this.type_id);
                            },
                            scope: this
                        }
                    }],

                    buttons: [{
                        text: 'Close',
                        handler: function(){
                            this.win.hide();
                        }
.createDelegate(this)
                    }]
                })
            });

            this.tabpanel = this.win.getComponent('winTabs');
        } else {
            // clear out here and reload the comments
            this.win.center();
            this.tabpanel.findById('firstWinTab').body.update(o.responseText);
            var swt = this.tabpanel.findById('secondWinTab');
            this.updateCommentsTab(swt, '/comments/fetch/item_id/' + this.design_id + '/type_id/' + this.type_id);

            var twt = this.tabpanel.findById('thirdWinTab');
            this.updateFormTab(twt, '/comments/index/form/item_id/' + this.design_id + '/type_id/' + this.type_id);
        }
        this.win.show();
        this.tabpanel.activate(this._initTab);
    },

    updateCommentsTab: function(cmp, _url){
        var u = cmp.getUpdater();
        if (!u.hasListener('update')) {
            u.on('update', function(el, o){
                // page nav
                pn = el.select('table.pagenav_tbl td.has_link a');
                pn.on('click', this.pageNavClick, this);

                // comment rate buttons
                cr = el.select('div.rating img.rate');
                cr.on('click', this.rateComment, this);
            }, this)
            u.on('failure', function(el, o){
                // make sure we have the second one.
                var swt = Ext.fly(this.tabpanel.findById('secondWinTab').getEl().query('.x-panel-body')[0]);
                swt.update(o.responseText);
            }, this)
        }
        u.update({
            url: _url
        })
    },
    updateFormTab: function(cmp, _url){
        var u = cmp.getUpdater();
        if (!u.hasListener('update')) {
            // add listeners
            u.on('update', function(el, o){
                frm = el.select('form.commentForm');
                frm.on('submit', this.commentFormSubmit, this, {
                    stopEvent: true
                });
            }, this);
        }

        u.update({
            url: _url
        })

    },
    commentFormSubmit: function(evt, obj){
        evt.stopEvent();
        _targ = evt.getTarget();

        Ext.Ajax.request({
            url: _targ.getAttribute('action'),
            form: _targ.id,
            callback: function(opt, is_success, o){
                var twt = Ext.fly(this.tabpanel.findById('thirdWinTab').getEl().query('.x-panel-body')[0]);
                if (is_success) {
                    twt.update(o.responseText);
                } else {
                    twt.update(o.responseText);
                    var frm = twt.select('form.commentForm');
                    frm.on('submit', this.commentFormSubmit, this, {
                        stopEvent: true
                    });
                }
            },
            scope: this
        });

    },

    pageNavClick: function(evt, obj){
        evt.stopEvent();
        this.updateCommentsTab(Ext.fly(obj).parent('.x-panel-body'), obj.getAttribute("href"));
    },
    rateComment: function(evt, obj){
        evt.stopEvent();
        var val = '1';

        var _targ = evt.getTarget();
        if (_targ.id.indexOf('-no-') > 0) {
            val = '-1';
        }
        var _item_id = _targ.id.substring(_targ.id.lastIndexOf('-') + 1);

        var _type_id = _item_id.substring(_item_id.lastIndexOf('_') + 1);
        var _item_id = _item_id.substring(0, _item_id.lastIndexOf('_'));

        Ext.Ajax.request({
            url: '/comments/save/rate/type_id/' + _type_id + '/item_id/' + _item_id + '/rating/' + val,
            callback: function(opt, is_success, o){
                if (is_success) {
                    // success
                    Ext.fly('rate-holder-' + _item_id + '_' + _type_id).update(o.responseText);
                } else {
                    Ext.MessageBox.show({
                        title: 'Rating Error',
                        msg: o.responseText,
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR
                    })
                }
            },
            scope: this
        });
    },
    showFetchError: function(){
        Ext.MessageBox.show({
            title: 'Fetch Error',
            msg: 'There was an error fetching the design.  Please Try again.',
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.ERROR
        })
    },
    addTags: function(evt, obj){
        href = obj.getAttribute('href');
        var re = new RegExp('\/tags\/modify\/add\/i\/([0-9]*)\/t\/([0-9]*)\/');
        var m = re.exec(href);

        var c = {
            item_id: m[1],
            type_id: m[2]
        };

        if (typeof TAG_LINK != 'undefined') {
            c.route = TAG_LINK;
        }

        Ext.MessageBox.prompt('Add Tags', 'Separate each tag with a comma', function(btn, text){
            if (btn == 'ok' && text != '') {
                c.tags = text;
                Ext.Ajax.request({
                    url: '/tags/modify/add',
                    params: c,
                    callback: function(opt, is_success, o){
                        if (is_success) {
                            Ext.fly('tagHolder' + c.item_id + '_' + c.type_id).update(o.responseText);
                            this.linkTags(c.item_id, c.type_id);
                        } else {
                            Ext.MessageBox.show({
                                title: 'Error Adding Tags',
                                msg: 'There was an error adding the tags.  It has been reported to the Site Administrators',
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.ERROR
                            })
                        }
                    },
                    scope: this
                });
            }
        }, this);
    },
    removeTag: function(evt, obj){
        href = obj.parentNode.getAttribute('href');
        var re = new RegExp('\/tags\/modify\/remove\/tag\/([^/]*)\/i\/([0-9]*)\/t\/([0-9]*)');
        var m = re.exec(href);
        var c = {
            tag: m[1],
            item_id: m[2],
            type_id: m[3]
        };

        if (typeof TAG_LINK != 'undefined') {
            c.route = TAG_LINK;
        }

        Ext.MessageBox.show({
            title: 'Remove Tag?',
            msg: 'Are you sure you want to remove the tag: ' + m[1] + '?',
            buttons: Ext.Msg.YESNO,
            scope: this,
            fn: function(btn){
                if (btn == 'yes') {
                    Ext.Ajax.request({
                        url: '/tags/modify/remove',
                        params: c,
                        callback: function(opt, is_success, o){
                            if (is_success) {
                                Ext.fly('tagHolder' + c.item_id + '_' + c.type_id).update(o.responseText);
                                this.linkTags(c.item_id, c.type_id);
                            } else {
                                Ext.MessageBox.show({
                                    title: 'Error Removing Tag',
                                    msg: 'There was an error while removing the tag.  It has been reported to the Site Administrators',
                                    buttons: Ext.MessageBox.OK,
                                    icon: Ext.MessageBox.ERROR
                                })
                            }
                        },
                        scope: this
                    });
                }
            },
            icon: Ext.MessageBox.QUESTION
        });
    },

    linkTags: function(item_id, type_id){
        var el = Ext.fly('tagHolder' + item_id + '_' + type_id);
        var tagAdd = el.select('a.tagAdd');
        if (tagAdd.elements.length > 0) {
            tagAdd.on('click', this.addTags, this, {
                stopEvent: true
            });
        }

        var tagRemove = el.select('a.removeTag');
        if (tagRemove.elements.length > 0) {
            tagRemove.on('click', this.removeTag, this, {
                stopEvent: true
            });
        }
    },

    favorite: function(evt, obj){
        href = obj.getAttribute('href');
        var re = new RegExp('\/favorites\/modify\/(add|remove)\/i\/([0-9]*)\/t\/([0-9]*)');
        var m = re.exec(href);

        var action = m[1];
        var c = {
            item_id: m[2],
            type_id: m[3]
        };

        Ext.Ajax.request({
            url: '/favorites/modify/' + action,
            params: c,
            callback: function(opt, is_success, o){
                if (is_success) {
                    Ext.fly('favorite' + c.item_id + '_' + c.type_id).update(o.responseText);

                    var el = Ext.fly('fav' + c.item_id + '_' + c.type_id);
                    if (action == 'remove' && el != null) {
                        el.setStyle('overflow', 'hidden');
                        el.setHeight(0, {
                            duration: .4,
                            callback: function(){
                                this.remove();
                            }
                        })
                    } else {
                        this.linkFavorite(c.item_id, c.type_id);
                    }
                } else {
                    json = Ext.decode(o.responseText);
                    if (json.responseText == 'not_logged_in') {
                        Ext.MessageBox.show({
                            title: 'Error Saving Favorite',
                            msg: 'You need to be logged in to save an item as a favorite.  Please login or register.',
                            buttons: Ext.MessageBox.OK,
                            icon: Ext.MessageBox.ERROR
                        })
                    }
                }

            },
            scope: this
        });
    },
    linkFavorite: function(item_id, type_id){
        var el = Ext.fly('favorite' + item_id + '_' + type_id);
        var tagFavorite = el.select('a');
        if (tagFavorite.elements.length > 0) {
            tagFavorite.on('click', this.favorite, this, {
                stopEvent: true
            });
        }
    }
}


