GY.search = (function(parent, $) {
	
	var self = parent.search = parent.search || {};
	
	self.init = function(target, options) {
		this.target = $(target);
		this.options = $.extend({
			animationDuration: 250, // time in MS it takes to animate
			defaultCollapse: true, // should form be collapsed by default?
			inputWrapper: '.input-wrapper' // wrapper around input
		}, options || {});
		
		this.inputWrapper = this.target.find(this.options.inputWrapper);
		this.inputWrapperWidth = this.inputWrapper.width();
		this.inputField = this.inputWrapper.find('input');
		this.isFocused = false;
		
		if(this.options.defaultCollapse) {
			this.inputWrapper.css('width', '0px');
			this.inputField.hide();
		}
		
		this.inputField.focusin(function() {
			self.isFocused = true;
		});
		
		this.inputField.focusout(function() {
			self.isFocused = false;
		});
		
		
		// outside clicks
		$(document.body).bind('click', function() {
			if(!self.isFocused && self.inputField.is(':visible')) {
				self.collapse();
			}
			
		});
		
		this.target.bind('click', self.__click);
		
		this.target.bind('submit', function(e) {
			e.preventDefault();
			if(self.inputField.val() !== '') {
				this.submit();
			}
		});
		
	};
	
	self.__click = function(e) {
		e.preventDefault();
		e.stopPropagation();
		self.expand();
	};
	
	self.expand = function() {
		// weird hack to make the input wrapper actually animate
		this.inputWrapper.css('width', '1px').animate({
			width: '130px'
		}, this.options.animationDuration, function(e) {
			self.inputField.show(); // show input field
			self.target.unbind('click'); // make submit button active again
		});
	};
	
	self.collapse = function() {
		self.inputField.hide(); // hide the input field
		// animate out the wrapper
		this.inputWrapper.animate({
			width: '0px'
		}, this.options.animationDuration, function(e) {
			self.target.bind('click', self.__click); // rebind the toggle expand / collapse button 
		});
		this.isFocused = false;
	};
	
	return self;
	
})(GY || {}, jQuery);
