{% load common_tags %}
{% load mapr_tags %}

{% comment %}
/**
  Copyright (C) 2012-2014 University of Dundee & Open Microscopy Environment.
  All rights reserved.

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as
  published by the Free Software Foundation, either version 3 of the
  License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU Affero General Public License for more details.

  You should have received a copy of the GNU Affero General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
{% endcomment %}


<style type="text/css">

    .keyValueTable tbody tr td span.favicon img {
        border: 1px solid hsl(210, 8%, 65%);
        box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
        vertical-align: middle;
        width: 15px;
        height: 15px;
    }
    .keyValueTable tbody tr td span.blank img {
        width: 17px;
        height: 15px;
    }
    .keyValueTable thead tr h1 {
        padding: 2px 0px;
    }
</style>


<script type="text/javascript">
/**
 * This script is included in the main containers.html page as well as the container_tags.html and public.html pages,
 * adding itself as a selection listener to the jsTree in each case.
 * It loads appropriate data into the right-hand 'general' tab on selection changes in the jsTree.
**/

var urlRegex = new RegExp("(https?|ftp|file):\/\/[!-~]*", "igm");

var iconify = function(input, imgsrc) {
    if (typeof imgsrc === 'undefined') {
        //imgsrc = 'http://www.google.com/s2/favicons?domain=';
        imgsrc = "{% url "mapannotations_favicon" %}?u=";
    }
    function replacer(match){
        return ' <span class="favicon"><a href="' + match + '" target="_blank" ><img src="' + imgsrc + encodeURIComponent(decodeURIComponent(match)) + '" /></a></span>';
    };
    return input.replace(urlRegex, replacer);
};

var isURL = function(input) {
    return urlRegex.test(input);
};

var old_linkify_element = OME.linkify_element;
OME.linkify_element = function(elements) {
    if ($("table.keyValueTable").is(elements) ) {
        var mapr_menu = {% mapr_menu_config %};

        // Replace namespace with label
        var ns2menu = {};
        $.each( mapr_menu, function( i, obj ) {
            $.each( obj['ns'], function( j, ns ) {
                ns2menu[ns] = obj['label'];
            });
        });
        var t = elements.find("thead").find("tr");
        var $targets = t.filter(function() {
            if ($(this).attr('title') in ns2menu) {
                var old = $(this).children("th").text();
                $(this).children("th").html("<h1>" + ns2menu[$(this).attr('title')] + "</h1>");
                $(this).closest('tr').nextAll("tr.tooltip").children('th').children('span')
                    .append('<br/><b>NS:</b> ' + old + '');
            }
        });

        // linkify also mapr keys and convert URL to icons
        var menu2keys = [];
        var keys2menu = {};
        $.each( mapr_menu, function( i, obj ) {
            $.merge(menu2keys, obj['all']);
            $.each( obj['all'], function( j, d ) {
                keys2menu[d] = i
            });
        });

        elements.find("tbody").find("tr").each(function() {
            var $row = $(this);
            if (!$row.parent().parent().hasClass("editableKeyValueTable")) {
                var $chlabel = $row.children("td:nth-child(1)");
                var $chvalue = $row.children("td:nth-child(2)");
                // if label matchs mapr PK
                var _key = $chlabel.text().trim();
                var _val = $chvalue.text().trim();
                var _tkey = _key.replace(/url/i, "").trim();
                if ( $.inArray(_tkey, menu2keys) > -1  ) {
                    $chvalue.html(iconify($chvalue.text()));
                    if ( $.inArray(_key, menu2keys) > -1 ) {
                        if ( _key in keys2menu && keys2menu[_key] !== undefined ) {
                            // create mapr url
                            var _url = location.protocol + "//" + location.host + "{% url 'maprindex' %}" + keys2menu[_key] +"/?value=" + encodeURIComponent(_val);
                            $chvalue.html($chvalue.html().replace(_val, '<a href="' + _url + '">' + _val + '</a>'));
                        }
                    }
                    if ( _key.match(new RegExp("url", "i"))  ) {
                        // Find nearest URL
                        //var $target1 = $row.prev('tr');
                        var $target = $row.parent().find("tr").filter(function() {
                            var $chl = $(this).children("td:nth-child(1)");
                            var $chv = $(this).children("td:nth-child(2)");
                            var $chs = $row.children("td:nth-child(2)").find("span a img").attr('src');
                            return $chl.text() === _tkey && (($chv.find("a").text().lenght > 0 && ($chs.indexOf(encodeURIComponent($chv.find("a").text())) >= 0 || $chs.indexOf($chv.find("a").text()) >= 0)) || ($chv.text().length > 0 && ($chs.indexOf(encodeURIComponent($chv.text())) >= 0 || $chs.indexOf($chv.text()) >= 0)));
                        }).closest("tr");
                        if ( $target.length ) {
                            var $targetchlabel = $target.children("td:nth-child(1)");
                            var $targetchvalue = $target.children("td:nth-child(2)");
                            // add icon to the target and hide
                            $targetchvalue.append($chvalue.html());
                            $row.hide();
                        }
                    }
                } else {
                    old_linkify_element($row);
                }
            }

        });
    } else {
        old_linkify_element(elements);
    }
};



