var InsertFormated = false;


var supportedTags = ["a", "b", "big", "br", "blockquote", "div", "em", "font ", "hr", "i", "img", "input", "li", "ol", "p", "s", "small", "span", "strike", "sub", "sup", "strong", "table", "tbody", "td", "th", "thead", "tr", "u", "ul"];
var supportedAttributes = ["align", "alt", "background", "bgcolor", "border", "cellpadding", "cellspacing", "class", "clear", "color", "colspan", "height", "href", "hspace", "id", "label", "name", "rel", "rowspan", "size", "src", "style", "target", "title", "type", "usemap", "valign", "value", "vspace", "width", "smartlink"];
var domPath;

function toXML(node, isContainerNode) {

    if (isContainerNode)
        domPath = new Array();
    var out = '';
    var unsupportedTag = true;
    var unsupportedContent = false;
    var nodeTagName = node.tagName.toLowerCase();


    if (!isContainerNode) {
        var i = supportedTags.length;
        while (i--)
            if (supportedTags[i] == nodeTagName) {
            unsupportedTag = false;
            break;
        }
    }
    if (unsupportedTag && nodeTagName == "style") {
        unsupportedContent = true;
    }

    if (nodeTagName == "img") {
        for (var i = 0; i < node.attributes.length; i++) {
            if (node.attributes[i].nodeName.toLowerCase() == "src") {
                if (node.attributes[i].nodeValue.toLowerCase().indexOf("file://") == 0) {
                    unsupportedTag = true;
                    unsupportedContent = true;
                }
                break;
            }
        }
    }

    if (!unsupportedTag && nodeTagName == "p") {
        var i = domPath.length;
        while (i--) {
            if (domPath[i] == "p") {
                unsupportedTag = true;
                break;
            }
        }
    }

    if (!unsupportedTag) {
        domPath.push(nodeTagName);
        out += '<' + nodeTagName;
    }

    if (!unsupportedTag) {
        var sortedAttributes = new Array();
        for (var i = 0; i < node.attributes.length; i++) {
            var attr = node.attributes[i];
            var attrName = attr.nodeName.toLowerCase();

            var attributeSupported = false;
            var a = supportedAttributes.length;
            while (a--)
                if (supportedAttributes[a] == attrName) {
                attributeSupported = true;
                break;
            }
            if (!attributeSupported)
                continue;

            var attrValue;
            if (attrName == 'style') { //IE
                attrValue = node.getAttribute(attrName);
                if (attrValue && attrValue.cssText) {
                    attrValue = attrValue.cssText.toLowerCase();
                }
                else {
                    if (typeof (attrValue) != "string")
                        continue;
                }

                if (attrValue.length == 0)
                    continue;

                var aStyles = new Array();
                var aStyleLines = attrValue.split(";");
                for (var j = 0; j < aStyleLines.length; j++) {
                    var line = aStyleLines[j].split(":");
                    if (line.length == 2) {
                        var style = { n: trim(line[0]), v: trim(line[1]) };
                        if (style.v.indexOf(', ') >= 0)
                            style.v = style.v.replace(/\, /g, ',');
                        if (style.n.indexOf('margin-right') < 0 && style.n.indexOf('padding-right') < 0 && style.n.indexOf('border') < 0 && style.n.indexOf('-x') != 0 && style.n.indexOf('mso-') != 0) {
                            aStyles.push(style);
                        }
                    }
                }
                if (aStyles.length > 1)
                    aStyles.sort(compareByVarN);
                var sStyles = '';
                for (var j = 0; j < aStyles.length; j++) {
                    sStyles += aStyles[j].n + ":" + aStyles[j].v + ";";
                }
                attrValue = sStyles;
            }
            else
                attrValue = node.getAttribute(attrName, 2);

            if (
                attrValue
                && !((attrName == "rowspan" || attrName == "colspan") && String(attrValue) == "1")
                && attrName != "contenteditable"
                && attrName.indexOf("_moz_") != 0
                && attrValue != "_moz" //Mozilla fügt beim bearbeiten "_moz" Attribute und "-moz" Styles ein.
                && attrName.indexOf(':') < 0
                && (attrName != "class" || attrValue.toLowerCase().indexOf("mso") != 0)
                ) {
                var nValue = String(attrValue).replace(/(\-moz).+/g, "");
                sortedAttributes.push({ n: attrName, v: nValue });
            }
        }

        if (sortedAttributes.length > 0) {
            if (sortedAttributes.length > 1)
                sortedAttributes.sort(compareByVarN);
            for (var i = 0; i < sortedAttributes.length; i++) {
                out += ' ' + sortedAttributes[i].n + "='" + sortedAttributes[i].v + "'";
            }
        }

    }


    function compareByVarN(a, b) {
        if (a.n < b.n)
            return -1;
        else
            return 1;
    }

    function trim(str) {
        while (str.indexOf(' ') == 0)
            str = str.substr(1);
        while (str.lastIndexOf(' ') == str.length)
            str = str.substr(0, str.length - 1);
        return str;
    }

    var content = '';
    if (!unsupportedContent)
        content = addChildNodes(node.childNodes);

    if (unsupportedTag) {
        if (content.length > 0)
            out += content;
    }
    else {

        if (nodeTagName == "img" || nodeTagName == "hr" || nodeTagName == "br") {
            out += '/>';
        }
        else {

            out += '>';
            out += content;
            out += '</' + nodeTagName + '>';
        }
        domPath.pop();

    }
    return out;
}

