/**
 * Class for ShoutOK:
 * @auther: Orhan Keskin
 *
 * Persistence: DB
 *
 * In order to run this Shoutbox you will need the following Javascript libraries:
 * - JQuery.js
 * - Date.js
 *
 * Custom Styling can be performed in the file shoutok.css
 * 
 */
function ShoutOK()
{
    var width = 600;
    var messageContainerHeight = 300;
    var qualifier = "default";

    // check periodically if new data is available: -> input is in ms:
    var refreshRateInMs = 10000;

    var title = "ShoutOK - the simple Shoutbox";
    var msgCacheSize = 40;
    var text = 'no entries so far!';
    var shoutbox = "";
    var intervall = "";

    // initialize the shoutbox:
    function initialize(the_qualifier, the_title, the_CacheSize)
    {
        qualifier = the_qualifier;
        title = the_title;
        msgCacheSize = the_CacheSize;

        // create the shoutbox:
        shoutbox = "<div id='sb_mainContainerID' class='sb_container' style='width: "+width+"px'>";
        shoutbox += "<div class='sb_headerBox'>";
        shoutbox += "<div style='float:left'>"+title+"</div>";
        shoutbox += "<div style='float:right' id='loading'></div>";
        shoutbox += "</div>";
        shoutbox += "<div id='upper_scrollbar' onclick=\"ShoutOK.prototype.scrollMessageContainer('sb_messageContainer', -1);\">";
        shoutbox += "<div id='upper_button'></div>";
        shoutbox += "</div>";
        shoutbox += "<div id='sb_messageContainer' style='height: "+messageContainerHeight+"px'>";
        shoutbox += "</div>";
        shoutbox += "<div id='lower_scrollbar' onclick=\"ShoutOK.prototype.scrollMessageContainer('sb_messageContainer', 1);\">";
        shoutbox += "<div id='lower_button'></div>";
        shoutbox += "</div>";
        shoutbox += "<div class='sb_footerBox'>";
        shoutbox += "<div style='float: left'><input onblur=\"ShoutOK.prototype.resetInput(this.id, this.value, 'Nickname');\" onfocus=\"ShoutOK.prototype.clearInput(this.id, this.value, 'Nickname');\" style='width:105px; font-size:11px; color: #B3B3B3' class='sb_input' " +
                    "type='text' id='sb_uid' maxlength='25'' accesskey='N' value='Nickname'/></div>";
        shoutbox += "<div style='float: left'><input onblur=\"ShoutOK.prototype.resetInput(this.id, this.value, 'your message');\" onfocus=\"ShoutOK.prototype.clearInput(this.id, this.value, 'your message');\" style='width:200px; font-size:11px; color: #B3B3B3' class='sb_input' " +
                    "type='text' id='sb_msg_input' maxlength='250' accesskey='M' value='your message'/></div>";

        shoutbox += "<div style='float: left; margin-left: 5px;'>";
        shoutbox += "<div id='sendButton' onclick=\"ShoutOK.prototype.addMessage();\"></div>";
        //shoutbox += "<input type='button' name='send' value='Send' onclick=\"ShoutOK.prototype.addMessage();\">";
        shoutbox += "</div>";

        shoutbox += "<div style='clear: left'/>";
        shoutbox += "</div>";
        shoutbox += "</div>";

        // Refresh the shoutbox from time to time in order to get the latest messages without reload:
        clearInterval(intervall);
        intervall = setInterval(ShoutOK.prototype.refresh, refreshRateInMs);
    }

    // display the shoutbox:
    function display(container)
    {
        // code for display method goes here
        $("#"+container).html(shoutbox);
        
        // initialize message box:
        ShoutOK.prototype.initMessageBox(msgCacheSize);
    }

    // referesh and get the latest messages:
    ShoutOK.prototype.refresh = function()
    {
        // get the currently latest entry in the shoutbox:
        var msgID_label = $("#sb_messageContainer div:first-child").attr("id");
        if(msgID_label != false && msgID_label != undefined)
            var latest_MsgID = msgID_label.split("_")[1]; 

        //alert("First ID = "+latest_MsgID);
        $.post("shoutbox/shoutok/refresh", { action: 'refresh', qualifier: qualifier, msgID: latest_MsgID},
        function(data)
        {
           if(data.status_code == "LOAD_SUCCESS")
           {
               var latest_messages = data.latest_msgs;
               for(i = 0; i<latest_messages.length; i++)
               {
                   var id = latest_messages[i].id;
                   var uid = latest_messages[i].user;
                   var msg_input = latest_messages[i].message;
                   var the_timestamp = latest_messages[i].datetime;

                   var message = "<div id=msg_"+id+" class='postbox'>";
                   message += "<div style='float:left'>";
                   message += "<b>"+uid+"</b>: "+msg_input;
                   message += "</div>";
                   message += "<div style='float:right; color: #B3B3B3; font-size: 10px'>";
                   message += the_timestamp;
                   message += "</div>";
                   message += "</div>";

                   // add new message at top:
                   $("#sb_messageContainer").prepend(message);
               }
               return true;

           }
           else if(data.status_code == "LOAD_EMPTY")
           {
               return false;
           }
        }, "json");                
    }

    // add a new message:
    ShoutOK.prototype.addMessage = function()
    {
        var uid = $("#sb_uid").val();
        var msg_input = $("#sb_msg_input").val();        

        if(uid != "" && uid != undefined && msg_input != "" && msg_input != undefined &&
                uid != "Nickname" && msg_input != "your message")
        {
            // first of all scroll to top!
            $("#sb_messageContainer").animate({scrollTop: 0}, 200);

            var jetzt = new Date();
            var the_timestamp = jetzt.format('Y-m-d H:i:s');
            var show_timestamp = jetzt.format('d.m.Y H:i:s'); 

            // send the message to storage:
            var testColor = "blue";
            ShoutOK.prototype.persistMessage(qualifier, uid, testColor, msg_input, the_timestamp, show_timestamp );
        }
    }

    // initialize messages for the current qualifier:
    ShoutOK.prototype.initMessageBox = function(msgCacheSize)
    {
        // show load icon:
        var pic = "<img id='loadIcon' src='media/images/ajax_load.gif'/>";
        $("#loading").ajaxStart(function(){$("#loading").html(pic);});
        $("#loading").ajaxStop(function(){$("#loadIcon").remove();});

        // post Ajax request:
        $.post("shoutbox/shoutok/init", { action: 'init', qualifier: qualifier, cacheSize: msgCacheSize},
        function(data)
        {
            if(data.status_code == "INIT_SUCCESS")
            {
                // get the messages:
                var messages = data.messages;
                for(i = 0; i<messages.length; i++)
                {
                    var id = messages[i].id;
                    var uid = messages[i].user;
                    var msg_input = messages[i].message; 
                    var the_timestamp = messages[i].datetime; 

                    var message = "<div id=msg_"+id+" class='postbox'>";
                    message += "<div style='float:left'>";
                    message += "<b>"+uid+"</b>: "+msg_input;
                    message += "</div>";
                    message += "<div style='float:right; color: #B3B3B3; font-size: 10px'>";
                    message += the_timestamp;
                    message += "</div>";
                    message += "</div>";

                    // add new message at top:
                    $("#sb_messageContainer").prepend(message);
                    $("#msg_"+id).hide().fadeIn("slow");                   
                }
                return true;
            }
            else if(data.status_code == "INIT_FAILURE")
            {
                return false;
            }
        }, "json");
    }

    // persist the given message:
    ShoutOK.prototype.persistMessage = function(qualifier, user, color, msg, datetime, show_timestamp)
    {
        // show load icon:
        var pic = "<img id='loadIcon' src='media/images/ajax_load.gif'/>";
        $("#loading").ajaxStart(function(){$("#loading").html(pic);});
        $("#loading").ajaxStop(function(){$("#loadIcon").remove();});

        // post Ajax request:
        $.post("shoutbox/shoutok/addMsg", { action: 'addMsg', cacheSize: msgCacheSize, qualifier: qualifier, user: user, user_color: color, message: msg, datetime: datetime},
        function(data)
        {
            if(data.status_code == "ADD_SUCCESS")
            {
                // first remove exceeded messages:
                var rids = data.removedIDs;
                if(rids != null && rids != "" && rids != undefined)
                {
                    var ridsArray = rids.split(",");

                    for(i = 0; i<ridsArray.length; i++)
                    {
                        var current_mid = "msg_"+ridsArray[i];
                        $("#"+current_mid).remove();
                    }
                }

                var message = "<div id=msg_"+data.lastInsertedId+" class='postbox'>";
                message += "<div style='float:left'>";
                message += "<b>"+data.user+"</b>: "+data.msg;
                message += "</div>";
                message += "<div style='float:right; color: #B3B3B3; font-size: 10px'>";
                message += show_timestamp;
                message += "</div>";
                message += "</div>";

                // add new message at top:
                $("#sb_messageContainer").prepend(message);
                $("#msg_"+data.lastInsertedId).hide().fadeIn("slow");
                $("#sb_msg_input").val("").focus();
            }
            else if(data.status_code == "ADD_FAILURE")
            {
                alert("something gone wrong while trying to persist the message!");                
            }
        }, "json");
    }

    // scroll messageContainer:
    ShoutOK.prototype.scrollMessageContainer = function(mc_id, direction)
    {
        // Scroll Height = aktuelle Scroll hoehe
        // Scroll Top = aktuelle Ueberlauf

        var currentScrollHeight = $("#"+mc_id).attr("scrollHeight");
        var scrollTop = $("#"+mc_id).attr("scrollTop");

        // Scroll:
        if(direction == 1)
        {
            var newScrollTop = scrollTop + 100;
            $("#"+mc_id).animate({scrollTop: newScrollTop}, 200);
            scrollTop = newScrollTop;
        }
        if(direction == -1)
        {
            var newScrollTop = scrollTop - 100;
            $("#"+mc_id).animate({scrollTop: newScrollTop}, 200);
            scrollTop = newScrollTop;
        }
    }


    // clear input field if necessary:
    ShoutOK.prototype.clearInput = function(id, value, template)
    {
        if(value == template)
        {
            $("#"+id).val("");
            $("#"+id).css("color","black");
        }
    }

    ShoutOK.prototype.resetInput = function(id, value, template)
    {
        if(value == "" || value == undefined)
        {
            $("#"+id).val(template);
            $("#"+id).css("color","#B3B3B3");            
        }
    }

   // initialize the shoutbox:
    ShoutOK.prototype.initialize = initialize;

    // display the shoutbox:
    ShoutOK.prototype.display = display;
};

// Implementing Singleton pattern: -> this is need in order to run periodically setIntervall only once:
// Otherwise the setIntervall will be calles each time the class will be instantiated:
ShoutOK.instance = null;

// Singleton:
ShoutOK.getInstance = function()
{
    if (ShoutOK.instance == null)
    {
        ShoutOK.instance = new ShoutOK();
    }
    return ShoutOK.instance;
}