$(function () {

    $("#annotation_tabs").tabs({cache: true, disabled: true});
    var $metadata_general = $("#metadata_general");
    var general_tab_index = 0;

    // make sure details are ALWAYS opened
    OME.setPaneExpanded('details', true);
    // make sure maps are ALWAYS opened
    OME.setPaneExpanded('maps', true);

    // this is called on change in jstree selection, or switching tabs
    var update_metadata_general_tab = function() {
        var selected = $("body").data("selected_objects.ome");

        var prefix = '{% url 'webindex' %}';

        if(selected.length == 0) {
            return;
        }
        if (selected.length > 1) {
            // handle batch annotation...
            var productListQuery = new Array();
            var well_index;
            for (var i=0; i<selected.length; i++) {
                productListQuery[i] = selected[i]["id"].replace("-","=");
                well_index = well_index || selected[i]["index"];
            }
            var query = '{% url 'batch_annotate' %}'+"?"+productListQuery.join("&");
            if (well_index) {
                query += "&index=" + well_index;
            }
            // Load right hand panel...
            $.ajax({
                url: query,
                dataType: "html",
                // Need to check that the selected objects haven't changed during AJAX call...
                success: function(data) {
                    var selected_ids = [], i,
                        selected_data = $("body").data("selected_objects.ome");
                    for(i=0; i<selected_data.length; i++) {
                        selected_ids.push(selected_data[i].id);
                    }
                    var oids = $(data).filter("#object-ids").text().split("|");
                    // need to compare two arrays of strings...
                    selected_ids.sort();
                    oids.sort();
                    for(i=0;i<oids.length; i++) {
                        if (oids[i] !== selected_ids[i]) {
                            return;     // any differences, don't load panel.
                        }
                    }
                    $metadata_general.html(data);
                }
            });
            
        } else {
            $("#annotation_tabs").tabs("enable", general_tab_index);    // always want metadata_general enabled
            var url = null;
            var data = {};
            //var oid = selected.attr('id');
            //var orel = selected[0].attr('rel');
            var oid = selected[0]["id"];
            var orel = oid.split("-")[0];
            if (typeof oid =="undefined" || oid==false) return;

            // handle loading of GENERAL tab
            if ($metadata_general.is(":visible") && $metadata_general.is(":empty")) {
                // orphaned
                if (oid.indexOf("orphaned")>=0) {
                    $metadata_general.html('<div class="right_tab_inner"><p class="description">{{ ui.orphans.description }}</p></div>');
                    //return;
                // experimenter
                } else if (oid.indexOf("experimenter")>=0) {
                    //$metadata_general.html('<p>'+selected.children().eq(1).text()+'</p>');
                } else if (orel.indexOf("map")>=0) {
                    var map_prefix = '{% url "maprindex" %}';
                    url = map_prefix+'metadata_details/{{ menu }}/';
                    data = {'value': oid.split(/-(.+)/)[1]};
                // everything else
                } else {
                    if(orel=="image") {
                        if (selected[0]["shareId"]) {
                            url = prefix+'metadata_details/'+orel+'/'+oid.split("-")[1]+'/'+selected[0]["shareId"]+'/';
                        } else {
                            url = prefix+'metadata_details/'+orel+'/'+oid.split("-")[1]+'/';
                        }
                    } else if(orel=="well"){
                        var well_index = selected[0]["index"] || 0;
                        url = '{% url "load_metadata_details" %}well/'+oid.split('-')[1]+'/';
                        data = {'index': well_index};
                    } else {
                        url = prefix+'metadata_details/'+orel+'/'+oid.split("-")[1]+'/';
                    }
                }
                if (url !== null) {
                    // We are effectively doing $metadata_general.load(url) BUT we need to check that selection
                    // is still correct (hasn't changed during the AJAX call);
                    $.ajax({
                        url: url,
                        data: $.param(data),
                        dataType: "html",
                        success: function(data) {
                            var selected_id = $("body").data("selected_objects.ome")[0].id;
                            var oid = $(data).filter("#object-id").text();
                            if (oid === selected_id) {
                                $metadata_general.html(data);
                            }
                        }
                    });
                }
            }
        }
    }

    // update tabs when tabs switch
    $("#annotation_tabs").on( "tabsactivate", function(event, ui){
        // we get a "tabsactivate" event, but need to check if 'this' tab was chosen...
        if (ui.newTab.index() == general_tab_index) {
            // sometimes this doesn't get shown until too late, so the :visible check above failed
            $metadata_general.show();
            update_metadata_general_tab();
        }
    });

    // on selection change, clear tab contents then update
    $("body").on("selection_change.ome", function(event) {
        // clear contents of panel
        $("#metadata_general").empty();

        update_metadata_general_tab();     // update
    });

});
</script>
