/*
* Part of the Collection Workflow Integration System (CWIS)
* Copyright 2015 Internet Scout Project
* http://scout.wisc.edu
*/

/**
* Create a new QuickSearch Object. Customizes the functionality of the generic
* jquery-ui-autocomplete to search a specific MetadataField (the FieldId param).
* @param ElementId String The html id of the input where the autocomplete should attach
* @param FieldId String The integer id of the MetaDataField associated with the input
* @param MultipleValues Boolean; if the field should accomodate multiple values
* @param CurrentValue string value to display for this field
* after it, or if we should deligate cloning to a later field.
*
* The QuickSearch requires HTML elements of the form generated by
* PrintQuickSearchField() defined in
* interface/default/include/F-PrintQuickSearchField.php
*
* Expects JSON responses from search handlers in either of these formats:
*
* failure (a single js object having 2 members):
*   {
*     success: false,
*     general_message: 'FAILURE MESSAGE HERE',
*   }
*
*
* success (an array of js objects each w/ 3 members):
*   [
*       { "label" : "HTML to display in the menu",
*         "value" : "Text to enter in search box when this item is selected",
*         "ItemId": ItemId
*        },
*   ]
*/

/**
* Set up quick search event handlers.
* @param Element el A div.cw-quicksearch to wire up.
*/
function QuickSearch(el) {
    // extract our fieldid and grab the elements we'll want to manipulate
    var fieldid = el.data('fieldid'),
        el_message = $(".cw-quicksearch-message", el),
        el_menu = $(".cw-quicksearch-menu", el),
        el_display = $('.cw-quicksearch-display', el),
        el_value = $('.cw-quicksearch-value', el);

    // set the prompt up to display when a user selects the dropdwon
    el_display.focus(function() {
        $(this).data('prev_value', $(this).val());

        if ($(this).val().trim().length == 0) {
            el_message.html(
                "Type some keywords to begin searching");
            el_message.show();
            el_menu.show();
        }
    });

    // when our search entry loses focus
    el_display.focusout(function() {
        // hide the container that shows search results
        el_menu.hide();

        // for keyword searches nothing else is needed
        if (fieldid === "KeywordSearch") {
            return;
        }

        // but for field value searches, check if we had a previous value
        if ($(this).data('prev_value') !== undefined) {
            // if the user didn't just clear the current value,
            // but didn't select a new one
            if ($(this).val().length > 0) {
                // reset to the last good value
                $(this).val( $(this).data('prev_value') );
            } else {
                el_value.val('');
            }

            // and forget the last value we had stored
            $(this).removeData('prev_value');
        }
    });

    // adjust the height of the autocomplete textareas to fit its content
    el_display.height(0);
    el_display.height(el_display.prop('scrollHeight'));

    // set up autocomplete widget
    el_display.autocomplete({
        minLength: 2,
        html: true,
        autoFocus: (fieldid !== "KeywordSearch"),
        response: function(event, ui) {
            if (ui.content.length == 0) {
                el_message.html("No results found for <i>" + event.target.value + "</i>.");
                el_message.show();
                el_menu.show();
            } else {
                el_message.hide();
            }
        },
        source: function (request, response) {
            el_message.html("Searching for <i>" + request.term + "</i>.");
            el_message.show();
            el_menu.show();

            // determine which page by the search type
            TgtPage = (fieldid == "KeywordSearch") ?
                "KeywordQuickSearchCallback" :
                ("MetadataFieldQuickSearchCallback&MF="+fieldid) ;
            jQuery.get(CWIS_BASE_URL+"index.php?P="+TgtPage+"&SS="+request.term, {
                query: request.term
            }, function (data) {
                ParsedResponse = JSON.parse(data);
                response(ParsedResponse);
            });

            // adjust the height of the autocomplete textareas to fit its content
            el_display.height(0);
            el_display.height(el_display.prop('scrollHeight'));
        },
        select: function (event, ui) {
            if (fieldid == "KeywordSearch") {
                var ItemId = ui.item.ItemId;
                // if a resource was clicked, jump to that resource
                if (ItemId.length > 0) {
                    event.preventDefault();
                    window.location.assign(
                        CWIS_BASE_URL + "index.php?P=FullRecord&ID="+ItemId.substring(1));
                    return false;
                }
            } else {
                event.preventDefault();

                // strip html, insert the value, remove our marker for the previous value
                var StrippedItem = ui.item.value.replace(/<\/?[^>]+(>|$)/g, "");
                el_value.val(ui.item.ItemId);

                el_display.val(StrippedItem);
                el_display.removeData('prev_value');

                // hide the menu
                el_menu.hide();

                // see if we have a template row to clone
                if ($(".cw-quicksearch-template"+
                      ".cw-quicksearch-fieldid-"+fieldid).length > 0) {
                    // determine if there are any empty containers aside from the
                    // template row
                    var have_empty = false;

                    $('.cw-quicksearch-display',
                      $('.cw-quicksearch-fieldid-'+fieldid).not('.cw-quicksearch-template')
                     ).each(function(ix){
                         if ($(this).val().length == 0) {
                             have_empty = true;
                             return false;
                         }});

                    // if there aren't any empty entries, create more
                    if (!have_empty) {
                        var new_row = $(".cw-quicksearch-template"+
                                        ".cw-quicksearch-fieldid-"+fieldid).clone();

                        // make it visible
                        new_row.attr("style","");
                        new_row.removeClass('cw-quicksearch-template');

                        // append it to our list of fields
                        $(".cw-quicksearch.cw-quicksearch-fieldid-"+fieldid).not(
                            ".cw-quicksearch-template").last().after( new_row );

                        // connect it to the machine
                        QuickSearch(new_row)
                    }
                }
            }

            // adjust the height of the autocomplete textareas to fit its content
            el_display.height(0);
            el_display.height(el_display.prop('scrollHeight'));
        },
        focus: function(event, ui) {
            event.preventDefault();
        },
        open: function(event, ui) {
            $('.cw-quicksearch-moreresults').parent().parent().css('padding',0);
        },
    });
}

// wire up all our quicksearch boxes
$(document).ready( function() {
    $('.cw-quicksearch').not(".cw-quicksearch-template").each(
        function(i){ QuickSearch($(this))});
});

/*
* jQuery UI Autocomplete HTML Extension
* start
*
* Copyright 2010, Scott Gonzalez (http://scottgonzalez.com)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* http://github.com/scottgonzalez/jquery-ui-extensions
*/
(function( $ ) {

var proto = $.ui.autocomplete.prototype,
  initSource = proto._initSource;

function filter( array, term ) {
  var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
  return $.grep( array, function(value) {
    return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
  });
}

$.extend( proto, {
  _initSource: function() {
    if ( this.options.html && $.isArray(this.options.source) ) {
      this.source = function( request, response ) {
        response( filter( this.options.source, request.term ) );
      };
    } else {
      initSource.call( this );
    }
  },

  _renderItem: function( ul, item) {
    return $( "<li></li>" )
      .data( "item.autocomplete", item )
      .append( $( "<span></span>" )[ this.options.html ? "html" : "text" ]( item.label ) )
      .appendTo( ul );
  }
});

})( jQuery );
/*
* jQuery UI Autocomplete HTML Extension
* end
*/
