// the EditorManager provides methods to manage (add/remove) editors on a page. 
// There is only allowed (at this time) to be one active editor per page. The current active
// will be deactivated before activating another.
EditorManager = {};
EditorManager.Manager = Class.create();	
EditorManager.Manager.prototype = {
	initialize: function() {	
		var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
		if(isIE6) {
			// dont do anything
 		} else {
			Event.observe(document, 'click', this.globalClickHandler.bind(this), false);
		}
	},
	activeEditor : null,
	editors : new $H(),
	toolbarClick: false,
	globalClickHandler: function(event) {
		// alert('in global click handler');
		var eventElemDiv = Event.findElement(event, 'div');
		var eventElemTable = Event.findElement(event, 'table');
		var eventNotesEditor = tinyMCE.activeEditor;
		var eventElemDivId = eventElemDiv.id;
		if(eventNotesEditor != null) {
			// alert('event elem div: ' + eventElemDivId);
			// alert('event span class name: ' + eventElemTable.className);
			if(!eventNotesEditor.Editor.isHidden) {
				if(eventElemDiv.id != '3Message' && eventElemDiv.id != 'messageComponent_richText' && eventElemDivId.indexOf('messageComponent') == -1) {
					// alert('event span class name: ' + eventElemTable.className);
					if(!hasClassName(eventElemTable, 'mceColorSplitMenu') && eventElemDivId.length > 0) {
						var content3 = tinyMCE.activeEditor.getContent();
						// alert(content3);
						// alert(content3.length);
						// alert(' in unedit');
						this.unedit(this.activeEditor);
					}
				}
			}
		}
	},
	getEditor : function(elementId, options) {
		var editor = this.editors[elementId];
		if( editor == null ) {
			editor = new EditorManager.Editor(elementId, options);
			// this will show the "DONE" control when editor is showing
			editor.showCallback = function(elId, showCtrl) {
				var el = $('edit_' + elId);
				if( el != null ) {
					el.innerHTML = 'DONE';
				}
			}
			// this will show the "EDIT" control when editor is hiding
			editor.hideCallback = function(elId, showCtrl) {
				var el = $('edit_' + elId);
				if( el != null ) {
					el.innerHTML = 'EDIT';
				} 
			}
			this.editors[elementId] = editor;

		}
		if( editor.isDynamic() ) {
			this.registerForEvents(elementId);				    
		}
		return editor;
	},
	registerForEvents: function(elementId) {
		Logger.logDebug('registerForEvents');
		if( elementId == null || $(elementId) == null ) return;
		Event.observe(elementId, 'click', this.observerCallback, false);
		
		// if the only child of the element is a div, register with that one as well
		var children = $(elementId).childNodes;
		if( children != null && children.length > 0 ) {
			var child = children[0];
			if( child.nodeName == 'div' || child.nodeName == 'DIV' ) {
				Event.observe(child, 'click', this.observerCallback, false);				
			}
		}
	},
	observerCallback: function(event){
		Logger.logDebug('observerCallback:');
    	var element = event.target || event.srcElement;
    	if( element == null ) return;
    	try {
			Logger.logDebug('id='+element.id+', element='+element);
	        while(!editorManager.editById(element.id)) {
				// try the parent node
				element = element.parentNode;
				if( element == null ) break;
			}
    	} catch(ex) {

    	}
	},
	unregisterForEvents: function(elementId) {
		Logger.logDebug('unregisterForEvents: '+elementId);
		if( elementId == null )	return;
		Event.stopObserving(elementId, 'click', this.observerCallback);
		
		// if the only child of the element is a div, unregister with that one as well
		var children = $(elementId).children;
		if( children != null && children.length == 1) {
			var child = children[0];
			if( child.name == 'div' || child.name == 'DIV' ) {
				Event.stopObserving(child, 'click', this.observerCallback);				
			}
		}

	},
	toggleEdit : function(elementId, options) {
		var editor = this.getEditor(elementId, options || {});
		if(editor.hidden) {
			this.edit(editor);
		} else {
			this.unedit(editor);	
		}
	},
    editById : function(elementId) {	
		Logger.logDebug('editById:'+elementId);
		if( elementId == null || elementId == '') return false;
		this.unregisterForEvents(elementId);	
		
   		var editor = this.editors[elementId];
		if( editor != null ) {
			return this.edit(editor);
		}
		return false;
    },
    edit : function(editor) {
		if(this.activeEditor != null) {
		Logger.logDebug('entering edit');
			this.unedit(this.activeEditor);
		}

		this.activeEditor = editor;
		
		editor.show();
		
		var toolbar = document.getElementsByClassName('mceToolbar')[0];
		Event.observe(toolbar, 'mousedown', (function(event) {
					editorManager.toolbarClick = true;
					Event.stop(event);
					setTimeout( function() { editorManager.toolbarClick = false; }, 1000);					
					return false;
   				}).bind(this),
			false
		);
	 },
	 uneditById : function(elementId) {
		var editor = this.editors[elementId];
		if( editor != null && (!tinyMCE.isMSIE || !this.toolbarClick)) {
			this.unedit(editor);
		}
		this.toolbarClick = false;
	 },
	 unedit : function(editor) {
		Logger.logDebug('entering unedit: activeEditor='+this.activeEditor+', editor='+editor);
	 	if( editor == null || this.toolbarClick || !editor.isDynamic() ) return;
	 	// convertWord();
		this.activeEditor = null;

		editor.hide();
		if( !editor.isInitialValue() ) {
			editor.updateToChangedClass();
			
			if( editor.originalFgColor != null ) {
				$(editor.elementId).style.color = editor.originalFgColor;
			}
		}
		setTimeout( (function() {
				this.registerForEvents(editor.elementId);
			}).bind(this), 10);
	 }, 
	 contentChanged: function(inst) {
	 	var editorId = inst.formTargetElementId;
	 	var editor = this.editors[editorId];

	 	
	 	//propagate the event to the editor itself
		if( editor != null ) {
	 		editor.contentChanged(inst);
		}
	 }
}

