var gInitialized;
if (typeof(gInitialized) == 'undefined')
	gInitialized = false;

var gClicked;
if (typeof(gClicked) == 'undefined')
	gClicked = false;

// Ji's change about localization
var gLocale;
if (typeof(gLocale) == 'undefined')
	gLocale = 'en';

var gEditorId;

function getDefaultParams(bUsesXForms)
{
	var dsParams = new Object;
	//dsParams.debug = true;
	dsParams.mode = "none"; // don't load any initially...createToggleButtons() will do it
//	dsParams.mode = "textareas";
	dsParams.theme = "advanced";
	dsParams.theme_advanced_buttons1 = "bold, italic, underline, strikethrough" +
																		 ", justifyleft, justifycenter, justifyright" +
																		 ", bullist, numlist, outdent, indent, undo, redo, link" +
																		 ", hr, forecolor, fontselect, fontsizeselect";
	dsParams.theme_advanced_statusbar_buttons = "fullscreen"; // statusbar buttons are a custom EA enhancement
	dsParams.theme_advanced_buttons2 = "";
	dsParams.theme_advanced_buttons3 = "";
	dsParams.theme_advanced_toolbar_location = "top";
	dsParams.theme_advanced_toolbar_align = "left";
	dsParams.theme_advanced_statusbar_location = "bottom";	// required for resizing
	dsParams.theme_advanced_resizing = true;								// resizing button
//	dsParams.theme_advanced_resizing_use_cookie = false;		// don't save/retrieve textarea size
//	dsParams.theme_advanced_resize_horizontal = false;			// no horizontal resizing
	dsParams.theme_advanced_path = false;										// turn off the path text
	dsParams.fix_list_elements = true;
	dsParams.plugins = "fullscreen";												// full screen plug-in
	//dsParams.fullscreen_new_window = true;								// full screen can popup new window...doesn't work so well
    dsParams.content_css = "/docushare/javascript/tiny_mce/themes/advanced/css/docushare_config.css";

	dsParams.auto_reset_designmode = true;
	dsParams.relative_urls = false; // assume user input url's are absolute url's

//	dsParams.force_br_newlines = true; // not recommended by TinyMCE
	dsParams.convert_newlines_to_brs = true;
	dsParams.strict_loading_mode = true;
	//dsParams.entity_encoding	 = "raw";
	dsParams.cleanup_serializer = "xml";
	dsParams.remove_linebreaks = false;			// don't remove linebreaks the user enters
	dsParams.force_p_newlines = true;			// don't add <p></p> everywhere we put a newline
	dsParams.fix_content_duplication = false; // gets rid of the mce_serialization attributes

	if (bUsesXForms)
		dsParams.handle_event_callback = "tinyMCE_eventhandler";

	dsParams.cleanup_callback = "ds_cleanupHTML"; // cleanup HTML in/out

        // ji's change: oninit, call createToggleButtons
        dsParams.oninit = 'createToggleButtons';

        // Ji's change about localization
        dsParams.language = gLocale;

	return dsParams;
}

function initDS_tinyMCE(bUsesXForms, locale)
{
  // Jis change about localization: set gLocale
  if (locale)
  {
        gLocale = locale;
  }

  if (gInitialized) {
		return;
	}

	var dsParams = getDefaultParams(bUsesXForms);
	// add a wiki button to Wiki pages
	if ( (window.location.href.search(/\/Edit\/WikiPage-\d+/) >= 0) ||
			 (window.location.href.search(/\/ServicesLib\/WikiPage-\d+\/Properties/) >= 0) )
        // Ji changes: Since we still could not convert ALL wiki syntax, it is not good to enable it for customer
        //dsParams.theme_advanced_statusbar_buttons = "wiki, code, fullscreen";
        dsParams.theme_advanced_statusbar_buttons = "fullscreen";

	tinyMCE.init(dsParams);
	gInitialized = true;
};


