var JMEditor = parent.JMEditor || {};
var JME_TOP_VERSION = 0;
var JME_VERSION_MSG = "";

document.write(
    "<link href=\"" + "../../3rdparty/mathquill/mathquill.css\" rel=\"stylesheet\" type=\"text/css\" />" +
        "<script type=\"text/javascript\" src=\"" + "../../../../../share//assert/js//3rdparty/jquery/2.0.3/jquery.js\"></script>" +
        "<script type=\"text/javascript\" src=\"" + "../../3rdparty/mathquill/mathquill.min.js\"></script>" +
        "<script type=\"text/javascript\" src=\"" + "asset/js/ckeditor/ckeditor.js\"></script>" +
        "<script type=\"text/javascript\">function callJmeInit(){if(window.jQuery){jmeInit();}else{setTimeout(callJmeInit,50);}} callJmeInit(); </script>");
var jmeMath = [
    [
        "{/}frac{}{}", "^{}/_{}", "x^{}", "x_{}", "x^{}_{}", "{/}bar{}", "{/}sqrt{}", "{/}nthroot{}{}",
        "{/}sum_{a}^{b}{c}", "{/}sum", "{/}log_{}", "{/}ln", "{/}int_{}^{}", "{/}oint_{}^{}"
    ],
    [
        "{/}alpha", "{/}beta", "{/}gamma", "{/}delta", "{/}varepsilon", "{/}varphi", "{/}lambda", "{/}mu",
        "{/}rho", "{/}sigma", "{/}omega", "{/}Gamma", "{/}Delta", "{/}Theta", "{/}Lambda", "{/}Xi",
        "{/}Pi", "{/}Sigma", "{/}Upsilon", "{/}Phi", "{/}Psi", "{/}Omega"
    ],
    [
        "+", "-", "{/}pm", "{/}times", "{/}ast", "{/}div", "/", "{/}bigtriangleup",
        "=", "{/}ne", "{/}approx", ">", "<", "{/}ge", "{/}le", "{/}infty",
        "{/}cap", "{/}cup", "{/}because", "{/}therefore", "{/}subset", "{/}supset", "{/}subseteq", "{/}supseteq",
        "{/}nsubseteq", "{/}nsupseteq", "{/}in", "{/}ni", "{/}notin", "{/}mapsto", "{/}leftarrow", "{/}rightarrow",
        "{/}Leftarrow", "{/}Rightarrow", "{/}leftrightarrow", "{/}Leftrightarrow"
    ],
    [
        "(x-1)(x+3)","{/}sqrt{a^2+b^2}"
    ],
    [
        "H_2+CuO===Cu+H_2O",
        "Zn+H_2SO_4===ZnSO_4+H_2{/}uparrow",
        "CuO+2HCl===CuCl_2+H_2O",
        "HCl+NaOH===NaCl+H_2O"
    ],
    [
        "W=UIt=I^2Rt={/}frac{U^2}{R}t",
        "F_1L_1=F_2L_2",
        "v={/}frac{s}{t}"
    ]
];
function mathHtml(obj) {
//    var cols = 8;//一行放几个
    var slidLen = 34;//每个图标的宽或高
    var html = "<div class='mathIcon'>";
    for (var i = 0; i < obj.count; i++) {
        html += "<li onclick=\"insert('" + jmeMath[obj.groupid][i] + "')\" style=\"background-position:-" + (obj.x + Math.floor(i % 8) * slidLen) + "px -" + (obj.y + Math.floor(i / 8) * slidLen) + "px;\"></li>";
    }
    html += "</div>";
//    if (obj.count > cols * 2) {
//        html += "<div class='more' mrows='" + Math.floor((obj.count + cols - 1) / cols) + "' isOpen='0'>更多</div>"
//    }
    return html;
}


function mathHtml2(obj){
    var html = "<div class='mathIcon'>";
    for (var i = 0; i < obj.count; i++) {
        html += "<div onclick=\"insert('" + jmeMath[obj.groupid][i] + "')\" style=\"width:100%;margin:5px\"><div style='border:1px solid #CCCCCC;padding:5px'><img src=\"./asset/images/"+obj.prefix+i+".gif\" ></div></div>";
    }
    html += "</div>";
    return html;
}


