



// te is the tinyMCE instance
var te = null;
// mce iframe element
var mce_iframe = null;
// Set to true if user has been shown the "You have unsaved changes" prompt
var noSavePrompt = false;
var mceCharLimit = -1;

function initGuiEditor(mceSetupMode,mceWidth,mceHeight, isEdit, isVideo, guiAllowAttach) {
	var buttons2 =  "fontselect,fontsizeselect,forecolor";
	if (!isEdit && !isVideo)
		buttons2 += ",lwspell";
	buttons2 += ",code";
	buttons2 += ",separator,emotions";
	buttons2 += ",image";
	if (guiAllowAttach) 
		buttons2 += ",attach";
	tinyMCE.init({	
		
		/* 
			Use setup: none if embedding tinyMCE in jQuery dialog - if you do this, 
			you must then calltinyMCE.execCommand('mceAddControl', false, 'post-textarea') to render the editor once the dialog is opened
		*/
		mode : mceSetupMode,
		elements : "post-textarea",
		theme : "advanced",
		plugins : "emotions,attach,media,lwspell",
		width: mceWidth,
		height: mceHeight,
		theme_advanced_buttons1 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,link,unlink",
		theme_advanced_buttons2 : buttons2,
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_path : false,
		valid_elements : "+a[id|rel|rev|charset|hreflang|dir|lang|tabindex|accesskey|type|name|href|target|title],strong/b,-em,i,strike,u,p[class=mce-p|id|dir|align],ol,ul,li,br,img[id|dir|lang|longdesc|usemap|src|border|alt=|title|hspace|vspace|width|height|align|class],-sub,-sup,-blockquote[dir],-table[border=0|cellspacing|cellpadding|width|height|align|summary|dir|id|lang|bgcolor|background|bordercolor],-tr[id|lang|dir|rowspan|width|height|align|valign|bgcolor|background|bordercolor],tbody[id],thead[id],tfoot[id],-td[id|lang|dir|colspan|rowspan|width|height|align|valign|bgcolor|background|bordercolor|scope],-th[id|lang|dir|colspan|rowspan|width|height|align|valign|scope],caption[id|lang|dir],span[align|style],-pre[align],address[align],-h1[id|dir|align],-h2[id|dir|align],-h3[id|dir|align],-h4[id|dir|align],-h5[id|dir|align],-h6[id|dir|align],hr[class],-font[face|size|id|dir|color],dd[id|title|dir|lang],dl[id|title|dir|lang],dt[id|title|dir|lang]",
		extended_valid_elements: "div[id|dir|align],object[width|height],param[name|value],embed[src|type|wmode|width|height|flashvars|salign|quality|bgcolor|name|id]",
		/*
			If media_use_script is set to true, it will use js to display embedded media (requires standard/scripts/tiny_mce_embed.js)
			However, this will break if the word break filter is enabled since the script writes a single long line of js
		*/
		//media_use_script : true,
		/*
			if not using js to display flash, set media_strict: false otherwise <embed> doesn't get written
		*/
		media_strict : false,
		// set convert_newlines_to_brs: false otherwise we get <br /> tags on newlines (can also be caused by LW newline filter!!)
		convert_newlines_to_brs : false,
		content_css: "/merge/scripts/tiny_mce/lw_mce_editor_content.css",
		setup : function(ed) {
			if (guiAllowAttach) {
					ed.onInit.add(function(ed,e) {
						if (isEdit) { 
								// only get attachment list if user is editing - if new post attachment list generated in mce-attachlist-window
								getAttachmentList();
						} 
					  	mce_iframe = $('post-textarea_ifr');
					});
					
					if (isEdit) { 
							/*
								To help prevent "orphaned images", add click event to <a> elements, then 
								check if user has made changes to the editor before leaving (gmail-esque)
								
								Orphaned images can occur when a user edits a message with an attachment embedded in the body. If the attachment
								is deleted but the message body isn't saved (the user navigates away, refreshes, clicks "Cancel"), the body will still contain the reference to the nonexistent attachment
							*/
							jQuery('a').bind('click',function(e) {
								// Check to see if the <a> is a javascript call - if it is we don't want to pop the confirm
								var jsLink = e.target.href.indexOf('javascript:') > -1;
								if(!jsLink && tinyMCE.activeEditor.isDirty()) {
									var noSave = confirm('You have unsaved changes in your post.\nClick "OK" to continue.\nClick "Cancel" to stay on this page.');
									if(!noSave) {
										// User clicked "Cancel" so stay on the page
										e.preventDefault();
									}						
								}
							});
							
							jQuery('#postform-doCancel').bind('click',function(e) {
								if(!noSavePrompt && tinyMCE.activeEditor.isDirty()) {
									var noSave = confirm('You have unsaved changes in your post.\nClick "OK" to continue.\nClick "Cancel" to stay on this page.');
									if(!noSave) {
										// User clicked "Cancel" so stay on the page
										e.preventDefault();
									}						
								}
							});
							
							
					} 
      			} 
      			
      		// Check to see if there's a character limit imposed on the editor (/elements/groups/post-edit-body.jsp)
					if(mceCharLimit > 0) {
						/* 
							Store previous editor contents
							If charLimitReached = true, replace content with previous editor content
						*/
						var charLimitReached = false;
						var previousContent = '';
						var bm;	// stores cursor bookmark
						ed.onKeyUp.add(function(ed,e) {
							// Get raw editor contents (don't include HTML tags as characters)
							var edContents = ed.getContent({format : 'raw'});
							// Strip tags tinyMCE has added
							var plainTextEdContents = edContents.stripTags();
							var numChars = plainTextEdContents.length;
							if(numChars >= mceCharLimit) {
								if(charLimitReached) {
									// charLimitReached would have been set to true on the last keyup
									ed.setContent(previousContent);
									ed.selection.moveToBookmark(bm);
								}
								// Save editor contents
								previousContent = ed.getContent({format : 'raw'});
								charLimitReached = true;
								// keep cursor at the end of the content
								bm = ed.selection.getBookmark();
							} else if(numChars < mceCharLimit) {
								charLimitReached = false;
							}
						});
					
					}
      		// Set te to the editor instance
      		te = ed; 
   		}
	});
	
	/*
		Set width of attachments window if it exists based on width of mce editor
		First get the padding inside the attachments window so we can subtract it from the width
	*/
	if (guiAllowAttach) { 
		jQuery(document).ready(function() {
			var attachWindow = jQuery('#tinymce-attachlist-window');
			if(attachWindow.length > 0) {
				if(jQuery.support.boxModel) {
					// Subtract padding & border to get the correct width if not IE quirks mode
					var attachPaddingBorder = parseInt(attachWindow.css('padding-left').substring(0,2)) + parseInt(attachWindow.css('padding-right').substring(0,2)) + parseInt((attachWindow.outerWidth() - attachWindow.innerWidth()));
					attachWindow.width(mceWidth - attachPaddingBorder);
				} else {
					attachWindow.width(mceWidth);
				}
			}
		});
	} 
}
