/*
 * Observe tinyMCE editor for changes
 *
 * @example new Form.Element.tinyMCE_Observer('editor_id',1,callback);
 * This will check the editor_id every second for content changes and
 * execute the callback function if the content has changed.
 */
Form.Element.tinyMCE_Observer = Class.create(Abstract.TimedObserver, {
	getValue: function() {
		// The first check happens before tinyMCE transforms the textareas to editors.
		// The unidentified check prevents the javascript error.
		return (tinyMCE.get(this.element.id) == undefined) ? '' : tinyMCE.get(this.element.id).getContent();
	}
});

Object.extend(Form.Element.tinyMCE_Observer.prototype, {
	registerCallback: function() {
		this.intervalId = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
	},
	stop: function() {
		if (this.intervalId) clearInterval(this.intervalId);
	}
});

/**
 * 
 */
var tinyMCE_config = Class.create();
tinyMCE_config.prototype = {
	initialize: function(){
		this.debug = false;
		
		// default settings
		this.options = {
			accessibility_focus             : false,
			cleanup_on_startup              : true,
			convert_fonts_to_spans          : true,
			convert_urls                    : false,
			debug                           : this.debug,
			document_base_url               : window.domain.reverse().replace(/^(?!\/)/, '/').reverse(), // idea from http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript
			fix_list_elements               : true,
			gecko_spellcheck                : true,
			invalid_elements                : "script",
			language                        : window.iso_lang,
			mode                            : 'specific_textareas',
			theme                           : 'advanced',
			font_size_style_values          : "xx-small,x-small,small,medium,large,x-large,xx-large",
			paste_create_paragraphs         : false,
			paste_create_linebreaks         : false,
			paste_use_dialog                : true,
			paste_auto_cleanup_on_paste     : true,
			paste_convert_middot_lists      : false,
			paste_unindented_list_class     : "unindentedList",
			paste_convert_headers_to_strong : true,
			relative_urls                   : false,
			remove_script_host              : false,
			strict_loading_mode             : true,
			theme_advanced_toolbar_align    : 'left',
			theme_advanced_toolbar_location : 'top',
			
			save_callback : function(element_id, html, body) {
				return html.replace(/<!--.*?-->/g,''); // strip comments
			},
			
			setup : function(ed) {
				var buttons, plugins;
				
				if ($(ed.id).hasClassName("tinymce_wiris")) {
					buttons = ed.settings.theme_advanced_buttons2.split(",");
					plugins = ed.settings.plugins.split(",");
					
					buttons.push("|","tiny_mce_wiris_formulaEditor","tiny_mce_wiris_CAS");
					plugins.push("tiny_mce_wiris");
					
					ed.settings.theme_advanced_buttons2 = buttons.join(",");
					ed.settings.plugins                 = plugins.join(",");
					ed.settings.height                  = "400";
				}
				
				if ($(ed.id).hasClassName("tinymce_image")) {
					buttons = ed.settings.theme_advanced_buttons2.split(",");
					plugins = ed.settings.plugins.split(",");
					
					buttons.push("|","image","insertimage");
					plugins.push("advimage","imagemanager","media");
					
					ed.settings.theme_advanced_buttons2 = buttons.join(",");
					ed.settings.plugins                 = plugins.join(",");
				}
				
				if ($(ed.id).hasClassName("tinymce_width")) {
					ed.settings.width = $(ed.id).getWidth();
				}
				
				if ($(ed.id).hasClassName("tinymce_height")) {
					ed.settings.height = $(ed.id).getHeight();
				}
				
				ed.addButton('kcContribution', {
					title : languages.get_text('kc_contribution'),
					image : '/template/default/img/kc_tinymce_forum.png',
					onclick : function test() {
						var obj_nr = window.prompt(languages.get_text('enter_object_id'), '');
						
						if (isNum(obj_nr) && obj_nr != 0) {
							var html = '<strong><a href="'+window.domain+'/'+obj_nr+'">'+get_object_title(obj_nr)+'</a></strong>';
							ed.selection.setContent(html);
						}
						else if (obj_nr !== null) {
							test();
						}
					}
				});
			}
		};
		
		//basic
		tinyMCE.init(this.basic());
		
		// inline edit
		tinyMCE.init(this.inline_edit(false));
		
		tinyMCE.init(this.inline_edit(true));
		
		//mail
		tinyMCE.init(this.mail());
		
		//contribution
		tinyMCE.init(this.contribution());
	},
	
	contribution: function(){
		var editor_selector = 'tinymce_contribution',
		    buttons_row1 = ["bold", "italic", "underline", "|",
		                    "sub", "sup", "|",
		                    "justifyleft", "justifyright", "justifycenter", "|",
		                    "pastetext", "removeformat", "|",
		                    "bullist", "numlist", "|",
		                    "outdent", "indent", "blockquote","|",
		                    "undo", "redo", "|",
		                    "link", "unlink", "kcContribution"],
		    buttons_row2 = ["code", "|", "charmap"],
		    buttons_row3 = [],
		    height = "200",
		    width  = "100%";
		
		var plugins = ["advhr", "advlink", "paste", "noneditable"];
		
		return this._getOptions(editor_selector, height, width, [buttons_row1, buttons_row2, buttons_row3], plugins);
	},
	
	inline_edit: function(isSmall){
		var editor_selector = "";
		var buttons_row1 = [];
		var buttons_row2 = [];
		var buttons_row3 = [];
		var plugins = [];
		var height = '';
		var width = '100%';
		
		if(isSmall){
			editor_selector = "tinymce_inline_edit_small";
			buttons_row1 = ["bold", "italic", "underline", "fontsizeselect", "forecolor", "backcolor", "|"];
			buttons_row2 = ["link", "unlink", "|",
			                "outdent", "indent", "|",
			                "bullist", "numlist", "|",
			                "undo", "redo", "|",
			                "code"];
		}else{
			editor_selector = "tinymce_inline_edit";
			buttons_row1 = ["bold", "italic", "underline", "fontsizeselect", "forecolor", "backcolor", "|",
			                "link", "unlink", "|",
			                "outdent", "indent", "|",
			                "bullist", "numlist", "|",
			                "undo", "redo", "|",
			                "pastetext", "removeformat"];
			buttons_row2 = ["emotions", "image", "insertimage", "|",
			                "code"];
		}
		
		plugins = ["advhr", "advlink", "paste", "emotions", "advimage", "media", "imagemanager"];
		
		delete this.options.invalid_elements;
		
		return this._getOptions(editor_selector, height, width, [buttons_row1, buttons_row2, buttons_row3], plugins);
	},
	
	basic: function(){
		var editor_selector = "tinymce_basic";
		var height = '200';
		var width ='100%';
		
		var buttons_row1 = ["bold", "italic", "underline", "sub", "sup", "|", 
		                     "justifyleft", "justifycenter", "justifyright", "|",
		                     "paste", "pastetext", "|",
		                     "link", "unlink", "|",
		                     "bullist", "numlist", "|",
		                     "undo", "redo", "|",
		                     "emotions", "code", "kcContribution"];
		var buttons_row2 = [];
		var buttons_row3 = [];
		
		var plugins = ["paste", "emotions"];
		
		return this._getOptions(editor_selector, height, width, [buttons_row1, buttons_row2, buttons_row3], plugins);
	},
	
	mail: function(){
		var editor_selector = "tinymce_mail";
		var height = '500';
		var width = '100%';
		
		var buttons_row1 = ["save", "newdocument", "|",
		                    "bold", "italic", "underline", "sub", "sup", "|", 
		                    "justifyleft", "justifycenter", "justifyright", "|",
		                    "paste", "pastetext", "|",
		                    "link", "unlink", "|",
		                    "bullist", "numlist", "|",
		                    "undo", "redo", "|",
		                    "emotions", "code", "kcContribution"];
		var buttons_row2 = ["styleselect", "formatselect", "fontselect", "fontsizeselect", "forecolor", "backcolor", "|",
		                    "charmap", "media", "image", "insertimage", "|",
		                    "cite", "visualchars"];
		
		var buttons_row3 = ["table", "|",
		                    "row_props", "cell_props", "|",
		                    "row_before", "row_after", "delete_row", "|",
		                    "col_before", "col_after", "delete_col", "|",
		                    "split_cells", "merge_cells", "|",
		                    "advhr", "fullscreen", "|",
		                    "visualaid", "print"];
		
		var plugins = ["contextmenu", "print", "visualchars", "save", "advhr", "advlink", "paste", "emotions", "table", "advimage", "imagemanager", "media", "fullscreen", "xhtmlxtras"];
		
		return this._getOptions(editor_selector, height, width, [buttons_row1, buttons_row2, buttons_row3], plugins);
	},
	
	_getOptions: function(editor_selector, height, width, toolbars, plugins){
		var options = this.options;
		
		if(this.debug){
			console.group("Build tinyMCE");
			console.debug("editor_selector: " + editor_selector);
			console.debug("height: " + height);
			console.debug("width: " + width);
			toolbars.each(function(toolvar,i){
				console.debug("toolbar "+(i+1)+" : " + toolvar);
			});
			console.debug("plugins: " + plugins);
			console.groupEnd();
		}
		
		options.editor_selector = editor_selector;
		
		options.height = height;
		options.width = width;
		
		// buttons
		toolbars.each(function(toolbar,i){
			var option_name = "theme_advanced_buttons"+(i+1);
			options[option_name] = toolbar.join(",");
		});
		
		// plugins
		options.plugins = plugins.join(",");
		
		if(this.debug){
			console.debug(options);
		}
		
		return options;
	}
};
