(function($, Lego) {

    Lego.block['b-textedit'] = function(params) {
        var text = $('.b-textedit__text',this),
            form = $('.b-textedit__form',this),
            textarea = $('.b-textedit__textarea',this),
            defvalue = text.html(),
            edit = $('.b-textedit__edit',this),
            spin = $('.b-textedit__spin',this),
            cancel = $('.b-textedit__cancel',this),

            ajaxhandler = params.ajaxhandler,
            ajaxAddData = params.ajaxAddData || {},
            requestDataType = params.requestDataType || "json";

        edit.click(function(){
            defvalue = defvalue.replace(/<br\s*\/?>/g,'\n');
            textarea.val(defvalue);
            showForm();
        })

        cancel.click(function(){
            hideForm();
        })

        form.submit(function(e){
            var newtext = textarea.val();
            if (ajaxhandler) {
                e.preventDefault();
                if (defvalue != newtext) {
                    $.ajax({
                        url: ajaxhandler,
                        data: $.extend({text:newtext}, ajaxAddData),
                        type: requestDataType=="jsonp" ? "GET" : "POST",
                        dataType: requestDataType,
                        success: successHandler
                    })
                    spin.removeClass('g-hidden');
                } else {
                    hideForm();
                }
            }
        })

        function successHandler(data) {
            defvalue = data.text;
            text.html(defvalue);
            hideForm();
        }

        function showForm() {
            text.addClass('g-hidden');
            edit.addClass('g-hidden');
            form.removeClass('g-hidden');
        }

        function hideForm() {
            text.removeClass('g-hidden');
            edit.removeClass('g-hidden');
            form.addClass('g-hidden');
            spin.addClass('g-hidden');
        }
    }

})(jQuery, window.Lego);