Current File : //var/wcp4/million/public_html/file/private/templates.old/common/editor.js
/*  
 * =================================================================
 * HTML Editor - A wysiwyg web based editor for IE5.5+
 *    Website  : http://gossamer-threads.com/
 *    Revision : $Id: editor.js,v 1.12 2002/05/10 20:41:30 bao Exp $
 *
 * Copyright (c) 2002 Gossamer Threads Inc. All Rights Reserved.
 * Redistribution in part or in whole strictly prohibited. Please
 * see LICENSE file for full details.
 * =================================================================
 *
 * Description: Common functions needed to display the toolbar for an
 * HTML-editing iframe, as used in Gossamer Forum.
 */

/* -- Javascript needed to write a post -- */

var url = window.location.protocol + '//' + window.location.hostname + window.location.pathname + '?<%url_opts%>';

var image_url = '<%html_url%>/tools';

var iframe, editor, inner_content, outerdoc; // iframe is the inner iframe, editor is the editor (document object), and content is the editor's body.

var innerInterval, tbInterval, pressedInterval, initialized;

var controlRange; // selection is a ControlRange collection

window.onresize = tb_layout;

var unStack = new Array();
var reStack = new Array();
var unPress = false;

function initOuterIFrame () {
    // How fun - we write the HTML (which includes JavaScript) for this iframe, then write the HTML for the iframe contained within the iframe. :)
    document.frames.editor_iframe.document.write('<%GT::FileMan::js_quote_include('editor_iframe.html')%>');
    innerInterval = setInterval("initInnerIFrame()", 100);
}

function initInnerIFrame () {
    if ( typeof(document.frames.editor_iframe.document.editor_iframe) != 'undefined' && typeof(document.frm_main.pre_content) != 'undefined' ) {
        clearInterval(innerInterval);
    }
    else {
        return; // The inner <iframe> hasn't been loaded yet
    }
    outerdoc = document.frames.editor_iframe.document;
    iframe = outerdoc.frames.editor_iframe;
    editor = iframe.document;

    var initValue = document.frm_main.pre_content.value;
    var epos = initValue.search('<BODY');
    if (epos == -1) epos = initValue.search('<body');

    var head = initValue.substr(0,epos);
    head = head.replace('<html>','');
    document.frm_main.header.value = head;

    initValue = initValue.replace(head,'');
    initValue = initValue.replace('</html>','');
    editor.write('<%GT::FileMan::js_quote_include('editor_editor.html')%>' + initValue + '</body></html>');

    inner_content = editor.all.inner_content; 

    tbInterval = setInterval("toolbarInit()", 100);

    document.frm_main.onsubmit = retrieveHTML;
   
    pressedInterval = setInterval("calcPressed()", 300); // DEBUG - Set this to 300
}

function press (button, image) { // Takes a span from the outer iframe and "presses" it.
    button.isPressed = true;
    button.className = "menu_item_mouseoverdown";
    image.className  = "icon_down";
} 

function unpress (button, image) { // Takes one of the spans from the editor_iframe page and unpresses the button
    button.isPressed = false;
    button.className = "tb_menu_item";
    image.className  = "tb_icon";
}

function disable (button) { // Disables a span
	button.className  = "tb_menu_item";
    button.disabled = true;
    button.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0, opacity=25)";
}

function enable (button) { // Enables a span
    button.disabled = false;
    button.style.filter = null;
}

