/***
	 * search a value in an array and return the index
	 */	
function ArraySearch(str, tab) {
    for(var i = 0; (i < tab.length); i++) {
        if (tab[i] == str)
            return i;
    }
    return false;
}	
	
/***
	 * Function used to have always 1 chatbox open maximum
	 */
function toggleChat(box_id, toggle) {
    var toggle = toggle || false;
		
    $(".chatbox:not(#"+box_id+") > div.chatboxcontent").hide();
    $(".chatbox:not(#"+box_id+") > div.chatboxinput").hide();
    if (!toggle) {
        $("#"+box_id+" > div.chatboxcontent").toggle();
        $("#"+box_id+" > div.chatboxinput").toggle();
    }
}

/***
	 * Write a notification in the chatbox
	 */
function writeNotification(message, selector) {
    chatboxcontent = $("#" + selector).children()[1];
    chatboxmessage =  $('<div>').attr({
        'class' : 'chatboxmessage'
    }).appendTo(chatboxcontent);
    $('<span>').attr({
        'class' : 'chatboxinfo'
    }).text(message).appendTo(chatboxmessage);
    //Scroll down the chat content
    $("#" + selector + " > div.chatboxcontent").scrollTop( getBoxContentHeight( $("#" + selector + " > div.chatboxcontent > div.chatboxmessage") ) );
}

/***
	 * Write message in the chatbox
	 */
function writeMessage(message, senderNickname, selector){
    var oDate = new Date();

    chatboxcontent = $("#" + selector).children()[1];
    chatboxmessage =  $('<div>').attr({
        'class' : 'chatboxmessage'
    }).appendTo(chatboxcontent);
    $('<span>').attr({
        'class' : 'chatboxinfo'
    }).text(dateFormat('d/m/Y H:i', oDate)).appendTo(chatboxmessage);
    chatboxmessage =  $('<div>').attr({
        'class' : 'chatboxmessage'
    }).appendTo(chatboxcontent);
    $('<span>').attr({
        'class' : 'chatboxmessagefrom'
    }).text(senderNickname.replace(/(_)+/g, ' ')+':  ').appendTo(chatboxmessage);
    $('<span>').attr( {
        'class' : 'chatboxmessagecontent'
    }).text(unescape(message)).appendTo(chatboxmessage);

    //Scroll down the chat content
    $("#" + selector + " > div.chatboxcontent").scrollTop( getBoxContentHeight( $("#" + selector + " > div.chatboxcontent > div.chatboxmessage") ) );
}

/***
	 *  Creation of a chatbox
	 */
function createChatbox(username, hide) {
    var position = 10;
    var box_id = username.replace(/( )+/g, "_");
    var chatboxes = $('.chatbox');
    var target = $('#'+box_id);
           
    position = position + (chatboxes.length * 225);
             
    if (target.length == 0) {
        chatbox =  $('<div>').attr({
            'id' : box_id,
            'class': 'chatbox',
            'style': 'bottom: 0px; right: '+position+'px; display: block;'
            }).appendTo($(document.body));

        chatboxhead =  $('<div>').attr({
            'class': 'chatboxhead',
            'style': 'cursor: pointer;',
            'onClick' : 'toggleChat("'+box_id+'")'
            }).appendTo(chatbox);
        chatboxtitle =  $('<div>').attr({
            'class': 'chatboxtitle'
        }).text(username).appendTo(chatboxhead);
        chatboxoptions =  $('<div>').attr({
            'class': 'chatboxoptions'
        }).appendTo(chatboxhead);
        chatboxoptionsclose =  $('<a>').attr({
            'onClick' : 'chat.closeChat("'+box_id+'")'
            }).text("X").appendTo(chatboxoptions);
        $('<br />').attr({
            'clear': 'all'
        }).appendTo(chatboxhead);

        chatboxcontent =  $('<div>').attr({
            'class': 'chatboxcontent'
        }).appendTo(chatbox);

        chatboxinput = $('<div>').attr({
            'class': 'chatboxinput'
        }).appendTo(chatbox);
        chatboxtextarea = $('<textarea>').attr({
            'class': 'chatboxtextarea',
            'style': 'height: 44px;',
            'onKeydown' : "event.keyCode == 13 ? chat.postMessage(this, '"+box_id+"') : false;",
            'onKeyup' : "event.keyCode == 13 ? this.value = '' : false;"
        }).appendTo(chatboxinput);
        if (hide){
            $(chatboxcontent).hide();
            $(chatboxinput).hide();
        }
        else
            toggleChat(box_id, true);
    }
    else
        toggleChat(box_id);
    $("#" + box_id).children()[2].children[0].focus();
}

/***
	 * return the height total of a chatbox for auto scrolling
	 */
function getBoxContentHeight(content) {
    var height = 0;

    for (var i = 0; i < content.length; i++) {
        height += $(content[i]).height();
    }
    return height;
}


function dateFormat(format, date) {
    if (date == undefined) {
        date = new Date();
    }
    if (typeof date == 'number') {
        time = new Date();
        time.setTime(date);
        date = time;
    } else if (typeof date == 'string') {
        date = new Date(date);
    }
    var fullYear = date.getYear();
    if (fullYear < 1000) {
        fullYear = fullYear + 1900;
    }
    var hour = date.getHours();
    var day = date.getDate();
    var month = date.getMonth() + 1;
    var minute = date.getMinutes();
    var seconde = date.getSeconds();
    var milliSeconde = date.getMilliseconds();
    var reg = new RegExp('(d|m|Y|H|i|s)', 'g');
    var replacement = new Array();
    replacement['d'] = day < 10 ? '0' + day : day;
    replacement['m'] = month < 10 ? '0' + month : month;
    replacement['Y'] = fullYear;
    replacement['Y'] = fullYear;
    replacement['H'] = hour < 10 ? '0' + hour : hour;
    replacement['i'] = minute < 10 ? '0' + minute : minute;
    replacement['s'] = seconde < 10 ? '0' + seconde : seconde;
    return format.replace(reg, function($0) {
        return ($0 in replacement) ? replacement[$0] : $0.slice(1,
            $0.length - 1);
    });
}



