{% extends "webclient/base/base_container.html" %}
{% load i18n %}
{% load common_filters %}


{% comment %}
<!--
  Copyright (C) 2011 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 %}

{% block link %}
    {{ block.super }}
    <link rel="stylesheet" href="{% static "webgateway/css/ome.table.css"|add:url_suffix %}" type="text/css" media="screen"/>
    <link rel="stylesheet" href="{% static "3rdparty/jquery.tablesorter-2.0.3/jquery.tablesorter.css" %}" type="text/css" media="screen"/>
{% endblock %}

{% block script %}
    {{ block.super }}
    <script type="text/javascript" src="{% static "3rdparty/jquery.tablesorter-2.0.3/jquery.tablesorter.js" %}"></script>
    <script type="text/javascript" src="{% static "3rdparty/jquery.quicksearch-1.0.js" %}"></script>
    
    <script type="text/javascript">
        $(document).ready(function() 
            {

                // Disable the groups/users dropdown menu.
                $("#groupsUsersButton")
                    .css('background-image', 'url()')
                    .attr('title', 'Use "Scope" in form below to search within specific Groups / Users');
                setTimeout(function(){
                    // make sure we remove click handler AFTER it's been added
                    $("#groupsUsersButton").off('click');
                },500);

                var $ownedBy = $("select[name='ownedBy']");

                var selectUsersFromGroup = function(groupId) {
                    $ownedBy.prop("disabled", true).hide();
                    $("#searchByGroupMember-" + groupId).prop('disabled', false).show();
                }

                // Choose group, then pick a user from that group
                $("#searchGroup").change(function() {
                    var gid = $(this).val();
                    selectUsersFromGroup(gid);
                });

                var gid = -1;
                $("#searchGroup").val(gid);
                selectUsersFromGroup(gid);


                $("#filtersearch label").inFieldLabels();


                // Init date-pickers...
                $('#startdateinput').datepicker({
                    changeMonth: true,
                    changeYear: true,
                    maxDate: 0,     // only allow dates in past.
                    firstDay: 1,
                    dateFormat: 'yy-mm-dd',
                    beforeShow: function(input, inst) {
                        // z-index is set to 1 on 'show' - need to reset if AFTER show
                        setTimeout(function(){
                            $("#ui-datepicker-div").css('z-index','50');
                        }, 10);
                    },
                    onClose: function( selectedDate ) {
                        $( "#enddateinput" ).datepicker( "option", "minDate", selectedDate );
                        $(this).next(".clearDate").show();
                    }
                });
                $('#enddateinput').datepicker({
                    changeMonth: true,
                    changeYear: true,
                    maxDate: 0,     // only allow dates in past.
                    firstDay: 1,
                    dateFormat: 'yy-mm-dd',
                    beforeShow: function(input, inst) {
                        // z-index is set to 1 on 'show' - need to reset if AFTER show
                        setTimeout(function(){
                            $("#ui-datepicker-div").css('z-index','50');
                        }, 10);
                    },
                    onClose: function( selectedDate ) {
                        if (selectedDate){
                            $( "#startdateinput" ).datepicker( "option", "maxDate", selectedDate );
                        }
                        if ($(this).val().length > 0) {
                            $(this).next(".clearDate").show();
                        }
                    }
                });
                // removing dates - clear fields and reset ranges.
                $(".clearDate").click(function() {
                    $(this).hide().prev("input").val("");
                    var end = $( "#enddateinput" ).datepicker( "getDate" ) || 0;
                    $( "#startdateinput" ).datepicker( "option", "maxDate", end);
                    var start = $( "#startdateinput" ).datepicker( "getDate" );
                    $( "#enddateinput" ).datepicker( "option", "minDate", start);
                    return false;
                });
                // hide each 'X' if corresponding date field is empty
                $(".clearDate").each(function(){
                    if ($(this).prev().val().length == 0) {
                        $(this).hide();
                    }
                })

                $(".searching_info, #daterange").tooltip({
                    track: true,
                    show: false,
                    hide: false,
                    items: '[data-content]',
                    content: function() {
                        return $(this).data('content');
                    }
                });

                $("#searching_form").ajaxForm({
                    beforeSubmit: function(fields) {

                        var q = '';
                        if ($('input[name="advanced"]').prop('checked')) {
                            q = $("input[name='advanced_search']").val();
                        } else {
                            q = $("input[name='query']").val();
                        }
                        // check we have some search query...
                        q = $.trim(q);
                        if (q.length <= 0) {
                            OME.alert_dialog("Search must contain some text.");
                            return false;
                        } else if (q == "*") {
                            OME.alert_dialog("Wildcard searches (*) must contain more than a single wildcard.");
                            return false;
                        }

                        // check dates
                        var startdateinput = $("input[name='startdateinput']");
                        var enddateinput = $("input[name='enddateinput']");
                        if(enddateinput.val()!=null && enddateinput.val()!="") {
                            // check if start date is before, otherwise we have problem
                            var start = startdateinput.val();
                            var end = enddateinput.val();
                            if (start==null || start=="") {
                                OME.alert_dialog("Choose start date for range");
                                return false;
                            }
                            if (start > end) {
                                OME.alert_dialog("Start date is after End date");
                                return false;
                            }
                        }

                        // show 'loading...'
                        $("div#content_details").html('<p>{% trans "Loading data... please wait" %} <img src ="{% static "webgateway/img/spinner.gif" %}"/></p>');
                        $("#filtersearch").hide().find('input').val("");    // hide and clear filter
                    },
                    success: function(html) {
                        $("div#content_details").html(html);
                        $("#filtersearch").show();
                        var rTable = $("#dataTable"),
                            rCount = rTable.length > 0 ? parseInt(rTable.attr('data-result-count')): 0,
                            result = (rCount === 0 || rCount > 1) ? "results":"result",
                            resultMessage = rCount + " " + result;
                        if ($("#dataTable").attr('data-more-results')) {
                            resultMessage = "More than " + resultMessage;
                        }
                        $("#searchResultCount").text(resultMessage);
                        OME.table_selection_changed();      // clear right panel
                    }
                });

                {% if init.query %}
                    // query field is already populated with init.query
                    $("#searching_form").submit();
                {% endif %}


                OME.table_selection_changed();     // clear selection (hides acquisition & preview tabs)

                $("#showSearchHints").click(function(event){
                    event.preventDefault();
                    $("#searchHints").toggle();
                    return false;
                });

                $("#show_annotations").click(function(){
                    $("#search_ann_type").toggleClass("hide");

                    if ($(this).is(':checked')) {
                        // if visible, check the 'all annotations' radio button
                        $("input[value='annotation']").prop('checked',true);
                    } else {
                        // otherwise, uncheck ALL annotation radio buttons
                        $("#search_ann_type input[type='radio']").prop('checked',false);
                    }
                });

                $("#searching_tabs").tabs({
                    activate: function( event, ui ) {
                        // Checkk hidden checkbox if we're on the 'advanced search' tab
                        // This will be included in search submitted data
                        $('input[name="advanced"]').prop('checked', ui.newPanel.attr('id') === 'advanced_search');
                    }
                });
        });
    </script>

