/*
 * HTMLField, client version
 *
 * Copyright, Gerben <www.gerbenvv.nl>
 */

/*
  browsers supported:

  IE6
  IE7

  FF2
  FF3

  Safari 9
  Opera (limited)
*/

var resource_path;

var ie    = (navigator.appName == "Microsoft Internet Explorer");
var ff    = (navigator.appName == "Netscape");
var opera = (navigator.appName == "Opera");

var data = new Object();

function InitHTMLField(name, _resource_path) {
    resource_path = _resource_path;

    content = document.getElementById(name);

    document.write(' \
      <iframe id="iframe_' + name + '" class="iframe ' + content.className + '" frameborder="0" border="0"></iframe> \
    ');

    iframe = document.getElementById("iframe_" + name);

    try {
        doc = iframe.contentWindow.document;

        doc.open();
        doc.write(
          "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" " +
          "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
          "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head>" +
          "<link rel=\"stylesheet\" href=\"" +
          resource_path +
          "/iframe.css\" type=\"text/css\" />" +
          "</head><body>" +
          content.value +
          ((ff && (content.value == "")) ? "<br />" : "") +
          "</body></html>"
        );
        doc.close();

        if (ie) {
            doc.body.contentEditable = true;

            for (i = 0; i < document.forms.length; i++) {
                document.forms[i].attachEvent("onsubmit", function() {
                    UpdateContent(name);
                });
            }

            events = ["onkeydown", "onkeyup", "onmouseup"];
            for (id in events) {
                doc.attachEvent(events[id], function(e) {
                    UpdateButtons(name);
                });
            }
        } else {
            doc.designMode = "on";

            for (i = 0; i < document.forms.length; i++) {
                document.forms[i].addEventListener("submit", function() {
                    UpdateContent(name);
                }, false);
            }

            events = ["keydown", "keyup", "mousedown", "mouseup"];
            for (id in events) {
                doc.addEventListener(events[id], function() {
                    UpdateButtons(name);
                }, false);
            }
        }
    } catch (e) {
        iframe.style.display = "none";

        document.getElementById("warning_" + name).style.display = "";

        return;
    }

    data[name].content = content;
    data[name].iframe  = iframe;

    if (data[name].chose) {
        data[name].html   = document.getElementById("html_"   + name);
        data[name].nohtml = document.getElementById("nohtml_" + name);
        data[name].toggle = document.getElementById("toggle_" + name);

        data[name].html.style.display   = "none";
        data[name].nohtml.style.display = "";

        if (data[name].toggle.value != "1") {
            DisableHTMLField(name);
            return;
        }
    }

    buttons = ["bold", "underline", "italic", "subscript", "superscript",
               "outdent", "indent", "bullets", "numbers", "link", "unlink", "image"];
    for (id in buttons) {
        EnableButton(buttons[id], name);
    }

    content.style.display = "none";

    setTimeout("OnLoad('" + name + "');", 50);
}

function OnLoad(name) {
    doc = data[name].iframe.contentWindow.document;
    try {
        doc.execCommand("styleWithCSS", false, false);
    } catch(e) {
        try {
            doc.execCommand("useCSS", false, true);
        } catch (e) { }
    }

    UpdateButtons(name);
}

function DisableHTMLField(name) {
    buttons = ["bold", "underline", "italic", "subscript", "superscript",
               "outdent", "indent", "bullets", "numbers", "link", "unlink", "image"];
    for (id in buttons) {
        DisableButton(buttons[id], name);
    }

    iframe  = data[name].iframe;
    content = data[name].content;
    html    = data[name].html;
    nohtml  = data[name].nohtml;
    toggle  = data[name].toggle;

    content.style.display = "";
    iframe.style.display  = "none";
    html.style.display    = "";
    nohtml.style.display  = "none";

    toggle.value = "0";

    doc = iframe.contentWindow.document;

    if (ie) {
        content.value            = iframe.contentWindow.document.body.innerText;
        doc.body.contentEditable = false;
    } else {
        content.value  = GetTextContent(name);
        doc.designMode = "off";
    }

    content.focus();
}

function EnableHTMLField(name) {
    buttons = ["bold", "underline", "italic", "subscript", "superscript",
               "outdent", "indent", "bullets", "numbers", "link", "unlink"];
    for (id in buttons) {
        EnableButton(buttons[id], name);
    }

    iframe  = data[name].iframe;
    content = data[name].content;
    html    = data[name].html;
    nohtml  = data[name].nohtml;
    toggle  = data[name].toggle;

    content.style.display = "none";
    iframe.style.display  = "";
    html.style.display    = "none";
    nohtml.style.display  = "";

    toggle.value = "1";

    iframe.contentWindow.document.body.innerHTML = content.value
    .replace(/&/g, "&amp;")
    .replace(/"/g, "&quot;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/ /g, "&nbsp;")
    .replace(/\n/g, "<br>");

    doc = iframe.contentWindow.document;

    if (ie) {
        doc.body.contentEditable = true;
    } else {
        doc.designMode = "on";
    }

    if (!opera)
        iframe.contentWindow.focus();

    UpdateButtons(name);
}

