//#####
//###  Epoz - a cross-browser-wysiwyg-editor for Zope
//##   Copyright (C) 2003 Maik Jablonski (maik.jablonski@uni-bielefeld.de)
//#

// Just to prevent typos when fetching the Epoz-IFrame...

var Epoz = "EpozEditor";

// Speed-Up-Storage for document.getElementById(Epoz);

var EpozElement;
var EpozTextArea;

// Global storages

var form_data;  // the document-data
var form_name;  // the name of the form-element
var form_path;  // path to buttons, font-selectors, ...
var form_toolbox; // path to optional toolbox
var form_area_style; // css-definition for wysiwyg-area
var form_button_style; // css-definition for buttons
var form_css; // css-style for iframe
var form_customcss; // customized css-style for iframe
var form_charset; // charset for iframe
var form_pageurl; // real url for the edited page

// Detect browser type and create Epoz- or Default-Textbox

function InitEpoz(name, data, path, toolbox, style, button, css, customcss, charset, pageurl) {

    form_name = name;
    form_data = data; 
    form_path = path;
    form_toolbox = toolbox;
    form_area_style = style;
    form_button_style = button;
    form_css = css;
    form_customcss = customcss;
    form_charset = charset;
    form_pageurl = pageurl;
    
    if (browser.isIE55 || browser.isIE6up) {
        // Mac-IE doesn't support RichText-Edit at the moment
        if (browser.isMac) {
            CreateTextarea();
        } else {
            CreateEpoz();
        }
    }
    else if (browser.isGecko) {
        //check to see if midas is enabled
        try {
        
        	// Just a few cleanups for Mozilla
        	
			form_data = form_data.replace(/<strong>/ig,'<b>');        	
			form_data = form_data.replace(/<strong(\s[^>]*)>/ig,'<b$1>');
			form_data = form_data.replace(/<\/strong>/ig,'</b>');

			form_data = form_data.replace(/<em>/ig,'<i>');
			form_data = form_data.replace(/<em(\s[^>]*)>/ig,'<i$1>');
			form_data = form_data.replace(/<\/em>/ig,'</i>');
        
            document.getElementById('EpozIFrame').contentDocument.designMode = "on";
            document.getElementById('EpozIFrame').contentWindow.document.execCommand("undo", false, null);
            CreateEpoz();
        } catch (e) {
            CreateTextarea();
        }
    }
    else {
        CreateTextarea();
    }
}

// Needs to be called by timeout for Mozilla...

function EnableDesignMode() {

    if (browser.isIE5up) {
        frames[Epoz].document.designMode = "On";
    }
    else {
    		// just a try-catch-poll to see
    		// when Mozilla is ready to go...
			try {
				EpozElement.contentDocument.designMode = "on";
			} catch (e) {
				setTimeout(EnableDesignMode, 10);
				return;
			}
    }
	
    // Set all forms in sync with Epoz
    
    if (document.getElementsByTagName)
        var x = document.getElementsByTagName('FORM');
    else if (document.all)
        var x = document.all.tags('FORM');

    for (var i=0;i<x.length;i++) {
        x[i].onsubmit = SyncEpoz;
    }
}


// A submit-wrapper to pass the parameters into the form-element

function SyncEpoz() {
    var html = TidyHTML(GetHTML());
    document.getElementById(form_name).value = html;
}

// Intialize the document

function InitDocument() {
    // Store the Editor-Element in a global variable    
    EpozElement = document.getElementById(Epoz);
    EpozTextArea = document.getElementById(form_name);

    setTimeout(EnableDesignMode, 10);
        
    // Put data into Epoz-Editor
    EpozElement.contentWindow.document.body.innerHTML = form_data;
}

// Returns the current HTML.

function GetHTML(source_mode) {
    if (source_mode == null)
        source_mode = document.getElementById('EpozViewMode').checked;
    if (source_mode) {
        return EpozTextArea.value;
    }
    else {
        try {
            return EpozElement.contentWindow.document.body.innerHTML;
        } catch (e) {
            return EpozElement.value;
        }
    }
}

// Just a XMLRPC to a web-service to clean up the html

function TidyHTML(html) {
    window.status = "Tidying...";
    try {
		// Call EpozTidy one step above the given pageurl.
		// This should avoid some problems with VHM & PageTemplates etc.
		xmlrpchost = form_pageurl + "/..";
        result = XMLRPC.call(xmlrpchost, "EpozTidy", html, form_pageurl);

        errors = result[0];
        output = result[1];
        errordata = result[2];
        
        if (errors != 0) {
            window.status = "Detected errors in the HTML block.";
            alert(errordata);
        }
        else {
            window.status = "Tidying complete.";
        }
        return (output);
    } catch (e) {
        return (html);
    }
}

// -------------------------------------------------------------
// Here are the definitions for the control-and-format-functions

// Format text with RichText-Controls

function FormatText(command, option) {
    EpozElement.contentWindow.focus();
    
    // Mozilla inserts css-styles per default
    
	if (browser.isGecko) {
    	EpozElement.contentWindow.document.execCommand('useCSS',false, true);
    }
    
    EpozElement.contentWindow.document.execCommand(command, false, option);
}


// Insert arbitrary HTML at current selection