var pressLoopInit = false;
var pressButtons = {};
var pressLoop = [];
function calcPressed () {
    var sel = editor.selection.createRange();
	controlRange = (editor.selection.type == "Control") ? true : false;

    if (!pressLoopInit) {
        pressLoop[pressLoop.length] = 'Bold';
        pressButtons['Bold'] = [outerdoc.all.bold, outerdoc.all.boldImage];

        pressLoop[pressLoop.length] = 'Italic';
        pressButtons['Italic'] = [outerdoc.all.italic, outerdoc.all.italicImage];

        pressLoop[pressLoop.length] = 'Underline';
        pressButtons['Underline'] = [outerdoc.all.underline, outerdoc.all.underlineImage];

        pressLoop[pressLoop.length] = 'JustifyLeft';
        pressButtons['JustifyLeft'] = [outerdoc.all.jleft, outerdoc.all.jleftImage];

        pressLoop[pressLoop.length] = 'JustifyCenter';
        pressButtons['JustifyCenter'] = [outerdoc.all.jcenter, outerdoc.all.jcenterImage];

        pressLoop[pressLoop.length] = 'JustifyRight';
        pressButtons['JustifyRight'] = [outerdoc.all.jright, outerdoc.all.jrightImage];

        pressLoop[pressLoop.length] = 'InsertOrderedList';
        pressButtons['InsertOrderedList'] = [outerdoc.all.ol, outerdoc.all.olImage];

        pressLoop[pressLoop.length] = 'InsertUnorderedList';
        pressButtons['InsertUnorderedList'] = [outerdoc.all.ul, outerdoc.all.ulImage];

        pressLoopInit = true;
    }

    for (var i = 0; i < pressLoop.length; i++) {
        var pressed = sel.queryCommandValue(pressLoop[i]);
        var span  = pressButtons[pressLoop[i]][0];
        var image = pressButtons[pressLoop[i]][1];

        if      (pressed && !span.isPressed)   press(span, image);
        else if (!pressed && span.isPressed) unpress(span, image);
        else if (span.isPressed == null) span.isPressed = false;
    }

    var cutable = sel.queryCommandEnabled('Cut');
    var copyable = sel.queryCommandEnabled('Copy');
    var pastable = sel.queryCommandEnabled('Paste');
    var linkable = (sel.htmlText != '' && sel.htmlText != '\n<P>&nbsp;</P>');

    if      ( cutable  &&  outerdoc.all.cut.disabled  ) enable (outerdoc.all.cut  );
    else if (!cutable  && !outerdoc.all.cut.disabled  ) disable(outerdoc.all.cut  );
    if      ( copyable &&  outerdoc.all.copy.disabled ) enable (outerdoc.all.copy );
    else if (!copyable && !outerdoc.all.copy.disabled ) disable(outerdoc.all.copy );
    if      ( pastable &&  outerdoc.all.paste.disabled) enable (outerdoc.all.paste);
    else if (!pastable && !outerdoc.all.paste.disabled) disable(outerdoc.all.paste);    	
    if		(linkable  &&  outerdoc.all.link.disabled)  enable (outerdoc.all.link );
    else if (!linkable && !outerdoc.all.link.disabled)  disable(outerdoc.all.link );


	var bool_table = check_env();
    var bool_merge = check_merge(1);

	if ( bool_table ) {
		if (outerdoc.all.insCell.disabled) enable (outerdoc.all.insCell);
		if (outerdoc.all.insRow.disabled)  enable (outerdoc.all.insRow);
		if (outerdoc.all.insCol.disabled)  enable (outerdoc.all.insCol);
		if (outerdoc.all.delCell.disabled) enable (outerdoc.all.delCell);
		if (outerdoc.all.delRow.disabled)  enable (outerdoc.all.delRow);
		if (outerdoc.all.delCol.disabled)  enable (outerdoc.all.delCol);
		if (outerdoc.all.split.disabled)   enable (outerdoc.all.split);
	}
    else {
		if (!outerdoc.all.insCell.disabled) disable (outerdoc.all.insCell);
		if (!outerdoc.all.insRow.disabled)  disable (outerdoc.all.insRow);
		if (!outerdoc.all.insCol.disabled)  disable (outerdoc.all.insCol);
		if (!outerdoc.all.delCell.disabled) disable (outerdoc.all.delCell);
		if (!outerdoc.all.delRow.disabled)  disable (outerdoc.all.delRow);
		if (!outerdoc.all.delCol.disabled)  disable (outerdoc.all.delCol);
		if (!outerdoc.all.split.disabled)   disable (outerdoc.all.split);
	}

    if (check_merge()) {
        if (outerdoc.all.merge.disabled) enable(outerdoc.all.merge);
    }
    else {
        disable(outerdoc.all.merge);
    }

    if (unStack.length == 0) unStack[0] = inner_content.innerHTML;

    if (isChanged() || unStack.length > 1) {
        if (outerdoc.all.undo.disabled) enable(outerdoc.all.undo);
    }
    else disable(outerdoc.all.undo);

    if (reStack.length > 0) {
        if (outerdoc.all.redo.disabled) enable(outerdoc.all.redo);
    }
    else disable(outerdoc.all.redo);


	if (controlRange) { // selection in ControlRange collection
		if (!outerdoc.all.table.disabled)	  disable (outerdoc.all.table);
		
		if (!outerdoc.all.bold.disabled)	  disable (outerdoc.all.bold);
		if (!outerdoc.all.italic.disabled)	  disable (outerdoc.all.italic);
		if (!outerdoc.all.underline.disabled) disable (outerdoc.all.underline);

		if (!outerdoc.all.ol.disabled)        disable (outerdoc.all.ol);
		if (!outerdoc.all.ul.disabled)        disable (outerdoc.all.ul);
		if (!outerdoc.all.od.disabled)        disable (outerdoc.all.od);
		if (!outerdoc.all.id.disabled)        disable (outerdoc.all.id);

		if (!outerdoc.all.font.disabled)	  disable (outerdoc.all.font);
		if (!outerdoc.all.fcolor.disabled)	  disable (outerdoc.all.fcolor);
		if (!outerdoc.all.horRule.disabled)	  disable (outerdoc.all.horRule);
		if (!outerdoc.all.insImage.disabled)  disable (outerdoc.all.insImage);	

        if (!outerdoc.all.text.disabled)	  disable (outerdoc.all.text);
		if (!outerdoc.all.textarea.disabled)  disable (outerdoc.all.textarea);
		if (!outerdoc.all.form.disabled)	  disable (outerdoc.all.form);
		if (!outerdoc.all.checkbox.disabled)  disable (outerdoc.all.checkbox);	
       	if (!outerdoc.all.radio.disabled)	  disable (outerdoc.all.radio);
		if (!outerdoc.all.select.disabled)    disable (outerdoc.all.select);	
		if (!outerdoc.all.button.disabled)    disable (outerdoc.all.button);	
	}
	else {
        if (bool_merge) {
    		if (!outerdoc.all.table.disabled)    disable (outerdoc.all.table);
            if (!outerdoc.all.horRule.disabled)	 disable (outerdoc.all.horRule);
		    if (!outerdoc.all.insImage.disabled) disable (outerdoc.all.insImage);	

            if (!outerdoc.all.text.disabled)	 disable (outerdoc.all.text);
            if (!outerdoc.all.textarea.disabled) disable (outerdoc.all.textarea);
            if (!outerdoc.all.form.disabled)	 disable (outerdoc.all.form);
            if (!outerdoc.all.checkbox.disabled) disable (outerdoc.all.checkbox);	
            if (!outerdoc.all.radio.disabled)	 disable (outerdoc.all.radio);
            if (!outerdoc.all.select.disabled)   disable (outerdoc.all.select);	
            if (!outerdoc.all.button.disabled)   disable (outerdoc.all.button);	
        }
        else {
            if (outerdoc.all.table.disabled )    enable (outerdoc.all.table);
        	if (outerdoc.all.horRule.disabled)	 enable (outerdoc.all.horRule);
	    	if (outerdoc.all.insImage.disabled)  enable (outerdoc.all.insImage);		

            if (outerdoc.all.text.disabled)	     enable (outerdoc.all.text);
            if (outerdoc.all.textarea.disabled)  enable (outerdoc.all.textarea);
            if (outerdoc.all.form.disabled)	     enable (outerdoc.all.form);
            if (outerdoc.all.checkbox.disabled)  enable (outerdoc.all.checkbox);	
            if (outerdoc.all.radio.disabled)	 enable (outerdoc.all.radio);
            if (outerdoc.all.select.disabled)    enable (outerdoc.all.select);	
            if (outerdoc.all.button.disabled)    enable (outerdoc.all.button);	
        }

		if (outerdoc.all.bold.disabled)		 enable (outerdoc.all.bold);
		if (outerdoc.all.italic.disabled)	 enable (outerdoc.all.italic);
		if (outerdoc.all.underline.disabled) enable (outerdoc.all.underline);

		if (outerdoc.all.ol.disabled) enable (outerdoc.all.ol);
		if (outerdoc.all.ul.disabled) enable (outerdoc.all.ul);
		if (outerdoc.all.od.disabled) enable (outerdoc.all.od);
		if (outerdoc.all.id.disabled) enable (outerdoc.all.id);

		if (outerdoc.all.font.disabled)		enable (outerdoc.all.font);
		if (outerdoc.all.fcolor.disabled)	enable (outerdoc.all.fcolor);     
	}
}

