#
# Support LaTeX math equations for Redmine.
#
# Ling Li, March 2011
#
require 'redmine'
RAILS_DEFAULT_LOGGER.info 'Redmine LaTeX MathJax'

Redmine::Plugin.register :latex_math do
    name 'LaTeX math equations'
    author 'Ling Li'
    description 'Enable LaTeX math equation in wiki and issues via MathJax.'
end

# After this macro is called, LaTeX equations will be processed by MathJax.
#
# {{EnableLaTeXMath}}
# \[ x_{1,2} = \frac{-b \pm \sqrt{b^2-4ac}}{2a} \]
#
Redmine::WikiFormatting::Macros.register do
  desc "Enable LaTeX math equations via MathJax"
  macro :EnableLaTeXMath do |obj, args|
    args, options = extract_macro_options(args, :parent)
    if args.size > 0
      raise 'No arguments are needed.'
    end

    if defined? @IncludedMathJaxScript
      return ''
    end
    @IncludedMathJaxScript = 1

    # Dynamically load MathJax
    "<script type=\"text/javascript\">
//<![CDATA[
(function () {
  var script = document.createElement(\"script\");
  script.type = \"text/javascript\";
  script.src=\"http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML\";

  var config = 'MathJax.Hub.Config({' +
                 'extensions: [\"tex2jax.js\"],' +
                 'jax: [\"input/TeX\",\"output/HTML-CSS\"]' +
               '});' +
               'MathJax.Hub.Startup.onload();';

  if (window.opera) {script.innerHTML = config}
               else {script.text = config}

  document.getElementsByTagName(\"head\")[0].appendChild(script);
})();
//]]>
</script>"

  end
end
