$(function () {

    Prolific.module('messaging', function () {
        var curClass = '',
            $container = $('<div id="message"><h2></h2><p></p><a href="javascript:void(0)" class="button ok">OK</a></div>'),
            $title = $('h2', $container),
            $text = $('p', $container),
            $ok = $('a', $container),
            hideTimeout;

        function notify (type, text, callback, timeout) {
            setType(type);
            setTitle(type);
            setText(text);
            show(callback);

            if (typeof timeout === 'number') {
                hideTimeout = window.setTimeout(hide, Math.ceil(timeout));
            }

            return this;
        }

        function setTitle (title) {
            $title.text(title || '');
            return this;
        }

        function setText (text) {
            $text.text(text || '');
            return this;
        }

        function setType (type) {
            type = type.toLowerCase();
            $container
                .removeClass(curClass)
                .addClass(type || '');
            curClass = type || '';
            return this;
        }

        function show (callback) {
            $container
                .css('left', '50%')
                .fadeIn(300, callback);
            return this;
        }

        function hide (callback) {
            $container
                .fadeOut(200, function () {
                    $container.css('left', '-9999px');
                    if (typeof callback === 'function') {
                        callback();
                    }
                });
            window.clearTimeout(hideTimeout);
            return this;
        }

        return {
            notify: notify,
            setTitle: setTitle,
            setText: setText,
            setType: setType,
            show: show,
            hide: hide,
            init: function () {
                $container
                    .click(function () {
                        return false;
                    })
                    .fadeOut(0)
                    .appendTo('body');
                $ok
                    .click(function () {
                        hide();
                        return false;
                    });
                $('body')
                    .click(function () {
                        hide();
                    });
                    
                $container.ajaxError(function () {
                    notify('Error', 'There\'s been an error during your request.', null, 2500);
                });

            }()
        };
    });

});