function edit_source(key) {
	var elem = document.id("html_"+key);
	if (!elem) return;

	new Request({
		url: "/ajax/get_html.php",
		onComplete: function(response) {
			elem.empty();
			var textarea = new Element("textarea", {
					id: 'editor',
					style: "width:100%;",
					text: response,
					rows: 20
				}).inject(elem);

			var ed = new tinymce.Editor('editor', {
					theme: "advanced",
					plugins: "table,imagemanager,advimage",
					theme_advanced_buttons1: "bold,italic,underline,strikethrough,formatselect,link,unlink,|,cut,copy,paste,pastetext,pasteword,|,bullist,numlist,outdent,indent,blockquote,hr,|,undo,redo,|,code",
					theme_advanced_buttons2: "tablecontrols,|,insertimage,image",
					theme_advanced_buttons3: "",
					theme_advanced_toolbar_location: "top",
					theme_advanced_toolbar_align: "left",
					theme_advanced_statusbar_location: "bottom",
					theme_advanced_resizing: true,
					theme_advanced_blockformats: "p,h1",
					content_css: "/styles/tinymce.css",
					save_callback: "save_editor",
					height: "500"
				});

			new Element("br").inject(elem);
			var button = new Element("input", {
					type: "button",
					value: "Save",
					events: {
						click: function() { save_source(key, elem, ed, button); }
					}
				}).inject(elem);
			new Element("span", {html:" or "}).inject(elem);
			var link = new Element("a", {
					href: "javascript:void(0);",
					text: "Cancel",
					events: {
						click: function() { load_markup(key, elem, link); }
					}
				}).inject(elem);

			ed.render();
		}
	}).post({"key":key});
}

function save_source(key, elem, ed, button) {
	button.disabled = true;
	button.setProperty("value", "Saving...");

	var source = ed.getContent();
	new Request({
		url: "/ajax/save_html.php",
		onComplete: function(response) {
			elem.setProperty("html", response);
		}
	}).post({"key":key, "source":source});
}

function load_markup(key, elem, link) {
	link.disabled = true;

	new Request({
		url: "/ajax/get_include_html.php",
		onComplete: function(response) {
			elem.setProperty("html", response);
		}
	}).post({"key":key});
}