function check_env() {
	var mytable = selected_table();
	if (!mytable) return;
	if ( selected_tr(mytable) >=0 ) return true;
}

function check_merge(type) {
	if (controlRange) return false;
	htmlText = editor.selection.createRange().htmlText;		
	htmlText.toUpperCase();
	var ret = (type) ? ((htmlText.search('<TR') != -1 || htmlText.search('<TD') != -1) && htmlText != '') : (htmlText.search('<TR') == -1 && htmlText != '' && htmlText.search('<TD') != -1);
	return ret;
}

function retrieveHTML () {
    var body    = inner_content.outerHTML;   
    var head    = document.frm_main.header.value
    if (body){
        var style = /style="BORDER-RIGHT: red 1px dotted; PADDING-RIGHT: 2px; BORDER-TOP: red 1px dotted; PADDING-LEFT: 2px; PADDING-BOTTOM: 2px; BORDER-LEFT: red 1px dotted; PADDING-TOP: 2px; BORDER-BOTTOM: red 1px dotted"/gi;
        body = body.replace(style,'');
        body = body.replace('id=inner_content contentEditable=true','');

        var html = '<html>' + head + body + '\n</html>';
        html = html.replace(/\n\s/gi,'');
        document.frm_main.content.value = html;
    }
}

function command (cmd) {
    iframe.focus();
	//alert("Command with " + cmd);
    editor.execCommand(cmd);
    iframe.focus();
    insItem();
}

// This is called for things like [quote]...[/quote] - they should surround the selected text.
function surroundTag (start, end) {
    iframe.focus();
    var selection = editor.selection.createRange();
    selection.pasteHTML(start + selection.htmlText + end);
    iframe.focus();
}

// This is called for tags like [smile] - it replaces any selected text
function insertTag (tag) {
    iframe.focus();
    var selection = editor.selection.createRange();
    selection.pasteHTML(tag);
    iframe.focus();
}

function imageDialog () {
    var imageSrc = showModalDialog(url + '&fdo=cmd_show&page=common/editor_image.html', null, "dialogHeight: 135px; dialogWidth: 435px; scroll: no; help: no; status: no");
    if (imageSrc) {
        iframe.focus();
        editor.execCommand('InsertImage', false, imageSrc);
    }
    iframe.focus();
    insItem();
}

function linkDialog () {
    var sel = editor.selection.createRange();
    if (sel.htmlText == '' || sel.htmlText == '\n<P>&nbsp;</P>') return;

    iframe.focus();
    setTimeout("editor.execCommand('CreateLink', true); iframe.focus();", 100);
}

