/*
 * jQuery Replace Buttons plug-in.
 * 
 * This plugin replaces submit buttons with styled links.
 * Copyright (c) 2009 Lost Boys NL.
 *
 * TODO: Add scope.
 */

(function($) {
	
	$.replaceButtons = {
		// default behaviour of the plug-in if settings are not provided.
		defaults: {
			// the plug-in replaces all submit buttons.
			selector:"input[type='submit']",
			// the mark-up that replaces the buttons.
			replacement:"<a href='#'>+value+</a>"
		}
	}
	
	$.fn.extend({
		// the function to call to replace the buttons you wish.
		replaceButtons: function(settings) {
			// If other settings are provided, override the dafaults.
			var settings = $.extend({}, $.replaceButtons.defaults, settings);
			// Get all the buttons.
			var buttons = getButtons(settings.selector);
			
			// Hide all the buttons at once.
			buttons.hide();
			
			// Declare re-usable variables.
			var btn,
				btnId, 
				btnClass, 
				btnTitle, 
				btnValue = null;
			
			// 
			var insert = null;
			
			// Loop through all the buttons.
			for (var i = 0; i < buttons.length; i++) {
				
				// the current button being replaced.
				btn = buttons.eq(i);
				
				// get all the attributes of the current button.
				btnId = btn.attr("id");
				btnClass = btn.attr("class");
				btnTitle = btn.attr("title");
				btnValue = btn.attr("value");
				
				// create a new replacement.
				insert = settings.replacement;
				insert = $(insert.replace('+value+', btnValue));
				
				// transfer all the attributes.
				btnId && insert.attr('id', btnId);
				btnClass && insert.attr('class', btnClass);
				btnTitle && insert.attr('title', btnTitle);
				
				// Bind behaviours to the insert.
				bindBehaviours(insert);
				
				// insert the styled button at the same
				btn.before(insert);
				
				// Reset the insert, to make sure it's empty.
				insert = null;
			}
		}
	});
	
	// Get all the buttons.
	function getButtons(selector) {
		return $(selector);
	}
	
	function bindBehaviours(insert) {
		// bind focus behaviour.
		insert.focus(function() {
			$(this).addClass('focus');
		});
		
		// bind blur behaviour.
		insert.blur(function() {
			$(this).removeClass('focus');
		});
		
		// bind click behaviour.
		insert.click(function(e) {
			$(this).parent().find('input[type=submit]').click();
			e.preventDefault();
		});
	}
	
})(jQuery);