xref: /dokuwiki/lib/scripts/script.js (revision 620404a5dcfbccb29cd939932ecaead95b6e24cd)
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    obj.parentNode.style.cursor = 'pointer';
219}
220
221/**
222 * This toggles the visibility of the Table of Contents
223 */
224function toggleToc() {
225  var toc = $('toc__inside');
226  var obj = $('toc__toggle');
227  if(toc.style.display == 'none') {
228    toc.style.display   = '';
229    obj.innerHTML       = '<span>&minus;</span>';
230    obj.className       = 'toc_close';
231  } else {
232    toc.style.display   = 'none';
233    obj.innerHTML       = '<span>+</span>';
234    obj.className       = 'toc_open';
235  }
236}
237
238/**
239 * Display an insitu footnote popup
240 *
241 * @author Andreas Gohr <andi@splitbrain.org>
242 * @author Chris Smith <chris@jalakai.co.uk>
243 */
244function footnote(e){
245    var obj = e.target;
246    var id = obj.id.substr(5);
247
248    // get or create the footnote popup div
249    var fndiv = $('insitu__fn');
250    if(!fndiv){
251        fndiv = document.createElement('div');
252        fndiv.id        = 'insitu__fn';
253        fndiv.className = 'insitu-footnote JSpopup dokuwiki';
254
255        // autoclose on mouseout - ignoring bubbled up events
256        addEvent(fndiv,'mouseout',function(e){
257            if(e.target != fndiv){
258                e.stopPropagation();
259                return;
260            }
261            // check if the element was really left
262            if(e.pageX){        // Mozilla
263                var bx1 = findPosX(fndiv);
264                var bx2 = bx1 + fndiv.offsetWidth;
265                var by1 = findPosY(fndiv);
266                var by2 = by1 + fndiv.offsetHeight;
267                var x = e.pageX;
268                var y = e.pageY;
269                if(x > bx1 && x < bx2 && y > by1 && y < by2){
270                    // we're still inside boundaries
271                    e.stopPropagation();
272                    return;
273                }
274            }else{              // IE
275                if(e.offsetX > 0 && e.offsetX < fndiv.offsetWidth-1 &&
276                   e.offsetY > 0 && e.offsetY < fndiv.offsetHeight-1){
277                    // we're still inside boundaries
278                    e.stopPropagation();
279                    return;
280                }
281            }
282            // okay, hide it
283            fndiv.style.display='none';
284        });
285        document.body.appendChild(fndiv);
286    }
287
288    // locate the footnote anchor element
289    var a = $( "fn__"+id );
290    if (!a){ return; }
291
292    // anchor parent is the footnote container, get its innerHTML
293    var content = new String (a.parentNode.parentNode.innerHTML);
294
295    // strip the leading content anchors and their comma separators
296    content = content.replace(/<sup>.*<\/sup>/gi, '');
297    content = content.replace(/^\s+(,\s+)+/,'');
298
299    // prefix ids on any elements with "insitu__" to ensure they remain unique
300    content = content.replace(/\bid=\"(.*?)\"/gi,'id="insitu__$1');
301
302    // now put the content into the wrapper
303    fndiv.innerHTML = content;
304
305    // position the div and make it visible
306    var x; var y;
307    if(e.pageX){        // Mozilla
308        x = e.pageX;
309        y = e.pageY;
310    }else{              // IE
311        x = e.offsetX;
312        y = e.offsetY;
313    }
314    fndiv.style.position = 'absolute';
315    fndiv.style.left = (x+2)+'px';
316    fndiv.style.top  = (y+2)+'px';
317    fndiv.style.display = '';
318}
319
320/**
321 * Add the event handlers to footnotes
322 *
323 * @author Andreas Gohr <andi@splitbrain.org>
324 */
325addInitEvent(function(){
326    var elems = getElementsByClass('fn_top',null,'a');
327    for(var i=0; i<elems.length; i++){
328        addEvent(elems[i],'mouseover',function(e){footnote(e);});
329    }
330});
331
332/**
333 * Add the edit window size controls
334 */
335function initSizeCtl(ctlid,edid){
336    if(!document.getElementById){ return; }
337
338    var ctl      = $(ctlid);
339    var textarea = $(edid);
340    if(!ctl || !textarea) return;
341
342    var hgt = DokuCookie.getValue('sizeCtl');
343    if(hgt){
344      textarea.style.height = hgt;
345    }else{
346      textarea.style.height = '300px';
347    }
348
349    var wrp = DokuCookie.getValue('wrapCtl');
350    if(wrp){
351      setWrap(textarea, wrp);
352    } // else use default value
353
354    var l = document.createElement('img');
355    var s = document.createElement('img');
356    var w = document.createElement('img');
357    l.src = DOKU_BASE+'lib/images/larger.gif';
358    s.src = DOKU_BASE+'lib/images/smaller.gif';
359    w.src = DOKU_BASE+'lib/images/wrap.gif';
360    addEvent(l,'click',function(){sizeCtl(edid,100);});
361    addEvent(s,'click',function(){sizeCtl(edid,-100);});
362    addEvent(w,'click',function(){toggleWrap(edid);});
363    ctl.appendChild(l);
364    ctl.appendChild(s);
365    ctl.appendChild(w);
366}
367
368/**
369 * This sets the vertical size of the editbox
370 */
371function sizeCtl(edid,val){
372  var textarea = $(edid);
373  var height = parseInt(textarea.style.height.substr(0,textarea.style.height.length-2));
374  height += val;
375  textarea.style.height = height+'px';
376
377  DokuCookie.setValue('sizeCtl',textarea.style.height);
378}
379
380/**
381 * Toggle the wrapping mode of a textarea
382 */
383function toggleWrap(edid){
384    var textarea = $(edid);
385    var wrap = textarea.getAttribute('wrap');
386    if(wrap && wrap.toLowerCase() == 'off'){
387        setWrap(textarea, 'soft');
388    }else{
389        setWrap(textarea, 'off');
390    }
391
392    DokuCookie.setValue('wrapCtl',textarea.getAttribute('wrap'));
393}
394
395/**
396 * Set the wrapping mode of a textarea
397 *
398 * @author Fluffy Convict <fluffyconvict@hotmail.com>
399 * @author <shutdown@flashmail.com>
400 * @link   http://news.hping.org/comp.lang.javascript.archive/12265.html
401 * @link   https://bugzilla.mozilla.org/show_bug.cgi?id=41464
402 */
403function setWrap(textarea, wrapAttrValue){
404    textarea.setAttribute('wrap', wrapAttrValue);
405
406    // Fix display for mozilla
407    var parNod = textarea.parentNode;
408    var nxtSib = textarea.nextSibling;
409    parNod.removeChild(textarea);
410    parNod.insertBefore(textarea, nxtSib);
411}
412
413/**
414 * Handler to close all open Popups
415 */
416function closePopups(){
417  if(!document.getElementById){ return; }
418
419  var divs = document.getElementsByTagName('div');
420  for(var i=0; i < divs.length; i++){
421    if(divs[i].className.indexOf('JSpopup') != -1){
422            divs[i].style.display = 'none';
423    }
424  }
425}
426
427/**
428 * Looks for an element with the ID scroll__here at scrolls to it
429 */
430function scrollToMarker(){
431    var obj = $('scroll__here');
432    if(obj) obj.scrollIntoView();
433}
434
435/**
436 * Looks for an element with the ID focus__this at sets focus to it
437 */
438function focusMarker(){
439    var obj = $('focus__this');
440    if(obj) obj.focus();
441}
442
443/**
444 * Remove messages
445 */
446function cleanMsgArea(){
447    var elems = getElementsByClass('(success|info|error)',document,'div');
448    if(elems){
449        for(var i=0; i<elems.length; i++){
450            elems[i].style.display = 'none';
451        }
452    }
453}
454
455/**
456 * disable multiple revisions checkboxes if two are checked
457 *
458 * @author Anika Henke <anika@selfthinker.org>
459 */
460addInitEvent(function(){
461    var revForm = $('page__revisions');
462    if (!revForm) return;
463    var elems = revForm.elements;
464    var countTicks = 0;
465    for (var i=0; i<elems.length; i++) {
466        var input1 = elems[i];
467        if (input1.type=='checkbox') {
468            addEvent(input1,'click',function(e){
469                if (this.checked) countTicks++;
470                else countTicks--;
471                for (var j=0; j<elems.length; j++) {
472                    var input2 = elems[j];
473                    if (countTicks >= 2) input2.disabled = (input2.type=='checkbox' && !input2.checked);
474                    else input2.disabled = (input2.type!='checkbox');
475                }
476            });
477            input1.checked = false; // chrome reselects on back button which messes up the logic
478        } else if(input1.type=='submit'){
479            input1.disabled = true;
480        }
481    }
482});
483
484/**
485 * Add the event handler to the actiondropdown
486 *
487 * @author Andreas Gohr <andi@splitbrain.org>
488 */
489addInitEvent(function(){
490    var selector = $('action__selector');
491    if(!selector) return;
492
493    addEvent(selector,'change',function(e){
494        this.form.submit();
495    });
496
497    $('action__selectorbtn').style.display = 'none';
498});
499
500/**
501 * Display error for Windows Shares on browsers other than IE
502 *
503 * @author Michael Klier <chi@chimeric.de>
504 */
505function checkWindowsShares() {
506    if(!LANG['nosmblinks']) return true;
507    var elems = getElementsByClass('windows',document,'a');
508    if(elems){
509        for(var i=0; i<elems.length; i++){
510            var share = elems[i];
511            addEvent(share,'click',function(){
512                if(document.all == null) {
513                    alert(LANG['nosmblinks']);
514                }
515            });
516        }
517    }
518}
519
520/**
521 * Add the event handler for the Windows Shares check
522 *
523 * @author Michael Klier <chi@chimeric.de>
524 */
525addInitEvent(function(){
526    checkWindowsShares();
527});
528
529/**
530 * Highlight the section when hovering over the appropriate section edit button
531 *
532 * @author Andreas Gohr <andi@splitbrain.org>
533 */
534addInitEvent(function(){
535    var btns = getElementsByClass('btn_secedit',document,'form');
536    for(var i=0; i<btns.length; i++){
537        addEvent(btns[i],'mouseover',function(e){
538            var tgt = e.target.form.parentNode;
539            var nr = tgt.className.match(/(\s+|^)editbutton_(\d+)(\s+|$)/)[2];
540            do {
541                tgt = tgt.previousSibling;
542            } while (tgt !== null && typeof tgt.tagName === 'undefined');
543            if (tgt === null) return;
544            while(typeof tgt.className === 'undefined' ||
545                  tgt.className.match('(\\s+|^)sectionedit' + nr + '(\\s+|$)') === null) {
546                if (typeof tgt.className !== 'undefined') {
547                    tgt.className += ' section_highlight';
548                }
549                tgt = (tgt.previousSibling !== null) ? tgt.previousSibling : tgt.parentNode;
550            }
551            if (typeof tgt.className !== 'undefined') tgt.className += ' section_highlight';
552        });
553
554        addEvent(btns[i],'mouseout',function(e){
555            var secs = getElementsByClass('section_highlight');
556            for(var j=0; j<secs.length; j++){
557                secs[j].className = secs[j].className.replace(/section_highlight/,'');
558            }
559        });
560    }
561});
562