/**
 * Input replace script
 * (c) 2009 LBI Lost Boys
 */

(function($){
	var REG_INPUT     = /^input$/i,
		REG_SUBMIT    = /^submit$/i,
		REG_FILTER    = /\$([a-z]+)/mig,
		TYPE_STRING   = 'string',
		TYPE_FUNCTION = 'function',
		EVENT_CLICK   = 'click',
		EVENT_SUBMIT  = 'submit';

	function InputReplacer(input, settings) {
		$.extend(this, InputReplacerSettings, settings);
		if(
			!REG_INPUT.test(input.nodeName) || 
			!REG_SUBMIT.test(input.type) ||
			$(input).hasClass(this.replacedClass)
		){
			return;
		}
		
		var template = this.template, events = {};
		var buttonHtml = template.replace(REG_FILTER, function(match, attr){
			var attribute = input[attr] || '';
			switch (typeof attribute) {
				case TYPE_STRING: return attribute; break;
				case TYPE_FUNCTION:
					events[attr] = this.preserveInputScope? 
						function(e){ return attribute.call(input, e); } : attribute;
				break;
			}
		});

		var button = $(buttonHtml), jInput = $(input), jForm = $(input.form);
		if(this.copyInlineEvents) { $.extend(button[0], events); }
		if(this.onclick) { button.bind(EVENT_CLICK, this.onclick); }
		if(this.simulateInputClick) {
			button.bind(EVENT_CLICK, function(e){
				e.preventDefault();
				var sub = jForm.triggerHandler(EVENT_SUBMIT);
				if(sub !== false) {
					jInput.trigger(EVENT_CLICK);
				}
			});
		}
		
		jInput.addClass(this.replacedClass);
		jInput.after(button);
	}

	InputReplacerSettings = {
		template: '<a href="#" onclick="$onclick" rel="$name" class="button $className"><span>$value</span></a>',
		copyInlineEvents: false,
		preserveInputScope: true,
		simulateInputClick: true,
		replacedClass: 'replaced',
		onclick: null
	};

	$.fn.replaceInputs = function(settings) {
		for(var i=0; i<this.length; i++) {
			new InputReplacer(this[i], settings);
		}
		return this;
	};
})(jQuery);
