define([
    'app'
  , 'text!searchbar.html!strip'
  , 'css!searchbar'
  ],
  function (App, source) {
    var response = {};

    response.data = source;
    response.callback = function (self) {
      var filter = self.dom.find(".searchbar_filter"),
        value, runSearch;

      runSearch = function (value) {
        // only go to search.html, if we are currently not on it, else only trigger hashchange
        $.mobile.changePage( "search.html", {
          "transition": "slide",
          "data": {
            "search": value
          }
        });
      };

      filter.on("filterbarbeforefilter", function (e, data) {
        value = data.input.value;

        if ( value ) {
          // now we can autocomplete...
          // this should also run from JIO
          // whatever happens should take into account presets
          // like sorting criteria or filters set!

          // we have two actions
          //  > display suggestions listitems with a checkbox
          //  > user can check, then it will be a delete
          //  > checked items will be... moved to input, kept in suggestions
          // second action is user hitting search button
          //  > this searches, clears the autocomplete
          //  start with this!

          // question will be how to store information...
          // if we follow the DC scheme, we have some core metadata and the
          // rest must be stored in an attachment.
        }
      })
      .on( "filterbarcreate", function( e, ui ) {
        var uuid = $(e.target).data("mobileFilterbar").uuid,
          target = $("#ui-filter-"+uuid),
          action = target.find(".ui-input-action"),
          input = target.find("input");

        // TODO: search should be run here and results should be passed to
        // items or ?. Otherwise items has to listen for ... something, grab
        // data from somewhere and query. This makes more sense here.
        action.on("click", function(e) {
          runSearch(input.val());
        });

        input.on("keypress", function (e) {
          if (e.which == 13) {
            runSearch(input.val());
          }
        });
      });



      if (App === undefined) {
        def = new $.Deferred;

        def.done(function(gadget) {
          // prefix instance-ids, pass JSON
          App.renderGadgets(gadget);
        });

        window.fallbackLoader.deferreds.push(def);
        window.fallbackLoader.args.push(self);
      } else {
        // prefix instance-ids, pass JSON
        App.renderGadgets(self);
      }
    };

  // return response object
  return response;
  }
);
