{% load staticfiles %}
<script type="text/javascript">
{% autoescape off %}
    var select_button_active = false;

    $('.modal-forms').css('max-height', '500px').css('overflow-y', 'scroll');
    $('.modal-cloose-btn').css('margin','20px');

    $('.modal-cloose-btn').click(function(){
      $('.modal-forms').modal('hide');
    });

    $('#id_resource-poc').change(function(){
      if($(this).val() === ''){
        $('#poc_form').modal();
      }
    });

    var metadata_uri = $(location).attr('pathname').split('/').pop();
    var metadata_update_done = false;
    var is_advanced = (metadata_uri.match(/metadata_advanced/i) != null);
    var is_group_mandatory = {% if GROUP_MANDATORY_RESOURCES %}true{% else %}false{% endif %};

    var updateWizard = function() {
      var activeTab = $("#edit-metadata .wizard--progress li.is-active");
      var first = $("#edit-metadata .wizard--progress li:first-child");
      var last = $("#edit-metadata .wizard--progress li:last-child");
      var firstIndex= first && $(first[0]).data("step");
      var tabIndex = activeTab && $(activeTab[0]).data("step");
      var lastIndex = last && $(last[0]).data("step");

      // buttons visibility
      $('#btn_back_dwn').toggle(firstIndex !== tabIndex);
      $('#btn_next_dwn').toggle(lastIndex !== tabIndex);

      // wizard
      if (tabIndex >= 0) {
        var first;
        for (var i = 0; i < lastIndex; i++) {
          var nextTab = $("#edit-metadata .wizard--progress li[data-step=" + (i) + "]");
          if (nextTab) {
            if(i < tabIndex) {
              nextTab.toggleClass('is-complete', true);
            } else {
              nextTab.toggleClass('is-complete', false);
            }
          }
        }
      }
    }

    // done button tooltip variables
    var tooltipShown = false;
    var gotIt = false;
    var tooltipContent =  'All fields declared mandatory by the schema are completed, you can continue editing the optional fields or click on "Done" to save your changes and close this page. '
      + '<a id="close-popover-done" data-toggle="clickover" class="btn btn-small btn-primary pull-right">Got it</a><br/>';
    $('.metadata-edit-done').popover({
        placement: 'left',
        html: true,
        animation: true,
        content: tooltipContent
      });

    var updateCompleteness = function(completeness) {
      $('#profileCompleteness .progress-bar').html(parseFloat(((completeness)*100).toFixed(0)) + ' %').width(parseFloat(((completeness)*100).toFixed(2)) + '%');
      $('#profileCompleteness .completed').toggle(completeness === 1);
      $('#profileCompleteness .not-completed').toggle(completeness !== 1);
      var mandatoryMissing =  $('#mandatory').find('.input-empty:not([id^=autocomlete])').length > 0;
      var advancedMissing = $('#advanced').find('.input-empty').length > 0;
      $('#completeness-hints .mandatory-hint')
        .toggleClass('progress-bar-danger', mandatoryMissing)
        .toggleClass('progress-bar-success', !mandatoryMissing)
        .attr('title', mandatoryMissing ? "some schema mandatory fields are missing" : "Metadata Schema mandatory fields completed" )
        .tooltip('fixTitle');
      $('#completeness-hints .advanced-hint')
        .toggleClass('progress-bar-danger', advancedMissing)
        .toggleClass('progress-bar-success', !advancedMissing)
        .attr('title', advancedMissing ? "some schema mandatory fields are missing" : "Metadata Schema mandatory fields completed" )
        .tooltip('fixTitle');

        //done button tooltip
        if(completeness === 1 && $('.metadata-edit-done').css('opacity')+"" === "0" && !tooltipShown && !gotIt) {
          tooltipShown = true;
          setTimeout(function() {
            $('.metadata-edit-done').popover('show');
            $(document).on('click', '#close-popover-done', function() {
                 $('.metadata-edit-done').popover('hide');
                 gotIt = true;
             });
          },1500);
        } else if (completeness < 1){
          tooltipShown = false;
          $('.metadata-edit-done').popover('hide');
        }
        // show/hide done button
        $('.metadata-edit-done').animate(completeness === 1 ? {width: '100px', opacity: 1} : {width: 0, opacity: 0});
    }

    function getTab(number) {
      var activeTab = $("#edit-metadata .wizard--progress li.is-active");
      var tabIndex = activeTab && $(activeTab[0]).data("step");
      var nextTab = $("#edit-metadata .wizard--progress li[data-step=" + number + "]");
      if (nextTab) {
        activeTab.toggleClass('is-active');
        nextTab.tab('show');
        nextTab.toggleClass('is-active');
      }
      updateWizard();
    }

    function getPrevTab(){
      var activeTab = $("#edit-metadata .wizard--progress li.is-active");
      var tabIndex = activeTab && $(activeTab[0]).data("step");
      if (tabIndex >= 0) {
          getTab( tabIndex - 1 );
      }

    };

    function getNextTab(){
        var activeTab = $("#edit-metadata .wizard--progress li.is-active");
        var tabIndex = activeTab && $(activeTab[0]).data("step");
        if (tabIndex >= 0) {
            getTab( tabIndex + 1 );
        }
    };

    $(document).ready(
        function() {
          var pickerOptions = {
              // format: 'YYYY-MM-DD hh:mm',
              format: 'YYYY-MM-DD',
              icons: {
                  time: 'fa fa-clock-o',
                  date: 'fa fa-calendar',
                  up: 'fa fa-chevron-up',
                  down: 'fa fa-chevron-down'
              }
          };

          $('#id_resource-date_picker').datetimepicker(pickerOptions);
          $('#id_resource-temporal_extent_start_picker').datetimepicker(pickerOptions);
          $('#id_resource-temporal_extent_end_picker').datetimepicker(pickerOptions);
    });

    $(document).ready(function() {
        $('.has-external-popover').each(function(){
                var help_text = $(this).attr("data-content");
                $(this)
                    .closest("div")
                    .children("span:not(.input-group)")
                    .append("<span class='external-popover' data-content='" + help_text + "'><strong><i class='fa fa fa-question-circle fa-1x'></i></strong></span>");
            });
        $('.external-popover').each(function(){
                $(this).popover({'trigger':'hover'});
            });

        $("#preview_image").show();
        $("#preview_map").hide();
        $("#set_thumbnail").hide();

        var changeTxt = ["Edit", "Close"];

        $("#change_thumbnail").click(function () {
            $(this).text(changeTxt.reverse()[0]);
            $("#preview_map, #preview_image").toggle(1000);
            $("#set_thumbnail").toggle();

            // $("#preview_image_src").attr('src', $("#preview_image_src").attr('src')+'?'+Math.random());
            src = $('#preview_image_src').attr('src');
               // check for existing ? and remove if found
               queryPos = src.indexOf('?');
               if(queryPos != -1) {
                  src = src.substring(0, queryPos);
               }
               $('#preview_image_src').attr('src', src + '?' + Math.random());
        });

        /*function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    $('#preview_image_src').attr('src', e.target.result);
                }

                reader.readAsDataURL(input.files[0]);
            }
        }

        $("#imgInp").change(function(){
            readURL(this);
        });*/
    });

    $(document).ready(function() {
        var prevNum = 0, totalNum = 0;
        var empty = 0;
        $('#completeness-hints .mandatory-hint').click(getTab.bind(null, 1));
        $('#completeness-hints .advanced-hint').click(getTab.bind(null, 2));

        // set proper classes to count empty fields and display them
        var setInputEmpty = function( target, empty ) {
          if($(target).hasClass('value-select')) {
            // tkeywords
            // $(target).toggleClass("input-empty", empty);
            // $(target).parent().find('input.autocomplete').toggleClass("input-empty", empty);
          } else if( !$(target).hasClass('autocomplete') ){
            // display error status for token fields if not completed
            $(target).toggleClass("input-empty", empty);
          }

          if(target.id === 'id_resource-keywords') {
            $(target).closest('.keywords-container').toggleClass('has-error', empty);
            $(target).toggleClass("input-empty", empty);
          }

          if(target.id === 'category_form' ||
             target.id === 'id_resource-regions' ||
             target.id === 'id_resource-group'
          ) {
              // group selector
              $(target).closest('#basicGroupInfo').toggleClass('has-error', empty);

              // category selector
              $(target).closest('#basicCategoryInfo').toggleClass('has-error', empty);

              // regions container
              $(target).closest('#regions_multiselect_container').toggleClass('has-error', empty);

              $(target).toggleClass("input-empty", empty);
          }

          // bootstrap-select copies the select's classes, so it have to be removed
          if( $( '.bootstrap-select' ).hasClass("input-empty") ) {
            $( '.bootstrap-select' ).toggleClass("input-empty");
          }
        }

        //check if a field is mandatory
        var otherRestrictionsSelected  = function(e){
          var otherRestrictions = false
          try {
            idx = $('#id_resource-restriction_code_type')[0].selectedIndex;
            value = $('#id_resource-restriction_code_type')[0].options[idx].text;
            if(value === "otherRestrictions") {
                otherRestrictions = true;
            }
          } catch (err) {
              otherRestrictions = false;
          }

          return otherRestrictions;
        }

        var toggleRestrictionsConstraints = function(e){
          try {
            if(e && e.target &&
                    e.target.id == 'id_resource-constraints_other') {
              var ee = $('#id_resource-constraints_other')[0];
              if(otherRestrictionsSelected() && ee.value !== undefined && ee.value.trim() === '') {
                if(!$(ee).hasClass("input-empty")) {
                    setInputEmpty(ee, true);
                    $(ee).parent().append("<p class='xxs-font-size mandatory-warning'>&nbsp;&nbsp;&nbsp;<strong>* Field declared Mandatory by the Metadata Schema</strong></p>");
                    empty++;
                } else {
                    setInputEmpty(ee, false);
                    $(ee).parent().find(".mandatory-warning").remove();
                    empty--;
                }
              }
             }
          } catch (err) {
            // Log error
            return false;
          }

          return true;
        }

        var isMandatoryField = function (el) {
          if(el.id.indexOf("resource-constraints") >= 0) {
            if(otherRestrictionsSelected()) {
                return true;
            }
            return false;
          }

          var is_mandatory = (el.id.indexOf("autocomplete") < 0 &&
                        !$(el).hasClass('value-select') &&
                        el.type !== 'radio' &&
                        el.type !== 'button');
            return is_mandatory;
        }

        var onInputChange = function(e){
            toggleRestrictionsConstraints(e);

            if(e.target.value !== undefined && e.target.value.trim() === ''){
                if(!$(e.target).hasClass("input-empty")){
                    if(isMandatoryField(this)) {
                        setInputEmpty(e.target, true);
                        if(!!$(this).closest('#mdinfo').length) {
                            $(e.target).parent().append("<p class='xxs-font-size mandatory-warning'>&nbsp;&nbsp;&nbsp;<strong>* Field declared Mandatory by the Metadata Schema</strong></p>");
                        }
                        empty++;
                    }
                }
            }
            else {
                if($(e.target).hasClass("input-empty")) {
                    if(isMandatoryField(this)) {
                        empty--;
                    }
                    setInputEmpty(e.target, false);
                    $(e.target).parent().find(".mandatory-warning").remove();
                }
            }

            if(totalNum == prevNum) {
                try {
                    var perc = (totalNum <= 0 ? 0 : (totalNum-empty)/totalNum);
                        perc = (perc <= 1 ? perc : 1);
                    updateCompleteness(perc);
                } catch(err) {
                    // Log error
                }
            }
        };

        $('#category_form').change(onInputChange).change();
        $('#id_resource-group').change(onInputChange).change();
        $('#id_resource-regions').change(onInputChange).change();
        $('#mandatory').find(":input:not(.value-select):not(.autocomplete)").each(function(){
            if(isMandatoryField(this)) {
                prevNum++;
            }
            $('#category_form').on('rendered.bs.select', function() {
              $('.has-popover').popover({'trigger':'hover'});
            });

            $(this).change(onInputChange).change();

            if(isMandatoryField(this)){
                totalNum++;
            }
        });

        $('#mdinfo').find(":input:not(.value-select):not(.autocomplete)").each(function(){
            if(isMandatoryField(this)) {
                prevNum++;
            }

            $(this).change(onInputChange).change();

            if(isMandatoryField(this)){
                totalNum++;
            }
        });

        // Dataset attributes sorting
        $(document).ready(function() {
            //Helper function to keep table row from collapsing when being sorted
            var fixHelperModified = function(e, tr) {
                var $originals = tr.children();
                var $helper = tr.clone();
                $helper.children().each(function(index) {
                  $(this).width($originals.eq(index).width())
                });
                return $helper;
            };
            //Renumber table rows
            function renumber_table(tableID) {
                $(tableID + " input[name$=display_order]").each(function() {
                    //note: index 0 is for the header
                    count = $(this).closest('tr').index(tableID +' tr');
                    $(this).val(count);
                });
            }
            //Make table sortable
            $("#dataset tbody").sortable({
                items: "tr:not(.table-header)",
                helper: fixHelperModified,
                stop: function(event,ui) {renumber_table('#dataset table')}
            }).disableSelection();

            //change position on display_order field change
            $("#dataset table input[name$=display_order]").change(function(e) {
              if (e.originalEvent) {
                // user-triggered event
                var nextIndex = $( this ).val();
                if(nextIndex > 0) {
                  var to = $('#dataset tbody');
                  var currentPosition = $(this).closest('tr').index('#dataset tbody tr');
                  if(currentPosition > nextIndex) { nextIndex--; }
                  $(this).closest('tr').insertAfter(to.children().eq(nextIndex));
                }
                renumber_table('#dataset table')
              }
            });
        });

        $(".wizard--progress li").click(function(){
          $(this).tab('show');
          $(".wizard--progress li.is-active").toggleClass('is-active', false);
          $(this).toggleClass('is-active', true);
          updateWizard();
        });

        $('#btn_back_up').click(function(){getPrevTab()});
        $('#btn_back_dwn').click(function(){getPrevTab()});

        $('#btn_next_up').click(function(){getNextTab()});
        $('#btn_next_dwn').click(function(){getNextTab()});

        $('#btn_upd_md_up').click(function(){
            if((!is_advanced && $('#category_form').hasClass("input-empty")) ||
                (is_advanced && !$('#category_form input:checked').val())) {
                $('#category_mandatoryDialog').modal();
            } else if
              ( is_group_mandatory &&
                (
                  (!is_advanced && $('#id_resource-group').hasClass("input-empty")) ||
                  (is_advanced && !$('#id_resource-group').val())
                )
              ) {
                $('#group_mandatoryDialog').modal();
            } else {
                $('#preview_pleaseWaitDialog').modal();
            }
        });

        $('#btn_upd_md_dwn').click(function(){
            if((!is_advanced && $('#category_form').hasClass("input-empty")) ||
                (is_advanced && !$('#category_form input:checked').val())) {
                $('#category_mandatoryDialog').modal();
            } else if
              ( is_group_mandatory &&
                (
                  (!is_advanced && $('#id_resource-group').hasClass("input-empty")) ||
                  (is_advanced && !$('#id_resource-group').val())
                )
              ) {
                $('#group_mandatoryDialog').modal();
            } else {
                $('#preview_pleaseWaitDialog').modal();
            }
        });

        $('#btn_upd_md_done').click(function(){
            if((!is_advanced && $('#category_form').hasClass("input-empty")) ||
                (is_advanced && !$('#category_form input:checked').val())) {
                $('#category_mandatoryDialog').modal();
            } else if
              ( is_group_mandatory &&
                (
                  (!is_advanced && $('#id_resource-group').hasClass("input-empty")) ||
                  (is_advanced && !$('#id_resource-group').val())
                )
              ) {
                $('#group_mandatoryDialog').modal();
            } else {
                $('#preview_pleaseWaitDialog').modal();
                $('#metadata_update').submit();
                metadata_update_done = true;
            }
        });

        $('#preview_tab').on('show.bs.tab', function(){
            if((!is_advanced && $('#category_form').hasClass("input-empty")) ||
                (is_advanced && !$('#category_form input:checked').val())) {
                $('#category_mandatoryDialog').modal();
            } else if
              ( is_group_mandatory &&
                (
                  (!is_advanced && $('#id_resource-group').hasClass("input-empty")) ||
                  (is_advanced && !$('#id_resource-group').val())
                )
              ) {
                $('#group_mandatoryDialog').modal();
            } else {
                $('#preview_pleaseWaitDialog').modal();
                try {
                    $('#preview_encoder_iframe')[0].style.width='0';
                    $('#preview_encoder_iframe')[0].style.height='0';
                    $('#metadata_update').submit();

                    // buttons visibility
                    $('#btn_back_dwn').hide();
                    $('#btn_next_dwn').hide();
                    $('#btn_upd_md_dwn').hide();
                } catch(err) {
                    // Log error
                }
            }
        });

        $('#settings_tab').on('show.bs.tab', function() {
            // buttons visibility
            $('#btn_back_dwn').hide();
            $('#btn_next_dwn').hide();
            $('#btn_upd_md_dwn').show();
        });

        $('#metadata_edit_tab').on('show.bs.tab', function() {
          // buttons visibility
          $('#btn_upd_md_dwn').show();
          updateWizard();
        });

        $('#metadata_update').submit(function(e) {
            if((!is_advanced && $('#category_form').hasClass("input-empty")) ||
                (is_advanced && !$('#category_form input:checked').val())) {
                $('#category_mandatoryDialog').modal();
            } else if
              ( is_group_mandatory &&
                (
                  (!is_advanced && $('#id_resource-group').hasClass("input-empty")) ||
                  (is_advanced && !$('#id_resource-group').val())
                )
              ) {
                $('#group_mandatoryDialog').modal();
            } else {
                var formData = $(this).serializeArray();
                // edit data here
                    /* var date = $('#id_resource-date').val();
                    var resource_date = $.grep(formData, function(e){ return e.name == 'resource-date'; });
                    if (resource_date.length >= 1) {
                        resource_date[0].value = date + ' AM';
                    } */
                $.post('metadata', /*$(this).serialize()*/ $.param(formData), function(data){
                    // Do something more fancy with your respone
                    // $('.message').html(data.message);
                    if (!is_advanced) {
                        try {
                            $('#preview_encoder_iframe')[0].style.width='100%';
                            $('#preview_encoder_iframe')[0].style.height='100%';
                            $('#preview_encoder_iframe')[0].contentWindow.location.reload(true);
                        } catch(err) {
                            // Log error
                            console.log(err);
                        }
                    }
                    $('#preview_pleaseWaitDialog').modal('hide');
                });
            }
            e.preventDefault();
            if (metadata_update_done) {
                window.location.replace(e.target.action.replace('/'+metadata_uri,''));
            }
        });

        if(totalNum == prevNum) {
            try {
                var perc = (totalNum <= 0 ? 0 : (totalNum-empty)/totalNum);
                    perc = (perc <= 1 ? perc : 1);
                updateCompleteness(perc);
            } catch(err) {
                // Log error
                console.log(err);
            }
        }
    });

    $('#id_resource-metadata_author').change(function(){
      if($(this).val() === ''){
        $('#metadata_form').modal();
      }
    });

    $(document).ready(function() {
      {% if layer.metadata_uploaded_preserve %}
        $('#metadata_update :input').attr('readonly','readonly');
      {% endif %}
        $('.has-popover').popover({'trigger':'hover'});

        var params = typeof FILTER_TYPE == 'undefined' ? {} : {'type': FILTER_TYPE};
        $.ajax('/h_keywords_api', {params: params}).success(function(data){
            data = JSON.parse(data)
            var kws = [];
            for (kw in data) {
                if (data[kw] && data[kw].text) {
				    kws.push(data[kw].text);
                }
            }

            {% if freetext_readonly %}
                $('#id_resource-keywords').tokenfield({
                    createTokensOnBlur: true,
                    autocomplete: {
                        source: kws,
                        delay: 100
                    },
                    showAutocompleteOnFocus: true
                }).on('tokenfield:createtoken', function (event) {
                    var exists = false;
                    $.each(kws, function(index, value) {
                        if (event.attrs.value === value) {
                            exists = true;
                        }
                    });
                    if(!exists) {
                        event.preventDefault(); //prevents creation of token
                    }

                    var existingTokens = $(this).tokenfield('getTokens');
                    $.each(existingTokens, function(index, token) {
                        if (token.value === event.attrs.value)
                            event.preventDefault();  //prevents creation of token
                    });
                });
                // $('#id_resource-keywords').tokenfield('readonly');
                /* $('div.token .close').click(function() {
                    const token_close_button = $(this);
                    const token_item = token_close_button.parent();
                    token_item.remove();
                    return false;
                }); */
            {% else %}
                $('#id_resource-keywords').tokenfield({
                    createTokensOnBlur: true,
                    autocomplete: {
                        source: kws,
                        delay: 100
                    },
                    showAutocompleteOnFocus: true
                }).on('tokenfield:createtoken', function (event) {
                    var existingTokens = $(this).tokenfield('getTokens');
                    $.each(existingTokens, function(index, token) {
                        if (token.value === event.attrs.value)
                            event.preventDefault();  //prevents creation of token
                    });
                });
            {% endif %}

            if (window.location.href.match('/metadata_advanced$')) {
                /*if (!select_button_active) {
                    const select_button = $('<button id="id_freetext_keyword_select" class="btn btn-primary">Select</button>');
                    const select_button_parent = $('#id_resource-keywords').parent().parent();
                    select_button_parent.append(select_button);
                    select_button_active = true;
                }
                $('#id_freetext_keyword_select').click(function() {
                    $('#id_resource-keywords-tokenfield').blur().focus();
                });*/

                const resource_group = $('#id_resource-group');
                resource_group.empty();
                resource_group.append('<option value="">-----</option>');
                {% for group in metadata_author_groups %}
                    {% if resource.group == group.group %}
                        resource_group.append(
                            '<option value="{{ group.group.id }}" selected="selected">{{ group.group.name }}</option>'
                        );
                    {% else %}
                        resource_group.append(
                            '<option value="{{ group.group.id }}">{{ group.group.name }}</option>'
                        );
                    {% endif %}
                {% endfor %}
            }

            $('#treeview').treeview({
                color: "#428bca",
                expandIcon: "fa fa-folder",
                collapseIcon: "fa fa-folder-open",
                nodeIcon: "fa fa-tag",
                showTags: true,
                showIcon: true,
                showCheckbox: false,
                data: data,
                levels: 1,
                onNodeSelected: function($event, $data) {
                    var kws = $('#id_resource-keywords').tokenfield('getTokens');
                    var newToken = $data.text
                    var exists = false
                    for (var i=0; i<kws.length; i++) {
                        if (kws[i]['value'].indexOf(newToken) >=0) {
                            exists = true
                        }
                    }
                    if (!exists) {
                        $('#id_resource-keywords').tokenfield('createToken', $data.text);
                    }
                    // $('#treeview-toggle').click();
                }
            });

            $('#treeview-toggle').click((e, value) => {
              $('#treeview').toggle();
              var icon = $(this).find('i');
              icon.toggleClass('fa-folder').toggleClass('fa-folder-open');
            });
        });
    });
{% endautoescape %}
</script>
