xref: /dokuwiki/lib/scripts/script.js (revision 6ae7cff52259b73ed8da9ad51e61240c8125d305)
1/**
2 * Some of these scripts were taken from wikipedia.org and were modified for DokuWiki
3 */
4
5/**
6 * Some browser detection
7 */
8var clientPC  = navigator.userAgent.toLowerCase(); // Get client info
9var is_macos  = navigator.appVersion.indexOf('Mac') != -1;
10var is_gecko  = ((clientPC.indexOf('gecko')!=-1) && (clientPC.indexOf('spoofer')==-1) &&
11                (clientPC.indexOf('khtml') == -1) && (clientPC.indexOf('netscape/7.0')==-1));
12var is_safari = ((clientPC.indexOf('AppleWebKit')!=-1) && (clientPC.indexOf('spoofer')==-1));
13var is_khtml  = (navigator.vendor == 'KDE' || ( document.childNodes && !document.all && !navigator.taintEnabled ));
14if (clientPC.indexOf('opera')!=-1) {
15    var is_opera = true;
16    var is_opera_preseven = (window.opera && !document.childNodes);
17    var is_opera_seven = (window.opera && document.childNodes);
18}
19
20/**
21 * Handy shortcut to document.getElementById
22 *
23 * This function was taken from the prototype library
24 *
25 * @link http://prototype.conio.net/
26 */
27function $() {
28  var elements = new Array();
29
30  for (var i = 0; i < arguments.length; i++) {
31    var element = arguments[i];
32    if (typeof element == 'string')
33      element = document.getElementById(element);
34
35    if (arguments.length == 1)
36      return element;
37
38    elements.push(element);
39  }
40
41  return elements;
42}
43
44/**
45 * Simple function to check if a global var is defined
46 *
47 * @author Kae Verens
48 * @link http://verens.com/archives/2005/07/25/isset-for-javascript/#comment-2835
49 */
50function isset(varname){
51  return(typeof(window[varname])!='undefined');
52}
53
54/**
55 * Select elements by their class name
56 *
57 * @author Dustin Diaz <dustin [at] dustindiaz [dot] com>
58 * @link   http://www.dustindiaz.com/getelementsbyclass/
59 */
60function getElementsByClass(searchClass,node,tag) {
61    var classElements = new Array();
62    if ( node == null )
63        node = document;
64    if ( tag == null )
65        tag = '*';
66    var els = node.getElementsByTagName(tag);
67    var elsLen = els.length;
68    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
69    for (var i = 0, j = 0; i < elsLen; i++) {
70        if ( pattern.test(els[i].className) ) {
71            classElements[j] = els[i];
72            j++;
73        }
74    }
75    return classElements;
76}
77
78/**
79 * Get the X offset of the top left corner of the given object
80 *
81 * @link http://www.quirksmode.org/index.html?/js/findpos.html
82 */
83function findPosX(object){
84  var curleft = 0;
85  var obj = $(object);
86  if (obj.offsetParent){
87    while (obj.offsetParent){
88      curleft += obj.offsetLeft;
89      obj = obj.offsetParent;
90    }
91  }
92  else if (obj.x){
93    curleft += obj.x;
94  }
95  return curleft;
96} //end findPosX function
97
98/**
99 * Get the Y offset of the top left corner of the given object
100 *
101 * @link http://www.quirksmode.org/index.html?/js/findpos.html
102 */
103function findPosY(object){
104  var curtop = 0;
105  var obj = $(object);
106  if (obj.offsetParent){
107    while (obj.offsetParent){
108      curtop += obj.offsetTop;
109      obj = obj.offsetParent;
110    }
111  }
112  else if (obj.y){
113    curtop += obj.y;
114  }
115  return curtop;
116} //end findPosY function
117
118/**
119 * Escape special chars in JavaScript
120 *
121 * @author Andreas Gohr <andi@splitbrain.org>
122 */
123function jsEscape(text){
124    var re=new RegExp("\\\\","g");
125    text=text.replace(re,"\\\\");
126    re=new RegExp("'","g");
127    text=text.replace(re,"\\'");
128    re=new RegExp('"',"g");
129    text=text.replace(re,'&quot;');
130    re=new RegExp("\\\\\\\\n","g");
131    text=text.replace(re,"\\n");
132    return text;
133}
134
135/**
136 * This function escapes some special chars
137 * @deprecated by above function
138 */
139function escapeQuotes(text) {
140  var re=new RegExp("'","g");
141  text=text.replace(re,"\\'");
142  re=new RegExp('"',"g");
143  text=text.replace(re,'&quot;');
144  re=new RegExp("\\n","g");
145  text=text.replace(re,"\\n");
146  return text;
147}
148
149/**
150 * Adds a node as the first childenode to the given parent
151 *
152 * @see appendChild()
153 */
154function prependChild(parent,element) {
155    if(!parent.firstChild){
156        parent.appendChild(element);
157    }else{
158        parent.insertBefore(element,parent.firstChild);
159    }
160}
161
162/**
163 * Prints a animated gif to show the search is performed
164 *
165 * Because we need to modify the DOM here before the document is loaded
166 * and parsed completely we have to rely on document.write()
167 *
168 * @author Andreas Gohr <andi@splitbrain.org>
169 */
170function showLoadBar(){
171
172  document.write('<img src="'+DOKU_BASE+'lib/images/loading.gif" '+
173                 'width="150" height="12" alt="..." />');
174
175  /* this does not work reliable in IE
176  obj = $(id);
177
178  if(obj){
179    obj.innerHTML = '<img src="'+DOKU_BASE+'lib/images/loading.gif" '+
180                    'width="150" height="12" alt="..." />';
181    obj.style.display="block";
182  }
183  */
184}
185
186/**
187 * Disables the animated gif to show the search is done
188 *
189 * @author Andreas Gohr <andi@splitbrain.org>
190 */
191function hideLoadBar(id){
192  obj = $(id);
193  if(obj) obj.style.display="none";
194}
195
196/**
197 * Adds the toggle switch to the TOC
198 */
199function addTocToggle() {
200    if(!document.getElementById) return;
201    var header = $('toc__header');
202    if(!header) return;
203    var toc = $('toc__inside');
204
205    var obj          = document.createElement('span');
206    obj.id           = 'toc__toggle';
207    obj.style.cursor = 'pointer';
208    if (toc && toc.style.display == 'none') {
209        obj.innerHTML    = '<span>+</span>';
210        obj.className    = 'toc_open';
211    } else {
212        obj.innerHTML    = '<span>&minus;</span>';
213        obj.className    = 'toc_close';
214    }
215
216    prependChild(header,obj);
217    obj.parentNode.onclick = toggleToc;
218    try {
219       obj.parentNode.style.cursor = 'pointer';
220       obj.parentNode.style.cursor = 'hand';
221    }catch(e){}
222}
223
224/**
225 * This toggles the visibility of the Table of Contents
226 */
227function toggleToc() {
228  var toc = $('toc__inside');
229  var obj = $('toc__toggle');
230  if(toc.style.display == 'none') {
231    toc.style.display   = '';
232    obj.innerHTML       = '<span>&minus;</span>';
233    obj.className       = 'toc_close';
234  } else {
235    toc.style.display   = 'none';
236    obj.innerHTML       = '<span>+</span>';
237    obj.className       = 'toc_open';
238  }
239}
240
241/**
242 * Display an insitu footnote popup
243 *
244 * @author Andreas Gohr <andi@splitbrain.org>
245 * @author Chris Smith <chris@jalakai.co.uk>
246 */
247function footnote(e){
248    var obj = e.target;
249    var id = obj.id.substr(5);
250
251    // get or create the footnote popup div
252    var fndiv = $('insitu__fn');
253    if(!fndiv){
254        fndiv = document.createElement('div');
255        fndiv.id        = 'insitu__fn';
256        fndiv.className = 'insitu-footnote JSpopup dokuwiki';
257
258        // autoclose on mouseout - ignoring bubbled up events
259        addEvent(fndiv,'mouseout',function(e){
260            if(e.target != fndiv){
261                e.stopPropagation();
262                return;
263            }
264            // check if the element was really left
265            if(e.pageX){        // Mozilla
266                var bx1 = findPosX(fndiv);
267                var bx2 = bx1 + fndiv.offsetWidth;
268                var by1 = findPosY(fndiv);
269                var by2 = by1 + fndiv.offsetHeight;
270                var x = e.pageX;
271                var y = e.pageY;
272                if(x > bx1 && x < bx2 && y > by1 && y < by2){
273                    // we're still inside boundaries
274                    e.stopPropagation();
275                    return;
276                }
277            }else{              // IE
278                if(e.offsetX > 0 && e.offsetX < fndiv.offsetWidth-1 &&
279                   e.offsetY > 0 && e.offsetY < fndiv.offsetHeight-1){
280                    // we're still inside boundaries
281                    e.stopPropagation();
282                    return;
283                }
284            }
285            // okay, hide it
286            fndiv.style.display='none';
287        });
288        document.body.appendChild(fndiv);
289    }
290
291    // locate the footnote anchor element
292    var a = $( "fn__"+id );
293    if (!a){ return; }
294
295    // anchor parent is the footnote container, get its innerHTML
296    var content = new String (a.parentNode.parentNode.innerHTML);
297
298    // strip the leading content anchors and their comma separators
299    content = content.replace(/<sup>.*<\/sup>/gi, '');
300    content = content.replace(/^\s+(,\s+)+/,'');
301
302    // prefix ids on any elements with "insitu__" to ensure they remain unique
303    content = content.replace(/\bid=\"(.*?)\"/gi,'id="insitu__$1');
304
305    // now put the content into the wrapper
306    fndiv.innerHTML = content;
307
308    // position the div and make it visible
309    var x; var y;
310    if(e.pageX){        // Mozilla
311        x = e.pageX;
312        y = e.pageY;
313    }else{              // IE
314        x = e.offsetX;
315        y = e.offsetY;
316    }
317    fndiv.style.position = 'absolute';
318    fndiv.style.left = (x+2)+'px';
319    fndiv.style.top  = (y+2)+'px';
320    fndiv.style.display = '';
321}
322
323/**
324 * Add the event handlers to footnotes
325 *
326 * @author Andreas Gohr <andi@splitbrain.org>
327 */
328addInitEvent(function(){
329    var elems = getElementsByClass('fn_top',null,'a');
330    for(var i=0; i<elems.length; i++){
331        addEvent(elems[i],'mouseover',function(e){footnote(e);});
332    }
333});
334
335/**
336 * Add the edit window size controls
337 */
338function initSizeCtl(ctlid,edid){
339    if(!document.getElementById){ return; }
340
341    var ctl      = $(ctlid);
342    var textarea = $(edid);
343    if(!ctl || !textarea) return;
344
345    var hgt = DokuCookie.getValue('sizeCtl');
346    if(hgt){
347      textarea.style.height = hgt;
348    }else{
349      textarea.style.height = '300px';
350    }
351
352    var wrp = DokuCookie.getValue('wrapCtl');
353    if(wrp){
354      setWrap(textarea, wrp);
355    } // else use default value
356
357    var l = document.createElement('img');
358    var s = document.createElement('img');
359    var w = document.createElement('img');
360    l.src = DOKU_BASE+'lib/images/larger.gif';
361    s.src = DOKU_BASE+'lib/images/smaller.gif';
362    w.src = DOKU_BASE+'lib/images/wrap.gif';
363    addEvent(l,'click',function(){sizeCtl(edid,100);});
364    addEvent(s,'click',function(){sizeCtl(edid,-100);});
365    addEvent(w,'click',function(){toggleWrap(edid);});
366    ctl.appendChild(l);
367    ctl.appendChild(s);
368    ctl.appendChild(w);
369}
370
371/**
372 * This sets the vertical size of the editbox
373 */
374function sizeCtl(edid,val){
375  var textarea = $(edid);
376  var height = parseInt(textarea.style.height.substr(0,textarea.style.height.length-2));
377  height += val;
378  textarea.style.height = height+'px';
379
380  DokuCookie.setValue('sizeCtl',textarea.style.height);
381}
382
383/**
384 * Toggle the wrapping mode of a textarea
385 */
386function toggleWrap(edid){
387    var textarea = $(edid);
388    var wrap = textarea.getAttribute('wrap');
389    if(wrap && wrap.toLowerCase() == 'off'){
390        setWrap(textarea, 'soft');
391    }else{
392        setWrap(textarea, 'off');
393    }
394
395    DokuCookie.setValue('wrapCtl',textarea.getAttribute('wrap'));
396}
397
398/**
399 * Set the wrapping mode of a textarea
400 *
401 * @author Fluffy Convict <fluffyconvict@hotmail.com>
402 * @author <shutdown@flashmail.com>
403 * @link   http://news.hping.org/comp.lang.javascript.archive/12265.html
404 * @link   https://bugzilla.mozilla.org/show_bug.cgi?id=41464
405 */
406function setWrap(textarea, wrapAttrValue){
407    textarea.setAttribute('wrap', wrapAttrValue);
408
409    // Fix display for mozilla
410    var parNod = textarea.parentNode;
411    var nxtSib = textarea.nextSibling;
412    parNod.removeChild(textarea);
413    parNod.insertBefore(textarea, nxtSib);
414}
415
416/**
417 * Handler to close all open Popups
418 */
419function closePopups(){
420  if(!document.getElementById){ return; }
421
422  var divs = document.getElementsByTagName('div');
423  for(var i=0; i < divs.length; i++){
424    if(divs[i].className.indexOf('JSpopup') != -1){
425            divs[i].style.display = 'none';
426    }
427  }
428}
429
430/**
431 * Looks for an element with the ID scroll__here at scrolls to it
432 */
433function scrollToMarker(){
434    var obj = $('scroll__here');
435    if(obj) obj.scrollIntoView();
436}
437
438/**
439 * Looks for an element with the ID focus__this at sets focus to it
440 */
441function focusMarker(){
442    var obj = $('focus__this');
443    if(obj) obj.focus();
444}
445
446/**
447 * Remove messages
448 */
449function cleanMsgArea(){
450    var elems = getElementsByClass('(success|info|error)',document,'div');
451    if(elems){
452        for(var i=0; i<elems.length; i++){
453            elems[i].style.display = 'none';
454        }
455    }
456}
457
458/**
459 * disable multiple revisions checkboxes if two are checked
460 *
461 * @author Anika Henke <anika@selfthinker.org>
462 */
463addInitEvent(function(){
464    var revForm = $('page__revisions');
465    if (!revForm) return;
466    var elems = revForm.elements;
467    var countTicks = 0;
468    for (var i=0; i<elems.length; i++) {
469        var input1 = elems[i];
470        if (input1.type=='checkbox') {
471            addEvent(input1,'click',function(e){
472                if (this.checked) countTicks++;
473                else countTicks--;
474                for (var j=0; j<elems.length; j++) {
475                    var input2 = elems[j];
476                    if (countTicks >= 2) input2.disabled = (input2.type=='checkbox' && !input2.checked);
477                    else input2.disabled = (input2.type!='checkbox');
478                }
479            });
480            input1.checked = false; // chrome reselects on back button which messes up the logic
481        } else if(input1.type=='submit'){
482            input1.disabled = true;
483        }
484    }
485});
486
487/**
488 * Add the event handler to the actiondropdown
489 *
490 * @author Andreas Gohr <andi@splitbrain.org>
491 */
492addInitEvent(function(){
493    var selector = $('action__selector');
494    if(!selector) return;
495
496    addEvent(selector,'change',function(e){
497        this.form.submit();
498    });
499
500    $('action__selectorbtn').style.display = 'none';
501});
502
503/**
504 * Display error for Windows Shares on browsers other than IE
505 *
506 * @author Michael Klier <chi@chimeric.de>
507 */
508function checkWindowsShares() {
509    if(!LANG['nosmblinks']) return true;
510    var elems = getElementsByClass('windows',document,'a');
511    if(elems){
512        for(var i=0; i<elems.length; i++){
513            var share = elems[i];
514            addEvent(share,'click',function(){
515                if(document.all == null) {
516                    alert(LANG['nosmblinks']);
517                }
518            });
519        }
520    }
521}
522
523/**
524 * Add the event handler for the Windows Shares check
525 *
526 * @author Michael Klier <chi@chimeric.de>
527 */
528addInitEvent(function(){
529    checkWindowsShares();
530});
531
532/**
533 * Highlight the section when hovering over the appropriate section edit button
534 *
535 * @author Andreas Gohr <andi@splitbrain.org>
536 */
537addInitEvent(function(){
538    var break_classes = new RegExp('secedit|toc|page');
539    var btns = getElementsByClass('btn_secedit',document,'form');
540    for(var i=0; i<btns.length; i++){
541        addEvent(btns[i],'mouseover',function(e){
542            var tgt = e.target;
543            if(tgt.form) tgt = tgt.form;
544            tgt = tgt.parentNode.previousSibling;
545            if(tgt.nodeName != "DIV") tgt = tgt.previousSibling;
546            while(!break_classes.test(tgt.className)) {
547                tgt.className += ' section_highlight';
548                if (tgt.tagName == 'H1') break;
549                tgt = (tgt.previousSibling != null) ? tgt.previousSibling : tgt.parentNode;
550            }
551        });
552
553        addEvent(btns[i],'mouseout',function(e){
554            var secs = getElementsByClass('section_highlight');
555            for(var j=0; j<secs.length; j++){
556                secs[j].className = secs[j].className.replace(/section_highlight/,'');
557            }
558            var secs = getElementsByClass('section_highlight');
559        });
560    }
561});
562