function insert(q) {
    $("#jme-math").focus().mathquill("write", q.replace("{/}", "\\"));
}
function jmeInit() {
    //隐藏内容div
    $(".tabContent div.mathBox").hide();
    //菜单点击事件
    $(".tabTitle li").click(function () {
        $(".tabContent div.mathBox").hide();
        var n = 0;
        var obj = this;
        $(".tabTitle li").each(function (i, o) {
            if (obj == o) {
                n = i;
            }
        });
        $(".tabTitle li").removeClass("current");
        $(obj).addClass("current");
        $(".tabContent div.mathBox:eq(" + n + ")").show();
    });
    //缺省显示第一个
    $(".tabTitle li:eq(0)").click();
    //公式定义
    $(".tabContent div.mathBox:eq(0)").html(mathHtml({
        groupid: 0,
        x: 0,
        y: 272,
        count: 14
    }));
    $(".tabContent div.mathBox:eq(1)").html(mathHtml({
        groupid: 1,
        x: 0,
        y: 170,
        count: 22
    }));

    $(".tabContent div.mathBox:eq(2)").html(mathHtml({
        groupid: 2,
        x: 0,
        y: 0,
        count: 36
    }));

    $(".tabContent div.mathBox:eq(3)").html(mathHtml2({
        groupid: 3,
        prefix:'ds',
        count: 2
    }));

    $(".tabContent div.mathBox:eq(4)").html(mathHtml2({
        groupid: 4,
        prefix:'hx',
        count: 4
    }));

    $(".tabContent div.mathBox:eq(5)").html(mathHtml2({
        groupid: 5,
        prefix:'wl',
        count: 3
    }));

//    //常用公式,更多按钮绑定的事件
//    $(".tabContent div.mathBox div.more").click(function () {
//        var rowHei = 40;
//        var mi = $(this).parent().find(".mathIcon");
//        if ($(this).attr("isOpen") == '0') {
//            mi.animate({"height": (rowHei * Number($(this).attr("mrows"))) + "px"});
//            $(this).html("↑ 收起");
//            $(this).attr("isOpen", '1');
//        } else {
//            mi.animate({"height": (rowHei * 2) + "px"});
//            $(this).html("更多");
//            $(this).attr("isOpen", '0');
//        }
//    });

    //公式编辑框
    $("#jme-math").html("").css("font-size", JMEditor.defaultFontSize).mathquill('editable').mathquill('write', "");
    $($("#jme-math").find("textarea")[0]).css("background-color","transparent");     //将textarea的背景设为透明，解决其生成的图片中有白色背景的问题

   $("#jme-math").find("textarea")[0].addEventListener("input",function(e){
       if(e.target.value){
           e.target.value = e.target.value.replace(/\s+/g, "");
           e.target.value=e.target.value.replace(/[\u4e00-\u9fa5]/g,'');
       }
    },false) ;

   var isSelecting = false;
   $("#jme-math").mousedown(function(){
//       console.log("mousedown");
       isSelecting = true;
   });

    $("body").mouseleave(function(){
//        console.log("mouseleave");
        if(isSelecting){
//            console.log("isSelecting");
            $("body").mouseup();
            isSelecting = false;
        }
    });
}

function setCmdText(cmd) {
    $("#jme-math").mathquill('latex', cmd);
}

/**
 * 将canvas中的白色像素改为透明
 * */
function transparent(canvas) {
    var ctx = canvas.getContext("2d");
//        ctx.imageSmoothingEnabled = false;
//        ctx.webkitImageSmoothingEnabled = false;
//        ctx.mozImageSmoothingEnabled = false;
    var w = canvas.width;
    var h = canvas.height;
    var image = ctx.getImageData(0, 0, w, h);
// get the image data values
    var imageData = image.data;
    var transparentColor = {r: 0, g: 0, b: 0, a: 0};
    var blackColor = {r: 51, g: 51, b: 51, a: 255};

    for (var i = 0, n = imageData.length; i < n; i += 4) {
        var r = imageData[i],
            g = imageData[i + 1],
            b = imageData[i + 2],
            a = imageData[i + 3];

        if(r > 200 && g > 200 && b > 200){
            // Change the white to the new color.
            imageData[i] = transparentColor.r;
            imageData[i + 1] = transparentColor.g;
            imageData[i + 2] = transparentColor.b;
            imageData[i + 3] = transparentColor.a;
        }
//        else if((r > 100 && g > 100 && b > 100)
//            ||(r == 0 && g == 0 && b == 0 && a == 255)){
//            imageData[i] = blackColor.r;
//            imageData[i + 1] = blackColor.g;
//            imageData[i + 2] = blackColor.b;
//            imageData[i + 3] = blackColor.a;
//        }

    }

// and put the imagedata back to the canvas
    ctx.putImageData(image, 0, 0);
}

function getResult(callback) {
    var latex = $("#jme-math").mathquill('latex');
    if(latex == "")
    {
        return;
    }
    //将公式内容重新填装一次，避免选中公式造成的图片阴影,目前未找到别的解决办法
    $("#jme-math").mathquill('write','').mathquill('latex', latex);

    $("#jme-math").css("border", "0px");
    $("#jme-math").find("textarea")[0].style.border = "0px";
    $("#jme-math").removeClass("mathquill-editable");
    $("#jme-math").addClass("mathquill-embedded-latex");
    $("#jme-math").width('');
    //$("#mathDiv").width('');

    html2canvas($("#mathDiv")[0], {
        onrendered: function (canvas) {
            $("#jme-math").css("border", "1px solid gray");
            $("#jme-math").find(".textarea")[0].style.border = "1px";
//            $("#jme-math").removeClass("mathquill-embedded-latex");
//            $("#jme-math").addClass("mathquill-editable");
            transparent(canvas);
            var result = null;
            var cmd = $("#jme-math").mathquill('latex');
            if (cmd) {
                result = {"img": canvas.toDataURL(), "text": cmd};
            }
            if (callback) {
                callback(result)
            }
        }
    });
}