function addChildNodes(childNodes) {
    var content = '';
    if (childNodes) {
        for (var i = 0; i < childNodes.length; i++) {
            var childNode = childNodes[i];
            switch (childNode.nodeType) {
                case 1:     // ELEMENT_NODE
                    content += toXML(childNode);
                    break;
                case 2:     // ATTRIBUTE_NODE
                    break;
                case 8:    // COMMENT_NODE
                    break;
                case 3:     // TEXT_NODE
                case 4:     // CDATA_SECTION_NODE
                case 5:     // ENTITY_REFERENCE_NODE
                case 6:     // ENTITY_NODE
                case 7:     // PROCESSING_INSTRUCTION_NODE

                case 9:     // DOCUMENT_NODE
                case 10:    // DOCUMENT_TYPE_NODE
                case 11:    // DOCUMENT_FRAGMENT_NODE
                case 12:    // NOTATION_NODE                    
                    content += childNode.nodeValue.replace(/\</g, '&lt;').replace(/\>/g, '&gt;').replace(/[\r\n]+/g, " "); ;
                    break;
            }
        }
    }
    return content;
}



function PreviewToHTML(PropertyID, CleanupHTML) {
    if (window.document.getElementById("prop_" + PropertyID) && window.document.getElementById("oDiv_" + PropertyID)) {
        var currentRawHTML = document.getElementById("oDiv_" + PropertyID).innerHTML;
        if (lastRawHTML != currentRawHTML) {
            var html;
            if (CleanupHTML)
                html = toXML(document.getElementById("oDiv_" + PropertyID), true);
            else
                html = currentRawHTML;
            if (window.document.getElementById("prop_" + PropertyID).value != html)
                window.document.getElementById("prop_" + PropertyID).value = html;
            SetFormatSelection(PropertyID);
            lastRawHTML = currentRawHTML;


            var charcount = window.document.getElementById("CharCounter_" + PropertyID);
            if (charcount) {

                var textOnly = document.getElementById("oDiv_" + PropertyID).innerText;

                textOnly = textOnly.replace(/\n/g, '').replace(/\r/g, '').replace(/ /g, '');
                var curLen = textOnly.length;
                 charcount.innerHTML = curLen;
            }

        }
    }
}

function htmleditorchanged(PropertyID, CleanupHTML) {
    PreviewToHTMLFireFox(PropertyID, CleanupHTML);
    window.setTimeout("htmleditorchanged('" + PropertyID + "'," + CleanupHTML + ")", 100);
}

