%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% giac/hevea interaction code definitions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Use one of the environment \begin{giacjs}...\end{giacjs} or \begin{giacjsonline}...\end{giacjsonline}
%% to load the javascript code (from hard disk or Internet)
%% Commands \giacinput{} or \giacinputmath{} or \giacinputbigmath{} 
%% \giaccmd{} or \giaccmdmath{} or \giaccmdbigmath{} 
%% or \begin{giacprog}...\end{giacprog}
\usepackage{hevea} 
\usepackage{listings}
\usepackage{fancyvrb}
\ifhevea 
\newenvironment{giacjs}[1]["max-height: 500px; overflow:auto"]
{\loadgiacmain{#1}
}
{\loadgiaccontrol
\loadgiacscriptstart
\@print{
<script src="file:///usr/share/giac/doc/giac.js" async></script> 
}
\loadgiacscriptend
} 
\newenvironment{giacjshere}[1]["max-height: 500px; overflow:auto"]
{\loadgiacmain{#1}
}
{\loadgiaccontrol
\loadgiacscriptstart
\@print{
<script src="giac.js" async></script> 
}
\loadgiacscriptend
} 
\newenvironment{giacparijs}[1]["max-height: 500px; overflow:auto"]
{\loadgiacmain{#1}
}
{
\loadgiaccontrol
\loadgiacscriptstart
\@print{
<script src="file:///usr/share/giac/doc/giacpari.js" async></script> 
}
\loadgiacscriptend
} 
\newenvironment{giacjsonline}[1]["max-height: 500px; overflow:auto"]
{\loadgiacmain{#1}
}
{
\loadgiaccontrol
\loadgiacscriptstart
\@print{
<script src="http://www-fourier.ujf-grenoble.fr/~parisse/giac.js" async></script> 
}
\loadgiacscriptend
} 
\newenvironment{giacparijsonline}[1]["max-height: 500px; overflow:auto"]
{\loadgiacmain{#1}
}
{
\loadgiaccontrol
\loadgiacscriptstart
\@print{
<script src="http://www-fourier.ujf-grenoble.fr/~parisse/giacpari.js" async></script> 
}
\loadgiacscriptend
} 
\else
\newenvironment{giacjs}[1]["max-height: 500px; overflow:auto"]{}{}
\newenvironment{giacjshere}[1]["max-height: 500px; overflow:auto"]{}{}
\newenvironment{giacparijs}[1]["max-height: 500px; overflow:auto"]{}{}
\newenvironment{giacjsonline}[1]["max-height: 500px; overflow:auto"]{}{}
\newenvironment{giacparijsonline}[1]["max-height: 500px; overflow:auto"]{}{}
\fi
\newcommand{\loadgiacscriptstart}{
\ifhevea
\@print{
<script language="javascript"> 
var Module = { 
        htmlcheck:true,
        htmlbuffer:'',
        preRun: [],
        postRun: [],
        print: (function() {
          var element = document.getElementById('output');
          element.innerHTML='';// element.value = ''; // clear browser cache
          return function(text) {
            //console.log(text.charCodeAt(0));
            if (text.length==1 && text.charCodeAt(0)==12){ element.innerHTML=''; return; }
            if (text.length>=1 && text.charCodeAt(0)==2) {console.log('STX');Module.htmlcheck=false; htmlbuffer='';return;}
            if (text.length>=1 && text.charCodeAt(0)==3) {console.log('ETX');Module.htmlcheck=true; element.style.display='inherit'; element.innerHTML += htmlbuffer;htmlbuffer='';element.scrollTop = 99999; return;}
            if (Module.htmlcheck){
            // These replacements are necessary if you render to raw HTML 
             text = text.replace(/&/g, "&amp;");
             text = text.replace(/</g, "&lt;");
             text = text.replace(/>/g, "&gt;");
             text = text.replace('\n', '<br>', 'g');
             text += '<br>'
             element.style.display='inherit';
             element.innerHTML += text; // element.value += text + "\n";
             element.scrollTop = 99999; // focus on bottom
            } else htmlbuffer += text;
          };
        })(),
     canvas: document.getElementById('canvas'),};
</script>
}
\fi
}
\newcommand{\loadgiacmain}[1]{
\ifhevea
\@print{
<div>
<div id="maindiv" style=}#1\@print{>}
\fi
}
\newcommand{\loadgiaccontrol}{
\ifhevea
\@print{
</div>
<div id="controldiv" style="max-height: 400px; overflow:auto">
<span id="controlindex"></span>
<button title="Efface la console" onclick="document.getElementById('output').innerHTML='';">Efface</button>
<button title="Augmente la taille de la console" onclick="var field=document.getElementById('output'); var s=field.style.maxHeight; s=s.substr(0,s.length-2);s=eval(s)+20 ;s=s+'px';field.style.maxHeight =s;">+</button>
<button title="Diminue la taille de la console" onclick="var field=document.getElementById('output'); var s=field.style.maxHeight; s=s.substr(0,s.length-2);s=eval(s)-20 ; if(s>100){s=s+'px';field.style.maxHeight =s;}">-</button>
<textarea title="Ligne de commande pour un calcul rapide" onkeypress="UI.ckenter(event,this,3)" style="width:400px;height:20px;font-size:large"></textarea><button  title="Evalue cellule precedente" onclick="UI.quick(this);">-></button><span></span>
&nbsp;&nbsp;<button onclick="var s=UI.caseval('restart;'); Module.print(s);" title="Reinitialise le moteur de calcul formel">Restart</button>
<button onclick="UI.exec(document.documentElement);" title='Cliquer ici pour executer toutes les commandes (attention cela peut etre long!)'>Exec. tout</button>
<canvas id='canvas' width=0 height=0   onmousedown="UI.canvas_pushed=true;UI.canvas_lastx=event.clientX; UI.canvas_lasty=event.clientY;"  onmouseup="UI.canvas_pushed=false;" onmousemove="UI.canvas_mousemove(event,'')"></canvas>
<div id="output" style="max-height: 100px; overflow:auto"></div>
</div>
</div>}
\fi
}
\newcommand{\loadgiacscriptend}{
\ifhevea
\@print{
<script language="javascript">
 var UI = {
  histcount:0,
  usemathjax:false,
  canvas_pushed:false,
  canvas_lastx:0,
  canvas_lasty:0,
  canvas_mousemove:function(event,no){
    if (UI.canvas_pushed){
      // Module.print(event.clientX);
      if (UI.canvas_lastx!=event.clientX){
        if (event.clientX>UI.canvas_lastx)
          giac3d('r'+no);
        else
          giac3d('l'+no);
        UI.canvas_lastx=event.clientX;
      }
      if (UI.canvas_lasty!=event.clientY){
        if (event.clientY>UI.canvas_lasty)
          giac3d('d'+no);
        else
          giac3d('u'+no);
        UI.canvas_lasty=event.clientY;
      }
    }
  },  
  ltgt:function(s){
    var ss=s.length,i,res='';
    for (i=0;i<ss-4;i++){
      if (s[i]!='&' || s[i+2]!='t' || s[i+3]!=';'){
        res += s[i];
        continue;
      }
      if (s[i+1]=='l'){
        res += '<';
        i +=3;
        continue;
      }
      if (s[i+1]=='g'){
        res += '>';
        i +=3;
        continue;
      }
      res += s[i];
    }
    for (;i<ss;i++) res+=s[i];
    return res;
  },
  rmquote:function(tmp){
    var s=tmp.length;
    if (s>2 && tmp.charCodeAt(0)==34 && tmp.charCodeAt(s-1)==34)
      tmp=tmp.substr(1,s-2);
    return tmp;
  },
  quick:function(field){
    var tmp1=field.previousSibling.value;
    var tmp=UI.caseval(tmp1);
    tmp=UI.rmquote(tmp); 
    tmp=UI.latexeval(tmp);
    Module.print(String.fromCharCode(2));
    Module.print("<tt>");
    Module.print(tmp1);
    Module.print("</tt><br>&nbsp;&nbsp;");
    Module.print(tmp);
    Module.print("<br>");
    Module.print(String.fromCharCode(3));
    field.nextSibling.innerHTML='&nbsp;'+tmp;
   //UI.render_canvas(nextSibling);  
  },
  caseval:function(text){
    var s="non evalu&eacute;",err;
    try {
       s= giaceval(text);
    } catch (err) { s=err.message;}
    var is_3d=s.length>5 && s.substr(0,5)=='gl3d ';
    if (is_3d){
	var n3d=s.substr(5,s.length-5);
	s = '<canvas id="gl3d_'+n3d+'" onmousedown="UI.canvas_pushed=true;UI.canvas_lastx=event.clientX; UI.canvas_lasty=event.clientY;" onmouseup="UI.canvas_pushed=false;" onmousemove="UI.canvas_mousemove(event,'+n3d+')" width=400 height=250></canvas>';
    }
    return s;
  },
  render_canvas:function(field){
   var n=field.id;
   if (n && n.length>5 && n.substr(0,5)=='gl3d_'){
    Module.print(n);
    var n3d=n.substr(5,n.length-5);
    giac3d(n3d);
    return;
   }
   var f=field.firstChild;
   for (;f;f=f.nextSibling){
     UI.render_canvas(f);
   }
  },
  eval_form: function(field){
    giaceval('assume('+field.name.value+'='+field.valname.value+')');
    var s=UI.caseval(field.prog.value);
    var is_svg=s.substr(1,4)=='<svg';
    if (is_svg) field.parentNode.lastChild.innerHTML=s.substr(1,s.length-2);
    else field.parentNode.lastChild.innerHTML=s;
    UI.render_canvas(field.parentNode.lastChild);
  },
  latexeval:function(text){
    var tmp=text;
    if (tmp.length>5 && tmp.substr(0,5)=='gl3d_') return tmp;
    if (tmp.length>5 && tmp.substr(1,4)=='<svg') return tmp.substr(1,tmp.length-2);
    if (tmp.length>5 && tmp.substr(0,4)=='<svg') return tmp;
     if (UI.usemathjax){
       tmp=giaceval('latex(quote('+tmp+'))');
       tmp='$$'+tmp.substr(1,tmp.length-2)+'$$';
       return tmp;
     }
     tmp=giaceval('mathml(quote('+tmp+',1))');
     tmp=tmp.substr(1,tmp.length-2);
    return tmp;   
  },
  ckenter:function(event,field,mode){
    var key = event.keyCode;
    if (key != 13 || event.shiftKey) return true;
   if (mode==3){ UI.quick(field.nextSibling); event.preventDefault(); return true; }
    var tmp=field.value;
   Module.print(tmp);
    tmp=UI.caseval(tmp);
    if (mode==1){
      tmp=UI.rmquote(tmp); 
   }
   if (mode==2){
     tmp=UI.latexeval(tmp);
   }
   field.nextSibling.nextSibling.innerHTML=tmp;
   UI.render_canvas(field.nextSibling.nextSibling);
   if (UI.usemathjax) MathJax.Hub.Queue(["Typeset",MathJax.Hub,field.nextSibling.nextSibling]);
   if (event.preventDefault) event.preventDefault();
    return false;
  },
  exec: function(field){
     if (field.nodeName=="BUTTON"){
        field.click();
        return;
     }
     var f=field.firstChild;
     while (f){
       UI.exec(f);
       f=f.nextSibling;
     }
   }
 };
 window.onload = function(e){
   var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
   var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
  var ua = window.navigator.userAgent;
  var old_ie = ua.indexOf('MSIE ');
  var new_ie = ua.indexOf('Trident/');
  if ((!isFirefox && !isSafari) || (old_ie > -1) || (new_ie > -1) || window.chrome){
     UI.usemathjax=true;
     alert("Votre navigateur ne supporte MathML, on utilise MathJax pour l'affichage 2d.  Les calculs seraient plus rapides et les resultats seraient mieux affiches avec Firefox.");
  }
  if (UI.usemathjax){
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src  = "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
    document.getElementsByTagName("head")[0].appendChild(script);
  }
  var elem= document.getElementById('controlindex');
  elem.innerHTML='<hr><a href="'+String.fromCharCode(35)+'sec1">Table</a>, <a href="'+String.fromCharCode(35)+'sec2">Index</a>'+elem.innerHTML;
  elem=document.getElementById('maindiv');
  if (elem.style.maxHeight=='500px')
    elem.style.maxHeight=(window.innerHeight-120)+'px';
  giaceval=Module.cwrap('caseval',  'string', ['string']);
  giac3d = Module.cwrap('_ZN4giac13giac_rendererEPKc','number', ['string']);
  giaceval('set_language(1);');
  giaceval('factor(x^4-1)');
  giaceval('sin(x+y)+f(t)');
 // if (confirm('Executer les commandes?')) UI.exec(document.documentElement);
 };
</script>
}
\fi
}
\ifhevea
\newenvironment{giacprog}{
\verbatim}
{\endverbatim 
\@print{<button onclick="var field=parentNode.previousSibling; var tmp=field.innerHTML;if(tmp.length==0) tmp=field.value;var t=createElement('TEXTAREA');t.style.fontSize=16;t.cols=60;t.rows=10;var tmp1=UI.ltgt(tmp);t.value=tmp1;tmp=UI.caseval(tmp);tmp=UI.rmquote(tmp);nextSibling.innerHTML=tmp; UI.render_canvas(nextSibling.innerHTML);field.parentNode.insertBefore(t,field);field.parentNode.removeChild(field);">ok</button><span></span><br>
}
}
\else
\newenvironment{giacprog}
{
\VerbatimEnvironment
\begin{Verbatim}
}
{
\end{Verbatim}
}
\fi

% for example \giaccmd{factor}{x^4-1}
\newcommand{\giaccmd}[3][style="width:400px;height:20px;font-size:large"]{
\ifhevea
\@print{<textarea}
\@getprint{#1>#3}
\@print{</textarea><button onclick="var tmp=UI.caseval(}
\@getprint{'#2('}
\@print{+previousSibling.value+')');tmp=UI.rmquote(tmp); nextSibling.innerHTML='&nbsp;'+tmp;UI.render_canvas(nextSibling);">}
\@getprint{#2}
\@print{</button><span></span><br>}
\else
\lstinline@#2(#3)@
\fi
}
\newcommand{\giacinput}[2][style="width:400px;height:20px;font-size:large"]{
\ifhevea
\@print{<textarea onkeypress="UI.ckenter(event,this,1)" }
\@getprint{#1>#2}
\@print{</textarea><button onclick="previousSibling.style.display='inherit';var tmp=UI.caseval(previousSibling.value);tmp=UI.rmquote(tmp); nextSibling.innerHTML='&nbsp;'+tmp;UI.render_canvas(nextSibling);">ok</button><span></span><br>}
\else
\lstinline@#2@
\fi
}
\newcommand{\giachidden}[3][style="display:none;width:400px;height:20px;font-size:large"]{
\ifhevea
\@print{<textarea onkeypress="UI.ckenter(event,this,1)" }
\@getprint{#1>#2}
\@print{</textarea><button onclick="previousSibling.style.display='inherit';var tmp=UI.caseval(previousSibling.value);tmp=UI.rmquote(tmp); nextSibling.innerHTML='&nbsp;'+tmp;UI.render_canvas(nextSibling);">}
\@getprint{#3}
\@print{</button><span></span><br>}
\else
\lstinline@#2@
\fi
}
\newcommand{\giacinputbig}[2][style="width:800px;height:20px;font-size:large"]{
\ifhevea
\@print{<textarea onkeypress="UI.ckenter(event,this,1)" }
\@getprint{#1>#2}
\@print{</textarea><button onclick="previousSibling.style.display='inherit';var tmp=UI.caseval(previousSibling.value);tmp=UI.rmquote(tmp); nextSibling.innerHTML='&nbsp;'+tmp;UI.render_canvas(nextSibling);">ok</button><span></span><br>}
\else
\lstinline@#2@
\fi
}
\newcommand{\giaccmdmath}[3][style="width:400px;height:20px;font-size:large"]{\ifhevea
\begin{rawhtml}<br><textarea \end{rawhtml}
\@getprint{#1>#3}
\begin{rawhtml}</textarea><button onclick="var tmp=UI.caseval(\end{rawhtml} 
\@getprint{'#2('+}
\begin{rawhtml}previousSibling.value+')');  tmp=UI.latexeval(tmp);nextSibling.innerHTML='&nbsp;'+tmp; if (UI.usemathjax) MathJax.Hub.Queue(['Typeset',MathJax.Hub,nextSibling]);
">\end{rawhtml}
\@getprint{#2}
\begin{rawhtml}</button><span></span><br>\end{rawhtml}
\else
\lstinline@#2(#3)@
\fi
}
\newcommand{\giacinputmath}[2][style="width:400px;height:20px;font-size:large"]{\ifhevea
\begin{rawhtml}<br><textarea onkeypress="UI.ckenter(event,this,2)" \end{rawhtml}
\@getprint{#1>#2} 
\begin{rawhtml}</textarea><button onclick="previousSibling.style.display='inherit';var tmp=UI.caseval(previousSibling.value); tmp=UI.latexeval(tmp);nextSibling.innerHTML='&nbsp;'+tmp; if (UI.usemathjax) MathJax.Hub.Queue(['Typeset',MathJax.Hub,nextSibling])">ok</button><span></span><br>\end{rawhtml}
\else
\lstinline@#2@
\fi
}
\newcommand{\giachiddenmath}[3][style="display:none;width:400px;height:20px;font-size:large"]{\ifhevea
\begin{rawhtml}<br><textarea onkeypress="UI.ckenter(event,this,2)" \end{rawhtml}
\@getprint{#1>#2} 
\begin{rawhtml}</textarea><button onclick="previousSibling.style.display='inherit';var tmp=UI.caseval(previousSibling.value); tmp=UI.latexeval(tmp);nextSibling.innerHTML='&nbsp;'+tmp; if (UI.usemathjax) MathJax.Hub.Queue(['Typeset',MathJax.Hub,nextSibling])">\end{rawhtml}
\@getprint{#3}
\begin{rawhtml}</button><span></span><br>\end{rawhtml}
\else
\lstinline@#2@
\fi
}
\newcommand{\giaccmdbigmath}[3][style="width:800px;height:20px;font-size:large"]{\ifhevea
\begin{rawhtml}<br><textarea \end{rawhtml}
\@getprint{#1>#3} 
\begin{rawhtml}</textarea><button onclick="var tmp=UI.caseval(\end{rawhtml} 
\@getprint{'#2('+}
\begin{rawhtml}previousSibling.value+')');  tmp=UI.latexeval(tmp);nextSibling.innerHTML=tmp; if (UI.usemathjax) MathJax.Hub.Queue(['Typeset',MathJax.Hub,nextSibling])">\end{rawhtml}
\@getprint{#2}
\begin{rawhtml}</button><div style="width:800px;max-height:200px;overflow:auto;color:blue;text-align:center"></div><br>\end{rawhtml}
\else
\lstinline@#2(#3)@
\fi
}
\newcommand{\giacinputbigmath}[2][style="width:800px;height:20px;font-size:large"]{\ifhevea
\begin{rawhtml}<div><textarea onkeypress="UI.ckenter(event,this,2)" \end{rawhtml}
\@getprint{#1>#2} 
\begin{rawhtml}</textarea><button onclick="previousSibling.style.display='inherit';var tmp=UI.caseval(previousSibling.value); tmp=UI.latexeval(tmp);nextSibling.innerHTML=tmp; if (UI.usemathjax) MathJax.Hub.Queue(['Typeset',MathJax.Hub,nextSibling])">ok</button><div style="width:800px;max-height:200px;overflow:auto;color:blue;text-align:center"></div></div>\end{rawhtml}
\else
\lstinline@#2@
\fi
}
\newcommand{\giaclink}[2][Tester en ligne]{\ifhevea
\begin{rawhtml}<a href=\end{rawhtml}\@getprint{"#2"}
\begin{rawhtml} target="_blank">\end{rawhtml}
\@getprint{#1}
\begin{rawhtml}</a>\end{rawhtml}
\else
\fi
}
% \giacslider{name}{mini}{maxi}{step}{value}{prog}
\newcommand{\giacslider}[6]{
\ifhevea
\begin{rawhtml}
<div><form onsubmit="setTimeout(function(){UI.eval_form(form);});return false;">
<input type="text" name="name" size="1" value=
\end{rawhtml}
\@getprint{"#1">}
\begin{rawhtml}
=<input type="number" name="valname" onchange="UI.eval_form(form);" value=
\end{rawhtml}
\@getprint{"#5">}
\begin{rawhtml}
<input type="button" value="-" onclick="valname.value -= stepname.value;UI.eval_form(form);">
<input type="button" value="+" onclick="valname.value -= -stepname.value;UI.eval_form(form);">
<input type="number" name="stepname" value=
\end{rawhtml}
\@getprint{"#4">}
\begin{rawhtml}
<input type="range" name="rangename"
onclick="valname.value=value;UI.eval_form(form);" value=
\end{rawhtml}
\@getprint{"#5" min="#2" max="#3" step="#4">}
\begin{rawhtml}
<textarea name="prog" onchange="UI.eval_form(form)" style="width:400px;height:120px;vertical-align:bottom;font-size:large">
\end{rawhtml}
\@getprint{#6}
\begin{rawhtml}
</textarea>
</form>
<span>Not evaled</span></div>
\end{rawhtml}
\else
\fi
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% giac/hevea end code definitions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
