/**
 * 依赖jquery，需要放置在jquery后面
 */

/** MathJax核心库配置对象(默认) */
window.MathJax = {
    options: {
        ignoreHtmlClass: "ig",
        renderActions: {
            addMenu: [0, "", ""],
        },
        menuOptions: {
            settings: {assistiveMml: false}
        }
    },
    loader: {
        load: ["[tex]/all-packages"]
    },
    tex: {
    	/*
        packages: {
            "[+]": ["color"],
            "[+]": ["boldsymbol"],
            "[+]": ["physics"],
            "[+]": ["mhchem"],
            "[+]": ["cancel"],
            "[+]": ["ams"],
            "[+]": ["amscd"],
            "[+]": ["unicode"],
            "[+]": ["bbox"],
            "[+]": ["noerrors"],
            "[+]": ["newcommand"]
        },
     */
        inlineMath: [
            //["$", "$"],
            //["\\(", "\\)"],
        ],
        displayMath: [
        	//["$$", "$$"], 
        	//["\\[", "\\]"]
       ]
    },
    svg: {
       // displayAlign: 'left',
        scale: '1.2',
        displayIndent: '0'
    },
    startup: {
          ready: function(){
        	try { 
	            if (MathJax.version === "3.0.5") {
	              var SVGWrapper = MathJax._.output.svg.Wrapper.SVGWrapper;
	              var CommonWrapper = SVGWrapper.prototype.__proto__;
	              SVGWrapper.prototype.unicodeChars = function (text, variant) {
	                if (!variant) variant = this.variant || "normal";
	                  return CommonWrapper.unicodeChars.call(this, text, variant);
	              };
	            }
	            MathJax.startup.defaultReady();
	            mathJaxCustomStyle();
	            mathJaxLatex2Svg();
	            asyncMathJaxLatex2Svg();
        	  }catch(err){
        		  console.log(err);
        	  }
          },
          typeset: false 
      }
};


function mathJaxLatex2Svg() {
    try {
        $(document).ready(function () {
        	//$('img.ans-latex-moudle,img.ans-edrawmath-moudle,img.ans-formula-moudle').each(function () {
            $('img.ans-latex-moudle,img.ans-formula-moudle').each(function () {
            	var module = 'latex';
            	if($(this).hasClass('ans-edrawmath-moudle')){
            		module = 'edrawmath';
            	}
            	if($(this).hasClass('ans-formula-moudle')){
            		module = 'formula';
            	}
                tex2SvgAction(this,module);
            });
            //  $('span.latex-formula').each(function () {
           // 	      sourceTex2SvgAction(this);
            //   });
        });
    } catch (err) {
        console.log(err);
    }
}


function mathJaxTex2svg(data) {
    try {
        if (!data) {
            return '';
        }
        var svg = MathJax.tex2svg(data, {});
        svg = tex2SvgErrorCheck(data, svg);
        return svg;
    } catch (err) {
        console.log(err);
        return '';
    }
}

function sourceTex2SvgAction(span) {
    try {
        var me = span;
        var data = $(me).text();
        if (!data) {
            return;
        }
        var svg = MathJax.tex2svg(data, {});
        svg = tex2SvgErrorCheck(data, svg);
        if (svg && svg != '') {
            $(svg).attr('latex-formula',escape(JSON.stringify(data)));
            $(me).replaceWith(svg);
        }
    } catch (err) {
        console.log(err);
    }
}

function tex2SvgAction(img,module) {
    try {
        var me = img;
        var data = $(me).attr('data');
        if(!data){
           //console.log(me);
        	return;
        }
        data = JSON.parse(unescape(data));

       if(module == 'formula'){
           data = data.formula;
           data = formulaRemoveDollars(data);
       }

        var svg  = '';
       if(data.indexOf('<math') != -1){
    	   if(typeof(MathJax.mathml2svg) == 'function'){
    		   svg = MathJax.mathml2svg(data,{});
    	   }
       }else{
           if(module == 'edrawmath'){
               data = edrawMathReplaceBracket(data);
            }
            svg = MathJax.tex2svg(data, {});
       }
       
       svg = tex2SvgErrorCheck(data,svg);
       if($(svg).find('svg.wrong-formula-svg').length > 0){
    	   svg = '';
       }
        //var svg = MathJax.tex2svg(data, {});
        if(svg && svg != ''){
       	  $(me).replaceWith(svg);
        }
        //$(me).after(svg);
    } catch (err) {
        console.log(err);
    }
}


function formulaRemoveDollars(str) {
	if(!str){
		return str;
	}
    var result = '';
    for (var i = 0; i < str.length; i++) {
        if (str[i] === '$' && str[i - 1]!== '\\') {
            result += '';
        } else {
            result += str[i];
        }
    }
    return result;
}