function CreateFireFoxLink(PropertyID) //doesn't work
{

    var url = window.prompt("Url:", "");
    window.document.getElementById("doc" + PropertyID).contentDocument.execCommand('CreateLink', true, url);

}
var lastRawHTML;
function PreviewToHTMLFireFox(PropertyID, CleanupHTML) {
    try {
        if (window.document.getElementById("prop_" + PropertyID)) {
            var currentRawHTML = window.document.getElementById("doc" + PropertyID).contentDocument.body.innerHTML;
            if (lastRawHTML != currentRawHTML) {
                var html;
                if (CleanupHTML)
                    html = toXML(document.getElementById("doc" + PropertyID).contentDocument.body, true);
                else
                    html = currentRawHTML;
                if (window.document.getElementById("prop_" + PropertyID).value != html) {
                    window.document.getElementById("prop_" + PropertyID).value = html;
                }
                lastRawHTML = currentRawHTML;

                var charcount = window.document.getElementById("CharCounter_" + PropertyID);
                if (charcount) {


                    var textOnly =  window.document.getElementById("doc" + PropertyID).contentDocument.body.textContent;
                    
                    
                   textOnly = textOnly.replace(/\n/g, '').replace(/\r/g, '').replace(/ /g, '');

                    
                    var curLen = textOnly.length;
                    //                if (curLen == 0)
                    //                    charcount.innerText = '';
                    //                else

                    charcount.innerHTML = curLen;
                }

            }
        }
    }
    catch (e) {
        if (CleanupHTML)
            PreviewToHTMLFireFox(PropertyID, false)
    }

    return false;
}

function SetStyleClass(className, target) {
    try {
        var sel = document.selection;
        if (sel != null && className != "0") {
            var rng;
            rng = sel.createRange();
            var oRng1 = document.body.createTextRange();
            oRng1.moveToElementText(target);
            if (oRng1.inRange(rng)) {
                var el;
                if (rng.isEqual(oRng1)) {
                    ClearStyleSpans(target, true);
                    rng.pasteHTML("<span class='" + className + "'>" + rng.htmlText + "</span>");
                }
                else {
                    el = rng.parentElement();
                    oRng1.moveToElementText(el);
                    if (el.tagName != "SPAN" || rng.text != oRng1.text)
                        rng.pasteHTML("<span class='" + className + "'>" + rng.htmlText + "</span>");
                    else {
                        el.className = className;

                    }
                    rng = sel.createRange();
                    el = rng.parentElement();
                    ClearStyleSpans(el, true);

                }
            }
        }
    }
    catch (e) {
        alert('SetStyleClass-Error: ' + e);
    }

}

function ClearStyleSpans(el, bDel) {
    var i;
    var child;
    for (i = 0; i < el.childNodes.length; i++) {
        child = el.childNodes.item(i);
        ClearStyleSpans(child, true);
        if (child.tagName == "SPAN") {
            //child.className="x";

            if (bDel)
                if (child.innerHTML)
                if (child.outerHTML)
                child.outerHTML = child.innerHTML;
        }

    }
}
function create_table(h, b, target, typeSel) {
    var outHTML;
    var style;
    if (typeSel != null) {
        style = typeSel.value;
    }
    else {
        style = "db_classic_";
    }
    h++;
    b++;
    outHTML = "<table class=" + style + "table  border='0' cellpadding='0' cellspacing='0'>";
    var i, j;
    for (i = 1; i != h; i++) {
        if (i == 1)
            outHTML = outHTML + "<tr class=" + style + "header_row>";
        else if (i % 2 == 0)
            outHTML = outHTML + "<tr class=" + style + "data_row>";
        else
            outHTML = outHTML + "<tr class=" + style + "data_row_odd>";
        for (j = 1; j != b; j++) {
            outHTML = outHTML + "<td valign='top'>" + i + "x" + j + "</td>";
        }
        outHTML = outHTML + "</tr>";
    }
    outHTML = outHTML + "</table>";
    var sel = document.selection;

    if (sel != null) {
        var rng;
        if (sel.type == 'Text')
            rng = sel.createRange();
        else
            rng = document.body.createTextRange();

        if (rng != null) {
            var oRng1 = document.body.createTextRange();
            oRng1.moveToElementText(target);
            if (oRng1.inRange(rng))
                rng.pasteHTML(outHTML);
            else {
                oRng1.collapse(false);
                oRng1.pasteHTML(outHTML);
            }
        }
    }
}

