/**
 * @type {Object}
 */
var MkSocialComment = {

    commentSubmitted: false,

    /**
     * @return {undefined}
     */
    initialize: function() {
        var self = this;
        jQuery('body').on('submit', 'form.tx_mksocialcomment_newComment_form', function(event) {
            event.preventDefault();
            self.submitNewComment(this);
        });

        jQuery('body').on('click', '.tx_mksocialcomment_listComments .pagebrowser a',function(event) {
            event.preventDefault();
            self.refreshCommentList(jQuery(this).attr('href'));
        });

        this.handleAnswers();
    },

    /**
    * @return {string}
    */
    getBaseUrlWithParamConnector: function() {
        var baseUrl = window.location.href;
        // remove anchor
        if((positionOfAnchor = baseUrl.lastIndexOf("#")) >= 0){
            baseUrl = baseUrl.substring(0, positionOfAnchor);
        }
        if(baseUrl.split("?").length > 1)
            return baseUrl + '&';
        else
            return baseUrl + '?';
    },

    /**
     * @return {undefined}
     */
    handleAnswers: function() {
        var self = this;
        // die Kommentare können überall eingefügt werden. Also gehen wir immer
        // vom body aus, auch wenn es etwas Performance kostet
        jQuery('body').on('click', '.answer-to-comment', function(event) {
            event.preventDefault();
            jQuery('.answer-form').hide();

            var commentUid = jQuery(this).data('comment');
            var answerFormId = '#answer-form-' + commentUid;

            if (jQuery(answerFormId + ' form').length == 0) {
                // normales Kommentarformular klonen
                jQuery(answerFormId).append(jQuery('form.tx_mksocialcomment_newComment_form.original').clone());
                // verhindern dass bereits vorhandene Fehler- und Erfolgsmeldungen ausgegeben werden
                jQuery(answerFormId + ' form .error').remove();
                jQuery(answerFormId + ' form .alert').remove();
                // alle Eingaben leeren
                jQuery(answerFormId + ' form').find('input[type="text"],textarea').val('');
                // Antwortformular vom Original unterscheidbar machen.
                jQuery(answerFormId + ' form').removeClass('original');
                // ID anpassen damit bei Ajax Calls das korrekte Formular ersetzt wird
                jQuery(answerFormId + ' form').attr('id', jQuery(answerFormId + ' form').attr('id') + '_' + commentUid);
                self.adjustFormForAnswer(commentUid);
            }

            jQuery(answerFormId).show();
        });

        // die Kommentare können überall eingefügt werden. Also gehen wir immer
        // vom body aus, auch wenn es etwas Performance kostet
        jQuery('body').on('click', '.cancel-comment-answer', function(event) {
            event.preventDefault();
            jQuery(jQuery(this).data('answer-form-id')).hide();
        });
    },

    /**
     * @return {undefined}
     */
    adjustFormForAnswer: function(commentUid) {
        var answerFormId = '#answer-form-' + commentUid;
        // die ID des zu beantwortenden Kommentars einfügen
        jQuery(answerFormId + ' form').append(
            jQuery('<input/>', {
                type: 'hidden',
                name: 'mksocialcomment[newComment][parent_comment]',
                value: commentUid
            })
        );
        // Abbrechen Button anpassen
        jQuery(answerFormId + ' form .tx_mksocialcomment_newComment_answer_cancelButton').
            find('.cancel-comment-answer').
            attr({
                "data-answer-form-id" : answerFormId
            });
        jQuery(answerFormId + ' form .tx_mksocialcomment_newComment_answer_cancelButton').show();
    },

    /**
     * @return {undefined}
     */
    submitNewComment: function (form) {
        var self = this;
        if (!this.commentSubmitted) {
            this.commentSubmitted = true;
            form = jQuery(form);
            var targetClassName = form.data('target-name');
            var targetUid = form.data('target-uid');

            baseUrlWithParamConnector = this.getBaseUrlWithParamConnector();

            this.startAjaxRequest(form);

            jQuery.ajax({
                url: baseUrlWithParamConnector,
                type: "POST",
                dataType: "json",
                data: form.serialize() + "&type=1296543578",
                success: function (data) {
                    self.endAjaxRequest(form);
                    var formId = '#' + form.attr('id');
                    if (data.content) {
                        jQuery(formId).replaceWith(jQuery('<div>').html($(data.content)).find(formId).prop('outerHTML'))
                    }
                    if (data.metaInformation && data.metaInformation.success == "1") {
                        self.newCommentSuccessCallback(targetClassName, targetUid);
                    }
                    if (jQuery(formId).parents('.answer-form')) {
                        self.adjustFormForAnswer(jQuery(formId).parents('.answer-form').data('comment'));
                    }
                },
                complete: function() {
                    self.commentSubmitted = false;
                },
            });
        }
    },

    /**
     * @return {undefined}
     */
    newCommentSuccessCallback: function (targetClassName, targetUid){
        if (jQuery('.answer-form form').data('approval') == 'needsApproval') {
            jQuery('.answer-form form *').not('.alert').hide();
        } else {
            this.refreshCommentList(this.getBaseUrlWithParamConnector());
        }
    },

    /**
     * @param Object button
     * @return {undefined}
     */
    startAjaxRequest: function(form) {
        var button = form.find('input[type="submit"]');
        button.prop('disabled', 'disabled');
        button.addClass('disabled');
        form.find('.tx_mksocialcomment_newComment_ajaxloader_content').show();
    },

    /**
     * @param Object button
     * @return {undefined}
     */
    endAjaxRequest: function(form) {
        var button = form.find('input[type="submit"]');
        button.removeAttr('disabled');
        button.removeClass('disabled');
        form.find('.tx_mksocialcomment_newComment_ajaxloader_content').hide();
    },

    /**
     * @return {undefined}
     */
    refreshCommentList: function(url){
        var self = this;
        jQuery('.answer-form').hide();
        commentsListSelector = 'div.tx_mksocialcomment_listComments';
        commentsList = jQuery(commentsListSelector);
        commentsList.find('.tx_mksocialcomment_listComment_ajaxloader_content').show();
        jQuery.ajax({
            url : url,
            type: "POST",
            dataType: "json",
            data: {
                "type": "1296543578",
                "mksocialcomment": {"do": "listComments"}
            },
            complete: function() {
                commentsList.find('.tx_mksocialcomment_listComment_ajaxloader_content').hide();
            },
            success: function(data){
                if(data.content){
                    commentsList.replaceWith(jQuery('<div>').html($(data.content)).find(commentsListSelector).prop('outerHTML'));
                }

                self.refreshCommentListCallback();
            }
        });
    },

    /**
     * @return {undefined}
     */
    refreshCommentListCallback: function (){
        // nothing to do at the moment. can be overwritten
    },
}

jQuery(document).ready(function(){
    MkSocialComment.initialize();
});
