/*
   SiteComponents version:
   6.6.4.1, tag SC_6_6_4_1, created Tue Oct 27 21:28:23 +0100 2009
   $Name:  $
   
   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.
  
*/

var EntityCommentUtil = Class.create({

    initialize: function(element) {
        this.element = $(element);
        
        this.openedPosts = new Object();
        this.initializeSubPostForms();
        this.initializeToggleLinks();
    },

    /**
     * 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 = new Object();
            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: .5
                        });
                    
                        new Effect.Morph(post, {
                            style: {
                                height: post.scrollHeight + 'px'
                            },
                            duration: .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.buttonClickListener.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.
     */
    buttonClickListener: 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="subpost-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.formSubmitListener.bindAsEventListener(this));
    },

    formSubmitListener: 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']); //removed by Erik 20.12.2010
                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)
        });
    }

});