function fontDialog () {
    var sel = editor.selection.createRange();
    var font = sel.queryCommandValue('FontName');
    var size = sel.queryCommandValue('FontSize');
    var color = sel.queryCommandValue('ForeColor');
    var bold = sel.queryCommandValue('Bold');
    var italic = sel.queryCommandValue('Italic');
    var underline = sel.queryCommandValue('Underline');
    var args = [font, size, color, bold, italic, underline];

    // ret is an array, just like args: [font, size, color, b, i, u]
    var ret = showModalDialog(url + '&fdo=cmd_show&page=common/editor_font.html', args, "dialogHeight: 332px; dialogWidth: 442px; scroll: no; help: no; status: no");

    if (ret) {
        var applyTo;
        if (sel.htmlText.length == 0 || sel.htmlText == '\n<P>&nbsp;</P>')
            applyTo = editor;
        else
            applyTo = sel;
        if (ret[0]) applyTo.execCommand('FontName', false, ret[0]);
        if (ret[1]) applyTo.execCommand('FontSize', false, ret[1]);
        if (ret[2]) applyTo.execCommand('ForeColor', false, ret[2]);
        if (ret[3] != null && ((ret[3] && !bold) || (!ret[3] && bold))) // Toggle bold if bold was on and is now off or if bold was off and is now on
            applyTo.execCommand('Bold');
        if (ret[4] != null && ((ret[4] && !italic) || (!ret[4] && italic))) // Toggle italics if it was on and is now off or if it was off and is now on
            applyTo.execCommand('Italic');
        if (ret[5] != null && ((ret[5] && !underline) || (!ret[5] && underline))) // Toggle underline if it was on and is now off or if it was off and is now on
            applyTo.execCommand('Underline');
    }
    iframe.focus();
    insItem();
}

<%if ie_version >= 6%>
function colorDialog (type) {   
    if (type) setTimeout('IE6bgColor(); iframe.focus()');
    else setTimeout('IE6Color(); iframe.focus()');
}

function IE6Color () {
    var color = document.all.dlg.ChooseColorDlg();

    var hexColor = color.toString(16);
    if (hexColor.length < 6) hexColor = "000000".substring(0, 6 - hexColor.length) + hexColor;

    editor.execCommand("ForeColor", true, hexColor);
}

function IE6bgColor () {
    var color = document.all.dlg.ChooseColorDlg();

    var hexColor = color.toString(16);
    if (hexColor.length < 6) hexColor = "000000".substring(0, 6 - hexColor.length) + hexColor;
    fillColor(hexColor);
    insItem();
}

<%else%>
function colorDialog (type) {
    var hexColor = showModalDialog(url + '&fdo=cmd_show&page=common/editor_color.html', null, "dialogHeight: 380px; dialogWidth: 115px; scroll: no; help: no; status: no");
    if (type) fillColor(hexColor);
    else editor.execCommand("ForeColor", true, hexColor);
    iframe.focus();
    insItem();
}
<%endif%>

function fillColor (color) {
    if (controlRange) {     
         var oControlRange = editor.selection.createRange();
         for (i = 0; i < oControlRange.length; i++) {
            if (oControlRange(i).tagName.toUpperCase() == "TABLE")
                oControlRange(i).bgColor = color;
        }
    } 
    else {
        var mytable = selected_table();
	    if (mytable) {
            var currentRow = selected_tr(mytable);
        	var currentCol = selected_td(mytable,currentRow);
            mytable.rows[currentRow].cells[currentCol].bgColor = color;
        }
        else inner_content.bgColor = color;
    }    
}
/* -- Toolbar initialization is below -- */


var initInterval, toolbars, tb;

// Keep track of number of images loaded.
//var imagesLoaded = 0;

function toolbarInit () {
/* ---------------------------------------------------------
 * Should be called after the outerdoc has loaded. 
 * Initializes the Toolbar for display.
 */
    // 'toolbars' contains all the div tags
	var tbs = outerdoc.body.all.tags("DIV");

    // There are 3 <div>'s. If another is ever added, this number should be incremented.
    if (tbs.length < 3)
        return;
    else
        clearInterval(tbInterval);

    initialized = true;

    tb = {};
    toolbars = [];
    document.all.editor_iframe.style.visibility = 'visible';
// Go through the outerdoc and get the toolbar classes
	for (var i = 0; i < tbs.length; i++) {
		var toolbar = tbs[i];

		tb[toolbar.title] = toolbar;
		toolbars[toolbars.length] = toolbar;

		toolbar.TB_INDEX  = toolbars.length;

// Initialize the toolbar
        tb_init(toolbar);
	}

	tb_layout();

// If the window is resized we need to re-layout the 
// toolbar.
	toolbar_init = true;
}

function tb_init (toolbar) {
/* ---------------------------------------------------------
 * Called for each toolbar DIV. Populates the toolbar and 
 * sets the width.
 */
	toolbar.TBWidth = 1;
    tb_populate(toolbar)
	toolbar.style.posWidth = toolbar.TBWidth;
	return true;
}

