#{extends 'main.html' /}
#{set title:'Chat room' /}

<h1>WebSocket — You are now chatting as ${user} <a href="@{Application.index()}">Leave the chat room</a></h1> 

<div id="thread">
    <script type="text/html" id="message_tmpl">
        <% if(event.type == 'message') { %>
            <div class="message <%= event.user == '${user}' ? 'you' : '' %>">
                <h2><%= event.user %></h2>
                <p>
                    <%= event.text %>
                </p>
            </div>
        <% } %>
        <% if(event.type == 'join') { %>
            <div class="message notice">
                <h2></h2>
                <p>
                    <%= event.user %> joined the room
                </p>
            </div>
        <% } %>
        <% if(event.type == 'leave') { %>
            <div class="message notice">
                <h2></h2>
                <p>
                    <%= event.user %> left the room
                </p>
            </div>
        <% } %>
        <% if(event.type == 'quit') { %>
            <div class="message important">
                <h2></h2>
                <p>
                    You are now disconnected!
                </p>
            </div>
        <% } %>
    </script>
</div>

<div id="newMessage">
    <input type="text" id="message" autocomplete="off">
    <input type="submit" value="send" id="send">
</div>

<script type="text/javascript">

    // Create a socket
    var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
    var socket = new WS('@@{WebSocket.ChatRoomSocket.join(user)}')
    
    // Display a message
    var display = function(event) {
        $('#thread').append(tmpl('message_tmpl', {event: event}));
        $('#thread').scrollTo('max')
    }
    
    // Message received on the socket
    socket.onmessage = function(event) {
        var parts = /^([^:]+):([^:]+)(:(.*))?$/.exec(event.data)
        display({
            type: parts[1],
            user: parts[2],
            text: parts[4]
        })
    }
    
    $('#send').click(function(e) {
        var message = $('#message').val()
        $('#message').val('')
        socket.send(message)
    });
    
    $('#message').keypress(function(e) {
        if(e.charCode == 13 || e.keyCode == 13) {
            $('#send').click()
            e.preventDefault()
        }
    })
    
</script>
