/*jslint node: true, nomen: true, unparam: true */
/*global jquery, $, _, define, Marionette, jqm, describe, it, expect, beforeEach, spyOn */

define([ 'Global', 'jquery.mobile-autocomplete',
	'Text!patient-search/templates/autocompleteList.html' ],
	function (Global, jqmAutocomplete, template) {
		'use strict';

		return Backbone.Marionette.CompositeView.extend({
			model: new Backbone.Model(),
			template: _.template(template),
			itemViewContainer: 'ul',
			collectionEvents: {
				'sync': 'refreshAutocomplete'
			},
			ui: {
				'autocompleteList': 'ul'
			},
			events: {
				'tap ul a': 'preventDefault',
				'keyup ul a': 'keyupList'
			},
			onRender: function () {
				var autocompleteCallback = this._autocomplete();

				this.ui.autocompleteList.accessibleautocomplete({
					'populateList': autocompleteCallback.populateList,
					'selectItem': autocompleteCallback.selectItem,
					'filterMinLength': 2,
					'filterReveal': true,
					'inset': true
				});
				this.$el.trigger('create');
			},
			refreshAutocomplete: function () {
				if (this._isRendered) {
					this.ui.autocompleteList.accessibleautocomplete('refresh');
				}
			},
			preventDefault: function (e) {
				e.preventDefault();
			},
			keyupList: function (e) {
				if (e.which === 13 || e.which === 32 || e.which === 39) {
					// Enter || Space Bar || Right Arrow
					e.preventDefault();
				}
			},
			_autocomplete: function () {
				var that = this,

					populateList = function (deferred, searchValue, list) {
						return deferred.resolve();
					},
					selectItem = function (search, item) {
						return;
					};

				return {
					populateList: populateList,
					selectItem: selectItem
				};
			}
		});
	});