function select_fields(h, b, UniqueID) {

    var i, j;
    for (i = 1; i <= 6; i++) {
        for (j = 1; j <= 6; j++) {
            if ((j <= b) && (i <= h))
                document.all(UniqueID + "_" + i + "_" + j).style.backgroundColor = "#7794C5";
            else
                document.all(UniqueID + "_" + i + "_" + j).style.backgroundColor = "transparent";
        }
    }

}

var lastHtmlEditor;

function createLink(targetObj, EditorURL, WriteToTextBox) {
    if (document.all) {
        if (WriteToTextBox) {
            var targetURL = window.showModalDialog(EditorURL, "", "dialogHeight:460px; dialogWidth:650px;scroll:no;help:no;status:no");
            if (targetURL) {
                targetObj.value = targetURL;
            }
        }
        else {
            var sel = document.selection;
            if (sel != null) {
                var rng = sel.createRange();
                if (rng != null) {

                    var oRng1 = document.body.createTextRange();
                    try {
                        oRng1.moveToElementText(targetObj);
                    }
                    catch (ex) {
                        //window.alert("orng1.moveto..."+ex);
                    }

                    var targetURL = window.showModalDialog(EditorURL, "", "dialogHeight:460px; dialogWidth:650px;scroll:no;help:no;status:no");

                    //window.alert(targetURL);
                    if (targetURL) {
                        if (oRng1.inRange(rng))
                            rng.pasteHTML(targetURL + rng.text + '</a>');
                        else {
                            oRng1.collapse(false);
                            oRng1.pasteHTML(targetURL + '%Link%</a>');
                        }
                    }
                }
            }
        }
    }
    else {
        lastHtmlEditor = targetObj;
        window.open(EditorURL, "", "height=460,width=550,scroll=no,status=no");

    }

}

function SetFormatSelection(PropertyID) {

    var sel = document.selection;
    if (sel != null) {

        if (sel.type != "Text")
            return;
        var rng = sel.createRange();


        var element = rng.parentElement();


        try {

            var htmlRange = sel.createRange();
            htmlRange.moveToElementText(document.all["oDiv_" + PropertyID]);


            if (htmlRange.inRange(rng) && document.all["StyleSelection_" + PropertyID]) {
                while (element != null && element.className == '')
                    element = element.parentElement;
                if (element != null) {
                    if (element.className != "")
                        document.all["StyleSelection_" + PropertyID].value = element.className;
                    else
                        document.all["StyleSelection_" + PropertyID].value = '0';
                }
                else
                    document.all["StyleSelection_" + PropertyID].value = '0';
            }

        }
        catch (e) {
        }
    }
}

function HTMLToPreview(PropertyID) {

    document.all["oDiv_" + PropertyID].innerHTML = document.all["prop_" + PropertyID].value;
}

function SimplifyHTML(target) {
    target.innerHTML = toXML(target, true);
}

function CreateColorButton(targetName) {
    try {
        lastSelection = document.selection.createRange();
        var targetObj = document.getElementById(targetName);
        //document.body.insertBefore(targetObj, theForm);
        targetObj.style.display = "block";
        targetObj.style.left = (window.event.clientX + 10) + "px";
        targetObj.style.top = (window.event.clientY + document.body.scrollTop + 10) + "px";

    }
    catch (e) {
        
        window.alert('CreateColorButton: ' + e);
    }
}

