﻿var TinyMCEOptions = {
    // Location of TinyMCE script
    //script_url: '/Content/js/tiny_mce/tiny_mce.js',

    // General options
    theme: "advanced",
    plugins: "safari,inlinepopups,xhtmlxtras,spellchecker,autoresize,tabfocus,paste",
    //,autosave
    // Theme options
    image_list_url:"/ImageManager/",
    theme_advanced_buttons1: "bold,italic,|,bullist,numlist,|,spellchecker",
    //theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
    theme_advanced_buttons2: "", theme_advanced_buttons3: "", theme_advanced_buttons4: "",
    //theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
    //theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",

    theme_advanced_toolbar_location: "top",
    theme_advanced_toolbar_align: "center",
    height: "auto",
    // Example content CSS (should be your site CSS)
    content_css: "Content/css/Dash.css",
    auto_resize: true,

    inline_styles: false,
    spellchecker_languages: "+English=en",
    spellchecker_rpc_url: "/Spelling/Check",
    setup: function(ed) {
        ed.onInit.add(function() {
            ed.makeReadOnly(false);
        });
        // Force Paste-as-Plain-Text
        ed.onPaste.add(function(ed, e, o) {
            ed.execCommand('mcePasteText', true);
            return tinymce.dom.Event.cancel(e);
        });
        ed.onBeforeSetContent.add(function(ed, o) {
            o.content = markdown.toHmtl(o.content);
        });
        ed.onGetContent.add(function(ed, o) {
            o.content = markdown.fromHtml(o.content);
        });
        ed.onChange.add(function(ed, o) {
            var t = this, s = t.settings, DOM = tinymce.DOM, d = t.getDoc();
            if (!DOM.hasClass(d.body, 'mceReadonly')) {
                ed.save();
                $("#" + ed.id).valid();
                $("#" + ed.id).trigger("change");
            }
        });

        ed.makeReadOnly = function(ro) {
            var t = this, s = t.settings, DOM = tinymce.DOM, d = t.getDoc();
            if (ro)
                DOM.addClass(d.body, 'mceReadonly');
            else
                DOM.removeClass(d.body, 'mceReadonly');

            if (!s.readonly && ro) {
                if (!tinymce.isIE) {
                    try {
                        d.designMode = 'Off';
                    } catch (ex) {

                    }
                } else {
                    b = t.getBody();
                    DOM.hide(b);
                    b.contentEditable = false;
                    DOM.show(b);
                }
                s.readonly = true;
            } else if (s.readonly && !ro) {
                if (!tinymce.isIE) {
                    try {
                        d.designMode = 'On';
                        // Design mode must be set here once again to fix a bug where
                        // Ctrl+A/Delete/Backspace didn't work if the editor was added using mceAddControl then removed then added again
                        d.designMode = 'Off';
                        d.designMode = 'On';
                    } catch (ex) {

                    }
                } else {
                    b = t.getBody();
                    DOM.hide(b);
                    b.contentEditable = true;
                    DOM.show(b);
                }
                s.readonly = false;
            }
        };
    }

};
var TinyMCEFullOptions = {
    // Location of TinyMCE script
    //script_url: '/Content/js/tiny_mce/tiny_mce.js',

    // General options
    theme: "advanced",
    plugins: "safari,inlinepopups,xhtmlxtras,spellchecker,tabfocus,paste,advimage",
    //,autosave
    // Theme options

    theme_advanced_buttons1: "bold,italic,|,bullist,numlist,|,spellchecker,|,sub,sup,|, justifyleft, justifycenter, justifyright, |,outdent,indent,blockquote,|,undo,redo,|,link,unlink,image",
        //theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
    theme_advanced_buttons2: "", theme_advanced_buttons3: "", theme_advanced_buttons4: "",
    //theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
    //theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",

    theme_advanced_toolbar_location: "top",
    theme_advanced_toolbar_align: "center",
    height: "400px",
    // Example content CSS (should be your site CSS)
    content_css: "Content/css/Dash.css",
    auto_resize: false,

    inline_styles: false,
    spellchecker_languages: "+English=en",
    spellchecker_rpc_url: "/Spelling/Check",
    setup: function(ed) {
        ed.onInit.add(function() {
            ed.makeReadOnly(false);
        });
        // Force Paste-as-Plain-Text
        ed.onPaste.add(function(ed, e, o) {
            ed.execCommand('mcePasteText', true);
            return tinymce.dom.Event.cancel(e);
        });
        ed.onBeforeSetContent.add(function(ed, o) {
            o.content = markdown.toHmtl(o.content);
        });

        ed.makeReadOnly = function(ro) {
            var t = this, s = t.settings, DOM = tinymce.DOM, d = t.getDoc();
            if (ro)
                DOM.addClass(d.body, 'mceReadonly');
            else
                DOM.removeClass(d.body, 'mceReadonly');

            if (!s.readonly && ro) {
                if (!tinymce.isIE) {
                    try {
                        d.designMode = 'Off';
                    } catch (ex) {

                    }
                } else {
                    b = t.getBody();
                    DOM.hide(b);
                    b.contentEditable = false;
                    DOM.show(b);
                }
                s.readonly = true;
            } else if (s.readonly && !ro) {
                if (!tinymce.isIE) {
                    try {
                        d.designMode = 'On';
                        // Design mode must be set here once again to fix a bug where
                        // Ctrl+A/Delete/Backspace didn't work if the editor was added using mceAddControl then removed then added again
                        d.designMode = 'Off';
                        d.designMode = 'On';
                    } catch (ex) {

                    }
                } else {
                    b = t.getBody();
                    DOM.hide(b);
                    b.contentEditable = true;
                    DOM.show(b);
                }
                s.readonly = false;
            }
        };
    }

};