function InsertHTML(html) {

    EpozElement.contentWindow.focus();

    if (browser.isIE5up) {
        selection = EpozElement.contentWindow.document.selection;
        range = selection.createRange();
        try {
            range.pasteHTML(html);        
        } catch (e) {
            // catch error when range is evil for IE        
        }
    } else {
        selection = EpozElement.contentWindow.window.getSelection();
        EpozElement.contentWindow.focus();
        if (selection) {
            range = selection.getRangeAt(0);
        } else {
            range = EpozElement.contentWindow.document.createRange();
        } 

        var fragment = EpozElement.contentWindow.document.createDocumentFragment();
        var div = EpozElement.contentWindow.document.createElement("div");
        div.innerHTML = html;

        while (div.firstChild) {
            fragment.appendChild(div.firstChild);
        }

        selection.removeAllRanges();
        range.deleteContents();

        var node = range.startContainer;
        var pos = range.startOffset;

        switch (node.nodeType) {
            case 3:
                if (fragment.nodeType == 3) {
                    node.insertData(pos, fragment.data);
                    range.setEnd(node, pos + fragment.length);
                    range.setStart(node, pos + fragment.length);
                } else {
                    node = node.splitText(pos);
                    node.parentNode.insertBefore(fragment, node);
                    range.setEnd(node, pos + fragment.length);
                    range.setStart(node, pos + fragment.length);
                }
                break;

            case 1:
                node = node.childNodes[pos];
                node.parentNode.insertBefore(fragment, node);
                range.setEnd(node, pos + fragment.length);
                range.setStart(node, pos + fragment.length);
                break;
        }
        selection.addRange(range);
    }
}


// Create an anchor - no browser supports this directly

function CreateAnchor(name) {
	name = prompt(EpozLang["EnterAnchorName"], "");
	if (name) {
		anchorhtml = '<a name="' + name + '" title="' + name + '"></a>';
		InsertHTML(anchorhtml);
	}
}


// Create a Hyperlink - IE has its own implementation

function CreateLink(URL) {
    if (browser.isIE5up == false && ((URL == null) || (URL == ""))) {
        URL = prompt(EpozLang["EnterLinkURL"], "");

        if ((URL != null) && (URL != "")) {
            EpozElement.contentWindow.document.execCommand("CreateLink",false,URL)
        } else {
            EpozElement.contentWindow.document.execCommand("Unlink",false, "")
        }
    } else {
        EpozElement.contentWindow.document.execCommand("CreateLink",false,URL)
    }
}


// Insert image via a URL

function CreateImage(URL) {
    if ((URL == null) || (URL == "")) {
        URL = prompt(EpozLang["EnterImageURL"], "");
    }
    if ((URL != null) && (URL != "")) {
        EpozElement.contentWindow.focus()
        EpozElement.contentWindow.document.execCommand('InsertImage', false, URL);
    }
}


// Creates a simple table

function CreateTable(rows, cols, border, head) {
    rows = parseInt(rows);
    cols = parseInt(cols);

    if ((rows > 0) && (cols > 0)) {
       table = ' <table border="' + border + '">\n';

       for (var i=0; i < rows; i++) {
          table = table + " <tr>\n";
          for (var j=0; j < cols; j++) {
             if(i==0 && head=="1") {
             	table += "  <th>#</th>\n";
            } else {
             	table += "  <td>#</td>\n";
			}            
          }
          table += " </tr>\n";
       }
       table += " </table>\n";
       InsertHTML(table);
    }
    EpozElement.contentWindow.focus()
}


// Sets selected formats
	
function SelectFormat(selectname)
{
    // First one is only a label
    if (selectname.selectedIndex != 0) {
        EpozElement.contentWindow.document.execCommand(selectname.id, false, selectname.options[selectname.selectedIndex].value);
        selectname.selectedIndex = 0;
    }
    EpozElement.contentWindow.focus();
}


// Sets foreground-color

function SetTextColor() {
    EpozColorCommand='forecolor';
    window.open(form_path+'epoz_script_color.html','EpozColor','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=220,height=220');
}    

// Sets background-color

function SetBackColor() {
    EpozColorCommand='backcolor';
    window.open(form_path+'epoz_script_color.html','EpozColor','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=220,height=220');
}    

// Submit color-command to Rich-Text-Controls

function SetColor(color) {

    if (browser.isGecko) {
       EpozElement.contentWindow.document.execCommand('useCSS',false, false);
    }
    
    EpozElement.contentWindow.document.execCommand(EpozColorCommand, false, color);
    EpozElement.contentWindow.focus();
}

// Switch between Source- and Wysiwyg-View

function SwitchViewMode(source_mode)
{
    var html = GetHTML(!source_mode);

    if (source_mode) {
        EpozTextArea.value=TidyHTML(html);
        document.getElementById("EpozToolbar").style.display="none";
        EpozTextArea.style.display="inline";
    } else {
        EpozElement.contentWindow.document.body.innerHTML = html;
        document.getElementById("EpozToolbar").style.display="inline";
        EpozTextArea.style.display="none";
 
        if (browser.isGecko) {
            EpozElement.contentDocument.designMode = "on"; 
        }
    }  
}
