/**
 *
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
(function($) {
	/**
	 * adds an "execute code" link to the specified elements
	 * to allow execution of sample JavaScript code that is
	 * contained in <pre> tags inside the specified elements
	 *
	 * sample markup:
	 *
	 * <div class="code executable">
	 * <pre>// attaching to multiple textareas,
	 * // using the default options, except for max
	 * $("#myTextArea, #myTextArea2").charCounter(1000);</pre>
	 * </div>
	 *
	 * sample CSS:
	 * .code {
	 * 	background-color: #eee;
	 * 	border: 1px solid #999;
	 * 	line-height: 1.1em;
	 * 	margin: 1em 0;
	 * 	padding: 5px;
	 * 	width: 500px;
	 * }
	 * .code pre {
	 * 	clear: left;
	 * 	margin: 0;
	 * }
	 * .execute {
	 * 	background-color: #fff;
	 * 	border: 1px solid #999;
	 * 	border-width: 0 1px 1px 0;
	 * 	float: left;
	 * 	font-size: 11px;
	 * 	margin: -5px 0 10px -5px;
	 * 	padding: 0 5px;
	 * }
	 * .execute a {
	 * 	color: red;
	 * 	text-decoration: none;
	 * }
	 *
	 * usage: $(".executable").executable( {text: "&raquo; execute code", classname: "execute"} );
	 * 
	 */
	 
	$.fn.executable = function(settings){
		settings = $.extend({
			text: "&raquo; execute code",
			classname: "execute"
		}, settings);
		
		function execute(el) {
			var source = $(el).children("pre").html();
			source = source.replace(/&lt;/g, "<");
			source = source.replace(/&gt;/g, ">");
			source = source.replace(/&quot;/g, "\"");
			source = source.replace(/&amp;/g, "&");
			try {
				eval(source);
				$(el).children(".execute").remove();
			} catch(err) {
				alert(err);
			};
			return false;
  		};
  
		return this.each(function() {
			var me = this;
			$(this).prepend('<p class="' + settings.classname + '"><a href="#")">' + settings.text + '</a></p>');
			$(this).children("." + settings.classname + " a")
				.bind("click", function() {
					execute(me);
					$(this).unbind("click");
					return false;
				});
		});
	};
	
})(jQuery);