/**
 * jQuery Chatbox Plugin
 *
 * @author      Flash
 * @created     2010/02/22
 * @website     http://www.mangamasters.com/
 */

jQuery(function($){

    $.fn.chatBox = function(options) {
        var options = jQuery.extend({
            last_time:      0,
            last_id:        null,
            post_time:      null,
            user_id:        null,
            is_admin:       null,
            read_interval:  15000,
            slow_interval:  60000
        }, options);

        var o=options;
        var obj=$(this);
        
        function getMsgs(){
            $(obj).addClass('loading');
            $.ajax({
                cache: true, // Stops IE caching the msgs
                type: 'GET',
                url: '/ajax/getChatMessages',
                data: {last_time: o.last_time},
                dataType: 'json',
                success: function(data){
                    $(obj).removeClass('loading');
                    $(obj).empty(); // Clear the messages

                    $.each(data, function(i, item){
                        if (i == 0) {
                            o.last_id = item.message_id;
                            o.last_time = item.time;
                            o.post_time = item.time;
                        }

                        // Build the message string
                        $("<div>")
                            .attr({id: 'm' + item.message_id})
                            .appendTo(obj);
                        $("<div>")
                            .addClass('info')
                            .html('<em>' + item.username + '</em>, <span>' + item.date + '</span>')
                            .appendTo('#m' + item.message_id);
                        $("<div>")
                            .addClass('message')
                            .html(item.message)
                            .appendTo('#m' + item.message_id);
                        if (o.user_id == item.user_id || true == o.is_admin) {
                            $("<a>")
                                .text('Del')
                                .bind('click', function(){$(this).chatSend('delete', item.message_id);})
                                .css({cursor: 'pointer'})
                                .addClass('delMsg')
                                .appendTo('#m' + item.message_id + ' .info');
                        }
                        $("<input>")
                            .attr({
                                type: 'hidden',
                                name: 'msg_id',
                                value: item.message_id
                            })
                            .appendTo('#m' + item.message_id);
                        $("<input>")
                            .attr({
                                type: 'hidden',
                                name: 'msg_time',
                                value: item.time
                            })
                            .appendTo('#m' + item.message_id);
                        if (i % 2 == 0) {
                            $('#m' + item.message_id).addClass('row1');
                        } else {
                            $('#m' + item.message_id).addClass('row2');
                        }
                    });

                    window.clearInterval(interval);
                    interval = setInterval(function(){getMsgs();}, o.read_interval);
                },
                error: function() {
                    $(obj).removeClass('loading');

                    clearInterval(interval);
                    interval = setInterval(function(){getMsgs();}, o.slow_interval);
                }
            });
        }

        $.fn.chatSend = function(mode, f){
            param = 'mode=' + mode;
            param += '&last_id=' + o.last_id;
            param += '&last_time=' + o.last_time;
            param += '&last_post=' + o.post_time;
            param += '&read_interval=' + o.read_interval;

            if ('add' == mode && $(f).val() != '') {
                $.each(f, function(i, item){param += '&' + item.name + '=' + encodeURIComponent(item.value);});
                $(f).attr('value', '');

                $.ajax({
                    type: 'POST',
                    url: '/forum/chat.php',
                    data: param,
                    success: function() {
                        o.last_time = 0;
                        o.last_id = null;
                        o.post_time = null;

                        getMsgs(); // Refresh messages

                        clearInterval(interval);
                        interval = setInterval(function(){getMsgs();}, o.read_interval);
                    },
                    error: function(){
                        $(obj).html('Failed to get messages...');
                    }
                });
            } else if ('delete' == mode) {
                param += '&chat_id=' + f;

                $.ajax({
                    type: 'POST',
                    url: '/forum/chat.php',
                    data: param,
                    success: function() {
                        $('#m' + f).animate({opacity: 0}, 'slow', function(){
                            $(this).remove();

                            o.last_time = 0;
                            o.last_id = null;
                            o.post_time = null;

                            clearInterval(interval);
                            interval = setInterval(function(){getMsgs();}, o.read_interval);
                        })
                    }
                });
            }
        }

        getMsgs(); // First time messages get loaded
        var interval = setInterval(function(){getMsgs();}, o.read_interval);

        return this;
    }
});