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