/* Comment and Response Handling */
jQuery(document).ready(function($) {
    var RECAPTCHA_KEY = "6LfdNgQAAAAAAEk1Y6Y_qyYLlb-XBndKnc20zv2Z",
        /* These may change during development, constants are put here to make it easy to change */
        ADDCOMMENT_FORM_ID = "ajax-addanonymouscomment",
        ADDCOMMENT_FORM_SELECTOR = "form#"+ADDCOMMENT_FORM_ID;

    $.fn.setup_recaptcha = function() {
        /* Quick'n'dirty jQuery plugin to set up the Recaptcha support on the
         * matched elements, using the Bottlerocket public recaptcha key.
         * ``$('div.recaptcha-holder').setup_recaptcha();``
         */
        return this.each(function() {
            var elem = $(this);
            Recaptcha.create(RECAPTCHA_KEY, elem.attr('id'), {theme:'white'});
        });
    };

    /*******************************************************************
     * Responses! Or 'Replies' as IRidePC calls them. This gets a little
     * more tricky as the addresponse form has to move itself around and
     * preferably clean up other addcomment / add response forms that may
     * be lying around the page...
     *******************************************************************/
    $('#page').delegate('a.addresponselink', 'click', function(e) {
        /* Load or show\hide the 'addresponse' form. This is a little tricky
         * as it needs to show in an area that is relevant to the comment
         * to which the reply should, um, apply. It does this by looking for
         * the class '.comment-and-replies' which encapsulates the comment itself
         * AND all of its replies, and then finds the 'addresponse-holder' class
         * within that structure. Multiple 'addresponse' forms can be on the
         * page at the same time. The form is set up to generate unique ids and
         * prefixes for each form.
         */
        e.preventDefault();
        var elem = $(this),
            outer_block = $(this).parents('div.comment-and-replies'),
            addform_holder = outer_block.find('div.addresponse-holder');

        if(addform_holder.children().length != 0) {
            addform_holder.toggle('fast');
            return false;
        }

        $.ajax({
            url: $(this).attr('href'),
            dataType: 'html',
            success: function(data) {
                addform_holder
                    .hide()
                    .html(data)
                    .find('div.recaptcha-holder').setup_recaptcha().end()
                    .show('fast');
            }
        });
    });

    var addresponse_form_submit = function(e) {
        var elem = $(this),
            form = elem.parents('form'),
            formdata = form.serializeArray(),
            outer_block = $(this).parents('div.comment-and-replies'),
            addform_holder = outer_block.find('div.addresponse-holder'),
            newresponse_holder = outer_block.find('div.newreplies');
        /* serializeArray does not add the submit button to the serialized form data.
         * z3c.form needs this information so it knows which action handler it should
         * use. */
        if(elem.is(':submit')) {
            formdata.push({'name': elem.attr('name'), 'value': elem.attr('value')});
        } else if (elem.is('form')) {
            var submit = form.find(':submit');
            formdata.push({'name': submit.attr('name'), 'value': submit.attr('value')});
        }

        $.ajax({
            url: form.attr('action'),
            data: formdata,
            traditional: true,
            type: 'POST',
            error: function(result) { alert('error: ' + result); },
            success: function(result, status, xhr) {
                if(typeof(result) === 'string') {
                    /* HTML Response, it's the form! */
                    addform_holder.html(result);
                    addform_holder.find('div.recaptcha-holder').setup_recaptcha();
                } else {
                    /* JSON Response, addition succeeded! */
                    /* alert("Comment by "+result.comment_info.posted_by+" posted."); */
                    addform_holder.hide('fast').empty();
                    /* Get the result content HTML, hide it, insert at top of new responses, and fade in */
                    $(result.content).hide().prependTo(newresponse_holder).fadeIn();
                }
            }
        });
        e.preventDefault();
    };

    $('#page').delegate('form.addresponseform', 'submit', addresponse_form_submit);
    $('#page').delegate('form.addresponseform :submit', 'click', addresponse_form_submit);
});

