/**
 * Plugin for fixing problems that occur when instances of the
 * tinymce control get moved around in the document tree
 */
dynamiclist_addPlugin ({

/**
 * Properties
 */

_aInstances : null,

/**
 * Public Functions
 */

// afterAddNode
// auto-enable instances that should start off enabled
afterAddNode : function (node) {
	var a = this._findAutoEnableMCE(node);
	this._toggleMCE(a);
},

// beforeMoveNode
// disable all currently enabled instances
beforeMoveNode : function (node) {
	//alert('beforeInsertNode');
	//if (document.all) {return;}
	this._aInstances = this._findEnabledMCE(node);
	this._toggleMCE(this._aInstances);
},

// afterMoveNode
// re-enable the previously disabled instances
afterMoveNode : function (node) {
	//alert('afterInsertNode');
	//if (document.all) {return;}
	this._toggleMCE(this._aInstances);
	this._aInstances = null;
},

/**
 * Private Functions
 */

// _findMCE
// return an array of all MCE instances
_findMCE : function (node, result) {
	var i, a, o, mce;
	if (!result) {result = [];}

	a = node.childNodes;
	for (i=0; i < a.length; i++) {
		o = a[i];
		if (o.nodeType == 1) {
			if (o.id && o.id.substr(0,8) == "wysiwyg4") {
				result.push(o);
			}
			this._findMCE(o, result);
		}
	}		

	return (result);
},

// _findEnabledMCE
// return an array of enabled MCE instances
_findEnabledMCE : function (node) {
	var i, a, o, mce, result;
	if (!result) {result = [];}

	a = this._findMCE(node);
	for (i=0; i < a.length; i++) {
		o = a[i];
		mce = document.getElementById("edit-" + o.id.substr(8));
		if (tinyMCE.getEditorId(mce.name) != null) {
			result.push(o);
		}
	}		

	return (result);
},

// _findAutoEnableMCE
// return an array of MCE instances that are disabled, but should start off enabled
_findAutoEnableMCE : function (node) {
	var i, a, o, mce, result;
	if (!result) {result = [];}

	a = this._findMCE(node);
	for (i=0; i < a.length; i++) {
		o = a[i];
		mce = document.getElementById("edit-" + o.id.substr(8));
		if ( 	(o.innerHTML.substr(0,7) == 'disable') && 
					(tinyMCE.getEditorId(mce.name) == null) ) {
			result.push(o);
		}
	}	

	return (result);	
},

// _toggleMCE
// toggle (enable / disable) each MCE instance passed in
_toggleMCE : function (a) {
	var i, sID;
	if (a) {
		for (i=0; i < a.length; i++) {
			sID = a[i].id;
			mceToggle("edit-" + sID.substr(8), sID);
		}
	}
}

/**
 * End of plugin definition
 */

}); 
