{% extends "base_menu.html" %}

{% block title %} ADS {% endblock %}

{% block content %}
<h1>Ads</h1>
<div style="float:right">
<!-- https://www.w3schools.com/howto/howto_css_search_button.asp -->
<form class="d-flex">
  <input class="form-control" type="text" name="search" placeholder="Search" aria-label="Search"
  {% if search %} value="{{ search }}" {% endif %}>
  <button type="submit" class="btn btn-success mx-2"><i class="fa fa-search"></i></button>
  <button type="cancel" onclick="location.href='{% url 'ads:index' %}'; return false;" class="btn btn-danger"><i class="fa fa-undo"></i></button>
</form>
</div>
<p>
{% if ad_list %}
<ul>
  {% for ad in ad_list %}
    <li>
        <a href="{% url 'ads:ad detail'  ad.id %}">{{ ad.title }}</a>
        {% if ad.owner == user %}
        (<a href="{% url 'ads:ad update' ad.id %}">Edit</a> |
        <a href="{% url 'ads:ad delete' ad.id %}">Delete</a>)
        {% endif %}
         {% if user.is_authenticated %}
        <!-- Two hrefs with two stacked icons each - one showing and one hidden -->
        <a href="#" onclick=
            "favPost('{% url 'ads:ad unfavorite' ad.id %}', {{ ad.id }} );return false;"
            {% if ad.id not in favorites %} style="display: none;" {% endif %}
            id="favorite_star_{{ad.id}}">
        <span class="fa-stack" style="vertical-align: middle;">
        <i class="fa fa-star fa-stack-1x" style="color: orange;"></i>
        <i class="fa fa-star-o fa-stack-1x"></i>
        </span>
        </a>
        <!-- the second href -->
        <a href="#" onclick=
             "favPost('{% url 'ads:ad favorite' ad.id %}', {{ ad.id }} );return false;"
            {% if ad.id in favorites %} style="display: none;" {% endif %}
            id="unfavorite_star_{{ad.id}}">
        <span class="fa-stack" style="vertical-align: middle;">
        <i class="fa fa-star fa-stack-1x" style="display: none; color: orange;"></i>
        <i class="fa fa-star-o fa-stack-1x"></i>
        </span>
        </a>
        {% endif %}
    </li>
  {% endfor %}
</ul>
{% else %}
  <p>There are no ads in the database.</p>
{% endif %}
</p>
<p>
<a href="{% url 'ads:ad create' %}">Add an Ad</a> |
{% if user.is_authenticated %}
<a href="{% url 'logout' %}?next={% url 'ads:index' %}">Logout</a>
{% else %}
<a href="{% url 'login' %}?next={% url 'ads:index' %}">Login</a>
{% endif %}
</p>
<script>
function favPost(url, thing_id) {
    console.log('Requesting JSON');
    $.post(url, {},  function(rowz){
        console.log(url, 'finished');
        $("#unfavorite_star_"+thing_id).toggle();
        $("#favorite_star_"+thing_id).toggle();
    }).fail(function(xhr) {
        alert('Url failed with '+xhr.status+' '+url);
    });
}
</script>
{% endblock %}