{% endblock %}

{% block left %}

<div id="searching">
	
	
	{% comment %}
    <div>
        <p>{% trans "Searching feature enables you to search within the images, datasets, projects, plates and screens stored on the server. It supports single and multiple character wildcard searches." %}</p>
    </div>
	{% endcomment %}

    <form id="searching_form" class="search_panel standard_form" action="{% url 'load_searching' 'form' %}">

        <div id="searching_tabs">
            <ul id="left_panel_tab_list" class="ui-tabs-nav">
                <li id="explore_tab" class="ui-state-default">
                    <a href="#basic_search" class="ui-tabs-anchor" title="Explore">Search</a>
                </li>
                <li id="tags_tab" class="ui-state-default">
                    <a href="#advanced_search" class="ui-tabs-anchor" title="Advanced Search">Advanced</a>
                </li>
            </ul>


            <div class="search_panel_header">

                <div id="basic_search">
                    <div class="search_panel_header__text" >

                        <div class="search_panel_header__text--hints" >
                            <a id="showSearchHints" class="search_tips__button" href="#">Show search hints</a>
                            <span class="searching_info" data-content="? Single character wildcard<br>* Multiple character wildcard<br>'AND' Results will contain both terms. E.g: GFP AND H2B">
                                <img class="search_tips__image" src="{% static "webgateway/img/help16.png" %}"/>
                            </span>
                        </div>
                    </div>

                    <div style="clear: both; height: 10px;"></div>
                    <!-- Hidden hints box shown when the user clicks to show hints -->
                    <div id="searchHints" style="display: none">
                        <ul>
                            <li> <strong> ? </strong> Single character wildcard</li>
                            <li> <strong> * </strong> Multiple character wildcard</li>
                            <li> <strong> AND </strong> Results will contain both terms. E.g: GFP AND H2B</li>
                        </ul>
                        <br>
                        <div>
                            For more info, see the
                            <a title="Open link in new Tab" target="new" href="http://help.openmicroscopy.org/search.html">
                                User Help</a>
                            pages.
                        </div>
                    </div>


                    <label for="query">{% trans "Search" %}:</label>
                    <input class="search" name="query" value="{{ init.query }}" size="35"/>
                    <hr>

                    <label style="white-space:nowrap;">
                        Restrict by Field:
                        <span class="searching_info" data-content="Restrict search to specified fields.<br>If none chosen, we search across all fields">
                            <img src="{% static "webgateway/img/help16.png" %}" />
                        </span>
                    </label>

                    <ul class="criteria">
                        <li><input type="checkbox" name="field" value="name" />{% trans "Name" %}</li>
                        <li><input type="checkbox" name="field" value="description" />{% trans "Description" %}</li>
                        <li style="white-space:nowrap;">
                            <input id="show_annotations" type="checkbox" />{% trans "Annotations" %}
                            <span class="searching_info" data-content="Includes file attachments, tags, comments etc">
                               <img src="{% static "webgateway/img/help16.png" %}" />
                            </span>
                        </li>
                    </ul>

                    <ul id="search_ann_type" class="criteria criteria_right hide">
                        <li><input type="radio" name="field" value="annotation">All Annotations</li>
                        <li><input type="radio" name="field" value="file">Files</li>
                        <li><input type="radio" name="field" value="tag">Tags</li>
                    </ul>

                </div>

                <div id="advanced_search">
                    <label for="advanced_search">Advanced:</label>
                    <!-- Checkbox is checked when user switches to Advanced tab -->
                    <input type="checkbox" name="advanced" style="visibility: hidden" />
                    <input class="advanced_search" name="advanced_search" value="{{ init.query }}" size="35"/>
                    <p>Enter raw search term, for example:</p>
                    <code>name:Control AND tag:"GFP H2B"</code>
                    <p>
                        See the
                        <a target="_blank" href="https://help.openmicroscopy.org/search.html#advanced">
                            Advanced Search documentation
                        </a>
                    </p>
                </div>
            </div>
        </div>

        <div style="clear:both"></div>
        <div style="padding: 0 10px">
            <hr>

            <label id="criteria">Search for:</label>

            <ul class="criteria">
                <li><input type="checkbox" name="datatype" value="images" CHECKED />{% trans "Images" %}</li>
                <li><input type="checkbox" name="datatype" value="datasets" CHECKED />{% trans "Datasets" %}</li>
                <li><input type="checkbox" name="datatype" value="projects" CHECKED />{% trans "Projects" %}</li>
                <li><input type="checkbox" name="datatype" value="wells" CHECKED />{% trans "Wells" %}</li>
                <li><input type="checkbox" name="datatype" value="plates" CHECKED />{% trans "Plates" %}</li>
                <li><input type="checkbox" name="datatype" value="screens" CHECKED />{% trans "Screens" %}</li>
            </ul>

            <hr>

            <label>Scope:</label>

            <br>

            In group:

            <select name="searchGroup" id="searchGroup">
                <option value="-1">All Groups</option>
                {% for grp in myGroups %}
                    <option value="{{ grp.id }}">{{ grp.getName }}</option>
                {% endfor %}
            </select>


            <br>

            Data owned by:

            <!-- when 'All Groups' - can choose 'Me' or 'All users' -->
            <select name="ownedBy" id="searchByGroupMember--1">
                <option value="-1">All Users</option>
                {% for user in myColleagues %}}
                    <option value="{{ user.id }}" {% ifequal user.id ome.user.id %}selected="selected"{% endifequal %}>
                        {{ user.getFullName|truncateafter:"50" }}
                    </option>
                {% endfor %}
            </select>

            <!-- for each group we can choose users - only show <select> for 1 group at a time -->
            {% for grp in groups %}
            <select name="ownedBy" id="searchByGroupMember-{{ grp.id }}">
                <option value="-1">All Members</option>
                {% for user in grp.leaders %}}
                    <option value="{{ user.id }}" {% ifequal user.id ome.user.id %}selected="selected"{% endifequal %}>
                        {{ user.getFullName|truncateafter:"50" }}
                    </option>
                {% endfor %}
                {% for user in grp.colleagues %}}
                    <option value="{{ user.id }}" {% ifequal user.id ome.user.id %}selected="selected"{% endifequal %}>
                        {{ user.getFullName|truncateafter:"50" }}
                    </option>
                {% endfor %}
            </select>
            {% endfor %}

            <hr>

            <label for="startdateinput">{% trans "Date" %}:</label>

            <select name="useAcquisitionDate" id="useAcquisitionDate">
                <option value="false" title="Date Imported / Created">Import date</option>
                <option value="true" title="Date Acquired, for Images only">Acquisition date</option>
            </select>

            <span class="searching_info" data-content="Search by date imported / created or acquired.<br>
                    Acquisition dates are for Images only.">
                    <img src="{% static "webgateway/img/help16.png" %}" />
            </span>

            <br/>
            <span style="position: relative">
                <input type="text" id="startdateinput" name="startdateinput" size="12"
                    value="{{ manager.criteria.period }}" title="Search for data 'From' this date"/>
                <span class="clearDate">
                    <img src="{% static "webclient/image/icon_basic_delete.png" %}" />
                </span>
            </span>
            -
            <span style="position: relative">
                <input type="text" id="enddateinput" name="enddateinput" value="" size="12"
                    title="Search for data 'To' this date. Leave blank for 'today'."/>
                <span class="clearDate">
                    <img src="{% static "webclient/image/icon_basic_delete.png" %}" />
                </span>
            </span>
            <span id="daterange" data-content="The 'to' date will be today's date if left blank.">
                    <img src="{% static "webgateway/img/help16.png" %}" />
            </span>

            <hr>

            <input id="search_button" type="submit" value="Search" />
        </div>

    </form>

</div>

{% endblock %}

{% block center %}

	<div id="center_panel_header" >
		
		<form class="search filtersearch searchresult_filter" id="filtersearch" action="#" style="display:none">
		    <div>
		        <label for="id_search">
		            Filter Results
		        </label>
			    <input type="text" id="id_search" size="25" />
			</div>
			<span class="loading">
				<img class="loader" alt="Loading" src="{% static "webgateway/img/spinner.gif" %}">
			</span>
		</form>
		<ul style="position: relative; left: 200px; width: 300px; top: 12px; font-size:110%">
            <li id="searchResultCount"></li>
        </ul>
	</div>

	<div id="content_details" class="center_panel_content"> </div>

{% endblock %}