function ds_cleanupHTML(type, content, inst)
{
    var cleanhtm = content;
    if (type == "get_from_editor") { // save
        if (tinyMCE.settings['convert_newlines_to_brs']) {

            if (gClicked)
            {
                cleanhtm = tinyMCE.regexpReplace(cleanhtm, "<p mce_keep=\"true\">", "<p>", "gi");
                cleanhtm = tinyMCE.regexpReplace(cleanhtm, "<p>", "", "gi");
                cleanhtm = tinyMCE.regexpReplace(cleanhtm, "</p>", "\n", "gi");
                cleanhtm = tinyMCE.regexpReplace(cleanhtm, "&nbsp;", "", "gi");

                if (endsWith(cleanhtm, "\n"))
                {
                    cleanhtm = cleanhtm.substring(0, cleanhtm.lastIndexOf("\n"))
                }
                if (typeof _clear == 'function' && gEditorId)
                {
                    if (gEditorId.substring(gEditorId.length - 6, gEditorId.length) == "-value") // cut off "-value"
                        gEditorId = gEditorId.substring(0, gEditorId.length - 6);

                    _clear();
                    localActivity();
                    DWREngine.setOrdered(true);
                    DWREngine.setErrorHandler(handleExceptions);
                    var sessionKey = document.getElementById("chibaSessionKey").value;
                    Flux.setXFormsValue(updateUI, gEditorId, cleanhtm, sessionKey);
                }

                gClicked = false;
            }
        }
    }

    else if (type == "insert_to_editor") {
        if (tinyMCE.settings['convert_newlines_to_brs'])
        {

            cleanhtmLower = cleanhtm.trim().toLowerCase();

            while (endsWith(cleanhtmLower, "<br />"))
            {
                var lastIndexOfBr = cleanhtmLower.lastIndexOf("<br />");
                cleanhtm = cleanhtm.substring(0, lastIndexOfBr);
                cleanhtmLower = cleanhtm.toLowerCase();
            }

            cleanhtm = tinyMCE.regexpReplace(cleanhtm, "<br />", "</p><p>", "gi");
            if (cleanhtm.trim().indexOf("<p>") != 0)
            {
                cleanhtm = "<p>" + cleanhtm;
            }
            if (endsWith(cleanhtm.trim(), "</p>") == false)
            {
                cleanhtm = cleanhtm + "</p>";
            }
        }

    }
    return cleanhtm;
}

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function endsWith(str, s){
	var reg = new RegExp(s + "$");
	return reg.test(str);
}

// Ji's changes: click the enable/disable wysiwyg checkbox
function clickCheckBox(evt)
{
    var curEvent = (window.event) ? window.event : evt;

    // get the object of the disable/enable wysiwyg checkbox
    var editor_checkbox = curEvent.target || curEvent.srcElement;
    var editor_checkbox_str = new String (editor_checkbox.id);
    var index = editor_checkbox_str.lastIndexOf('_cbx');

    // get current editor id
    var editor_id = editor_checkbox_str.substring(0, index);
    gEditorId = editor_id;

    // if current editor is wysiwyg, click it to switch back to the original editor
    if (editor_checkbox.checked)
    {
        // add Tiny MCE control
        tinyMCE.addMCEControl(tinyMCE._getElementById(editor_id), editor_id);

        // show the wiki-editing-tips element
        var wikiEditTip = getElementsByStyleClass('wiki-editing-tips');
        if(wikiEditTip)
        {
            wikiEditTip.style.visibility = 'hidden';
        }

    }
    // if current editor is original editor, click it to turn on wysiwyg
    else
    {
        gClicked = true;
/* EA says this doesn't work: not using modified content...pulling from the wrong place
-- note: this cleanup now occurs in ds_cleanupHTML()
        // get current content
        var brReg = new RegExp("<br />");
        var curText = new String(document.getElementById(editor_id).value);
        curText = curText.replace(brReg,'\n');
 */
        // remove TinyMCE control
        tinyMCE.removeMCEControl(tinyMCE.getEditorId(editor_id));

        // hide the wiki-editing-tips element
        var wikiEditTip = getElementsByStyleClass('wiki-editing-tips');
        if(wikiEditTip)
        {
            wikiEditTip.style.visibility = 'visible';
        }

        document.getElementById(editor_id).focus();

        // set the new content without <br />
//        document.getElementById(editor_id).value = curText;
    }
} // clickCheckBox

