
/* Merged Plone Javascript file
 * This file is dynamically assembled from separate parts.
 * Some of these parts have 3rd party licenses or copyright information attached
 * Such information is valid for that section,
 * not for the entire composite file
 * originating files are separated by - filename.js -
 */

/* - kupu_latexmathimage.js - */
function getNewHTTPObject()
{
        var xmlhttp;

        /** Special IE only code ... */
        /*@cc_on
          @if (@_jscript_version >= 5)
              try
              {
                  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
              }
              catch (e)
              {
                  try
                  {
                      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                  }
                  catch (E)
                  {
                      xmlhttp = false;
                  }
             }
          @else
             xmlhttp = false;
        @end @*/

        /** Every other browser on the planet */
        if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
        {
            try
            {
                xmlhttp = new XMLHttpRequest();
            }
            catch (e)
            {
                xmlhttp = false;
            }
        }

        return xmlhttp;
}

function escapePlusChar(string) {
  var lsRegExp = /\+/g;
  tmp = string.replace(lsRegExp, "%2B")
  return tmp
}

function LatexMathImageDrawer(elementid, tool, wrap) {
    /* Latex Math Image Drawer */
    this.element = getFromSelector(elementid);
    this.tool = tool;

    function wrap(id, tag) {
        return '#'+this.element.id+' '+tag+'.'+id;
    }

    var formula = getBaseTagClass(this.element, 'input', 'kupu-latexmathimage-formula-drawer-input');
    var formula_title = getBaseTagClass(this.element, 'input', 'kupu-latexmathimage-title-drawer-input');
    var message = getBaseTagClass(this.element, 'p', 'kupu-latexmathimage-message-drawer');
    var ok = getBaseTagClass(this.element, 'button', 'kupu-dialog-button');

    this.target = "";

    this.createContent = function() {
        /* display the drawer */
        var currnode = this.editor.getSelectedNode();
        var linkel = this.editor.getNearestParentOfType(currnode, 'img');
        formula.value = "";
        formula_title.value = ""

        if (linkel) {
            this.tool.cleanLink(linkel)
            url = linkel.getAttribute('src');
            if (this.tool.isLatexMathImage(url)=='True') {
                formula.value = this.tool.getFormula(url);
                formula_title.value = this.tool.getFormulaTitle(url);
                this.enableForm();
            } else {
                this.disableForm();
            }
        } else {
            formula.value = '';
        };
        this.element.style.display = 'block';
        this.focusElement();
    };

    this.disableForm = function() {
        message.style.display = 'block';
        formula.disabled = '1';
        formula_title.disabled = '1';
        ok.disabled = '1';
    }

    this.enableForm = function() {
        message.style.display = 'none';
        formula.removeAttribute('disabled');
        formula_title.removeAttribute('disabled');
        ok.removeAttribute('disabled');
    }

    this.save = function() {
        /* add or modify a LatexMathImage */

        this.editor.resumeEditing();
        var formula_str = formula.value;
        var formula_title_str = formula_title.value;

        var currnode = this.editor.getSelectedNode();
        var linkel = this.editor.getNearestParentOfType(currnode, 'img');
        if (linkel) {
            url = linkel.getAttribute('src');
            //this.tool.setFormula(url, formula_str);
            //this.tool.setFormulaTitle(url, formula_title_str);
            this.tool.setFormulaAndTitle(url, formula_title_str, formula_str);
            this.tool.updateLink(linkel)
        } else {
            url = this.tool.createLatexMathImage(formula_title_str, formula_str);
            this.tool.createLatexMathImageTag(url);
        }
        this.editor.updateState();
        this.drawertool.closeDrawer();
    };



};

LatexMathImageDrawer.prototype = new Drawer;