function tb_populate (toolbar) {
/* ---------------------------------------------------------
 * Moves all of toolbar 'toolbar's icons to the proper location on
 * the screen and sets the correct size for the toolbars.
 */

	var elements = toolbar.children;
	if (!elements) return;

// Loop through all the toolbars children.
	for (var i = 0; i < elements.length; i++) {
		var element = elements[i];
		if (element.tagName == "SCRIPT" || element.tagName == "!") continue;

// Switch to see what element we are workin with.
		switch (element.className) {
			case "tb_menu_item": // A button
				if (element.INITIALIZED == null)
                    tb_init_button(element)
				element.style.posLeft = toolbar.TBWidth;
				toolbar.TBWidth += element.offsetWidth + 1;
				break;

			case "tb_general": // Not a button - most likely a form field

			case "tb_menu_text":
				element.style.posLeft = toolbar.TBWidth;
				toolbar.TBWidth += element.offsetWidth + 5;
				break;

			case "tb_sep": // Seperator
				element.style.posLeft = toolbar.TBWidth + 2;
				toolbar.TBWidth += 5;
				break;

			case "tb_handle": // Toolbar handle
				element.style.posLeft = 2;
				toolbar.TBWidth += element.offsetWidth + 7;
				break;

			default: // Should never get here unless the html is messed
		}
	}

	toolbar.TBWidth++; // Add 1 in case the width is zero
	return true;
}

function tb_init_button (element) {
/* ---------------------------------------------------------
 * Sets op all the defaults for a button DIV. Saves any 
 * onclick and detaches the event. OnClick events are called
 * onMouseDown.
 */
	if (element.className == "tb_general") return true;

// Set events
	element.onmouseover   = tb_mouseover;
	element.onmouseout    = tb_mouseout;
	element.onmousedown   = tb_mousedown;
	element.onmouseup     = tb_mouseup;

// Disable events
	element.ondragstart   = cancel_event;
	element.onselectstart = cancel_event;
	element.onselect      = cancel_event;

// Save onClick event for onMouseDown
	element.YUSERONCLICK  = element.onclick;
	element.onclick       = cancel_event;

// So we don't re-initialize
	element.INITIALIZED  = true;

	return true;
}

function tb_layout () {
/* ---------------------------------------------------------
 * Layouts the toolbar on the screen based on the screen
 * width and the widths built in tb_populate().
 */

    if (!initialized)
        toolbarInit();

	var num_tb = toolbars.length;

// No toolbars
	if (num_tb == 0) return;
	var i;

// Get the screen width minus the width of the scrollbar
	var sbar = outerdoc.body.offsetWidth - outerdoc.body.clientWidth;
	var ScrWid = (outerdoc.body.offsetWidth  - sbar);
	var ScrHit = (outerdoc.body.offsetHeight - sbar);

// Go through the toolbars and find the width of the widest
// one.
	var TotalLen = ScrWid;
	var tb = [];
	var e = 0;
	for (i = 0; i < num_tb; i++) {
		tb[e] = toolbars[i];
		if (tb[e].TBWidth > TotalLen) TotalLen = tb[e].TBWidth;
		e++;
	}
	e--;
	if (!tb.length) { return; }
	var PrevTB;
	var LastStart = 0;
	var RelTop = 0;
	var LastWid, CurrWid;

// Position the top toolbar to the top of the screen
	var TB           = tb[0];
	TB.style.posTop  = 0;
	TB.style.posLeft = 0;
	var rows         = 1;

// Go through the toolbars and update there width
// and position.
	var Start = TB.TBWidth;
    var wExtra = 0
    var hExtra = 0;
    <%if ie_version >= 6%>
    wExtra = (inner_content.clientWidth > 980) ? 0  : 16;
    hExtra = 15;
    <%endif%>
	for (i = 1; i < tb.length; i++) {
		PrevTB = TB;
		TB = tb[i];
		CurrWid = TB.TBWidth;

// Reached the end of the screen, reset to the start
		if ((Start + CurrWid) > ScrWid) { 
			Start = 0;
			rows++;
			LastWid = TotalLen - LastStart + hExtra;
		}
		else {
			LastWid = PrevTB.TBWidth;
			RelTop -= TB.offsetHeight;
		}
	  
		TB.style.posTop = RelTop;
		TB.style.posLeft = Start;
		PrevTB.style.width = LastWid;

		LastStart = Start;
		Start    += CurrWid;

	}    
	outerdoc.all.editor_iframe.style.posTop     = rows * 25 ;
	outerdoc.all.editor_iframe.style.posHeight  = ScrHit - (rows * 25) + wExtra;
	outerdoc.all.editor_iframe.style.posWidth   = ScrWid + wExtra;
	outerdoc.all.editor_iframe.style.visibility = 'visible';
// Set the total width
	TB.style.width = TotalLen - LastStart + hExtra;

// Move the rest of the toolbars down
	TB = tb[--i];
	var TBInd = TB.sourceIndex;
	var A = TB.document.all;
	for (var i in A) {
		var item = A.item(i);
		if (item && item.style && item.sourceIndex > TBInd && tb[item.title])
		    item.style.posTop = RelTop;
	}
}

