/* TODO (Still a work in progress!):
    -   Figure out a better way to attach event handlers to the newly created comment, maybe scope it?
*/

var Comments = new Class({
    Implements: Options,

    options: {
        url:'/pages/ajax/comment.php',
        comments_list: false,
        comment_form_module: '.post_comment',
        comment_form_submit_btn: 'input[name=submit_btn]',
        comment_form_toggler: 'a.post_comment_link',
        response_container: '.results',
        comment_container_class: 'comment',
        actions_container: '.actions',
        hidden_form_elements_container: 'div.hidden',
        hide_form: false,
        num_comments: false
    },

    /*selectors: {
        'form_module': 'div.add_comment',
        'comment_count': 'h2',
        'comments_list' : 'ul.comments',
        'btn_toggle': '.head a',
        'btn_submit': 'form input.submit',
        'actions_inject_el': '.actions',
        'moderate_form': 'li.comment .moderate form',
        'moderate': 'li.comment .moderate form select',
        'btn_moderate': 'li.comment .moderate a',
        'btn_agree': 'li.comment a.agree',
        'btn_disagree': 'li.comment a.disagree',
        'btn_firstlast': 'ul.tabs a.firstlast',
        'btn_latest': 'ul.tabs a.latest',
        'btn_pages': 'div.page_nav a',
        'posted_comments': 'div.posted_comments .body',
        'btn_toggle_comment': 'a.toggle_comment'
    },*/

    initialize: function(el, options, selectors) {
        // If there's no form and no posted comments, quit.
        // if (!$chk(el.getElement('form')) && !$chk(el.getElement('posted_comments'))) return false;
        if (!$chk(el)){
            return;
        }

        this.setOptions(this.options, options);
        if(selectors){
            this.selectors = $H(this.selectors).extend(selectors).getClean();
        }

        //setup module
        this.module = el;

        //setup form
        this.comment_form_module = this.module.getElement(this.options.comment_form_module);
        if (!$chk(this.comment_form_module)) {
            return;
        }else{
            this.comment_form = this.comment_form_module.getElement('form');
            if(!this.comment_form){
                return;
            }
            this.initForm();
        }

        //check for num_comments
        if(this.options.num_comments){
            this.num_comments = this.module.getElement(this.options.num_comments);
        }

        // need to keep these separate for now
        /*this.initRatings();
        this.initTabs();
        this.initPages();
        this.initToggleComments();*/

        return true;
    },

    initForm: function(){
            //create action input
            new Element('input', {
                'type': 'hidden',
                'name': 'action',
                'value': false
            }).inject(this.comment_form.getElement(this.options.hidden_form_elements_container));

            // show or hide form on startup

            if(this.options.hide_form){
                this.comment_form_module.slide('hide');
            }

            //hook in form display/hide toggler
            this.form_toggler = this.module.getElement(this.options.comment_form_toggler);
            if(this.form_toggler){
                this.form_toggler.addEvent('click', function(e){
                    e.stop();
                    this.comment_form_module.slide('toggle');
                }.bind(this));
            }

            //setup the comments list
            this.comments_list = this.module.getElement(this.options.comments_list);

            //setup the response container to hold the preview and spellchecking tpls
            this.response_container = this.module.getElement(this.options.response_container);

            //setup how the form buttons will act
            this.actions = {
                submit: this.comment_form.getElement(this.options.comment_form_submit_btn)
            };

            // submit button
            this.actions.submit.addEvent('click', function(e) {
                e.stop();
                this.comment_form.getElement('input[name=check_spelling]').set('value',false);
                this.comment_form.getElement('input[name=action]').set('value', 'submit_comment');
                this.processData('submit');
            }.bind(this));

            // preview link
            this.actions.preview = new Element('li', {
                'class': 'first'
                }).adopt(new Element('a', {
                'href': '#preview',
                'html': 'Preview',
                'events': {
                    'click': function(e) {
                        e.stop();
                        this.comment_form.getElement('input[name=check_spelling]').set('value',false);
                        this.comment_form.getElement('input[name=action]').set('value', 'preview_comment');
                        this.processData('preview');
                    }.bind(this)
                }
            }));

            // spell check link
            this.actions.spellCheck = new Element('li').adopt(new Element('a', {
                'href': '#spellCheck',
                'html': 'Check Spelling',
                'events': {
                    'click': function(e) {
                        e.stop();
                        this.comment_form.getElement('input[name=check_spelling]').set('value',true);
                        this.comment_form.getElement('input[name=action]').set('value', 'spellcheck_comment');
                        this.processData('preview');
                    }.bind(this)
                }
            }));
                        
            // reset link
            this.actions.reset = new Element('li').adopt(new Element('a', {
                'href': '#reset',
                'html': 'Reset',
                'events': {
                    'click': function(e) {
                        e.stop();
                        this.reset();
                    }.bind(this)
                }
            }));
            
            this.links_list = new Element('ul');
            this.links_list.adopt(this.actions.preview, this.actions.spellCheck, this.actions.reset).inject(this.module.getElement(this.options.actions_container));
            
    
    
    },

    initRatings: function() {
        this.ratings = {
            agree: this.module.getElements(this.selectors.btn_agree),
            disagree: this.module.getElements(this.selectors.btn_disagree)
        };
        this.ratings.agree.addEvent('click', function(e) {
            (new Event(e)).stop();
            this.processRating(e.target, 1);
        }.bind(this));
        this.ratings.disagree.addEvent('click', function(e) {
            (new Event(e)).stop();
            this.processRating(e.target, 0);
        }.bind(this));
    },

    initTabs: function() {
        if ($chk(this.module.getElement(this.selectors.btn_firstlast))) {
            this.actions.btn_firstlast = this.module.getElement(this.selectors.btn_firstlast);
            this.actions.btn_firstlast.addEvent('click', function(e) {
                (new Event(e)).stop();
                this.getNewComments($H(this.actions.btn_firstlast.getJSONData('rel')));
            }.bind(this));
        }

        if ($chk(this.module.getElement(this.selectors.btn_latest))) {
            this.actions.btn_latest = this.module.getElement(this.selectors.btn_latest);
            this.actions.btn_latest.addEvent('click', function(e) {
                (new Event(e)).stop();
                this.getNewComments($H(this.actions.btn_latest.getJSONData('rel')));
            }.bind(this));
        }
    },

    initPages: function() {
        if ($chk(this.module.getElements(this.selectors.btn_pages))) {
            this.btn_pages = this.module.getElements(this.selectors.btn_pages);
            this.btn_pages.addEvent('click', function(e) {
                (new Event(e)).stop();
                this.getNewComments($H(e.target.getJSONData('rel')));
            }.bind(this));
            this.comments = this.module.getElement(this.selectors.posted_comments);
        }
    },

    initToggleComments: function() {
        if ($chk(this.module.getElements(this.selectors.btn_toggle_comment))) {
            this.toggleComments = this.module.getElements(this.selectors.btn_toggle_comment);
            this.toggleComments.addEvent('click', function(e) {
                (new Event(e)).stop();
                this.toggleComment = e.target.getParent('li.comment');
                this.display_message = this.toggleComment.getElement('p.display_criteria');
                this.comment_message = this.toggleComment.getElement('div.message');
                this.display_message.toggleClass('hide_comment');
                this.comment_message.toggleClass('hide_comment');
            }.bind(this));
        }
    },

    processData: function(action) {
        this.comment_form.getElement('input[name=mode]').set('value', action);
        this.comment_request = new Request.JSON({
            url: this.options.url,
            method: 'post',
            data: this.comment_form,
            onSuccess: this.post.bind(this)
        }).send();
    },

    post: function(results) {
        // Message was previewed, edited, or spell-checked
        if (!results['data']['msg_posted']) {
            this.previewSpellCheck(results['template']);
            return false;
        }

        // If there are no comments, create the elements so we can inject the new comment
        /*if (!$chk(this.module.getElement(this.selectors.comments_list))) {
            this.comments_list = new Element('ul', {
                'class': 'comments'
            });
            this.posted_module_body = new Element('div', {
                'class': 'body'
            }).adopt(this.comments_list);
            this.posted_module = new Element('div', {
                'class': 'posted_comments module contain_singles'
            }).adopt(this.posted_module_body);
            this.posted_module.injectAfter(this.form_module);
        }*/
        
        // Build new comment, add it to the list
        var new_comment = new Element('li', {
            'class' : this.options.comment_container_class,
            'styles': {
                'visibility' : 'hidden'
            }
        }).set('html', results.template);

        new_comment.inject(this.comments_list, 'top');
        new_comment.fade('in');
        /*var fx = new Fx.Morph(new_comment, { duration: 1000 });
        fx.start({'opacity': [0,1]});*/

        // Update comment count, reset form
        if(this.num_comments){
            this.num_comments.set('html', results.data.topic.comment_count + ' Comments');
        }

        //reset the form
        this.reset();

        //add moderation to the new comment
        var new_comment_form = new_comment.getElement('form');
        if(new_comment_form){
            new Moderation({form: new_comment.getElement('form'), actions:'select'});
        }
        //this.initRatings();
    },

    previewSpellCheck: function(tpl) {
        this.hidePreview();
        this.preview_comment = new Element('div', {
            'class': 'preview'
        }).set('html', tpl);
        this.preview_comment.inject(this.response_container);
        this.response_container.tween('display','block');
    },

    reset: function() {
        this.comment_form.reset();
        this.hidePreview();
    },

    hidePreview: function() {
        if ($chk(this.preview_comment)){
            this.response_container.tween('display','none');
            this.preview_comment.destroy();
        }
    },

    processRating: function(link, value) {
        var comment_id = link.get('href').split('#')[1];
        var data = "msg_id=" + comment_id + "&thumb_val=" + value;
        this.rate_request = new Request.JSON({
            url: '/pages/ajax/thumb_comment.php',
            method: 'post',
            data: data,
            onSuccess: this.postRating.bind(this)
        }).send();
    },

    postRating: function(results) {
        $('thumbs_diff_' + results['msg_id']).set('html', results['thumbs']['thumbs_up'] + ' of ' + results['thumbs']['thumbs_total'] + ' users agree');
    },

    getNewComments: function(options) {
        this.comments.addClass('loading');
        this.comments.empty();

        checking_for_new_comments = true;
        this.page_data = options.toQueryString();

        // Button Type detection for DW tracking
        if(options.checkNew) {
            buttonType = "NewComments";
        } else if(options.cpage == undefined && options.msg_sort == 1) {
            buttonType = "First2Last";
        } else if(options.cpage == undefined && options.msg_sort == 2) {
            buttonType = "Latest";
        } else {
            buttonType = "Page"+(options.cpage+1);
        }
        var new_comments = new Request.JSON({
            url: '/pages/ajax/load_comments.php',
            method: 'post',
            data: this.page_data,
            onSuccess: this.processNewComments.bind(this),
            onComplete: function(){this.comments.removeClass('loading')}.bind(this)
        }).send();

        return false;
    },

    processNewComments: function(results) {
        this.new_comments = this.comments.getParent();
        this.new_comments.set('html',results['template']);
        this.initTabs();
        this.initRatings();
        this.initPages();
        this.initToggleComments();
        //new Moderation();
    }

});