// 去掉 '\[{}\]'标记
function edrawMathReplaceBracket(str) {
	 if (str.indexOf('\\[{') == 0) {
	    str = str.slice(3);
	  }
	  if (str.indexOf('}\\]') == str.length - 3) {
	    str = str.slice(0, -3);
	  }
	  return str;
}

function tex2SvgErrorCheck(data, svg) {
    try {
        if ($(svg).find('g[data-mml-node="merror"]').length > 0) {
        	var errorSvg = '<mjx-container class="MathJax" jax="SVG" display="true" role="presentation" style="position: relative; color: rgb(0, 0, 0);" latex-formula="' + escape(JSON.stringify(data)) + '"><svg class="wrong-formula-svg" width="100px"height="24px"style="transform:translate(0,2px)"xmlns="http://www.w3.org/2000/svg"><rect x="0"y="0"width="100"height="24"rx="4"ry="4"fill="#F7F8FA"/><path fill-rule="evenodd"transform="translate(8,2)"viewBox="0 0 20 20"transform="scale(0.9)"clip-rule="evenodd"d="M10 19.1666C15.0626 19.1666 19.1667 15.0625 19.1667 9.99992C19.1667 4.93731 15.0626 0.833252 10 0.833252C4.93743 0.833252 0.833374 4.93731 0.833374 9.99992C0.833374 15.0625 4.93743 19.1666 10 19.1666ZM8.54167 6.66667C8.54167 5.86125 9.19458 5.20833 10 5.20833C10.8054 5.20833 11.4583 5.86125 11.4583 6.66667C11.4583 6.87438 11.4149 7.07195 11.3366 7.25079L10.514 11.1996C10.3979 11.7569 9.60213 11.7569 9.48604 11.1996L8.66336 7.25079C8.58509 7.07195 8.54167 6.87438 8.54167 6.66667ZM11.0743 13.866C11.0743 14.4593 10.5933 14.9403 10 14.9403C9.40668 14.9403 8.92569 14.4593 8.92569 13.866C8.92569 13.2726 9.40668 12.7917 10 12.7917C10.5933 12.7917 11.0743 13.2726 11.0743 13.866Z"fill="#FFAF40"/><text x="60"y="17"fill="#333"font-size="14"text-anchor="middle">无效公式</text></svg></mjx-container>';
            console.log('tex2Svg error：' + $(svg).text());
            console.log(data);
            console.log('\r\n');
            return errorSvg;
        }
        return svg;
    } catch (err) {
        console.log(err);
        return errorSvg;
    }
}

function asyncMathJaxLatex2Svg() {
    try {
        $(document).ajaxSuccess(function (event, xhr, settings) {
            mathJaxLatex2Svg();
        });
    } catch (err) {
        console.log(err);
    }
}

function mathJaxCustomStyle() {
    var style = document.createElement('style');
    style.type = 'text/css';
    style.id = '_MJX-SVG-styles';
    var css = 'mjx-container[jax="SVG"][display="true"]{display: inline !important;margin1: 0 !important;}mjx-container svg{max-width:100%;}';
    style.appendChild(document.createTextNode(css));
    document.head.appendChild(style);
}

// 不直接替换掉图片，图片隐藏掉，在图片后边插入一个svg
function tex2SvgActionAppend(img,module) {
    try {
        var me = img;
        var data = $(me).attr('data');
        if(!data){
            //console.log(me);
            return;
        }
        data = JSON.parse(unescape(data));

        if(module == 'formula'){
            data = data.formula;
        }

        var svg  = '';
        if(data.indexOf('<math') != -1){
            if(typeof(MathJax.mathml2svg) == 'function'){
                svg = MathJax.mathml2svg(data,{});
            }
        }else{
            if(module == 'edrawmath'){
                data = edrawMathReplaceBracket(data);
            }
            svg = MathJax.tex2svg(data, {});
        }

        svg = tex2SvgErrorCheck(data,svg);

        //var svg = MathJax.tex2svg(data, {});
        if(svg && svg != ''){
            $(me).addClass("ans-latex-moudle-hidden");
            var latexImgSrc = $(me).attr("src");
            var newLatexContainer = $('<span class="latex-svg" latexData="' + escape(JSON.stringify(data)) + '" latexImgSrc="' + latexImgSrc + '"></>');
            $(newLatexContainer).attr("contenteditable", "false");
            $(svg).appendTo(newLatexContainer);
            var newSpan = $('<span>\u200B</span>')
            // $("<br/>").appendTo(newDiv);
            $(newLatexContainer).insertAfter(me);
            $(newSpan).insertAfter(newLatexContainer);
        }
        //$(me).after(svg);
    } catch (err) {
        console.log(err);
    }
}