function EnableButton(id, name) {
    button = document.getElementById(id + "_" + name);

    if (button) {
        button.firstChild.src = resource_path
                              + "/images/"
                              + id
                              + ".png";
    }
}

function DisableButton(id, name) {
    button = document.getElementById(id + "_" + name);

    if (button) {
        button.className      = "toolbutton";
        button.firstChild.src = resource_path
                              + "/images/"
                              + id
                              + "_disabled.png";
    }
}

function UpdateButtons(name) {
    doc = data[name].iframe.contentWindow.document;

    commands = {
      "bold":        "bold",
      "underline":   "underline",
      "italic":      "italic",
      "subscript":   "subscript",
      "superscript": "superscript",
      "bullets":     "insertunorderedlist",
      "numbers":     "insertorderedlist"
    };

    for (buttonid in commands) {
        button = document.getElementById(buttonid + "_" + name);
        if (button) {
            if (doc.queryCommandState(commands[buttonid])) {
                button.className = "toolbutton_active";
            } else {
                button.className = "toolbutton";
            }
        }
    }

    commands = {
      "outdent": "outdent",
      "indent":  "indent",
      "link":    "createlink",
      "unlink":  "unlink"
    };

    for (button in commands) {
        if (doc.queryCommandEnabled(commands[button])) {
            EnableButton(button, name);
        } else {
            DisableButton(button, name);
        }
    }
}

function CreateLink(name) {
    iframe = data[name].iframe;

    if ((href = prompt(l.enterdestws, "http://")) && (href != "http://")) {
        try {
            iframe.contentWindow.document.execCommand("createlink", false, href);
            iframe.contentWindow.focus();
        } catch(e) { }
    }

    UpdateButtons(name);
}

function FormatText(name, command) {
    iframe = data[name].iframe;

    try {
        iframe.contentWindow.focus();
        iframe.contentWindow.document.execCommand(command, false, null);
        iframe.contentWindow.focus();
    } catch(e) { }

    UpdateButtons(name);
}

function UpdateContent(name) {
    iframe  = data[name].iframe;
    content = data[name].content;
    toggle  = data[name].toggle;

    if (!toggle || (toggle.value == "1")) {
        content.value = iframe.contentWindow.document.body.innerHTML;
    }
}

function GetTextContent(name) {
    iframe = data[name].iframe;

    walker = iframe.contentWindow.document.createTreeWalker(
      iframe.contentWindow.document.body,
      NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
      { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } },
      false
    );

    content = "";
    while (walker.nextNode()) {
        if (walker.currentNode.nodeName == "BR") {
            content += "\n";
        } else if (walker.currentNode.nodeName == "LI") {
            content += "\n*  ";
        } else if (walker.currentNode.nodeName == "#text") {
            content += walker.currentNode.data;
        }
    }

    if (ff && (content.substr(-1) == "\n")) {
        content = content.substr(0, content.length - 1);
    }

    return content;
}

function DrawToolbar(name, chose) {
   data[name] = new Object();

   data[name].chose = chose;

   document.write(' \
     <span class="toolbutton" title="' + l.bold + '" onclick="FormatText(\'' + name + '\', \'bold\');"\
     id="bold_' + name + '"><img src="images/htmlfield/bold_disabled.png" /></span> \
     <span class="toolbutton" title="' + l.underline + '" onclick="FormatText(\'' + name + '\', \'underline\');"\
     id="underline_' + name + '"><img src="images/htmlfield/underline_disabled.png" /></span> \
     <span class="toolbutton" title="' + l.italic + '" onclick="FormatText(\'' + name + '\', \'italic\');"\
     id="italic_' + name + '"><img src="images/htmlfield/italic_disabled.png" /></span> \
     <span class="toolbutton" title="' + l.bulletlist + '" onclick="FormatText(\'' + name + '\', \'insertunorderedlist\');"\
     id="bullets_' + name + '"><img src="images/htmlfield/bullets_disabled.png" /></span> \
     <span class="toolbutton" title="' + l.numberedlist + '" onclick="FormatText(\'' + name + '\', \'insertorderedlist\');"\
     id="numbers_' + name + '"><img src="images/htmlfield/numbers_disabled.png" /></span> \
     <span class="toolbutton" title="' + l.createlink + '" onclick="CreateLink(\'' + name + '\');"\
     id="link_' + name + '"><img src="images/htmlfield/link_disabled.png" /></span> \
     <span class="toolbutton" title="' + l.removelink + '" onclick="FormatText(\'' + name + '\', \'unlink\');"\
     id="unlink_' + name + '"><img src="images/htmlfield/unlink_disabled.png" /></span> \
     &nbsp;&nbsp; \
   ');

   if (chose) {
       document.write('\
         <a href="javascript:DisableHTMLField(\'' + name + '\');" id="nohtml_' + name + '" style="display: none;"> \
          ' + l.plaineditor + ' \
         </a> \
         <a href="javascript:EnableHTMLField(\'' + name + '\');" id="html_' + name + '" style="display: none;"> \
          ' + l.richeditor + ' \
         </a> \
       ')
   } else {
       document.write('\
         <span id="warning_' + name + '" style="display: none;"><b>You browser is not currently supported!</b></span> \
       ');
   }
}

