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

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

Ext.ux.Page = function(parent_el, init_tags){
    this.init_tags = (init_tags || false);
    this.parent = Ext.get(parent_el);
    this.init();
}

Ext.ux.Page.prototype = {
    init: function(){
        // set the ratings
        cr = this.parent.select('div.rating img.rate');
        cr.on('click', this.rateComment, this);

        // fix the page nav;
        pn = this.parent.select('table.pagenav_tbl td.has_link a');
        pn.on('click', this.pageNavClick, this);


        var frm = this.parent.select('form.commentForm');
        frm.on('submit', this.commentFormSubmit, this, {
            stopEvent: true
        });

        if (this.init_tags !== false) {
            /** 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
                });
            }
        }
    },

    _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);
    },

    destroy: function(){
        cr = this.parent.select('div.rating img.rate');
        cr.un('click', this.rateComment);

        // fix the page nav;
        pn = this.parent.select('table.pagenav_tbl td.has_link a');
        pn.un('click', this.pageNavClick);


        var frm = this.parent.select('form.commentForm');
        frm.un('submit', this.commentFormSubmit);

        if (this.init_tags !== false) {
            /** Tag Support **/
            var tagAdd = this.parent.select('a.tagAdd');
            if (tagAdd.elements.length > 0) {
                tagAdd.un('click', this.addTags);
            }

            var tagRemove = this.parent.select('a.removeTag');
            if (tagRemove.elements.length > 0) {
                tagRemove.un('click', this.removeTag);
            }
        }
    },
    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);

                window.scrollTo(0, el.getBox()['y'] - 50);
            }, this)
            u.on('failure', function(el, o){
                // make sure we have the second one.
                var swt = Ext.fly(this.parent.query('.box-inside-text'));
                swt.update(o.responseText);
            }, 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.parent.query('.comment_form_holder')[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('.comment_holder'), 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
            });
        }
    }
}

Ext.namespace("Ext.ux.MapPage");

Ext.ux.MapPage = function(parent_el){
    this.parent_el = parent_el;
    this.parent = Ext.get(parent_el);
    this.init_tags = false;
    this.mapInit();
}

Ext.extend(Ext.ux.MapPage, Ext.ux.Page, {
    mapInit: function(){
        if (this.parent) {
            this.init();
        } else {
            var t = new Ext.util.DelayedTask(this.registerParent, this, [this.parent_el]);
            t.delay(20);
        }
    },
    registerParent: function(el){
        this.parent = Ext.get(el);
        this.mapInit();
    }
});


