var orig;
var content;

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function activateEdits() {
$('#menu').onselectstart = function() { return false; };
$('#menu').unselectable = "on";

$('#editor').hide();

$('.editable').dblclick(function() {
	if ($(this).attr('target') == "EditImage") {
		$('#imgeditor').css('margin-top', '-22px');
		$('#imgeditor').css('top', $(this).offset().top);
		$('#imgeditor').css('left', $(this).offset().left);
		$('#imgeditor').fadeIn("normal");
		$('#imgeditor input#path').val($(this).attr('src'))
		$('#imgeditor input#imgw').val($(this).attr('width'))
		$('#imgeditor input#imgh').val($(this).attr('height'))
		// alert("SETTING " + $('#imgeditor input#path').val())
	} else {
		var editor = tinyMCE.getInstanceById('editorform');
		if (editor == undefined) {
			tinyMCE.execCommand('mceAddControl', true, 'editorform');
			editor = tinyMCE.getInstanceById('editorform');
			return;
		}
		$('#editor').css('margin-top', '-22px');
		$('#editor').css('top', $(this).offset().top);
		$('#editor').css('left', $(this).offset().left);
		$('#editor #resource').empty().prepend($(this).attr('path'));
		$('#mce_editor_0').height($(this).height());
		$('#mce_editor_0').width($(this).width());
		$('.mceEditor').height($(this).height());

		orig = $(this);
		content = $(this).clone();
		$(':hidden', content).show();
		$('*', content).removeAttr('style');
		$('a.PlusMinus', content).remove();
		$('a.NoLink', content).remove();
		$('a.selected_menu_item', content).removeClass("selected_menu_item");
		$('div.hr2', content).before('<hr />').remove();

		tinyMCE.execCommand('mceSetContent', true, $(content).html());

		$('#editor').fadeIn("normal");
		editor.resizeToContent();
	}
});

$('.saveButton').click(function(){
	var editor = tinyMCE.getInstanceById('editorform');
	$('#editor').fadeOut("normal");

	atts = {};
	atts['path']  = content.attr('path');
	atts['save'] = 'Save';

	if (content.attr('attribute') == undefined) {
		atts['content'] = tinyMCE.getContent();
	} else {
		atts['attr.'+ content.attr('attribute')] = tinyMCE.getContent();
	}

	var target = '/Edit';
	if (content.attr('target') != undefined) {
		target = '/' + content.attr('target');
	}

	$.post(target, atts,
		function (data) { 	
			window.location.reload();
		});
});

$('.cancelButton').click(function(){
	var editor = tinyMCE.getInstanceById('editorform');
	$('#editor').fadeOut("normal");
	$('#imgeditor').fadeOut("normal");
	return false;
});
}

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