<%@language = "javascript" %>
<% /*
     $Revision$
     $Id$

     Chatter.asp

     Chat dialoog zodra from en to bekend zijn
*/

%>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/iface.inc" -->
<!-- #include file="./chat.inc" -->
<!-- #include file="../Shared/flexfiles.inc" -->
<!-- #include file="../Shared/persoonselector.inc" -->

<%
    var chatReadchannelId = getQParam("chatreadid", shared.random()); // wijzelf
    var chatSendchannelId = getQParam("chatsendid"); // de ander
    var prs_key = getQParamInt("prs_key", -1); // de ander
    var dis_key = getQParamInt("dis_key", -1); // discipline
    var ins_discipline_omschrijving = get_disc_name(dis_key);
    var acceptor = getQParamInt("accept", -1); // am I the acceptor?
    var startMessage = getQParam("message", ""); // initial message
    var other = getQParam("naam", ""); // the other person
    if (prs_key > 0)
        var otherPerslid = new Perslid(prs_key);

    Application.Lock(); // wis de wanting
    var chat_queue = JSON.parse(Application(chat_queue_name) || "{}");
    if (chat_queue.wanting)
    {
        delete chat_queue.wanting[chatReadchannelId]; // we weten niet wie van de twee de wanting was
        delete chat_queue.wanting[chatSendchannelId]; // en wissen gewoon beide
    }
    Application(chat_queue_name) = JSON.stringify(chat_queue);
    Application.UnLock();

    function user_photo_icon(prs_key)
    {
        // details of a different user
        var chat_user = new Perslid(prs_key);
        var info = chat_user.photoinfo();
        var initialen = "";
        var initials;
        var classes;
        var src;
        if (info.isDefault)
        {
            var alle_namen = chat_user.naam().split(" ");
            var initialen = alle_namen[0].substring(0,1);
            if (alle_namen.length > 1)
            {
                initialen += alle_namen[alle_namen.length - 1].substring(0,1);
            }
            classes = "userphoto circle initials align-middle";
            initials = initialen.toUpperCase();
        }
        else
        {
            classes = "userphoto profile";
            src = info.photopaththumb;
        }

        var userphotoResult = '<span class="' + classes + '"{0}>{1}</span>';
        var onclick =  (prs_key > 0 ? ' onclick="iface.persoonDetails(null, null, ' + prs_key + ')"' : '');
        if (initials)
        {
            return userphotoResult.format(onclick, safe.html(initials));
        }
        else
        {
            return userphotoResult.format(onclick, '<img alt="' + safe.htmlattr(L("fac_profiel")) + " " + safe.htmlattr(L("lcl_photos")) + '" src="' + safe.htmlattr(src) + '">');
        }

    }

    FCLTHeader.Requires({plugins:["jQuery"], js: ["jquery-ui.js", "date.js", "./notify.js"]})
%>
<html>
<head>
<%
    FCLTHeader.Generate();
