$(function(){
	doCSS();
	doBind();
});

function doUnbind() {
	$("span.ajaxify").unbind('click');
}

function doBind() {
	$("span.ajaxify").click(function(){
		releaseAll();
		$(this).edit();
	});
}

function doCSS() {
	$("span.ajaxify").css({
		cursor:"pointer"
	});
	$("span.ajaxify.edited").css({
		color:"green"
	});
}

function releaseAll() {
	var editor = $("#ajaxify-current");
	editor.replaceWith("<span name='"+editor.attr('name')+"' class='ajaxify' title='"+editor.children('div#ov').attr('title')+"'>"+editor.children('div#ov').text()+"</span>")
	doCSS();
	doUnbind();
	doBind();
}
function release(e, title) {
	var editor = $("#ajaxify-current");
	editor.replaceWith("<span name='"+editor.attr('name')+"' class='ajaxify edited' title='"+title+"'>"+e+"</span>")
	doCSS();
	doUnbind();
	doBind();
}

$.fn.edit = function() {
	$(this).addClass('editing');
	
	// LOAD ACCEPT IMAGE
	
	var accept = "<img class='ajaxify-accept' src='/includes/js/accept.png' style='width:1em; padding-left:5px;cursor:pointer;' />";
	var cancel = "<img class='ajaxify-cancel' src='/includes/js/cancel.png' style='width:1em; margin-left:5px;cursor:pointer;' />";
	
	var type = $(this).attr('name');
	var title = $(this).attr('title'); // WE'LL NEED THIS TO REBUILD ON RELEASE FUNCTION
	var keys = parseKeys(title);	
	var value;
	
	switch(type) {
		case 'line':
			value = $(this).text();
			$(this).replaceWith('<div style="display:inline-block;" id="ajaxify-current" name="line"><input id="ajaxify-editbox" type="text" value="'+value+'" /><div style="display:none;" id="ov" title="'+title+'">'+value+'</div></div>');
			var ajaxifybox = $("input#ajaxify-editbox");
			ajaxifybox.focus().after(accept+cancel).keypress(function(ev){
				var keycode;
				if (window.event) keycode = window.event.keyCode;
				else if (ev) keycode = ev.which;
				if (keycode == 13){
   					var newvalue = ajaxifybox.val();
					$.ajax({
						type	: 'post',
						url		: '/includes/modules/'+keys.target+'/module.'+keys.target+'.ajaxify.php',
						data	: 'value='+newvalue+'&name='+keys.name,
						success : function(e) {
							// var e must return either new value (upon success) or original value...
							release(e, title);
						}
					});
    			}
			});
			
			// DO NEW BINDING
			
			accept = $("img.ajaxify-accept");
			cancel = $("img.ajaxify-cancel");
			cancel.click(function(){releaseAll();})
			accept.unbind('click').click(function(){
				var newvalue = ajaxifybox.val();
				$.ajax({
					type	: 'post',
					url		: '/includes/modules/'+keys.target+'/module.'+keys.target+'.ajaxify.php',
					data	: 'value='+newvalue+'&name='+keys.name,
					success : function(e) {
						// var e must return either new value (upon success) or original value...
						release(e, title);
					}
				});
			});			
		break;
		case 'area':
			value = $(this).html();
			$(this).replaceWith('<div style="display:inline-block;" id="ajaxify-current" name="area"><textarea id="ajaxify-editbox" type="text">'+value+'</textarea><div style="display:none;" id="ov" title="'+title+'">'+value+'</div></div>');
			load_tiny_mce();
			var ajaxifybox = $("textarea#ajaxify-editbox");
			ajaxifybox.focus().after(accept+cancel);
			
			// DO NEW BINDING
			
			accept = $("img.ajaxify-accept");
			cancel = $("img.ajaxify-cancel");
			cancel.click(function(){releaseAll();})
			accept.unbind('click').click(function(){
				tinyMCE.triggerSave(true,true);
				var newvalue = ajaxifybox.val();
				alert(newvalue);
				$.ajax({
					type	: 'post',
					url		: '/includes/modules/'+keys.target+'/module.'+keys.target+'.ajaxify.php',
					data	: 'value='+newvalue+'&name='+keys.name,
					success : function(e) {
						// var e must return either new value (upon success) or original value...
						release(e, title);
					}
				});
			});			
		break;
	}
}

function parseKeys(keys) {
	keys = keys.split('%');
	var output = {
		target  : keys[0],
		name	: keys[1]
	}
	return output;
}
function submitenter(e){
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return false;
	if (keycode == 13){
   		return true;
    } else return false;
}


function load_tiny_mce() {
	tinyMCE.init({
	mode : "textareas",
	theme : "advanced",
	plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,imagemanager,filemanager",
	skin: 'o2k7',
	// Theme options
	theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect",
	theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
	theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
	theme_advanced_buttons4 : "moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,|,visualchars,nonbreaking,blockquote,pagebreak,|,insertfile,insertimage",
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "left",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_resizing : true,
	content_css : "/includes/theme/te-styles.css",
	// Drop lists for link/image/media/template dialogs
	external_link_list_url : "/js/link_list.js",
	external_image_list_url : "/js/image_list.js",
	media_external_list_url : "/js/media_list.js"
});
}
