/*global Ext*/

var acms = acms || { };

Ext.onReady(function() {
	var fn;
	acms.Search = {
		SearchField : Ext.get('search-field'),
		Submit      : Ext.get('search-button')
	};
	
	fn = function() {
		var val = '';
		
		this.getValue = function() {
			return val;
		};
		this.setValue = function(value) {
			val = value;
			this.setRawValue(value);
		};
		this.setRawValue = function(value) {
			this.dom.value = value;
		};
		this.getRawValue = function() {
			return this.dom.value;
		};
		
		this.setRawValue(acms.ls('SEARCHITEM'));
		
		this.on('focus', function() {
			if (this.getRawValue() != this.getValue()) {
				this.setRawValue(this.getValue());
			}
		}, this);
		
		this.on('blur', function() {
			val = this.getRawValue();
			if (this.getRawValue().length === 0) {
				this.setRawValue(acms.ls('SEARCHITEM'));
			}
		}, this);
		
		this.on('keypress', function(e) {
			if (e.getKey() == Ext.EventObject.RETURN) {
				acms.Search.Submit.focus();
				acms.Search.Submit.dom.click();
			}
		}, this);
		
	};
	fn.call(acms.Search.SearchField);
	
	acms.Search.Submit.on('click', function() {
		var val = acms.Search.SearchField.getValue(),
		    query = escape(val);
		
		if (query.indexOf('/') !== -1) {
			query = '?query=' + query;
		}
		
		if (val.length > 0) {
			window.location.href = acms.mkUrl('/search/' + query); 
		}
	});
});
