// global var for current editor
var edit = null;

// for mode change
var numfields = 0;
var editors = new Array();
var names = new Array();
var configs = new Array();

var tagCrStart = new Array();
tagCrStart["body"] = 1;
tagCrStart["table"] = 1;
tagCrStart["tbody"] = 1;
tagCrStart["tr"] = 1;
tagCrStart["td"] = 0;
tagCrStart["p"] = 0;
tagCrStart["hr"] = 1;
tagCrStart["ul"] = 1;
tagCrStart["ol"] = 1;
tagCrStart["li"] = 0;
tagCrStart["form"] = 1;
tagCrStart["blockquote"] = 1;

var tagCrEnd = new Array();
tagCrEnd["body"] = 1;
tagCrEnd["table"] = 1;
tagCrEnd["tbody"] = 1;
tagCrEnd["tr"] = 1;
tagCrEnd["td"] = 0;
tagCrEnd["p"] = 0;
tagCrEnd["br"] = 0;
tagCrEnd["ul"] = 1;
tagCrEnd["ol"] = 1;
tagCrEnd["li"] = 0;
tagCrEnd["form"] = 1;
tagCrEnd["blockquote"] = 1;

function makeConfig(style,preset) {
  // create configuration object
  config = new HTMLArea.Config();


// Mediadb and Linkman buttons
config.registerButton({
  id        : "linkmanager",
  tooltip   : "Linkmanager",
  image     : "/htmlarea/images/ed_link.gif",
  textMode  : false,
  action    : function(editor, id) {
                edit=editor;
                openwin('popups/system_linkman_new.php?lm[types]=<?=urlencode("file:,ftp:,gopher:,http:,https:,mailto:,news:,telnet:,wais:") ?>&callback=main.insert_link',800,550,'resizable=1,scrollbars=1,status=yes');
              }
});

config.registerButton({
  id        : "Media Manager",
  tooltip   : "Media Manager",
  image     : "/htmlarea/images/ed_Media Manager.gif",
  textMode  : false,
  action    : function(editor, id) {
		edit=editor;
                openwin('popups/system_media_popup_new.php?show=popup&data[callback_func]=main.insert_media',1000,680,'resizable=1,scrollbars=1')
              }
});

  // Toolbar config

  if (preset=='fullEditor') {
      if (HTMLArea.is_ie) {
          config.toolbar = [[ "unorderedlist", "orderedlist", "outdent", "indent", "separator",
                      "justifyleft", "justifycenter", "justifyright", "justifyfull", "separator",
                      "bold", "italic", "underline", "separator",
                      "subscript", "superscript", "space", "separator",
                      "inserthorizontalrule", "linkmanager", "Media Manager", "inserttable" ]
                  ];
	  } else {
          config.toolbar = [[ "undo", "redo", "separator",
                      "unorderedlist", "orderedlist", "outdent", "indent", "separator",
                      "justifyleft", "justifycenter", "justifyright", "justifyfull", "separator",
                      "bold", "italic", "underline", "separator",
                      "subscript", "superscript", "space", "separator",
                      "inserthorizontalrule", "linkmanager", "Media Manager", "inserttable" ]
                  ];
	  }
  } else if (preset=='miniEditor') {
	  config.toolbar = [[ "bold", "italic", "underline", "separator",
			      "space",
			      "linkmanager", "Media Manager" ]
			  ];
  } else if (preset=='simpleEditor') {
      if (HTMLArea.is_ie) {
          config.toolbar = [[ "bold", "italic", "underline", "separator",
                      "subscript", "superscript", "space", "separator",
                      "linkmanager", "Media Manager" ]
                  ];
      } else {
          config.toolbar = [[ "undo", "redo", "separator",
                      "bold", "italic", "underline", "separator",
                      "subscript", "superscript", "space", "separator",
                      "linkmanager", "Media Manager" ]
                  ];

      }
  } else {
      if (HTMLArea.is_ie) {
          config.toolbar = [[ "unorderedlist", "orderedlist", "outdent", "indent", "separator",
                      "justifyleft", "justifycenter", "justifyright", "justifyfull", "separator",
                      "bold", "italic", "underline", "separator",
                      "subscript", "superscript", "space", "separator",
                      "inserthorizontalrule", "linkmanager", "Media Manager", "inserttable" ]
                  ];
	  } else {
          config.toolbar = [[ "undo", "redo", "separator",
                      "unorderedlist", "orderedlist", "outdent", "indent", "separator",
                      "justifyleft", "justifycenter", "justifyright", "justifyfull", "separator",
                      "bold", "italic", "underline", "separator",
                      "subscript", "superscript", "space", "separator",
                      "inserthorizontalrule", "linkmanager", "Media Manager", "inserttable" ]
                  ];
	  }
  }

  // No statusbar, we need undo ;)
  config.statusBar=false;

  // Css
  config.pageStyle = "@import url(" + style + ");\n@import url(/htmlarea/helper.css);";

  return config;
}