function tb_mouseover () {
/* ---------------------------------------------------------
 * OnMouseOver event handler function for toolbar buttons.
 */
 // Source must be an image
    var event = document.frames.editor_iframe.event;
	if (event.srcElement.tagName != "IMG") return cancel_event(event);
	var image   = event.srcElement;
	var element = image.parentElement;

// If we are in text mode and the button is disables for 
// text mode. cancel the mouseover.
	if (element.disabled) return cancel_event(event);

// If the image in normal state put it in mouseover state
	if (image.className == "tb_icon") {
		element.className = "menu_item_mouseoverup";
	}
// else if it is in down state put it in mouseover
// for down states.
	else if (image.className == "icon_down") {
		element.className = "menu_item_mouseoverdown";
	}

	return cancel_event(event);
}

function tb_mouseout () {
/* ---------------------------------------------------------
 * MouseOut event handler function for toolbar buttons
 */
 // The source tag must be an image.
    var event = document.frames.editor_iframe.event;
	if (event.srcElement.tagName != "IMG") return cancel_event(event);
	var image   = event.srcElement;
	var element = image.parentElement;

	if (element.disabled) return cancel_event(event);

// If the button is a toggle update it's state.
    if (element.isPressed) {
		element.className = "menu_item_mouseoverdown"
		image.className   = 'icon_down';
	}
// else put the image back to it's normal state.
	else {
	    element.className  = "tb_menu_item";
	    image.className    = "tb_icon";
	}

    return cancel_event(event);
}

function tb_mousedown () {
/* ---------------------------------------------------------
 * MouseDown event handler for toolbar buttons.
 */

 // The source tag must be an image.
    var evnt = document.frames.editor_iframe.event;
	if (evnt.srcElement.tagName != "IMG") return cancel_event(evnt);
	var image   = evnt.srcElement;
	var element = image.parentElement;

// If we are in "text mode" and the button is not supported in
// "text mode" cancel the event and return false.
	if (element.disabled) return cancel_event(evnt);

    if (element.isPressed != null && !element.isPressed)
        press(element, image);
	element.className = "menu_item_mouseoverdown";
	image.className   = "icon_down";

// We disabled the click function and saved it in this.
// Eval it here and run it.

	if (element.YUSERONCLICK) eval(element.YUSERONCLICK + "anonymous()");
	return cancel_event(evnt);
}

function tb_mouseup () {
/* ---------------------------------------------------------
 * MouseUp event handler function for toolbar buttons.
 */
 // The source element must be an image type.
    var event = document.frames.editor_iframe.event;
	if (event.srcElement.tagName != "IMG") return cancel_event(event);
	var image   = event.srcElement;
	var element = image.parentElement;

// If we are in "text mode" and the field is disabled in that
// mode return and cancel the event.
	if (element.disabled) return cancel_event(event);

// It the icons to the mouseUp state.
	element.className = "menu_item_mouseoverup";
	image.className   = "tb_icon";

// Refocus the compose window here.
	iframe.focus();

	return cancel_event(event);

}

function cancel_event (evnt) {
/* ---------------------------------------------------------
 * General function to cancel an event.
 */
    if (!evnt) evnt = event;
    if (!evnt) return false;
    evnt.returnValue  = false;
    evnt.cancelBubble = true;
    if (event) {
        event.returnValue  = false;
        event.cancelBubble = true;
    }
    return false;
}

function showDialog (file,height,width,type) {
/*------------------------------------------------------------
 * show dialog window
 */
    var html = showModalDialog(url + '&fdo=cmd_show&page=common/' + file, null, "dialogHeight: " + height + "px; dialogWidth: " + width + "px; scroll: no; help: no; status: no");	
	if (!html) return;

	var obj,opt;	

	iframe.focus();
	var selection = editor.selection.createRange();

	if (type == 'select') {
		obj = html[0];
		opt = html[1];
        if (!obj || !opt) return;
		var aElement = editor.createElement(obj);
		for (var i=0; i < opt.length; i++ ) {
			var oOpt = document.createElement("OPTION");
			aElement.options.add(oOpt);	
			oOpt.Value = opt[i][1];
			if (opt[i][0]) oOpt.innerText = opt[i][0];						
			if (opt[i][2]) oOpt.selected  = true;
		}
        html = aElement.outerHTML;		
	}
	else if (type == 'textarea') {
		var aElement = editor.createElement(html[0]);
        if (html[1]) aElement.innerText = html[1];
		html = aElement.outerHTML;
	}
    selection.pasteHTML(html);
	iframe.focus();		
    insItem();
}

