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) {
        $.mobile.changePage( "products.html", {
          "transition": "slide",
          "allowSamePageTransition": true,
          "data": {
            "search": value
          }
        });
      };

      filter.on("filterablebeforefilter", function (e, data) {
        value = data.input.value;
        // stop JQM
        e.preventDefault();

        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.

          // and jIO
        }

      })
      .on( "filterablecreate", function( e, ui ) {
        var $el = $( e.target.previousSibling ),
          input = $el.find("input"),
          action = $el.find("a.ui-input-action");

        // 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) {
            e.preventDefault();
            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;
  }
);
