
/**
Handles the appearance and layout of the top part with search and filter/address buttons.
Handles search input, but not filter/address button events - these are handled by LayoutView.
*/
var ControlsView = Backbone.View.extend({

	router: undefined,
	templates: undefined,
	template: undefined,
	
	initialize : function(options) {

		this.router = options.router;
		this.templates = options.templates;
		this.template = _.template(this.templates.app.form); // compiles template

		this._initInterface();
	},
	
	events : {
		"submit #searchForm" : "_search",
		"click #searchForm .form-reset" : "_reset",
		"keyup| #searchForm .form-input" : "_redrawCancelButton",
		"change #searchForm .form-input" : "_redrawCancelButton"
	},

	render: function(screenMode, screenModes) {
	
		this._resize(screenMode, screenModes);

		return this;
	},
	
	setSearch: function(value) {
		if (value === undefined) {
			value = '';
		}
		this.$('.form-input').val(value).change();
	},
	
	_initInterface: function() {
		// render template
		var content = this.template();
		this.el.html(content);
	},
	
	_redrawCancelButton: function() {
		var value = self.$('.form-input').val();
		$('.form-reset', self.el).css({
			//display: (value !== '') ? 'inline-block' : 'none'
			display: 'inline-block'
		});
	},
	
	_resize: function(screenMode, screenModes) {
		if (!screenMode) {
			return;
		}
		
		
		var placeholder;
		if (screenMode === CONSTANTS.screenModes.HANDHELD) {
			placeholder = _.template(this.templates.app.placeholder_short)();
		} else {
			placeholder = _.template(this.templates.app.placeholder)();
		}
		this.$('.form-input').attr('placeholder', placeholder);
		
		var width;
		if (screenMode !== CONSTANTS.screenModes.DESKTOP) {
			// update input field width
			var buttonsWidth = this.$('.lbButtonSet').width();
			width = this.el.width() - buttonsWidth - parseInt($('#searchForm', this.el).css('margin-right'), 10);
		} else {
			width = 400;
		}
		$('fieldset', this.el).css({
			width: width
		});
		$('.form-input', this.el).css({
			width: width
		});
		$('#searchForm').css({
			width: width
		});
	},
	
	_search: function(event) {
		//stop the form from submitting
		event.preventDefault();
		var val = this.$('.form-input').val();
		this.router.navigate(val, true);
	},
	
	_reset: function() {
		
		this.router.navigate('_', true);
	}
	
});