// Ji's changes: create the disable-wysiwyg button and enable-wysiwyg button
function createToggleButtons()
{
    // get all text areas
    var textareas = document.getElementsByTagName('textarea');

    // for each text area, add the disable-wysiwyg button and enable-wysiwyg button
    for (var i = 0; i < textareas.length; ++i) {
		    // get the class name for the text areas, disable wysiwyg editor for css, text input, xmlFields and xmlTemplates
            var editor_id = textareas[i].id;
   			var className = textareas[i].className;
		    if (isWYSIWYG(className)) {

            // create enable/disable wysiwyg checkbox
            var editor_checkbox = document.createElement('input');
            editor_checkbox.type = "checkbox";
            editor_checkbox.id = textareas[i].id + "_cbx";
            editor_checkbox.defaultChecked = true;

            var parentNodeType = textareas[i].parentNode.tagName.toUpperCase();
            var refNode;

            // create the div element and checkbox text
            divElement = document.createElement('div');

            if (parentNodeType == 'DIV')
            {
                // layout for IE and wiki
                if (tinyMCE.isMSIE ||
                    window.location.href.search(/\/Edit\/WikiPage-\d+/) >= 0 ||
                    window.location.href.search(/\/ServicesLib\/WikiPage-\d+/) >= 0 ||
                    window.location.href.search(/\/Add\/Wiki-\d+/) >= 0) {
                    // create a label element if parent is 'div'
                    labelElement = document.createElement('label');
                    divElement.appendChild(labelElement);
                }
                else
                {
                    // create the div element and checkbox text
                    divElement.style.position = 'relative';
                    divElement.style.left = '130px';
                }

                // set refNode to be textareas[i].parentNode
                refNode = textareas[i].parentNode;
            }
            else
            {
                // set refNode to be textareas[i]
                refNode = textareas[i];
            }

            divElement.appendChild(editor_checkbox);
            divElement.appendChild( document.createTextNode( 'wysiwyg' ) );

            // add the check box before the refNode
            refNode.parentNode.insertBefore(divElement, refNode.nextSibling);

            // tabIndex change: return the new editor id
            // enable wysiwyg contrl
            newEditorId = tinyMCE.addMCEControl(tinyMCE._getElementById(editor_id), editor_id);
            // hide the wiki-editing-tips element
            var wikiEditTip = getElementsByStyleClass('wiki-editing-tips');
            if(wikiEditTip)
            {
                wikiEditTip.style.visibility = 'hidden';
            }

            // tabIndex change: set tabindex
            document.getElementById(newEditorId).setAttribute('tabIndex', '1');

            editor_checkbox.onclick = clickCheckBox;
        }
    }
} // createToggleButtons()

// check if the class contains wysiwyg
function isWYSIWYG(classValue)
{
    var classArray = new Array();
    classArray = classValue.split(' ');

    for (var i = 0; i < classArray.length; i++) {
        var curClassValue = classArray[i].toLowerCase();
        if (curClassValue == 'wysiwyg') {
            return true;
        }
    }
    return false;
}

/**
 * EA: TinyMCE event handler glue. Ties the TinyMCE textarea interface into Chiba/Flux
 */
function tinyMCE_eventhandler(evt)
{
	switch (evt.type) {
//	case "beforedeactivate":	// only works for IE, not Firefox
		case "blur":								// works in both
			//window.confirm('event handler: ' + evt.type);
		window.setTimeout("tinyMCE_saveText()",0);
			break;
		default:
			break;
	}
	return true;
}

var m_tinyMCE_text = "";

function tinyMCE_saveText()
{
	var curText = tinyMCE.selectedInstance.getHTML(false);
	if (curText != m_tinyMCE_text) {
		tinyMCE_setXFormsValue(curText);
		m_tinyMCE_text = curText;
	}
//	m_tinyMCE_text = ""; // clear for next time we hit this text box
}

function tinyMCE_setXFormsValue(textIn)
{
		var target;
		if (window.event)
			target = window.event.srcElement;
		else {
	    target = tinyMCE.selectedInstance.oldTargetElement;
  	  while (target && !_hasClass(target, "value")) {
    	  target = target.parentNode;
	   	}
	  }
    var id = target.id;
    if (id.substring(id.length - 6, id.length) == "-value") // cut off "-value"
	    id = id.substring(0, id.length - 6);

    _clear();
    _debug("Flux.tinyMCE_setXFormsValue: " + id + "='" + textIn + "'");
    // [JCraig] indicator is removed because its icon is a relative reference
    // and we do not want to see it anyway.
    //useLoadingMessage();

    localActivity();
    DWREngine.setOrdered(true);
    DWREngine.setErrorHandler(handleExceptions);
    var sessionKey = document.getElementById("chibaSessionKey").value;

    Flux.setXFormsValue(updateUI, id, textIn, sessionKey);
}


