{% load common_tags %}

{% comment %}
/**
  Copyright (C) 2012-2016 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 %}


<script type="text/javascript">
/**
 * This script is included in the main containers.html page as well as public.html,
 * 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.
**/

$(function () {

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

    // 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;
        }
        // Don't load if not visible or content aleady loaded (when moving between tabs)
        if (!$metadata_general.is(":visible") || !$metadata_general.is(":empty")) {
            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...
            OME.fadeInSpinner($metadata_general);
            $.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);
                },
                error: function(data) {
                    // If request string too long. e.g. image=1&image=2&image=3.... etc
                    // Just show the error message in right panel.
                    // This error will be ignored by OME.setupAjaxError();
                    if (data.status == 414 || data.responseText.indexOf('Request Line is too large') > -1) {
                        $metadata_general.html(data.responseText);
                    }
                }
            });
            
        } else {
            $("#annotation_tabs").tabs("enable", general_tab_index);    // always want metadata_general enabled
            var url = null;
            var oid = selected[0]["id"];
            var orel = oid.split("-")[0];
            if (typeof oid =="undefined" || oid==false) return;
            
            // handle loading of GENERAL tab...
            // 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>');
            // 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]+'/?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);
                OME.fadeInSpinner($metadata_general);
                $.ajax({
                    url: url,
                    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>