%>
<script>
    var chatReadchannelId = "<%=safe.jsstring(chatReadchannelId)%>"; // wijzelf
    var chatSendchannelId = "<%=safe.jsstring(chatSendchannelId)%>"; // de ander
    notify.signal(chatSendchannelId, chatReadchannelId);

    function add2chat(messages)
    {
        for (var i = 0; i < messages.length; i++)
        {
            var extraClass = messages[i].system?' system' : '';
            extraClass += messages[i].aborted?' aborted' : '';
            extraClass += messages[i].inactive?' inactive' : '';
            extraClass += messages[i].mine?' self' : ' other';
            $("#chathistory").prepend($('<span>').addClass('chatmsg'+extraClass).html(messages[i].safe_message))
                             .prepend($('<span>').addClass('chatfrom'+extraClass).text(messages[i].fromname))
                             .prepend($('<span>').addClass('chattime').text(messages[i].sincetime));
        }
        $('#chat').focus();
    }

    // === receiving ===
    function process_chat_message(data)
    {
        if (data.messages && data.messages.length)
        {
            add2chat(data.messages);
            warning_1 = false;
            warning_2 = false;
            ended = false;
        }
        check_chat_queue();
    }
    var warning_1 = false;
    var warning_2 = false;
    var ended = false;
    function get_chat_message(data)
    {
        // Haal het bericht echt op
        if (data.message) {
            $.post("ChatGet.asp?channelId=" + chatReadchannelId, process_chat_message);
        } else {
            if ("end" in data)
            {
                // session ended due to inactivity
                if (data.end == 1)
                {
                    add2chat([{safe_message: "<%=L('lcl_chat_inactive_ended')%>", sincetime: toTimeString(new Date(), true), fromname: "<%=L('lcl_chat_system')%>", inactive: true, mine: false}]);
                    $("#chat, span.sendbutton").attr('readonly', true);
                    return false; // stop polling notify
                }
                // session aborted by user
                else if (data.end == 2)
                {
                    add2chat([{safe_message: "<%=L('lcl_chat_user_ended')%>", sincetime: toTimeString(new Date(), true), fromname: "<%=L('lcl_chat_system')%>", aborted: true, mine: false}]);
                    $("#chat, span.sendbutton").attr('readonly', true);
                    return false; // stop polling notify
                }
            }
            else
            {
                var last_alive = data.last_alive;
                var ago10 = new Date(data.ts);
                var ago14 = new Date(data.ts);
                var ago15 = new Date(data.ts);
                ago10.setMinutes(ago10.getMinutes() - 10);
                ago14.setMinutes(ago14.getMinutes() - 14);
                ago15.setMinutes(ago15.getMinutes() - 15);
                if (!ended && last_alive < ago15.getTime())
                {
                    add2chat([{safe_message: "<%=L("lcl_chat_ended")%>", sincetime: toTimeString(new Date(), true), fromname: "<%=L('lcl_chat_system')%>", inactive: true, system: true, mine: false}]);
                    $("#chat, span.sendbutton").attr('readonly', true);
                    notify.end(chatSendchannelId, chatReadchannelId, 1); // session ended due to inactivity
                    ended = true;
                    return false;
                } else if (!warning_2 && last_alive < ago14.getTime())
                {
                    add2chat([{safe_message: "<%=L("lcl_chat_inactive_warning_2")%>", sincetime: toTimeString(new Date(), true), fromname: "<%=L('lcl_chat_system')%>", system: true, mine: false}]);
                    warning_2 = true;
                } else if (!warning_1 && last_alive < ago10.getTime())
                {
                    add2chat([{safe_message: "<%=L("lcl_chat_inactive_warning_1")%>", sincetime: toTimeString(new Date(), true), fromname: "<%=L('lcl_chat_system')%>", system: true, mine: false}]);
                    warning_1 = true;
                }
            }
        }
        return true;
    }
    function check_chat_queue() // Zijn er berichten voor mij?
    {
        notify.wait(chatReadchannelId, chatSendchannelId, get_chat_message);
    }
    $(check_chat_queue); // start de check-loop

    // === sending ===
    function process_chat_send(data)
    {
        warning_1 = false;
        warning_2 = false;
        ended = false;
        notify.signal(chatSendchannelId, chatReadchannelId); // Signal new message
    }
    function chat_send()
    {
        var msg = $("textarea#chat").val();
        if (msg) {
            $("textarea#chat").val("");
            $.post("../Shared/get_shared_info.asp", {
                req_info: "eval_bb_code",
                fcltlinks: 1,
                input: msg
            }, function (json) {
                add2chat([{ safe_message: json.fclthtml, sincetime: toTimeString(new Date(), true), fromname: "<%=L('lcl_chat_selfname')%>", mine: true }]);
                chat_dosend(msg);
            });
        }
    }
    function chat_dosend(msg)
    {
        $.post( "./ChatSend.asp",
            {
                fromchannelId: chatReadchannelId,
                channelId: chatSendchannelId,
                message: msg,
                acceptor: (<%=acceptor%> > 0 ? "1" : "0")
            },
            process_chat_send);
    }
    function unloadHandler()
    {
        notify.end(chatSendchannelId, chatReadchannelId, 2); // Session aborted by user
    }
    $(process_chat_send); // activeert de andere kant
    $(get_chat_message); // Misschien staat er al eentje te wachten (welkomsbericht)

    $(function () {
        FcltMgr.startEdit(window); // hot tab
        add2chat([{safe_message: L("lcl_chat_initialmsg"), sincetime: toTimeString(new Date(), true), fromname: "<%=(prs_key > 0 ? L('lcl_chat_selfname') : L('lcl_chatter_naam'))%>", mine: <%=prs_key > 0 ? "true" : "false"%> }]);
        add2chat([{safe_message: "<%=safe.jsstring(safe.fclthtml(startMessage, { "fcltlinks": true }))%>", sincetime: toTimeString(new Date(), true), fromname: "<%=safe.jsstring(prs_key > 0 ? other : L('lcl_chat_selfname'))%>", mine: <%=prs_key > 0 ? "false" : "true"%> }]);
        $("#chat").on("keydown", function(event) {
            if (event.keyCode == 13 && !event.shiftKey) {
                event.preventDefault();
                chat_send();
            }
        });
    });
</script>
</head>
<body class="chatbody">
<% PAGE_START(); %>
    <%BLOCK_START("chat", (prs_key > 0 ? L("lcl_chatter_incoming") : L("lcl_chatter_outgoing")).format(ins_discipline_omschrijving), { ishtmlsafe1: true, html: (prs_key > 0 ? user_photo_icon(prs_key) : ""), icon: (prs_key < 0 ? "fa-user-headset" : ""), center: true });%>
<!--Debug: reading channel <%=safe.html(chatReadchannelId)%><br>sending channel <%=safe.html(chatSendchannelId)%>-->
<div id="chatinput" class="chatinput">
    <div class="text-wrapper">
        <textarea id="chat" class="fldtxt" placeholder="<%=L("lcl_chat_entermessage")%>"></textarea>
        <span class="sendbutton" onclick="chat_send()" title="<%=safe.htmlattr(L("lcl_chat_send"))%>"><%=I("fa-paper-plane fa-lg")%></span>
    </div>

<div id="chathistory" class="chathistory"></div>
    <%BLOCK_END();%>
<% PAGE_END(); %>
</body>
</html>
<% ASPPAGE_END(); %>
