/**
 * Search/filter form above the documents list. Displays its state accorfing to model SearchFormModel.
 * Modifies the attached model when user types something in the filter form.
 */
var SearchFormView = Backbone.View.extend({
	el: $('#search_form'),
	is_search: false,
	model: null, // SearchFormModel - model that contains keywords for filter
	search_keywords: '', // simple string with the current keywords for searching (not using special model in this case)
	delayed_filter_timeout: 500,

	events: {
		'change #search' : "onKeywordsChange",
		//'keydown #search' : "onType",
		'keyup #search' : "onType",
		'click .js-search-reset': 'reset',
		//'click .search-type-search': 'toggleSearchMode',
		//'click .search-type-filter': 'toggleSearchMode',
		'click .search-button': 'startSearch'
	},

	initialize: function ()
	{
		$('#search_form').bind('submit', jQuery.proxy(function () { return false; }, this));
	},

	render: function ()
	{
		this.$('#search').val(this.is_search ? this.search_keywords : (this.model ? this.model.get('keywords') : ''));
		this.$('.search-type-filter').toggle(!this.is_search);
		this.$('.search-type-search').toggle(this.is_search);
		this.$('.search-button').toggle(this.is_search);
	},

	// change model property when value in input element is changed
	onKeywordsChange: function ()
	{
		this.stopTimer();
		if (this.is_search)
			this.search_keywords = this.$('#search').val();
		else if (this.model)
			this.model.set({'keywords': this.$('#search').val()});
	},

	onType: function (event)
	{
		if (!this.is_search)
		{
			this.stopTimer();
			this.type_timer = window.setTimeout(function () { $(event.currentTarget).change(); }, this.delayed_filter_timeout);
		}
	},

	reset: function ()
	{
		this.stopTimer();
		if (this.is_search)
			this.search_keywords = '';
		else if (this.model)
			this.model.set({'keywords': ''});
		this.render();
	},

	setFilterModel: function (model)
	{
		if (model == null)
		{
			this.model = null;
			this.is_search = true;
		} else
		{
			if (!(this.model == model))
			{
				this.onKeywordsChange(); // save existing keywords into old model
				this.model = model;
			}
			if (model.get('keywords').length > 0)
				this.is_search = false;
		}
		this.render();
	},

/*	setSearchMode: function ()
	{
		this.is_search = true;
		this.render();
	},
*/
	stopTimer: function ()
	{
		if (this.type_timer)
			window.clearTimeout(this.type_timer);
		this.type_timer = null;
	}
});