/*
    SiteComponents version:
    6.8.0.1, tag SC_6_8_0_1, created Fri Aug 20 11:18:33 +0200 2010

    Disclaimer
    
    While we make every effort to ensure that this code is fit for its intended
    purpose, we make no guarantees as to its functionality. CoreTrek AS will
    accept no responsibility for the loss of data or any other damage or
    financial loss caused by use of this code.


    Copyright
    
    This programming code is copyright of CoreTrek AS. Permission to run this
    code is given to approved users of CoreTrek's publishing system CorePublish.
    
    This source code may not be copied, modified or otherwise repurposed for use
    by a third party without the written permission of CoreTrek AS.
    
    Contact webmaster@coretrek.com for information.
    
*/

// JSLint validation config
/*jslint laxbreak: true, sub: true, white: false, browser: true,
onevar: false, nomen: false, noindent: true, eqeqeq: false */
/*global siteComponentsConfig: false, Ajax: false, $$: false, $: false,
Element: false, window: false, Class: false, Effect: false, lightbox: false */

var EntityCommentUtil = Class.create({

    initialize: function(element) {
        this.element = $(element);
        
        this.openedPosts = {};
        this.initializeSubPostForms();
        this.initializeToggleLinks();
        this.initializeEditForms();
    },
    
    initializeEditForms: function() {
        this.element.select('ul.entitycommentlist li div.entitycomment-tools button.editcomment').each(function(element) {
            element.observe('click', this.editButtonClickListener.bindAsEventListener(this));
        }.bind(this));
    },
    
    /**
     * Add click observers to the subpost toggle links
     */
    initializeToggleLinks: function() {
        this.element.select('a.toggler').each(function(element) {
            element.observe('click', function(event) {
                event.stop();
                this.toggleSubpost(event.findElement('a'));
            }.bindAsEventListener(this));
        }.bind(this));
    },
    
    /**
     * Function to toggle a sub post visiblity
     */
    toggleSubpost: function(button) {
        var item = button.up(2);
        var currentId = item.id.match(/[0-9]+$/).first();
        
        item.toggleClassName('collapsed');
        
        if(typeof this.openedPosts[currentId] == 'undefined') {
            var params = {};
            params['post_id'] = currentId;
            params['service'] = 'entitycommentpost.getBody';
            
            new Ajax.Request('/xmlhttprequest.php', {
                parameters: params,
                onSuccess: function(req) {
                    var text = req.responseText;
                    var post = $('post-body-' + currentId);
                    
                    try {
                        post.setStyle({ height: post.getHeight() + 'px' });
                        post.setOpacity(0.0);
                        post.setStyle({ overflow: 'hidden' });
                        post.update(text);
                        
                        this.openedPosts[currentId] = true;
                        
                        new Effect.Opacity(post, {
                            to: 1.0,
                            from: 0.0,
                            duration: 0.5
                        });
                        
                        new Effect.Morph(post, {
                            style: {
                                height: post.scrollHeight + 'px'
                            },
                            duration: 0.5
                        });
                    } catch (err) {
                        // The above will fail if scriptaculous is missing.
                        // If it does just update and show the post
                        post.setStyle({
                            height: 'auto',
                            overflow: 'auto'
                        });
                        post.setOpacity(1.0);
                        post.update(text);
                    }
                }.bind(this)
            });
        } else {
            // If post height is set to 0px, the initial animation after the
            // ajax request did not finish correctly. We need to reset the
            // style here to make the post visible
            var post = $('post-body-' + currentId);
            if(post.getStyle('height') == '0px') {
                post.setStyle({
                    height: 'auto',
                    overflow: 'auto'
                });
                post.setOpacity(1.0);
            }
        }
    },
    
    initializeSubPostForms: function() {
        this.element.select('button.entity-comment-answer').each(function(element) {
            element.observe('click', this.answerButtonClickListener.bindAsEventListener(this));
        }.bind(this));
    },
    
    // ========================================================================
    // Listeners
    
    /**
     * This listener is triggered when the user clicks the answer button on a
     * comment post. What we need to do is copy the subpost form HTML into
     * a lightbox. After this is done we modify the form and add parent post id,
     * a quote of the original message. We also rewrite the form to do it's
     * posting using Ajax instead of a normal post.
     */
    answerButtonClickListener: function(event) {
        event.stop();
        
        this.parentId = event.element().id.substring(15);
        var form = $('subpost-entitycomment-form');
        
        // Update lightbox with to display the form
        lightbox.showHtml('<div class="lightbox-entitycomment-form">' + form.innerHTML + '</div>');
        
        var parentInput = lightbox.content.select('input[name=parentpostid]').first();
        parentInput.value = this.parentId;
        
        var quoted = lightbox.content.select('div.entitycomment-form-quoted').first();
        quoted.update($('post-body-' + this.parentId).innerHTML);
        
        // Rewrite form to post using Ajax
        this.form = lightbox.content.select('form').first();
        this.form.observe('submit', this.answerFormSubmitListener.bindAsEventListener(this));
    },
    
    editButtonClickListener: function(event) {
        event.stop();
        
        // Lets find the first element containing the post id, and extract
        // just the id part from that element id
        this.postId = event.element().up(3).identify().substr(5);
        
        new Ajax.Request('/xmlhttprequest.php?service=entitycommentpost.getEditForm', {
            parameters: { 'post_id': this.postId },
            onSuccess: function(res) {
                lightbox.showHtml('<div class="lightbox-entitycomment-form">' + res.responseText + '</div>');
                
                // Rewrite form to post using Ajax
                this.form = lightbox.content.select('form').first();
                this.form.observe('submit', this.editFormSubmitListener.bindAsEventListener(this));
            }.bind(this),
            onFailure: function(res) {
                alert("Could not get post edit form from service, check logs");
            }
        });
    },
    
    answerFormSubmitListener: function(event) {
        event.stop();
        
        new Ajax.Request(this.form.readAttribute('action'), {
            parameters: this.form.serialize(),
            onSuccess: function(req) {
                var obj = req.responseText.evalJSON();
                alert(obj['message']);
                if(!obj['isError']) {
                    // Lets redirect the user to the original returnpage
                    // to reload the comment list
                    var returnpage = this.form.select('input[name=returnpage]').first().value;
                    returnpage = returnpage.substring(0, returnpage.indexOf('#'));
                    location.href = returnpage;
                }
            }.bind(this)
        });
    },
    
    editFormSubmitListener: function(event) {
        event.stop();
        
        new Ajax.Request(this.form.readAttribute('action'), {
            parameters: this.form.serialize(),
            onSuccess: function(req) {
                var obj = req.responseText.evalJSON();
                if(obj['isError']) {
                    alert(obj['message']);
                } else {
                    // Update the post content
                    if(!Object.isUndefined(this.postId)) {
                        $('post-' + this.postId).select('p').first().update(obj['body'].replace(/\n/g, '<br/>'));
                        var urlElement = $('post-' + this.postId).select('div.entitycomment-urls').first();
                        
                        var urlLink = urlElement.select('a').first();
                        if(Object.isUndefined(obj['url'])) {
                            urlLink.setAttribute('href', '#');
                            urlLink.update();
                            urlElement.hide();
                        } else {
                            urlLink.setAttribute('href', obj['url']);
                            urlLink.update(obj['url']);
                            urlElement.show();
                        }
                        $('post-' + this.postId).pulsate({ pulses: 2, duration: 0.5 });
                    }
                    
                    lightbox.hide();
                }
            }.bind(this)
        });
    }

});

