]> matita.cs.unibo.it Git - helm.git/blob - matitaB/matita/matitaweb.js
Matitaweb: secure SHA-256 encryption for passwords.
[helm.git] / matitaB / matita / matitaweb.js
1 var locked;
2 var unlocked;
3 var workarea;
4 var scriptcell;
5 var goalcell;
6 var goals;
7 var goalview;
8 var filename;
9 var logarea;
10 var advanceButton;
11 var retractButton;
12 var cursorButton;
13 var bottomButton;
14 var dialogBox;
15 var dialogTitle;
16 var dialogContent;
17 var metasenv = "";
18 var lockedbackup = "";
19 var matita;
20
21 function text_of_html(h)
22 {
23   if(document.all) {
24      return h.innerText;
25   } else {
26      return h.textContent;
27   }
28 }
29
30 function unescape_html(s)
31 {
32   u = document.getElementById("unescape");
33   u.innerHTML = s;
34   return text_of_html(u)
35 }
36
37 function filterByClass (elements,cname){
38   var itemsfound = new Array;
39   for(var i=0;i<elements.length;i++){
40     if(elements[i].className == cname){
41       itemsfound.push(elements[i]);
42     }
43   }
44   return itemsfound;
45 }
46
47 function initialize()
48 {
49   if (readCookie("session") == null) {
50     window.location = "/login.html"
51   } else {
52     body = document.body;
53     titlebar = document.getElementById("titlebar");
54     matitaTitle = document.getElementById("matitaTitle");
55     apparea = document.getElementById("matitaapparea");
56     locked = document.getElementById("locked");
57     unlocked = document.getElementById("unlocked");
58     toparea = document.getElementById("toparea");
59     workarea = document.getElementById("workarea");
60     scriptcell = document.getElementById("scriptcell");
61     sidearea = document.getElementById("sidearea");
62     disambcell = document.getElementById("disambcell");
63     goalcell = document.getElementById("goalcell");
64     goals = document.getElementById("goals");
65     goalview = document.getElementById("goalview");
66     filename = document.getElementById("filename");
67     logarea = document.getElementById("logarea");
68     advanceButton = document.getElementById("advance");
69     retractButton = document.getElementById("retract");
70     cursorButton = document.getElementById("cursor");
71     bottomButton = document.getElementById("bottom");
72     dialogBox = document.getElementById("dialogBox");
73     uploadBox = document.getElementById("uploadBox");
74     dialogTitle = document.getElementById("dialogTitle");
75     dialogContent = document.getElementById("dialogContent");
76
77     matita = new Object();
78     matita.disambMode = matita.proofMode = false;
79
80     // hide sequent view at start
81     initializeLayout();
82     updateSide();
83
84     changeFile("test.ma");
85
86     // initialize keyboard events in the unlocked script
87     init_keyboard(unlocked);
88
89     init_autotraces();
90
91   }
92 }
93
94 function init_autotraces() {
95     $("#unlocked .autotactic").tooltip({ 
96       delay: 0, 
97       showURL: false, 
98       bodyHandler: function() { 
99         return (trace_of($(this)[0])); 
100       }
101     });
102     $("#locked .autotactic").tooltip({ 
103       delay: 0, 
104       showURL: false, 
105       bodyHandler: function() { 
106         return (trace_of($(this)[0]));
107       }
108     });
109 }
110
111 function trace_of(node) {
112   return text_of_html(filterByClass(node.childNodes,"autotrace")[0]);
113 }
114
115 function changeFile(name) {
116     current_fname = name;
117     matitaTitle.innerHTML = "Matita - cic:/matita/" + name;
118 }
119
120 function init_keyboard(target)
121 {
122     if (target.addEventListener)
123     {
124 //       target.addEventListener("keydown",keydown,false);
125        target.addEventListener("keypress",keypress,false);
126 //       target.addEventListener("keyup",keyup,false);
127 //       target.addEventListener("textInput",textinput,false);
128     }
129     else if (target.attachEvent)
130     {
131 //       target.attachEvent("onkeydown", keydown);
132        target.attachEvent("onkeypress", keypress);
133 //       target.attachEvent("onkeyup", keyup);
134 //       target.attachEvent("ontextInput", textinput);
135     }
136     else
137     {
138 //       target.onkeydown= keydown;
139        target.onkeypress= keypress;
140 //       target.onkeyup= keyup;
141 //       target.ontextinput= textinput;   // probably doesn't work
142     }
143  
144 }
145
146 function keyval(n)
147 {
148     if (n == null) return 'undefined';
149     var s= '' + n;
150     if (n >= 32 && n < 127) s+= ' (' + String.fromCharCode(n) + ')';
151     while (s.length < 9) s+= ' ';
152     return s;
153 }
154  
155 function string_of_key(n)
156 {
157     if (n == null) return 'undefined';
158     return String.fromCharCode(n);
159 }
160
161 function pressmesg(w,e)
162 {
163    debug(w + '  keyCode=' + keyval(e.keyCode) +
164                  ' which=' + keyval(e.which) +
165                  ' charCode=' + keyval(e.charCode) +
166                  '\n          shiftKey='+e.shiftKey
167               + ' ctrlKey='+e.ctrlKey
168               + ' altKey='+e.altKey
169               + ' metaKey='+e.metaKey);
170 }
171  
172 function suppressdefault(e,flag)
173 {
174    if (flag)
175    {
176        if (e.preventDefault) e.preventDefault();
177        if (e.stopPropagation) e.stopPropagation();
178    }
179    return !flag;
180 }
181
182 function restoreSelection(r) {
183     unlocked.focus();
184     if (r != null) {
185         if (window.getSelection)//non IE and there is already a selection
186         {
187             var s = window.getSelection();
188             if (s.rangeCount > 0) 
189                 s.removeAllRanges();
190             s.addRange(r);
191         }
192         else 
193             if (document.createRange)//non IE and no selection
194             {
195                 window.getSelection().addRange(r);
196             }
197             else 
198                 if (document.selection)//IE
199                 {
200                     r.select();
201                 }
202     }
203 }
204
205 function lookup_tex(texmacro)
206 {
207   texmacro = texmacro.substring(1);
208   return unescape(macro2utf8[texmacro]);
209 }
210
211 function strip_tags(tagname,classname) 
212 {
213     var tags = unlocked.getElementsByTagName(tagname);
214     if (is_defined(classname)) {
215         tags = filterByClass(tags,classname);
216     }
217     for (i = 0; i < tags.length; i++) {
218         var children = tags[i].childNodes;
219         for (j = 0; j < children.length; j++) {
220             tags[i].parentNode.insertBefore(children[j],tags[i]);
221         }
222     }
223     while (tags.length > 0) {
224       tags[0].parentNode.removeChild(tags[0]);
225     }
226 }
227
228 function strip_interpr() {
229         strip_tags("A");
230         alert("strip_interpr ended");
231 }
232  
233 function keypress(e)
234 {
235    if (!e) e= event;
236    pressmesg('keypress',e);
237    var s = string_of_key(e.charCode);
238    strip_tags("span","error");
239    if (s == " ") {
240         j = getCursorPos();
241         i = unlocked.innerHTML.html_to_matita().lastIndexOf('\\',j);
242         if (i >= 0) {
243           match = unlocked.innerHTML.html_to_matita().substring(i,j);
244           sym = unescape_html(lookup_tex(match));
245           if (sym != "undefined") {
246              if (window.getSelection) { // non IE
247                 savedRange.setStart(savedsc,savedso - (j-i));
248                 savedRange.deleteContents();
249                 savedRange.insertNode(document.createTextNode(sym));
250                 savedsc.parentNode.normalize();
251                 if (savedRange.collapsed) { // Mozilla
252                   savedRange.setEnd(savedsc,savedRange.endOffset + sym.length);
253                 }
254                 savedRange.collapse(false);
255              } else {
256                 savedRange.moveStart(i-j);
257                 savedRange.text(sym);
258                 savedRange.collapse(false);
259              }
260              restoreSelection(savedRange); 
261              return suppressdefault(e,true);
262           }
263           else {
264              // restoreSelection(0); 
265              return suppressdefault(e,false);
266           }
267         }
268         else return suppressdefault(e,false);
269    } else {
270         return suppressdefault(e,false);
271    }
272 }
273  
274 var logtxt = "";
275
276 function debug(txt)
277 {
278         // internet explorer (v.9) doesn't work with innerHTML
279         // but google chrome's innerText is, in a sense, "write only"
280         // what should we do?
281         // logarea.innerText = txt + "\n" + logarea.innerText;
282         logtxt = /* logtxt + "\n" +*/ txt;
283 }
284
285 function showLog() {
286   logWin = window.open( "", "Matita Log",
287      "width=600,height=450,status,scrollbars,resizable,screenX=20,screenY=40,left=20,top=40");
288   logWin.document.write('<html><head><title>Matita Log' + '</title></head>');   
289   logWin.document.write('<body><textarea style="width:100%;height:100%;">' +
290     logtxt + '</textarea></body></html>');
291   logWin.document.close(); 
292 }
293
294 function listhd(l)
295 {
296         ar = l.split("#");
297         debug("hd of '" + l + "' = '" + ar[0] + "'");
298         return (ar[0]);
299 }
300
301 function listtl(l)
302 {
303         i = l.indexOf("#");
304         tl = l.substr(i+1);
305         debug("tl of '" + l + "' = '" + tl + "'");
306         return (tl);
307 }
308
309 function listcons(x,l)
310 {
311         debug("cons '" + x + "' on '" + l + "'");
312         return (x + "#" + l);
313 }
314
315 function listnil()
316 {
317         return ("");
318 }
319
320 function list_append(l1,l2)
321 { return (l1 + l2) }
322
323 function is_nil(l)
324 {
325         return (l == "");
326 }
327
328 function fold_left (f,acc,l)
329 {
330         if (is_nil(l))
331            { debug("'" + l + "' is fold end");
332            return (acc); }
333         else
334            { debug("'" + l + "' is fold cons");
335              return(fold_left (f,f(acc,(listhd(l))),listtl(l))); }
336 }
337
338 function listiter (f,l)
339 {
340         if (is_nil(l))
341         { debug("'" + l + "' is nil");
342            return;
343         }
344         else
345         {
346            debug("'" + l + "' is not nil");
347            f(listhd(l));
348            listiter(f,listtl(l));
349         }
350 }
351
352 function listmap (f,l)
353 {
354         debug("listmap on " + l);
355         if (is_nil(l)) 
356            { debug("returning listnil");
357              return(listnil());
358            }
359         else 
360            { debug("cons f(hd) map(f,tl)");
361              return(f(listhd(l)) + "#" + listmap(f,listtl(l)));
362            }
363 }
364
365 var statements = listnil();
366
367 var goalarray;
368 var metalist = listnil();
369
370 function pairmap (f,p)
371 {
372   debug("pairmap of '" + p + "'");
373   ar = p.split("|");
374   return (f(ar[0],ar[1])); 
375 }
376
377 function tripletmap (f,p)
378 {
379   debug("tripletmap of '" + p + "'");
380   ar = p.split("|");
381   return (f(ar[0],ar[1],ar[2])); 
382 }
383
384 function fst (p)
385 {
386   debug("fst");
387   return (pairmap (function (a,b) { return (a); }, p));
388 }
389
390 function p13 (p)
391 {
392   debug("p13");
393   return (tripletmap (function (a,b,c) { return (a); }, p));
394 }
395
396 function p23 (p)
397 {
398   debug("p23");
399   return (tripletmap (function (a,b,c) { return (b); }, p));
400 }
401
402 function p33 (p)
403 {
404   debug("f33");
405   return (tripletmap (function (a,b,c) { return (c); }, p));
406 }
407
408 function populate_goalarray(menv)
409 {
410   debug("metasenv.length = " + menv.length);
411   if (menv.length == 0) {
412       try {
413           hideSequent();
414       } catch (err) { };
415   } else {
416       showSequent();
417       goalarray = new Array();
418       metalist = listnil();
419       var tmp_goallist = "";
420       for (i = 0; i < menv.length; i++) {
421         metano = menv[i].getAttribute("number");
422         metaname = menv[i].childNodes[0].childNodes[0].data;
423         goal = menv[i].childNodes[1].childNodes[0].data;
424         debug ("found meta n. " + metano);
425         debug ("found goal\nBEGIN" + goal + "\nEND");
426         goalarray[metano] = goal;
427         tmp_goallist = " <A href=\"javascript:switch_goal(" + metano + ")\">" + metaname + "</A>" + tmp_goallist;
428         metalist = listcons(metano,metalist);
429         debug ("goalarray[\"" + metano + "\"] = " + goalarray[metano]); 
430       }
431       goals.innerHTML = tmp_goallist;
432       debug("new metalist is '" + metalist + "'");
433       if (is_nil(metalist)) {
434         switch_goal();
435       }
436       else {
437         switch_goal(listhd(metalist));
438       }
439   }
440 }
441
442 function switch_goal(meta)
443 {
444   if (typeof meta == "undefined") {
445     goalview.innerHTML = "";
446   }
447   else {
448     debug("switch_goal " + meta + "\n" + goalarray[meta]);
449     goalview.innerHTML = "<B>Goal ?" + meta + ":</B>\n\n" + goalarray[meta];
450   }
451 }
452
453 // the following is used to avoid escaping unicode, which results in 
454 // the server being unable to unescape the string
455 String.prototype.sescape = function() {
456         var patt1 = /%/gi;
457         var patt2 = /=/gi;
458         var patt3 = /&/gi;
459         var patt4 = /\+/gi;
460         var result = this;
461         result = result.replace(patt1,"%25");
462         result = result.replace(patt2,"%3D");
463         result = result.replace(patt3,"%26");
464         result = result.replace(patt4,"%2B");
465         return (result);
466 }
467
468 String.prototype.html_to_matita = function()
469 {
470         var patt1 = /<br(\/|)>/gi;
471         var patt2 = /</gi
472         var patt3 = />/gi
473         var patt4 = /&lt;/gi;
474         var patt5 = /&gt;/gi;
475         var patt6 = /&nbsp;/gi;
476         var result = this;
477         result = result.replace(patt1,"\n");
478         result = result.replace(patt2,"\005");
479         result = result.replace(patt3,"\006");
480         result = result.replace(patt4,"<");
481         result = result.replace(patt5,">");
482         result = result.replace(patt6," ");
483         return (unescape(result));
484 }
485
486 String.prototype.matita_to_html = function()
487 {
488         var patt1 = /</gi
489         var patt2 = />/gi
490         var patt3 = /\005/gi;
491         var patt4 = /\006/gi;
492         var result = this;
493         result = result.replace(patt1,"&lt;");
494         result = result.replace(patt2,"&gt;");
495         result = result.replace(patt3,"<");
496         result = result.replace(patt4,">");
497         return (unescape(result));
498 }
499
500 function pause()
501 {
502         advanceButton.disabled = true;
503         retractButton.disabled = true;
504         cursorButton.disabled = true;
505         bottomButton.disabled = true;
506 }
507
508 function resume()
509 {
510         advanceButton.disabled = false;
511         retractButton.disabled = false;
512         cursorButton.disabled = false;
513         bottomButton.disabled = false;
514 }
515
516 function is_defined(x)
517 {
518         return (typeof x != "undefined");
519 }
520
521 /* servicename: name of the service being called
522  * reqbody: text of the request
523  * processResponse: processes the server response
524  *     (takes the response text in input, undefined in case of error)
525  */
526 function callServer(servicename,processResponse,reqbody)
527 {
528         var req = null; 
529         // pause();
530         if (window.XMLHttpRequest)
531         {
532                 req = new XMLHttpRequest();
533         } 
534         else if (window.ActiveXObject) 
535         {
536                 try {
537                                 req = new ActiveXObject("Msxml2.XMLHTTP");
538                 } catch (e)
539                 {
540                         try {
541                                 req = new ActiveXObject("Microsoft.XMLHTTP");
542                                 } catch (e) {}
543                 }
544         }
545         req.onreadystatechange = function()
546         { 
547
548                 rs = req.readyState;
549
550                 if(rs == 4)
551                 {
552                         stat = req.status;
553                         stxt = req.statusText;
554                         if(stat == 200)
555                         {
556                           debug(req.responseText);
557                           if (window.DOMParser) {
558                             parser=new DOMParser();
559                             xmlDoc=parser.parseFromString(req.responseText,"text/xml");
560                           }
561                           else // Internet Explorer
562                           {
563                             xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
564                             xmlDoc.async="false";
565                             xmlDoc.loadXML(req.responseText);
566                           }     
567                           processResponse(xmlDoc);
568                         } else {
569                           processResponse();
570                         }
571                 } 
572         };
573         req.open("POST", servicename); // + escape(unlocked.innerHTML), true);
574         req.setRequestHeader("Content-type","application/x-www-form-urlencoded");       
575         if (reqbody) {
576                 req.send(reqbody); 
577         } else {
578                 req.send();
579         }
580   
581 }
582
583 function advanceForm1()
584 {
585         processor = function(xml) {
586                 if (is_defined(xml)) {
587                         var parsed = xml.getElementsByTagName("parsed")[0];
588                         var ambiguity = xml.getElementsByTagName("ambiguity")[0];
589                         var disamberr = xml.getElementsByTagName("disamberror")[0];
590                         if (is_defined(parsed)) {
591                         // debug("advance: received response\nBEGIN\n" + req.responseText + "\nEND");
592                             var len = parseInt(parsed.getAttribute("length"));
593                             // len0 = unlocked.innerHTML.length;
594                             var unescaped = unlocked.innerHTML.html_to_matita();
595                             var parsedtxt = parsed.childNodes[0].wholeText;
596                             //parsedtxt = unescaped.substr(0,len); 
597                             var unparsedtxt = unescaped.substr(len);
598                             lockedbackup += parsedtxt;
599                             locked.innerHTML = lockedbackup;
600                             unlocked.innerHTML = unparsedtxt.matita_to_html();
601                             // len1 = unlocked.innerHTML.length;
602                             // len2 = len0 - len1;
603                             var len2 = parsedtxt.length;
604                             var metasenv = xml.getElementsByTagName("meta");
605                             populate_goalarray(metasenv);
606                             init_autotraces();
607                             statements = listcons(len2,statements);
608                             unlocked.scrollIntoView(true);
609                         }
610                         else if (is_defined(ambiguity)) {
611                             var start = parseInt(ambiguity.getAttribute("start"));
612                             var stop = parseInt(ambiguity.getAttribute("stop"));
613                             var choices = xml.getElementsByTagName("choice");
614
615                             matita.ambiguityStart = start;
616                             matita.ambiguityStop = stop;
617                             matita.unlockedbackup = unlocked.innerHTML.html_to_matita();
618                             matita.interpretations = [];
619                         
620                             var unlockedtxt = unlocked.innerHTML.html_to_matita();
621                             var pre = unlockedtxt.substring(0,start).matita_to_html();
622                             var mid = unlockedtxt.substring(start,stop).matita_to_html();
623                             var post = unlockedtxt.substring(stop).matita_to_html();
624                             unlocked.innerHTML = pre + 
625                                     "<span class=\"error\" title=\"disambiguation error\">" +
626                                     mid + "</span>" + post;
627
628                             var title = "<H3>Ambiguous input</H3>";
629                             disambcell.innerHTML = title;
630                             for (i = 0;i < choices.length;i++) {
631                                 matita.interpretations[i] = new Object();
632
633                                 var href = choices[i].getAttribute("href");
634                                 var title = choices[i].getAttribute("title");
635                                 var desc = choices[i].childNodes[0].nodeValue;
636
637                                 matita.interpretations[i].href = href;
638                                 matita.interpretations[i].title = title;
639                                 matita.interpretations[i].desc = desc;
640                                 
641                                 var choice = document.createElement("input");
642                                 choice.setAttribute("type","radio");
643                                 choice.setAttribute("name","interpr");
644                                 choice.setAttribute("href",href);
645                                 choice.setAttribute("title",title);
646                                 if (i == 0) choice.setAttribute("checked","");
647                                 
648                                 disambcell.appendChild(choice);
649                                 disambcell.appendChild(document.createTextNode(desc));
650                                 disambcell.appendChild(document.createElement("br"));
651                             }
652
653                             var okbutton = document.createElement("input");
654                             okbutton.setAttribute("type","button");
655                             okbutton.setAttribute("value","OK");
656                             okbutton.setAttribute("onclick","do_disambiguate()");
657                             var cancelbutton = document.createElement("input");
658                             cancelbutton.setAttribute("type","button");
659                             cancelbutton.setAttribute("value","Cancel");
660                             cancelbutton.setAttribute("onclick","cancel_disambiguate()");
661
662                             disambcell.appendChild(okbutton);
663                             disambcell.appendChild(cancelbutton);
664
665                             disable_toparea();
666
667                             matita.disambMode = true;
668                             updateSide();
669                         }
670                         else if (is_defined(disamberr)) {
671                             set_cps(disamberr.childNodes);
672                             matita.unlockedbackup = unlocked.innerHTML.html_to_matita();
673                             matita.disambMode = true;
674                             disable_toparea();
675                             next_cp(0);
676                         }
677                         else {
678                             var error = xml.getElementsByTagName("error")[0]; 
679                             unlocked.innerHTML = error.childNodes[0].wholeText;
680                             // debug(xml.childNodes[0].nodeValue);
681                         }
682                 } else {
683                         debug("advance failed");
684                 }
685                 resume();
686         };
687         pause();
688         callServer("advance",processor,"body=" + (unlocked.innerHTML.html_to_matita()).sescape());
689   
690 }
691
692 // get or set <choicepoint>'s (in case of disamb error)
693 function get_cps() {
694         return matita.choicepoints
695 }
696
697 function set_cps(cps) {
698         matita.choicepoints = cps;
699 }
700
701 // get radio buttons for <choice>'s in a given cp
702 function get_choice_opts(i) {
703    var res = [];
704    var choices = get_cps()[i].childNodes;
705    for (var j = 0;j < choices.length;j++) {
706       var href = choices[j].getAttribute("href");
707       var title = choices[j].getAttribute("title");
708       var desc;
709       if (is_defined(title)) {
710            desc = title;
711       } else if (is_defined(href)) {
712            desc = href;
713       } else {
714            desc = "Preliminary error";
715       }
716   
717       res[j] = document.createElement("input");
718       res[j].setAttribute("type","radio");
719       res[j].setAttribute("name","choice");
720       res[j].setAttribute("choicepointno",i);
721       res[j].setAttribute("choiceno",j);
722       res[j].setAttribute("href",href);
723       res[j].setAttribute("title",title);
724       res[j].setAttribute("desc",desc);
725       
726       if (j == 0) res[j].setAttribute("checked","");
727   }
728   return res;
729 }
730
731 // get radio buttons for <failure>'s in a given choice
732 function get_failure_opts(i,j) {
733    var res = [];
734    var failures = get_cps()[i].childNodes[j].childNodes;
735    for (var k = 0;k < failures.length;k++) {
736       var start = failures[k].getAttribute("start");
737       var stop = failures[k].getAttribute("stop");
738       var title = failures[k].getAttribute("title");
739   
740       res[k] = document.createElement("input");
741       res[k].setAttribute("type","radio");
742       res[k].setAttribute("name","failure");
743       res[k].setAttribute("choicepointno",i);
744       res[k].setAttribute("choiceno",j);
745       res[k].setAttribute("failureno",k);
746       res[k].setAttribute("start",start);
747       res[k].setAttribute("stop",stop);
748       res[k].setAttribute("title",title);
749       
750       if (k == 0) res[k].setAttribute("checked","");
751   }
752   return res;
753 }
754
755 function next_cp(curcp) {
756         var cp = get_cps()[curcp];
757         var start = parseInt(cp.getAttribute("start"));
758         var stop = parseInt(cp.getAttribute("stop"));
759
760         matita.errorStart = start;
761         matita.errorStop = stop;
762         // matita.unlockedbackup = unlocked.innerHTML.html_to_matita();
763         
764         var unlockedtxt = matita.unlockedbackup;
765         var pre = unlockedtxt.substring(0,start).matita_to_html();
766         var mid = unlockedtxt.substring(start,stop).matita_to_html();
767         var post = unlockedtxt.substring(stop).matita_to_html();
768         unlocked.innerHTML = pre + 
769                 "<span class=\"error\" title=\"disambiguation failed\">" +
770                 mid + "</span>" + post;
771
772         var title = "<H3>Disambiguation failed</H3>";
773         disambcell.innerHTML = title;
774         var choices = get_choice_opts(curcp);
775         for (var i = 0;i < choices.length;i++) {
776             disambcell.appendChild(choices[i]);
777             disambcell.appendChild(document.createTextNode(choices[i].getAttribute("desc")));
778             disambcell.appendChild(document.createElement("br"));
779         }
780         
781         // update index of the next choicepoint
782         new_curcp = (curcp + 1) % get_cps().length;
783
784         var okbutton = document.createElement("input");
785         okbutton.setAttribute("type","button");
786         okbutton.setAttribute("value","OK");
787         okbutton.setAttribute("onclick","show_failures()");
788         var cancelbutton = document.createElement("input");
789         cancelbutton.setAttribute("type","button");
790         cancelbutton.setAttribute("value","Close");
791         cancelbutton.setAttribute("onclick","cancel_disambiguate()");
792         var tryagainbutton = document.createElement("input");
793         tryagainbutton.setAttribute("type","button");
794         if (new_curcp > 0) {
795             tryagainbutton.setAttribute("value","Try something else");
796         } else {
797             tryagainbutton.setAttribute("value","Restart");
798         }
799         tryagainbutton.setAttribute("onclick","next_cp(" + new_curcp + ")");
800
801         disambcell.appendChild(okbutton);
802         disambcell.appendChild(tryagainbutton);
803         disambcell.appendChild(cancelbutton);
804
805         //disable_toparea();
806
807         //matita.disambMode = true;
808         updateSide();
809         
810 }
811
812 function show_failures() {
813
814         var choice = document.getElementsByName("choice")[get_checked_index("choice")];
815         var cpno = parseInt(choice.getAttribute("choicepointno"));
816         var choiceno = parseInt(choice.getAttribute("choiceno"));
817         var choicedesc = choice.getAttribute("desc");
818
819         var title = "<H3>Disambiguation failed</H3>";
820         var subtitle = "<p>Errors at node " + cpno + " = " + choicedesc + "</p>";
821
822         disambcell.innerHTML = title + subtitle;
823         var failures = get_failure_opts(cpno,choiceno);
824         for (var i = 0;i < failures.length;i++) {
825             disambcell.appendChild(failures[i]);
826             disambcell.appendChild(document.createTextNode(failures[i].getAttribute("title")));
827             disambcell.appendChild(document.createElement("br"));
828         }
829         
830         var okbutton = document.createElement("input");
831         okbutton.setAttribute("type","button");
832         okbutton.setAttribute("value","Show error loc");
833         okbutton.setAttribute("onclick","show_err()");
834         var cancelbutton = document.createElement("input");
835         cancelbutton.setAttribute("type","button");
836         cancelbutton.setAttribute("value","Close");
837         cancelbutton.setAttribute("onclick","cancel_disambiguate()");
838         var backbutton = document.createElement("input");
839         backbutton.setAttribute("type","button");
840         backbutton.setAttribute("value","<< Back");
841         backbutton.setAttribute("onclick","next_cp(" + cpno + ")");
842
843         disambcell.appendChild(backbutton);
844         disambcell.appendChild(okbutton);
845         disambcell.appendChild(cancelbutton);
846         
847 }
848
849 function show_err() {
850         var radios = document.getElementsByName("failure");
851         for (i = 0; i < radios.length; i++) {
852             if (radios[i].checked) {
853                 var start = radios[i].getAttribute("start");
854                 var stop = radios[i].getAttribute("stop");
855                 var title = radios[i].getAttribute("title");
856                 var unlockedtxt = matita.unlockedbackup;
857                 var pre = unlockedtxt.substring(0,start).matita_to_html();
858                 var mid = unlockedtxt.substring(start,stop).matita_to_html();
859                 var post = unlockedtxt.substring(stop).matita_to_html();
860                 unlocked.innerHTML = pre + 
861                         "<span class=\"error\" title=\"Disambiguation failure\">" +
862                         mid + "</span>" + post;
863                 break;
864             }
865         }
866 }
867
868 function gotoBottom()
869 {
870         processor = function(xml) {
871                 if (is_defined(xml)) {
872                         // debug("goto bottom: received response\nBEGIN\n" + req.responseText + "\nEND");
873                         var parsed = xml.getElementsByTagName("parsed");
874                         var localized = xml.getElementsByTagName("localized")[0];
875                         var ambiguity = xml.getElementsByTagName("ambiguity")[0];
876                         var generic_err = xml.getElementsByTagName("error")[0];
877                         for (var i = 0;i < parsed.length; i++) {
878                           var len = parsed[i].getAttribute("length");
879                           // len0 = unlocked.innerHTML.length;
880                           var unescaped = unlocked.innerHTML.html_to_matita();
881                           // the browser may decide to split textnodes: use wholeText!
882                           var parsedtxt = parsed[i].childNodes[0].wholeText;
883                           //parsedtxt = unescaped.substr(0,len); 
884                           var unparsedtxt = unescaped.substr(len);
885                           lockedbackup += parsedtxt;
886                           locked.innerHTML = lockedbackup; //.matita_to_html();
887                           unlocked.innerHTML = unparsedtxt.matita_to_html();
888                           // len1 = unlocked.innerHTML.length;
889                           var len2 = parsedtxt.length;
890                           statements = listcons(len2,statements);
891                         }
892                         unlocked.scrollIntoView(true);
893                         metasenv = xml.getElementsByTagName("meta");
894                         init_autotraces();
895                         populate_goalarray(metasenv);
896
897                         if (is_defined(ambiguity)) {
898                             var start = parseInt(ambiguity.getAttribute("start"));
899                             var stop = parseInt(ambiguity.getAttribute("stop"));
900                             var choices = xml.getElementsByTagName("choice");
901
902                             matita.ambiguityStart = start;
903                             matita.ambiguityStop = stop;
904                             matita.unlockedbackup = unlocked.innerHTML.html_to_matita();
905                             matita.interpretations = [];
906                         
907                             var unlockedtxt = unlocked.innerHTML.html_to_matita();
908                             var pre = unlockedtxt.substring(0,start).matita_to_html();
909                             var mid = unlockedtxt.substring(start,stop).matita_to_html();
910                             var post = unlockedtxt.substring(stop).matita_to_html();
911                             unlocked.innerHTML = pre + 
912                                     "<span class=\"error\" title=\"disambiguation error\">" +
913                                     mid + "</span>" + post;
914
915                             var title = "<H3>Ambiguous input</H3>";
916                             disambcell.innerHTML = title;
917                             for (i = 0;i < choices.length;i++) {
918                                 matita.interpretations[i] = new Object();
919
920                                 var href = choices[i].getAttribute("href");
921                                 var title = choices[i].getAttribute("title");
922                                 var desc = choices[i].childNodes[0].nodeValue;
923
924                                 matita.interpretations[i].href = href;
925                                 matita.interpretations[i].title = title;
926                                 matita.interpretations[i].desc = desc;
927                                 
928                                 var choice = document.createElement("input");
929                                 choice.setAttribute("type","radio");
930                                 choice.setAttribute("name","interpr");
931                                 choice.setAttribute("href",href);
932                                 choice.setAttribute("title",title);
933                                 if (i == 0) choice.setAttribute("checked","");
934                                 
935                                 disambcell.appendChild(choice);
936                                 disambcell.appendChild(document.createTextNode(desc));
937                                 disambcell.appendChild(document.createElement("br"));
938                             }
939
940                             var okbutton = document.createElement("input");
941                             okbutton.setAttribute("type","button");
942                             okbutton.setAttribute("value","OK");
943                             okbutton.setAttribute("onclick","do_disambiguate()");
944                             var cancelbutton = document.createElement("input");
945                             cancelbutton.setAttribute("type","button");
946                             cancelbutton.setAttribute("value","Cancel");
947                             cancelbutton.setAttribute("onclick","cancel_disambiguate()");
948
949                             disambcell.appendChild(okbutton);
950                             disambcell.appendChild(cancelbutton);
951
952                             disable_toparea();
953
954                             matita.disambMode = true;
955                             updateSide();
956                         }
957                         if (is_defined(localized)) {
958                             unlocked.innerHTML = localized.wholeText;
959                         }
960                         if (is_defined(generic_err)) {
961                             debug("Unmanaged error:\n" ^ generic_err.wholeText);
962                         }
963                 } else {
964                         debug("goto bottom failed");
965                 } 
966                 resume();
967         };
968         pause();
969         callServer("bottom",processor,"body=" + (unlocked.innerHTML.html_to_matita()).sescape());
970 }
971
972
973 function gotoTop()
974 {
975         processor = function(xml) {
976                 if (is_defined(xml)) {
977                   if (xml.childNodes[0].textContent != "ok") {
978                      debug("goto top failed");
979                   }
980                   else
981                         statements = listnil();
982                         /*
983                         lockedlen = locked.innerHTML.length - statementlen;
984                         statement = locked.innerHTML.substr(lockedlen, statementlen);
985                         locked.innerHTML = locked.innerHTML.substr(0,lockedlen);
986                         unlocked.innerHTML = statement + unlocked.innerHTML;
987                         */
988                         unlocked.innerHTML = lockedbackup + unlocked.innerHTML;
989                         lockedbackup = "";
990                         locked.innerHTML = lockedbackup;
991                         init_autotraces();
992                         hideSequent();
993                         unlocked.scrollIntoView(true);
994                 } else {
995                         debug("goto top failed");
996                 } 
997                 resume();
998         };
999         pause();
1000         callServer("top",processor,"body=" + (unlocked.innerHTML.html_to_matita()).sescape());
1001   
1002 }
1003 function gotoPos(offset)
1004 {
1005         if (!is_defined(offset)) {
1006                 offset = getCursorPos();
1007         }
1008         processor = function(xml) {
1009                 if (is_defined(xml)) {
1010                         parsed = xml.getElementsByTagName("parsed")[0];
1011                         len = parseInt(parsed.getAttribute("length"));
1012                         // len0 = unlocked.innerHTML.length;
1013                         unescaped = unlocked.innerHTML.html_to_matita();
1014                         parsedtxt = parsed.childNodes[0].wholeText;
1015                         //parsedtxt = unescaped.substr(0,len); 
1016                         unparsedtxt = unescaped.substr(len);
1017                         lockedbackup += parsedtxt;
1018                         locked.innerHTML = lockedbackup; //.matita_to_html();
1019                         unlocked.innerHTML = unparsedtxt.matita_to_html();
1020                         // len1 = unlocked.innerHTML.length;
1021                         len2 = parsedtxt.length;
1022                         metasenv = xml.getElementsByTagName("meta");
1023                         // populate_goalarray(metasenv);
1024                         statements = listcons(len2,statements);
1025                         unlocked.scrollIntoView(true);
1026                         // la populate non andrebbe fatta a ogni passo
1027                         if (offset <= len) {
1028                                 init_autotraces();
1029                                 populate_goalarray(metasenv);
1030                                 resume();
1031                         } else {
1032                                 gotoPos(offset - len);
1033                         }
1034                 } else {
1035                         init_autotraces();
1036                         unlocked.scrollIntoView(true);
1037                         populate_goalarray(metasenv);
1038                         resume();
1039                 }
1040         }
1041         pause();
1042         callServer("advance",processor,"body=" + (unlocked.innerHTML.html_to_matita()).sescape());
1043 }
1044
1045 function retract()
1046 {
1047         processor = function(xml) {
1048                 if (typeof xml != "undefined") {
1049                         // debug("advance: received response\nBEGIN\n" + req.responseText + "\nEND");
1050                         statementlen = parseInt(listhd(statements));
1051                         statements = listtl(statements);
1052                         /*
1053                         lockedlen = locked.innerHTML.length - statementlen;
1054                         statement = locked.innerHTML.substr(lockedlen, statementlen);
1055                         locked.innerHTML = locked.innerHTML.substr(0,lockedlen);
1056                         unlocked.innerHTML = statement + unlocked.innerHTML;
1057                         */
1058                         lockedlen = lockedbackup.length - statementlen;
1059                         statement = lockedbackup.substr(lockedlen, statementlen);
1060                         lockedbackup = lockedbackup.substr(0,lockedlen);
1061                         locked.innerHTML = lockedbackup;
1062                         unlocked.innerHTML = statement + unlocked.innerHTML;
1063                         metasenv = xml.getElementsByTagName("meta");
1064                         init_autotraces();
1065                         populate_goalarray(metasenv);
1066                         unlocked.scrollIntoView(true);
1067                 } else {
1068                         debug("retract failed");
1069                 }
1070                 resume();
1071         };
1072         debug("retract 1");
1073         pause();
1074         callServer("retract",processor);
1075         debug("retract 2");
1076 }
1077
1078 function openFile()
1079
1080         processor = function(xml)
1081         {
1082                 if (is_defined(xml)) {  
1083                         lockedbackup = "";
1084                         locked.innerHTML = lockedbackup;
1085                         unlocked.innerHTML = xml.documentElement.wholeText;
1086                 } else {
1087                         debug("file open failed");
1088                 }
1089         };
1090         callServer("open",processor,"file=" + escape(filename.value)); 
1091 }
1092
1093 function retrieveFile(thefile)
1094
1095         processor = function(xml)
1096         {
1097                 if (is_defined(xml)) {  
1098                         changeFile(thefile);
1099                         lockedbackup = ""
1100                         locked.innerHTML = lockedbackup;
1101                         // code originally used in google chrome (problems with mozilla)
1102                         // debug(xml.getElementsByTagName("file")[0].childNodes[0].nodeValue);
1103                         // unlocked.innerHTML = xml.getElementsByTagName("file")[0].childNodes[0].nodeValue;
1104                         debug(xml.childNodes[0].textContent);
1105                         if (document.all) { // IE
1106                           unlocked.innerHTML = xml.childNodes[0].text;
1107                         } else {
1108                           unlocked.innerHTML = xml.childNodes[0].textContent;
1109                         }
1110                         init_autotraces();
1111
1112                 } else {
1113                         debug("file open failed");
1114                 }
1115         };
1116         abortDialog();
1117         callServer("open",processor,"file=" + escape(thefile)); 
1118 }
1119
1120 function showLibrary(title,callback,reloadDialog)
1121
1122         var req = null;
1123         dialogBox.reload = reloadDialog; 
1124         // pause();
1125         if (window.XMLHttpRequest)
1126         {
1127                 req = new XMLHttpRequest();
1128         } 
1129         else if (window.ActiveXObject) 
1130         {
1131                 try {
1132                                 req = new ActiveXObject("Msxml2.XMLHTTP");
1133                 } catch (e)
1134                 {
1135                         try {
1136                                 req = new ActiveXObject("Microsoft.XMLHTTP");
1137                                 } catch (e) {}
1138                 }
1139         }
1140         req.onreadystatechange = function()
1141         { 
1142
1143                 rs = req.readyState;
1144
1145                 if(rs == 4)
1146                 {
1147                         stat = req.status;
1148                         stxt = req.statusText;
1149                         if(stat == 200)
1150                         {
1151                           debug(req.responseText);
1152                           showDialog("<H2>" + title + "</H2>",req.responseText, callback);
1153                         } 
1154                 } 
1155         };
1156         req.open("POST", "viewlib"); // + escape(unlocked.innerHTML), true);
1157         req.setRequestHeader("Content-type","application/x-www-form-urlencoded");       
1158         req.send();
1159   
1160 }
1161
1162 function uploadDialog()
1163 {  
1164         uploadBox.style.display = "block";
1165 }
1166
1167 function uploadOK()
1168 {   
1169    var file = document.getElementById("uploadFilename").files[0];
1170    if (file) { 
1171        var filecontent = file.getAsText("UTF-8");
1172        locked.innerHTML = lockedbackup;
1173        unlocked.innerHTML = filecontent;
1174        uploadBox.style.display = "none";
1175    }
1176 //   if (file) { 
1177 //      var reader = new FileReader();
1178 //      reader.readAsText(file, "UTF-8");
1179 //       reader.onloadend = function (evt) {
1180 //         lockedbackup = "";
1181 //           locked.innerHTML = lockedbackup
1182 //           unlocked.innerHTML = evt.target.result;
1183 //           uploadBox.style.display = "none";
1184 //       }
1185 //       reader.onerror = function (evt) {
1186 //         debug("file open failed");
1187 //           uploadBox.style.display = "none";
1188 //      }
1189 //   }
1190 }
1191
1192 function openDialog()
1193 {  
1194         callback = function (fname) { retrieveFile(fname); };
1195         showLibrary("Open file", callback, openDialog);
1196 }
1197
1198 function saveDialog()
1199 {  
1200         callback = function (fname) { 
1201           abortDialog();
1202           saveFile(fname,
1203                    (locked.innerHTML.html_to_matita()).sescape(),
1204                    (unlocked.innerHTML.html_to_matita()).sescape(),
1205                    false,saveDialog); 
1206         };
1207         showLibrary("Save file as", callback, saveDialog);
1208 }
1209
1210 function newDialog()
1211 {
1212         callback = function (fname) { 
1213           abortDialog();
1214           saveFile(fname,"","",false,newDialog,true);
1215         };
1216         showLibrary("Create new file", callback, newDialog);
1217 }
1218
1219
1220 function saveFile(fname,lockedtxt,unlockedtxt,force,reloadDialog,reloadFile)
1221 {
1222         if (!is_defined(reloadFile)) { reloadFile = true };
1223         if (!is_defined(fname)) {
1224             fname = current_fname;
1225             lockedtxt = (locked.innerHTML.html_to_matita()).sescape();
1226             unlockedtxt = (unlocked.innerHTML.html_to_matita()).sescape();
1227             force = true;
1228             // when force is true, reloadDialog is not needed 
1229         }
1230         processor = function(xml) {
1231                 if (is_defined(xml)) {
1232                   if (xml.childNodes[0].textContent != "ok") {
1233                     if (confirm("File already exists. All existing data will be lost.\nDo you want to proceed anyway?")) {
1234                        saveFile(fname,lockedtxt,unlockedtxt,true,reloadDialog,reloadFile);
1235                     } else {
1236                       reloadDialog();
1237                     }
1238                   } else {
1239                     changeFile(fname);
1240                     debug("file saved!");
1241                     if (reloadFile) { retrieveFile(fname); }
1242                   }
1243                 } else {
1244                         debug("save file failed");
1245                 }
1246                 resume();
1247         };
1248         if (is_defined(fname)) {
1249           pause();
1250           callServer("save",processor,"file=" + escape(fname) + 
1251                                     "&locked=" + lockedtxt +
1252                                     "&unlocked=" + unlockedtxt +
1253                                     "&force=" + force);
1254         }
1255         else { debug("no file selected"); }
1256 }
1257
1258 function createDir() {
1259    abortDialog();
1260    dirname = prompt("New directory name:\ncic:/matita/","newdir");
1261    if (dirname != null) {
1262         processor = function(xml) {
1263                 if (is_defined(xml)) {
1264                   if (xml.childNodes[0].textContent != "ok") {
1265                       alert("An error occurred :-(");
1266                   }
1267                 } else {
1268                       alert("An error occurred :-(");
1269                 }
1270                 dialogBox.reload();
1271         };
1272         pause();
1273         callServer("save",processor,"file=" + escape(dirname) + 
1274                                     "&locked=&unlocked=&force=false&dir=true");
1275    } else {
1276       dialogBox.reload();
1277    }
1278 }
1279
1280 function commitAll()
1281 {
1282         processor = function(xml) {
1283                 if (is_defined(xml)) {
1284                         debug(xml.getElementsByTagName("details")[0].textContent);
1285                         alert("Commit executed: see details in the log.\n\n" +
1286                               "NOTICE: this message does NOT imply (yet) that the commit was successful.");
1287                 } else {
1288                         alert("Commit failed!");
1289                 }
1290                 resume();
1291         };
1292         pause();
1293         callServer("commit",processor);
1294 }
1295
1296 function updateAll()
1297 {
1298         processor = function(xml) {
1299                 if (is_defined(xml)) {
1300                         alert("Update executed.\n\n" +
1301                               "Details:\n" +
1302                               xml.getElementsByTagName("details")[0].textContent);
1303                 } else {
1304                         alert("Update failed!");
1305                 }
1306                 resume();
1307         };
1308         pause();
1309         callServer("update",processor);
1310 }
1311
1312 var goalcell;
1313
1314 function hideSequent() {
1315         matita.proofMode = false;
1316         updateSide();
1317 }
1318
1319 function showSequent() {
1320         matita.proofMode = true;
1321         updateSide();
1322 }
1323
1324 function showDialog(title,content,callback) {
1325   dialogTitle.innerHTML = title;
1326   dialogContent.innerHTML = content;
1327   dialogBox.callback = callback;
1328
1329   //Get the screen height and width
1330   var maskHeight = $(document).height();
1331   var maskWidth = $(window).width();
1332   
1333   //Set heigth and width to mask to fill up the whole screen
1334   $('#mask').css({'width':maskWidth,'height':maskHeight});
1335   
1336   //transition effect           
1337   $('#mask').fadeIn(100);       
1338   $('#mask').fadeTo(200,0.8);   
1339   
1340   //Get the window height and width
1341   var winH = $(window).height();
1342   var winW = $(window).width();
1343   
1344   //Set the popup window to center
1345   $('#dialogBox').css('top',  winH/2-$('#dialogBox').height()/2);
1346   $('#dialogBox').css('left', winW/2-$('#dialogBox').width()/2);
1347   
1348   //transition effect
1349   $('#dialogBox').fadeIn(200); 
1350
1351   dialogBox.style.display = "block";
1352 }
1353
1354 function abortDialog(dialog) {
1355   $('#mask').hide();
1356   dialogBox.style.display = "none";
1357 }
1358
1359 function removeElement(id) {
1360   var element = document.getElementById(id);
1361   element.parentNode.removeChild(element);
1362
1363
1364 var savedsc;
1365 var savedso;
1366
1367 function getCursorPos() {
1368   var cursorPos;
1369   if (window.getSelection) {
1370     var selObj = window.getSelection();
1371     savedRange = selObj.getRangeAt(0);
1372     savedsc = savedRange.startContainer;
1373     savedso = savedRange.startOffset;
1374     //cursorPos =  findNode(selObj.anchorNode.parentNode.childNodes, selObj.anchorNode) + selObj.anchorOffset;
1375     cursorPos =  findNode(unlocked.childNodes, selObj.anchorNode,0) + selObj.anchorOffset;
1376     /* FIXME the following works wrong in Opera when the document is longer than 32767 chars */
1377     return(cursorPos);
1378   }
1379   else if (document.selection) {
1380     savedRange = document.selection.createRange();
1381     var bookmark = savedRange.getBookmark();
1382     /* FIXME the following works wrong when the document is longer than 65535 chars */
1383     cursorPos = bookmark.charCodeAt(2) - 11; /* Undocumented function [3] */
1384     return(cursorPos);
1385   }
1386 }
1387
1388 function findNode(list, node, acc) {
1389   for (var i = 0; i < list.length; i++) {
1390     if (list[i] == node) {
1391    //   debug("success " + i);
1392       return acc;
1393     }
1394     if (list[i].hasChildNodes()) {
1395        try {
1396    //      debug("recursion on node " + i);
1397          return (findNode(list[i].childNodes,node,acc))
1398        }
1399        catch (e) { /* debug("recursion failed"); */ }
1400     }
1401     sandbox = document.getElementById("sandbox");
1402     dup = list[i].cloneNode(true);
1403     sandbox.appendChild(dup);
1404 //    debug("fail " + i + ": " + sandbox.innerHTML);
1405     acc += sandbox.innerHTML.html_to_matita().length;
1406     sandbox.removeChild(dup);
1407   }
1408   throw "not found";
1409 }
1410
1411 function test () {
1412   debug("cursor test: " + unlocked.innerHTML.substr(0,getCursorPos()));
1413 }
1414
1415 function get_checked_index(name) {
1416         var radios = document.getElementsByName(name);
1417         for (i = 0; i < radios.length; i++) {
1418             if (radios[i].checked) {
1419                     return i;
1420             }
1421         }
1422         return null;
1423 }
1424
1425 function cancel_disambiguate() {
1426         matita.disambMode = false;
1427         $('#whitemask').hide();
1428         updateSide();
1429 }
1430
1431 function do_disambiguate() {
1432         var i = get_checked_index("interpr");
1433         if (i != null) {
1434             var pre = matita.unlockedbackup
1435                       .substring(0,matita.ambiguityStart).matita_to_html();
1436             var mid = matita.unlockedbackup
1437                       .substring(matita.ambiguityStart,matita.ambiguityStop)
1438                       .matita_to_html();
1439             var post = matita.unlockedbackup
1440                        .substring(matita.ambiguityStop).matita_to_html();
1441
1442             var href = matita.interpretations[i].href;
1443             var title = matita.interpretations[i].title;
1444
1445             if (is_defined(title)) {
1446                 mid = "<A href=\"" + href + "\" title=\"" + title + "\">" + mid + "</A>";
1447             } else {
1448                 mid = "<A href=\"" + href + "\">" + mid + "</A>";
1449             }
1450
1451             unlocked.innerHTML = pre + mid + post;
1452
1453             matita.disambMode = false;
1454             $('#whitemask').hide();
1455             updateSide();
1456         }
1457 }
1458
1459 function do_showerror() {
1460         var i = get_checked_index("choice");
1461         if (i != null) {
1462             var pre = matita.unlockedbackup
1463                       .substring(0,matita.ambiguityStart).matita_to_html();
1464             var mid = matita.unlockedbackup
1465                       .substring(matita.ambiguityStart,matita.ambiguityStop)
1466                       .matita_to_html();
1467             var post = matita.unlockedbackup
1468                        .substring(matita.ambiguityStop).matita_to_html();
1469
1470             var href = matita.interpretations[i].href;
1471             var title = matita.interpretations[i].title;
1472
1473             if (is_defined(title)) {
1474                 mid = "<A href=\"" + href + "\" title=\"" + title + "\">" + mid + "</A>";
1475             } else {
1476                 mid = "<A href=\"" + href + "\">" + mid + "</A>";
1477             }
1478
1479             unlocked.innerHTML = pre + mid + post;
1480
1481         }
1482 }
1483
1484 function readCookie(name) {
1485         var nameEQ = name + "=";
1486         var ca = document.cookie.split(';');
1487         for(var i=0;i < ca.length;i++) {
1488                 var c = ca[i];
1489                 while (c.charAt(0)==' ') c = c.substring(1,c.length);
1490                 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
1491         }
1492         return null;
1493 }
1494
1495 function delete_cookie ( cookie_name )
1496 {
1497   var cookie_date = new Date();  // current date & time
1498   cookie_date.setTime ( cookie_date.getTime() - 1 );
1499   document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
1500 }
1501
1502 function delete_session()
1503 {
1504         delete_cookie("session");
1505 }
1506
1507 function disable_toparea() {
1508         var offset = $('#toparea').offset();
1509         $('#whitemask').css('top',offset.top);
1510         $('#whitemask').css('left',offset.left);
1511         $('#whitemask').css('width',$('#toparea').outerWidth() + "px");
1512         $('#whitemask').css('height',$('#toparea').outerHeight() + "px");
1513         $('#whitemask').fadeTo('fast',0.7);
1514 }