xref: /dokuwiki/lib/scripts/media.js (revision 7abc270f7333e2055bcdbbea8031f77593e08fb9)
1/**
2 * JavaScript functionality for the media management popup
3 *
4 * @author Andreas Gohr <andi@splitbrain.org>
5 * @author Pierre Spring <pierre.spring@caillou.ch>
6 */
7
8var dw_mediamanager = {
9    keepopen: false,
10    hide: false,
11    popup: false,
12    display: false,
13    ext: false,
14    $popup: null,
15
16    // Image insertion opts
17    align: false,
18    link: false,
19    size: false,
20    forbidden_opts: {},
21
22    // File list options
23    view_opts: {list: false, sort: false},
24
25    layout_width: 0,
26
27    // The minimum height of the full-screen mediamanager in px
28    minHeights: {thumbs: 200, rows: 100},
29
30    init: function () {
31        var $content, $tree;
32        $content = jQuery('#media__content');
33        $tree    = jQuery('#media__tree');
34        if(!$tree.length) return;
35
36        dw_mediamanager.prepare_content($content);
37
38        dw_mediamanager.attachoptions();
39        dw_mediamanager.initpopup();
40
41        // add the action to autofill the "upload as" field
42        $content
43            .delegate('#upload__file', 'change', dw_mediamanager.suggest)
44            // Attach the image selector action to all links
45            .delegate('a.select', 'click', dw_mediamanager.select)
46            // Attach deletion confirmation dialog to the delete buttons
47            .delegate('#media__content a.btn_media_delete', 'click',
48                      dw_mediamanager.confirmattach)
49            .delegate('#mediamanager__done_form', 'submit', dw_mediamanager.list);
50
51        $tree.dw_tree({toggle_selector: 'img',
52                       load_data: function (show_sublist, $clicky) {
53                           // get the enclosed link (is always the first one)
54                           var $link = $clicky.parent().find('div.li a.idx_dir');
55
56                           jQuery.post(
57                               DOKU_BASE + 'lib/exe/ajax.php',
58                               $link[0].search.substr(1) + '&call=medians',
59                               show_sublist,
60                               'html'
61                           );
62                       },
63
64                       toggle_display: function ($clicky, opening) {
65                           $clicky.attr('src',
66                                        DOKU_BASE + 'lib/images/' +
67                                        (opening ? 'minus' : 'plus') + '.gif');
68                       }});
69        $tree.delegate('a', 'click', dw_mediamanager.list);
70
71        // Init view property
72        dw_mediamanager.set_fileview_list();
73
74        dw_mediamanager.init_options();
75
76        dw_mediamanager.image_diff();
77        dw_mediamanager.init_ajax_uploader();
78
79        // changing opened tab in the file list panel
80        var $page = jQuery('#mediamanager__page');
81        $page.find('div.filelist')
82            .delegate('ul.tabs a', 'click', dw_mediamanager.list)
83            // loading file details
84            .delegate('div.panelContent a', 'click', dw_mediamanager.details)
85            // search form
86            .delegate('#dw__mediasearch', 'submit', dw_mediamanager.list)
87            // "upload as" field autofill
88            .delegate('#upload__file', 'change', dw_mediamanager.suggest)
89            // uploaded images
90            .delegate('.qq-upload-file a', 'click', dw_mediamanager.details);
91
92        // changing opened tab in the file details panel
93        $page.find('div.file')
94            .delegate('ul.tabs a', 'click', dw_mediamanager.details)
95            // "update new version" button
96            .delegate('#mediamanager__btn_update', 'submit', dw_mediamanager.list)
97            // revisions form
98            .delegate('#page__revisions', 'submit', dw_mediamanager.details)
99            .delegate('#page__revisions a', 'click', dw_mediamanager.details)
100            // meta edit form
101            .delegate('#mediamanager__save_meta', 'submit', dw_mediamanager.details)
102            // delete button
103            .delegate('#mediamanager__btn_delete', 'submit', dw_mediamanager.details)
104            // "restore this version" button
105            .delegate('#mediamanager__btn_restore', 'submit', dw_mediamanager.details)
106            // less/more recent buttons in media revisions form
107            .delegate('.btn_newer, .btn_older', 'submit', dw_mediamanager.details);
108
109        dw_mediamanager.update_resizable();
110        dw_mediamanager.layout_width = $page.width();
111        jQuery(window).resize(dw_mediamanager.window_resize);
112    },
113
114    init_options: function () {
115        var $options = jQuery('div.filelist div.panelHeader form.options'),
116            $listType, $sortBy, $both;
117        if ($options.length === 0) {
118            return;
119        }
120
121        $listType = $options.find('li.listType');
122        $sortBy = $options.find('li.sortBy');
123        $both = $listType.add($sortBy);
124
125        // Remove the submit button
126        $options.find('button[type=submit]').parent().hide();
127
128        // Prepare HTML for jQuery UI buttonset
129        $both.find('label').each(function () {
130            var $this = jQuery(this);
131            $this.children('input').appendTo($this.parent());
132        });
133
134        // Init buttonset
135        $both.buttonset();
136
137        // Change handlers
138        $listType.children('input').change(function () {
139            dw_mediamanager.set_fileview_list();
140        });
141        $sortBy.children('input').change(function (event) {
142            dw_mediamanager.set_fileview_sort();
143            dw_mediamanager.list.call(jQuery('#dw__mediasearch')[0] || this, event);
144        });
145    },
146
147    /**
148     * build the popup window
149     *
150     * @author Dominik Eckelmann <eckelmann@cosmocode.de>
151     */
152    initpopup: function () {
153        var opts, $insp, $insbtn;
154
155        dw_mediamanager.$popup = jQuery(document.createElement('div'))
156                 .attr('id', 'media__popup_content')
157                 .dialog({autoOpen: false, width: 280, modal: true,
158                          draggable: true, title: LANG.mediatitle,
159                          resizable: false});
160
161        opts = [{id: 'link', label: LANG.mediatarget,
162                 btns: ['lnk', 'direct', 'nolnk', 'displaylnk']},
163                {id: 'align', label: LANG.mediaalign,
164                 btns: ['noalign', 'left', 'center', 'right']},
165                {id: 'size', label: LANG.mediasize,
166                 btns: ['small', 'medium', 'large', 'original']}
167               ];
168
169        jQuery.each(opts, function (_, opt) {
170            var $p, $l;
171            $p = jQuery(document.createElement('p'))
172                 .attr('id', 'media__' + opt.id);
173
174            if (dw_mediamanager.display === "2") {
175                $p.hide();
176            }
177
178            $l = jQuery(document.createElement('label'))
179                 .text(opt.label);
180            $p.append($l);
181
182            jQuery.each(opt.btns, function (i, text) {
183                var $btn, $img;
184                $btn = jQuery(document.createElement('button'))
185                       .addClass('button')
186                       .attr('id', "media__" + opt.id + "btn" + (i + 1))
187                       .attr('title', LANG['media' + text])
188                       .click(bind(dw_mediamanager.setOpt, opt.id));
189
190                $img = jQuery(document.createElement('img'))
191                       .attr('src', DOKU_BASE + 'lib/images/media_' +
192                                    opt.id + '_' + text + '.png');
193
194                $btn.append($img);
195                $p.append($btn);
196            });
197
198            dw_mediamanager.$popup.append($p);
199        });
200
201        // insert button
202        $insp = jQuery(document.createElement('p'));
203        dw_mediamanager.$popup.append($insp);
204
205        $insbtn = jQuery(document.createElement('input'))
206                  .attr('id', 'media__sendbtn')
207                  .attr('type', 'button')
208                  .addClass('button')
209                  .val(LANG.mediainsert);
210        $insp.append($insbtn);
211    },
212
213    /**
214     * Insert the clicked image into the opener's textarea
215     *
216     * @author Andreas Gohr <andi@splitbrain.org>
217     * @author Dominik Eckelmann <eckelmann@cosmocode.de>
218     * @author Pierre Spring <pierre.spring@caillou.ch>
219     */
220    insert: function (id) {
221        var opts, cb, edid, s;
222
223        // set syntax options
224        dw_mediamanager.$popup.dialog('close');
225
226        opts = '';
227
228        if ({img: 1, swf: 1}[dw_mediamanager.ext] === 1) {
229
230            if (dw_mediamanager.link === '4') {
231                    opts = '?linkonly';
232            } else {
233
234                if (dw_mediamanager.link === "3" && dw_mediamanager.ext === 'img') {
235                    opts = '?nolink';
236                } else if (dw_mediamanager.link === "2" && dw_mediamanager.ext === 'img') {
237                    opts = '?direct';
238                }
239
240                s = parseInt(dw_mediamanager.size, 10);
241
242                if (s && s >= 1 && s < 4) {
243                    opts += (opts.length)?'&':'?';
244                    opts += dw_mediamanager.size + '00';
245                    if (dw_mediamanager.ext === 'swf') {
246                        switch (s) {
247                        case 1:
248                            opts += 'x62';
249                            break;
250                        case 2:
251                            opts += 'x123';
252                            break;
253                        case 3:
254                            opts += 'x185';
255                            break;
256                        }
257                    }
258                }
259            }
260        }
261        edid = String.prototype.match.call(document.location, /&edid=([^&]+)/);
262        edid = edid ? edid[1] : 'wiki__text';
263        cb   = String.prototype.match.call(document.location, /&onselect=([^&]+)/);
264        cb   = cb ? cb[1].replace(/[^\w]+/, '') : 'dw_mediamanager_item_select';
265
266        opener[cb](edid, id, opts, dw_mediamanager.align);
267        if(!dw_mediamanager.keepopen) {
268            window.close();
269        }
270        opener.focus();
271        return false;
272    },
273
274
275
276    /**
277     * Prefills the wikiname.
278     *
279     * @author Andreas Gohr <andi@splitbrain.org>
280     */
281    suggest: function(){
282        var $file, $name, text;
283
284        $file = jQuery(this);
285        $name = jQuery('#upload__name');
286
287        if ($name.val() != '') return;
288
289        if(!$file.length || !$name.length) {
290            return;
291        }
292
293        text = $file.val();
294        text = text.substr(text.lastIndexOf('/')+1);
295        text = text.substr(text.lastIndexOf('\\')+1);
296        $name.val(text);
297    },
298
299    /**
300     * list the content of a namespace using AJAX
301     *
302     * @author Andreas Gohr <andi@splitbrain.org>
303     * @author Pierre Spring <pierre.spring@caillou.ch>
304     */
305    list: function (event) {
306        var $link, $content, params;
307
308        if (event) {
309            event.preventDefault();
310        }
311
312        jQuery('div.success, div.info, div.error, div.notify').remove();
313
314        $link = jQuery(this);
315
316        //popup
317        $content = jQuery('#media__content');
318
319        if ($content.length === 0) {
320            //fullscreen media manager
321            $content = jQuery('div.filelist');
322
323            if ($link.hasClass('idx_dir')) {
324                //changing namespace
325                jQuery('div.file').empty();
326                jQuery('div.namespaces .selected').removeClass('selected');
327                $link.addClass('selected');
328            }
329        }
330
331        params = 'call=medialist&';
332
333        if ($link[0].search) {
334            params += $link[0].search.substr(1);
335        } else if ($link.is('form')) {
336            params += dw_mediamanager.form_params($link);
337        } else if ($link.closest('form').length > 0) {
338            params += dw_mediamanager.form_params($link.closest('form'));
339        }
340
341        // fetch the subtree
342        dw_mediamanager.update_content($content, params);
343    },
344
345     /**
346     * Returns form parameters
347     *
348     * @author Kate Arzamastseva <pshns@ukr.net>
349     */
350    form_params: function ($form) {
351        if (!$form.length) return;
352        var action = '';
353        var i = $form[0].action.indexOf('?');
354        if (i >= 0) action = $form[0].action.substr(i+1);
355        return action+'&'+$form.serialize();
356    },
357
358    set_fileview_list: function (new_type) {
359        dw_mediamanager.set_fileview_opt(['list', 'listType', function (new_type) {
360            jQuery('div.filelist div.panelContent ul')
361               .toggleClass('rows', new_type === 'rows')
362               .toggleClass('thumbs', new_type === 'thumbs');
363        }], new_type);
364
365        // FIXME: Move to onchange handler (opt[2])?
366        dw_mediamanager.resize();
367    },
368
369    set_fileview_sort: function (new_sort) {
370        dw_mediamanager.set_fileview_opt(['sort', 'sortBy', function (new_sort) {
371            // FIXME
372        }], new_sort);
373    },
374
375    set_fileview_opt: function (opt, new_val) {
376        if (typeof new_val === 'undefined') {
377            new_val = jQuery('form.options li.' + opt[1] + ' input')
378                        .filter(':checked').val();
379            // if new_val is still undefined (because form.options is not in active tab), set to most spacious option
380            if (typeof new_val === 'undefined') {
381                new_val = 'thumbs';
382            }
383        }
384
385        if (new_val !== dw_mediamanager.view_opts[opt[0]]) {
386            opt[2](new_val);
387
388            DokuCookie.setValue(opt[0], new_val);
389
390            dw_mediamanager.view_opts[opt[0]] = new_val;
391        }
392    },
393
394     /**
395     * Lists the content of the right column (image details) using AJAX
396     *
397     * @author Kate Arzamastseva <pshns@ukr.net>
398     */
399    details: function (event) {
400        var $link, $content, params, update_list;
401        $link = jQuery(this);
402        event.preventDefault();
403
404        jQuery('div.success, div.info, div.error, div.notify').remove();
405
406        if ($link[0].id == 'mediamanager__btn_delete' && !confirm(LANG.del_confirm)) {
407            return false;
408        }
409        if ($link[0].id == 'mediamanager__btn_restore' && !confirm(LANG.restore_confirm)) {
410            return false;
411        }
412
413        $content = jQuery('div.file');
414        params = 'call=mediadetails&';
415
416        if ($link[0].search) {
417            params += $link[0].search.substr(1);
418        } else if ($link.is('form')) {
419            params += dw_mediamanager.form_params($link);
420        } else if ($link.closest('form').length > 0) {
421            params += dw_mediamanager.form_params($link.closest('form'));
422        }
423
424        update_list = ($link[0].id == 'mediamanager__btn_delete' ||
425                       $link[0].id == 'mediamanager__btn_restore');
426
427        dw_mediamanager.update_content($content, params, update_list);
428    },
429
430    update_content: function ($content, params, update_list) {
431        var $container;
432
433        jQuery.post(
434            DOKU_BASE + 'lib/exe/ajax.php',
435            params,
436            function (data) {
437                dw_mediamanager.$resizables().resizable('destroy');
438
439                if (update_list) {
440                    dw_mediamanager.list.call(jQuery('#mediamanager__page').find('form.options button[type="submit"]')[0]);
441                }
442
443                $content.html(data);
444
445                dw_mediamanager.prepare_content($content);
446                dw_mediamanager.updatehide();
447
448                dw_mediamanager.update_resizable();
449                dw_behaviour.revisionBoxHandler();
450
451                // Make sure that the list view style stays the same
452                dw_mediamanager.set_fileview_list(dw_mediamanager.view_opts.list);
453
454                dw_mediamanager.image_diff();
455                dw_mediamanager.init_ajax_uploader();
456                dw_mediamanager.init_options();
457
458            },
459            'html'
460        );
461        $container = $content.find('div.panelContent');
462        if ($container.length === 0) {
463            $container = $content;
464        }
465        $container.html('<img src="' + DOKU_BASE + 'lib/images/loading.gif" alt="..." class="load" />');
466    },
467
468    window_resize: function () {
469        dw_mediamanager.resize();
470
471        dw_mediamanager.opacity_slider();
472        dw_mediamanager.portions_slider();
473    },
474
475    $resizables: function () {
476        return jQuery('#mediamanager__page').find('div.namespaces, div.filelist');
477    },
478
479    /**
480     * Updates mediamanager layout
481     *
482     * @author Kate Arzamastseva <pshns@ukr.net>
483     */
484    update_resizable: function () {
485        var $resizables = dw_mediamanager.$resizables();
486
487        $resizables.resizable({
488            handles: (jQuery('html[dir=rtl]') ? 'w' :'e'),
489            resize: function(event, ui){
490                var $page = jQuery('#mediamanager__page');
491                var widthFull = $page.width();
492                var widthResizables = 0;
493                $resizables.each(function() {
494                    widthResizables += jQuery(this).width();
495                });
496                var $filePanel = $page.find('div.panel.file');
497
498                // set max width of resizable column
499                var widthOtherResizable = widthResizables - jQuery(this).width();
500                var minWidthNonResizable = parseFloat($filePanel.css("min-width"));
501                var maxWidth = widthFull - (widthOtherResizable + minWidthNonResizable) - 1;
502                $resizables.resizable( "option", "maxWidth", maxWidth );
503
504                // width of file panel in % = 100% - width of resizables in %
505                // this calculates with 99.9 and not 100 to overcome rounding errors
506                var relWidthNonResizable = 99.9 - (100 * widthResizables / widthFull);
507                // set width of file panel
508                $filePanel.width(relWidthNonResizable+'%');
509
510                // FIXME: please fix without browser sniffing
511                if (!jQuery.browser.webkit) {
512                    $resizables.each(function() {
513                        var w = jQuery(this).width();
514                        w = (99.99 * w / widthFull);
515                        w += "%";
516                        jQuery(this).width(w);
517                    });
518                }
519
520                dw_mediamanager.resize();
521
522                dw_mediamanager.opacity_slider();
523                dw_mediamanager.portions_slider();
524            }
525        });
526
527        dw_mediamanager.resize();
528    },
529
530    resize: function () {
531        var $contents = jQuery('#mediamanager__page').find('div.panelContent'),
532            height = jQuery(window).height() - jQuery(document.body).height() +
533                      Math.max.apply(null, jQuery.map($contents, function (v) {
534            return jQuery(v).height();
535        }));
536
537        // If the screen is too small, don’t try to resize
538        if (height < dw_mediamanager.minHeights[dw_mediamanager.view_opts.list]) {
539            $contents.add(dw_mediamanager.$resizables()).height('auto');
540        } else {
541            $contents.height(height);
542            dw_mediamanager.$resizables().each(function () {
543                var $this = jQuery(this);
544                $this.height(height + $this.find('div.panelContent').offset().top -
545                             $this.offset().top);
546            });
547        }
548    },
549
550     /**
551     * Prints 'select' for image difference representation type
552     *
553     * @author Kate Arzamastseva <pshns@ukr.net>
554     */
555    image_diff: function () {
556        if (jQuery('#mediamanager__difftype').length) return;
557
558        var $form = jQuery('#mediamanager__form_diffview');
559        if (!$form.length) return;
560
561        var $label = jQuery(document.createElement('label'));
562        $label.append('<span>'+LANG.media_diff+'</span> ');
563        var $select = jQuery(document.createElement('select'))
564         .attr('id', 'mediamanager__difftype')
565         .attr('name', 'difftype')
566         .change(dw_mediamanager.change_diff_type);
567        $select.append(new Option(LANG.media_diff_both, "both"));
568        $select.append(new Option(LANG.media_diff_opacity, "opacity"));
569        $select.append(new Option(LANG.media_diff_portions, "portions"));
570        $label.append($select);
571        $form.append($label);
572
573        // for IE
574        var select = document.getElementById('mediamanager__difftype');
575        select.options[0].text = LANG.media_diff_both;
576        select.options[1].text = LANG.media_diff_opacity;
577        select.options[2].text = LANG.media_diff_portions;
578    },
579
580    /**
581     * Handles selection of image difference representation type
582     *
583     * @author Kate Arzamastseva <pshns@ukr.net>
584     */
585    change_diff_type: function () {
586        var $select = jQuery('#mediamanager__difftype');
587        var $content = jQuery('#mediamanager__diff');
588
589        var params = dw_mediamanager.form_params($select.closest('form'))+'&call=mediadiff';
590        jQuery.post(
591            DOKU_BASE + 'lib/exe/ajax.php',
592            params,
593            function (data) {
594                $content.html(data);
595                dw_mediamanager.portions_slider();
596                dw_mediamanager.opacity_slider();
597            },
598            'html'
599        );
600    },
601
602    /**
603     * Sets options for opacity diff slider
604     *
605     * @author Kate Arzamastseva <pshns@ukr.net>
606     */
607    opacity_slider: function () {
608        var $diff = jQuery("#mediamanager__diff");
609        var $slider = $diff.find("div.slider");
610        if (!$slider.length) return;
611
612        var $image = $diff.find('div.imageDiff.opacity div.image1 img');
613        if (!$image.length) return;
614        $slider.width($image.width()-20);
615
616        $slider.slider();
617        $slider.slider("option", "min", 0);
618        $slider.slider("option", "max", 0.999);
619        $slider.slider("option", "step", 0.001);
620        $slider.slider("option", "value", 0.5);
621        $slider.bind("slide", function(event, ui) {
622            jQuery('#mediamanager__diff').find('div.imageDiff.opacity div.image2 img').css({ opacity: $slider.slider("option", "value")});
623        });
624    },
625
626     /**
627     * Sets options for red line diff slider
628     *
629     * @author Kate Arzamastseva <pshns@ukr.net>
630     */
631    portions_slider: function () {
632        var $diff = jQuery("#mediamanager__diff");
633        if (!$diff.length) return;
634
635        var $image1 = $diff.find('div.imageDiff.portions div.image1 img');
636        var $image2 = $diff.find('div.imageDiff.portions div.image2 img');
637        if (!$image1.length || !$image2.length) return;
638
639        $diff.width('100%');
640        $image2.parent().width('97%');
641        $image1.width('100%');
642        $image2.width('100%');
643
644        if ($image1.width() < $diff.width()) {
645            $diff.width($image1.width());
646        }
647
648        $image2.parent().width('50%');
649        $image2.width($image1.width());
650        $image1.width($image1.width());
651
652        var $slider = $diff.find("div.slider");
653        if (!$slider.length) return;
654        $slider.width($image1.width()-20);
655
656        $slider.slider();
657        $slider.slider("option", "min", 0);
658        $slider.slider("option", "max", 97);
659        $slider.slider("option", "step", 1);
660        $slider.slider("option", "value", 50);
661        $slider.bind("slide", function(event, ui) {
662            jQuery('#mediamanager__diff').find('div.imageDiff.portions div.image2').css({ width: $slider.slider("option", "value")+'%'});
663        });
664    },
665
666    /**
667     * Parse a URI query string to an associative array
668     *
669     * @author Kate Arzamastseva <pshns@ukr.net>
670     */
671    params_toarray: function (str) {
672        var vars = [], hash;
673        var hashes = str.split('&');
674        for(var i = 0; i < hashes.length; i++) {
675            hash = hashes[i].split('=');
676            vars[decodeURIComponent(hash[0])] = decodeURIComponent(hash[1]);
677        }
678        return vars;
679    },
680
681    init_ajax_uploader: function () {
682        if (!jQuery('#mediamanager__uploader').length) return;
683        if (jQuery('.qq-upload-list').length) return;
684
685        var params = dw_mediamanager.form_params(jQuery('#dw__upload'))+'&call=mediaupload';
686        params = dw_mediamanager.params_toarray(params);
687
688        var uploader = new qq.FileUploaderExtended({
689            element: document.getElementById('mediamanager__uploader'),
690            action: DOKU_BASE + 'lib/exe/ajax.php',
691            params: params
692        });
693    },
694
695    prepare_content: function ($content) {
696        // hide syntax example
697        $content.find('div.example:visible').hide();
698    },
699
700    /**
701     * shows the popup for a image link
702     */
703    select: function(event){
704        var $link, id, dot, ext;
705
706        event.preventDefault();
707
708        $link = jQuery(this);
709        id = $link.attr('id').substr(2);
710
711        if(!opener){
712            // if we don't run in popup display example
713            // the id's are a bit wierd and jQuery('#ex_wiki_dokuwiki-128.png')
714            // will not be found by Sizzle (the CSS Selector Engine
715            // used by jQuery), hence the document.getElementById() call
716            jQuery(document.getElementById('ex_'+id.replace(/:/g,'_').replace(/^_/,''))).dw_toggle();
717            return;
718        }
719
720        dw_mediamanager.ext = false;
721        dot = id.lastIndexOf(".");
722
723        if (-1 === dot) {
724            dw_mediamanager.insert(id);
725            return;
726        }
727
728        ext = id.substr(dot);
729
730        if ({'.jpg':1, '.jpeg':1, '.png':1, '.gif':1, '.swf':1}[ext] !== 1) {
731            dw_mediamanager.insert(id);
732            return;
733        }
734
735        // remove old callback from the insert button and set the new one.
736        var $sendbtn = jQuery('#media__sendbtn');
737        $sendbtn.unbind().click(bind(dw_mediamanager.insert, id));
738
739        dw_mediamanager.unforbid('ext');
740        if (ext === '.swf') {
741            dw_mediamanager.ext = 'swf';
742            dw_mediamanager.forbid('ext', {link: ['1', '2'],
743                                           size: ['4']});
744        } else {
745            dw_mediamanager.ext = 'img';
746        }
747
748        // Set to defaults
749        dw_mediamanager.setOpt('link');
750        dw_mediamanager.setOpt('align');
751        dw_mediamanager.setOpt('size');
752
753        // toggle buttons for detail and linked image, original size
754        jQuery('#media__linkbtn1, #media__linkbtn2, #media__sizebtn4')
755            .toggle(dw_mediamanager.ext === 'img');
756
757        dw_mediamanager.$popup.dialog('open');
758
759        $sendbtn.focus();
760    },
761
762    /**
763     * Deletion confirmation dialog to the delete buttons.
764     *
765     * @author Michael Klier <chi@chimeric.de>
766     * @author Pierre Spring <pierre.spring@caillou.ch>
767     */
768    confirmattach: function(e){
769        if(!confirm(LANG.del_confirm + "\n" + jQuery(this).attr('title'))) {
770            e.preventDefault();
771        }
772    },
773
774    /**
775     * Creates checkboxes for additional options
776     *
777     * @author Andreas Gohr <andi@splitbrain.org>
778     * @author Pierre Spring <pierre.spring@caillou.ch>
779     */
780    attachoptions: function(){
781        var $obj, opts;
782
783        $obj = jQuery('#media__opts');
784        if($obj.length === 0) {
785            return;
786        }
787
788        opts = [];
789        // keep open
790        if(opener){
791            opts.push(['keepopen', 'keepopen']);
792        }
793        opts.push(['hide', 'hidedetails']);
794
795        jQuery.each(opts,
796                    function(_, opt) {
797                        var $box, $lbl;
798                        $box = jQuery(document.createElement('input'))
799                                 .attr('type', 'checkbox')
800                                 .attr('id', 'media__' + opt[0])
801                                 .click(bind(dw_mediamanager.toggleOption,
802                                             opt[0]));
803
804                        if(DokuCookie.getValue(opt[0])){
805                            $box.prop('checked', true);
806                            dw_mediamanager[opt[0]] = true;
807                        }
808
809                        $lbl = jQuery(document.createElement('label'))
810                                 .attr('for', 'media__' + opt[0])
811                                 .text(LANG[opt[1]]);
812
813                        $obj.append($box, $lbl, document.createElement('br'));
814                    });
815
816        dw_mediamanager.updatehide();
817    },
818
819    /**
820     * Generalized toggler
821     *
822     * @author Pierre Spring <pierre.spring@caillou.ch>
823     */
824    toggleOption: function (variable) {
825        if (jQuery(this).prop('checked')) {
826            DokuCookie.setValue(variable, 1);
827            dw_mediamanager[variable] = true;
828        } else {
829            DokuCookie.setValue(variable, '');
830            dw_mediamanager[variable] = false;
831        }
832        if (variable === 'hide') {
833            dw_mediamanager.updatehide();
834        }
835    },
836
837    /**
838     * Sets the visibility of the image details accordingly to the
839     * chosen hide state
840     *
841     * @author Andreas Gohr <andi@splitbrain.org>
842     */
843    updatehide: function(){
844        jQuery('#media__content').find('div.detail').dw_toggle(!dw_mediamanager.hide);
845    },
846
847    /**
848     * set media insertion option
849     *
850     * @author Dominik Eckelmann <eckelmann@cosmocode.de>
851     */
852    setOpt: function(opt, e){
853        var val, i;
854        if (typeof e !== 'undefined') {
855            val = this.id.substring(this.id.length - 1);
856        } else {
857            val = dw_mediamanager.getOpt(opt);
858        }
859
860        if (val === false) {
861            DokuCookie.setValue(opt,'');
862            dw_mediamanager[opt] = false;
863            return;
864        }
865
866        if (opt === 'link') {
867            if (val !== '4' && dw_mediamanager.link === '4') {
868                dw_mediamanager.unforbid('linkonly');
869                dw_mediamanager.setOpt('align');
870                dw_mediamanager.setOpt('size');
871            } else if (val === '4') {
872                dw_mediamanager.forbid('linkonly', {align: false, size: false});
873            }
874
875            jQuery("#media__size, #media__align").dw_toggle(val !== '4');
876        }
877
878        DokuCookie.setValue(opt, val);
879        dw_mediamanager[opt] = val;
880
881        for (i = 1; i <= 4; i++) {
882            jQuery("#media__" + opt + "btn" + i).removeClass('selected');
883        }
884        jQuery('#media__' + opt + 'btn' + val).addClass('selected');
885    },
886
887    unforbid: function (group) {
888        delete dw_mediamanager.forbidden_opts[group];
889    },
890
891    forbid: function (group, forbids) {
892        dw_mediamanager.forbidden_opts[group] = forbids;
893    },
894
895    allowedOpt: function (opt, val) {
896        var ret = true;
897        jQuery.each(dw_mediamanager.forbidden_opts,
898                    function (_, forbids) {
899                        ret = forbids[opt] !== false &&
900                              jQuery.inArray(val, forbids[opt]) === -1;
901                        return ret;
902                    });
903        return ret;
904    },
905
906    getOpt: function (opt) {
907        var allowed = bind(dw_mediamanager.allowedOpt, opt);
908
909        // Current value
910        if (dw_mediamanager[opt] !== false && allowed(dw_mediamanager[opt])) {
911            return dw_mediamanager[opt];
912        }
913
914        // From cookie
915        if (DokuCookie.getValue(opt) && allowed(DokuCookie.getValue(opt))) {
916            return DokuCookie.getValue(opt);
917        }
918
919        // size default
920        if (opt === 'size' && allowed('2')) {
921            return '2';
922        }
923
924        // Whatever is allowed, and be it false
925        return jQuery.grep(['1', '2', '3', '4'], allowed)[0] || false;
926    }
927};
928
929/**
930 * Default implementation for the media manager's select action
931 *
932 * Can be overriden with the onselect URL parameter. Is called on the opener context
933 *
934 * @param {string} edid
935 * @param {string} mediaid
936 * @param {string} opts
937 * @param {string} align [none, left, center, right]
938 */
939function dw_mediamanager_item_select(edid, mediaid, opts, align) {
940    var alignleft = '';
941    var alignright = '';
942    if (align !== '1') {
943        alignleft = align === '2' ? '' : ' ';
944        alignright = align === '4' ? '' : ' ';
945    }
946
947    insertTags(edid, '{{' + alignleft + mediaid + opts + alignright + '|', '}}', '');
948}
949
950jQuery(dw_mediamanager.init);
951