function isset(variable){
    var bool = variable || 0;

    if ( bool ) {
        return true;
    }
    else {
        return false;
    }
}

function Chatbox(nickname){
    var ape;
    var userlist;

    // we call this function once APE has finished loading
    this.initialize = function(ape_core){
        this.nickname = nickname;
        ape = ape_core;

        //Chat request link
        $('#chat-request').bind('click', this.chatRequest);

        //when a page is unload
        $(window).unload(this.makeSession);

        //Restore chatboxes
        ape.addEvent('restoreEnd', this.restoreChatboxes);
                
        //when a user joins, update the user list
        ape.addEvent('userJoin', function(){
            ape.request.send('list');
        });

        //when a user leaves, update the user list
        ape.addEvent('userLeft',  function(){
            ape.request.send('list');
        });

        //Catch message reception
        ape.onRaw('data', this.rawData);

        //Catch message sending
        ape.onCmd('send', this.cmdSend);

        //Catch userlist from server to client
        ape.onRaw('userlist', this.updateList);

        this.start();
    }

    /***
	 * Connection to APE server when client is loaded
	 */
    this.start = function() {
        if(!ape.options.restore){
            var nickname = this.nickname.replace(/( )+/g, "_");
        }else{
            var nickname = null;
        }
        //Call start method from core to start connection to APE server
        ape.start({
            'name': nickname
        });
    }

    /***
	 * Restore chatboxes saved in session when a page is loaded
	 */
    this.restoreChatboxes = function() {

        ape.getSession('activeChats', function(resp) {
            var chats = eval( decodeURIComponent(resp.data.sessions.activeChats) );
            if (isset(chats)) {
                for(var i= 0; i < chats.length; i++) {
                    createChatbox(chats[i][0].replace(/(_)+/g, " "), false);
                    $('#'+chats[i][0]+" > div.chatboxcontent" ).append(chats[i][1]);
                    $("#" + chats[i][0] + " > div.chatboxcontent").scrollTop( getBoxContentHeight( $("#" + chats[i][0] + " > div.chatboxcontent > div.chatboxmessage") ) );
                }
            }
        });
    }

    /***
	 * Save in session current chatboxes when page is unload
	 */
    this.makeSession = function() {
        var chatboxes = $('.chatbox');
        var savechat = new Array();

        if(isset(chatboxes)) {
            chatboxes.each(function(i) {
                var chatboxcontent = $(chatboxes[i]).children()[1];
                var temp = [$(chatboxes[i]).attr('id'), $(chatboxcontent).html()];
		
                savechat.push(temp);
            });
        }
        ape.setSession({
            'activeChats': JSON.stringify(savechat)
            });
    }

    /***
	 * Create chatbox when 'Chat with' is clicked
	 */
    this.chatRequest = function(link) {
             
        var username = link.currentTarget.name;
	
        createChatbox(username, false);
    }

    /***
	 * Update Userlist
	 */
    this.updateList= function(params){
        userlist = params.data.userlist;
    }

    /***
	 * Destroy a chatbox
	 */
    this.closeChat = function(box_id) {
        $('#'+box_id).detach();
    }

    /***
	 * Intercept send command and write a message
	 */
    this.cmdSend = function(param,pipe) {
        writeMessage(param.msg, ape.user.properties.name, pipe.properties.name);
    }

    /***
	 * Intercept raw command and write a message
	 */
    this.rawData = function(raw, pipe){
        if (ape.user.properties.name != raw.data.from.properties.name) {
            if ($('#'+raw.data.from.properties.name).length != 1){
                createChatbox(raw.data.from.properties.name.replace(/(_)+/g, " "), true);
            }
            writeMessage(unescape(raw.data.msg), raw.data.from.properties.name, raw.data.from.properties.name);
        }
        else {
            if ($('#'+pipe.properties.name).length != 1){
                createChatbox(pipe.properties.name.replace(/(_)+/g, " "), true);
            }
            writeMessage(unescape(raw.data.msg), raw.data.from.properties.name, pipe.properties.name);
        }
    }

    /***
	 * Get user pubid with nickname, return false if user not connected
	 */
    this.getUserPubid =  function(nickname){
        var pubid = false;
        if (isset(userlist)) {
            userlist.each( function(user) {
                if (user[0] == nickname){
                    pubid = user[1];
                    return pubid;
                }
            });
        }
        return pubid;
    }
		
    /***
	 * Send Message
	 */
    this.postMessage = function(textarea, username){
        //get input value
        var msg = escape(textarea.value);

        //clean message from spaces
        msg = msg.trim();
                
        var cmd = msg.split(" ");

        if (cmd[0] == "list"){
            ape.request.send('list');
            console.log(userlist);
            textarea.value = "";
        }
        //If message not empty, send message
        else if(msg!=''){
            var pubid = this.getUserPubid(username);

            //If pubid is defined user is online => send message
            if (isset(pubid))
                ape.getPipe(pubid).send(msg);
            else
                writeNotification("Resident offline", username);
            //input clean
            textarea.value = "";
        }
    }
}