// Editor class, encapsulates and hides the specific rich editor implemenation (in this case tinyMCE)
EditorManager.Editor = {};
EditorManager.Editor = Class.create();	
EditorManager.Editor.prototype = {
	firstFocus: true,
	controls: "link,bold,italic,underline,justifyleft,justifycenter,justifyright,forecolor,backcolor",
	baseOptions: new $H({
		 theme : "advanced",
		 plugins : "inlinepopups",
		 theme_advanced_layout_manager : "RowLayout", 
		 relative_urls : false,
		 safari_warning : false
	}),
	initialize: function(elementId, options) {
//		if( BrowserInfo.isIE() ) {
			this.baseOptions['plugins'] = '';
//		}
		this.elementId = elementId;
		this.hidden = true;
		this.options = options || {};
		

		if( this.isDynamic() ) {				
			this.setupInitialValue();
		}
	},
	isInitialValue: function() {
		var initialValue = this.options['initialValue'];
		var value = $(this.elementId).innerHTML;
		return( (initialValue != null) && (value == '' || value == initialValue) );
	},
	setupInitialValue: function() {
		if( $(this.elementId) == null ) return;
		if( this.isInitialValue() ) {
			Element.update(this.elementId, this.options['initialValue']);
			this.originalFgColor = $(this.elementId).style.color;
		}
	},
	updateToChangedClass: function() {
		var changedClass = this.options['changedClass'];		

		if( changedClass != null ) { 
			Element.classNames(this.elementId).set(changedClass);
		}
	},
	show : function() {
		// alert('in show editor');
		this.init();
		tinyMCE.execCommand('mceAddControl', null, this.elementId);
		this.hidden = false;		
		tinyMCE.execCommand('mceFocus', null, this.elementId);		
		this.showCallback(this.elementId);
		// select all
		this.selectAll();
		this.firstFocus = false;
		
		this.sendTrackingInfo();
	},
	sendTrackingInfo : function() {
		if( !this.sentTrackingInfo ) {
			 Tracker.sendTrackingEvent(this.elementId);
			 this.sentTrackingInfo = true;
		}	
	},
	isDynamic: function() {
		return (this.options['dynamic'] == true);	
	},
	hide : function() {
		tinyMCE.execCommand('mceRemoveControl', null, this.elementId);	
		this.hideCallback(this.elementId);
		this.hidden = true;				
	},
	selectAll: function() {
		if( !this.firstFocus ) return;
		setTimeout( function() {
			if( tinyMCE.selectedInstance != null ) {
				tinyMCE.execCommand('selectall', false, this.elementId);
			}
		}, 100);
	},
	init : function() {
		var allOptions = new $H().merge(this.baseOptions);
		 allOptions = allOptions.merge( {
		     theme_advanced_containers : "top1,mceEditor",
		     theme_advanced_containers_default_class : "mceToolbar",
		     theme_advanced_containers_default_align : "center",
		     theme_advanced_container_top1 : this.controls,
		     force_br_newlines : false,
		     force_p_newlines : false,
		     convert_newlines_to_brs : true,
		     relative_urls : false
	     } );

		var height = this.options['height'];
		if( height != null ) allOptions['height'] = height;
		
		var width = this.options['width'];
		if( width != null ) allOptions['width'] = width;
		
		allOptions['onchange_callback'] = 'editorManager.contentChanged';
		
		this.characterCounterDivId = this.options['characterCounterDivId'];
		this.maxChars = this.options['maxChars'] || -1;	
		
		var vwmGuestModule = getURLParam('vwmModuleId');
		
		var uagent = navigator.userAgent.toLowerCase();
		var ffVersion = uagent.indexOf("firefox") > -1;
		var isWindowsBox = uagent.indexOf("win") > -1;
		
		if(vwmGuestModule == 'guestmodule') {
			if(ffVersion && isWindowsBox) {
				tinyMCE.init({
					mode : "none",
					theme : "advanced",
					force_br_newlines : true,
        			forced_root_block : '',
		    		force_p_newlines : false,
		    		convert_newlines_to_brs : false,
		    		relative_urls : false,
		    		plugins : "inlinepopups, safari, paste2",
		    		paste_use_dialog : false,
		    		paste_create_paragraphs : false,
					paste_create_linebreaks : false,
					paste_convert_middot_lists : false,
					paste_unindented_list_class : "unindentedList",
					paste_convert_headers_to_strong : true,
					paste_remove_styles: true,
		    		theme_advanced_buttons1 : "bold,italic,underline,justifyleft,justifycenter,justifyright",
		    		theme_advanced_fonts : "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sand;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva",
		    		theme_advanced_buttons2 : "",
            		theme_advanced_buttons3 : "",
		    		theme_advanced_toolbar_location : "top",
		    		theme_advanced_toolbar_align : "center"
				});
			} else {
				tinyMCE.init({
				mode : "none",
				theme : "advanced",
				force_br_newlines : true,
        		forced_root_block : '',
		    	force_p_newlines : false,
		    	convert_newlines_to_brs : false,
		    	relative_urls : false,
		    	plugins : "inlinepopups, safari, paste",
		    	paste_use_dialog : false,
		    	paste_create_paragraphs : false,
				paste_create_linebreaks : false,
				paste_convert_middot_lists : false,
				paste_unindented_list_class : "unindentedList",
				paste_convert_headers_to_strong : true,
				paste_remove_styles: true,
		    	theme_advanced_buttons1 : "bold,italic,underline,justifyleft,justifycenter,justifyright",
		    	theme_advanced_fonts : "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sand;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva",
		    	theme_advanced_buttons2 : "",
            	theme_advanced_buttons3 : "",
		    	theme_advanced_toolbar_location : "top",
		    	theme_advanced_toolbar_align : "center"
				});
			}
		} else {
			if(ffVersion && isWindowsBox) {
				tinyMCE.init({
					mode : "none",
					theme : "advanced",
					force_br_newlines : true,
        			forced_root_block : '',
		    		force_p_newlines : false,
		    		convert_newlines_to_brs : false,
		    		relative_urls : false,
		    		plugins : "inlinepopups, safari, paste2",
		    		paste_use_dialog : false,
		    		paste_create_paragraphs : true,
					paste_create_linebreaks : true,
					paste_convert_middot_lists : true,
					paste_unindented_list_class : "unindentedList",
					paste_convert_headers_to_strong : true,
					paste_remove_styles: true,
		    		theme_advanced_buttons1 : "link,bold,italic,underline,justifyleft,justifycenter,justifyright,forecolor,fontselect,fontsizeselect",
		    		theme_advanced_fonts : "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sand;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva",
		    		theme_advanced_buttons2 : "",
            		theme_advanced_buttons3 : "",
		    		theme_advanced_toolbar_location : "top",
		    		theme_advanced_toolbar_align : "center"
		    		
				});
			} else {
				tinyMCE.init({
					mode : "none",
					theme : "advanced",
					force_br_newlines : true,
        			forced_root_block : '',
		    		force_p_newlines : false,
		    		convert_newlines_to_brs : false,
		    		relative_urls : false,
		    		plugins : "inlinepopups, safari, paste",
		    		paste_use_dialog : false,
		    		paste_create_paragraphs : true,
					paste_create_linebreaks : true,
					paste_convert_middot_lists : true,
					paste_unindented_list_class : "unindentedList",
					paste_convert_headers_to_strong : true,
					paste_remove_styles: true,
		    		theme_advanced_buttons1 : "link,bold,italic,underline,justifyleft,justifycenter,justifyright,forecolor,fontselect,fontsizeselect",
		    		theme_advanced_fonts : "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sand;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva",
		    		theme_advanced_buttons2 : "",
            		theme_advanced_buttons3 : "",
		    		theme_advanced_toolbar_location : "top",
		    		theme_advanced_toolbar_align : "center"
				});
			}
		}
		// tinyMCE.init(allOptions);
	},
    contentChanged: function(inst) {
    	if( this.maxChars == -1 ) return;
		var body = inst.getBody().innerHTML || '';
		var len = body.length;
		var lenLeft = this.maxChars - len;
	    if( lenLeft <= 0 ) {
			body = body.substring(0, this.maxChars-1);
			inst.setContent(body);
			lenLeft = 0;
		}
		
    	if( this.characterCounterDivId == null ) return;
		Element.update( this.characterCounterDivId, lenLeft+'' );
    },
    getValue: function() {
    	if( this.hidden ) {
    		return $(this.elementId).innerHTML;
    	} else {
			return tinyMCE.activeEditor.getContent();
		}
    },
    setValue: function(value) {
    	if( this.hidden ) {
    		return Element.update(this.elementId, value);
    	} else {
			return tinyMCE.activeEditor.setContent(value);
		}
    },
	// these are just stubs, meant to be overridden
	showCallback : function(elementId, showControls) {},
	hideCallback : function(elementId, showControls) {}
}


