]> matita.cs.unibo.it Git - helm.git/blob - matitaB/matita/matitaweb.js
Matitaweb: clicking buttons disables the GUI to prevent another operation from
[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 is_defined(x)
501 {
502         return (typeof x != "undefined");
503 }
504
505 /* servicename: name of the service being called
506  * reqbody: text of the request
507  * processResponse: processes the server response
508  *     (takes the response text in input, undefined in case of error)
509  */
510 function callServer(servicename,processResponse,reqbody)
511 {
512         var req = null; 
513         // pause();
514         if (window.XMLHttpRequest)
515         {
516                 req = new XMLHttpRequest();
517         } 
518         else if (window.ActiveXObject) 
519         {
520                 try {
521                                 req = new ActiveXObject("Msxml2.XMLHTTP");
522                 } catch (e)
523                 {
524                         try {
525                                 req = new ActiveXObject("Microsoft.XMLHTTP");
526                                 } catch (e) {}
527                 }
528         }
529         req.onreadystatechange = function()
530         { 
531
532                 rs = req.readyState;
533
534                 if(rs == 4)
535                 {
536                         stat = req.status;
537                         stxt = req.statusText;
538                         if(stat == 200)
539                         {
540                           debug(req.responseText);
541                           if (window.DOMParser) {
542                             parser=new DOMParser();
543                             xmlDoc=parser.parseFromString(req.responseText,"text/xml");
544                           }
545                           else // Internet Explorer
546                           {
547                             xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
548                             xmlDoc.async="false";
549                             xmlDoc.loadXML(req.responseText);
550                           }     
551                           processResponse(xmlDoc);
552                         } else {
553                           processResponse();
554                         }
555                 } 
556         };
557         req.open("POST", servicename); // + escape(unlocked.innerHTML), true);
558         req.setRequestHeader("Content-type","application/x-www-form-urlencoded");       
559         if (reqbody) {
560                 req.send(reqbody); 
561         } else {
562                 req.send();
563         }
564   
565 }
566
567 function advanceForm1()
568 {
569         processor = function(xml) {
570                 if (is_defined(xml)) {
571                         var parsed = xml.getElementsByTagName("parsed")[0];
572                         var ambiguity = xml.getElementsByTagName("ambiguity")[0];
573                         var disamberr = xml.getElementsByTagName("disamberror")[0];
574                         if (is_defined(parsed)) {
575                         // debug("advance: received response\nBEGIN\n" + req.responseText + "\nEND");
576                             var len = parseInt(parsed.getAttribute("length"));
577                             // len0 = unlocked.innerHTML.length;
578                             var unescaped = unlocked.innerHTML.html_to_matita();
579                             var parsedtxt = parsed.childNodes[0].wholeText;
580                             //parsedtxt = unescaped.substr(0,len); 
581                             var unparsedtxt = unescaped.substr(len);
582                             lockedbackup += parsedtxt;
583                             locked.innerHTML = lockedbackup;
584                             unlocked.innerHTML = unparsedtxt.matita_to_html();
585                             // len1 = unlocked.innerHTML.length;
586                             // len2 = len0 - len1;
587                             var len2 = parsedtxt.length;
588                             var metasenv = xml.getElementsByTagName("meta");
589                             populate_goalarray(metasenv);
590                             init_autotraces();
591                             statements = listcons(len2,statements);
592                             unlocked.scrollIntoView(true);
593                         }
594                         else if (is_defined(ambiguity)) {
595                             var start = parseInt(ambiguity.getAttribute("start"));
596                             var stop = parseInt(ambiguity.getAttribute("stop"));
597                             var choices = xml.getElementsByTagName("choice");
598
599                             matita.ambiguityStart = start;
600                             matita.ambiguityStop = stop;
601                             matita.unlockedbackup = unlocked.innerHTML.html_to_matita();
602                             matita.interpretations = [];
603                         
604                             var unlockedtxt = unlocked.innerHTML.html_to_matita();
605                             var pre = unlockedtxt.substring(0,start).matita_to_html();
606                             var mid = unlockedtxt.substring(start,stop).matita_to_html();
607                             var post = unlockedtxt.substring(stop).matita_to_html();
608                             unlocked.innerHTML = pre + 
609                                     "<span class=\"error\" title=\"disambiguation error\">" +
610                                     mid + "</span>" + post;
611
612                             var title = "<H3>Ambiguous input</H3>";
613                             disambcell.innerHTML = title;
614                             for (i = 0;i < choices.length;i++) {
615                                 matita.interpretations[i] = new Object();
616
617                                 var href = choices[i].getAttribute("href");
618                                 var title = choices[i].getAttribute("title");
619                                 var desc = choices[i].childNodes[0].nodeValue;
620
621                                 matita.interpretations[i].href = href;
622                                 matita.interpretations[i].title = title;
623                                 matita.interpretations[i].desc = desc;
624                                 
625                                 var choice = document.createElement("input");
626                                 choice.setAttribute("type","radio");
627                                 choice.setAttribute("name","interpr");
628                                 choice.setAttribute("href",href);
629                                 choice.setAttribute("title",title);
630                                 if (i == 0) choice.setAttribute("checked","");
631                                 
632                                 disambcell.appendChild(choice);
633                                 disambcell.appendChild(document.createTextNode(desc));
634                                 disambcell.appendChild(document.createElement("br"));
635                             }
636
637                             var okbutton = document.createElement("input");
638                             okbutton.setAttribute("type","button");
639                             okbutton.setAttribute("value","OK");
640                             okbutton.setAttribute("onclick","do_disambiguate()");
641                             var cancelbutton = document.createElement("input");
642                             cancelbutton.setAttribute("type","button");
643                             cancelbutton.setAttribute("value","Cancel");
644                             cancelbutton.setAttribute("onclick","cancel_disambiguate()");
645
646                             disambcell.appendChild(okbutton);
647                             disambcell.appendChild(cancelbutton);
648
649                             disable_toparea();
650
651                             matita.disambMode = true;
652                             updateSide();
653                         }
654                         else if (is_defined(disamberr)) {
655                             set_cps(disamberr.childNodes);
656                             matita.unlockedbackup = unlocked.innerHTML.html_to_matita();
657                             matita.disambMode = true;
658                             disable_toparea();
659                             next_cp(0);
660                         }
661                         else {
662                             var error = xml.getElementsByTagName("error")[0]; 
663                             unlocked.innerHTML = error.childNodes[0].wholeText;
664                             // debug(xml.childNodes[0].nodeValue);
665                         }
666                 } else {
667                         debug("advance failed");
668                 }
669                 resume();
670         };
671         pause();
672         callServer("advance",processor,"body=" + (unlocked.innerHTML.html_to_matita()).sescape());
673   
674 }
675
676 // get or set <choicepoint>'s (in case of disamb error)
677 function get_cps() {
678         return matita.choicepoints
679 }
680
681 function set_cps(cps) {
682         matita.choicepoints = cps;
683 }
684
685 // get radio buttons for <choice>'s in a given cp
686 function get_choice_opts(i) {
687    var res = [];
688    var choices = get_cps()[i].childNodes;
689    for (var j = 0;j < choices.length;j++) {
690       var href = choices[j].getAttribute("href");
691       var title = choices[j].getAttribute("title");
692       var desc;
693       if (is_defined(title)) {
694            desc = title;
695       } else if (is_defined(href)) {
696            desc = href;
697       } else {
698            desc = "Preliminary error";
699       }
700   
701       res[j] = document.createElement("input");
702       res[j].setAttribute("type","radio");
703       res[j].setAttribute("name","choice");
704       res[j].setAttribute("choicepointno",i);
705       res[j].setAttribute("choiceno",j);
706       res[j].setAttribute("href",href);
707       res[j].setAttribute("title",title);
708       res[j].setAttribute("desc",desc);
709       
710       if (j == 0) res[j].setAttribute("checked","");
711   }
712   return res;
713 }
714
715 // get radio buttons for <failure>'s in a given choice
716 function get_failure_opts(i,j) {
717    var res = [];
718    var failures = get_cps()[i].childNodes[j].childNodes;
719    for (var k = 0;k < failures.length;k++) {
720       var start = failures[k].getAttribute("start");
721       var stop = failures[k].getAttribute("stop");
722       var title = failures[k].getAttribute("title");
723   
724       res[k] = document.createElement("input");
725       res[k].setAttribute("type","radio");
726       res[k].setAttribute("name","failure");
727       res[k].setAttribute("choicepointno",i);
728       res[k].setAttribute("choiceno",j);
729       res[k].setAttribute("failureno",k);
730       res[k].setAttribute("start",start);
731       res[k].setAttribute("stop",stop);
732       res[k].setAttribute("title",title);
733       
734       if (k == 0) res[k].setAttribute("checked","");
735   }
736   return res;
737 }
738
739 function next_cp(curcp) {
740         var cp = get_cps()[curcp];
741         var start = parseInt(cp.getAttribute("start"));
742         var stop = parseInt(cp.getAttribute("stop"));
743
744         matita.errorStart = start;
745         matita.errorStop = stop;
746         // matita.unlockedbackup = unlocked.innerHTML.html_to_matita();
747         
748         var unlockedtxt = matita.unlockedbackup;
749         var pre = unlockedtxt.substring(0,start).matita_to_html();
750         var mid = unlockedtxt.substring(start,stop).matita_to_html();
751         var post = unlockedtxt.substring(stop).matita_to_html();
752         unlocked.innerHTML = pre + 
753                 "<span class=\"error\" title=\"disambiguation failed\">" +
754                 mid + "</span>" + post;
755
756         var title = "<H3>Disambiguation failed</H3>";
757         disambcell.innerHTML = title;
758         var choices = get_choice_opts(curcp);
759         for (var i = 0;i < choices.length;i++) {
760             disambcell.appendChild(choices[i]);
761             disambcell.appendChild(document.createTextNode(choices[i].getAttribute("desc")));
762             disambcell.appendChild(document.createElement("br"));
763         }
764         
765         // update index of the next choicepoint
766         new_curcp = (curcp + 1) % get_cps().length;
767
768         var okbutton = document.createElement("input");
769         okbutton.setAttribute("type","button");
770         okbutton.setAttribute("value","OK");
771         okbutton.setAttribute("onclick","show_failures()");
772         var cancelbutton = document.createElement("input");
773         cancelbutton.setAttribute("type","button");
774         cancelbutton.setAttribute("value","Close");
775         cancelbutton.setAttribute("onclick","cancel_disambiguate()");
776         var tryagainbutton = document.createElement("input");
777         tryagainbutton.setAttribute("type","button");
778         if (new_curcp > 0) {
779             tryagainbutton.setAttribute("value","Try something else");
780         } else {
781             tryagainbutton.setAttribute("value","Restart");
782         }
783         tryagainbutton.setAttribute("onclick","next_cp(" + new_curcp + ")");
784
785         disambcell.appendChild(okbutton);
786         disambcell.appendChild(tryagainbutton);
787         disambcell.appendChild(cancelbutton);
788
789         //disable_toparea();
790
791         //matita.disambMode = true;
792         updateSide();
793         
794 }
795
796 function show_failures() {
797
798         var choice = document.getElementsByName("choice")[get_checked_index("choice")];
799         var cpno = parseInt(choice.getAttribute("choicepointno"));
800         var choiceno = parseInt(choice.getAttribute("choiceno"));
801         var choicedesc = choice.getAttribute("desc");
802
803         var title = "<H3>Disambiguation failed</H3>";
804         var subtitle = "<p>Errors at node " + cpno + " = " + choicedesc + "</p>";
805
806         disambcell.innerHTML = title + subtitle;
807         var failures = get_failure_opts(cpno,choiceno);
808         for (var i = 0;i < failures.length;i++) {
809             disambcell.appendChild(failures[i]);
810             disambcell.appendChild(document.createTextNode(failures[i].getAttribute("title")));
811             disambcell.appendChild(document.createElement("br"));
812         }
813         
814         var okbutton = document.createElement("input");
815         okbutton.setAttribute("type","button");
816         okbutton.setAttribute("value","Show error loc");
817         okbutton.setAttribute("onclick","show_err()");
818         var cancelbutton = document.createElement("input");
819         cancelbutton.setAttribute("type","button");
820         cancelbutton.setAttribute("value","Close");
821         cancelbutton.setAttribute("onclick","cancel_disambiguate()");
822         var backbutton = document.createElement("input");
823         backbutton.setAttribute("type","button");
824         backbutton.setAttribute("value","<< Back");
825         backbutton.setAttribute("onclick","next_cp(" + cpno + ")");
826
827         disambcell.appendChild(backbutton);
828         disambcell.appendChild(okbutton);
829         disambcell.appendChild(cancelbutton);
830         
831 }
832
833 function show_err() {
834         var radios = document.getElementsByName("failure");
835         for (i = 0; i < radios.length; i++) {
836             if (radios[i].checked) {
837                 var start = radios[i].getAttribute("start");
838                 var stop = radios[i].getAttribute("stop");
839                 var title = radios[i].getAttribute("title");
840                 var unlockedtxt = matita.unlockedbackup;
841                 var pre = unlockedtxt.substring(0,start).matita_to_html();
842                 var mid = unlockedtxt.substring(start,stop).matita_to_html();
843                 var post = unlockedtxt.substring(stop).matita_to_html();
844                 unlocked.innerHTML = pre + 
845                         "<span class=\"error\" title=\"Disambiguation failure\">" +
846                         mid + "</span>" + post;
847                 break;
848             }
849         }
850 }
851
852 function gotoBottom()
853 {
854         processor = function(xml) {
855                 if (is_defined(xml)) {
856                         // debug("goto bottom: received response\nBEGIN\n" + req.responseText + "\nEND");
857                         var parsed = xml.getElementsByTagName("parsed");
858                         var localized = xml.getElementsByTagName("localized")[0];
859                         var ambiguity = xml.getElementsByTagName("ambiguity")[0];
860                         var generic_err = xml.getElementsByTagName("error")[0];
861                         for (var i = 0;i < parsed.length; i++) {
862                           var len = parsed[i].getAttribute("length");
863                           // len0 = unlocked.innerHTML.length;
864                           var unescaped = unlocked.innerHTML.html_to_matita();
865                           // the browser may decide to split textnodes: use wholeText!
866                           var parsedtxt = parsed[i].childNodes[0].wholeText;
867                           //parsedtxt = unescaped.substr(0,len); 
868                           var unparsedtxt = unescaped.substr(len);
869                           lockedbackup += parsedtxt;
870                           locked.innerHTML = lockedbackup; //.matita_to_html();
871                           unlocked.innerHTML = unparsedtxt.matita_to_html();
872                           // len1 = unlocked.innerHTML.length;
873                           var len2 = parsedtxt.length;
874                           statements = listcons(len2,statements);
875                         }
876                         unlocked.scrollIntoView(true);
877                         metasenv = xml.getElementsByTagName("meta");
878                         init_autotraces();
879                         populate_goalarray(metasenv);
880
881                         if (is_defined(ambiguity)) {
882                             var start = parseInt(ambiguity.getAttribute("start"));
883                             var stop = parseInt(ambiguity.getAttribute("stop"));
884                             var choices = xml.getElementsByTagName("choice");
885
886                             matita.ambiguityStart = start;
887                             matita.ambiguityStop = stop;
888                             matita.unlockedbackup = unlocked.innerHTML.html_to_matita();
889                             matita.interpretations = [];
890                         
891                             var unlockedtxt = unlocked.innerHTML.html_to_matita();
892                             var pre = unlockedtxt.substring(0,start).matita_to_html();
893                             var mid = unlockedtxt.substring(start,stop).matita_to_html();
894                             var post = unlockedtxt.substring(stop).matita_to_html();
895                             unlocked.innerHTML = pre + 
896                                     "<span class=\"error\" title=\"disambiguation error\">" +
897                                     mid + "</span>" + post;
898
899                             var title = "<H3>Ambiguous input</H3>";
900                             disambcell.innerHTML = title;
901                             for (i = 0;i < choices.length;i++) {
902                                 matita.interpretations[i] = new Object();
903
904                                 var href = choices[i].getAttribute("href");
905                                 var title = choices[i].getAttribute("title");
906                                 var desc = choices[i].childNodes[0].nodeValue;
907
908                                 matita.interpretations[i].href = href;
909                                 matita.interpretations[i].title = title;
910                                 matita.interpretations[i].desc = desc;
911                                 
912                                 var choice = document.createElement("input");
913                                 choice.setAttribute("type","radio");
914                                 choice.setAttribute("name","interpr");
915                                 choice.setAttribute("href",href);
916                                 choice.setAttribute("title",title);
917                                 if (i == 0) choice.setAttribute("checked","");
918                                 
919                                 disambcell.appendChild(choice);
920                                 disambcell.appendChild(document.createTextNode(desc));
921                                 disambcell.appendChild(document.createElement("br"));
922                             }
923
924                             var okbutton = document.createElement("input");
925                             okbutton.setAttribute("type","button");
926                             okbutton.setAttribute("value","OK");
927                             okbutton.setAttribute("onclick","do_disambiguate()");
928                             var cancelbutton = document.createElement("input");
929                             cancelbutton.setAttribute("type","button");
930                             cancelbutton.setAttribute("value","Cancel");
931                             cancelbutton.setAttribute("onclick","cancel_disambiguate()");
932
933                             disambcell.appendChild(okbutton);
934                             disambcell.appendChild(cancelbutton);
935
936                             disable_toparea();
937
938                             matita.disambMode = true;
939                             updateSide();
940                         }
941                         if (is_defined(localized)) {
942                             unlocked.innerHTML = localized.wholeText;
943                         }
944                         if (is_defined(generic_err)) {
945                             debug("Unmanaged error:\n" ^ generic_err.wholeText);
946                         }
947                 } else {
948                         debug("goto bottom failed");
949                 } 
950                 resume();
951         };
952         pause();
953         callServer("bottom",processor,"body=" + (unlocked.innerHTML.html_to_matita()).sescape());
954 }
955
956
957 function gotoTop()
958 {
959         processor = function(xml) {
960                 if (is_defined(xml)) {
961                   if (xml.childNodes[0].textContent != "ok") {
962                      debug("goto top failed");
963                   }
964                   else
965                         statements = listnil();
966                         /*
967                         lockedlen = locked.innerHTML.length - statementlen;
968                         statement = locked.innerHTML.substr(lockedlen, statementlen);
969                         locked.innerHTML = locked.innerHTML.substr(0,lockedlen);
970                         unlocked.innerHTML = statement + unlocked.innerHTML;
971                         */
972                         unlocked.innerHTML = lockedbackup + unlocked.innerHTML;
973                         lockedbackup = "";
974                         locked.innerHTML = lockedbackup;
975                         init_autotraces();
976                         hideSequent();
977                         unlocked.scrollIntoView(true);
978                 } else {
979                         debug("goto top failed");
980                 } 
981                 resume();
982         };
983         pause();
984         callServer("top",processor,"body=" + (unlocked.innerHTML.html_to_matita()).sescape());
985   
986 }
987 function gotoPos(offset)
988 {
989         if (!is_defined(offset)) {
990                 offset = getCursorPos();
991         }
992         processor = function(xml) {
993                 if (is_defined(xml)) {
994                         parsed = xml.getElementsByTagName("parsed")[0];
995                         len = parseInt(parsed.getAttribute("length"));
996                         // len0 = unlocked.innerHTML.length;
997                         unescaped = unlocked.innerHTML.html_to_matita();
998                         parsedtxt = parsed.childNodes[0].wholeText;
999                         //parsedtxt = unescaped.substr(0,len); 
1000                         unparsedtxt = unescaped.substr(len);
1001                         lockedbackup += parsedtxt;
1002                         locked.innerHTML = lockedbackup; //.matita_to_html();
1003                         unlocked.innerHTML = unparsedtxt.matita_to_html();
1004                         // len1 = unlocked.innerHTML.length;
1005                         len2 = parsedtxt.length;
1006                         metasenv = xml.getElementsByTagName("meta");
1007                         // populate_goalarray(metasenv);
1008                         statements = listcons(len2,statements);
1009                         unlocked.scrollIntoView(true);
1010                         // la populate non andrebbe fatta a ogni passo
1011                         if (offset <= len) {
1012                                 init_autotraces();
1013                                 populate_goalarray(metasenv);
1014                                 resume();
1015                         } else {
1016                                 gotoPos(offset - len);
1017                         }
1018                 } else {
1019                         init_autotraces();
1020                         unlocked.scrollIntoView(true);
1021                         populate_goalarray(metasenv);
1022                         resume();
1023                 }
1024         }
1025         pause();
1026         callServer("advance",processor,"body=" + (unlocked.innerHTML.html_to_matita()).sescape());
1027 }
1028
1029 function retract()
1030 {
1031         processor = function(xml) {
1032                 if (typeof xml != "undefined") {
1033                         // debug("advance: received response\nBEGIN\n" + req.responseText + "\nEND");
1034                         statementlen = parseInt(listhd(statements));
1035                         statements = listtl(statements);
1036                         /*
1037                         lockedlen = locked.innerHTML.length - statementlen;
1038                         statement = locked.innerHTML.substr(lockedlen, statementlen);
1039                         locked.innerHTML = locked.innerHTML.substr(0,lockedlen);
1040                         unlocked.innerHTML = statement + unlocked.innerHTML;
1041                         */
1042                         lockedlen = lockedbackup.length - statementlen;
1043                         statement = lockedbackup.substr(lockedlen, statementlen);
1044                         lockedbackup = lockedbackup.substr(0,lockedlen);
1045                         locked.innerHTML = lockedbackup;
1046                         unlocked.innerHTML = statement + unlocked.innerHTML;
1047                         metasenv = xml.getElementsByTagName("meta");
1048                         init_autotraces();
1049                         populate_goalarray(metasenv);
1050                         unlocked.scrollIntoView(true);
1051                 } else {
1052                         debug("retract failed");
1053                 }
1054                 resume();
1055         };
1056         debug("retract 1");
1057         pause();
1058         callServer("retract",processor);
1059         debug("retract 2");
1060 }
1061
1062 function openFile()
1063
1064         processor = function(xml)
1065         {
1066                 if (is_defined(xml)) {  
1067                         lockedbackup = "";
1068                         locked.innerHTML = lockedbackup;
1069                         unlocked.innerHTML = xml.documentElement.wholeText;
1070                 } else {
1071                         debug("file open failed");
1072                 }
1073         };
1074         callServer("open",processor,"file=" + escape(filename.value)); 
1075 }
1076
1077 function retrieveFile(thefile)
1078
1079         processor = function(xml)
1080         {
1081                 if (is_defined(xml)) {  
1082                         changeFile(thefile);
1083                         lockedbackup = ""
1084                         locked.innerHTML = lockedbackup;
1085                         // code originally used in google chrome (problems with mozilla)
1086                         // debug(xml.getElementsByTagName("file")[0].childNodes[0].nodeValue);
1087                         // unlocked.innerHTML = xml.getElementsByTagName("file")[0].childNodes[0].nodeValue;
1088                         debug(xml.childNodes[0].textContent);
1089                         if (document.all) { // IE
1090                           unlocked.innerHTML = xml.childNodes[0].text;
1091                         } else {
1092                           unlocked.innerHTML = xml.childNodes[0].textContent;
1093                         }
1094                         init_autotraces();
1095
1096                 } else {
1097                         debug("file open failed");
1098                 }
1099         };
1100         abortDialog();
1101         callServer("open",processor,"file=" + escape(thefile)); 
1102 }
1103
1104 function showLibrary(title,callback,reloadDialog)
1105
1106         var req = null;
1107         dialogBox.reload = reloadDialog; 
1108         // pause();
1109         if (window.XMLHttpRequest)
1110         {
1111                 req = new XMLHttpRequest();
1112         } 
1113         else if (window.ActiveXObject) 
1114         {
1115                 try {
1116                                 req = new ActiveXObject("Msxml2.XMLHTTP");
1117                 } catch (e)
1118                 {
1119                         try {
1120                                 req = new ActiveXObject("Microsoft.XMLHTTP");
1121                                 } catch (e) {}
1122                 }
1123         }
1124         req.onreadystatechange = function()
1125         { 
1126
1127                 rs = req.readyState;
1128
1129                 if(rs == 4)
1130                 {
1131                         stat = req.status;
1132                         stxt = req.statusText;
1133                         if(stat == 200)
1134                         {
1135                           debug(req.responseText);
1136                           showDialog("<H2>" + title + "</H2>",req.responseText, callback);
1137                         } 
1138                 } 
1139         };
1140         req.open("POST", "viewlib"); // + escape(unlocked.innerHTML), true);
1141         req.setRequestHeader("Content-type","application/x-www-form-urlencoded");       
1142         req.send();
1143   
1144 }
1145
1146 function uploadDialog()
1147 {  
1148         uploadBox.style.display = "block";
1149 }
1150
1151 function uploadOK()
1152 {   
1153    var file = document.getElementById("uploadFilename").files[0];
1154    if (file) { 
1155        var filecontent = file.getAsText("UTF-8");
1156        locked.innerHTML = lockedbackup;
1157        unlocked.innerHTML = filecontent;
1158        uploadBox.style.display = "none";
1159    }
1160 //   if (file) { 
1161 //      var reader = new FileReader();
1162 //      reader.readAsText(file, "UTF-8");
1163 //       reader.onloadend = function (evt) {
1164 //         lockedbackup = "";
1165 //           locked.innerHTML = lockedbackup
1166 //           unlocked.innerHTML = evt.target.result;
1167 //           uploadBox.style.display = "none";
1168 //       }
1169 //       reader.onerror = function (evt) {
1170 //         debug("file open failed");
1171 //           uploadBox.style.display = "none";
1172 //      }
1173 //   }
1174 }
1175
1176 function openDialog()
1177 {  
1178         callback = function (fname) { retrieveFile(fname); };
1179         showLibrary("Open file", callback, openDialog);
1180 }
1181
1182 function saveDialog()
1183 {  
1184         callback = function (fname) { 
1185           abortDialog();
1186           saveFile(fname,
1187                    (locked.innerHTML.html_to_matita()).sescape(),
1188                    (unlocked.innerHTML.html_to_matita()).sescape(),
1189                    false,saveDialog); 
1190         };
1191         showLibrary("Save file as", callback, saveDialog);
1192 }
1193
1194 function newDialog()
1195 {
1196         callback = function (fname) { 
1197           abortDialog();
1198           saveFile(fname,"","",false,newDialog,true);
1199         };
1200         showLibrary("Create new file", callback, newDialog);
1201 }
1202
1203
1204 function saveFile(fname,lockedtxt,unlockedtxt,force,reloadDialog,reloadFile)
1205 {
1206         if (!is_defined(reloadFile)) { reloadFile = true };
1207         if (!is_defined(fname)) {
1208             fname = current_fname;
1209             lockedtxt = (locked.innerHTML.html_to_matita()).sescape();
1210             unlockedtxt = (unlocked.innerHTML.html_to_matita()).sescape();
1211             force = true;
1212             // when force is true, reloadDialog is not needed 
1213         }
1214         processor = function(xml) {
1215                 if (is_defined(xml)) {
1216                   if (xml.childNodes[0].textContent != "ok") {
1217                     if (confirm("File already exists. All existing data will be lost.\nDo you want to proceed anyway?")) {
1218                        saveFile(fname,lockedtxt,unlockedtxt,true,reloadDialog,reloadFile);
1219                     } else {
1220                       reloadDialog();
1221                     }
1222                   } else {
1223                     changeFile(fname);
1224                     debug("file saved!");
1225                     if (reloadFile) { retrieveFile(fname); }
1226                   }
1227                 } else {
1228                         debug("save file failed");
1229                 }
1230                 resume();
1231         };
1232         if (is_defined(fname)) {
1233           pause();
1234           callServer("save",processor,"file=" + escape(fname) + 
1235                                     "&locked=" + lockedtxt +
1236                                     "&unlocked=" + unlockedtxt +
1237                                     "&force=" + force);
1238         }
1239         else { debug("no file selected"); }
1240 }
1241
1242 function createDir() {
1243    abortDialog();
1244    dirname = prompt("New directory name:\ncic:/matita/","newdir");
1245    if (dirname != null) {
1246         processor = function(xml) {
1247                 if (is_defined(xml)) {
1248                   if (xml.childNodes[0].textContent != "ok") {
1249                       alert("An error occurred :-(");
1250                   }
1251                 } else {
1252                       alert("An error occurred :-(");
1253                 }
1254                 dialogBox.reload();
1255         };
1256         pause();
1257         callServer("save",processor,"file=" + escape(dirname) + 
1258                                     "&locked=&unlocked=&force=false&dir=true");
1259    } else {
1260       dialogBox.reload();
1261    }
1262 }
1263
1264 function commitAll()
1265 {
1266         processor = function(xml) {
1267                 if (is_defined(xml)) {
1268                         debug(xml.getElementsByTagName("details")[0].textContent);
1269                         alert("Commit executed: see details in the log.\n\n" +
1270                               "NOTICE: this message does NOT imply (yet) that the commit was successful.");
1271                 } else {
1272                         alert("Commit failed!");
1273                 }
1274                 resume();
1275         };
1276         pause();
1277         callServer("commit",processor);
1278 }
1279
1280 function updateAll()
1281 {
1282         processor = function(xml) {
1283                 if (is_defined(xml)) {
1284                         alert("Update executed.\n\n" +
1285                               "Details:\n" +
1286                               xml.getElementsByTagName("details")[0].textContent);
1287                 } else {
1288                         alert("Update failed!");
1289                 }
1290                 resume();
1291         };
1292         pause();
1293         callServer("update",processor);
1294 }
1295
1296 var goalcell;
1297
1298 function hideSequent() {
1299         matita.proofMode = false;
1300         updateSide();
1301 }
1302
1303 function showSequent() {
1304         matita.proofMode = true;
1305         updateSide();
1306 }
1307
1308 function showDialog(title,content,callback) {
1309   dialogTitle.innerHTML = title;
1310   dialogContent.innerHTML = content;
1311   dialogBox.callback = callback;
1312
1313   //Get the screen height and width
1314   var maskHeight = $(document).height();
1315   var maskWidth = $(window).width();
1316   
1317   //Set heigth and width to mask to fill up the whole screen
1318   $('#mask').css({'width':maskWidth,'height':maskHeight});
1319   
1320   //transition effect           
1321   $('#mask').fadeIn(100);       
1322   $('#mask').fadeTo(200,0.8);   
1323   
1324   //Get the window height and width
1325   var winH = $(window).height();
1326   var winW = $(window).width();
1327   
1328   //Set the popup window to center
1329   $('#dialogBox').css('top',  winH/2-$('#dialogBox').height()/2);
1330   $('#dialogBox').css('left', winW/2-$('#dialogBox').width()/2);
1331   
1332   //transition effect
1333   $('#dialogBox').fadeIn(200); 
1334
1335   dialogBox.style.display = "block";
1336 }
1337
1338 function abortDialog(dialog) {
1339   $('#mask').hide();
1340   dialogBox.style.display = "none";
1341 }
1342
1343 function removeElement(id) {
1344   var element = document.getElementById(id);
1345   element.parentNode.removeChild(element);
1346
1347
1348 var savedsc;
1349 var savedso;
1350
1351 function getCursorPos() {
1352   var cursorPos;
1353   if (window.getSelection) {
1354     var selObj = window.getSelection();
1355     savedRange = selObj.getRangeAt(0);
1356     savedsc = savedRange.startContainer;
1357     savedso = savedRange.startOffset;
1358     //cursorPos =  findNode(selObj.anchorNode.parentNode.childNodes, selObj.anchorNode) + selObj.anchorOffset;
1359     cursorPos =  findNode(unlocked.childNodes, selObj.anchorNode,0) + selObj.anchorOffset;
1360     /* FIXME the following works wrong in Opera when the document is longer than 32767 chars */
1361     return(cursorPos);
1362   }
1363   else if (document.selection) {
1364     savedRange = document.selection.createRange();
1365     var bookmark = savedRange.getBookmark();
1366     /* FIXME the following works wrong when the document is longer than 65535 chars */
1367     cursorPos = bookmark.charCodeAt(2) - 11; /* Undocumented function [3] */
1368     return(cursorPos);
1369   }
1370 }
1371
1372 function findNode(list, node, acc) {
1373   for (var i = 0; i < list.length; i++) {
1374     if (list[i] == node) {
1375    //   debug("success " + i);
1376       return acc;
1377     }
1378     if (list[i].hasChildNodes()) {
1379        try {
1380    //      debug("recursion on node " + i);
1381          return (findNode(list[i].childNodes,node,acc))
1382        }
1383        catch (e) { /* debug("recursion failed"); */ }
1384     }
1385     sandbox = document.getElementById("sandbox");
1386     dup = list[i].cloneNode(true);
1387     sandbox.appendChild(dup);
1388 //    debug("fail " + i + ": " + sandbox.innerHTML);
1389     acc += sandbox.innerHTML.html_to_matita().length;
1390     sandbox.removeChild(dup);
1391   }
1392   throw "not found";
1393 }
1394
1395 function test () {
1396   debug("cursor test: " + unlocked.innerHTML.substr(0,getCursorPos()));
1397 }
1398
1399 function get_checked_index(name) {
1400         var radios = document.getElementsByName(name);
1401         for (i = 0; i < radios.length; i++) {
1402             if (radios[i].checked) {
1403                     return i;
1404             }
1405         }
1406         return null;
1407 }
1408
1409 function cancel_disambiguate() {
1410         matita.disambMode = false;
1411         enable_toparea();
1412         enable_editing();
1413         updateSide();
1414 }
1415
1416 function do_disambiguate() {
1417         var i = get_checked_index("interpr");
1418         if (i != null) {
1419             var pre = matita.unlockedbackup
1420                       .substring(0,matita.ambiguityStart).matita_to_html();
1421             var mid = matita.unlockedbackup
1422                       .substring(matita.ambiguityStart,matita.ambiguityStop)
1423                       .matita_to_html();
1424             var post = matita.unlockedbackup
1425                        .substring(matita.ambiguityStop).matita_to_html();
1426
1427             var href = matita.interpretations[i].href;
1428             var title = matita.interpretations[i].title;
1429
1430             if (is_defined(title)) {
1431                 mid = "<A href=\"" + href + "\" title=\"" + title + "\">" + mid + "</A>";
1432             } else {
1433                 mid = "<A href=\"" + href + "\">" + mid + "</A>";
1434             }
1435
1436             unlocked.innerHTML = pre + mid + post;
1437
1438             matita.disambMode = false;
1439             enable_toparea();
1440             enable_editing();
1441             updateSide();
1442         }
1443 }
1444
1445 function do_showerror() {
1446         var i = get_checked_index("choice");
1447         if (i != null) {
1448             var pre = matita.unlockedbackup
1449                       .substring(0,matita.ambiguityStart).matita_to_html();
1450             var mid = matita.unlockedbackup
1451                       .substring(matita.ambiguityStart,matita.ambiguityStop)
1452                       .matita_to_html();
1453             var post = matita.unlockedbackup
1454                        .substring(matita.ambiguityStop).matita_to_html();
1455
1456             var href = matita.interpretations[i].href;
1457             var title = matita.interpretations[i].title;
1458
1459             if (is_defined(title)) {
1460                 mid = "<A href=\"" + href + "\" title=\"" + title + "\">" + mid + "</A>";
1461             } else {
1462                 mid = "<A href=\"" + href + "\">" + mid + "</A>";
1463             }
1464
1465             unlocked.innerHTML = pre + mid + post;
1466
1467         }
1468 }
1469
1470 function readCookie(name) {
1471         var nameEQ = name + "=";
1472         var ca = document.cookie.split(';');
1473         for(var i=0;i < ca.length;i++) {
1474                 var c = ca[i];
1475                 while (c.charAt(0)==' ') c = c.substring(1,c.length);
1476                 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
1477         }
1478         return null;
1479 }
1480
1481 function delete_cookie ( cookie_name )
1482 {
1483   var cookie_date = new Date();  // current date & time
1484   cookie_date.setTime ( cookie_date.getTime() - 1 );
1485   document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
1486 }
1487
1488 function delete_session()
1489 {
1490         delete_cookie("session");
1491 }
1492
1493 function disable_toparea() {
1494         var offset = $('#toparea').offset();
1495         $('#whitemask').css('top',offset.top);
1496         $('#whitemask').css('left',offset.left);
1497         $('#whitemask').css('width',$('#toparea').outerWidth() + "px");
1498         $('#whitemask').css('height',$('#toparea').outerHeight() + "px");
1499         $('#whitemask').fadeTo('fast',0.7);
1500 }
1501
1502 function enable_toparea() {
1503         $('#whitemask').hide();
1504 }
1505
1506 function disable_editing() {
1507         unlocked.contentEditable = false;
1508 }
1509
1510 function enable_editing() {
1511         unlocked.contentEditable = true;
1512 }
1513
1514 function pause()
1515 {
1516         // advanceButton.disabled = true;
1517         // retractButton.disabled = true;
1518         // cursorButton.disabled = true;
1519         // bottomButton.disabled = true;
1520         disable_toparea();
1521         disable_editing();
1522 }
1523
1524 function resume()
1525 {
1526         // advanceButton.disabled = false;
1527         // retractButton.disabled = false;
1528         // cursorButton.disabled = false;
1529         // bottomButton.disabled = false;
1530         enable_toparea();
1531         enable_editing();
1532 }
1533