{% extends "egonomy_base.html" %}
{% load static %}
{% load i18n %}
{% load thumbnail %}
{% load egonomy_thumbnail %}

{% block title %}{% trans "Create or edit a fragment" %}{% endblock %}
{% block css_page %}
        <link rel="stylesheet" href="{% static 'egonomy/css/jquery-ui.css' %}" />
        <link rel="stylesheet" href="{% static 'egonomy/css/jquery.tagit.css' %}" />
        <link rel="stylesheet" href="{% static 'egonomy/css/tagit.ui-zendesk.css' %}" />
{% endblock %}
{% block js_import %}
{{block.super}}
        <script type="text/javascript" src="{% static 'egonomy/lib/raphael-min.js' %}"></script>
        <script type="text/javascript" src="{% static 'egonomy/js/cutout.js' %}"></script>
        <script type="text/javascript" src="{% static 'egonomy/lib/jquery-ui.min.js' %}"></script>
        <script type="text/javascript" src="{% static 'egonomy/js/tag-it.js' %}"></script>
{% endblock %}
{% block js_inline %}
{{block.super}}
        <script type="text/javascript">
            function init_sensitive_click(){
                // Init senseetive api request
                if($("#senseetive_click")){
                    $("#senseetive_click").click(function() {
                        var v = $(".fragment-path").val();
                        if(v!="" && v!="MZ" && !$("#senseetive_click").hasClass("loader")){
                            $("#senseetive_click").addClass("loader");
                            var data_obj = { "image":"{{ img.id }}", "path":$("#fragment_path").val() };
                            $.ajax({
                                url: '{% url "senseetive_api" %}',
                                data: data_obj,
                                dataType: "json",
                                success: function(data, status, request){
                                	var keywords = data["keywords"];
                                    var n = keywords.length;
                                    if(n>0){
                                    	s = '<div id="tabs" style="height: 320px;"><ul><li><a href="#tabs-1">Mots-clés</a></li><li><a href="#tabs-2">Images</a></li></ul>'
                                            + '<div id="tabs-1" style="overflow-y: scroll; overflow-x: hidden; height: 250px;">'
                                            + '<ul id="add_senseetive_tags">';
                                        var images = data["images"];
                                        var m = images.length;
                                        for(var i=0;i<n;i++){
                                        	// We search if images have been tagged with the current tag. 
                                        	var img_urls = "";
                                        	for(var j=0;j<m;j++){
                                        		kws = images[j]["keywords"];
                                        		var nb_kws = kws.length;
                                        		for(var k=0;k<nb_kws;k++){
                                        			if(keywords[i]==kws[k]){
                                        			    img_urls += ((img_urls=="") ? "" : ",") + images[j].url_height;
                                        			}
                                        		}
                                        	}
                                            s += '<li><span class="clickable addable_tag" data="' + img_urls + '">' + keywords[i] + '</span></li>';
                                        }
                                        s += '</ul><span id="senseetive_tags" class="right clickable">+ {% trans 'Add all Senseetive keywords to yours' %}</span>'
	                                        +'</div><div id="tabs-2" style="overflow-y: scroll; overflow-x: hidden; height: 250px;">'
	                                        +'<ul>';
	                                    // Add pictures
	                                    for(var i=0;i<m;i++){
                                            s += '<li class="senapi_li"><img src="' + images[i].url_width + '" class="senapi_img" alt="' + images[i].title + '"/>'
                                               + '<span class="senapi_text">' + images[i].title + '</span>'
                                               + '<br/><span class="senapi_tags">';
                                            kws = images[i]["keywords"];
                                            var nb_kws = kws.length;
                                            for(var k=0;k<nb_kws;k++){
                                            	s += ((k==0) ? "" : ", ") + '<span class="clickable addable_tag">' + kws[k] + '</span>';
                                            }
                                            s +='</span></li>';
                                        }
	                                    s += '</ul>'
	                                        +'</div></div>';
                                        $("#senseetive_holder").html(s);
                                        // Init tabs
                                        $("#tabs").tabs();
                                        // Function to add one tag
                                        $("#senseetive_holder .addable_tag").click(function() {
                                            addTags([$(this).text()]);
                                        });
                                        // Functions to add all tags from senseetive
                                        $("#senseetive_tags").click(function() {
                                        	$(".addable_tag").each(function() {
                                        		addTags([this.textContent]);
                                        	});
                                        });
                                        // Functions to show tag's images
                                        $("#add_senseetive_tags .addable_tag").hover(
                                        	function(e){
                                        		urls = $(this).attr("data").split(",");
                                        		var s = "";
                                        		var n = urls.length;
                                        		for(i=0;i<n;i++){
                                        			s += '<img src="' + urls[i] + '" alt=""/>';
                                        		}
                                        		$("#info_tag").html(s);
                                        		$("#info_tag").css({'top':e.pageY-110,'right':$(window).width()-e.pageX});
                                        		$("#info_tag").show();
                                        	},
                                        	function(e){
                                        		$("#info_tag").hide();
                                        	}
                                        );
                                    }
                                },
                                error: function(jqXHR, textStatus, errorThrown) {
                                    $("#senseetive_holder").html("<strong>ERROR</strong> : " + jqXHR.responseText);
                                }
                            });
                        }
                    });
                }
            }
            window.onload = function() {
            	// Functions to add all tags from various sources
                if($("#add_rmn_tags")){
                    $("#add_rmn_tags").click(function() {
                        addTags($("#rmn_tags").text().split(', '));
                    });
                }
                if($("#add_pertimm_title")){
                    $("#add_pertimm_title").click(function() {
                        addTags($("#pertimm_title_tags").text().split(', '));
                    });
                }
                if($("#add_pertimm_description")){
                    $("#add_pertimm_description").click(function() {
                        addTags($("#pertimm_description_tags").text().split(', '));
                    });
                }
                if($("#add_pertimm_thesaurus")){
                    $("#add_pertimm_thesaurus").click(function() {
                        addTags($("#pertimm_thesaurus_tags").text().split(', '));
                    });
                }
                // Check if path is not empty ("" or "MZ")
                $(".fragment-path").change(function() {
                	if($("#senseetive_holder").children()[0].id!="senseetive_click"){
                	    $("#senseetive_holder").html("<p id=\"senseetive_click\" class=\"add-button-grey\">{% trans 'Request keywords from Senseetive API' %}</p>");
                	    init_sensitive_click();
                	}
                    var v = $(".fragment-path").val();
                    if(v!="" && v!="MZ"){
                    	$("#senseetive_click").removeClass("add-button-grey");
                    	$("#senseetive_click").addClass("clickable add-button");
                    }
                    else{
                        $("#senseetive_click").addClass("add-button-grey");
                        $("#senseetive_click").removeClass("clickable add-button");
                    }
                });
                // Init tagit autocomplete with tags from various sources
                autocomplete_tags = $("#rmn_tags").text().split(', ');
                autocomplete_tags = autocomplete_tags.concat($("#pertimm_title_tags").text().split(', '));
                autocomplete_tags = autocomplete_tags.concat($("#pertimm_description_tags").text().split(', '));
                autocomplete_tags = autocomplete_tags.concat($("#pertimm_thesaurus_tags").text().split(', '));
                $('#user_keywords').tagit({availableTags: autocomplete_tags, allowSpaces: true});
                
                // Function to add one tag
                $(".addable_tag").click(function() {
                    addTags([$(this).text()]);
                });
                
                // Init senseetive api request
                init_sensitive_click();
           	};
           	function addTags(tags){
                nt = tags.length;
                for(var i=0; i<nt; i++){
                    $('#user_keywords').tagit('createTag', tags[i]);
                }
           	}
        </script>
{% endblock %}

