/**
 * Chat object used to chat to other user(s) through a remote server
 */
function Chat(varName,interval) {
    this.varName = varName;
    this.userId  = -1;
    this.channel = -1;
    this.chatUrl = '/ajax.php';
    this.messages = [];
    this.placeholderId = '#chatlocation';
    this.getMessageInterval = interval;
    setInterval(this.varName+".getMessages()", this.getMessageInterval);
}

/**
 * Sets the Chat's userid
 */
Chat.prototype.setUserId = function(userId) {
    this.userId = userId;
}

/**
 * Creates a new Chat Channel on the server
 */
Chat.prototype.createChannel=function() {
    var channel;
    $.ajax({
        type: 'POST',
        url: this.chatUrl,
        data: "ajaxModule=chat&ajaxFunction=createChannel&userId="+this.userId,
        success: function (data) {
            channel = data;
        },
        async: false,
        dataType: 'json'
    });
    this.channel = channel;
    return channel;
}

/**
 * Retrieves the logged in userId from the server
 */
Chat.prototype.getUserId=function() {
    var userId;
    $.ajax({
        type: 'POST',
        url: this.chatUrl,
        data: "ajaxModule=chat&ajaxFunction=getUserId",
        success: function (data) {
            userId = data;
        },
        async: false,
        dataType: 'json'
    });
    this.userId = userId;
    return userId;
}

/**
 * Retrieves a Channel JSON Object from the server
 *
 * @number the Channel Number
 */
Chat.prototype.getChannel=function(number) {
    this.clearMessages();
    var channel;
    $.ajax({
        type: 'POST',
        url: this.chatUrl,
        data: "ajaxModule=chat&ajaxFunction=getChannel&channelId="+number,
        success: function (data) {
            channel = data;
        },
        async: false,
        dataType: 'json'
    });
    this.channel = channel;
    return channel;
}

/**
 * Locates the last MessageId retrieved from the server
 */
Chat.prototype.getLastMessageId=function() {
    var lastMessageId = 0;
    for (var i in this.messages) {
        if (this.messages[i].id > lastMessageId) lastMessageId = this.messages[i].id;
    }
    return lastMessageId;
}

/**
 * Retrieves messages from the server, uses getLastMessageId() to get the messageId
 *  retrieved
 *
 */
Chat.prototype.getMessages=function() {
    if (this.channel === -1) return false;
    var chatObject = this;
    $.ajax({
        type: 'POST',
        url: this.chatUrl,
        data: "ajaxModule=chat&ajaxFunction=getMessages&channelId="+this.channel.id+"&lastMessageId="+this.getLastMessageId(),
        success: function (data) {
            chatObject.addNewMessages(data);
        },
        async: true,
        dataType: 'json'
    });
    return false;
}

/**
 * Clears all Messages from the Message History
 */
Chat.prototype.clearMessages=function() {
    this.messages = [];
}

/**
 * Adds new Messages to the History box
 *
 * @newMessages Message[] Array of Message objects
 *
 */
Chat.prototype.addNewMessages=function(newMessages) {
    for (var i in newMessages) {
        this.addNewMessage(newMessages[i]);
    }
}

/**
 * Retrieve the messageContent from the server and place it within in the
 *  chatHistory
 *  
 *  @newMessage Message message JSON Object
 */
Chat.prototype.addNewMessage=function(newMessage) {
    this.messages.push(newMessage);
    var history = $(this.placeholderId).find("div[name=chatHistory]");

    $.ajax({
        type: 'POST',
        url: this.chatUrl,
        data: "ajaxModule=chat&ajaxFunction=showChatMessage&messageId="+newMessage.id,
        success: function (data) {
            history.find("table").append(data)
            history.prop({
                scrollTop: history.prop("scrollHeight")
            });
        },
        async: false
    });
}

/**
 * Retrieves the chat element from the server and put it within the placeholder
 *
 */
Chat.prototype.showChat=function() {
    var placeholder = this.placeholderId;
    $.ajax({
        type: 'POST',
        url: this.chatUrl,
        data: "ajaxModule=chat&ajaxFunction=showChat&channelId="+this.channel.id+"&varName="+this.varName,
        success: function (data) {
            $(placeholder).html(data);
        },
        async: false
    });
}

/**
 * Sets the id of the placeholder
 * @placeholderId string the id of the placeholder element 
 *  (a # must be put before this string)
 */
Chat.prototype.setPlaceholderId=function(placeholderId) {
    this.placeholderId = placeholderId;
}

/**
 * Post a message
 *
 * @messageContainerId string the Id of the element that containes the message
 *  (a # must be put before this string)
 */
Chat.prototype.postMessage=function(messageContainerId) {
    var result;
    var container = $(messageContainerId);
    var messageData = container.val();
    if (messageData == '') return false;
    container.val('');
    container.focus();
    messageData = escape(messageData);
    $.ajax({
        type: 'POST',
        url: this.chatUrl,
        data: "ajaxModule=chat&ajaxFunction=postMessage&userId="+this.userId+"&channelId="+this.channel.id+"&messageData="+messageData,
        success: function (data) {
            result = data;
        },
        async: true
    });
    return result;
}

/**
 * Post a message
 *
 * @messageContainerId string the Id of the element that containes the message
 *  (a # must be put before this string)
 */
Chat.prototype.postCommand=function(command) {
    var result;
    if (command == '') return false;
    $.ajax({
        type: 'POST',
        url: this.chatUrl,
        data: "ajaxModule=chat&ajaxFunction=postCommand&userId="+this.userId+"&channelId="+this.channel.id+"&commandData="+command,
        success: function (data) {
            result = data;
        },
        async: true
    });
    return result;
}


/**
 * Start the chat
 *
 * @placeholderId string the Id of the placeholder (add a # before this string)
 * @channelId string the Id of the channel, if undefined it creates a new channel
 *
 */
Chat.prototype.startChat=function(placeholderId,channelId) {
    $(window).unload(function() {
        this.postCommand("exit");
    });
    this.setPlaceholderId(placeholderId);
    this.getUserId();
    if (channelId === undefined) {
        this.createChannel();
    } else {
        this.getChannel(channelId);
    }
    this.showChat();
    this.postCommand("enter");
    return false;
}

/**
 * Check if the ENTER key is pressed to post the message contained in the
 *  messageContainer
 *  
 *  @messageContainer element the element that contains the message
 *    the element *MUST* have an id
 *  @e event The event generated by the onKey event
 *  
 */
Chat.prototype.checkEnterPressed=function(messageContainer,e)
{
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;

    if (keycode == 13)
    {
        this.postMessage("#"+messageContainer.id);
        return false;
    }
    else
        return true;
}