function insert_table () {
/* ---------------------------------------------------------
 * Calles dialoge in table_url to prompt for the table
 * info needed to insert the table, then does the insert.
 * 
 */
	var tbl = showModalDialog(url + '&fdo=cmd_show&page=common/editor_table.html', null, "dialogHeight:200px;dialogWidth:400px");
	if (!tbl) 
		return;
	iframe.focus();	
	var oTable = editor.createElement("TABLE");
	var cols = (tbl.NumCols) ? tbl.NumCols : 0;
	var rows = (tbl.NumRows) ? tbl.NumRows : 0;
	oTable.width		= (tbl.Width)		? tbl.Width + tbl.Unit : '';
	oTable.border		= (tbl.Border)		? tbl.Border : '0'
	oTable.cellPadding	= (tbl.CellPadding) ? tbl.CellPadding : '';
	oTable.cellspacing	= (tbl.CellSpacing) ? tbl.CellSpacing : '';
	oTable.contentEditable = true;

	//create rows and cells
	if (cols > 0 && rows >0) {
		for (var i=0; i < rows; i++ ) {
			var oRow = editor.createElement("TR");
			for (var j=0; j < cols ; j++ ) { 
				var oCell = editor.createElement("TD");
				oRow.appendChild(oCell);
			}
			oTable.appendChild(oRow)
		}		
	}
	var selection = editor.selection.createRange();
	selection.pasteHTML(oTable.outerHTML);
	iframe.focus();	
    insItem();
}

function insert_row() {
/*------------------------------------------------------------
 * Insert new row
 */	
  	var mytable = selected_table();	    
    if (mytable) {	
		var currentRow = selected_tr(mytable);        
		var cols = mytable.rows[currentRow].cells.length; 
		var oRow = mytable.insertRow(currentRow);
		for (var i=0; i<cols ;i++ ) oRow.insertCell();		
	}
}

function insert_col() {
/*------------------------------------------------------------
 * Insert a column
 */
	var mytable = selected_table();
	if (mytable) {
		var rows = mytable.rows.length;
		for (var i=0; i<rows; i++) insert_cell(i);
	}
}

function insert_cell(nrow,ncol) {
/*------------------------------------------------------------
 * Insert a cell
 */
	var mytable = selected_table();

	if (mytable) {	
		var currentRow = (nrow >=0) ? nrow : selected_tr(mytable);
		var currentCol = (ncol >=0) ? ncol : selected_td(mytable,currentRow);
		mytable.rows[currentRow].insertCell(currentCol);
	}
}

function delete_row() {
/*------------------------------------------------------------
 * Delete a row
 */
	var mytable = selected_table();
	if (mytable) mytable.deleteRow(selected_tr(mytable));
}

function delete_col() {
/*------------------------------------------------------------
 * Delete a column
 */
	var mytable = selected_table();
	if (mytable) {
		var currentRow = selected_tr(mytable);
		var currentCol = selected_td(mytable,currentRow);
		var rows = mytable.rows.length;
		for (var i=0; i<rows; i++) delete_cell(i,currentCol);
	}
}

function delete_cell(nrow,ncol) {
/*------------------------------------------------------------
 * Delete a cell
 */
	var mytable = selected_table();
	if (mytable) {	
		var currentRow = (nrow >=0)? nrow : selected_tr(mytable);
		var currentCol = (ncol >=0)? ncol : selected_td(mytable,currentRow);
		if (currentCol < mytable.rows[currentRow].cells.length)  mytable.rows[currentRow].deleteCell(currentCol);
        if (mytable.rows[currentRow].cells.length == 0)          mytable.deleteRow(currentRow);
	}
}

function split_cell() {
/*------------------------------------------------------------
 * Split a cell
 */
    var mytable = selected_table();
	if (!mytable) return
   	var currentRow = selected_tr(mytable);
	var currentCol = selected_td(mytable,currentRow);
	var rows = mytable.rows.length;
	var cols = mytable.rows[currentRow].cells.length;
    var span = mytable.rows[currentRow].cells[currentCol].colSpan;
	for (var i=0; i<rows; i++) {
		if ( i == currentRow) {
			if (mytable.rows[i].cells[currentCol].colSpan > 1) mytable.rows[i].cells[currentCol].colSpan--;
			insert_cell(currentRow,currentCol);
		}
		else {
            var ncol;
			var nlen = mytable.rows[i].cells.length;            
            if ( span == 1) {                
                var jspan = 0;
                for (var j=0; j<nlen ; j++) {
                    jspan += mytable.rows[i].cells[j].colSpan;
                    if (jspan - 1 >= currentCol) { ncol = j; break; }
                }                           
                mytable.rows[i].cells[ncol].colSpan++;
            }
            else {
                if (currentCol > 0 ) {
                    var jmax = 0;
                    var jcol = (currentCol >= nlen - 1) ? nlen - 1 : currentCol-1;

                    for (var j=0; j<rows ; j++) {
                        var mlen = mytable.rows[j].cells.length
                        var mcol = (currentCol >= mlen-1) ? mlen - 1 : currentCol-1;
                        if (mytable.rows[j].cells[mcol].colSpan > jmax) jmax = mytable.rows[j].cells[mcol].colSpan;
                    }                    
                    if (mytable.rows[i].cells[jcol].colSpan == jmax) { ncol = currentCol; }
                    else {
                        var jspan = 0;
                        for (var j=0; j<jmax ; j++ ) {
                            jspan += mytable.rows[i].cells[j].colSpan;
                            if (jspan == jmax) ncol = (j == jmax - 1) ? jmax : j;
                        }
                    }
                }
            }
        }
    }
}