{% block content %}
                <div class="fullwidth">
                    <form action="{% url 'save_fragment' %}" method="POST">
                        <div class="column column-half">
                            <a href="#" class="head-button clear-fragment" title="{% trans 'Erase the drawing' %}">&times;</a>
                            <a href="#" class="head-button reset-fragment" title="{% trans 'Back to the original drawing' %}">&#8634;</a>
                            <h2>{% if frg_to_modify %}{{ frg_data.title }}{% else %}{% trans 'New fragment' %}{% endif %}&nbsp;:</h2>
                            <div class="center-image">
	                            <div class="image-and-fragment">
	                              {% with img.info.image_file as image %}
	                              {% if image|ratio > 0.8 %}
	                               {% thumbnail image "476" format="PNG" crop="center" as im %}
		                            <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"/>
		                           {% empty %}
		                            <img src="{% static 'egonomy/img/empty.gif' %}" width="476" height="476" class="placeholder" />
		                           {% endthumbnail %}
		                          {% else %}
	                               {% thumbnail image "x600" format="PNG" crop="center" as im %}
	                                <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"/>
	                               {% empty %}
	                                <img src="{% static 'egonomy/img/empty.gif' %}" width="476" height="476" class="placeholder" />
	                               {% endthumbnail %}
		                          {% endif %}
		                          {% endwith %}
	                                <div class="cutout-canvas"></div>
	                            </div>
                            </div>
                            <input name="fragment_path" id="fragment_path" type="hidden" class="fragment-path column-half" value="{% if frg_data %}{{ frg_data.coordinates }}{% endif %}" />
                            <input name="image_id" id="image_id" type="hidden" value="{{ img.id }}" />
                            {% if frg_to_modify %}<input name="fragment_pk" id="fragment_pk" type="hidden" value="{{ frg_data.pk }}" />{% endif %}
                            {% csrf_token %}
                        </div>
                        <div class="column column-half">
                            <table class="image-metadata">
                                <tr>
                                    <th>{% trans 'Source picture' %}&nbsp;:</th>
                                    <td><a href="{% url 'annotate_picture' image_id=img.id %}">{{ img.metadata.titre|default:_("No title") }}</a></td>
                                </tr>
                                <tr>
                                    <th>{% trans "Fragment's title" %}&nbsp;:</th>
                                    <td><input type="text" class="fragment-title" placeholder="{% trans "Fragment's title" %}" name="fragment_title" id="fragment_title" {% if frg_data %}value="{{ frg_data.title }}"{% endif %}/></td>
                                </tr>
                                <tr>
                                    <th>{% trans "Fragment's description" %}&nbsp;:</th>
                                    <td><textarea class="fragment-description" name="fragment_description" id="fragment_description" {% if frg_data %}value="{{ frg_data.description }}"{% endif %}></textarea></td>
                                </tr>
                                <tr>
                                    <th>{% trans 'Users keywords' %}&nbsp;:</th>
                                    <td><input id="user_keywords" name="user_keywords" class="user-keywords" {% if frg_data %}value="{{ frg_data.tags }}"{% endif %}></ul>
                                </tr>
                                {% if img.metadata.mots_cles %}
                                <tr>
                                    <th>{% trans 'RMN keywords' %}&nbsp;:</th>
                                    <td><span id="rmn_tags">{% for t in img.metadata.mots_cles_list %}<span class="clickable addable_tag">{{ t }}</span>{% if not forloop.last %}, {% endif %}{% endfor %}</span>
                                        <br/><span id="add_rmn_tags" class="right clickable">+ {% trans 'Add all RMN keywords to yours' %}</span></td>
                                </tr>
                                {% endif %}
                                {% if img.metadata.titre_pertimm %}
	                            <tr>
	                                <th>{% trans "Pertimm title" %}&nbsp;:</th>
	                                <td><span id="pertimm_title_tags">{% for t in img.metadata.titre_pertimm_list %}<span class="clickable addable_tag">{{ t }}</span>{% if not forloop.last %}, {% endif %}{% endfor %}</span>
	                                    <br/><span id="add_pertimm_title" class="right clickable">+ {% trans 'Add all Pertimm title keywords to yours' %}</span></td>
	                            </tr>
                                {% endif %}
                                {% if img.metadata.description_pertimm %}
	                            <tr>
	                                <th>{% trans "Pertimm description" %}&nbsp;:</th>
	                                <td><span id="pertimm_description_tags">{% for t in img.metadata.description_pertimm_list %}<span class="clickable addable_tag">{{ t }}</span>{% if not forloop.last %}, {% endif %}{% endfor %}</span>
	                                    <br/><span id="add_pertimm_description" class="right clickable">+ {% trans 'Add all Pertimm description keywords to yours' %}</span></td>
	                            </tr>
                                {% endif %}
                                {% if img.metadata.thesaurus_pertimm %}
	                            <tr>
	                                <th>{% trans "Pertimm thesaurus" %}&nbsp;:</th>
	                                <td><span id="pertimm_thesaurus_tags">{% for t in img.metadata.thesaurus_pertimm_list %}<span class="clickable addable_tag">{{ t }}</span>{% if not forloop.last %}, {% endif %}{% endfor %}</span>
	                                    <br/><span id="add_pertimm_thesaurus" class="right clickable">+ {% trans 'Add all Pertimm thesaurus keywords to yours' %}</span></td>
	                            </tr>
                                {% endif %}
                                <tr>
                                    <th>{% trans "Senseetive keywords" %}&nbsp;:</th>
                                    <td id="senseetive_holder"><p id="senseetive_click" class="add-button-grey">{% trans 'Request keywords from Senseetive API' %}</p></td>
                                </tr>
                            </table>
                            <div class="fullwidth">
                                <input class="user-submit" type="submit" value="{% trans 'Save the fragment' %}" />
                            </div>
                        </div>
                    </form>
                </div>
                <div class="fullwidth">
                    <div class="column column-full">
                        <h2>{% trans "Fragments from this picture" %}</h2>
                        <ul class="fullwidth">
                          {% for fragment in fragment_list %}
                            <li class="subcol subcol-eighth">
                                <a href="{% url 'view_fragment' fragment_pk=fragment.pk  %}">
                                <div class="center-image">
                                    <div class="image-and-fragment">
                                     {% include "partial/picture_and_red_fragment.html" %}
                                    </div>
                                </div>
                                <h3>{{ fragment.title }}</h3></a>
                                <p>{% trans "Annotated by" %} <strong><a href="{% url 'user_fragments' username=fragment.author %}">{{ fragment.author }}</a></strong></p>
                            </li>
                          {% endfor %}
                        </ul>
                    </div>
                </div>
                <div id="info_tag" style="display:none;">
                  <p>coucou</p>
                </div>
{% endblock %}