function replaceArea(id,config,preset) {

  // create an editor for the "content" textbox
  editor = new HTMLArea(id,config);

  // register the FullPage plugin
//  editor.registerPlugin(FullPage);

if (preset=='fullEditor') {

  // register the Table plugin
  editor.registerPlugin(TableOperations);

}

if ((preset=='fullEditor') || (preset=='normalEditor')) {

  // register the ListType plugin
  editor.registerPlugin(ListType);

  // add a contextual menu
  editor.registerPlugin("ContextMenu");

}

  // register the CSS plugin
  editor.registerPlugin(DynamicCSS);

  // Save the editor object for later use
  editors[numfields]=editor;
  names[numfields]=id;
  configs[numfields]=config;

  // increase field counter
  numfields++;

  return false;
}


function insert_link(link) {

  // Linkmanager check
  if ( link != '') {

    // is something selected ?
    if (edit.getSelectedHTML()!='') {

      // make a link
      var end_link=link.indexOf("Link");
      edit.surroundHTML(link.substr(0,end_link),'</a>');

    } else {

      // insert linked "LINK"
      edit.insertHTML(link);
    } 
  }
}

function insert_media(insert,prefix,suffix) {
  if (insert!='')
    edit.insertHTML(insert);

  if (prefix!='') {
    // is something selected ?
    if (edit.getSelectedHTML()!='') {

      // make a link
      edit.surroundHTML(prefix,suffix);

    } else {

      // insert
      edit.insertHTML(prefix + 'Medialink' + suffix);
    }
  }
}


// Set mode of editor
function setMode(id,mode) {

  // Call the method for the right editor
  for(i=0;i<numfields;i++) {
    if (id==names[i])
      editors[i].setMode(mode);
  }

  // hilight buttons
  if (mode=='wysiwyg') {
    document.getElementById('wysiwyg_' + id).src='/rsys_aimageserv/richedit/wysiwyg_active.gif';
    document.getElementById('textmode_' + id).src='/rsys_aimageserv/richedit/html_inactive.gif';
  } else {
  document.getElementById('wysiwyg_' + id).src='/rsys_aimageserv/richedit/wysiwyg_inactive.gif';
    document.getElementById('textmode_' + id).src='/rsys_aimageserv/richedit/html_active.gif';
  }

}

function generate() {

  // generate editors
  for(i=0;i<numfields;i++) {
      editors[i].generate();
  }

}

function transferHTML(delay) {

  // read html code from editors
	for(i=0;i<numfields;i++) {
		if (typeof(editor[i]) != "undefined")
			editor[i]._textArea.value=editors[i].getHTML();
	}
	
	setTimeout(transferHTML,delay);
}

