$(function(){

  var formInfoGenerator = {
	getFormAttributes: function(dataElement) {
		return $(dataElement).data('form-attr');
	},
	
	getFormFields: function(dataElement) {
		return $(dataElement).data('form-fields');
	},
	
	getKeywordFieldName: function(dataElement) {
		return $(dataElement).data('keyword-field-name');
	},
	
	generate: function(dataElement, form, fieldCont, keywordField) {
		var formAttributes = this.getFormAttributes(dataElement),
			formFields = this.getFormFields(dataElement),
			keywordFieldName = this.getKeywordFieldName(dataElement),
			hiddenFieldsHtml = '',
			hiddenFieldsTpl = '<input type="hidden" name="{name}" value="{value}" />';
		
		if (formFields) {
			// Adding fields
			$.each(formFields, function(index, val) {
				hiddenFieldsHtml += hiddenFieldsTpl + "\n";
				hiddenFieldsHtml = hiddenFieldsHtml.replace('{name}', index).replace('{value}', val);
			});
			
			if (fieldCont) {
				$(fieldCont).html(hiddenFieldsHtml);
			}
			else {
				form.prepend(hiddenFieldsHtml);
			}
		}
		
		if (formAttributes) {
			// Adding attributes
			$.each(formAttributes, function(index, val) {
				$(form).attr(index, val);
			});
		}
		
		// Adding custom placeholder
		var placeholder = $(dataElement).data('placeholder') || 'Search ' + $(dataElement).html();
		$(dataElement).parents('form').find('input[type=search]').attr('placeholder', placeholder);
		
		// Adding keyword field
		$(keywordField).attr('name', keywordFieldName);
	}
  };
  
  $('#multiSearchForm a').click(function(e){
	e.preventDefault();
	formInfoGenerator.generate(this, '#multiSearchForm', '#multiSearchForm .hidden-fields', '#multiSearchForm #s');
	
	$('#multiSearchForm a').removeClass('active');
	$(this).addClass('active');
  });
  
  $('#multiSearchForm').submit(function(){
	if ($('#s').attr('name') == 'hash') {
		var url = $(this).attr('action'),
			hash = $('#s').val();
		
		location.href = url + '#' + hash;
		
		return false;
	}
  });

});