// set up a (page) singleton for the editorManager
var editorManager = new EditorManager.Manager();
new EditorManager.Editor('', false).init();

// HasClassName
//
// Description : returns boolean indicating whether the object has the class name
//    built with the understanding that there may be multiple classes
//
// Arguments:
//    objElement              - element to manipulate
//    strClass                - class name to add
//
function hasClassName(objElement, strClass) {
   // if there is a class
   if ( objElement.className ) {
      // the classes are just a space separated list, so first get the list
      var arrList = objElement.className.split(' ');

      // get uppercase class for comparison purposes
      var strClassUpper = strClass.toUpperCase();

      // find all instances and remove them
      for ( var i = 0; i < arrList.length; i++ ) {
         // if class found
         if ( arrList[i].toUpperCase() == strClassUpper ) {
            // we found it
            return true;
         }
      }
   }
   // if we got here then the class name is not there
   return false;
   }
// 
// HasClassName
// ----------------------------------------------------------------------------

// Function getURLParam
function getURLParam(strParamName) {
	var strReturn = "";
  	var strHref = window.location.href;
  	if ( strHref.indexOf("?") > -1 ) {
    	var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    	var aQueryString = strQueryString.split("&");
    	for ( var iParam = 0; iParam < aQueryString.length; iParam++ ) {
      		if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        		var aParam = aQueryString[iParam].split("=");
        		strReturn = aParam[1];
        		break;
      		}
    	}
  	}
  	return unescape(strReturn);
} 

function convertWord() {
	alert('in convert word');
	var eventNotesEditorContent = tinyMCE.activeEditor.getContent();
	alert(eventNotesEditorContent);
	eventNotesEditorContent = eventNotesEditorContent.replace(/<!(?:--[\s\S]*?--\s*)?>\s*/g, '');
	tinyMCE.activeEditor.setContent(eventNotesEditorContent);
}




