//一键排版
(function () {
    CKEDITOR.plugins.add('autoformat', {
        requires: ['styles', 'button'],
        init: function (a) {
            a.addCommand('autoformat', CKEDITOR.plugins.autoformat.commands.autoformat);
            a.ui.addButton('autoformat', {
                label: "一键排版",
                command: 'autoformat',
                icon: this.path + "images/autoformat.gif"
            });
        }
    });
    CKEDITOR.plugins.autoformat = {
        commands: {
            autoformat: {
                exec: function (editor) {
                    formatText(editor);
                }
            }
        }
    };

    function formatText(editor) {
        var myeditor = editor;
        if (myeditor.mode == "wysiwyg") {
            var tempimg = new Array();
            var temptable = new Array();
            var tempobject = new Array();
            var tempinput = new Array();
            var tempembed = new Array();
            var tempform = new Array();

            var isPart = false;
            if (!isPart) {
                var tmpDiv = document.createElement("DIV");
                var editorhtml = myeditor.getData();
                editorhtml = editorhtml.replace(/<div style="page-break-after: always;?">\s*<span style="display: none;?">&nbsp;<\/span>\s*<\/div>/gi, '<p>[page]</p>');
                tmpDiv.innerHTML = editorhtml.replace(/&nbsp;/gi, '');

                if (window.navigator.userAgent.toLowerCase().indexOf("msie") > 0) {
                    tmpDiv.innerHTML = tmpDiv.innerHTML.replace(/<\/p>/gi, '<br /><\/p>');
                }

                var forms = tmpDiv.getElementsByTagName("form");
                if (forms != null && forms.length > 0) {
                    for (var i = 0; i < forms.length; i++) {
                        tempform[tempform.length] = forms[i].outerHTML;
                    }
                    var formatformCount = 0;
                    for (var j = 0; j < forms.length; ) {
                        forms[j].outerHTML = "#FormatFormID_" + formatformCount + "#";
                        formatformCount++;
                    }
                }

                var inputs = tmpDiv.getElementsByTagName("input");
                if (inputs != null && inputs.length > 0) {
                    for (var i = 0; i < inputs.length; i++) {
                        tempinput[tempinput.length] = inputs[i].outerHTML;
                    }
                    var formatinputCount = 0;
                    for (var j = 0; j < inputs.length; ) {
                        inputs[j].outerHTML = "#FormatInputID_" + formatinputCount + "#";
                        formatinputCount++;
                    }
                }

                var objects = tmpDiv.getElementsByTagName("OBJECT");
                if (objects != null && objects.length > 0) {
                    for (var j = 0; j < objects.length; j++) {
                        tempobject[tempobject.length] = objects[j].outerHTML;
                    }
                    var formatobjectCount = 0;
                    for (var j = 0; j < objects.length; ) {
                        setOuterHtml(objects[j], "#FormatObjectID_" + formatobjectCount + "#");
                        formatobjectCount++;
                    }
                }

                var embeds = tmpDiv.getElementsByTagName("embed");
                if (embeds != null && embeds.length > 0) {
                    for (var i = 0; i < embeds.length; i++) {
                        tempembed[tempembed.length] = embeds[i].outerHTML;
                    }
                    var formatembedCount = 0;
                    for (var j = 0; j < embeds.length; ) {
                        setOuterHtml(embeds[j], "#FormatEmbedID_" + formatembedCount + "#");
                        formatembedCount++;
                    }
                }

                var tables = tmpDiv.getElementsByTagName("TABLE");
                if (tables != null && tables.length > 0) {
                    for (var j = 0; j < tables.length; j++) {
                        var tab = tables[j];

                        tab.setAttribute("border", "1");
                        tab.setAttribute("cellspacing", "0");
                        tab.setAttribute("cellspacing", "0");
                        tab.style.cssText = "border: 1px solid #000000;border-collapse: collapse;";

                        var tds = tab.getElementsByTagName("td");
                        for (var i = 0; i < tds.length; i++) {
                            tds[i].innerHTML = tds[i].innerText;
                            tds[i].height = tds[i].style.height || tds[i].height;
                            tds[i].width = tds[i].style.width || tds[i].width;
                            tds[i].removeAttribute("style");
                        }

                        var ths = tab.getElementsByTagName("th");
                        for (var i = 0; i < ths.length; i++) {
                            ths[i].removeAttribute("style");
                            ths[i].removeAttribute("scope");
                        }

                        var trs = tab.getElementsByTagName("tr");
                        for (var i = 0; i < trs.length; i++) {
                            trs[i].removeAttribute("style");
                        }

                        temptable[temptable.length] = tab.outerHTML;
                    }
                    var formattableCount = 0;
                    for (var j = 0; j < tables.length; ) {
                        setOuterHtml(tables[j], "#FormatTableID_" + formattableCount + "#");
                        formattableCount++;
                    }
                }

                var imgs = tmpDiv.getElementsByTagName("IMG");
                if (imgs != null && imgs.length > 0) {
                    for (var j = 0; j < imgs.length; j++) {
                        var t = document.createElement("IMG");
                        t.alt = imgs[j].alt;
                        t.src = jQuery(imgs[j]).attr("src");
                        t.width = parseInt(imgs[j].style.width) || imgs[j].width;
                        t.height = parseInt(imgs[j].style.height) || imgs[j].height;
                        t.align = imgs[j].align;
                        tempimg[tempimg.length] = t;
                    }
                    var formatImgCount = 0;
                    for (var j = 0; j < imgs.length; ) {
                        setOuterHtml(imgs[j], "#FormatImgID_" + formatImgCount + "#");
                        formatImgCount++;
                    }
                }
                var html = processFormatText(tmpDiv.innerText);
                html = html.replace(/<p>\[page\]<\/p>/gi, '<div style="page-break-after: always;"><span style="display: none;">&nbsp;</span></div>');
                if (temptable != null && temptable.length > 0) {
                    for (var j = 0; j < temptable.length; j++) {
                        var tablehtml = temptable[j];
                        html = html.replace("#FormatTableID_" + j + "#", tablehtml);
                    }
                }

                if (tempobject != null && tempobject.length > 0) {
                    for (var j = 0; j < tempobject.length; j++) {
                        var objecthtml = "<p align=\"center\">" + tempobject[j] + "</p>";
                        html = html.replace("#FormatObjectID_" + j + "#", objecthtml);
                    }
                }

                if (tempform != null && tempform.length > 0) {
                    for (var j = 0; j < tempform.length; j++) {
                        var formhtml = tempform[j];
                        html = html.replace("#FormatFormID_" + j + "#", formhtml);
                    }
                }

                if (tempinput != null && tempinput.length > 0) {
                    for (var j = 0; j < tempinput.length; j++) {
                        var inputhtml = tempinput[j];
                        html = html.replace("#FormatInputID_" + j + "#", inputhtml);
                    }
                }

                if (tempembed != null && tempembed.length > 0) {
                    for (var j = 0; j < tempembed.length; j++) {
                        var embedhtml = "<p align=\"center\">" + tempembed[j] + "</p>";
                        html = html.replace("#FormatEmbedID_" + j + "#", embedhtml);
                    }
                }

                if (tempimg != null && tempimg.length > 0) {
                    for (var j = 0; j < tempimg.length; j++) {
                        var imgheight = "";
                        var imgwidth = "";
                        if (tempimg[j].height != 0)
                            imgheight = " height=\"" + tempimg[j].height + "\"";
                        if (tempimg[j].width != 0)
                            imgwidth = " width=\"" + tempimg[j].width + "\"";
                        var imgalign = "";
                        if (tempimg[j].align != "")
                            imgalign = " align=\"" + tempimg[j].align + "\"";
                        var imghtml = "<p align=\"center\"><img src=\"" + jQuery(tempimg[j]).attr("src") + "\" alt=\"" + tempimg[j].alt + "\"" + imgwidth + " " + imgheight + " align=\"" + tempimg[j].align + "\" border=\"0\"></p>";
                        html = html.replace("#FormatImgID_" + j + "#", imghtml);
                    }
                }

                while (html.indexOf("</p></p>") != -1) html = html.replace("</p></p>", "</p>");
                while (html.indexOf('<p><p align="center">') != -1) html = html.replace('<p><p align="center">', '<p align="center">');
                editor.setData(html);

            }
        } else {
            alert('必须在设计模式下操作！');
        }
    }

    function processFormatText(textContext) {
        var text = dbc2Sbc(textContext);
        var prefix = "";
        var tmps = text.split("\n");
        var html = "";
        for (var i = 0; i < tmps.length; i++) {
            var tmp = tmps[i].trim();
            if (tmp.length > 0) {
                var reg = /#Format[A-Za-z]+_\d+#/gi;
                var f = reg.exec(tmp);
                if (f != null) {
                    var str = f.toString();
                    if (str.substring(0, 12) == "#FormatInput") {
                        html += "<p style='text-indent:2em;'>" + tmp + "</p>\n";
                    } else {
                        tmp = tmp.replace(/#Format[A-Za-z]+_\d+#/gi, '');
                        html += f;
                        if (tmp != "")
                            html += "<p align=\"center\">" + tmp + "</p>\n";
                    }
                } else {
                    html += "<p style='text-indent:2em;'>" + tmp + "</p>\n";
                }
            }
        }
        return html;
    }

    function dbc2Sbc(str) {
        var result = '';
        for (var i = 0; i < str.length; i++) {
            var code = str.charCodeAt(i);

            if (code > 65281 && code < 65373 && code != 65292 && code != 65306 && code != 65307 && code != 65311) {
                result += String.fromCharCode(str.charCodeAt(i) - 65248);
            } else {
                result += str.charAt(i);
            }
        }
        return result;
    }

    function setOuterHtml(element, html) {
        if (window.navigator.userAgent.toLowerCase().indexOf("msie") > 0) {

            var tempElement = document.createElement("p");
            if (IEVersion() == "7.0") {
                tempElement.innerHTML = "<br/>" + html + "<br/>";
            } else {
                tempElement.innerHTML = html;
            }
            element.parentNode.appendChild(tempElement);
            element.parentNode.replaceChild(tempElement, element);
        } else {
            element.outerHTML = "\n" + html + "\n";
        }
    }

    function IEVersion() {
        var userAgent = window.navigator.userAgent; //取得浏览器的userAgent字符串
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        return fIEVersion;
    }

    String.prototype.trim = function () {
        return this.replace(/(^[\s　]*)|([\s　]*$)/g, "");
    };

    String.prototype.leftTrim = function () {
        return this.replace(/(^\s*)/g, "");
    };

    String.prototype.rightTrim = function () {
        return this.replace(/(\s*$)/g, "");
    };
})();