//*******************************
var saveURI = "/common/save.php";
var cssURI = "/common/css_for_edit.php";
var rawURI = "/common/view.php?mode=raw&object=";
var contentURI = "/common/view.php?mode=content&object=";
var tinymceURI = "/common/tinymce/tiny_mce.js";
var closeIcon = "/common/icons/close.gif"

$(document).ready(function() {


	//****************************
	$(".embed").hover(
		function(e){
			if(e.shiftKey){
				$(this).attr("oldborder", $(this).css("border") );
				$(this).css({"border":"solid 1px red"});
				$(this).parents(".embed").css({"border":$(this).attr("oldborder") });
				var idd = $(this).attr("id");
				idd = idd.replace(/:/, "\/");
				$(this).prepend("<div class='stickynote' style='position:absolute; background-color:#DDD; font-size:small; border:solid 1px #777;'>"+idd+"</div>");
			}
		},
		function(e){
			$(".stickynote").remove();
			$(this).css({"border":$(this).attr("oldborder") });
		}
	);
	$("#main .embed").bind("dblclick", function(){
		//$("canvas").remove();
		var file = $(this).attr("id");
		file = file.replace(/:/g, "/");
		//alert($(this).html());
		// $(this).
		$(".content").load(rawURI+file, function(){ 
			edit($(".content"), cssURI, mysave, "no_edit", nonEditCallbackFunc);
		});
		return false;
	});
	

});


var dialogs=0;
//*******************************
function centerDialog(id){
	if($("#mask").length <=0){
		$(document.body).append("<div id='mask'></div>");
		$("#mask").css({"position":"absolute","left":0,"top":0,"zIndex":9000,"backgroundColor":"#000","display":"none"});
	}

	var maskHeight = $(document).height();
	var maskWidth = $(window).width();

	//Set heigth and width to mask to fill up the whole screen
	$('#mask').css({'width':maskWidth,'height':maskHeight});

	//transition effect		
	//$('#mask').fadeIn(1000);	
	$('#mask').fadeTo("slow",0.8);	

	//Get the window height and width
	var winH = $(window).height();
	var winW = $(window).width();

	//Set the popup window to center
	$("#"+id).css('top',  winH/2-$("#"+id).height()/2);
	$("#"+id).css('left', winW/2-$("#"+id).width()/2);

	//transition effect
	//$("#"+id).fadeIn(2000); 
	
}
//*******************************
function nonEditCallbackFunc(e){
	var htm = $(e.target).html();

	if( htm.substr(0,3) == "{{@"){
		$(document.body).append("<div><input type='text' id='dalink' value='"+htm+"' style='width:100%;' /></div>");
		$("#dalink").dialog()
	}else if( htm.substr(0,2) == "[[" || htm.substr(0,3) == "*[["){
		$(document.body).append("<div><input type='text' id='dalink' value='+htm+' /></div>");
		$("#dalink").dialog()
	}else{
		dialogEdit(e);
	}
}
//*******************************
function dialogEdit(e){
	var htm = $(e.target).html();
	var file = htm.replace(/{{|}}|[[|]]/g, "");
	var id = "modaly_"+(dialogs++);
	$(document.body).append("<div class='modal_fields jqDnR' id='"+id+"' style='z-index:9001;position:absolute;width:640px;'><div style='cursor:move; border:solid 1px red; background-color:#DDD;' class='jqHandle jqDrag'>"+htm+"</div><div class='embed'>"+htm+"</div></div>");

	centerDialog(id);
	
	$("#"+id+" > .embed").load(rawURI+file, function(){
	
		edit(this, cssURI, mysave, "no_edit", nonEditCallbackFunc);
		//$("#"+id).dialog({ width: 600,  });
		$("#"+id).jqDrag('.jqDrag');
		$('.jqDrag').bind('mousemove', function(e){ $(this).html(e.pageX+" "+e.pageY)});

	});

	
/*	tinyMCE.activeEditor.windowManager.open({
	   url : 'http://neu.out-in.ch',
	   width : 320,
	   height : 240
	}, {
	        // second object: additional parameters
	        inline: true, // only works if inlinepopups plugin is available
	        win: window, // might be useful to store the current window object somewhere
	        customArg: 'myCustomValue' // you can use this value in your popup
	});	
*/
}

//*******************************
function mysave(e, item){
	var postData = {};
	postData.id = $(item).attr("id");
	var file = postData.id.replace(/:/g, "/");
	postData.file = file;
	postData.editor = "tangerine";
	postData.data = e.getContent();
	
	e.remove();

	$.get(saveURI, {},
	  function(data, result){
		if(data=="OK" || data=="READY"){
		//alert(1);
			doSave(postData.id, file, postData);
		}else{
		//	alert(2);
			postData.username = "potenzial";
			postData.password = "haselnuss";
			doSave(postData.id, file, postData);
		}
	  });
}

//*******************************
function doSave(id, file, postData){

	$.post(saveURI, postData, function(data){ 
	//document.location.reload(); 
	/*alert("done");*//*$("#"+id+" > .embed").html(data);*/ });
//**??	tinyMCE.execCommand('mceRemoveControl', false, 'txaEditableContent');

//	var str = "";
//	for(var i in e){
//		str += " "+i;
//	}
//	alert(str);
}
//*******************************
function edit(item, css, saveFunc, nonEditClass, nonEditCallbackFunc){
	$(item).tinymce({
		// Location of TinyMCE script
		script_url : tinymceURI,
		language : "de",
	setup : function(ed) { 
		//ed.onClick.add( function(ed, e){ if( $(e.target).hasClass(nonEditClass) ){ nonEditCallbackFunc(e) } });
		//ed.onMouseover.add( function(ed, e){ if( $(e.target).hasClass(nonEditClass) ){ alert(1); } });
		ed.addButton('exit', {
			    title : 'exit',
			    image : closeIcon,
			    onclick : function(e) {
				alert(1);
				ed.remove();
				if($(item).parent().hasClass("modal_fields")){
					$(item).parent().remove();
					if( $(".modal_fields").length <=0){
						$("#mask").hide();
					}
				}
				//alert($(item).attr("id"));

				//ed.selection.setContent('<strong>Hello world!</strong>');

				//tinyMCE.execCommand('mceRemoveControl', false, item)
			    }
		});
	},
	save_enablewhendirty : true,
	save_onsavecallback : function(e){ saveFunc(e, item); },
	plugins : "inlinepopups,noneditable", /* aob */
	//noneditable_leave_contenteditable : true, /* aob */
	noneditable_noneditable_class: nonEditClass,
		// General options
		theme : "advanced",
		plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,searchreplace,print,contextmenu,paste,directionality,fullscreen,visualchars,nonbreaking,xhtmlxtras,template,advlist",

		// Theme options
		theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect,|,exit",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,forecolor,backcolor",
		theme_advanced_buttons3 : "tablecontrols,|,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,fullscreen",
		theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",

		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,

	dialog_type : "modal", /* aob */

		// Example content CSS (should be your site CSS)
		content_css : css,

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",
		convert_urls : false, /*aob*/
		valid_elements : '*[*]', /*aob*/
		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});

}
//*******************************