HTMLArea.getRedSYSHTMLWrapper = function(root, outputRoot, editor, tab) {
	var html = "";
	switch (root.nodeType) {
	    case 1: // Node.ELEMENT_NODE
	    case 11: // Node.DOCUMENT_FRAGMENT_NODE
		var closed;
		var i;
		var root_tag = (root.nodeType == 1) ? root.tagName.toLowerCase() : '';
		if (outputRoot)
			outputRoot = !(editor.config.htmlRemoveTags && editor.config.htmlRemoveTags.test(root_tag));
		if (HTMLArea.is_ie && root_tag == "head") {
			if (outputRoot)
				html += "<head>";
			// lowercasize
			var save_multiline = RegExp.multiline;
			RegExp.multiline = true;
			var txt = root.innerHTML.replace(HTMLArea.RE_tagName, function(str, p1, p2) {
				return p1 + p2.toLowerCase();
			});
			RegExp.multiline = save_multiline;
			html += txt;
			if (outputRoot)
				html += "</head>";
			break;
		} else if (outputRoot) {
			closed = (!(root.hasChildNodes() || HTMLArea.needsClosingTag(root)));
			html = "";
			if (root_tag != "" && typeof(tagCrStart[root_tag]) != "undefined") {
				if (tagCrStart[root_tag] == 1)
					html += "\n";
				for (i=1; i<=tab; i++)
					html += "\t";
			}
			html += "<" + root.tagName.toLowerCase();
			var attrs = root.attributes;
			for (i = 0; i < attrs.length; ++i) {
				var a = attrs.item(i);
				if (!a.specified) {
					continue;
				}
				var name = a.nodeName.toLowerCase();
				if (/_moz_editor_bogus_node/.test(name)) {
					html = "";
					break;
				}
				if (/_moz|contenteditable|_msh/.test(name)) {
					// avoid certain attributes
					continue;
				}
				var value;
				if (name != "style") {
					// IE5.5 reports 25 when cellSpacing is
					// 1; other values might be doomed too.
					// For this reason we extract the
					// values directly from the root node.
					// I'm starting to HATE JavaScript
					// development.  Browser differences
					// suck.
					//
					// Using Gecko the values of href and src are converted to absolute links
					// unless we get them using nodeValue()
					if (typeof root[a.nodeName] != "undefined" && name != "href" && name != "src" && !/^on/.test(name)) {
						value = root[a.nodeName];
					} else {
						value = a.nodeValue;
						// IE seems not willing to return the original values - it converts to absolute
						// links using a.nodeValue, a.value, a.stringValue, root.getAttribute("href")
						// So we have to strip the baseurl manually -/
						if (HTMLArea.is_ie && (name == "href" || name == "src")) {
							value = editor.stripBaseURL(value);
						}
					}
				} else { // IE fails to put style in attributes list
					// FIXME: cssText reported by IE is UPPERCASE
					value = root.style.cssText;
				}
				if (/(_moz|^$)/.test(value)) {
					// Mozilla reports some special tags
					// here; we don't need them.
					continue;
				}
				html += " " + name + '="' + value + '"';
			}
			if (html != "") {
				html += closed ? " />" : ">";
				if ((typeof(tagCrStart[root_tag]) != "undefined" && tagCrStart[root_tag] == 1) || (closed && typeof(tagCrEnd[root_tag]) != "undefined"))
					html += "\n";
			}
			tab += 1;
		}
		for (i = root.firstChild; i; i = i.nextSibling) {
			html += HTMLArea.getRedSYSHTMLWrapper(i, true, editor, tab);
		}
		if (outputRoot)
			tab -= 1;
		if (outputRoot && !closed) {
			if (typeof(tagCrEnd[root_tag]) != "undefined" && tagCrEnd[root_tag] == 1) {
				for (i=1; i<=tab; i++)
					html += "\t";
			}
			html += "</" + root.tagName.toLowerCase() + ">";
			if (typeof(tagCrEnd[root_tag]) != "undefined")
				html += "\n";
		}
		break;
	    case 3: // Node.TEXT_NODE
		// If a text node is alone in an element and all spaces, replace it with an non breaking one
		// This partially undoes the damage done by moz, which translates '&nbsp;'s into spaces in the data element
		if ( !root.previousSibling && !root.nextSibling && root.data.match(/^\s*$/i) )
			html = '&nbsp;';
		else
			html = /^script|style$/i.test(root.parentNode.tagName) ? root.data : HTMLArea.htmlEncode(root.data);
		break;
	    case 4: // Node.CDATA_SECTION_NODE
		// FIXME: it seems we never get here, but I believe we should..
		//        maybe a browser problem?--CDATA sections are converted to plain text nodes and normalized
		// CDATA sections should go "as is" without further encoding
		html = "<![CDATA[" + root.data + "]]>";
		break;
	    case 8: // Node.COMMENT_NODE
		html = "<!--" + root.data + "-->";
		break;		// skip comments, for now.
	}
	return html;
}