// Edit in place

$(document).ready(function(){
	setClickable();
});


function showEditBox(content) {
	obj = $('#editInPlace');
	
	content = stripslashes(content);
	
	var textarea = '<div><textarea class="AdminPageEdit_textarea">'+content+'</textarea>';
	var button	 = '<div><input type="button" value="SAVE" class="saveButton" /> OR <input type="button" value="CANCEL" class="cancelButton" />';
	button += '<span class="opendialog" id="adminModeAddLink">Ajouter un lien</span>';
	button += '</div></div>';
	var revert = obj.html();
	obj.after(textarea+button).remove();
	$('.saveButton').click(function(){saveChanges(this, false);});
	$('.cancelButton').click(function(){saveChanges(this, revert);});

	$("#adminModeAddLink").click(function() { // when clicking on a button
		adminDialog = setDialogType("adminModeAddLink","Add link","/");
		adminDialog.dialog('open');
	});
	
	$('.AdminPageEdit_textarea').elastic();
	$('.AdminPageEdit_textarea').indent();
}

function setClickable() {
	$('#editInPlace').dblclick(
						function() { 
							$.post(window.location.pathname,{ fetchContent: true },showEditBox); 
							})
					.mouseover(
						function() { $(this).addClass("editable"); })
					.mouseout(
						function() { $(this).removeClass("editable");});
};


function stripslashes(str) {
str=str.replace(/\\'/g,'\'');
str=str.replace(/\\"/g,'"');
str=str.replace(/\\0/g,'\0');
str=str.replace(/\\\\/g,'\\');
return str;
}

function saveChanges(obj, cancel) {
	if(!cancel) {
		var t = $(obj).parent().siblings(0).val();
		$.post(window.location.pathname,{
			content: t, updateContent: true
		},function(txt){
			//alert(txt);
			t = txt;
			updateDiv(t);
		}); /* ,"json" */
		$(obj).parent().parent().after('<div id="editInPlace">...</div>').remove();
	} else {
		var t = cancel;
		$(obj).parent().parent().after('<div id="editInPlace">'+t+'</div>').remove();
		setClickable();
	}
	//if(t=='') t='(click to add text)';
}

function updateDiv(content) {
	$('#editInPlace').after('<div id="editInPlace">'+content+'</div>').remove();
	setClickable();
}