/* example function demonstrating how to completely reload TinyMCE:
function initDS_reloadTinyMCE(bUsesXForms, pageType)
{
	if (!gUseTinyMCE)
		return;

	var dsParams = getDefaultParams(bUsesXForms);
	if (pageType == 'wiki') {
		dsParams.theme_advanced_statusbar_buttons = "wiki, code, fullscreen"; // custom EA enhancement

		if ( (typeof(gInitialized) != 'undefined') && (gInitialized) ) {
			// blow away the previous tinyMCE engine
			tinyMCE = new TinyMCE_Engine();
		}
		tinyMCE.init(dsParams); // replace with our modified status buttons
		gInitialized = true;
	}
}
*/

// a function to convert Wiki syntax to HTML
TinyMCE_Engine.prototype.ripWiki = function()
{
	var inst = tinyMCE.selectedInstance;
	var content = inst.getHTML();

  inst.undoRedo.add({content: content});

  // replace \\ with <br>
	content = content.replace(/\\\\/gi, '<br class="newline">');

  // replace **text** with <strong>text</strong>
	content = content.replace(/\*\*(.+)\*\*/gi, "<strong>$1</strong>");
	// replace ~~text~~ with <em>text</em>
	content = content.replace(/~~(.+)~~/gi, "<em>$1</em>");
	// replace --text-- with <del>text</del>
	content = content.replace(/--(.+)--/gi, "<del>$1</del>");

	// extract the wiki page and base DocuShare URL
	var wikiPage, dsWebURL;
	var myURL = window.location.href;
	var wikiIdx = myURL.search(/\/Edit\/WikiPage-/);
	if (wikiIdx >= 0) {
		wikiPage = myURL.substring(wikiIdx+6);
		dsWebURL = myURL.substring(0, wikiIdx+1);
		// somehow need the Wiki Handle...
	}

	// replace [[Document-XX]] with <a>
	content = content.replace(/\[\[(Document\-\d+)\]\]/gi, "<a href=\"" + dsWebURL + "Get/$1\">$1</a>");
	// replace [[WikiPage@Wiki-XX]] with <a>
	content = content.replace(/\[\[(.+)@(Wiki-\d+)\]\]/gi, "<a href=\"" + dsWebURL + "View/$2/$1\">$1</a>");

	// replace {image:Document-XX} with <img>
	content = content.replace(/{image:(Document\-\d+)}/gi, "<img src=\"" + dsWebURL + "Get/$1\" />");

// this one still not working: ?? test this it may be working now
	// replace [[http://address|title]] with <a href="address">title</a>
	content = content.replace(/\[\[(http:\/\/.+)\|(.+)\]\]/gi, "<a href=\"$1\">$2</a>");
	// replace [[http://address]] with <a>
	content = content.replace(/\[\[(http:\/\/.+)\]\]/gi, "<a href=\"$1\">$1</a>");

/* still needs work; getting close
	// replace the different ! - !!!!!! heading levels
	content = content.replace(/(\n!{6})|(^!{6}) (.+)/gi, "<h6>$3</h6>");
	content = content.replace(/(\n!{5})|(^!{5}) (.+)/gi, "<h5>$3</h5>");
	content = content.replace(/(\n!{4})|(^!{4}) (.+)/gi, "<h4>$3</h4>");
	content = content.replace(/(\n!{3})|(^!{3}) (.+)/gi, "<h3>$3</h3>");
	content = content.replace(/(\n!{2})|(^!{2}) (.+)/gi, "<h2>$3</h2>");
	content = content.replace(/(\n!)|(^!) (.+)/gi, "<h1>$3</h1>");
 */

	inst.setHTML(content);
};

function dump(s, obj)
{
	var str = s;
	for (var i in obj)
	  str += (i + ' => ' + obj[i] + ", ");
	window.confirm("dump: " + str);
}

// get div element by class name
function getElementsByStyleClass (className) {
  var all = document.all ? document.all :  document.getElementsByTagName('div');
  for (var e = 0; e < all.length; e++)
  {
    if (all[e].className == className)
    {
      return all[e];
    }
  }
}
