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