$(document).ready(function(){
	hoverable();
});

jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
	var op = $(this).css('opacity');
	return this.animate({opacity: op != 0.3 ? 0.3 : 1.0, height: 'toggle'}, speed, easing, callback);
};

function hoverable() {
	$(".hoverlink").hover(function(){
		$(this).prepend('<div class="editLink">[ <a href="javascript:">edit</a> ]</div>');
		
		$(".editLink").click(function(){
			var obj = $(this).siblings('.editIn');
			$('.editLink').remove();
			$(".hoverlink").unbind();
			
			edit(obj);
		});
		
	},function(){ 
		$('.editLink').remove();
	});
};

function edit(obj) {
	var textarea = '<div><textarea id="content" name="content" rows="15" cols="50">'+$(obj).html()+'</textarea>';
	var button	 = '<div style="margin-top: 10px; margin-right: 5px;"><input style="margin-right: 5px" type="button" value="save" class="saveButton" /> <input type="button" value="cancel" class="cancelButton" /></div></div>';
	var revert = $(obj).html();

	$(obj).after(textarea+button).slideFadeToggle('medium');
	$('.saveButton').click(function(){saveChanges(obj, '.saveButton', false);});
	$('.cancelButton').click(function(){saveChanges(obj, '.cancelButton', revert);});

	mceOn('content');
}

function saveChanges(div, obj, cancel) {
	mceOff('content');
	
	if(!cancel) {
		var t = $(obj).parent().siblings(0).val();
		
		$.post("/edit_news.php",{
		  content: t
		});
		
		$(div).parent().children('.changed').remove();
		$(div).parent().append('<div class="changed">Changes have been sent to the web team for approval.</div>');
	}

	hoverable();

	$(div).slideFadeToggle('medium');
	$(obj).parent().parent().remove();
}