$(function() {
    $('textarea.richtext').each(function() {
        var t = $(this);
        if (!t.is(":disabled"))
            t.tinymce(TinyMCEOptions);
        else {

            v = $("<div class='richtext'></div>");
            t.before(v);
            t.hide();
            c = new Showdown.converter();
            v.append($(c.makeHtml(t.val())));
        }
    })

    $('textarea.wysiwyg').tinymce(TinyMCEFullOptions);
});







//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
var markdown = {
    fromHtml: function(html) {
        //clean up superfluouse spaces and newlines, as we are only using the raw html to render us.
        cleanHtml = html
            .replace(/\n/g, "")
            .replace(/([ ]{2,})/g, " ")
            .replace(/\&nbsp;/g, " ")
            .replace(/<(strong|STRONG|blur|B)>([ ]*)/g, "$2<strong>")
            .replace(/([ ]*)<\/(strong|STRONG|blur|B)>/g, "</strong>$1")
            .replace(/<(em|EM|i|I)>([ ]*)/g, "$2<em>")
            .replace(/([ ]*)<\/(em|EM|i|I)>/g, "</em>$1")
            .replace(/<(li|LI)>([ ]*)/g, "$2<li>")
            .replace(/([ ]*)<\/(li|LI)>/g, "</li>$1")
            .replace(/<(p|P)>([ ]*)/g, "$2<p>")
            .replace(/([ ]*)<\/(p|P)>/g, "</p>$1")
            .replace(/\<\/li\>([ ]*)/g, "</li>") //</li>[spaces] => </li> trim trailing spaces
            .replace(/([ ]*)\<li\>/g, "<li>") //[spaces]<li>=> <li> trim leading spaces

            .replace(/<li><p>/g, "<li>")          //convert <li><p> blah </p></li> to <li> blah </li>
            .replace(/<\/p><\/li>/g, "</li>")

            .replace(/<p>[ ]{0,}<\/p>/g, "");     //remove <p></p>

        jnode = $("<div>" + cleanHtml + "</div>");
        var olPos = 0;
        $("*", jnode).each(function() {
            t = $(this);
            switch (this.tagName.toLowerCase()) {
                case "div":
                case "p": t.prepend("\n").append("\n"); break;
                case "ul":
                case "ol": olPos = 0; break;
                case "strong":
                case "b": if (t.text().length > 0) t.prepend("**").append("**"); break;
                case "em":
                case "i": if (t.text().length > 0) t.prepend("_").append("_"); break;
                case "li":
                    olPos++;
                    if (this.parentNode.tagName.toLowerCase() == "ol")
                        t.prepend(olPos + ". ");
                    else
                        t.prepend("* ");
                    if (olPos == 1)
                        t.prepend("\n");
                    t.append("\n");

                    break;

            }
        });
        txt = jnode.text().replace(/(\n)*/, "");
        return txt + "\n";
    },

    converter: new Showdown.converter(),

    toHmtl: function(text) {
        return this.converter.makeHtml(text);
    }

}