/**
 * attach fckeditor for selected textarea
 * @package macem page
*/

var d = document;

var Editor = {

  loadNewInstance: function (textareaName, toolbar, width, height, configfile) {
		if (this.checkInstance(textareaName) == false) {
			var newinstance = new FCKeditor (textareaName, width|null, (height||400), (toolbar||'Custom'));
			newinstance.BasePath = '/app/wysiwyg/fckeditor/';
			newinstance.Config['CustomConfigurationsPath'] = configfile ? ('../' + configfile) : ('../fckconfig.js');
			newinstance.Config['textAreaName'] = textareaName;
			newinstance.ReplaceTextarea();
		}
	},
	
	setContent: function (textarea, html) {
    if (window.parent.FCKeditorAPI && window.parent.FCKeditorAPI.__Instances[textarea])
      FCKeditorAPI.GetInstance(textarea).SetHTML(html);
	},
	
	getContent: function (textarea) {
    if (window.parent.FCKeditorAPI && window.parent.FCKeditorAPI.__Instances[textarea])
      return FCKeditorAPI.GetInstance(textarea).GetXHTML();
	},

	updateContent: function (parent, className) {
    var editables = dom.byClassName (parent, className, 'textarea');
    for (var i = 0; i < editables.length; i++) {
      editables[i].value = Editor.getContent (editables[i].name);
    }
  },
  
	checkInstance: function (textarea) {
    if (!window.parent.FCKeditorAPI || !window.parent.FCKeditorAPI.__Instances[textarea])
			return false;
		return true;
	},
	
	getInstance: function (textarea) {
    if (window.parent.FCKeditorAPI && window.parent.FCKeditorAPI.__Instances[textarea])
      return FCKeditorAPI.GetInstance(textarea);
		return false;
	},

	_removeInstance: function (textarea) {
    if (window.parent.FCKeditorAPI && window.parent.FCKeditorAPI.__Instances[textarea])
      delete window.parent.FCKeditorAPI.__Instances[textarea];

		if (window.parent.FCKeditorAPI.__Instances.length == 0)
		  delete window.parent.FCKeditorAPI;
	},
	
	destroyInstance: function (textareaId, textarea) {
    if (this.checkInstance(textarea) == true) {
			var elem = d.getElementById( textareaId);
			var iframe = d.getElementById (textarea + "___Frame");
			if(iframe) iframe.style.display = "none";
			var input = d.getElementById (textarea + "___Config");
			if(input) input.style.display = "none";
      elem.value = this.getContent (textarea, "xhtml");
			elem.style.display = "block";
			this._removeInstance(textarea);
		}
	}
}

// fckeditor external function
function FCKeditor_OnComplete (editorInstance) {
	editorInstance.Events.AttachEvent('OnFocus', FCKeditor_OnFocus);
}

// fckeditor external function
function FCKeditor_OnFocus (editorInstance) {
	if (document.getBoxObjectFor!=null) {
    editorInstance.EditorDocument.designMode = "on"; // FF bug
	  editorInstance.Focus();
	}
}
