{{set . "title" "Chat room"}}
{{template "header.html" .}}

<h1>Ajax, long polling — You are now chatting as {{.user}}
  <a href="/longpolling/room/leave?user={{.user}}">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>
    <% } %>
  </script>
</div>

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

<script type="text/javascript">

  var lastReceived = 0
  var waitMessages = '/longpolling/room/messages?lastReceived='
  var say = '/longpolling/room/messages?user={{.user}}'

  $('#send').click(function(e) {
    var message = $('#message').val()
    $('#message').val('')
    $.post(say, {message: message})
  });

  $('#message').keypress(function(e) {
    if(e.charCode == 13 || e.keyCode == 13) {
      $('#send').click()
      e.preventDefault()
    }
  })

  // Retrieve new messages
  var getMessages = function() {
    $.ajax({
      url: waitMessages + lastReceived,
      success: function(events) {
        $(events).each(function() {
          display(this)
          lastReceived = this.Timestamp
        })
        getMessages()
      },
      dataType: 'json'
    });
  }
  getMessages();

  // Display a message
  var display = function(event) {
    $('#thread').append(tmpl('message_tmpl', {event: event}));
    $('#thread').scrollTo('max')
  }

</script>
{{template "footer.html" .}}