function merge_cell() {
/*------------------------------------------------------------
 * Split a cell
 */
	var mytable = selected_table();
	if (!mytable)
		return
	rows = mytable.rows.length;

//mark TD id
	for (var i=0; i<rows ; i++) {
		cols = mytable.rows[i].cells.length;
		for (var j=0; j<cols ; j++) mytable.rows[i].cells[j].ch = i + '-' + j;
	}
	htmlText = editor.selection.createRange().htmlText;		
	htmlText.toUpperCase();
	if (htmlText.search('<TR') != -1) return;

    var pos = pre_merge(htmlText);
	currentRow = parseInt(pos[0]); begCol = parseInt(pos[1]); endCol = parseInt(pos[2])
	if ( begCol <= endCol && currentRow >= 0) {
		var data = '';
        var html = '';
		var count = 0;		
        var nspan = 0;
		for (var i=begCol; i<=endCol; i++) {
			if (mytable.rows[currentRow].cells[i].hasChildNodes()) {                                
                if (mytable.rows[currentRow].cells[i].innerHTML) html += mytable.rows[currentRow].cells[i].innerHTML;
				data += mytable.rows[currentRow].cells[i].childNodes.item(0).data + ' ';
            }
            nspan += mytable.rows[currentRow].cells[i].colSpan; 
            count++;
		}
		for (var i=begCol; i<endCol ; i++ ) { delete_cell(currentRow,begCol); }

		mytable.rows[currentRow].cells[begCol].colSpan = nspan;
		mytable.rows[currentRow].cells[begCol].childNodes.item(0).data = data;
        if (html) mytable.rows[currentRow].cells[begCol].innerHTML = html;
	}
}

function pre_merge(htmlText) {
/*----------------------------------
Define currentRow, begCol, endCol in merge cell
*/
	items = htmlText.split("</TD>");
	var currentRow,begCol,endCol;
	for (i=0; i<items.length ;i++) {
		if ( items[i] != '' && items[i].search('<TR') == -1) {			
			pos1 = items[i].indexOf(">");			
            pos2 = items[i].indexOf("ch=");
			tmp = items[i].substr(pos2+3,pos1-pos2-3)
			
			elem = tmp.split('-');
			if (i==0) {
				currentRow = elem[0];
				begCol = elem[1];
			}
			endCol = elem[1];			
		}
	}
	return [currentRow,begCol,endCol];
}

function selected_table () {
/*------------------------------------------------------------
 * Return a current table object 
 */
	if (!editor) return;
    var table = inner_content.getElementsByTagName("table");
    for (var i=table.length-1; i >= 0; i-- )   
    	if (isChild(table(i))) return table(i);
}

function selected_tr (mytable) {
/*------------------------------------------------------------
 * Return a number of current row
 */
	var rows = mytable.rows;
	for (var i=0; i < rows.length; i++) 
		if (isChild(rows(i))) return i;
}

function selected_td (mytable,currentRow) {
/*------------------------------------------------------------
 * Return a number of current column
 */
    var cols = mytable.rows[currentRow].cells;
	for (var i=0; i < cols.length; i++) 
		if (isChild(cols(i))) return i;
}

function isChild(obj) {
/*------------------------------------------------------------
 * Return 1: if the cursor is in an object area
 */
	if (!controlRange) {
		// selection is a TextRange		
		var rcts = obj.getClientRects();
		var selection = editor.selection.createRange();
		var sel_rcts = selection.getClientRects();
		var keyCount=0;        
		if ( (sel_rcts[keyCount].top >= rcts[keyCount].top) && (sel_rcts[keyCount].bottom <= rcts[keyCount].bottom) && (sel_rcts[keyCount].left >= rcts[keyCount].left) && (sel_rcts[keyCount].right <= rcts[keyCount].right) )
			return 1;
	}    
}

function undo() {
/*---------------------------------------------
/ Undo command
*/    
    if (unStack.length > 0) {
        insItem();        
        var ulen = unStack.length;
        var step = (ulen > 1) ? ulen - 2 : 0;
        reStack[reStack.length++] = (step == ulen - 1) ? unStack[0] : unStack[step+1];
        inner_content.innerHTML = unStack[step];
        unStack.pop();
        unPress = true;
    }
}

function redo() {
/*---------------------------------------------
/ Redo command
*/
    if (reStack.length > 0) {
        var tmp = reStack[reStack.length-1];
        unStack[unStack.length++] = tmp;
        inner_content.innerHTML   = tmp;
        reStack.pop();
    }
}

function insItem () {
/*---------------------------------------------
/ insert an element in stack
*/
    var body = inner_content.innerHTML;
    var max = unStack.length;
    if (body && isChanged())  unStack[max++] = body;
}

function cleStack() {
/*---------------------------------------------
/ clean stack
*/
    if (unPress) {
        usStack = []; reStack = []; unPress = false;
    }
}

function isChanged() {
/*---------------------------------------------
Return boolean, True if it's changed
*/
    var body = inner_content.innerHTML;
    if (unStack.length == 0 || !body) return false;
    else if (body != unStack[unStack.length-1]) return true;
}

/* Help VIM out
vim:ts=4:shiftwidth=4:syntax=javascript
*/