function CreateColorButtonNoRange(targetName) {

    //window.alert(targetName);
    if (document.all[targetName].style.display == "none") {
        document.body.insertBefore(document.all[targetName]);
        document.all[targetName].style.display = "block";
        document.all[targetName].style.left = window.event.clientX + 10;
        document.all[targetName].style.top = window.event.clientY + document.body.scrollTop + 10;
    }
    else
        document.all[targetName].style.display = "none";
}

function InsertTable(target) {

    document.body.insertBefore(target);
    target.style.display = "block";
    target.style.left = window.event.clientX + document.body.scrollLeft - target.scrollWidth / 2;
    target.style.top = window.event.clientY + document.body.scrollTop + 10;
}


function returnColor(UniqueID) {
    var CallbackFunc = new String(document.all['CallBack_' + UniqueID].value);
    var re = /%color%/i;

    CallbackFunc = CallbackFunc.replace(re, document.all['ColorValue_' + UniqueID].value);

    eval(CallbackFunc);
}

function CancelSelection(UniqueID) {
    eval(document.all['CancelCallBack_' + UniqueID].value);

}

function setSelectedColor(sColor, UniqueID) {
    try {
        sColor = sColor.toUpperCase();
        document.all.tryColor.style.color = sColor;
        document.all['ColorValue_' + UniqueID].value = sColor;
        document.all['ColorTextbox' + UniqueID].value = sColor;
        ColorPreview(sColor, UniqueID);
    }
    catch (e) {
        alert('ungültige Farbauswahl');  //todo:translate
    }
    try {
        var re = /#/i;
        var prevColor = (document.all['prevColor_' + UniqueID].value).replace(re, '');
        document.all['prevColor_' + UniqueID].value = sColor;
        if (document.all['colorDiv_' + UniqueID + '_' + prevColor] != null) {
            document.all['colorDiv_' + UniqueID + '_' + prevColor].style.borderStyle = "";
        }
        if (document.all['colorDiv_' + UniqueID + '_' + (sColor.replace(re, ''))] != null) {
            document.all['colorDiv_' + UniqueID + '_' + (sColor.replace(re, ''))].style.borderStyle = "dashed";
        }
    }
    catch (e) {
    }
}

function getColor(UniqueID) {
    return document.all['ColorValue_' + UniqueID].value;
}

function ColorPreview(sColor, UniqueID) {
    document.all['Preview' + UniqueID].style.backgroundColor = sColor;
}


function callColorDlg(UniqueID) {
    var sSelectedColor = getColor(UniqueID);
    if (sSelectedColor == null)
        var sColor = document.all.dlgHelper.ChooseColorDlg();
    else
        var sColor = document.all.dlgHelper.ChooseColorDlg(sSelectedColor);
    sColor = sColor.toString(16);
    if (sColor.length < 6) {
        var sTempString = "000000".substring(0, 6 - sColor.length);
        sColor = sTempString.concat(sColor);
    }
    setSelectedColor('#' + sColor, UniqueID);
}


function MouseEnter(obj) {
    obj.style.backgroundColor = '#B4B7C2';
    obj.style.borderColor = '#0A246A';
}

function MouseLeave(obj) {
    obj.style.backgroundColor = '#efefef';
    obj.style.borderColor = '#efefef';
}

function spellcheck(ctrl, useAdvancedSpellCheck) {
    if (useAdvancedSpellCheck) {
        try {
            advancedSpellCheck(ctrl);
        }
        catch (e)
        { }
    }
}

function pasteFromClipboard() {

    if (InsertFormated == false) {
        window.event.returnValue = false;
        document.selection.createRange().text = window.clipboardData.getData('Text');
    }
}

function triggerPaste(thectrl) {
    if (document.selection.type == 'None') {
        var ctrl = thectrl;
        thectrl.focus();
        ctrl = document.selection.createRange();
        ctrl.execCommand('Paste');
    }
    else
        document.execCommand('Paste');
}
