{% load i18n static %}
{% if not alerts %}
<!--This needs to be replaced by a simple single ajax request instead-->
<li id="tab_messages" class="dropdown">
  <p><span id="alerts"></span></p>
  <div>
    <p>
      <a id="new_messages" href="{% url "alerts" %}">{% trans "Inbox" %}
        <span id="alert_bucket" data-url="{% url "alerts.json" %}" 
        data-sound="{% static "warp.wav" %}" 
        {% comment %}Translators: Leave SOME_NUMBER intact, this is for the number of new messages{% endcomment %}
        data-trans="{% trans "(SOME_NUMBER new)" %}"></span>
      </a>
    </p>
    <p><a id="sent_messages" href="{% url "message.outbox" %}">{% trans "Outbox" %}</a></p>
    <hr/>
    <p><a href="{% url "alert.settings" %}">{% trans "Notification Settings" %}</a></p>
    <script type="text/javascript">
    $(document).ready(function() {
      var originalTitle = document.title;
      var wasAlerted = false;
      var titleTimer = null;
      var beep = null;

      var window_focus;
      $(window).focus(function() {window_focus = true;})
               .blur(function() {window_focus = false;});

      function updateAlerts(isLoading) {
        var alerts  = $('#alerts');
        var bucket  = $('#alert_bucket');

        $.getJSON( bucket.data('url'), function( data ) {
          bucket.empty();
          if(data.new == null) {
            data.new = [];
          }
          bucket.append(" " + bucket.data('trans').replace("SOME_NUMBER", data.new.length));

          if(data.new.length > 0) {
            /* Yes I have unread messages */
            if(!wasAlerted) {
              /* No I was not previously alerted */
              alerts.addClass('alert');
              if(!isLoading) {
                if(beep == null) {
                  beep = new Audio($("#alert_bucket").data('sound'));
                }
                beep.play();
                if(!window_focus) {
                  titleTimer = window.setInterval(function() {
                    document.title = document.title == originalTitle
                              ? "{% trans "New Notification!" %}" : originalTitle;
                  }, 1200);
                  $(window).on("focus",function() {
                    document.title = originalTitle;
                    clearInterval(titleTimer);
                  });
                }
              }
              wasAlerted = true;
            }
          } else {
            clearInterval(titleTimer);
            alerts.removeClass('alert');
            wasAlerted = false;
          }
        });
      }

      updateAlerts(true);
      var updater =  window.setInterval(updateAlerts, 900000)  /* 15 mins */

    });
    </script>
  </div>
</li>
{% endif %}