function LatexMathImageLinkTool() {
    /* Add and update source image link */

    this.initialize = function(editor) {
        this.editor = editor;
        this.editor.logMessage(_('LatexMathImage Link Tool initialized'));
    };

    this.createLatexMathImageTag = function(url) {
        /* create an image */
        var img = this.editor.getInnerDocument().createElement('img');
        img.src = url;
        img.removeAttribute('height');
        img.removeAttribute('width');
        img = this.editor.insertNodeAtSelection(img, 1);
        this.editor.logMessage(_('Image inserted'));
        this.editor.updateState();
        return img;
    };

    this.cleanLink = function (linkel) {
        url = linkel.getAttribute('src')
        linkel.removeAttribute('src');
        url = url.split('?')[0];
        linkel.setAttribute('src', url);
    };


    this.updateLink = function (linkel) {
        url = linkel.getAttribute('src');
        linkel.removeAttribute('src');
        d = new Date();
        serial = d.getTime();
        linkel.setAttribute('src', url + '?' + serial);
    };

    // server side calls

    this.createLatexMathImage = function(title_str, formula_str) {
      var xmlHttp = getNewHTTPObject();

      url = document.location.href.replace('/edit', '')
      url += '/createLatexMathImage?';
//       url += 'id=f1&';
      url += 'title=' + escape(title_str);
      url += '&'
      url += 'formula=' + escapePlusChar(escape(formula_str));

      xmlHttp.open('GET', url, false);
      xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xmlHttp.send(null);

      return xmlHttp.responseText;
    }

    this.getFormula = function(url) {
      var xmlHttp = getNewHTTPObject();

      url = url + '/getLatexMathExpression'

      xmlHttp.open('GET', url, false);
      xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xmlHttp.send(null);

      return xmlHttp.responseText;
    }

    this.getFormulaTitle = function(url) {
      var xmlHttp = getNewHTTPObject();

      url = url + '/Title'

      xmlHttp.open('GET', url, false);
      xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xmlHttp.send(null);

      return xmlHttp.responseText;
    }

    this.isLatexMathImage = function(url) {
      var xmlHttp = getNewHTTPObject();

      url = url + '/isLatexMathImage'

      xmlHttp.open('GET', url, false);
      xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xmlHttp.send(null);

      return xmlHttp.responseText;
    }

    this.setFormulaAndTitle = function(url, formula_title_str, formula_str) {
      var xmlHttp = getNewHTTPObject();

      url =  url + '/setLatexMathFormulaAndTitle?'
      url += 'title=' + escape(formula_title_str)
      url += '&'
      url += 'formula=' + escapePlusChar(escape(formula_str))

      xmlHttp.open('GET', url, false);
      xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xmlHttp.send(null);
    }

    this.setFormula = function(url, formula) {
      var xmlHttp = getNewHTTPObject();

      url = url + '/setLatexMathExpression?value=' + escapePlusChar(escape(formula))

      xmlHttp.open('GET', url, false);
      xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xmlHttp.send(null);
    }

    this.setFormulaTitle = function(url, formula_title) {
      var xmlHttp = getNewHTTPObject();

      url = url + '/setTitle?value=' + escape(formula_title)

      xmlHttp.open('GET', url, false);
      xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xmlHttp.send(null);
    }


}

LatexMathImageLinkTool.prototype = new KupuTool;


/* - kupu_latexmathimage_init.js - */
function initLatexMathImageKupu(kupu, editorId) {

    var prefix = '#'+editorId+' ';
    var drawertool = kupu.getTool('drawertool');

    var opendrawer = function(drawerid) {
        return function(button, editor) {
            drawertool.openDrawer(prefix+drawerid);
        };
    };

    var latexmathimagelink_tool = NoContextMenu(new LatexMathImageLinkTool());
    kupu.registerTool('latexmathimagelink_tool', latexmathimagelink_tool);

    var latexmathimage_drawerbutton = new KupuButton(prefix+'button.kupu-latexmathimage-hyperlink',
                                                        opendrawer('latexmathimage_drawer'));
    kupu.registerTool('latexmathimage_libdrawerbutton', latexmathimage_drawerbutton);

    var latexmathimage_drawer = new LatexMathImageDrawer(prefix+'div.kupu-latexmathimage-drawer', latexmathimagelink_tool);
    drawertool.registerDrawer(prefix+'latexmathimage_drawer', latexmathimage_drawer, kupu);

    return kupu;
};

